SPAPS SDK (TypeScript)
spaps-sdk is the typed TypeScript client for SPAPS-compatible APIs. It wraps common API surfaces in namespaces (auth, payments, issueReporting, entitlements, and others), re-exports many spaps-types contracts, and ships helper utilities for permission checks, feature gates, WebSocket auth, and webhook verification.
Verified source surface: spaps-sdk 1.14.1 at Sweet Potato
5b09d3df1194577c5313c865fef1db98f694cdea, with Node.js 14 or newer. The symbols below come from
packages/sdk/src; check the installed version because a published package can lag the checkout.
Install
npm install spaps-sdk
npm ls spaps-sdkAlternative package managers:
pnpm add spaps-sdk
yarn add spaps-sdkClient Setup And Key Modes
The SDK supports:
publishableKeyfor browser-safe usage.secretKeyfor server-side privileged usage.- legacy
apiKeyfor compatibility.
Constructor values override environment variables.
import { SPAPSClient, createBrowserClient, createServerClient } from 'spaps-sdk'
// Generic constructor
const spaps = new SPAPSClient({
apiUrl: 'https://api.example.test',
publishableKey: 'spaps_pub_example'
})
// Browser helper
const browserClient = createBrowserClient('spaps_pub_example', {
apiUrl: 'https://api.example.test'
})
// Server helper
const serverClient = createServerClient('spaps_sec_example', {
apiUrl: 'https://api.example.test'
})Relevant env vars:
SPAPS_API_URLNEXT_PUBLIC_SPAPS_API_URLSPAPS_API_KEYNEXT_PUBLIC_SPAPS_API_KEY
Namespace Surface
| Namespace | Purpose |
|---|---|
auth | Password, wallet, magic-link, refresh, logout, and password management flows |
payments | Checkout, products, prices, subscriptions, and crypto helpers |
sessions | Session lookup and lifecycle helpers |
secureMessages | Secure message create/list helpers |
issueReporting | Status, list/get/create/update/reply, and voice-token helpers |
email | Template lookup, preview, and send helpers |
entitlements | User and resource entitlement queries |
dayrate | Availability and booking helpers |
admin | Product/pricing admin helper methods |
cfo | CFO-facing reporting helper methods |
Permission And Role Helpers
The SDK exports permission helpers from packages/sdk/src/permissions.ts, including:
isAdminAccountgetUserRolehasPermissioncanAccessAdminPermissionCheckercreatePermissionChecker
import { createPermissionChecker, canAccessAdmin, isAdminAccount } from 'spaps-sdk'
const checker = createPermissionChecker(['admin@example.com'])
const role = checker.getRole('staff@example.com')
const access = canAccessAdmin({ id: 'u1', email: 'admin@example.com' })
const isAdmin = isAdminAccount('admin@example.com')
console.log(role, access.allowed, isAdmin)RoleHierarchy And FeatureEvaluator
RoleHierarchy gives deterministic role comparisons. FeatureEvaluator applies three layers in order:
- System kill switch entitlement key
- Resource-scoped block entitlement key
- Minimum role check
import { FeatureEvaluator, RoleHierarchy } from 'spaps-sdk'
const hierarchy = new RoleHierarchy({
guest: 0,
user: 10,
accountant: 20,
admin: 30
})
const evaluator = new FeatureEvaluator(hierarchy)
evaluator.registerFeature('billing_export', {
killSwitchKey: 'kill:billing_export',
resourceBlockKey: 'block:billing_export',
resourceBlockType: 'company',
minimumRole: 'accountant'
})WebSocketAuthHelper
WebSocketAuthHelper manages authenticated WebSocket connections with token refresh and reconnect handling.
Notable behaviors from packages/sdk/src/websocket-auth-helper.ts:
- Prefers a short-lived, single-use connect ticket in
?ticket=...; never puts the long-lived access token in the URL. Without a ticket, the bearer token travels in theSec-WebSocket-Protocolhandshake header. - Refreshes tokens before expiry (buffer-based).
- Reconnects on auth close codes
4001and4003. - Uses exponential backoff for network retries.
- Optional ping interval for stale connection detection.
import { WebSocketAuthHelper } from 'spaps-sdk'
const ws = new WebSocketAuthHelper({
url: 'wss://api.example.test/ws',
getAccessToken: () => localStorage.getItem('access_token') || undefined,
refreshAccessToken: async () => {
// Call your refresh flow and return a fresh access token
return 'new_access_token'
},
getConnectTicket: async () => {
const response = await fetch('https://api.example.test/api/realtime/ws-ticket', {
method: 'POST',
headers: {
'X-API-Key': 'spaps_pub_example',
Authorization: `Bearer ${localStorage.getItem('access_token')}`
}
})
if (!response.ok) throw new Error(`WebSocket ticket failed: ${response.status}`)
return (await response.json()).data.ticket
},
onMessage: data => console.log(data)
})
await ws.connect()Issue Reporting Helpers
The issueReporting namespace exposes:
getStatuslistgetcreateupdatereplycreateVoiceToken
scope is currently restricted to "mine" in the stock SPAPS API path; wider scopes are rejected by the SDK guard.
Entitlements Helpers
The entitlements namespace includes:
list(params?)check(key, userId?)listByResource(resourceType, resourceId?)
Scope behavior:
- Publishable-key contexts require user JWT and are user-scoped.
- Secret-key contexts can query broader resource scopes.
- Non-user resource scopes in publishable contexts are blocked server-side.
Webhook Verification Helper
Use verifyCryptoWebhookSignature for crypto webhook signature validation.
import { verifyCryptoWebhookSignature } from 'spaps-sdk'
verifyCryptoWebhookSignature({
body: requestBody,
signature: request.headers['x-spaps-signature'] as string,
// Resolve the provider-specific signing secret from your server-side secret store.
// SPAPS does not define one universal webhook-secret environment variable.
secret: await loadWebhookSecret('crypto-provider')
})Never expose this secret through a browser bundle or a NEXT_PUBLIC_*/VITE_* variable. The
hosted server’s provider map is CRYPTO_WEBHOOK_SECRETS; downstream consumers may use a different
secret-store key.
Test Coverage And Validation
From packages/sdk:
npm ci
npm run build
npm run typecheck:readme
npm run test:readme
npm run testKey behavior is covered by tests such as:
test/entitlements.test.tstest/issue-reporting.test.tstest/feature-evaluator.test.tstest/role-hierarchy.test.tstest/websocket-auth-helper.test.ts
For endpoint semantics and backend rules, pair this page with Endpoint reference, Billing and entitlements, and Issue reporting and support.