SDK guide
Secure mode and cryptography
What the @sloppyvoice/sdk/crypto entry point implements of suite sv1-c1, how to seal and open a SealedMessage given K_hist, which parts of secure mode you plug in yourself, and what 0.1 leaves out.
Specification: 04 Cryptographic conventions, 07 Identity keys, certificates and verification, 08 Turning on encryption, pairing, backup and the vault, 11 Messages, attachments, read state and presence, 12 Direct messages and group DMs, 13 MLS profile, 14 Sealed messages, history visibility and sharing, 18 Media end-to-end encryption
Secure contexts only
Most of this page applies only to secure accounts and secure contexts. The exceptions are JWS verification, identity-object verification and DM IDs, which insecure clients need too (04 Conformance, 07 §1.3, 12 §5.2).
The SDK splits secure mode into three places:
@sloppyvoice/sdk/cryptoholds suitesv1-c1of document 04 and the verification and derivation helpers of 07, 12 and 14. Nothing in it talks to a server or persists anything: its functions take keys and bytes and return bytes, keys or a verdict. The only stateful pieces are two in-memory reference stores for pins and identity evidence.@sloppyvoice/sdk(the main entry) holds the MLS provider seam of 13, the KeyBackup and pairing ceremonies of 08, and the resource APIs that carry secure objects (messages,mls,history,identity).@sloppyvoice/sdk/mediaholds SFrame and MediaAttestation for calls (18).
The protocol side of all this is explained in Cryptography, Secure accounts and MLS and sealed messages. This page covers what the SDK does with it.
The primitives run on WebCrypto (crypto.subtle), including Ed25519 and X25519; the only bundled arithmetic is the strict Ed25519 checks and the CPace map described below. On a runtime without WebCrypto, subtleCrypto throws sdk.not_implemented.
What the crypto entry point provides
Errors follow a few patterns:
- Verifiers and decrypters that throw, such as verifyJws, decodeCryptoField, hpkeOpen and the SVF1 functions, throw a SloppyVoiceError with the
crypto.*code of 04 §15, such as crypto.bad_signature or crypto.invalid_key. - The identity-object verifiers throw IdentityCheckError, whose
codeissdk.verification_failedand whosereasonis the 07 result. - verifyEd25519 and verifyLabelled return a boolean.
- Bad input from your own code throws
sdk.invalid_argument. signJws also throws it for a payload a verifier would reject, with thecrypto.*code the verifier would give indata.cryptoCode. - Functions whose spec algorithm has outcomes rather than errors, such as openSealed, return a tagged result instead of throwing.
Ed25519 and labelled signatures
Ed25519 verification follows the strict rules of 04 §4.3: canonical 32-byte keys of prime order, canonical R not of small order, S < L, and the cofactorless equation. A browser's crypto.subtle.verify doesn't promise any of that, so verifyEd25519 applies the key, R and S checks itself and uses crypto.subtle.verify only after ed25519SelfTest has shown that the platform accepts vector V-4a and rejects V-4g. Otherwise it falls back to a bundled cofactorless check. Pass { implementation: 'portable' } to force the bundled check.
A signing key is anything that implements Ed25519Signer: a raw 32-byte publicKey and an async sign(message). The SDK's own key pairs wrap a WebCrypto CryptoKey, non-extractable unless you ask, because only the identity key ever travels, and then only as its seed (04 §14.2). You can wrap a hardware or platform keystore key in the same interface.
Labelled signatures are the device signing key's (DSK's) signatures outside JWS and MLS. The signed bytes are "sv1 sig" || 0x00 || label || 0x00 || content, so a signature made for one label never verifies under another (04 §7.1). Only registered labels are accepted unless you pass allowUnregistered, for a label an owner has added since (04 §8.7); the test label needs allowTestLabel because no production verifier accepts it (04 §7.3).
import { generateEd25519KeyPair, jwkThumbprint, signLabelled, verifyLabelled } from '@sloppyvoice/sdk/crypto'
const dsk = await generateEd25519KeyPair()
console.log(await jwkThumbprint(dsk.publicKey)) // the dkf: RFC 7638 thumbprint, 43 base64url characters (04 §5.2)
const content = new TextEncoder().encode('owner-defined binary content')
const opts = { allowTestLabel: true }
const sig = await signLabelled(dsk, 'test', content, opts)
console.log(await verifyLabelled(dsk.publicKey, 'test', content, sig, opts)) // true
console.log(await verifyLabelled(dsk.publicKey, 'sealed', content, sig)) // false: another label, other signed bytesJWS
signJws and verifyJws implement the profile of 04 §6: alg EdDSA, a registered typ, a kid in the form the type's signer class requires, I-JSON payloads and the time-claim rules. signJws checks the payload against the same rules before signing, so the SDK never produces an object that a verifier must reject.
verifyJws never takes the key from the JWS itself. You pass the key the context expects, or a resolver that receives the parsed kid and looks the key up, for a server-class type in the issuer's ServerMetadata (04 §6.4). It runs steps 1 to 11 of 04 §6.8; the owner's claim checks (step 12) are yours.
import { verifyJws } from '@sloppyvoice/sdk/crypto'
// Your lookup of a server signing key by kid, through discovery (02).
declare function serverSigningKey(domain: string, keyId: string): Promise<Uint8Array>
export async function verifyAssertion(compact: string) {
const jws = await verifyJws(compact, {
typ: 'sv-assert+jwt',
key: ({ serverKid }) => serverSigningKey(serverKid!.domain, serverKid!.keyId),
})
return jws.payload // aud, sub and the other HomeAssertion claims are still yours to check (06)
}Identity objects have their own verifiers that wrap this profile and add the checks of 07: verifyIdentityCertificate, verifyDeviceCertificate, verifyDeviceRevocation and verifyIdentityState. They throw IdentityCheckError (code sdk.verification_failed) with the 07 result (bad_signature, key_mismatch, subject_mismatch and so on), which identityCheckReason reads back.
Safety numbers and DM IDs
A safety number is computed from the identity key the client trusts for each person and their canonical address. It changes when either identity key changes, never when a device is added or removed (07 §17.1). A 1:1 DM's context reference is a hash of the two canonical addresses, so anyone can compute it and the same pair has the same dm: reference on every server (12 §5.2).
import {
dmContextId,
formatSafetyNumber,
generateEd25519KeyPair,
issueIdentityCertificate,
safetyNumber,
verifyIdentityCertificate,
} from '@sloppyvoice/sdk/crypto'
const iat = Math.floor(Date.now() / 1000)
const aliceIk = await generateEd25519KeyPair()
const bobIk = await generateEd25519KeyPair()
// Bob's IdentityCertificate as Alice's client would receive it.
const bobIdc = await issueIdentityCertificate({ identityKey: bobIk, sub: 'bob@b.example', igen: 1, kind: 'user', iat })
const bob = await verifyIdentityCertificate(bobIdc)
const number = await safetyNumber({ ik: aliceIk.publicKey, addr: 'alice@a.example' }, { ik: bob.ik, addr: bob.sub })
console.log(formatSafetyNumber(number)) // 3 rows of 4 groups of 5 digits; display all 60 digits
console.log(await dmContextId('bob@b.example', 'alice@a.example')) // "dm:" + 22 base64url characters, same in either orderIn a real client the contact's key comes from the pin (trustedKeyOfPin), not from a certificate on its own: an IdentityCertificate proves nothing until a verified IdentityState names it or a pin holds its key (07 §5.1).
Sealing and opening a message
A secure context's content is a SealedMessage. Every key it uses comes from K_hist(e), the 32-byte history key that every member device exports from MLS epoch e (14 §3.1):
ekid = HKDF-Expand(K_hist, "sv1 ekid", 8), public, so receivers can find the key and notice forks (14 §3.2);K_msg = HKDF-Expand(K_hist, "sv1 msg" || mid16(mid), 32), one key per message (14 §3.3);kc = HMAC-SHA256(K_msg, "sv1 kc")[0..16], the key commitment, checked in constant time before any decryption (14 §3.4).
sealMessage does the cryptographic part of steps 3 to 8 of 14 §4.7; reusing a stored SealedMessage on a retry and storing the new one with the outbox entry are yours. It derives the three values, pads the content JSON with spaces to a multiple of 256 bytes, encrypts it with AES-256-GCM using the SealedHeader as associated data, and signs the header and ciphertext with the sealed labelled signature. openSealed is OpenSealed of 14 §6.3: it returns content only after the sender's signature verified.
This example seals a message under the K_hist test vector of 14 §16.3.2 and opens it again:
import { uuidv7 } from '@sloppyvoice/sdk'
import {
cryptoRandomBytes,
deriveEkid,
encodeCryptoField,
generateEd25519KeyPair,
hexToBytes,
openSealed,
resolveEkidMismatch,
sealMessage,
type HistoryKeyRef,
} from '@sloppyvoice/sdk/crypto'
// K_hist(42) of the 14 §16.3.2 vector. A real client exports it with exportHistoryKey(group)
// when it enters the epoch, and reads it back from its key store (14 §3.7).
const kHist = hexToBytes('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f')
const host = 'b.example' // canonical domain of the hosting server
const ctx = 'ch:01938a11-2b3c-7d4e-8f90-112233445566'
const sender = 'alice@a.example' // the sending account's canonical address
const did = encodeCryptoField(cryptoRandomBytes(16)) // this device's ID, 22 base64url characters
const dsk = await generateEd25519KeyPair() // this device's DSK
// --- Sender (14 §4.7) ---
const sealed = await sealMessage({
host,
ctx,
gen: 1,
sender,
did,
mid: uuidv7(), // record it in the outbox first; a retry reuses it
epoch: 42,
kind: 'message',
content: { text: 'Hello', replyTo: null, attachments: [] },
kHist,
signer: dsk,
})
// Store `sealed` with the outbox entry now: a retry in the same (gen, epoch) resends these bytes.
// --- Receiver (14 §6.3) ---
const keyStore = new Map<string, HistoryKeyRef>([['1:42', { key: kHist, ekid: await deriveEkid(kHist), source: 'mls' }]])
const result = await openSealed(sealed, {
ctx, // the carrier's context
host,
sender, // the carrier's sender.addr
historyKey: (gen, epoch) => keyStore.get(`${gen}:${epoch}`) ?? null,
// The sender's candidate DSKs for (sender, sealed.did), in the order of 14 §6.2.
// Here the live leaf; a real client reads it from its validated MLS state.
senderKeys: () => [dsk.publicKey],
})
switch (result.outcome) {
case 'ok':
console.log(result.content.text) // "Hello"; with a history key, mark the key-store entry confirmed (step 11)
break
case 'pending_key':
case 'pending_sender':
// Keep a placeholder in the timeline and retry later (14 §6.4, §6.5). A pending_sender
// still unresolved after 24 h becomes invalid, with diagnostic step 'timeout' (14 §6.4, §9.4).
break
case 'ekid_mismatch':
// Only reached after the signature verified. R is the settled reference ekid (13 §4.4), or null.
console.log(resolveEkidMismatch({ source: result.source ?? 'mls', ekid: result.ownEkid }, null))
break
case 'invalid':
// Show "This message can't be shown" and send the sealed_verify diagnostic (14 §9.4).
console.log('failed at step', result.step)
break
}Things openSealed leaves to you, because they need state the SDK doesn't hold (14 §6.3):
- finding the sender's candidate keys under the rules of 14 §6.2. For an epoch this device was in (a history key with
sourcemls), the key must come from a leaf the device validated itself, sofetchRecordKeysis never called then; - deduplicating by (
ctx,mid) and checking that aneditordeletecomes from the target's author; - the content schema checks of 11 beyond
targetequalsref, which you can add withcheckContent; - marking a key-store entry confirmed after the first
ok.
Posting
For posting, use the messages API rather than calling sealMessage directly. MessagesApi.secureEntry validates the content object with the secure rules of 11, serializes it, seals it with the server's maxMessageBytes, and adds the cleartext members of the secure carrier: kind and target, which the server checks against the SealedHeader, the mention hint and attachmentIds (11 §4.3). When a post fails, sealedSendAction maps the error to the next step of 14 §4.7.
import type { ServerClient } from '@sloppyvoice/sdk'
import { sealedSendAction, type Ed25519Signer } from '@sloppyvoice/sdk/crypto'
export async function sendSecureText(
server: ServerClient,
p: { host: string; ctx: string; gen: number; epoch: number; kHist: Uint8Array; sender: string; did: string; dsk: Ed25519Signer; text: string },
) {
const entry = await server.messages.secureEntry({
host: p.host,
ctx: p.ctx,
gen: p.gen,
epoch: p.epoch,
kHist: p.kHist,
sender: p.sender,
did: p.did,
signer: p.dsk,
mid: server.messages.newMid(),
content: { text: p.text },
})
// Persist `entry` in the outbox before the first attempt (11 §13.4, 04 §9.6).
try {
return await server.messages.post(p.ctx, entry)
} catch (e) {
// 'resend_same', 'catch_up_and_reseal', 'join_and_reseal', 'not_secure', 'not_sent', ...
const action = sealedSendAction(e)
if (action === 'not_secure') {
// Never resend as plaintext automatically (14 §4.7 step 12).
}
throw e
}
}A re-seal after sealed.wrong_epoch keeps the same mid and uses the new epoch's key; a plain retry in the same epoch resends the stored bytes, because the client must never encrypt twice under one K_msg (04 §9.6).
History shares and reports
A HistoryShare hands chosen per-message keys to one other account, never K_hist (14 §7). createHistoryShare builds the request body: a fresh K_share that encrypts the bundle of (mid, K_msg) items, wrapped with HPKE to each recipient device's box key, and signed with the history-share label. On the receiving side, openHistoryShare unwraps, verifies and decrypts the bundle, and each key must then pass verifySharedItem against its stored SealedMessage before you show or store anything (14 §7.8). verifyRevealedKey runs the same check for a key revealed in a report (14 §13.2). Send the result with server.history.createShare(ctx, share).
Attachments
Every file and thumbnail in a secure context is encrypted with SVF1: a fresh 32-byte K_file, AES-256-GCM in 64 KiB segments, a key commitment in the header, and padding to a size bucket (04 §10). The key and sha256 of the AttachmentRef travel inside the sealed content, so the server sees only the blob.
import { encodeCryptoField, openSecureAttachment, svf1Encrypt } from '@sloppyvoice/sdk/crypto'
const file = new TextEncoder().encode('report.txt contents')
const { blob, fileKey, fileSha256, blobSha256 } = await svf1Encrypt(file)
// Upload `blob` with sha256 = encodeCryptoField(blobSha256) (11 §14.2); the reference goes in the sealed content.
console.log(blob.length, encodeCryptoField(blobSha256))
const ref = { key: encodeCryptoField(fileKey), size: file.length, sha256: encodeCryptoField(fileSha256) }
const back = await openSecureAttachment(blob, ref) // decrypts, then checks size and sha256 (11 §14.3)
console.log(new TextDecoder().decode(back))For large files, svf1EncryptStream yields the header and each segment as it is sealed, and Svf1Decryptor decrypts single segments fetched with range requests. Any failure is crypto.decrypt_failed, which a client shows as an ordinary attachment failure, not a security warning.
Pluggable parts
Some of secure mode needs code that WebCrypto doesn't provide and the SDK, having no dependencies, doesn't bundle. You supply it through an interface.
MlsProvider
The SDK has the parts of the MLS profile of 13 that need no group secrets: group_id building and checks, the GroupContext extensions, the sv_device credential, KeyPackage building and checks, server-proposal verification, and the Delivery Service endpoints (server.mls). The RFC 9420 state machine itself (commits, Welcome processing, the key schedule, the ratchet tree) is an MlsProvider you plug in.
| Member | What it does |
|---|---|
createGroup |
Create a one-leaf epoch-0 group for a bootstrap (13 §10.1) |
joinFromWelcome |
Join a DM or group DM from a Welcome (13 §10.3) |
externalJoin |
Build an external commit from a GroupInfo, for channels and resync (13 §10.2) |
inspectGroupInfo |
Verify a GroupInfo and summarize it |
loadGroup, deleteGroup |
Load or discard the state of one group_id |
generateKeyPackages |
Generate KeyPackages and keep their private keys (13 §9.1); buildKeyPackage does the encoding |
An MlsGroupHandle exposes export, the RFC 9420 exporter, and the SDK builds the sv1 values on top of a handle or a pending commit: exportHistoryKey for K_hist, epochAckFor, commitSubmissionFor and groupBootstrapFor for the Delivery Service bodies. A provider that exposes only the epoch's exporter_secret can use mlsExporterFromSecret.
import { epochAckFor, exportHistoryKey, type MlsGroupHandle } from '@sloppyvoice/sdk'
import { deriveEkid } from '@sloppyvoice/sdk/crypto'
// Call when the device enters an epoch, before the provider deletes that epoch's secrets (14 §3.1).
export async function onEpochEntered(group: MlsGroupHandle) {
const kHist = await exportHistoryKey(group)
const entry = { epoch: group.epoch(), key: kHist, ekid: await deriveEkid(kHist), source: 'mls' as const, confirmed: true }
const ack = await epochAckFor(group) // { epoch, ekid, extPub } for POST …/mls/epoch-ack (13 §7.8)
return { entry, ack }
}Nothing in the SDK calls a provider itself: your code drives it and passes its handles to these helpers. unimplementedMlsProvider is a placeholder that rejects every call with sdk.not_implemented. A provider reports failures with MlsProviderError, whose kind (unprocessable, rejected, invalid_group_info, not_found) decides between a resync and a positive rejection (13 §15.4).
Argon2idProvider
The backup key of a KeyBackup is derived with Argon2id from the recovery phrase entropy (08 §5.3). WebCrypto has no Argon2id, so deriveBackupKey takes an Argon2idProvider. It checks the parameters against the ranges of 04 §12.1 before calling it, and runs the HKDF step itself.
import { deriveBackupKey, newArgon2idParams, type Argon2idProvider } from '@sloppyvoice/sdk'
// Your binding to an Argon2id implementation (WebAssembly or native), run off the UI thread (04 §12.3).
declare function argon2idHash(o: { pass: Uint8Array; salt: Uint8Array; m: number; t: number; p: number; hashLen: number }): Promise<Uint8Array>
const argon2: Argon2idProvider = {
argon2id: (i) => argon2idHash({ pass: i.password, salt: i.salt, m: i.memoryKiB, t: i.passes, p: i.parallelism, hashLen: i.tagLength }),
}
export async function backupKeyFor(entropy: Uint8Array, addr: string) {
const kdf = newArgon2idParams() // m = 65,536 KiB, t = 3, p = 1, fresh 16-byte salt
return { kdf, bk: await deriveBackupKey(entropy, kdf, addr, argon2) }
}The provider must compute Argon2id version 0x13 with an empty secret and associated data and a 32-byte tag (04 §12).
CPace generator
Pairing a new device runs CPace CPACE-X25519-SHA512 (04 §11). The SDK implements both roles, CpaceInitiator and CpaceResponder, using WebCrypto X25519. Each instance runs once, and the responder erases the displayed pairing credentials as it uses them (04 §11.7). The one replaceable piece is the CpaceGenerator, calculateGenerator(prs, ci, sid). The default, elligator2Generator, maps to the curve with JavaScript BigInt arithmetic, which isn't constant time; pass { generator } to use a vetted platform implementation instead (04 §14.4).
SFrame in calls
Media encryption isn't pluggable at the crypto level: @sloppyvoice/sdk/media implements the SFrame profile of 18 §3 on WebCrypto AES-128-GCM. sframeEpochSecret exports the media epoch secret from an MlsGroupHandle, SFrameEpochKeys derives per-KID keys, SFrameEncryptor owns the counters and the usage limits of 18 §3.6, and protectVoiceFrame, protectVideoFrame and protectSfuFrame apply it per transport (18 §8). What you supply is the transform itself: the SDK doesn't run WebRTC, so calling these functions from an encoded-frame transform or a data channel handler is your code. See Calls and Media for the protocol side.
Limits of 0.1
- No MLS state machine. Secure channels, secure DMs and calls with SFrame need an MlsProvider from you. Without one you can't create, join or process a group, so you have no
K_histand no SFrame keys; the Delivery Service calls ofserver.mlsstill work. - No Argon2id. Creating or restoring a KeyBackup needs an Argon2idProvider.
- No key storage. The SDK persists nothing. The key store of 14 §3.7, the outbox that keeps sealed bytes for retries, the local credential cache of 14 §6.2, pins and the media epoch state are yours to persist. MemoryPinStore and MemoryVerifierStore are in-memory references, not durable storage.
- No automatic decryption. The event socket delivers SealedMessages as wire objects. You call openSealed yourself, with keys you looked up.
- Constant time. Secret-dependent comparisons use constantTimeEqual, and AES, X25519 and Ed25519 signing run in WebCrypto. The bundled pieces in JavaScript BigInt (the portable Ed25519 verifier and the Elligator 2 map) aren't constant time. Verification only handles public values; the Elligator 2 map handles the pairing secret, so replace the CpaceGenerator where that matters.
- WebCrypto with Ed25519 and X25519 is required. Node 22.12 and current browsers have both; on a platform without them, key generation, signing and HPKE fail.