@seedprotocol/encryption 0.8.4-next.1913.g77fa9da → 0.8.4-next.1983.g8eb1851
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/SPEC.md +5 -2
- package/dist/envelopeDecryptor.d.ts +2 -1
- package/dist/envelopeDecryptor.d.ts.map +1 -1
- package/dist/index.js +323 -318
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["encoder","concat","encoder","WRAPPED_KEY_LENGTH","encoder","EMPTY","toHex","ALPHABET","LOOKUP","i","encodeBase64NoPad","out","bytes","n","rest","decodeBase64NoPad","text","acc","bits","o","c","v","ENVELOPE_FORMAT","ENVELOPE_CONTENT_TYPE","ENVELOPE_FORMAT_TAG","FILE_KEY_LENGTH","CHUNK_SIZE","TAG_LENGTH","PAYLOAD_NONCE_LENGTH","BODY_LINE_LENGTH","MAX_CONTENT_META_LENGTH","VERSION_LINE","HEADER_INFO","PAYLOAD_INFO","encoder$3","decoder","EnvelopeError","message","code","BIND_KEY","ENVELOPE_ID","STANZA_ARG","randomBytes","length","generateFileKey","generateEnvelopeId","b","isEnvelope","canonicalBind","keys","bind","key","k","concat$1","parts","p","copy","hkdf","ikm","salt","info","headerMacKey","raw","fileKey","usage","payloadKey","nonce","bindText","chunkNonce","iv","index","padmeLength","e","s","step","encodeContentFrame","meta","body","len","unpadded","padded","padding","decodeContentFrame","plain","metaLength","contentType","bodyStart","bodyLength","bodyEnd","encodeStanza","stanza","a","b64","lines","headerPrefix","stanzas","encryptEnvelopeWithNonce","input","payloadNonce","prefix","mac","chunks","count","part","sealed","encryptEnvelope","readLine","end","start","line","parse","pos","r","bindBytes","type","args","parseEnvelopeHeader","decryptEnvelope","header","value","options","payload","sealedChunk","remaining","last","chunk","XWING_KEM_ID","KDF_ID","AEAD_ID","NK","NN","NH","XWING_PUBLIC_KEY_LENGTH","XWING_SECRET_KEY_LENGTH","XWING_ENC_LENGTH","encoder$2","u16","concat","SUITE_ID","HPKE_V1","hmac","data","labeledExtract","label","labeledExpand","prk","keySchedule","empty","pskIdHash","infoHash","context","secret","sharedSecret","xwingKeyPair","ml_kem768_x25519","seed","sealBase","publicKey","randomness","aad","plaintext","cipherText","openBase","enc","secretKey","ciphertext","XWING_STANZA_TYPE","XWING_INFO","WRAPPED_KEY_LENGTH$1","generateRecipientKeyPair","wrapFileKeyWithRandomness","wrapFileKey","unwrapFileKey","unwrapWithSecretKeys","secretKeys","UnknownEntitlementKindError","kind","adapters","registerEntitlementAdapter","adapter","isEntitled","policy","address","blockTag","IDENTITY_SECRET_LENGTH","encoder$1","EMPTY$1","toHex$1","encryptionIdentityFromSecret","xwingSeed","tagSecret","recipient","bindingSecret","tagKey","x25519","bindingKey","ed25519","encryptionKeyId","recipientPublicKey","tagPublicKey","bindingPublicKey","hexToBytes","hex","what","keyBindingMessage","chain","chainId","keyId","account","signKeyBinding","identity","target","verifyKeyBinding","signature","createEncryptionIdentity","generateRecoveryPhrase","generateMnemonic","wordlist","normalizePhrase","phrase","recoveryKeyFromPhrase","words","entropy","mnemonicToEntropy","KEYSTORE_CONTENT_TYPE","PASSKEY_PRF_STANZA_TYPE","EOA_SIGNATURE_STANZA_TYPE","SALT_LENGTH","WRAPPED_KEY_LENGTH","encoder","EMPTY","ZERO_NONCE","keystoreFileKey","sealWithKek","kek","openWithKek","randomSalt","toHex","checkArgs","decoded","d","lengths","recoveryStanza","recoveryPublicKey","passkeyKek","prfOutput","generatePasskeySalt","passkeyStanza","credentialId","passkeyArgs","eoaSignatureMessage","generateEoaSignatureSalt","SECP256K1_N","signatureKeyMaterial","full","signatureKek","eoaSignatureStanza","acceptWalletKeyRisk","buildKeystoreManifest","describeKeystoreManifest","keystoreHeader","authenticators","unwrapKeystore","unlock","requests","result","sameBytes","openKeystoreManifest","unwrapped","opened","h","base64Url","binary","toBytes","randomChallenge","passkeyPrf","evalByCredential","credential","first","enrollPasskey","created","DB_NAME","STORE","request","resolve","req","reject","openDb","withStore","db","tx","mode","done","fn","saveIdentityOnDevice","deviceKey","record","store","loadIdentityFromDevice","listIdentitiesOnDevice","forgetIdentityOnDevice","createPrivateUploadEncryptor","recipients","envelope","blob","createEnvelopeDecryptor","unwrap","identities","error"],"sources":["../src/base64.ts","../src/envelope.ts","../src/hpke.ts","../src/recipient.ts","../src/entitlement.ts","../src/identity.ts","../src/keystore.ts","../src/passkey.ts","../src/deviceStore.ts","../src/uploadEncryptor.ts","../src/envelopeDecryptor.ts"],"sourcesContent":["/** Standard base64 alphabet without padding, as age uses in headers. Strict: rejects padding and non-canonical trailing bits. */\n\nconst ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nconst LOOKUP = new Int16Array(128).fill(-1)\nfor (let i = 0; i < ALPHABET.length; i++) LOOKUP[ALPHABET.charCodeAt(i)] = i\n\nexport function encodeBase64NoPad(bytes: Uint8Array): string {\n let out = ''\n let i = 0\n for (; i + 2 < bytes.length; i += 3) {\n const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8) | bytes[i + 2]!\n out += ALPHABET[n >> 18]! + ALPHABET[(n >> 12) & 63]! + ALPHABET[(n >> 6) & 63]! + ALPHABET[n & 63]!\n }\n const rest = bytes.length - i\n if (rest === 1) {\n const n = bytes[i]! << 16\n out += ALPHABET[n >> 18]! + ALPHABET[(n >> 12) & 63]!\n } else if (rest === 2) {\n const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8)\n out += ALPHABET[n >> 18]! + ALPHABET[(n >> 12) & 63]! + ALPHABET[(n >> 6) & 63]!\n }\n return out\n}\n\n/** Returns null when `text` is not canonical unpadded base64. */\nexport function decodeBase64NoPad(text: string): Uint8Array<ArrayBuffer> | null {\n if (text.length % 4 === 1) return null\n const out = new Uint8Array(Math.floor((text.length * 3) / 4))\n let acc = 0\n let bits = 0\n let o = 0\n for (let i = 0; i < text.length; i++) {\n const c = text.charCodeAt(i)\n const v = c < 128 ? LOOKUP[c]! : -1\n if (v < 0) return null\n acc = (acc << 6) | v\n bits += 6\n if (bits >= 8) {\n bits -= 8\n out[o++] = (acc >> bits) & 0xff\n }\n }\n // Leftover bits must be zero, or two encodings would decode to the same bytes.\n if (bits > 0 && (acc & ((1 << bits) - 1)) !== 0) return null\n return out\n}\n","/**\n * The `seed-private/v1` envelope: an age-style header of recipient stanzas, authenticated with an\n * HMAC under the file key, followed by a chunked AES-256-GCM payload. SPEC.md is the normative\n * description; this file implements it with WebCrypto only.\n */\n\nimport { decodeBase64NoPad, encodeBase64NoPad } from './base64'\n\nexport const ENVELOPE_FORMAT = 'seed-private/v1'\n/** Content-Type for an uploaded envelope. The real type is inside the encrypted payload. */\nexport const ENVELOPE_CONTENT_TYPE = 'application/octet-stream'\n/** Upload tag that marks an envelope, so readers know to decrypt before sniffing. */\nexport const ENVELOPE_FORMAT_TAG = { name: 'Seed-Encryption', value: ENVELOPE_FORMAT } as const\n\nexport const FILE_KEY_LENGTH = 32\nexport const CHUNK_SIZE = 64 * 1024\nconst TAG_LENGTH = 16\nconst PAYLOAD_NONCE_LENGTH = 16\nconst BODY_LINE_LENGTH = 64\nconst MAX_CONTENT_META_LENGTH = 64 * 1024\n\nconst VERSION_LINE = `${ENVELOPE_FORMAT}\\n`\nconst HEADER_INFO = `${ENVELOPE_FORMAT}/header`\nconst PAYLOAD_INFO = `${ENVELOPE_FORMAT}/payload`\n\nconst encoder = new TextEncoder()\nconst decoder = new TextDecoder('utf-8', { fatal: true })\n\nexport type EnvelopeErrorCode =\n | 'NOT_ENVELOPE'\n | 'BAD_HEADER'\n | 'BAD_BIND'\n | 'BIND_MISMATCH'\n | 'NO_KEY'\n | 'BAD_FILE_KEY'\n | 'BAD_RECIPIENT_KEY'\n | 'HEADER_MAC'\n | 'TRUNCATED'\n | 'BAD_CHUNK'\n | 'TRAILING_DATA'\n | 'BAD_CONTENT_FRAME'\n | 'BAD_RECOVERY_PHRASE'\n | 'BAD_KEYSTORE'\n | 'PASSKEY_PRF_UNSUPPORTED'\n\nexport class EnvelopeError extends Error {\n readonly code: EnvelopeErrorCode\n constructor(code: EnvelopeErrorCode, message: string) {\n super(message)\n this.name = 'EnvelopeError'\n this.code = code\n }\n}\n\n/** One recipient's wrap of the file key. Types are defined in SPEC.md; this layer treats them as opaque. */\nexport interface Stanza {\n type: string\n args: string[]\n body: Uint8Array\n}\n\n/**\n * Values the envelope is bound to, known before upload. `envelopeId` is required and is recorded\n * in the envelope attestation, so a ciphertext can't be presented as another Version's.\n */\nexport type EnvelopeBind = { envelopeId: string } & Record<string, string>\n\nexport interface EnvelopeHeader {\n bind: EnvelopeBind\n stanzas: Stanza[]\n}\n\nexport interface EncryptEnvelopeInput {\n /** 32 random bytes, from `generateFileKey()`. One per private Version. */\n fileKey: Uint8Array\n bind: EnvelopeBind\n /** At least one. Always include the publisher's own wrap. */\n stanzas: Stanza[]\n /** The plaintext's real MIME type; stored inside the encrypted payload. */\n contentType: string\n body: Uint8Array\n /**\n * `'padme'` (default) zero-pads the plaintext to its PADMÉ length, so the ciphertext size\n * reveals only a size class (at most 12% extra bytes). `'none'` leaves the exact length visible.\n */\n padding?: EnvelopePadding\n}\n\nexport type EnvelopePadding = 'padme' | 'none'\n\nexport interface DecryptEnvelopeOptions {\n /** The file key, when the caller already unwrapped it. */\n fileKey?: Uint8Array\n /** Called with the parsed header when `fileKey` is not given; returns the unwrapped file key or null. */\n unwrap?: (header: EnvelopeHeader) => Promise<Uint8Array | null> | Uint8Array | null\n /** Every key given must equal the envelope's bind value, or decryption fails with BIND_MISMATCH. */\n expectBind?: Partial<EnvelopeBind>\n}\n\nexport interface DecryptedEnvelope {\n bind: EnvelopeBind\n contentType: string\n body: Uint8Array\n}\n\nconst BIND_KEY = /^[A-Za-z][A-Za-z0-9]*$/\nconst ENVELOPE_ID = /^0x[0-9a-f]{64}$/\nconst STANZA_ARG = /^[\\x21-\\x7e]+$/\n\nfunction randomBytes(length: number): Uint8Array<ArrayBuffer> {\n const out = new Uint8Array(length)\n crypto.getRandomValues(out)\n return out\n}\n\nexport function generateFileKey(): Uint8Array {\n return randomBytes(FILE_KEY_LENGTH)\n}\n\n/** A random `0x`-prefixed 32-byte hex id, chosen before encryption and attested with the Version. */\nexport function generateEnvelopeId(): string {\n return `0x${Array.from(randomBytes(32), (b) => b.toString(16).padStart(2, '0')).join('')}`\n}\n\n/** True when `bytes` start with the envelope's version line. Doesn't validate the rest. */\nexport function isEnvelope(bytes: Uint8Array): boolean {\n if (bytes.length < VERSION_LINE.length) return false\n for (let i = 0; i < VERSION_LINE.length; i++) {\n if (bytes[i] !== VERSION_LINE.charCodeAt(i)) return false\n }\n return true\n}\n\n/** Sorted keys, string values, no whitespace. The bytes feed the payload key derivation. */\nexport function canonicalBind(bind: EnvelopeBind): string {\n const keys = Object.keys(bind).sort()\n for (const key of keys) {\n if (!BIND_KEY.test(key)) throw new EnvelopeError('BAD_BIND', `Invalid bind key ${JSON.stringify(key)}`)\n if (typeof bind[key] !== 'string') throw new EnvelopeError('BAD_BIND', `Bind value for ${key} must be a string`)\n }\n if (!ENVELOPE_ID.test(bind.envelopeId ?? '')) {\n throw new EnvelopeError('BAD_BIND', 'bind.envelopeId must be 0x followed by 64 lowercase hex digits')\n }\n return JSON.stringify(Object.fromEntries(keys.map((k) => [k, bind[k]])))\n}\n\nfunction concat(parts: Uint8Array[]): Uint8Array<ArrayBuffer> {\n const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))\n let o = 0\n for (const p of parts) {\n out.set(p, o)\n o += p.length\n }\n return out\n}\n\nfunction copy(bytes: Uint8Array): Uint8Array<ArrayBuffer> {\n return new Uint8Array(bytes)\n}\n\nexport async function hkdf(ikm: Uint8Array, salt: Uint8Array, info: Uint8Array, length: number): Promise<Uint8Array<ArrayBuffer>> {\n const key = await crypto.subtle.importKey('raw', copy(ikm), 'HKDF', false, ['deriveBits'])\n const bits = await crypto.subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt: copy(salt), info: copy(info) },\n key,\n length * 8,\n )\n return new Uint8Array(bits)\n}\n\nasync function headerMacKey(fileKey: Uint8Array, usage: 'sign' | 'verify'): Promise<CryptoKey> {\n const raw = await hkdf(fileKey, new Uint8Array(0), encoder.encode(HEADER_INFO), 32)\n return crypto.subtle.importKey('raw', raw, { name: 'HMAC', hash: 'SHA-256' }, false, [usage])\n}\n\nasync function payloadKey(fileKey: Uint8Array, nonce: Uint8Array, bindText: string, usage: 'encrypt' | 'decrypt'): Promise<CryptoKey> {\n const info = concat([encoder.encode(PAYLOAD_INFO), new Uint8Array([0]), encoder.encode(bindText)])\n const raw = await hkdf(fileKey, nonce, info, 32)\n return crypto.subtle.importKey('raw', raw, 'AES-GCM', false, [usage])\n}\n\nfunction chunkNonce(index: number, last: boolean): Uint8Array<ArrayBuffer> {\n const iv = new Uint8Array(12)\n // 11-byte big-endian counter; indexes stay below 2^53, so the top bytes are zero.\n let n = index\n for (let i = 10; i >= 0 && n > 0; i--) {\n iv[i] = n % 256\n n = Math.floor(n / 256)\n }\n iv[11] = last ? 1 : 0\n return iv\n}\n\n/**\n * PADMÉ (Nikitin et al., \"Reducing Metadata Leakage from Encrypted Files and Communication with\n * PURBs\", 2019): round `length` up so only the top `floor(log2(E)) + 1` bits of its exponent `E`\n * vary. Overhead is at most 12%.\n */\nexport function padmeLength(length: number): number {\n if (length < 2) return length\n let e = 0\n while (2 ** (e + 1) <= length) e++\n let s = 0\n while (2 ** (s + 1) <= e) s++\n const step = 2 ** (e - (s + 1))\n return Math.ceil(length / step) * step\n}\n\nfunction encodeContentFrame(contentType: string, body: Uint8Array, padding: EnvelopePadding): Uint8Array<ArrayBuffer> {\n const meta = encoder.encode(JSON.stringify({ bodyLength: body.length, contentType }))\n const len = new Uint8Array(4)\n new DataView(len.buffer).setUint32(0, meta.length)\n const unpadded = 4 + meta.length + body.length\n const padded = padding === 'padme' ? padmeLength(unpadded) : unpadded\n return concat([len, meta, body, new Uint8Array(padded - unpadded)])\n}\n\nfunction decodeContentFrame(plain: Uint8Array): { contentType: string; body: Uint8Array } {\n if (plain.length < 4) throw new EnvelopeError('BAD_CONTENT_FRAME', 'Payload is shorter than its content frame')\n const metaLength = new DataView(plain.buffer, plain.byteOffset, 4).getUint32(0)\n if (metaLength > MAX_CONTENT_META_LENGTH || 4 + metaLength > plain.length) {\n throw new EnvelopeError('BAD_CONTENT_FRAME', 'Content metadata length is out of range')\n }\n let meta: unknown\n try {\n meta = JSON.parse(decoder.decode(plain.subarray(4, 4 + metaLength)))\n } catch {\n throw new EnvelopeError('BAD_CONTENT_FRAME', 'Content metadata is not UTF-8 JSON')\n }\n const { contentType, bodyLength } = (meta ?? {}) as { contentType?: unknown; bodyLength?: unknown }\n if (typeof contentType !== 'string') throw new EnvelopeError('BAD_CONTENT_FRAME', 'Content metadata has no contentType')\n const bodyStart = 4 + metaLength\n if (typeof bodyLength !== 'number' || !Number.isSafeInteger(bodyLength) || bodyLength < 0 || bodyStart + bodyLength > plain.length) {\n throw new EnvelopeError('BAD_CONTENT_FRAME', 'Content metadata bodyLength is missing or out of range')\n }\n const bodyEnd = bodyStart + bodyLength\n for (let i = bodyEnd; i < plain.length; i++) {\n if (plain[i] !== 0) throw new EnvelopeError('BAD_CONTENT_FRAME', 'Padding after the body is not all zero')\n }\n return { contentType, body: plain.subarray(bodyStart, bodyEnd) }\n}\n\nfunction encodeStanza(stanza: Stanza): string {\n if (!STANZA_ARG.test(stanza.type) || stanza.args.some((a) => !STANZA_ARG.test(a))) {\n throw new EnvelopeError('BAD_HEADER', 'Stanza type and arguments must be non-empty printable ASCII without spaces')\n }\n const b64 = encodeBase64NoPad(stanza.body)\n let lines = ''\n for (let i = 0; i <= b64.length; i += BODY_LINE_LENGTH) {\n // The final line is shorter than 64 characters, and empty when the body fills its last line.\n lines += `${b64.slice(i, i + BODY_LINE_LENGTH)}\\n`\n }\n return `-> ${[stanza.type, ...stanza.args].join(' ')}\\n${lines}`\n}\n\n/** The header through `---`, which the MAC covers. */\nfunction headerPrefix(bindText: string, stanzas: Stanza[]): string {\n if (stanzas.length === 0) throw new EnvelopeError('BAD_HEADER', 'An envelope needs at least one stanza')\n return `${VERSION_LINE}bind ${encodeBase64NoPad(encoder.encode(bindText))}\\n${stanzas.map(encodeStanza).join('')}---`\n}\n\n/** Encrypt with a caller-chosen payload nonce. Exported for test vectors only; use `encryptEnvelope`. */\nexport async function encryptEnvelopeWithNonce(input: EncryptEnvelopeInput, payloadNonce: Uint8Array): Promise<Uint8Array> {\n if (input.fileKey.length !== FILE_KEY_LENGTH) throw new EnvelopeError('BAD_FILE_KEY', `File key must be ${FILE_KEY_LENGTH} bytes`)\n if (payloadNonce.length !== PAYLOAD_NONCE_LENGTH) throw new EnvelopeError('BAD_HEADER', 'Payload nonce must be 16 bytes')\n const bindText = canonicalBind(input.bind)\n const prefix = encoder.encode(headerPrefix(bindText, input.stanzas))\n const mac = new Uint8Array(await crypto.subtle.sign('HMAC', await headerMacKey(input.fileKey, 'sign'), prefix))\n\n const key = await payloadKey(input.fileKey, payloadNonce, bindText, 'encrypt')\n const plain = encodeContentFrame(input.contentType, input.body, input.padding ?? 'padme')\n const chunks: Uint8Array[] = []\n const count = Math.max(1, Math.ceil(plain.length / CHUNK_SIZE))\n for (let i = 0; i < count; i++) {\n const part = plain.subarray(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE)\n const sealed = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: chunkNonce(i, i === count - 1) }, key, part)\n chunks.push(new Uint8Array(sealed))\n }\n return concat([prefix, encoder.encode(` ${encodeBase64NoPad(mac)}\\n`), payloadNonce, ...chunks])\n}\n\nexport function encryptEnvelope(input: EncryptEnvelopeInput): Promise<Uint8Array> {\n return encryptEnvelopeWithNonce(input, randomBytes(PAYLOAD_NONCE_LENGTH))\n}\n\ninterface ParsedHeader extends EnvelopeHeader {\n bindText: string\n /** Bytes through `---`, covered by the MAC. */\n macInput: Uint8Array\n mac: Uint8Array\n payloadOffset: number\n}\n\nfunction readLine(bytes: Uint8Array, start: number): { line: string; next: number } {\n const end = bytes.indexOf(0x0a, start)\n if (end < 0) throw new EnvelopeError('BAD_HEADER', 'Header ends without a newline')\n let line: string\n try {\n line = decoder.decode(bytes.subarray(start, end))\n } catch {\n throw new EnvelopeError('BAD_HEADER', 'Header is not UTF-8')\n }\n if (!/^[\\x20-\\x7e]*$/.test(line)) throw new EnvelopeError('BAD_HEADER', 'Header lines must be printable ASCII')\n return { line, next: end + 1 }\n}\n\nfunction parse(bytes: Uint8Array): ParsedHeader {\n if (!isEnvelope(bytes)) throw new EnvelopeError('NOT_ENVELOPE', `Bytes do not start with ${ENVELOPE_FORMAT}`)\n let pos = VERSION_LINE.length\n\n let r = readLine(bytes, pos)\n if (!r.line.startsWith('bind ')) throw new EnvelopeError('BAD_HEADER', 'Missing bind line')\n const bindBytes = decodeBase64NoPad(r.line.slice(5))\n if (!bindBytes) throw new EnvelopeError('BAD_HEADER', 'bind line is not canonical base64')\n let bindText: string\n let bind: EnvelopeBind\n try {\n bindText = decoder.decode(bindBytes)\n bind = JSON.parse(bindText) as EnvelopeBind\n } catch {\n throw new EnvelopeError('BAD_BIND', 'bind is not UTF-8 JSON')\n }\n if (bind === null || typeof bind !== 'object' || Array.isArray(bind) || canonicalBind(bind) !== bindText) {\n throw new EnvelopeError('BAD_BIND', 'bind is not canonical')\n }\n pos = r.next\n\n const stanzas: Stanza[] = []\n for (;;) {\n r = readLine(bytes, pos)\n if (r.line.startsWith('--- ')) break\n if (!r.line.startsWith('-> ')) throw new EnvelopeError('BAD_HEADER', 'Expected a stanza or the MAC line')\n const [type, ...args] = r.line.slice(3).split(' ')\n if (!type || !STANZA_ARG.test(type) || args.some((a) => !STANZA_ARG.test(a))) {\n throw new EnvelopeError('BAD_HEADER', 'Malformed stanza line')\n }\n pos = r.next\n let b64 = ''\n for (;;) {\n r = readLine(bytes, pos)\n pos = r.next\n if (r.line.length > BODY_LINE_LENGTH) throw new EnvelopeError('BAD_HEADER', 'Stanza body line is too long')\n b64 += r.line\n if (r.line.length < BODY_LINE_LENGTH) break\n }\n const body = decodeBase64NoPad(b64)\n if (!body) throw new EnvelopeError('BAD_HEADER', 'Stanza body is not canonical base64')\n stanzas.push({ type, args, body })\n }\n if (stanzas.length === 0) throw new EnvelopeError('BAD_HEADER', 'Envelope has no stanzas')\n\n const mac = decodeBase64NoPad(r.line.slice(4))\n if (!mac || mac.length !== 32) throw new EnvelopeError('BAD_HEADER', 'MAC is not 32 bytes of canonical base64')\n return { bind, bindText, stanzas, macInput: bytes.subarray(0, pos + 3), mac, payloadOffset: r.next }\n}\n\n/** Reads the bind values and stanzas without a key, so a reader can pick the stanza to unwrap. */\nexport function parseEnvelopeHeader(bytes: Uint8Array): EnvelopeHeader {\n const { bind, stanzas } = parse(bytes)\n return { bind, stanzas }\n}\n\nexport async function decryptEnvelope(bytes: Uint8Array, options: DecryptEnvelopeOptions): Promise<DecryptedEnvelope> {\n const header = parse(bytes)\n for (const [key, value] of Object.entries(options.expectBind ?? {})) {\n if (header.bind[key] !== value) throw new EnvelopeError('BIND_MISMATCH', `Envelope bind ${key} does not match`)\n }\n const fileKey = options.fileKey ?? (await options.unwrap?.({ bind: header.bind, stanzas: header.stanzas }))\n if (!fileKey) throw new EnvelopeError('NO_KEY', 'No stanza could be unwrapped')\n if (fileKey.length !== FILE_KEY_LENGTH) throw new EnvelopeError('BAD_FILE_KEY', `File key must be ${FILE_KEY_LENGTH} bytes`)\n\n const macOk = await crypto.subtle.verify('HMAC', await headerMacKey(fileKey, 'verify'), copy(header.mac), copy(header.macInput))\n if (!macOk) throw new EnvelopeError('HEADER_MAC', 'Header MAC does not verify; wrong key or altered header')\n\n const payload = bytes.subarray(header.payloadOffset)\n if (payload.length < PAYLOAD_NONCE_LENGTH + TAG_LENGTH) throw new EnvelopeError('TRUNCATED', 'Payload is truncated')\n const key = await payloadKey(fileKey, payload.subarray(0, PAYLOAD_NONCE_LENGTH), header.bindText, 'decrypt')\n\n const sealedChunk = CHUNK_SIZE + TAG_LENGTH\n const parts: Uint8Array[] = []\n let pos = PAYLOAD_NONCE_LENGTH\n for (let i = 0; ; i++) {\n const remaining = payload.length - pos\n if (remaining < TAG_LENGTH) throw new EnvelopeError('TRUNCATED', 'Payload ends without a final chunk')\n const last = remaining <= sealedChunk\n const chunk = copy(payload.subarray(pos, pos + Math.min(remaining, sealedChunk)))\n let plain: Uint8Array\n try {\n plain = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: chunkNonce(i, last) }, key, chunk))\n } catch {\n if (last && remaining === sealedChunk) {\n // A full-size chunk that fails as the last one may be a non-final chunk whose successor was cut off.\n try {\n await crypto.subtle.decrypt({ name: 'AES-GCM', iv: chunkNonce(i, false) }, key, chunk)\n } catch {\n throw new EnvelopeError('BAD_CHUNK', `Chunk ${i} does not authenticate`)\n }\n throw new EnvelopeError('TRUNCATED', 'Payload ends without a final chunk')\n }\n if (!last) {\n // A chunk sealed as final followed by more bytes.\n try {\n await crypto.subtle.decrypt({ name: 'AES-GCM', iv: chunkNonce(i, true) }, key, chunk)\n } catch {\n throw new EnvelopeError('BAD_CHUNK', `Chunk ${i} does not authenticate`)\n }\n throw new EnvelopeError('TRAILING_DATA', 'Bytes follow the final chunk')\n }\n throw new EnvelopeError('BAD_CHUNK', `Chunk ${i} does not authenticate`)\n }\n if (last && plain.length === 0 && i > 0) throw new EnvelopeError('BAD_CHUNK', 'The final chunk is empty')\n parts.push(plain)\n pos += chunk.length\n if (last) break\n }\n const { contentType, body } = decodeContentFrame(concat(parts))\n return { bind: header.bind, contentType, body }\n}\n","/**\n * Single-shot HPKE (RFC 9180) in base mode, for one suite: KEM MLKEM768-X25519 (X-Wing, `0x647a`),\n * KDF HKDF-SHA256 (`0x0001`), AEAD AES-256-GCM (`0x0002`). Only the first message of a context is\n * sealed or opened, so the nonce is the base nonce. The KEM comes from `@noble/post-quantum`; the\n * key schedule and AEAD use WebCrypto.\n */\n\nimport { ml_kem768_x25519 } from '@noble/post-quantum/hybrid.js'\n\nexport const XWING_KEM_ID = 0x647a\nconst KDF_ID = 0x0001\nconst AEAD_ID = 0x0002\nconst NK = 32\nconst NN = 12\nconst NH = 32\n\nexport const XWING_PUBLIC_KEY_LENGTH = 1216\nexport const XWING_SECRET_KEY_LENGTH = 32\nexport const XWING_ENC_LENGTH = 1120\n\nconst encoder = new TextEncoder()\n\nfunction u16(n: number): Uint8Array<ArrayBuffer> {\n return new Uint8Array([n >> 8, n & 0xff])\n}\n\nfunction concat(parts: Uint8Array[]): Uint8Array<ArrayBuffer> {\n const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))\n let o = 0\n for (const p of parts) {\n out.set(p, o)\n o += p.length\n }\n return out\n}\n\nconst SUITE_ID = concat([encoder.encode('HPKE'), u16(XWING_KEM_ID), u16(KDF_ID), u16(AEAD_ID)])\nconst HPKE_V1 = encoder.encode('HPKE-v1')\n\nasync function hmac(key: Uint8Array, data: Uint8Array): Promise<Uint8Array<ArrayBuffer>> {\n // An empty HMAC key equals HashLen zero bytes; WebCrypto rejects zero-length keys.\n const raw = key.length === 0 ? new Uint8Array(NH) : new Uint8Array(key)\n const k = await crypto.subtle.importKey('raw', raw, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])\n return new Uint8Array(await crypto.subtle.sign('HMAC', k, new Uint8Array(data)))\n}\n\nfunction labeledExtract(salt: Uint8Array, label: string, ikm: Uint8Array): Promise<Uint8Array<ArrayBuffer>> {\n return hmac(salt, concat([HPKE_V1, SUITE_ID, encoder.encode(label), ikm]))\n}\n\n/** HKDF-Expand for L <= HashLen, which is all this suite needs. */\nasync function labeledExpand(prk: Uint8Array, label: string, info: Uint8Array, length: number): Promise<Uint8Array<ArrayBuffer>> {\n const labeledInfo = concat([u16(length), HPKE_V1, SUITE_ID, encoder.encode(label), info])\n const t1 = await hmac(prk, concat([labeledInfo, new Uint8Array([1])]))\n return t1.slice(0, length)\n}\n\nasync function keySchedule(sharedSecret: Uint8Array, info: Uint8Array, usage: 'encrypt' | 'decrypt') {\n const empty = new Uint8Array(0)\n const pskIdHash = await labeledExtract(empty, 'psk_id_hash', empty)\n const infoHash = await labeledExtract(empty, 'info_hash', info)\n const context = concat([new Uint8Array([0x00]), pskIdHash, infoHash])\n const secret = await labeledExtract(sharedSecret, 'secret', empty)\n const key = await labeledExpand(secret, 'key', context, NK)\n const nonce = await labeledExpand(secret, 'base_nonce', context, NN)\n return { key: await crypto.subtle.importKey('raw', key, 'AES-GCM', false, [usage]), nonce }\n}\n\nexport function xwingKeyPair(seed: Uint8Array): { secretKey: Uint8Array; publicKey: Uint8Array } {\n const { secretKey, publicKey } = ml_kem768_x25519.keygen(seed)\n return { secretKey, publicKey }\n}\n\n/** RFC 9180 SealBase. `randomness` is for test vectors only; leave it out to use the CSPRNG. */\nexport async function sealBase(\n publicKey: Uint8Array,\n info: Uint8Array,\n aad: Uint8Array,\n plaintext: Uint8Array,\n randomness?: Uint8Array,\n): Promise<{ enc: Uint8Array; ciphertext: Uint8Array }> {\n const { sharedSecret, cipherText } = ml_kem768_x25519.encapsulate(publicKey, randomness)\n const { key, nonce } = await keySchedule(sharedSecret, info, 'encrypt')\n const sealed = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce, additionalData: new Uint8Array(aad) }, key, new Uint8Array(plaintext))\n return { enc: cipherText, ciphertext: new Uint8Array(sealed) }\n}\n\n/** RFC 9180 OpenBase. Returns null when the ciphertext doesn't authenticate under this key. */\nexport async function openBase(\n enc: Uint8Array,\n secretKey: Uint8Array,\n info: Uint8Array,\n aad: Uint8Array,\n ciphertext: Uint8Array,\n): Promise<Uint8Array | null> {\n const sharedSecret = ml_kem768_x25519.decapsulate(enc, secretKey)\n const { key, nonce } = await keySchedule(sharedSecret, info, 'decrypt')\n try {\n return new Uint8Array(\n await crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce, additionalData: new Uint8Array(aad) }, key, new Uint8Array(ciphertext)),\n )\n } catch {\n return null\n }\n}\n","/**\n * The `mlkem768x25519` recipient stanza: the file key sealed with HPKE to an X-Wing public key.\n * The publisher's own wrap and the recovery wrap are both this stanza type, to different keys.\n * SPEC.md \"Recipient stanzas\" is the normative description.\n */\n\nimport { decodeBase64NoPad, encodeBase64NoPad } from './base64'\nimport { EnvelopeError, FILE_KEY_LENGTH, type EnvelopeHeader, type Stanza } from './envelope'\nimport {\n XWING_ENC_LENGTH,\n XWING_PUBLIC_KEY_LENGTH,\n XWING_SECRET_KEY_LENGTH,\n openBase,\n sealBase,\n xwingKeyPair,\n} from './hpke'\n\nexport const XWING_STANZA_TYPE = 'mlkem768x25519'\nconst XWING_INFO = new TextEncoder().encode('seed-private/v1/mlkem768x25519')\nconst WRAPPED_KEY_LENGTH = FILE_KEY_LENGTH + 16\n\nexport { XWING_PUBLIC_KEY_LENGTH, XWING_SECRET_KEY_LENGTH }\n\nexport interface RecipientKeyPair {\n /** 32 bytes. Everything else is derived from it, so this is the only part to keep secret and store. */\n secretKey: Uint8Array\n /** 1216 bytes: the ML-KEM-768 encapsulation key, then the X25519 public key. */\n publicKey: Uint8Array\n}\n\n/** A new X-Wing key pair. Pass a 32-byte seed to derive the same pair again. */\nexport function generateRecipientKeyPair(seed?: Uint8Array): RecipientKeyPair {\n const s = seed ?? crypto.getRandomValues(new Uint8Array(XWING_SECRET_KEY_LENGTH))\n if (s.length !== XWING_SECRET_KEY_LENGTH) {\n throw new EnvelopeError('BAD_RECIPIENT_KEY', `Recipient seed must be ${XWING_SECRET_KEY_LENGTH} bytes`)\n }\n return xwingKeyPair(s)\n}\n\n/** Wrap with caller-chosen encapsulation randomness (64 bytes). Exported for test vectors only. */\nexport async function wrapFileKeyWithRandomness(fileKey: Uint8Array, publicKey: Uint8Array, randomness?: Uint8Array): Promise<Stanza> {\n if (fileKey.length !== FILE_KEY_LENGTH) throw new EnvelopeError('BAD_FILE_KEY', `File key must be ${FILE_KEY_LENGTH} bytes`)\n if (publicKey.length !== XWING_PUBLIC_KEY_LENGTH) {\n throw new EnvelopeError('BAD_RECIPIENT_KEY', `Recipient public key must be ${XWING_PUBLIC_KEY_LENGTH} bytes`)\n }\n const { enc, ciphertext } = await sealBase(publicKey, XWING_INFO, new Uint8Array(0), fileKey, randomness)\n return { type: XWING_STANZA_TYPE, args: [encodeBase64NoPad(enc)], body: ciphertext }\n}\n\n/** A stanza that gives the holder of `publicKey`'s secret key the file key. */\nexport function wrapFileKey(fileKey: Uint8Array, publicKey: Uint8Array): Promise<Stanza> {\n return wrapFileKeyWithRandomness(fileKey, publicKey)\n}\n\n/**\n * The file key, or null when the stanza is another type or was wrapped to a different key.\n * Throws BAD_HEADER for an `mlkem768x25519` stanza that is malformed.\n */\nexport async function unwrapFileKey(stanza: Stanza, secretKey: Uint8Array): Promise<Uint8Array | null> {\n if (stanza.type !== XWING_STANZA_TYPE) return null\n if (secretKey.length !== XWING_SECRET_KEY_LENGTH) {\n throw new EnvelopeError('BAD_RECIPIENT_KEY', `Recipient secret key must be ${XWING_SECRET_KEY_LENGTH} bytes`)\n }\n const enc = stanza.args.length === 1 ? decodeBase64NoPad(stanza.args[0]!) : null\n if (!enc || enc.length !== XWING_ENC_LENGTH) {\n throw new EnvelopeError('BAD_HEADER', `${XWING_STANZA_TYPE} stanza needs one argument: ${XWING_ENC_LENGTH} bytes of base64`)\n }\n if (stanza.body.length !== WRAPPED_KEY_LENGTH) {\n throw new EnvelopeError('BAD_HEADER', `${XWING_STANZA_TYPE} stanza body must be ${WRAPPED_KEY_LENGTH} bytes`)\n }\n return openBase(enc, secretKey, XWING_INFO, new Uint8Array(0), stanza.body)\n}\n\n/**\n * An `unwrap` callback for `decryptEnvelope` that tries every `mlkem768x25519` stanza against\n * each secret key, in order, and returns the first file key that opens.\n */\nexport function unwrapWithSecretKeys(secretKeys: Uint8Array[]): (header: EnvelopeHeader) => Promise<Uint8Array | null> {\n return async (header) => {\n for (const stanza of header.stanzas) {\n for (const key of secretKeys) {\n const fileKey = await unwrapFileKey(stanza, key)\n if (fileKey) return fileKey\n }\n }\n return null\n }\n}\n","/**\n * Who may receive keys for an access policy. Adapters answer one question for one policy kind:\n * was `address` entitled at `blockTag`? Licensing, subscriptions and token gates each register\n * their own kind; key grants are issued only to addresses an adapter says yes to.\n */\n\n/** The parts of an access policy an adapter reads. `kind` selects the adapter. */\nexport interface AccessPolicyRef {\n policyId: string\n kind: string\n /** Adapter-specific configuration fixed when the policy was created (contract address, schema uid...). */\n gateConfig?: unknown\n}\n\n/** A block number, or a tag such as 'latest'. Entitlement decisions pin a block so they can be re-run. */\nexport type EntitlementBlockTag = bigint | 'latest'\n\nexport interface EntitlementAdapter {\n isEntitled(policy: AccessPolicyRef, address: string, blockTag: EntitlementBlockTag): Promise<boolean>\n}\n\nexport class UnknownEntitlementKindError extends Error {\n readonly kind: string\n constructor(kind: string) {\n super(`No entitlement adapter is registered for policy kind \"${kind}\"`)\n this.name = 'UnknownEntitlementKindError'\n this.kind = kind\n }\n}\n\nconst adapters = new Map<string, EntitlementAdapter>()\n\n/**\n * Registers the adapter for a policy kind and returns a function that removes it. Registering a\n * kind that already has an adapter throws, so two packages can't silently replace each other.\n */\nexport function registerEntitlementAdapter(kind: string, adapter: EntitlementAdapter): () => void {\n if (!kind) throw new Error('Entitlement kind must be a non-empty string')\n if (adapters.has(kind)) throw new Error(`An entitlement adapter is already registered for \"${kind}\"`)\n adapters.set(kind, adapter)\n return () => {\n if (adapters.get(kind) === adapter) adapters.delete(kind)\n }\n}\n\n/** Asks the adapter registered for `policy.kind`. Throws UnknownEntitlementKindError when there is none. */\nexport function isEntitled(policy: AccessPolicyRef, address: string, blockTag: EntitlementBlockTag = 'latest'): Promise<boolean> {\n const adapter = adapters.get(policy.kind)\n if (!adapter) return Promise.reject(new UnknownEntitlementKindError(policy.kind))\n return adapter.isEntitled(policy, address, blockTag)\n}\n","/**\n * The encryption identity: one random 32-byte secret from which the X-Wing recipient key, the\n * X25519 tag key and the Ed25519 binding key are derived, and the recovery key, derived from a\n * 24-word phrase. SPEC.md \"Identity\" and \"Key binding\" are the normative description.\n */\n\nimport { ed25519, x25519 } from '@noble/curves/ed25519.js'\nimport { generateMnemonic, mnemonicToEntropy } from '@scure/bip39'\nimport { wordlist } from '@scure/bip39/wordlists/english.js'\nimport { EnvelopeError, hkdf } from './envelope'\nimport { generateRecipientKeyPair, type RecipientKeyPair } from './recipient'\n\nexport const IDENTITY_SECRET_LENGTH = 32\n\nconst encoder = new TextEncoder()\nconst EMPTY = new Uint8Array(0)\n\nexport interface EncryptionIdentity {\n /**\n * `0x` and 64 hex digits: SHA-256 over the label, the X-Wing public key, the X25519 public key\n * and the Ed25519 binding public key.\n */\n keyId: string\n /** The 32 random bytes everything else derives from. The keystore manifest wraps exactly this. */\n secret: Uint8Array\n /** Version file keys are wrapped to `recipient.publicKey`. */\n recipient: RecipientKeyPair\n /** Static X25519 key for blinded tags (Phase 3). */\n tagKey: { secretKey: Uint8Array; publicKey: Uint8Array }\n /** Ed25519 key that signs the key binding an account registers ({@link signKeyBinding}). */\n bindingKey: { secretKey: Uint8Array; publicKey: Uint8Array }\n}\n\nfunction toHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/** The identity derived from `secret`. Throws BAD_KEYSTORE when it isn't 32 bytes. */\nexport async function encryptionIdentityFromSecret(secret: Uint8Array): Promise<EncryptionIdentity> {\n if (secret.length !== IDENTITY_SECRET_LENGTH) {\n throw new EnvelopeError('BAD_KEYSTORE', `Identity secret must be ${IDENTITY_SECRET_LENGTH} bytes`)\n }\n const xwingSeed = await hkdf(secret, EMPTY, encoder.encode('seed-private/v1/identity/mlkem768x25519'), 32)\n const tagSecret = await hkdf(secret, EMPTY, encoder.encode('seed-private/v1/identity/x25519'), 32)\n const recipient = generateRecipientKeyPair(xwingSeed)\n const bindingSecret = await hkdf(secret, EMPTY, encoder.encode('seed-private/v1/identity/ed25519'), 32)\n const tagKey = { secretKey: tagSecret, publicKey: x25519.getPublicKey(tagSecret) }\n const bindingKey = { secretKey: bindingSecret, publicKey: ed25519.getPublicKey(bindingSecret) }\n const keyId = await encryptionKeyId(recipient.publicKey, tagKey.publicKey, bindingKey.publicKey)\n return { keyId, secret: new Uint8Array(secret), recipient, tagKey, bindingKey }\n}\n\n/** The key id of three public keys, as SPEC.md \"Identity\" defines it. */\nexport async function encryptionKeyId(recipientPublicKey: Uint8Array, tagPublicKey: Uint8Array, bindingPublicKey: Uint8Array): Promise<string> {\n const label = encoder.encode('seed-private/v1/key-id')\n const input = new Uint8Array(label.length + 1 + recipientPublicKey.length + tagPublicKey.length + bindingPublicKey.length)\n input.set(label, 0)\n input.set(recipientPublicKey, label.length + 1)\n input.set(tagPublicKey, label.length + 1 + recipientPublicKey.length)\n input.set(bindingPublicKey, label.length + 1 + recipientPublicKey.length + tagPublicKey.length)\n return `0x${toHex(new Uint8Array(await crypto.subtle.digest('SHA-256', input)))}`\n}\n\n/** What a key binding names: the account registering the key and the chain it registers on. */\nexport interface KeyBindingTarget {\n /** `0x` and 40 hex digits, any case. */\n account: string\n chainId: number | bigint\n}\n\nfunction hexToBytes(value: string, length: number, what: string): Uint8Array {\n const hex = value.startsWith('0x') ? value.slice(2) : value\n if (!new RegExp(`^[0-9a-fA-F]{${length * 2}}$`).test(hex)) throw new EnvelopeError('BAD_KEYSTORE', `${what} must be ${length} bytes of hex`)\n return Uint8Array.from({ length }, (_, i) => parseInt(hex.slice(i * 2, i * 2 + 2), 16))\n}\n\n/**\n * The bytes a binding signature covers (SPEC.md \"Key binding\"): the label, a zero byte, the\n * 32-byte key id, the chain id as a 32-byte big-endian integer and the 20-byte account.\n */\nexport function keyBindingMessage(keyId: string, { account, chainId }: KeyBindingTarget): Uint8Array {\n const label = encoder.encode('seed-private/v1/key-binding')\n const chain = BigInt(chainId)\n if (chain < 0n || chain >= 1n << 256n) throw new EnvelopeError('BAD_KEYSTORE', 'chainId must fit in 32 bytes')\n const out = new Uint8Array(label.length + 1 + 32 + 32 + 20)\n out.set(label, 0)\n out.set(hexToBytes(keyId, 32, 'keyId'), label.length + 1)\n out.set(hexToBytes(chain.toString(16).padStart(64, '0'), 32, 'chainId'), label.length + 33)\n out.set(hexToBytes(account, 20, 'account'), label.length + 65)\n return out\n}\n\n/**\n * The identity's Ed25519 signature that it belongs to `account` on `chainId`. The account's\n * `seedprotocol.encryptionKey` registration carries it, so a reader can tell the account's own\n * key from another account's keys copied into its registration.\n */\nexport function signKeyBinding(identity: EncryptionIdentity, target: KeyBindingTarget): Uint8Array {\n return ed25519.sign(keyBindingMessage(identity.keyId, target), identity.bindingKey.secretKey)\n}\n\n/** Whether `signature` is `bindingPublicKey`'s binding of `keyId` to `target`. */\nexport function verifyKeyBinding(\n { keyId, bindingPublicKey, signature }: { keyId: string; bindingPublicKey: Uint8Array; signature: Uint8Array },\n target: KeyBindingTarget,\n): boolean {\n try {\n return ed25519.verify(signature, keyBindingMessage(keyId, target), bindingPublicKey)\n } catch {\n return false\n }\n}\n\n/** A new identity from fresh random bytes. */\nexport function createEncryptionIdentity(): Promise<EncryptionIdentity> {\n return encryptionIdentityFromSecret(crypto.getRandomValues(new Uint8Array(IDENTITY_SECRET_LENGTH)))\n}\n\n/** 24 English BIP39 words encoding 32 random bytes. Show it to the user once; it isn't stored. */\nexport function generateRecoveryPhrase(): string {\n return generateMnemonic(wordlist, 256)\n}\n\nfunction normalizePhrase(phrase: string): string {\n return phrase.normalize('NFKD').trim().toLowerCase().split(/\\s+/).join(' ')\n}\n\n/**\n * The recovery key pair for a phrase. Case, extra spaces and line breaks are ignored. Throws\n * BAD_RECOVERY_PHRASE for anything but 24 known words with a valid checksum.\n */\nexport async function recoveryKeyFromPhrase(phrase: string): Promise<RecipientKeyPair> {\n const words = normalizePhrase(phrase)\n let entropy: Uint8Array\n try {\n entropy = mnemonicToEntropy(words, wordlist)\n } catch {\n throw new EnvelopeError('BAD_RECOVERY_PHRASE', 'Recovery phrase has an unknown word or a bad checksum')\n }\n if (entropy.length !== 32) throw new EnvelopeError('BAD_RECOVERY_PHRASE', 'Recovery phrase must be 24 words')\n const seed = await hkdf(entropy, EMPTY, encoder.encode('seed-private/v1/recovery/mlkem768x25519'), 32)\n return generateRecipientKeyPair(seed)\n}\n","/**\n * The keystore manifest: a seed-private/v1 envelope whose body is the identity secret, with one\n * stanza per way to unlock it (recovery phrase, a passkey's PRF, an EOA signature). It is public,\n * so every stanza must be safe to publish. SPEC.md \"Keystore manifest\" is the normative description.\n */\n\nimport { decodeBase64NoPad, encodeBase64NoPad } from './base64'\nimport {\n EnvelopeError,\n FILE_KEY_LENGTH,\n decryptEnvelope,\n encryptEnvelope,\n generateEnvelopeId,\n hkdf,\n parseEnvelopeHeader,\n type EnvelopeHeader,\n type Stanza,\n} from './envelope'\nimport { IDENTITY_SECRET_LENGTH, encryptionIdentityFromSecret, recoveryKeyFromPhrase, type EncryptionIdentity } from './identity'\nimport { XWING_STANZA_TYPE, unwrapFileKey, wrapFileKey } from './recipient'\n\nexport const KEYSTORE_CONTENT_TYPE = 'application/vnd.seedprotocol.identity-secret'\nexport const PASSKEY_PRF_STANZA_TYPE = 'passkey-prf'\nexport const EOA_SIGNATURE_STANZA_TYPE = 'eoa-signature'\nconst SALT_LENGTH = 32\nconst WRAPPED_KEY_LENGTH = FILE_KEY_LENGTH + 16\n\nconst encoder = new TextEncoder()\nconst EMPTY = new Uint8Array(0)\nconst ZERO_NONCE = new Uint8Array(12)\n\n/** The keystore's file key. It depends only on the identity, so any unlocked device can add a stanza. */\nfunction keystoreFileKey(identity: EncryptionIdentity): Promise<Uint8Array<ArrayBuffer>> {\n return hkdf(identity.secret, EMPTY, encoder.encode('seed-private/v1/keystore'), FILE_KEY_LENGTH)\n}\n\nasync function sealWithKek(kek: Uint8Array<ArrayBuffer>, fileKey: Uint8Array<ArrayBuffer>): Promise<Uint8Array> {\n const key = await crypto.subtle.importKey('raw', kek, 'AES-GCM', false, ['encrypt'])\n return new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: ZERO_NONCE }, key, fileKey))\n}\n\nasync function openWithKek(kek: Uint8Array<ArrayBuffer>, body: Uint8Array): Promise<Uint8Array | null> {\n const key = await crypto.subtle.importKey('raw', kek, 'AES-GCM', false, ['decrypt'])\n try {\n return new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: ZERO_NONCE }, key, new Uint8Array(body)))\n } catch {\n return null\n }\n}\n\nfunction randomSalt(): Uint8Array<ArrayBuffer> {\n return crypto.getRandomValues(new Uint8Array(SALT_LENGTH))\n}\n\nfunction toHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\nfunction checkArgs(stanza: Stanza, count: number, lengths: number[]): Uint8Array<ArrayBuffer>[] {\n const decoded = stanza.args.length === count ? stanza.args.map((a) => decodeBase64NoPad(a)) : []\n const ok =\n decoded.length === count &&\n decoded.every((d, i) => d !== null && (lengths[i] === 0 ? d.length > 0 : d.length === lengths[i])) &&\n stanza.body.length === WRAPPED_KEY_LENGTH\n if (!ok) throw new EnvelopeError('BAD_HEADER', `Malformed ${stanza.type} stanza`)\n return decoded as Uint8Array<ArrayBuffer>[]\n}\n\n// Recovery phrase ------------------------------------------------------------------------------\n\n/** A stanza that lets the recovery phrase behind `recoveryPublicKey` unlock this identity. */\nexport async function recoveryStanza(identity: EncryptionIdentity, recoveryPublicKey: Uint8Array): Promise<Stanza> {\n return wrapFileKey(await keystoreFileKey(identity), recoveryPublicKey)\n}\n\n// Passkey PRF ----------------------------------------------------------------------------------\n\nexport interface PasskeyPrfRequest {\n credentialId: Uint8Array\n /** The PRF input (`prf.eval.first`) for this credential. */\n salt: Uint8Array\n}\n\n/**\n * Asks the user for one of `requests`' passkeys and returns its PRF output, or null when they\n * cancel or have none of them. `passkeyPrf()` is the WebAuthn implementation.\n */\nexport type PasskeyPrfEvaluator = (\n requests: PasskeyPrfRequest[],\n) => Promise<{ credentialId: Uint8Array; prfOutput: Uint8Array } | null>\n\nasync function passkeyKek(prfOutput: Uint8Array, salt: Uint8Array): Promise<Uint8Array<ArrayBuffer>> {\n return hkdf(prfOutput, salt, encoder.encode('seed-private/v1/passkey-prf'), 32)\n}\n\n/** A new random PRF input for `passkeyStanza`. Evaluate the passkey's PRF with it, then build the stanza. */\nexport function generatePasskeySalt(): Uint8Array {\n return randomSalt()\n}\n\n/** A stanza that lets the passkey `credentialId` unlock this identity, given its PRF output for `salt`. */\nexport async function passkeyStanza(\n identity: EncryptionIdentity,\n { credentialId, salt, prfOutput }: { credentialId: Uint8Array; salt: Uint8Array; prfOutput: Uint8Array },\n): Promise<Stanza> {\n if (salt.length !== SALT_LENGTH) throw new EnvelopeError('BAD_KEYSTORE', `Passkey salt must be ${SALT_LENGTH} bytes`)\n if (credentialId.length === 0 || prfOutput.length < 32) throw new EnvelopeError('BAD_KEYSTORE', 'Missing passkey credential or PRF output')\n const body = await sealWithKek(await passkeyKek(prfOutput, salt), await keystoreFileKey(identity))\n return { type: PASSKEY_PRF_STANZA_TYPE, args: [encodeBase64NoPad(credentialId), encodeBase64NoPad(salt)], body }\n}\n\nfunction passkeyArgs(stanza: Stanza): PasskeyPrfRequest {\n const [credentialId, salt] = checkArgs(stanza, 2, [0, SALT_LENGTH]) as [Uint8Array, Uint8Array]\n return { credentialId, salt }\n}\n\n// EOA signature --------------------------------------------------------------------------------\n\n/**\n * The text an EOA signs with `personal_sign` (EIP-191) to unlock the identity. The salt makes it\n * different per stanza; the warning is there because the signature is the key.\n */\nexport function eoaSignatureMessage(salt: Uint8Array): string {\n return [\n 'Unlock your Seed Protocol encryption key',\n '',\n 'Signing this message lets this app read your private Versions. Anyone who gets this signature can read them too, so sign it only in apps you trust.',\n '',\n `Key: 0x${toHex(salt)}`,\n ].join('\\n')\n}\n\n/** A new random salt for `eoaSignatureStanza`. Sign `eoaSignatureMessage(salt)`, then build the stanza. */\nexport function generateEoaSignatureSalt(): Uint8Array {\n return randomSalt()\n}\n\nconst SECP256K1_N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n\n\n/**\n * `r || s` with `s` in the lower half of the curve order. Accepts a 65-byte signature (any `v`) or a\n * 64-byte EIP-2098 one, so wallets that differ only in how they encode `v` derive the same key.\n */\nfunction signatureKeyMaterial(signature: string): Uint8Array<ArrayBuffer> {\n const hex = signature.startsWith('0x') ? signature.slice(2) : signature\n if (!/^[0-9a-fA-F]*$/.test(hex) || (hex.length !== 130 && hex.length !== 128)) {\n throw new EnvelopeError('BAD_KEYSTORE', 'Signature must be 64 or 65 bytes of hex')\n }\n const r = hex.slice(0, 64)\n let s = BigInt(`0x${hex.slice(64, 128)}`)\n if (hex.length === 128) s &= (1n << 255n) - 1n\n if (s > SECP256K1_N / 2n) s = SECP256K1_N - s\n const out = new Uint8Array(64)\n const full = r + s.toString(16).padStart(64, '0')\n for (let i = 0; i < 64; i++) out[i] = parseInt(full.slice(i * 2, i * 2 + 2), 16)\n return out\n}\n\nasync function signatureKek(signature: string, salt: Uint8Array): Promise<Uint8Array<ArrayBuffer>> {\n return hkdf(signatureKeyMaterial(signature), salt, encoder.encode('seed-private/v1/eoa-signature'), 32)\n}\n\n/**\n * A stanza that lets an EOA unlock this identity by signing `eoaSignatureMessage(salt)` again.\n * Only for EOAs whose wallet signs deterministically (RFC 6979); smart-account signatures change\n * every time and would never unlock it.\n *\n * Prefer a passkey and the recovery phrase. This stanza trades security for convenience: the\n * manifest is public, so anyone who gets the EOA's private key can sign the message, open the\n * manifest and read every private Version wrapped to this identity, past and future. That\n * includes a leaked or phished key, and a future quantum computer, which can recover the key from\n * any transaction the EOA has sent. `acceptWalletKeyRisk: true` says the user chose that.\n */\nexport async function eoaSignatureStanza(\n identity: EncryptionIdentity,\n { salt, signature, acceptWalletKeyRisk }: { salt: Uint8Array; signature: string; acceptWalletKeyRisk: true },\n): Promise<Stanza> {\n if (acceptWalletKeyRisk !== true) {\n throw new EnvelopeError('BAD_KEYSTORE', 'eoaSignatureStanza needs acceptWalletKeyRisk: true; prefer a passkey and the recovery phrase')\n }\n if (salt.length !== SALT_LENGTH) throw new EnvelopeError('BAD_KEYSTORE', `Signature salt must be ${SALT_LENGTH} bytes`)\n const body = await sealWithKek(await signatureKek(signature, salt), await keystoreFileKey(identity))\n return { type: EOA_SIGNATURE_STANZA_TYPE, args: [encodeBase64NoPad(salt)], body }\n}\n\n// Manifest -------------------------------------------------------------------------------------\n\n/** A keystore manifest for `identity` carrying `stanzas`. Each call picks a new envelope id. */\nexport async function buildKeystoreManifest(identity: EncryptionIdentity, stanzas: Stanza[]): Promise<Uint8Array> {\n if (stanzas.length === 0) throw new EnvelopeError('BAD_KEYSTORE', 'A keystore manifest needs at least one stanza')\n return encryptEnvelope({\n fileKey: await keystoreFileKey(identity),\n bind: { envelopeId: generateEnvelopeId(), keyId: identity.keyId, purpose: 'keystore' },\n stanzas,\n contentType: KEYSTORE_CONTENT_TYPE,\n body: identity.secret,\n })\n}\n\nexport type KeystoreAuthenticator =\n | { type: 'recovery' }\n | { type: 'passkey'; credentialId: Uint8Array }\n | { type: 'eoa-signature'; salt: Uint8Array }\n\n/** The key id a manifest claims and the authenticators that can unlock it. Doesn't decrypt anything. */\nexport function describeKeystoreManifest(bytes: Uint8Array): { keyId: string; authenticators: KeystoreAuthenticator[] } {\n const header = keystoreHeader(bytes)\n const authenticators: KeystoreAuthenticator[] = []\n for (const stanza of header.stanzas) {\n if (stanza.type === XWING_STANZA_TYPE) authenticators.push({ type: 'recovery' })\n else if (stanza.type === PASSKEY_PRF_STANZA_TYPE) authenticators.push({ type: 'passkey', credentialId: passkeyArgs(stanza).credentialId })\n else if (stanza.type === EOA_SIGNATURE_STANZA_TYPE) authenticators.push({ type: 'eoa-signature', salt: checkArgs(stanza, 1, [SALT_LENGTH])[0]! })\n }\n return { keyId: header.bind.keyId!, authenticators }\n}\n\nfunction keystoreHeader(bytes: Uint8Array): EnvelopeHeader {\n const header = parseEnvelopeHeader(bytes)\n if (header.bind.purpose !== 'keystore' || !/^0x[0-9a-f]{64}$/.test(header.bind.keyId ?? '')) {\n throw new EnvelopeError('BAD_KEYSTORE', 'Not a keystore manifest')\n }\n return header\n}\n\nexport type KeystoreUnlock =\n | { recoveryPhrase: string }\n | { passkey: PasskeyPrfEvaluator }\n | { signMessage: (message: string) => Promise<string> }\n\nasync function unwrapKeystore(header: EnvelopeHeader, unlock: KeystoreUnlock): Promise<Uint8Array | null> {\n if ('recoveryPhrase' in unlock) {\n const { secretKey } = await recoveryKeyFromPhrase(unlock.recoveryPhrase)\n for (const stanza of header.stanzas) {\n const fileKey = await unwrapFileKey(stanza, secretKey)\n if (fileKey) return fileKey\n }\n return null\n }\n if ('passkey' in unlock) {\n const stanzas = header.stanzas.filter((s) => s.type === PASSKEY_PRF_STANZA_TYPE)\n if (stanzas.length === 0) return null\n const requests = stanzas.map(passkeyArgs)\n const result = await unlock.passkey(requests)\n if (!result) return null\n for (let i = 0; i < stanzas.length; i++) {\n if (!sameBytes(requests[i]!.credentialId, result.credentialId)) continue\n const fileKey = await openWithKek(await passkeyKek(result.prfOutput, requests[i]!.salt), stanzas[i]!.body)\n if (fileKey) return fileKey\n }\n return null\n }\n for (const stanza of header.stanzas) {\n if (stanza.type !== EOA_SIGNATURE_STANZA_TYPE) continue\n const [salt] = checkArgs(stanza, 1, [SALT_LENGTH]) as [Uint8Array]\n const signature = await unlock.signMessage(eoaSignatureMessage(salt))\n const fileKey = await openWithKek(await signatureKek(signature, salt), stanza.body)\n if (fileKey) return fileKey\n }\n return null\n}\n\nfunction sameBytes(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((v, i) => v === b[i])\n}\n\n/**\n * Unlocks a keystore manifest and returns the identity. Throws NO_KEY when the authenticator\n * opens no stanza, and BAD_KEYSTORE when the manifest's contents don't match its key id (pass\n * `expectKeyId`, from the registration attestation, to also reject another identity's manifest).\n */\nexport async function openKeystoreManifest(\n bytes: Uint8Array,\n unlock: KeystoreUnlock,\n options: { expectKeyId?: string } = {},\n): Promise<EncryptionIdentity> {\n const header = keystoreHeader(bytes)\n if (options.expectKeyId !== undefined && header.bind.keyId !== options.expectKeyId) {\n throw new EnvelopeError('BIND_MISMATCH', 'Keystore manifest is for another key id')\n }\n const unwrapped: { fileKey: Uint8Array | null } = { fileKey: null }\n const opened = await decryptEnvelope(bytes, {\n unwrap: async (h) => (unwrapped.fileKey = await unwrapKeystore(h, unlock)),\n })\n if (opened.contentType !== KEYSTORE_CONTENT_TYPE || opened.body.length !== IDENTITY_SECRET_LENGTH) {\n throw new EnvelopeError('BAD_KEYSTORE', 'Keystore manifest body is not an identity secret')\n }\n const identity = await encryptionIdentityFromSecret(opened.body)\n if (identity.keyId !== header.bind.keyId || !sameBytes(await keystoreFileKey(identity), unwrapped.fileKey!)) {\n throw new EnvelopeError('BAD_KEYSTORE', 'Keystore manifest contents do not match its key id')\n }\n return identity\n}\n","/**\n * WebAuthn calls for the `passkey-prf` keystore stanza. Browser only. The challenges are random and\n * never checked by a server: the passkey is used for its PRF output, not to sign in.\n */\n\nimport { EnvelopeError, type Stanza } from './envelope'\nimport type { EncryptionIdentity } from './identity'\nimport { generatePasskeySalt, passkeyStanza, type PasskeyPrfEvaluator } from './keystore'\n\nexport interface PasskeyOptions {\n /** Defaults to the page's effective domain. A passkey works only on the domain it was made for. */\n rpId?: string\n}\n\nfunction base64Url(bytes: Uint8Array): string {\n let binary = ''\n for (const b of bytes) binary += String.fromCharCode(b)\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\nfunction toBytes(value: BufferSource): Uint8Array {\n return value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value.buffer, value.byteOffset, value.byteLength)\n}\n\nfunction randomChallenge(): Uint8Array<ArrayBuffer> {\n return crypto.getRandomValues(new Uint8Array(32))\n}\n\n/** A `PasskeyPrfEvaluator` that asks the browser for one of the requested passkeys. */\nexport function passkeyPrf(options: PasskeyOptions = {}): PasskeyPrfEvaluator {\n return async (requests) => {\n const evalByCredential: Record<string, AuthenticationExtensionsPRFValues> = {}\n for (const r of requests) evalByCredential[base64Url(r.credentialId)] = { first: new Uint8Array(r.salt) }\n const credential = (await navigator.credentials.get({\n publicKey: {\n challenge: randomChallenge(),\n rpId: options.rpId,\n allowCredentials: requests.map((r) => ({ type: 'public-key' as const, id: new Uint8Array(r.credentialId) })),\n userVerification: 'required',\n extensions: { prf: { evalByCredential } },\n },\n })) as PublicKeyCredential | null\n if (!credential) return null\n const first = credential.getClientExtensionResults().prf?.results?.first\n if (!first) throw new EnvelopeError('PASSKEY_PRF_UNSUPPORTED', 'This passkey or browser does not support the PRF extension')\n return { credentialId: new Uint8Array(credential.rawId), prfOutput: toBytes(first) }\n }\n}\n\n/**\n * Creates a passkey and returns a keystore stanza for it. Two prompts: one to create the passkey,\n * one to evaluate its PRF. Throws PASSKEY_PRF_UNSUPPORTED when the authenticator has no PRF.\n */\nexport async function enrollPasskey(\n identity: EncryptionIdentity,\n options: PasskeyOptions & { rpName: string; userName: string },\n): Promise<Stanza> {\n const created = (await navigator.credentials.create({\n publicKey: {\n challenge: randomChallenge(),\n rp: { name: options.rpName, id: options.rpId },\n user: { id: crypto.getRandomValues(new Uint8Array(16)), name: options.userName, displayName: options.userName },\n pubKeyCredParams: [\n { type: 'public-key', alg: -7 },\n { type: 'public-key', alg: -257 },\n ],\n authenticatorSelection: { residentKey: 'preferred', userVerification: 'required' },\n extensions: { prf: {} },\n },\n })) as PublicKeyCredential | null\n if (!created) throw new EnvelopeError('PASSKEY_PRF_UNSUPPORTED', 'No passkey was created')\n if (created.getClientExtensionResults().prf?.enabled === false) {\n throw new EnvelopeError('PASSKEY_PRF_UNSUPPORTED', 'This passkey does not support the PRF extension')\n }\n const credentialId = new Uint8Array(created.rawId)\n const salt = generatePasskeySalt()\n const result = await passkeyPrf(options)([{ credentialId, salt }])\n if (!result) throw new EnvelopeError('PASSKEY_PRF_UNSUPPORTED', 'The passkey was not used')\n return passkeyStanza(identity, { credentialId, salt, prfOutput: result.prfOutput })\n}\n","/**\n * Keeps unlocked identities on this device in IndexedDB, each encrypted with its own\n * non-extractable AES-GCM key stored beside it. That keeps the secret from being read out of the\n * database by copying its files or calling `exportKey`, but any script on the origin can still\n * decrypt it. Don't save an identity on a shared device; unlock it from the keystore manifest\n * each session instead.\n */\n\nimport { EnvelopeError } from './envelope'\nimport { encryptionIdentityFromSecret, type EncryptionIdentity } from './identity'\n\nconst DB_NAME = 'seed-encryption'\nconst STORE = 'identities'\n\ninterface DeviceIdentityRecord {\n keyId: string\n deviceKey: CryptoKey\n iv: Uint8Array\n ciphertext: Uint8Array\n savedAt: number\n}\n\nfunction request<T>(req: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n req.onsuccess = () => resolve(req.result)\n req.onerror = () => reject(req.error)\n })\n}\n\nfunction openDb(): Promise<IDBDatabase> {\n const req = indexedDB.open(DB_NAME, 1)\n req.onupgradeneeded = () => req.result.createObjectStore(STORE, { keyPath: 'keyId' })\n return request(req)\n}\n\nasync function withStore<T>(mode: IDBTransactionMode, fn: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {\n const db = await openDb()\n try {\n const tx = db.transaction(STORE, mode)\n const done = new Promise<void>((resolve, reject) => {\n tx.oncomplete = () => resolve()\n tx.onerror = () => reject(tx.error)\n tx.onabort = () => reject(tx.error)\n })\n const result = await request(fn(tx.objectStore(STORE)))\n await done\n return result\n } finally {\n db.close()\n }\n}\n\n/** Saves `identity` on this device, replacing an earlier save of the same key id. */\nexport async function saveIdentityOnDevice(identity: EncryptionIdentity): Promise<void> {\n const deviceKey = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])\n const iv = crypto.getRandomValues(new Uint8Array(12))\n const aad = new TextEncoder().encode(identity.keyId)\n const ciphertext = new Uint8Array(\n await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: aad }, deviceKey, new Uint8Array(identity.secret)),\n )\n const record: DeviceIdentityRecord = { keyId: identity.keyId, deviceKey, iv, ciphertext, savedAt: Date.now() }\n await withStore('readwrite', (store) => store.put(record))\n}\n\n/** The identity saved under `keyId`, or null when this device has none. */\nexport async function loadIdentityFromDevice(keyId: string): Promise<EncryptionIdentity | null> {\n const record = (await withStore('readonly', (store) => store.get(keyId))) as DeviceIdentityRecord | undefined\n if (!record) return null\n let secret: Uint8Array\n try {\n secret = new Uint8Array(\n await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: new Uint8Array(record.iv), additionalData: new TextEncoder().encode(keyId) },\n record.deviceKey,\n new Uint8Array(record.ciphertext),\n ),\n )\n } catch {\n throw new EnvelopeError('BAD_KEYSTORE', `The identity saved for ${keyId} does not decrypt`)\n }\n const identity = await encryptionIdentityFromSecret(secret)\n if (identity.keyId !== keyId) throw new EnvelopeError('BAD_KEYSTORE', `The identity saved for ${keyId} has another key id`)\n return identity\n}\n\n/** Key ids of the identities saved on this device. */\nexport async function listIdentitiesOnDevice(): Promise<string[]> {\n return (await withStore('readonly', (store) => store.getAllKeys())) as string[]\n}\n\n/** Deletes the identity saved under `keyId` from this device. Its keystore manifest is unaffected. */\nexport async function forgetIdentityOnDevice(keyId: string): Promise<void> {\n await withStore('readwrite', (store) => store.delete(keyId))\n}\n","/**\n * Encrypts the uploads of private properties for `@seedprotocol/publish` (its\n * `encryptPrivateUpload` config, the SDK's `encryptUpload`). Each upload becomes its own envelope\n * with a fresh file key and envelope id, wrapped to every recipient. It needs only public keys, so\n * a session key can publish private Versions wrapped to the account's registered key.\n */\n\nimport { ENVELOPE_FORMAT_TAG, EnvelopeError, encryptEnvelope, generateEnvelopeId, generateFileKey, type EnvelopePadding } from './envelope'\nimport { XWING_PUBLIC_KEY_LENGTH, wrapFileKey } from './recipient'\n\nexport interface PrivateUploadEncryptorOptions {\n /**\n * X-Wing public keys to wrap each upload's file key to. Always include the publisher's\n * registered key (`recipientKey` from `getVerifiedEncryptionKey` in `@seedprotocol/publish`), or the\n * publisher can't read the Version on another device.\n */\n recipients: Uint8Array[]\n /** Bind values known before upload, such as `chainId` and `publisher`. `envelopeId` is added per upload. */\n bind?: Record<string, string>\n /** Default `padme`. */\n padding?: EnvelopePadding\n}\n\n/** What the SDK hands an encryptor, and what it takes back. Structural, so no SDK import. */\nexport interface UploadToEncrypt {\n blob: Blob\n contentType: string | undefined\n}\nexport interface EncryptedUpload {\n blob: Blob\n tags: { name: string; value: string }[]\n}\n\n/** An `encryptPrivateUpload` for `@seedprotocol/publish`. */\nexport function createPrivateUploadEncryptor(options: PrivateUploadEncryptorOptions): (upload: UploadToEncrypt) => Promise<EncryptedUpload> {\n const recipients = options.recipients.map((key) => new Uint8Array(key))\n if (recipients.length === 0) throw new EnvelopeError('BAD_RECIPIENT_KEY', 'A private upload needs at least one recipient')\n for (const key of recipients) {\n if (key.length !== XWING_PUBLIC_KEY_LENGTH) {\n throw new EnvelopeError('BAD_RECIPIENT_KEY', `Recipient public key must be ${XWING_PUBLIC_KEY_LENGTH} bytes`)\n }\n }\n if (options.bind && 'envelopeId' in options.bind) {\n throw new EnvelopeError('BAD_BIND', 'envelopeId is chosen per upload; leave it out of bind')\n }\n return async ({ blob, contentType }) => {\n const fileKey = generateFileKey()\n const envelope = await encryptEnvelope({\n fileKey,\n bind: { ...options.bind, envelopeId: generateEnvelopeId() },\n stanzas: await Promise.all(recipients.map((key) => wrapFileKey(fileKey, key))),\n contentType: contentType || 'application/octet-stream',\n body: new Uint8Array(await blob.arrayBuffer()),\n padding: options.padding,\n })\n return { blob: new Blob([envelope as BlobPart]), tags: [{ ...ENVELOPE_FORMAT_TAG }] }\n }\n}\n","/**\n * Opens downloaded envelopes for the SDK (`setEnvelopeDecryptor` in `@seedprotocol/sdk`): tries\n * each unlocked identity's recipient key and returns the plaintext with the content type recorded\n * inside, or null when none of them is a recipient.\n */\n\nimport { EnvelopeError, decryptEnvelope } from './envelope'\nimport type { EncryptionIdentity } from './identity'\nimport { unwrapWithSecretKeys } from './recipient'\n\n/** What `setEnvelopeDecryptor` takes. Structural, so no SDK import. */\nexport type EnvelopeOpener = (envelope: Uint8Array) => Promise<{ contentType: string; body: Uint8Array } | null>\n\nexport function createEnvelopeDecryptor(identities: EncryptionIdentity[]): EnvelopeOpener {\n const unwrap = unwrapWithSecretKeys(identities.map((identity) => identity.recipient.secretKey))\n return async (envelope) => {\n try {\n const { contentType, body } = await decryptEnvelope(envelope, { unwrap })\n return { contentType, body }\n } catch (error) {\n if (error instanceof EnvelopeError && error.code === 'NO_KEY') return null\n throw error\n }\n }\n}\n"],"mappings":";;;;;AAEA,IAAMO,IAAW,oEACXC,qBAAS,IAAI,WAAW,GAAG,EAAA,CAAE,KAAK,EAAE;AAC1C,KAAK,IAAIC,IAAI,GAAGA,IAAI,IAAiB,KAAK,EAAOF,EAAS,WAAWE,CAAC,KAAKA;AAE3E,SAAgBC,EAAkB,GAA2B;CAC3D,IAAIC,IAAM,IACNF,IAAI;CACR,OAAOA,IAAI,IAAIG,EAAM,QAAQ,KAAK,GAAG;EACnC,IAAMC,IAAKD,EAAMH,MAAO,KAAOG,EAAMH,IAAI,MAAO,IAAKG,EAAMH,IAAI;EAC/D,KAAOF,EAASM,KAAK,MAAON,EAAUM,KAAK,KAAM,MAAON,EAAUM,KAAK,IAAK,MAAON,EAASM,IAAI;CAClG;CACA,IAAMC,IAAOF,EAAM,SAASH;CAC5B,IAAIK,MAAS,GAAG;EACd,IAAMD,IAAID,EAAMH,MAAO;EACvB,KAAOF,EAASM,KAAK,MAAON,EAAUM,KAAK,KAAM;CACnD,OAAO,IAAIC,MAAS,GAAG;EACrB,IAAMD,IAAKD,EAAMH,MAAO,KAAOG,EAAMH,IAAI,MAAO;EAChD,KAAOF,EAASM,KAAK,MAAON,EAAUM,KAAK,KAAM,MAAON,EAAUM,KAAK,IAAK;CAC9E;CACA,OAAOF;AACT;AAGA,SAAgBI,EAAkB,GAA8C;CAC9E,IAAIC,EAAK,SAAS,KAAM,GAAG,OAAO;CAClC,IAAML,IAAM,IAAI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AE;IAAa;GAAK;EAC7B,SAASK,GAAO;GACd,IAAIA,aAAiBhR,KAAiBgR,EAAM,SAAS,UAAU,OAAO;GACtE,MAAMA;EACR;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["encoder","concat","encoder","WRAPPED_KEY_LENGTH","encoder","EMPTY","toHex","__defProp","target","ALPHABET","LOOKUP","i","out","bytes","n","rest","text","acc","bits","o","c","v","ENVELOPE_FORMAT","ENVELOPE_CONTENT_TYPE","ENVELOPE_FORMAT_TAG","FILE_KEY_LENGTH","CHUNK_SIZE","TAG_LENGTH","PAYLOAD_NONCE_LENGTH","BODY_LINE_LENGTH","MAX_CONTENT_META_LENGTH","VERSION_LINE","HEADER_INFO","PAYLOAD_INFO","encoder$3","decoder","message","code","BIND_KEY","ENVELOPE_ID","STANZA_ARG","length","b","keys","bind","key","k","parts","p","ikm","salt","info","raw","fileKey","usage","nonce","bindText","iv","index","e","s","step","meta","body","len","unpadded","padded","padding","plain","metaLength","contentType","bodyStart","bodyLength","bodyEnd","stanza","a","b64","lines","stanzas","input","payloadNonce","prefix","mac","chunks","count","part","sealed","end","start","line","pos","r","bindBytes","type","args","header","value","options","payload","sealedChunk","remaining","last","chunk","XWING_KEM_ID","KDF_ID","AEAD_ID","NK","NN","NH","XWING_PUBLIC_KEY_LENGTH","XWING_SECRET_KEY_LENGTH","XWING_ENC_LENGTH","encoder$2","SUITE_ID","HPKE_V1","data","label","prk","empty","pskIdHash","infoHash","context","secret","sharedSecret","ml_kem768_x25519","seed","publicKey","randomness","aad","plaintext","cipherText","enc","secretKey","ciphertext","XWING_STANZA_TYPE","XWING_INFO","WRAPPED_KEY_LENGTH$1","secretKeys","kind","adapters","adapter","policy","address","blockTag","IDENTITY_SECRET_LENGTH","encoder$1","EMPTY$1","xwingSeed","tagSecret","recipient","bindingSecret","tagKey","x25519","bindingKey","ed25519","recipientPublicKey","tagPublicKey","bindingPublicKey","hex","what","chain","chainId","keyId","account","identity","signature","generateMnemonic","wordlist","phrase","words","entropy","mnemonicToEntropy","KEYSTORE_CONTENT_TYPE","PASSKEY_PRF_STANZA_TYPE","EOA_SIGNATURE_STANZA_TYPE","SALT_LENGTH","WRAPPED_KEY_LENGTH","encoder","EMPTY","ZERO_NONCE","kek","decoded","d","lengths","recoveryPublicKey","prfOutput","credentialId","SECP256K1_N","full","acceptWalletKeyRisk","authenticators","unlock","requests","result","unwrapped","opened","h","binary","evalByCredential","credential","first","created","DB_NAME","STORE","resolve","req","reject","db","tx","mode","done","fn","deviceKey","record","store","recipients","envelope","blob","unwrap","identities","error"],"sources":["../src/base64.ts","../src/envelope.ts","../src/hpke.ts","../src/recipient.ts","../src/entitlement.ts","../src/identity.ts","../src/keystore.ts","../src/passkey.ts","../src/deviceStore.ts","../src/uploadEncryptor.ts","../src/envelopeDecryptor.ts"],"sourcesContent":["/** Standard base64 alphabet without padding, as age uses in headers. Strict: rejects padding and non-canonical trailing bits. */\n\nconst ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nconst LOOKUP = new Int16Array(128).fill(-1)\nfor (let i = 0; i < ALPHABET.length; i++) LOOKUP[ALPHABET.charCodeAt(i)] = i\n\nexport function encodeBase64NoPad(bytes: Uint8Array): string {\n let out = ''\n let i = 0\n for (; i + 2 < bytes.length; i += 3) {\n const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8) | bytes[i + 2]!\n out += ALPHABET[n >> 18]! + ALPHABET[(n >> 12) & 63]! + ALPHABET[(n >> 6) & 63]! + ALPHABET[n & 63]!\n }\n const rest = bytes.length - i\n if (rest === 1) {\n const n = bytes[i]! << 16\n out += ALPHABET[n >> 18]! + ALPHABET[(n >> 12) & 63]!\n } else if (rest === 2) {\n const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8)\n out += ALPHABET[n >> 18]! + ALPHABET[(n >> 12) & 63]! + ALPHABET[(n >> 6) & 63]!\n }\n return out\n}\n\n/** Returns null when `text` is not canonical unpadded base64. */\nexport function decodeBase64NoPad(text: string): Uint8Array<ArrayBuffer> | null {\n if (text.length % 4 === 1) return null\n const out = new Uint8Array(Math.floor((text.length * 3) / 4))\n let acc = 0\n let bits = 0\n let o = 0\n for (let i = 0; i < text.length; i++) {\n const c = text.charCodeAt(i)\n const v = c < 128 ? LOOKUP[c]! : -1\n if (v < 0) return null\n acc = (acc << 6) | v\n bits += 6\n if (bits >= 8) {\n bits -= 8\n out[o++] = (acc >> bits) & 0xff\n }\n }\n // Leftover bits must be zero, or two encodings would decode to the same bytes.\n if (bits > 0 && (acc & ((1 << bits) - 1)) !== 0) return null\n return out\n}\n","/**\n * The `seed-private/v1` envelope: an age-style header of recipient stanzas, authenticated with an\n * HMAC under the file key, followed by a chunked AES-256-GCM payload. SPEC.md is the normative\n * description; this file implements it with WebCrypto only.\n */\n\nimport { decodeBase64NoPad, encodeBase64NoPad } from './base64'\n\nexport const ENVELOPE_FORMAT = 'seed-private/v1'\n/** Content-Type for an uploaded envelope. The real type is inside the encrypted payload. */\nexport const ENVELOPE_CONTENT_TYPE = 'application/octet-stream'\n/** Upload tag that marks an envelope, so readers know to decrypt before sniffing. */\nexport const ENVELOPE_FORMAT_TAG = { name: 'Seed-Encryption', value: ENVELOPE_FORMAT } as const\n\nexport const FILE_KEY_LENGTH = 32\nexport const CHUNK_SIZE = 64 * 1024\nconst TAG_LENGTH = 16\nconst PAYLOAD_NONCE_LENGTH = 16\nconst BODY_LINE_LENGTH = 64\nconst MAX_CONTENT_META_LENGTH = 64 * 1024\n\nconst VERSION_LINE = `${ENVELOPE_FORMAT}\\n`\nconst HEADER_INFO = `${ENVELOPE_FORMAT}/header`\nconst PAYLOAD_INFO = `${ENVELOPE_FORMAT}/payload`\n\nconst encoder = new TextEncoder()\nconst decoder = new TextDecoder('utf-8', { fatal: true })\n\nexport type EnvelopeErrorCode =\n | 'NOT_ENVELOPE'\n | 'BAD_HEADER'\n | 'BAD_BIND'\n | 'BIND_MISMATCH'\n | 'NO_KEY'\n | 'BAD_FILE_KEY'\n | 'BAD_RECIPIENT_KEY'\n | 'HEADER_MAC'\n | 'TRUNCATED'\n | 'BAD_CHUNK'\n | 'TRAILING_DATA'\n | 'BAD_CONTENT_FRAME'\n | 'BAD_RECOVERY_PHRASE'\n | 'BAD_KEYSTORE'\n | 'PASSKEY_PRF_UNSUPPORTED'\n\nexport class EnvelopeError extends Error {\n readonly code: EnvelopeErrorCode\n constructor(code: EnvelopeErrorCode, message: string) {\n super(message)\n this.name = 'EnvelopeError'\n this.code = code\n }\n}\n\n/** One recipient's wrap of the file key. Types are defined in SPEC.md; this layer treats them as opaque. */\nexport interface Stanza {\n type: string\n args: string[]\n body: Uint8Array\n}\n\n/**\n * Values the envelope is bound to, known before upload. `envelopeId` is required and is recorded\n * in the envelope attestation, so a ciphertext can't be presented as another Version's.\n */\nexport type EnvelopeBind = { envelopeId: string } & Record<string, string>\n\nexport interface EnvelopeHeader {\n bind: EnvelopeBind\n stanzas: Stanza[]\n}\n\nexport interface EncryptEnvelopeInput {\n /** 32 random bytes, from `generateFileKey()`. One per private Version. */\n fileKey: Uint8Array\n bind: EnvelopeBind\n /** At least one. Always include the publisher's own wrap. */\n stanzas: Stanza[]\n /** The plaintext's real MIME type; stored inside the encrypted payload. */\n contentType: string\n body: Uint8Array\n /**\n * `'padme'` (default) zero-pads the plaintext to its PADMÉ length, so the ciphertext size\n * reveals only a size class (at most 12% extra bytes). `'none'` leaves the exact length visible.\n */\n padding?: EnvelopePadding\n}\n\nexport type EnvelopePadding = 'padme' | 'none'\n\nexport interface DecryptEnvelopeOptions {\n /** The file key, when the caller already unwrapped it. */\n fileKey?: Uint8Array\n /** Called with the parsed header when `fileKey` is not given; returns the unwrapped file key or null. */\n unwrap?: (header: EnvelopeHeader) => Promise<Uint8Array | null> | Uint8Array | null\n /** Every key given must equal the envelope's bind value, or decryption fails with BIND_MISMATCH. */\n expectBind?: Partial<EnvelopeBind>\n}\n\nexport interface DecryptedEnvelope {\n bind: EnvelopeBind\n contentType: string\n body: Uint8Array\n}\n\nconst BIND_KEY = /^[A-Za-z][A-Za-z0-9]*$/\nconst ENVELOPE_ID = /^0x[0-9a-f]{64}$/\nconst STANZA_ARG = /^[\\x21-\\x7e]+$/\n\nfunction randomBytes(length: number): Uint8Array<ArrayBuffer> {\n const out = new Uint8Array(length)\n crypto.getRandomValues(out)\n return out\n}\n\nexport function generateFileKey(): Uint8Array {\n return randomBytes(FILE_KEY_LENGTH)\n}\n\n/** A random `0x`-prefixed 32-byte hex id, chosen before encryption and attested with the Version. */\nexport function generateEnvelopeId(): string {\n return `0x${Array.from(randomBytes(32), (b) => b.toString(16).padStart(2, '0')).join('')}`\n}\n\n/** True when `bytes` start with the envelope's version line. Doesn't validate the rest. */\nexport function isEnvelope(bytes: Uint8Array): boolean {\n if (bytes.length < VERSION_LINE.length) return false\n for (let i = 0; i < VERSION_LINE.length; i++) {\n if (bytes[i] !== VERSION_LINE.charCodeAt(i)) return false\n }\n return true\n}\n\n/** Sorted keys, string values, no whitespace. The bytes feed the payload key derivation. */\nexport function canonicalBind(bind: EnvelopeBind): string {\n const keys = Object.keys(bind).sort()\n for (const key of keys) {\n if (!BIND_KEY.test(key)) throw new EnvelopeError('BAD_BIND', `Invalid bind key ${JSON.stringify(key)}`)\n if (typeof bind[key] !== 'string') throw new EnvelopeError('BAD_BIND', `Bind value for ${key} must be a string`)\n }\n if (!ENVELOPE_ID.test(bind.envelopeId ?? '')) {\n throw new EnvelopeError('BAD_BIND', 'bind.envelopeId must be 0x followed by 64 lowercase hex digits')\n }\n return JSON.stringify(Object.fromEntries(keys.map((k) => [k, bind[k]])))\n}\n\nfunction concat(parts: Uint8Array[]): Uint8Array<ArrayBuffer> {\n const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))\n let o = 0\n for (const p of parts) {\n out.set(p, o)\n o += p.length\n }\n return out\n}\n\nfunction copy(bytes: Uint8Array): Uint8Array<ArrayBuffer> {\n return new Uint8Array(bytes)\n}\n\nexport async function hkdf(ikm: Uint8Array, salt: Uint8Array, info: Uint8Array, length: number): Promise<Uint8Array<ArrayBuffer>> {\n const key = await crypto.subtle.importKey('raw', copy(ikm), 'HKDF', false, ['deriveBits'])\n const bits = await crypto.subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt: copy(salt), info: copy(info) },\n key,\n length * 8,\n )\n return new Uint8Array(bits)\n}\n\nasync function headerMacKey(fileKey: Uint8Array, usage: 'sign' | 'verify'): Promise<CryptoKey> {\n const raw = await hkdf(fileKey, new Uint8Array(0), encoder.encode(HEADER_INFO), 32)\n return crypto.subtle.importKey('raw', raw, { name: 'HMAC', hash: 'SHA-256' }, false, [usage])\n}\n\nasync function payloadKey(fileKey: Uint8Array, nonce: Uint8Array, bindText: string, usage: 'encrypt' | 'decrypt'): Promise<CryptoKey> {\n const info = concat([encoder.encode(PAYLOAD_INFO), new Uint8Array([0]), encoder.encode(bindText)])\n const raw = await hkdf(fileKey, nonce, info, 32)\n return crypto.subtle.importKey('raw', raw, 'AES-GCM', false, [usage])\n}\n\nfunction chunkNonce(index: number, last: boolean): Uint8Array<ArrayBuffer> {\n const iv = new Uint8Array(12)\n // 11-byte big-endian counter; indexes stay below 2^53, so the top bytes are zero.\n let n = index\n for (let i = 10; i >= 0 && n > 0; i--) {\n iv[i] = n % 256\n n = Math.floor(n / 256)\n }\n iv[11] = last ? 1 : 0\n return iv\n}\n\n/**\n * PADMÉ (Nikitin et al., \"Reducing Metadata Leakage from Encrypted Files and Communication with\n * PURBs\", 2019): round `length` up so only the top `floor(log2(E)) + 1` bits of its exponent `E`\n * vary. Overhead is at most 12%.\n */\nexport function padmeLength(length: number): number {\n if (length < 2) return length\n let e = 0\n while (2 ** (e + 1) <= length) e++\n let s = 0\n while (2 ** (s + 1) <= e) s++\n const step = 2 ** (e - (s + 1))\n return Math.ceil(length / step) * step\n}\n\nfunction encodeContentFrame(contentType: string, body: Uint8Array, padding: EnvelopePadding): Uint8Array<ArrayBuffer> {\n const meta = encoder.encode(JSON.stringify({ bodyLength: body.length, contentType }))\n const len = new Uint8Array(4)\n new DataView(len.buffer).setUint32(0, meta.length)\n const unpadded = 4 + meta.length + body.length\n const padded = padding === 'padme' ? padmeLength(unpadded) : unpadded\n return concat([len, meta, body, new Uint8Array(padded - unpadded)])\n}\n\nfunction decodeContentFrame(plain: Uint8Array): { contentType: string; body: Uint8Array } {\n if (plain.length < 4) throw new EnvelopeError('BAD_CONTENT_FRAME', 'Payload is shorter than its content frame')\n const metaLength = new DataView(plain.buffer, plain.byteOffset, 4).getUint32(0)\n if (metaLength > MAX_CONTENT_META_LENGTH || 4 + metaLength > plain.length) {\n throw new EnvelopeError('BAD_CONTENT_FRAME', 'Content metadata length is out of range')\n }\n let meta: unknown\n try {\n meta = JSON.parse(decoder.decode(plain.subarray(4, 4 + metaLength)))\n } catch {\n throw new EnvelopeError('BAD_CONTENT_FRAME', 'Content metadata is not UTF-8 JSON')\n }\n const { contentType, bodyLength } = (meta ?? {}) as { contentType?: unknown; bodyLength?: unknown }\n if (typeof contentType !== 'string') throw new EnvelopeError('BAD_CONTENT_FRAME', 'Content metadata has no contentType')\n const bodyStart = 4 + metaLength\n if (typeof bodyLength !== 'number' || !Number.isSafeInteger(bodyLength) || bodyLength < 0 || bodyStart + bodyLength > plain.length) {\n throw new EnvelopeError('BAD_CONTENT_FRAME', 'Content metadata bodyLength is missing or out of range')\n }\n const bodyEnd = bodyStart + bodyLength\n for (let i = bodyEnd; i < plain.length; i++) {\n if (plain[i] !== 0) throw new EnvelopeError('BAD_CONTENT_FRAME', 'Padding after the body is not all zero')\n }\n return { contentType, body: plain.subarray(bodyStart, bodyEnd) }\n}\n\nfunction encodeStanza(stanza: Stanza): string {\n if (!STANZA_ARG.test(stanza.type) || stanza.args.some((a) => !STANZA_ARG.test(a))) {\n throw new EnvelopeError('BAD_HEADER', 'Stanza type and arguments must be non-empty printable ASCII without spaces')\n }\n const b64 = encodeBase64NoPad(stanza.body)\n let lines = ''\n for (let i = 0; i <= b64.length; i += BODY_LINE_LENGTH) {\n // The final line is shorter than 64 characters, and empty when the body fills its last line.\n lines += `${b64.slice(i, i + BODY_LINE_LENGTH)}\\n`\n }\n return `-> ${[stanza.type, ...stanza.args].join(' ')}\\n${lines}`\n}\n\n/** The header through `---`, which the MAC covers. */\nfunction headerPrefix(bindText: string, stanzas: Stanza[]): string {\n if (stanzas.length === 0) throw new EnvelopeError('BAD_HEADER', 'An envelope needs at least one stanza')\n return `${VERSION_LINE}bind ${encodeBase64NoPad(encoder.encode(bindText))}\\n${stanzas.map(encodeStanza).join('')}---`\n}\n\n/** Encrypt with a caller-chosen payload nonce. Exported for test vectors only; use `encryptEnvelope`. */\nexport async function encryptEnvelopeWithNonce(input: EncryptEnvelopeInput, payloadNonce: Uint8Array): Promise<Uint8Array> {\n if (input.fileKey.length !== FILE_KEY_LENGTH) throw new EnvelopeError('BAD_FILE_KEY', `File key must be ${FILE_KEY_LENGTH} bytes`)\n if (payloadNonce.length !== PAYLOAD_NONCE_LENGTH) throw new EnvelopeError('BAD_HEADER', 'Payload nonce must be 16 bytes')\n const bindText = canonicalBind(input.bind)\n const prefix = encoder.encode(headerPrefix(bindText, input.stanzas))\n const mac = new Uint8Array(await crypto.subtle.sign('HMAC', await headerMacKey(input.fileKey, 'sign'), prefix))\n\n const key = await payloadKey(input.fileKey, payloadNonce, bindText, 'encrypt')\n const plain = encodeContentFrame(input.contentType, input.body, input.padding ?? 'padme')\n const chunks: Uint8Array[] = []\n const count = Math.max(1, Math.ceil(plain.length / CHUNK_SIZE))\n for (let i = 0; i < count; i++) {\n const part = plain.subarray(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE)\n const sealed = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: chunkNonce(i, i === count - 1) }, key, part)\n chunks.push(new Uint8Array(sealed))\n }\n return concat([prefix, encoder.encode(` ${encodeBase64NoPad(mac)}\\n`), payloadNonce, ...chunks])\n}\n\nexport function encryptEnvelope(input: EncryptEnvelopeInput): Promise<Uint8Array> {\n return encryptEnvelopeWithNonce(input, randomBytes(PAYLOAD_NONCE_LENGTH))\n}\n\ninterface ParsedHeader extends EnvelopeHeader {\n bindText: string\n /** Bytes through `---`, covered by the MAC. */\n macInput: Uint8Array\n mac: Uint8Array\n payloadOffset: number\n}\n\nfunction readLine(bytes: Uint8Array, start: number): { line: string; next: number } {\n const end = bytes.indexOf(0x0a, start)\n if (end < 0) throw new EnvelopeError('BAD_HEADER', 'Header ends without a newline')\n let line: string\n try {\n line = decoder.decode(bytes.subarray(start, end))\n } catch {\n throw new EnvelopeError('BAD_HEADER', 'Header is not UTF-8')\n }\n if (!/^[\\x20-\\x7e]*$/.test(line)) throw new EnvelopeError('BAD_HEADER', 'Header lines must be printable ASCII')\n return { line, next: end + 1 }\n}\n\nfunction parse(bytes: Uint8Array): ParsedHeader {\n if (!isEnvelope(bytes)) throw new EnvelopeError('NOT_ENVELOPE', `Bytes do not start with ${ENVELOPE_FORMAT}`)\n let pos = VERSION_LINE.length\n\n let r = readLine(bytes, pos)\n if (!r.line.startsWith('bind ')) throw new EnvelopeError('BAD_HEADER', 'Missing bind line')\n const bindBytes = decodeBase64NoPad(r.line.slice(5))\n if (!bindBytes) throw new EnvelopeError('BAD_HEADER', 'bind line is not canonical base64')\n let bindText: string\n let bind: EnvelopeBind\n try {\n bindText = decoder.decode(bindBytes)\n bind = JSON.parse(bindText) as EnvelopeBind\n } catch {\n throw new EnvelopeError('BAD_BIND', 'bind is not UTF-8 JSON')\n }\n if (bind === null || typeof bind !== 'object' || Array.isArray(bind) || canonicalBind(bind) !== bindText) {\n throw new EnvelopeError('BAD_BIND', 'bind is not canonical')\n }\n pos = r.next\n\n const stanzas: Stanza[] = []\n for (;;) {\n r = readLine(bytes, pos)\n if (r.line.startsWith('--- ')) break\n if (!r.line.startsWith('-> ')) throw new EnvelopeError('BAD_HEADER', 'Expected a stanza or the MAC line')\n const [type, ...args] = r.line.slice(3).split(' ')\n if (!type || !STANZA_ARG.test(type) || args.some((a) => !STANZA_ARG.test(a))) {\n throw new EnvelopeError('BAD_HEADER', 'Malformed stanza line')\n }\n pos = r.next\n let b64 = ''\n for (;;) {\n r = readLine(bytes, pos)\n pos = r.next\n if (r.line.length > BODY_LINE_LENGTH) throw new EnvelopeError('BAD_HEADER', 'Stanza body line is too long')\n b64 += r.line\n if (r.line.length < BODY_LINE_LENGTH) break\n }\n const body = decodeBase64NoPad(b64)\n if (!body) throw new EnvelopeError('BAD_HEADER', 'Stanza body is not canonical base64')\n stanzas.push({ type, args, body })\n }\n if (stanzas.length === 0) throw new EnvelopeError('BAD_HEADER', 'Envelope has no stanzas')\n\n const mac = decodeBase64NoPad(r.line.slice(4))\n if (!mac || mac.length !== 32) throw new EnvelopeError('BAD_HEADER', 'MAC is not 32 bytes of canonical base64')\n return { bind, bindText, stanzas, macInput: bytes.subarray(0, pos + 3), mac, payloadOffset: r.next }\n}\n\n/** Reads the bind values and stanzas without a key, so a reader can pick the stanza to unwrap. */\nexport function parseEnvelopeHeader(bytes: Uint8Array): EnvelopeHeader {\n const { bind, stanzas } = parse(bytes)\n return { bind, stanzas }\n}\n\nexport async function decryptEnvelope(bytes: Uint8Array, options: DecryptEnvelopeOptions): Promise<DecryptedEnvelope> {\n const header = parse(bytes)\n for (const [key, value] of Object.entries(options.expectBind ?? {})) {\n if (header.bind[key] !== value) throw new EnvelopeError('BIND_MISMATCH', `Envelope bind ${key} does not match`)\n }\n const fileKey = options.fileKey ?? (await options.unwrap?.({ bind: header.bind, stanzas: header.stanzas }))\n if (!fileKey) throw new EnvelopeError('NO_KEY', 'No stanza could be unwrapped')\n if (fileKey.length !== FILE_KEY_LENGTH) throw new EnvelopeError('BAD_FILE_KEY', `File key must be ${FILE_KEY_LENGTH} bytes`)\n\n const macOk = await crypto.subtle.verify('HMAC', await headerMacKey(fileKey, 'verify'), copy(header.mac), copy(header.macInput))\n if (!macOk) throw new EnvelopeError('HEADER_MAC', 'Header MAC does not verify; wrong key or altered header')\n\n const payload = bytes.subarray(header.payloadOffset)\n if (payload.length < PAYLOAD_NONCE_LENGTH + TAG_LENGTH) throw new EnvelopeError('TRUNCATED', 'Payload is truncated')\n const key = await payloadKey(fileKey, payload.subarray(0, PAYLOAD_NONCE_LENGTH), header.bindText, 'decrypt')\n\n const sealedChunk = CHUNK_SIZE + TAG_LENGTH\n const parts: Uint8Array[] = []\n let pos = PAYLOAD_NONCE_LENGTH\n for (let i = 0; ; i++) {\n const remaining = payload.length - pos\n if (remaining < TAG_LENGTH) throw new EnvelopeError('TRUNCATED', 'Payload ends without a final chunk')\n const last = remaining <= sealedChunk\n const chunk = copy(payload.subarray(pos, pos + Math.min(remaining, sealedChunk)))\n let plain: Uint8Array\n try {\n plain = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: chunkNonce(i, last) }, key, chunk))\n } catch {\n if (last && remaining === sealedChunk) {\n // A full-size chunk that fails as the last one may be a non-final chunk whose successor was cut off.\n try {\n await crypto.subtle.decrypt({ name: 'AES-GCM', iv: chunkNonce(i, false) }, key, chunk)\n } catch {\n throw new EnvelopeError('BAD_CHUNK', `Chunk ${i} does not authenticate`)\n }\n throw new EnvelopeError('TRUNCATED', 'Payload ends without a final chunk')\n }\n if (!last) {\n // A chunk sealed as final followed by more bytes.\n try {\n await crypto.subtle.decrypt({ name: 'AES-GCM', iv: chunkNonce(i, true) }, key, chunk)\n } catch {\n throw new EnvelopeError('BAD_CHUNK', `Chunk ${i} does not authenticate`)\n }\n throw new EnvelopeError('TRAILING_DATA', 'Bytes follow the final chunk')\n }\n throw new EnvelopeError('BAD_CHUNK', `Chunk ${i} does not authenticate`)\n }\n if (last && plain.length === 0 && i > 0) throw new EnvelopeError('BAD_CHUNK', 'The final chunk is empty')\n parts.push(plain)\n pos += chunk.length\n if (last) break\n }\n const { contentType, body } = decodeContentFrame(concat(parts))\n return { bind: header.bind, contentType, body }\n}\n","/**\n * Single-shot HPKE (RFC 9180) in base mode, for one suite: KEM MLKEM768-X25519 (X-Wing, `0x647a`),\n * KDF HKDF-SHA256 (`0x0001`), AEAD AES-256-GCM (`0x0002`). Only the first message of a context is\n * sealed or opened, so the nonce is the base nonce. The KEM comes from `@noble/post-quantum`; the\n * key schedule and AEAD use WebCrypto.\n */\n\nimport { ml_kem768_x25519 } from '@noble/post-quantum/hybrid.js'\n\nexport const XWING_KEM_ID = 0x647a\nconst KDF_ID = 0x0001\nconst AEAD_ID = 0x0002\nconst NK = 32\nconst NN = 12\nconst NH = 32\n\nexport const XWING_PUBLIC_KEY_LENGTH = 1216\nexport const XWING_SECRET_KEY_LENGTH = 32\nexport const XWING_ENC_LENGTH = 1120\n\nconst encoder = new TextEncoder()\n\nfunction u16(n: number): Uint8Array<ArrayBuffer> {\n return new Uint8Array([n >> 8, n & 0xff])\n}\n\nfunction concat(parts: Uint8Array[]): Uint8Array<ArrayBuffer> {\n const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))\n let o = 0\n for (const p of parts) {\n out.set(p, o)\n o += p.length\n }\n return out\n}\n\nconst SUITE_ID = concat([encoder.encode('HPKE'), u16(XWING_KEM_ID), u16(KDF_ID), u16(AEAD_ID)])\nconst HPKE_V1 = encoder.encode('HPKE-v1')\n\nasync function hmac(key: Uint8Array, data: Uint8Array): Promise<Uint8Array<ArrayBuffer>> {\n // An empty HMAC key equals HashLen zero bytes; WebCrypto rejects zero-length keys.\n const raw = key.length === 0 ? new Uint8Array(NH) : new Uint8Array(key)\n const k = await crypto.subtle.importKey('raw', raw, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])\n return new Uint8Array(await crypto.subtle.sign('HMAC', k, new Uint8Array(data)))\n}\n\nfunction labeledExtract(salt: Uint8Array, label: string, ikm: Uint8Array): Promise<Uint8Array<ArrayBuffer>> {\n return hmac(salt, concat([HPKE_V1, SUITE_ID, encoder.encode(label), ikm]))\n}\n\n/** HKDF-Expand for L <= HashLen, which is all this suite needs. */\nasync function labeledExpand(prk: Uint8Array, label: string, info: Uint8Array, length: number): Promise<Uint8Array<ArrayBuffer>> {\n const labeledInfo = concat([u16(length), HPKE_V1, SUITE_ID, encoder.encode(label), info])\n const t1 = await hmac(prk, concat([labeledInfo, new Uint8Array([1])]))\n return t1.slice(0, length)\n}\n\nasync function keySchedule(sharedSecret: Uint8Array, info: Uint8Array, usage: 'encrypt' | 'decrypt') {\n const empty = new Uint8Array(0)\n const pskIdHash = await labeledExtract(empty, 'psk_id_hash', empty)\n const infoHash = await labeledExtract(empty, 'info_hash', info)\n const context = concat([new Uint8Array([0x00]), pskIdHash, infoHash])\n const secret = await labeledExtract(sharedSecret, 'secret', empty)\n const key = await labeledExpand(secret, 'key', context, NK)\n const nonce = await labeledExpand(secret, 'base_nonce', context, NN)\n return { key: await crypto.subtle.importKey('raw', key, 'AES-GCM', false, [usage]), nonce }\n}\n\nexport function xwingKeyPair(seed: Uint8Array): { secretKey: Uint8Array; publicKey: Uint8Array } {\n const { secretKey, publicKey } = ml_kem768_x25519.keygen(seed)\n return { secretKey, publicKey }\n}\n\n/** RFC 9180 SealBase. `randomness` is for test vectors only; leave it out to use the CSPRNG. */\nexport async function sealBase(\n publicKey: Uint8Array,\n info: Uint8Array,\n aad: Uint8Array,\n plaintext: Uint8Array,\n randomness?: Uint8Array,\n): Promise<{ enc: Uint8Array; ciphertext: Uint8Array }> {\n const { sharedSecret, cipherText } = ml_kem768_x25519.encapsulate(publicKey, randomness)\n const { key, nonce } = await keySchedule(sharedSecret, info, 'encrypt')\n const sealed = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce, additionalData: new Uint8Array(aad) }, key, new Uint8Array(plaintext))\n return { enc: cipherText, ciphertext: new Uint8Array(sealed) }\n}\n\n/** RFC 9180 OpenBase. Returns null when the ciphertext doesn't authenticate under this key. */\nexport async function openBase(\n enc: Uint8Array,\n secretKey: Uint8Array,\n info: Uint8Array,\n aad: Uint8Array,\n ciphertext: Uint8Array,\n): Promise<Uint8Array | null> {\n const sharedSecret = ml_kem768_x25519.decapsulate(enc, secretKey)\n const { key, nonce } = await keySchedule(sharedSecret, info, 'decrypt')\n try {\n return new Uint8Array(\n await crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce, additionalData: new Uint8Array(aad) }, key, new Uint8Array(ciphertext)),\n )\n } catch {\n return null\n }\n}\n","/**\n * The `mlkem768x25519` recipient stanza: the file key sealed with HPKE to an X-Wing public key.\n * The publisher's own wrap and the recovery wrap are both this stanza type, to different keys.\n * SPEC.md \"Recipient stanzas\" is the normative description.\n */\n\nimport { decodeBase64NoPad, encodeBase64NoPad } from './base64'\nimport { EnvelopeError, FILE_KEY_LENGTH, type EnvelopeHeader, type Stanza } from './envelope'\nimport {\n XWING_ENC_LENGTH,\n XWING_PUBLIC_KEY_LENGTH,\n XWING_SECRET_KEY_LENGTH,\n openBase,\n sealBase,\n xwingKeyPair,\n} from './hpke'\n\nexport const XWING_STANZA_TYPE = 'mlkem768x25519'\nconst XWING_INFO = new TextEncoder().encode('seed-private/v1/mlkem768x25519')\nconst WRAPPED_KEY_LENGTH = FILE_KEY_LENGTH + 16\n\nexport { XWING_PUBLIC_KEY_LENGTH, XWING_SECRET_KEY_LENGTH }\n\nexport interface RecipientKeyPair {\n /** 32 bytes. Everything else is derived from it, so this is the only part to keep secret and store. */\n secretKey: Uint8Array\n /** 1216 bytes: the ML-KEM-768 encapsulation key, then the X25519 public key. */\n publicKey: Uint8Array\n}\n\n/** A new X-Wing key pair. Pass a 32-byte seed to derive the same pair again. */\nexport function generateRecipientKeyPair(seed?: Uint8Array): RecipientKeyPair {\n const s = seed ?? crypto.getRandomValues(new Uint8Array(XWING_SECRET_KEY_LENGTH))\n if (s.length !== XWING_SECRET_KEY_LENGTH) {\n throw new EnvelopeError('BAD_RECIPIENT_KEY', `Recipient seed must be ${XWING_SECRET_KEY_LENGTH} bytes`)\n }\n return xwingKeyPair(s)\n}\n\n/** Wrap with caller-chosen encapsulation randomness (64 bytes). Exported for test vectors only. */\nexport async function wrapFileKeyWithRandomness(fileKey: Uint8Array, publicKey: Uint8Array, randomness?: Uint8Array): Promise<Stanza> {\n if (fileKey.length !== FILE_KEY_LENGTH) throw new EnvelopeError('BAD_FILE_KEY', `File key must be ${FILE_KEY_LENGTH} bytes`)\n if (publicKey.length !== XWING_PUBLIC_KEY_LENGTH) {\n throw new EnvelopeError('BAD_RECIPIENT_KEY', `Recipient public key must be ${XWING_PUBLIC_KEY_LENGTH} bytes`)\n }\n const { enc, ciphertext } = await sealBase(publicKey, XWING_INFO, new Uint8Array(0), fileKey, randomness)\n return { type: XWING_STANZA_TYPE, args: [encodeBase64NoPad(enc)], body: ciphertext }\n}\n\n/** A stanza that gives the holder of `publicKey`'s secret key the file key. */\nexport function wrapFileKey(fileKey: Uint8Array, publicKey: Uint8Array): Promise<Stanza> {\n return wrapFileKeyWithRandomness(fileKey, publicKey)\n}\n\n/**\n * The file key, or null when the stanza is another type or was wrapped to a different key.\n * Throws BAD_HEADER for an `mlkem768x25519` stanza that is malformed.\n */\nexport async function unwrapFileKey(stanza: Stanza, secretKey: Uint8Array): Promise<Uint8Array | null> {\n if (stanza.type !== XWING_STANZA_TYPE) return null\n if (secretKey.length !== XWING_SECRET_KEY_LENGTH) {\n throw new EnvelopeError('BAD_RECIPIENT_KEY', `Recipient secret key must be ${XWING_SECRET_KEY_LENGTH} bytes`)\n }\n const enc = stanza.args.length === 1 ? decodeBase64NoPad(stanza.args[0]!) : null\n if (!enc || enc.length !== XWING_ENC_LENGTH) {\n throw new EnvelopeError('BAD_HEADER', `${XWING_STANZA_TYPE} stanza needs one argument: ${XWING_ENC_LENGTH} bytes of base64`)\n }\n if (stanza.body.length !== WRAPPED_KEY_LENGTH) {\n throw new EnvelopeError('BAD_HEADER', `${XWING_STANZA_TYPE} stanza body must be ${WRAPPED_KEY_LENGTH} bytes`)\n }\n return openBase(enc, secretKey, XWING_INFO, new Uint8Array(0), stanza.body)\n}\n\n/**\n * An `unwrap` callback for `decryptEnvelope` that tries every `mlkem768x25519` stanza against\n * each secret key, in order, and returns the first file key that opens.\n */\nexport function unwrapWithSecretKeys(secretKeys: Uint8Array[]): (header: EnvelopeHeader) => Promise<Uint8Array | null> {\n return async (header) => {\n for (const stanza of header.stanzas) {\n for (const key of secretKeys) {\n const fileKey = await unwrapFileKey(stanza, key)\n if (fileKey) return fileKey\n }\n }\n return null\n }\n}\n","/**\n * Who may receive keys for an access policy. Adapters answer one question for one policy kind:\n * was `address` entitled at `blockTag`? Licensing, subscriptions and token gates each register\n * their own kind; key grants are issued only to addresses an adapter says yes to.\n */\n\n/** The parts of an access policy an adapter reads. `kind` selects the adapter. */\nexport interface AccessPolicyRef {\n policyId: string\n kind: string\n /** Adapter-specific configuration fixed when the policy was created (contract address, schema uid...). */\n gateConfig?: unknown\n}\n\n/** A block number, or a tag such as 'latest'. Entitlement decisions pin a block so they can be re-run. */\nexport type EntitlementBlockTag = bigint | 'latest'\n\nexport interface EntitlementAdapter {\n isEntitled(policy: AccessPolicyRef, address: string, blockTag: EntitlementBlockTag): Promise<boolean>\n}\n\nexport class UnknownEntitlementKindError extends Error {\n readonly kind: string\n constructor(kind: string) {\n super(`No entitlement adapter is registered for policy kind \"${kind}\"`)\n this.name = 'UnknownEntitlementKindError'\n this.kind = kind\n }\n}\n\nconst adapters = new Map<string, EntitlementAdapter>()\n\n/**\n * Registers the adapter for a policy kind and returns a function that removes it. Registering a\n * kind that already has an adapter throws, so two packages can't silently replace each other.\n */\nexport function registerEntitlementAdapter(kind: string, adapter: EntitlementAdapter): () => void {\n if (!kind) throw new Error('Entitlement kind must be a non-empty string')\n if (adapters.has(kind)) throw new Error(`An entitlement adapter is already registered for \"${kind}\"`)\n adapters.set(kind, adapter)\n return () => {\n if (adapters.get(kind) === adapter) adapters.delete(kind)\n }\n}\n\n/** Asks the adapter registered for `policy.kind`. Throws UnknownEntitlementKindError when there is none. */\nexport function isEntitled(policy: AccessPolicyRef, address: string, blockTag: EntitlementBlockTag = 'latest'): Promise<boolean> {\n const adapter = adapters.get(policy.kind)\n if (!adapter) return Promise.reject(new UnknownEntitlementKindError(policy.kind))\n return adapter.isEntitled(policy, address, blockTag)\n}\n","/**\n * The encryption identity: one random 32-byte secret from which the X-Wing recipient key, the\n * X25519 tag key and the Ed25519 binding key are derived, and the recovery key, derived from a\n * 24-word phrase. SPEC.md \"Identity\" and \"Key binding\" are the normative description.\n */\n\nimport { ed25519, x25519 } from '@noble/curves/ed25519.js'\nimport { generateMnemonic, mnemonicToEntropy } from '@scure/bip39'\nimport { wordlist } from '@scure/bip39/wordlists/english.js'\nimport { EnvelopeError, hkdf } from './envelope'\nimport { generateRecipientKeyPair, type RecipientKeyPair } from './recipient'\n\nexport const IDENTITY_SECRET_LENGTH = 32\n\nconst encoder = new TextEncoder()\nconst EMPTY = new Uint8Array(0)\n\nexport interface EncryptionIdentity {\n /**\n * `0x` and 64 hex digits: SHA-256 over the label, the X-Wing public key, the X25519 public key\n * and the Ed25519 binding public key.\n */\n keyId: string\n /** The 32 random bytes everything else derives from. The keystore manifest wraps exactly this. */\n secret: Uint8Array\n /** Version file keys are wrapped to `recipient.publicKey`. */\n recipient: RecipientKeyPair\n /** Static X25519 key for blinded tags (Phase 3). */\n tagKey: { secretKey: Uint8Array; publicKey: Uint8Array }\n /** Ed25519 key that signs the key binding an account registers ({@link signKeyBinding}). */\n bindingKey: { secretKey: Uint8Array; publicKey: Uint8Array }\n}\n\nfunction toHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/** The identity derived from `secret`. Throws BAD_KEYSTORE when it isn't 32 bytes. */\nexport async function encryptionIdentityFromSecret(secret: Uint8Array): Promise<EncryptionIdentity> {\n if (secret.length !== IDENTITY_SECRET_LENGTH) {\n throw new EnvelopeError('BAD_KEYSTORE', `Identity secret must be ${IDENTITY_SECRET_LENGTH} bytes`)\n }\n const xwingSeed = await hkdf(secret, EMPTY, encoder.encode('seed-private/v1/identity/mlkem768x25519'), 32)\n const tagSecret = await hkdf(secret, EMPTY, encoder.encode('seed-private/v1/identity/x25519'), 32)\n const recipient = generateRecipientKeyPair(xwingSeed)\n const bindingSecret = await hkdf(secret, EMPTY, encoder.encode('seed-private/v1/identity/ed25519'), 32)\n const tagKey = { secretKey: tagSecret, publicKey: x25519.getPublicKey(tagSecret) }\n const bindingKey = { secretKey: bindingSecret, publicKey: ed25519.getPublicKey(bindingSecret) }\n const keyId = await encryptionKeyId(recipient.publicKey, tagKey.publicKey, bindingKey.publicKey)\n return { keyId, secret: new Uint8Array(secret), recipient, tagKey, bindingKey }\n}\n\n/** The key id of three public keys, as SPEC.md \"Identity\" defines it. */\nexport async function encryptionKeyId(recipientPublicKey: Uint8Array, tagPublicKey: Uint8Array, bindingPublicKey: Uint8Array): Promise<string> {\n const label = encoder.encode('seed-private/v1/key-id')\n const input = new Uint8Array(label.length + 1 + recipientPublicKey.length + tagPublicKey.length + bindingPublicKey.length)\n input.set(label, 0)\n input.set(recipientPublicKey, label.length + 1)\n input.set(tagPublicKey, label.length + 1 + recipientPublicKey.length)\n input.set(bindingPublicKey, label.length + 1 + recipientPublicKey.length + tagPublicKey.length)\n return `0x${toHex(new Uint8Array(await crypto.subtle.digest('SHA-256', input)))}`\n}\n\n/** What a key binding names: the account registering the key and the chain it registers on. */\nexport interface KeyBindingTarget {\n /** `0x` and 40 hex digits, any case. */\n account: string\n chainId: number | bigint\n}\n\nfunction hexToBytes(value: string, length: number, what: string): Uint8Array {\n const hex = value.startsWith('0x') ? value.slice(2) : value\n if (!new RegExp(`^[0-9a-fA-F]{${length * 2}}$`).test(hex)) throw new EnvelopeError('BAD_KEYSTORE', `${what} must be ${length} bytes of hex`)\n return Uint8Array.from({ length }, (_, i) => parseInt(hex.slice(i * 2, i * 2 + 2), 16))\n}\n\n/**\n * The bytes a binding signature covers (SPEC.md \"Key binding\"): the label, a zero byte, the\n * 32-byte key id, the chain id as a 32-byte big-endian integer and the 20-byte account.\n */\nexport function keyBindingMessage(keyId: string, { account, chainId }: KeyBindingTarget): Uint8Array {\n const label = encoder.encode('seed-private/v1/key-binding')\n const chain = BigInt(chainId)\n if (chain < 0n || chain >= 1n << 256n) throw new EnvelopeError('BAD_KEYSTORE', 'chainId must fit in 32 bytes')\n const out = new Uint8Array(label.length + 1 + 32 + 32 + 20)\n out.set(label, 0)\n out.set(hexToBytes(keyId, 32, 'keyId'), label.length + 1)\n out.set(hexToBytes(chain.toString(16).padStart(64, '0'), 32, 'chainId'), label.length + 33)\n out.set(hexToBytes(account, 20, 'account'), label.length + 65)\n return out\n}\n\n/**\n * The identity's Ed25519 signature that it belongs to `account` on `chainId`. The account's\n * `seedprotocol.encryptionKey` registration carries it, so a reader can tell the account's own\n * key from another account's keys copied into its registration.\n */\nexport function signKeyBinding(identity: EncryptionIdentity, target: KeyBindingTarget): Uint8Array {\n return ed25519.sign(keyBindingMessage(identity.keyId, target), identity.bindingKey.secretKey)\n}\n\n/** Whether `signature` is `bindingPublicKey`'s binding of `keyId` to `target`. */\nexport function verifyKeyBinding(\n { keyId, bindingPublicKey, signature }: { keyId: string; bindingPublicKey: Uint8Array; signature: Uint8Array },\n target: KeyBindingTarget,\n): boolean {\n try {\n return ed25519.verify(signature, keyBindingMessage(keyId, target), bindingPublicKey)\n } catch {\n return false\n }\n}\n\n/** A new identity from fresh random bytes. */\nexport function createEncryptionIdentity(): Promise<EncryptionIdentity> {\n return encryptionIdentityFromSecret(crypto.getRandomValues(new Uint8Array(IDENTITY_SECRET_LENGTH)))\n}\n\n/** 24 English BIP39 words encoding 32 random bytes. Show it to the user once; it isn't stored. */\nexport function generateRecoveryPhrase(): string {\n return generateMnemonic(wordlist, 256)\n}\n\nfunction normalizePhrase(phrase: string): string {\n return phrase.normalize('NFKD').trim().toLowerCase().split(/\\s+/).join(' ')\n}\n\n/**\n * The recovery key pair for a phrase. Case, extra spaces and line breaks are ignored. Throws\n * BAD_RECOVERY_PHRASE for anything but 24 known words with a valid checksum.\n */\nexport async function recoveryKeyFromPhrase(phrase: string): Promise<RecipientKeyPair> {\n const words = normalizePhrase(phrase)\n let entropy: Uint8Array\n try {\n entropy = mnemonicToEntropy(words, wordlist)\n } catch {\n throw new EnvelopeError('BAD_RECOVERY_PHRASE', 'Recovery phrase has an unknown word or a bad checksum')\n }\n if (entropy.length !== 32) throw new EnvelopeError('BAD_RECOVERY_PHRASE', 'Recovery phrase must be 24 words')\n const seed = await hkdf(entropy, EMPTY, encoder.encode('seed-private/v1/recovery/mlkem768x25519'), 32)\n return generateRecipientKeyPair(seed)\n}\n","/**\n * The keystore manifest: a seed-private/v1 envelope whose body is the identity secret, with one\n * stanza per way to unlock it (recovery phrase, a passkey's PRF, an EOA signature). It is public,\n * so every stanza must be safe to publish. SPEC.md \"Keystore manifest\" is the normative description.\n */\n\nimport { decodeBase64NoPad, encodeBase64NoPad } from './base64'\nimport {\n EnvelopeError,\n FILE_KEY_LENGTH,\n decryptEnvelope,\n encryptEnvelope,\n generateEnvelopeId,\n hkdf,\n parseEnvelopeHeader,\n type EnvelopeHeader,\n type Stanza,\n} from './envelope'\nimport { IDENTITY_SECRET_LENGTH, encryptionIdentityFromSecret, recoveryKeyFromPhrase, type EncryptionIdentity } from './identity'\nimport { XWING_STANZA_TYPE, unwrapFileKey, wrapFileKey } from './recipient'\n\nexport const KEYSTORE_CONTENT_TYPE = 'application/vnd.seedprotocol.identity-secret'\nexport const PASSKEY_PRF_STANZA_TYPE = 'passkey-prf'\nexport const EOA_SIGNATURE_STANZA_TYPE = 'eoa-signature'\nconst SALT_LENGTH = 32\nconst WRAPPED_KEY_LENGTH = FILE_KEY_LENGTH + 16\n\nconst encoder = new TextEncoder()\nconst EMPTY = new Uint8Array(0)\nconst ZERO_NONCE = new Uint8Array(12)\n\n/** The keystore's file key. It depends only on the identity, so any unlocked device can add a stanza. */\nfunction keystoreFileKey(identity: EncryptionIdentity): Promise<Uint8Array<ArrayBuffer>> {\n return hkdf(identity.secret, EMPTY, encoder.encode('seed-private/v1/keystore'), FILE_KEY_LENGTH)\n}\n\nasync function sealWithKek(kek: Uint8Array<ArrayBuffer>, fileKey: Uint8Array<ArrayBuffer>): Promise<Uint8Array> {\n const key = await crypto.subtle.importKey('raw', kek, 'AES-GCM', false, ['encrypt'])\n return new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: ZERO_NONCE }, key, fileKey))\n}\n\nasync function openWithKek(kek: Uint8Array<ArrayBuffer>, body: Uint8Array): Promise<Uint8Array | null> {\n const key = await crypto.subtle.importKey('raw', kek, 'AES-GCM', false, ['decrypt'])\n try {\n return new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: ZERO_NONCE }, key, new Uint8Array(body)))\n } catch {\n return null\n }\n}\n\nfunction randomSalt(): Uint8Array<ArrayBuffer> {\n return crypto.getRandomValues(new Uint8Array(SALT_LENGTH))\n}\n\nfunction toHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\nfunction checkArgs(stanza: Stanza, count: number, lengths: number[]): Uint8Array<ArrayBuffer>[] {\n const decoded = stanza.args.length === count ? stanza.args.map((a) => decodeBase64NoPad(a)) : []\n const ok =\n decoded.length === count &&\n decoded.every((d, i) => d !== null && (lengths[i] === 0 ? d.length > 0 : d.length === lengths[i])) &&\n stanza.body.length === WRAPPED_KEY_LENGTH\n if (!ok) throw new EnvelopeError('BAD_HEADER', `Malformed ${stanza.type} stanza`)\n return decoded as Uint8Array<ArrayBuffer>[]\n}\n\n// Recovery phrase ------------------------------------------------------------------------------\n\n/** A stanza that lets the recovery phrase behind `recoveryPublicKey` unlock this identity. */\nexport async function recoveryStanza(identity: EncryptionIdentity, recoveryPublicKey: Uint8Array): Promise<Stanza> {\n return wrapFileKey(await keystoreFileKey(identity), recoveryPublicKey)\n}\n\n// Passkey PRF ----------------------------------------------------------------------------------\n\nexport interface PasskeyPrfRequest {\n credentialId: Uint8Array\n /** The PRF input (`prf.eval.first`) for this credential. */\n salt: Uint8Array\n}\n\n/**\n * Asks the user for one of `requests`' passkeys and returns its PRF output, or null when they\n * cancel or have none of them. `passkeyPrf()` is the WebAuthn implementation.\n */\nexport type PasskeyPrfEvaluator = (\n requests: PasskeyPrfRequest[],\n) => Promise<{ credentialId: Uint8Array; prfOutput: Uint8Array } | null>\n\nasync function passkeyKek(prfOutput: Uint8Array, salt: Uint8Array): Promise<Uint8Array<ArrayBuffer>> {\n return hkdf(prfOutput, salt, encoder.encode('seed-private/v1/passkey-prf'), 32)\n}\n\n/** A new random PRF input for `passkeyStanza`. Evaluate the passkey's PRF with it, then build the stanza. */\nexport function generatePasskeySalt(): Uint8Array {\n return randomSalt()\n}\n\n/** A stanza that lets the passkey `credentialId` unlock this identity, given its PRF output for `salt`. */\nexport async function passkeyStanza(\n identity: EncryptionIdentity,\n { credentialId, salt, prfOutput }: { credentialId: Uint8Array; salt: Uint8Array; prfOutput: Uint8Array },\n): Promise<Stanza> {\n if (salt.length !== SALT_LENGTH) throw new EnvelopeError('BAD_KEYSTORE', `Passkey salt must be ${SALT_LENGTH} bytes`)\n if (credentialId.length === 0 || prfOutput.length < 32) throw new EnvelopeError('BAD_KEYSTORE', 'Missing passkey credential or PRF output')\n const body = await sealWithKek(await passkeyKek(prfOutput, salt), await keystoreFileKey(identity))\n return { type: PASSKEY_PRF_STANZA_TYPE, args: [encodeBase64NoPad(credentialId), encodeBase64NoPad(salt)], body }\n}\n\nfunction passkeyArgs(stanza: Stanza): PasskeyPrfRequest {\n const [credentialId, salt] = checkArgs(stanza, 2, [0, SALT_LENGTH]) as [Uint8Array, Uint8Array]\n return { credentialId, salt }\n}\n\n// EOA signature --------------------------------------------------------------------------------\n\n/**\n * The text an EOA signs with `personal_sign` (EIP-191) to unlock the identity. The salt makes it\n * different per stanza; the warning is there because the signature is the key.\n */\nexport function eoaSignatureMessage(salt: Uint8Array): string {\n return [\n 'Unlock your Seed Protocol encryption key',\n '',\n 'Signing this message lets this app read your private Versions. Anyone who gets this signature can read them too, so sign it only in apps you trust.',\n '',\n `Key: 0x${toHex(salt)}`,\n ].join('\\n')\n}\n\n/** A new random salt for `eoaSignatureStanza`. Sign `eoaSignatureMessage(salt)`, then build the stanza. */\nexport function generateEoaSignatureSalt(): Uint8Array {\n return randomSalt()\n}\n\nconst SECP256K1_N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n\n\n/**\n * `r || s` with `s` in the lower half of the curve order. Accepts a 65-byte signature (any `v`) or a\n * 64-byte EIP-2098 one, so wallets that differ only in how they encode `v` derive the same key.\n */\nfunction signatureKeyMaterial(signature: string): Uint8Array<ArrayBuffer> {\n const hex = signature.startsWith('0x') ? signature.slice(2) : signature\n if (!/^[0-9a-fA-F]*$/.test(hex) || (hex.length !== 130 && hex.length !== 128)) {\n throw new EnvelopeError('BAD_KEYSTORE', 'Signature must be 64 or 65 bytes of hex')\n }\n const r = hex.slice(0, 64)\n let s = BigInt(`0x${hex.slice(64, 128)}`)\n if (hex.length === 128) s &= (1n << 255n) - 1n\n if (s > SECP256K1_N / 2n) s = SECP256K1_N - s\n const out = new Uint8Array(64)\n const full = r + s.toString(16).padStart(64, '0')\n for (let i = 0; i < 64; i++) out[i] = parseInt(full.slice(i * 2, i * 2 + 2), 16)\n return out\n}\n\nasync function signatureKek(signature: string, salt: Uint8Array): Promise<Uint8Array<ArrayBuffer>> {\n return hkdf(signatureKeyMaterial(signature), salt, encoder.encode('seed-private/v1/eoa-signature'), 32)\n}\n\n/**\n * A stanza that lets an EOA unlock this identity by signing `eoaSignatureMessage(salt)` again.\n * Only for EOAs whose wallet signs deterministically (RFC 6979); smart-account signatures change\n * every time and would never unlock it.\n *\n * Prefer a passkey and the recovery phrase. This stanza trades security for convenience: the\n * manifest is public, so anyone who gets the EOA's private key can sign the message, open the\n * manifest and read every private Version wrapped to this identity, past and future. That\n * includes a leaked or phished key, and a future quantum computer, which can recover the key from\n * any transaction the EOA has sent. `acceptWalletKeyRisk: true` says the user chose that.\n */\nexport async function eoaSignatureStanza(\n identity: EncryptionIdentity,\n { salt, signature, acceptWalletKeyRisk }: { salt: Uint8Array; signature: string; acceptWalletKeyRisk: true },\n): Promise<Stanza> {\n if (acceptWalletKeyRisk !== true) {\n throw new EnvelopeError('BAD_KEYSTORE', 'eoaSignatureStanza needs acceptWalletKeyRisk: true; prefer a passkey and the recovery phrase')\n }\n if (salt.length !== SALT_LENGTH) throw new EnvelopeError('BAD_KEYSTORE', `Signature salt must be ${SALT_LENGTH} bytes`)\n const body = await sealWithKek(await signatureKek(signature, salt), await keystoreFileKey(identity))\n return { type: EOA_SIGNATURE_STANZA_TYPE, args: [encodeBase64NoPad(salt)], body }\n}\n\n// Manifest -------------------------------------------------------------------------------------\n\n/** A keystore manifest for `identity` carrying `stanzas`. Each call picks a new envelope id. */\nexport async function buildKeystoreManifest(identity: EncryptionIdentity, stanzas: Stanza[]): Promise<Uint8Array> {\n if (stanzas.length === 0) throw new EnvelopeError('BAD_KEYSTORE', 'A keystore manifest needs at least one stanza')\n return encryptEnvelope({\n fileKey: await keystoreFileKey(identity),\n bind: { envelopeId: generateEnvelopeId(), keyId: identity.keyId, purpose: 'keystore' },\n stanzas,\n contentType: KEYSTORE_CONTENT_TYPE,\n body: identity.secret,\n })\n}\n\nexport type KeystoreAuthenticator =\n | { type: 'recovery' }\n | { type: 'passkey'; credentialId: Uint8Array }\n | { type: 'eoa-signature'; salt: Uint8Array }\n\n/** The key id a manifest claims and the authenticators that can unlock it. Doesn't decrypt anything. */\nexport function describeKeystoreManifest(bytes: Uint8Array): { keyId: string; authenticators: KeystoreAuthenticator[] } {\n const header = keystoreHeader(bytes)\n const authenticators: KeystoreAuthenticator[] = []\n for (const stanza of header.stanzas) {\n if (stanza.type === XWING_STANZA_TYPE) authenticators.push({ type: 'recovery' })\n else if (stanza.type === PASSKEY_PRF_STANZA_TYPE) authenticators.push({ type: 'passkey', credentialId: passkeyArgs(stanza).credentialId })\n else if (stanza.type === EOA_SIGNATURE_STANZA_TYPE) authenticators.push({ type: 'eoa-signature', salt: checkArgs(stanza, 1, [SALT_LENGTH])[0]! })\n }\n return { keyId: header.bind.keyId!, authenticators }\n}\n\nfunction keystoreHeader(bytes: Uint8Array): EnvelopeHeader {\n const header = parseEnvelopeHeader(bytes)\n if (header.bind.purpose !== 'keystore' || !/^0x[0-9a-f]{64}$/.test(header.bind.keyId ?? '')) {\n throw new EnvelopeError('BAD_KEYSTORE', 'Not a keystore manifest')\n }\n return header\n}\n\nexport type KeystoreUnlock =\n | { recoveryPhrase: string }\n | { passkey: PasskeyPrfEvaluator }\n | { signMessage: (message: string) => Promise<string> }\n\nasync function unwrapKeystore(header: EnvelopeHeader, unlock: KeystoreUnlock): Promise<Uint8Array | null> {\n if ('recoveryPhrase' in unlock) {\n const { secretKey } = await recoveryKeyFromPhrase(unlock.recoveryPhrase)\n for (const stanza of header.stanzas) {\n const fileKey = await unwrapFileKey(stanza, secretKey)\n if (fileKey) return fileKey\n }\n return null\n }\n if ('passkey' in unlock) {\n const stanzas = header.stanzas.filter((s) => s.type === PASSKEY_PRF_STANZA_TYPE)\n if (stanzas.length === 0) return null\n const requests = stanzas.map(passkeyArgs)\n const result = await unlock.passkey(requests)\n if (!result) return null\n for (let i = 0; i < stanzas.length; i++) {\n if (!sameBytes(requests[i]!.credentialId, result.credentialId)) continue\n const fileKey = await openWithKek(await passkeyKek(result.prfOutput, requests[i]!.salt), stanzas[i]!.body)\n if (fileKey) return fileKey\n }\n return null\n }\n for (const stanza of header.stanzas) {\n if (stanza.type !== EOA_SIGNATURE_STANZA_TYPE) continue\n const [salt] = checkArgs(stanza, 1, [SALT_LENGTH]) as [Uint8Array]\n const signature = await unlock.signMessage(eoaSignatureMessage(salt))\n const fileKey = await openWithKek(await signatureKek(signature, salt), stanza.body)\n if (fileKey) return fileKey\n }\n return null\n}\n\nfunction sameBytes(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((v, i) => v === b[i])\n}\n\n/**\n * Unlocks a keystore manifest and returns the identity. Throws NO_KEY when the authenticator\n * opens no stanza, and BAD_KEYSTORE when the manifest's contents don't match its key id (pass\n * `expectKeyId`, from the registration attestation, to also reject another identity's manifest).\n */\nexport async function openKeystoreManifest(\n bytes: Uint8Array,\n unlock: KeystoreUnlock,\n options: { expectKeyId?: string } = {},\n): Promise<EncryptionIdentity> {\n const header = keystoreHeader(bytes)\n if (options.expectKeyId !== undefined && header.bind.keyId !== options.expectKeyId) {\n throw new EnvelopeError('BIND_MISMATCH', 'Keystore manifest is for another key id')\n }\n const unwrapped: { fileKey: Uint8Array | null } = { fileKey: null }\n const opened = await decryptEnvelope(bytes, {\n unwrap: async (h) => (unwrapped.fileKey = await unwrapKeystore(h, unlock)),\n })\n if (opened.contentType !== KEYSTORE_CONTENT_TYPE || opened.body.length !== IDENTITY_SECRET_LENGTH) {\n throw new EnvelopeError('BAD_KEYSTORE', 'Keystore manifest body is not an identity secret')\n }\n const identity = await encryptionIdentityFromSecret(opened.body)\n if (identity.keyId !== header.bind.keyId || !sameBytes(await keystoreFileKey(identity), unwrapped.fileKey!)) {\n throw new EnvelopeError('BAD_KEYSTORE', 'Keystore manifest contents do not match its key id')\n }\n return identity\n}\n","/**\n * WebAuthn calls for the `passkey-prf` keystore stanza. Browser only. The challenges are random and\n * never checked by a server: the passkey is used for its PRF output, not to sign in.\n */\n\nimport { EnvelopeError, type Stanza } from './envelope'\nimport type { EncryptionIdentity } from './identity'\nimport { generatePasskeySalt, passkeyStanza, type PasskeyPrfEvaluator } from './keystore'\n\nexport interface PasskeyOptions {\n /** Defaults to the page's effective domain. A passkey works only on the domain it was made for. */\n rpId?: string\n}\n\nfunction base64Url(bytes: Uint8Array): string {\n let binary = ''\n for (const b of bytes) binary += String.fromCharCode(b)\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\nfunction toBytes(value: BufferSource): Uint8Array {\n return value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value.buffer, value.byteOffset, value.byteLength)\n}\n\nfunction randomChallenge(): Uint8Array<ArrayBuffer> {\n return crypto.getRandomValues(new Uint8Array(32))\n}\n\n/** A `PasskeyPrfEvaluator` that asks the browser for one of the requested passkeys. */\nexport function passkeyPrf(options: PasskeyOptions = {}): PasskeyPrfEvaluator {\n return async (requests) => {\n const evalByCredential: Record<string, AuthenticationExtensionsPRFValues> = {}\n for (const r of requests) evalByCredential[base64Url(r.credentialId)] = { first: new Uint8Array(r.salt) }\n const credential = (await navigator.credentials.get({\n publicKey: {\n challenge: randomChallenge(),\n rpId: options.rpId,\n allowCredentials: requests.map((r) => ({ type: 'public-key' as const, id: new Uint8Array(r.credentialId) })),\n userVerification: 'required',\n extensions: { prf: { evalByCredential } },\n },\n })) as PublicKeyCredential | null\n if (!credential) return null\n const first = credential.getClientExtensionResults().prf?.results?.first\n if (!first) throw new EnvelopeError('PASSKEY_PRF_UNSUPPORTED', 'This passkey or browser does not support the PRF extension')\n return { credentialId: new Uint8Array(credential.rawId), prfOutput: toBytes(first) }\n }\n}\n\n/**\n * Creates a passkey and returns a keystore stanza for it. Two prompts: one to create the passkey,\n * one to evaluate its PRF. Throws PASSKEY_PRF_UNSUPPORTED when the authenticator has no PRF.\n */\nexport async function enrollPasskey(\n identity: EncryptionIdentity,\n options: PasskeyOptions & { rpName: string; userName: string },\n): Promise<Stanza> {\n const created = (await navigator.credentials.create({\n publicKey: {\n challenge: randomChallenge(),\n rp: { name: options.rpName, id: options.rpId },\n user: { id: crypto.getRandomValues(new Uint8Array(16)), name: options.userName, displayName: options.userName },\n pubKeyCredParams: [\n { type: 'public-key', alg: -7 },\n { type: 'public-key', alg: -257 },\n ],\n authenticatorSelection: { residentKey: 'preferred', userVerification: 'required' },\n extensions: { prf: {} },\n },\n })) as PublicKeyCredential | null\n if (!created) throw new EnvelopeError('PASSKEY_PRF_UNSUPPORTED', 'No passkey was created')\n if (created.getClientExtensionResults().prf?.enabled === false) {\n throw new EnvelopeError('PASSKEY_PRF_UNSUPPORTED', 'This passkey does not support the PRF extension')\n }\n const credentialId = new Uint8Array(created.rawId)\n const salt = generatePasskeySalt()\n const result = await passkeyPrf(options)([{ credentialId, salt }])\n if (!result) throw new EnvelopeError('PASSKEY_PRF_UNSUPPORTED', 'The passkey was not used')\n return passkeyStanza(identity, { credentialId, salt, prfOutput: result.prfOutput })\n}\n","/**\n * Keeps unlocked identities on this device in IndexedDB, each encrypted with its own\n * non-extractable AES-GCM key stored beside it. That keeps the secret from being read out of the\n * database by copying its files or calling `exportKey`, but any script on the origin can still\n * decrypt it. Don't save an identity on a shared device; unlock it from the keystore manifest\n * each session instead.\n */\n\nimport { EnvelopeError } from './envelope'\nimport { encryptionIdentityFromSecret, type EncryptionIdentity } from './identity'\n\nconst DB_NAME = 'seed-encryption'\nconst STORE = 'identities'\n\ninterface DeviceIdentityRecord {\n keyId: string\n deviceKey: CryptoKey\n iv: Uint8Array\n ciphertext: Uint8Array\n savedAt: number\n}\n\nfunction request<T>(req: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n req.onsuccess = () => resolve(req.result)\n req.onerror = () => reject(req.error)\n })\n}\n\nfunction openDb(): Promise<IDBDatabase> {\n const req = indexedDB.open(DB_NAME, 1)\n req.onupgradeneeded = () => req.result.createObjectStore(STORE, { keyPath: 'keyId' })\n return request(req)\n}\n\nasync function withStore<T>(mode: IDBTransactionMode, fn: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {\n const db = await openDb()\n try {\n const tx = db.transaction(STORE, mode)\n const done = new Promise<void>((resolve, reject) => {\n tx.oncomplete = () => resolve()\n tx.onerror = () => reject(tx.error)\n tx.onabort = () => reject(tx.error)\n })\n const result = await request(fn(tx.objectStore(STORE)))\n await done\n return result\n } finally {\n db.close()\n }\n}\n\n/** Saves `identity` on this device, replacing an earlier save of the same key id. */\nexport async function saveIdentityOnDevice(identity: EncryptionIdentity): Promise<void> {\n const deviceKey = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])\n const iv = crypto.getRandomValues(new Uint8Array(12))\n const aad = new TextEncoder().encode(identity.keyId)\n const ciphertext = new Uint8Array(\n await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: aad }, deviceKey, new Uint8Array(identity.secret)),\n )\n const record: DeviceIdentityRecord = { keyId: identity.keyId, deviceKey, iv, ciphertext, savedAt: Date.now() }\n await withStore('readwrite', (store) => store.put(record))\n}\n\n/** The identity saved under `keyId`, or null when this device has none. */\nexport async function loadIdentityFromDevice(keyId: string): Promise<EncryptionIdentity | null> {\n const record = (await withStore('readonly', (store) => store.get(keyId))) as DeviceIdentityRecord | undefined\n if (!record) return null\n let secret: Uint8Array\n try {\n secret = new Uint8Array(\n await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: new Uint8Array(record.iv), additionalData: new TextEncoder().encode(keyId) },\n record.deviceKey,\n new Uint8Array(record.ciphertext),\n ),\n )\n } catch {\n throw new EnvelopeError('BAD_KEYSTORE', `The identity saved for ${keyId} does not decrypt`)\n }\n const identity = await encryptionIdentityFromSecret(secret)\n if (identity.keyId !== keyId) throw new EnvelopeError('BAD_KEYSTORE', `The identity saved for ${keyId} has another key id`)\n return identity\n}\n\n/** Key ids of the identities saved on this device. */\nexport async function listIdentitiesOnDevice(): Promise<string[]> {\n return (await withStore('readonly', (store) => store.getAllKeys())) as string[]\n}\n\n/** Deletes the identity saved under `keyId` from this device. Its keystore manifest is unaffected. */\nexport async function forgetIdentityOnDevice(keyId: string): Promise<void> {\n await withStore('readwrite', (store) => store.delete(keyId))\n}\n","/**\n * Encrypts the uploads of private properties for `@seedprotocol/publish` (its\n * `encryptPrivateUpload` config, the SDK's `encryptUpload`). Each upload becomes its own envelope\n * with a fresh file key and envelope id, wrapped to every recipient. It needs only public keys, so\n * a session key can publish private Versions wrapped to the account's registered key.\n */\n\nimport { ENVELOPE_FORMAT_TAG, EnvelopeError, encryptEnvelope, generateEnvelopeId, generateFileKey, type EnvelopePadding } from './envelope'\nimport { XWING_PUBLIC_KEY_LENGTH, wrapFileKey } from './recipient'\n\nexport interface PrivateUploadEncryptorOptions {\n /**\n * X-Wing public keys to wrap each upload's file key to. Always include the publisher's\n * registered key (`recipientKey` from `getVerifiedEncryptionKey` in `@seedprotocol/publish`), or the\n * publisher can't read the Version on another device.\n */\n recipients: Uint8Array[]\n /** Bind values known before upload, such as `chainId` and `publisher`. `envelopeId` is added per upload. */\n bind?: Record<string, string>\n /** Default `padme`. */\n padding?: EnvelopePadding\n}\n\n/** What the SDK hands an encryptor, and what it takes back. Structural, so no SDK import. */\nexport interface UploadToEncrypt {\n blob: Blob\n contentType: string | undefined\n}\nexport interface EncryptedUpload {\n blob: Blob\n tags: { name: string; value: string }[]\n}\n\n/** An `encryptPrivateUpload` for `@seedprotocol/publish`. */\nexport function createPrivateUploadEncryptor(options: PrivateUploadEncryptorOptions): (upload: UploadToEncrypt) => Promise<EncryptedUpload> {\n const recipients = options.recipients.map((key) => new Uint8Array(key))\n if (recipients.length === 0) throw new EnvelopeError('BAD_RECIPIENT_KEY', 'A private upload needs at least one recipient')\n for (const key of recipients) {\n if (key.length !== XWING_PUBLIC_KEY_LENGTH) {\n throw new EnvelopeError('BAD_RECIPIENT_KEY', `Recipient public key must be ${XWING_PUBLIC_KEY_LENGTH} bytes`)\n }\n }\n if (options.bind && 'envelopeId' in options.bind) {\n throw new EnvelopeError('BAD_BIND', 'envelopeId is chosen per upload; leave it out of bind')\n }\n return async ({ blob, contentType }) => {\n const fileKey = generateFileKey()\n const envelope = await encryptEnvelope({\n fileKey,\n bind: { ...options.bind, envelopeId: generateEnvelopeId() },\n stanzas: await Promise.all(recipients.map((key) => wrapFileKey(fileKey, key))),\n contentType: contentType || 'application/octet-stream',\n body: new Uint8Array(await blob.arrayBuffer()),\n padding: options.padding,\n })\n return { blob: new Blob([envelope as BlobPart]), tags: [{ ...ENVELOPE_FORMAT_TAG }] }\n }\n}\n","/**\n * Opens downloaded envelopes for the SDK (`setEnvelopeDecryptor` in `@seedprotocol/sdk`): tries\n * each unlocked identity's recipient key and returns the plaintext with the content type recorded\n * inside, or null when the bytes aren't an envelope or none of them is a recipient. A damaged\n * envelope throws `EnvelopeError`.\n */\n\nimport { EnvelopeError, decryptEnvelope } from './envelope'\nimport type { EncryptionIdentity } from './identity'\nimport { unwrapWithSecretKeys } from './recipient'\n\n/** What `setEnvelopeDecryptor` takes. Structural, so no SDK import. */\nexport type EnvelopeOpener = (envelope: Uint8Array) => Promise<{ contentType: string; body: Uint8Array } | null>\n\nexport function createEnvelopeDecryptor(identities: EncryptionIdentity[]): EnvelopeOpener {\n const unwrap = unwrapWithSecretKeys(identities.map((identity) => identity.recipient.secretKey))\n return async (envelope) => {\n try {\n const { contentType, body } = await decryptEnvelope(envelope, { unwrap })\n return { contentType, body }\n } catch (error) {\n if (error instanceof EnvelopeError && (error.code === 'NO_KEY' || error.code === 'NOT_ENVELOPE')) return null\n throw error\n }\n }\n}\n"],"mappings":";;;;;;;;IAEMS,IAAW,oEACXC,qBAAS,IAAI,WAAW,GAAG,EAAA,CAAE,KAAK,EAAE;AAC1C,KAAK,IAAIC,IAAI,GAAGA,IAAI,IAAiB,KAAK,EAAOF,EAAS,WAAWE,CAAC,KAAKA;AAE3E,SAAgB,kBAAkB,GAA2B;CAC3D,IAAIC,IAAM,IACND,IAAI;CACR,OAAOA,IAAI,IAAIE,EAAM,QAAQ,KAAK,GAAG;EACnC,IAAMC,IAAKD,EAAMF,MAAO,KAAOE,EAAMF,IAAI,MAAO,IAAKE,EAAMF,IAAI;EAC/D,KAAOF,EAASK,KAAK,MAAOL,EAAUK,KAAK,KAAM,MAAOL,EAAUK,KAAK,IAAK,MAAOL,EAASK,IAAI;CAClG;CACA,IAAMC,IAAOF,EAAM,SAASF;CAC5B,IAAII,MAAS,GAAG;EACd,IAAMD,IAAID,EAAMF,MAAO;EACvB,KAAOF,EAASK,KAAK,MAAOL,EAAUK,KAAK,KAAM;CACnD,OAAO,IAAIC,MAAS,GAAG;EACrB,IAAMD,IAAKD,EAAMF,MAAO,KAAOE,EAAMF,IAAI,MAAO;E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851",
|
|
4
4
|
"description": "Encryption for Seed Protocol private Versions: the seed-private/v1 envelope format and entitlement adapters",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"seed-protocol",
|