SDK guide
Runtimes and bundling
What the SDK needs from Node, browsers, Deno, Bun and Cloudflare Workers, how discovery works on each, the /node entry point, the browser ES module download, bundler settings and the Content-Security-Policy of a web client.
Specification: 01 Addresses, display names and links, 02 Discovery, server metadata and server keys, 03 Client transport, envelopes and errors, 04 Cryptographic conventions, 05 Accounts, login, sessions, devices and bots, 20 Client behaviour and user experience
@sloppyvoice/sdk is ESM only, targets ES2022 and has no runtime dependencies. Outside the /node entry point it uses only web platform APIs (fetch, WebSocket, crypto.subtle, crypto.getRandomValues, TextEncoder, URL, AbortController, setTimeout, structuredClone and the like), so the same code runs on Node 22.12 and later, current browsers, Deno, Bun and Cloudflare Workers. The one thing that differs between them is how discovery finds a server, because only some runtimes can send DNS queries.
What the SDK needs
| Platform feature | Used for | Without it |
|---|---|---|
fetch, URL, AbortController, timers |
Every HTTP request, discovery, retries | Nothing works; there is no fallback. |
crypto.getRandomValues |
Keys, seeds and nonces; UUIDv7 IDs, PKCE verifiers, retry and reconnect jitter (04 §13) | The operation stops. Key, seed and nonce generation throw crypto.rng_failure; the other uses fail with the runtime's own error. The SDK never falls back to Math.random. |
crypto.subtle (SHA-256, SHA-512, HMAC, AES-GCM) |
Signature checks, sealed messages, attachments, SFrame (04 §2.1) | sdk.not_implemented from the first crypto call. |
| WebCrypto Ed25519 | Signing (identity keys and DSKs, 04 §4.2) | Signing fails. Verification still works: the SDK has a portable fallback (below). |
| WebCrypto X25519 | HPKE for vault grants, pairing and history shares (08, 14) | Those secure-account operations fail. |
WebSocket (WHATWG) |
The event socket (03 §5) | The socket stops with sdk.invalid_argument when it tries to connect; pass the WebSocket option to the client. |
| Unicode 16.0.0 or later | Addresses and domains (01 §1.4) | Address and domain functions throw sdk.not_implemented, and so does the SloppyVoiceClient constructor when it prepares the home domain. |
A TXT resolver, or a home server's /v1/resolve |
Discovery (02 §5) | The SloppyVoiceClient constructor throws sdk.invalid_argument. |
The Unicode requirement is there because the SDK bundles Unicode 16.0.0 tables but still uses the runtime's own NFC, NFKC and URL parser for some steps; on an older engine the two would disagree for characters added in 16.0, so the SDK fails closed rather than prepare an address differently from the server (01 §1.4).
Ed25519 verification. Every runtime gets the strict verification of 04 §4.3. The SDK checks the key and the R and S encodings itself, and uses crypto.subtle.verify for the final equation only after ed25519SelfTest has shown that the platform accepts vector V-4a and rejects V-4g. If the self-test fails, or the platform has no Ed25519 in WebCrypto, it evaluates the cofactorless equation in its own BigInt code. That is the procedure the spec requires of web clients (04 §4.3 "Web clients"), and the SDK applies it on every runtime. Insecure accounts and bots hold no keys and only verify (04 §2.4), so they don't need WebCrypto Ed25519 at all; a secure account needs it to sign.
Runtimes at a glance
| Runtime | Discovery | Event socket | Notes |
|---|---|---|---|
| Node 22.12+ | Native: nodeTxtResolver() from @sloppyvoice/sdk/node |
Global WebSocket |
Node 22.12 ships ICU 76 (Unicode 16.0). Sends User-Agent. |
| Deno | Native: nodeTxtResolver() (Deno provides node:dns) |
Global WebSocket |
Needs --allow-net. |
| Bun | Native: nodeTxtResolver() (Bun provides node:dns) |
Global WebSocket |
|
| Browsers | Web: the home server's /v1/resolve, then optionally DoH |
Global WebSocket |
No User-Agent, credentials: 'omit'. See Browsers. |
| Cloudflare Workers | Native, through dohTxtResolver() |
Not in a request handler | See Cloudflare Workers. |
"Native" and "web" are the two discovery procedures of the spec: native clients query _sloppyv.<domain> TXT themselves (02 §5.2); web clients ask their home server (02 §5.4). The client picks the mode from its options: txt alone selects native discovery, homeBaseUrl selects web discovery with txt as the DoH fallback.
Checking a runtime
The SDK reports a missing feature when you first use it. To find out at start-up instead, probe the things that vary between engines: Unicode 16, Ed25519 signing, the Ed25519 self-test and WebSocket.
import { isSloppyVoiceError } from '@sloppyvoice/sdk'
import { prepareDomain } from '@sloppyvoice/sdk/address'
import { ed25519SelfTest, generateEd25519KeyPair } from '@sloppyvoice/sdk/crypto'
export async function checkRuntime() {
let unicode16 = true
try {
prepareDomain('sloppyvoice.com')
} catch (e) {
if (!isSloppyVoiceError(e, 'sdk.not_implemented')) throw e
unicode16 = false // older than Unicode 16.0.0 (01 §1.4)
}
let ed25519Sign = true
try {
await generateEd25519KeyPair()
} catch {
ed25519Sign = false // no WebCrypto Ed25519: verification still works, signing doesn't
}
return {
unicode16,
ed25519Sign,
// true: crypto.subtle.verify is used for the final equation; false: the portable check is
nativeEd25519Verify: await ed25519SelfTest(),
webSocket: typeof globalThis.WebSocket === 'function',
}
}
console.log(await checkRuntime())On Node, process.versions.unicode tells you the Unicode version directly.
Node
Node 22.12 or later has everything the SDK needs: fetch, a global WebSocket, WebCrypto with Ed25519 and X25519, and ICU 76. Give the client a TXT resolver from the /node entry point:
import { SloppyVoiceClient, botToken } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'
const sv = new SloppyVoiceClient({
client: 'my-bot/1.0',
home: 'sloppyvoice.com',
auth: botToken(process.env.SV_BOT_TOKEN!),
txt: nodeTxtResolver(),
})
const home = await sv.home()
console.log(home.baseUrl, home.metadata.name)
await sv.close()Outside browsers the API HTTP client sends User-Agent, as 03 §2.3 item 6 asks of non-browser clients: <client> sloppyvoice-sdk/<version> when the client option has the <product>/<version> form (my-bot/1.0 sloppyvoice-sdk/0.1.0 here), otherwise sloppyvoice-sdk/<version> alone. Discovery fetches (.well-known, /meta, DoH) send no User-Agent.
The /node entry point
@sloppyvoice/sdk/node is the only part of the SDK that uses Node APIs. It exports:
- nodeTxtResolver: a TxtResolver on
node:dns/promises. One TXT query, 5 s per attempt, at most 2 attempts (02 §3.5). NXDOMAIN and NODATA are "no record"; SERVFAIL, REFUSED and timeouts are temporary failures. It also answers the A/AAAA check that tells "the domain has no address" (discovery.not_found) from "unreachable" (02 §4.2). Options:servers(for example['127.0.0.1:53']),timeoutMs,tries(capped at 2). - loadPublicSuffixList: reads
public_suffix_list.datfrom disk forsame-siteevidence (02 §9.1). It doesn't check the file's age. A server should refresh its copy at least every 30 days and must not use one older than 180 days (02 §9.3). - mapNodeDnsError: the
node:dnserror code to lookup result mapping, for building your own resolver.
Node's resolveTxt reports neither TTLs nor DNSSEC status. Delegations found this way are cached for the 300 s minimum of 02 §13.1 and never get dnssec evidence. If you need either, write a TxtResolver on a DNS library that reports them; report dnssec: 'secure' only from a validating resolver you trust, never from the AD bit of one reached over an unauthenticated path (02 §3.5).
The module loads node:dns/promises and node:fs/promises with dynamic import(), so nothing Node-specific runs until you call it. A bundler still sees the specifiers: never import @sloppyvoice/sdk/node from code bundled for the browser. esbuild with platform: 'browser' fails with Could not resolve "node:dns/promises".
Deno and Bun
Both provide node:dns and node:fs, and nodeTxtResolver and the Node example above are written to run on them. The SDK's own tests run on Node only, so check discovery on the version you deploy. Install the tarball from Downloads into node_modules with npm install; Bun resolves packages from there, and so does Deno 2 when the project has a package.json. Both run TypeScript directly:
deno run --allow-net --allow-env bot.ts
bun run bot.tsDeno needs --allow-net for HTTP, DNS and WebSocket, and --allow-env if you read the token from the environment. Neither runtime promises the same Unicode or WebCrypto support as Node 22.12; run the runtime check once on the version you deploy.
Browsers
A browser can't send DNS queries, and its fetch follows CORS rules. The SDK detects a browser (a document, or a navigator.userAgent starting with Mozilla/, which covers dedicated, shared and service workers) and changes two things in its API HTTP client:
- It doesn't send
User-Agent, which a browser ignores or which breaks the CORS preflight (03 §2.3 item 6, 03 §4). - It sends API requests with
credentials: 'omit', because no endpoint accepts ambient credentials such as cookies (03 §3.2 rule 2). Discovery fetches never sendAuthorizationand use the fetch default.
Web discovery (homeBaseUrl, below) changes a third thing, whatever the runtime: for cache-bypassing /meta fetches it uses the fetch cache: 'no-cache' mode instead of a Cache-Control header where the runtime supports that mode, because Cache-Control isn't in the Access-Control-Allow-Headers list servers must send (03 §4). 02 §13.5 asks for the header; the spec doesn't say how a browser should send it, and the SDK notes this as a spec issue.
The event socket needs no headers: the token travels in session.hello (03 §5.4), so the browser WebSocket works as it is.
Discovery through the home server
Configure a web client with homeBaseUrl, the base URL of the server that served it (its bootstrap server, and after sign-in the account's home server). The client then resolves every domain with GET /v1/resolve on that server and checks /meta itself (02 §5.4):
import { SloppyVoiceClient, dohTxtResolver } from '@sloppyvoice/sdk'
const sv = new SloppyVoiceClient({
client: 'my-web-client/1.0',
home: 'sloppyvoice.com',
homeBaseUrl: 'https://chat.sloppyvoice.com/server',
// Optional: used only when the home server can't be reached (02 §5.4 step 3).
txt: dohTxtResolver({ url: 'https://dns.example/dns-query' }),
})
const lobby = await sv.resolve('publiclobby.example')
console.log(lobby.baseUrl, lobby.metadata.name, lobby.evidence)The order is fixed by 02 §5.4:
- A definitive
discovery.*answer from/v1/resolve,discovery.peer_suspendedincluded, is final. A retryable one (discovery.dns_failure,discovery.server_unreachable) orcore.rate_limitedis the answer for this attempt. The SDK never goes to DoH for these, because DoH would bypass the home server's pins exactly when they detect an attack. - Only when the home server gives no usable answer (a network error, a timeout, a 5xx without a
discovery.*problem,core.unavailable) does the SDK usetxt. Without it, the result isdiscovery.server_unreachable. - On the DoH path, a
.well-known/sloppyvdocument that CORS blocks counts as absent. Browsers report a CORS block exactly like a network failure, so the SDK treats every network error there as absent.
dohTxtResolver sends RFC 8484 GET queries. The endpoint must allow CORS, and the SDK ships no default endpoint. A web client never records dnssec evidence (02 §5.4 step 3), and the DoH resolver never reports it.
Sessions in the browser
05 §7.7 sets the storage rules for web clients: no tokens in localStorage or cookies, the refresh token in IndexedDB (under a non-extractable wrapping key for a secure account), memory only in shared-computer mode, and one refresh in flight across all tabs. webLocks gives HomeSession a cross-tab lock through the Web Locks API; load lets a tab pick up a refresh another tab made instead of presenting a rotated token, which would revoke the device (05 §7.6 rule 3):
import { SloppyVoiceClient, webLocks, type HomeSessionState, type ServerPinStore } from '@sloppyvoice/sdk'
// Your IndexedDB-backed storage (05 §7.7) and a durable pin store (02 §10.6).
declare function loadSession(): Promise<HomeSessionState | null>
declare function saveSession(state: HomeSessionState): Promise<void>
declare const pins: ServerPinStore
const stored = await loadSession()
if (stored) {
const sv = new SloppyVoiceClient({
client: 'my-web-client/1.0',
home: 'sloppyvoice.com',
homeBaseUrl: 'https://chat.sloppyvoice.com/server',
auth: {
session: stored,
options: { lock: webLocks('sv-session'), load: loadSession, persist: saveSession },
},
discovery: { pins },
})
const home = await sv.home()
console.log(home.domain)
}A restored session needs a durable discovery.pins store; the constructor refuses one without it, because pins that vanish on reload would let a stored token follow a spoofed delegation (02 §10.6).
Don't run a SloppyVoiceClient with a session in a service worker. Service workers must not hold, use or refresh session tokens; they read notifications with the push fetch token only (05 §7.7, 20 §16.6 rule 4).
Which origin may hold keys
A web client may create, receive or hold a secure account's identity and vault keys only on the origin of the home server's links.web, or on any origin if the metadata has no links.web (20 §16.11). webClientOrigin reads it with the spec's rule that a present but invalid value matches no origin:
import { webClientOrigin, type ServerClient } from '@sloppyvoice/sdk'
export function mayHoldKeys(home: ServerClient): boolean {
const web = webClientOrigin(home.metadata)
return !web.present || web.origin === globalThis.location.origin
}When it returns false, offer "Open {domain}'s web app" and "Get the app" in place of the key action, as 20 §16.11 describes. Insecure contexts keep working.
Cloudflare Workers
Workers have fetch, WebCrypto and the WHATWG WebSocket, but no system DNS resolver for the SDK to use. Pass dohTxtResolver as txt without homeBaseUrl: the client then runs native discovery (02 §5.2) over DNS-over-HTTPS. CORS doesn't apply in a Worker, so any DoH endpoint works, and delegations never get dnssec evidence. The SDK doesn't treat a Worker as a browser (its navigator.userAgent is Cloudflare-Workers), so it sends User-Agent.
import { SloppyVoiceClient, botToken, dohTxtResolver } from '@sloppyvoice/sdk'
interface Env {
SV_BOT_TOKEN: string
SV_CHANNEL: string
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
if (request.method !== 'POST') return new Response(null, { status: 405 })
const sv = new SloppyVoiceClient({
client: 'deploy-notifier/1.0',
home: 'sloppyvoice.com',
auth: botToken(env.SV_BOT_TOKEN),
txt: dohTxtResolver({ url: 'https://dns.example/dns-query' }),
})
try {
const home = await sv.home()
const ack = await home.messages.send(env.SV_CHANNEL, await request.text())
return Response.json({ seq: ack.seq })
} finally {
await sv.close()
}
},
}A request handler ends when its response is sent, so it suits HTTP calls: sending messages, managing channels, answering webhooks. The event socket is a long-lived connection with heartbeats and reconnects (03 §5); run it where a process stays up, such as a Durable Object or a server. A client created per request repeats discovery each time; a client at module scope keeps its caches only as long as the isolate, which Workers may discard at any time.
Don't import @sloppyvoice/sdk/node in a Worker: without Node.js compatibility the bundler can't resolve node:dns/promises, the SDK isn't tested against the Workers node:dns, and dohTxtResolver already covers discovery.
Bundlers and tree-shaking
The package is ES modules with "sideEffects": false and these entry points in exports:
| Entry point | Contents |
|---|---|
@sloppyvoice/sdk |
The client, transport, auth, resource APIs, discovery, calls, the MLS seam, wire types |
@sloppyvoice/sdk/address |
Addresses, display names, links (01) |
@sloppyvoice/sdk/discovery |
Discovery building blocks (02) |
@sloppyvoice/sdk/crypto |
Encodings and crypto conventions (04), identity verification (07), DM IDs, sealed messages and history shares (12, 14) |
@sloppyvoice/sdk/media |
voice-dc/1, video-dc/1 and SFrame helpers (16 to 18) |
@sloppyvoice/sdk/wire |
Wire types only |
@sloppyvoice/sdk/testing |
MockServer |
@sloppyvoice/sdk/node |
The Node TXT resolver and Public Suffix List loader |
What this means for your build:
- Import standalone helpers from their entry point. A tool that only verifies signatures or formats addresses pulls in only those modules.
- SloppyVoiceClient builds a ServerClient with every resource API, discovery and the event socket, so importing it brings in most of the main entry whatever you call. Tree-shaking can't remove resource APIs that are properties of an object you create.
@sloppyvoice/sdk/addresscarries the bundled Unicode 16.0.0 tables; the client uses them too.- Keep the build target at ES2020 or later. The SDK uses BigInt literals (for Ed25519) and
#privateclass fields, and BigInt literals can't be compiled down. It also calls ES2022 library functions such asObject.hasOwn, which bundlers don't polyfill, so the runtime itself must support ES2022. - In TypeScript, use
"moduleResolution": "Bundler"or"NodeNext"so the subpathexportsresolve. - Bundle for the browser with
platform: 'browser'(esbuild) or the equivalent, and never include@sloppyvoice/sdk/node(see The /node entry point).
The browser ES module download
Downloads has sloppyvoice-sdk-<version>.mjs, the main entry @sloppyvoice/sdk bundled by esbuild into one ES module: target ES2022, not minified, no imports, with the MIT licence in its header comment. Use it when you don't have a bundler.
- It exports only what the main entry exports. The
/address,/crypto,/media,/testingand/nodehelpers aren't in it; for those, install the npm tarball and bundle. - It contains the whole main entry, so nothing is tree-shaken.
- Serve it from your own origin. Rules 5 and 6 of 20 §16.4 and WH-7 of 20 §16.1 forbid loading code from another origin or a CDN, and that includes developer.sloppyvoice.com.
Check the file against the SHA-256 on the downloads page, then compute a SHA-384 digest for its integrity attribute (20 §16.4 rule 1 accepts SHA-384 or SHA-512):
sha256sum sloppyvoice-sdk-0.1.0.mjs
printf 'sha384-%s\n' "$(openssl dgst -sha384 -binary sloppyvoice-sdk-0.1.0.mjs | openssl base64 -A)"Give it a content-hashed file name and load it with an integrity attribute, together with your own module:
<link rel="modulepreload" href="/assets/sloppyvoice-sdk-0.1.0.4f2c91.mjs"
integrity="sha384-…" crossorigin="anonymous">
<script type="module" src="/assets/app.7d1e02.js"
integrity="sha384-…" crossorigin="anonymous"></script>app.js then imports /assets/sloppyvoice-sdk-0.1.0.4f2c91.mjs, and the browser uses the integrity-checked module the preload fetched. Rule 2 of 20 §16.4 asks that modules imported at run time be listed in an import map's integrity section or bundled into a script that rule 1 covers. An import map is an inline script, which the policy of 20 §16.2 blocks because it allows no hashes or nonces, and the spec doesn't say whether a static import of a preloaded module counts as imported at run time. Bundling the SDK into your application script, so that one integrity attribute covers both, meets rule 2 without that question.
Content-Security-Policy
A web client that can hold a secure account's keys must serve the policy of 20 §16.2 on every HTML document, worker and service-worker script, and may only make it stricter. The SDK runs under it unchanged:
- It has no
eval, nonew Function, no WebAssembly, and touches no DOM sink, soscript-src 'self'andrequire-trusted-types-for 'script'don't affect it. - It needs
connect-src 'self' https: wss:. A client talks to every server it federates with, which you can't list in advance, and the DoH endpoint ishttps:too. Narrowingconnect-srcto a fixed list of hosts breaks federation. - It loads no code at run time. Everything it runs is in the module you serve.
Your application has to meet the rest of the profile (20 §16.1):
| Rule | What it means with the SDK |
|---|---|
| WH-2, WH-7 | Serve the SDK from your origin; no CDN, analytics or third-party fonts. |
| WH-3, §16.4 rules 1 and 2 | An integrity attribute on every script, the SDK included (see above). |
| §16.4 rule 3 | A dedicated worker (where 08 unwraps the identity key) must be one bundled file with no imports, fetched with fetch(url, { integrity }) and started from a blob: URL. Bundle the SDK into the worker script; the .mjs download can't be imported there. |
| WH-8, §16.9 | Render message content, names and topics with DOM text APIs, never as HTML. The SDK hands you data; rendering is yours. |
| §16.3 | The response headers (Strict-Transport-Security, Referrer-Policy: no-referrer, Cross-Origin-Opener-Policy, Permissions-Policy and the rest) come from your web server. |
| WH-5, §16.5 | Serve the client from an origin that serves no user content, and preferably not from the API base URL. |
| WH-9, §16.6 | A service worker only for Web Push, decrypting notifications and caching your own assets, with no session tokens. |
Client behaviour covers the rest of document 20, and Discovery explains the native and web procedures in full.