@muhkoo/connect 0.3.0-alpha.0 → 0.6.0-alpha.1
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/README.md +107 -10
- package/dist/browser/index.js +530 -8
- package/dist/browser/index.js.map +1 -1
- package/dist/connect.d.ts +587 -3
- package/dist/server/index.js +530 -8
- package/dist/server/index.js.map +1 -1
- package/dist/workers/index.js +20 -1
- package/dist/workers/index.js.map +1 -1
- package/package.json +2 -2
package/dist/server/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../src/crypto/primitives/subtle.ts","../../src/crypto/primitives/random.ts","../../src/crypto/primitives/aes-gcm.ts","../../src/crypto/primitives/kdf.ts","../../src/utilities/Logger.ts","../../src/utilities/bytes.ts","../../src/utilities/index.ts","../../src/crypto/KeyStore.ts","../../src/crypto/DoubleRatchet.ts","../../src/crypto/ZeroKnowledge.ts","../../src/crypto/Authenticator.ts","../../src/crypto/DoubleRatchetManager.ts","../../src/crypto/ChunkCipher.ts","../../src/crypto/PassphraseWrap.ts","../../src/types/zk.ts","../../src/events/EventCore.ts","../../src/messaging/Message.ts","../../src/messaging/Packet.ts","../../src/messaging/decorators.ts","../../src/messaging/index.ts","../../src/auth/AuthClient.ts","../../src/auth/identity.ts","../../src/auth/poseidon.ts","../../src/auth/proof.ts","../../src/auth/keys.ts","../../src/core/HttpClient.ts","../../src/core/Session.ts","../../src/core/namespaces/AuthNamespace.ts","../../src/crypto/StorageCipher.ts","../../src/transport/WSTransport.ts","../../src/core/namespaces/KvNamespace.ts","../../src/storage/types.ts","../../src/storage/encoding/ReedSolomon/wasm/rs.ts","../../src/storage/encoding/ReedSolomon/ReedSolomonCodec.ts","../../src/storage/transport/ShardClient.ts","../../src/storage/FileStorage.ts","../../src/storage/transport/SharedSpaceClient.ts","../../src/core/namespaces/FileNamespace.ts","../../src/sessions/EncryptedSession.ts","../../src/sessions/BroadcastChannel.ts","../../src/spaces/SpaceCipher.ts","../../src/spaces/SpacePacketCipher.ts","../../src/spaces/Space.ts","../../src/core/namespaces/MessageNamespace.ts","../../src/spaces/SpaceKeyring.ts","../../src/spaces/KeyringClient.ts","../../src/core/namespaces/SpaceNamespace.ts","../../src/core/Client.ts","../../src/core/index.ts","../../src/workers/groth16-verifier.ts","../../src/personal/PersonalSpaceClient.ts","../../src/network/PacketCipher.ts","../../src/storage/encoding/ReedSolomon/wasm/bundled-loader.ts"],"sourcesContent":["/**\n * WebCrypto subtle-interface resolver.\n *\n * Available natively in every runtime this SDK targets (modern browsers,\n * Node 16+, CF Workers). Centralized here so the runtime check + error\n * message are consistent across every primitive — and so a future polyfill\n * shim has one place to plug in.\n */\n\nexport function getSubtle(): SubtleCrypto {\n const s = (globalThis.crypto as Crypto | undefined)?.subtle;\n if (!s) {\n throw new Error(\n \"@muhkoo/connect crypto: `globalThis.crypto.subtle` is unavailable. \" +\n \"Modern browsers, Node 16+, and CF Workers expose it natively.\",\n );\n }\n return s;\n}\n","/**\n * Cryptographically secure random bytes.\n *\n * Wraps `crypto.getRandomValues` with two small affordances every caller\n * needs:\n * - Allocates over a fresh, non-shared `ArrayBuffer` so the returned\n * `Uint8Array` satisfies WebCrypto's `BufferSource` type under strict\n * TS lib settings (where `Uint8Array<ArrayBufferLike>` isn't directly\n * assignable).\n * - Chunks requests larger than 65 KiB, the per-call cap browsers enforce\n * on `getRandomValues`.\n */\n\nconst MAX_PER_CALL = 65536;\n\nexport function randomBytes(n: number): Uint8Array {\n if (!Number.isInteger(n) || n < 0) {\n throw new Error(`randomBytes: n must be a non-negative integer (got ${n})`);\n }\n const buf = new Uint8Array(new ArrayBuffer(n));\n for (let offset = 0; offset < n; offset += MAX_PER_CALL) {\n const slice = buf.subarray(offset, Math.min(offset + MAX_PER_CALL, n));\n (globalThis.crypto as Crypto).getRandomValues(slice);\n }\n return buf;\n}\n","/**\n * AES-256-GCM encryption / decryption with raw key bytes.\n *\n * The two functions here are the single canonical AES-GCM call site in the\n * SDK. Earlier copies of this logic existed inline in `DoubleRatchet`, in the\n * storage `ChunkCipher`, and in the passphrase-wrap helpers — they all now\n * route through here so the algorithm, IV size, and tag handling stay in one\n * place.\n *\n * Conventions:\n * - 256-bit keys only. Passing 16- or 24-byte keys throws; callers that\n * need AES-128 should add a dedicated primitive.\n * - 96-bit IVs. WebCrypto's recommended GCM IV length; trades the 4-byte\n * IV economy of 128-bit for compatibility with every spec-compliant\n * implementation.\n * - The 16-byte GCM authentication tag is appended to the ciphertext by\n * WebCrypto's default behavior. Callers don't manage it separately.\n *\n * If a future need arises for AAD (associated data), add an optional `aad`\n * parameter to both functions rather than introducing a parallel primitive.\n */\n\nimport { getSubtle } from \"./subtle\";\n\n/** Length of the AES key in bytes. */\nexport const AES_GCM_KEY_BYTES = 32;\n\n/** Length of the AES-GCM IV in bytes (WebCrypto-recommended). */\nexport const AES_GCM_IV_BYTES = 12;\n\n/** Length of the AES-GCM authentication tag in bytes (appended to ciphertext). */\nexport const AES_GCM_TAG_BYTES = 16;\n\n/**\n * Encrypt `plaintext` under a 32-byte AES-256 key with the supplied 12-byte\n * IV. Returns ciphertext with the 16-byte GCM tag appended (so the output\n * length is `plaintext.length + 16`).\n *\n * The IV must be unique per (key, message). Callers that generate the IV\n * randomly should grab it via `randomBytes(AES_GCM_IV_BYTES)`; callers\n * managing a counter pass their own.\n */\nexport async function encryptAesGcm(\n key: Uint8Array,\n iv: Uint8Array,\n plaintext: Uint8Array,\n): Promise<Uint8Array> {\n assertKey(key);\n assertIv(iv);\n const cryptoKey = await importAesGcmKey(key, [\"encrypt\"]);\n const ciphertext = await getSubtle().encrypt(\n { name: \"AES-GCM\", iv: iv as BufferSource },\n cryptoKey,\n plaintext as BufferSource,\n );\n return new Uint8Array(ciphertext);\n}\n\n/**\n * Inverse of {@link encryptAesGcm}. Throws if the GCM auth tag fails — this\n * captures \"wrong key\", \"wrong IV\", or \"ciphertext was tampered with\",\n * indistinguishably. Callers that care about distinguishing those should\n * keep separate provenance bookkeeping, not invent a parallel MAC.\n */\nexport async function decryptAesGcm(\n key: Uint8Array,\n iv: Uint8Array,\n ciphertext: Uint8Array,\n): Promise<Uint8Array> {\n assertKey(key);\n assertIv(iv);\n const cryptoKey = await importAesGcmKey(key, [\"decrypt\"]);\n const plaintext = await getSubtle().decrypt(\n { name: \"AES-GCM\", iv: iv as BufferSource },\n cryptoKey,\n ciphertext as BufferSource,\n );\n return new Uint8Array(plaintext);\n}\n\nasync function importAesGcmKey(key: Uint8Array, usages: KeyUsage[]): Promise<CryptoKey> {\n return await getSubtle().importKey(\n \"raw\",\n key as BufferSource,\n { name: \"AES-GCM\" },\n false,\n usages,\n );\n}\n\nfunction assertKey(key: Uint8Array): void {\n if (key.byteLength !== AES_GCM_KEY_BYTES) {\n throw new Error(\n `aes-gcm: key must be ${AES_GCM_KEY_BYTES} bytes (got ${key.byteLength})`,\n );\n }\n}\n\nfunction assertIv(iv: Uint8Array): void {\n if (iv.byteLength !== AES_GCM_IV_BYTES) {\n throw new Error(\n `aes-gcm: iv must be ${AES_GCM_IV_BYTES} bytes (got ${iv.byteLength})`,\n );\n }\n}\n","/**\n * Key-derivation primitives — PBKDF2 (for passphrase → key) and HKDF (for\n * symmetric key material → expanded key material).\n *\n * PBKDF2 is the slow, salted KDF the passphrase-wrap helper uses to harden\n * user passwords against offline guessing. HKDF is the fast, deterministic\n * KDF the Double Ratchet uses to derive root + chain + message keys from\n * shared secrets.\n *\n * Both are SHA-256-backed everywhere in this codebase — keep it that way\n * unless there's a concrete reason to diverge.\n */\n\nimport { getSubtle } from \"./subtle\";\n\n/**\n * Iteration count default for PBKDF2 passphrase hardening. Tuned for\n * 2024–2026 hardware: slow enough to deter offline guessing of weak\n * passphrases (~100ms on commodity laptops), fast enough that interactive\n * unlock stays sub-second.\n */\nexport const PBKDF2_DEFAULT_ITERATIONS = 200_000;\n\n/**\n * Derive a 256-bit AES-GCM key from `passphrase + salt` via PBKDF2-SHA256.\n *\n * Returned as raw bytes (not a `CryptoKey`) so callers can hand it straight\n * to {@link encryptAesGcm} — that's the convention everywhere else in the\n * primitive layer. If a future caller needs the non-extractable\n * `CryptoKey` form, add a parallel `deriveCryptoKeyFromPassphrase` variant\n * rather than overloading this one.\n */\nexport async function deriveAesKeyFromPassphrase(\n passphrase: string,\n salt: Uint8Array,\n iterations: number = PBKDF2_DEFAULT_ITERATIONS,\n): Promise<Uint8Array> {\n if (typeof passphrase !== \"string\" || passphrase.length === 0) {\n throw new Error(\"kdf.deriveAesKeyFromPassphrase: passphrase must be a non-empty string\");\n }\n const s = getSubtle();\n const passphraseKey = await s.importKey(\n \"raw\",\n new TextEncoder().encode(passphrase),\n { name: \"PBKDF2\" },\n false,\n [\"deriveBits\"],\n );\n const bits = await s.deriveBits(\n {\n name: \"PBKDF2\",\n salt: salt as BufferSource,\n iterations,\n hash: \"SHA-256\",\n },\n passphraseKey,\n 256,\n );\n return new Uint8Array(bits);\n}\n\n/**\n * HKDF-Expand with SHA-256, returning `lengthBytes` raw bytes of key material.\n *\n * `info` is the per-purpose label (e.g. `\"DoubleRatchetMsg\"`). Optional\n * `salt` defaults to an empty buffer, matching the way the Double Ratchet\n * code has always used it.\n *\n * Note: this is intentionally a one-shot Extract-then-Expand call rather than\n * exposing Extract and Expand separately — every call site in this codebase\n * wants the same shape, and a richer API can be added later if needed.\n */\nexport async function deriveBitsHkdf(\n inputKeyMaterial: Uint8Array,\n info: string,\n lengthBytes: number,\n salt: Uint8Array = new Uint8Array(0),\n): Promise<Uint8Array> {\n if (lengthBytes <= 0) {\n throw new Error(`kdf.deriveBitsHkdf: lengthBytes must be > 0 (got ${lengthBytes})`);\n }\n const s = getSubtle();\n const key = await s.importKey(\n \"raw\",\n inputKeyMaterial as BufferSource,\n { name: \"HKDF\" },\n false,\n [\"deriveBits\"],\n );\n const bits = await s.deriveBits(\n {\n name: \"HKDF\",\n hash: \"SHA-256\",\n salt: salt as BufferSource,\n info: new TextEncoder().encode(info) as BufferSource,\n },\n key,\n lengthBytes * 8,\n );\n return new Uint8Array(bits);\n}\n","// Tiny browser-safe replacement for the `chalk` Node module.\n// Emits ANSI escape codes when running attached to a TTY (Node terminal);\n// returns plain strings everywhere else (browsers, log files, CF Workers).\n// Avoids dragging chalk + its terminfo deps into the browser/Workers bundles.\ntype ColorFn = (s: string) => string;\nconst _isTty: boolean = (() => {\n try {\n const proc = (globalThis as { process?: { stdout?: { isTTY?: boolean } } }).process;\n return !!proc?.stdout?.isTTY;\n } catch { return false; }\n})();\nconst _ansi = (code: string): ColorFn =>\n _isTty ? (s) => `\\x1b[${code}m${s}\\x1b[0m` : (s) => s;\nconst colors = {\n gray: _ansi('90'),\n red: _ansi('31'),\n green: _ansi('32'),\n yellow: _ansi('33'),\n blue: _ansi('34'),\n magenta: _ansi('35'),\n cyan: _ansi('36'),\n dim: _ansi('2'),\n};\n\nenum LogLevel {\n VERBOSE = 0,\n DEBUG = 1,\n INFO = 2,\n SUCCESS = 3,\n WARN = 4,\n ERROR = 5,\n}\n\ninterface CallerInfo {\n file?: string;\n line?: number;\n column?: number;\n function?: string;\n}\n\nclass Logger {\n private prefix: string;\n private logLevel: LogLevel;\n private console: Console;\n private showCaller: boolean;\n level: string = 'INFO';\n\n constructor(prefix: string = 'CONNECT', LOGLEVEL: string = 'INFO', showCaller: boolean = false) {\n this.prefix = colors.gray(`[${prefix}]`);\n this.showCaller = showCaller;\n let envLevel;\n\n // Check environment: browser vs Node.js\n if (typeof window !== 'undefined') {\n // Browser environment\n envLevel = (LOGLEVEL).toUpperCase() as keyof typeof LogLevel;\n } else {\n // Node.js environment - safely access process.env\n const globalProcess = (globalThis as any).process;\n const nodeEnv = globalProcess?.env?.LOG_LEVEL;\n envLevel = (nodeEnv || LOGLEVEL).toUpperCase() as keyof typeof LogLevel;\n }\n\n this.level = envLevel;\n this.logLevel = LogLevel[envLevel] ?? LogLevel.INFO;\n this.console = globalThis.console;\n }\n\n private shouldLog(level: LogLevel): boolean {\n return level >= this.logLevel;\n }\n\n /**\n * Extract caller information from stack trace\n */\n private getCallerInfo(): CallerInfo | null {\n if (!this.showCaller) return null;\n\n try {\n const stack = new Error().stack;\n if (!stack) return null;\n\n // Split stack trace into lines\n const lines = stack.split('\\n');\n\n // Skip first 3 lines (Error, getCallerInfo, the log method itself)\n // The 4th line should be the actual caller\n const callerLine = lines[3];\n if (!callerLine) return null;\n\n // Parse stack trace line\n // Format: \" at ClassName.methodName (file:line:column)\"\n // or: \" at file:line:column\"\n const match = callerLine.match(/at\\s+(?:(.+?)\\s+\\()?(.+?):(\\d+):(\\d+)\\)?/);\n\n if (!match) return null;\n\n const [, functionName, filePath, line, column] = match;\n\n // Extract just the filename from the full path\n const file = filePath.split('/').pop()?.split('?')[0];\n\n return {\n file,\n line: parseInt(line, 10),\n column: parseInt(column, 10),\n function: functionName || undefined,\n };\n } catch (error) {\n // If we can't parse the stack, just return null\n return null;\n }\n }\n\n /**\n * Format caller info for display\n */\n private formatCallerInfo(info: CallerInfo | null): string {\n if (!info) return '';\n\n const parts: string[] = [];\n\n if (info.function) {\n parts.push(colors.cyan(info.function));\n }\n\n if (info.file) {\n const location = info.line ? `${info.file}:${info.line}` : info.file;\n parts.push(colors.dim(`(${location})`));\n }\n\n return parts.length > 0 ? ' ' + parts.join(' ') : '';\n }\n\n setLevel(level: string): void {\n this.level = level.toUpperCase();\n const envLevel = level.toUpperCase() as keyof typeof LogLevel;\n this.logLevel = LogLevel[envLevel] ?? LogLevel.INFO;\n }\n\n setShowCaller(show: boolean): void {\n this.showCaller = show;\n }\n\n // Logging methods with automatic caller detection\n info(...args: any[]): void {\n if (this.shouldLog(LogLevel.INFO)) {\n const caller = this.formatCallerInfo(this.getCallerInfo());\n this.console.info(this.prefix, colors.blue('INFO') + caller, ...args);\n }\n }\n\n log(...args: any[]): void {\n this.info(...args); // Alias for info\n }\n\n verbose(...args: any[]): void {\n if (this.shouldLog(LogLevel.VERBOSE)) {\n const caller = this.formatCallerInfo(this.getCallerInfo());\n this.console.log(this.prefix, colors.cyan('VERBOSE') + caller, ...args);\n }\n }\n\n success(...args: any[]): void {\n if (this.shouldLog(LogLevel.SUCCESS)) {\n const caller = this.formatCallerInfo(this.getCallerInfo());\n this.console.debug(this.prefix, colors.green('SUCCESS') + caller, ...args);\n }\n }\n\n warn(...args: any[]): void {\n if (this.shouldLog(LogLevel.WARN)) {\n const caller = this.formatCallerInfo(this.getCallerInfo());\n this.console.warn(this.prefix, colors.yellow('WARN') + caller, ...args);\n }\n }\n\n error(...args: any[]): void {\n if (this.shouldLog(LogLevel.ERROR)) {\n const caller = this.formatCallerInfo(this.getCallerInfo());\n this.console.error(this.prefix, colors.red('ERROR') + caller, ...args);\n }\n }\n\n debug(...args: any[]): void {\n if (this.shouldLog(LogLevel.DEBUG)) {\n const caller = this.formatCallerInfo(this.getCallerInfo());\n this.console.debug(this.prefix, colors.magenta('DEBUG') + caller, ...args);\n }\n }\n\n // Rest of the methods remain unchanged\n assert(condition?: boolean, ...data: any[]): void {\n this.console.assert(condition, ...data);\n }\n\n clear(): void {\n this.console.clear();\n }\n\n count(label?: string): void {\n this.console.count(label);\n }\n\n countReset(label?: string): void {\n this.console.countReset(label);\n }\n\n dir(item?: any, options?: any): void {\n this.console.dir(item, options);\n }\n\n dirxml(...data: any[]): void {\n this.console.dirxml(...data);\n }\n\n group(...data: any[]): void {\n this.console.group(...data);\n }\n\n groupCollapsed(...data: any[]): void {\n this.console.groupCollapsed(...data);\n }\n\n groupEnd(): void {\n this.console.groupEnd();\n }\n\n table(tabularData?: any, properties?: string[]): void {\n this.console.table(tabularData, properties);\n }\n\n time(label?: string): void {\n this.console.time(label);\n }\n\n timeEnd(label?: string): void {\n this.console.timeEnd(label);\n }\n\n timeLog(label?: string, ...data: any[]): void {\n this.console.timeLog(label, ...data);\n }\n\n trace(...data: any[]): void {\n this.console.trace(...data);\n }\n\n // Note: Console property removed as it's Node.js-specific and not needed\n\n profile(label?: string): void {\n if ('profile' in this.console) {\n (this.console as any).profile(label);\n }\n }\n\n profileEnd(label?: string): void {\n if ('profileEnd' in this.console) {\n (this.console as any).profileEnd(label);\n }\n }\n\n timeStamp(label?: string): void {\n if ('timeStamp' in this.console) {\n (this.console as any).timeStamp(label);\n }\n }\n}\n\n// Export Logger class for custom instances\nexport { Logger };\n\n// Export default instance for general use\nexport const log = new Logger('CONNECT', 'INFO', false);\n\n// Also export as default\nexport default log;\n\ndeclare global {\n interface Console {\n success(...args: any[]): void;\n verbose(...args: any[]): void;\n }\n}","/**\n * Byte conversion helpers usable in both Node and the browser.\n *\n * Replaces Node's `Buffer` API for the small set of operations we actually\n * need in the crypto layer: hex/base64/base64url encode + decode, and array\n * concatenation. Lets `DoubleRatchet`, `KeyStore`, etc. compile against\n * platforms without `Buffer` (browsers, CF Workers).\n */\n\nconst HEX_CHARS = \"0123456789abcdef\";\n\n/** Encode a byte array as a lowercase hex string. */\nexport function toHex(bytes: Uint8Array): string {\n let out = \"\";\n for (let i = 0; i < bytes.length; i++) {\n const b = bytes[i];\n out += HEX_CHARS[b >> 4] + HEX_CHARS[b & 0x0f];\n }\n return out;\n}\n\n/** Decode a hex string into a byte array. Accepts upper/lowercase; rejects odd-length input. */\nexport function fromHex(hex: string): Uint8Array<ArrayBuffer> {\n if (hex.length % 2 !== 0) {\n throw new Error(`fromHex: input length must be even (got ${hex.length})`);\n }\n const ab = new ArrayBuffer(hex.length / 2);\n const out = new Uint8Array(ab);\n for (let i = 0; i < out.length; i++) {\n const byte = parseInt(hex.substring(i * 2, i * 2 + 2), 16);\n if (Number.isNaN(byte)) {\n throw new Error(`fromHex: invalid hex character at offset ${i * 2}`);\n }\n out[i] = byte;\n }\n return out;\n}\n\n/** Encode a byte array as a standard base64 string. */\nexport function toBase64(bytes: Uint8Array): string {\n let binary = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n/** Decode a standard base64 string to bytes. */\nexport function fromBase64(b64: string): Uint8Array<ArrayBuffer> {\n const binary = atob(b64);\n const ab = new ArrayBuffer(binary.length);\n const out = new Uint8Array(ab);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out;\n}\n\n/** Encode a byte array as a base64url string (no padding). */\nexport function toBase64Url(bytes: Uint8Array): string {\n return toBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** Decode a base64url string (with or without padding) to bytes. */\nexport function fromBase64Url(b64url: string): Uint8Array<ArrayBuffer> {\n const padded = b64url.replace(/-/g, \"+\").replace(/_/g, \"/\") +\n \"=\".repeat((4 - (b64url.length % 4)) % 4);\n return fromBase64(padded);\n}\n\n/** Concatenate any number of byte arrays into a single Uint8Array. */\nexport function concatBytes(...arrays: (Uint8Array | ArrayBuffer)[]): Uint8Array<ArrayBuffer> {\n let total = 0;\n for (const a of arrays) total += a.byteLength;\n const ab = new ArrayBuffer(total);\n const out = new Uint8Array(ab);\n let offset = 0;\n for (const a of arrays) {\n const view = a instanceof Uint8Array ? a : new Uint8Array(a);\n out.set(view, offset);\n offset += view.length;\n }\n return out;\n}\n\n/** Encode a UTF-8 string as bytes. Thin wrapper around TextEncoder for symmetry. */\nexport function utf8Encode(s: string): Uint8Array<ArrayBuffer> {\n // TextEncoder.encode returns Uint8Array<ArrayBufferLike>; widen to the\n // ArrayBuffer variant explicitly so WebCrypto's BufferSource type accepts it.\n const u8 = new TextEncoder().encode(s);\n const ab = new ArrayBuffer(u8.byteLength);\n const out = new Uint8Array(ab);\n out.set(u8);\n return out;\n}\n\n/** Decode UTF-8 bytes to a string. */\nexport function utf8Decode(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n","import log, { Logger } from './Logger';\n\nconst base58Alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\nexport {\n log,\n Logger\n}\n\n// Browser-safe byte conversion helpers (hex / base64 / base64url / concat).\n// The crypto layer uses these instead of Node's Buffer so it runs in browsers\n// and CF Workers as well as Node.\nexport * from './bytes';\n//0ba25dcb0db07dbac27435857ab55150d2a2e6c8f73a969c74b7659c7a8dd3a3\n\n/**\n * @public\n * @remarks Asserts the basic type of a variable\n * @param value - The value to check\n * @param type - The expected type\n * \n * @throws Error - If the type of the value does not match the expected type\n * \n */\nexport function assertType<T>(\n value: unknown,\n typeOrConstructors: string | (new (...args: any[]) => any) | (new (...args: any[]) => any)[]\n): asserts value is T {\n if (typeof typeOrConstructors === 'string') {\n // Single primitive type\n if (typeof value !== typeOrConstructors) {\n throw new Error(\n `Expected type '${typeOrConstructors}', received '${typeof value}'`\n );\n }\n } else if (Array.isArray(typeOrConstructors)) {\n // OR scenario: Array of constructors\n const isValid = typeOrConstructors.some((ctor) => value instanceof ctor);\n if (!isValid) {\n const expectedTypes = typeOrConstructors.map((ctor) => ctor.name).join(' or ');\n const receivedType = value?.constructor?.name || typeof value;\n throw new Error(\n `Expected instance of ${expectedTypes}, received '${receivedType}'`\n );\n }\n } else if (typeof typeOrConstructors === 'function') {\n // Single constructor check\n if (!(value instanceof typeOrConstructors)) {\n const expectedType = typeOrConstructors.name || 'Unknown';\n const receivedType = value?.constructor?.name || typeof value;\n throw new Error(\n `Expected instance of '${expectedType}', received '${receivedType}'`\n );\n }\n } else {\n throw new Error(`Invalid type or constructor provided for assertion.`);\n }\n}\n\n/**\n * @public\n * @remarks Encodes a string to Base58\n * @param input - the data to encode, must be a cloneable object\n * @returns string\n */\nexport function base58Encode(input: ArrayBuffer | string): string {\n const bytes = typeof input === \"string\"\n ? new TextEncoder().encode(input)\n : new Uint8Array(input);\n\n let num = BigInt(0);\n for (const byte of bytes) {\n num = (num << BigInt(8)) + BigInt(byte);\n }\n\n let result = \"\";\n while (num > 0) {\n const remainder = Number(num % BigInt(58));\n num = num / BigInt(58);\n result = base58Alphabet[remainder] + result;\n }\n\n // Preserve leading zero bytes as \"1\" in Base58\n for (const byte of bytes) {\n if (byte === 0) result = \"1\" + result;\n else break;\n }\n return result;\n}\n\n\n/**\n * @public\n * @remarks Decodes a Base58 string to a Uint8Array\n * @param input - the Base58 string to decode\n * @returns Uint8Array\n */\n\n\n// Function to decode a Base58 string to ArrayBuffer\nexport function base58Decode(input: string): ArrayBuffer {\n try {\n const base58Map = new Map(base58Alphabet.split(\"\").map((char, index) => [char, index]));\n\n let num = BigInt(0);\n for (const char of input) {\n const value = base58Map.get(char);\n if (value === undefined) throw new Error(`Invalid Base58 character: ${char}`);\n num = num * BigInt(58) + BigInt(value);\n }\n\n const byteArray: number[] = [];\n while (num > 0) {\n byteArray.push(Number(num % BigInt(256)));\n num = num / BigInt(256);\n }\n\n byteArray.reverse();\n\n // Restore leading zero bytes from Base58 \"1\"\n const leadingZeros = Array.from(input).filter((char) => char === \"1\").length;\n return new Uint8Array([...Array(leadingZeros).fill(0), ...byteArray]).buffer;\n } catch (e) {\n log.error(e);\n throw new Error(\"Invalid input\");\n }\n}\n\n/**\n * Simple checksum function using djb2 hash algorithm\n * Works in both browser and Node.js environments\n */\nfunction simpleChecksum(str: string): string {\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) + hash) + str.charCodeAt(i); // hash * 33 + c\n }\n return (hash >>> 0).toString(16); // Convert to unsigned 32-bit hex\n}\n\n\n\n/**\n * @public\n * @remarks Generates a checksum for a given input\n * @param input - The input to generate a checksum for as a string\n * @returns string\n */\nexport function generateChecksum(input: string): string {\n assertType<string>(input, \"string\");\n return simpleChecksum(input);\n}\n\n/**\n * @public\n * @remarks Verifies a checksum for a given input\n * @param input - The input to verify as a string\n * @param checksum - The checksum to verify as a string\n * @returns boolean\n */\nexport function verifyChecksum(input: string, checksum: string): boolean {\n assertType<string>(input, \"string\");\n assertType<string>(checksum, \"string\");\n return !!(simpleChecksum(input) === checksum);\n}\n\n/**\n * @internal\n * @remarks Generates a random UUID for a given packet\n * @returns string\n */\nexport function _packetId(): string {\n return \"PKT\" + generateId();\n}\n\n/**\n * @internal\n * @remarks Generates a random UUID for a given object\n * @returns string\n * \n */\n\nexport function _objectId(): string {\n return \"OBJ\" + generateId();\n}\n\n/**\n * @internal\n * @remarks Generates a random UUID for a given user\n * @returns string\n * \n */\n\nexport function _userId(): string {\n return \"USR\" + generateId();\n}\n\n/**\n * @internal\n * @remarks Generates a random UUID for a given account\n * @returns string\n * \n */\n\nexport function _accountId(): string {\n return \"ACC\" + generateId();\n}\n\n/**\n * @internal\n * @remarks Generates a random UUID for a socket\n * @returns string\n * \n */\nexport function _socketId(): string {\n return \"SKT\" + generateId();\n}\n\n/**\n * @internal\n * @remarks Generates a random UUID for a message\n * @returns string\n */\n\nexport function _messageId(): string {\n return \"MSG\" + generateId();\n}\n\n/**\n * @public\n * @remarks Generates a random UUID and base58 encodes it\n * @returns string\n */\n\nexport function generateId(): string {\n // Web-standard UUID generator (available in every modern browser and\n // Node 14+). Replaces the npm `uuid` dep so the browser bundle has one\n // fewer external import to resolve.\n return base58Encode(crypto.randomUUID());\n}\n\n/**\n * @public\n * @remarks Serializes data to a base58 encoded string\n * @param data - The data to serialize\n * @typeParam T - The type of the data to serialize\n * @returns base58 encoded string\n */\nexport function serialize<T>(data: T): string {\n const arrayBuffer = structuredCloneToArrayBuffer(data);\n return base58Encode(arrayBuffer);\n}\n\n/**\n * @public\n * @remarks Deserializes a base58 encoded string to data\n * @param base58String - The base58 encoded string to deserialize\n * @returns Deserialized data\n */\nexport function deserialize<T>(base58String: string): T {\n const arrayBuffer = base58Decode(base58String);\n return deserializeWithStructuredClone(arrayBufferToData(arrayBuffer)) as T;\n}\n\nfunction deserializeWithStructuredClone(data: any): unknown {\n const deserializeHelper = (item: any): any => {\n if (item === null || typeof item !== 'object') {\n return item; // Handle primitives directly\n }\n\n if (item.__type === \"Symbol\") {\n return Symbol.for(item.value) || Symbol(item.value);\n }\n\n if (item.__type === 'Date') {\n return new Date(item.value); // Rehydrate Date\n }\n\n if (item.__type === 'Map') {\n return new Map(item.value); // Rehydrate Map\n }\n\n if (item.__type === 'Set') {\n return new Set(item.value); // Rehydrate Set\n }\n\n if (Array.isArray(item)) {\n return item.map(deserializeHelper); // Rehydrate Array recursively\n }\n\n // Generic object case\n const deserializedObject: any = {};\n for (const key of Object.keys(item)) {\n deserializedObject[key] = deserializeHelper(item[key]);\n }\n return deserializedObject;\n };\n\n return deserializeHelper(data);\n}\n\nfunction structuredCloneToArrayBuffer(data: any): ArrayBuffer {\n // Clone and transform the data for serialization\n const serializeHelper = (item: any): any => {\n if (item === null || typeof item !== \"object\") return item;\n\n if (typeof item === \"symbol\") {\n const key = Symbol.keyFor(item) || item.description || \"\";\n return { __type: \"Symbol\", value: key };\n }\n\n if (item.constructor === Date) return { __type: \"Date\", value: item.toISOString() };\n if (item.constructor === Map) return { __type: \"Map\", value: Array.from(item.entries()) };\n if (item.constructor === Set) return { __type: \"Set\", value: Array.from(item) };\n if (Array.isArray(item)) return item.map(serializeHelper);\n\n const serializedObject: any = {};\n for (const key of Object.keys(item)) {\n serializedObject[key] = serializeHelper(item[key]);\n }\n return serializedObject;\n };\n\n // Serialize the structured data into a JSON string\n const jsonString = JSON.stringify(serializeHelper(data));\n return new TextEncoder().encode(jsonString).buffer as ArrayBuffer;\n}\n\nfunction arrayBufferToData(arrayBuffer: ArrayBuffer): any {\n let jsonString = new TextDecoder().decode(new Uint8Array(arrayBuffer));\n jsonString = jsonString.replace(/^\\0+/, '')\n return JSON.parse(jsonString);\n}\n\n/**\n * @public\n * @remarks Retries a method a specified number of times with a delay between each attempt, this is a decorator\n * @param retries - The number of times to retry the method\n * @param delay - The delay in milliseconds between each attempt\n */\nexport function Retry(retries: number = 3, delay: number = 1000): MethodDecorator {\n\n return function (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<any>) {\n // Ensure the descriptor exists\n if (!descriptor || typeof descriptor.value !== \"function\") {\n throw new Error(\"Retry decorator can only be applied to methods.\");\n }\n\n const originalMethod = descriptor.value;\n\n descriptor.value = async function (...args: any[]) {\n let attempt = 0;\n\n while (attempt < retries) {\n try {\n return await originalMethod.apply(this, args);\n } catch (error) {\n attempt++;\n log.debug(`Retrying ${String(propertyKey)} - Attempt ${attempt}/${retries}`);\n if (attempt >= retries) {\n throw error; // Re-throw the error if retries are exhausted\n }\n log.log(`Waiting for ${delay}ms before retrying...`);\n await new Promise(res => setTimeout(res, delay));\n }\n }\n };\n\n return descriptor;\n };\n}\n\n/**\n * @public\n * @remarks Waits for a class property to be ready before executing a method, this is a decorator.\n * @param readyPropertyName - The class property to check for readiness\n */\nexport function Ready(readyPropertyName: string = \"ready\"): MethodDecorator | PropertyDecorator {\n return function (target: object, propertyKey: string | symbol, descriptor: PropertyDescriptor) {\n if (descriptor === undefined) {\n throw new Error(\"@Ready can only be applied to methods, getters, or setters.\");\n }\n\n const isGetter = typeof descriptor.get === \"function\";\n const isSetter = typeof descriptor.set === \"function\";\n const isMethod = typeof descriptor.value === \"function\";\n\n const readyCheck = async (instance: any) => {\n const readyProperty = instance[readyPropertyName];\n\n if (!readyProperty || !(readyProperty instanceof Promise)) {\n log.warn(`Property \"${readyPropertyName}\" must be a Promise.`);\n return\n }\n await readyProperty; // Wait for the property to resolve\n };\n\n if (isMethod) {\n const originalMethod = descriptor.value;\n descriptor.value = async function (...args: any[]) {\n await readyCheck(this);\n return originalMethod.apply(this, args);\n };\n } else if (isGetter || isSetter) {\n const originalGetter = descriptor.get;\n const originalSetter = descriptor.set;\n\n if (isGetter) {\n descriptor.get = async function () {\n await readyCheck(this);\n return originalGetter!.call(this);\n };\n }\n\n if (isSetter) {\n descriptor.set = async function (value: any) {\n await readyCheck(this);\n return originalSetter!.call(this, value);\n };\n }\n } else {\n throw new Error(\"@Ready can only be applied to methods, getters, or setters.\");\n }\n\n return descriptor;\n };\n}\n\n\n/**\n * Converts bytes into a more human-friendly format (e.g., KB, MB, GB).\n * @internal\n * @param bytes - The number of bytes to convert.\n * @param decimals - The number of decimals to display (default is 2).\n * @returns A formatted string representing the size in appropriate units.\n */\nexport function _formatBytes(bytes: number, decimals: number = 2): string {\n if (bytes === 0) return \"0 Bytes\";\n\n const k = 1024; // 1 KB = 1024 Bytes\n const sizes = [\"Bytes\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"];\n const i = Math.floor(Math.log(bytes) / Math.log(k)); // Determines the index for size\n const sizeInUnit = bytes / Math.pow(k, i); // Converts bytes to appropriate unit\n\n return `${sizeInUnit.toFixed(decimals)} ${sizes[i]}`;\n}\n\n/**\n * Retrieves the IP address(es) for a given hostname using Cloudflare's DNS-over-HTTPS service.\n *\n * This function queries the Cloudflare DNS API to resolve the provided hostname to its corresponding\n * IPv4 address(es) (A records). It returns an array of IP addresses or logs an error if the resolution fails.\n *\n * @param hostname - The hostname to resolve (e.g., \"example.com\").\n * @returns A promise that resolves to an array of IP addresses (strings) associated with the hostname.\n * If no IP addresses are found or an error occurs, an empty array or undefined may be returned.\n * @throws Error If the DNS query fails due to a network error or invalid response from the server.\n * @public\n * @example\n * ```typescript\n * import { log } from '@muhkoo/connect/utilities';\n * getIPAddress(\"example.com\").then(ips => log.debug(ips));\n * // Output: [\"93.184.216.34\"]\n * ```\n */\nexport async function getIPAddress(hostname: string) {\n const url = `https://cloudflare-dns.com/dns-query?name=${hostname}&type=A`;\n\n try {\n const response = await fetch(url, {\n headers: {\n Accept: \"application/dns-json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch DNS records: ${response.statusText}`);\n }\n\n const data = await response.json();\n\n // Extract the IP address from the DNS response\n const ipAddresses = data.Answer?.map((record: { data: string }) => record.data) || [];\n log.debug(`IP addresses for ${hostname}:`, ipAddresses);\n\n return ipAddresses;\n } catch (error) {\n log.error(`Error resolving IP for ${hostname}:`, error);\n }\n}\n\nexport function isNumber(value: string | number): boolean {\n // Check if the value is a number\n if (typeof value === 'number' && !isNaN(value) && isFinite(value)) {\n return true;\n }\n // Check if the value is a string and represents a valid number\n if (typeof value === 'string') {\n return !isNaN(parseFloat(value)) && isFinite(value as any);\n }\n // Return false for other types\n return false;\n}\n\nexport function getId(row: { insertId?: number, id?: number }): number {\n if (row.insertId) {\n return row.insertId;\n } else if (row.id) {\n return row.id;\n } else {\n throw new Error('No ID found in the row');\n }\n}","import { serialize, deserialize, toBase64, fromBase64, fromBase64Url, concatBytes, utf8Decode } from '../utilities';\ninterface KeyPair {\n privateKey: CryptoKey | null;\n publicKey: CryptoKey;\n}\n\ninterface AuthKeyPair {\n privateKey: CryptoKey | null;\n publicKey: CryptoKey;\n}\n\ninterface DehydratedKeys {\n ecdhPub: string; // ECDH public key in JWK format\n ecdhPriv: string; // ECDH private key in JWK format\n ecdsaPub: string; // ECDSA public key in JWK format\n ecdsaPriv: string; // ECDSA private key in JWK format\n}\n\nclass KeyStore {\n private static instance: KeyStore;\n private _keys: Map<string, KeyPair> = new Map();\n private _authKeys: Map<string, AuthKeyPair> = new Map();\n\n private constructor() { }\n\n public static getInstance(): KeyStore {\n if (!KeyStore.instance) {\n KeyStore.instance = new KeyStore();\n }\n return KeyStore.instance;\n }\n\n get keys(): Map<string, KeyPair> {\n return this._keys;\n }\n\n get authKeys(): Map<string, AuthKeyPair> {\n return this._authKeys;\n }\n\n public async generateOwnKeyPair(id: string): Promise<KeyPair> {\n if (this._keys.has(id)) {\n throw new Error(`Key pair for ${id} already exists.`);\n }\n const ecdhKeyPair = await crypto.subtle.generateKey(\n { name: 'ECDH', namedCurve: 'P-384' },\n true,\n ['deriveKey', 'deriveBits']\n );\n this._keys.set(id, { privateKey: ecdhKeyPair.privateKey, publicKey: ecdhKeyPair.publicKey });\n\n const ecdsaKeyPair = await crypto.subtle.generateKey(\n { name: 'ECDSA', namedCurve: 'P-384' },\n true,\n ['sign', 'verify']\n );\n this._authKeys.set(id, { privateKey: ecdsaKeyPair.privateKey, publicKey: ecdsaKeyPair.publicKey });\n\n const dehydrated = await this.dehydrateKeyPair(id);\n appLogger.debug(`Generated key pair for ${id}: publicKey=${dehydrated.ecdhPub.slice(0, 16)}...`);\n return { privateKey: ecdhKeyPair.privateKey, publicKey: ecdhKeyPair.publicKey };\n }\n\n public async storeRemotePublicKeys(id: string, ecdhPublicKey: CryptoKey, ecdsaPublicKey: CryptoKey): Promise<void> {\n const existing = this._keys.get(id);\n if (!existing || !existing.privateKey) {\n this._keys.set(id, { privateKey: null, publicKey: ecdhPublicKey });\n }\n const existingAuth = this._authKeys.get(id);\n if (!existingAuth || !existingAuth.privateKey) {\n this._authKeys.set(id, { privateKey: null, publicKey: ecdsaPublicKey });\n }\n const dehydrated = await this.dehydrateKeyPair(id);\n appLogger.debug(`Stored remote public keys for ${id}: ecdhPub=${dehydrated.ecdhPub.slice(0, 16)}...`);\n }\n\n public async hydrateKeyPair(id: string, dehydrated: DehydratedKeys): Promise<void> {\n const ecdhPubJwk = JSON.parse(deserialize(dehydrated.ecdhPub));\n const ecdhPublicKey = await crypto.subtle.importKey(\n 'jwk',\n ecdhPubJwk,\n { name: 'ECDH', namedCurve: 'P-384' },\n true,\n []\n );\n const ecdsaPubJwk = JSON.parse(deserialize(dehydrated.ecdsaPub));\n const ecdsaPublicKey = await crypto.subtle.importKey(\n 'jwk',\n ecdsaPubJwk,\n { name: 'ECDSA', namedCurve: 'P-384' },\n true,\n ['verify']\n );\n let ecdhPrivateKey: CryptoKey | null = null;\n let ecdsaPrivateKey: CryptoKey | null = null;\n if (dehydrated.ecdhPriv) {\n const ecdhPrivJwk = JSON.parse(deserialize(dehydrated.ecdhPriv));\n ecdhPrivateKey = await crypto.subtle.importKey(\n 'jwk',\n ecdhPrivJwk,\n { name: 'ECDH', namedCurve: 'P-384' },\n true,\n ['deriveKey', 'deriveBits']\n );\n }\n if (dehydrated.ecdsaPriv) {\n const ecdsaPrivJwk = JSON.parse(deserialize(dehydrated.ecdsaPriv));\n ecdsaPrivateKey = await crypto.subtle.importKey(\n 'jwk',\n ecdsaPrivJwk,\n { name: 'ECDSA', namedCurve: 'P-384' },\n true,\n ['sign']\n );\n }\n const existing = this._keys.get(id);\n if (!existing || !existing.privateKey) {\n this._keys.set(id, { privateKey: ecdhPrivateKey, publicKey: ecdhPublicKey });\n }\n const existingAuth = this._authKeys.get(id);\n if (!existingAuth || !existingAuth.privateKey) {\n this._authKeys.set(id, { privateKey: ecdsaPrivateKey, publicKey: ecdsaPublicKey });\n }\n }\n\n public getKeyPair(id: string): KeyPair | null {\n return this._keys.get(id) || null;\n }\n\n public getAuthKeyPair(id: string): AuthKeyPair | null {\n return this._authKeys.get(id) || null;\n }\n\n public async dehydrateKeyPair(id: string): Promise<DehydratedKeys> {\n const keyPair = this._keys.get(id);\n const authKeyPair = this._authKeys.get(id);\n if (!keyPair || !authKeyPair) {\n throw new Error(`No key pair for ${id}`);\n }\n const ecdhPubJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey);\n const ecdhPrivJwk = keyPair.privateKey ? await crypto.subtle.exportKey('jwk', keyPair.privateKey) : null;\n const ecdsaPubJwk = await crypto.subtle.exportKey('jwk', authKeyPair.publicKey);\n const ecdsaPrivJwk = authKeyPair.privateKey ? await crypto.subtle.exportKey('jwk', authKeyPair.privateKey) : null;\n const ecdhPubBase64 = JSON.stringify(ecdhPubJwk).replace(/=+$/, '');\n const ecdhPrivBase64 = ecdhPrivJwk ? JSON.stringify(ecdhPrivJwk).replace(/=+$/, '') : '';\n const ecdsaPubBase64 = JSON.stringify(ecdsaPubJwk).replace(/=+$/, '');\n const ecdsaPrivBase64 = ecdsaPrivJwk ? JSON.stringify(ecdsaPrivJwk).replace(/=+$/, '') : '';\n return {\n ecdhPub: serialize(ecdhPubBase64),\n ecdhPriv: ecdhPrivBase64 ? serialize(ecdhPrivBase64) : '',\n ecdsaPub: serialize(ecdsaPubBase64),\n ecdsaPriv: ecdsaPrivBase64 ? serialize(ecdsaPrivBase64) : '',\n };\n }\n\n public async getRawEcdsaPublicKey(id: string): Promise<Uint8Array | null> {\n const authKeyPair = this._authKeys.get(id);\n if (!authKeyPair) {\n return null;\n }\n const jwk = await crypto.subtle.exportKey('jwk', authKeyPair.publicKey);\n const x = fromBase64Url(jwk.x!);\n const y = fromBase64Url(jwk.y!);\n // SEC1 uncompressed point: 0x04 || x || y\n return concatBytes(new Uint8Array([0x04]), x, y);\n }\n\n public async packDehydratedKeys(id: string): Promise<string> {\n const dehydrated = await this.dehydrateKeyPair(id);\n const combined = JSON.stringify(dehydrated);\n return toBase64(new TextEncoder().encode(combined));\n }\n\n public async hydrateFromPacked(id: string, masterKey: string): Promise<void> {\n const decoded = utf8Decode(fromBase64(masterKey));\n const dehydrated: DehydratedKeys = JSON.parse(decoded);\n await this.hydrateKeyPair(id, dehydrated);\n }\n}\n\nexport { KeyStore, KeyPair, AuthKeyPair, DehydratedKeys };","import { RatchetState, CipherMessage, CipherMessageHeader } from './types.d';\nimport { KeyStore } from './KeyStore';\nimport { deserialize, toHex, fromHex, concatBytes, utf8Encode } from '../utilities';\nimport {\n encryptAesGcm,\n decryptAesGcm,\n deriveBitsHkdf,\n randomBytes,\n AES_GCM_IV_BYTES,\n} from './primitives';\n\n// We rely on the WebCrypto global (`crypto`/`globalThis.crypto`) — present in\n// browsers, CF Workers, and Node 19+. No `require('crypto')` Node fallback;\n// supported runtimes all expose WebCrypto natively.\n\nasync function getPubKeyHex(pubKey: CryptoKey): Promise<string> {\n const exported = await crypto.subtle.exportKey('raw', pubKey);\n return toHex(new Uint8Array(exported));\n}\n\nasync function keysEqual(key1: CryptoKey, key2: CryptoKey): Promise<boolean> {\n const hex1 = await getPubKeyHex(key1);\n const hex2 = await getPubKeyHex(key2);\n return hex1 === hex2;\n}\n\n\nclass DoubleRatchet {\n private state: RatchetState;\n private sessionType: 'global' | 'specific';\n private maxSkip: number = 3000;\n private overlapPeriod: number = 30000; // ms\n private windowSize: number = 100; // messages per DH ratchet\n\n constructor(senderId: string, recipientId: string, sessionType: 'global' | 'specific', isClient: boolean = true) {\n this.sessionType = sessionType;\n const keyStore = KeyStore.getInstance();\n const senderKeyPair = keyStore.getKeyPair(senderId);\n const recipientKeyPair = keyStore.getKeyPair(recipientId);\n\n if (!senderKeyPair || !senderKeyPair.privateKey) {\n throw new Error(`Missing own key pair for sender ${senderId}`);\n }\n if (!recipientKeyPair || !recipientKeyPair.publicKey) {\n throw new Error(`Missing public key for recipient ${recipientId}`);\n }\n\n this.state = {\n clientDhPriv: isClient ? senderKeyPair.privateKey : null,\n clientDhPub: isClient ? senderKeyPair.publicKey : recipientKeyPair.publicKey,\n serverDhPriv: isClient ? null : senderKeyPair.privateKey,\n serverDhPub: isClient ? recipientKeyPair.publicKey : senderKeyPair.publicKey,\n rootKey: null,\n sendChainKey: null,\n recvChainKey: null,\n sendCount: 0,\n recvCount: 0,\n prevChainLength: 0,\n currentSkippedKeys: new Map(),\n oldSkippedMessageKeys: new Map(),\n };\n\n appLogger.debug(`Constructor: senderId=${senderId}, recipientId=${recipientId}, isClient=${isClient}`);\n }\n\n private hkdf(input: Uint8Array, info: string, length: number): Promise<Uint8Array> {\n return deriveBitsHkdf(input, info, length);\n }\n\n public async initializeSession(isClient: boolean = true): Promise<void> {\n appLogger.debug(`Initializing session: isClient=${isClient}, sessionType=${this.sessionType}`);\n const ownPriv = isClient ? this.state.clientDhPriv : this.state.serverDhPriv;\n if (!ownPriv) {\n throw new Error('Missing own private key');\n }\n const remotePub = isClient ? this.state.serverDhPub : this.state.clientDhPub;\n const sharedSecret = await crypto.subtle.deriveBits(\n { name: 'ECDH', public: remotePub },\n ownPriv,\n 384\n );\n const keys = await this.hkdf(new Uint8Array(sharedSecret), 'DoubleRatchetInit', 32);\n this.state.rootKey = keys;\n this.state.sendChainKey = this.state.rootKey;\n this.state.recvChainKey = this.state.rootKey;\n appLogger.debug(`Initialized: rootKey set`);\n }\n\n private async dhRatchet(newPubKey: CryptoKey, isClient: boolean = true): Promise<void> {\n appLogger.debug(`DH ratchet: isClient=${isClient}`);\n const ownPriv = isClient ? this.state.clientDhPriv : this.state.serverDhPriv;\n if (!ownPriv) {\n throw new Error('Missing own private key');\n }\n const sharedSecret = await crypto.subtle.deriveBits(\n { name: 'ECDH', public: newPubKey },\n ownPriv,\n 384\n );\n const input = concatBytes(this.state.rootKey!, new Uint8Array(sharedSecret));\n const keys = await this.hkdf(input, 'DoubleRatchetDH', 64);\n this.state.rootKey = keys.subarray(0, 32);\n this.state.recvChainKey = keys.subarray(32);\n this.state.sendChainKey = isClient ? this.state.recvChainKey : this.state.rootKey;\n this.state.prevChainLength = this.state.sendCount;\n this.state.sendCount = 0;\n this.state.recvCount = 0;\n appLogger.debug(`DH ratchet complete`);\n }\n\n private async symmetricRatchet(chainKey: Uint8Array): Promise<[Uint8Array, Uint8Array]> {\n const keys = await this.hkdf(chainKey, 'DoubleRatchetMsg', 64);\n const messageKey = keys.subarray(0, 32);\n const newChainKey = keys.subarray(32);\n appLogger.debug(`Symmetric ratchet: messageKey generated`);\n return [messageKey, newChainKey];\n }\n\n public async encrypt(\n plaintext: string,\n newDhKey: boolean = false,\n senderId: string,\n recipientId: string,\n sessionId: string,\n sessionType: 'global' | 'specific'\n ): Promise<CipherMessage> {\n if (sessionType !== this.sessionType) {\n throw new Error(`Session type mismatch: expected ${this.sessionType}, got ${sessionType}`);\n }\n\n const keyStore = KeyStore.getInstance();\n if (this.sessionType === 'specific' && this.state.sendCount >= this.windowSize && this.state.sendCount > 0) {\n newDhKey = true;\n }\n if (newDhKey && this.sessionType === 'specific') {\n appLogger.debug(`Generating new DH key pair for ${senderId}`);\n const ecdhKeyPair = await crypto.subtle.generateKey(\n { name: 'ECDH', namedCurve: 'P-384' },\n true,\n ['deriveKey', 'deriveBits']\n );\n this.state.clientDhPriv = ecdhKeyPair.privateKey as CryptoKey;\n this.state.clientDhPub = ecdhKeyPair.publicKey as CryptoKey;\n keyStore.keys.set(senderId, { privateKey: ecdhKeyPair.privateKey as CryptoKey, publicKey: ecdhKeyPair.publicKey as CryptoKey });\n await this.dhRatchet(this.state.serverDhPub, true);\n }\n\n const [messageKey, newChainKey] = await this.symmetricRatchet(this.state.sendChainKey!);\n this.state.sendChainKey = newChainKey;\n\n const iv = randomBytes(AES_GCM_IV_BYTES);\n const encrypted = await encryptAesGcm(messageKey, iv, utf8Encode(plaintext));\n const cipherTextWithTag = toHex(encrypted);\n appLogger.debug(`Encrypt: plaintextLength=${plaintext.length}, ciphertextLength=${encrypted.byteLength}`);\n\n this.state.sendCount++;\n const dehydratedSender = await keyStore.dehydrateKeyPair(senderId);\n const header: CipherMessageHeader = {\n dhPub: dehydratedSender.ecdhPub,\n prevChainLength: this.state.prevChainLength,\n messageNumber: this.state.sendCount,\n sessionId,\n sessionType,\n senderId,\n recipientId,\n timestamp: Date.now(),\n signature: '',\n };\n appLogger.debug(`Message header:`, header);\n appLogger.debug(`Message header:`, keyStore.getAuthKeyPair(senderId)!.privateKey!);\n const sign = await crypto.subtle.sign(\n { name: 'ECDSA', hash: 'SHA-256' },\n keyStore.getAuthKeyPair(senderId)!.privateKey!,\n utf8Encode(JSON.stringify({\n dhPub: header.dhPub,\n prevChainLength: header.prevChainLength,\n messageNumber: header.messageNumber,\n sessionId,\n sessionType,\n senderId,\n recipientId,\n timestamp: header.timestamp\n }))\n );\n header.signature = toHex(new Uint8Array(sign));\n\n appLogger.debug(`Encrypted: sessionId=${sessionId}, messageNumber=${this.state.sendCount}, sender=${senderId}, recipient=${recipientId}`);\n return {\n header,\n ciphertext: cipherTextWithTag,\n nonce: toHex(iv),\n };\n }\n\n private cleanOldSkippedKeys(): void {\n const now = Date.now();\n for (const skipped of this.state.oldSkippedMessageKeys.entries()) {\n // [pubHex, { created }]\n const pubHex = skipped[0];\n const data = skipped[1];\n const created = data.created;\n if (now > created + this.overlapPeriod) {\n this.state.oldSkippedMessageKeys.delete(pubHex);\n }\n }\n }\n\n public async decrypt(message: CipherMessage, isClient: boolean = true): Promise<string> {\n // const { header, ciphertext, nonce } = message;\n const header = message.header;\n const ciphertext = message.ciphertext;\n const nonce = message.nonce;\n if (header.sessionType !== this.sessionType) {\n throw new Error(`Session type mismatch: expected ${this.sessionType}, got ${header.sessionType}`);\n }\n\n const keyStore = KeyStore.getInstance();\n const verify = await crypto.subtle.verify(\n { name: 'ECDSA', hash: 'SHA-256' },\n keyStore.getAuthKeyPair(header.senderId)!.publicKey,\n fromHex(header.signature),\n utf8Encode(JSON.stringify({\n dhPub: header.dhPub,\n prevChainLength: header.prevChainLength,\n messageNumber: header.messageNumber,\n sessionId: header.sessionId,\n sessionType: header.sessionType,\n senderId: header.senderId,\n recipientId: header.recipientId,\n timestamp: header.timestamp\n }))\n );\n if (!verify) {\n throw new Error('Invalid signature');\n }\n\n const maxAge = 5 * 60 * 1000;\n if (Math.abs(Date.now() - header.timestamp) > maxAge) {\n throw new Error('CipherMessage too old, possible replay attack');\n }\n\n appLogger.debug(`Decrypting: sessionId=${header.sessionId}, messageNumber=${header.messageNumber}, sender=${header.senderId}, recipient=${header.recipientId}`);\n\n if (!ciphertext || !nonce || !header.dhPub) {\n throw new Error('Invalid message: missing ciphertext, nonce, or dhPub');\n }\n\n if (!/^[0-9a-fA-F]+$/.test(ciphertext) || ciphertext.length % 2 !== 0) {\n throw new Error(`Invalid ciphertext: not a valid hex string (length=${ciphertext.length})`);\n }\n\n if (!/^[0-9a-fA-F]+$/.test(nonce) || nonce.length % 2 !== 0) {\n throw new Error(`Invalid nonce: not a valid hex string (length=${nonce.length})`);\n }\n\n const ciphertextBuffer = fromHex(ciphertext);\n const nonceBuffer = fromHex(nonce);\n if (nonceBuffer.length !== 12) {\n throw new Error(`Invalid nonce: must be 12 bytes (length=${nonceBuffer.length})`);\n }\n\n const senderPubJwk = JSON.parse(deserialize(header.dhPub));\n const senderPubKey = await crypto.subtle.importKey(\n 'jwk',\n senderPubJwk,\n { name: 'ECDH', namedCurve: 'P-384' },\n true,\n []\n );\n const senderPubHex = await getPubKeyHex(senderPubKey as CryptoKey);\n const currentSenderPub = isClient ? this.state.serverDhPub : this.state.clientDhPub;\n const currentSenderPubHex = await getPubKeyHex(currentSenderPub);\n\n this.cleanOldSkippedKeys();\n\n let messageKey: Uint8Array;\n if (senderPubHex === currentSenderPubHex) {\n // Current chain\n if (header.messageNumber > this.state.recvCount) {\n const numSkips = header.messageNumber - this.state.recvCount - 1;\n if (numSkips > this.maxSkip) {\n throw new Error('Too many skipped messages');\n }\n for (let i = 0; i < numSkips; i++) {\n const [skippedKey, newChainKey] = await this.symmetricRatchet(this.state.recvChainKey!);\n this.state.currentSkippedKeys.set(this.state.recvCount + 1 + i, skippedKey);\n this.state.recvChainKey = newChainKey;\n }\n }\n\n if (this.state.currentSkippedKeys.has(header.messageNumber)) {\n messageKey = this.state.currentSkippedKeys.get(header.messageNumber)!;\n this.state.currentSkippedKeys.delete(header.messageNumber);\n appLogger.debug(`Using skipped key for messageNumber=${header.messageNumber}`);\n } else {\n const [msgKey, newChainKey] = await this.symmetricRatchet(this.state.recvChainKey!);\n messageKey = msgKey;\n this.state.recvChainKey = newChainKey;\n }\n\n this.state.recvCount = Math.max(this.state.recvCount, header.messageNumber);\n } else {\n // Check if new DH pub\n const expectedPubKey = keyStore.getKeyPair(header.senderId)!.publicKey;\n if (!(await keysEqual(senderPubKey as CryptoKey, expectedPubKey))) {\n // New DH key, handle skip on old chain before ratchet\n const oldSenderPubHex = currentSenderPubHex;\n const numSkips = header.prevChainLength - this.state.recvCount;\n if (numSkips > this.maxSkip) {\n throw new Error('Too many skipped messages on old chain');\n }\n let oldSkips = this.state.oldSkippedMessageKeys.get(oldSenderPubHex)?.skips || new Map<number, Uint8Array>();\n let tempRecvChainKey = this.state.recvChainKey!;\n for (let i = 0; i < numSkips; i++) {\n const [skippedKey, newChainKey] = await this.symmetricRatchet(tempRecvChainKey);\n oldSkips.set(this.state.recvCount + 1 + i, skippedKey);\n tempRecvChainKey = newChainKey;\n }\n this.state.oldSkippedMessageKeys.set(oldSenderPubHex, { skips: oldSkips, created: Date.now() });\n\n // Clear current skipped\n this.state.currentSkippedKeys.clear();\n\n // Perform DH ratchet\n await this.dhRatchet(senderPubKey as CryptoKey, isClient);\n\n // Update state sender pub\n if (isClient) {\n this.state.serverDhPub = senderPubKey as CryptoKey;\n } else {\n this.state.clientDhPub = senderPubKey as CryptoKey;\n }\n\n // Update keyStore\n keyStore.storeRemotePublicKeys(header.senderId, senderPubKey as CryptoKey, keyStore.getAuthKeyPair(header.senderId)!.publicKey);\n\n // Now derive message key for new chain\n if (header.messageNumber > this.state.recvCount) {\n const numSkipsNew = header.messageNumber - this.state.recvCount - 1;\n if (numSkipsNew > this.maxSkip) {\n throw new Error('Too many skipped messages');\n }\n for (let i = 0; i < numSkipsNew; i++) {\n const [skippedKey, newChainKey] = await this.symmetricRatchet(this.state.recvChainKey!);\n this.state.currentSkippedKeys.set(this.state.recvCount + 1 + i, skippedKey);\n this.state.recvChainKey = newChainKey;\n }\n }\n\n if (this.state.currentSkippedKeys.has(header.messageNumber)) {\n messageKey = this.state.currentSkippedKeys.get(header.messageNumber)!;\n this.state.currentSkippedKeys.delete(header.messageNumber);\n } else {\n const [msgKey, newChainKey] = await this.symmetricRatchet(this.state.recvChainKey!);\n messageKey = msgKey;\n this.state.recvChainKey = newChainKey;\n }\n\n this.state.recvCount = Math.max(this.state.recvCount, header.messageNumber);\n } else {\n // Old chain\n const oldData = this.state.oldSkippedMessageKeys.get(senderPubHex);\n if (oldData && oldData.skips.has(header.messageNumber)) {\n messageKey = oldData.skips.get(header.messageNumber)!;\n oldData.skips.delete(header.messageNumber);\n if (oldData.skips.size === 0) {\n this.state.oldSkippedMessageKeys.delete(senderPubHex);\n }\n appLogger.debug(`Using old skipped key for messageNumber=${header.messageNumber} on old chain`);\n } else {\n throw new Error('No key for message on old chain');\n }\n }\n }\n\n try {\n const decrypted = await decryptAesGcm(messageKey, nonceBuffer, ciphertextBuffer);\n appLogger.debug(`Decrypted successfully: sessionId=${header.sessionId}, messageNumber=${header.messageNumber}`);\n return new TextDecoder().decode(decrypted);\n } catch (error) {\n appLogger.error(`Decryption failed: ${error instanceof Error ? error.message : 'unknown error'}`);\n throw new Error(`Decryption failed: ${error instanceof Error ? error.message : 'unknown error'}`);\n }\n }\n\n public getState(): RatchetState {\n return { ...this.state };\n }\n\n public setState(state: RatchetState): void {\n this.state = { ...state };\n }\n}\n\nexport {\n RatchetState,\n CipherMessage,\n CipherMessageHeader,\n DoubleRatchet,\n}","import { prove as groth16Prove, verify as groth16Verify } from '@zk-kit/groth16';\nimport type { PublicSignals as Groth16PublicSignals } from '@zk-kit/groth16';\n// Shared ZK types live in src/types/zk so the workers build (which can't pull\n// in snarkjs) sees the same VerificationKey / Groth16Proof shapes used here.\nimport type { Groth16Proof, VerificationKey } from '../types/zk';\n\n// Re-export so existing consumers of crypto/* keep working\nexport type SnarkProof = Groth16Proof;\nexport type { VerificationKey } from '../types/zk';\n\nexport interface ZkCompiled {\n verificationKey: VerificationKey;\n}\n\n// Authentication public input structure\nexport class AuthPublicInput {\n commitment: string;\n nonce: string;\n ecdsaPubHash: string;\n\n constructor(commitment: string, nonce: string, ecdsaPubHash: string) {\n this.commitment = commitment;\n this.nonce = nonce;\n this.ecdsaPubHash = ecdsaPubHash;\n }\n\n toPublicSignals(): string[] {\n return [this.commitment, this.nonce, this.ecdsaPubHash];\n }\n}\n\n// Helper functions for Field operations using native BigInt\nexport class Field {\n private value: bigint;\n public static readonly FIELD_SIZE = BigInt('21888242871839275222246405745257275088548364400416034343698204186575808495617'); // BN254 field size\n\n constructor(value: bigint | string | number) {\n if (typeof value === 'string') {\n this.value = BigInt(value);\n } else if (typeof value === 'number') {\n this.value = BigInt(value);\n } else {\n this.value = value;\n }\n // Ensure value is within field\n this.value = this.value % Field.FIELD_SIZE;\n if (this.value < 0n) {\n this.value += Field.FIELD_SIZE;\n }\n }\n\n toBigInt(): bigint {\n return this.value;\n }\n\n toString(): string {\n return this.value.toString();\n }\n\n toHex(): string {\n return '0x' + this.value.toString(16).padStart(64, '0');\n }\n\n equals(other: Field): boolean {\n return this.value === other.value;\n }\n\n static fromHex(hex: string): Field {\n if (!hex.startsWith('0x')) {\n throw new Error('Invalid hex prefix');\n }\n return new Field(BigInt(hex));\n }\n}\n\n// Import Poseidon from circomlibjs\nlet poseidonModule: any = null;\nlet poseidonF: any = null;\n\nasync function loadPoseidon() {\n if (!poseidonModule) {\n try {\n // Try to load circomlibjs poseidon\n const buildPoseidon = (await import('circomlibjs')).buildPoseidon;\n const poseidonBuilder = await buildPoseidon();\n poseidonModule = poseidonBuilder;\n poseidonF = poseidonBuilder.F;\n } catch (error) {\n console.warn('Failed to load circomlibjs poseidon, using fallback:', error);\n // Fallback implementation for testing - this is NOT cryptographically secure\n poseidonModule = async (inputs: any[]) => {\n const data = inputs.map(i => i.toString()).join('');\n const encoder = new TextEncoder();\n const hashBuffer = await crypto.subtle.digest('SHA-256', encoder.encode(data));\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n return BigInt('0x' + hashHex) % Field.FIELD_SIZE;\n };\n poseidonF = {\n toString: (val: any) => val.toString()\n };\n }\n }\n return { poseidon: poseidonModule, F: poseidonF };\n}\n\n// Poseidon hash implementation\nexport class Poseidon {\n static async hash(inputs: Field[]): Promise<Field> {\n const { poseidon, F } = await loadPoseidon();\n const inputBigInts = inputs.map(f => f.toBigInt());\n const hashResult = poseidon(inputBigInts);\n const hashString = F.toString(hashResult);\n return new Field(BigInt(hashString));\n }\n}\n\n// Encoding: BigInt to hex string\nexport function encodeToHex(field: Field): string {\n return field.toHex();\n}\n\n// Decoding: Hex string back to Field\nexport function decodeFromHex(hexStr: string): Field {\n return Field.fromHex(hexStr);\n}\n\n// Circuit configuration - buffers only\nexport interface CircuitBufferConfig {\n wasm: Uint8Array;\n zkey: Uint8Array;\n verificationKey: VerificationKey;\n}\n\n// Circuit wrapper for HashKnowledge\nexport class HashKnowledge {\n private static wasmBuffer?: Uint8Array;\n private static zkeyBuffer?: Uint8Array;\n private static verificationKey?: VerificationKey;\n\n static setCircuitBuffers(wasm: Uint8Array, zkey: Uint8Array, verificationKey: VerificationKey) {\n this.wasmBuffer = wasm;\n this.zkeyBuffer = zkey;\n this.verificationKey = verificationKey;\n }\n\n static async compile(): Promise<ZkCompiled> {\n if (!this.verificationKey) {\n throw new Error('Circuit not initialized. Call setCircuitBuffers() first.');\n }\n return { verificationKey: this.verificationKey };\n }\n\n static async prove(secret: Field): Promise<{ proof: SnarkProof; publicSignals: string[] }> {\n if (!this.wasmBuffer || !this.zkeyBuffer) {\n throw new Error('Circuit not initialized. Call setCircuitBuffers() first.');\n }\n\n // Calculate the hash (this should match what the circuit computes)\n await Poseidon.hash([secret]);\n\n // Create input for the circuit\n const input = {\n secret: secret.toString()\n };\n\n // Generate the proof using @zk-kit/groth16\n const { proof, publicSignals } = await groth16Prove(\n input,\n this.wasmBuffer,\n this.zkeyBuffer\n );\n\n return { proof, publicSignals: publicSignals as string[] };\n }\n\n static async verify(proof: SnarkProof, publicSignals?: string[]): Promise<boolean> {\n if (!this.verificationKey) {\n throw new Error('Circuit not initialized. Call setCircuitBuffers() first.');\n }\n\n try {\n // Cast to satisfy @zk-kit/groth16's stricter Groth16Proof type\n // (protocol/curve required there, optional in our shared type).\n const result = await groth16Verify(\n this.verificationKey,\n { proof: proof as unknown as Parameters<typeof groth16Verify>[1][\"proof\"], publicSignals: (publicSignals || []) as Groth16PublicSignals }\n );\n return result;\n } catch (error) {\n console.error('Verification error:', error);\n return false;\n }\n }\n}\n\n// Circuit wrapper for PreimagePoK (Proof of Knowledge)\nexport class PreimagePoK {\n private static wasmBuffer?: Uint8Array;\n private static zkeyBuffer?: Uint8Array;\n private static verificationKey?: VerificationKey;\n\n static setCircuitBuffers(wasm: Uint8Array, zkey: Uint8Array, verificationKey: VerificationKey) {\n this.wasmBuffer = wasm;\n this.zkeyBuffer = zkey;\n this.verificationKey = verificationKey;\n }\n\n static async compile(): Promise<ZkCompiled> {\n if (!this.verificationKey) {\n throw new Error('Circuit not initialized. Call setCircuitBuffers() first.');\n }\n return { verificationKey: this.verificationKey };\n }\n\n static async prove(\n publicInput: AuthPublicInput,\n secret: Field,\n salt: Field,\n ecdsaPub: Field\n ): Promise<{ proof: SnarkProof; publicSignals: string[] }> {\n if (!this.wasmBuffer || !this.zkeyBuffer) {\n throw new Error('Circuit not initialized. Call setCircuitBuffers() first.');\n }\n\n // Create input for the circuit\n const input = {\n // Public inputs\n commitment: publicInput.commitment,\n nonce: publicInput.nonce,\n ecdsaPubHash: publicInput.ecdsaPubHash,\n // Private inputs\n secret: secret.toString(),\n salt: salt.toString(),\n ecdsaPub: ecdsaPub.toString()\n };\n\n // Generate the proof using @zk-kit/groth16\n const { proof, publicSignals } = await groth16Prove(\n input,\n this.wasmBuffer,\n this.zkeyBuffer\n );\n\n return { proof, publicSignals: publicSignals as string[] };\n }\n\n static async verify(proof: SnarkProof, publicSignals?: string[]): Promise<boolean> {\n if (!this.verificationKey) {\n throw new Error('Circuit not initialized. Call setCircuitBuffers() first.');\n }\n\n try {\n // Cast to satisfy @zk-kit/groth16's stricter Groth16Proof type\n // (protocol/curve required there, optional in our shared type).\n const result = await groth16Verify(\n this.verificationKey,\n { proof: proof as unknown as Parameters<typeof groth16Verify>[1][\"proof\"], publicSignals: (publicSignals || []) as Groth16PublicSignals }\n );\n return result;\n } catch (error) {\n console.error('Verification error:', error);\n return false;\n }\n }\n}\n\n// Verify function for HashKnowledge proof\nexport async function verifyHashKnowledge(\n proof: SnarkProof,\n expectedOutput?: Field,\n publicSignals?: string[]\n): Promise<boolean> {\n try {\n const result = await HashKnowledge.verify(proof, publicSignals);\n\n if (!result) {\n console.error('Hash knowledge proof verification failed');\n return false;\n }\n\n // Optionally verify the public output matches expected value\n if (expectedOutput && publicSignals && publicSignals.length > 0) {\n const outputField = new Field(publicSignals[0]);\n if (!outputField.equals(expectedOutput)) {\n console.error('Public output mismatch in hash knowledge proof');\n return false;\n }\n }\n\n return true;\n } catch (error) {\n console.error('Error verifying hash knowledge proof:', error);\n return false;\n }\n}\n\n// Verify function for PreimagePoK proof\nexport async function verifyPreimagePoK(\n proof: SnarkProof,\n publicSignals?: string[]\n): Promise<boolean> {\n try {\n const result = await PreimagePoK.verify(proof, publicSignals);\n\n if (!result) {\n console.error('Preimage proof verification failed');\n return false;\n }\n\n console.log('Preimage proof verified successfully');\n return true;\n } catch (error) {\n console.error('Error verifying preimage proof:', error);\n return false;\n }\n}\n\n// Generic verify function that determines which program to use\nexport async function verify(\n programType: 'HashKnowledge' | 'PreimagePoK',\n proof: SnarkProof,\n options?: {\n expectedOutput?: Field,\n publicSignals?: string[]\n }\n): Promise<boolean> {\n if (programType === 'HashKnowledge') {\n return verifyHashKnowledge(proof, options?.expectedOutput, options?.publicSignals);\n } else if (programType === 'PreimagePoK') {\n return verifyPreimagePoK(proof, options?.publicSignals);\n } else {\n throw new Error(`Unknown program type: ${programType}`);\n }\n}\n\n// Helper function to verify proof directly\nexport async function quickVerify(\n program: typeof HashKnowledge | typeof PreimagePoK,\n proof: SnarkProof,\n publicSignals?: string[]\n): Promise<boolean> {\n try {\n return await program.verify(proof, publicSignals);\n } catch (error) {\n console.error('Quick verify failed:', error);\n return false;\n }\n}\n\n// Function to initialize circuits with buffers\nexport function initializeCircuits(config: {\n hashKnowledge?: CircuitBufferConfig;\n preimagePoK?: CircuitBufferConfig;\n}) {\n if (config.hashKnowledge) {\n HashKnowledge.setCircuitBuffers(\n config.hashKnowledge.wasm,\n config.hashKnowledge.zkey,\n config.hashKnowledge.verificationKey\n );\n }\n if (config.preimagePoK) {\n PreimagePoK.setCircuitBuffers(\n config.preimagePoK.wasm,\n config.preimagePoK.zkey,\n config.preimagePoK.verificationKey\n );\n }\n}\n\n// Function to compile and cache verification keys\nexport async function compilePrograms(): Promise<{\n hashKnowledge: ZkCompiled,\n preimagePoK: ZkCompiled\n}> {\n console.log('Compiling ZK circuits...');\n\n const [hashKnowledgeCompiled, preimagePoKCompiled] = await Promise.all([\n HashKnowledge.compile(),\n PreimagePoK.compile()\n ]);\n\n console.log('ZK circuits compiled successfully');\n\n return {\n hashKnowledge: hashKnowledgeCompiled,\n preimagePoK: preimagePoKCompiled\n };\n}\n\nexport { Field as FieldElement }; // Export with alias to avoid confusion with Field type\n","import { PreimagePoK, AuthPublicInput, Field, Poseidon, verify, VerificationKey } from './ZeroKnowledge';\nimport { toHex, fromHex, fromBase64Url } from '../utilities';\n\ninterface AuthToken {\n peerId: string;\n timestamp: number;\n signature: string;\n}\n\nclass Authenticator {\n private trustedKeys: Map<string, CryptoKey> = new Map();\n private zkVerificationKey: VerificationKey | null = null;\n\n public async initializeZK(): Promise<void> {\n if (!this.zkVerificationKey) {\n appLogger.debug('Compiling PreimagePoK for verification...');\n const compiled = await PreimagePoK.compile();\n this.zkVerificationKey = compiled.verificationKey;\n }\n }\n\n public getZKVerificationKey(): VerificationKey | null {\n return this.zkVerificationKey;\n }\n\n public addTrustedServer(serverId: string, publicKey: CryptoKey): void {\n this.trustedKeys.set(serverId, publicKey);\n }\n\n public async generateAuthToken(peerId: string, privateKey: CryptoKey): Promise<AuthToken> {\n if (!privateKey) {\n throw new Error(`No private key for ${peerId}`);\n }\n const timestamp = Date.now();\n const data = new TextEncoder().encode(`${peerId}:${timestamp}`);\n const signature = await crypto.subtle.sign(\n { name: 'ECDSA', hash: 'SHA-256' },\n privateKey,\n data\n );\n return { peerId, timestamp, signature: toHex(new Uint8Array(signature)) };\n }\n\n public async verifyAuthToken(token: AuthToken, clientPublicKey: CryptoKey): Promise<boolean> {\n const maxAge = 5 * 60 * 1000;\n if (Math.abs(Date.now() - token.timestamp) > maxAge) {\n appLogger.debug('Auth token expired');\n return false;\n }\n return await crypto.subtle.verify(\n { name: 'ECDSA', hash: 'SHA-256' },\n clientPublicKey,\n fromHex(token.signature),\n new TextEncoder().encode(`${token.peerId}:${token.timestamp}`)\n );\n }\n\n public async verifyZKProof(\n proof: any,\n publicInput: AuthPublicInput,\n storedCommitment: Field,\n ecdsaPub: CryptoKey\n ): Promise<boolean> {\n if (!this.zkVerificationKey) {\n throw new Error('ZK verification key not initialized');\n }\n\n // Convert publicInput to signals array for snarkjs\n const publicSignals = publicInput.toPublicSignals();\n\n // Verify the proof using snarkjs\n const isValid = await verify('PreimagePoK', proof, { publicSignals });\n if (!isValid) {\n appLogger.debug('ZK proof verification failed');\n return false;\n }\n\n // Verify the commitment matches stored value\n const proofCommitment = new Field(publicSignals[0]);\n const matchesCommitment = proofCommitment.equals(storedCommitment);\n\n // Verify nonce matches\n const proofNonce = new Field(publicSignals[1]);\n const expectedNonce = new Field(publicInput.nonce);\n const matchesNonce = proofNonce.equals(expectedNonce);\n\n // Verify ECDSA public key hash\n const ecdsaJwk = await crypto.subtle.exportKey('jwk', ecdsaPub);\n const ecdsaHex = toHex(fromBase64Url(ecdsaJwk.x!)).slice(0, 64);\n const ecdsaPubField = new Field(BigInt('0x' + ecdsaHex));\n const expectedEcdsaPubHash = await Poseidon.hash([ecdsaPubField]);\n const proofEcdsaPubHash = new Field(publicSignals[2]);\n const matchesEcdsaPub = proofEcdsaPubHash.equals(expectedEcdsaPubHash);\n\n appLogger.debug('ZK proof valid:', isValid, 'Commitment:', matchesCommitment, 'Nonce:', matchesNonce, 'ECDSA:', matchesEcdsaPub);\n return isValid && matchesCommitment && matchesNonce && matchesEcdsaPub;\n }\n}\n\nexport { Authenticator, AuthToken };","import { AuthPublicInput, Field, Poseidon } from './ZeroKnowledge';\nimport { Authenticator, AuthToken } from './Authenticator';\nimport { DoubleRatchet } from './DoubleRatchet';\nimport { KeyStore } from './KeyStore';\nimport { CipherMessage, RatchetState } from './types.d';\nimport { toHex, fromBase64Url } from '../utilities';\n\n\nclass DoubleRatchetManager {\n private sessions: Map<string, DoubleRatchet> = new Map();\n private sessionStates: Map<string, RatchetState> = new Map(); // In-memory storage for session states\n private keyStore: KeyStore;\n private _authenticator: Authenticator;\n private registeredUsers: Map<string, { commitment: Field; salt: Field }> = new Map();\n private id: string; // Unique ID for this manager (e.g., client1, server1)\n\n constructor(id: string) {\n this.id = id;\n this.keyStore = KeyStore.getInstance();\n this._authenticator = new Authenticator();\n }\n\n get authenticator(): Authenticator {\n return this._authenticator;\n }\n\n public async addTrustedServer(serverId: string, publicKey: CryptoKey): Promise<void> {\n this._authenticator.addTrustedServer(serverId, publicKey);\n }\n\n public async registerZK(\n clientId: string,\n secret: Field,\n salt: Field,\n ecdsaPub: CryptoKey,\n ): Promise<void> {\n await this._authenticator.initializeZK();\n console.log(`Registering ZK for ${clientId}...`);\n console.log('ECDSA Public Key:', ecdsaPub);\n const ecdsaJwk = await crypto.subtle.exportKey('jwk', ecdsaPub);\n const ecdsaHex = toHex(fromBase64Url(ecdsaJwk.x!)).slice(0, 64);\n const ecdsaPubField = new Field(BigInt('0x' + ecdsaHex));\n const ecdsaPubHash = await Poseidon.hash([ecdsaPubField]);\n const commitment = await Poseidon.hash([secret, salt, ecdsaPubHash]);\n console.log(`Commitment for ${clientId}:`, { commitment, salt });\n this.registeredUsers.set(clientId, { commitment, salt });\n appLogger.debug(`Registered ${clientId}: commitment=${commitment.toString()}, salt=${salt.toString()}`);\n\n }\n\n public async performHandshake(\n senderId: string,\n recipientId: string,\n zkProof: any,\n publicInput: AuthPublicInput,\n clientPublicKey: CryptoKey, // ECDH pub for session\n clientAuthPublicKey: CryptoKey, // ECDSA pub for auth\n authToken: AuthToken // Client-generated token\n ): Promise<void> {\n await this._authenticator.initializeZK();\n\n const userData = this.registeredUsers.get(senderId);\n if (!userData) {\n throw new Error(`No registered commitment for ${senderId}`);\n }\n\n const isZKValid = await this._authenticator.verifyZKProof(\n zkProof,\n publicInput,\n userData.commitment,\n clientAuthPublicKey\n );\n if (!isZKValid) {\n throw new Error(`ZK handshake failed for ${senderId}`);\n }\n\n // Verify client-provided auth token\n if (!await this._authenticator.verifyAuthToken(authToken, clientAuthPublicKey)) {\n throw new Error(`Token verification failed for ${senderId}`);\n }\n\n // Store only public keys\n await this.keyStore.storeRemotePublicKeys(senderId, clientPublicKey, clientAuthPublicKey);\n const serverKeyPair = this.keyStore.getKeyPair(recipientId)!;\n const serverAuth = this.keyStore.getAuthKeyPair(recipientId)!;\n await this.keyStore.storeRemotePublicKeys(recipientId, serverKeyPair.publicKey, serverAuth.publicKey);\n appLogger.debug(`Handshake completed for ${senderId} -> ${recipientId}`);\n }\n\n public async initializeSession(\n senderId: string,\n recipientId: string,\n isClient: boolean = true,\n sessionType: 'global' | 'specific' = 'specific',\n sessionId?: string,\n zkProof?: any,\n publicInput?: AuthPublicInput,\n clientPublicKey?: CryptoKey,\n clientAuthPublicKey?: CryptoKey,\n clientEcdhPrivateKey?: CryptoKey,\n clientAuthPrivateKey?: CryptoKey\n ): Promise<string> {\n const keyStore = KeyStore.getInstance();\n const recipientKeyPair = keyStore.getKeyPair(recipientId);\n if (!recipientKeyPair?.publicKey && sessionType === 'specific' && isClient) {\n // Generate auth token from client auth private key if provided\n const authToken = clientAuthPrivateKey ?\n await this._authenticator.generateAuthToken(senderId, clientAuthPrivateKey) :\n await this._authenticator.generateAuthToken(senderId, this.keyStore.getAuthKeyPair(senderId)!.privateKey!);\n\n await this.performHandshake(\n senderId,\n recipientId,\n zkProof!,\n publicInput!,\n clientPublicKey!,\n clientAuthPublicKey!,\n authToken\n );\n } else if (!recipientKeyPair?.publicKey) {\n throw new Error(`Missing public key for ${recipientId}. Perform handshake or register first.`);\n }\n\n const finalSessionId = sessionId || (sessionType === 'specific'\n ? [senderId, recipientId].sort().join(':') + `:${Date.now()}`\n : `${senderId}:${recipientId}:${Date.now()}`);\n\n const ratchet = new DoubleRatchet(senderId, recipientId, sessionType, isClient);\n await ratchet.initializeSession(isClient);\n this.sessions.set(finalSessionId, ratchet);\n await this.saveState(finalSessionId, ratchet.getState());\n appLogger.debug(`Session initialized: ${finalSessionId}, type=${sessionType}`);\n return finalSessionId;\n }\n\n public async encrypt(\n senderId: string,\n recipientId: string,\n sessionId: string,\n plaintext: string,\n newDhKey: boolean = false,\n sessionType: 'global' | 'specific' = 'specific'\n ): Promise<CipherMessage> {\n let ratchet = this.sessions.get(sessionId);\n if (!ratchet) {\n const state = await this.loadState(sessionId);\n if (!state) throw new Error(`Session not found: ${sessionId}`);\n ratchet = new DoubleRatchet(senderId, recipientId, sessionType, false);\n ratchet.setState(state);\n this.sessions.set(sessionId, ratchet);\n }\n\n const message = await ratchet.encrypt(plaintext, newDhKey, senderId, recipientId, sessionId, sessionType);\n await this.saveState(sessionId, ratchet.getState());\n appLogger.debug('KeyStore after encrypt:', Array.from(this.keyStore.keys.entries()).map(([id]) => `${id}: publicKey`));\n return message;\n }\n\n public async decrypt(message: CipherMessage, isClient: boolean = true): Promise<string> {\n // const { sessionId, sessionType, senderId, recipientId } = message.header;\n const header = message.header;\n let ratchet = this.sessions.get(header.sessionId);\n if (!ratchet) {\n const state = await this.loadState(header.sessionId);\n if (!state) throw new Error(`Session not found: ${header.sessionId}`);\n ratchet = new DoubleRatchet(header.senderId, header.recipientId, header.sessionType, isClient);\n ratchet.setState(state);\n this.sessions.set(header.sessionId, ratchet);\n }\n\n const plaintext = await ratchet.decrypt(message, isClient);\n await this.saveState(header.sessionId, ratchet.getState());\n return plaintext;\n }\n\n public async getSessionSharedSecret(sessionId: string): Promise<Uint8Array | null> {\n let ratchet = this.sessions.get(sessionId);\n if (!ratchet) {\n const state = await this.loadState(sessionId);\n if (!state || !state.rootKey) {\n appLogger.debug(`No shared secret found for session: ${sessionId}`);\n return null;\n }\n return state.rootKey;\n }\n\n const state = ratchet.getState();\n if (!state.rootKey) {\n appLogger.debug(`Session ${sessionId} not initialized yet`);\n return null;\n }\n\n return state.rootKey;\n }\n\n private async saveState(sessionId: string, state: RatchetState): Promise<void> {\n appLogger.debug(`Saving state in memory: sessionId=${sessionId}`);\n // Store the state directly in memory\n // No need to serialize/deserialize as we're keeping it in memory\n this.sessionStates.set(`${this.id}-${sessionId}`, state);\n }\n\n private async loadState(sessionId: string): Promise<RatchetState | null> {\n appLogger.debug(`Loading state from memory: sessionId=${sessionId}`);\n // Retrieve the state directly from memory\n const state = this.sessionStates.get(`${this.id}-${sessionId}`);\n return state || null;\n }\n}\n\nexport { DoubleRatchetManager, RatchetState, CipherMessage, AuthPublicInput };","/**\n * Per-chunk AES-256-GCM encryption with random keys and IVs.\n *\n * Each chunk of a stored file gets its own freshly generated 256-bit AES key\n * and 96-bit IV. The (key, IV) pair lives in the file manifest, which the\n * application is responsible for storing under whatever access-control regime\n * it uses (in this codebase: the `SharedSpaceClient` writes manifests into\n * ZK-gated multi-user spaces; the shard store itself is open).\n *\n * Per-chunk keys (rather than a per-file DEK) lets future versions revoke or\n * re-share individual chunks without re-encrypting the whole file. The\n * additional manifest size is dominated by the shard hash list anyway.\n *\n * The cipher itself delegates to the canonical `encryptAesGcm` / `decryptAesGcm`\n * primitives — this class only wraps them with key-material generation and\n * the JSON-friendly base64 serialization the manifest needs.\n */\n\nimport { fromBase64, toBase64 } from \"../utilities/bytes\";\nimport {\n encryptAesGcm,\n decryptAesGcm,\n randomBytes,\n AES_GCM_KEY_BYTES,\n AES_GCM_IV_BYTES,\n} from \"./primitives\";\n\n/**\n * Per-chunk key material, base64-encoded for JSON-friendly storage in the\n * manifest. The IV is unique per chunk; the key is unique per chunk too in\n * this codebase, though that's a stricter property than AES-GCM strictly\n * requires (which is \"unique IV per key\").\n */\nexport interface ChunkKeyMaterial {\n /** Base64-encoded 32-byte AES-256 key. */\n key: string;\n /** Base64-encoded 12-byte AES-GCM IV. */\n iv: string;\n}\n\nexport class ChunkCipher {\n /**\n * Generate a fresh random (key, iv) pair encoded for the manifest.\n * Callers should generate one of these per chunk before calling\n * {@link encryptChunk}.\n */\n generateKeyMaterial(): ChunkKeyMaterial {\n return {\n key: toBase64(randomBytes(AES_GCM_KEY_BYTES)),\n iv: toBase64(randomBytes(AES_GCM_IV_BYTES)),\n };\n }\n\n /**\n * Encrypt `plaintext` under the supplied key + IV. Returns the AES-GCM\n * ciphertext with the 16-byte auth tag appended (WebCrypto's default\n * GCM behavior).\n */\n async encryptChunk(plaintext: Uint8Array, material: ChunkKeyMaterial): Promise<Uint8Array> {\n return encryptAesGcm(fromBase64(material.key), fromBase64(material.iv), plaintext);\n }\n\n /**\n * Inverse of {@link encryptChunk}. Throws if the auth tag fails — that\n * means the ciphertext was tampered with, the key/iv was wrong, or the\n * shards were reassembled incorrectly.\n */\n async decryptChunk(ciphertext: Uint8Array, material: ChunkKeyMaterial): Promise<Uint8Array> {\n try {\n return await decryptAesGcm(\n fromBase64(material.key),\n fromBase64(material.iv),\n ciphertext,\n );\n } catch {\n // WebCrypto throws a vague OperationError on GCM tag mismatch.\n // Surface a stable, readable message so callers can react to it.\n throw new Error(\n \"ChunkCipher.decryptChunk: decryption failed (key/iv mismatch, corrupted ciphertext, or reassembly error)\",\n );\n }\n }\n}\n\nexport default ChunkCipher;\n","/**\n * Passphrase-based wrap / unwrap helpers using WebCrypto.\n *\n * Encrypt a payload with a user-supplied passphrase before persisting it\n * somewhere the server can see (e.g. the manifest blob in a ZK-gated\n * SharedSpace, or chat-key material in a PersonalSpace). The server never\n * sees the passphrase or the plaintext — both wrap and unwrap run entirely\n * client-side.\n *\n * Algorithm (the only one this codebase has ever shipped):\n * - PBKDF2-SHA256 with 200_000 iterations derives a 256-bit AES key from\n * `passphrase || salt`.\n * - AES-256-GCM encrypts the plaintext with a fresh random 12-byte IV.\n * - The auth tag is appended to the ciphertext by WebCrypto's default\n * GCM behaviour, so {@link WrappedPayload.ciphertext} carries it implicitly.\n *\n * The returned {@link WrappedPayload} is JSON-friendly (all base64 fields), so\n * it can be `JSON.stringify`-ed straight into a KV layer.\n */\n\nimport {\n encryptAesGcm,\n decryptAesGcm,\n deriveAesKeyFromPassphrase,\n randomBytes,\n PBKDF2_DEFAULT_ITERATIONS,\n AES_GCM_IV_BYTES,\n} from \"./primitives\";\n\n/**\n * The persisted, JSON-friendly representation of a passphrase-wrapped blob.\n *\n * The `alg` field is a self-describing marker — if we ever rotate KDF/cipher,\n * unwrap can switch on this value to keep older payloads readable.\n */\nexport interface WrappedPayload {\n /** Random per-wrap salt for PBKDF2, base64. */\n salt: string;\n /** AES-GCM IV, base64. */\n iv: string;\n /** AES-GCM ciphertext (includes 16-byte GCM auth tag), base64. */\n ciphertext: string;\n /** Algorithm marker so future readers know what they're looking at. */\n alg: \"PBKDF2-SHA256/AES-256-GCM\";\n /** PBKDF2 iteration count used. */\n iter: number;\n}\n\n/** Length of the PBKDF2 salt, in bytes. */\nconst SALT_BYTES = 16;\n\n/** Encode a `Uint8Array` to standard base64 (with padding). */\nfunction bytesToBase64(bytes: Uint8Array): string {\n // Build chunk-wise to avoid blowing the call stack on large payloads.\n let binary = \"\";\n const CHUNK = 0x8000;\n for (let i = 0; i < bytes.length; i += CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));\n }\n if (typeof btoa === \"function\") return btoa(binary);\n return Buffer.from(bytes).toString(\"base64\");\n}\n\n/** Decode a base64 string back into a `Uint8Array`. */\nfunction base64ToBytes(b64: string): Uint8Array {\n if (typeof atob === \"function\") {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n }\n return new Uint8Array(Buffer.from(b64, \"base64\"));\n}\n\n/**\n * Encrypt `plaintext` under a key derived from `passphrase`. The returned\n * payload bundles the salt, IV, and ciphertext so unwrap only needs the\n * passphrase to reverse the operation.\n */\nexport async function wrapWithPassphrase(\n passphrase: string,\n plaintext: Uint8Array,\n): Promise<WrappedPayload> {\n if (typeof passphrase !== \"string\" || passphrase.length === 0) {\n throw new Error(\"wrapWithPassphrase: passphrase must be a non-empty string\");\n }\n const salt = randomBytes(SALT_BYTES);\n const iv = randomBytes(AES_GCM_IV_BYTES);\n const key = await deriveAesKeyFromPassphrase(passphrase, salt, PBKDF2_DEFAULT_ITERATIONS);\n const ciphertext = await encryptAesGcm(key, iv, plaintext);\n return {\n salt: bytesToBase64(salt),\n iv: bytesToBase64(iv),\n ciphertext: bytesToBase64(ciphertext),\n alg: \"PBKDF2-SHA256/AES-256-GCM\",\n iter: PBKDF2_DEFAULT_ITERATIONS,\n };\n}\n\n/**\n * Decrypt a {@link WrappedPayload} produced by {@link wrapWithPassphrase}.\n * Throws if the passphrase is wrong, the payload is tampered with, or the\n * algorithm marker is unrecognised.\n */\nexport async function unwrapWithPassphrase(\n passphrase: string,\n wrapped: WrappedPayload,\n): Promise<Uint8Array> {\n if (typeof passphrase !== \"string\" || passphrase.length === 0) {\n throw new Error(\"unwrapWithPassphrase: passphrase must be a non-empty string\");\n }\n if (wrapped.alg !== \"PBKDF2-SHA256/AES-256-GCM\") {\n throw new Error(`unwrapWithPassphrase: unsupported alg \"${wrapped.alg}\"`);\n }\n const salt = base64ToBytes(wrapped.salt);\n const iv = base64ToBytes(wrapped.iv);\n const ciphertext = base64ToBytes(wrapped.ciphertext);\n const key = await deriveAesKeyFromPassphrase(\n passphrase,\n salt,\n wrapped.iter ?? PBKDF2_DEFAULT_ITERATIONS,\n );\n try {\n return await decryptAesGcm(key, iv, ciphertext);\n } catch {\n // WebCrypto throws a vague OperationError on GCM tag mismatch; turn it\n // into a stable, readable message so callers can react to it.\n throw new Error(\n \"unwrapWithPassphrase: decryption failed (wrong passphrase or tampered payload)\",\n );\n }\n}\n","/**\n * Shared zero-knowledge types and circuit constants.\n *\n * Used by both the browser/server builds (where snarkjs handles proof generation\n * and verification) and the workers build (where verification runs through\n * `bn128.wasm` via `src/workers/groth16-verifier.ts`). Keeping these here ensures\n * proof shapes and verification keys stay identical across runtimes.\n */\n\n/**\n * Groth16 proof structure (BN128).\n *\n * - `pi_a`: G1 point as `[x, y]` or projective `[x, y, z]`.\n * - `pi_b`: G2 point as `[[x0, x1], [y0, y1]]` or projective `[..., [z0, z1]]`.\n * - `pi_c`: G1 point as `[x, y]` or projective `[x, y, z]`.\n *\n * Field elements are decimal-string-encoded BigInts (snarkjs convention).\n */\nexport interface Groth16Proof {\n pi_a: string[];\n pi_b: string[][];\n pi_c: string[];\n protocol?: string;\n curve?: string;\n}\n\n/**\n * Groth16 verification key (BN128).\n *\n * Field elements are decimal-string-encoded BigInts (snarkjs convention).\n */\nexport interface VerificationKey {\n protocol: string;\n curve: string;\n nPublic: number;\n vk_alpha_1: string[];\n vk_beta_2: string[][];\n vk_gamma_2: string[][];\n vk_delta_2: string[][];\n vk_alphabeta_12: string[][][];\n IC: string[][];\n}\n\n/**\n * Verification key for the `preimagePoK` circuit (Poseidon-commitment\n * proof-of-knowledge with three public signals: commitment, nonce, ecdsaPubHash).\n *\n * Pinned here so worker-side and SDK-side verification agree on the key being\n * checked. If the circuit is recompiled, regenerate this constant and\n * `public/circuits/build/preimagePoK_verification_key.json` together.\n */\nexport const PREIMAGE_POK_VERIFICATION_KEY: VerificationKey = {\n protocol: \"groth16\",\n curve: \"bn128\",\n nPublic: 3,\n vk_alpha_1: [\n \"20491192805390485299153009773594534940189261866228447918068658471970481763042\",\n \"9383485363053290200918347156157836566562967994039712273449902621266178545958\",\n \"1\"\n ],\n vk_beta_2: [\n [\n \"6375614351688725206403948262868962793625744043794305715222011528459656738731\",\n \"4252822878758300859123897981450591353533073413197771768651442665752259397132\"\n ],\n [\n \"10505242626370262277552901082094356697409835680220590971873171140371331206856\",\n \"21847035105528745403288232691147584728191162732299865338377159692350059136679\"\n ],\n [\n \"1\",\n \"0\"\n ]\n ],\n vk_gamma_2: [\n [\n \"10857046999023057135944570762232829481370756359578518086990519993285655852781\",\n \"11559732032986387107991004021392285783925812861821192530917403151452391805634\"\n ],\n [\n \"8495653923123431417604973247489272438418190587263600148770280649306958101930\",\n \"4082367875863433681332203403145435568316851327593401208105741076214120093531\"\n ],\n [\n \"1\",\n \"0\"\n ]\n ],\n vk_delta_2: [\n [\n \"16843627858994773805056502117979518680360297888097507527057721641174626133429\",\n \"2669618170444825402403730985182974839894668798317345855172970345856260721653\"\n ],\n [\n \"20564952487570762020467138133408075499830271526522626813107251678961587215295\",\n \"9630342855454833575580303045534431010412631371159617591163132980579520487965\"\n ],\n [\n \"1\",\n \"0\"\n ]\n ],\n vk_alphabeta_12: [\n [\n [\n \"2029413683389138792403550203267699914886160938906632433982220835551125967885\",\n \"21072700047562757817161031222997517981543347628379360635925549008442030252106\"\n ],\n [\n \"5940354580057074848093997050200682056184807770593307860589430076672439820312\",\n \"12156638873931618554171829126792193045421052652279363021382169897324752428276\"\n ],\n [\n \"7898200236362823042373859371574133993780991612861777490112507062703164551277\",\n \"7074218545237549455313236346927434013100842096812539264420499035217050630853\"\n ]\n ],\n [\n [\n \"7077479683546002997211712695946002074877511277312570035766170199895071832130\",\n \"10093483419865920389913245021038182291233451549023025229112148274109565435465\"\n ],\n [\n \"4595479056700221319381530156280926371456704509942304414423590385166031118820\",\n \"19831328484489333784475432780421641293929726139240675179672856274388269393268\"\n ],\n [\n \"11934129596455521040620786944827826205713621633706285934057045369193958244500\",\n \"8037395052364110730298837004334506829870972346962140206007064471173334027475\"\n ]\n ]\n ],\n IC: [\n [\n \"6593633352362890744195366164011945207337919238085164401989523182031213441232\",\n \"21183283244721822514187218730411278389501771108619619957207607994811554523781\",\n \"1\"\n ],\n [\n \"19317830753800014286972931403860527733342849870141075528271937285218206220756\",\n \"14626265811834596630857393417326981325583938311796888424299048456918853093257\",\n \"1\"\n ],\n [\n \"7942727853353225551121019923926808347232536417992238353855978019969636961405\",\n \"8824649763391398686420260814761862276544573369118345976741973565095405175062\",\n \"1\"\n ],\n [\n \"8369441262422248167284752361555580367206817200973928868895308479466335503315\",\n \"7836653245051994305208746627300011506099851195782496031197976259815728652585\",\n \"1\"\n ]\n ]\n};\n","export enum EventCoreEvents {\n CONNECTED = \"connected\",\n DISCONNECTED = \"disconnected\",\n RECONNECTING = \"reconnecting\",\n ERROR = \"error\",\n DATA_RECEIVED = \"data_received\",\n DATA_SENT = \"data_sent\",\n MESSAGE = \"message\",\n GET_HISTORY = \"get_history\",\n RECEIVED_HISTORY = \"received_history\",\n}\n\n\n/**\n * @public\n * EventCore is a static event emitter with singleton functionality for global event handling.\n */\nexport class EventCore {\n private static eventTarget: EventTarget = new EventTarget();\n private static events = new Map<string, EventListener | CallableFunction>();\n\n /**\n * @remarks Listen to an event.\n * @example EventCore.on('event', (e) =\\> appLogger.debug(e));\n */\n static on(event: EventCoreEvents, handler: EventListener | CallableFunction) {\n if (!EventCore.events.has(event)) {\n EventCore.events.set(event, handler);\n }\n EventCore.eventTarget.addEventListener(event, handler as EventListener);\n }\n\n /**\n * @remarks Stop listening to an event.\n * @example EventCore.off('event', handler);\n */\n static off(event: EventCoreEvents, handler: EventListener | CallableFunction) {\n if (EventCore.events.has(event)) {\n EventCore.events.delete(event);\n }\n EventCore.eventTarget.removeEventListener(event, handler as EventListener);\n }\n\n /**\n * @remarks Emit an event.\n * @example EventCore.emit('event', data);\n */\n static emit(event: EventCoreEvents, data: any) {\n if (!EventCore.events.has(event)) {\n appLogger.debug(`Warning: No listeners for event: ${event}`);\n // appLogger.verbose(`Event data:`, data);\n }\n EventCore.eventTarget.dispatchEvent(new CustomEvent(event, { detail: data }));\n }\n}\n\nexport default EventCore;","import { _messageId, generateChecksum, verifyChecksum, serialize, deserialize, _formatBytes, log } from '../utilities';\n\n/**\n * @public\n * @remarks\n * The body type is a generic type that can be any value. Internally we handle the serialization and deserialization of the body.\n */\nexport type MessageBody = any;\n\n/**\n * @public\n * @remarks\n * The message headers type is a simple record object that contains key value pairs. Think of these as metadata for the message, similar to HTTP headers.\n */\nexport type MessageHeaders = Map<string, string>;\n\n/**\n * @public\n * @remarks\n * The message options type is a record object that contains the options for the message.\n */\nexport interface MessageOptions {\n id?: string;\n body: MessageBody;\n status?: \"pending\" | \"processed\" | \"failed\" | \"delivered\";\n checksum?: string;\n}\n\n\n/**\n * @public\n * @remarks\n * The message class is a simple class that represents a message object.\n * @sealed\n */\nexport class Message {\n id: string = _messageId();\n timestamp: number = Date.now();\n status?: \"pending\" | \"processed\" | \"failed\" | \"delivered\" = \"pending\";\n checksum?: string;\n private _body: MessageBody;\n\n constructor(msg: MessageBody)\n constructor(msg: MessageOptions)\n constructor(msg: MessageOptions | MessageBody) {\n\n if (typeof msg === 'object' && msg.hasOwnProperty('body')) {\n this.id = msg.id || this.id;\n this.timestamp = msg.timestamp || this.timestamp;\n this.status = msg.status || this.status;\n this.checksum = msg.checksum || this.checksum;\n this.body = msg.body;\n } else {\n this.body = msg;\n }\n this.validatebodySize();\n }\n\n get body(): MessageBody {\n return deserialize(this._body);\n }\n\n set body(value: MessageBody) {\n this._body = serialize(value);\n if (!this.checksum) {\n this.checksum = generateChecksum(this._body);\n }\n }\n\n verifyChecksum = () => {\n if (!this.checksum) throw new Error(\"No message checksum\");\n const isValid = verifyChecksum(this._body, this.checksum);\n if (!isValid) throw new Error(\"Invalid message checksum\");\n }\n\n private validatebodySize(maxSize: number = 1024 * 1024 * 3) {\n const sizeInBytes = new TextEncoder().encode(this._body).length;\n if (sizeInBytes > maxSize) {\n throw new Error(`body size exceeds the limit of ${_formatBytes(maxSize)}.`);\n }\n }\n\n\n serialize = (): string => {\n return JSON.stringify({\n id: this.id,\n timestamp: this.timestamp,\n body: this.body,\n status: this.status,\n checksum: this.checksum,\n });\n }\n\n static deserialize = (data: string): Message => {\n if (typeof data !== 'string') {\n log.warn('Message.deserialize: data is not a string', data);\n }\n const msg = JSON.parse(data);\n return new Message(msg);\n }\n}\n\nexport default Message;","import { Message } from \"./Message\";\nimport { _packetId } from \"../utilities\";\n\ntype Address = string; // Represents a unique peer or node ID in the network\n\nexport interface PacketOptions {\n id?: string;\n subject: string;\n source: Address;\n target: Address;\n headers?: {\n [key: string]: string | number | boolean | undefined; // Optional: Additional headers for the packet\n };\n message?: Message;\n ttl?: number;\n timestamp?: number;\n signature?: string;\n}\n\n/**\n * @public\n * @remarks\n * This class represents a message object that can be sent over the network\n * @sealed\n */\nexport class Packet {\n id: string;\n subject: string;\n source: Address;\n target: Address;\n headers?: PacketOptions['headers']; // Optional: Additional headers for the packet\n message?: Message; // By making the message optional, we can send packets without messages. Essentially performing a GET request or other bodyless requests\n timestamp: number;\n ttl?: number; // Optional: Time-to-live in milliseconds\n signature?: string; // Optional: Cryptographic signature for verification\n\n constructor({\n id,\n subject,\n source,\n target,\n headers,\n message,\n ttl,\n signature,\n timestamp\n }: PacketOptions) {\n this.id = id || _packetId(); // Ensure the packet has a unique ID\n this.subject = subject;\n this.source = source;\n this.target = target;\n this.headers = headers || {};\n this.message = message;\n this.timestamp = Date.now(); // Automatically track packet creation time\n this.ttl = ttl;\n this.signature = signature;\n this.timestamp = timestamp || Date.now();\n }\n\n // Serialize the packet for network transmission\n serialize(): string {\n return JSON.stringify({\n id: this.id,\n source: this.source,\n subject: this.subject,\n target: this.target,\n headers: this.headers,\n message: this.message && this.message.serialize(),\n timestamp: this.timestamp,\n ttl: this.ttl,\n signature: this.signature,\n });\n }\n\n // Deserialize a packet from a string\n static deserialize(data: string): Packet {\n const obj = JSON.parse(data);\n return new Packet({\n id: obj.id,\n subject: obj.subject,\n source: obj.source,\n target: obj.target,\n headers: obj.headers,\n message: obj.message && Message.deserialize(obj.message),\n timestamp: obj.timestamp,\n ttl: obj.ttl,\n signature: obj.signature,\n });\n }\n\n // Verify TTL: Checks if the packet is still valid based on TTL\n isExpired(): boolean {\n if (!this.ttl) return false; // No TTL means no expiration\n return Date.now() > this.timestamp + this.ttl;\n }\n\n // sign(signingKey: string) {\n // this.signature = generateSignature(this.serialize(), signingKey); // Example signature function\n // }\n\n // verifySignature(publicKey: string): boolean {\n // if (!this.signature) throw new Error(\"No signature to verify\");\n // return verifySignature(this.serialize(), this.signature, publicKey);\n // }\n}","import { Message } from \"./Message\";\nimport { Packet } from \"./Packet\";\n\n\nexport function SerializeMessage(target: any, propertyKey: string, descriptor: PropertyDescriptor) {\n const originalMethod = descriptor.value;\n\n descriptor.value = function (...args: any[]) {\n const [subject, message] = args;\n\n if (typeof message !== \"string\") {\n throw new Error(\"Message must be a string\");\n }\n\n const serializedMessage = new Message({\n subject,\n payload: message,\n status: \"pending\",\n headers: new Map([[\"Content-Type\", \"application/json\"]]),\n }).serialize();\n\n\n return originalMethod.apply(this, [subject, serializedMessage]);\n };\n\n return descriptor;\n}","// Re-export Message and its types\nexport { Message, type MessageHeaders, type MessageBody, type MessageOptions } from \"./Message\";\nexport { default as MessageDefault } from \"./Message\";\n\n// Re-export Packet and its types\nexport { Packet, type PacketOptions } from \"./Packet\";\n\n// Export decorators\nexport { SerializeMessage } from \"./decorators\";\n\nimport { SerializeMessage } from \"./decorators\";\nconst decorators = {\n SerializeMessage\n}\n\nexport { decorators }","/**\n * HTTP client for the accelerator's `/api/auth/*` endpoints.\n *\n * Owns the wire shapes for register / challenge / authenticate / verify so\n * the React SPA (and any future consumers) don't reimplement them. The ZK\n * identity derivation + Groth16 proof generation stay on the application\n * side — this client handles only the round-trips.\n *\n * Mirrors `PersonalSpaceClient` / `ShardClient` / `SharedSpaceClient`: takes\n * a `baseUrl`, optional custom `fetch`, throws typed `Error`s on failure\n * (with the worker's message inlined where available).\n */\n\nimport type { Groth16Proof } from \"../types/zk\";\n\n// ---------------------------------------------------------------------------\n// Wire types — must stay in sync with `accelerator/src/durable-objects/UserAuth.ts`.\n// ---------------------------------------------------------------------------\n\nexport interface ZkRegisterRequest {\n username: string;\n /** Decimal-string Poseidon commitment. */\n commitment: string;\n /** Base64-encoded raw uncompressed ECDH public key (SEC1 0x04‖X‖Y). */\n ecdhPublicKey: string;\n /** Base64-encoded raw uncompressed ECDSA public key. */\n ecdsaPublicKey: string;\n email?: string | null;\n}\n\nexport interface ZkRegisterResponse {\n success: boolean;\n}\n\nexport interface ZkChallengeResponse {\n challengeId: string;\n /** Hex-encoded random nonce — caller reduces into a BN254 field element for the proof. */\n nonce: string;\n /** Decimal-string Poseidon commitment the server has on file for this user. */\n commitment: string;\n}\n\nexport interface ZkAuthenticateRequest {\n challengeId: string;\n proof: {\n commitment: string;\n /** Original hex nonce from the challenge (NOT the field-reduced version). */\n nonce: string;\n response: {\n proof: Groth16Proof;\n publicSignals: string[];\n };\n /** Base64 ECDSA-SHA256 signature over `JSON.stringify(response.proof)`. */\n signature: string;\n };\n rememberMe?: boolean;\n}\n\nexport interface AuthSuccess {\n token: string;\n username: string;\n}\n\n// ---------------------------------------------------------------------------\n// AuthClient\n// ---------------------------------------------------------------------------\n\nexport interface AuthClientOptions {\n /** Absolute URL of the accelerator worker (no trailing slash required). */\n baseUrl: string;\n /** Optional custom fetch — defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n}\n\nexport class AuthClient {\n private readonly baseUrl: string;\n private readonly fetchFn: typeof fetch;\n\n constructor(opts: AuthClientOptions) {\n if (!opts?.baseUrl) throw new Error(\"AuthClient: `baseUrl` is required\");\n this.baseUrl = opts.baseUrl.replace(/\\/+$/, \"\");\n const f = opts.fetch ?? globalThis.fetch;\n if (typeof f !== \"function\") {\n throw new Error(\"AuthClient: `globalThis.fetch` is unavailable; pass an explicit fetch.\");\n }\n this.fetchFn = f.bind(globalThis);\n }\n\n /** Submit ZK registration. Caller has already derived the identity + commitment. */\n async register(req: ZkRegisterRequest): Promise<ZkRegisterResponse> {\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/zk-register`, this.json(\"POST\", req));\n return await this.parse<ZkRegisterResponse>(\"register\", res);\n }\n\n /** Request an auth challenge for `username` (server issues a fresh nonce). */\n async getChallenge(username: string): Promise<ZkChallengeResponse> {\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/challenge`, this.json(\"POST\", { username }));\n return await this.parse<ZkChallengeResponse>(\"getChallenge\", res);\n }\n\n /** Trade a challenge + proof for a session token. */\n async authenticate(req: ZkAuthenticateRequest): Promise<AuthSuccess> {\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/zk-authenticate`, this.json(\"POST\", req));\n return await this.parse<AuthSuccess>(\"authenticate\", res);\n }\n\n /**\n * Validate a previously stored session token. Returns `{ username }` on\n * success; throws on 401/404 — caller uses that to drop a stale token\n * when restoring a session after a reload.\n */\n async verify(token: string): Promise<{ username: string }> {\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/verify`, this.json(\"POST\", { token }));\n return await this.parse<{ username: string }>(\"verify\", res);\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private json(method: string, body: unknown): RequestInit {\n return {\n method,\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n };\n }\n\n private async parse<T>(label: string, res: Response): Promise<T> {\n let body: unknown = null;\n try {\n body = await res.json();\n } catch {\n // Leave body null; we'll fall through to the status-only message.\n }\n if (!res.ok) {\n const msg =\n body && typeof body === \"object\" && \"error\" in (body as object)\n ? String((body as { error: unknown }).error)\n : `${res.status} ${res.statusText}`;\n throw new Error(`AuthClient.${label}: ${msg}`);\n }\n return body as T;\n }\n}\n\nexport default AuthClient;\n","/**\n * Deterministic ZK identity derivation from `(username, password)`.\n *\n * Same inputs on ANY device produce the same secret, salt, and P-256\n * ECDSA + ECDH keypairs — which is what makes federated login from a\n * fresh browser possible. There is no localStorage involvement: every\n * register and login call re-derives the identity on demand.\n *\n * Pipeline:\n * master_seed = PBKDF2-SHA256(password, \"muhkoo-zk-v1:\" || username, 200k iters)\n * secret = HKDF-Expand-SHA256(master_seed, \"zk-secret\", 32 bytes) → hex\n * salt = HKDF-Expand-SHA256(master_seed, \"zk-salt\", 32 bytes) → hex\n * ecdsa_priv = HKDF-Expand-SHA256(master_seed, \"ecdsa-priv\", 32 bytes)\n * ecdh_priv = HKDF-Expand-SHA256(master_seed, \"ecdh-priv\", 32 bytes)\n *\n * P-256 public points are computed via `@noble/curves` (WebCrypto has no\n * derive-public-from-private-scalar API), then both keypairs are imported\n * into SubtleCrypto in JWK form so the rest of the crypto stack can keep\n * using `crypto.subtle.sign` / `crypto.subtle.deriveBits`.\n *\n * Originally lived in `accelerator/public/js/zk-identity.js` and was ported\n * to `muhkoo/web/src/zk/identity.ts`; consolidated here so the SDK owns\n * identity derivation end-to-end.\n */\n\n// @noble/curves v2 consolidated all NIST curves under `nist`; v1 had a\n// `/p256` subpath. Update if the dep changes again.\nimport { p256 } from \"@noble/curves/nist.js\";\nimport { toHex } from \"../utilities/bytes\";\n\nconst TEXT_ENCODER = new TextEncoder();\nconst PBKDF2_ITERATIONS = 200_000;\nconst SCALAR_BYTES = 32;\n\nexport interface ZkIdentity {\n /** 32-byte secret, hex-encoded. Private witness for the ZK circuit. */\n secretHex: string;\n /** 32-byte salt, hex-encoded. Private witness for the ZK circuit. */\n saltHex: string;\n /** P-256 ECDSA keypair, used to sign auth proofs. */\n ecdsaKeyPair: CryptoKeyPair;\n /** P-256 ECDH keypair, used by the chat ratchet. */\n ecdhKeyPair: CryptoKeyPair;\n}\n\nasync function pbkdf2Bytes(password: string, info: string, byteLength: number): Promise<Uint8Array> {\n const baseKey = await crypto.subtle.importKey(\n \"raw\",\n TEXT_ENCODER.encode(password),\n { name: \"PBKDF2\" },\n false,\n [\"deriveBits\"],\n );\n const bits = await crypto.subtle.deriveBits(\n {\n name: \"PBKDF2\",\n salt: TEXT_ENCODER.encode(info),\n iterations: PBKDF2_ITERATIONS,\n hash: \"SHA-256\",\n },\n baseKey,\n byteLength * 8,\n );\n return new Uint8Array(bits);\n}\n\nasync function hkdfExpand(prk: Uint8Array, info: string, byteLength: number): Promise<Uint8Array> {\n const baseKey = await crypto.subtle.importKey(\n \"raw\",\n prk as BufferSource,\n { name: \"HKDF\" },\n false,\n [\"deriveBits\"],\n );\n const bits = await crypto.subtle.deriveBits(\n {\n name: \"HKDF\",\n hash: \"SHA-256\",\n salt: new Uint8Array() as BufferSource,\n info: TEXT_ENCODER.encode(info) as BufferSource,\n },\n baseKey,\n byteLength * 8,\n );\n return new Uint8Array(bits);\n}\n\nfunction bytesToBase64url(bytes: Uint8Array): string {\n let str = \"\";\n for (let i = 0; i < bytes.length; i++) str += String.fromCharCode(bytes[i]);\n return btoa(str).replace(/=+$/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n}\n\n// Convert a 32-byte scalar into a valid P-256 keypair. Probability of drawing\n// 0 or a value >= curve order from HKDF output is negligible (~2^-128); noble\n// will throw if it ever happens.\nasync function importP256KeyPair(\n privBytes: Uint8Array,\n algo: EcKeyAlgorithm,\n privKeyUses: KeyUsage[],\n pubKeyUses: KeyUsage[],\n): Promise<CryptoKeyPair> {\n const pubBytes = p256.getPublicKey(privBytes, false); // 65-byte 0x04||X||Y\n const x = pubBytes.slice(1, 33);\n const y = pubBytes.slice(33, 65);\n const xB = bytesToBase64url(x);\n const yB = bytesToBase64url(y);\n const dB = bytesToBase64url(privBytes);\n\n const privateKey = await crypto.subtle.importKey(\n \"jwk\",\n { kty: \"EC\", crv: \"P-256\", d: dB, x: xB, y: yB, ext: true },\n algo,\n false,\n privKeyUses,\n );\n const publicKey = await crypto.subtle.importKey(\n \"jwk\",\n { kty: \"EC\", crv: \"P-256\", x: xB, y: yB, ext: true },\n algo,\n true,\n pubKeyUses,\n );\n return { privateKey, publicKey };\n}\n\nasync function importEcdsaKeyPair(privBytes: Uint8Array): Promise<CryptoKeyPair> {\n return importP256KeyPair(\n privBytes,\n { name: \"ECDSA\", namedCurve: \"P-256\" },\n [\"sign\"],\n [\"verify\"],\n );\n}\n\nasync function importEcdhKeyPair(privBytes: Uint8Array): Promise<CryptoKeyPair> {\n return importP256KeyPair(\n privBytes,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n [\"deriveKey\", \"deriveBits\"],\n [],\n );\n}\n\n/**\n * Derive a deterministic ZK identity from `(username, password)`.\n *\n * Same inputs always produce the same identity, on any device — that's\n * what makes federated login work without dragging encrypted state across\n * devices.\n */\nexport async function deriveIdentity(username: string, password: string): Promise<ZkIdentity> {\n if (typeof username !== \"string\" || username.length === 0) {\n throw new Error(\"deriveIdentity: `username` is required\");\n }\n if (typeof password !== \"string\" || password.length === 0) {\n throw new Error(\"deriveIdentity: `password` is required\");\n }\n\n const seed = await pbkdf2Bytes(password, \"muhkoo-zk-v1:\" + username, SCALAR_BYTES);\n\n const secretBytes = await hkdfExpand(seed, \"zk-secret\", SCALAR_BYTES);\n const saltBytes = await hkdfExpand(seed, \"zk-salt\", SCALAR_BYTES);\n const ecdsaPriv = await hkdfExpand(seed, \"ecdsa-priv\", SCALAR_BYTES);\n const ecdhPriv = await hkdfExpand(seed, \"ecdh-priv\", SCALAR_BYTES);\n\n const ecdsaKeyPair = await importEcdsaKeyPair(ecdsaPriv);\n const ecdhKeyPair = await importEcdhKeyPair(ecdhPriv);\n\n return {\n secretHex: toHex(secretBytes),\n saltHex: toHex(saltBytes),\n ecdsaKeyPair,\n ecdhKeyPair,\n };\n}\n","/**\n * Poseidon hash wrapper used by the ZK auth flow.\n *\n * Backed by `circomlibjs`'s `buildPoseidon`. Builder is lazy and cached\n * because the JS-side Babyjubjub field reps take ~100ms to construct, and\n * we'd rather not pay that on every page load.\n *\n * Returns hashes as decimal-string BigInts — same format snarkjs and the\n * `preimagePoK` circuit expect for inputs.\n *\n * Note: circomlibjs is `optionalDependencies` in connect's package.json.\n * Consumers that use the ZK auth flow (browser/server, not workers) need\n * it installed. The workers build does not import this module.\n */\n\nimport { buildPoseidon } from \"circomlibjs\";\n\ntype PoseidonF = { toString(val: unknown): string };\ntype PoseidonFn = ((inputs: Array<bigint | string | number>) => unknown) & { F: PoseidonF };\n\nlet _poseidon: PoseidonFn | null = null;\nlet _loadPromise: Promise<PoseidonFn> | null = null;\n\nasync function loadPoseidon(): Promise<PoseidonFn> {\n if (_poseidon) return _poseidon;\n if (_loadPromise) return _loadPromise;\n _loadPromise = (async () => {\n const fn = (await buildPoseidon()) as unknown as PoseidonFn;\n _poseidon = fn;\n return fn;\n })();\n return _loadPromise;\n}\n\n/**\n * Poseidon-hash `inputs` and return the result as a decimal-string BigInt.\n * Inputs are converted to BigInt — pass either bigints, numbers, or numeric\n * strings.\n */\nexport async function poseidonHash(\n inputs: Array<bigint | string | number>,\n): Promise<string> {\n const p = await loadPoseidon();\n const bigInputs = inputs.map((i) => {\n if (typeof i === \"bigint\") return i;\n if (typeof i === \"string\") return BigInt(i);\n return BigInt(i);\n });\n const hash = p(bigInputs);\n return p.F.toString(hash);\n}\n","/**\n * Groth16 proof generation for the `preimagePoK` circuit.\n *\n * The circuit proves knowledge of `(secret, salt, ecdsaPub)` such that\n * commitment = Poseidon(secret, salt, Poseidon(ecdsaPub))\n * while only revealing `(commitment, nonce, ecdsaPubHash)` as public signals.\n *\n * Circuit assets (wasm + zkey) are served by the accelerator worker. Their\n * URLs are a required argument of {@link generateAuthProof} — there is no\n * default. The web app constructs them relative to its configured worker\n * `baseUrl` so the SPA can target either the local wrangler dev or a deployed\n * worker depending on `VITE_WORKER_URL`.\n */\n\n// snarkjs has no TypeScript types in the npm package — the shared shim in\n// `types/snarkjs.d.ts` (already present for ZeroKnowledge.ts) covers the\n// `groth16.fullProve` call we need here too.\n//\n// Imported lazily (dynamic `import`) rather than at module top-level: snarkjs\n// is an externalized peer dependency that only the ZK login proof path needs.\n// Loading it eagerly would force every consumer of the SDK — and the test\n// runner — to have snarkjs resolvable just to construct a `Client`. The lazy\n// loader defers that cost until `generateAuthProof` actually runs.\nimport type { Groth16Proof } from \"../types/zk\";\nimport { poseidonHash } from \"./poseidon\";\n\ntype Snarkjs = {\n groth16: {\n fullProve: (\n input: unknown,\n wasm: string,\n zkey: string,\n ) => Promise<{ proof: unknown; publicSignals: string[] }>;\n };\n};\nlet _snarkjs: Snarkjs | null = null;\nasync function loadSnarkjs(): Promise<Snarkjs> {\n if (_snarkjs) return _snarkjs;\n _snarkjs = (await import(\"snarkjs\")) as unknown as Snarkjs;\n return _snarkjs;\n}\n\nexport type { Groth16Proof };\n\nexport interface CircuitUrls {\n /** preimagePoK.wasm — the circuit's witness generator. */\n wasmUrl: string;\n /** preimagePoK_0001.zkey — the proving key. */\n zkeyUrl: string;\n}\n\n/**\n * Canonical {@link CircuitUrls} for the `preimagePoK` login circuit, anchored\n * at a base URL where the accelerator serves the circuit assets out of\n * `circuits/build/`. The filenames here are fixed by the circom build output\n * (the witness generator lands inside a `preimagePoK_js/` directory); callers\n * shouldn't hard-code them. `Client` uses this to default its `circuits`\n * option, and `PersonalSpaceClient` consumers can pass `defaultCircuitUrls(baseUrl)`.\n */\nexport function defaultCircuitUrls(baseUrl: string): CircuitUrls {\n const base = baseUrl.replace(/\\/+$/, \"\");\n return {\n wasmUrl: `${base}/circuits/build/preimagePoK_js/preimagePoK.wasm`,\n zkeyUrl: `${base}/circuits/build/preimagePoK_0001.zkey`,\n };\n}\n\n/** BN254 scalar field modulus — the prime the circuit's signals live in. */\nconst FIELD_SIZE = 21888242871839275222246405745257275088548364400416034343698204186575808495617n;\n\n/**\n * Reduce any hex/decimal/byte input to a decimal-string field element in\n * `[0, FIELD_SIZE)`. snarkjs and the `preimagePoK` circuit both want decimal\n * strings; everything else gets normalized here.\n *\n * **Behavior is intentionally byte-for-byte compatible with the legacy\n * `accelerator/public/js/zk-snarkjs-client.js#toField`.** Diverging produces\n * different commitments than accounts registered via the legacy flow,\n * which locks those users out forever — the worker stores whatever\n * commitment the client sent at register time and compares it as a string\n * at login time.\n *\n * In particular: a 32+ char string of hex chars is always treated as hex,\n * even if every character happens to be 0-9 with no a-f letters. An\n * earlier version of this function gated the hex branch on \"has at least\n * one letter\" — that broke the digit-only-hex edge case (rare in practice,\n * but real). DO NOT add that letter check back.\n */\nexport function toField(value: string | bigint | number): string {\n let v: bigint;\n if (typeof value === \"bigint\") v = value;\n else if (typeof value === \"number\") v = BigInt(value);\n else if (value.startsWith(\"0x\")) v = BigInt(value);\n else if (/^[0-9a-fA-F]+$/.test(value) && value.length >= 32) {\n // Raw hex without prefix — secret, salt, ecdsaPub, nonce all hit this.\n v = BigInt(\"0x\" + value);\n } else if (/^[0-9]+$/.test(value)) v = BigInt(value);\n else {\n // Treat any other string as utf-8 bytes — matches the legacy client.\n const bytes = new TextEncoder().encode(value);\n let hex = \"\";\n for (const b of bytes) hex += b.toString(16).padStart(2, \"0\");\n v = BigInt(\"0x\" + hex);\n }\n v = v % FIELD_SIZE;\n if (v < 0n) v += FIELD_SIZE;\n return v.toString();\n}\n\n/**\n * Build the user's Poseidon commitment binding `(secret, salt, ecdsaPubHash)`.\n * Same formula the worker verifies against on register and authenticate.\n */\nexport async function buildCommitment(\n secretHex: string,\n saltHex: string,\n ecdsaPubHex: string,\n): Promise<string> {\n const secretField = toField(secretHex);\n const saltField = toField(saltHex);\n const ecdsaPubField = toField(ecdsaPubHex);\n const ecdsaPubHash = await poseidonHash([ecdsaPubField]);\n return await poseidonHash([secretField, saltField, ecdsaPubHash]);\n}\n\n/**\n * Generate a Groth16 proof for the `preimagePoK` circuit. Public signals end\n * up `[commitment, nonce, ecdsaPubHash]` — the worker checks the commitment\n * matches the stored one and the nonce matches the issued challenge nonce\n * reduced into the field.\n *\n * Throws if circuit URLs are unreachable or snarkjs decides the inputs are\n * malformed.\n */\nexport async function generateAuthProof(args: {\n secretHex: string;\n saltHex: string;\n ecdsaPubHex: string;\n nonceHex: string;\n /** Required — caller supplies URLs scoped to the worker they want to talk to. */\n circuits: CircuitUrls;\n}): Promise<{\n proof: Groth16Proof;\n publicSignals: string[];\n commitment: string;\n nonceField: string;\n ecdsaPubHash: string;\n}> {\n const secretField = toField(args.secretHex);\n const saltField = toField(args.saltHex);\n const ecdsaPubField = toField(args.ecdsaPubHex);\n const nonceField = toField(args.nonceHex);\n\n const ecdsaPubHash = await poseidonHash([ecdsaPubField]);\n const commitment = await poseidonHash([secretField, saltField, ecdsaPubHash]);\n\n const circuitInput: Record<string, string> = {\n // Public inputs (must appear in the same order the circuit declares).\n commitment,\n nonce: nonceField,\n ecdsaPubHash,\n // Private witnesses.\n secret: secretField,\n salt: saltField,\n ecdsaPub: ecdsaPubField,\n };\n\n const snarkjs = await loadSnarkjs();\n const { proof, publicSignals } = await snarkjs.groth16.fullProve(\n circuitInput,\n args.circuits.wasmUrl,\n args.circuits.zkeyUrl,\n );\n\n return {\n proof: proof as Groth16Proof,\n publicSignals,\n commitment,\n nonceField,\n ecdsaPubHash,\n };\n}\n","/**\n * Conversions between SubtleCrypto `CryptoKey`s and the wire formats the\n * accelerator's auth endpoints + `preimagePoK` circuit expect.\n *\n * Two outputs we need from an ECDSA `CryptoKey`:\n * - **base64 raw** — passed to `/api/auth/zk-register` as\n * `ecdsaPublicKey` / `ecdhPublicKey`. (Name is historical;\n * the legacy client called it `exportPublicKeyToBase58`\n * but actually used base64 — kept as base64.)\n * - **hex raw** — fed to the proof as `ecdsaPub` input; the circuit\n * reduces it into a field element.\n *\n * Both go through `crypto.subtle.exportKey(\"raw\", ...)` which yields the\n * uncompressed SEC1 form (`0x04 || X || Y`).\n */\n\nimport { toHex } from \"../utilities/bytes\";\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let str = \"\";\n for (let i = 0; i < bytes.length; i++) str += String.fromCharCode(bytes[i]);\n return btoa(str);\n}\n\n/** Raw uncompressed (`0x04 || X || Y`) public key bytes, as lowercase hex. */\nexport async function exportPublicKeyHex(publicKey: CryptoKey): Promise<string> {\n const buf = await crypto.subtle.exportKey(\"raw\", publicKey);\n return toHex(new Uint8Array(buf));\n}\n\n/** Raw uncompressed public key as base64 — wire format for the auth endpoints. */\nexport async function exportPublicKeyBase64(publicKey: CryptoKey): Promise<string> {\n const buf = await crypto.subtle.exportKey(\"raw\", publicKey);\n return bytesToBase64(new Uint8Array(buf));\n}\n\n/** Sign a UTF-8 `message` with an ECDSA private key. Returns base64. */\nexport async function signMessage(message: string, privateKey: CryptoKey): Promise<string> {\n const data = new TextEncoder().encode(message);\n const sig = await crypto.subtle.sign(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n privateKey,\n data,\n );\n return bytesToBase64(new Uint8Array(sig));\n}\n","/**\n * `HttpClient` — the one place the unified {@link Client} talks to the\n * accelerator over HTTP.\n *\n * Every request carries two independent credentials:\n * - the **app key** (`mk_…`) on `X-Muhkoo-Key` — resolves the app /\n * developer / env context the accelerator uses for routing + billing;\n * - the **user session token** on `X-Muhkoo-Session` (when a user is\n * logged in) — the accelerator validates it and injects a trusted\n * `X-Muhkoo-User-Context` downstream so per-user spaces can authorize\n * the request without a fresh Groth16 proof.\n *\n * `X-Muhkoo-Key` is used (rather than `Authorization: Bearer`) because it is\n * a non-forbidden header that skips the CORS preflight in browsers.\n *\n * The class exposes a header-injecting {@link fetch} that can be handed to\n * lower-level building blocks (`AuthClient`, `PersonalSpaceClient`) so they\n * keep owning their own wire shapes while still getting the credentials, plus\n * convenience JSON helpers (`get`/`post`/`del`) for code that talks to the\n * accelerator directly.\n */\n\nexport interface HttpClientOptions {\n /** Absolute URL of the accelerator worker (trailing slash optional). */\n baseUrl: string;\n /**\n * App / publishable key, e.g. `mk_test_pk_…`. Sent on every request as\n * `X-Muhkoo-Key` when present. Transitionally optional (auth + personal\n * storage still function without it), but the product direction is to\n * REQUIRE it — it attributes traffic for billing/metering and authorizes\n * shared-space (messaging) websockets.\n */\n apiKey?: string;\n /** Returns the current user session token, or `null` when logged out. */\n getSessionToken?: () => string | null;\n /** Custom fetch — defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n /**\n * Called when a token-gated request comes back `401` (stale/expired\n * session). Should attempt to silently re-establish a session and resolve\n * `true` if it succeeded (the request is then retried once with the fresh\n * token) or `false` if it couldn't (the `401` propagates as an\n * {@link HttpError}). Wired by {@link Client} to `auth.zk.recover()`.\n *\n * Only consulted by the JSON helpers (`get`/`post`/`del`); the raw\n * {@link fetch} passes 401s straight through so the auth wire calls that\n * power recovery itself can't recurse.\n */\n onUnauthorized?: () => Promise<boolean>;\n}\n\n/** Thrown for any non-2xx accelerator response. Carries the HTTP status. */\nexport class HttpError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly body?: unknown,\n ) {\n super(message);\n this.name = \"HttpError\";\n }\n}\n\nexport class HttpClient {\n readonly baseUrl: string;\n private readonly apiKey: string | null;\n private readonly getSessionToken: () => string | null;\n private readonly onUnauthorized: (() => Promise<boolean>) | null;\n private readonly fetchFn: typeof fetch;\n\n constructor(opts: HttpClientOptions) {\n if (!opts?.baseUrl) throw new Error(\"HttpClient: `baseUrl` is required\");\n this.baseUrl = opts.baseUrl.replace(/\\/+$/, \"\");\n this.apiKey = opts.apiKey ?? null;\n this.getSessionToken = opts.getSessionToken ?? (() => null);\n this.onUnauthorized = opts.onUnauthorized ?? null;\n\n const f = opts.fetch ?? globalThis.fetch;\n if (typeof f !== \"function\") {\n throw new Error(\n \"HttpClient: `globalThis.fetch` is unavailable; pass an explicit `fetch`.\",\n );\n }\n this.fetchFn = f.bind(globalThis);\n }\n\n /**\n * A `fetch`-compatible function that injects the app key + session token\n * headers. Hand this to `AuthClient` / `PersonalSpaceClient` so they pick\n * up credentials without knowing about them.\n */\n readonly fetch: typeof fetch = (input, init) => {\n const headers = new Headers(init?.headers);\n if (this.apiKey) headers.set(\"X-Muhkoo-Key\", this.apiKey);\n const token = this.getSessionToken();\n if (token) headers.set(\"X-Muhkoo-Session\", token);\n return this.fetchFn(input, { ...init, headers });\n };\n\n // -------------------------------------------------------------------------\n // JSON convenience helpers (path is relative to baseUrl)\n // -------------------------------------------------------------------------\n\n get<T = unknown>(path: string): Promise<T> {\n return this.request<T>(\"GET\", path);\n }\n\n post<T = unknown>(path: string, body?: unknown): Promise<T> {\n return this.request<T>(\"POST\", path, body);\n }\n\n del<T = unknown>(path: string, body?: unknown): Promise<T> {\n return this.request<T>(\"DELETE\", path, body);\n }\n\n private async request<T>(method: string, path: string, body?: unknown, allowRecovery = true): Promise<T> {\n const url = path.startsWith(\"http\") ? path : `${this.baseUrl}${path.startsWith(\"/\") ? \"\" : \"/\"}${path}`;\n const init: RequestInit = { method };\n if (body !== undefined) {\n init.headers = { \"Content-Type\": \"application/json\" };\n init.body = JSON.stringify(body);\n }\n const res = await this.fetch(url, init);\n\n // Stale session: try to silently re-auth and replay the request once.\n // `allowRecovery` is cleared on the retry so a still-401 response (e.g.\n // recovery minted a token the endpoint still rejects) can't loop.\n if (res.status === 401 && allowRecovery && this.onUnauthorized && this.getSessionToken()) {\n const recovered = await this.onUnauthorized();\n if (recovered) {\n return this.request<T>(method, path, body, false);\n }\n }\n\n let parsed: unknown = null;\n try {\n parsed = await res.json();\n } catch {\n // Non-JSON body — leave null and fall through to status-only error.\n }\n if (!res.ok) {\n const msg =\n parsed && typeof parsed === \"object\" && \"error\" in (parsed as object)\n ? String((parsed as { error: unknown }).error)\n : `${res.status} ${res.statusText}`;\n throw new HttpError(msg, res.status, parsed);\n }\n return parsed as T;\n }\n}\n\nexport default HttpClient;\n","/**\n * `SessionState` — the in-memory source of truth for \"who is signed in\" on a\n * {@link Client}.\n *\n * It separates two concerns that have different lifetimes and security\n * properties:\n *\n * - **session** (`{ token, username, commitment }`) — proves the user is\n * authenticated to the accelerator. Cheap to persist (the token is an\n * opaque server-side handle) and enough to authorize token-gated REST\n * calls. Restored from a {@link SessionStore} across reloads.\n *\n * - **identity** ({@link ZkIdentity}) — the derived secret + keypairs. Lets\n * the client *prove* ownership (ZK), derive at-rest encryption keys, and\n * run the messaging ratchet. It is derived from `(username, password)` and\n * is deliberately **never** persisted by default — a restored session has\n * a valid token but no identity until the user re-derives it\n * (`client.auth.zk.unlock(password)`).\n *\n * This split is what makes `restore()` (authenticated, can't decrypt) and\n * `unlock()` (now can decrypt) two distinct, intentional states.\n */\n\nimport type { ZkIdentity } from \"../auth/identity\";\n\n/** The persistable part of a session — safe-ish to keep across reloads. */\nexport interface StoredSession {\n token: string;\n username: string;\n /** Decimal-string Poseidon commitment — the user's stable id. */\n commitment: string;\n}\n\n/**\n * Pluggable persistence for the session token. Browser apps typically back\n * this with `localStorage`; the default is in-memory (lost on reload).\n *\n * Identity material is intentionally not part of this interface — see the\n * class docs. Apps that want federated session restore without re-prompting\n * for a password can persist it themselves and call `unlock()` on boot.\n */\nexport interface SessionStore {\n load(): StoredSession | null | Promise<StoredSession | null>;\n save(session: StoredSession): void | Promise<void>;\n clear(): void | Promise<void>;\n}\n\n/** Default in-memory store — holds the session for the process lifetime only. */\nexport class MemorySessionStore implements SessionStore {\n private current: StoredSession | null = null;\n load(): StoredSession | null {\n return this.current;\n }\n save(session: StoredSession): void {\n this.current = session;\n }\n clear(): void {\n this.current = null;\n }\n}\n\n/**\n * A {@link SessionStore} backed by the browser's `localStorage`, so a session\n * survives page reloads. This is the store most browser apps want — pass it to\n * `new Client({ sessionStore: new LocalStorageSessionStore() })`.\n *\n * Browser-only: construction throws if `localStorage` is unavailable (Node,\n * Workers, or SSR before hydration) — use {@link MemorySessionStore} or a\n * custom store there. Keys are namespaced under `keyPrefix` so multiple apps\n * on the same origin don't collide.\n */\nexport class LocalStorageSessionStore implements SessionStore {\n private readonly tokenKey: string;\n private readonly usernameKey: string;\n private readonly commitmentKey: string;\n\n constructor(keyPrefix = \"muhkoo.session.\") {\n if (typeof localStorage === \"undefined\") {\n throw new Error(\n \"LocalStorageSessionStore requires a browser environment with localStorage; \" +\n \"use MemorySessionStore (or a custom SessionStore) on the server.\",\n );\n }\n this.tokenKey = `${keyPrefix}token`;\n this.usernameKey = `${keyPrefix}username`;\n this.commitmentKey = `${keyPrefix}commitment`;\n }\n\n load(): StoredSession | null {\n const token = localStorage.getItem(this.tokenKey);\n const username = localStorage.getItem(this.usernameKey);\n const commitment = localStorage.getItem(this.commitmentKey);\n if (!token || !username || !commitment) return null;\n return { token, username, commitment };\n }\n\n save(session: StoredSession): void {\n localStorage.setItem(this.tokenKey, session.token);\n localStorage.setItem(this.usernameKey, session.username);\n localStorage.setItem(this.commitmentKey, session.commitment);\n }\n\n clear(): void {\n localStorage.removeItem(this.tokenKey);\n localStorage.removeItem(this.usernameKey);\n localStorage.removeItem(this.commitmentKey);\n }\n}\n\n/**\n * The {@link SessionStore} a {@link Client} uses when none is supplied: a\n * {@link LocalStorageSessionStore} in the browser (so sessions survive\n * reloads), falling back to {@link MemorySessionStore} anywhere `localStorage`\n * is unavailable or unusable (Node, Workers, SSR, or private-mode browsers\n * that throw on access). Pass an explicit store to override.\n */\nexport function defaultSessionStore(keyPrefix?: string): SessionStore {\n try {\n // Touch the API, not just `typeof`: some environments expose\n // `localStorage` but throw on access (Safari private mode, sandboxed\n // iframes). LocalStorageSessionStore's constructor only checks for\n // existence, so probe a real read here and fall back on any throw.\n if (typeof localStorage !== \"undefined\") {\n localStorage.getItem(\"muhkoo.__probe__\");\n return new LocalStorageSessionStore(keyPrefix);\n }\n } catch {\n // fall through to in-memory\n }\n return new MemorySessionStore();\n}\n\nexport class SessionState {\n private session: StoredSession | null = null;\n private _identity: ZkIdentity | null = null;\n private readonly store: SessionStore;\n\n constructor(store?: SessionStore) {\n this.store = store ?? new MemorySessionStore();\n }\n\n /** True once a token-bearing session exists (regardless of identity). */\n get isAuthenticated(): boolean {\n return this.session !== null;\n }\n\n /** True once identity material is available (login or unlock happened). */\n get isUnlocked(): boolean {\n return this._identity !== null;\n }\n\n get token(): string | null {\n return this.session?.token ?? null;\n }\n\n get username(): string | null {\n return this.session?.username ?? null;\n }\n\n get commitment(): string | null {\n return this.session?.commitment ?? null;\n }\n\n get identity(): ZkIdentity | null {\n return this._identity;\n }\n\n /** Identity material, throwing a clear error when the client is locked. */\n requireIdentity(): ZkIdentity {\n if (!this._identity) {\n throw new Error(\n \"This operation needs the user's identity. Call `client.auth.zk.login()` \" +\n \"or `client.auth.zk.unlock(password)` first.\",\n );\n }\n return this._identity;\n }\n\n /** Persist + hold a freshly authenticated session. */\n async setSession(session: StoredSession): Promise<void> {\n this.session = session;\n await this.store.save(session);\n }\n\n /** Attach derived identity material to the current session. */\n setIdentity(identity: ZkIdentity): void {\n this._identity = identity;\n }\n\n /** Load a persisted session (used by `restore()`); identity stays null. */\n async loadPersisted(): Promise<StoredSession | null> {\n const loaded = await this.store.load();\n if (loaded) this.session = loaded;\n return loaded;\n }\n\n /** Drop all session + identity state and clear persistence. */\n async clear(): Promise<void> {\n this.session = null;\n this._identity = null;\n await this.store.clear();\n }\n}\n\nexport default SessionState;\n","/**\n * `client.auth` — user authentication, exposed today through the `zk`\n * sub-namespace (`client.auth.zk.login(...)`). Leaving room under `auth` for\n * other strategies later (e.g. `auth.oauth`) without reshaping the surface.\n *\n * `ZkAuth` absorbs the full ZK register/login dance that used to live in the\n * web app's `AuthContext`:\n *\n * register: derive identity → commitment → POST /api/auth/zk-register\n * login: derive identity → challenge → Groth16 proof → sign →\n * POST /api/auth/zk-authenticate → session token\n *\n * The derived {@link ZkIdentity} (secret + ECDSA/ECDH keypairs) is held in\n * {@link SessionState} so the storage + message namespaces can reuse it for\n * at-rest encryption and the messaging ratchet without re-deriving.\n */\n\nimport { AuthClient } from \"../../auth/AuthClient\";\nimport { deriveIdentity, type ZkIdentity } from \"../../auth/identity\";\nimport { generateAuthProof, buildCommitment, type CircuitUrls } from \"../../auth/proof\";\nimport { exportPublicKeyHex, exportPublicKeyBase64, signMessage } from \"../../auth/keys\";\nimport type { SessionState } from \"../Session\";\n\n/** What the auth methods resolve to — the stable, non-secret user facts. */\nexport interface AuthUser {\n username: string;\n /** Decimal-string Poseidon commitment — the user's stable id. */\n commitment: string;\n}\n\nexport interface RegisterParams {\n username: string;\n password: string;\n email?: string | null;\n /** Sign in immediately after registering (default: true). */\n login?: boolean;\n}\n\nexport interface LoginOptions {\n /** Ask the accelerator for a long-lived (30d) session (default: false). */\n rememberMe?: boolean;\n}\n\nexport interface ZkAuthDeps {\n auth: AuthClient;\n circuits: CircuitUrls;\n session: SessionState;\n}\n\n/**\n * ZK identity auth. One instance per {@link Client}; reads/writes the shared\n * {@link SessionState}.\n */\nexport class ZkAuth {\n constructor(private readonly deps: ZkAuthDeps) {}\n\n /**\n * Register a new user, then (by default) sign them in. The identity is\n * derived deterministically from `(username, password)` — the same inputs\n * reproduce it on any device, so there's no key material to ship around.\n */\n async register(params: RegisterParams): Promise<AuthUser> {\n const { username, password, email = null, login = true } = params;\n const identity = await deriveIdentity(username, password);\n const commitment = await this.commitmentFor(identity);\n\n await this.deps.auth.register({\n username,\n commitment,\n ecdhPublicKey: await exportPublicKeyBase64(identity.ecdhKeyPair.publicKey),\n ecdsaPublicKey: await exportPublicKeyBase64(identity.ecdsaKeyPair.publicKey),\n email,\n });\n\n if (login) {\n return this.login(username, password);\n }\n return { username, commitment };\n }\n\n /**\n * Sign in: re-derive the identity, prove knowledge of it against a fresh\n * server challenge, and trade the proof for a session token. On success\n * both the session and the identity are stored on the client.\n */\n async login(username: string, password: string, opts: LoginOptions = {}): Promise<AuthUser> {\n const identity = await deriveIdentity(username, password);\n return this.proveAndStore(username, identity, opts);\n }\n\n /**\n * Silently re-authenticate the current user without prompting for a\n * password. Only possible while the client is **unlocked** — i.e. the\n * derived {@link ZkIdentity} (secret + keypairs) is still in memory from a\n * prior `login()`/`unlock()`. Re-runs the full challenge→proof→authenticate\n * dance with that in-memory identity and swaps in the fresh token.\n *\n * Returns `true` if a new session was minted, `false` if recovery isn't\n * possible (no active user, or locked — the identity was never derived or\n * was lost on reload). A `false` result is the app's cue to send the user\n * back to the login screen.\n *\n * Used automatically by the {@link Client} when a token-gated request comes\n * back `401` (stale/expired token), so transient session expiry self-heals\n * instead of surfacing errors mid-session.\n */\n async recover(): Promise<boolean> {\n const username = this.deps.session.username;\n const identity = this.deps.session.identity;\n if (!username || !identity) return false;\n try {\n await this.proveAndStore(username, identity, {});\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Shared sign-in core: prove knowledge of `identity` against a fresh\n * challenge and persist the resulting session + identity. Used by both\n * `login()` (identity derived from a password) and `recover()` (identity\n * already in memory).\n */\n private async proveAndStore(\n username: string,\n identity: ZkIdentity,\n opts: LoginOptions,\n ): Promise<AuthUser> {\n const ecdsaPubHex = await exportPublicKeyHex(identity.ecdsaKeyPair.publicKey);\n\n const challenge = await this.deps.auth.getChallenge(username);\n\n const { proof, publicSignals, commitment } = await generateAuthProof({\n secretHex: identity.secretHex,\n saltHex: identity.saltHex,\n ecdsaPubHex,\n nonceHex: challenge.nonce,\n circuits: this.deps.circuits,\n });\n\n const signature = await signMessage(JSON.stringify(proof), identity.ecdsaKeyPair.privateKey);\n\n const result = await this.deps.auth.authenticate({\n challengeId: challenge.challengeId,\n proof: {\n commitment,\n // The accelerator expects the original hex nonce here, not the\n // field-reduced version fed into the circuit.\n nonce: challenge.nonce,\n response: { proof, publicSignals },\n signature,\n },\n rememberMe: opts.rememberMe,\n });\n\n await this.deps.session.setSession({\n token: result.token,\n username: result.username,\n commitment,\n });\n this.deps.session.setIdentity(identity);\n\n return { username: result.username, commitment };\n }\n\n /**\n * Restore a persisted session on boot. Validates the stored token with the\n * accelerator; returns the user when valid, or `null` (and clears the\n * stale session) otherwise. Identity stays locked — call {@link unlock}\n * to re-enable encryption/messaging without a full re-login.\n */\n async restore(): Promise<AuthUser | null> {\n const stored = await this.deps.session.loadPersisted();\n if (!stored) return null;\n try {\n await this.deps.auth.verify(stored.token);\n return { username: stored.username, commitment: stored.commitment };\n } catch {\n await this.deps.session.clear();\n return null;\n }\n }\n\n /**\n * Re-derive identity material for an already-authenticated (restored)\n * session, so the client can decrypt storage and run the ratchet. Verifies\n * the password by checking the derived commitment matches the session's.\n */\n async unlock(password: string): Promise<void> {\n const username = this.deps.session.username;\n const expected = this.deps.session.commitment;\n if (!username || !expected) {\n throw new Error(\"ZkAuth.unlock: no active session to unlock — sign in first.\");\n }\n const identity = await deriveIdentity(username, password);\n const commitment = await this.commitmentFor(identity);\n if (commitment !== expected) {\n throw new Error(\"ZkAuth.unlock: incorrect password (commitment mismatch).\");\n }\n this.deps.session.setIdentity(identity);\n }\n\n /** Sign out: clears the session, identity, and persisted token. */\n async logout(): Promise<void> {\n await this.deps.session.clear();\n }\n\n /** The signed-in user, or `null`. Synchronous read of current state. */\n get user(): AuthUser | null {\n const username = this.deps.session.username;\n const commitment = this.deps.session.commitment;\n return username && commitment ? { username, commitment } : null;\n }\n\n /**\n * The derived identity material for the current session, or `null` when\n * locked. Exposed so apps that still drive lower-level primitives (e.g. a\n * chat ratchet keyed off the same identity) can reuse it without\n * re-deriving from the password.\n */\n get identity(): ZkIdentity | null {\n return this.deps.session.identity;\n }\n\n /** The current session token, or `null` when signed out. */\n get token(): string | null {\n return this.deps.session.token;\n }\n\n // -------------------------------------------------------------------------\n\n /** Poseidon commitment for an identity — the value the server stores. */\n private async commitmentFor(identity: ZkIdentity): Promise<string> {\n // generateAuthProof recomputes this internally, but registration needs\n // it before any challenge exists, so derive it directly here.\n const ecdsaPubHex = await exportPublicKeyHex(identity.ecdsaKeyPair.publicKey);\n return buildCommitment(identity.secretHex, identity.saltHex, ecdsaPubHex);\n }\n}\n\n/** `client.auth` — the auth namespace. Strategies hang off here. */\nexport class AuthNamespace {\n readonly zk: ZkAuth;\n constructor(deps: ZkAuthDeps) {\n this.zk = new ZkAuth(deps);\n }\n\n /** Convenience pass-through: the currently signed-in user, or `null`. */\n get user(): AuthUser | null {\n return this.zk.user;\n }\n}\n\nexport default AuthNamespace;\n","/**\n * `StorageCipher` — transparent at-rest encryption for `client.storage`.\n *\n * Derives a single AES-256-GCM key from the user's ZK identity (HKDF over the\n * secret, salted with the identity salt) and uses it to seal/open the JSON\n * values the storage namespace persists. The accelerator only ever sees the\n * {@link EncryptedEnvelope} — opaque ciphertext + a per-value random IV.\n *\n * The key is deterministic in the identity, so the same `(username, password)`\n * decrypts the same data on any device — no key material is shipped or stored.\n */\n\nimport {\n deriveBitsHkdf,\n encryptAesGcm,\n decryptAesGcm,\n randomBytes,\n AES_GCM_IV_BYTES,\n AES_GCM_KEY_BYTES,\n} from \"./primitives\";\nimport { fromHex, toBase64, fromBase64, utf8Encode, utf8Decode } from \"../utilities/bytes\";\n\n/** The on-the-wire shape of an encrypted value. `_enc` tags the scheme. */\nexport interface EncryptedEnvelope {\n _enc: \"a256gcm\";\n /** Base64 random 12-byte GCM IV. */\n iv: string;\n /** Base64 ciphertext with the appended 16-byte GCM tag. */\n ct: string;\n}\n\n/** HKDF label binding the derived key to the storage-at-rest purpose. */\nconst STORAGE_KEY_INFO = \"muhkoo-storage-v1\";\n\nexport class StorageCipher {\n /** Lazily-derived AES key, memoized for the cipher's lifetime. */\n private readonly keyPromise: Promise<Uint8Array>;\n\n constructor(secretHex: string, saltHex: string) {\n this.keyPromise = deriveBitsHkdf(\n fromHex(secretHex),\n STORAGE_KEY_INFO,\n AES_GCM_KEY_BYTES,\n fromHex(saltHex),\n );\n }\n\n /** Seal a JSON-serializable value into an {@link EncryptedEnvelope}. */\n async encrypt(value: unknown): Promise<EncryptedEnvelope> {\n const key = await this.keyPromise;\n const iv = randomBytes(AES_GCM_IV_BYTES);\n const plaintext = utf8Encode(JSON.stringify(value));\n const ciphertext = await encryptAesGcm(key, iv, plaintext);\n return { _enc: \"a256gcm\", iv: toBase64(iv), ct: toBase64(ciphertext) };\n }\n\n /** Open an {@link EncryptedEnvelope} back into the original value. */\n async decrypt<T = unknown>(envelope: EncryptedEnvelope): Promise<T> {\n const key = await this.keyPromise;\n const iv = fromBase64(envelope.iv);\n const ciphertext = fromBase64(envelope.ct);\n const plaintext = await decryptAesGcm(key, iv, ciphertext);\n return JSON.parse(utf8Decode(plaintext)) as T;\n }\n\n /** Type guard — is `v` an encrypted envelope (vs. a plaintext value)? */\n static isEnvelope(v: unknown): v is EncryptedEnvelope {\n return (\n !!v &&\n typeof v === \"object\" &&\n (v as { _enc?: unknown })._enc === \"a256gcm\" &&\n typeof (v as { iv?: unknown }).iv === \"string\" &&\n typeof (v as { ct?: unknown }).ct === \"string\"\n );\n }\n}\n\nexport default StorageCipher;\n","/**\n * Pure WebSocket transport — owns the socket lifecycle and nothing else.\n *\n * Hands raw frame strings up (via the `MESSAGE` event) and accepts raw frame\n * strings down (via `send`). Anything frame-shape, encryption, or serialization\n * related belongs in the layer above (e.g. `Network` for client↔server\n * encrypted pipes, `BroadcastChannel` for multi-peer E2E rooms).\n *\n * Responsibilities:\n * - Open / close the WebSocket\n * - Auto-reconnect with linear backoff after an unexpected close\n * - Buffer outbound frames while disconnected (capped queue)\n * - Emit lifecycle events (CONNECTED / DISCONNECTED / RECONNECTING / ERROR)\n * plus raw inbound MESSAGE events\n */\n\nimport { EventCore, EventCoreEvents } from \"../events\";\n\n/** Monotonic source of unique transport ids when a caller doesn't supply one. */\nlet __wsInstanceSeq = 0;\n\nexport interface WSTransportOptions {\n /** WebSocket URL, e.g. `ws://localhost:8787/foo`. */\n url: string;\n /**\n * Stable identifier for this connection (a channel / space / personal-space\n * id). Lifecycle + MESSAGE events are namespaced by it on the shared\n * `EventCore` bus so concurrent transports (chat room A, room B, the storage\n * feed, …) never receive each other's frames. Optional — a unique id is\n * generated when omitted; pass a semantic one for clearer debugging.\n */\n id?: string;\n /** Reconnect automatically after unexpected disconnect (default `true`). */\n autoReconnect?: boolean;\n /** Delay between reconnect attempts in ms (default `3000`). */\n reconnectDelay?: number;\n /** Cap on reconnect attempts (default `5`; `0` means unlimited). */\n maxReconnectAttempts?: number;\n /**\n * Max outbound frames buffered while disconnected. Sending past this caps\n * throws synchronously. Default `100`.\n */\n maxQueueSize?: number;\n /**\n * Heartbeat interval in ms. While connected, a `pingFrame` is sent every\n * interval to keep the socket warm (long-lived WebSockets get dropped by CF\n * / intermediaries when idle) and to detect a silently-dead connection.\n * Default `30000`. Set `0` to disable the heartbeat entirely.\n */\n heartbeatInterval?: number;\n /**\n * How long (ms) to wait for a `pongFrame` after sending a ping before\n * treating the connection as dead and forcing a reconnect. Should be well\n * under `heartbeatInterval`. Default `10000`.\n */\n heartbeatTimeout?: number;\n /** Outbound keep-alive frame. Default `\"ping\"`. */\n pingFrame?: string;\n /**\n * Inbound keep-alive ack. Matching frames are swallowed (never surfaced as a\n * `MESSAGE`) and reset the liveness timer. Must match the server's\n * auto-response. Default `\"pong\"`.\n */\n pongFrame?: string;\n}\n\nexport class WSTransport extends EventCore {\n /**\n * Per-instance event scope. `EventCore` is a process-global static emitter,\n * so without namespacing every WSTransport would hear every other one's\n * frames. We prefix each event with this transport's `id` and expose\n * `on`/`off`/`emit` that scope transparently — callers still use the plain\n * `EventCoreEvents` enum and only ever see their own connection's events.\n */\n readonly id: string;\n\n readonly emit = (event: EventCoreEvents, data: unknown): void => {\n EventCore.emit(this.scopedEvent(event), data);\n };\n readonly on = (event: EventCoreEvents, handler: EventListener | CallableFunction): void => {\n EventCore.on(this.scopedEvent(event), handler);\n };\n readonly off = (event: EventCoreEvents, handler: EventListener | CallableFunction): void => {\n EventCore.off(this.scopedEvent(event), handler);\n };\n\n private scopedEvent(event: EventCoreEvents): EventCoreEvents {\n return `${this.id}:${event}` as EventCoreEvents;\n }\n\n private url: string;\n private socket: WebSocket | null = null;\n private _isConnected = false;\n private _isConnecting = false;\n\n // Reconnect state\n private autoReconnect: boolean;\n private reconnectDelay: number;\n private maxReconnectAttempts: number;\n private reconnectAttempts = 0;\n private reconnectTimeout: ReturnType<typeof setTimeout> | null = null;\n\n // Outbound queue (raw frame strings — already serialized by caller)\n private outboundQueue: string[] = [];\n private maxQueueSize: number;\n\n // Heartbeat / liveness state\n private heartbeatInterval: number;\n private heartbeatTimeout: number;\n private pingFrame: string;\n private pongFrame: string;\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n private pongTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(opts: WSTransportOptions) {\n super();\n if (!opts || !opts.url) {\n throw new Error(\"WSTransport: `url` is required\");\n }\n this.url = opts.url;\n this.id = opts.id ?? `ws${++__wsInstanceSeq}`;\n this.autoReconnect = opts.autoReconnect ?? true;\n this.reconnectDelay = opts.reconnectDelay ?? 3000;\n this.maxReconnectAttempts = opts.maxReconnectAttempts ?? 5;\n this.maxQueueSize = opts.maxQueueSize ?? 100;\n this.heartbeatInterval = opts.heartbeatInterval ?? 30000;\n this.heartbeatTimeout = opts.heartbeatTimeout ?? 10000;\n this.pingFrame = opts.pingFrame ?? \"ping\";\n this.pongFrame = opts.pongFrame ?? \"pong\";\n }\n\n /** Open the socket. Resolves when CONNECTED fires. Rejects on first error. */\n async connect(): Promise<void> {\n if (this._isConnected || this._isConnecting) {\n throw new Error(\"WSTransport: already connected or connecting\");\n }\n this._isConnecting = true;\n\n return new Promise<void>((resolve, reject) => {\n try {\n const socket = new WebSocket(this.url);\n this.socket = socket;\n\n socket.onopen = () => {\n this._isConnected = true;\n this._isConnecting = false;\n this.reconnectAttempts = 0;\n this.emit(EventCoreEvents.CONNECTED, undefined);\n this.flushQueue();\n this.startHeartbeat();\n resolve();\n };\n\n socket.onmessage = (event: MessageEvent) => {\n // Heartbeat ack — swallow it (don't surface as a MESSAGE) and clear\n // the liveness deadline. The layer above never sees keep-alive frames.\n if (event.data === this.pongFrame) {\n if (this.pongTimer) {\n clearTimeout(this.pongTimer);\n this.pongTimer = null;\n }\n return;\n }\n // Raw inbound frame — layer above is responsible for parsing.\n this.emit(EventCoreEvents.MESSAGE, event.data);\n };\n\n socket.onerror = (err) => {\n this.emit(EventCoreEvents.ERROR, err);\n if (this._isConnecting) {\n this._isConnecting = false;\n reject(err);\n }\n };\n\n socket.onclose = () => {\n const wasConnected = this._isConnected;\n this._isConnected = false;\n this._isConnecting = false;\n this.stopHeartbeat();\n this.emit(EventCoreEvents.DISCONNECTED, undefined);\n if (this.autoReconnect && wasConnected) {\n this.scheduleReconnect();\n }\n };\n } catch (err) {\n this._isConnecting = false;\n reject(err);\n }\n });\n }\n\n /** Close the socket and stop reconnecting. */\n disconnect(): void {\n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n }\n this.stopHeartbeat();\n this.autoReconnect = false;\n if (this.socket) {\n try { this.socket.close(); } catch { /* ignore */ }\n this.socket = null;\n }\n this._isConnected = false;\n this._isConnecting = false;\n }\n\n /**\n * Send a raw frame. If currently disconnected, the frame is queued and sent\n * after the next successful reconnect (up to `maxQueueSize`).\n */\n send(frame: string): void {\n if (this._isConnected && this.socket) {\n this.socket.send(frame);\n return;\n }\n if (this.outboundQueue.length >= this.maxQueueSize) {\n throw new Error(\n `WSTransport: outbound queue full (${this.maxQueueSize}); drop or wait for reconnect`,\n );\n }\n this.outboundQueue.push(frame);\n }\n\n isConnected(): boolean { return this._isConnected; }\n isConnecting(): boolean { return this._isConnecting; }\n queuedFrames(): number { return this.outboundQueue.length; }\n reconnectAttemptCount(): number { return this.reconnectAttempts; }\n\n // -- internals -------------------------------------------------------------\n\n /** Begin the keep-alive loop (no-op when disabled). */\n private startHeartbeat(): void {\n if (this.heartbeatInterval <= 0) return;\n this.stopHeartbeat();\n this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.heartbeatInterval);\n }\n\n /** Stop the keep-alive loop and clear any pending liveness deadline. */\n private stopHeartbeat(): void {\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n if (this.pongTimer) {\n clearTimeout(this.pongTimer);\n this.pongTimer = null;\n }\n }\n\n /**\n * Send one ping and arm a liveness deadline. If no `pongFrame` arrives before\n * `heartbeatTimeout`, the connection is considered dead and we force a\n * reconnect — this is what catches a silently-dropped TCP connection that\n * never fired `onclose` (the failure mode that \"loses connection with the\n * Accelerator\" on long sessions).\n */\n private sendHeartbeat(): void {\n if (!this._isConnected || !this.socket) return;\n try {\n this.socket.send(this.pingFrame);\n } catch {\n this.forceReconnect();\n return;\n }\n // A still-pending deadline means the previous pong never came back.\n if (this.pongTimer) return;\n this.pongTimer = setTimeout(() => {\n this.pongTimer = null;\n this.forceReconnect();\n }, this.heartbeatTimeout);\n }\n\n /**\n * Tear down a connection we believe is dead and kick off reconnect, without\n * waiting on the OS/browser to eventually fire `onclose` (which a half-open\n * socket may never do). We detach the handlers first so the normal close path\n * can't double-fire the reconnect.\n */\n private forceReconnect(): void {\n this.stopHeartbeat();\n const sock = this.socket;\n const wasConnected = this._isConnected;\n this.socket = null;\n this._isConnected = false;\n this._isConnecting = false;\n if (sock) {\n sock.onopen = null;\n sock.onmessage = null;\n sock.onerror = null;\n sock.onclose = null;\n try { sock.close(); } catch { /* already gone */ }\n }\n this.emit(EventCoreEvents.ERROR, new Error(\"WSTransport: heartbeat timeout\"));\n this.emit(EventCoreEvents.DISCONNECTED, undefined);\n if (this.autoReconnect && wasConnected) {\n this.scheduleReconnect();\n }\n }\n\n private scheduleReconnect(): void {\n if (\n this.maxReconnectAttempts > 0 &&\n this.reconnectAttempts >= this.maxReconnectAttempts\n ) {\n this.emit(\n EventCoreEvents.ERROR,\n new Error(\"WSTransport: max reconnect attempts reached\"),\n );\n return;\n }\n this.reconnectAttempts++;\n this.emit(EventCoreEvents.RECONNECTING, { attempt: this.reconnectAttempts });\n this.reconnectTimeout = setTimeout(async () => {\n try {\n await this.connect();\n } catch {\n // scheduleReconnect will fire again from onclose\n }\n }, this.reconnectDelay);\n }\n\n private flushQueue(): void {\n if (this.outboundQueue.length === 0 || !this.socket) return;\n const pending = this.outboundQueue;\n this.outboundQueue = [];\n for (const frame of pending) {\n try {\n this.socket.send(frame);\n } catch {\n // re-queue if a flush fails\n this.outboundQueue.push(frame);\n }\n }\n }\n}\n\nexport default WSTransport;\n","/**\n * `client.kv` — per-user key/value storage backed by the accelerator's personal\n * space.\n *\n * await client.kv.set('todos', id, { title, completed })\n * const todo = await client.kv.get('todos', id)\n * const ids = await client.kv.list('todos')\n * await client.kv.delete('todos', id)\n * const off = client.kv.on('change', e => …) // realtime, cross-device\n *\n * A *collection* is a key namespace within the user's space; the stored key is\n * `${collection}/${id}`. Operations are authorized by the user's session token\n * (stamped on every request by {@link HttpClient}) — no per-op Groth16 proof.\n *\n * Values are encrypted at rest by default ({@link StorageCipher}, an AES-GCM\n * key derived from the ZK identity); pass `{ encrypt: false }` to store\n * plaintext. The realtime feed rides the personal space's websocket over a\n * {@link WSTransport} (heartbeat keep-alive + auto-reconnect, event-namespaced\n * so it doesn't cross wires with chat/space transports).\n *\n * For **files** (blobs), use `client.storage` instead — `client.kv` is for\n * small structured values. `query()` is intentionally deferred.\n */\n\nimport type { HttpClient } from \"../HttpClient\";\nimport type { SessionState } from \"../Session\";\nimport type { ZkIdentity } from \"../../auth/identity\";\nimport { StorageCipher } from \"../../crypto/StorageCipher\";\nimport { WSTransport } from \"../../transport/WSTransport\";\nimport { EventCoreEvents } from \"../../events\";\n\nexport interface KvNamespaceDeps {\n http: HttpClient;\n session: SessionState;\n /** WebSocket base (ws/wss) for the change feed; derived from baseUrl. */\n wsBaseUrl: string;\n}\n\nexport interface SetOptions {\n /** Encrypt the value at rest (default: true). */\n encrypt?: boolean;\n}\n\nexport interface StorageChangeEvent<T = unknown> {\n collection: string;\n id: string;\n type: \"set\" | \"delete\";\n /** The decrypted value for `set`; `null` for `delete`. */\n data: T | null;\n}\n\n/** Raw change frame pushed by `PersonalSpaceDO`'s websocket. */\ninterface ChangeFrame {\n _t: \"change\";\n key: string;\n op: \"set\" | \"delete\";\n value?: unknown;\n}\n\nexport class KvNamespace {\n private cipher: StorageCipher | null = null;\n private cipherIdentity: ZkIdentity | null = null;\n\n constructor(private readonly deps: KvNamespaceDeps) {}\n\n /** Store `value` under `collection`/`id` (encrypted at rest by default). */\n async set<T = unknown>(collection: string, id: string, value: T, opts?: SetOptions): Promise<void> {\n const encrypt = opts?.encrypt !== false;\n const stored = encrypt ? await this.getCipher().encrypt(value) : value;\n await this.deps.http.post(this.kvPath(collection, id), { value: stored });\n }\n\n /** Fetch the value at `collection`/`id`, or `null` if absent. */\n async get<T = unknown>(collection: string, id: string): Promise<T | null> {\n const res = await this.deps.http.post<{ value: unknown }>(\n `${this.kvPath(collection, id)}/get`,\n {},\n );\n return this.decode<T>(res.value);\n }\n\n /** Delete `collection`/`id`. Returns whether the key existed. */\n async delete(collection: string, id: string): Promise<boolean> {\n const res = await this.deps.http.del<{ ok: boolean; existed: boolean }>(\n this.kvPath(collection, id),\n {},\n );\n return Boolean(res.existed);\n }\n\n /** List the ids present in `collection`. */\n async list(collection: string): Promise<string[]> {\n const res = await this.deps.http.post<{ keys: string[] }>(this.spacePath(\"/list\"), {});\n const prefix = `${collection}/`;\n return (res.keys ?? [])\n .filter((k) => k.startsWith(prefix))\n .map((k) => k.slice(prefix.length));\n }\n\n /** Reserved — server-side query is deferred (see the overhaul plan). */\n async query(_collection: string, _filter?: unknown): Promise<never> {\n throw new Error(\"client.kv.query is not implemented yet (deferred in the SDK overhaul).\");\n }\n\n /**\n * Subscribe to realtime changes to this user's data across devices. Opens\n * the personal space's websocket and decrypts each change before handing\n * it to `handler`. Returns an unsubscribe function.\n *\n * Requires a `WebSocket` global (browsers; Node 22+ or a `ws` shim).\n */\n on<T = unknown>(event: \"change\", handler: (e: StorageChangeEvent<T>) => void): () => void {\n if (event !== \"change\") throw new Error(`client.kv: unknown event \"${event}\"`);\n\n if (typeof (globalThis as { WebSocket?: typeof WebSocket }).WebSocket !== \"function\") {\n throw new Error(\"client.kv.on: no `WebSocket` global available in this runtime.\");\n }\n const token = this.deps.session.token;\n if (!token) throw new Error(\"client.kv.on: not signed in.\");\n\n const commitment = this.commitment();\n const url = `${this.deps.wsBaseUrl}/api/personal/${encodeURIComponent(commitment)}/websocket?session=${encodeURIComponent(token)}`;\n\n // Ride a WSTransport rather than a bare socket: it keeps the (otherwise\n // idle) personal-space feed warm with heartbeat pings, auto-reconnects\n // if it drops, and namespaces its events by `id` so this feed never\n // crosses wires with chat/space transports on the shared EventCore bus.\n const transport = new WSTransport({ url, id: `personal:${commitment}` });\n const onMessage = (e: CustomEvent) => {\n void this.dispatchChange<T>(e.detail, handler);\n };\n transport.on(EventCoreEvents.MESSAGE, onMessage);\n // Fire-and-forget: the realtime feed is best-effort, and the transport\n // queues nothing it needs before CONNECTED (server→client only).\n void transport.connect();\n\n return () => {\n transport.off(EventCoreEvents.MESSAGE, onMessage);\n transport.disconnect();\n };\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private async dispatchChange<T>(\n raw: unknown,\n handler: (e: StorageChangeEvent<T>) => void,\n ): Promise<void> {\n let frame: ChangeFrame;\n try {\n frame = typeof raw === \"string\" ? JSON.parse(raw) : raw;\n } catch {\n return;\n }\n if (!frame || frame._t !== \"change\" || typeof frame.key !== \"string\") return;\n\n const slash = frame.key.indexOf(\"/\");\n if (slash < 0) return;\n const collection = frame.key.slice(0, slash);\n const id = frame.key.slice(slash + 1);\n\n const data = frame.op === \"set\" ? await this.decode<T>(frame.value) : null;\n handler({ collection, id, type: frame.op, data });\n }\n\n /** Decode a stored value: decrypt envelopes, pass plaintext through. */\n private async decode<T>(value: unknown): Promise<T | null> {\n if (value == null) return null;\n if (StorageCipher.isEnvelope(value)) return this.getCipher().decrypt<T>(value);\n return value as T;\n }\n\n private commitment(): string {\n const c = this.deps.session.commitment;\n if (!c) throw new Error(\"client.kv: not signed in — call client.auth.zk.login() first.\");\n return c;\n }\n\n private spacePath(suffix: string): string {\n return `/api/personal/${encodeURIComponent(this.commitment())}${suffix}`;\n }\n\n private kvPath(collection: string, id: string): string {\n const key = `${collection}/${id}`;\n return this.spacePath(`/kv/${encodeURIComponent(key)}`);\n }\n\n /** The at-rest cipher for the current identity (re-derived if it changes). */\n private getCipher(): StorageCipher {\n const identity = this.deps.session.requireIdentity();\n if (this.cipher && this.cipherIdentity === identity) return this.cipher;\n this.cipher = new StorageCipher(identity.secretHex, identity.saltHex);\n this.cipherIdentity = identity;\n return this.cipher;\n }\n}\n\nexport default KvNamespace;\n","/**\n * Wire types for the storage layer.\n *\n * The `FileManifest` is the single piece of metadata the system needs to\n * reassemble a file: per-chunk encryption material, RS parameters, and the\n * SHA-256 content hashes of every shard that belongs to the chunk. With the\n * manifest in hand, a reader can pull each shard from the open content-\n * addressed shard store, decode, decrypt, and concatenate to recover the\n * original bytes.\n *\n * The manifest itself lives inside a `SharedSpaceDO` (Phase B) which gates\n * access by ZK proof + ACL. Shards are stored in the open content-addressed\n * `ShardStoreDO` — anyone can put/get any shard, but without the manifest\n * (which has the keys) the ciphertext is just noise.\n */\n\nimport type { ChunkKeyMaterial } from \"../crypto/ChunkCipher\";\n\n/**\n * One chunk's metadata. A file is the concatenation of `chunks` in order.\n *\n * - `originalSize` is the chunk's plaintext length, before AES-GCM expanded\n * it by 16 bytes for the auth tag and before RS padded it for shard\n * alignment.\n * - `ciphertextSize` is the AES-GCM output length (plaintext + 16). This is\n * what the RS decoder trims back to.\n * - `shardHashes` lists every shard's SHA-256 in encoding order — the first\n * `dataShards` are data shards, the trailing `parityShards` are parity.\n */\nexport interface ChunkManifest {\n /** Stable per-chunk ID (uuid-like). Useful for client-side resume / dedup. */\n id: string;\n /** Position of this chunk in the file (0-indexed). */\n chunkIndex: number;\n /** Plaintext byte length of the chunk before encryption. */\n originalSize: number;\n /** AES-GCM ciphertext byte length (originalSize + 16 for the tag). */\n ciphertextSize: number;\n /** Number of RS data shards. */\n dataShards: number;\n /** Number of RS parity shards. */\n parityShards: number;\n /** Length in bytes of every shard (data and parity are equal). */\n shardSize: number;\n /** SHA-256 (hex) of each shard's ciphertext bytes, in shard order. */\n shardHashes: string[];\n /** Per-chunk AES-256-GCM key + IV. Plain in the manifest — gating happens at the SpaceDO. */\n cipher: ChunkKeyMaterial;\n}\n\n/**\n * Top-level manifest for a single stored file. Persisted in the user's\n * SharedSpace by file id; readable / writable per the space's ACL.\n */\nexport interface FileManifest {\n /** Stable file ID. Assigned by the SDK at write time; used to read or delete. */\n id: string;\n /** Human-readable filename (display only — not used by the shard store). */\n name: string;\n /** Total plaintext byte length. Sum of chunk `originalSize`s. */\n size: number;\n /** MIME type the application supplied at write time. Opaque to storage. */\n type: string;\n /** Optional virtual path / folder hint for the application. */\n path?: string;\n /** When the file was last modified per the application (ms epoch). */\n lastModified: number;\n /** When this manifest was created on the SDK side (ms epoch). */\n createdAt: number;\n /** Ordered list of chunks. Concatenate them in index order to rebuild the file. */\n chunks: ChunkManifest[];\n /** SDK schema version. Bump on breaking manifest-shape changes. */\n version: 1;\n}\n\n/**\n * Lightweight summary returned by `FileStorage.writeFile` and surfaced in\n * directory-style listings. The full manifest is only fetched when actually\n * reassembling the file.\n */\nexport interface FileStat {\n id: string;\n name: string;\n size: number;\n type: string;\n path?: string;\n lastModified: number;\n createdAt: number;\n chunkCount: number;\n shardCount: number;\n}\n\n/** Distil a `FileManifest` into a `FileStat`. */\nexport function manifestToStat(manifest: FileManifest): FileStat {\n let shardCount = 0;\n for (const c of manifest.chunks) shardCount += c.shardHashes.length;\n return {\n id: manifest.id,\n name: manifest.name,\n size: manifest.size,\n type: manifest.type,\n path: manifest.path,\n lastModified: manifest.lastModified,\n createdAt: manifest.createdAt,\n chunkCount: manifest.chunks.length,\n shardCount,\n };\n}\n","/**\n * Universal wasm-bindgen glue for `wasm-reed-solomon-erasure` (v0.2.2 — Rust\n * Reed–Solomon erasure-coding library compiled with `wasm-pack --target nodejs`).\n *\n * The upstream npm package ships `wasm_reed_solomon_erasure.js` which uses\n * `require('fs').readFileSync()` to load the WASM file at module load time —\n * that hard-codes Node and breaks browsers / CF Workers. This file is a port\n * of that glue with the Node-only pieces removed:\n *\n * - `TextDecoder` is taken from the global (available in Node 12+, every\n * modern browser, and Workers — no `require('util')`).\n * - The WASM module is loaded via the rollup-inlined `.wasm` import, the\n * same `targetEnv: 'auto-inline'` path the bn128 verifier uses. Works in\n * Node, browser, and Workers without runtime fs access.\n *\n * Only the two public functions consumers actually need (`encode` and\n * `reconstruct`) are exported. The rest is the wbindgen heap-table dance.\n *\n * Encoding:\n * `encode(dataShards: Uint8Array[], parityShard: number)` → array of\n * `dataShards.length + parityShard` Uint8Arrays. The first N are the input\n * shards unchanged; the trailing M are the freshly computed parity shards.\n * All shards are the same length — caller is responsible for padding the\n * data into equal-size data shards.\n *\n * Reconstruction:\n * `reconstruct(corruptedShards, parityShard, deadIndexes)` → fully recovered\n * array. Pass placeholders (empty Uint8Arrays) at the dead indexes; the\n * reconstructor fills them in. Up to `parityShard` shards may be missing.\n */\n\n// The bundled-WASM loader lives in its own module so the `.wasm` static import\n// is only encountered when the fallback path is actually exercised. Tools\n// that can't parse the import (vitest without `vite-plugin-wasm`) can import\n// `rs.ts` cleanly so long as callers always pass a pre-compiled\n// `WebAssembly.Module` to `initRsWasm`.\n//\n// `@rollup/plugin-wasm` (with `targetEnv: 'auto-inline'`) actually returns\n// the result of `WebAssembly.instantiate(buffer, imports)` — which, when\n// called with a `BufferSource`, yields the `{ module, instance }` source\n// pair, NOT a bare `WebAssembly.Instance`. The plugin's own typings claim\n// the latter; treat the result as `unknown` and unwrap defensively below.\ntype BundledLoader = (\n imports?: Record<string, Record<string, unknown>>,\n) => Promise<unknown>;\n\n// ---------------------------------------------------------------------------\n// wbindgen heap-object table\n// ---------------------------------------------------------------------------\n//\n// wbindgen passes JS values to/from WASM by storing them in this JS-side heap\n// and shuttling integer indexes across the boundary. Indexes 0–35 are reserved\n// for runtime constants (`undefined`, `null`, `true`, `false`); 36+ are\n// recyclable slots.\n\nconst heap: unknown[] = new Array(32).fill(undefined);\nheap.push(undefined, null, true, false);\nlet heap_next = heap.length;\n\nfunction getObject(idx: number): unknown {\n return heap[idx];\n}\n\nfunction dropObject(idx: number): void {\n if (idx < 36) return;\n heap[idx] = heap_next;\n heap_next = idx;\n}\n\nfunction takeObject(idx: number): unknown {\n const ret = getObject(idx);\n dropObject(idx);\n return ret;\n}\n\nfunction addHeapObject(obj: unknown): number {\n if (heap_next === heap.length) heap.push(heap.length + 1);\n const idx = heap_next;\n heap_next = heap[idx] as number;\n heap[idx] = obj;\n return idx;\n}\n\n// ---------------------------------------------------------------------------\n// WASM memory views (lazily re-bound when memory.buffer grows on alloc)\n// ---------------------------------------------------------------------------\n\nlet wasm: WasmExports | null = null;\n\nlet cachedUint8: Uint8Array | null = null;\nfunction u8(): Uint8Array {\n if (cachedUint8 === null || cachedUint8.buffer !== wasm!.memory.buffer) {\n cachedUint8 = new Uint8Array(wasm!.memory.buffer);\n }\n return cachedUint8;\n}\n\nlet cachedUint32: Uint32Array | null = null;\nfunction u32(): Uint32Array {\n if (cachedUint32 === null || cachedUint32.buffer !== wasm!.memory.buffer) {\n cachedUint32 = new Uint32Array(wasm!.memory.buffer);\n }\n return cachedUint32;\n}\n\nlet cachedInt32: Int32Array | null = null;\nfunction i32(): Int32Array {\n if (cachedInt32 === null || cachedInt32.buffer !== wasm!.memory.buffer) {\n cachedInt32 = new Int32Array(wasm!.memory.buffer);\n }\n return cachedInt32;\n}\n\nconst textDecoder = new TextDecoder(\"utf-8\", { ignoreBOM: true, fatal: true });\n\n// ---------------------------------------------------------------------------\n// Boundary helpers — moving JS arrays of Uint8Arrays across the FFI\n// ---------------------------------------------------------------------------\n\nlet WASM_VECTOR_LEN = 0;\n\n/**\n * Allocate `array.length * 4` bytes inside the WASM heap and write each\n * element's heap-table index there as a u32. Used to pass `Uint8Array[]` into\n * Rust — wbindgen reads each index back via the `__wbg_*` import callbacks.\n */\nfunction passArrayJsValueToWasm(array: Uint8Array[], malloc: (n: number) => number): number {\n const ptr = malloc(array.length * 4);\n const mem = u32();\n for (let i = 0; i < array.length; i++) {\n mem[ptr / 4 + i] = addHeapObject(array[i]);\n }\n WASM_VECTOR_LEN = array.length;\n return ptr;\n}\n\n/**\n * Pull `len` heap-table indexes from WASM memory starting at `ptr`, take each\n * referenced object, and return them as a plain JS array. The take() consumes\n * the heap slot so it can be reused.\n */\nfunction getArrayJsValueFromWasm(ptr: number, len: number): Uint8Array[] {\n const mem = u32();\n const slice = mem.subarray(ptr / 4, ptr / 4 + len);\n const result: Uint8Array[] = [];\n for (let i = 0; i < slice.length; i++) {\n result.push(takeObject(slice[i]) as Uint8Array);\n }\n return result;\n}\n\nfunction getStringFromWasm(ptr: number, len: number): string {\n return textDecoder.decode(u8().subarray(ptr, ptr + len));\n}\n\n// ---------------------------------------------------------------------------\n// WASM module typings + initialization\n// ---------------------------------------------------------------------------\n\ninterface WasmExports {\n memory: WebAssembly.Memory;\n encode: (retptr: number, ptr: number, len: number, parity: number) => void;\n reconstruct: (retptr: number, ptr: number, len: number, parity: number, deadIdx: number) => void;\n __wbindgen_add_to_stack_pointer: (n: number) => number;\n __wbindgen_malloc: (n: number) => number;\n __wbindgen_free: (ptr: number, size: number) => void;\n}\n\n/**\n * The wbindgen import object — every callback Rust expects from JS. Names are\n * hard-coded by wasm-bindgen based on the Rust function signatures; do not\n * rename. If the upstream package is regenerated, these may drift and need\n * resyncing with the new `wasm_reed_solomon_erasure.js`.\n */\nfunction buildImports(): WebAssembly.Imports {\n const wbindgen: Record<string, (...args: number[]) => number | void> = {\n __wbindgen_object_drop_ref: (arg0: number) => {\n takeObject(arg0);\n },\n __wbg_buffer_7af23f65f6c64548: (arg0: number) => {\n const ret = (getObject(arg0) as Uint8Array).buffer;\n return addHeapObject(ret);\n },\n __wbg_newwithbyteoffsetandlength_ce1e75f0ce5f7974: (arg0: number, arg1: number, arg2: number) => {\n const ret = new Uint8Array(getObject(arg0) as ArrayBuffer, arg1 >>> 0, arg2 >>> 0);\n return addHeapObject(ret);\n },\n __wbg_new_cc9018bd6f283b6f: (arg0: number) => {\n const ret = new Uint8Array(getObject(arg0) as ArrayBuffer);\n return addHeapObject(ret);\n },\n __wbg_set_f25e869e4565d2a2: (arg0: number, arg1: number, arg2: number) => {\n (getObject(arg0) as Uint8Array).set(getObject(arg1) as Uint8Array, arg2 >>> 0);\n },\n __wbg_length_0acb1cf9bbaf8519: (arg0: number) => {\n return (getObject(arg0) as Uint8Array).length;\n },\n __wbg_new_e8c5277c0f9e2cfc: (arg0: number) => {\n const ret = new Uint32Array(getObject(arg0) as ArrayBuffer);\n return addHeapObject(ret);\n },\n __wbg_set_03c7d8c063f469ef: (arg0: number, arg1: number, arg2: number) => {\n (getObject(arg0) as Uint32Array).set(getObject(arg1) as Uint32Array, arg2 >>> 0);\n },\n __wbg_length_f98ca60981480796: (arg0: number) => {\n return (getObject(arg0) as Uint32Array).length;\n },\n __wbindgen_throw: (arg0: number, arg1: number) => {\n throw new Error(getStringFromWasm(arg0, arg1));\n },\n __wbindgen_memory: () => {\n return addHeapObject(wasm!.memory);\n },\n };\n return { __wbindgen_placeholder__: wbindgen as unknown as WebAssembly.ModuleImports };\n}\n\nlet _readyPromise: Promise<void> | null = null;\n\n/**\n * Load and instantiate the WASM module. Idempotent — repeated calls await the\n * same one-shot promise.\n *\n * Two ways to initialize, matching the pattern used by `workers/groth16-verifier`:\n * 1. `await initRsWasm()` — uses the bundled .wasm (base64-inlined at build\n * time by `@rollup/plugin-wasm`). Works in any runtime that allows\n * runtime `WebAssembly.compile()`.\n * 2. `await initRsWasm(myWasmModule)` — accepts a pre-compiled\n * `WebAssembly.Module`. Useful when the bundled loader path isn't\n * available (vitest, CF Workers wanting deploy-time precompile, etc.).\n */\nexport async function initRsWasm(wasmModule?: WebAssembly.Module): Promise<void> {\n if (_readyPromise) return _readyPromise;\n _readyPromise = (async () => {\n const imports = buildImports();\n let instance: WebAssembly.Instance;\n if (wasmModule) {\n // `instantiate(module, imports)` returns a bare Instance.\n instance = await WebAssembly.instantiate(wasmModule, imports);\n } else {\n // Defer the `.wasm` import to a separate module so vitest can load\n // `rs.ts` without it. Production callers either don't pass a\n // module (and hit the bundled loader here) or pass one explicitly.\n const bundled = (await import(\"./bundled-loader\")).default as BundledLoader;\n const result = await bundled(imports as Record<string, Record<string, unknown>>);\n // The bundled loader's actual return type is\n // `{ module: WebAssembly.Module, instance: WebAssembly.Instance }`\n // — the rollup-plugin-wasm shape from `WebAssembly.instantiate(buffer, imports)`.\n // Older versions (or future changes) may return a bare Instance,\n // so accept either shape.\n instance = unwrapInstance(result);\n }\n wasm = instance.exports as unknown as WasmExports;\n })();\n return _readyPromise;\n}\n\n/**\n * Normalize the value returned by `WebAssembly.instantiate` / the\n * rollup-plugin-wasm loader into a bare `WebAssembly.Instance`. Handles\n * both the `(module, imports)` overload (returns Instance) and the\n * `(buffer, imports)` overload (returns `{ module, instance }`).\n */\nfunction unwrapInstance(result: unknown): WebAssembly.Instance {\n if (result && typeof result === \"object\") {\n const candidate = result as { instance?: WebAssembly.Instance; exports?: unknown };\n if (candidate.instance && typeof candidate.instance === \"object\" && \"exports\" in candidate.instance) {\n return candidate.instance;\n }\n if (\"exports\" in candidate) {\n return result as WebAssembly.Instance;\n }\n }\n throw new Error(\n \"rs.ts: bundled WASM loader returned an unrecognized shape — expected WebAssembly.Instance or { module, instance }\",\n );\n}\n\n/**\n * Reset the singleton (test-only escape hatch). Lets a test load a different\n * pre-compiled module without restarting the process. Production code should\n * never need this.\n */\nexport function _resetRsWasmForTests(): void {\n _readyPromise = null;\n wasm = null;\n cachedUint8 = null;\n cachedUint32 = null;\n cachedInt32 = null;\n}\n\nfunction ensureReady(): void {\n if (!wasm) {\n throw new Error(\"rs.ts: WASM not initialized. Call `await initRsWasm()` first.\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public API — encode + reconstruct\n// ---------------------------------------------------------------------------\n\n/**\n * Encode the input data shards with `parityShard` parity shards. All input\n * shards must be Uint8Arrays of equal length; output contains the input shards\n * unchanged plus `parityShard` newly computed parity shards.\n */\nexport function encode(dataShards: Uint8Array[], parityShard: number): Uint8Array[] {\n ensureReady();\n const w = wasm!;\n try {\n const retptr = w.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm(dataShards, w.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n w.encode(retptr, ptr0, len0, parityShard);\n const r0 = i32()[retptr / 4 + 0];\n const r1 = i32()[retptr / 4 + 1];\n const v1 = getArrayJsValueFromWasm(r0, r1).slice();\n w.__wbindgen_free(r0, r1 * 4);\n return v1;\n } finally {\n w.__wbindgen_add_to_stack_pointer(16);\n }\n}\n\n/**\n * Reconstruct the original full shard array. `corruptedShards` is the full\n * list (data + parity) with placeholder Uint8Arrays at positions listed in\n * `deadShardIndexes`. Returns the recovered, complete list of shards.\n *\n * Up to `parityShard` shards may be missing; more than that is uncorrectable\n * and the underlying WASM throws.\n */\nexport function reconstruct(\n corruptedShards: Uint8Array[],\n parityShard: number,\n deadShardIndexes: Uint32Array,\n): Uint8Array[] {\n ensureReady();\n const w = wasm!;\n try {\n const retptr = w.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm(corruptedShards, w.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n w.reconstruct(retptr, ptr0, len0, parityShard, addHeapObject(deadShardIndexes));\n const r0 = i32()[retptr / 4 + 0];\n const r1 = i32()[retptr / 4 + 1];\n const v1 = getArrayJsValueFromWasm(r0, r1).slice();\n w.__wbindgen_free(r0, r1 * 4);\n return v1;\n } finally {\n w.__wbindgen_add_to_stack_pointer(16);\n }\n}\n","/**\n * Reed–Solomon erasure-coding codec.\n *\n * Wraps the WASM-backed `encode` / `reconstruct` primitives in `wasm/rs.ts`\n * with shard-padding bookkeeping so callers can hand it any-length input and\n * get back uniform-size shards.\n *\n * Usage:\n * const codec = new ReedSolomonCodec();\n * await codec.ready();\n * const { shards, shardSize, originalSize } = codec.encode(plaintext, 4, 2);\n * // 6 shards (4 data + 2 parity), each `shardSize` bytes\n * // …ship them, lose up to 2, then …\n * const recovered = codec.decode(shards, 2, deadIndexes, originalSize);\n *\n * Why the explicit `originalSize`: RS pads input to make every data shard the\n * same length. The decoder must trim that padding back off after recovery.\n * The caller is responsible for stashing `originalSize` somewhere durable\n * (the file manifest, in this codebase).\n */\n\nimport { initRsWasm, encode as wasmEncode, reconstruct as wasmReconstruct } from \"./wasm/rs\";\n\nexport interface EncodeResult {\n /** All `dataShards + parityShards` shards. All have length `shardSize`. */\n shards: Uint8Array[];\n /** Length of every shard (data and parity). */\n shardSize: number;\n /** Length of the original input before padding. Needed to trim on decode. */\n originalSize: number;\n /** How many of the leading shards are data (the rest are parity). */\n dataShards: number;\n /** How many parity shards trail the data shards. */\n parityShards: number;\n}\n\nexport class ReedSolomonCodec {\n /**\n * Resolves once the WASM module is loaded; safe to call repeatedly.\n *\n * Pass `wasmModule` to use a pre-compiled module (e.g. in tests where the\n * rollup-inlined loader path isn't available, or in CF Workers where you\n * want to load the module at deploy time). Default path uses the bundled\n * base64-inlined wasm — works in Node, browsers, and Workers.\n */\n ready(wasmModule?: WebAssembly.Module): Promise<void> {\n return initRsWasm(wasmModule);\n }\n\n /**\n * Split `data` into `dataShards` equal-size chunks (zero-padded to fit),\n * compute `parityShards` parity shards, and return all of them.\n */\n encode(data: Uint8Array, dataShards: number, parityShards: number): EncodeResult {\n if (dataShards < 1) throw new Error(\"ReedSolomonCodec.encode: dataShards must be >= 1\");\n if (parityShards < 1) throw new Error(\"ReedSolomonCodec.encode: parityShards must be >= 1\");\n if (data.length === 0) throw new Error(\"ReedSolomonCodec.encode: data is empty\");\n\n // The wbindgen-generated WASM in `wasm-reed-solomon-erasure@0.2.2` takes\n // the `parity_shard` count separately and infers `total = data.length +\n // parity_shard`. Every shard must be the same length, so we pad the\n // input to `dataShards * shardSize` with trailing zeros.\n const shardSize = Math.ceil(data.length / dataShards);\n const splitInputs: Uint8Array[] = [];\n for (let i = 0; i < dataShards; i++) {\n // Each shard is its own backing ArrayBuffer so the WASM side\n // doesn't observe overlapping views (which would confuse the\n // wbindgen length lookups).\n const shard = new Uint8Array(shardSize);\n const start = i * shardSize;\n const end = Math.min(start + shardSize, data.length);\n if (start < data.length) {\n shard.set(data.subarray(start, end));\n }\n splitInputs.push(shard);\n }\n\n const shards = wasmEncode(splitInputs, parityShards);\n // The underlying call returns N+M shards; first N are the (padded)\n // data shards we just sent in, last M are the parity shards.\n return {\n shards,\n shardSize,\n originalSize: data.length,\n dataShards,\n parityShards,\n };\n }\n\n /**\n * Reconstruct the original `data` from `shards`. Up to `parityShards`\n * shards may be missing; for each missing shard, pass an empty\n * `Uint8Array` placeholder at its position and list the position in\n * `deadShardIndexes`.\n *\n * `originalSize` is required so the trailing zero-padding can be trimmed.\n */\n decode(\n shards: Uint8Array[],\n parityShards: number,\n deadShardIndexes: number[],\n originalSize: number,\n ): Uint8Array {\n if (parityShards < 1) throw new Error(\"ReedSolomonCodec.decode: parityShards must be >= 1\");\n if (shards.length <= parityShards) {\n throw new Error(\"ReedSolomonCodec.decode: shards.length must be > parityShards\");\n }\n if (deadShardIndexes.length > parityShards) {\n throw new Error(\n `ReedSolomonCodec.decode: too many missing shards (${deadShardIndexes.length} > ${parityShards})`,\n );\n }\n\n const dataShards = shards.length - parityShards;\n const recovered =\n deadShardIndexes.length === 0\n ? shards\n : wasmReconstruct(shards, parityShards, new Uint32Array(deadShardIndexes));\n\n // Concatenate the leading `dataShards`, then trim padding back off.\n const shardSize = recovered[0]?.length ?? 0;\n const out = new Uint8Array(dataShards * shardSize);\n for (let i = 0; i < dataShards; i++) {\n out.set(recovered[i], i * shardSize);\n }\n return out.subarray(0, originalSize);\n }\n}\n\nexport default ReedSolomonCodec;\n","/**\n * HTTP client for the open content-addressed shard store.\n *\n * Each shard is named by the lowercase hex SHA-256 of its ciphertext bytes.\n * The server verifies the hash on PUT, so the address authenticates the\n * contents — there's no benefit to ACLing PUT/GET, and making them open\n * enables cross-user dedup down the line.\n *\n * Wire protocol:\n * PUT /api/shards/:hash body: shard bytes (application/octet-stream)\n * 200 { ok: true, hash, size, dedup: boolean }\n * 400 if hash doesn't match body\n *\n * GET /api/shards/:hash 200 with shard bytes (application/octet-stream)\n * 404 if absent\n *\n * HEAD /api/shards/:hash 200 if present (no body) — used by callers to\n * skip a PUT they'd otherwise dedup-rewrite. The\n * server can ignore the optimization if it wants.\n */\n\nimport { toHex } from \"../../utilities/bytes\";\n\nexport interface ShardClientOptions {\n /** Base URL of the accelerator (e.g. `https://muhkoo-accelerator.workers.dev`). */\n baseUrl: string;\n /**\n * Path prefix for the shard endpoints, joined to `baseUrl` before the\n * hash. Defaults to `/api/shards`, which targets a global shard store\n * (e.g. a dedicated `ShardStoreDO`). Pass a room-scoped value like\n * `/api/spaces/{roomId}/shards` to keep shards bound to a specific\n * `SharedSpaceDO` — that's the path the chat application uses today.\n *\n * Leading slash optional; trailing slash stripped. The final URL is\n * always `${baseUrl}${normalizedPrefix}/${encodeURIComponent(hash)}`.\n */\n pathPrefix?: string;\n /**\n * Optional custom fetch implementation. Defaults to `globalThis.fetch`.\n * Provided so callers can inject retries / auth / instrumentation.\n */\n fetch?: typeof fetch;\n}\n\n/**\n * Compute the lowercase hex SHA-256 of `bytes`. Available via WebCrypto in\n * every runtime this SDK targets.\n */\nexport async function shardHash(bytes: Uint8Array): Promise<string> {\n const subtle = (globalThis.crypto as Crypto | undefined)?.subtle;\n if (!subtle) {\n throw new Error(\"shardHash: `globalThis.crypto.subtle` is unavailable in this runtime.\");\n }\n const digest = await subtle.digest(\"SHA-256\", bytes as BufferSource);\n return toHex(new Uint8Array(digest));\n}\n\nexport class ShardClient {\n private readonly baseUrl: string;\n private readonly pathPrefix: string;\n private readonly fetchFn: typeof fetch;\n\n constructor(opts: ShardClientOptions) {\n if (!opts?.baseUrl) throw new Error(\"ShardClient: `baseUrl` is required\");\n // Strip trailing slash so url concatenation stays clean.\n this.baseUrl = opts.baseUrl.replace(/\\/+$/, \"\");\n // Normalize prefix to leading-slash + no-trailing-slash form so the\n // URL builder can blindly append `/{hash}`.\n const rawPrefix = opts.pathPrefix ?? \"/api/shards\";\n const withSlash = rawPrefix.startsWith(\"/\") ? rawPrefix : `/${rawPrefix}`;\n this.pathPrefix = withSlash.replace(/\\/+$/, \"\");\n const f = opts.fetch ?? globalThis.fetch;\n if (typeof f !== \"function\") {\n throw new Error(\"ShardClient: `globalThis.fetch` is unavailable; pass an explicit fetch.\");\n }\n this.fetchFn = f.bind(globalThis);\n }\n\n /** Build the URL for a given shard hash — exposed for callers that want to log or pre-resolve. */\n urlForHash(hash: string): string {\n return `${this.baseUrl}${this.pathPrefix}/${encodeURIComponent(hash)}`;\n }\n\n /**\n * Upload a shard. The server verifies SHA-256(body) matches `:hash` and\n * rejects with 400 if not, so the caller is the source of truth on\n * naming. Re-uploading an existing shard is idempotent — the server\n * returns `dedup: true` in that case.\n */\n async putShard(hash: string, bytes: Uint8Array): Promise<{ dedup: boolean }> {\n const url = this.urlForHash(hash);\n const response = await this.fetchFn(url, {\n method: \"PUT\",\n headers: { \"content-type\": \"application/octet-stream\" },\n // BufferSource is what fetch's body expects; a Uint8Array satisfies it.\n body: bytes as BodyInit,\n });\n if (!response.ok) {\n const text = await safeText(response);\n throw new Error(`ShardClient.putShard(${hash}) failed (${response.status}): ${text}`);\n }\n let dedup = false;\n try {\n const json = (await response.json()) as { dedup?: boolean };\n dedup = Boolean(json?.dedup);\n } catch {\n // Server returned 200 with no body — treat as fresh upload.\n }\n return { dedup };\n }\n\n /**\n * Fetch a shard by hash. Throws if the server returns a non-200; returns\n * `null` for 404 so callers can distinguish \"missing\" from \"errored\".\n */\n async getShard(hash: string): Promise<Uint8Array | null> {\n const url = this.urlForHash(hash);\n const response = await this.fetchFn(url, { method: \"GET\" });\n if (response.status === 404) return null;\n if (!response.ok) {\n const text = await safeText(response);\n throw new Error(`ShardClient.getShard(${hash}) failed (${response.status}): ${text}`);\n }\n const buf = await response.arrayBuffer();\n return new Uint8Array(buf);\n }\n\n /**\n * Check whether a shard exists. Lets the caller skip a PUT they'd otherwise\n * dedup-rewrite. The server can implement this as a HEAD or return a small\n * JSON body — we don't depend on either.\n */\n async hasShard(hash: string): Promise<boolean> {\n const url = this.urlForHash(hash);\n const response = await this.fetchFn(url, { method: \"HEAD\" });\n return response.status === 200;\n }\n}\n\nasync function safeText(response: Response): Promise<string> {\n try { return await response.text(); } catch { return \"\"; }\n}\n","/**\n * `FileStorage` — top-level entry point for chunked, encrypted, erasure-coded\n * file storage.\n *\n * Pipeline for writing a file:\n * 1. Split the plaintext into fixed-size chunks (default 4 MiB).\n * 2. For each chunk:\n * a. Generate a fresh AES-256-GCM key + 12-byte IV (`ChunkCipher`).\n * b. Encrypt the chunk → ciphertext (plaintext.length + 16 bytes tag).\n * c. Reed–Solomon encode the ciphertext into `dataShards + parityShards`\n * equal-length shards (`ReedSolomonCodec`).\n * d. PUT every shard to the content-addressed shard store, keyed by\n * SHA-256 of the shard bytes (`ShardClient`).\n * 3. Build a `FileManifest` listing every chunk's keys, IVs, sizes, and\n * the SHA-256 of every shard in order.\n *\n * Two ways to use the manifest:\n * - {@link FileStorage.writeFileToShards} returns it to the caller, who is\n * then responsible for delivering it to readers (e.g. by E2E-encrypting\n * it as a chat message). The chat application takes this path.\n * - {@link FileStorage.writeFile} additionally POSTs the manifest to a\n * gated multi-user space (`SharedSpaceClient`) so any participant of the\n * space can read the file by manifest id later.\n *\n * Reading is the inverse: {@link FileStorage.readFileFromShards} takes a\n * manifest and reassembles the plaintext; {@link FileStorage.readFile} first\n * fetches the manifest from the space.\n */\n\nimport type { FileManifest, FileStat, ChunkManifest } from \"./types\";\nimport { manifestToStat } from \"./types\";\nimport { ChunkCipher } from \"../crypto/ChunkCipher\";\nimport type { ChunkKeyMaterial } from \"../crypto/ChunkCipher\";\nimport { ReedSolomonCodec } from \"./encoding\";\nimport { ShardClient, shardHash } from \"./transport/ShardClient\";\nimport { SharedSpaceClient } from \"./transport/SharedSpaceClient\";\nimport { generateId } from \"../utilities\";\n\nexport interface FileStorageOptions {\n /** Talks to the content-addressed shard store. Always required. */\n shards: ShardClient;\n /**\n * Talks to the gated multi-user space holding manifests + ACLs.\n * Optional — only required by {@link FileStorage.writeFile} /\n * {@link FileStorage.readFile} / {@link FileStorage.deleteFile} /\n * {@link FileStorage.listFiles} / {@link FileStorage.readManifest}.\n *\n * Callers that ship the manifest themselves (e.g. via an encrypted chat\n * message) can omit `space` and use the `*FromShards` / `*ToShards`\n * methods directly.\n */\n space?: SharedSpaceClient;\n /**\n * Plaintext chunk size in bytes. After encryption each chunk gains 16\n * bytes (GCM tag); after RS encoding the size is rounded up to a multiple\n * of `dataShards` per chunk. Default 4 MiB — a balance between\n * round-trip cost and parallelism on the upload path.\n */\n chunkSize?: number;\n /** RS data shards per chunk (default 4). */\n dataShards?: number;\n /** RS parity shards per chunk (default 2). */\n parityShards?: number;\n /**\n * Cap on concurrent shard uploads / downloads. Tune for the network. The\n * default of 8 saturates most home connections without overwhelming the\n * server's per-IP rate limiter.\n */\n concurrency?: number;\n /**\n * Optional pre-compiled RS WebAssembly module. Defaults to the bundled\n * loader. Pass this in environments where the bundled loader path isn't\n * available (vitest, deploy-time-precompiled CF Workers).\n */\n rsWasmModule?: WebAssembly.Module;\n}\n\n/**\n * Input to {@link FileStorage.writeFile} (which writes the manifest to a\n * `SharedSpaceClient`). Carries the destination `spaceId`.\n */\nexport interface WriteFileInput extends WriteToShardsInput {\n /** Space to write the manifest to — must allow the caller `write`. */\n spaceId: string;\n}\n\n/**\n * Input to {@link FileStorage.writeFileToShards} (which doesn't write a\n * manifest anywhere — that's the caller's job).\n */\nexport interface WriteToShardsInput {\n /** Raw data, a Blob, or a File. */\n data: Uint8Array | Blob | File;\n /** Application-supplied display metadata. */\n metadata: {\n name: string;\n type: string;\n path?: string;\n lastModified?: number;\n };\n /**\n * Optional pre-allocated file id. Defaults to a fresh one. Useful for\n * resumable uploads: the same id always maps to the same manifest slot.\n */\n fileId?: string;\n}\n\nexport class FileStorage {\n private readonly space: SharedSpaceClient | undefined;\n private readonly shards: ShardClient;\n private readonly chunkSize: number;\n private readonly dataShards: number;\n private readonly parityShards: number;\n private readonly concurrency: number;\n private readonly cipher = new ChunkCipher();\n private readonly codec = new ReedSolomonCodec();\n private readonly rsWasmModule?: WebAssembly.Module;\n\n constructor(opts: FileStorageOptions) {\n if (!opts?.shards) throw new Error(\"FileStorage: `shards` (ShardClient) is required\");\n\n this.space = opts.space;\n this.shards = opts.shards;\n this.chunkSize = opts.chunkSize ?? 4 * 1024 * 1024;\n this.dataShards = opts.dataShards ?? 4;\n this.parityShards = opts.parityShards ?? 2;\n this.concurrency = Math.max(1, opts.concurrency ?? 8);\n this.rsWasmModule = opts.rsWasmModule;\n\n if (this.chunkSize < 1) throw new Error(\"FileStorage: chunkSize must be >= 1 byte\");\n if (this.dataShards < 1) throw new Error(\"FileStorage: dataShards must be >= 1\");\n if (this.parityShards < 1) throw new Error(\"FileStorage: parityShards must be >= 1\");\n }\n\n // -------------------------------------------------------------------------\n // Shard-only pipeline — the caller owns the manifest. Used by chat file\n // sharing, where the manifest rides as an E2E-encrypted chat message.\n // -------------------------------------------------------------------------\n\n /**\n * Chunk → encrypt → encode → upload-shards. Returns the resulting manifest\n * along with a `FileStat` summary. The caller is responsible for storing\n * or transmitting the manifest however it likes.\n */\n async writeFileToShards(\n input: WriteToShardsInput,\n ): Promise<{ manifest: FileManifest; stat: FileStat }> {\n await this.codec.ready(this.rsWasmModule);\n\n const data = await toUint8Array(input.data);\n const fileId = input.fileId ?? generateId();\n const createdAt = Date.now();\n const chunks: ChunkManifest[] = [];\n\n // Slicing + encrypting + encoding + uploading is done per-chunk so\n // the peak memory footprint stays at ~chunkSize even for huge files.\n // Within a chunk, the shard uploads are parallelized up to\n // `this.concurrency`.\n for (let chunkIndex = 0; chunkIndex * this.chunkSize < Math.max(1, data.length); chunkIndex++) {\n const start = chunkIndex * this.chunkSize;\n const end = Math.min(start + this.chunkSize, data.length);\n const plaintext = data.subarray(start, end);\n chunks.push(await this.writeChunk(plaintext, chunkIndex));\n // Stop after one iteration if the file is empty — we still emit a\n // single zero-length chunk so the manifest has a stable shape.\n if (data.length === 0) break;\n }\n\n const manifest: FileManifest = {\n id: fileId,\n name: input.metadata.name,\n size: data.length,\n type: input.metadata.type,\n path: input.metadata.path,\n lastModified: input.metadata.lastModified ?? createdAt,\n createdAt,\n chunks,\n version: 1,\n };\n\n return { manifest, stat: manifestToStat(manifest) };\n }\n\n /**\n * Inverse of {@link writeFileToShards}. Takes a manifest the caller\n * obtained somehow (chat message, share link, etc.) and reassembles the\n * plaintext. Throws if too many shards are missing or any chunk's auth\n * tag fails.\n */\n async readFileFromShards(\n manifest: FileManifest,\n ): Promise<{ data: Uint8Array; stat: FileStat }> {\n await this.codec.ready(this.rsWasmModule);\n\n // Materialize each chunk into plaintext, then concatenate. We don't\n // stream across chunks here because the consuming surface returns\n // `Uint8Array`; a streaming variant would reuse `readChunk` unchanged.\n const plaintextChunks: Uint8Array[] = [];\n for (const chunkManifest of [...manifest.chunks].sort((a, b) => a.chunkIndex - b.chunkIndex)) {\n plaintextChunks.push(await this.readChunk(chunkManifest));\n }\n let total = 0;\n for (const c of plaintextChunks) total += c.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const c of plaintextChunks) {\n out.set(c, offset);\n offset += c.length;\n }\n return { data: out, stat: manifestToStat(manifest) };\n }\n\n // -------------------------------------------------------------------------\n // Space-backed convenience wrappers — encrypt + upload + write manifest.\n // Require a `SharedSpaceClient` to have been provided at construction.\n // -------------------------------------------------------------------------\n\n /** As {@link writeFileToShards}, plus POSTs the manifest to `input.spaceId`. */\n async writeFile(input: WriteFileInput): Promise<FileStat> {\n const space = this.requireSpace(\"writeFile\");\n const { manifest, stat } = await this.writeFileToShards(input);\n await space.writeFileManifest(input.spaceId, manifest);\n return stat;\n }\n\n /** As {@link readFileFromShards}, but fetches the manifest from a space first. */\n async readFile(spaceId: string, fileId: string): Promise<{ data: Uint8Array; stat: FileStat }> {\n const space = this.requireSpace(\"readFile\");\n const manifest = await space.readFileManifest(spaceId, fileId);\n return await this.readFileFromShards(manifest);\n }\n\n /**\n * Delete the manifest from a space. **Does not GC the shards** — those\n * are content-addressed and may be referenced by other manifests.\n * Garbage collection is a separate server-side concern (Phase D / D-ish).\n */\n async deleteFile(spaceId: string, fileId: string): Promise<boolean> {\n const space = this.requireSpace(\"deleteFile\");\n return space.deleteFileManifest(spaceId, fileId);\n }\n\n /** Convenience pass-through. */\n async listFiles(spaceId: string): Promise<FileStat[]> {\n const space = this.requireSpace(\"listFiles\");\n return space.listFiles(spaceId);\n }\n\n /** Read a manifest verbatim — useful for \"share file\" / export flows. */\n async readManifest(spaceId: string, fileId: string): Promise<FileManifest> {\n const space = this.requireSpace(\"readManifest\");\n return space.readFileManifest(spaceId, fileId);\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private requireSpace(operation: string): SharedSpaceClient {\n if (!this.space) {\n throw new Error(\n `FileStorage.${operation}: a SharedSpaceClient is required for this operation ` +\n \"(constructor was called without `space`)\",\n );\n }\n return this.space;\n }\n\n /** Encrypt + encode + upload one chunk; return its manifest entry. */\n private async writeChunk(plaintext: Uint8Array, chunkIndex: number): Promise<ChunkManifest> {\n const keyMaterial: ChunkKeyMaterial = this.cipher.generateKeyMaterial();\n const ciphertext =\n plaintext.length === 0\n ? new Uint8Array(0)\n : await this.cipher.encryptChunk(plaintext, keyMaterial);\n\n // An empty chunk encodes to nothing — emit a manifest entry with no\n // shards so the reader can re-emit an empty plaintext and skip the\n // shard round-trip.\n if (ciphertext.length === 0) {\n return {\n id: generateId(),\n chunkIndex,\n originalSize: 0,\n ciphertextSize: 0,\n dataShards: this.dataShards,\n parityShards: this.parityShards,\n shardSize: 0,\n shardHashes: [],\n cipher: keyMaterial,\n };\n }\n\n const encoded = this.codec.encode(ciphertext, this.dataShards, this.parityShards);\n const hashes = await Promise.all(encoded.shards.map((s) => shardHash(s)));\n await this.runWithConcurrency(\n encoded.shards.map((bytes, i) => async () => {\n await this.shards.putShard(hashes[i], bytes);\n }),\n );\n\n return {\n id: generateId(),\n chunkIndex,\n originalSize: plaintext.length,\n ciphertextSize: ciphertext.length,\n dataShards: encoded.dataShards,\n parityShards: encoded.parityShards,\n shardSize: encoded.shardSize,\n shardHashes: hashes,\n cipher: keyMaterial,\n };\n }\n\n /** Inverse of `writeChunk`. */\n private async readChunk(manifest: ChunkManifest): Promise<Uint8Array> {\n if (manifest.shardHashes.length === 0) {\n // Empty chunk fast path.\n return new Uint8Array(0);\n }\n\n // Fetch shards in parallel. Anything missing becomes a placeholder so\n // the decoder can fill it in from the parity shards (up to\n // `parityShards` allowed).\n const fetched = new Array<Uint8Array | null>(manifest.shardHashes.length);\n await this.runWithConcurrency(\n manifest.shardHashes.map((hash, i) => async () => {\n fetched[i] = await this.shards.getShard(hash);\n }),\n );\n\n const deadIndexes: number[] = [];\n const shards: Uint8Array[] = fetched.map((bytes, i) => {\n if (bytes === null) {\n deadIndexes.push(i);\n return new Uint8Array(manifest.shardSize);\n }\n if (bytes.length !== manifest.shardSize) {\n throw new Error(\n `FileStorage: shard ${manifest.shardHashes[i]} has wrong size ` +\n `(got ${bytes.length}, expected ${manifest.shardSize})`,\n );\n }\n return bytes;\n });\n\n if (deadIndexes.length > manifest.parityShards) {\n throw new Error(\n `FileStorage: chunk ${manifest.id} unrecoverable — ${deadIndexes.length} shards missing, ` +\n `only ${manifest.parityShards} tolerated`,\n );\n }\n\n const ciphertextPadded = this.codec.decode(\n shards,\n manifest.parityShards,\n deadIndexes,\n manifest.ciphertextSize,\n );\n return await this.cipher.decryptChunk(ciphertextPadded, manifest.cipher);\n }\n\n /** Run `tasks` with at most `this.concurrency` in flight. */\n private async runWithConcurrency(tasks: Array<() => Promise<void>>): Promise<void> {\n let cursor = 0;\n const concurrency = this.concurrency;\n async function nextWorker(): Promise<void> {\n while (cursor < tasks.length) {\n const idx = cursor++;\n await tasks[idx]();\n }\n }\n const workers = new Array(Math.min(concurrency, tasks.length))\n .fill(null)\n .map(() => nextWorker());\n await Promise.all(workers);\n }\n}\n\n/** Normalize `data` to a flat `Uint8Array`. */\nasync function toUint8Array(data: Uint8Array | Blob | File): Promise<Uint8Array> {\n if (data instanceof Uint8Array) return data;\n // Blob covers File too (File extends Blob in every runtime we target).\n const ab = await data.arrayBuffer();\n return new Uint8Array(ab);\n}\n\nexport default FileStorage;\n","/**\n * HTTP client for the gated file-manifest store on a SharedSpace\n * (`/api/spaces/:spaceId/files`).\n *\n * A \"file\" in a space is its **manifest** (per-chunk keys + the SHA-256 of each\n * global shard). The shard bytes live in the open `/api/shards` store; the\n * manifest is the capability. This client only moves manifests in/out of the\n * space's gated store.\n *\n * Authorization is **session-based**, consistent with the rest of the\n * SharedSpace (keyring, websocket): the SDK's credential-stamping `fetch`\n * (from {@link HttpClient}) attaches the app key + session token, the platform\n * validates the session and injects a trusted `X-Muhkoo-User-Context`, and the\n * DO authorizes on that + channel membership. There is no per-op Groth16 proof.\n *\n * Wire protocol (server: `SharedSpaceDO`):\n * POST /api/spaces/:spaceId/files body: { manifest } → { ok, fileId }\n * GET /api/spaces/:spaceId/files → { files: FileStat[] }\n * GET /api/spaces/:spaceId/files/:fileId → { manifest }\n * DELETE /api/spaces/:spaceId/files/:fileId → { ok, existed }\n */\n\nimport type { FileManifest, FileStat } from \"../types\";\n\nexport interface SharedSpaceClientOptions {\n /** Base URL of the accelerator (e.g. `https://api.muhkoo.dev`). */\n baseUrl: string;\n /**\n * Credential-stamping fetch — pass {@link HttpClient.fetch} so requests\n * carry the app key + session token. Defaults to `globalThis.fetch`\n * (unauthenticated; only useful in tests).\n */\n fetch?: typeof fetch;\n}\n\nexport class SharedSpaceClient {\n private readonly baseUrl: string;\n private readonly fetchFn: typeof fetch;\n\n constructor(opts: SharedSpaceClientOptions) {\n if (!opts?.baseUrl) throw new Error(\"SharedSpaceClient: `baseUrl` is required\");\n this.baseUrl = opts.baseUrl.replace(/\\/+$/, \"\");\n const f = opts.fetch ?? globalThis.fetch;\n if (typeof f !== \"function\") {\n throw new Error(\"SharedSpaceClient: `globalThis.fetch` is unavailable; pass an explicit fetch.\");\n }\n this.fetchFn = f.bind(globalThis);\n }\n\n /** Write a file manifest into the space. Requires space membership. */\n async writeFileManifest(spaceId: string, manifest: FileManifest): Promise<void> {\n const url = `${this.filesBase(spaceId)}`;\n const res = await this.fetchFn(url, this.jsonRequest(\"POST\", { manifest }));\n await parseOrThrow<{ ok: true; fileId: string }>(res, `writeFileManifest(${manifest.id})`);\n }\n\n /** Read a file manifest by id. Requires space membership. */\n async readFileManifest(spaceId: string, fileId: string): Promise<FileManifest> {\n const url = `${this.filesBase(spaceId)}/${encodeURIComponent(fileId)}`;\n const res = await this.fetchFn(url, this.jsonRequest(\"GET\"));\n const data = await parseOrThrow<{ manifest: FileManifest }>(res, `readFileManifest(${fileId})`);\n return data.manifest;\n }\n\n /** Delete a file manifest by id. Requires space membership. */\n async deleteFileManifest(spaceId: string, fileId: string): Promise<boolean> {\n const url = `${this.filesBase(spaceId)}/${encodeURIComponent(fileId)}`;\n const res = await this.fetchFn(url, this.jsonRequest(\"DELETE\"));\n const data = await parseOrThrow<{ ok: true; existed: boolean }>(res, `deleteFileManifest(${fileId})`);\n return data.existed;\n }\n\n /** List file summaries in the space. Requires space membership. */\n async listFiles(spaceId: string): Promise<FileStat[]> {\n const url = `${this.filesBase(spaceId)}`;\n const res = await this.fetchFn(url, this.jsonRequest(\"GET\"));\n const data = await parseOrThrow<{ files: FileStat[] }>(res, \"listFiles\");\n return Array.isArray(data.files) ? data.files : [];\n }\n\n // -------------------------------------------------------------------------\n\n private filesBase(spaceId: string): string {\n return `${this.baseUrl}/api/spaces/${encodeURIComponent(spaceId)}/files`;\n }\n\n private jsonRequest(method: string, body?: unknown): RequestInit {\n const init: RequestInit = { method };\n if (body !== undefined) {\n init.headers = { \"Content-Type\": \"application/json\" };\n init.body = JSON.stringify(body);\n }\n return init;\n }\n}\n\nasync function parseOrThrow<T>(response: Response, op: string): Promise<T> {\n let parsed: unknown = null;\n try {\n parsed = await response.json();\n } catch {\n // non-JSON body\n }\n if (!response.ok) {\n const msg =\n parsed && typeof parsed === \"object\" && \"error\" in (parsed as object)\n ? String((parsed as { error: unknown }).error)\n : `${response.status} ${response.statusText}`;\n throw new Error(`SharedSpaceClient.${op}: ${msg}`);\n }\n return parsed as T;\n}\n\nexport default SharedSpaceClient;\n","/**\n * `client.storage` — file storage. Hides the `FileStorage` / `ShardClient` /\n * `SharedSpaceClient` primitives behind the unified client.\n *\n * const { stat, manifest } = await client.storage.writeFile({ spaceId, data, metadata })\n * const { data } = await client.storage.readFile(spaceId, fileId)\n * const files = await client.storage.listFiles() // my shared files\n * const files = await client.storage.listFiles({ spaceId }) // a space's files\n * await client.storage.deleteFile(spaceId, fileId)\n *\n * Model:\n * - **Files are written to a SharedSpace** (never the personal space). A file\n * is its manifest (per-chunk keys + global shard hashes); the manifest lives\n * in the space's gated, metered `/files` store, the shard ciphertext in the\n * global open `/api/shards` store.\n * - **The manifest is the capability** — anyone holding it reads the file from\n * the global shards, anywhere ({@link readByManifest}). Share a file by\n * sharing its manifest.\n * - **Personal discovery mirror** — on a successful write the SDK also records\n * the manifest in the user's `client.kv` under a reserved collection, so\n * {@link listFiles} (no `spaceId`) can show \"files I've shared\" without\n * enumerating spaces. The mirror is unmetered and is NOT a write path.\n *\n * For small structured values use `client.kv` instead.\n */\n\nimport type { HttpClient } from \"../HttpClient\";\nimport type { KvNamespace } from \"./KvNamespace\";\nimport { FileStorage } from \"../../storage/FileStorage\";\nimport { ShardClient } from \"../../storage/transport/ShardClient\";\nimport { SharedSpaceClient } from \"../../storage/transport/SharedSpaceClient\";\nimport { manifestToStat, type FileManifest, type FileStat } from \"../../storage/types\";\n\n/** Reserved `client.kv` collection holding the personal manifest mirror. */\nconst MIRROR_COLLECTION = \"__files__\";\n\nexport interface FileNamespaceDeps {\n http: HttpClient;\n baseUrl: string;\n /** Used for the unmetered personal discovery mirror. */\n kv: KvNamespace;\n /**\n * Optional pre-compiled Reed–Solomon WASM module. Defaults to the bundled\n * loader; pass one where the bundled loader path isn't available (vitest,\n * deploy-time-precompiled environments). Forwarded to {@link FileStorage}.\n */\n rsWasmModule?: WebAssembly.Module;\n}\n\nexport interface WriteFileOptions {\n /** SharedSpace the file is written to (obtain via `client.space`). */\n spaceId: string;\n data: Uint8Array | Blob | File;\n metadata: { name: string; type: string; path?: string; lastModified?: number };\n}\n\n/** What the personal mirror stores per file. */\ninterface MirrorEntry {\n spaceId: string;\n manifest: FileManifest;\n}\n\nexport class StorageNamespace {\n private fileStorage: FileStorage | null = null;\n\n constructor(private readonly deps: FileNamespaceDeps) {}\n\n /**\n * Write a file to a SharedSpace: shard ciphertext → the global store, the\n * manifest → the space's gated store, and a mirror copy → the caller's\n * personal index. Returns the `stat` and the `manifest` (share the manifest\n * to let others read the file).\n */\n async writeFile(input: WriteFileOptions): Promise<{ stat: FileStat; manifest: FileManifest }> {\n if (!input?.spaceId) {\n throw new Error(\"client.storage.writeFile: `spaceId` is required (files live in a SharedSpace).\");\n }\n const fs = this.fs();\n const { manifest, stat } = await fs.writeFileToShards({\n data: input.data,\n metadata: input.metadata,\n });\n // Authoritative, metered write: the manifest into the space's gated store.\n await this.space().writeFileManifest(input.spaceId, manifest);\n // Best-effort personal discovery mirror (unmetered). A failure here\n // leaves the file intact in the space — log and continue.\n try {\n await this.deps.kv.set<MirrorEntry>(MIRROR_COLLECTION, manifest.id, {\n spaceId: input.spaceId,\n manifest,\n });\n } catch (err) {\n console.warn(\"client.storage.writeFile: discovery mirror failed (file still written):\", err);\n }\n return { stat, manifest };\n }\n\n /** Read a file from its space (resolves the manifest, then the shards). */\n async readFile(spaceId: string, fileId: string): Promise<{ data: Uint8Array; stat: FileStat }> {\n return this.fs().readFile(spaceId, fileId);\n }\n\n /**\n * Read a file straight from a manifest — the capability path. No space\n * membership needed; this is how a shared file is opened.\n */\n async readByManifest(manifest: FileManifest): Promise<{ data: Uint8Array; stat: FileStat }> {\n return this.fs().readFileFromShards(manifest);\n }\n\n /**\n * List files. With no argument, returns the caller's own shared files from\n * the personal mirror; with `{ spaceId }`, lists that space's files.\n */\n async listFiles(opts?: { spaceId?: string }): Promise<FileStat[]> {\n if (opts?.spaceId) return this.space().listFiles(opts.spaceId);\n const ids = await this.deps.kv.list(MIRROR_COLLECTION);\n const entries = await Promise.all(\n ids.map((id) => this.deps.kv.get<MirrorEntry>(MIRROR_COLLECTION, id)),\n );\n return entries\n .filter((e): e is MirrorEntry => Boolean(e?.manifest))\n .map((e) => manifestToStat(e.manifest));\n }\n\n /** Delete a file from its space and remove the personal mirror entry. */\n async deleteFile(spaceId: string, fileId: string): Promise<boolean> {\n const existed = await this.fs().deleteFile(spaceId, fileId);\n try {\n await this.deps.kv.delete(MIRROR_COLLECTION, fileId);\n } catch {\n // mirror cleanup is best-effort\n }\n return existed;\n }\n\n /** Read a manifest verbatim (e.g. to share a file). */\n async getManifest(spaceId: string, fileId: string): Promise<FileManifest> {\n return this.fs().readManifest(spaceId, fileId);\n }\n\n // -------------------------------------------------------------------------\n // Internals — lazily built so an unauthenticated client is cheap to create.\n // -------------------------------------------------------------------------\n\n private fs(): FileStorage {\n if (!this.fileStorage) {\n this.fileStorage = new FileStorage({\n shards: this.shards(),\n space: this.space(),\n rsWasmModule: this.deps.rsWasmModule,\n });\n }\n return this.fileStorage;\n }\n\n private _shards: ShardClient | null = null;\n private shards(): ShardClient {\n // Global, content-addressed shard store. The credential-stamping fetch\n // attaches the app key so PUTs are attributed + quota-gated; GETs are open.\n if (!this._shards) {\n this._shards = new ShardClient({\n baseUrl: this.deps.baseUrl,\n pathPrefix: \"/api/shards\",\n fetch: this.deps.http.fetch,\n });\n }\n return this._shards;\n }\n\n private _space: SharedSpaceClient | null = null;\n private space(): SharedSpaceClient {\n if (!this._space) {\n this._space = new SharedSpaceClient({\n baseUrl: this.deps.baseUrl,\n fetch: this.deps.http.fetch,\n });\n }\n return this._space;\n }\n}\n\nexport default StorageNamespace;\n","/**\n * An end-to-end-encrypted communication session for one local identity\n * (`myId`) talking to an arbitrary set of peers. Wraps `KeyStore` +\n * per-pair `DoubleRatchet` instances and owns the protocol bookkeeping\n * (handshake reciprocation, dedup, role assignment, broadcast fan-out,\n * recipient filtering) so application code doesn't have to.\n *\n * Transport-agnostic by design: the Session never touches a WebSocket\n * (or HTTP, or anything else). Application code:\n * - calls `session.encrypt(text)` and gets back an array of frames it\n * ships over whatever transport it has;\n * - calls `session.receive(frame)` with each inbound frame and acts on\n * the typed result (plaintext, handshake-done, ignored).\n *\n * Frames are plain JSON objects with the same shape the existing chat\n * protocol uses (`{ keyExchange: {...} }` and `{ cipherMessage: {...} }`),\n * so this can drop into a chat app without changing the wire format.\n */\n\nimport { KeyStore } from \"../crypto/KeyStore\";\nimport { DoubleRatchet } from \"../crypto/DoubleRatchet\";\nimport type { CipherMessage } from \"../crypto/types.d\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface SessionOptions {\n /** This client's identifier (e.g. username / DID / public-key string). */\n myId: string;\n}\n\n/** A handshake frame the application ships to peers (or receives from them). */\nexport interface KeyExchangeFrame {\n type: \"handshake\" | \"update\";\n userId: string;\n /** Base64-encoded JWK of the sender's ECDH public key. */\n ecdhPublicKey: string;\n /** Base64-encoded JWK of the sender's ECDSA public key. */\n ecdsaPublicKey: string;\n}\n\n/** A ciphertext frame, addressed to exactly one peer. */\nexport interface CipherFrame {\n cipherMessage: CipherMessage;\n}\n\n/** Anything inbound the application might hand to `session.receive()`. */\nexport type IncomingFrame =\n | { keyExchange: KeyExchangeFrame }\n | { cipherMessage: CipherMessage }\n // Permits passing arbitrary frames; Session returns `kind: 'ignored'`.\n | Record<string, unknown>;\n\n/** Outcome of feeding one frame through `session.receive()`. */\nexport type ReceiveResult =\n | {\n kind: \"plaintext\";\n /** The sender's id (from the cipherMessage header). */\n from: string;\n /** Decrypted message body. */\n text: string;\n /** The original cipherMessage, for callers that want it. */\n cipherMessage: CipherMessage;\n }\n | {\n kind: \"handshake\";\n /** The peer whose handshake was just processed. */\n peerId: string;\n /**\n * If non-null, the application MUST send this frame back to the peer\n * (e.g. broadcast on the room WebSocket). It's our reciprocation —\n * giving the peer our public keys so they can verify our messages.\n *\n * The Session dedups internally: we only emit this on the first\n * handshake we process for a given peer in this Session's lifetime.\n */\n outbound: { keyExchange: KeyExchangeFrame } | null;\n }\n | {\n kind: \"ignored\";\n /** Why we ignored the frame (debugging aid; not for branching on). */\n reason: string;\n };\n\n// ---------------------------------------------------------------------------\n// EncryptedSession\n// ---------------------------------------------------------------------------\n\nexport class EncryptedSession {\n private readonly myId: string;\n private readonly keyStore: KeyStore;\n\n /** One DoubleRatchet per peer pair. */\n private readonly ratchets = new Map<string, DoubleRatchet>();\n\n /** Peers we've already sent our keyExchange to in this Session. */\n private readonly sentHandshakeTo = new Set<string>();\n\n /** Resolved when own keys are generated and ready to use. */\n private readonly _ready: Promise<void>;\n private _resolveReady!: () => void;\n private _initialized = false;\n\n constructor(opts: SessionOptions) {\n if (!opts || !opts.myId) {\n throw new Error(\"EncryptedSession: `myId` is required\");\n }\n this.myId = opts.myId;\n this.keyStore = KeyStore.getInstance();\n this._ready = new Promise<void>((resolve) => {\n this._resolveReady = resolve;\n });\n }\n\n /** A promise that resolves once `initialize()` has completed. */\n get ready(): Promise<void> {\n return this._ready;\n }\n\n /** Our local identifier. */\n get id(): string {\n return this.myId;\n }\n\n /**\n * Generate this client's ECDH + ECDSA keypair (idempotent — safe to call\n * multiple times across reconnects; only the first call generates).\n */\n async initialize(): Promise<void> {\n if (this._initialized) return;\n if (!this.keyStore.getKeyPair(this.myId)) {\n await this.keyStore.generateOwnKeyPair(this.myId);\n }\n this._initialized = true;\n this._resolveReady();\n }\n\n /**\n * Build the keyExchange frame this client should send to peers when it\n * comes online. Application is responsible for actually transmitting it\n * (e.g. ws.send(JSON.stringify(frame))).\n */\n async getOwnKeyExchange(): Promise<{ keyExchange: KeyExchangeFrame }> {\n await this._ready;\n const ownEcdh = this.keyStore.getKeyPair(this.myId);\n const ownEcdsa = this.keyStore.getAuthKeyPair(this.myId);\n if (!ownEcdh || !ownEcdsa) {\n throw new Error(\"EncryptedSession.getOwnKeyExchange: keys not initialized\");\n }\n return {\n keyExchange: {\n type: \"handshake\",\n userId: this.myId,\n ecdhPublicKey: await exportJwkBase64(ownEcdh.publicKey),\n ecdsaPublicKey: await exportJwkBase64(ownEcdsa.publicKey),\n },\n };\n }\n\n /**\n * Encrypt a plaintext to every peer we currently have a ratchet for, and\n * return one cipherMessage frame per recipient. The application sends\n * each frame over its transport.\n *\n * If there are no peers yet (or all peers are still mid-handshake), the\n * returned array may be empty — the caller should typically render the\n * outgoing message locally in that case (since there's no one to send\n * it to yet).\n */\n async encrypt(plaintext: string): Promise<CipherFrame[]> {\n await this._ready;\n const frames: CipherFrame[] = [];\n for (const peerId of this.ratchets.keys()) {\n const ratchet = this.ratchets.get(peerId)!;\n const sessionId = this._sessionIdFor(peerId);\n const cipherMessage = await ratchet.encrypt(\n plaintext,\n /* newDhKey */ false,\n this.myId,\n peerId,\n sessionId,\n \"specific\",\n );\n frames.push({ cipherMessage });\n }\n return frames;\n }\n\n /**\n * Hand an inbound frame to the session. Returns a typed result the\n * application acts on.\n *\n * - `kind: 'plaintext'` — decrypted; render `result.text`\n * - `kind: 'handshake'` — a peer's keys are now stored, and if\n * `result.outbound` is set, send it\n * - `kind: 'ignored'` — not for us, malformed, duplicate, etc.\n *\n * Calling code should always handle `'ignored'` (no UI side effect).\n */\n async receive(frame: IncomingFrame): Promise<ReceiveResult> {\n await this._ready;\n\n // -- handshake frame -----------------------------------------------------\n if (isKeyExchangeFrame(frame)) {\n const kx = frame.keyExchange;\n const peerId = kx.userId;\n\n if (peerId === this.myId) {\n return { kind: \"ignored\", reason: \"own keyExchange echo\" };\n }\n\n const isNew = !this.ratchets.has(peerId);\n\n // (Re-)store the peer's pubkeys + (re-)build the ratchet if needed.\n const peerEcdh = await importJwkBase64(kx.ecdhPublicKey, \"ECDH\");\n const peerEcdsa = await importJwkBase64(kx.ecdsaPublicKey, \"ECDSA\");\n await this.keyStore.storeRemotePublicKeys(peerId, peerEcdh, peerEcdsa);\n\n if (isNew) {\n const isClient = this.myId < peerId;\n const ratchet = new DoubleRatchet(this.myId, peerId, \"specific\", isClient);\n await ratchet.initializeSession(isClient);\n this.ratchets.set(peerId, ratchet);\n }\n\n // Reciprocate exactly once per peer per session lifetime.\n let outbound: { keyExchange: KeyExchangeFrame } | null = null;\n if (isNew && !this.sentHandshakeTo.has(peerId)) {\n outbound = await this.getOwnKeyExchange();\n this.sentHandshakeTo.add(peerId);\n }\n\n return { kind: \"handshake\", peerId, outbound };\n }\n\n // -- ciphertext frame ----------------------------------------------------\n if (isCipherFrame(frame)) {\n const cipherMessage = frame.cipherMessage;\n const header = cipherMessage?.header;\n if (!header) {\n return { kind: \"ignored\", reason: \"cipherMessage has no header\" };\n }\n if (header.senderId === this.myId) {\n return { kind: \"ignored\", reason: \"own outbound echo\" };\n }\n if (header.recipientId && header.recipientId !== this.myId) {\n return { kind: \"ignored\", reason: \"addressed to a different peer\" };\n }\n\n const ratchet = this.ratchets.get(header.senderId);\n if (!ratchet) {\n return {\n kind: \"ignored\",\n reason: `no ratchet with sender ${header.senderId} (handshake hasn't completed)`,\n };\n }\n\n const isClient = this.myId < header.senderId;\n let text: string;\n try {\n text = await ratchet.decrypt(cipherMessage, isClient);\n } catch (err) {\n // DoubleRatchet's wallclock-based replay-protection check throws\n // \"CipherMessage too old, possible replay attack\" for any frame\n // older than 5 minutes. Real replays still fail downstream because\n // the message key has been consumed; the wallclock check is a\n // defense-in-depth heuristic, not a security boundary. Treating it\n // as `ignored` lets the channel survive legacy backlog replays and\n // CF WS-idle-timeout reconnect cycles without spamming the\n // channel's ERROR stream.\n const msg = err instanceof Error ? err.message : String(err);\n if (msg.includes(\"too old\") || msg.includes(\"replay attack\")) {\n return { kind: \"ignored\", reason: `stale cipherMessage rejected: ${msg}` };\n }\n throw err;\n }\n return { kind: \"plaintext\", from: header.senderId, text, cipherMessage };\n }\n\n return { kind: \"ignored\", reason: \"unknown frame type\" };\n }\n\n // -- introspection ---------------------------------------------------------\n\n /** List of peer ids we have an established ratchet for. */\n peers(): string[] {\n return Array.from(this.ratchets.keys());\n }\n\n /** Has the handshake completed for this peer? */\n hasRatchetFor(peerId: string): boolean {\n return this.ratchets.has(peerId);\n }\n\n /**\n * Tear down a peer's ratchet (e.g. when they leave the room). The peer's\n * stored keys remain in `KeyStore` so a fresh handshake can be set up\n * later without re-fetching them, but the ratchet state is dropped.\n */\n forgetPeer(peerId: string): void {\n this.ratchets.delete(peerId);\n this.sentHandshakeTo.delete(peerId);\n }\n\n // -- internals -------------------------------------------------------------\n\n /** Deterministic per-pair session id — same string on both sides. */\n private _sessionIdFor(peerId: string): string {\n return [this.myId, peerId].sort().join(\":\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers — JWK <-> base64 string for key transport\n// ---------------------------------------------------------------------------\n\nasync function exportJwkBase64(key: CryptoKey): Promise<string> {\n const jwk = await crypto.subtle.exportKey(\"jwk\", key);\n return btoa(JSON.stringify(jwk));\n}\n\nasync function importJwkBase64(\n b64: string,\n type: \"ECDH\" | \"ECDSA\",\n): Promise<CryptoKey> {\n const jwk = JSON.parse(atob(b64));\n const algorithm =\n type === \"ECDH\"\n ? { name: \"ECDH\", namedCurve: \"P-384\" }\n : { name: \"ECDSA\", namedCurve: \"P-384\" };\n const usages: KeyUsage[] = type === \"ECDH\" ? [] : [\"verify\"];\n return await crypto.subtle.importKey(\"jwk\", jwk, algorithm, true, usages);\n}\n\n// ---------------------------------------------------------------------------\n// Type guards\n// ---------------------------------------------------------------------------\n\nfunction isKeyExchangeFrame(\n frame: IncomingFrame,\n): frame is { keyExchange: KeyExchangeFrame } {\n const kx = (frame as { keyExchange?: unknown }).keyExchange;\n if (!kx || typeof kx !== \"object\") return false;\n const k = kx as Partial<KeyExchangeFrame>;\n return (\n typeof k.userId === \"string\" &&\n typeof k.ecdhPublicKey === \"string\" &&\n typeof k.ecdsaPublicKey === \"string\"\n );\n}\n\nfunction isCipherFrame(\n frame: IncomingFrame,\n): frame is { cipherMessage: CipherMessage } {\n const cm = (frame as { cipherMessage?: unknown }).cipherMessage;\n if (!cm || typeof cm !== \"object\") return false;\n const m = cm as Partial<CipherMessage>;\n return Boolean(m.header && m.ciphertext && m.nonce);\n}\n","/**\n * BroadcastChannel — a turnkey end-to-end encrypted channel for multi-peer\n * \"room\"-style apps (e.g. a chat). Wires together:\n *\n * - `WSTransport` for socket lifecycle, reconnect, and offline frame queue\n * - `EncryptedSession` for per-peer Double Ratchet state, handshake\n * reciprocation, fan-out encryption, and recipient filtering\n *\n * The host app only deals with high-level events and method calls; it never\n * touches `new WebSocket(...)` or builds cipherMessage frames by hand.\n *\n * Wire protocol (kept compatible with the existing chat protocol so this\n * drops into the deployed Accelerator without server changes):\n *\n * outbound: `{ keyExchange: {...} }` — produced by us on `announce()`\n * `{ cipherMessage: {...} }` — produced by `send(text)`,\n * one frame per peer\n * arbitrary JSON — sent via `sendRaw(obj)`\n *\n * inbound: `{ keyExchange: {...} }` — routed into EncryptedSession;\n * emits `peer_handshake`\n * `{ cipherMessage: {...} }` — decrypted; emits `message`\n * anything else — passes through as `raw_frame`\n * (the app decides what to do)\n *\n * **Event scoping.** Unlike `Network`, BroadcastChannel uses a per-instance\n * `EventTarget`, so two channels (e.g. two rooms in the same app) don't\n * cross-contaminate each other's events.\n *\n * Note: this class shadows the `BroadcastChannel` Web API global (cross-tab\n * messaging) only when imported by name. They're unrelated.\n */\n\nimport { EventCoreEvents } from \"../events\";\nimport { WSTransport, WSTransportOptions } from \"../transport\";\nimport { EncryptedSession } from \"./EncryptedSession\";\n\n// ---------------------------------------------------------------------------\n// Event names\n// ---------------------------------------------------------------------------\n\n/**\n * Event names BroadcastChannel emits. Lifecycle events reuse the\n * `EventCoreEvents` string values (`connected`, `disconnected`, etc.) so\n * apps can use shared constants if they want. Channel-specific events are\n * prefixed `channel:` to avoid colliding with other event systems in the\n * same app.\n */\nexport const BroadcastChannelEvents = {\n CONNECTED: EventCoreEvents.CONNECTED,\n DISCONNECTED: EventCoreEvents.DISCONNECTED,\n RECONNECTING: EventCoreEvents.RECONNECTING,\n ERROR: EventCoreEvents.ERROR,\n /** A peer's ratchet is now ready. `detail.peerId` is the peer's id. */\n PEER_HANDSHAKE: \"channel:peer_handshake\",\n /** Decrypted message. `detail` is `{ from, text, cipherMessage }`. */\n MESSAGE: \"channel:message\",\n /** Inbound frame BroadcastChannel didn't recognize. App handles it. */\n RAW_FRAME: \"channel:raw_frame\",\n} as const;\n\nexport type BroadcastChannelEvent = (typeof BroadcastChannelEvents)[keyof typeof BroadcastChannelEvents];\n\nexport interface BroadcastChannelOptions extends WSTransportOptions {\n /** This client's identifier (username, DID, public-key string, etc.). */\n myId: string;\n /**\n * If true (default false), automatically send our keyExchange as soon as\n * the socket is connected. For chat-style apps that send a `{name}` frame\n * first, leave this false and call `announce()` after that handshake.\n */\n autoAnnounce?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// BroadcastChannel\n// ---------------------------------------------------------------------------\n\nexport class BroadcastChannel {\n readonly transport: WSTransport;\n readonly session: EncryptedSession;\n readonly myId: string;\n\n private autoAnnounce: boolean;\n private announced = false;\n\n /** Per-instance EventTarget — events do NOT leak across BroadcastChannels. */\n private events = new EventTarget();\n\n constructor(opts: BroadcastChannelOptions) {\n if (!opts || !opts.myId) {\n throw new Error(\"BroadcastChannel: `myId` is required\");\n }\n this.myId = opts.myId;\n this.autoAnnounce = opts.autoAnnounce ?? false;\n\n this.transport = new WSTransport(opts);\n this.session = new EncryptedSession({ myId: opts.myId });\n\n // Pass-through lifecycle events from the transport. `EventCore.on` is\n // static so it routes back through the shared singleton; we bridge it\n // into our instance-scoped event target.\n this.transport.on(EventCoreEvents.CONNECTED, () => {\n // Reset the announce flag on every (re)connect. CF Workers WebSockets\n // hit an idle timeout and force reconnects; without resetting, the\n // SDK would short-circuit announce() and any peer who joined the\n // room after our last announce would never see our pubkey.\n this.announced = false;\n this.emit(BroadcastChannelEvents.CONNECTED);\n if (this.autoAnnounce) {\n void this.announce();\n }\n });\n this.transport.on(EventCoreEvents.DISCONNECTED, () => {\n this.emit(BroadcastChannelEvents.DISCONNECTED);\n });\n this.transport.on(EventCoreEvents.RECONNECTING, (e: CustomEvent) => {\n this.emit(BroadcastChannelEvents.RECONNECTING, e.detail);\n });\n this.transport.on(EventCoreEvents.ERROR, (e: CustomEvent) => {\n this.emit(BroadcastChannelEvents.ERROR, e.detail);\n });\n\n // Route inbound raw frames through our framing/decryption logic.\n this.transport.on(EventCoreEvents.MESSAGE, (e: CustomEvent) => {\n void this.handleInboundFrame(e.detail as string);\n });\n }\n\n // -- event API -------------------------------------------------------------\n\n /** Subscribe to a channel event. Handler receives a CustomEvent. */\n on(event: BroadcastChannelEvent | string, handler: (e: CustomEvent) => void): void {\n this.events.addEventListener(event, handler as EventListener);\n }\n\n /** Unsubscribe. */\n off(event: BroadcastChannelEvent | string, handler: (e: CustomEvent) => void): void {\n this.events.removeEventListener(event, handler as EventListener);\n }\n\n private emit(event: BroadcastChannelEvent | string, detail?: unknown): void {\n this.events.dispatchEvent(new CustomEvent(event, { detail }));\n }\n\n // -- lifecycle -------------------------------------------------------------\n\n /** Generate our keys (idempotent) and open the WebSocket. */\n async connect(): Promise<void> {\n await this.session.initialize();\n await this.transport.connect();\n }\n\n /** Close the WebSocket and stop reconnecting. */\n disconnect(): void {\n this.transport.disconnect();\n }\n\n /**\n * Send our `keyExchange` frame to the room. Idempotent — only sends on the\n * first call. Call this once your higher-level handshake (e.g. sending a\n * `{name}` identification frame) has completed.\n */\n async announce(): Promise<void> {\n if (this.announced) return;\n this.announced = true;\n const frame = await this.session.getOwnKeyExchange();\n this.transport.send(JSON.stringify(frame));\n }\n\n /**\n * Encrypt `plaintext` to every peer we have a ratchet with, and send each\n * cipherMessage as its own WS frame. Returns the number of peers we sent to\n * (0 if no peers are handshaken yet — in which case the caller should\n * typically render the message locally for the sender and try again later).\n */\n async send(plaintext: string): Promise<number> {\n const frames = await this.session.encrypt(plaintext);\n for (const frame of frames) {\n this.transport.send(JSON.stringify(frame));\n }\n return frames.length;\n }\n\n /**\n * Send an arbitrary JSON-serializable frame as-is. The app uses this for\n * any frame that isn't channel-managed (e.g. a chat's `{name}`, `{file}`,\n * or unencrypted `{message}`).\n */\n sendRaw(frame: unknown): void {\n this.transport.send(JSON.stringify(frame));\n }\n\n // -- introspection ---------------------------------------------------------\n\n /** List of peer ids we have an established ratchet for. */\n peers(): string[] {\n return this.session.peers();\n }\n\n /** Drop a peer's ratchet (e.g. when they leave the room). */\n forgetPeer(peerId: string): void {\n this.session.forgetPeer(peerId);\n }\n\n isConnected(): boolean {\n return this.transport.isConnected();\n }\n\n // -- internals -------------------------------------------------------------\n\n private async handleInboundFrame(raw: string): Promise<void> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n this.emit(BroadcastChannelEvents.ERROR, err);\n return;\n }\n\n if (!parsed || typeof parsed !== \"object\") {\n this.emit(BroadcastChannelEvents.RAW_FRAME, parsed);\n return;\n }\n\n const obj = parsed as Record<string, unknown>;\n\n // Channel-managed: keyExchange & cipherMessage. Anything else is RAW_FRAME.\n if (\"keyExchange\" in obj || \"cipherMessage\" in obj) {\n try {\n const result = await this.session.receive(\n obj as Parameters<typeof this.session.receive>[0],\n );\n if (result.kind === \"handshake\") {\n if (result.outbound) {\n this.transport.send(JSON.stringify(result.outbound));\n }\n this.emit(BroadcastChannelEvents.PEER_HANDSHAKE, { peerId: result.peerId });\n } else if (result.kind === \"plaintext\") {\n this.emit(BroadcastChannelEvents.MESSAGE, {\n from: result.from,\n text: result.text,\n cipherMessage: result.cipherMessage,\n });\n }\n // `ignored` is intentionally swallowed; subscribe to ERROR for bad frames.\n } catch (err) {\n this.emit(BroadcastChannelEvents.ERROR, err);\n }\n return;\n }\n\n this.emit(BroadcastChannelEvents.RAW_FRAME, obj);\n }\n}\n\nexport default BroadcastChannel;\n","/**\n * SpaceCipher — pure crypto for the fan-out group-encryption layer.\n *\n * Everything here routes through the canonical primitives in\n * `src/crypto/primitives` (AES-256-GCM, HKDF-SHA256, randomBytes) and the\n * P-384 ECDH `deriveBits` call the Double Ratchet already uses. No new\n * algorithms, no `crypto.subtle` reach-arounds beyond key gen / derive /\n * import-export (which the primitive layer intentionally doesn't cover).\n *\n * Three concerns:\n * 1. Space identity — a P-384 ECDH keypair; the encoded public key is the\n * space's id.\n * 2. Group key distribution — ECIES wrap/unwrap of `K_space` to a member's\n * identity ECDH public key (ephemeral-static ECDH → HKDF → AES-GCM).\n * 3. Message sealing — encrypt the serialized `Message` once under the\n * epoch's group key.\n *\n * Public keys are transported as base64url-encoded JWK, matching the JWK\n * transport convention already used in `EncryptedSession`.\n */\n\nimport { Message } from \"../messaging/Message\";\nimport {\n encryptAesGcm,\n decryptAesGcm,\n deriveBitsHkdf,\n randomBytes,\n getSubtle,\n AES_GCM_KEY_BYTES,\n AES_GCM_IV_BYTES,\n} from \"../crypto/primitives\";\nimport {\n toBase64,\n fromBase64,\n toBase64Url,\n fromBase64Url,\n utf8Encode,\n utf8Decode,\n} from \"../utilities\";\nimport type { WrappedKey } from \"./types\";\n\n/** HKDF label binding the wrap key to this protocol + version. */\nconst WRAP_INFO = \"muhkoo/space/keywrap/v1\";\n/** Algorithm tag stamped into every WrappedKey. */\nconst WRAP_ALG = \"ECDH-P384/HKDF-SHA256/AES-256-GCM\";\n/** Bits in a P-384 ECDH shared secret. */\nconst P384_BITS = 384;\n\nconst ECDH_PARAMS: EcKeyGenParams = { name: \"ECDH\", namedCurve: \"P-384\" };\n\n// ---------------------------------------------------------------------------\n// Public-key transport (base64url JWK)\n// ---------------------------------------------------------------------------\n\n/** Encode an ECDH public `CryptoKey` as a base64url JWK string. */\nexport async function exportEcdhPublicKey(key: CryptoKey): Promise<string> {\n const jwk = await getSubtle().exportKey(\"jwk\", key);\n return toBase64Url(utf8Encode(JSON.stringify(jwk)));\n}\n\n/** Decode a base64url JWK string back into an ECDH public `CryptoKey`. */\nexport async function importEcdhPublicKey(encoded: string): Promise<CryptoKey> {\n const jwk = JSON.parse(utf8Decode(fromBase64Url(encoded)));\n // Public keys carry no usages.\n return getSubtle().importKey(\"jwk\", jwk, ECDH_PARAMS, true, []);\n}\n\n/** The space's id is just its encoded ECDH public key. */\nexport const encodeSpaceId = exportEcdhPublicKey;\n\n// ---------------------------------------------------------------------------\n// Sender authentication (ECDSA P-384, matching the Double Ratchet path).\n// A fan-out message is signed by its sender's identity ECDSA key so receivers\n// can verify authorship end-to-end — independent of the relay, which only\n// stamps `source` server-side. SHA-256 hash to match `DoubleRatchet`.\n// ---------------------------------------------------------------------------\n\nconst ECDSA_PARAMS: EcKeyImportParams = { name: \"ECDSA\", namedCurve: \"P-384\" };\nconst ECDSA_SIGN: EcdsaParams = { name: \"ECDSA\", hash: \"SHA-256\" };\n\n/** Encode an ECDSA public `CryptoKey` as a base64url JWK string. */\nexport async function exportEcdsaPublicKey(key: CryptoKey): Promise<string> {\n const jwk = await getSubtle().exportKey(\"jwk\", key);\n return toBase64Url(utf8Encode(JSON.stringify(jwk)));\n}\n\n/** Decode a base64url JWK string back into an ECDSA verify-only public key. */\nexport async function importEcdsaPublicKey(encoded: string): Promise<CryptoKey> {\n const jwk = JSON.parse(utf8Decode(fromBase64Url(encoded)));\n return getSubtle().importKey(\"jwk\", jwk, ECDSA_PARAMS, true, [\"verify\"]);\n}\n\n/**\n * Canonical bytes a sender signs (and a receiver re-derives). Binds the claimed\n * sender + routing + the sealed ciphertext, so a relay can't relabel `source`\n * and a member can't reuse another's ciphertext under a new envelope.\n */\nexport function canonicalMessage(fields: {\n source: string;\n target: string;\n subject: string;\n epoch: number;\n iv: string;\n ciphertext: string;\n}): string {\n return [fields.source, fields.target, fields.subject, fields.epoch, fields.iv, fields.ciphertext].join(\"\\n\");\n}\n\n/** Sign the canonical bytes with the sender's ECDSA identity private key. */\nexport async function signSpaceMessage(canonical: string, ecdsaPriv: CryptoKey): Promise<string> {\n const sig = await getSubtle().sign(ECDSA_SIGN, ecdsaPriv, utf8Encode(canonical));\n return toBase64(new Uint8Array(sig));\n}\n\n/** Verify a signature over the canonical bytes against the sender's ECDSA key. */\nexport async function verifySpaceMessage(canonical: string, sigB64: string, ecdsaPub: CryptoKey): Promise<boolean> {\n try {\n return await getSubtle().verify(ECDSA_SIGN, ecdsaPub, fromBase64(sigB64), utf8Encode(canonical));\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Space identity\n// ---------------------------------------------------------------------------\n\nexport interface SpaceIdentity {\n /** Encoded public key — the space's logical id. */\n id: string;\n publicKey: CryptoKey;\n privateKey: CryptoKey;\n}\n\n/** Generate a fresh space identity keypair (P-384 ECDH). */\nexport async function generateSpaceIdentity(): Promise<SpaceIdentity> {\n const kp = await getSubtle().generateKey(ECDH_PARAMS, true, [\"deriveBits\"]);\n const id = await encodeSpaceId(kp.publicKey);\n return { id, publicKey: kp.publicKey, privateKey: kp.privateKey };\n}\n\n// ---------------------------------------------------------------------------\n// Group key\n// ---------------------------------------------------------------------------\n\n/** Mint a fresh 256-bit group key for an epoch. */\nexport function generateSpaceKey(): Uint8Array {\n return randomBytes(AES_GCM_KEY_BYTES);\n}\n\n// ---------------------------------------------------------------------------\n// ECIES wrap / unwrap of the group key\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap `kSpace` for `recipientEcdhPub` using an ephemeral ECDH keypair.\n * The HKDF salt binds the wrap key to `epoch`, so a wrap minted for one epoch\n * cannot be replayed to unwrap a different epoch's blob.\n */\nexport async function wrapSpaceKey(\n kSpace: Uint8Array,\n epoch: number,\n recipientEcdhPub: CryptoKey,\n): Promise<WrappedKey> {\n const eph = await getSubtle().generateKey(ECDH_PARAMS, true, [\"deriveBits\"]);\n const shared = new Uint8Array(\n await getSubtle().deriveBits(\n { name: \"ECDH\", public: recipientEcdhPub },\n eph.privateKey,\n P384_BITS,\n ),\n );\n const wrapKey = await deriveBitsHkdf(\n shared,\n WRAP_INFO,\n AES_GCM_KEY_BYTES,\n utf8Encode(`epoch:${epoch}`),\n );\n const iv = randomBytes(AES_GCM_IV_BYTES);\n const ciphertext = await encryptAesGcm(wrapKey, iv, kSpace);\n return {\n epoch,\n ephemeralPub: await exportEcdhPublicKey(eph.publicKey),\n iv: toBase64(iv),\n ciphertext: toBase64(ciphertext),\n alg: WRAP_ALG,\n };\n}\n\n/**\n * Unwrap a {@link WrappedKey} using the recipient's identity ECDH private key.\n * Throws (GCM tag failure) on the wrong private key or a tampered blob.\n */\nexport async function unwrapSpaceKey(\n wrapped: WrappedKey,\n ownEcdhPriv: CryptoKey,\n): Promise<Uint8Array> {\n const ephPub = await importEcdhPublicKey(wrapped.ephemeralPub);\n const shared = new Uint8Array(\n await getSubtle().deriveBits(\n { name: \"ECDH\", public: ephPub },\n ownEcdhPriv,\n P384_BITS,\n ),\n );\n const wrapKey = await deriveBitsHkdf(\n shared,\n WRAP_INFO,\n AES_GCM_KEY_BYTES,\n utf8Encode(`epoch:${wrapped.epoch}`),\n );\n return decryptAesGcm(wrapKey, fromBase64(wrapped.iv), fromBase64(wrapped.ciphertext));\n}\n\n// ---------------------------------------------------------------------------\n// Message sealing\n// ---------------------------------------------------------------------------\n\n/** Seal an already-serialized message string under the group key. */\nexport async function sealSerialized(\n kSpace: Uint8Array,\n serialized: string,\n): Promise<{ iv: string; ciphertext: string }> {\n const iv = randomBytes(AES_GCM_IV_BYTES);\n const ciphertext = await encryptAesGcm(kSpace, iv, utf8Encode(serialized));\n return { iv: toBase64(iv), ciphertext: toBase64(ciphertext) };\n}\n\n/**\n * Open a sealed payload back into its serialized message string. Throws (GCM\n * tag failure) on the wrong group key or a tampered ciphertext.\n */\nexport async function openSerialized(\n kSpace: Uint8Array,\n iv: string,\n ciphertext: string,\n): Promise<string> {\n const plaintext = await decryptAesGcm(kSpace, fromBase64(iv), fromBase64(ciphertext));\n return utf8Decode(plaintext);\n}\n\n/** Seal a `Message` once under the group key. Returns base64 iv + ciphertext. */\nexport async function sealMessage(\n kSpace: Uint8Array,\n msg: Message,\n): Promise<{ iv: string; ciphertext: string }> {\n return sealSerialized(kSpace, msg.serialize());\n}\n\n/**\n * Open a sealed message back into a `Message`. Throws (GCM tag failure) on the\n * wrong group key or a tampered ciphertext.\n */\nexport async function openMessage(\n kSpace: Uint8Array,\n iv: string,\n ciphertext: string,\n): Promise<Message> {\n return Message.deserialize(await openSerialized(kSpace, iv, ciphertext));\n}\n","/**\n * SpacePacketCipher — the {@link PacketCipher} that seals packets with a\n * space's group key instead of a per-peer Double Ratchet.\n *\n * It pulls the active epoch's key from an {@link EpochKeyProvider} (the\n * SpaceKeyring), so this adapter stays decoupled from the keyring's transport\n * and caching concerns — it only needs \"what key seals epoch N\".\n */\n\nimport type { PacketCipher, PacketHeaders, SealedHeaders } from \"../network/PacketCipher\";\nimport { sealSerialized, openSerialized } from \"./SpaceCipher\";\n\n/** Minimal view of the keyring the cipher needs. */\nexport interface EpochKeyProvider {\n /** Epoch new messages are sealed under (advances on rotation). */\n currentEpoch(): number;\n /** The 32-byte group key for an epoch, or undefined if we don't hold it. */\n keyForEpoch(epoch: number): Uint8Array | undefined;\n}\n\nexport class SpacePacketCipher implements PacketCipher {\n constructor(\n private readonly keys: EpochKeyProvider,\n private readonly contentType?: string,\n ) {}\n\n async seal(serializedMessage: string): Promise<SealedHeaders> {\n const epoch = this.keys.currentEpoch();\n const key = this.keys.keyForEpoch(epoch);\n if (!key) {\n throw new Error(`SpacePacketCipher: no group key for epoch ${epoch}`);\n }\n const { iv, ciphertext } = await sealSerialized(key, serializedMessage);\n const headers: SealedHeaders = { spaceSealed: true, epoch, iv, ciphertext };\n if (this.contentType) headers.contentType = this.contentType;\n return headers;\n }\n\n handles(headers: PacketHeaders): boolean {\n return headers?.spaceSealed === true &&\n typeof headers?.iv === \"string\" &&\n typeof headers?.ciphertext === \"string\";\n }\n\n /** Returns null for epochs we don't hold (surfaced as undecryptable). */\n async open(headers: PacketHeaders): Promise<string | null> {\n if (!this.handles(headers)) return null;\n const epoch = Number(headers!.epoch);\n const key = this.keys.keyForEpoch(epoch);\n if (!key) return null;\n return openSerialized(key, headers!.iv as string, headers!.ciphertext as string);\n }\n}\n","/**\n * `Space` — a client handle for one shared space.\n *\n * A space is the unit everything is built on. It carries:\n * - **realtime transport** over a {@link BroadcastChannel} (group handshake,\n * roster frames, raw-frame passthrough);\n * - **fan-out group messaging** — `Message`s sealed once with the space's\n * group key (via {@link SpacePacketCipher}), wrapped in a cleartext\n * {@link Packet} envelope, broadcast AND persisted by the server as\n * history (the `spaceMessage` frame);\n * - **room-scoped file storage** via {@link FileStorage} over the shard\n * endpoint;\n * - **legacy per-peer Double Ratchet messaging** (`send`/`announce`) for the\n * ephemeral, no-history path — unchanged so existing callers (the chat hook\n * reached via `client.message.room(name)`) keep working.\n *\n * `Space` was formerly `Room`; `Room` remains exported as an alias. The\n * fan-out methods (`sendMessage`/`onMessage`/`history`/`join`/`admit`/`rotate`)\n * require a {@link SpaceKeyring} dep; without one only the transport + DR +\n * file surface is available.\n */\n\nimport { BroadcastChannel, BroadcastChannelEvents } from \"../sessions/BroadcastChannel\";\nimport { FileStorage } from \"../storage/FileStorage\";\nimport { ShardClient } from \"../storage/transport/ShardClient\";\nimport type { FileManifest, FileStat } from \"../storage/types\";\nimport { Message } from \"../messaging/Message\";\nimport { Packet } from \"../messaging/Packet\";\nimport { SpacePacketCipher } from \"./SpacePacketCipher\";\nimport type { SpaceKeyring } from \"./SpaceKeyring\";\nimport { canonicalMessage, signSpaceMessage, verifySpaceMessage } from \"./SpaceCipher\";\nimport { KeyStore } from \"../crypto/KeyStore\";\nimport type { JoinRequest, HistoryPolicy } from \"./types\";\n\ntype Listener = (e: CustomEvent) => void;\n\nexport interface SpaceFileMetadata {\n name: string;\n type: string;\n path?: string;\n lastModified?: number;\n}\n\n/** A decrypted inbound fan-out message. */\nexport interface SpaceMessageEvent {\n from: string;\n channel: string;\n epoch: number;\n contentType?: string;\n /**\n * Server storage handle — the monotonic server timestamp this message is\n * persisted under (`msg:<handle>`). Stable across history replay; pass it to\n * {@link Space.editMessage} / {@link Space.deleteMessage} to mutate the\n * persisted entry. Carried on edit events too (same handle as the original).\n */\n handle: number;\n message: Message;\n}\n\n/**\n * An inbound ephemeral signal — an application broadcast the server relays to\n * the room but never persists (no history). Rides the generic `pub` relay:\n * `subject` is an app-defined routing key, `data` is opaque app JSON, and\n * `from` is the server-authenticated sender. Typing indicators, presence pings,\n * live cursors, etc. are built on top of this in the app layer — the SDK and\n * server stay domain-agnostic.\n */\nexport interface EphemeralEvent {\n /** Server-stamped authenticated sender. */\n from: string;\n /** Application-defined routing key (e.g. \"typing\"). */\n subject: string;\n /** Opaque application payload. */\n data: unknown;\n}\n\n/** A server-authoritative deletion of the persisted message at `handle`. */\nexport interface MessageDeletedEvent {\n handle: number;\n}\n\nexport interface SpaceDeps {\n /** Transport room id. For fan-out spaces this is the encoded space pubkey. */\n name: string;\n wsBaseUrl: string;\n httpBaseUrl: string;\n /** Header-injecting fetch from the client's HttpClient. */\n fetch: typeof fetch;\n /** Resolves the user id used for the ratchet / member id (signed-in username). */\n myId: () => string;\n /** Resolves a short-lived WS upgrade ticket (or null when keyless). */\n fetchTicket: () => Promise<string | null>;\n /** Optional group-key keyring — required for the fan-out methods. */\n keyring?: SpaceKeyring;\n /** History policy for this space (advisory; defaults to static). */\n historyPolicy?: HistoryPolicy;\n /**\n * When true (default), a connected member that holds the group key\n * automatically wraps it for any newcomer that posts a join request —\n * the \"any online key-holder admits\" model. Set false to gate membership\n * yourself via `onJoinRequest` + `admit`.\n */\n autoAdmit?: boolean;\n /**\n * Test seam — defaults to constructing a real {@link BroadcastChannel}.\n * A test can inject an in-memory channel to exercise the fan-out wire\n * without a live websocket.\n */\n createChannel?: (url: string, myId: string) => SpaceChannelLike;\n}\n\n/** The subset of {@link BroadcastChannel} a {@link Space} drives. */\nexport interface SpaceChannelLike {\n on(event: string, handler: (e: CustomEvent) => void): void;\n off(event: string, handler: (e: CustomEvent) => void): void;\n connect(): Promise<void>;\n disconnect(): void;\n announce(): Promise<void>;\n send(plaintext: string): Promise<number>;\n sendRaw(frame: unknown): void;\n peers?(): string[];\n isConnected?(): boolean;\n}\n\nexport class Space {\n readonly name: string;\n readonly historyPolicy: HistoryPolicy;\n private channel: SpaceChannelLike | null = null;\n private readonly pending: Array<[string, Listener]> = [];\n private readonly cipher: SpacePacketCipher | null;\n /** Per-instance event bus for fan-out events (isolated across spaces). */\n private readonly events = new EventTarget();\n private rawWired = false;\n\n constructor(private readonly deps: SpaceDeps) {\n this.name = deps.name;\n this.historyPolicy = deps.historyPolicy ?? \"static\";\n this.cipher = deps.keyring ? new SpacePacketCipher(deps.keyring) : null;\n }\n\n /** The encoded space id (same as the transport name for fan-out spaces). */\n get id(): string {\n return this.name;\n }\n\n /** The keyring backing this space's group keys, if any. */\n get keyring(): SpaceKeyring | undefined {\n return this.deps.keyring;\n }\n\n // -- transport -------------------------------------------------------------\n\n /** Open the space websocket (resolves the ticket + identity lazily). */\n async connect(): Promise<void> {\n if (!this.channel) {\n const ticket = await this.deps.fetchTicket();\n const url =\n `${this.deps.wsBaseUrl}/api/spaces/${encodeURIComponent(this.name)}/websocket` +\n (ticket ? `?ticket=${encodeURIComponent(ticket)}` : \"\");\n this.channel = this.deps.createChannel\n ? this.deps.createChannel(url, this.deps.myId())\n : new BroadcastChannel({ url, myId: this.deps.myId(), autoAnnounce: false });\n for (const [event, handler] of this.pending) this.channel.on(event, handler);\n this.pending.length = 0;\n // Fan-out spaces drive their own `{name}` handshake + frame routing.\n // Legacy (keyring-less) callers wire these themselves, so leave that\n // path byte-for-byte unchanged.\n if (this.deps.keyring) {\n this.channel.on(BroadcastChannelEvents.CONNECTED, () => {\n this.channel?.sendRaw({ name: this.deps.myId() });\n });\n this.wireFanout();\n }\n }\n await this.channel.connect();\n }\n\n disconnect(): void {\n this.channel?.disconnect();\n }\n\n /** Subscribe to a raw channel event. Buffered until `connect()` if early. */\n on(event: string, handler: Listener): void {\n if (this.channel) this.channel.on(event, handler);\n else this.pending.push([event, handler]);\n }\n\n off(event: string, handler: Listener): void {\n if (this.channel) this.channel.off(event, handler);\n else {\n const i = this.pending.findIndex(([e, h]) => e === event && h === handler);\n if (i >= 0) this.pending.splice(i, 1);\n }\n }\n\n // -- legacy Double Ratchet path (unchanged) --------------------------------\n\n /** Advertise our keyExchange to the room (idempotent per connection). */\n announce(): Promise<void> {\n return this.channel ? this.channel.announce() : Promise.resolve();\n }\n\n /** E2E-encrypt `text` to every peer via the Double Ratchet (no history). */\n send(text: string): Promise<number> {\n return this.channel ? this.channel.send(text) : Promise.resolve(0);\n }\n\n /** Send an arbitrary JSON frame (e.g. the `{name}` handshake). */\n sendRaw(frame: unknown): void {\n this.channel?.sendRaw(frame);\n }\n\n peers(): string[] {\n return this.channel?.peers ? this.channel.peers() : [];\n }\n\n isConnected(): boolean {\n return this.channel?.isConnected ? this.channel.isConnected() : false;\n }\n\n /** The underlying channel, for advanced use. `null` before `connect()`. */\n get raw(): SpaceChannelLike | null {\n return this.channel;\n }\n\n // -- fan-out group messaging -----------------------------------------------\n\n /**\n * Seal `payload` once with the current group key and broadcast it as a\n * persisted `spaceMessage`. Requires a keyring.\n */\n async sendMessage(\n payload: unknown,\n opts: { channel?: string; contentType?: string } = {},\n ): Promise<void> {\n this.sendRaw({ spaceMessage: await this.sealMessage(payload, opts.channel, opts.contentType) });\n }\n\n /** Subscribe to decrypted fan-out messages. Returns an unsubscribe fn. */\n onMessage(handler: (e: SpaceMessageEvent) => void): () => void {\n const listener = (e: Event) => handler((e as CustomEvent<SpaceMessageEvent>).detail);\n this.events.addEventListener(\"message\", listener);\n return () => this.events.removeEventListener(\"message\", listener);\n }\n\n /**\n * Edit a persisted message IN PLACE, addressed by its server\n * {@link SpaceMessageEvent.handle}. Re-seals `payload` and asks the server\n * to replace the stored entry; the server authorizes against the original\n * author. Receivers get an {@link onMessageEdited} event carrying the new\n * content at the same handle. This is a generic persisted-item edit — the\n * server has no notion of what the payload means.\n */\n async editMessage(handle: number, payload: unknown, opts: { channel?: string; contentType?: string } = {}): Promise<void> {\n const spaceMessage = await this.sealMessage(payload, opts.channel, opts.contentType);\n this.sendRaw({ editSpaceMessage: { ts: handle, spaceMessage } });\n }\n\n /**\n * Hard-delete a persisted message by its server {@link SpaceMessageEvent.handle}\n * — the ciphertext is removed from storage. Server authorizes against the\n * original author. Receivers get an {@link onMessageDeleted} event.\n */\n async deleteMessage(handle: number): Promise<void> {\n this.sendRaw({ deleteSpaceMessage: { ts: handle } });\n }\n\n /** Subscribe to in-place edits of persisted messages (new content at the same handle). */\n onMessageEdited(handler: (e: SpaceMessageEvent) => void): () => void {\n const listener = (e: Event) => handler((e as CustomEvent<SpaceMessageEvent>).detail);\n this.events.addEventListener(\"message-edited\", listener);\n return () => this.events.removeEventListener(\"message-edited\", listener);\n }\n\n /** Subscribe to deletions of persisted messages. */\n onMessageDeleted(handler: (e: MessageDeletedEvent) => void): () => void {\n const listener = (e: Event) => handler((e as CustomEvent<MessageDeletedEvent>).detail);\n this.events.addEventListener(\"message-deleted\", listener);\n return () => this.events.removeEventListener(\"message-deleted\", listener);\n }\n\n /**\n * Broadcast an ephemeral, never-persisted signal to the room over the\n * generic `pub` relay. `subject` is an app-defined routing key; `data` is\n * opaque. The transport stays domain-agnostic — app concepts like typing\n * indicators, presence, or live cursors are built on top of this. No-op if\n * the space isn't connected (ephemeral signals aren't worth queuing).\n */\n sendEphemeral(subject: string, data: unknown): void {\n if (!this.isConnected()) return;\n this.sendRaw({ pub: { subject, data } });\n }\n\n /** Subscribe to inbound ephemeral signals. `from` is the authenticated sender. */\n onEphemeral(handler: (e: EphemeralEvent) => void): () => void {\n const listener = (e: Event) => handler((e as CustomEvent<EphemeralEvent>).detail);\n this.events.addEventListener(\"ephemeral\", listener);\n return () => this.events.removeEventListener(\"ephemeral\", listener);\n }\n\n /** Subscribe to inbound join requests (for a key-holder to admit). */\n onJoinRequest(handler: (req: JoinRequest) => void): () => void {\n const listener = (e: Event) => handler((e as CustomEvent<JoinRequest>).detail);\n this.events.addEventListener(\"join-request\", listener);\n return () => this.events.removeEventListener(\"join-request\", listener);\n }\n\n /**\n * Fetch + decrypt persisted history beyond the live backlog.\n * `before` is an opaque cursor returned as `nextCursor`.\n */\n async history(\n opts: { before?: string; limit?: number } = {},\n ): Promise<{ messages: SpaceMessageEvent[]; nextCursor: string | null }> {\n const cipher = this.requireCipher();\n const params = new URLSearchParams();\n if (opts.before) params.set(\"before\", opts.before);\n if (opts.limit) params.set(\"limit\", String(opts.limit));\n const url =\n `${this.deps.httpBaseUrl}/api/spaces/${encodeURIComponent(this.name)}/history` +\n (params.toString() ? `?${params}` : \"\");\n const res = await this.deps.fetch(url);\n if (!res.ok) throw new Error(`Space.history: ${res.status} ${res.statusText}`);\n const body = (await res.json()) as { messages: string[]; nextCursor: string | null };\n // Warm the member directory once so historical senders' signatures verify.\n // (refreshDirectory swallows its own transport errors.)\n await this.deps.keyring?.refreshDirectory();\n const messages: SpaceMessageEvent[] = [];\n for (const raw of body.messages ?? []) {\n const decoded = await this.decodeFrame(raw, cipher);\n if (decoded) messages.push(decoded);\n }\n return { messages, nextCursor: body.nextCursor ?? null };\n }\n\n /**\n * Bring this member's group keys up to date: load from cache, and if we\n * hold nothing, request a key and poll until one arrives (or timeout).\n */\n async join(opts: { timeoutMs?: number; pollMs?: number } = {}): Promise<boolean> {\n const keyring = this.requireKeyring();\n await this.connect();\n if (await keyring.loadFromCache()) return true;\n if (keyring.hasAnyKey()) return true;\n await keyring.requestKey();\n const deadline = Date.now() + (opts.timeoutMs ?? 15000);\n const pollMs = opts.pollMs ?? 500;\n // eslint-disable-next-line no-constant-condition\n while (Date.now() < deadline) {\n if ((await keyring.pullKeys()) > 0) return true;\n await delay(pollMs);\n }\n return false;\n }\n\n /** Creator path: mint the initial group key, then connect. */\n async create(): Promise<void> {\n const keyring = this.requireKeyring();\n await keyring.bootstrapNew();\n await this.connect();\n // Publish our identity in the member directory so peers can verify our\n // message signatures (the creator never \"joins\", so register here).\n await keyring.requestKey().catch(() => {});\n // Admit anyone who requested a key before we were listening.\n if (this.deps.autoAdmit !== false) {\n await keyring.admitPending().catch(() => {});\n }\n }\n\n /** Wrap the group key for a newcomer and post it (key-holder action). */\n async admit(memberId: string, identityEcdhPub: string): Promise<void> {\n await this.requireKeyring().admit(memberId, identityEcdhPub);\n }\n\n /** Invite a user to this (private) channel's membership allowlist. */\n async invite(username: string): Promise<void> {\n await this.requireKeyring().invite(username);\n }\n\n /** Rotate to a fresh epoch and re-wrap to the roster (rotate spaces). */\n async rotate(roster?: Array<{ memberId: string; identityEcdhPub: string }>): Promise<number> {\n return this.requireKeyring().rotate(roster);\n }\n\n // -- room-scoped files (no websocket needed) -------------------------------\n\n async putFile(\n file: File | Blob | Uint8Array,\n metadata: SpaceFileMetadata,\n ): Promise<{ manifest: FileManifest; stat: FileStat }> {\n return this.fileStorage().writeFileToShards({ data: file, metadata });\n }\n\n async getFile(manifest: FileManifest): Promise<{ data: Uint8Array; stat: FileStat }> {\n return this.fileStorage().readFileFromShards(manifest);\n }\n\n private fileStorage(): FileStorage {\n // Global, content-addressed shard store — same store `client.storage`\n // uses, so a file shared into a channel resolves from anywhere by\n // manifest. (Shards are encrypted ciphertext; the manifest is the\n // capability.)\n const shards = new ShardClient({\n baseUrl: this.deps.httpBaseUrl,\n pathPrefix: \"/api/shards\",\n fetch: this.deps.fetch,\n });\n return new FileStorage({ shards });\n }\n\n // -- internals -------------------------------------------------------------\n\n /** Wire the RAW_FRAME handler that drives fan-out events. */\n private wireFanout(): void {\n if (this.rawWired || !this.channel) return;\n this.rawWired = true;\n this.channel.on(BroadcastChannelEvents.RAW_FRAME, (e: CustomEvent) => {\n void this.onRawFrame(e.detail);\n });\n }\n\n private async onRawFrame(frame: unknown): Promise<void> {\n const f = frame as Record<string, unknown>;\n if (!f || typeof f !== \"object\") return;\n if (typeof f.spaceMessage === \"string\" && this.cipher) {\n const decoded = await this.decodeFrame(f.spaceMessage as string, this.cipher, /*raw*/ true, Number(f.timestamp ?? 0));\n if (decoded) this.emitEvent(\"message\", decoded);\n return;\n }\n if (f.editSpaceMessage && typeof f.editSpaceMessage === \"object\" && this.cipher) {\n // Server-authoritative in-place edit: new sealed content at the same\n // handle. Decode and surface it; the app replaces by `handle`.\n const e = f.editSpaceMessage as { ts?: number; spaceMessage?: string };\n if (typeof e.spaceMessage === \"string\") {\n const decoded = await this.decodeFrame(e.spaceMessage, this.cipher, /*raw*/ true, Number(e.ts ?? 0));\n if (decoded) this.emitEvent(\"message-edited\", decoded);\n }\n return;\n }\n if (f.deleteSpaceMessage && typeof f.deleteSpaceMessage === \"object\") {\n const d = f.deleteSpaceMessage as { ts?: number };\n this.emitEvent(\"message-deleted\", { handle: Number(d.ts ?? 0) });\n return;\n }\n if (f.pub && typeof f.pub === \"object\") {\n // Generic ephemeral relay frame. The server stamps the authenticated\n // sender as `name`; `pub` carries the app's {subject, data}. We\n // surface the authenticated `name` as `from` (not any client-set\n // value inside `pub`), so app signals can't spoof their sender.\n const p = f.pub as { subject?: unknown; data?: unknown };\n const from = typeof f.name === \"string\" ? f.name : \"\";\n if (from && typeof p.subject === \"string\") {\n this.emitEvent(\"ephemeral\", { from, subject: p.subject, data: p.data });\n }\n return;\n }\n if (f.joinRequest && typeof f.joinRequest === \"object\") {\n const req = f.joinRequest as JoinRequest;\n this.emitEvent(\"join-request\", req);\n // A new member appeared — refresh the directory so their future\n // messages verify, and (if we hold the key) auto-admit them.\n void this.deps.keyring?.refreshDirectory();\n if (this.deps.autoAdmit !== false && this.deps.keyring?.hasAnyKey() && req.memberId !== this.deps.myId()) {\n void this.deps.keyring.admit(req.memberId, req.identityEcdhPub).catch(() => {});\n }\n return;\n }\n if (f.keyringReady && this.deps.keyring) {\n // A key was wrapped for us — pull it.\n void this.deps.keyring.pullKeys().catch(() => {});\n }\n }\n\n /**\n * Seal `payload` once with the current group key + sign it, returning the\n * serialized `Packet` string. Shared by send (a new message) and edit\n * (replacement content for an existing handle). Requires a keyring.\n */\n private async sealMessage(payload: unknown, channel?: string, contentType?: string): Promise<string> {\n const cipher = this.requireCipher(contentType);\n const message = new Message(payload);\n const headers = await cipher.seal(message.serialize());\n const source = this.deps.myId();\n const subject = channel ?? \"default\";\n // Sign with our identity ECDSA key so receivers can verify authorship\n // end-to-end (independent of the relay's `source` stamp).\n const authPriv = KeyStore.getInstance().getAuthKeyPair(source)?.privateKey;\n if (authPriv) {\n const canonical = canonicalMessage({\n source, target: this.name, subject,\n epoch: Number(headers.epoch), iv: String(headers.iv), ciphertext: String(headers.ciphertext),\n });\n headers.sig = await signSpaceMessage(canonical, authPriv);\n }\n return new Packet({ subject, source, target: this.name, headers }).serialize();\n }\n\n /**\n * Decode one persisted/broadcast frame into a SpaceMessageEvent.\n * `isRawFrame` true means `input` is the already-extracted `spaceMessage`\n * packet string (and `serverTs` carries the message's storage handle from\n * the enclosing frame); false means `input` is the full\n * `{spaceMessage, name, timestamp}` frame and the handle is read from it.\n */\n private async decodeFrame(\n input: string,\n cipher: SpacePacketCipher,\n isRawFrame = false,\n serverTs = 0,\n ): Promise<SpaceMessageEvent | null> {\n try {\n let packetJson = input;\n let handle = serverTs;\n if (!isRawFrame) {\n const outer = JSON.parse(input) as { spaceMessage?: string; timestamp?: number };\n if (typeof outer.spaceMessage !== \"string\") return null;\n packetJson = outer.spaceMessage;\n handle = Number(outer.timestamp ?? 0);\n }\n const packet = Packet.deserialize(packetJson);\n if (!cipher.handles(packet.headers)) return null;\n\n // Verify sender authenticity end-to-end: the message must be signed\n // by `source`'s identity ECDSA key (looked up in the member\n // directory). Drop anything unsigned, signed by an unknown member,\n // or whose signature doesn't match — this defeats both member\n // impersonation and a relay rewriting `source`.\n if (!(await this.verifySender(packet))) return null;\n\n const serialized = await cipher.open(packet.headers);\n if (serialized === null) return null; // epoch key we don't hold\n const message = Message.deserialize(serialized);\n return {\n from: packet.source,\n channel: packet.subject,\n epoch: Number(packet.headers?.epoch ?? 0),\n contentType: packet.headers?.contentType as string | undefined,\n handle,\n message,\n };\n } catch (err) {\n this.emitEvent(\"error\", err);\n return null;\n }\n }\n\n /**\n * True if `packet` carries a valid signature by `source`'s identity key.\n * On a directory cache miss, refresh once (a new member may have just\n * joined) before giving up. Without a keyring (legacy handle) there's\n * nothing to verify against → reject.\n */\n private async verifySender(packet: Packet): Promise<boolean> {\n const keyring = this.deps.keyring;\n const sig = packet.headers?.sig;\n if (!keyring || typeof sig !== \"string\") return false;\n let key = keyring.ecdsaKeyFor(packet.source);\n if (!key) {\n await keyring.refreshDirectory();\n key = keyring.ecdsaKeyFor(packet.source);\n if (!key) return false;\n }\n const canonical = canonicalMessage({\n source: packet.source,\n target: packet.target,\n subject: packet.subject,\n epoch: Number(packet.headers?.epoch ?? 0),\n iv: String(packet.headers?.iv ?? \"\"),\n ciphertext: String(packet.headers?.ciphertext ?? \"\"),\n });\n return verifySpaceMessage(canonical, sig, key);\n }\n\n private emitEvent(type: string, detail: unknown): void {\n this.events.dispatchEvent(new CustomEvent(type, { detail }));\n }\n\n private requireKeyring(): SpaceKeyring {\n if (!this.deps.keyring) {\n throw new Error(\"Space: this operation requires a keyring (open via client.space).\");\n }\n return this.deps.keyring;\n }\n\n private requireCipher(contentType?: string): SpacePacketCipher {\n if (!this.deps.keyring) {\n throw new Error(\"Space: fan-out messaging requires a keyring (open via client.space).\");\n }\n return contentType ? new SpacePacketCipher(this.deps.keyring, contentType) : this.cipher!;\n }\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nexport default Space;\n","/**\n * `client.message` — realtime messaging over the shared-space primitive.\n *\n * const sub = client.message.subscribe('todos', e => …) // pub/sub feed\n * await client.message.publish('todos', data)\n * await client.message.send('user:abc', { text: 'Hello!' }) // E2E DM\n *\n * Two distinct modes, one transport (a shared-space room websocket via\n * {@link BroadcastChannel}):\n *\n * - **pub/sub** — `publish`/`subscribe(subject)` ride plaintext `pub` frames\n * the accelerator blind-relays to everyone in the room `pub:<subject>`.\n * - **direct messages** — `send('user:x', …)` is end-to-end encrypted via the\n * Double Ratchet, fanned out in the recipient's inbox room `inbox:x`;\n * the recipient receives them by `subscribe('user:x', …)` (their own id).\n *\n * Every room websocket is opened with a short-lived signed ticket fetched from\n * `POST /api/ws-ticket` (browsers can't set the app-key header on\n * `new WebSocket()`), then completes the room's `{name}` → `{ready}` handshake\n * before any frame is sent.\n */\n\nimport type { HttpClient } from \"../HttpClient\";\nimport type { SessionState } from \"../Session\";\nimport { BroadcastChannel, BroadcastChannelEvents } from \"../../sessions/BroadcastChannel\";\nimport { Room } from \"../Room\";\n\n/** The subset of {@link BroadcastChannel} this namespace drives (test seam). */\nexport interface ChannelLike {\n on(event: string, handler: (e: CustomEvent) => void): void;\n off(event: string, handler: (e: CustomEvent) => void): void;\n connect(): Promise<void>;\n disconnect(): void;\n announce(): Promise<void>;\n send(plaintext: string): Promise<number>;\n sendRaw(frame: unknown): void;\n}\n\nexport interface MessageNamespaceDeps {\n http: HttpClient;\n session: SessionState;\n /** WebSocket base (ws/wss); derived from the accelerator baseUrl. */\n wsBaseUrl: string;\n /** Test seam — defaults to constructing a real {@link BroadcastChannel}. */\n createChannel?: (url: string, myId: string) => ChannelLike;\n}\n\nexport interface MuhkooMessageEvent<T = unknown> {\n subject: string;\n from: string;\n data: T;\n}\n\n/** Handle returned by `subscribe`; call `.unsubscribe()` to detach. */\nexport interface MessageSubscription {\n subject: string;\n unsubscribe(): void;\n}\n\ninterface RoomConn {\n channel: ChannelLike;\n /** Resolves once the room handshake (`{name}` → `{ready}`) completes. */\n ready: Promise<void>;\n}\n\nexport class MessageNamespace {\n /** One connection per room, memoized. */\n private readonly rooms = new Map<string, Promise<RoomConn>>();\n\n constructor(private readonly deps: MessageNamespaceDeps) {}\n\n /**\n * Subscribe to a subject (pub/sub) or to this user's own id (`user:<me>`)\n * to receive direct messages. Returns an unsubscribe handle.\n */\n subscribe<T = unknown>(subject: string, handler: (e: MuhkooMessageEvent<T>) => void): MessageSubscription {\n const isDM = subject.startsWith(\"user:\");\n const room = isDM ? `inbox:${subject.slice(\"user:\".length)}` : `pub:${subject}`;\n const connP = this.getRoom(room, isDM);\n\n let detach = () => {};\n void connP.then(({ channel }) => {\n if (isDM) {\n const onMsg = (e: CustomEvent) => {\n const { from, text } = (e.detail ?? {}) as { from: string; text: string };\n handler({ subject, from, data: parseMaybeJson<T>(text) });\n };\n channel.on(BroadcastChannelEvents.MESSAGE, onMsg);\n detach = () => channel.off(BroadcastChannelEvents.MESSAGE, onMsg);\n } else {\n const onRaw = (e: CustomEvent) => {\n const f = e.detail as { pub?: { subject: string; from?: string; data: T }; name?: string };\n if (f?.pub && f.pub.subject === subject) {\n handler({ subject, from: f.pub.from ?? f.name ?? \"\", data: f.pub.data });\n }\n };\n channel.on(BroadcastChannelEvents.RAW_FRAME, onRaw);\n detach = () => channel.off(BroadcastChannelEvents.RAW_FRAME, onRaw);\n }\n });\n\n return { subject, unsubscribe: () => detach() };\n }\n\n /** Publish `data` to every subscriber of `subject` (plaintext fan-out). */\n async publish<T = unknown>(subject: string, data: T): Promise<void> {\n const { channel, ready } = await this.getRoom(`pub:${subject}`, false);\n await ready;\n channel.sendRaw({ pub: { subject, from: this.myId(), data } });\n }\n\n /**\n * Send an end-to-end-encrypted direct message to `user:<id>`. Delivered in\n * the recipient's inbox room; the recipient must be subscribed\n * (`subscribe('user:<id>')`) and online to receive it (E2E requires a live\n * ratchet between both parties).\n */\n async send<T = unknown>(target: string, payload: T): Promise<void> {\n if (!target.startsWith(\"user:\")) {\n throw new Error(\"client.message.send: target must be 'user:<id>' (use publish() for pub/sub).\");\n }\n const { channel, ready } = await this.getRoom(`inbox:${target.slice(\"user:\".length)}`, true);\n await ready;\n await channel.announce();\n await channel.send(JSON.stringify(payload));\n }\n\n /**\n * Mint a new private shared-space id, server-side. The id MUST come from\n * the accelerator: it's a 64-hex string that embeds the spaces DO class\n * hash, which the worker validates on every subsequent request — client-\n * generated ids would be rejected. Pass the returned id to {@link room}\n * (or share it) to open the space.\n */\n async createRoom(): Promise<string> {\n const body = await this.deps.http.post<{ spaceId?: string }>(\"/api/spaces\");\n if (!body?.spaceId || !/^[0-9a-f]{64}$/.test(body.spaceId)) {\n throw new Error(\"createRoom: malformed server response (expected a 64-hex spaceId)\");\n }\n return body.spaceId;\n }\n\n /**\n * Open a handle to a shared-space room — group E2E messaging plus\n * room-scoped file storage. The websocket isn't opened until\n * `room.connect()`; `room.putFile`/`getFile` work without it. This is the\n * primitive group chat is built on (`publish`/`subscribe`/`send` are the\n * higher-level conveniences layered over the same space transport).\n */\n room(roomName: string): Room {\n return new Room({\n name: roomName,\n wsBaseUrl: this.deps.wsBaseUrl,\n httpBaseUrl: this.deps.http.baseUrl,\n fetch: this.deps.http.fetch,\n myId: () => this.myId(),\n fetchTicket: () => this.fetchTicket(),\n });\n }\n\n /** Close every open room connection (e.g. on logout). */\n disconnect(): void {\n for (const p of this.rooms.values()) {\n void p.then(({ channel }) => channel.disconnect()).catch(() => {});\n }\n this.rooms.clear();\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private getRoom(room: string, e2e: boolean): Promise<RoomConn> {\n let p = this.rooms.get(room);\n if (!p) {\n p = this.openRoom(room, e2e);\n this.rooms.set(room, p);\n }\n return p;\n }\n\n private async openRoom(room: string, _e2e: boolean): Promise<RoomConn> {\n const myId = this.myId();\n const ticket = await this.fetchTicket();\n const url =\n `${this.deps.wsBaseUrl}/api/spaces/${encodeURIComponent(room)}/websocket` +\n (ticket ? `?ticket=${encodeURIComponent(ticket)}` : \"\");\n\n const channel = (this.deps.createChannel ?? defaultCreateChannel)(url, myId);\n\n let resolveReady!: () => void;\n const ready = new Promise<void>((r) => { resolveReady = r; });\n\n // Room handshake: identify with `{name}` on every (re)connect, and\n // mark ready once the server echoes `{ready:true}`.\n channel.on(BroadcastChannelEvents.CONNECTED, () => channel.sendRaw({ name: myId }));\n channel.on(BroadcastChannelEvents.RAW_FRAME, (e: CustomEvent) => {\n if ((e.detail as { ready?: boolean })?.ready) resolveReady();\n });\n\n await channel.connect();\n return { channel, ready };\n }\n\n /** Fetch a short-lived WS upgrade ticket scoped to this app key. */\n private async fetchTicket(): Promise<string | null> {\n try {\n const res = await this.deps.http.post<{ ticket: string }>(\"/api/ws-ticket\", {});\n return res?.ticket ?? null;\n } catch {\n return null;\n }\n }\n\n private myId(): string {\n const id = this.deps.session.username;\n if (!id) throw new Error(\"client.message: not signed in — call client.auth.zk.login() first.\");\n return id;\n }\n}\n\n/** Default channel factory — a real `BroadcastChannel` over the room socket. */\nfunction defaultCreateChannel(url: string, myId: string): ChannelLike {\n return new BroadcastChannel({ url, myId, autoAnnounce: false });\n}\n\n/** Parse a DM payload back from its JSON string, tolerating plain strings. */\nfunction parseMaybeJson<T>(text: string): T {\n try {\n return JSON.parse(text) as T;\n } catch {\n return text as unknown as T;\n }\n}\n\nexport default MessageNamespace;\n","/**\n * SpaceKeyring — the client's view of a space's group keys.\n *\n * Holds the per-epoch group keys this member possesses (in memory, optionally\n * mirrored to PersonalSpace), and orchestrates the server-blind distribution\n * dance against a {@link KeyringTransport}:\n *\n * - a newcomer posts a join request and pulls the wrapped key blob addressed\n * to it, unwrapping with its identity private key;\n * - an existing key-holder wraps the group key for a newcomer (ECIES to the\n * newcomer's identity public key) and posts the opaque blob;\n * - on membership change (rotate spaces) a fresh epoch key is minted and\n * re-wrapped to the current roster.\n *\n * The server only ever stores opaque {@link WrappedKey} blobs — it cannot read\n * the group key. Implements {@link EpochKeyProvider} so it can back a\n * {@link SpacePacketCipher} directly.\n */\n\nimport type { WrappedKey, JoinRequest, HistoryPolicy, SpaceMetadata, RosterMember } from \"./types\";\nimport {\n generateSpaceKey,\n wrapSpaceKey,\n unwrapSpaceKey,\n importEcdhPublicKey,\n importEcdsaPublicKey,\n} from \"./SpaceCipher\";\nimport type { EpochKeyProvider } from \"./SpacePacketCipher\";\nimport { toBase64, fromBase64 } from \"../utilities\";\n\n/**\n * Reserved member id for the app's \"keeper\" — a trusted always-available member\n * (the accelerator's AppDOv1) that holds the group key and re-issues it to\n * newcomers, so a channel is joinable with no human online. Admitting this id\n * at channel creation hands the key to the keeper. MUST match the accelerator's\n * `KEEPER_MEMBER_ID`.\n */\nexport const KEEPER_MEMBER_ID = \"__keeper__\";\n\n/** Opaque-blob transport to the space's keyring (HTTP or in-memory test seam). */\nexport interface KeyringTransport {\n postJoinRequest(req: JoinRequest): Promise<void>;\n /** All wrapped blobs addressed to `memberId` (any epoch). */\n fetchBlobs(memberId: string): Promise<WrappedKey[]>;\n /** Post a wrapped key blob for `targetMemberId`. */\n postWrappedKey(targetMemberId: string, wrapped: WrappedKey, fromMemberId: string): Promise<void>;\n /** Outstanding join requests (for an online key-holder to fulfill). */\n fetchPending(): Promise<JoinRequest[]>;\n /** Current roster: member ids + their identity ECDH/ECDSA public keys. */\n fetchRoster(): Promise<RosterMember[]>;\n /** Advisory epoch bump; returns the agreed new epoch. */\n rotate(nextEpoch: number): Promise<{ epoch: number }>;\n /** Add `username` to a private channel's membership allowlist. */\n invite(username: string): Promise<void>;\n fetchMetadata(): Promise<SpaceMetadata | null>;\n}\n\n/** PersonalSpace-backed cache of this member's group keys (epoch → base64 key). */\nexport interface SpaceKeyCache {\n loadKeys(spaceId: string): Promise<Record<string, string> | null>;\n saveKeys(spaceId: string, keys: Record<string, string>): Promise<void>;\n}\n\nexport interface SpaceKeyringDeps {\n spaceId: string;\n memberId: string;\n /** This member's identity ECDH public key, base64url JWK (for join requests). */\n identityEcdhPub: string;\n /** This member's identity ECDSA public key, base64url JWK (published for\n * sender-signature verification). */\n identityEcdsaPub?: string;\n /** Resolves this member's identity ECDH private key (for unwrapping). */\n ownPrivateKey: () => CryptoKey | null;\n transport: KeyringTransport;\n cache?: SpaceKeyCache;\n historyPolicy?: HistoryPolicy;\n}\n\nexport class SpaceKeyring implements EpochKeyProvider {\n private readonly keys = new Map<number, Uint8Array>();\n private epoch = 0;\n private readonly policy: HistoryPolicy;\n /** Cached member directory: memberId → imported ECDSA verify key. */\n private readonly memberEcdsa = new Map<string, CryptoKey>();\n\n constructor(private readonly deps: SpaceKeyringDeps) {\n this.policy = deps.historyPolicy ?? \"static\";\n }\n\n // -- member directory (for verifying sender signatures) -------------------\n\n /** The cached ECDSA verify key for a member, if known. */\n ecdsaKeyFor(memberId: string): CryptoKey | undefined {\n return this.memberEcdsa.get(memberId);\n }\n\n /** Refresh the member directory (memberId → ECDSA key) from the roster. */\n async refreshDirectory(): Promise<void> {\n let roster: RosterMember[];\n try {\n roster = await this.deps.transport.fetchRoster();\n } catch {\n return;\n }\n for (const m of roster) {\n if (!m.identityEcdsaPub || this.memberEcdsa.has(m.memberId)) continue;\n try {\n this.memberEcdsa.set(m.memberId, await importEcdsaPublicKey(m.identityEcdsaPub));\n } catch {\n /* skip malformed entries */\n }\n }\n }\n\n // -- EpochKeyProvider ------------------------------------------------------\n\n currentEpoch(): number {\n return this.epoch;\n }\n\n keyForEpoch(epoch: number): Uint8Array | undefined {\n return this.keys.get(epoch);\n }\n\n hasAnyKey(): boolean {\n return this.keys.size > 0;\n }\n\n // -- lifecycle -------------------------------------------------------------\n\n /** Hydrate keys from the PersonalSpace cache, if available. Best-effort —\n * a cache miss/failure (e.g. not unlocked) must not block joining. */\n async loadFromCache(): Promise<boolean> {\n if (!this.deps.cache) return false;\n let cached: Record<string, string> | null;\n try {\n cached = await this.deps.cache.loadKeys(this.deps.spaceId);\n } catch {\n return false;\n }\n if (!cached) return false;\n for (const [epochStr, b64] of Object.entries(cached)) {\n this.keys.set(Number(epochStr), fromBase64(b64));\n }\n this.epoch = Math.max(0, ...Array.from(this.keys.keys()));\n return this.keys.size > 0;\n }\n\n private async persist(): Promise<void> {\n if (!this.deps.cache) return;\n const out: Record<string, string> = {};\n for (const [epoch, key] of this.keys) out[String(epoch)] = toBase64(key);\n // Best-effort: caching is an optimization; a write failure (e.g. locked\n // storage) must not break key acquisition.\n try {\n await this.deps.cache.saveKeys(this.deps.spaceId, out);\n } catch {\n /* ignore */\n }\n }\n\n /** Creator path: mint epoch-0 group key for a brand-new space. */\n async bootstrapNew(): Promise<void> {\n this.keys.set(0, generateSpaceKey());\n this.epoch = 0;\n await this.persist();\n }\n\n // -- newcomer: request + pull ---------------------------------------------\n\n /**\n * Post a join request so an online key-holder can wrap a key for us. Also\n * publishes our identity keys in the member directory (so others can verify\n * our message signatures, and the keeper can wrap to us).\n */\n async requestKey(desiredEpoch?: number): Promise<void> {\n await this.deps.transport.postJoinRequest({\n memberId: this.deps.memberId,\n identityEcdhPub: this.deps.identityEcdhPub,\n identityEcdsaPub: this.deps.identityEcdsaPub,\n desiredEpoch,\n });\n }\n\n /**\n * Pull and unwrap any blobs addressed to us. Returns the number of new\n * epoch keys obtained. Safe to call repeatedly (idempotent).\n */\n async pullKeys(): Promise<number> {\n const priv = this.deps.ownPrivateKey();\n if (!priv) throw new Error(\"SpaceKeyring: no identity private key to unwrap with\");\n const blobs = await this.deps.transport.fetchBlobs(this.deps.memberId);\n let added = 0;\n for (const blob of blobs) {\n if (this.keys.has(blob.epoch)) continue;\n try {\n const key = await unwrapSpaceKey(blob, priv);\n this.keys.set(blob.epoch, key);\n added++;\n } catch {\n // Not for us / tampered — skip this blob.\n }\n }\n if (added > 0) {\n this.epoch = Math.max(this.epoch, ...Array.from(this.keys.keys()));\n await this.persist();\n }\n return added;\n }\n\n // -- key-holder: admit + rotate -------------------------------------------\n\n /**\n * Wrap our group key(s) for a newcomer and post the blobs. In a `static`\n * space the newcomer receives every epoch we hold (full history); in a\n * `rotate` space they receive only the current epoch.\n */\n async admit(targetMemberId: string, identityEcdhPub: string): Promise<void> {\n const recipient = await importEcdhPublicKey(identityEcdhPub);\n const epochs = this.policy === \"static\"\n ? Array.from(this.keys.keys())\n : [this.epoch];\n for (const epoch of epochs) {\n const key = this.keys.get(epoch);\n if (!key) continue;\n const wrapped = await wrapSpaceKey(key, epoch, recipient);\n await this.deps.transport.postWrappedKey(targetMemberId, wrapped, this.deps.memberId);\n }\n }\n\n /**\n * Admit every outstanding join request (an online key-holder fulfilling\n * pending newcomers). Returns the ids admitted.\n */\n async admitPending(): Promise<string[]> {\n const pending = await this.deps.transport.fetchPending();\n const admitted: string[] = [];\n for (const req of pending) {\n if (req.memberId === this.deps.memberId) continue;\n await this.admit(req.memberId, req.identityEcdhPub);\n admitted.push(req.memberId);\n }\n return admitted;\n }\n\n /**\n * Rotate to a fresh epoch (rotate spaces). Mints a new group key, advances\n * the epoch, and re-wraps it to every member in `roster` (plus ourselves).\n */\n async rotate(roster?: Array<{ memberId: string; identityEcdhPub: string }>): Promise<number> {\n const members = roster ?? (await this.deps.transport.fetchRoster());\n const { epoch: nextEpoch } = await this.deps.transport.rotate(this.epoch + 1);\n const newKey = generateSpaceKey();\n this.keys.set(nextEpoch, newKey);\n this.epoch = nextEpoch;\n for (const m of members) {\n if (m.memberId === this.deps.memberId) continue;\n const recipient = await importEcdhPublicKey(m.identityEcdhPub);\n const wrapped = await wrapSpaceKey(newKey, nextEpoch, recipient);\n await this.deps.transport.postWrappedKey(m.memberId, wrapped, this.deps.memberId);\n }\n await this.persist();\n return nextEpoch;\n }\n\n /** Add `username` to a private channel's membership allowlist (member-only). */\n async invite(username: string): Promise<void> {\n await this.deps.transport.invite(username);\n }\n}\n","/**\n * KeyringClient — HTTP implementation of {@link KeyringTransport} against the\n * accelerator's per-space keyring endpoints. All blobs are opaque to the\n * server; this client just moves them.\n *\n * POST /api/spaces/:id/keyring/join-request { ...JoinRequest }\n * GET /api/spaces/:id/keyring/blobs/:member -> WrappedKey[]\n * POST /api/spaces/:id/keyring/wrap { targetMemberId, fromMemberId, wrapped }\n * GET /api/spaces/:id/keyring/pending -> JoinRequest[]\n * GET /api/spaces/:id/keyring/roster -> { memberId, identityEcdhPub }[]\n * POST /api/spaces/:id/keyring/rotate { nextEpoch } -> { epoch }\n * GET /api/spaces/:id/metadata -> SpaceMetadata\n */\n\nimport type { KeyringTransport } from \"./SpaceKeyring\";\nimport type { WrappedKey, JoinRequest, SpaceMetadata, RosterMember } from \"./types\";\n\nexport interface KeyringClientDeps {\n spaceId: string;\n httpBaseUrl: string;\n /** Header-injecting fetch from the client's HttpClient. */\n fetch: typeof fetch;\n}\n\nexport class KeyringClient implements KeyringTransport {\n constructor(private readonly deps: KeyringClientDeps) {}\n\n private url(suffix: string): string {\n return `${this.deps.httpBaseUrl}/api/spaces/${encodeURIComponent(this.deps.spaceId)}${suffix}`;\n }\n\n private async post<T>(suffix: string, body: unknown): Promise<T> {\n const res = await this.deps.fetch(this.url(suffix), {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (!res.ok) throw new Error(`KeyringClient POST ${suffix}: ${res.status} ${res.statusText}`);\n return (await res.json().catch(() => ({}))) as T;\n }\n\n private async get<T>(suffix: string): Promise<T> {\n const res = await this.deps.fetch(this.url(suffix));\n if (!res.ok) throw new Error(`KeyringClient GET ${suffix}: ${res.status} ${res.statusText}`);\n return (await res.json()) as T;\n }\n\n async postJoinRequest(req: JoinRequest): Promise<void> {\n await this.post(\"/keyring/join-request\", req);\n }\n\n async fetchBlobs(memberId: string): Promise<WrappedKey[]> {\n const body = await this.get<{ blobs?: WrappedKey[] }>(\n `/keyring/blobs/${encodeURIComponent(memberId)}`,\n );\n return body.blobs ?? [];\n }\n\n async postWrappedKey(targetMemberId: string, wrapped: WrappedKey, fromMemberId: string): Promise<void> {\n await this.post(\"/keyring/wrap\", { targetMemberId, fromMemberId, wrapped });\n }\n\n async fetchPending(): Promise<JoinRequest[]> {\n const body = await this.get<{ pending?: JoinRequest[] }>(\"/keyring/pending\");\n return body.pending ?? [];\n }\n\n async fetchRoster(): Promise<RosterMember[]> {\n const body = await this.get<{ roster?: RosterMember[] }>(\"/keyring/roster\");\n return body.roster ?? [];\n }\n\n async rotate(nextEpoch: number): Promise<{ epoch: number }> {\n return this.post<{ epoch: number }>(\"/keyring/rotate\", { nextEpoch });\n }\n\n async invite(username: string): Promise<void> {\n await this.post(\"/keyring/invite\", { username });\n }\n\n async fetchMetadata(): Promise<SpaceMetadata | null> {\n try {\n return await this.get<SpaceMetadata>(\"/metadata\");\n } catch {\n return null;\n }\n }\n}\n","/**\n * `client.space` — the fan-out group-encryption surface.\n *\n * const space = await client.space.createSpace({ historyPolicy: \"static\" });\n * await space.sendMessage({ text: \"hello\" });\n * space.onMessage(e => …);\n *\n * const joined = await client.space.joinSpace(space.id); // newcomer\n *\n * A space owns a client-generated keypair whose public key is its id, a\n * symmetric group key distributed server-blind via the keyring, and a\n * persisted message log. This namespace wires the {@link Space} handle to the\n * HTTP {@link KeyringClient}, the member's identity keys (from {@link KeyStore},\n * shared with the Double Ratchet path), and a PersonalSpace-backed key cache.\n */\n\nimport type { HttpClient } from \"../HttpClient\";\nimport { HttpError } from \"../HttpClient\";\nimport type { SessionState } from \"../Session\";\nimport { KeyStore } from \"../../crypto/KeyStore\";\nimport { Space } from \"../../spaces/Space\";\nimport { SpaceKeyring, KEEPER_MEMBER_ID, type SpaceKeyCache } from \"../../spaces/SpaceKeyring\";\nimport { KeyringClient } from \"../../spaces/KeyringClient\";\nimport { generateSpaceIdentity, exportEcdhPublicKey, exportEcdsaPublicKey } from \"../../spaces/SpaceCipher\";\nimport type { HistoryPolicy } from \"../../spaces/types\";\n\n/** Thrown by `joinChannel` when no channel with that name is registered. */\nexport class ChannelNotFoundError extends Error {\n constructor(readonly channelName: string) {\n super(`Channel \"${channelName}\" does not exist. Create it first.`);\n this.name = \"ChannelNotFoundError\";\n }\n}\n\n/** Thrown by `createChannel` when the name is already registered. */\nexport class ChannelExistsError extends Error {\n constructor(readonly channelName: string) {\n super(`Channel \"${channelName}\" already exists.`);\n this.name = \"ChannelExistsError\";\n }\n}\n\nexport interface SpaceNamespaceDeps {\n http: HttpClient;\n session: SessionState;\n /** WebSocket base (ws/wss); derived from the accelerator baseUrl. */\n wsBaseUrl: string;\n /** Optional PersonalSpace-backed cache of group keys (encrypted at rest). */\n cache?: SpaceKeyCache;\n}\n\nexport class SpaceNamespace {\n constructor(private readonly deps: SpaceNamespaceDeps) {}\n\n /**\n * Create a new space: generate its keypair (public key = id), register\n * metadata, mint the initial group key, and connect. Returns the open Space.\n */\n async createSpace(opts: { historyPolicy?: HistoryPolicy; private?: boolean } = {}): Promise<Space> {\n const historyPolicy = opts.historyPolicy ?? \"static\";\n const identity = await generateSpaceIdentity();\n // Register the space (server records pubkey + policy; the DO is lazy).\n // For a private space the server also records the creator (this user) as\n // its first member — so the metadata POST must carry the user session.\n await this.deps.http.post(\n `/api/spaces/${encodeURIComponent(identity.id)}/metadata`,\n { spacePubKey: identity.id, historyPolicy, visibility: opts.private ? \"private\" : \"public\" },\n );\n const space = await this.build(identity.id, historyPolicy);\n await space.create();\n return space;\n }\n\n /** Join an existing space by id (its public key). Resolves once a key arrives. */\n async joinSpace(spaceId: string, opts: { timeoutMs?: number } = {}): Promise<Space> {\n const policy = await this.fetchPolicy(spaceId);\n const space = await this.build(spaceId, policy);\n await space.join({ timeoutMs: opts.timeoutMs });\n return space;\n }\n\n /** A handle to a space without auto-connecting (uses cached keys on demand). */\n async get(spaceId: string, historyPolicy: HistoryPolicy = \"static\"): Promise<Space> {\n return this.build(spaceId, historyPolicy);\n }\n\n // -------------------------------------------------------------------------\n // Channels — named, app-scoped pointers to spaces. The name → space-id\n // directory is app-public config (server-readable, scoped to this app via\n // its key); the channel CONTENTS stay fan-out E2E-encrypted. Lets chat use\n // human room names (`general`) instead of raw pubkey ids.\n // -------------------------------------------------------------------------\n\n /** List this app's channels (name → space-id) for the key's environment. */\n async listChannels(): Promise<Array<{ name: string; spaceId: string }>> {\n const body = await this.deps.http.get<{ channels?: Array<{ name: string; spaceId: string }> }>(\n \"/api/app/channels\",\n );\n return body.channels ?? [];\n }\n\n /** Resolve a channel name to its space id, or null if it doesn't exist. */\n async resolveChannel(name: string): Promise<string | null> {\n try {\n const body = await this.deps.http.get<{ spaceId: string }>(\n `/api/app/channels/${encodeURIComponent(name)}`,\n );\n return body.spaceId ?? null;\n } catch (err) {\n if (err instanceof HttpError && err.status === 404) return null;\n throw err;\n }\n }\n\n /**\n * Create a new channel: mint a fan-out space (the caller becomes its first\n * key-holder) and register `name → spaceId` in the app directory. Throws\n * {@link ChannelExistsError} if the name is already taken.\n */\n async createChannel(name: string, opts: { historyPolicy?: HistoryPolicy; private?: boolean } = {}): Promise<Space> {\n const space = await this.createSpace(opts);\n // Register name → id first so a name clash doesn't leave an admitted keeper.\n try {\n await this.deps.http.post(\"/api/app/channels\", { name, spaceId: space.id, visibility: opts.private ? \"private\" : \"public\" });\n } catch (err) {\n if (err instanceof HttpError && err.status === 409) {\n throw new ChannelExistsError(name);\n }\n throw err;\n }\n // Admit the app keeper so the channel is joinable with no member online.\n // Best-effort: a channel still works (members admit each other) without it.\n try {\n const { pubkey } = await this.deps.http.get<{ pubkey?: string }>(\"/api/app/keeper\");\n if (pubkey && space.keyring) await space.keyring.admit(KEEPER_MEMBER_ID, pubkey);\n } catch (err) {\n console.warn(\"[client.space] keeper admit failed (channel still usable):\", err);\n }\n return space;\n }\n\n /**\n * Join an existing channel by name. Throws {@link ChannelNotFoundError} if\n * no channel with that name is registered (use {@link createChannel} first).\n */\n async joinChannel(name: string, opts: { timeoutMs?: number } = {}): Promise<Space> {\n const spaceId = await this.resolveChannel(name);\n if (!spaceId) throw new ChannelNotFoundError(name);\n return this.joinSpace(spaceId, opts);\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private async build(spaceId: string, historyPolicy: HistoryPolicy): Promise<Space> {\n const memberId = this.myId();\n const { ecdhPub, ecdsaPub } = await this.ensureIdentity(memberId);\n const transport = new KeyringClient({\n spaceId,\n httpBaseUrl: this.deps.http.baseUrl,\n fetch: this.deps.http.fetch,\n });\n const keyring = new SpaceKeyring({\n spaceId,\n memberId,\n identityEcdhPub: ecdhPub,\n identityEcdsaPub: ecdsaPub,\n ownPrivateKey: () => KeyStore.getInstance().getKeyPair(memberId)?.privateKey ?? null,\n transport,\n cache: this.deps.cache,\n historyPolicy,\n });\n return new Space({\n name: spaceId,\n wsBaseUrl: this.deps.wsBaseUrl,\n httpBaseUrl: this.deps.http.baseUrl,\n fetch: this.deps.http.fetch,\n myId: () => memberId,\n fetchTicket: () => this.fetchTicket(),\n keyring,\n historyPolicy,\n });\n }\n\n /** Ensure the member has an identity keypair; return its public ECDH + ECDSA keys. */\n private async ensureIdentity(memberId: string): Promise<{ ecdhPub: string; ecdsaPub: string }> {\n const store = KeyStore.getInstance();\n if (!store.getKeyPair(memberId)) {\n await store.generateOwnKeyPair(memberId);\n }\n const ecdhPub = await exportEcdhPublicKey(store.getKeyPair(memberId)!.publicKey);\n const ecdsaPub = await exportEcdsaPublicKey(store.getAuthKeyPair(memberId)!.publicKey);\n return { ecdhPub, ecdsaPub };\n }\n\n private async fetchPolicy(spaceId: string): Promise<HistoryPolicy> {\n const meta = await new KeyringClient({\n spaceId,\n httpBaseUrl: this.deps.http.baseUrl,\n fetch: this.deps.http.fetch,\n }).fetchMetadata();\n return meta?.historyPolicy ?? \"static\";\n }\n\n private async fetchTicket(): Promise<string | null> {\n try {\n const res = await this.deps.http.post<{ ticket: string }>(\"/api/ws-ticket\", {});\n return res?.ticket ?? null;\n } catch {\n return null;\n }\n }\n\n private myId(): string {\n const id = this.deps.session.username;\n if (!id) throw new Error(\"client.space: not signed in — call client.auth.zk.login() first.\");\n return id;\n }\n}\n\nexport default SpaceNamespace;\n","/**\n * `Client` — the single entry point to the Muhkoo SDK.\n *\n * Everything an app does flows through namespaces hanging off one client:\n *\n * const client = new Client({ apiKey, baseUrl });\n * const user = await client.auth.zk.login(username, password);\n * await client.storage.set('todos', id, { title, completed: false });\n * client.message.subscribe('todos', e => …);\n * await client.message.send('user:abc', { text: 'Hello!' });\n *\n * The client owns:\n * - an {@link HttpClient} that stamps the app key + session token onto every\n * request to the accelerator;\n * - a {@link SessionState} shared across namespaces (auth writes it; storage\n * and message read identity + token from it);\n * - the three namespaces: {@link AuthNamespace}, {@link StorageNamespace},\n * {@link MessageNamespace}.\n *\n * The lower-level building blocks (`AuthClient`, `PersonalSpaceClient`,\n * `FileStorage`, `EncryptedSession`, `Network`, …) remain exported and usable\n * directly, but the client is the supported, ergonomic surface.\n */\n\nimport { AuthClient } from \"../auth\";\nimport { defaultCircuitUrls, type CircuitUrls } from \"../auth/proof\";\nimport { HttpClient } from \"./HttpClient\";\nimport { SessionState, defaultSessionStore, type SessionStore } from \"./Session\";\nimport { AuthNamespace } from \"./namespaces/AuthNamespace\";\nimport { KvNamespace } from \"./namespaces/KvNamespace\";\nimport { StorageNamespace } from \"./namespaces/FileNamespace\";\nimport { MessageNamespace } from \"./namespaces/MessageNamespace\";\nimport { SpaceNamespace } from \"./namespaces/SpaceNamespace\";\nimport type { SpaceKeyCache } from \"../spaces/SpaceKeyring\";\n\n/** The hosted Muhkoo Accelerator — the default {@link ClientOptions.baseUrl}. */\nexport const DEFAULT_BASE_URL = \"https://api.muhkoo.dev\";\n\nexport interface ClientOptions {\n /**\n * App / publishable key issued by the accelerator (e.g. `mk_test_pk_…`).\n *\n * TRANSITIONALLY optional: auth + storage currently function without it so\n * the in-tree web app can migrate before a key is provisioned. The product\n * direction is that the app key becomes REQUIRED — it's how every app\n * authenticates to the Accelerator and gets attributed for metering/billing.\n * New integrations should always pass one.\n */\n apiKey?: string;\n /**\n * Absolute URL of the accelerator (trailing slash optional). Defaults to\n * the hosted Muhkoo Accelerator ({@link DEFAULT_BASE_URL}); override to\n * point at staging, a local `wrangler dev`, or a self-hosted deployment.\n */\n baseUrl?: string;\n /**\n * URLs of the `preimagePoK` circuit assets used for ZK login proofs.\n * Defaults to {@link defaultCircuitUrls} anchored at `baseUrl` — i.e.\n * `${baseUrl}/circuits/build/preimagePoK_js/preimagePoK.wasm` and\n * `…/preimagePoK_0001.zkey`, where the accelerator serves them.\n */\n circuits?: CircuitUrls;\n /** Pluggable session-token persistence. Defaults to in-memory. */\n sessionStore?: SessionStore;\n /** Custom fetch — defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n /** Optional log level for the SDK logger. */\n logLevel?: string;\n}\n\n/**\n * Turn the HTTP base URL into a websocket base (`http(s)://` → `ws(s)://`).\n * The accelerator serves spaces over both on the same origin.\n */\nfunction toWsBase(baseUrl: string): string {\n return baseUrl.replace(/\\/+$/, \"\").replace(/^http/, \"ws\");\n}\n\nexport class Client {\n readonly baseUrl: string;\n\n /** Authentication — `client.auth.zk.login(...)`, etc. */\n readonly auth: AuthNamespace;\n /** Per-user key/value storage — `client.kv.set(...)`, etc. */\n readonly kv: KvNamespace;\n /** File storage — `client.storage.writeFile(...)`, etc. */\n readonly storage: StorageNamespace;\n /** Realtime messaging — `client.message.subscribe(...)`, etc. */\n readonly message: MessageNamespace;\n /** Fan-out group spaces — `client.space.createSpace(...)`, etc. */\n readonly space: SpaceNamespace;\n\n private readonly session: SessionState;\n private readonly http: HttpClient;\n\n /** Subscribers notified when a session expires and can't be recovered. */\n private readonly sessionExpiredHandlers = new Set<() => void>();\n /** Shared in-flight recovery so a burst of 401s triggers one re-auth. */\n private recoverInFlight: Promise<boolean> | null = null;\n\n constructor(options: ClientOptions = {}) {\n if (options.logLevel && typeof globalThis.appLogger?.setLevel === \"function\") {\n globalThis.appLogger.setLevel(options.logLevel);\n }\n\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n this.session = new SessionState(options.sessionStore ?? defaultSessionStore());\n\n this.http = new HttpClient({\n baseUrl: this.baseUrl,\n apiKey: options.apiKey,\n getSessionToken: () => this.session.token,\n fetch: options.fetch,\n // Self-heal stale sessions: on a 401, try a silent re-auth (only\n // works while unlocked). If it can't, `recoverSession` fires the\n // session-expired event so the app can redirect to login.\n onUnauthorized: () => this.recoverSession(),\n });\n\n const circuits = options.circuits ?? defaultCircuitUrls(this.baseUrl);\n const authClient = new AuthClient({ baseUrl: this.baseUrl, fetch: this.http.fetch });\n\n const wsBaseUrl = toWsBase(this.baseUrl);\n this.auth = new AuthNamespace({ auth: authClient, circuits, session: this.session });\n this.kv = new KvNamespace({ http: this.http, session: this.session, wsBaseUrl });\n this.storage = new StorageNamespace({ http: this.http, baseUrl: this.baseUrl, kv: this.kv });\n this.message = new MessageNamespace({ http: this.http, session: this.session, wsBaseUrl });\n\n // Group keys are cached in the user's PersonalSpace (encrypted at rest\n // by client.kv), so a returning member hydrates without a fresh keyring\n // round-trip. The server only ever sees the ciphertext.\n const spaceKeyCache: SpaceKeyCache = {\n loadKeys: (spaceId) => this.kv.get<Record<string, string>>(\"space-keys\", spaceId),\n saveKeys: (spaceId, keys) => this.kv.set(\"space-keys\", spaceId, keys),\n };\n this.space = new SpaceNamespace({\n http: this.http,\n session: this.session,\n wsBaseUrl,\n cache: spaceKeyCache,\n });\n }\n\n /** The currently signed-in user, or `null`. */\n get user() {\n return this.auth.user;\n }\n\n /** Whether a token-bearing session is active. */\n get isAuthenticated(): boolean {\n return this.session.isAuthenticated;\n }\n\n /**\n * Subscribe to session expiry that couldn't be silently recovered (the\n * user's identity wasn't in memory to re-prove — typically after a reload\n * where only the token was persisted, and that token has since gone stale).\n * This is the signal to send the user back to the login screen.\n *\n * Returns an unsubscribe function.\n *\n * const off = client.onSessionExpired(() => router.push('/login'));\n */\n onSessionExpired(handler: () => void): () => void {\n this.sessionExpiredHandlers.add(handler);\n return () => this.sessionExpiredHandlers.delete(handler);\n }\n\n /**\n * Attempt a silent re-auth of the current user. Concurrent callers share a\n * single in-flight attempt (a stale token usually 401s several requests at\n * once — we re-auth once, not once per request). On failure the\n * session-expired event fires so the app can react. Exposed so apps can\n * also drive recovery proactively (e.g. on `visibilitychange`).\n */\n recoverSession(): Promise<boolean> {\n if (this.recoverInFlight) return this.recoverInFlight;\n this.recoverInFlight = this.auth.zk\n .recover()\n .then((ok) => {\n if (!ok) {\n for (const handler of this.sessionExpiredHandlers) {\n try { handler(); } catch { /* a bad listener mustn't break recovery */ }\n }\n }\n return ok;\n })\n .finally(() => {\n this.recoverInFlight = null;\n });\n return this.recoverInFlight;\n }\n}\n\nexport default Client;\n","import Client from \"./Client\";\nimport { Logger } from \"../utilities/Logger\";\n\ndeclare global {\n var appLogger: InstanceType<typeof Logger>;\n}\n\nconst appLogger = new Logger(\"connect\", 'ERROR');\nglobalThis.appLogger = appLogger;\n\nexport {\n appLogger,\n Logger,\n Client,\n};\n\n// Unified client surface.\nexport { DEFAULT_BASE_URL } from \"./Client\";\nexport type { ClientOptions } from \"./Client\";\nexport { HttpClient, HttpError } from \"./HttpClient\";\nexport type { HttpClientOptions } from \"./HttpClient\";\nexport { SessionState, MemorySessionStore, LocalStorageSessionStore, defaultSessionStore } from \"./Session\";\nexport type { SessionStore, StoredSession } from \"./Session\";\nexport { Room } from \"./Room\";\nexport type { RoomDeps, RoomFileMetadata } from \"./Room\";\nexport { Space } from \"../spaces/Space\";\nexport type { SpaceDeps, SpaceFileMetadata, SpaceMessageEvent, EphemeralEvent, MessageDeletedEvent } from \"../spaces/Space\";\nexport { AuthNamespace, ZkAuth } from \"./namespaces/AuthNamespace\";\nexport type { AuthUser, RegisterParams, LoginOptions } from \"./namespaces/AuthNamespace\";\nexport { KvNamespace } from \"./namespaces/KvNamespace\";\nexport type { SetOptions, StorageChangeEvent } from \"./namespaces/KvNamespace\";\nexport { StorageNamespace } from \"./namespaces/FileNamespace\";\nexport type { WriteFileOptions } from \"./namespaces/FileNamespace\";\nexport { MessageNamespace } from \"./namespaces/MessageNamespace\";\nexport type { MessageSubscription } from \"./namespaces/MessageNamespace\";\nexport { SpaceNamespace, ChannelNotFoundError, ChannelExistsError } from \"./namespaces/SpaceNamespace\";\nexport type { SpaceNamespaceDeps } from \"./namespaces/SpaceNamespace\";\n","/**\n * Cloudflare-Workers-compatible Groth16 ZK proof verifier.\n *\n * Drives the BN128 WASM module's exported pairing functions directly. Does NOT\n * use snarkjs/ffjavascript — those depend on runtime features (most notably\n * `URL.createObjectURL`) that CF Workers don't expose. See ROADMAP / CLAUDE.md.\n *\n * Two ways to initialize:\n * 1. `await initBn128Wasm()` — uses the bundled bn128.wasm (base64-inlined at\n * build time via `@rollup/plugin-wasm`). Works in any modern JS runtime\n * that allows runtime `WebAssembly.compile()` — Node, browsers, most\n * Workers configurations.\n * 2. `await initBn128Wasm(myWasmModule)` — accepts a pre-compiled\n * `WebAssembly.Module`. Lets a CF-Workers consumer keep the native pattern\n * of importing `.wasm` so wrangler precompiles it at deploy time and the\n * worker never pays for runtime compilation.\n */\n\nimport loadBundledBn128 from \"./wasm/bn128.wasm\";\nimport type { Groth16Proof, VerificationKey } from \"../types/zk\";\n\n// Re-export the shared ZK types so workers consumers can pull everything from\n// one place: `import { verifyGroth16, type Groth16Proof } from \"@muhkoo/connect\"`.\nexport type { Groth16Proof, VerificationKey } from \"../types/zk\";\nexport { PREIMAGE_POK_VERIFICATION_KEY } from \"../types/zk\";\n\n// BN128 curve sizing\nconst n8q = 32;\nconst n8r = 32;\nconst f1size = n8q;\nconst g1size = f1size * 3;\nconst g2size = f1size * 6;\nconst ftsize = f1size * 12;\n\n// Field modulus q (base field) and r (scalar field)\nconst q = BigInt(\"21888242871839275222246405745257275088696311157297823662689037894645226208583\");\nconst r = BigInt(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\n\n// Initial linear memory: 25 * 64KB = 1.6MB\nconst MEM_SIZE = 25;\n\nexport interface Bn128WasmInstance {\n instance: WebAssembly.Instance;\n memory: WebAssembly.Memory;\n initialPFree: number;\n}\n\n/**\n * Initialize the BN128 WASM module.\n *\n * @param wasmModule Optional pre-compiled `WebAssembly.Module`. If omitted, the\n * bundled bn128.wasm (base64-inlined by `@rollup/plugin-wasm` at build time)\n * is used. Passing your own module is the recommended path inside CF Workers,\n * where wrangler can precompile a `.wasm` import at deploy time and avoid the\n * runtime compile cost.\n */\nexport async function initBn128Wasm(wasmModule?: WebAssembly.Module): Promise<Bn128WasmInstance> {\n const memory = new WebAssembly.Memory({ initial: MEM_SIZE, maximum: 32767 });\n const imports = { env: { memory } };\n\n let instance: WebAssembly.Instance;\n if (wasmModule) {\n instance = await WebAssembly.instantiate(wasmModule, imports);\n } else {\n // Bundled fallback: the rollup plugin returns a loader function that takes\n // an import object and resolves to an instantiated WebAssembly.Instance.\n instance = await loadBundledBn128(imports as Record<string, Record<string, unknown>>);\n }\n\n // The first u32 in linear memory is the heap free pointer (set by the module\n // during static initialization). Remember it so we can reset between calls.\n const u32 = new Uint32Array(memory.buffer);\n const initialPFree = u32[0];\n return { instance, memory, initialPFree };\n}\n\n/**\n * Verify a Groth16 proof.\n *\n * Returns `false` (rather than throwing) for any structural problem — malformed\n * proof, out-of-range field elements, off-curve points, or a failed pairing.\n * Throws only for runtime/WASM faults.\n */\nexport async function verifyGroth16(\n wasmInstance: WebAssembly.Instance,\n memory: WebAssembly.Memory,\n initialPFree: number,\n verificationKey: VerificationKey,\n proof: Groth16Proof,\n publicSignals: string[]\n): Promise<boolean> {\n try {\n const vk = unstringifyBigInts(verificationKey);\n const p = unstringifyBigInts(proof);\n const signals: bigint[] = unstringifyBigInts(publicSignals);\n\n // Validate proof coordinates are within the base field\n if (!validateG1InField(p.pi_a)) return false;\n if (!validateG1InField(p.pi_c)) return false;\n for (let i = 0; i < 2; i++) {\n for (let j = 0; j < 2; j++) {\n const val = typeof p.pi_b[i][j] === \"bigint\" ? p.pi_b[i][j] : BigInt(String(p.pi_b[i][j]));\n if (val >= q) return false;\n }\n }\n\n // Validate public signals are within the scalar field\n for (const signal of signals) {\n if (signal >= r) return false;\n }\n\n const exports = wasmInstance.exports;\n const u8 = new Uint8Array(memory.buffer);\n const u32 = new Uint32Array(memory.buffer);\n\n // Reset the WASM allocator's heap pointer between invocations\n u32[0] = initialPFree;\n\n const g1m_add = exports[\"g1m_add\"] as CallableFunction;\n const g1m_timesScalar = exports[\"g1m_timesScalar\"] as CallableFunction;\n const g1m_neg = exports[\"g1m_neg\"] as CallableFunction;\n const g1m_inCurve = exports[\"g1m_inCurve\"] as CallableFunction;\n const g2m_inCurve = exports[\"g2m_inCurve\"] as CallableFunction;\n const ftm_one = exports[\"ftm_one\"] as CallableFunction;\n const bn128_pairingEq4 = exports[\"bn128_pairingEq4\"] as CallableFunction;\n\n // Compute vk_x = IC[0] + sum(IC[i+1] * signal[i])\n const pVkX = alloc(u32, g1size);\n const pIC0 = alloc(u32, g1size);\n writeG1Point(u8, pIC0, vk.IC[0], exports);\n u8.set(u8.slice(pIC0, pIC0 + g1size), pVkX);\n\n const pTemp = alloc(u32, g1size);\n const pScalar = alloc(u32, n8r);\n\n for (let i = 0; i < signals.length; i++) {\n const pICi = alloc(u32, g1size);\n writeG1Point(u8, pICi, vk.IC[i + 1], exports);\n\n u8.set(bigIntToLE(signals[i], n8r), pScalar);\n g1m_timesScalar(pICi, pScalar, n8r, pTemp);\n\n const pSum = alloc(u32, g1size);\n g1m_add(pVkX, pTemp, pSum);\n u8.set(u8.slice(pSum, pSum + g1size), pVkX);\n }\n\n // Allocate proof points\n const pA = alloc(u32, g1size);\n const pNegA = alloc(u32, g1size);\n const pB = alloc(u32, g2size);\n const pC = alloc(u32, g1size);\n\n writeG1Point(u8, pA, p.pi_a, exports);\n writeG2Point(u8, pB, p.pi_b, exports);\n writeG1Point(u8, pC, p.pi_c, exports);\n\n // Subgroup / on-curve checks\n if (!g1m_inCurve(pA)) return false;\n if (!g2m_inCurve(pB)) return false;\n if (!g1m_inCurve(pC)) return false;\n\n g1m_neg(pA, pNegA);\n\n // Verification key points\n const pAlpha = alloc(u32, g1size);\n const pBeta = alloc(u32, g2size);\n const pGamma = alloc(u32, g2size);\n const pDelta = alloc(u32, g2size);\n\n writeG1Point(u8, pAlpha, vk.vk_alpha_1, exports);\n writeG2Point(u8, pBeta, vk.vk_beta_2, exports);\n writeG2Point(u8, pGamma, vk.vk_gamma_2, exports);\n writeG2Point(u8, pDelta, vk.vk_delta_2, exports);\n\n // Target: F12 element representing 1\n const pOne = alloc(u32, ftsize);\n ftm_one(pOne);\n\n // e(-A, B) * e(alpha, beta) * e(vk_x, gamma) * e(C, delta) == 1\n const result = bn128_pairingEq4(\n pNegA, pB,\n pAlpha, pBeta,\n pVkX, pGamma,\n pC, pDelta,\n pOne\n );\n\n return result === 1;\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\nfunction parseToBigInt(value: bigint | string | number): bigint {\n if (typeof value === \"string\") {\n if (/^0x[0-9a-fA-F]+$/.test(value)) return BigInt(value);\n if (/^[0-9a-fA-F]+$/.test(value) && /[a-fA-F]/.test(value)) return BigInt(\"0x\" + value);\n if (/^[0-9]+$/.test(value)) return BigInt(value);\n throw new Error(`Cannot convert ${value} to BigInt`);\n }\n if (typeof value === \"number\") return BigInt(value);\n return value;\n}\n\nfunction bigIntToLE(value: bigint | string | number, size: number): Uint8Array {\n const result = new Uint8Array(size);\n let v = parseToBigInt(value);\n for (let i = 0; i < size; i++) {\n result[i] = Number(v & 0xffn);\n v = v >> 8n;\n }\n return result;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction unstringifyBigInts(o: any): any {\n if (typeof o === \"string\") {\n try {\n if (/^[0-9]+$/.test(o) || /^0x[0-9a-fA-F]+$/.test(o) ||\n (/^[0-9a-fA-F]+$/.test(o) && /[a-fA-F]/.test(o))) {\n return parseToBigInt(o);\n }\n } catch {\n // fall through\n }\n return o;\n }\n if (Array.isArray(o)) return o.map(unstringifyBigInts);\n if (typeof o === \"object\" && o !== null) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const res: any = {};\n for (const k of Object.keys(o)) res[k] = unstringifyBigInts(o[k]);\n return res;\n }\n return o;\n}\n\nfunction validateG1InField(point: (bigint | string | number)[]): boolean {\n const x = typeof point[0] === \"bigint\" ? point[0] : BigInt(String(point[0]));\n const y = typeof point[1] === \"bigint\" ? point[1] : BigInt(String(point[1]));\n return x < q && y < q;\n}\n\nfunction writeG1Point(\n u8: Uint8Array,\n offset: number,\n point: (bigint | string | number)[],\n exports: WebAssembly.Exports\n): void {\n const x = point[0];\n const y = point[1];\n const z = point.length > 2 ? point[2] : 1n;\n\n u8.set(bigIntToLE(x, f1size), offset);\n u8.set(bigIntToLE(y, f1size), offset + f1size);\n u8.set(bigIntToLE(z, f1size), offset + 2 * f1size);\n\n const f1m_toMontgomery = exports[\"f1m_toMontgomery\"] as CallableFunction;\n f1m_toMontgomery(offset, offset);\n f1m_toMontgomery(offset + f1size, offset + f1size);\n f1m_toMontgomery(offset + 2 * f1size, offset + 2 * f1size);\n}\n\nfunction writeG2Point(\n u8: Uint8Array,\n offset: number,\n point: (bigint | string | number)[][],\n exports: WebAssembly.Exports\n): void {\n const x = point[0];\n const y = point[1];\n const z = point.length > 2 ? point[2] : [1n, 0n];\n\n u8.set(bigIntToLE(x[0], f1size), offset);\n u8.set(bigIntToLE(x[1], f1size), offset + f1size);\n u8.set(bigIntToLE(y[0], f1size), offset + 2 * f1size);\n u8.set(bigIntToLE(y[1], f1size), offset + 3 * f1size);\n u8.set(bigIntToLE(z[0], f1size), offset + 4 * f1size);\n u8.set(bigIntToLE(z[1], f1size), offset + 5 * f1size);\n\n const f1m_toMontgomery = exports[\"f1m_toMontgomery\"] as CallableFunction;\n for (let i = 0; i < 6; i++) {\n f1m_toMontgomery(offset + i * f1size, offset + i * f1size);\n }\n}\n\nfunction alloc(u32: Uint32Array, size: number): number {\n while (u32[0] & 3) u32[0]++;\n const ptr = u32[0];\n u32[0] += size;\n return ptr;\n}\n","/**\n * `PersonalSpaceClient` — the client-side counterpart to the accelerator's\n * `PersonalSpaceDO`. Wraps the `/api/personal/:commitment/*` HTTP protocol so\n * callers can `put` / `get` / `delete` / `list` per-user KV blobs without\n * thinking about challenges, nonces, or Groth16 proof generation.\n *\n * Every gated operation:\n * 1. Requests a one-shot challenge from the DO (`POST /challenge`).\n * 2. Converts the returned hex nonce into a BN254 field element.\n * 3. Generates a fresh Groth16 proof for the `preimagePoK` circuit using\n * snarkjs, with the user's secret/salt/ecdsaPub as private inputs and\n * `{commitment, nonce, ecdsaPubHash}` as public signals.\n * 4. POSTs the proof + publicSignals + (optional) value to the gated endpoint.\n *\n * snarkjs is loaded lazily (dynamic `import`) the first time a proof is\n * generated — it's an optional peer dependency that only the ZK-proof path\n * needs, so importing this module (or constructing a `Client`) never requires\n * it. Consumers using the proof path install `snarkjs`, or provide it via an\n * import map in the browser (see the README).\n *\n * Encryption of the stored values is the caller's responsibility — the DO\n * sees only opaque JSON. The companion `wrap.ts` helpers in this folder are\n * a convenient way to passphrase-encrypt a payload before putting it.\n */\n\nimport type { Groth16Proof } from \"../types/zk\";\n\ntype Snarkjs = {\n groth16: {\n fullProve: (\n input: unknown,\n wasm: string,\n zkey: string,\n ) => Promise<{ proof: unknown; publicSignals: string[] }>;\n };\n};\nlet _snarkjs: Snarkjs | null = null;\nasync function loadSnarkjs(): Promise<Snarkjs> {\n if (_snarkjs) return _snarkjs;\n _snarkjs = (await import(\"snarkjs\")) as unknown as Snarkjs;\n return _snarkjs;\n}\n\n/**\n * BN254 scalar field modulus. The DO's challenge endpoint returns a 32-byte\n * random hex nonce — but the Circom circuit expects a field element, so the\n * nonce is reduced mod this prime before being fed into the witness.\n *\n * Must stay in sync with the `nonce` public-signal width used by both\n * accelerator's `verifyZkAuthProof` and the `preimagePoK` circuit.\n */\nconst FIELD_SIZE = 21888242871839275222246405745257275088548364400416034343698204186575808495617n;\n\n/**\n * Constructor options for {@link PersonalSpaceClient}.\n *\n * All of `secret`, `salt`, `ecdsaPub`, and `ecdsaPubHash` are decimal-encoded\n * BigInt strings (snarkjs convention). `commitment` is likewise decimal — it's\n * the Poseidon hash of `(secret, salt, ecdsaPubHash)`.\n */\nexport interface PersonalSpaceClientOptions {\n /** Base URL of the accelerator, e.g. `http://localhost:8787`. */\n baseUrl: string;\n /** The user's Poseidon commitment as a decimal string (~78 digits). */\n commitment: string;\n /** ZK identity material — private inputs to the proof. Decimal BigInt string. */\n secret: string;\n /** ZK identity salt. Decimal BigInt string. */\n salt: string;\n /** Raw ECDSA public-key field representation. Decimal BigInt string. */\n ecdsaPub: string;\n /** Poseidon hash of `ecdsaPub`, used as a public signal. Decimal BigInt string. */\n ecdsaPubHash: string;\n /** Where the runtime can fetch the compiled circuit assets. */\n circuits: {\n /** URL of the `preimagePoK.wasm` witness generator. */\n wasmUrl: string;\n /** URL of the `preimagePoK_0001.zkey` proving key. */\n zkeyUrl: string;\n };\n}\n\n/** Shape of the DO's `/challenge` response. */\ninterface ChallengeResponse {\n challengeId: string;\n nonce: string; // hex\n commitment: string;\n}\n\n/** Body shape sent to every gated endpoint. `value` is only used by PUT. */\ninterface GatedBody {\n challengeId: string;\n proof: Groth16Proof;\n publicSignals: string[];\n value?: unknown;\n}\n\n/**\n * Reduce a hex nonce into a BN254 field-element decimal string, matching what\n * the Circom circuit expects as the `nonce` public signal.\n */\nfunction nonceHexToFieldString(nonceHex: string): string {\n const hex = nonceHex.startsWith(\"0x\") ? nonceHex : \"0x\" + nonceHex;\n return (BigInt(hex) % FIELD_SIZE).toString();\n}\n\n/**\n * Read the response body as JSON, falling back to text for the error message\n * when the body isn't JSON. Centralized so every method handles failures the\n * same way.\n */\nasync function parseOrThrow<T>(response: Response, label: string): Promise<T> {\n if (!response.ok) {\n let detail = \"\";\n try {\n const text = await response.text();\n detail = text ? `: ${text}` : \"\";\n } catch {\n // ignore — we'll just use the status code\n }\n throw new Error(`PersonalSpaceClient ${label} failed (${response.status})${detail}`);\n }\n return (await response.json()) as T;\n}\n\nexport class PersonalSpaceClient {\n private readonly baseUrl: string;\n private readonly commitment: string;\n private readonly secret: string;\n private readonly salt: string;\n private readonly ecdsaPub: string;\n private readonly ecdsaPubHash: string;\n private readonly wasmUrl: string;\n private readonly zkeyUrl: string;\n\n constructor(opts: PersonalSpaceClientOptions) {\n if (!opts.baseUrl) throw new Error(\"PersonalSpaceClient: `baseUrl` is required\");\n if (!opts.commitment) throw new Error(\"PersonalSpaceClient: `commitment` is required\");\n if (!opts.secret) throw new Error(\"PersonalSpaceClient: `secret` is required\");\n if (!opts.salt) throw new Error(\"PersonalSpaceClient: `salt` is required\");\n if (!opts.ecdsaPub) throw new Error(\"PersonalSpaceClient: `ecdsaPub` is required\");\n if (!opts.ecdsaPubHash) throw new Error(\"PersonalSpaceClient: `ecdsaPubHash` is required\");\n if (!opts.circuits?.wasmUrl || !opts.circuits?.zkeyUrl) {\n throw new Error(\"PersonalSpaceClient: `circuits.wasmUrl` and `circuits.zkeyUrl` are required\");\n }\n\n // Strip trailing slash so concatenation stays clean regardless of how\n // the caller formatted the base URL.\n this.baseUrl = opts.baseUrl.replace(/\\/+$/, \"\");\n this.commitment = opts.commitment;\n this.secret = opts.secret;\n this.salt = opts.salt;\n this.ecdsaPub = opts.ecdsaPub;\n this.ecdsaPubHash = opts.ecdsaPubHash;\n this.wasmUrl = opts.circuits.wasmUrl;\n this.zkeyUrl = opts.circuits.zkeyUrl;\n }\n\n /** Store `value` under `key`, replacing any prior value. */\n async put(key: string, value: unknown): Promise<void> {\n const { challengeId, proof, publicSignals } = await this.proveFreshChallenge();\n const url = `${this.baseUrl}/api/personal/${encodeURIComponent(this.commitment)}/kv/${encodeURIComponent(key)}`;\n const body: GatedBody = { challengeId, proof, publicSignals, value };\n const response = await this.fetch(url, \"POST\", body);\n await parseOrThrow<{ ok: true }>(response, `put(${key})`);\n }\n\n /** Fetch the value stored under `key`. Returns `null` if absent. */\n async get<T = unknown>(key: string): Promise<T | null> {\n const { challengeId, proof, publicSignals } = await this.proveFreshChallenge();\n const url = `${this.baseUrl}/api/personal/${encodeURIComponent(this.commitment)}/kv/${encodeURIComponent(key)}/get`;\n const body: GatedBody = { challengeId, proof, publicSignals };\n const response = await this.fetch(url, \"POST\", body);\n const data = await parseOrThrow<{ key: string; value: T | null }>(response, `get(${key})`);\n return data.value ?? null;\n }\n\n /** Remove `key` from the user's space. Returns whether the key existed. */\n async delete(key: string): Promise<boolean> {\n const { challengeId, proof, publicSignals } = await this.proveFreshChallenge();\n const url = `${this.baseUrl}/api/personal/${encodeURIComponent(this.commitment)}/kv/${encodeURIComponent(key)}`;\n const body: GatedBody = { challengeId, proof, publicSignals };\n const response = await this.fetch(url, \"DELETE\", body);\n const data = await parseOrThrow<{ ok: true; existed: boolean }>(response, `delete(${key})`);\n return data.existed;\n }\n\n /** List every key currently stored in the user's space. */\n async list(): Promise<string[]> {\n const { challengeId, proof, publicSignals } = await this.proveFreshChallenge();\n const url = `${this.baseUrl}/api/personal/${encodeURIComponent(this.commitment)}/list`;\n const body: GatedBody = { challengeId, proof, publicSignals };\n const response = await this.fetch(url, \"POST\", body);\n const data = await parseOrThrow<{ keys: string[] }>(response, \"list()\");\n return Array.isArray(data.keys) ? data.keys : [];\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n /**\n * Run the full pre-flight: ask the DO for a challenge, reduce the nonce to\n * a field element, and generate a fresh Groth16 proof. Returns everything\n * the gated endpoints need in their body.\n */\n private async proveFreshChallenge(): Promise<{\n challengeId: string;\n proof: Groth16Proof;\n publicSignals: string[];\n }> {\n const challenge = await this.requestChallenge();\n const nonceField = nonceHexToFieldString(challenge.nonce);\n\n // Inputs to the `preimagePoK` circuit. Public signals are\n // `[commitment, nonce, ecdsaPubHash]`; the rest are private witnesses.\n const input = {\n commitment: this.commitment,\n nonce: nonceField,\n ecdsaPubHash: this.ecdsaPubHash,\n secret: this.secret,\n salt: this.salt,\n ecdsaPub: this.ecdsaPub,\n };\n\n const snarkjs = await loadSnarkjs();\n const { proof, publicSignals } = await snarkjs.groth16.fullProve(\n input,\n this.wasmUrl,\n this.zkeyUrl,\n );\n\n return {\n challengeId: challenge.challengeId,\n proof: proof as unknown as Groth16Proof,\n publicSignals: publicSignals as string[],\n };\n }\n\n /** Hit `POST /challenge` and return the issued nonce + ID. */\n private async requestChallenge(): Promise<ChallengeResponse> {\n const url = `${this.baseUrl}/api/personal/${encodeURIComponent(this.commitment)}/challenge`;\n const response = await this.fetch(url, \"POST\", {});\n return await parseOrThrow<ChallengeResponse>(response, \"challenge\");\n }\n\n /**\n * Thin wrapper over `globalThis.fetch` so all methods share a single set of\n * headers and body-encoding behaviour. `globalThis.fetch` is available in\n * modern browsers, Node 18+, Workers, and Bun.\n */\n private async fetch(url: string, method: string, body: unknown): Promise<Response> {\n const fetchFn = globalThis.fetch;\n if (typeof fetchFn !== \"function\") {\n throw new Error(\n \"PersonalSpaceClient: `globalThis.fetch` is not available. \" +\n \"On older Node versions, install a fetch polyfill (e.g. undici).\",\n );\n }\n return await fetchFn(url, {\n method,\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body ?? {}),\n });\n }\n}\n","/**\n * PacketCipher — the strategy `Network` uses to seal/open a packet's payload.\n *\n * `Network` owns the wire shape (Message ↔ Packet, header placement, transport,\n * reconnect, checksum). The *encryption* is pluggable: the default\n * {@link DoubleRatchetCipher} reproduces the per-peer Double Ratchet behavior\n * Network has always had, while the Space layer supplies a group-key cipher.\n *\n * The sealed ciphertext always rides in `Packet.headers` (cleartext routing\n * fields stay readable to the server); `Packet.message` is left undefined on\n * the wire so the server never sees the real payload.\n */\n\nimport type { Packet } from \"../messaging/Packet\";\nimport type { DoubleRatchetManager, CipherMessage } from \"../crypto/DoubleRatchetManager\";\n\nexport type PacketHeaders = Packet[\"headers\"];\n\n/** Header fields a cipher merges into the outgoing packet. */\nexport type SealedHeaders = Record<string, string | number | boolean>;\n\nexport interface PacketCipher {\n /**\n * Seal the serialized `Message`. Returns the header fields to merge into\n * the outgoing packet (these carry the ciphertext). `Network` clears\n * `packet.message` after calling this.\n */\n seal(serializedMessage: string, packet: Packet): Promise<SealedHeaders>;\n\n /** True if the inbound headers look like this cipher's sealed form. */\n handles(headers: PacketHeaders): boolean;\n\n /**\n * Open an inbound packet's headers back into a serialized `Message` string.\n * Returns `null` when the packet is not sealed for / not decryptable by us\n * (e.g. an epoch key we don't hold) — `Network` then leaves `packet.message`\n * untouched rather than throwing.\n */\n open(headers: PacketHeaders): Promise<string | null>;\n}\n\nexport interface DoubleRatchetCipherDeps {\n ratchetManager: DoubleRatchetManager;\n clientId: string;\n serverId: string;\n sessionType: \"global\" | \"specific\";\n /** Resolves the live session id (Network manages the session lifecycle). */\n getSessionId: () => string | null;\n /** Whether this side is the ratchet \"client\" (default true). */\n isClient?: boolean;\n}\n\n/**\n * Default cipher: per-peer Double Ratchet. Reproduces Network's original\n * `{ encrypted: true, cipherMessage: <json> }` header convention exactly so\n * existing consumers are unaffected.\n */\nexport class DoubleRatchetCipher implements PacketCipher {\n constructor(private readonly deps: DoubleRatchetCipherDeps) {}\n\n async seal(serializedMessage: string): Promise<SealedHeaders> {\n const sessionId = this.deps.getSessionId();\n if (!sessionId) {\n throw new Error(\"DoubleRatchetCipher: no active session to seal under\");\n }\n const cipherMessage = await this.deps.ratchetManager.encrypt(\n this.deps.clientId,\n this.deps.serverId,\n sessionId,\n serializedMessage,\n false, // newDhKey — let the ratchet manage key rotation\n this.deps.sessionType,\n );\n return { encrypted: true, cipherMessage: JSON.stringify(cipherMessage) };\n }\n\n handles(headers: PacketHeaders): boolean {\n return !!(headers?.encrypted && headers?.cipherMessage);\n }\n\n async open(headers: PacketHeaders): Promise<string | null> {\n if (!this.handles(headers)) return null;\n const cipherMessage = JSON.parse(headers!.cipherMessage as string) as CipherMessage;\n return this.deps.ratchetManager.decrypt(cipherMessage, this.deps.isClient ?? true);\n }\n}\n","/**\n * Bundled-WASM loader for the RS codec.\n *\n * Isolated in its own module so the rollup-plugin-wasm `import` of `.wasm` is\n * only encountered when this file is actually evaluated. The main `rs.ts`\n * file dynamically imports this module only on the fallback path (no\n * pre-compiled `WebAssembly.Module` provided), which lets tools that can't\n * parse the `.wasm` import (vitest under vite, without `vite-plugin-wasm`)\n * import `rs.ts` cleanly as long as callers always supply a module.\n *\n * Production builds (rollup) hit this path via the bundled loader; tests\n * skip it entirely by passing a fs-loaded module to `initRsWasm`.\n */\n\nimport loadRsWasm from \"./wasm_reed_solomon_erasure_bg.wasm\";\n\n/** Re-exports the rollup-plugin-wasm loader shape. */\nexport default loadRsWasm;\n"],"names":["loadPoseidon","groth16Prove","groth16Verify","bytesToBase64","_snarkjs","loadSnarkjs","FIELD_SIZE","wasmEncode","wasmReconstruct","parseOrThrow","Room","appLogger"],"mappings":";;;;AAAA;;;;;;;AAOG;SAEa,SAAS,GAAA;AACrB,IAAA,MAAM,CAAC,GAAI,UAAU,CAAC,MAA6B,EAAE,MAAM;IAC3D,IAAI,CAAC,CAAC,EAAE;QACJ,MAAM,IAAI,KAAK,CACX,qEAAqE;AACrE,YAAA,+DAA+D,CAClE;IACL;AACA,IAAA,OAAO,CAAC;AACZ;;AClBA;;;;;;;;;;;AAWG;AAEH,MAAM,YAAY,GAAG,KAAK;AAEpB,SAAU,WAAW,CAAC,CAAS,EAAA;AACjC,IAAA,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;AAC/B,QAAA,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAA,CAAA,CAAG,CAAC;IAC/E;IACA,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC;AAC9C,IAAA,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,MAAM,GAAG,CAAC,EAAE,MAAM,IAAI,YAAY,EAAE;AACrD,QAAA,MAAM,KAAK,GAAG,GAAG,CAAC,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,MAAM,GAAG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,YAAA,OAAO,IAAI;QACvC,MAAM,aAAa,GAAG,IAAI,CAAC,KAAK,CAAC,OAAQ,CAAC,aAAuB,CAAkB;AACnF,QAAA,OAAO,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC;IACtF;AACH;;;;ACrFD;;;;;;;;;;;;AAYG;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../src/crypto/primitives/subtle.ts","../../src/crypto/primitives/random.ts","../../src/crypto/primitives/aes-gcm.ts","../../src/crypto/primitives/kdf.ts","../../src/utilities/Logger.ts","../../src/utilities/bytes.ts","../../src/utilities/index.ts","../../src/crypto/KeyStore.ts","../../src/crypto/DoubleRatchet.ts","../../src/crypto/ZeroKnowledge.ts","../../src/crypto/Authenticator.ts","../../src/crypto/DoubleRatchetManager.ts","../../src/crypto/ChunkCipher.ts","../../src/crypto/PassphraseWrap.ts","../../src/types/zk.ts","../../src/events/EventCore.ts","../../src/messaging/Message.ts","../../src/messaging/Packet.ts","../../src/messaging/decorators.ts","../../src/messaging/index.ts","../../src/auth/AuthClient.ts","../../src/auth/identity.ts","../../src/auth/poseidon.ts","../../src/auth/proof.ts","../../src/auth/keys.ts","../../src/core/HttpClient.ts","../../src/core/Session.ts","../../src/core/namespaces/AuthNamespace.ts","../../src/crypto/StorageCipher.ts","../../src/transport/WSTransport.ts","../../src/core/namespaces/KvNamespace.ts","../../src/core/namespaces/DbNamespace.ts","../../src/storage/types.ts","../../src/storage/encoding/ReedSolomon/wasm/rs.ts","../../src/storage/encoding/ReedSolomon/ReedSolomonCodec.ts","../../src/storage/transport/ShardClient.ts","../../src/storage/FileStorage.ts","../../src/storage/transport/SharedSpaceClient.ts","../../src/core/namespaces/FileNamespace.ts","../../src/sessions/EncryptedSession.ts","../../src/sessions/BroadcastChannel.ts","../../src/spaces/SpaceCipher.ts","../../src/spaces/SpacePacketCipher.ts","../../src/spaces/Space.ts","../../src/core/namespaces/MessageNamespace.ts","../../src/spaces/SpaceKeyring.ts","../../src/spaces/KeyringClient.ts","../../src/core/namespaces/SpaceNamespace.ts","../../src/core/namespaces/AgentsNamespace.ts","../../src/core/namespaces/FunctionsNamespace.ts","../../src/core/Client.ts","../../src/core/agents/describe.ts","../../src/core/index.ts","../../src/workers/groth16-verifier.ts","../../src/personal/PersonalSpaceClient.ts","../../src/network/PacketCipher.ts","../../src/storage/encoding/ReedSolomon/wasm/bundled-loader.ts"],"sourcesContent":["/**\n * WebCrypto subtle-interface resolver.\n *\n * Available natively in every runtime this SDK targets (modern browsers,\n * Node 16+, CF Workers). Centralized here so the runtime check + error\n * message are consistent across every primitive — and so a future polyfill\n * shim has one place to plug in.\n */\n\nexport function getSubtle(): SubtleCrypto {\n const s = (globalThis.crypto as Crypto | undefined)?.subtle;\n if (!s) {\n throw new Error(\n \"@muhkoo/connect crypto: `globalThis.crypto.subtle` is unavailable. \" +\n \"Modern browsers, Node 16+, and CF Workers expose it natively.\",\n );\n }\n return s;\n}\n","/**\n * Cryptographically secure random bytes.\n *\n * Wraps `crypto.getRandomValues` with two small affordances every caller\n * needs:\n * - Allocates over a fresh, non-shared `ArrayBuffer` so the returned\n * `Uint8Array` satisfies WebCrypto's `BufferSource` type under strict\n * TS lib settings (where `Uint8Array<ArrayBufferLike>` isn't directly\n * assignable).\n * - Chunks requests larger than 65 KiB, the per-call cap browsers enforce\n * on `getRandomValues`.\n */\n\nconst MAX_PER_CALL = 65536;\n\nexport function randomBytes(n: number): Uint8Array {\n if (!Number.isInteger(n) || n < 0) {\n throw new Error(`randomBytes: n must be a non-negative integer (got ${n})`);\n }\n const buf = new Uint8Array(new ArrayBuffer(n));\n for (let offset = 0; offset < n; offset += MAX_PER_CALL) {\n const slice = buf.subarray(offset, Math.min(offset + MAX_PER_CALL, n));\n (globalThis.crypto as Crypto).getRandomValues(slice);\n }\n return buf;\n}\n","/**\n * AES-256-GCM encryption / decryption with raw key bytes.\n *\n * The two functions here are the single canonical AES-GCM call site in the\n * SDK. Earlier copies of this logic existed inline in `DoubleRatchet`, in the\n * storage `ChunkCipher`, and in the passphrase-wrap helpers — they all now\n * route through here so the algorithm, IV size, and tag handling stay in one\n * place.\n *\n * Conventions:\n * - 256-bit keys only. Passing 16- or 24-byte keys throws; callers that\n * need AES-128 should add a dedicated primitive.\n * - 96-bit IVs. WebCrypto's recommended GCM IV length; trades the 4-byte\n * IV economy of 128-bit for compatibility with every spec-compliant\n * implementation.\n * - The 16-byte GCM authentication tag is appended to the ciphertext by\n * WebCrypto's default behavior. Callers don't manage it separately.\n *\n * If a future need arises for AAD (associated data), add an optional `aad`\n * parameter to both functions rather than introducing a parallel primitive.\n */\n\nimport { getSubtle } from \"./subtle\";\n\n/** Length of the AES key in bytes. */\nexport const AES_GCM_KEY_BYTES = 32;\n\n/** Length of the AES-GCM IV in bytes (WebCrypto-recommended). */\nexport const AES_GCM_IV_BYTES = 12;\n\n/** Length of the AES-GCM authentication tag in bytes (appended to ciphertext). */\nexport const AES_GCM_TAG_BYTES = 16;\n\n/**\n * Encrypt `plaintext` under a 32-byte AES-256 key with the supplied 12-byte\n * IV. Returns ciphertext with the 16-byte GCM tag appended (so the output\n * length is `plaintext.length + 16`).\n *\n * The IV must be unique per (key, message). Callers that generate the IV\n * randomly should grab it via `randomBytes(AES_GCM_IV_BYTES)`; callers\n * managing a counter pass their own.\n */\nexport async function encryptAesGcm(\n key: Uint8Array,\n iv: Uint8Array,\n plaintext: Uint8Array,\n): Promise<Uint8Array> {\n assertKey(key);\n assertIv(iv);\n const cryptoKey = await importAesGcmKey(key, [\"encrypt\"]);\n const ciphertext = await getSubtle().encrypt(\n { name: \"AES-GCM\", iv: iv as BufferSource },\n cryptoKey,\n plaintext as BufferSource,\n );\n return new Uint8Array(ciphertext);\n}\n\n/**\n * Inverse of {@link encryptAesGcm}. Throws if the GCM auth tag fails — this\n * captures \"wrong key\", \"wrong IV\", or \"ciphertext was tampered with\",\n * indistinguishably. Callers that care about distinguishing those should\n * keep separate provenance bookkeeping, not invent a parallel MAC.\n */\nexport async function decryptAesGcm(\n key: Uint8Array,\n iv: Uint8Array,\n ciphertext: Uint8Array,\n): Promise<Uint8Array> {\n assertKey(key);\n assertIv(iv);\n const cryptoKey = await importAesGcmKey(key, [\"decrypt\"]);\n const plaintext = await getSubtle().decrypt(\n { name: \"AES-GCM\", iv: iv as BufferSource },\n cryptoKey,\n ciphertext as BufferSource,\n );\n return new Uint8Array(plaintext);\n}\n\nasync function importAesGcmKey(key: Uint8Array, usages: KeyUsage[]): Promise<CryptoKey> {\n return await getSubtle().importKey(\n \"raw\",\n key as BufferSource,\n { name: \"AES-GCM\" },\n false,\n usages,\n );\n}\n\nfunction assertKey(key: Uint8Array): void {\n if (key.byteLength !== AES_GCM_KEY_BYTES) {\n throw new Error(\n `aes-gcm: key must be ${AES_GCM_KEY_BYTES} bytes (got ${key.byteLength})`,\n );\n }\n}\n\nfunction assertIv(iv: Uint8Array): void {\n if (iv.byteLength !== AES_GCM_IV_BYTES) {\n throw new Error(\n `aes-gcm: iv must be ${AES_GCM_IV_BYTES} bytes (got ${iv.byteLength})`,\n );\n }\n}\n","/**\n * Key-derivation primitives — PBKDF2 (for passphrase → key) and HKDF (for\n * symmetric key material → expanded key material).\n *\n * PBKDF2 is the slow, salted KDF the passphrase-wrap helper uses to harden\n * user passwords against offline guessing. HKDF is the fast, deterministic\n * KDF the Double Ratchet uses to derive root + chain + message keys from\n * shared secrets.\n *\n * Both are SHA-256-backed everywhere in this codebase — keep it that way\n * unless there's a concrete reason to diverge.\n */\n\nimport { getSubtle } from \"./subtle\";\n\n/**\n * Iteration count default for PBKDF2 passphrase hardening. Tuned for\n * 2024–2026 hardware: slow enough to deter offline guessing of weak\n * passphrases (~100ms on commodity laptops), fast enough that interactive\n * unlock stays sub-second.\n */\nexport const PBKDF2_DEFAULT_ITERATIONS = 200_000;\n\n/**\n * Derive a 256-bit AES-GCM key from `passphrase + salt` via PBKDF2-SHA256.\n *\n * Returned as raw bytes (not a `CryptoKey`) so callers can hand it straight\n * to {@link encryptAesGcm} — that's the convention everywhere else in the\n * primitive layer. If a future caller needs the non-extractable\n * `CryptoKey` form, add a parallel `deriveCryptoKeyFromPassphrase` variant\n * rather than overloading this one.\n */\nexport async function deriveAesKeyFromPassphrase(\n passphrase: string,\n salt: Uint8Array,\n iterations: number = PBKDF2_DEFAULT_ITERATIONS,\n): Promise<Uint8Array> {\n if (typeof passphrase !== \"string\" || passphrase.length === 0) {\n throw new Error(\"kdf.deriveAesKeyFromPassphrase: passphrase must be a non-empty string\");\n }\n const s = getSubtle();\n const passphraseKey = await s.importKey(\n \"raw\",\n new TextEncoder().encode(passphrase),\n { name: \"PBKDF2\" },\n false,\n [\"deriveBits\"],\n );\n const bits = await s.deriveBits(\n {\n name: \"PBKDF2\",\n salt: salt as BufferSource,\n iterations,\n hash: \"SHA-256\",\n },\n passphraseKey,\n 256,\n );\n return new Uint8Array(bits);\n}\n\n/**\n * HKDF-Expand with SHA-256, returning `lengthBytes` raw bytes of key material.\n *\n * `info` is the per-purpose label (e.g. `\"DoubleRatchetMsg\"`). Optional\n * `salt` defaults to an empty buffer, matching the way the Double Ratchet\n * code has always used it.\n *\n * Note: this is intentionally a one-shot Extract-then-Expand call rather than\n * exposing Extract and Expand separately — every call site in this codebase\n * wants the same shape, and a richer API can be added later if needed.\n */\nexport async function deriveBitsHkdf(\n inputKeyMaterial: Uint8Array,\n info: string,\n lengthBytes: number,\n salt: Uint8Array = new Uint8Array(0),\n): Promise<Uint8Array> {\n if (lengthBytes <= 0) {\n throw new Error(`kdf.deriveBitsHkdf: lengthBytes must be > 0 (got ${lengthBytes})`);\n }\n const s = getSubtle();\n const key = await s.importKey(\n \"raw\",\n inputKeyMaterial as BufferSource,\n { name: \"HKDF\" },\n false,\n [\"deriveBits\"],\n );\n const bits = await s.deriveBits(\n {\n name: \"HKDF\",\n hash: \"SHA-256\",\n salt: salt as BufferSource,\n info: new TextEncoder().encode(info) as BufferSource,\n },\n key,\n lengthBytes * 8,\n );\n return new Uint8Array(bits);\n}\n","// Tiny browser-safe replacement for the `chalk` Node module.\n// Emits ANSI escape codes when running attached to a TTY (Node terminal);\n// returns plain strings everywhere else (browsers, log files, CF Workers).\n// Avoids dragging chalk + its terminfo deps into the browser/Workers bundles.\ntype ColorFn = (s: string) => string;\nconst _isTty: boolean = (() => {\n try {\n const proc = (globalThis as { process?: { stdout?: { isTTY?: boolean } } }).process;\n return !!proc?.stdout?.isTTY;\n } catch { return false; }\n})();\nconst _ansi = (code: string): ColorFn =>\n _isTty ? (s) => `\\x1b[${code}m${s}\\x1b[0m` : (s) => s;\nconst colors = {\n gray: _ansi('90'),\n red: _ansi('31'),\n green: _ansi('32'),\n yellow: _ansi('33'),\n blue: _ansi('34'),\n magenta: _ansi('35'),\n cyan: _ansi('36'),\n dim: _ansi('2'),\n};\n\nenum LogLevel {\n VERBOSE = 0,\n DEBUG = 1,\n INFO = 2,\n SUCCESS = 3,\n WARN = 4,\n ERROR = 5,\n}\n\ninterface CallerInfo {\n file?: string;\n line?: number;\n column?: number;\n function?: string;\n}\n\nclass Logger {\n private prefix: string;\n private logLevel: LogLevel;\n private console: Console;\n private showCaller: boolean;\n level: string = 'INFO';\n\n constructor(prefix: string = 'CONNECT', LOGLEVEL: string = 'INFO', showCaller: boolean = false) {\n this.prefix = colors.gray(`[${prefix}]`);\n this.showCaller = showCaller;\n let envLevel;\n\n // Check environment: browser vs Node.js\n if (typeof window !== 'undefined') {\n // Browser environment\n envLevel = (LOGLEVEL).toUpperCase() as keyof typeof LogLevel;\n } else {\n // Node.js environment - safely access process.env\n const globalProcess = (globalThis as any).process;\n const nodeEnv = globalProcess?.env?.LOG_LEVEL;\n envLevel = (nodeEnv || LOGLEVEL).toUpperCase() as keyof typeof LogLevel;\n }\n\n this.level = envLevel;\n this.logLevel = LogLevel[envLevel] ?? LogLevel.INFO;\n this.console = globalThis.console;\n }\n\n private shouldLog(level: LogLevel): boolean {\n return level >= this.logLevel;\n }\n\n /**\n * Extract caller information from stack trace\n */\n private getCallerInfo(): CallerInfo | null {\n if (!this.showCaller) return null;\n\n try {\n const stack = new Error().stack;\n if (!stack) return null;\n\n // Split stack trace into lines\n const lines = stack.split('\\n');\n\n // Skip first 3 lines (Error, getCallerInfo, the log method itself)\n // The 4th line should be the actual caller\n const callerLine = lines[3];\n if (!callerLine) return null;\n\n // Parse stack trace line\n // Format: \" at ClassName.methodName (file:line:column)\"\n // or: \" at file:line:column\"\n const match = callerLine.match(/at\\s+(?:(.+?)\\s+\\()?(.+?):(\\d+):(\\d+)\\)?/);\n\n if (!match) return null;\n\n const [, functionName, filePath, line, column] = match;\n\n // Extract just the filename from the full path\n const file = filePath.split('/').pop()?.split('?')[0];\n\n return {\n file,\n line: parseInt(line, 10),\n column: parseInt(column, 10),\n function: functionName || undefined,\n };\n } catch (error) {\n // If we can't parse the stack, just return null\n return null;\n }\n }\n\n /**\n * Format caller info for display\n */\n private formatCallerInfo(info: CallerInfo | null): string {\n if (!info) return '';\n\n const parts: string[] = [];\n\n if (info.function) {\n parts.push(colors.cyan(info.function));\n }\n\n if (info.file) {\n const location = info.line ? `${info.file}:${info.line}` : info.file;\n parts.push(colors.dim(`(${location})`));\n }\n\n return parts.length > 0 ? ' ' + parts.join(' ') : '';\n }\n\n setLevel(level: string): void {\n this.level = level.toUpperCase();\n const envLevel = level.toUpperCase() as keyof typeof LogLevel;\n this.logLevel = LogLevel[envLevel] ?? LogLevel.INFO;\n }\n\n setShowCaller(show: boolean): void {\n this.showCaller = show;\n }\n\n // Logging methods with automatic caller detection\n info(...args: any[]): void {\n if (this.shouldLog(LogLevel.INFO)) {\n const caller = this.formatCallerInfo(this.getCallerInfo());\n this.console.info(this.prefix, colors.blue('INFO') + caller, ...args);\n }\n }\n\n log(...args: any[]): void {\n this.info(...args); // Alias for info\n }\n\n verbose(...args: any[]): void {\n if (this.shouldLog(LogLevel.VERBOSE)) {\n const caller = this.formatCallerInfo(this.getCallerInfo());\n this.console.log(this.prefix, colors.cyan('VERBOSE') + caller, ...args);\n }\n }\n\n success(...args: any[]): void {\n if (this.shouldLog(LogLevel.SUCCESS)) {\n const caller = this.formatCallerInfo(this.getCallerInfo());\n this.console.debug(this.prefix, colors.green('SUCCESS') + caller, ...args);\n }\n }\n\n warn(...args: any[]): void {\n if (this.shouldLog(LogLevel.WARN)) {\n const caller = this.formatCallerInfo(this.getCallerInfo());\n this.console.warn(this.prefix, colors.yellow('WARN') + caller, ...args);\n }\n }\n\n error(...args: any[]): void {\n if (this.shouldLog(LogLevel.ERROR)) {\n const caller = this.formatCallerInfo(this.getCallerInfo());\n this.console.error(this.prefix, colors.red('ERROR') + caller, ...args);\n }\n }\n\n debug(...args: any[]): void {\n if (this.shouldLog(LogLevel.DEBUG)) {\n const caller = this.formatCallerInfo(this.getCallerInfo());\n this.console.debug(this.prefix, colors.magenta('DEBUG') + caller, ...args);\n }\n }\n\n // Rest of the methods remain unchanged\n assert(condition?: boolean, ...data: any[]): void {\n this.console.assert(condition, ...data);\n }\n\n clear(): void {\n this.console.clear();\n }\n\n count(label?: string): void {\n this.console.count(label);\n }\n\n countReset(label?: string): void {\n this.console.countReset(label);\n }\n\n dir(item?: any, options?: any): void {\n this.console.dir(item, options);\n }\n\n dirxml(...data: any[]): void {\n this.console.dirxml(...data);\n }\n\n group(...data: any[]): void {\n this.console.group(...data);\n }\n\n groupCollapsed(...data: any[]): void {\n this.console.groupCollapsed(...data);\n }\n\n groupEnd(): void {\n this.console.groupEnd();\n }\n\n table(tabularData?: any, properties?: string[]): void {\n this.console.table(tabularData, properties);\n }\n\n time(label?: string): void {\n this.console.time(label);\n }\n\n timeEnd(label?: string): void {\n this.console.timeEnd(label);\n }\n\n timeLog(label?: string, ...data: any[]): void {\n this.console.timeLog(label, ...data);\n }\n\n trace(...data: any[]): void {\n this.console.trace(...data);\n }\n\n // Note: Console property removed as it's Node.js-specific and not needed\n\n profile(label?: string): void {\n if ('profile' in this.console) {\n (this.console as any).profile(label);\n }\n }\n\n profileEnd(label?: string): void {\n if ('profileEnd' in this.console) {\n (this.console as any).profileEnd(label);\n }\n }\n\n timeStamp(label?: string): void {\n if ('timeStamp' in this.console) {\n (this.console as any).timeStamp(label);\n }\n }\n}\n\n// Export Logger class for custom instances\nexport { Logger };\n\n// Export default instance for general use\nexport const log = new Logger('CONNECT', 'INFO', false);\n\n// Also export as default\nexport default log;\n\ndeclare global {\n interface Console {\n success(...args: any[]): void;\n verbose(...args: any[]): void;\n }\n}","/**\n * Byte conversion helpers usable in both Node and the browser.\n *\n * Replaces Node's `Buffer` API for the small set of operations we actually\n * need in the crypto layer: hex/base64/base64url encode + decode, and array\n * concatenation. Lets `DoubleRatchet`, `KeyStore`, etc. compile against\n * platforms without `Buffer` (browsers, CF Workers).\n */\n\nconst HEX_CHARS = \"0123456789abcdef\";\n\n/** Encode a byte array as a lowercase hex string. */\nexport function toHex(bytes: Uint8Array): string {\n let out = \"\";\n for (let i = 0; i < bytes.length; i++) {\n const b = bytes[i];\n out += HEX_CHARS[b >> 4] + HEX_CHARS[b & 0x0f];\n }\n return out;\n}\n\n/** Decode a hex string into a byte array. Accepts upper/lowercase; rejects odd-length input. */\nexport function fromHex(hex: string): Uint8Array<ArrayBuffer> {\n if (hex.length % 2 !== 0) {\n throw new Error(`fromHex: input length must be even (got ${hex.length})`);\n }\n const ab = new ArrayBuffer(hex.length / 2);\n const out = new Uint8Array(ab);\n for (let i = 0; i < out.length; i++) {\n const byte = parseInt(hex.substring(i * 2, i * 2 + 2), 16);\n if (Number.isNaN(byte)) {\n throw new Error(`fromHex: invalid hex character at offset ${i * 2}`);\n }\n out[i] = byte;\n }\n return out;\n}\n\n/** Encode a byte array as a standard base64 string. */\nexport function toBase64(bytes: Uint8Array): string {\n let binary = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n/** Decode a standard base64 string to bytes. */\nexport function fromBase64(b64: string): Uint8Array<ArrayBuffer> {\n const binary = atob(b64);\n const ab = new ArrayBuffer(binary.length);\n const out = new Uint8Array(ab);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out;\n}\n\n/** Encode a byte array as a base64url string (no padding). */\nexport function toBase64Url(bytes: Uint8Array): string {\n return toBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** Decode a base64url string (with or without padding) to bytes. */\nexport function fromBase64Url(b64url: string): Uint8Array<ArrayBuffer> {\n const padded = b64url.replace(/-/g, \"+\").replace(/_/g, \"/\") +\n \"=\".repeat((4 - (b64url.length % 4)) % 4);\n return fromBase64(padded);\n}\n\n/** Concatenate any number of byte arrays into a single Uint8Array. */\nexport function concatBytes(...arrays: (Uint8Array | ArrayBuffer)[]): Uint8Array<ArrayBuffer> {\n let total = 0;\n for (const a of arrays) total += a.byteLength;\n const ab = new ArrayBuffer(total);\n const out = new Uint8Array(ab);\n let offset = 0;\n for (const a of arrays) {\n const view = a instanceof Uint8Array ? a : new Uint8Array(a);\n out.set(view, offset);\n offset += view.length;\n }\n return out;\n}\n\n/** Encode a UTF-8 string as bytes. Thin wrapper around TextEncoder for symmetry. */\nexport function utf8Encode(s: string): Uint8Array<ArrayBuffer> {\n // TextEncoder.encode returns Uint8Array<ArrayBufferLike>; widen to the\n // ArrayBuffer variant explicitly so WebCrypto's BufferSource type accepts it.\n const u8 = new TextEncoder().encode(s);\n const ab = new ArrayBuffer(u8.byteLength);\n const out = new Uint8Array(ab);\n out.set(u8);\n return out;\n}\n\n/** Decode UTF-8 bytes to a string. */\nexport function utf8Decode(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n","import log, { Logger } from './Logger';\n\nconst base58Alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\nexport {\n log,\n Logger\n}\n\n// Browser-safe byte conversion helpers (hex / base64 / base64url / concat).\n// The crypto layer uses these instead of Node's Buffer so it runs in browsers\n// and CF Workers as well as Node.\nexport * from './bytes';\n//0ba25dcb0db07dbac27435857ab55150d2a2e6c8f73a969c74b7659c7a8dd3a3\n\n/**\n * @public\n * @remarks Asserts the basic type of a variable\n * @param value - The value to check\n * @param type - The expected type\n * \n * @throws Error - If the type of the value does not match the expected type\n * \n */\nexport function assertType<T>(\n value: unknown,\n typeOrConstructors: string | (new (...args: any[]) => any) | (new (...args: any[]) => any)[]\n): asserts value is T {\n if (typeof typeOrConstructors === 'string') {\n // Single primitive type\n if (typeof value !== typeOrConstructors) {\n throw new Error(\n `Expected type '${typeOrConstructors}', received '${typeof value}'`\n );\n }\n } else if (Array.isArray(typeOrConstructors)) {\n // OR scenario: Array of constructors\n const isValid = typeOrConstructors.some((ctor) => value instanceof ctor);\n if (!isValid) {\n const expectedTypes = typeOrConstructors.map((ctor) => ctor.name).join(' or ');\n const receivedType = value?.constructor?.name || typeof value;\n throw new Error(\n `Expected instance of ${expectedTypes}, received '${receivedType}'`\n );\n }\n } else if (typeof typeOrConstructors === 'function') {\n // Single constructor check\n if (!(value instanceof typeOrConstructors)) {\n const expectedType = typeOrConstructors.name || 'Unknown';\n const receivedType = value?.constructor?.name || typeof value;\n throw new Error(\n `Expected instance of '${expectedType}', received '${receivedType}'`\n );\n }\n } else {\n throw new Error(`Invalid type or constructor provided for assertion.`);\n }\n}\n\n/**\n * @public\n * @remarks Encodes a string to Base58\n * @param input - the data to encode, must be a cloneable object\n * @returns string\n */\nexport function base58Encode(input: ArrayBuffer | string): string {\n const bytes = typeof input === \"string\"\n ? new TextEncoder().encode(input)\n : new Uint8Array(input);\n\n let num = BigInt(0);\n for (const byte of bytes) {\n num = (num << BigInt(8)) + BigInt(byte);\n }\n\n let result = \"\";\n while (num > 0) {\n const remainder = Number(num % BigInt(58));\n num = num / BigInt(58);\n result = base58Alphabet[remainder] + result;\n }\n\n // Preserve leading zero bytes as \"1\" in Base58\n for (const byte of bytes) {\n if (byte === 0) result = \"1\" + result;\n else break;\n }\n return result;\n}\n\n\n/**\n * @public\n * @remarks Decodes a Base58 string to a Uint8Array\n * @param input - the Base58 string to decode\n * @returns Uint8Array\n */\n\n\n// Function to decode a Base58 string to ArrayBuffer\nexport function base58Decode(input: string): ArrayBuffer {\n try {\n const base58Map = new Map(base58Alphabet.split(\"\").map((char, index) => [char, index]));\n\n let num = BigInt(0);\n for (const char of input) {\n const value = base58Map.get(char);\n if (value === undefined) throw new Error(`Invalid Base58 character: ${char}`);\n num = num * BigInt(58) + BigInt(value);\n }\n\n const byteArray: number[] = [];\n while (num > 0) {\n byteArray.push(Number(num % BigInt(256)));\n num = num / BigInt(256);\n }\n\n byteArray.reverse();\n\n // Restore leading zero bytes from Base58 \"1\"\n const leadingZeros = Array.from(input).filter((char) => char === \"1\").length;\n return new Uint8Array([...Array(leadingZeros).fill(0), ...byteArray]).buffer;\n } catch (e) {\n log.error(e);\n throw new Error(\"Invalid input\");\n }\n}\n\n/**\n * Simple checksum function using djb2 hash algorithm\n * Works in both browser and Node.js environments\n */\nfunction simpleChecksum(str: string): string {\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) + hash) + str.charCodeAt(i); // hash * 33 + c\n }\n return (hash >>> 0).toString(16); // Convert to unsigned 32-bit hex\n}\n\n\n\n/**\n * @public\n * @remarks Generates a checksum for a given input\n * @param input - The input to generate a checksum for as a string\n * @returns string\n */\nexport function generateChecksum(input: string): string {\n assertType<string>(input, \"string\");\n return simpleChecksum(input);\n}\n\n/**\n * @public\n * @remarks Verifies a checksum for a given input\n * @param input - The input to verify as a string\n * @param checksum - The checksum to verify as a string\n * @returns boolean\n */\nexport function verifyChecksum(input: string, checksum: string): boolean {\n assertType<string>(input, \"string\");\n assertType<string>(checksum, \"string\");\n return !!(simpleChecksum(input) === checksum);\n}\n\n/**\n * @internal\n * @remarks Generates a random UUID for a given packet\n * @returns string\n */\nexport function _packetId(): string {\n return \"PKT\" + generateId();\n}\n\n/**\n * @internal\n * @remarks Generates a random UUID for a given object\n * @returns string\n * \n */\n\nexport function _objectId(): string {\n return \"OBJ\" + generateId();\n}\n\n/**\n * @internal\n * @remarks Generates a random UUID for a given user\n * @returns string\n * \n */\n\nexport function _userId(): string {\n return \"USR\" + generateId();\n}\n\n/**\n * @internal\n * @remarks Generates a random UUID for a given account\n * @returns string\n * \n */\n\nexport function _accountId(): string {\n return \"ACC\" + generateId();\n}\n\n/**\n * @internal\n * @remarks Generates a random UUID for a socket\n * @returns string\n * \n */\nexport function _socketId(): string {\n return \"SKT\" + generateId();\n}\n\n/**\n * @internal\n * @remarks Generates a random UUID for a message\n * @returns string\n */\n\nexport function _messageId(): string {\n return \"MSG\" + generateId();\n}\n\n/**\n * @public\n * @remarks Generates a random UUID and base58 encodes it\n * @returns string\n */\n\nexport function generateId(): string {\n // Web-standard UUID generator (available in every modern browser and\n // Node 14+). Replaces the npm `uuid` dep so the browser bundle has one\n // fewer external import to resolve.\n return base58Encode(crypto.randomUUID());\n}\n\n/**\n * @public\n * @remarks Serializes data to a base58 encoded string\n * @param data - The data to serialize\n * @typeParam T - The type of the data to serialize\n * @returns base58 encoded string\n */\nexport function serialize<T>(data: T): string {\n const arrayBuffer = structuredCloneToArrayBuffer(data);\n return base58Encode(arrayBuffer);\n}\n\n/**\n * @public\n * @remarks Deserializes a base58 encoded string to data\n * @param base58String - The base58 encoded string to deserialize\n * @returns Deserialized data\n */\nexport function deserialize<T>(base58String: string): T {\n const arrayBuffer = base58Decode(base58String);\n return deserializeWithStructuredClone(arrayBufferToData(arrayBuffer)) as T;\n}\n\nfunction deserializeWithStructuredClone(data: any): unknown {\n const deserializeHelper = (item: any): any => {\n if (item === null || typeof item !== 'object') {\n return item; // Handle primitives directly\n }\n\n if (item.__type === \"Symbol\") {\n return Symbol.for(item.value) || Symbol(item.value);\n }\n\n if (item.__type === 'Date') {\n return new Date(item.value); // Rehydrate Date\n }\n\n if (item.__type === 'Map') {\n return new Map(item.value); // Rehydrate Map\n }\n\n if (item.__type === 'Set') {\n return new Set(item.value); // Rehydrate Set\n }\n\n if (Array.isArray(item)) {\n return item.map(deserializeHelper); // Rehydrate Array recursively\n }\n\n // Generic object case\n const deserializedObject: any = {};\n for (const key of Object.keys(item)) {\n deserializedObject[key] = deserializeHelper(item[key]);\n }\n return deserializedObject;\n };\n\n return deserializeHelper(data);\n}\n\nfunction structuredCloneToArrayBuffer(data: any): ArrayBuffer {\n // Clone and transform the data for serialization\n const serializeHelper = (item: any): any => {\n if (item === null || typeof item !== \"object\") return item;\n\n if (typeof item === \"symbol\") {\n const key = Symbol.keyFor(item) || item.description || \"\";\n return { __type: \"Symbol\", value: key };\n }\n\n if (item.constructor === Date) return { __type: \"Date\", value: item.toISOString() };\n if (item.constructor === Map) return { __type: \"Map\", value: Array.from(item.entries()) };\n if (item.constructor === Set) return { __type: \"Set\", value: Array.from(item) };\n if (Array.isArray(item)) return item.map(serializeHelper);\n\n const serializedObject: any = {};\n for (const key of Object.keys(item)) {\n serializedObject[key] = serializeHelper(item[key]);\n }\n return serializedObject;\n };\n\n // Serialize the structured data into a JSON string\n const jsonString = JSON.stringify(serializeHelper(data));\n return new TextEncoder().encode(jsonString).buffer as ArrayBuffer;\n}\n\nfunction arrayBufferToData(arrayBuffer: ArrayBuffer): any {\n let jsonString = new TextDecoder().decode(new Uint8Array(arrayBuffer));\n jsonString = jsonString.replace(/^\\0+/, '')\n return JSON.parse(jsonString);\n}\n\n/**\n * @public\n * @remarks Retries a method a specified number of times with a delay between each attempt, this is a decorator\n * @param retries - The number of times to retry the method\n * @param delay - The delay in milliseconds between each attempt\n */\nexport function Retry(retries: number = 3, delay: number = 1000): MethodDecorator {\n\n return function (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<any>) {\n // Ensure the descriptor exists\n if (!descriptor || typeof descriptor.value !== \"function\") {\n throw new Error(\"Retry decorator can only be applied to methods.\");\n }\n\n const originalMethod = descriptor.value;\n\n descriptor.value = async function (...args: any[]) {\n let attempt = 0;\n\n while (attempt < retries) {\n try {\n return await originalMethod.apply(this, args);\n } catch (error) {\n attempt++;\n log.debug(`Retrying ${String(propertyKey)} - Attempt ${attempt}/${retries}`);\n if (attempt >= retries) {\n throw error; // Re-throw the error if retries are exhausted\n }\n log.log(`Waiting for ${delay}ms before retrying...`);\n await new Promise(res => setTimeout(res, delay));\n }\n }\n };\n\n return descriptor;\n };\n}\n\n/**\n * @public\n * @remarks Waits for a class property to be ready before executing a method, this is a decorator.\n * @param readyPropertyName - The class property to check for readiness\n */\nexport function Ready(readyPropertyName: string = \"ready\"): MethodDecorator | PropertyDecorator {\n return function (target: object, propertyKey: string | symbol, descriptor: PropertyDescriptor) {\n if (descriptor === undefined) {\n throw new Error(\"@Ready can only be applied to methods, getters, or setters.\");\n }\n\n const isGetter = typeof descriptor.get === \"function\";\n const isSetter = typeof descriptor.set === \"function\";\n const isMethod = typeof descriptor.value === \"function\";\n\n const readyCheck = async (instance: any) => {\n const readyProperty = instance[readyPropertyName];\n\n if (!readyProperty || !(readyProperty instanceof Promise)) {\n log.warn(`Property \"${readyPropertyName}\" must be a Promise.`);\n return\n }\n await readyProperty; // Wait for the property to resolve\n };\n\n if (isMethod) {\n const originalMethod = descriptor.value;\n descriptor.value = async function (...args: any[]) {\n await readyCheck(this);\n return originalMethod.apply(this, args);\n };\n } else if (isGetter || isSetter) {\n const originalGetter = descriptor.get;\n const originalSetter = descriptor.set;\n\n if (isGetter) {\n descriptor.get = async function () {\n await readyCheck(this);\n return originalGetter!.call(this);\n };\n }\n\n if (isSetter) {\n descriptor.set = async function (value: any) {\n await readyCheck(this);\n return originalSetter!.call(this, value);\n };\n }\n } else {\n throw new Error(\"@Ready can only be applied to methods, getters, or setters.\");\n }\n\n return descriptor;\n };\n}\n\n\n/**\n * Converts bytes into a more human-friendly format (e.g., KB, MB, GB).\n * @internal\n * @param bytes - The number of bytes to convert.\n * @param decimals - The number of decimals to display (default is 2).\n * @returns A formatted string representing the size in appropriate units.\n */\nexport function _formatBytes(bytes: number, decimals: number = 2): string {\n if (bytes === 0) return \"0 Bytes\";\n\n const k = 1024; // 1 KB = 1024 Bytes\n const sizes = [\"Bytes\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"];\n const i = Math.floor(Math.log(bytes) / Math.log(k)); // Determines the index for size\n const sizeInUnit = bytes / Math.pow(k, i); // Converts bytes to appropriate unit\n\n return `${sizeInUnit.toFixed(decimals)} ${sizes[i]}`;\n}\n\n/**\n * Retrieves the IP address(es) for a given hostname using Cloudflare's DNS-over-HTTPS service.\n *\n * This function queries the Cloudflare DNS API to resolve the provided hostname to its corresponding\n * IPv4 address(es) (A records). It returns an array of IP addresses or logs an error if the resolution fails.\n *\n * @param hostname - The hostname to resolve (e.g., \"example.com\").\n * @returns A promise that resolves to an array of IP addresses (strings) associated with the hostname.\n * If no IP addresses are found or an error occurs, an empty array or undefined may be returned.\n * @throws Error If the DNS query fails due to a network error or invalid response from the server.\n * @public\n * @example\n * ```typescript\n * import { log } from '@muhkoo/connect/utilities';\n * getIPAddress(\"example.com\").then(ips => log.debug(ips));\n * // Output: [\"93.184.216.34\"]\n * ```\n */\nexport async function getIPAddress(hostname: string) {\n const url = `https://cloudflare-dns.com/dns-query?name=${hostname}&type=A`;\n\n try {\n const response = await fetch(url, {\n headers: {\n Accept: \"application/dns-json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch DNS records: ${response.statusText}`);\n }\n\n const data = await response.json();\n\n // Extract the IP address from the DNS response\n const ipAddresses = data.Answer?.map((record: { data: string }) => record.data) || [];\n log.debug(`IP addresses for ${hostname}:`, ipAddresses);\n\n return ipAddresses;\n } catch (error) {\n log.error(`Error resolving IP for ${hostname}:`, error);\n }\n}\n\nexport function isNumber(value: string | number): boolean {\n // Check if the value is a number\n if (typeof value === 'number' && !isNaN(value) && isFinite(value)) {\n return true;\n }\n // Check if the value is a string and represents a valid number\n if (typeof value === 'string') {\n return !isNaN(parseFloat(value)) && isFinite(value as any);\n }\n // Return false for other types\n return false;\n}\n\nexport function getId(row: { insertId?: number, id?: number }): number {\n if (row.insertId) {\n return row.insertId;\n } else if (row.id) {\n return row.id;\n } else {\n throw new Error('No ID found in the row');\n }\n}","import { serialize, deserialize, toBase64, fromBase64, fromBase64Url, concatBytes, utf8Decode } from '../utilities';\ninterface KeyPair {\n privateKey: CryptoKey | null;\n publicKey: CryptoKey;\n}\n\ninterface AuthKeyPair {\n privateKey: CryptoKey | null;\n publicKey: CryptoKey;\n}\n\ninterface DehydratedKeys {\n ecdhPub: string; // ECDH public key in JWK format\n ecdhPriv: string; // ECDH private key in JWK format\n ecdsaPub: string; // ECDSA public key in JWK format\n ecdsaPriv: string; // ECDSA private key in JWK format\n}\n\nclass KeyStore {\n private static instance: KeyStore;\n private _keys: Map<string, KeyPair> = new Map();\n private _authKeys: Map<string, AuthKeyPair> = new Map();\n\n private constructor() { }\n\n public static getInstance(): KeyStore {\n if (!KeyStore.instance) {\n KeyStore.instance = new KeyStore();\n }\n return KeyStore.instance;\n }\n\n get keys(): Map<string, KeyPair> {\n return this._keys;\n }\n\n get authKeys(): Map<string, AuthKeyPair> {\n return this._authKeys;\n }\n\n public async generateOwnKeyPair(id: string): Promise<KeyPair> {\n if (this._keys.has(id)) {\n throw new Error(`Key pair for ${id} already exists.`);\n }\n const ecdhKeyPair = await crypto.subtle.generateKey(\n { name: 'ECDH', namedCurve: 'P-384' },\n true,\n ['deriveKey', 'deriveBits']\n );\n this._keys.set(id, { privateKey: ecdhKeyPair.privateKey, publicKey: ecdhKeyPair.publicKey });\n\n const ecdsaKeyPair = await crypto.subtle.generateKey(\n { name: 'ECDSA', namedCurve: 'P-384' },\n true,\n ['sign', 'verify']\n );\n this._authKeys.set(id, { privateKey: ecdsaKeyPair.privateKey, publicKey: ecdsaKeyPair.publicKey });\n\n const dehydrated = await this.dehydrateKeyPair(id);\n appLogger.debug(`Generated key pair for ${id}: publicKey=${dehydrated.ecdhPub.slice(0, 16)}...`);\n return { privateKey: ecdhKeyPair.privateKey, publicKey: ecdhKeyPair.publicKey };\n }\n\n public async storeRemotePublicKeys(id: string, ecdhPublicKey: CryptoKey, ecdsaPublicKey: CryptoKey): Promise<void> {\n const existing = this._keys.get(id);\n if (!existing || !existing.privateKey) {\n this._keys.set(id, { privateKey: null, publicKey: ecdhPublicKey });\n }\n const existingAuth = this._authKeys.get(id);\n if (!existingAuth || !existingAuth.privateKey) {\n this._authKeys.set(id, { privateKey: null, publicKey: ecdsaPublicKey });\n }\n const dehydrated = await this.dehydrateKeyPair(id);\n appLogger.debug(`Stored remote public keys for ${id}: ecdhPub=${dehydrated.ecdhPub.slice(0, 16)}...`);\n }\n\n public async hydrateKeyPair(id: string, dehydrated: DehydratedKeys): Promise<void> {\n const ecdhPubJwk = JSON.parse(deserialize(dehydrated.ecdhPub));\n const ecdhPublicKey = await crypto.subtle.importKey(\n 'jwk',\n ecdhPubJwk,\n { name: 'ECDH', namedCurve: 'P-384' },\n true,\n []\n );\n const ecdsaPubJwk = JSON.parse(deserialize(dehydrated.ecdsaPub));\n const ecdsaPublicKey = await crypto.subtle.importKey(\n 'jwk',\n ecdsaPubJwk,\n { name: 'ECDSA', namedCurve: 'P-384' },\n true,\n ['verify']\n );\n let ecdhPrivateKey: CryptoKey | null = null;\n let ecdsaPrivateKey: CryptoKey | null = null;\n if (dehydrated.ecdhPriv) {\n const ecdhPrivJwk = JSON.parse(deserialize(dehydrated.ecdhPriv));\n ecdhPrivateKey = await crypto.subtle.importKey(\n 'jwk',\n ecdhPrivJwk,\n { name: 'ECDH', namedCurve: 'P-384' },\n true,\n ['deriveKey', 'deriveBits']\n );\n }\n if (dehydrated.ecdsaPriv) {\n const ecdsaPrivJwk = JSON.parse(deserialize(dehydrated.ecdsaPriv));\n ecdsaPrivateKey = await crypto.subtle.importKey(\n 'jwk',\n ecdsaPrivJwk,\n { name: 'ECDSA', namedCurve: 'P-384' },\n true,\n ['sign']\n );\n }\n const existing = this._keys.get(id);\n if (!existing || !existing.privateKey) {\n this._keys.set(id, { privateKey: ecdhPrivateKey, publicKey: ecdhPublicKey });\n }\n const existingAuth = this._authKeys.get(id);\n if (!existingAuth || !existingAuth.privateKey) {\n this._authKeys.set(id, { privateKey: ecdsaPrivateKey, publicKey: ecdsaPublicKey });\n }\n }\n\n public getKeyPair(id: string): KeyPair | null {\n return this._keys.get(id) || null;\n }\n\n public getAuthKeyPair(id: string): AuthKeyPair | null {\n return this._authKeys.get(id) || null;\n }\n\n public async dehydrateKeyPair(id: string): Promise<DehydratedKeys> {\n const keyPair = this._keys.get(id);\n const authKeyPair = this._authKeys.get(id);\n if (!keyPair || !authKeyPair) {\n throw new Error(`No key pair for ${id}`);\n }\n const ecdhPubJwk = await crypto.subtle.exportKey('jwk', keyPair.publicKey);\n const ecdhPrivJwk = keyPair.privateKey ? await crypto.subtle.exportKey('jwk', keyPair.privateKey) : null;\n const ecdsaPubJwk = await crypto.subtle.exportKey('jwk', authKeyPair.publicKey);\n const ecdsaPrivJwk = authKeyPair.privateKey ? await crypto.subtle.exportKey('jwk', authKeyPair.privateKey) : null;\n const ecdhPubBase64 = JSON.stringify(ecdhPubJwk).replace(/=+$/, '');\n const ecdhPrivBase64 = ecdhPrivJwk ? JSON.stringify(ecdhPrivJwk).replace(/=+$/, '') : '';\n const ecdsaPubBase64 = JSON.stringify(ecdsaPubJwk).replace(/=+$/, '');\n const ecdsaPrivBase64 = ecdsaPrivJwk ? JSON.stringify(ecdsaPrivJwk).replace(/=+$/, '') : '';\n return {\n ecdhPub: serialize(ecdhPubBase64),\n ecdhPriv: ecdhPrivBase64 ? serialize(ecdhPrivBase64) : '',\n ecdsaPub: serialize(ecdsaPubBase64),\n ecdsaPriv: ecdsaPrivBase64 ? serialize(ecdsaPrivBase64) : '',\n };\n }\n\n public async getRawEcdsaPublicKey(id: string): Promise<Uint8Array | null> {\n const authKeyPair = this._authKeys.get(id);\n if (!authKeyPair) {\n return null;\n }\n const jwk = await crypto.subtle.exportKey('jwk', authKeyPair.publicKey);\n const x = fromBase64Url(jwk.x!);\n const y = fromBase64Url(jwk.y!);\n // SEC1 uncompressed point: 0x04 || x || y\n return concatBytes(new Uint8Array([0x04]), x, y);\n }\n\n public async packDehydratedKeys(id: string): Promise<string> {\n const dehydrated = await this.dehydrateKeyPair(id);\n const combined = JSON.stringify(dehydrated);\n return toBase64(new TextEncoder().encode(combined));\n }\n\n public async hydrateFromPacked(id: string, masterKey: string): Promise<void> {\n const decoded = utf8Decode(fromBase64(masterKey));\n const dehydrated: DehydratedKeys = JSON.parse(decoded);\n await this.hydrateKeyPair(id, dehydrated);\n }\n}\n\nexport { KeyStore, KeyPair, AuthKeyPair, DehydratedKeys };","import { RatchetState, CipherMessage, CipherMessageHeader } from './types.d';\nimport { KeyStore } from './KeyStore';\nimport { deserialize, toHex, fromHex, concatBytes, utf8Encode } from '../utilities';\nimport {\n encryptAesGcm,\n decryptAesGcm,\n deriveBitsHkdf,\n randomBytes,\n AES_GCM_IV_BYTES,\n} from './primitives';\n\n// We rely on the WebCrypto global (`crypto`/`globalThis.crypto`) — present in\n// browsers, CF Workers, and Node 19+. No `require('crypto')` Node fallback;\n// supported runtimes all expose WebCrypto natively.\n\nasync function getPubKeyHex(pubKey: CryptoKey): Promise<string> {\n const exported = await crypto.subtle.exportKey('raw', pubKey);\n return toHex(new Uint8Array(exported));\n}\n\nasync function keysEqual(key1: CryptoKey, key2: CryptoKey): Promise<boolean> {\n const hex1 = await getPubKeyHex(key1);\n const hex2 = await getPubKeyHex(key2);\n return hex1 === hex2;\n}\n\n\nclass DoubleRatchet {\n private state: RatchetState;\n private sessionType: 'global' | 'specific';\n private maxSkip: number = 3000;\n private overlapPeriod: number = 30000; // ms\n private windowSize: number = 100; // messages per DH ratchet\n\n constructor(senderId: string, recipientId: string, sessionType: 'global' | 'specific', isClient: boolean = true) {\n this.sessionType = sessionType;\n const keyStore = KeyStore.getInstance();\n const senderKeyPair = keyStore.getKeyPair(senderId);\n const recipientKeyPair = keyStore.getKeyPair(recipientId);\n\n if (!senderKeyPair || !senderKeyPair.privateKey) {\n throw new Error(`Missing own key pair for sender ${senderId}`);\n }\n if (!recipientKeyPair || !recipientKeyPair.publicKey) {\n throw new Error(`Missing public key for recipient ${recipientId}`);\n }\n\n this.state = {\n clientDhPriv: isClient ? senderKeyPair.privateKey : null,\n clientDhPub: isClient ? senderKeyPair.publicKey : recipientKeyPair.publicKey,\n serverDhPriv: isClient ? null : senderKeyPair.privateKey,\n serverDhPub: isClient ? recipientKeyPair.publicKey : senderKeyPair.publicKey,\n rootKey: null,\n sendChainKey: null,\n recvChainKey: null,\n sendCount: 0,\n recvCount: 0,\n prevChainLength: 0,\n currentSkippedKeys: new Map(),\n oldSkippedMessageKeys: new Map(),\n };\n\n appLogger.debug(`Constructor: senderId=${senderId}, recipientId=${recipientId}, isClient=${isClient}`);\n }\n\n private hkdf(input: Uint8Array, info: string, length: number): Promise<Uint8Array> {\n return deriveBitsHkdf(input, info, length);\n }\n\n public async initializeSession(isClient: boolean = true): Promise<void> {\n appLogger.debug(`Initializing session: isClient=${isClient}, sessionType=${this.sessionType}`);\n const ownPriv = isClient ? this.state.clientDhPriv : this.state.serverDhPriv;\n if (!ownPriv) {\n throw new Error('Missing own private key');\n }\n const remotePub = isClient ? this.state.serverDhPub : this.state.clientDhPub;\n const sharedSecret = await crypto.subtle.deriveBits(\n { name: 'ECDH', public: remotePub },\n ownPriv,\n 384\n );\n const keys = await this.hkdf(new Uint8Array(sharedSecret), 'DoubleRatchetInit', 32);\n this.state.rootKey = keys;\n this.state.sendChainKey = this.state.rootKey;\n this.state.recvChainKey = this.state.rootKey;\n appLogger.debug(`Initialized: rootKey set`);\n }\n\n private async dhRatchet(newPubKey: CryptoKey, isClient: boolean = true): Promise<void> {\n appLogger.debug(`DH ratchet: isClient=${isClient}`);\n const ownPriv = isClient ? this.state.clientDhPriv : this.state.serverDhPriv;\n if (!ownPriv) {\n throw new Error('Missing own private key');\n }\n const sharedSecret = await crypto.subtle.deriveBits(\n { name: 'ECDH', public: newPubKey },\n ownPriv,\n 384\n );\n const input = concatBytes(this.state.rootKey!, new Uint8Array(sharedSecret));\n const keys = await this.hkdf(input, 'DoubleRatchetDH', 64);\n this.state.rootKey = keys.subarray(0, 32);\n this.state.recvChainKey = keys.subarray(32);\n this.state.sendChainKey = isClient ? this.state.recvChainKey : this.state.rootKey;\n this.state.prevChainLength = this.state.sendCount;\n this.state.sendCount = 0;\n this.state.recvCount = 0;\n appLogger.debug(`DH ratchet complete`);\n }\n\n private async symmetricRatchet(chainKey: Uint8Array): Promise<[Uint8Array, Uint8Array]> {\n const keys = await this.hkdf(chainKey, 'DoubleRatchetMsg', 64);\n const messageKey = keys.subarray(0, 32);\n const newChainKey = keys.subarray(32);\n appLogger.debug(`Symmetric ratchet: messageKey generated`);\n return [messageKey, newChainKey];\n }\n\n public async encrypt(\n plaintext: string,\n newDhKey: boolean = false,\n senderId: string,\n recipientId: string,\n sessionId: string,\n sessionType: 'global' | 'specific'\n ): Promise<CipherMessage> {\n if (sessionType !== this.sessionType) {\n throw new Error(`Session type mismatch: expected ${this.sessionType}, got ${sessionType}`);\n }\n\n const keyStore = KeyStore.getInstance();\n if (this.sessionType === 'specific' && this.state.sendCount >= this.windowSize && this.state.sendCount > 0) {\n newDhKey = true;\n }\n if (newDhKey && this.sessionType === 'specific') {\n appLogger.debug(`Generating new DH key pair for ${senderId}`);\n const ecdhKeyPair = await crypto.subtle.generateKey(\n { name: 'ECDH', namedCurve: 'P-384' },\n true,\n ['deriveKey', 'deriveBits']\n );\n this.state.clientDhPriv = ecdhKeyPair.privateKey as CryptoKey;\n this.state.clientDhPub = ecdhKeyPair.publicKey as CryptoKey;\n keyStore.keys.set(senderId, { privateKey: ecdhKeyPair.privateKey as CryptoKey, publicKey: ecdhKeyPair.publicKey as CryptoKey });\n await this.dhRatchet(this.state.serverDhPub, true);\n }\n\n const [messageKey, newChainKey] = await this.symmetricRatchet(this.state.sendChainKey!);\n this.state.sendChainKey = newChainKey;\n\n const iv = randomBytes(AES_GCM_IV_BYTES);\n const encrypted = await encryptAesGcm(messageKey, iv, utf8Encode(plaintext));\n const cipherTextWithTag = toHex(encrypted);\n appLogger.debug(`Encrypt: plaintextLength=${plaintext.length}, ciphertextLength=${encrypted.byteLength}`);\n\n this.state.sendCount++;\n const dehydratedSender = await keyStore.dehydrateKeyPair(senderId);\n const header: CipherMessageHeader = {\n dhPub: dehydratedSender.ecdhPub,\n prevChainLength: this.state.prevChainLength,\n messageNumber: this.state.sendCount,\n sessionId,\n sessionType,\n senderId,\n recipientId,\n timestamp: Date.now(),\n signature: '',\n };\n appLogger.debug(`Message header:`, header);\n appLogger.debug(`Message header:`, keyStore.getAuthKeyPair(senderId)!.privateKey!);\n const sign = await crypto.subtle.sign(\n { name: 'ECDSA', hash: 'SHA-256' },\n keyStore.getAuthKeyPair(senderId)!.privateKey!,\n utf8Encode(JSON.stringify({\n dhPub: header.dhPub,\n prevChainLength: header.prevChainLength,\n messageNumber: header.messageNumber,\n sessionId,\n sessionType,\n senderId,\n recipientId,\n timestamp: header.timestamp\n }))\n );\n header.signature = toHex(new Uint8Array(sign));\n\n appLogger.debug(`Encrypted: sessionId=${sessionId}, messageNumber=${this.state.sendCount}, sender=${senderId}, recipient=${recipientId}`);\n return {\n header,\n ciphertext: cipherTextWithTag,\n nonce: toHex(iv),\n };\n }\n\n private cleanOldSkippedKeys(): void {\n const now = Date.now();\n for (const skipped of this.state.oldSkippedMessageKeys.entries()) {\n // [pubHex, { created }]\n const pubHex = skipped[0];\n const data = skipped[1];\n const created = data.created;\n if (now > created + this.overlapPeriod) {\n this.state.oldSkippedMessageKeys.delete(pubHex);\n }\n }\n }\n\n public async decrypt(message: CipherMessage, isClient: boolean = true): Promise<string> {\n // const { header, ciphertext, nonce } = message;\n const header = message.header;\n const ciphertext = message.ciphertext;\n const nonce = message.nonce;\n if (header.sessionType !== this.sessionType) {\n throw new Error(`Session type mismatch: expected ${this.sessionType}, got ${header.sessionType}`);\n }\n\n const keyStore = KeyStore.getInstance();\n const verify = await crypto.subtle.verify(\n { name: 'ECDSA', hash: 'SHA-256' },\n keyStore.getAuthKeyPair(header.senderId)!.publicKey,\n fromHex(header.signature),\n utf8Encode(JSON.stringify({\n dhPub: header.dhPub,\n prevChainLength: header.prevChainLength,\n messageNumber: header.messageNumber,\n sessionId: header.sessionId,\n sessionType: header.sessionType,\n senderId: header.senderId,\n recipientId: header.recipientId,\n timestamp: header.timestamp\n }))\n );\n if (!verify) {\n throw new Error('Invalid signature');\n }\n\n const maxAge = 5 * 60 * 1000;\n if (Math.abs(Date.now() - header.timestamp) > maxAge) {\n throw new Error('CipherMessage too old, possible replay attack');\n }\n\n appLogger.debug(`Decrypting: sessionId=${header.sessionId}, messageNumber=${header.messageNumber}, sender=${header.senderId}, recipient=${header.recipientId}`);\n\n if (!ciphertext || !nonce || !header.dhPub) {\n throw new Error('Invalid message: missing ciphertext, nonce, or dhPub');\n }\n\n if (!/^[0-9a-fA-F]+$/.test(ciphertext) || ciphertext.length % 2 !== 0) {\n throw new Error(`Invalid ciphertext: not a valid hex string (length=${ciphertext.length})`);\n }\n\n if (!/^[0-9a-fA-F]+$/.test(nonce) || nonce.length % 2 !== 0) {\n throw new Error(`Invalid nonce: not a valid hex string (length=${nonce.length})`);\n }\n\n const ciphertextBuffer = fromHex(ciphertext);\n const nonceBuffer = fromHex(nonce);\n if (nonceBuffer.length !== 12) {\n throw new Error(`Invalid nonce: must be 12 bytes (length=${nonceBuffer.length})`);\n }\n\n const senderPubJwk = JSON.parse(deserialize(header.dhPub));\n const senderPubKey = await crypto.subtle.importKey(\n 'jwk',\n senderPubJwk,\n { name: 'ECDH', namedCurve: 'P-384' },\n true,\n []\n );\n const senderPubHex = await getPubKeyHex(senderPubKey as CryptoKey);\n const currentSenderPub = isClient ? this.state.serverDhPub : this.state.clientDhPub;\n const currentSenderPubHex = await getPubKeyHex(currentSenderPub);\n\n this.cleanOldSkippedKeys();\n\n let messageKey: Uint8Array;\n if (senderPubHex === currentSenderPubHex) {\n // Current chain\n if (header.messageNumber > this.state.recvCount) {\n const numSkips = header.messageNumber - this.state.recvCount - 1;\n if (numSkips > this.maxSkip) {\n throw new Error('Too many skipped messages');\n }\n for (let i = 0; i < numSkips; i++) {\n const [skippedKey, newChainKey] = await this.symmetricRatchet(this.state.recvChainKey!);\n this.state.currentSkippedKeys.set(this.state.recvCount + 1 + i, skippedKey);\n this.state.recvChainKey = newChainKey;\n }\n }\n\n if (this.state.currentSkippedKeys.has(header.messageNumber)) {\n messageKey = this.state.currentSkippedKeys.get(header.messageNumber)!;\n this.state.currentSkippedKeys.delete(header.messageNumber);\n appLogger.debug(`Using skipped key for messageNumber=${header.messageNumber}`);\n } else {\n const [msgKey, newChainKey] = await this.symmetricRatchet(this.state.recvChainKey!);\n messageKey = msgKey;\n this.state.recvChainKey = newChainKey;\n }\n\n this.state.recvCount = Math.max(this.state.recvCount, header.messageNumber);\n } else {\n // Check if new DH pub\n const expectedPubKey = keyStore.getKeyPair(header.senderId)!.publicKey;\n if (!(await keysEqual(senderPubKey as CryptoKey, expectedPubKey))) {\n // New DH key, handle skip on old chain before ratchet\n const oldSenderPubHex = currentSenderPubHex;\n const numSkips = header.prevChainLength - this.state.recvCount;\n if (numSkips > this.maxSkip) {\n throw new Error('Too many skipped messages on old chain');\n }\n let oldSkips = this.state.oldSkippedMessageKeys.get(oldSenderPubHex)?.skips || new Map<number, Uint8Array>();\n let tempRecvChainKey = this.state.recvChainKey!;\n for (let i = 0; i < numSkips; i++) {\n const [skippedKey, newChainKey] = await this.symmetricRatchet(tempRecvChainKey);\n oldSkips.set(this.state.recvCount + 1 + i, skippedKey);\n tempRecvChainKey = newChainKey;\n }\n this.state.oldSkippedMessageKeys.set(oldSenderPubHex, { skips: oldSkips, created: Date.now() });\n\n // Clear current skipped\n this.state.currentSkippedKeys.clear();\n\n // Perform DH ratchet\n await this.dhRatchet(senderPubKey as CryptoKey, isClient);\n\n // Update state sender pub\n if (isClient) {\n this.state.serverDhPub = senderPubKey as CryptoKey;\n } else {\n this.state.clientDhPub = senderPubKey as CryptoKey;\n }\n\n // Update keyStore\n keyStore.storeRemotePublicKeys(header.senderId, senderPubKey as CryptoKey, keyStore.getAuthKeyPair(header.senderId)!.publicKey);\n\n // Now derive message key for new chain\n if (header.messageNumber > this.state.recvCount) {\n const numSkipsNew = header.messageNumber - this.state.recvCount - 1;\n if (numSkipsNew > this.maxSkip) {\n throw new Error('Too many skipped messages');\n }\n for (let i = 0; i < numSkipsNew; i++) {\n const [skippedKey, newChainKey] = await this.symmetricRatchet(this.state.recvChainKey!);\n this.state.currentSkippedKeys.set(this.state.recvCount + 1 + i, skippedKey);\n this.state.recvChainKey = newChainKey;\n }\n }\n\n if (this.state.currentSkippedKeys.has(header.messageNumber)) {\n messageKey = this.state.currentSkippedKeys.get(header.messageNumber)!;\n this.state.currentSkippedKeys.delete(header.messageNumber);\n } else {\n const [msgKey, newChainKey] = await this.symmetricRatchet(this.state.recvChainKey!);\n messageKey = msgKey;\n this.state.recvChainKey = newChainKey;\n }\n\n this.state.recvCount = Math.max(this.state.recvCount, header.messageNumber);\n } else {\n // Old chain\n const oldData = this.state.oldSkippedMessageKeys.get(senderPubHex);\n if (oldData && oldData.skips.has(header.messageNumber)) {\n messageKey = oldData.skips.get(header.messageNumber)!;\n oldData.skips.delete(header.messageNumber);\n if (oldData.skips.size === 0) {\n this.state.oldSkippedMessageKeys.delete(senderPubHex);\n }\n appLogger.debug(`Using old skipped key for messageNumber=${header.messageNumber} on old chain`);\n } else {\n throw new Error('No key for message on old chain');\n }\n }\n }\n\n try {\n const decrypted = await decryptAesGcm(messageKey, nonceBuffer, ciphertextBuffer);\n appLogger.debug(`Decrypted successfully: sessionId=${header.sessionId}, messageNumber=${header.messageNumber}`);\n return new TextDecoder().decode(decrypted);\n } catch (error) {\n appLogger.error(`Decryption failed: ${error instanceof Error ? error.message : 'unknown error'}`);\n throw new Error(`Decryption failed: ${error instanceof Error ? error.message : 'unknown error'}`);\n }\n }\n\n public getState(): RatchetState {\n return { ...this.state };\n }\n\n public setState(state: RatchetState): void {\n this.state = { ...state };\n }\n}\n\nexport {\n RatchetState,\n CipherMessage,\n CipherMessageHeader,\n DoubleRatchet,\n}","import { prove as groth16Prove, verify as groth16Verify } from '@zk-kit/groth16';\nimport type { PublicSignals as Groth16PublicSignals } from '@zk-kit/groth16';\n// Shared ZK types live in src/types/zk so the workers build (which can't pull\n// in snarkjs) sees the same VerificationKey / Groth16Proof shapes used here.\nimport type { Groth16Proof, VerificationKey } from '../types/zk';\n\n// Re-export so existing consumers of crypto/* keep working\nexport type SnarkProof = Groth16Proof;\nexport type { VerificationKey } from '../types/zk';\n\nexport interface ZkCompiled {\n verificationKey: VerificationKey;\n}\n\n// Authentication public input structure\nexport class AuthPublicInput {\n commitment: string;\n nonce: string;\n ecdsaPubHash: string;\n\n constructor(commitment: string, nonce: string, ecdsaPubHash: string) {\n this.commitment = commitment;\n this.nonce = nonce;\n this.ecdsaPubHash = ecdsaPubHash;\n }\n\n toPublicSignals(): string[] {\n return [this.commitment, this.nonce, this.ecdsaPubHash];\n }\n}\n\n// Helper functions for Field operations using native BigInt\nexport class Field {\n private value: bigint;\n public static readonly FIELD_SIZE = BigInt('21888242871839275222246405745257275088548364400416034343698204186575808495617'); // BN254 field size\n\n constructor(value: bigint | string | number) {\n if (typeof value === 'string') {\n this.value = BigInt(value);\n } else if (typeof value === 'number') {\n this.value = BigInt(value);\n } else {\n this.value = value;\n }\n // Ensure value is within field\n this.value = this.value % Field.FIELD_SIZE;\n if (this.value < 0n) {\n this.value += Field.FIELD_SIZE;\n }\n }\n\n toBigInt(): bigint {\n return this.value;\n }\n\n toString(): string {\n return this.value.toString();\n }\n\n toHex(): string {\n return '0x' + this.value.toString(16).padStart(64, '0');\n }\n\n equals(other: Field): boolean {\n return this.value === other.value;\n }\n\n static fromHex(hex: string): Field {\n if (!hex.startsWith('0x')) {\n throw new Error('Invalid hex prefix');\n }\n return new Field(BigInt(hex));\n }\n}\n\n// Import Poseidon from circomlibjs\nlet poseidonModule: any = null;\nlet poseidonF: any = null;\n\nasync function loadPoseidon() {\n if (!poseidonModule) {\n try {\n // Try to load circomlibjs poseidon\n const buildPoseidon = (await import('circomlibjs')).buildPoseidon;\n const poseidonBuilder = await buildPoseidon();\n poseidonModule = poseidonBuilder;\n poseidonF = poseidonBuilder.F;\n } catch (error) {\n console.warn('Failed to load circomlibjs poseidon, using fallback:', error);\n // Fallback implementation for testing - this is NOT cryptographically secure\n poseidonModule = async (inputs: any[]) => {\n const data = inputs.map(i => i.toString()).join('');\n const encoder = new TextEncoder();\n const hashBuffer = await crypto.subtle.digest('SHA-256', encoder.encode(data));\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n return BigInt('0x' + hashHex) % Field.FIELD_SIZE;\n };\n poseidonF = {\n toString: (val: any) => val.toString()\n };\n }\n }\n return { poseidon: poseidonModule, F: poseidonF };\n}\n\n// Poseidon hash implementation\nexport class Poseidon {\n static async hash(inputs: Field[]): Promise<Field> {\n const { poseidon, F } = await loadPoseidon();\n const inputBigInts = inputs.map(f => f.toBigInt());\n const hashResult = poseidon(inputBigInts);\n const hashString = F.toString(hashResult);\n return new Field(BigInt(hashString));\n }\n}\n\n// Encoding: BigInt to hex string\nexport function encodeToHex(field: Field): string {\n return field.toHex();\n}\n\n// Decoding: Hex string back to Field\nexport function decodeFromHex(hexStr: string): Field {\n return Field.fromHex(hexStr);\n}\n\n// Circuit configuration - buffers only\nexport interface CircuitBufferConfig {\n wasm: Uint8Array;\n zkey: Uint8Array;\n verificationKey: VerificationKey;\n}\n\n// Circuit wrapper for HashKnowledge\nexport class HashKnowledge {\n private static wasmBuffer?: Uint8Array;\n private static zkeyBuffer?: Uint8Array;\n private static verificationKey?: VerificationKey;\n\n static setCircuitBuffers(wasm: Uint8Array, zkey: Uint8Array, verificationKey: VerificationKey) {\n this.wasmBuffer = wasm;\n this.zkeyBuffer = zkey;\n this.verificationKey = verificationKey;\n }\n\n static async compile(): Promise<ZkCompiled> {\n if (!this.verificationKey) {\n throw new Error('Circuit not initialized. Call setCircuitBuffers() first.');\n }\n return { verificationKey: this.verificationKey };\n }\n\n static async prove(secret: Field): Promise<{ proof: SnarkProof; publicSignals: string[] }> {\n if (!this.wasmBuffer || !this.zkeyBuffer) {\n throw new Error('Circuit not initialized. Call setCircuitBuffers() first.');\n }\n\n // Calculate the hash (this should match what the circuit computes)\n await Poseidon.hash([secret]);\n\n // Create input for the circuit\n const input = {\n secret: secret.toString()\n };\n\n // Generate the proof using @zk-kit/groth16\n const { proof, publicSignals } = await groth16Prove(\n input,\n this.wasmBuffer,\n this.zkeyBuffer\n );\n\n return { proof, publicSignals: publicSignals as string[] };\n }\n\n static async verify(proof: SnarkProof, publicSignals?: string[]): Promise<boolean> {\n if (!this.verificationKey) {\n throw new Error('Circuit not initialized. Call setCircuitBuffers() first.');\n }\n\n try {\n // Cast to satisfy @zk-kit/groth16's stricter Groth16Proof type\n // (protocol/curve required there, optional in our shared type).\n const result = await groth16Verify(\n this.verificationKey,\n { proof: proof as unknown as Parameters<typeof groth16Verify>[1][\"proof\"], publicSignals: (publicSignals || []) as Groth16PublicSignals }\n );\n return result;\n } catch (error) {\n console.error('Verification error:', error);\n return false;\n }\n }\n}\n\n// Circuit wrapper for PreimagePoK (Proof of Knowledge)\nexport class PreimagePoK {\n private static wasmBuffer?: Uint8Array;\n private static zkeyBuffer?: Uint8Array;\n private static verificationKey?: VerificationKey;\n\n static setCircuitBuffers(wasm: Uint8Array, zkey: Uint8Array, verificationKey: VerificationKey) {\n this.wasmBuffer = wasm;\n this.zkeyBuffer = zkey;\n this.verificationKey = verificationKey;\n }\n\n static async compile(): Promise<ZkCompiled> {\n if (!this.verificationKey) {\n throw new Error('Circuit not initialized. Call setCircuitBuffers() first.');\n }\n return { verificationKey: this.verificationKey };\n }\n\n static async prove(\n publicInput: AuthPublicInput,\n secret: Field,\n salt: Field,\n ecdsaPub: Field\n ): Promise<{ proof: SnarkProof; publicSignals: string[] }> {\n if (!this.wasmBuffer || !this.zkeyBuffer) {\n throw new Error('Circuit not initialized. Call setCircuitBuffers() first.');\n }\n\n // Create input for the circuit\n const input = {\n // Public inputs\n commitment: publicInput.commitment,\n nonce: publicInput.nonce,\n ecdsaPubHash: publicInput.ecdsaPubHash,\n // Private inputs\n secret: secret.toString(),\n salt: salt.toString(),\n ecdsaPub: ecdsaPub.toString()\n };\n\n // Generate the proof using @zk-kit/groth16\n const { proof, publicSignals } = await groth16Prove(\n input,\n this.wasmBuffer,\n this.zkeyBuffer\n );\n\n return { proof, publicSignals: publicSignals as string[] };\n }\n\n static async verify(proof: SnarkProof, publicSignals?: string[]): Promise<boolean> {\n if (!this.verificationKey) {\n throw new Error('Circuit not initialized. Call setCircuitBuffers() first.');\n }\n\n try {\n // Cast to satisfy @zk-kit/groth16's stricter Groth16Proof type\n // (protocol/curve required there, optional in our shared type).\n const result = await groth16Verify(\n this.verificationKey,\n { proof: proof as unknown as Parameters<typeof groth16Verify>[1][\"proof\"], publicSignals: (publicSignals || []) as Groth16PublicSignals }\n );\n return result;\n } catch (error) {\n console.error('Verification error:', error);\n return false;\n }\n }\n}\n\n// Verify function for HashKnowledge proof\nexport async function verifyHashKnowledge(\n proof: SnarkProof,\n expectedOutput?: Field,\n publicSignals?: string[]\n): Promise<boolean> {\n try {\n const result = await HashKnowledge.verify(proof, publicSignals);\n\n if (!result) {\n console.error('Hash knowledge proof verification failed');\n return false;\n }\n\n // Optionally verify the public output matches expected value\n if (expectedOutput && publicSignals && publicSignals.length > 0) {\n const outputField = new Field(publicSignals[0]);\n if (!outputField.equals(expectedOutput)) {\n console.error('Public output mismatch in hash knowledge proof');\n return false;\n }\n }\n\n return true;\n } catch (error) {\n console.error('Error verifying hash knowledge proof:', error);\n return false;\n }\n}\n\n// Verify function for PreimagePoK proof\nexport async function verifyPreimagePoK(\n proof: SnarkProof,\n publicSignals?: string[]\n): Promise<boolean> {\n try {\n const result = await PreimagePoK.verify(proof, publicSignals);\n\n if (!result) {\n console.error('Preimage proof verification failed');\n return false;\n }\n\n console.log('Preimage proof verified successfully');\n return true;\n } catch (error) {\n console.error('Error verifying preimage proof:', error);\n return false;\n }\n}\n\n// Generic verify function that determines which program to use\nexport async function verify(\n programType: 'HashKnowledge' | 'PreimagePoK',\n proof: SnarkProof,\n options?: {\n expectedOutput?: Field,\n publicSignals?: string[]\n }\n): Promise<boolean> {\n if (programType === 'HashKnowledge') {\n return verifyHashKnowledge(proof, options?.expectedOutput, options?.publicSignals);\n } else if (programType === 'PreimagePoK') {\n return verifyPreimagePoK(proof, options?.publicSignals);\n } else {\n throw new Error(`Unknown program type: ${programType}`);\n }\n}\n\n// Helper function to verify proof directly\nexport async function quickVerify(\n program: typeof HashKnowledge | typeof PreimagePoK,\n proof: SnarkProof,\n publicSignals?: string[]\n): Promise<boolean> {\n try {\n return await program.verify(proof, publicSignals);\n } catch (error) {\n console.error('Quick verify failed:', error);\n return false;\n }\n}\n\n// Function to initialize circuits with buffers\nexport function initializeCircuits(config: {\n hashKnowledge?: CircuitBufferConfig;\n preimagePoK?: CircuitBufferConfig;\n}) {\n if (config.hashKnowledge) {\n HashKnowledge.setCircuitBuffers(\n config.hashKnowledge.wasm,\n config.hashKnowledge.zkey,\n config.hashKnowledge.verificationKey\n );\n }\n if (config.preimagePoK) {\n PreimagePoK.setCircuitBuffers(\n config.preimagePoK.wasm,\n config.preimagePoK.zkey,\n config.preimagePoK.verificationKey\n );\n }\n}\n\n// Function to compile and cache verification keys\nexport async function compilePrograms(): Promise<{\n hashKnowledge: ZkCompiled,\n preimagePoK: ZkCompiled\n}> {\n console.log('Compiling ZK circuits...');\n\n const [hashKnowledgeCompiled, preimagePoKCompiled] = await Promise.all([\n HashKnowledge.compile(),\n PreimagePoK.compile()\n ]);\n\n console.log('ZK circuits compiled successfully');\n\n return {\n hashKnowledge: hashKnowledgeCompiled,\n preimagePoK: preimagePoKCompiled\n };\n}\n\nexport { Field as FieldElement }; // Export with alias to avoid confusion with Field type\n","import { PreimagePoK, AuthPublicInput, Field, Poseidon, verify, VerificationKey } from './ZeroKnowledge';\nimport { toHex, fromHex, fromBase64Url } from '../utilities';\n\ninterface AuthToken {\n peerId: string;\n timestamp: number;\n signature: string;\n}\n\nclass Authenticator {\n private trustedKeys: Map<string, CryptoKey> = new Map();\n private zkVerificationKey: VerificationKey | null = null;\n\n public async initializeZK(): Promise<void> {\n if (!this.zkVerificationKey) {\n appLogger.debug('Compiling PreimagePoK for verification...');\n const compiled = await PreimagePoK.compile();\n this.zkVerificationKey = compiled.verificationKey;\n }\n }\n\n public getZKVerificationKey(): VerificationKey | null {\n return this.zkVerificationKey;\n }\n\n public addTrustedServer(serverId: string, publicKey: CryptoKey): void {\n this.trustedKeys.set(serverId, publicKey);\n }\n\n public async generateAuthToken(peerId: string, privateKey: CryptoKey): Promise<AuthToken> {\n if (!privateKey) {\n throw new Error(`No private key for ${peerId}`);\n }\n const timestamp = Date.now();\n const data = new TextEncoder().encode(`${peerId}:${timestamp}`);\n const signature = await crypto.subtle.sign(\n { name: 'ECDSA', hash: 'SHA-256' },\n privateKey,\n data\n );\n return { peerId, timestamp, signature: toHex(new Uint8Array(signature)) };\n }\n\n public async verifyAuthToken(token: AuthToken, clientPublicKey: CryptoKey): Promise<boolean> {\n const maxAge = 5 * 60 * 1000;\n if (Math.abs(Date.now() - token.timestamp) > maxAge) {\n appLogger.debug('Auth token expired');\n return false;\n }\n return await crypto.subtle.verify(\n { name: 'ECDSA', hash: 'SHA-256' },\n clientPublicKey,\n fromHex(token.signature),\n new TextEncoder().encode(`${token.peerId}:${token.timestamp}`)\n );\n }\n\n public async verifyZKProof(\n proof: any,\n publicInput: AuthPublicInput,\n storedCommitment: Field,\n ecdsaPub: CryptoKey\n ): Promise<boolean> {\n if (!this.zkVerificationKey) {\n throw new Error('ZK verification key not initialized');\n }\n\n // Convert publicInput to signals array for snarkjs\n const publicSignals = publicInput.toPublicSignals();\n\n // Verify the proof using snarkjs\n const isValid = await verify('PreimagePoK', proof, { publicSignals });\n if (!isValid) {\n appLogger.debug('ZK proof verification failed');\n return false;\n }\n\n // Verify the commitment matches stored value\n const proofCommitment = new Field(publicSignals[0]);\n const matchesCommitment = proofCommitment.equals(storedCommitment);\n\n // Verify nonce matches\n const proofNonce = new Field(publicSignals[1]);\n const expectedNonce = new Field(publicInput.nonce);\n const matchesNonce = proofNonce.equals(expectedNonce);\n\n // Verify ECDSA public key hash\n const ecdsaJwk = await crypto.subtle.exportKey('jwk', ecdsaPub);\n const ecdsaHex = toHex(fromBase64Url(ecdsaJwk.x!)).slice(0, 64);\n const ecdsaPubField = new Field(BigInt('0x' + ecdsaHex));\n const expectedEcdsaPubHash = await Poseidon.hash([ecdsaPubField]);\n const proofEcdsaPubHash = new Field(publicSignals[2]);\n const matchesEcdsaPub = proofEcdsaPubHash.equals(expectedEcdsaPubHash);\n\n appLogger.debug('ZK proof valid:', isValid, 'Commitment:', matchesCommitment, 'Nonce:', matchesNonce, 'ECDSA:', matchesEcdsaPub);\n return isValid && matchesCommitment && matchesNonce && matchesEcdsaPub;\n }\n}\n\nexport { Authenticator, AuthToken };","import { AuthPublicInput, Field, Poseidon } from './ZeroKnowledge';\nimport { Authenticator, AuthToken } from './Authenticator';\nimport { DoubleRatchet } from './DoubleRatchet';\nimport { KeyStore } from './KeyStore';\nimport { CipherMessage, RatchetState } from './types.d';\nimport { toHex, fromBase64Url } from '../utilities';\n\n\nclass DoubleRatchetManager {\n private sessions: Map<string, DoubleRatchet> = new Map();\n private sessionStates: Map<string, RatchetState> = new Map(); // In-memory storage for session states\n private keyStore: KeyStore;\n private _authenticator: Authenticator;\n private registeredUsers: Map<string, { commitment: Field; salt: Field }> = new Map();\n private id: string; // Unique ID for this manager (e.g., client1, server1)\n\n constructor(id: string) {\n this.id = id;\n this.keyStore = KeyStore.getInstance();\n this._authenticator = new Authenticator();\n }\n\n get authenticator(): Authenticator {\n return this._authenticator;\n }\n\n public async addTrustedServer(serverId: string, publicKey: CryptoKey): Promise<void> {\n this._authenticator.addTrustedServer(serverId, publicKey);\n }\n\n public async registerZK(\n clientId: string,\n secret: Field,\n salt: Field,\n ecdsaPub: CryptoKey,\n ): Promise<void> {\n await this._authenticator.initializeZK();\n console.log(`Registering ZK for ${clientId}...`);\n console.log('ECDSA Public Key:', ecdsaPub);\n const ecdsaJwk = await crypto.subtle.exportKey('jwk', ecdsaPub);\n const ecdsaHex = toHex(fromBase64Url(ecdsaJwk.x!)).slice(0, 64);\n const ecdsaPubField = new Field(BigInt('0x' + ecdsaHex));\n const ecdsaPubHash = await Poseidon.hash([ecdsaPubField]);\n const commitment = await Poseidon.hash([secret, salt, ecdsaPubHash]);\n console.log(`Commitment for ${clientId}:`, { commitment, salt });\n this.registeredUsers.set(clientId, { commitment, salt });\n appLogger.debug(`Registered ${clientId}: commitment=${commitment.toString()}, salt=${salt.toString()}`);\n\n }\n\n public async performHandshake(\n senderId: string,\n recipientId: string,\n zkProof: any,\n publicInput: AuthPublicInput,\n clientPublicKey: CryptoKey, // ECDH pub for session\n clientAuthPublicKey: CryptoKey, // ECDSA pub for auth\n authToken: AuthToken // Client-generated token\n ): Promise<void> {\n await this._authenticator.initializeZK();\n\n const userData = this.registeredUsers.get(senderId);\n if (!userData) {\n throw new Error(`No registered commitment for ${senderId}`);\n }\n\n const isZKValid = await this._authenticator.verifyZKProof(\n zkProof,\n publicInput,\n userData.commitment,\n clientAuthPublicKey\n );\n if (!isZKValid) {\n throw new Error(`ZK handshake failed for ${senderId}`);\n }\n\n // Verify client-provided auth token\n if (!await this._authenticator.verifyAuthToken(authToken, clientAuthPublicKey)) {\n throw new Error(`Token verification failed for ${senderId}`);\n }\n\n // Store only public keys\n await this.keyStore.storeRemotePublicKeys(senderId, clientPublicKey, clientAuthPublicKey);\n const serverKeyPair = this.keyStore.getKeyPair(recipientId)!;\n const serverAuth = this.keyStore.getAuthKeyPair(recipientId)!;\n await this.keyStore.storeRemotePublicKeys(recipientId, serverKeyPair.publicKey, serverAuth.publicKey);\n appLogger.debug(`Handshake completed for ${senderId} -> ${recipientId}`);\n }\n\n public async initializeSession(\n senderId: string,\n recipientId: string,\n isClient: boolean = true,\n sessionType: 'global' | 'specific' = 'specific',\n sessionId?: string,\n zkProof?: any,\n publicInput?: AuthPublicInput,\n clientPublicKey?: CryptoKey,\n clientAuthPublicKey?: CryptoKey,\n clientEcdhPrivateKey?: CryptoKey,\n clientAuthPrivateKey?: CryptoKey\n ): Promise<string> {\n const keyStore = KeyStore.getInstance();\n const recipientKeyPair = keyStore.getKeyPair(recipientId);\n if (!recipientKeyPair?.publicKey && sessionType === 'specific' && isClient) {\n // Generate auth token from client auth private key if provided\n const authToken = clientAuthPrivateKey ?\n await this._authenticator.generateAuthToken(senderId, clientAuthPrivateKey) :\n await this._authenticator.generateAuthToken(senderId, this.keyStore.getAuthKeyPair(senderId)!.privateKey!);\n\n await this.performHandshake(\n senderId,\n recipientId,\n zkProof!,\n publicInput!,\n clientPublicKey!,\n clientAuthPublicKey!,\n authToken\n );\n } else if (!recipientKeyPair?.publicKey) {\n throw new Error(`Missing public key for ${recipientId}. Perform handshake or register first.`);\n }\n\n const finalSessionId = sessionId || (sessionType === 'specific'\n ? [senderId, recipientId].sort().join(':') + `:${Date.now()}`\n : `${senderId}:${recipientId}:${Date.now()}`);\n\n const ratchet = new DoubleRatchet(senderId, recipientId, sessionType, isClient);\n await ratchet.initializeSession(isClient);\n this.sessions.set(finalSessionId, ratchet);\n await this.saveState(finalSessionId, ratchet.getState());\n appLogger.debug(`Session initialized: ${finalSessionId}, type=${sessionType}`);\n return finalSessionId;\n }\n\n public async encrypt(\n senderId: string,\n recipientId: string,\n sessionId: string,\n plaintext: string,\n newDhKey: boolean = false,\n sessionType: 'global' | 'specific' = 'specific'\n ): Promise<CipherMessage> {\n let ratchet = this.sessions.get(sessionId);\n if (!ratchet) {\n const state = await this.loadState(sessionId);\n if (!state) throw new Error(`Session not found: ${sessionId}`);\n ratchet = new DoubleRatchet(senderId, recipientId, sessionType, false);\n ratchet.setState(state);\n this.sessions.set(sessionId, ratchet);\n }\n\n const message = await ratchet.encrypt(plaintext, newDhKey, senderId, recipientId, sessionId, sessionType);\n await this.saveState(sessionId, ratchet.getState());\n appLogger.debug('KeyStore after encrypt:', Array.from(this.keyStore.keys.entries()).map(([id]) => `${id}: publicKey`));\n return message;\n }\n\n public async decrypt(message: CipherMessage, isClient: boolean = true): Promise<string> {\n // const { sessionId, sessionType, senderId, recipientId } = message.header;\n const header = message.header;\n let ratchet = this.sessions.get(header.sessionId);\n if (!ratchet) {\n const state = await this.loadState(header.sessionId);\n if (!state) throw new Error(`Session not found: ${header.sessionId}`);\n ratchet = new DoubleRatchet(header.senderId, header.recipientId, header.sessionType, isClient);\n ratchet.setState(state);\n this.sessions.set(header.sessionId, ratchet);\n }\n\n const plaintext = await ratchet.decrypt(message, isClient);\n await this.saveState(header.sessionId, ratchet.getState());\n return plaintext;\n }\n\n public async getSessionSharedSecret(sessionId: string): Promise<Uint8Array | null> {\n let ratchet = this.sessions.get(sessionId);\n if (!ratchet) {\n const state = await this.loadState(sessionId);\n if (!state || !state.rootKey) {\n appLogger.debug(`No shared secret found for session: ${sessionId}`);\n return null;\n }\n return state.rootKey;\n }\n\n const state = ratchet.getState();\n if (!state.rootKey) {\n appLogger.debug(`Session ${sessionId} not initialized yet`);\n return null;\n }\n\n return state.rootKey;\n }\n\n private async saveState(sessionId: string, state: RatchetState): Promise<void> {\n appLogger.debug(`Saving state in memory: sessionId=${sessionId}`);\n // Store the state directly in memory\n // No need to serialize/deserialize as we're keeping it in memory\n this.sessionStates.set(`${this.id}-${sessionId}`, state);\n }\n\n private async loadState(sessionId: string): Promise<RatchetState | null> {\n appLogger.debug(`Loading state from memory: sessionId=${sessionId}`);\n // Retrieve the state directly from memory\n const state = this.sessionStates.get(`${this.id}-${sessionId}`);\n return state || null;\n }\n}\n\nexport { DoubleRatchetManager, RatchetState, CipherMessage, AuthPublicInput };","/**\n * Per-chunk AES-256-GCM encryption with random keys and IVs.\n *\n * Each chunk of a stored file gets its own freshly generated 256-bit AES key\n * and 96-bit IV. The (key, IV) pair lives in the file manifest, which the\n * application is responsible for storing under whatever access-control regime\n * it uses (in this codebase: the `SharedSpaceClient` writes manifests into\n * ZK-gated multi-user spaces; the shard store itself is open).\n *\n * Per-chunk keys (rather than a per-file DEK) lets future versions revoke or\n * re-share individual chunks without re-encrypting the whole file. The\n * additional manifest size is dominated by the shard hash list anyway.\n *\n * The cipher itself delegates to the canonical `encryptAesGcm` / `decryptAesGcm`\n * primitives — this class only wraps them with key-material generation and\n * the JSON-friendly base64 serialization the manifest needs.\n */\n\nimport { fromBase64, toBase64 } from \"../utilities/bytes\";\nimport {\n encryptAesGcm,\n decryptAesGcm,\n randomBytes,\n AES_GCM_KEY_BYTES,\n AES_GCM_IV_BYTES,\n} from \"./primitives\";\n\n/**\n * Per-chunk key material, base64-encoded for JSON-friendly storage in the\n * manifest. The IV is unique per chunk; the key is unique per chunk too in\n * this codebase, though that's a stricter property than AES-GCM strictly\n * requires (which is \"unique IV per key\").\n */\nexport interface ChunkKeyMaterial {\n /** Base64-encoded 32-byte AES-256 key. */\n key: string;\n /** Base64-encoded 12-byte AES-GCM IV. */\n iv: string;\n}\n\nexport class ChunkCipher {\n /**\n * Generate a fresh random (key, iv) pair encoded for the manifest.\n * Callers should generate one of these per chunk before calling\n * {@link encryptChunk}.\n */\n generateKeyMaterial(): ChunkKeyMaterial {\n return {\n key: toBase64(randomBytes(AES_GCM_KEY_BYTES)),\n iv: toBase64(randomBytes(AES_GCM_IV_BYTES)),\n };\n }\n\n /**\n * Encrypt `plaintext` under the supplied key + IV. Returns the AES-GCM\n * ciphertext with the 16-byte auth tag appended (WebCrypto's default\n * GCM behavior).\n */\n async encryptChunk(plaintext: Uint8Array, material: ChunkKeyMaterial): Promise<Uint8Array> {\n return encryptAesGcm(fromBase64(material.key), fromBase64(material.iv), plaintext);\n }\n\n /**\n * Inverse of {@link encryptChunk}. Throws if the auth tag fails — that\n * means the ciphertext was tampered with, the key/iv was wrong, or the\n * shards were reassembled incorrectly.\n */\n async decryptChunk(ciphertext: Uint8Array, material: ChunkKeyMaterial): Promise<Uint8Array> {\n try {\n return await decryptAesGcm(\n fromBase64(material.key),\n fromBase64(material.iv),\n ciphertext,\n );\n } catch {\n // WebCrypto throws a vague OperationError on GCM tag mismatch.\n // Surface a stable, readable message so callers can react to it.\n throw new Error(\n \"ChunkCipher.decryptChunk: decryption failed (key/iv mismatch, corrupted ciphertext, or reassembly error)\",\n );\n }\n }\n}\n\nexport default ChunkCipher;\n","/**\n * Passphrase-based wrap / unwrap helpers using WebCrypto.\n *\n * Encrypt a payload with a user-supplied passphrase before persisting it\n * somewhere the server can see (e.g. the manifest blob in a ZK-gated\n * SharedSpace, or chat-key material in a PersonalSpace). The server never\n * sees the passphrase or the plaintext — both wrap and unwrap run entirely\n * client-side.\n *\n * Algorithm (the only one this codebase has ever shipped):\n * - PBKDF2-SHA256 with 200_000 iterations derives a 256-bit AES key from\n * `passphrase || salt`.\n * - AES-256-GCM encrypts the plaintext with a fresh random 12-byte IV.\n * - The auth tag is appended to the ciphertext by WebCrypto's default\n * GCM behaviour, so {@link WrappedPayload.ciphertext} carries it implicitly.\n *\n * The returned {@link WrappedPayload} is JSON-friendly (all base64 fields), so\n * it can be `JSON.stringify`-ed straight into a KV layer.\n */\n\nimport {\n encryptAesGcm,\n decryptAesGcm,\n deriveAesKeyFromPassphrase,\n randomBytes,\n PBKDF2_DEFAULT_ITERATIONS,\n AES_GCM_IV_BYTES,\n} from \"./primitives\";\n\n/**\n * The persisted, JSON-friendly representation of a passphrase-wrapped blob.\n *\n * The `alg` field is a self-describing marker — if we ever rotate KDF/cipher,\n * unwrap can switch on this value to keep older payloads readable.\n */\nexport interface WrappedPayload {\n /** Random per-wrap salt for PBKDF2, base64. */\n salt: string;\n /** AES-GCM IV, base64. */\n iv: string;\n /** AES-GCM ciphertext (includes 16-byte GCM auth tag), base64. */\n ciphertext: string;\n /** Algorithm marker so future readers know what they're looking at. */\n alg: \"PBKDF2-SHA256/AES-256-GCM\";\n /** PBKDF2 iteration count used. */\n iter: number;\n}\n\n/** Length of the PBKDF2 salt, in bytes. */\nconst SALT_BYTES = 16;\n\n/** Encode a `Uint8Array` to standard base64 (with padding). */\nfunction bytesToBase64(bytes: Uint8Array): string {\n // Build chunk-wise to avoid blowing the call stack on large payloads.\n let binary = \"\";\n const CHUNK = 0x8000;\n for (let i = 0; i < bytes.length; i += CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));\n }\n if (typeof btoa === \"function\") return btoa(binary);\n return Buffer.from(bytes).toString(\"base64\");\n}\n\n/** Decode a base64 string back into a `Uint8Array`. */\nfunction base64ToBytes(b64: string): Uint8Array {\n if (typeof atob === \"function\") {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n }\n return new Uint8Array(Buffer.from(b64, \"base64\"));\n}\n\n/**\n * Encrypt `plaintext` under a key derived from `passphrase`. The returned\n * payload bundles the salt, IV, and ciphertext so unwrap only needs the\n * passphrase to reverse the operation.\n */\nexport async function wrapWithPassphrase(\n passphrase: string,\n plaintext: Uint8Array,\n): Promise<WrappedPayload> {\n if (typeof passphrase !== \"string\" || passphrase.length === 0) {\n throw new Error(\"wrapWithPassphrase: passphrase must be a non-empty string\");\n }\n const salt = randomBytes(SALT_BYTES);\n const iv = randomBytes(AES_GCM_IV_BYTES);\n const key = await deriveAesKeyFromPassphrase(passphrase, salt, PBKDF2_DEFAULT_ITERATIONS);\n const ciphertext = await encryptAesGcm(key, iv, plaintext);\n return {\n salt: bytesToBase64(salt),\n iv: bytesToBase64(iv),\n ciphertext: bytesToBase64(ciphertext),\n alg: \"PBKDF2-SHA256/AES-256-GCM\",\n iter: PBKDF2_DEFAULT_ITERATIONS,\n };\n}\n\n/**\n * Decrypt a {@link WrappedPayload} produced by {@link wrapWithPassphrase}.\n * Throws if the passphrase is wrong, the payload is tampered with, or the\n * algorithm marker is unrecognised.\n */\nexport async function unwrapWithPassphrase(\n passphrase: string,\n wrapped: WrappedPayload,\n): Promise<Uint8Array> {\n if (typeof passphrase !== \"string\" || passphrase.length === 0) {\n throw new Error(\"unwrapWithPassphrase: passphrase must be a non-empty string\");\n }\n if (wrapped.alg !== \"PBKDF2-SHA256/AES-256-GCM\") {\n throw new Error(`unwrapWithPassphrase: unsupported alg \"${wrapped.alg}\"`);\n }\n const salt = base64ToBytes(wrapped.salt);\n const iv = base64ToBytes(wrapped.iv);\n const ciphertext = base64ToBytes(wrapped.ciphertext);\n const key = await deriveAesKeyFromPassphrase(\n passphrase,\n salt,\n wrapped.iter ?? PBKDF2_DEFAULT_ITERATIONS,\n );\n try {\n return await decryptAesGcm(key, iv, ciphertext);\n } catch {\n // WebCrypto throws a vague OperationError on GCM tag mismatch; turn it\n // into a stable, readable message so callers can react to it.\n throw new Error(\n \"unwrapWithPassphrase: decryption failed (wrong passphrase or tampered payload)\",\n );\n }\n}\n","/**\n * Shared zero-knowledge types and circuit constants.\n *\n * Used by both the browser/server builds (where snarkjs handles proof generation\n * and verification) and the workers build (where verification runs through\n * `bn128.wasm` via `src/workers/groth16-verifier.ts`). Keeping these here ensures\n * proof shapes and verification keys stay identical across runtimes.\n */\n\n/**\n * Groth16 proof structure (BN128).\n *\n * - `pi_a`: G1 point as `[x, y]` or projective `[x, y, z]`.\n * - `pi_b`: G2 point as `[[x0, x1], [y0, y1]]` or projective `[..., [z0, z1]]`.\n * - `pi_c`: G1 point as `[x, y]` or projective `[x, y, z]`.\n *\n * Field elements are decimal-string-encoded BigInts (snarkjs convention).\n */\nexport interface Groth16Proof {\n pi_a: string[];\n pi_b: string[][];\n pi_c: string[];\n protocol?: string;\n curve?: string;\n}\n\n/**\n * Groth16 verification key (BN128).\n *\n * Field elements are decimal-string-encoded BigInts (snarkjs convention).\n */\nexport interface VerificationKey {\n protocol: string;\n curve: string;\n nPublic: number;\n vk_alpha_1: string[];\n vk_beta_2: string[][];\n vk_gamma_2: string[][];\n vk_delta_2: string[][];\n vk_alphabeta_12: string[][][];\n IC: string[][];\n}\n\n/**\n * Verification key for the `preimagePoK` circuit (Poseidon-commitment\n * proof-of-knowledge with three public signals: commitment, nonce, ecdsaPubHash).\n *\n * Pinned here so worker-side and SDK-side verification agree on the key being\n * checked. If the circuit is recompiled, regenerate this constant and\n * `public/circuits/build/preimagePoK_verification_key.json` together.\n */\nexport const PREIMAGE_POK_VERIFICATION_KEY: VerificationKey = {\n protocol: \"groth16\",\n curve: \"bn128\",\n nPublic: 3,\n vk_alpha_1: [\n \"20491192805390485299153009773594534940189261866228447918068658471970481763042\",\n \"9383485363053290200918347156157836566562967994039712273449902621266178545958\",\n \"1\"\n ],\n vk_beta_2: [\n [\n \"6375614351688725206403948262868962793625744043794305715222011528459656738731\",\n \"4252822878758300859123897981450591353533073413197771768651442665752259397132\"\n ],\n [\n \"10505242626370262277552901082094356697409835680220590971873171140371331206856\",\n \"21847035105528745403288232691147584728191162732299865338377159692350059136679\"\n ],\n [\n \"1\",\n \"0\"\n ]\n ],\n vk_gamma_2: [\n [\n \"10857046999023057135944570762232829481370756359578518086990519993285655852781\",\n \"11559732032986387107991004021392285783925812861821192530917403151452391805634\"\n ],\n [\n \"8495653923123431417604973247489272438418190587263600148770280649306958101930\",\n \"4082367875863433681332203403145435568316851327593401208105741076214120093531\"\n ],\n [\n \"1\",\n \"0\"\n ]\n ],\n vk_delta_2: [\n [\n \"16843627858994773805056502117979518680360297888097507527057721641174626133429\",\n \"2669618170444825402403730985182974839894668798317345855172970345856260721653\"\n ],\n [\n \"20564952487570762020467138133408075499830271526522626813107251678961587215295\",\n \"9630342855454833575580303045534431010412631371159617591163132980579520487965\"\n ],\n [\n \"1\",\n \"0\"\n ]\n ],\n vk_alphabeta_12: [\n [\n [\n \"2029413683389138792403550203267699914886160938906632433982220835551125967885\",\n \"21072700047562757817161031222997517981543347628379360635925549008442030252106\"\n ],\n [\n \"5940354580057074848093997050200682056184807770593307860589430076672439820312\",\n \"12156638873931618554171829126792193045421052652279363021382169897324752428276\"\n ],\n [\n \"7898200236362823042373859371574133993780991612861777490112507062703164551277\",\n \"7074218545237549455313236346927434013100842096812539264420499035217050630853\"\n ]\n ],\n [\n [\n \"7077479683546002997211712695946002074877511277312570035766170199895071832130\",\n \"10093483419865920389913245021038182291233451549023025229112148274109565435465\"\n ],\n [\n \"4595479056700221319381530156280926371456704509942304414423590385166031118820\",\n \"19831328484489333784475432780421641293929726139240675179672856274388269393268\"\n ],\n [\n \"11934129596455521040620786944827826205713621633706285934057045369193958244500\",\n \"8037395052364110730298837004334506829870972346962140206007064471173334027475\"\n ]\n ]\n ],\n IC: [\n [\n \"6593633352362890744195366164011945207337919238085164401989523182031213441232\",\n \"21183283244721822514187218730411278389501771108619619957207607994811554523781\",\n \"1\"\n ],\n [\n \"19317830753800014286972931403860527733342849870141075528271937285218206220756\",\n \"14626265811834596630857393417326981325583938311796888424299048456918853093257\",\n \"1\"\n ],\n [\n \"7942727853353225551121019923926808347232536417992238353855978019969636961405\",\n \"8824649763391398686420260814761862276544573369118345976741973565095405175062\",\n \"1\"\n ],\n [\n \"8369441262422248167284752361555580367206817200973928868895308479466335503315\",\n \"7836653245051994305208746627300011506099851195782496031197976259815728652585\",\n \"1\"\n ]\n ]\n};\n","export enum EventCoreEvents {\n CONNECTED = \"connected\",\n DISCONNECTED = \"disconnected\",\n RECONNECTING = \"reconnecting\",\n ERROR = \"error\",\n DATA_RECEIVED = \"data_received\",\n DATA_SENT = \"data_sent\",\n MESSAGE = \"message\",\n GET_HISTORY = \"get_history\",\n RECEIVED_HISTORY = \"received_history\",\n}\n\n\n/**\n * @public\n * EventCore is a static event emitter with singleton functionality for global event handling.\n */\nexport class EventCore {\n private static eventTarget: EventTarget = new EventTarget();\n private static events = new Map<string, EventListener | CallableFunction>();\n\n /**\n * @remarks Listen to an event.\n * @example EventCore.on('event', (e) =\\> appLogger.debug(e));\n */\n static on(event: EventCoreEvents, handler: EventListener | CallableFunction) {\n if (!EventCore.events.has(event)) {\n EventCore.events.set(event, handler);\n }\n EventCore.eventTarget.addEventListener(event, handler as EventListener);\n }\n\n /**\n * @remarks Stop listening to an event.\n * @example EventCore.off('event', handler);\n */\n static off(event: EventCoreEvents, handler: EventListener | CallableFunction) {\n if (EventCore.events.has(event)) {\n EventCore.events.delete(event);\n }\n EventCore.eventTarget.removeEventListener(event, handler as EventListener);\n }\n\n /**\n * @remarks Emit an event.\n * @example EventCore.emit('event', data);\n */\n static emit(event: EventCoreEvents, data: any) {\n if (!EventCore.events.has(event)) {\n appLogger.debug(`Warning: No listeners for event: ${event}`);\n // appLogger.verbose(`Event data:`, data);\n }\n EventCore.eventTarget.dispatchEvent(new CustomEvent(event, { detail: data }));\n }\n}\n\nexport default EventCore;","import { _messageId, generateChecksum, verifyChecksum, serialize, deserialize, _formatBytes, log } from '../utilities';\n\n/**\n * @public\n * @remarks\n * The body type is a generic type that can be any value. Internally we handle the serialization and deserialization of the body.\n */\nexport type MessageBody = any;\n\n/**\n * @public\n * @remarks\n * The message headers type is a simple record object that contains key value pairs. Think of these as metadata for the message, similar to HTTP headers.\n */\nexport type MessageHeaders = Map<string, string>;\n\n/**\n * @public\n * @remarks\n * The message options type is a record object that contains the options for the message.\n */\nexport interface MessageOptions {\n id?: string;\n body: MessageBody;\n status?: \"pending\" | \"processed\" | \"failed\" | \"delivered\";\n checksum?: string;\n}\n\n\n/**\n * @public\n * @remarks\n * The message class is a simple class that represents a message object.\n * @sealed\n */\nexport class Message {\n id: string = _messageId();\n timestamp: number = Date.now();\n status?: \"pending\" | \"processed\" | \"failed\" | \"delivered\" = \"pending\";\n checksum?: string;\n private _body: MessageBody;\n\n constructor(msg: MessageBody)\n constructor(msg: MessageOptions)\n constructor(msg: MessageOptions | MessageBody) {\n\n if (typeof msg === 'object' && msg.hasOwnProperty('body')) {\n this.id = msg.id || this.id;\n this.timestamp = msg.timestamp || this.timestamp;\n this.status = msg.status || this.status;\n this.checksum = msg.checksum || this.checksum;\n this.body = msg.body;\n } else {\n this.body = msg;\n }\n this.validatebodySize();\n }\n\n get body(): MessageBody {\n return deserialize(this._body);\n }\n\n set body(value: MessageBody) {\n this._body = serialize(value);\n if (!this.checksum) {\n this.checksum = generateChecksum(this._body);\n }\n }\n\n verifyChecksum = () => {\n if (!this.checksum) throw new Error(\"No message checksum\");\n const isValid = verifyChecksum(this._body, this.checksum);\n if (!isValid) throw new Error(\"Invalid message checksum\");\n }\n\n private validatebodySize(maxSize: number = 1024 * 1024 * 3) {\n const sizeInBytes = new TextEncoder().encode(this._body).length;\n if (sizeInBytes > maxSize) {\n throw new Error(`body size exceeds the limit of ${_formatBytes(maxSize)}.`);\n }\n }\n\n\n serialize = (): string => {\n return JSON.stringify({\n id: this.id,\n timestamp: this.timestamp,\n body: this.body,\n status: this.status,\n checksum: this.checksum,\n });\n }\n\n static deserialize = (data: string): Message => {\n if (typeof data !== 'string') {\n log.warn('Message.deserialize: data is not a string', data);\n }\n const msg = JSON.parse(data);\n return new Message(msg);\n }\n}\n\nexport default Message;","import { Message } from \"./Message\";\nimport { _packetId } from \"../utilities\";\n\ntype Address = string; // Represents a unique peer or node ID in the network\n\nexport interface PacketOptions {\n id?: string;\n subject: string;\n source: Address;\n target: Address;\n headers?: {\n [key: string]: string | number | boolean | undefined; // Optional: Additional headers for the packet\n };\n message?: Message;\n ttl?: number;\n timestamp?: number;\n signature?: string;\n}\n\n/**\n * @public\n * @remarks\n * This class represents a message object that can be sent over the network\n * @sealed\n */\nexport class Packet {\n id: string;\n subject: string;\n source: Address;\n target: Address;\n headers?: PacketOptions['headers']; // Optional: Additional headers for the packet\n message?: Message; // By making the message optional, we can send packets without messages. Essentially performing a GET request or other bodyless requests\n timestamp: number;\n ttl?: number; // Optional: Time-to-live in milliseconds\n signature?: string; // Optional: Cryptographic signature for verification\n\n constructor({\n id,\n subject,\n source,\n target,\n headers,\n message,\n ttl,\n signature,\n timestamp\n }: PacketOptions) {\n this.id = id || _packetId(); // Ensure the packet has a unique ID\n this.subject = subject;\n this.source = source;\n this.target = target;\n this.headers = headers || {};\n this.message = message;\n this.timestamp = Date.now(); // Automatically track packet creation time\n this.ttl = ttl;\n this.signature = signature;\n this.timestamp = timestamp || Date.now();\n }\n\n // Serialize the packet for network transmission\n serialize(): string {\n return JSON.stringify({\n id: this.id,\n source: this.source,\n subject: this.subject,\n target: this.target,\n headers: this.headers,\n message: this.message && this.message.serialize(),\n timestamp: this.timestamp,\n ttl: this.ttl,\n signature: this.signature,\n });\n }\n\n // Deserialize a packet from a string\n static deserialize(data: string): Packet {\n const obj = JSON.parse(data);\n return new Packet({\n id: obj.id,\n subject: obj.subject,\n source: obj.source,\n target: obj.target,\n headers: obj.headers,\n message: obj.message && Message.deserialize(obj.message),\n timestamp: obj.timestamp,\n ttl: obj.ttl,\n signature: obj.signature,\n });\n }\n\n // Verify TTL: Checks if the packet is still valid based on TTL\n isExpired(): boolean {\n if (!this.ttl) return false; // No TTL means no expiration\n return Date.now() > this.timestamp + this.ttl;\n }\n\n // sign(signingKey: string) {\n // this.signature = generateSignature(this.serialize(), signingKey); // Example signature function\n // }\n\n // verifySignature(publicKey: string): boolean {\n // if (!this.signature) throw new Error(\"No signature to verify\");\n // return verifySignature(this.serialize(), this.signature, publicKey);\n // }\n}","import { Message } from \"./Message\";\nimport { Packet } from \"./Packet\";\n\n\nexport function SerializeMessage(target: any, propertyKey: string, descriptor: PropertyDescriptor) {\n const originalMethod = descriptor.value;\n\n descriptor.value = function (...args: any[]) {\n const [subject, message] = args;\n\n if (typeof message !== \"string\") {\n throw new Error(\"Message must be a string\");\n }\n\n const serializedMessage = new Message({\n subject,\n payload: message,\n status: \"pending\",\n headers: new Map([[\"Content-Type\", \"application/json\"]]),\n }).serialize();\n\n\n return originalMethod.apply(this, [subject, serializedMessage]);\n };\n\n return descriptor;\n}","// Re-export Message and its types\nexport { Message, type MessageHeaders, type MessageBody, type MessageOptions } from \"./Message\";\nexport { default as MessageDefault } from \"./Message\";\n\n// Re-export Packet and its types\nexport { Packet, type PacketOptions } from \"./Packet\";\n\n// Export decorators\nexport { SerializeMessage } from \"./decorators\";\n\nimport { SerializeMessage } from \"./decorators\";\nconst decorators = {\n SerializeMessage\n}\n\nexport { decorators }","/**\n * HTTP client for the accelerator's `/api/auth/*` endpoints.\n *\n * Owns the wire shapes for register / challenge / authenticate / verify so\n * the React SPA (and any future consumers) don't reimplement them. The ZK\n * identity derivation + Groth16 proof generation stay on the application\n * side — this client handles only the round-trips.\n *\n * Mirrors `PersonalSpaceClient` / `ShardClient` / `SharedSpaceClient`: takes\n * a `baseUrl`, optional custom `fetch`, throws typed `Error`s on failure\n * (with the worker's message inlined where available).\n */\n\nimport type { Groth16Proof } from \"../types/zk\";\n\n// ---------------------------------------------------------------------------\n// Wire types — must stay in sync with `accelerator/src/durable-objects/UserAuth.ts`.\n// ---------------------------------------------------------------------------\n\nexport interface ZkRegisterRequest {\n username: string;\n /** Decimal-string Poseidon commitment. */\n commitment: string;\n /** Base64-encoded raw uncompressed ECDH public key (SEC1 0x04‖X‖Y). */\n ecdhPublicKey: string;\n /** Base64-encoded raw uncompressed ECDSA public key. */\n ecdsaPublicKey: string;\n email?: string | null;\n}\n\nexport interface ZkRegisterResponse {\n success: boolean;\n}\n\nexport interface ZkChallengeResponse {\n challengeId: string;\n /** Hex-encoded random nonce — caller reduces into a BN254 field element for the proof. */\n nonce: string;\n /** Decimal-string Poseidon commitment the server has on file for this user. */\n commitment: string;\n}\n\nexport interface ZkAuthenticateRequest {\n challengeId: string;\n proof: {\n commitment: string;\n /** Original hex nonce from the challenge (NOT the field-reduced version). */\n nonce: string;\n response: {\n proof: Groth16Proof;\n publicSignals: string[];\n };\n /** Base64 ECDSA-SHA256 signature over `JSON.stringify(response.proof)`. */\n signature: string;\n };\n rememberMe?: boolean;\n}\n\nexport interface AuthSuccess {\n token: string;\n username: string;\n}\n\n// ---------------------------------------------------------------------------\n// AuthClient\n// ---------------------------------------------------------------------------\n\nexport interface AuthClientOptions {\n /** Absolute URL of the accelerator worker (no trailing slash required). */\n baseUrl: string;\n /** Optional custom fetch — defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n}\n\nexport class AuthClient {\n private readonly baseUrl: string;\n private readonly fetchFn: typeof fetch;\n\n constructor(opts: AuthClientOptions) {\n if (!opts?.baseUrl) throw new Error(\"AuthClient: `baseUrl` is required\");\n this.baseUrl = opts.baseUrl.replace(/\\/+$/, \"\");\n const f = opts.fetch ?? globalThis.fetch;\n if (typeof f !== \"function\") {\n throw new Error(\"AuthClient: `globalThis.fetch` is unavailable; pass an explicit fetch.\");\n }\n this.fetchFn = f.bind(globalThis);\n }\n\n /** Submit ZK registration. Caller has already derived the identity + commitment. */\n async register(req: ZkRegisterRequest): Promise<ZkRegisterResponse> {\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/zk-register`, this.json(\"POST\", req));\n return await this.parse<ZkRegisterResponse>(\"register\", res);\n }\n\n /** Request an auth challenge for `username` (server issues a fresh nonce). */\n async getChallenge(username: string): Promise<ZkChallengeResponse> {\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/challenge`, this.json(\"POST\", { username }));\n return await this.parse<ZkChallengeResponse>(\"getChallenge\", res);\n }\n\n /** Trade a challenge + proof for a session token. */\n async authenticate(req: ZkAuthenticateRequest): Promise<AuthSuccess> {\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/zk-authenticate`, this.json(\"POST\", req));\n return await this.parse<AuthSuccess>(\"authenticate\", res);\n }\n\n /**\n * Validate a previously stored session token. Returns `{ username }` on\n * success; throws on 401/404 — caller uses that to drop a stale token\n * when restoring a session after a reload.\n */\n async verify(token: string): Promise<{ username: string }> {\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/verify`, this.json(\"POST\", { token }));\n return await this.parse<{ username: string }>(\"verify\", res);\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private json(method: string, body: unknown): RequestInit {\n return {\n method,\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n };\n }\n\n private async parse<T>(label: string, res: Response): Promise<T> {\n let body: unknown = null;\n try {\n body = await res.json();\n } catch {\n // Leave body null; we'll fall through to the status-only message.\n }\n if (!res.ok) {\n const msg =\n body && typeof body === \"object\" && \"error\" in (body as object)\n ? String((body as { error: unknown }).error)\n : `${res.status} ${res.statusText}`;\n throw new Error(`AuthClient.${label}: ${msg}`);\n }\n return body as T;\n }\n}\n\nexport default AuthClient;\n","/**\n * Deterministic ZK identity derivation from `(username, password)`.\n *\n * Same inputs on ANY device produce the same secret, salt, and P-256\n * ECDSA + ECDH keypairs — which is what makes federated login from a\n * fresh browser possible. There is no localStorage involvement: every\n * register and login call re-derives the identity on demand.\n *\n * Pipeline:\n * master_seed = PBKDF2-SHA256(password, \"muhkoo-zk-v1:\" || username, 200k iters)\n * secret = HKDF-Expand-SHA256(master_seed, \"zk-secret\", 32 bytes) → hex\n * salt = HKDF-Expand-SHA256(master_seed, \"zk-salt\", 32 bytes) → hex\n * ecdsa_priv = HKDF-Expand-SHA256(master_seed, \"ecdsa-priv\", 32 bytes)\n * ecdh_priv = HKDF-Expand-SHA256(master_seed, \"ecdh-priv\", 32 bytes)\n *\n * P-256 public points are computed via `@noble/curves` (WebCrypto has no\n * derive-public-from-private-scalar API), then both keypairs are imported\n * into SubtleCrypto in JWK form so the rest of the crypto stack can keep\n * using `crypto.subtle.sign` / `crypto.subtle.deriveBits`.\n *\n * Originally lived in `accelerator/public/js/zk-identity.js` and was ported\n * to `muhkoo/web/src/zk/identity.ts`; consolidated here so the SDK owns\n * identity derivation end-to-end.\n */\n\n// @noble/curves v2 consolidated all NIST curves under `nist`; v1 had a\n// `/p256` subpath. Update if the dep changes again.\nimport { p256 } from \"@noble/curves/nist.js\";\nimport { toHex } from \"../utilities/bytes\";\n\nconst TEXT_ENCODER = new TextEncoder();\nconst PBKDF2_ITERATIONS = 200_000;\nconst SCALAR_BYTES = 32;\n\nexport interface ZkIdentity {\n /** 32-byte secret, hex-encoded. Private witness for the ZK circuit. */\n secretHex: string;\n /** 32-byte salt, hex-encoded. Private witness for the ZK circuit. */\n saltHex: string;\n /** P-256 ECDSA keypair, used to sign auth proofs. */\n ecdsaKeyPair: CryptoKeyPair;\n /** P-256 ECDH keypair, used by the chat ratchet. */\n ecdhKeyPair: CryptoKeyPair;\n}\n\nasync function pbkdf2Bytes(password: string, info: string, byteLength: number): Promise<Uint8Array> {\n const baseKey = await crypto.subtle.importKey(\n \"raw\",\n TEXT_ENCODER.encode(password),\n { name: \"PBKDF2\" },\n false,\n [\"deriveBits\"],\n );\n const bits = await crypto.subtle.deriveBits(\n {\n name: \"PBKDF2\",\n salt: TEXT_ENCODER.encode(info),\n iterations: PBKDF2_ITERATIONS,\n hash: \"SHA-256\",\n },\n baseKey,\n byteLength * 8,\n );\n return new Uint8Array(bits);\n}\n\nasync function hkdfExpand(prk: Uint8Array, info: string, byteLength: number): Promise<Uint8Array> {\n const baseKey = await crypto.subtle.importKey(\n \"raw\",\n prk as BufferSource,\n { name: \"HKDF\" },\n false,\n [\"deriveBits\"],\n );\n const bits = await crypto.subtle.deriveBits(\n {\n name: \"HKDF\",\n hash: \"SHA-256\",\n salt: new Uint8Array() as BufferSource,\n info: TEXT_ENCODER.encode(info) as BufferSource,\n },\n baseKey,\n byteLength * 8,\n );\n return new Uint8Array(bits);\n}\n\nfunction bytesToBase64url(bytes: Uint8Array): string {\n let str = \"\";\n for (let i = 0; i < bytes.length; i++) str += String.fromCharCode(bytes[i]);\n return btoa(str).replace(/=+$/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n}\n\n// Convert a 32-byte scalar into a valid P-256 keypair. Probability of drawing\n// 0 or a value >= curve order from HKDF output is negligible (~2^-128); noble\n// will throw if it ever happens.\nasync function importP256KeyPair(\n privBytes: Uint8Array,\n algo: EcKeyAlgorithm,\n privKeyUses: KeyUsage[],\n pubKeyUses: KeyUsage[],\n): Promise<CryptoKeyPair> {\n const pubBytes = p256.getPublicKey(privBytes, false); // 65-byte 0x04||X||Y\n const x = pubBytes.slice(1, 33);\n const y = pubBytes.slice(33, 65);\n const xB = bytesToBase64url(x);\n const yB = bytesToBase64url(y);\n const dB = bytesToBase64url(privBytes);\n\n const privateKey = await crypto.subtle.importKey(\n \"jwk\",\n { kty: \"EC\", crv: \"P-256\", d: dB, x: xB, y: yB, ext: true },\n algo,\n false,\n privKeyUses,\n );\n const publicKey = await crypto.subtle.importKey(\n \"jwk\",\n { kty: \"EC\", crv: \"P-256\", x: xB, y: yB, ext: true },\n algo,\n true,\n pubKeyUses,\n );\n return { privateKey, publicKey };\n}\n\nasync function importEcdsaKeyPair(privBytes: Uint8Array): Promise<CryptoKeyPair> {\n return importP256KeyPair(\n privBytes,\n { name: \"ECDSA\", namedCurve: \"P-256\" },\n [\"sign\"],\n [\"verify\"],\n );\n}\n\nasync function importEcdhKeyPair(privBytes: Uint8Array): Promise<CryptoKeyPair> {\n return importP256KeyPair(\n privBytes,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n [\"deriveKey\", \"deriveBits\"],\n [],\n );\n}\n\n/**\n * Derive a deterministic ZK identity from `(username, password)`.\n *\n * Same inputs always produce the same identity, on any device — that's\n * what makes federated login work without dragging encrypted state across\n * devices.\n */\nexport async function deriveIdentity(username: string, password: string): Promise<ZkIdentity> {\n if (typeof username !== \"string\" || username.length === 0) {\n throw new Error(\"deriveIdentity: `username` is required\");\n }\n if (typeof password !== \"string\" || password.length === 0) {\n throw new Error(\"deriveIdentity: `password` is required\");\n }\n\n const seed = await pbkdf2Bytes(password, \"muhkoo-zk-v1:\" + username, SCALAR_BYTES);\n\n const secretBytes = await hkdfExpand(seed, \"zk-secret\", SCALAR_BYTES);\n const saltBytes = await hkdfExpand(seed, \"zk-salt\", SCALAR_BYTES);\n const ecdsaPriv = await hkdfExpand(seed, \"ecdsa-priv\", SCALAR_BYTES);\n const ecdhPriv = await hkdfExpand(seed, \"ecdh-priv\", SCALAR_BYTES);\n\n const ecdsaKeyPair = await importEcdsaKeyPair(ecdsaPriv);\n const ecdhKeyPair = await importEcdhKeyPair(ecdhPriv);\n\n return {\n secretHex: toHex(secretBytes),\n saltHex: toHex(saltBytes),\n ecdsaKeyPair,\n ecdhKeyPair,\n };\n}\n","/**\n * Poseidon hash wrapper used by the ZK auth flow.\n *\n * Backed by `circomlibjs`'s `buildPoseidon`. Builder is lazy and cached\n * because the JS-side Babyjubjub field reps take ~100ms to construct, and\n * we'd rather not pay that on every page load.\n *\n * Returns hashes as decimal-string BigInts — same format snarkjs and the\n * `preimagePoK` circuit expect for inputs.\n *\n * Note: circomlibjs is `optionalDependencies` in connect's package.json.\n * Consumers that use the ZK auth flow (browser/server, not workers) need\n * it installed. The workers build does not import this module.\n */\n\nimport { buildPoseidon } from \"circomlibjs\";\n\ntype PoseidonF = { toString(val: unknown): string };\ntype PoseidonFn = ((inputs: Array<bigint | string | number>) => unknown) & { F: PoseidonF };\n\nlet _poseidon: PoseidonFn | null = null;\nlet _loadPromise: Promise<PoseidonFn> | null = null;\n\nasync function loadPoseidon(): Promise<PoseidonFn> {\n if (_poseidon) return _poseidon;\n if (_loadPromise) return _loadPromise;\n _loadPromise = (async () => {\n const fn = (await buildPoseidon()) as unknown as PoseidonFn;\n _poseidon = fn;\n return fn;\n })();\n return _loadPromise;\n}\n\n/**\n * Poseidon-hash `inputs` and return the result as a decimal-string BigInt.\n * Inputs are converted to BigInt — pass either bigints, numbers, or numeric\n * strings.\n */\nexport async function poseidonHash(\n inputs: Array<bigint | string | number>,\n): Promise<string> {\n const p = await loadPoseidon();\n const bigInputs = inputs.map((i) => {\n if (typeof i === \"bigint\") return i;\n if (typeof i === \"string\") return BigInt(i);\n return BigInt(i);\n });\n const hash = p(bigInputs);\n return p.F.toString(hash);\n}\n","/**\n * Groth16 proof generation for the `preimagePoK` circuit.\n *\n * The circuit proves knowledge of `(secret, salt, ecdsaPub)` such that\n * commitment = Poseidon(secret, salt, Poseidon(ecdsaPub))\n * while only revealing `(commitment, nonce, ecdsaPubHash)` as public signals.\n *\n * Circuit assets (wasm + zkey) are served by the accelerator worker. Their\n * URLs are a required argument of {@link generateAuthProof} — there is no\n * default. The web app constructs them relative to its configured worker\n * `baseUrl` so the SPA can target either the local wrangler dev or a deployed\n * worker depending on `VITE_WORKER_URL`.\n */\n\n// snarkjs has no TypeScript types in the npm package — the shared shim in\n// `types/snarkjs.d.ts` (already present for ZeroKnowledge.ts) covers the\n// `groth16.fullProve` call we need here too.\n//\n// Imported lazily (dynamic `import`) rather than at module top-level: snarkjs\n// is an externalized peer dependency that only the ZK login proof path needs.\n// Loading it eagerly would force every consumer of the SDK — and the test\n// runner — to have snarkjs resolvable just to construct a `Client`. The lazy\n// loader defers that cost until `generateAuthProof` actually runs.\nimport type { Groth16Proof } from \"../types/zk\";\nimport { poseidonHash } from \"./poseidon\";\n\ntype Snarkjs = {\n groth16: {\n fullProve: (\n input: unknown,\n wasm: string,\n zkey: string,\n ) => Promise<{ proof: unknown; publicSignals: string[] }>;\n };\n};\nlet _snarkjs: Snarkjs | null = null;\nasync function loadSnarkjs(): Promise<Snarkjs> {\n if (_snarkjs) return _snarkjs;\n _snarkjs = (await import(\"snarkjs\")) as unknown as Snarkjs;\n return _snarkjs;\n}\n\nexport type { Groth16Proof };\n\nexport interface CircuitUrls {\n /** preimagePoK.wasm — the circuit's witness generator. */\n wasmUrl: string;\n /** preimagePoK_0001.zkey — the proving key. */\n zkeyUrl: string;\n}\n\n/**\n * Canonical {@link CircuitUrls} for the `preimagePoK` login circuit, anchored\n * at a base URL where the accelerator serves the circuit assets out of\n * `circuits/build/`. The filenames here are fixed by the circom build output\n * (the witness generator lands inside a `preimagePoK_js/` directory); callers\n * shouldn't hard-code them. `Client` uses this to default its `circuits`\n * option, and `PersonalSpaceClient` consumers can pass `defaultCircuitUrls(baseUrl)`.\n */\nexport function defaultCircuitUrls(baseUrl: string): CircuitUrls {\n const base = baseUrl.replace(/\\/+$/, \"\");\n return {\n wasmUrl: `${base}/circuits/build/preimagePoK_js/preimagePoK.wasm`,\n zkeyUrl: `${base}/circuits/build/preimagePoK_0001.zkey`,\n };\n}\n\n/** BN254 scalar field modulus — the prime the circuit's signals live in. */\nconst FIELD_SIZE = 21888242871839275222246405745257275088548364400416034343698204186575808495617n;\n\n/**\n * Reduce any hex/decimal/byte input to a decimal-string field element in\n * `[0, FIELD_SIZE)`. snarkjs and the `preimagePoK` circuit both want decimal\n * strings; everything else gets normalized here.\n *\n * **Behavior is intentionally byte-for-byte compatible with the legacy\n * `accelerator/public/js/zk-snarkjs-client.js#toField`.** Diverging produces\n * different commitments than accounts registered via the legacy flow,\n * which locks those users out forever — the worker stores whatever\n * commitment the client sent at register time and compares it as a string\n * at login time.\n *\n * In particular: a 32+ char string of hex chars is always treated as hex,\n * even if every character happens to be 0-9 with no a-f letters. An\n * earlier version of this function gated the hex branch on \"has at least\n * one letter\" — that broke the digit-only-hex edge case (rare in practice,\n * but real). DO NOT add that letter check back.\n */\nexport function toField(value: string | bigint | number): string {\n let v: bigint;\n if (typeof value === \"bigint\") v = value;\n else if (typeof value === \"number\") v = BigInt(value);\n else if (value.startsWith(\"0x\")) v = BigInt(value);\n else if (/^[0-9a-fA-F]+$/.test(value) && value.length >= 32) {\n // Raw hex without prefix — secret, salt, ecdsaPub, nonce all hit this.\n v = BigInt(\"0x\" + value);\n } else if (/^[0-9]+$/.test(value)) v = BigInt(value);\n else {\n // Treat any other string as utf-8 bytes — matches the legacy client.\n const bytes = new TextEncoder().encode(value);\n let hex = \"\";\n for (const b of bytes) hex += b.toString(16).padStart(2, \"0\");\n v = BigInt(\"0x\" + hex);\n }\n v = v % FIELD_SIZE;\n if (v < 0n) v += FIELD_SIZE;\n return v.toString();\n}\n\n/**\n * Build the user's Poseidon commitment binding `(secret, salt, ecdsaPubHash)`.\n * Same formula the worker verifies against on register and authenticate.\n */\nexport async function buildCommitment(\n secretHex: string,\n saltHex: string,\n ecdsaPubHex: string,\n): Promise<string> {\n const secretField = toField(secretHex);\n const saltField = toField(saltHex);\n const ecdsaPubField = toField(ecdsaPubHex);\n const ecdsaPubHash = await poseidonHash([ecdsaPubField]);\n return await poseidonHash([secretField, saltField, ecdsaPubHash]);\n}\n\n/**\n * Generate a Groth16 proof for the `preimagePoK` circuit. Public signals end\n * up `[commitment, nonce, ecdsaPubHash]` — the worker checks the commitment\n * matches the stored one and the nonce matches the issued challenge nonce\n * reduced into the field.\n *\n * Throws if circuit URLs are unreachable or snarkjs decides the inputs are\n * malformed.\n */\nexport async function generateAuthProof(args: {\n secretHex: string;\n saltHex: string;\n ecdsaPubHex: string;\n nonceHex: string;\n /** Required — caller supplies URLs scoped to the worker they want to talk to. */\n circuits: CircuitUrls;\n}): Promise<{\n proof: Groth16Proof;\n publicSignals: string[];\n commitment: string;\n nonceField: string;\n ecdsaPubHash: string;\n}> {\n const secretField = toField(args.secretHex);\n const saltField = toField(args.saltHex);\n const ecdsaPubField = toField(args.ecdsaPubHex);\n const nonceField = toField(args.nonceHex);\n\n const ecdsaPubHash = await poseidonHash([ecdsaPubField]);\n const commitment = await poseidonHash([secretField, saltField, ecdsaPubHash]);\n\n const circuitInput: Record<string, string> = {\n // Public inputs (must appear in the same order the circuit declares).\n commitment,\n nonce: nonceField,\n ecdsaPubHash,\n // Private witnesses.\n secret: secretField,\n salt: saltField,\n ecdsaPub: ecdsaPubField,\n };\n\n const snarkjs = await loadSnarkjs();\n const { proof, publicSignals } = await snarkjs.groth16.fullProve(\n circuitInput,\n args.circuits.wasmUrl,\n args.circuits.zkeyUrl,\n );\n\n return {\n proof: proof as Groth16Proof,\n publicSignals,\n commitment,\n nonceField,\n ecdsaPubHash,\n };\n}\n","/**\n * Conversions between SubtleCrypto `CryptoKey`s and the wire formats the\n * accelerator's auth endpoints + `preimagePoK` circuit expect.\n *\n * Two outputs we need from an ECDSA `CryptoKey`:\n * - **base64 raw** — passed to `/api/auth/zk-register` as\n * `ecdsaPublicKey` / `ecdhPublicKey`. (Name is historical;\n * the legacy client called it `exportPublicKeyToBase58`\n * but actually used base64 — kept as base64.)\n * - **hex raw** — fed to the proof as `ecdsaPub` input; the circuit\n * reduces it into a field element.\n *\n * Both go through `crypto.subtle.exportKey(\"raw\", ...)` which yields the\n * uncompressed SEC1 form (`0x04 || X || Y`).\n */\n\nimport { toHex } from \"../utilities/bytes\";\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let str = \"\";\n for (let i = 0; i < bytes.length; i++) str += String.fromCharCode(bytes[i]);\n return btoa(str);\n}\n\n/** Raw uncompressed (`0x04 || X || Y`) public key bytes, as lowercase hex. */\nexport async function exportPublicKeyHex(publicKey: CryptoKey): Promise<string> {\n const buf = await crypto.subtle.exportKey(\"raw\", publicKey);\n return toHex(new Uint8Array(buf));\n}\n\n/** Raw uncompressed public key as base64 — wire format for the auth endpoints. */\nexport async function exportPublicKeyBase64(publicKey: CryptoKey): Promise<string> {\n const buf = await crypto.subtle.exportKey(\"raw\", publicKey);\n return bytesToBase64(new Uint8Array(buf));\n}\n\n/** Sign a UTF-8 `message` with an ECDSA private key. Returns base64. */\nexport async function signMessage(message: string, privateKey: CryptoKey): Promise<string> {\n const data = new TextEncoder().encode(message);\n const sig = await crypto.subtle.sign(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n privateKey,\n data,\n );\n return bytesToBase64(new Uint8Array(sig));\n}\n","/**\n * `HttpClient` — the one place the unified {@link Client} talks to the\n * accelerator over HTTP.\n *\n * Every request carries two independent credentials:\n * - the **app key** (`mk_…`) on `X-Muhkoo-Key` — resolves the app /\n * developer / env context the accelerator uses for routing + billing;\n * - the **user session token** on `X-Muhkoo-Session` (when a user is\n * logged in) — the accelerator validates it and injects a trusted\n * `X-Muhkoo-User-Context` downstream so per-user spaces can authorize\n * the request without a fresh Groth16 proof.\n *\n * `X-Muhkoo-Key` is used (rather than `Authorization: Bearer`) because it is\n * a non-forbidden header that skips the CORS preflight in browsers.\n *\n * The class exposes a header-injecting {@link fetch} that can be handed to\n * lower-level building blocks (`AuthClient`, `PersonalSpaceClient`) so they\n * keep owning their own wire shapes while still getting the credentials, plus\n * convenience JSON helpers (`get`/`post`/`del`) for code that talks to the\n * accelerator directly.\n */\n\nexport interface HttpClientOptions {\n /** Absolute URL of the accelerator worker (trailing slash optional). */\n baseUrl: string;\n /**\n * App / publishable key, e.g. `mk_test_pk_…`. Sent on every request as\n * `X-Muhkoo-Key` when present. Transitionally optional (auth + personal\n * storage still function without it), but the product direction is to\n * REQUIRE it — it attributes traffic for billing/metering and authorizes\n * shared-space (messaging) websockets.\n */\n apiKey?: string;\n /** Returns the current user session token, or `null` when logged out. */\n getSessionToken?: () => string | null;\n /** Custom fetch — defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n /**\n * Called when a token-gated request comes back `401` (stale/expired\n * session). Should attempt to silently re-establish a session and resolve\n * `true` if it succeeded (the request is then retried once with the fresh\n * token) or `false` if it couldn't (the `401` propagates as an\n * {@link HttpError}). Wired by {@link Client} to `auth.zk.recover()`.\n *\n * Only consulted by the JSON helpers (`get`/`post`/`del`); the raw\n * {@link fetch} passes 401s straight through so the auth wire calls that\n * power recovery itself can't recurse.\n */\n onUnauthorized?: () => Promise<boolean>;\n}\n\n/** Thrown for any non-2xx accelerator response. Carries the HTTP status. */\nexport class HttpError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly body?: unknown,\n ) {\n super(message);\n this.name = \"HttpError\";\n }\n}\n\nexport class HttpClient {\n readonly baseUrl: string;\n private readonly apiKey: string | null;\n private readonly getSessionToken: () => string | null;\n private readonly onUnauthorized: (() => Promise<boolean>) | null;\n private readonly fetchFn: typeof fetch;\n\n constructor(opts: HttpClientOptions) {\n if (!opts?.baseUrl) throw new Error(\"HttpClient: `baseUrl` is required\");\n this.baseUrl = opts.baseUrl.replace(/\\/+$/, \"\");\n this.apiKey = opts.apiKey ?? null;\n this.getSessionToken = opts.getSessionToken ?? (() => null);\n this.onUnauthorized = opts.onUnauthorized ?? null;\n\n const f = opts.fetch ?? globalThis.fetch;\n if (typeof f !== \"function\") {\n throw new Error(\n \"HttpClient: `globalThis.fetch` is unavailable; pass an explicit `fetch`.\",\n );\n }\n this.fetchFn = f.bind(globalThis);\n }\n\n /**\n * A `fetch`-compatible function that injects the app key + session token\n * headers. Hand this to `AuthClient` / `PersonalSpaceClient` so they pick\n * up credentials without knowing about them.\n */\n readonly fetch: typeof fetch = (input, init) => {\n const headers = new Headers(init?.headers);\n if (this.apiKey) headers.set(\"X-Muhkoo-Key\", this.apiKey);\n const token = this.getSessionToken();\n if (token) headers.set(\"X-Muhkoo-Session\", token);\n return this.fetchFn(input, { ...init, headers });\n };\n\n // -------------------------------------------------------------------------\n // JSON convenience helpers (path is relative to baseUrl)\n // -------------------------------------------------------------------------\n\n get<T = unknown>(path: string): Promise<T> {\n return this.request<T>(\"GET\", path);\n }\n\n post<T = unknown>(path: string, body?: unknown): Promise<T> {\n return this.request<T>(\"POST\", path, body);\n }\n\n patch<T = unknown>(path: string, body?: unknown): Promise<T> {\n return this.request<T>(\"PATCH\", path, body);\n }\n\n del<T = unknown>(path: string, body?: unknown): Promise<T> {\n return this.request<T>(\"DELETE\", path, body);\n }\n\n private async request<T>(method: string, path: string, body?: unknown, allowRecovery = true): Promise<T> {\n const url = path.startsWith(\"http\") ? path : `${this.baseUrl}${path.startsWith(\"/\") ? \"\" : \"/\"}${path}`;\n const init: RequestInit = { method };\n if (body !== undefined) {\n init.headers = { \"Content-Type\": \"application/json\" };\n init.body = JSON.stringify(body);\n }\n const res = await this.fetch(url, init);\n\n // Stale session: try to silently re-auth and replay the request once.\n // `allowRecovery` is cleared on the retry so a still-401 response (e.g.\n // recovery minted a token the endpoint still rejects) can't loop.\n if (res.status === 401 && allowRecovery && this.onUnauthorized && this.getSessionToken()) {\n const recovered = await this.onUnauthorized();\n if (recovered) {\n return this.request<T>(method, path, body, false);\n }\n }\n\n let parsed: unknown = null;\n try {\n parsed = await res.json();\n } catch {\n // Non-JSON body — leave null and fall through to status-only error.\n }\n if (!res.ok) {\n const msg =\n parsed && typeof parsed === \"object\" && \"error\" in (parsed as object)\n ? String((parsed as { error: unknown }).error)\n : `${res.status} ${res.statusText}`;\n throw new HttpError(msg, res.status, parsed);\n }\n return parsed as T;\n }\n}\n\nexport default HttpClient;\n","/**\n * `SessionState` — the in-memory source of truth for \"who is signed in\" on a\n * {@link Client}.\n *\n * It separates two concerns that have different lifetimes and security\n * properties:\n *\n * - **session** (`{ token, username, commitment }`) — proves the user is\n * authenticated to the accelerator. Cheap to persist (the token is an\n * opaque server-side handle) and enough to authorize token-gated REST\n * calls. Restored from a {@link SessionStore} across reloads.\n *\n * - **identity** ({@link ZkIdentity}) — the derived secret + keypairs. Lets\n * the client *prove* ownership (ZK), derive at-rest encryption keys, and\n * run the messaging ratchet. It is derived from `(username, password)` and\n * is deliberately **never** persisted by default — a restored session has\n * a valid token but no identity until the user re-derives it\n * (`client.auth.zk.unlock(password)`).\n *\n * This split is what makes `restore()` (authenticated, can't decrypt) and\n * `unlock()` (now can decrypt) two distinct, intentional states.\n */\n\nimport type { ZkIdentity } from \"../auth/identity\";\n\n/** The persistable part of a session — safe-ish to keep across reloads. */\nexport interface StoredSession {\n token: string;\n username: string;\n /** Decimal-string Poseidon commitment — the user's stable id. */\n commitment: string;\n}\n\n/**\n * Pluggable persistence for the session token. Browser apps typically back\n * this with `localStorage`; the default is in-memory (lost on reload).\n *\n * Identity material is intentionally not part of this interface — see the\n * class docs. Apps that want federated session restore without re-prompting\n * for a password can persist it themselves and call `unlock()` on boot.\n */\nexport interface SessionStore {\n load(): StoredSession | null | Promise<StoredSession | null>;\n save(session: StoredSession): void | Promise<void>;\n clear(): void | Promise<void>;\n}\n\n/** Default in-memory store — holds the session for the process lifetime only. */\nexport class MemorySessionStore implements SessionStore {\n private current: StoredSession | null = null;\n load(): StoredSession | null {\n return this.current;\n }\n save(session: StoredSession): void {\n this.current = session;\n }\n clear(): void {\n this.current = null;\n }\n}\n\n/**\n * A {@link SessionStore} backed by the browser's `localStorage`, so a session\n * survives page reloads. This is the store most browser apps want — pass it to\n * `new Client({ sessionStore: new LocalStorageSessionStore() })`.\n *\n * Browser-only: construction throws if `localStorage` is unavailable (Node,\n * Workers, or SSR before hydration) — use {@link MemorySessionStore} or a\n * custom store there. Keys are namespaced under `keyPrefix` so multiple apps\n * on the same origin don't collide.\n */\nexport class LocalStorageSessionStore implements SessionStore {\n private readonly tokenKey: string;\n private readonly usernameKey: string;\n private readonly commitmentKey: string;\n\n constructor(keyPrefix = \"muhkoo.session.\") {\n if (typeof localStorage === \"undefined\") {\n throw new Error(\n \"LocalStorageSessionStore requires a browser environment with localStorage; \" +\n \"use MemorySessionStore (or a custom SessionStore) on the server.\",\n );\n }\n this.tokenKey = `${keyPrefix}token`;\n this.usernameKey = `${keyPrefix}username`;\n this.commitmentKey = `${keyPrefix}commitment`;\n }\n\n load(): StoredSession | null {\n const token = localStorage.getItem(this.tokenKey);\n const username = localStorage.getItem(this.usernameKey);\n const commitment = localStorage.getItem(this.commitmentKey);\n if (!token || !username || !commitment) return null;\n return { token, username, commitment };\n }\n\n save(session: StoredSession): void {\n localStorage.setItem(this.tokenKey, session.token);\n localStorage.setItem(this.usernameKey, session.username);\n localStorage.setItem(this.commitmentKey, session.commitment);\n }\n\n clear(): void {\n localStorage.removeItem(this.tokenKey);\n localStorage.removeItem(this.usernameKey);\n localStorage.removeItem(this.commitmentKey);\n }\n}\n\n/**\n * The {@link SessionStore} a {@link Client} uses when none is supplied: a\n * {@link LocalStorageSessionStore} in the browser (so sessions survive\n * reloads), falling back to {@link MemorySessionStore} anywhere `localStorage`\n * is unavailable or unusable (Node, Workers, SSR, or private-mode browsers\n * that throw on access). Pass an explicit store to override.\n */\nexport function defaultSessionStore(keyPrefix?: string): SessionStore {\n try {\n // Touch the API, not just `typeof`: some environments expose\n // `localStorage` but throw on access (Safari private mode, sandboxed\n // iframes). LocalStorageSessionStore's constructor only checks for\n // existence, so probe a real read here and fall back on any throw.\n if (typeof localStorage !== \"undefined\") {\n localStorage.getItem(\"muhkoo.__probe__\");\n return new LocalStorageSessionStore(keyPrefix);\n }\n } catch {\n // fall through to in-memory\n }\n return new MemorySessionStore();\n}\n\nexport class SessionState {\n private session: StoredSession | null = null;\n private _identity: ZkIdentity | null = null;\n private readonly store: SessionStore;\n\n constructor(store?: SessionStore) {\n this.store = store ?? new MemorySessionStore();\n }\n\n /** True once a token-bearing session exists (regardless of identity). */\n get isAuthenticated(): boolean {\n return this.session !== null;\n }\n\n /** True once identity material is available (login or unlock happened). */\n get isUnlocked(): boolean {\n return this._identity !== null;\n }\n\n get token(): string | null {\n return this.session?.token ?? null;\n }\n\n get username(): string | null {\n return this.session?.username ?? null;\n }\n\n get commitment(): string | null {\n return this.session?.commitment ?? null;\n }\n\n get identity(): ZkIdentity | null {\n return this._identity;\n }\n\n /** Identity material, throwing a clear error when the client is locked. */\n requireIdentity(): ZkIdentity {\n if (!this._identity) {\n throw new Error(\n \"This operation needs the user's identity. Call `client.auth.zk.login()` \" +\n \"or `client.auth.zk.unlock(password)` first.\",\n );\n }\n return this._identity;\n }\n\n /** Persist + hold a freshly authenticated session. */\n async setSession(session: StoredSession): Promise<void> {\n this.session = session;\n await this.store.save(session);\n }\n\n /** Attach derived identity material to the current session. */\n setIdentity(identity: ZkIdentity): void {\n this._identity = identity;\n }\n\n /** Load a persisted session (used by `restore()`); identity stays null. */\n async loadPersisted(): Promise<StoredSession | null> {\n const loaded = await this.store.load();\n if (loaded) this.session = loaded;\n return loaded;\n }\n\n /** Drop all session + identity state and clear persistence. */\n async clear(): Promise<void> {\n this.session = null;\n this._identity = null;\n await this.store.clear();\n }\n}\n\nexport default SessionState;\n","/**\n * `client.auth` — user authentication, exposed today through the `zk`\n * sub-namespace (`client.auth.zk.login(...)`). Leaving room under `auth` for\n * other strategies later (e.g. `auth.oauth`) without reshaping the surface.\n *\n * `ZkAuth` absorbs the full ZK register/login dance that used to live in the\n * web app's `AuthContext`:\n *\n * register: derive identity → commitment → POST /api/auth/zk-register\n * login: derive identity → challenge → Groth16 proof → sign →\n * POST /api/auth/zk-authenticate → session token\n *\n * The derived {@link ZkIdentity} (secret + ECDSA/ECDH keypairs) is held in\n * {@link SessionState} so the storage + message namespaces can reuse it for\n * at-rest encryption and the messaging ratchet without re-deriving.\n */\n\nimport { AuthClient } from \"../../auth/AuthClient\";\nimport { deriveIdentity, type ZkIdentity } from \"../../auth/identity\";\nimport { generateAuthProof, buildCommitment, type CircuitUrls } from \"../../auth/proof\";\nimport { exportPublicKeyHex, exportPublicKeyBase64, signMessage } from \"../../auth/keys\";\nimport type { SessionState } from \"../Session\";\n\n/** What the auth methods resolve to — the stable, non-secret user facts. */\nexport interface AuthUser {\n username: string;\n /** Decimal-string Poseidon commitment — the user's stable id. */\n commitment: string;\n}\n\nexport interface RegisterParams {\n username: string;\n password: string;\n email?: string | null;\n /** Sign in immediately after registering (default: true). */\n login?: boolean;\n}\n\nexport interface LoginOptions {\n /** Ask the accelerator for a long-lived (30d) session (default: false). */\n rememberMe?: boolean;\n}\n\nexport interface ZkAuthDeps {\n auth: AuthClient;\n circuits: CircuitUrls;\n session: SessionState;\n}\n\n/**\n * ZK identity auth. One instance per {@link Client}; reads/writes the shared\n * {@link SessionState}.\n */\nexport class ZkAuth {\n constructor(private readonly deps: ZkAuthDeps) {}\n\n /**\n * Register a new user, then (by default) sign them in. The identity is\n * derived deterministically from `(username, password)` — the same inputs\n * reproduce it on any device, so there's no key material to ship around.\n */\n async register(params: RegisterParams): Promise<AuthUser> {\n const { username, password, email = null, login = true } = params;\n const identity = await deriveIdentity(username, password);\n const commitment = await this.commitmentFor(identity);\n\n await this.deps.auth.register({\n username,\n commitment,\n ecdhPublicKey: await exportPublicKeyBase64(identity.ecdhKeyPair.publicKey),\n ecdsaPublicKey: await exportPublicKeyBase64(identity.ecdsaKeyPair.publicKey),\n email,\n });\n\n if (login) {\n return this.login(username, password);\n }\n return { username, commitment };\n }\n\n /**\n * Sign in: re-derive the identity, prove knowledge of it against a fresh\n * server challenge, and trade the proof for a session token. On success\n * both the session and the identity are stored on the client.\n */\n async login(username: string, password: string, opts: LoginOptions = {}): Promise<AuthUser> {\n const identity = await deriveIdentity(username, password);\n return this.proveAndStore(username, identity, opts);\n }\n\n /**\n * Silently re-authenticate the current user without prompting for a\n * password. Only possible while the client is **unlocked** — i.e. the\n * derived {@link ZkIdentity} (secret + keypairs) is still in memory from a\n * prior `login()`/`unlock()`. Re-runs the full challenge→proof→authenticate\n * dance with that in-memory identity and swaps in the fresh token.\n *\n * Returns `true` if a new session was minted, `false` if recovery isn't\n * possible (no active user, or locked — the identity was never derived or\n * was lost on reload). A `false` result is the app's cue to send the user\n * back to the login screen.\n *\n * Used automatically by the {@link Client} when a token-gated request comes\n * back `401` (stale/expired token), so transient session expiry self-heals\n * instead of surfacing errors mid-session.\n */\n async recover(): Promise<boolean> {\n const username = this.deps.session.username;\n const identity = this.deps.session.identity;\n if (!username || !identity) return false;\n try {\n await this.proveAndStore(username, identity, {});\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Shared sign-in core: prove knowledge of `identity` against a fresh\n * challenge and persist the resulting session + identity. Used by both\n * `login()` (identity derived from a password) and `recover()` (identity\n * already in memory).\n */\n private async proveAndStore(\n username: string,\n identity: ZkIdentity,\n opts: LoginOptions,\n ): Promise<AuthUser> {\n const ecdsaPubHex = await exportPublicKeyHex(identity.ecdsaKeyPair.publicKey);\n\n const challenge = await this.deps.auth.getChallenge(username);\n\n const { proof, publicSignals, commitment } = await generateAuthProof({\n secretHex: identity.secretHex,\n saltHex: identity.saltHex,\n ecdsaPubHex,\n nonceHex: challenge.nonce,\n circuits: this.deps.circuits,\n });\n\n const signature = await signMessage(JSON.stringify(proof), identity.ecdsaKeyPair.privateKey);\n\n const result = await this.deps.auth.authenticate({\n challengeId: challenge.challengeId,\n proof: {\n commitment,\n // The accelerator expects the original hex nonce here, not the\n // field-reduced version fed into the circuit.\n nonce: challenge.nonce,\n response: { proof, publicSignals },\n signature,\n },\n rememberMe: opts.rememberMe,\n });\n\n await this.deps.session.setSession({\n token: result.token,\n username: result.username,\n commitment,\n });\n this.deps.session.setIdentity(identity);\n\n return { username: result.username, commitment };\n }\n\n /**\n * Restore a persisted session on boot. Validates the stored token with the\n * accelerator; returns the user when valid, or `null` (and clears the\n * stale session) otherwise. Identity stays locked — call {@link unlock}\n * to re-enable encryption/messaging without a full re-login.\n */\n async restore(): Promise<AuthUser | null> {\n const stored = await this.deps.session.loadPersisted();\n if (!stored) return null;\n try {\n await this.deps.auth.verify(stored.token);\n return { username: stored.username, commitment: stored.commitment };\n } catch {\n await this.deps.session.clear();\n return null;\n }\n }\n\n /**\n * Re-derive identity material for an already-authenticated (restored)\n * session, so the client can decrypt storage and run the ratchet. Verifies\n * the password by checking the derived commitment matches the session's.\n */\n async unlock(password: string): Promise<void> {\n const username = this.deps.session.username;\n const expected = this.deps.session.commitment;\n if (!username || !expected) {\n throw new Error(\"ZkAuth.unlock: no active session to unlock — sign in first.\");\n }\n const identity = await deriveIdentity(username, password);\n const commitment = await this.commitmentFor(identity);\n if (commitment !== expected) {\n throw new Error(\"ZkAuth.unlock: incorrect password (commitment mismatch).\");\n }\n this.deps.session.setIdentity(identity);\n }\n\n /** Sign out: clears the session, identity, and persisted token. */\n async logout(): Promise<void> {\n await this.deps.session.clear();\n }\n\n /** The signed-in user, or `null`. Synchronous read of current state. */\n get user(): AuthUser | null {\n const username = this.deps.session.username;\n const commitment = this.deps.session.commitment;\n return username && commitment ? { username, commitment } : null;\n }\n\n /**\n * The derived identity material for the current session, or `null` when\n * locked. Exposed so apps that still drive lower-level primitives (e.g. a\n * chat ratchet keyed off the same identity) can reuse it without\n * re-deriving from the password.\n */\n get identity(): ZkIdentity | null {\n return this.deps.session.identity;\n }\n\n /** The current session token, or `null` when signed out. */\n get token(): string | null {\n return this.deps.session.token;\n }\n\n // -------------------------------------------------------------------------\n\n /** Poseidon commitment for an identity — the value the server stores. */\n private async commitmentFor(identity: ZkIdentity): Promise<string> {\n // generateAuthProof recomputes this internally, but registration needs\n // it before any challenge exists, so derive it directly here.\n const ecdsaPubHex = await exportPublicKeyHex(identity.ecdsaKeyPair.publicKey);\n return buildCommitment(identity.secretHex, identity.saltHex, ecdsaPubHex);\n }\n}\n\n/** `client.auth` — the auth namespace. Strategies hang off here. */\nexport class AuthNamespace {\n readonly zk: ZkAuth;\n constructor(deps: ZkAuthDeps) {\n this.zk = new ZkAuth(deps);\n }\n\n /** Convenience pass-through: the currently signed-in user, or `null`. */\n get user(): AuthUser | null {\n return this.zk.user;\n }\n}\n\nexport default AuthNamespace;\n","/**\n * `StorageCipher` — transparent at-rest encryption for `client.storage`.\n *\n * Derives a single AES-256-GCM key from the user's ZK identity (HKDF over the\n * secret, salted with the identity salt) and uses it to seal/open the JSON\n * values the storage namespace persists. The accelerator only ever sees the\n * {@link EncryptedEnvelope} — opaque ciphertext + a per-value random IV.\n *\n * The key is deterministic in the identity, so the same `(username, password)`\n * decrypts the same data on any device — no key material is shipped or stored.\n */\n\nimport {\n deriveBitsHkdf,\n encryptAesGcm,\n decryptAesGcm,\n randomBytes,\n AES_GCM_IV_BYTES,\n AES_GCM_KEY_BYTES,\n} from \"./primitives\";\nimport { fromHex, toBase64, fromBase64, utf8Encode, utf8Decode } from \"../utilities/bytes\";\n\n/** The on-the-wire shape of an encrypted value. `_enc` tags the scheme. */\nexport interface EncryptedEnvelope {\n _enc: \"a256gcm\";\n /** Base64 random 12-byte GCM IV. */\n iv: string;\n /** Base64 ciphertext with the appended 16-byte GCM tag. */\n ct: string;\n}\n\n/** HKDF label binding the derived key to the storage-at-rest purpose. */\nconst STORAGE_KEY_INFO = \"muhkoo-storage-v1\";\n\nexport class StorageCipher {\n /** Lazily-derived AES key, memoized for the cipher's lifetime. */\n private readonly keyPromise: Promise<Uint8Array>;\n\n constructor(secretHex: string, saltHex: string) {\n this.keyPromise = deriveBitsHkdf(\n fromHex(secretHex),\n STORAGE_KEY_INFO,\n AES_GCM_KEY_BYTES,\n fromHex(saltHex),\n );\n }\n\n /** Seal a JSON-serializable value into an {@link EncryptedEnvelope}. */\n async encrypt(value: unknown): Promise<EncryptedEnvelope> {\n const key = await this.keyPromise;\n const iv = randomBytes(AES_GCM_IV_BYTES);\n const plaintext = utf8Encode(JSON.stringify(value));\n const ciphertext = await encryptAesGcm(key, iv, plaintext);\n return { _enc: \"a256gcm\", iv: toBase64(iv), ct: toBase64(ciphertext) };\n }\n\n /** Open an {@link EncryptedEnvelope} back into the original value. */\n async decrypt<T = unknown>(envelope: EncryptedEnvelope): Promise<T> {\n const key = await this.keyPromise;\n const iv = fromBase64(envelope.iv);\n const ciphertext = fromBase64(envelope.ct);\n const plaintext = await decryptAesGcm(key, iv, ciphertext);\n return JSON.parse(utf8Decode(plaintext)) as T;\n }\n\n /** Type guard — is `v` an encrypted envelope (vs. a plaintext value)? */\n static isEnvelope(v: unknown): v is EncryptedEnvelope {\n return (\n !!v &&\n typeof v === \"object\" &&\n (v as { _enc?: unknown })._enc === \"a256gcm\" &&\n typeof (v as { iv?: unknown }).iv === \"string\" &&\n typeof (v as { ct?: unknown }).ct === \"string\"\n );\n }\n}\n\nexport default StorageCipher;\n","/**\n * Pure WebSocket transport — owns the socket lifecycle and nothing else.\n *\n * Hands raw frame strings up (via the `MESSAGE` event) and accepts raw frame\n * strings down (via `send`). Anything frame-shape, encryption, or serialization\n * related belongs in the layer above (e.g. `Network` for client↔server\n * encrypted pipes, `BroadcastChannel` for multi-peer E2E rooms).\n *\n * Responsibilities:\n * - Open / close the WebSocket\n * - Auto-reconnect with linear backoff after an unexpected close\n * - Buffer outbound frames while disconnected (capped queue)\n * - Emit lifecycle events (CONNECTED / DISCONNECTED / RECONNECTING / ERROR)\n * plus raw inbound MESSAGE events\n */\n\nimport { EventCore, EventCoreEvents } from \"../events\";\n\n/** Monotonic source of unique transport ids when a caller doesn't supply one. */\nlet __wsInstanceSeq = 0;\n\nexport interface WSTransportOptions {\n /** WebSocket URL, e.g. `ws://localhost:8787/foo`. */\n url: string;\n /**\n * Optional async provider for a FRESH connection URL, called before each\n * RECONNECT. Use it when the URL carries a single-use/expiring credential\n * (e.g. a one-time WS upgrade ticket): on reconnect the baked-in ticket is\n * already consumed/expired, so without this the reconnect is rejected and the\n * transport burns through its attempts. The initial connect uses `url` as-is.\n */\n urlProvider?: () => string | Promise<string>;\n /**\n * Stable identifier for this connection (a channel / space / personal-space\n * id). Lifecycle + MESSAGE events are namespaced by it on the shared\n * `EventCore` bus so concurrent transports (chat room A, room B, the storage\n * feed, …) never receive each other's frames. Optional — a unique id is\n * generated when omitted; pass a semantic one for clearer debugging.\n */\n id?: string;\n /** Reconnect automatically after unexpected disconnect (default `true`). */\n autoReconnect?: boolean;\n /** Delay between reconnect attempts in ms (default `3000`). */\n reconnectDelay?: number;\n /** Cap on reconnect attempts (default `5`; `0` means unlimited). */\n maxReconnectAttempts?: number;\n /**\n * Max outbound frames buffered while disconnected. Sending past this caps\n * throws synchronously. Default `100`.\n */\n maxQueueSize?: number;\n /**\n * Heartbeat interval in ms. While connected, a `pingFrame` is sent every\n * interval to keep the socket warm (long-lived WebSockets get dropped by CF\n * / intermediaries when idle) and to detect a silently-dead connection.\n * Default `30000`. Set `0` to disable the heartbeat entirely.\n */\n heartbeatInterval?: number;\n /**\n * How long (ms) to wait for a `pongFrame` after sending a ping before\n * treating the connection as dead and forcing a reconnect. Should be well\n * under `heartbeatInterval`. Default `10000`.\n */\n heartbeatTimeout?: number;\n /** Outbound keep-alive frame. Default `\"ping\"`. */\n pingFrame?: string;\n /**\n * Inbound keep-alive ack. Matching frames are swallowed (never surfaced as a\n * `MESSAGE`) and reset the liveness timer. Must match the server's\n * auto-response. Default `\"pong\"`.\n */\n pongFrame?: string;\n}\n\nexport class WSTransport extends EventCore {\n /**\n * Per-instance event scope. `EventCore` is a process-global static emitter,\n * so without namespacing every WSTransport would hear every other one's\n * frames. We prefix each event with this transport's `id` and expose\n * `on`/`off`/`emit` that scope transparently — callers still use the plain\n * `EventCoreEvents` enum and only ever see their own connection's events.\n */\n readonly id: string;\n\n readonly emit = (event: EventCoreEvents, data: unknown): void => {\n EventCore.emit(this.scopedEvent(event), data);\n };\n readonly on = (event: EventCoreEvents, handler: EventListener | CallableFunction): void => {\n EventCore.on(this.scopedEvent(event), handler);\n };\n readonly off = (event: EventCoreEvents, handler: EventListener | CallableFunction): void => {\n EventCore.off(this.scopedEvent(event), handler);\n };\n\n private scopedEvent(event: EventCoreEvents): EventCoreEvents {\n return `${this.id}:${event}` as EventCoreEvents;\n }\n\n private url: string;\n private urlProvider?: () => string | Promise<string>;\n private socket: WebSocket | null = null;\n private _isConnected = false;\n private _isConnecting = false;\n\n // Reconnect state\n private autoReconnect: boolean;\n private reconnectDelay: number;\n private maxReconnectAttempts: number;\n private reconnectAttempts = 0;\n private reconnectTimeout: ReturnType<typeof setTimeout> | null = null;\n\n // Outbound queue (raw frame strings — already serialized by caller)\n private outboundQueue: string[] = [];\n private maxQueueSize: number;\n\n // Heartbeat / liveness state\n private heartbeatInterval: number;\n private heartbeatTimeout: number;\n private pingFrame: string;\n private pongFrame: string;\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n private pongTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(opts: WSTransportOptions) {\n super();\n if (!opts || !opts.url) {\n throw new Error(\"WSTransport: `url` is required\");\n }\n this.url = opts.url;\n this.urlProvider = opts.urlProvider;\n this.id = opts.id ?? `ws${++__wsInstanceSeq}`;\n this.autoReconnect = opts.autoReconnect ?? true;\n this.reconnectDelay = opts.reconnectDelay ?? 3000;\n this.maxReconnectAttempts = opts.maxReconnectAttempts ?? 5;\n this.maxQueueSize = opts.maxQueueSize ?? 100;\n this.heartbeatInterval = opts.heartbeatInterval ?? 30000;\n this.heartbeatTimeout = opts.heartbeatTimeout ?? 10000;\n this.pingFrame = opts.pingFrame ?? \"ping\";\n this.pongFrame = opts.pongFrame ?? \"pong\";\n }\n\n /** Open the socket. Resolves when CONNECTED fires. Rejects on first error. */\n async connect(): Promise<void> {\n if (this._isConnected || this._isConnecting) {\n throw new Error(\"WSTransport: already connected or connecting\");\n }\n this._isConnecting = true;\n\n // On a RECONNECT, refresh the URL (the baked-in single-use ticket is spent).\n // The first connect uses `url` as-is. If the provider throws (e.g. can't\n // mint a ticket), surface it and let scheduleReconnect retry.\n if (this.urlProvider && this.reconnectAttempts > 0) {\n try {\n this.url = await this.urlProvider();\n } catch (err) {\n this._isConnecting = false;\n throw err;\n }\n }\n\n return new Promise<void>((resolve, reject) => {\n try {\n const socket = new WebSocket(this.url);\n this.socket = socket;\n\n socket.onopen = () => {\n this._isConnected = true;\n this._isConnecting = false;\n this.reconnectAttempts = 0;\n this.emit(EventCoreEvents.CONNECTED, undefined);\n this.flushQueue();\n this.startHeartbeat();\n resolve();\n };\n\n socket.onmessage = (event: MessageEvent) => {\n // Heartbeat ack — swallow it (don't surface as a MESSAGE) and clear\n // the liveness deadline. The layer above never sees keep-alive frames.\n if (event.data === this.pongFrame) {\n if (this.pongTimer) {\n clearTimeout(this.pongTimer);\n this.pongTimer = null;\n }\n return;\n }\n // Raw inbound frame — layer above is responsible for parsing.\n this.emit(EventCoreEvents.MESSAGE, event.data);\n };\n\n socket.onerror = (err) => {\n this.emit(EventCoreEvents.ERROR, err);\n if (this._isConnecting) {\n this._isConnecting = false;\n reject(err);\n }\n };\n\n socket.onclose = () => {\n const wasConnected = this._isConnected;\n this._isConnected = false;\n this._isConnecting = false;\n this.stopHeartbeat();\n this.emit(EventCoreEvents.DISCONNECTED, undefined);\n if (this.autoReconnect && wasConnected) {\n this.scheduleReconnect();\n }\n };\n } catch (err) {\n this._isConnecting = false;\n reject(err);\n }\n });\n }\n\n /** Close the socket and stop reconnecting. */\n disconnect(): void {\n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n }\n this.stopHeartbeat();\n this.autoReconnect = false;\n if (this.socket) {\n try { this.socket.close(); } catch { /* ignore */ }\n this.socket = null;\n }\n this._isConnected = false;\n this._isConnecting = false;\n }\n\n /**\n * Send a raw frame. If currently disconnected, the frame is queued and sent\n * after the next successful reconnect (up to `maxQueueSize`).\n */\n send(frame: string): void {\n if (this._isConnected && this.socket) {\n this.socket.send(frame);\n return;\n }\n if (this.outboundQueue.length >= this.maxQueueSize) {\n throw new Error(\n `WSTransport: outbound queue full (${this.maxQueueSize}); drop or wait for reconnect`,\n );\n }\n this.outboundQueue.push(frame);\n }\n\n isConnected(): boolean { return this._isConnected; }\n isConnecting(): boolean { return this._isConnecting; }\n queuedFrames(): number { return this.outboundQueue.length; }\n reconnectAttemptCount(): number { return this.reconnectAttempts; }\n\n // -- internals -------------------------------------------------------------\n\n /** Begin the keep-alive loop (no-op when disabled). */\n private startHeartbeat(): void {\n if (this.heartbeatInterval <= 0) return;\n this.stopHeartbeat();\n this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.heartbeatInterval);\n }\n\n /** Stop the keep-alive loop and clear any pending liveness deadline. */\n private stopHeartbeat(): void {\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n if (this.pongTimer) {\n clearTimeout(this.pongTimer);\n this.pongTimer = null;\n }\n }\n\n /**\n * Send one ping and arm a liveness deadline. If no `pongFrame` arrives before\n * `heartbeatTimeout`, the connection is considered dead and we force a\n * reconnect — this is what catches a silently-dropped TCP connection that\n * never fired `onclose` (the failure mode that \"loses connection with the\n * Accelerator\" on long sessions).\n */\n private sendHeartbeat(): void {\n if (!this._isConnected || !this.socket) return;\n try {\n this.socket.send(this.pingFrame);\n } catch {\n this.forceReconnect();\n return;\n }\n // A still-pending deadline means the previous pong never came back.\n if (this.pongTimer) return;\n this.pongTimer = setTimeout(() => {\n this.pongTimer = null;\n this.forceReconnect();\n }, this.heartbeatTimeout);\n }\n\n /**\n * Tear down a connection we believe is dead and kick off reconnect, without\n * waiting on the OS/browser to eventually fire `onclose` (which a half-open\n * socket may never do). We detach the handlers first so the normal close path\n * can't double-fire the reconnect.\n */\n private forceReconnect(): void {\n this.stopHeartbeat();\n const sock = this.socket;\n const wasConnected = this._isConnected;\n this.socket = null;\n this._isConnected = false;\n this._isConnecting = false;\n if (sock) {\n sock.onopen = null;\n sock.onmessage = null;\n sock.onerror = null;\n sock.onclose = null;\n try { sock.close(); } catch { /* already gone */ }\n }\n this.emit(EventCoreEvents.ERROR, new Error(\"WSTransport: heartbeat timeout\"));\n this.emit(EventCoreEvents.DISCONNECTED, undefined);\n if (this.autoReconnect && wasConnected) {\n this.scheduleReconnect();\n }\n }\n\n private scheduleReconnect(): void {\n if (\n this.maxReconnectAttempts > 0 &&\n this.reconnectAttempts >= this.maxReconnectAttempts\n ) {\n this.emit(\n EventCoreEvents.ERROR,\n new Error(\"WSTransport: max reconnect attempts reached\"),\n );\n return;\n }\n this.reconnectAttempts++;\n this.emit(EventCoreEvents.RECONNECTING, { attempt: this.reconnectAttempts });\n this.reconnectTimeout = setTimeout(async () => {\n try {\n await this.connect();\n } catch {\n // A failed reconnect never opened the socket, so its `onclose` won't\n // re-schedule (that path is guarded by `wasConnected`). Re-schedule here\n // so we keep retrying (with a fresh ticket each time) until we succeed\n // or hit the attempt cap.\n if (this.autoReconnect) this.scheduleReconnect();\n }\n }, this.reconnectDelay);\n }\n\n private flushQueue(): void {\n if (this.outboundQueue.length === 0 || !this.socket) return;\n const pending = this.outboundQueue;\n this.outboundQueue = [];\n for (const frame of pending) {\n try {\n this.socket.send(frame);\n } catch {\n // re-queue if a flush fails\n this.outboundQueue.push(frame);\n }\n }\n }\n}\n\nexport default WSTransport;\n","/**\n * `client.kv` — per-user key/value storage backed by the accelerator's personal\n * space.\n *\n * await client.kv.set('todos', id, { title, completed })\n * const todo = await client.kv.get('todos', id)\n * const ids = await client.kv.list('todos')\n * await client.kv.delete('todos', id)\n * const off = client.kv.on('change', e => …) // realtime, cross-device\n *\n * A *collection* is a key namespace within the user's space; the stored key is\n * `${collection}/${id}`. Operations are authorized by the user's session token\n * (stamped on every request by {@link HttpClient}) — no per-op Groth16 proof.\n *\n * Values are encrypted at rest by default ({@link StorageCipher}, an AES-GCM\n * key derived from the ZK identity); pass `{ encrypt: false }` to store\n * plaintext. The realtime feed rides the personal space's websocket over a\n * {@link WSTransport} (heartbeat keep-alive + auto-reconnect, event-namespaced\n * so it doesn't cross wires with chat/space transports).\n *\n * For **files** (blobs), use `client.storage` instead — `client.kv` is for\n * small structured values. `query()` is intentionally deferred.\n */\n\nimport type { HttpClient } from \"../HttpClient\";\nimport type { SessionState } from \"../Session\";\nimport type { ZkIdentity } from \"../../auth/identity\";\nimport { StorageCipher } from \"../../crypto/StorageCipher\";\nimport { WSTransport } from \"../../transport/WSTransport\";\nimport { EventCoreEvents } from \"../../events\";\n\nexport interface KvNamespaceDeps {\n http: HttpClient;\n session: SessionState;\n /** WebSocket base (ws/wss) for the change feed; derived from baseUrl. */\n wsBaseUrl: string;\n}\n\nexport interface SetOptions {\n /** Encrypt the value at rest (default: true). */\n encrypt?: boolean;\n}\n\nexport interface StorageChangeEvent<T = unknown> {\n collection: string;\n id: string;\n type: \"set\" | \"delete\";\n /** The decrypted value for `set`; `null` for `delete`. */\n data: T | null;\n}\n\n/** Raw change frame pushed by `PersonalSpaceDO`'s websocket. */\ninterface ChangeFrame {\n _t: \"change\";\n key: string;\n op: \"set\" | \"delete\";\n value?: unknown;\n}\n\nexport class KvNamespace {\n private cipher: StorageCipher | null = null;\n private cipherIdentity: ZkIdentity | null = null;\n\n constructor(private readonly deps: KvNamespaceDeps) {}\n\n /** Store `value` under `collection`/`id` (encrypted at rest by default). */\n async set<T = unknown>(collection: string, id: string, value: T, opts?: SetOptions): Promise<void> {\n const encrypt = opts?.encrypt !== false;\n const stored = encrypt ? await this.getCipher().encrypt(value) : value;\n await this.deps.http.post(this.kvPath(collection, id), { value: stored });\n }\n\n /** Fetch the value at `collection`/`id`, or `null` if absent. */\n async get<T = unknown>(collection: string, id: string): Promise<T | null> {\n const res = await this.deps.http.post<{ value: unknown }>(\n `${this.kvPath(collection, id)}/get`,\n {},\n );\n return this.decode<T>(res.value);\n }\n\n /** Delete `collection`/`id`. Returns whether the key existed. */\n async delete(collection: string, id: string): Promise<boolean> {\n const res = await this.deps.http.del<{ ok: boolean; existed: boolean }>(\n this.kvPath(collection, id),\n {},\n );\n return Boolean(res.existed);\n }\n\n /** List the ids present in `collection`. */\n async list(collection: string): Promise<string[]> {\n const res = await this.deps.http.post<{ keys: string[] }>(this.spacePath(\"/list\"), {});\n const prefix = `${collection}/`;\n return (res.keys ?? [])\n .filter((k) => k.startsWith(prefix))\n .map((k) => k.slice(prefix.length));\n }\n\n /** Reserved — server-side query is deferred (see the overhaul plan). */\n async query(_collection: string, _filter?: unknown): Promise<never> {\n throw new Error(\"client.kv.query is not implemented yet (deferred in the SDK overhaul).\");\n }\n\n /**\n * Subscribe to realtime changes to this user's data across devices. Opens\n * the personal space's websocket and decrypts each change before handing\n * it to `handler`. Returns an unsubscribe function.\n *\n * Requires a `WebSocket` global (browsers; Node 22+ or a `ws` shim).\n */\n on<T = unknown>(event: \"change\", handler: (e: StorageChangeEvent<T>) => void): () => void {\n if (event !== \"change\") throw new Error(`client.kv: unknown event \"${event}\"`);\n\n if (typeof (globalThis as { WebSocket?: typeof WebSocket }).WebSocket !== \"function\") {\n throw new Error(\"client.kv.on: no `WebSocket` global available in this runtime.\");\n }\n const token = this.deps.session.token;\n if (!token) throw new Error(\"client.kv.on: not signed in.\");\n\n const commitment = this.commitment();\n const url = `${this.deps.wsBaseUrl}/api/personal/${encodeURIComponent(commitment)}/websocket?session=${encodeURIComponent(token)}`;\n\n // Ride a WSTransport rather than a bare socket: it keeps the (otherwise\n // idle) personal-space feed warm with heartbeat pings, auto-reconnects\n // if it drops, and namespaces its events by `id` so this feed never\n // crosses wires with chat/space transports on the shared EventCore bus.\n const transport = new WSTransport({ url, id: `personal:${commitment}` });\n const onMessage = (e: CustomEvent) => {\n void this.dispatchChange<T>(e.detail, handler);\n };\n transport.on(EventCoreEvents.MESSAGE, onMessage);\n // Fire-and-forget: the realtime feed is best-effort, and the transport\n // queues nothing it needs before CONNECTED (server→client only).\n void transport.connect();\n\n return () => {\n transport.off(EventCoreEvents.MESSAGE, onMessage);\n transport.disconnect();\n };\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private async dispatchChange<T>(\n raw: unknown,\n handler: (e: StorageChangeEvent<T>) => void,\n ): Promise<void> {\n let frame: ChangeFrame;\n try {\n frame = typeof raw === \"string\" ? JSON.parse(raw) : raw;\n } catch {\n return;\n }\n if (!frame || frame._t !== \"change\" || typeof frame.key !== \"string\") return;\n\n const slash = frame.key.indexOf(\"/\");\n if (slash < 0) return;\n const collection = frame.key.slice(0, slash);\n const id = frame.key.slice(slash + 1);\n\n const data = frame.op === \"set\" ? await this.decode<T>(frame.value) : null;\n handler({ collection, id, type: frame.op, data });\n }\n\n /** Decode a stored value: decrypt envelopes, pass plaintext through. */\n private async decode<T>(value: unknown): Promise<T | null> {\n if (value == null) return null;\n if (StorageCipher.isEnvelope(value)) return this.getCipher().decrypt<T>(value);\n return value as T;\n }\n\n private commitment(): string {\n const c = this.deps.session.commitment;\n if (!c) throw new Error(\"client.kv: not signed in — call client.auth.zk.login() first.\");\n return c;\n }\n\n private spacePath(suffix: string): string {\n return `/api/personal/${encodeURIComponent(this.commitment())}${suffix}`;\n }\n\n private kvPath(collection: string, id: string): string {\n const key = `${collection}/${id}`;\n return this.spacePath(`/kv/${encodeURIComponent(key)}`);\n }\n\n /** The at-rest cipher for the current identity (re-derived if it changes). */\n private getCipher(): StorageCipher {\n const identity = this.deps.session.requireIdentity();\n if (this.cipher && this.cipherIdentity === identity) return this.cipher;\n this.cipher = new StorageCipher(identity.secretHex, identity.saltHex);\n this.cipherIdentity = identity;\n return this.cipher;\n }\n}\n\nexport default KvNamespace;\n","/**\n * `client.db` — the app's scalable database. A developer defines tables in the\n * Muhkoo portal (columns + indexes); each table is backed by its own Durable\n * Object SQLite instance and reachable through a sanitized REST gateway. This\n * namespace wraps that gateway:\n *\n * const todos = client.db.table('todos');\n * const { id } = await todos.insert({ title: 'Buy milk', done: false });\n * const one = await todos.get(id);\n * const { rows, nextCursor } = await todos.query({\n * where: [{ column: 'done', op: 'eq', value: false }],\n * orderBy: { column: 'rank', dir: 'asc' },\n * limit: 50,\n * });\n * await todos.update(id, { done: true });\n * await todos.delete(id);\n *\n * Authorization is the **app key** ({@link HttpClient} stamps it on every\n * request); the appId + environment are resolved server-side from the key, so a\n * key can only ever reach its own app's tables. The front end never touches the\n * database directly — this REST surface is the only gateway, and all input is\n * validated against the table's schema (parameterized statements, column +\n * operator allowlists). There is no raw-SQL passthrough.\n *\n * Schema is authored in the portal, not here (the SDK reads + writes rows, it\n * doesn't create tables). Pagination is keyset-based: pass the `nextCursor` from\n * a previous `query()` back as `cursor` to fetch the next page.\n */\n\nimport type { HttpClient } from \"../HttpClient\";\n\nexport interface DbNamespaceDeps {\n http: HttpClient;\n}\n\n/** Comparison operators allowed in a {@link DbQuery} `where` clause. */\nexport type DbFilterOp =\n | \"eq\" | \"neq\" | \"gt\" | \"gte\" | \"lt\" | \"lte\"\n | \"in\" | \"like\" | \"likeStartsWith\" | \"likeContains\";\n\nexport interface DbWhereCondition {\n column: string;\n op: DbFilterOp;\n /** Scalar for most ops; an array for `in`; a string for the `like` family. */\n value: unknown;\n}\n\nexport interface DbQuery {\n /** Columns to return; omit for all columns. */\n select?: string[];\n /** Conditions AND-combined. */\n where?: DbWhereCondition[];\n /** Sort by a column (defaults to the primary key, ascending). */\n orderBy?: { column: string; dir?: \"asc\" | \"desc\" };\n /** Page size, clamped server-side to 100. */\n limit?: number;\n /** Opaque keyset cursor from a previous query's `nextCursor`. */\n cursor?: string;\n}\n\nexport interface DbQueryResult<T = Record<string, unknown>> {\n rows: T[];\n /** Cursor for the next page, or `null` when the last page was returned. */\n nextCursor: string | null;\n}\n\n/** A handle to one table — the ergonomic surface for row operations. */\nexport class DbTable<T extends Record<string, unknown> = Record<string, unknown>> {\n constructor(private readonly http: HttpClient, private readonly name: string) {}\n\n private base(): string {\n return `/api/db/${encodeURIComponent(this.name)}`;\n }\n\n /** Insert a row. Returns the created row and its primary-key value. */\n async insert(values: Partial<T>): Promise<{ row: T; id: unknown }> {\n return this.http.post<{ row: T; id: unknown }>(this.base(), { values });\n }\n\n /** Fetch a row by primary key, or `null` if it doesn't exist. */\n async get(id: string | number): Promise<T | null> {\n try {\n const res = await this.http.get<{ row: T }>(`${this.base()}/${encodeURIComponent(String(id))}`);\n return res.row;\n } catch (e) {\n if ((e as { status?: number })?.status === 404) return null;\n throw e;\n }\n }\n\n /** Query rows with filters, ordering, and keyset pagination. */\n async query(query: DbQuery = {}): Promise<DbQueryResult<T>> {\n return this.http.post<DbQueryResult<T>>(`${this.base()}/query`, query);\n }\n\n /** Update a row by primary key. Returns the updated row. */\n async update(id: string | number, values: Partial<T>): Promise<{ row: T }> {\n return this.http.patch<{ row: T }>(`${this.base()}/${encodeURIComponent(String(id))}`, { values });\n }\n\n /** Delete a row by primary key. Returns the number of rows removed (0 or 1). */\n async delete(id: string | number): Promise<number> {\n const res = await this.http.del<{ deleted: number }>(`${this.base()}/${encodeURIComponent(String(id))}`);\n return res.deleted ?? 0;\n }\n}\n\nexport class DbNamespace {\n constructor(private readonly deps: DbNamespaceDeps) {}\n\n /**\n * A handle to a table defined in the portal. The optional type parameter\n * gives row operations a typed shape:\n *\n * interface Todo { _id: number; title: string; done: boolean }\n * const todos = client.db.table<Todo>('todos');\n */\n table<T extends Record<string, unknown> = Record<string, unknown>>(name: string): DbTable<T> {\n return new DbTable<T>(this.deps.http, name);\n }\n}\n\nexport default DbNamespace;\n","/**\n * Wire types for the storage layer.\n *\n * The `FileManifest` is the single piece of metadata the system needs to\n * reassemble a file: per-chunk encryption material, RS parameters, and the\n * SHA-256 content hashes of every shard that belongs to the chunk. With the\n * manifest in hand, a reader can pull each shard from the open content-\n * addressed shard store, decode, decrypt, and concatenate to recover the\n * original bytes.\n *\n * The manifest itself lives inside a `SharedSpaceDO` (Phase B) which gates\n * access by ZK proof + ACL. Shards are stored in the open content-addressed\n * `ShardStoreDO` — anyone can put/get any shard, but without the manifest\n * (which has the keys) the ciphertext is just noise.\n */\n\nimport type { ChunkKeyMaterial } from \"../crypto/ChunkCipher\";\n\n/**\n * One chunk's metadata. A file is the concatenation of `chunks` in order.\n *\n * - `originalSize` is the chunk's plaintext length, before AES-GCM expanded\n * it by 16 bytes for the auth tag and before RS padded it for shard\n * alignment.\n * - `ciphertextSize` is the AES-GCM output length (plaintext + 16). This is\n * what the RS decoder trims back to.\n * - `shardHashes` lists every shard's SHA-256 in encoding order — the first\n * `dataShards` are data shards, the trailing `parityShards` are parity.\n */\nexport interface ChunkManifest {\n /** Stable per-chunk ID (uuid-like). Useful for client-side resume / dedup. */\n id: string;\n /** Position of this chunk in the file (0-indexed). */\n chunkIndex: number;\n /** Plaintext byte length of the chunk before encryption. */\n originalSize: number;\n /** AES-GCM ciphertext byte length (originalSize + 16 for the tag). */\n ciphertextSize: number;\n /** Number of RS data shards. */\n dataShards: number;\n /** Number of RS parity shards. */\n parityShards: number;\n /** Length in bytes of every shard (data and parity are equal). */\n shardSize: number;\n /** SHA-256 (hex) of each shard's ciphertext bytes, in shard order. */\n shardHashes: string[];\n /** Per-chunk AES-256-GCM key + IV. Plain in the manifest — gating happens at the SpaceDO. */\n cipher: ChunkKeyMaterial;\n}\n\n/**\n * Top-level manifest for a single stored file. Persisted in the user's\n * SharedSpace by file id; readable / writable per the space's ACL.\n */\nexport interface FileManifest {\n /** Stable file ID. Assigned by the SDK at write time; used to read or delete. */\n id: string;\n /** Human-readable filename (display only — not used by the shard store). */\n name: string;\n /** Total plaintext byte length. Sum of chunk `originalSize`s. */\n size: number;\n /** MIME type the application supplied at write time. Opaque to storage. */\n type: string;\n /** Optional virtual path / folder hint for the application. */\n path?: string;\n /** When the file was last modified per the application (ms epoch). */\n lastModified: number;\n /** When this manifest was created on the SDK side (ms epoch). */\n createdAt: number;\n /** Ordered list of chunks. Concatenate them in index order to rebuild the file. */\n chunks: ChunkManifest[];\n /** SDK schema version. Bump on breaking manifest-shape changes. */\n version: 1;\n}\n\n/**\n * Lightweight summary returned by `FileStorage.writeFile` and surfaced in\n * directory-style listings. The full manifest is only fetched when actually\n * reassembling the file.\n */\nexport interface FileStat {\n id: string;\n name: string;\n size: number;\n type: string;\n path?: string;\n lastModified: number;\n createdAt: number;\n chunkCount: number;\n shardCount: number;\n}\n\n/** Distil a `FileManifest` into a `FileStat`. */\nexport function manifestToStat(manifest: FileManifest): FileStat {\n let shardCount = 0;\n for (const c of manifest.chunks) shardCount += c.shardHashes.length;\n return {\n id: manifest.id,\n name: manifest.name,\n size: manifest.size,\n type: manifest.type,\n path: manifest.path,\n lastModified: manifest.lastModified,\n createdAt: manifest.createdAt,\n chunkCount: manifest.chunks.length,\n shardCount,\n };\n}\n","/**\n * Universal wasm-bindgen glue for `wasm-reed-solomon-erasure` (v0.2.2 — Rust\n * Reed–Solomon erasure-coding library compiled with `wasm-pack --target nodejs`).\n *\n * The upstream npm package ships `wasm_reed_solomon_erasure.js` which uses\n * `require('fs').readFileSync()` to load the WASM file at module load time —\n * that hard-codes Node and breaks browsers / CF Workers. This file is a port\n * of that glue with the Node-only pieces removed:\n *\n * - `TextDecoder` is taken from the global (available in Node 12+, every\n * modern browser, and Workers — no `require('util')`).\n * - The WASM module is loaded via the rollup-inlined `.wasm` import, the\n * same `targetEnv: 'auto-inline'` path the bn128 verifier uses. Works in\n * Node, browser, and Workers without runtime fs access.\n *\n * Only the two public functions consumers actually need (`encode` and\n * `reconstruct`) are exported. The rest is the wbindgen heap-table dance.\n *\n * Encoding:\n * `encode(dataShards: Uint8Array[], parityShard: number)` → array of\n * `dataShards.length + parityShard` Uint8Arrays. The first N are the input\n * shards unchanged; the trailing M are the freshly computed parity shards.\n * All shards are the same length — caller is responsible for padding the\n * data into equal-size data shards.\n *\n * Reconstruction:\n * `reconstruct(corruptedShards, parityShard, deadIndexes)` → fully recovered\n * array. Pass placeholders (empty Uint8Arrays) at the dead indexes; the\n * reconstructor fills them in. Up to `parityShard` shards may be missing.\n */\n\n// The bundled-WASM loader lives in its own module so the `.wasm` static import\n// is only encountered when the fallback path is actually exercised. Tools\n// that can't parse the import (vitest without `vite-plugin-wasm`) can import\n// `rs.ts` cleanly so long as callers always pass a pre-compiled\n// `WebAssembly.Module` to `initRsWasm`.\n//\n// `@rollup/plugin-wasm` (with `targetEnv: 'auto-inline'`) actually returns\n// the result of `WebAssembly.instantiate(buffer, imports)` — which, when\n// called with a `BufferSource`, yields the `{ module, instance }` source\n// pair, NOT a bare `WebAssembly.Instance`. The plugin's own typings claim\n// the latter; treat the result as `unknown` and unwrap defensively below.\ntype BundledLoader = (\n imports?: Record<string, Record<string, unknown>>,\n) => Promise<unknown>;\n\n// ---------------------------------------------------------------------------\n// wbindgen heap-object table\n// ---------------------------------------------------------------------------\n//\n// wbindgen passes JS values to/from WASM by storing them in this JS-side heap\n// and shuttling integer indexes across the boundary. Indexes 0–35 are reserved\n// for runtime constants (`undefined`, `null`, `true`, `false`); 36+ are\n// recyclable slots.\n\nconst heap: unknown[] = new Array(32).fill(undefined);\nheap.push(undefined, null, true, false);\nlet heap_next = heap.length;\n\nfunction getObject(idx: number): unknown {\n return heap[idx];\n}\n\nfunction dropObject(idx: number): void {\n if (idx < 36) return;\n heap[idx] = heap_next;\n heap_next = idx;\n}\n\nfunction takeObject(idx: number): unknown {\n const ret = getObject(idx);\n dropObject(idx);\n return ret;\n}\n\nfunction addHeapObject(obj: unknown): number {\n if (heap_next === heap.length) heap.push(heap.length + 1);\n const idx = heap_next;\n heap_next = heap[idx] as number;\n heap[idx] = obj;\n return idx;\n}\n\n// ---------------------------------------------------------------------------\n// WASM memory views (lazily re-bound when memory.buffer grows on alloc)\n// ---------------------------------------------------------------------------\n\nlet wasm: WasmExports | null = null;\n\nlet cachedUint8: Uint8Array | null = null;\nfunction u8(): Uint8Array {\n if (cachedUint8 === null || cachedUint8.buffer !== wasm!.memory.buffer) {\n cachedUint8 = new Uint8Array(wasm!.memory.buffer);\n }\n return cachedUint8;\n}\n\nlet cachedUint32: Uint32Array | null = null;\nfunction u32(): Uint32Array {\n if (cachedUint32 === null || cachedUint32.buffer !== wasm!.memory.buffer) {\n cachedUint32 = new Uint32Array(wasm!.memory.buffer);\n }\n return cachedUint32;\n}\n\nlet cachedInt32: Int32Array | null = null;\nfunction i32(): Int32Array {\n if (cachedInt32 === null || cachedInt32.buffer !== wasm!.memory.buffer) {\n cachedInt32 = new Int32Array(wasm!.memory.buffer);\n }\n return cachedInt32;\n}\n\nconst textDecoder = new TextDecoder(\"utf-8\", { ignoreBOM: true, fatal: true });\n\n// ---------------------------------------------------------------------------\n// Boundary helpers — moving JS arrays of Uint8Arrays across the FFI\n// ---------------------------------------------------------------------------\n\nlet WASM_VECTOR_LEN = 0;\n\n/**\n * Allocate `array.length * 4` bytes inside the WASM heap and write each\n * element's heap-table index there as a u32. Used to pass `Uint8Array[]` into\n * Rust — wbindgen reads each index back via the `__wbg_*` import callbacks.\n */\nfunction passArrayJsValueToWasm(array: Uint8Array[], malloc: (n: number) => number): number {\n const ptr = malloc(array.length * 4);\n const mem = u32();\n for (let i = 0; i < array.length; i++) {\n mem[ptr / 4 + i] = addHeapObject(array[i]);\n }\n WASM_VECTOR_LEN = array.length;\n return ptr;\n}\n\n/**\n * Pull `len` heap-table indexes from WASM memory starting at `ptr`, take each\n * referenced object, and return them as a plain JS array. The take() consumes\n * the heap slot so it can be reused.\n */\nfunction getArrayJsValueFromWasm(ptr: number, len: number): Uint8Array[] {\n const mem = u32();\n const slice = mem.subarray(ptr / 4, ptr / 4 + len);\n const result: Uint8Array[] = [];\n for (let i = 0; i < slice.length; i++) {\n result.push(takeObject(slice[i]) as Uint8Array);\n }\n return result;\n}\n\nfunction getStringFromWasm(ptr: number, len: number): string {\n return textDecoder.decode(u8().subarray(ptr, ptr + len));\n}\n\n// ---------------------------------------------------------------------------\n// WASM module typings + initialization\n// ---------------------------------------------------------------------------\n\ninterface WasmExports {\n memory: WebAssembly.Memory;\n encode: (retptr: number, ptr: number, len: number, parity: number) => void;\n reconstruct: (retptr: number, ptr: number, len: number, parity: number, deadIdx: number) => void;\n __wbindgen_add_to_stack_pointer: (n: number) => number;\n __wbindgen_malloc: (n: number) => number;\n __wbindgen_free: (ptr: number, size: number) => void;\n}\n\n/**\n * The wbindgen import object — every callback Rust expects from JS. Names are\n * hard-coded by wasm-bindgen based on the Rust function signatures; do not\n * rename. If the upstream package is regenerated, these may drift and need\n * resyncing with the new `wasm_reed_solomon_erasure.js`.\n */\nfunction buildImports(): WebAssembly.Imports {\n const wbindgen: Record<string, (...args: number[]) => number | void> = {\n __wbindgen_object_drop_ref: (arg0: number) => {\n takeObject(arg0);\n },\n __wbg_buffer_7af23f65f6c64548: (arg0: number) => {\n const ret = (getObject(arg0) as Uint8Array).buffer;\n return addHeapObject(ret);\n },\n __wbg_newwithbyteoffsetandlength_ce1e75f0ce5f7974: (arg0: number, arg1: number, arg2: number) => {\n const ret = new Uint8Array(getObject(arg0) as ArrayBuffer, arg1 >>> 0, arg2 >>> 0);\n return addHeapObject(ret);\n },\n __wbg_new_cc9018bd6f283b6f: (arg0: number) => {\n const ret = new Uint8Array(getObject(arg0) as ArrayBuffer);\n return addHeapObject(ret);\n },\n __wbg_set_f25e869e4565d2a2: (arg0: number, arg1: number, arg2: number) => {\n (getObject(arg0) as Uint8Array).set(getObject(arg1) as Uint8Array, arg2 >>> 0);\n },\n __wbg_length_0acb1cf9bbaf8519: (arg0: number) => {\n return (getObject(arg0) as Uint8Array).length;\n },\n __wbg_new_e8c5277c0f9e2cfc: (arg0: number) => {\n const ret = new Uint32Array(getObject(arg0) as ArrayBuffer);\n return addHeapObject(ret);\n },\n __wbg_set_03c7d8c063f469ef: (arg0: number, arg1: number, arg2: number) => {\n (getObject(arg0) as Uint32Array).set(getObject(arg1) as Uint32Array, arg2 >>> 0);\n },\n __wbg_length_f98ca60981480796: (arg0: number) => {\n return (getObject(arg0) as Uint32Array).length;\n },\n __wbindgen_throw: (arg0: number, arg1: number) => {\n throw new Error(getStringFromWasm(arg0, arg1));\n },\n __wbindgen_memory: () => {\n return addHeapObject(wasm!.memory);\n },\n };\n return { __wbindgen_placeholder__: wbindgen as unknown as WebAssembly.ModuleImports };\n}\n\nlet _readyPromise: Promise<void> | null = null;\n\n/**\n * Load and instantiate the WASM module. Idempotent — repeated calls await the\n * same one-shot promise.\n *\n * Two ways to initialize, matching the pattern used by `workers/groth16-verifier`:\n * 1. `await initRsWasm()` — uses the bundled .wasm (base64-inlined at build\n * time by `@rollup/plugin-wasm`). Works in any runtime that allows\n * runtime `WebAssembly.compile()`.\n * 2. `await initRsWasm(myWasmModule)` — accepts a pre-compiled\n * `WebAssembly.Module`. Useful when the bundled loader path isn't\n * available (vitest, CF Workers wanting deploy-time precompile, etc.).\n */\nexport async function initRsWasm(wasmModule?: WebAssembly.Module): Promise<void> {\n if (_readyPromise) return _readyPromise;\n _readyPromise = (async () => {\n const imports = buildImports();\n let instance: WebAssembly.Instance;\n if (wasmModule) {\n // `instantiate(module, imports)` returns a bare Instance.\n instance = await WebAssembly.instantiate(wasmModule, imports);\n } else {\n // Defer the `.wasm` import to a separate module so vitest can load\n // `rs.ts` without it. Production callers either don't pass a\n // module (and hit the bundled loader here) or pass one explicitly.\n const bundled = (await import(\"./bundled-loader\")).default as BundledLoader;\n const result = await bundled(imports as Record<string, Record<string, unknown>>);\n // The bundled loader's actual return type is\n // `{ module: WebAssembly.Module, instance: WebAssembly.Instance }`\n // — the rollup-plugin-wasm shape from `WebAssembly.instantiate(buffer, imports)`.\n // Older versions (or future changes) may return a bare Instance,\n // so accept either shape.\n instance = unwrapInstance(result);\n }\n wasm = instance.exports as unknown as WasmExports;\n })();\n return _readyPromise;\n}\n\n/**\n * Normalize the value returned by `WebAssembly.instantiate` / the\n * rollup-plugin-wasm loader into a bare `WebAssembly.Instance`. Handles\n * both the `(module, imports)` overload (returns Instance) and the\n * `(buffer, imports)` overload (returns `{ module, instance }`).\n */\nfunction unwrapInstance(result: unknown): WebAssembly.Instance {\n if (result && typeof result === \"object\") {\n const candidate = result as { instance?: WebAssembly.Instance; exports?: unknown };\n if (candidate.instance && typeof candidate.instance === \"object\" && \"exports\" in candidate.instance) {\n return candidate.instance;\n }\n if (\"exports\" in candidate) {\n return result as WebAssembly.Instance;\n }\n }\n throw new Error(\n \"rs.ts: bundled WASM loader returned an unrecognized shape — expected WebAssembly.Instance or { module, instance }\",\n );\n}\n\n/**\n * Reset the singleton (test-only escape hatch). Lets a test load a different\n * pre-compiled module without restarting the process. Production code should\n * never need this.\n */\nexport function _resetRsWasmForTests(): void {\n _readyPromise = null;\n wasm = null;\n cachedUint8 = null;\n cachedUint32 = null;\n cachedInt32 = null;\n}\n\nfunction ensureReady(): void {\n if (!wasm) {\n throw new Error(\"rs.ts: WASM not initialized. Call `await initRsWasm()` first.\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public API — encode + reconstruct\n// ---------------------------------------------------------------------------\n\n/**\n * Encode the input data shards with `parityShard` parity shards. All input\n * shards must be Uint8Arrays of equal length; output contains the input shards\n * unchanged plus `parityShard` newly computed parity shards.\n */\nexport function encode(dataShards: Uint8Array[], parityShard: number): Uint8Array[] {\n ensureReady();\n const w = wasm!;\n try {\n const retptr = w.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm(dataShards, w.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n w.encode(retptr, ptr0, len0, parityShard);\n const r0 = i32()[retptr / 4 + 0];\n const r1 = i32()[retptr / 4 + 1];\n const v1 = getArrayJsValueFromWasm(r0, r1).slice();\n w.__wbindgen_free(r0, r1 * 4);\n return v1;\n } finally {\n w.__wbindgen_add_to_stack_pointer(16);\n }\n}\n\n/**\n * Reconstruct the original full shard array. `corruptedShards` is the full\n * list (data + parity) with placeholder Uint8Arrays at positions listed in\n * `deadShardIndexes`. Returns the recovered, complete list of shards.\n *\n * Up to `parityShard` shards may be missing; more than that is uncorrectable\n * and the underlying WASM throws.\n */\nexport function reconstruct(\n corruptedShards: Uint8Array[],\n parityShard: number,\n deadShardIndexes: Uint32Array,\n): Uint8Array[] {\n ensureReady();\n const w = wasm!;\n try {\n const retptr = w.__wbindgen_add_to_stack_pointer(-16);\n const ptr0 = passArrayJsValueToWasm(corruptedShards, w.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n w.reconstruct(retptr, ptr0, len0, parityShard, addHeapObject(deadShardIndexes));\n const r0 = i32()[retptr / 4 + 0];\n const r1 = i32()[retptr / 4 + 1];\n const v1 = getArrayJsValueFromWasm(r0, r1).slice();\n w.__wbindgen_free(r0, r1 * 4);\n return v1;\n } finally {\n w.__wbindgen_add_to_stack_pointer(16);\n }\n}\n","/**\n * Reed–Solomon erasure-coding codec.\n *\n * Wraps the WASM-backed `encode` / `reconstruct` primitives in `wasm/rs.ts`\n * with shard-padding bookkeeping so callers can hand it any-length input and\n * get back uniform-size shards.\n *\n * Usage:\n * const codec = new ReedSolomonCodec();\n * await codec.ready();\n * const { shards, shardSize, originalSize } = codec.encode(plaintext, 4, 2);\n * // 6 shards (4 data + 2 parity), each `shardSize` bytes\n * // …ship them, lose up to 2, then …\n * const recovered = codec.decode(shards, 2, deadIndexes, originalSize);\n *\n * Why the explicit `originalSize`: RS pads input to make every data shard the\n * same length. The decoder must trim that padding back off after recovery.\n * The caller is responsible for stashing `originalSize` somewhere durable\n * (the file manifest, in this codebase).\n */\n\nimport { initRsWasm, encode as wasmEncode, reconstruct as wasmReconstruct } from \"./wasm/rs\";\n\nexport interface EncodeResult {\n /** All `dataShards + parityShards` shards. All have length `shardSize`. */\n shards: Uint8Array[];\n /** Length of every shard (data and parity). */\n shardSize: number;\n /** Length of the original input before padding. Needed to trim on decode. */\n originalSize: number;\n /** How many of the leading shards are data (the rest are parity). */\n dataShards: number;\n /** How many parity shards trail the data shards. */\n parityShards: number;\n}\n\nexport class ReedSolomonCodec {\n /**\n * Resolves once the WASM module is loaded; safe to call repeatedly.\n *\n * Pass `wasmModule` to use a pre-compiled module (e.g. in tests where the\n * rollup-inlined loader path isn't available, or in CF Workers where you\n * want to load the module at deploy time). Default path uses the bundled\n * base64-inlined wasm — works in Node, browsers, and Workers.\n */\n ready(wasmModule?: WebAssembly.Module): Promise<void> {\n return initRsWasm(wasmModule);\n }\n\n /**\n * Split `data` into `dataShards` equal-size chunks (zero-padded to fit),\n * compute `parityShards` parity shards, and return all of them.\n */\n encode(data: Uint8Array, dataShards: number, parityShards: number): EncodeResult {\n if (dataShards < 1) throw new Error(\"ReedSolomonCodec.encode: dataShards must be >= 1\");\n if (parityShards < 1) throw new Error(\"ReedSolomonCodec.encode: parityShards must be >= 1\");\n if (data.length === 0) throw new Error(\"ReedSolomonCodec.encode: data is empty\");\n\n // The wbindgen-generated WASM in `wasm-reed-solomon-erasure@0.2.2` takes\n // the `parity_shard` count separately and infers `total = data.length +\n // parity_shard`. Every shard must be the same length, so we pad the\n // input to `dataShards * shardSize` with trailing zeros.\n const shardSize = Math.ceil(data.length / dataShards);\n const splitInputs: Uint8Array[] = [];\n for (let i = 0; i < dataShards; i++) {\n // Each shard is its own backing ArrayBuffer so the WASM side\n // doesn't observe overlapping views (which would confuse the\n // wbindgen length lookups).\n const shard = new Uint8Array(shardSize);\n const start = i * shardSize;\n const end = Math.min(start + shardSize, data.length);\n if (start < data.length) {\n shard.set(data.subarray(start, end));\n }\n splitInputs.push(shard);\n }\n\n const shards = wasmEncode(splitInputs, parityShards);\n // The underlying call returns N+M shards; first N are the (padded)\n // data shards we just sent in, last M are the parity shards.\n return {\n shards,\n shardSize,\n originalSize: data.length,\n dataShards,\n parityShards,\n };\n }\n\n /**\n * Reconstruct the original `data` from `shards`. Up to `parityShards`\n * shards may be missing; for each missing shard, pass an empty\n * `Uint8Array` placeholder at its position and list the position in\n * `deadShardIndexes`.\n *\n * `originalSize` is required so the trailing zero-padding can be trimmed.\n */\n decode(\n shards: Uint8Array[],\n parityShards: number,\n deadShardIndexes: number[],\n originalSize: number,\n ): Uint8Array {\n if (parityShards < 1) throw new Error(\"ReedSolomonCodec.decode: parityShards must be >= 1\");\n if (shards.length <= parityShards) {\n throw new Error(\"ReedSolomonCodec.decode: shards.length must be > parityShards\");\n }\n if (deadShardIndexes.length > parityShards) {\n throw new Error(\n `ReedSolomonCodec.decode: too many missing shards (${deadShardIndexes.length} > ${parityShards})`,\n );\n }\n\n const dataShards = shards.length - parityShards;\n const recovered =\n deadShardIndexes.length === 0\n ? shards\n : wasmReconstruct(shards, parityShards, new Uint32Array(deadShardIndexes));\n\n // Concatenate the leading `dataShards`, then trim padding back off.\n const shardSize = recovered[0]?.length ?? 0;\n const out = new Uint8Array(dataShards * shardSize);\n for (let i = 0; i < dataShards; i++) {\n out.set(recovered[i], i * shardSize);\n }\n return out.subarray(0, originalSize);\n }\n}\n\nexport default ReedSolomonCodec;\n","/**\n * HTTP client for the open content-addressed shard store.\n *\n * Each shard is named by the lowercase hex SHA-256 of its ciphertext bytes.\n * The server verifies the hash on PUT, so the address authenticates the\n * contents — there's no benefit to ACLing PUT/GET, and making them open\n * enables cross-user dedup down the line.\n *\n * Wire protocol:\n * PUT /api/shards/:hash body: shard bytes (application/octet-stream)\n * 200 { ok: true, hash, size, dedup: boolean }\n * 400 if hash doesn't match body\n *\n * GET /api/shards/:hash 200 with shard bytes (application/octet-stream)\n * 404 if absent\n *\n * HEAD /api/shards/:hash 200 if present (no body) — used by callers to\n * skip a PUT they'd otherwise dedup-rewrite. The\n * server can ignore the optimization if it wants.\n */\n\nimport { toHex } from \"../../utilities/bytes\";\n\nexport interface ShardClientOptions {\n /** Base URL of the accelerator (e.g. `https://muhkoo-accelerator.workers.dev`). */\n baseUrl: string;\n /**\n * Path prefix for the shard endpoints, joined to `baseUrl` before the\n * hash. Defaults to `/api/shards`, which targets a global shard store\n * (e.g. a dedicated `ShardStoreDO`). Pass a room-scoped value like\n * `/api/spaces/{roomId}/shards` to keep shards bound to a specific\n * `SharedSpaceDO` — that's the path the chat application uses today.\n *\n * Leading slash optional; trailing slash stripped. The final URL is\n * always `${baseUrl}${normalizedPrefix}/${encodeURIComponent(hash)}`.\n */\n pathPrefix?: string;\n /**\n * Optional custom fetch implementation. Defaults to `globalThis.fetch`.\n * Provided so callers can inject retries / auth / instrumentation.\n */\n fetch?: typeof fetch;\n}\n\n/**\n * Compute the lowercase hex SHA-256 of `bytes`. Available via WebCrypto in\n * every runtime this SDK targets.\n */\nexport async function shardHash(bytes: Uint8Array): Promise<string> {\n const subtle = (globalThis.crypto as Crypto | undefined)?.subtle;\n if (!subtle) {\n throw new Error(\"shardHash: `globalThis.crypto.subtle` is unavailable in this runtime.\");\n }\n const digest = await subtle.digest(\"SHA-256\", bytes as BufferSource);\n return toHex(new Uint8Array(digest));\n}\n\nexport class ShardClient {\n private readonly baseUrl: string;\n private readonly pathPrefix: string;\n private readonly fetchFn: typeof fetch;\n\n constructor(opts: ShardClientOptions) {\n if (!opts?.baseUrl) throw new Error(\"ShardClient: `baseUrl` is required\");\n // Strip trailing slash so url concatenation stays clean.\n this.baseUrl = opts.baseUrl.replace(/\\/+$/, \"\");\n // Normalize prefix to leading-slash + no-trailing-slash form so the\n // URL builder can blindly append `/{hash}`.\n const rawPrefix = opts.pathPrefix ?? \"/api/shards\";\n const withSlash = rawPrefix.startsWith(\"/\") ? rawPrefix : `/${rawPrefix}`;\n this.pathPrefix = withSlash.replace(/\\/+$/, \"\");\n const f = opts.fetch ?? globalThis.fetch;\n if (typeof f !== \"function\") {\n throw new Error(\"ShardClient: `globalThis.fetch` is unavailable; pass an explicit fetch.\");\n }\n this.fetchFn = f.bind(globalThis);\n }\n\n /** Build the URL for a given shard hash — exposed for callers that want to log or pre-resolve. */\n urlForHash(hash: string): string {\n return `${this.baseUrl}${this.pathPrefix}/${encodeURIComponent(hash)}`;\n }\n\n /**\n * Upload a shard. The server verifies SHA-256(body) matches `:hash` and\n * rejects with 400 if not, so the caller is the source of truth on\n * naming. Re-uploading an existing shard is idempotent — the server\n * returns `dedup: true` in that case.\n */\n async putShard(hash: string, bytes: Uint8Array): Promise<{ dedup: boolean }> {\n const url = this.urlForHash(hash);\n const response = await this.fetchFn(url, {\n method: \"PUT\",\n headers: { \"content-type\": \"application/octet-stream\" },\n // BufferSource is what fetch's body expects; a Uint8Array satisfies it.\n body: bytes as BodyInit,\n });\n if (!response.ok) {\n const text = await safeText(response);\n throw new Error(`ShardClient.putShard(${hash}) failed (${response.status}): ${text}`);\n }\n let dedup = false;\n try {\n const json = (await response.json()) as { dedup?: boolean };\n dedup = Boolean(json?.dedup);\n } catch {\n // Server returned 200 with no body — treat as fresh upload.\n }\n return { dedup };\n }\n\n /**\n * Fetch a shard by hash. Throws if the server returns a non-200; returns\n * `null` for 404 so callers can distinguish \"missing\" from \"errored\".\n */\n async getShard(hash: string): Promise<Uint8Array | null> {\n const url = this.urlForHash(hash);\n const response = await this.fetchFn(url, { method: \"GET\" });\n if (response.status === 404) return null;\n if (!response.ok) {\n const text = await safeText(response);\n throw new Error(`ShardClient.getShard(${hash}) failed (${response.status}): ${text}`);\n }\n const buf = await response.arrayBuffer();\n return new Uint8Array(buf);\n }\n\n /**\n * Check whether a shard exists. Lets the caller skip a PUT they'd otherwise\n * dedup-rewrite. The server can implement this as a HEAD or return a small\n * JSON body — we don't depend on either.\n */\n async hasShard(hash: string): Promise<boolean> {\n const url = this.urlForHash(hash);\n const response = await this.fetchFn(url, { method: \"HEAD\" });\n return response.status === 200;\n }\n}\n\nasync function safeText(response: Response): Promise<string> {\n try { return await response.text(); } catch { return \"\"; }\n}\n","/**\n * `FileStorage` — top-level entry point for chunked, encrypted, erasure-coded\n * file storage.\n *\n * Pipeline for writing a file:\n * 1. Split the plaintext into fixed-size chunks (default 4 MiB).\n * 2. For each chunk:\n * a. Generate a fresh AES-256-GCM key + 12-byte IV (`ChunkCipher`).\n * b. Encrypt the chunk → ciphertext (plaintext.length + 16 bytes tag).\n * c. Reed–Solomon encode the ciphertext into `dataShards + parityShards`\n * equal-length shards (`ReedSolomonCodec`).\n * d. PUT every shard to the content-addressed shard store, keyed by\n * SHA-256 of the shard bytes (`ShardClient`).\n * 3. Build a `FileManifest` listing every chunk's keys, IVs, sizes, and\n * the SHA-256 of every shard in order.\n *\n * Two ways to use the manifest:\n * - {@link FileStorage.writeFileToShards} returns it to the caller, who is\n * then responsible for delivering it to readers (e.g. by E2E-encrypting\n * it as a chat message). The chat application takes this path.\n * - {@link FileStorage.writeFile} additionally POSTs the manifest to a\n * gated multi-user space (`SharedSpaceClient`) so any participant of the\n * space can read the file by manifest id later.\n *\n * Reading is the inverse: {@link FileStorage.readFileFromShards} takes a\n * manifest and reassembles the plaintext; {@link FileStorage.readFile} first\n * fetches the manifest from the space.\n */\n\nimport type { FileManifest, FileStat, ChunkManifest } from \"./types\";\nimport { manifestToStat } from \"./types\";\nimport { ChunkCipher } from \"../crypto/ChunkCipher\";\nimport type { ChunkKeyMaterial } from \"../crypto/ChunkCipher\";\nimport { ReedSolomonCodec } from \"./encoding\";\nimport { ShardClient, shardHash } from \"./transport/ShardClient\";\nimport { SharedSpaceClient } from \"./transport/SharedSpaceClient\";\nimport { generateId } from \"../utilities\";\n\nexport interface FileStorageOptions {\n /** Talks to the content-addressed shard store. Always required. */\n shards: ShardClient;\n /**\n * Talks to the gated multi-user space holding manifests + ACLs.\n * Optional — only required by {@link FileStorage.writeFile} /\n * {@link FileStorage.readFile} / {@link FileStorage.deleteFile} /\n * {@link FileStorage.listFiles} / {@link FileStorage.readManifest}.\n *\n * Callers that ship the manifest themselves (e.g. via an encrypted chat\n * message) can omit `space` and use the `*FromShards` / `*ToShards`\n * methods directly.\n */\n space?: SharedSpaceClient;\n /**\n * Plaintext chunk size in bytes. After encryption each chunk gains 16\n * bytes (GCM tag); after RS encoding the size is rounded up to a multiple\n * of `dataShards` per chunk. Default 4 MiB — a balance between\n * round-trip cost and parallelism on the upload path.\n */\n chunkSize?: number;\n /** RS data shards per chunk (default 4). */\n dataShards?: number;\n /** RS parity shards per chunk (default 2). */\n parityShards?: number;\n /**\n * Cap on concurrent shard uploads / downloads. Tune for the network. The\n * default of 8 saturates most home connections without overwhelming the\n * server's per-IP rate limiter.\n */\n concurrency?: number;\n /**\n * Optional pre-compiled RS WebAssembly module. Defaults to the bundled\n * loader. Pass this in environments where the bundled loader path isn't\n * available (vitest, deploy-time-precompiled CF Workers).\n */\n rsWasmModule?: WebAssembly.Module;\n}\n\n/**\n * Input to {@link FileStorage.writeFile} (which writes the manifest to a\n * `SharedSpaceClient`). Carries the destination `spaceId`.\n */\nexport interface WriteFileInput extends WriteToShardsInput {\n /** Space to write the manifest to — must allow the caller `write`. */\n spaceId: string;\n}\n\n/**\n * Input to {@link FileStorage.writeFileToShards} (which doesn't write a\n * manifest anywhere — that's the caller's job).\n */\nexport interface WriteToShardsInput {\n /** Raw data, a Blob, or a File. */\n data: Uint8Array | Blob | File;\n /** Application-supplied display metadata. */\n metadata: {\n name: string;\n type: string;\n path?: string;\n lastModified?: number;\n };\n /**\n * Optional pre-allocated file id. Defaults to a fresh one. Useful for\n * resumable uploads: the same id always maps to the same manifest slot.\n */\n fileId?: string;\n /**\n * Optional upload-progress callback, invoked after each chunk finishes\n * (`completed` of `total` chunks). Lets a UI show a progress bar. Called once\n * with `(0, total)` before the first chunk so a bar can render immediately.\n */\n onProgress?: (completed: number, total: number) => void;\n}\n\nexport class FileStorage {\n private readonly space: SharedSpaceClient | undefined;\n private readonly shards: ShardClient;\n private readonly chunkSize: number;\n private readonly dataShards: number;\n private readonly parityShards: number;\n private readonly concurrency: number;\n private readonly cipher = new ChunkCipher();\n private readonly codec = new ReedSolomonCodec();\n private readonly rsWasmModule?: WebAssembly.Module;\n\n constructor(opts: FileStorageOptions) {\n if (!opts?.shards) throw new Error(\"FileStorage: `shards` (ShardClient) is required\");\n\n this.space = opts.space;\n this.shards = opts.shards;\n this.chunkSize = opts.chunkSize ?? 4 * 1024 * 1024;\n this.dataShards = opts.dataShards ?? 4;\n this.parityShards = opts.parityShards ?? 2;\n this.concurrency = Math.max(1, opts.concurrency ?? 8);\n this.rsWasmModule = opts.rsWasmModule;\n\n if (this.chunkSize < 1) throw new Error(\"FileStorage: chunkSize must be >= 1 byte\");\n if (this.dataShards < 1) throw new Error(\"FileStorage: dataShards must be >= 1\");\n if (this.parityShards < 1) throw new Error(\"FileStorage: parityShards must be >= 1\");\n }\n\n // -------------------------------------------------------------------------\n // Shard-only pipeline — the caller owns the manifest. Used by chat file\n // sharing, where the manifest rides as an E2E-encrypted chat message.\n // -------------------------------------------------------------------------\n\n /**\n * Chunk → encrypt → encode → upload-shards. Returns the resulting manifest\n * along with a `FileStat` summary. The caller is responsible for storing\n * or transmitting the manifest however it likes.\n */\n async writeFileToShards(\n input: WriteToShardsInput,\n ): Promise<{ manifest: FileManifest; stat: FileStat }> {\n await this.codec.ready(this.rsWasmModule);\n\n const data = await toUint8Array(input.data);\n const fileId = input.fileId ?? generateId();\n const createdAt = Date.now();\n const chunks: ChunkManifest[] = [];\n const totalChunks = Math.max(1, Math.ceil(data.length / this.chunkSize));\n input.onProgress?.(0, totalChunks);\n\n // Slicing + encrypting + encoding + uploading is done per-chunk so\n // the peak memory footprint stays at ~chunkSize even for huge files.\n // Within a chunk, the shard uploads are parallelized up to\n // `this.concurrency`.\n for (let chunkIndex = 0; chunkIndex * this.chunkSize < Math.max(1, data.length); chunkIndex++) {\n const start = chunkIndex * this.chunkSize;\n const end = Math.min(start + this.chunkSize, data.length);\n const plaintext = data.subarray(start, end);\n chunks.push(await this.writeChunk(plaintext, chunkIndex));\n input.onProgress?.(chunks.length, totalChunks);\n // Stop after one iteration if the file is empty — we still emit a\n // single zero-length chunk so the manifest has a stable shape.\n if (data.length === 0) break;\n }\n\n const manifest: FileManifest = {\n id: fileId,\n name: input.metadata.name,\n size: data.length,\n type: input.metadata.type,\n path: input.metadata.path,\n lastModified: input.metadata.lastModified ?? createdAt,\n createdAt,\n chunks,\n version: 1,\n };\n\n return { manifest, stat: manifestToStat(manifest) };\n }\n\n /**\n * Inverse of {@link writeFileToShards}. Takes a manifest the caller\n * obtained somehow (chat message, share link, etc.) and reassembles the\n * plaintext. Throws if too many shards are missing or any chunk's auth\n * tag fails.\n */\n async readFileFromShards(\n manifest: FileManifest,\n ): Promise<{ data: Uint8Array; stat: FileStat }> {\n await this.codec.ready(this.rsWasmModule);\n\n // Materialize each chunk into plaintext, then concatenate. We don't\n // stream across chunks here because the consuming surface returns\n // `Uint8Array`; a streaming variant would reuse `readChunk` unchanged.\n const plaintextChunks: Uint8Array[] = [];\n for (const chunkManifest of [...manifest.chunks].sort((a, b) => a.chunkIndex - b.chunkIndex)) {\n plaintextChunks.push(await this.readChunk(chunkManifest));\n }\n let total = 0;\n for (const c of plaintextChunks) total += c.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const c of plaintextChunks) {\n out.set(c, offset);\n offset += c.length;\n }\n return { data: out, stat: manifestToStat(manifest) };\n }\n\n // -------------------------------------------------------------------------\n // Space-backed convenience wrappers — encrypt + upload + write manifest.\n // Require a `SharedSpaceClient` to have been provided at construction.\n // -------------------------------------------------------------------------\n\n /** As {@link writeFileToShards}, plus POSTs the manifest to `input.spaceId`. */\n async writeFile(input: WriteFileInput): Promise<FileStat> {\n const space = this.requireSpace(\"writeFile\");\n const { manifest, stat } = await this.writeFileToShards(input);\n await space.writeFileManifest(input.spaceId, manifest);\n return stat;\n }\n\n /** As {@link readFileFromShards}, but fetches the manifest from a space first. */\n async readFile(spaceId: string, fileId: string): Promise<{ data: Uint8Array; stat: FileStat }> {\n const space = this.requireSpace(\"readFile\");\n const manifest = await space.readFileManifest(spaceId, fileId);\n return await this.readFileFromShards(manifest);\n }\n\n /**\n * Delete the manifest from a space. **Does not GC the shards** — those\n * are content-addressed and may be referenced by other manifests.\n * Garbage collection is a separate server-side concern (Phase D / D-ish).\n */\n async deleteFile(spaceId: string, fileId: string): Promise<boolean> {\n const space = this.requireSpace(\"deleteFile\");\n return space.deleteFileManifest(spaceId, fileId);\n }\n\n /** Convenience pass-through. */\n async listFiles(spaceId: string): Promise<FileStat[]> {\n const space = this.requireSpace(\"listFiles\");\n return space.listFiles(spaceId);\n }\n\n /** Read a manifest verbatim — useful for \"share file\" / export flows. */\n async readManifest(spaceId: string, fileId: string): Promise<FileManifest> {\n const space = this.requireSpace(\"readManifest\");\n return space.readFileManifest(spaceId, fileId);\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private requireSpace(operation: string): SharedSpaceClient {\n if (!this.space) {\n throw new Error(\n `FileStorage.${operation}: a SharedSpaceClient is required for this operation ` +\n \"(constructor was called without `space`)\",\n );\n }\n return this.space;\n }\n\n /** Encrypt + encode + upload one chunk; return its manifest entry. */\n private async writeChunk(plaintext: Uint8Array, chunkIndex: number): Promise<ChunkManifest> {\n const keyMaterial: ChunkKeyMaterial = this.cipher.generateKeyMaterial();\n const ciphertext =\n plaintext.length === 0\n ? new Uint8Array(0)\n : await this.cipher.encryptChunk(plaintext, keyMaterial);\n\n // An empty chunk encodes to nothing — emit a manifest entry with no\n // shards so the reader can re-emit an empty plaintext and skip the\n // shard round-trip.\n if (ciphertext.length === 0) {\n return {\n id: generateId(),\n chunkIndex,\n originalSize: 0,\n ciphertextSize: 0,\n dataShards: this.dataShards,\n parityShards: this.parityShards,\n shardSize: 0,\n shardHashes: [],\n cipher: keyMaterial,\n };\n }\n\n const encoded = this.codec.encode(ciphertext, this.dataShards, this.parityShards);\n const hashes = await Promise.all(encoded.shards.map((s) => shardHash(s)));\n await this.runWithConcurrency(\n encoded.shards.map((bytes, i) => async () => {\n await this.shards.putShard(hashes[i], bytes);\n }),\n );\n\n return {\n id: generateId(),\n chunkIndex,\n originalSize: plaintext.length,\n ciphertextSize: ciphertext.length,\n dataShards: encoded.dataShards,\n parityShards: encoded.parityShards,\n shardSize: encoded.shardSize,\n shardHashes: hashes,\n cipher: keyMaterial,\n };\n }\n\n /** Inverse of `writeChunk`. */\n private async readChunk(manifest: ChunkManifest): Promise<Uint8Array> {\n if (manifest.shardHashes.length === 0) {\n // Empty chunk fast path.\n return new Uint8Array(0);\n }\n\n // Fetch shards in parallel. Anything missing becomes a placeholder so\n // the decoder can fill it in from the parity shards (up to\n // `parityShards` allowed).\n const fetched = new Array<Uint8Array | null>(manifest.shardHashes.length);\n await this.runWithConcurrency(\n manifest.shardHashes.map((hash, i) => async () => {\n fetched[i] = await this.shards.getShard(hash);\n }),\n );\n\n const deadIndexes: number[] = [];\n const shards: Uint8Array[] = fetched.map((bytes, i) => {\n if (bytes === null) {\n deadIndexes.push(i);\n return new Uint8Array(manifest.shardSize);\n }\n if (bytes.length !== manifest.shardSize) {\n throw new Error(\n `FileStorage: shard ${manifest.shardHashes[i]} has wrong size ` +\n `(got ${bytes.length}, expected ${manifest.shardSize})`,\n );\n }\n return bytes;\n });\n\n if (deadIndexes.length > manifest.parityShards) {\n throw new Error(\n `FileStorage: chunk ${manifest.id} unrecoverable — ${deadIndexes.length} shards missing, ` +\n `only ${manifest.parityShards} tolerated`,\n );\n }\n\n const ciphertextPadded = this.codec.decode(\n shards,\n manifest.parityShards,\n deadIndexes,\n manifest.ciphertextSize,\n );\n return await this.cipher.decryptChunk(ciphertextPadded, manifest.cipher);\n }\n\n /** Run `tasks` with at most `this.concurrency` in flight. */\n private async runWithConcurrency(tasks: Array<() => Promise<void>>): Promise<void> {\n let cursor = 0;\n const concurrency = this.concurrency;\n async function nextWorker(): Promise<void> {\n while (cursor < tasks.length) {\n const idx = cursor++;\n await tasks[idx]();\n }\n }\n const workers = new Array(Math.min(concurrency, tasks.length))\n .fill(null)\n .map(() => nextWorker());\n await Promise.all(workers);\n }\n}\n\n/** Normalize `data` to a flat `Uint8Array`. */\nasync function toUint8Array(data: Uint8Array | Blob | File): Promise<Uint8Array> {\n if (data instanceof Uint8Array) return data;\n // Blob covers File too (File extends Blob in every runtime we target).\n const ab = await data.arrayBuffer();\n return new Uint8Array(ab);\n}\n\nexport default FileStorage;\n","/**\n * HTTP client for the gated file-manifest store on a SharedSpace\n * (`/api/spaces/:spaceId/files`).\n *\n * A \"file\" in a space is its **manifest** (per-chunk keys + the SHA-256 of each\n * global shard). The shard bytes live in the open `/api/shards` store; the\n * manifest is the capability. This client only moves manifests in/out of the\n * space's gated store.\n *\n * Authorization is **session-based**, consistent with the rest of the\n * SharedSpace (keyring, websocket): the SDK's credential-stamping `fetch`\n * (from {@link HttpClient}) attaches the app key + session token, the platform\n * validates the session and injects a trusted `X-Muhkoo-User-Context`, and the\n * DO authorizes on that + channel membership. There is no per-op Groth16 proof.\n *\n * Wire protocol (server: `SharedSpaceDO`):\n * POST /api/spaces/:spaceId/files body: { manifest } → { ok, fileId }\n * GET /api/spaces/:spaceId/files → { files: FileStat[] }\n * GET /api/spaces/:spaceId/files/:fileId → { manifest }\n * DELETE /api/spaces/:spaceId/files/:fileId → { ok, existed }\n */\n\nimport type { FileManifest, FileStat } from \"../types\";\n\nexport interface SharedSpaceClientOptions {\n /** Base URL of the accelerator (e.g. `https://api.muhkoo.dev`). */\n baseUrl: string;\n /**\n * Credential-stamping fetch — pass {@link HttpClient.fetch} so requests\n * carry the app key + session token. Defaults to `globalThis.fetch`\n * (unauthenticated; only useful in tests).\n */\n fetch?: typeof fetch;\n}\n\nexport class SharedSpaceClient {\n private readonly baseUrl: string;\n private readonly fetchFn: typeof fetch;\n\n constructor(opts: SharedSpaceClientOptions) {\n if (!opts?.baseUrl) throw new Error(\"SharedSpaceClient: `baseUrl` is required\");\n this.baseUrl = opts.baseUrl.replace(/\\/+$/, \"\");\n const f = opts.fetch ?? globalThis.fetch;\n if (typeof f !== \"function\") {\n throw new Error(\"SharedSpaceClient: `globalThis.fetch` is unavailable; pass an explicit fetch.\");\n }\n this.fetchFn = f.bind(globalThis);\n }\n\n /** Write a file manifest into the space. Requires space membership. */\n async writeFileManifest(spaceId: string, manifest: FileManifest): Promise<void> {\n const url = `${this.filesBase(spaceId)}`;\n const res = await this.fetchFn(url, this.jsonRequest(\"POST\", { manifest }));\n await parseOrThrow<{ ok: true; fileId: string }>(res, `writeFileManifest(${manifest.id})`);\n }\n\n /** Read a file manifest by id. Requires space membership. */\n async readFileManifest(spaceId: string, fileId: string): Promise<FileManifest> {\n const url = `${this.filesBase(spaceId)}/${encodeURIComponent(fileId)}`;\n const res = await this.fetchFn(url, this.jsonRequest(\"GET\"));\n const data = await parseOrThrow<{ manifest: FileManifest }>(res, `readFileManifest(${fileId})`);\n return data.manifest;\n }\n\n /** Delete a file manifest by id. Requires space membership. */\n async deleteFileManifest(spaceId: string, fileId: string): Promise<boolean> {\n const url = `${this.filesBase(spaceId)}/${encodeURIComponent(fileId)}`;\n const res = await this.fetchFn(url, this.jsonRequest(\"DELETE\"));\n const data = await parseOrThrow<{ ok: true; existed: boolean }>(res, `deleteFileManifest(${fileId})`);\n return data.existed;\n }\n\n /** List file summaries in the space. Requires space membership. */\n async listFiles(spaceId: string): Promise<FileStat[]> {\n const url = `${this.filesBase(spaceId)}`;\n const res = await this.fetchFn(url, this.jsonRequest(\"GET\"));\n const data = await parseOrThrow<{ files: FileStat[] }>(res, \"listFiles\");\n return Array.isArray(data.files) ? data.files : [];\n }\n\n // -------------------------------------------------------------------------\n\n private filesBase(spaceId: string): string {\n return `${this.baseUrl}/api/spaces/${encodeURIComponent(spaceId)}/files`;\n }\n\n private jsonRequest(method: string, body?: unknown): RequestInit {\n const init: RequestInit = { method };\n if (body !== undefined) {\n init.headers = { \"Content-Type\": \"application/json\" };\n init.body = JSON.stringify(body);\n }\n return init;\n }\n}\n\nasync function parseOrThrow<T>(response: Response, op: string): Promise<T> {\n let parsed: unknown = null;\n try {\n parsed = await response.json();\n } catch {\n // non-JSON body\n }\n if (!response.ok) {\n const msg =\n parsed && typeof parsed === \"object\" && \"error\" in (parsed as object)\n ? String((parsed as { error: unknown }).error)\n : `${response.status} ${response.statusText}`;\n throw new Error(`SharedSpaceClient.${op}: ${msg}`);\n }\n return parsed as T;\n}\n\nexport default SharedSpaceClient;\n","/**\n * `client.storage` — file storage. Hides the `FileStorage` / `ShardClient` /\n * `SharedSpaceClient` primitives behind the unified client.\n *\n * const { stat, manifest } = await client.storage.writeFile({ spaceId, data, metadata })\n * const { data } = await client.storage.readFile(spaceId, fileId)\n * const files = await client.storage.listFiles() // my shared files\n * const files = await client.storage.listFiles({ spaceId }) // a space's files\n * await client.storage.deleteFile(spaceId, fileId)\n *\n * Model:\n * - **Files are written to a SharedSpace** (never the personal space). A file\n * is its manifest (per-chunk keys + global shard hashes); the manifest lives\n * in the space's gated, metered `/files` store, the shard ciphertext in the\n * global open `/api/shards` store.\n * - **The manifest is the capability** — anyone holding it reads the file from\n * the global shards, anywhere ({@link readByManifest}). Share a file by\n * sharing its manifest.\n * - **Personal discovery mirror** — on a successful write the SDK also records\n * the manifest in the user's `client.kv` under a reserved collection, so\n * {@link listFiles} (no `spaceId`) can show \"files I've shared\" without\n * enumerating spaces. The mirror is unmetered and is NOT a write path.\n *\n * For small structured values use `client.kv` instead.\n */\n\nimport type { HttpClient } from \"../HttpClient\";\nimport type { KvNamespace } from \"./KvNamespace\";\nimport { FileStorage } from \"../../storage/FileStorage\";\nimport { ShardClient } from \"../../storage/transport/ShardClient\";\nimport { SharedSpaceClient } from \"../../storage/transport/SharedSpaceClient\";\nimport { manifestToStat, type FileManifest, type FileStat } from \"../../storage/types\";\n\n/** Reserved `client.kv` collection holding the personal manifest mirror. */\nconst MIRROR_COLLECTION = \"__files__\";\n\nexport interface FileNamespaceDeps {\n http: HttpClient;\n baseUrl: string;\n /** Used for the unmetered personal discovery mirror. */\n kv: KvNamespace;\n /**\n * Optional pre-compiled Reed–Solomon WASM module. Defaults to the bundled\n * loader; pass one where the bundled loader path isn't available (vitest,\n * deploy-time-precompiled environments). Forwarded to {@link FileStorage}.\n */\n rsWasmModule?: WebAssembly.Module;\n}\n\nexport interface WriteFileOptions {\n /** SharedSpace the file is written to (obtain via `client.space`). */\n spaceId: string;\n data: Uint8Array | Blob | File;\n metadata: { name: string; type: string; path?: string; lastModified?: number };\n}\n\n/** What the personal mirror stores per file. */\ninterface MirrorEntry {\n spaceId: string;\n manifest: FileManifest;\n}\n\nexport class StorageNamespace {\n private fileStorage: FileStorage | null = null;\n\n constructor(private readonly deps: FileNamespaceDeps) {}\n\n /**\n * Write a file to a SharedSpace: shard ciphertext → the global store, the\n * manifest → the space's gated store, and a mirror copy → the caller's\n * personal index. Returns the `stat` and the `manifest` (share the manifest\n * to let others read the file).\n */\n async writeFile(input: WriteFileOptions): Promise<{ stat: FileStat; manifest: FileManifest }> {\n if (!input?.spaceId) {\n throw new Error(\"client.storage.writeFile: `spaceId` is required (files live in a SharedSpace).\");\n }\n const fs = this.fs();\n const { manifest, stat } = await fs.writeFileToShards({\n data: input.data,\n metadata: input.metadata,\n });\n // Authoritative, metered write: the manifest into the space's gated store.\n await this.space().writeFileManifest(input.spaceId, manifest);\n // Best-effort personal discovery mirror (unmetered). A failure here\n // leaves the file intact in the space — log and continue.\n try {\n await this.deps.kv.set<MirrorEntry>(MIRROR_COLLECTION, manifest.id, {\n spaceId: input.spaceId,\n manifest,\n });\n } catch (err) {\n console.warn(\"client.storage.writeFile: discovery mirror failed (file still written):\", err);\n }\n return { stat, manifest };\n }\n\n /** Read a file from its space (resolves the manifest, then the shards). */\n async readFile(spaceId: string, fileId: string): Promise<{ data: Uint8Array; stat: FileStat }> {\n return this.fs().readFile(spaceId, fileId);\n }\n\n /**\n * Read a file straight from a manifest — the capability path. No space\n * membership needed; this is how a shared file is opened.\n */\n async readByManifest(manifest: FileManifest): Promise<{ data: Uint8Array; stat: FileStat }> {\n return this.fs().readFileFromShards(manifest);\n }\n\n /**\n * List files. With no argument, returns the caller's own shared files from\n * the personal mirror; with `{ spaceId }`, lists that space's files.\n */\n async listFiles(opts?: { spaceId?: string }): Promise<FileStat[]> {\n if (opts?.spaceId) return this.space().listFiles(opts.spaceId);\n const ids = await this.deps.kv.list(MIRROR_COLLECTION);\n const entries = await Promise.all(\n ids.map((id) => this.deps.kv.get<MirrorEntry>(MIRROR_COLLECTION, id)),\n );\n return entries\n .filter((e): e is MirrorEntry => Boolean(e?.manifest))\n .map((e) => manifestToStat(e.manifest));\n }\n\n /** Delete a file from its space and remove the personal mirror entry. */\n async deleteFile(spaceId: string, fileId: string): Promise<boolean> {\n const existed = await this.fs().deleteFile(spaceId, fileId);\n try {\n await this.deps.kv.delete(MIRROR_COLLECTION, fileId);\n } catch {\n // mirror cleanup is best-effort\n }\n return existed;\n }\n\n /** Read a manifest verbatim (e.g. to share a file). */\n async getManifest(spaceId: string, fileId: string): Promise<FileManifest> {\n return this.fs().readManifest(spaceId, fileId);\n }\n\n // -------------------------------------------------------------------------\n // Internals — lazily built so an unauthenticated client is cheap to create.\n // -------------------------------------------------------------------------\n\n private fs(): FileStorage {\n if (!this.fileStorage) {\n this.fileStorage = new FileStorage({\n shards: this.shards(),\n space: this.space(),\n rsWasmModule: this.deps.rsWasmModule,\n });\n }\n return this.fileStorage;\n }\n\n private _shards: ShardClient | null = null;\n private shards(): ShardClient {\n // Global, content-addressed shard store. The credential-stamping fetch\n // attaches the app key so PUTs are attributed + quota-gated; GETs are open.\n if (!this._shards) {\n this._shards = new ShardClient({\n baseUrl: this.deps.baseUrl,\n pathPrefix: \"/api/shards\",\n fetch: this.deps.http.fetch,\n });\n }\n return this._shards;\n }\n\n private _space: SharedSpaceClient | null = null;\n private space(): SharedSpaceClient {\n if (!this._space) {\n this._space = new SharedSpaceClient({\n baseUrl: this.deps.baseUrl,\n fetch: this.deps.http.fetch,\n });\n }\n return this._space;\n }\n}\n\nexport default StorageNamespace;\n","/**\n * An end-to-end-encrypted communication session for one local identity\n * (`myId`) talking to an arbitrary set of peers. Wraps `KeyStore` +\n * per-pair `DoubleRatchet` instances and owns the protocol bookkeeping\n * (handshake reciprocation, dedup, role assignment, broadcast fan-out,\n * recipient filtering) so application code doesn't have to.\n *\n * Transport-agnostic by design: the Session never touches a WebSocket\n * (or HTTP, or anything else). Application code:\n * - calls `session.encrypt(text)` and gets back an array of frames it\n * ships over whatever transport it has;\n * - calls `session.receive(frame)` with each inbound frame and acts on\n * the typed result (plaintext, handshake-done, ignored).\n *\n * Frames are plain JSON objects with the same shape the existing chat\n * protocol uses (`{ keyExchange: {...} }` and `{ cipherMessage: {...} }`),\n * so this can drop into a chat app without changing the wire format.\n */\n\nimport { KeyStore } from \"../crypto/KeyStore\";\nimport { DoubleRatchet } from \"../crypto/DoubleRatchet\";\nimport type { CipherMessage } from \"../crypto/types.d\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface SessionOptions {\n /** This client's identifier (e.g. username / DID / public-key string). */\n myId: string;\n}\n\n/** A handshake frame the application ships to peers (or receives from them). */\nexport interface KeyExchangeFrame {\n type: \"handshake\" | \"update\";\n userId: string;\n /** Base64-encoded JWK of the sender's ECDH public key. */\n ecdhPublicKey: string;\n /** Base64-encoded JWK of the sender's ECDSA public key. */\n ecdsaPublicKey: string;\n}\n\n/** A ciphertext frame, addressed to exactly one peer. */\nexport interface CipherFrame {\n cipherMessage: CipherMessage;\n}\n\n/** Anything inbound the application might hand to `session.receive()`. */\nexport type IncomingFrame =\n | { keyExchange: KeyExchangeFrame }\n | { cipherMessage: CipherMessage }\n // Permits passing arbitrary frames; Session returns `kind: 'ignored'`.\n | Record<string, unknown>;\n\n/** Outcome of feeding one frame through `session.receive()`. */\nexport type ReceiveResult =\n | {\n kind: \"plaintext\";\n /** The sender's id (from the cipherMessage header). */\n from: string;\n /** Decrypted message body. */\n text: string;\n /** The original cipherMessage, for callers that want it. */\n cipherMessage: CipherMessage;\n }\n | {\n kind: \"handshake\";\n /** The peer whose handshake was just processed. */\n peerId: string;\n /**\n * If non-null, the application MUST send this frame back to the peer\n * (e.g. broadcast on the room WebSocket). It's our reciprocation —\n * giving the peer our public keys so they can verify our messages.\n *\n * The Session dedups internally: we only emit this on the first\n * handshake we process for a given peer in this Session's lifetime.\n */\n outbound: { keyExchange: KeyExchangeFrame } | null;\n }\n | {\n kind: \"ignored\";\n /** Why we ignored the frame (debugging aid; not for branching on). */\n reason: string;\n };\n\n// ---------------------------------------------------------------------------\n// EncryptedSession\n// ---------------------------------------------------------------------------\n\nexport class EncryptedSession {\n private readonly myId: string;\n private readonly keyStore: KeyStore;\n\n /** One DoubleRatchet per peer pair. */\n private readonly ratchets = new Map<string, DoubleRatchet>();\n\n /** Peers we've already sent our keyExchange to in this Session. */\n private readonly sentHandshakeTo = new Set<string>();\n\n /** Resolved when own keys are generated and ready to use. */\n private readonly _ready: Promise<void>;\n private _resolveReady!: () => void;\n private _initialized = false;\n\n constructor(opts: SessionOptions) {\n if (!opts || !opts.myId) {\n throw new Error(\"EncryptedSession: `myId` is required\");\n }\n this.myId = opts.myId;\n this.keyStore = KeyStore.getInstance();\n this._ready = new Promise<void>((resolve) => {\n this._resolveReady = resolve;\n });\n }\n\n /** A promise that resolves once `initialize()` has completed. */\n get ready(): Promise<void> {\n return this._ready;\n }\n\n /** Our local identifier. */\n get id(): string {\n return this.myId;\n }\n\n /**\n * Generate this client's ECDH + ECDSA keypair (idempotent — safe to call\n * multiple times across reconnects; only the first call generates).\n */\n async initialize(): Promise<void> {\n if (this._initialized) return;\n if (!this.keyStore.getKeyPair(this.myId)) {\n await this.keyStore.generateOwnKeyPair(this.myId);\n }\n this._initialized = true;\n this._resolveReady();\n }\n\n /**\n * Build the keyExchange frame this client should send to peers when it\n * comes online. Application is responsible for actually transmitting it\n * (e.g. ws.send(JSON.stringify(frame))).\n */\n async getOwnKeyExchange(): Promise<{ keyExchange: KeyExchangeFrame }> {\n await this._ready;\n const ownEcdh = this.keyStore.getKeyPair(this.myId);\n const ownEcdsa = this.keyStore.getAuthKeyPair(this.myId);\n if (!ownEcdh || !ownEcdsa) {\n throw new Error(\"EncryptedSession.getOwnKeyExchange: keys not initialized\");\n }\n return {\n keyExchange: {\n type: \"handshake\",\n userId: this.myId,\n ecdhPublicKey: await exportJwkBase64(ownEcdh.publicKey),\n ecdsaPublicKey: await exportJwkBase64(ownEcdsa.publicKey),\n },\n };\n }\n\n /**\n * Encrypt a plaintext to every peer we currently have a ratchet for, and\n * return one cipherMessage frame per recipient. The application sends\n * each frame over its transport.\n *\n * If there are no peers yet (or all peers are still mid-handshake), the\n * returned array may be empty — the caller should typically render the\n * outgoing message locally in that case (since there's no one to send\n * it to yet).\n */\n async encrypt(plaintext: string): Promise<CipherFrame[]> {\n await this._ready;\n const frames: CipherFrame[] = [];\n for (const peerId of this.ratchets.keys()) {\n const ratchet = this.ratchets.get(peerId)!;\n const sessionId = this._sessionIdFor(peerId);\n const cipherMessage = await ratchet.encrypt(\n plaintext,\n /* newDhKey */ false,\n this.myId,\n peerId,\n sessionId,\n \"specific\",\n );\n frames.push({ cipherMessage });\n }\n return frames;\n }\n\n /**\n * Hand an inbound frame to the session. Returns a typed result the\n * application acts on.\n *\n * - `kind: 'plaintext'` — decrypted; render `result.text`\n * - `kind: 'handshake'` — a peer's keys are now stored, and if\n * `result.outbound` is set, send it\n * - `kind: 'ignored'` — not for us, malformed, duplicate, etc.\n *\n * Calling code should always handle `'ignored'` (no UI side effect).\n */\n async receive(frame: IncomingFrame): Promise<ReceiveResult> {\n await this._ready;\n\n // -- handshake frame -----------------------------------------------------\n if (isKeyExchangeFrame(frame)) {\n const kx = frame.keyExchange;\n const peerId = kx.userId;\n\n if (peerId === this.myId) {\n return { kind: \"ignored\", reason: \"own keyExchange echo\" };\n }\n\n const isNew = !this.ratchets.has(peerId);\n\n // (Re-)store the peer's pubkeys + (re-)build the ratchet if needed.\n const peerEcdh = await importJwkBase64(kx.ecdhPublicKey, \"ECDH\");\n const peerEcdsa = await importJwkBase64(kx.ecdsaPublicKey, \"ECDSA\");\n await this.keyStore.storeRemotePublicKeys(peerId, peerEcdh, peerEcdsa);\n\n if (isNew) {\n const isClient = this.myId < peerId;\n const ratchet = new DoubleRatchet(this.myId, peerId, \"specific\", isClient);\n await ratchet.initializeSession(isClient);\n this.ratchets.set(peerId, ratchet);\n }\n\n // Reciprocate exactly once per peer per session lifetime.\n let outbound: { keyExchange: KeyExchangeFrame } | null = null;\n if (isNew && !this.sentHandshakeTo.has(peerId)) {\n outbound = await this.getOwnKeyExchange();\n this.sentHandshakeTo.add(peerId);\n }\n\n return { kind: \"handshake\", peerId, outbound };\n }\n\n // -- ciphertext frame ----------------------------------------------------\n if (isCipherFrame(frame)) {\n const cipherMessage = frame.cipherMessage;\n const header = cipherMessage?.header;\n if (!header) {\n return { kind: \"ignored\", reason: \"cipherMessage has no header\" };\n }\n if (header.senderId === this.myId) {\n return { kind: \"ignored\", reason: \"own outbound echo\" };\n }\n if (header.recipientId && header.recipientId !== this.myId) {\n return { kind: \"ignored\", reason: \"addressed to a different peer\" };\n }\n\n const ratchet = this.ratchets.get(header.senderId);\n if (!ratchet) {\n return {\n kind: \"ignored\",\n reason: `no ratchet with sender ${header.senderId} (handshake hasn't completed)`,\n };\n }\n\n const isClient = this.myId < header.senderId;\n let text: string;\n try {\n text = await ratchet.decrypt(cipherMessage, isClient);\n } catch (err) {\n // DoubleRatchet's wallclock-based replay-protection check throws\n // \"CipherMessage too old, possible replay attack\" for any frame\n // older than 5 minutes. Real replays still fail downstream because\n // the message key has been consumed; the wallclock check is a\n // defense-in-depth heuristic, not a security boundary. Treating it\n // as `ignored` lets the channel survive legacy backlog replays and\n // CF WS-idle-timeout reconnect cycles without spamming the\n // channel's ERROR stream.\n const msg = err instanceof Error ? err.message : String(err);\n if (msg.includes(\"too old\") || msg.includes(\"replay attack\")) {\n return { kind: \"ignored\", reason: `stale cipherMessage rejected: ${msg}` };\n }\n throw err;\n }\n return { kind: \"plaintext\", from: header.senderId, text, cipherMessage };\n }\n\n return { kind: \"ignored\", reason: \"unknown frame type\" };\n }\n\n // -- introspection ---------------------------------------------------------\n\n /** List of peer ids we have an established ratchet for. */\n peers(): string[] {\n return Array.from(this.ratchets.keys());\n }\n\n /** Has the handshake completed for this peer? */\n hasRatchetFor(peerId: string): boolean {\n return this.ratchets.has(peerId);\n }\n\n /**\n * Tear down a peer's ratchet (e.g. when they leave the room). The peer's\n * stored keys remain in `KeyStore` so a fresh handshake can be set up\n * later without re-fetching them, but the ratchet state is dropped.\n */\n forgetPeer(peerId: string): void {\n this.ratchets.delete(peerId);\n this.sentHandshakeTo.delete(peerId);\n }\n\n // -- internals -------------------------------------------------------------\n\n /** Deterministic per-pair session id — same string on both sides. */\n private _sessionIdFor(peerId: string): string {\n return [this.myId, peerId].sort().join(\":\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers — JWK <-> base64 string for key transport\n// ---------------------------------------------------------------------------\n\nasync function exportJwkBase64(key: CryptoKey): Promise<string> {\n const jwk = await crypto.subtle.exportKey(\"jwk\", key);\n return btoa(JSON.stringify(jwk));\n}\n\nasync function importJwkBase64(\n b64: string,\n type: \"ECDH\" | \"ECDSA\",\n): Promise<CryptoKey> {\n const jwk = JSON.parse(atob(b64));\n const algorithm =\n type === \"ECDH\"\n ? { name: \"ECDH\", namedCurve: \"P-384\" }\n : { name: \"ECDSA\", namedCurve: \"P-384\" };\n const usages: KeyUsage[] = type === \"ECDH\" ? [] : [\"verify\"];\n return await crypto.subtle.importKey(\"jwk\", jwk, algorithm, true, usages);\n}\n\n// ---------------------------------------------------------------------------\n// Type guards\n// ---------------------------------------------------------------------------\n\nfunction isKeyExchangeFrame(\n frame: IncomingFrame,\n): frame is { keyExchange: KeyExchangeFrame } {\n const kx = (frame as { keyExchange?: unknown }).keyExchange;\n if (!kx || typeof kx !== \"object\") return false;\n const k = kx as Partial<KeyExchangeFrame>;\n return (\n typeof k.userId === \"string\" &&\n typeof k.ecdhPublicKey === \"string\" &&\n typeof k.ecdsaPublicKey === \"string\"\n );\n}\n\nfunction isCipherFrame(\n frame: IncomingFrame,\n): frame is { cipherMessage: CipherMessage } {\n const cm = (frame as { cipherMessage?: unknown }).cipherMessage;\n if (!cm || typeof cm !== \"object\") return false;\n const m = cm as Partial<CipherMessage>;\n return Boolean(m.header && m.ciphertext && m.nonce);\n}\n","/**\n * BroadcastChannel — a turnkey end-to-end encrypted channel for multi-peer\n * \"room\"-style apps (e.g. a chat). Wires together:\n *\n * - `WSTransport` for socket lifecycle, reconnect, and offline frame queue\n * - `EncryptedSession` for per-peer Double Ratchet state, handshake\n * reciprocation, fan-out encryption, and recipient filtering\n *\n * The host app only deals with high-level events and method calls; it never\n * touches `new WebSocket(...)` or builds cipherMessage frames by hand.\n *\n * Wire protocol (kept compatible with the existing chat protocol so this\n * drops into the deployed Accelerator without server changes):\n *\n * outbound: `{ keyExchange: {...} }` — produced by us on `announce()`\n * `{ cipherMessage: {...} }` — produced by `send(text)`,\n * one frame per peer\n * arbitrary JSON — sent via `sendRaw(obj)`\n *\n * inbound: `{ keyExchange: {...} }` — routed into EncryptedSession;\n * emits `peer_handshake`\n * `{ cipherMessage: {...} }` — decrypted; emits `message`\n * anything else — passes through as `raw_frame`\n * (the app decides what to do)\n *\n * **Event scoping.** Unlike `Network`, BroadcastChannel uses a per-instance\n * `EventTarget`, so two channels (e.g. two rooms in the same app) don't\n * cross-contaminate each other's events.\n *\n * Note: this class shadows the `BroadcastChannel` Web API global (cross-tab\n * messaging) only when imported by name. They're unrelated.\n */\n\nimport { EventCoreEvents } from \"../events\";\nimport { WSTransport, WSTransportOptions } from \"../transport\";\nimport { EncryptedSession } from \"./EncryptedSession\";\n\n// ---------------------------------------------------------------------------\n// Event names\n// ---------------------------------------------------------------------------\n\n/**\n * Event names BroadcastChannel emits. Lifecycle events reuse the\n * `EventCoreEvents` string values (`connected`, `disconnected`, etc.) so\n * apps can use shared constants if they want. Channel-specific events are\n * prefixed `channel:` to avoid colliding with other event systems in the\n * same app.\n */\nexport const BroadcastChannelEvents = {\n CONNECTED: EventCoreEvents.CONNECTED,\n DISCONNECTED: EventCoreEvents.DISCONNECTED,\n RECONNECTING: EventCoreEvents.RECONNECTING,\n ERROR: EventCoreEvents.ERROR,\n /** A peer's ratchet is now ready. `detail.peerId` is the peer's id. */\n PEER_HANDSHAKE: \"channel:peer_handshake\",\n /** Decrypted message. `detail` is `{ from, text, cipherMessage }`. */\n MESSAGE: \"channel:message\",\n /** Inbound frame BroadcastChannel didn't recognize. App handles it. */\n RAW_FRAME: \"channel:raw_frame\",\n} as const;\n\nexport type BroadcastChannelEvent = (typeof BroadcastChannelEvents)[keyof typeof BroadcastChannelEvents];\n\nexport interface BroadcastChannelOptions extends WSTransportOptions {\n /** This client's identifier (username, DID, public-key string, etc.). */\n myId: string;\n /**\n * If true (default false), automatically send our keyExchange as soon as\n * the socket is connected. For chat-style apps that send a `{name}` frame\n * first, leave this false and call `announce()` after that handshake.\n */\n autoAnnounce?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// BroadcastChannel\n// ---------------------------------------------------------------------------\n\nexport class BroadcastChannel {\n readonly transport: WSTransport;\n readonly session: EncryptedSession;\n readonly myId: string;\n\n private autoAnnounce: boolean;\n private announced = false;\n\n /** Per-instance EventTarget — events do NOT leak across BroadcastChannels. */\n private events = new EventTarget();\n\n constructor(opts: BroadcastChannelOptions) {\n if (!opts || !opts.myId) {\n throw new Error(\"BroadcastChannel: `myId` is required\");\n }\n this.myId = opts.myId;\n this.autoAnnounce = opts.autoAnnounce ?? false;\n\n this.transport = new WSTransport(opts);\n this.session = new EncryptedSession({ myId: opts.myId });\n\n // Pass-through lifecycle events from the transport. `EventCore.on` is\n // static so it routes back through the shared singleton; we bridge it\n // into our instance-scoped event target.\n this.transport.on(EventCoreEvents.CONNECTED, () => {\n // Reset the announce flag on every (re)connect. CF Workers WebSockets\n // hit an idle timeout and force reconnects; without resetting, the\n // SDK would short-circuit announce() and any peer who joined the\n // room after our last announce would never see our pubkey.\n this.announced = false;\n this.emit(BroadcastChannelEvents.CONNECTED);\n if (this.autoAnnounce) {\n void this.announce();\n }\n });\n this.transport.on(EventCoreEvents.DISCONNECTED, () => {\n this.emit(BroadcastChannelEvents.DISCONNECTED);\n });\n this.transport.on(EventCoreEvents.RECONNECTING, (e: CustomEvent) => {\n this.emit(BroadcastChannelEvents.RECONNECTING, e.detail);\n });\n this.transport.on(EventCoreEvents.ERROR, (e: CustomEvent) => {\n this.emit(BroadcastChannelEvents.ERROR, e.detail);\n });\n\n // Route inbound raw frames through our framing/decryption logic.\n this.transport.on(EventCoreEvents.MESSAGE, (e: CustomEvent) => {\n void this.handleInboundFrame(e.detail as string);\n });\n }\n\n // -- event API -------------------------------------------------------------\n\n /** Subscribe to a channel event. Handler receives a CustomEvent. */\n on(event: BroadcastChannelEvent | string, handler: (e: CustomEvent) => void): void {\n this.events.addEventListener(event, handler as EventListener);\n }\n\n /** Unsubscribe. */\n off(event: BroadcastChannelEvent | string, handler: (e: CustomEvent) => void): void {\n this.events.removeEventListener(event, handler as EventListener);\n }\n\n private emit(event: BroadcastChannelEvent | string, detail?: unknown): void {\n this.events.dispatchEvent(new CustomEvent(event, { detail }));\n }\n\n // -- lifecycle -------------------------------------------------------------\n\n /** Generate our keys (idempotent) and open the WebSocket. */\n async connect(): Promise<void> {\n await this.session.initialize();\n await this.transport.connect();\n }\n\n /** Close the WebSocket and stop reconnecting. */\n disconnect(): void {\n this.transport.disconnect();\n }\n\n /**\n * Send our `keyExchange` frame to the room. Idempotent — only sends on the\n * first call. Call this once your higher-level handshake (e.g. sending a\n * `{name}` identification frame) has completed.\n */\n async announce(): Promise<void> {\n if (this.announced) return;\n this.announced = true;\n const frame = await this.session.getOwnKeyExchange();\n this.transport.send(JSON.stringify(frame));\n }\n\n /**\n * Encrypt `plaintext` to every peer we have a ratchet with, and send each\n * cipherMessage as its own WS frame. Returns the number of peers we sent to\n * (0 if no peers are handshaken yet — in which case the caller should\n * typically render the message locally for the sender and try again later).\n */\n async send(plaintext: string): Promise<number> {\n const frames = await this.session.encrypt(plaintext);\n for (const frame of frames) {\n this.transport.send(JSON.stringify(frame));\n }\n return frames.length;\n }\n\n /**\n * Send an arbitrary JSON-serializable frame as-is. The app uses this for\n * any frame that isn't channel-managed (e.g. a chat's `{name}`, `{file}`,\n * or unencrypted `{message}`).\n */\n sendRaw(frame: unknown): void {\n this.transport.send(JSON.stringify(frame));\n }\n\n // -- introspection ---------------------------------------------------------\n\n /** List of peer ids we have an established ratchet for. */\n peers(): string[] {\n return this.session.peers();\n }\n\n /** Drop a peer's ratchet (e.g. when they leave the room). */\n forgetPeer(peerId: string): void {\n this.session.forgetPeer(peerId);\n }\n\n isConnected(): boolean {\n return this.transport.isConnected();\n }\n\n // -- internals -------------------------------------------------------------\n\n private async handleInboundFrame(raw: string): Promise<void> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n this.emit(BroadcastChannelEvents.ERROR, err);\n return;\n }\n\n if (!parsed || typeof parsed !== \"object\") {\n this.emit(BroadcastChannelEvents.RAW_FRAME, parsed);\n return;\n }\n\n const obj = parsed as Record<string, unknown>;\n\n // Channel-managed: keyExchange & cipherMessage. Anything else is RAW_FRAME.\n if (\"keyExchange\" in obj || \"cipherMessage\" in obj) {\n try {\n const result = await this.session.receive(\n obj as Parameters<typeof this.session.receive>[0],\n );\n if (result.kind === \"handshake\") {\n if (result.outbound) {\n this.transport.send(JSON.stringify(result.outbound));\n }\n this.emit(BroadcastChannelEvents.PEER_HANDSHAKE, { peerId: result.peerId });\n } else if (result.kind === \"plaintext\") {\n this.emit(BroadcastChannelEvents.MESSAGE, {\n from: result.from,\n text: result.text,\n cipherMessage: result.cipherMessage,\n });\n }\n // `ignored` is intentionally swallowed; subscribe to ERROR for bad frames.\n } catch (err) {\n this.emit(BroadcastChannelEvents.ERROR, err);\n }\n return;\n }\n\n this.emit(BroadcastChannelEvents.RAW_FRAME, obj);\n }\n}\n\nexport default BroadcastChannel;\n","/**\n * SpaceCipher — pure crypto for the fan-out group-encryption layer.\n *\n * Everything here routes through the canonical primitives in\n * `src/crypto/primitives` (AES-256-GCM, HKDF-SHA256, randomBytes) and the\n * P-384 ECDH `deriveBits` call the Double Ratchet already uses. No new\n * algorithms, no `crypto.subtle` reach-arounds beyond key gen / derive /\n * import-export (which the primitive layer intentionally doesn't cover).\n *\n * Three concerns:\n * 1. Space identity — a P-384 ECDH keypair; the encoded public key is the\n * space's id.\n * 2. Group key distribution — ECIES wrap/unwrap of `K_space` to a member's\n * identity ECDH public key (ephemeral-static ECDH → HKDF → AES-GCM).\n * 3. Message sealing — encrypt the serialized `Message` once under the\n * epoch's group key.\n *\n * Public keys are transported as base64url-encoded JWK, matching the JWK\n * transport convention already used in `EncryptedSession`.\n */\n\nimport { Message } from \"../messaging/Message\";\nimport {\n encryptAesGcm,\n decryptAesGcm,\n deriveBitsHkdf,\n randomBytes,\n getSubtle,\n AES_GCM_KEY_BYTES,\n AES_GCM_IV_BYTES,\n} from \"../crypto/primitives\";\nimport {\n toBase64,\n fromBase64,\n toBase64Url,\n fromBase64Url,\n utf8Encode,\n utf8Decode,\n} from \"../utilities\";\nimport type { WrappedKey } from \"./types\";\n\n/** HKDF label binding the wrap key to this protocol + version. */\nconst WRAP_INFO = \"muhkoo/space/keywrap/v1\";\n/** Algorithm tag stamped into every WrappedKey. */\nconst WRAP_ALG = \"ECDH-P384/HKDF-SHA256/AES-256-GCM\";\n/** Bits in a P-384 ECDH shared secret. */\nconst P384_BITS = 384;\n\nconst ECDH_PARAMS: EcKeyGenParams = { name: \"ECDH\", namedCurve: \"P-384\" };\n\n// ---------------------------------------------------------------------------\n// Public-key transport (base64url JWK)\n// ---------------------------------------------------------------------------\n\n/** Encode an ECDH public `CryptoKey` as a base64url JWK string. */\nexport async function exportEcdhPublicKey(key: CryptoKey): Promise<string> {\n const jwk = await getSubtle().exportKey(\"jwk\", key);\n return toBase64Url(utf8Encode(JSON.stringify(jwk)));\n}\n\n/** Decode a base64url JWK string back into an ECDH public `CryptoKey`. */\nexport async function importEcdhPublicKey(encoded: string): Promise<CryptoKey> {\n const jwk = JSON.parse(utf8Decode(fromBase64Url(encoded)));\n // Public keys carry no usages.\n return getSubtle().importKey(\"jwk\", jwk, ECDH_PARAMS, true, []);\n}\n\n/** The space's id is just its encoded ECDH public key. */\nexport const encodeSpaceId = exportEcdhPublicKey;\n\n// ---------------------------------------------------------------------------\n// Sender authentication (ECDSA P-384, matching the Double Ratchet path).\n// A fan-out message is signed by its sender's identity ECDSA key so receivers\n// can verify authorship end-to-end — independent of the relay, which only\n// stamps `source` server-side. SHA-256 hash to match `DoubleRatchet`.\n// ---------------------------------------------------------------------------\n\nconst ECDSA_PARAMS: EcKeyImportParams = { name: \"ECDSA\", namedCurve: \"P-384\" };\nconst ECDSA_SIGN: EcdsaParams = { name: \"ECDSA\", hash: \"SHA-256\" };\n\n/** Encode an ECDSA public `CryptoKey` as a base64url JWK string. */\nexport async function exportEcdsaPublicKey(key: CryptoKey): Promise<string> {\n const jwk = await getSubtle().exportKey(\"jwk\", key);\n return toBase64Url(utf8Encode(JSON.stringify(jwk)));\n}\n\n/** Decode a base64url JWK string back into an ECDSA verify-only public key. */\nexport async function importEcdsaPublicKey(encoded: string): Promise<CryptoKey> {\n const jwk = JSON.parse(utf8Decode(fromBase64Url(encoded)));\n return getSubtle().importKey(\"jwk\", jwk, ECDSA_PARAMS, true, [\"verify\"]);\n}\n\n/**\n * Canonical bytes a sender signs (and a receiver re-derives). Binds the claimed\n * sender + routing + the sealed ciphertext, so a relay can't relabel `source`\n * and a member can't reuse another's ciphertext under a new envelope.\n */\nexport function canonicalMessage(fields: {\n source: string;\n target: string;\n subject: string;\n epoch: number;\n iv: string;\n ciphertext: string;\n}): string {\n return [fields.source, fields.target, fields.subject, fields.epoch, fields.iv, fields.ciphertext].join(\"\\n\");\n}\n\n/** Sign the canonical bytes with the sender's ECDSA identity private key. */\nexport async function signSpaceMessage(canonical: string, ecdsaPriv: CryptoKey): Promise<string> {\n const sig = await getSubtle().sign(ECDSA_SIGN, ecdsaPriv, utf8Encode(canonical));\n return toBase64(new Uint8Array(sig));\n}\n\n/** Verify a signature over the canonical bytes against the sender's ECDSA key. */\nexport async function verifySpaceMessage(canonical: string, sigB64: string, ecdsaPub: CryptoKey): Promise<boolean> {\n try {\n return await getSubtle().verify(ECDSA_SIGN, ecdsaPub, fromBase64(sigB64), utf8Encode(canonical));\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Space identity\n// ---------------------------------------------------------------------------\n\nexport interface SpaceIdentity {\n /** Encoded public key — the space's logical id. */\n id: string;\n publicKey: CryptoKey;\n privateKey: CryptoKey;\n}\n\n/** Generate a fresh space identity keypair (P-384 ECDH). */\nexport async function generateSpaceIdentity(): Promise<SpaceIdentity> {\n const kp = await getSubtle().generateKey(ECDH_PARAMS, true, [\"deriveBits\"]);\n const id = await encodeSpaceId(kp.publicKey);\n return { id, publicKey: kp.publicKey, privateKey: kp.privateKey };\n}\n\n// ---------------------------------------------------------------------------\n// Group key\n// ---------------------------------------------------------------------------\n\n/** Mint a fresh 256-bit group key for an epoch. */\nexport function generateSpaceKey(): Uint8Array {\n return randomBytes(AES_GCM_KEY_BYTES);\n}\n\n// ---------------------------------------------------------------------------\n// ECIES wrap / unwrap of the group key\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap `kSpace` for `recipientEcdhPub` using an ephemeral ECDH keypair.\n * The HKDF salt binds the wrap key to `epoch`, so a wrap minted for one epoch\n * cannot be replayed to unwrap a different epoch's blob.\n */\nexport async function wrapSpaceKey(\n kSpace: Uint8Array,\n epoch: number,\n recipientEcdhPub: CryptoKey,\n): Promise<WrappedKey> {\n const eph = await getSubtle().generateKey(ECDH_PARAMS, true, [\"deriveBits\"]);\n const shared = new Uint8Array(\n await getSubtle().deriveBits(\n { name: \"ECDH\", public: recipientEcdhPub },\n eph.privateKey,\n P384_BITS,\n ),\n );\n const wrapKey = await deriveBitsHkdf(\n shared,\n WRAP_INFO,\n AES_GCM_KEY_BYTES,\n utf8Encode(`epoch:${epoch}`),\n );\n const iv = randomBytes(AES_GCM_IV_BYTES);\n const ciphertext = await encryptAesGcm(wrapKey, iv, kSpace);\n return {\n epoch,\n ephemeralPub: await exportEcdhPublicKey(eph.publicKey),\n iv: toBase64(iv),\n ciphertext: toBase64(ciphertext),\n alg: WRAP_ALG,\n };\n}\n\n/**\n * Unwrap a {@link WrappedKey} using the recipient's identity ECDH private key.\n * Throws (GCM tag failure) on the wrong private key or a tampered blob.\n */\nexport async function unwrapSpaceKey(\n wrapped: WrappedKey,\n ownEcdhPriv: CryptoKey,\n): Promise<Uint8Array> {\n const ephPub = await importEcdhPublicKey(wrapped.ephemeralPub);\n const shared = new Uint8Array(\n await getSubtle().deriveBits(\n { name: \"ECDH\", public: ephPub },\n ownEcdhPriv,\n P384_BITS,\n ),\n );\n const wrapKey = await deriveBitsHkdf(\n shared,\n WRAP_INFO,\n AES_GCM_KEY_BYTES,\n utf8Encode(`epoch:${wrapped.epoch}`),\n );\n return decryptAesGcm(wrapKey, fromBase64(wrapped.iv), fromBase64(wrapped.ciphertext));\n}\n\n// ---------------------------------------------------------------------------\n// Message sealing\n// ---------------------------------------------------------------------------\n\n/** Seal an already-serialized message string under the group key. */\nexport async function sealSerialized(\n kSpace: Uint8Array,\n serialized: string,\n): Promise<{ iv: string; ciphertext: string }> {\n const iv = randomBytes(AES_GCM_IV_BYTES);\n const ciphertext = await encryptAesGcm(kSpace, iv, utf8Encode(serialized));\n return { iv: toBase64(iv), ciphertext: toBase64(ciphertext) };\n}\n\n/**\n * Open a sealed payload back into its serialized message string. Throws (GCM\n * tag failure) on the wrong group key or a tampered ciphertext.\n */\nexport async function openSerialized(\n kSpace: Uint8Array,\n iv: string,\n ciphertext: string,\n): Promise<string> {\n const plaintext = await decryptAesGcm(kSpace, fromBase64(iv), fromBase64(ciphertext));\n return utf8Decode(plaintext);\n}\n\n/** Seal a `Message` once under the group key. Returns base64 iv + ciphertext. */\nexport async function sealMessage(\n kSpace: Uint8Array,\n msg: Message,\n): Promise<{ iv: string; ciphertext: string }> {\n return sealSerialized(kSpace, msg.serialize());\n}\n\n/**\n * Open a sealed message back into a `Message`. Throws (GCM tag failure) on the\n * wrong group key or a tampered ciphertext.\n */\nexport async function openMessage(\n kSpace: Uint8Array,\n iv: string,\n ciphertext: string,\n): Promise<Message> {\n return Message.deserialize(await openSerialized(kSpace, iv, ciphertext));\n}\n","/**\n * SpacePacketCipher — the {@link PacketCipher} that seals packets with a\n * space's group key instead of a per-peer Double Ratchet.\n *\n * It pulls the active epoch's key from an {@link EpochKeyProvider} (the\n * SpaceKeyring), so this adapter stays decoupled from the keyring's transport\n * and caching concerns — it only needs \"what key seals epoch N\".\n */\n\nimport type { PacketCipher, PacketHeaders, SealedHeaders } from \"../network/PacketCipher\";\nimport { sealSerialized, openSerialized } from \"./SpaceCipher\";\n\n/** Minimal view of the keyring the cipher needs. */\nexport interface EpochKeyProvider {\n /** Epoch new messages are sealed under (advances on rotation). */\n currentEpoch(): number;\n /** The 32-byte group key for an epoch, or undefined if we don't hold it. */\n keyForEpoch(epoch: number): Uint8Array | undefined;\n}\n\nexport class SpacePacketCipher implements PacketCipher {\n constructor(\n private readonly keys: EpochKeyProvider,\n private readonly contentType?: string,\n ) {}\n\n async seal(serializedMessage: string): Promise<SealedHeaders> {\n const epoch = this.keys.currentEpoch();\n const key = this.keys.keyForEpoch(epoch);\n if (!key) {\n throw new Error(`SpacePacketCipher: no group key for epoch ${epoch}`);\n }\n const { iv, ciphertext } = await sealSerialized(key, serializedMessage);\n const headers: SealedHeaders = { spaceSealed: true, epoch, iv, ciphertext };\n if (this.contentType) headers.contentType = this.contentType;\n return headers;\n }\n\n handles(headers: PacketHeaders): boolean {\n return headers?.spaceSealed === true &&\n typeof headers?.iv === \"string\" &&\n typeof headers?.ciphertext === \"string\";\n }\n\n /** Returns null for epochs we don't hold (surfaced as undecryptable). */\n async open(headers: PacketHeaders): Promise<string | null> {\n if (!this.handles(headers)) return null;\n const epoch = Number(headers!.epoch);\n const key = this.keys.keyForEpoch(epoch);\n if (!key) return null;\n return openSerialized(key, headers!.iv as string, headers!.ciphertext as string);\n }\n}\n","/**\n * `Space` — a client handle for one shared space.\n *\n * A space is the unit everything is built on. It carries:\n * - **realtime transport** over a {@link BroadcastChannel} (group handshake,\n * roster frames, raw-frame passthrough);\n * - **fan-out group messaging** — `Message`s sealed once with the space's\n * group key (via {@link SpacePacketCipher}), wrapped in a cleartext\n * {@link Packet} envelope, broadcast AND persisted by the server as\n * history (the `spaceMessage` frame);\n * - **room-scoped file storage** via {@link FileStorage} over the shard\n * endpoint;\n * - **legacy per-peer Double Ratchet messaging** (`send`/`announce`) for the\n * ephemeral, no-history path — unchanged so existing callers (the chat hook\n * reached via `client.message.room(name)`) keep working.\n *\n * `Space` was formerly `Room`; `Room` remains exported as an alias. The\n * fan-out methods (`sendMessage`/`onMessage`/`history`/`join`/`admit`/`rotate`)\n * require a {@link SpaceKeyring} dep; without one only the transport + DR +\n * file surface is available.\n */\n\nimport { BroadcastChannel, BroadcastChannelEvents } from \"../sessions/BroadcastChannel\";\nimport { FileStorage } from \"../storage/FileStorage\";\nimport { ShardClient } from \"../storage/transport/ShardClient\";\nimport type { FileManifest, FileStat } from \"../storage/types\";\nimport { Message } from \"../messaging/Message\";\nimport { Packet } from \"../messaging/Packet\";\nimport { SpacePacketCipher } from \"./SpacePacketCipher\";\nimport type { SpaceKeyring } from \"./SpaceKeyring\";\nimport { canonicalMessage, signSpaceMessage, verifySpaceMessage } from \"./SpaceCipher\";\nimport { KeyStore } from \"../crypto/KeyStore\";\nimport type { JoinRequest, HistoryPolicy } from \"./types\";\n\ntype Listener = (e: CustomEvent) => void;\n\nexport interface SpaceFileMetadata {\n name: string;\n type: string;\n path?: string;\n lastModified?: number;\n}\n\n/** A decrypted inbound fan-out message. */\nexport interface SpaceMessageEvent {\n from: string;\n channel: string;\n epoch: number;\n contentType?: string;\n /**\n * Server storage handle — the monotonic server timestamp this message is\n * persisted under (`msg:<handle>`). Stable across history replay; pass it to\n * {@link Space.editMessage} / {@link Space.deleteMessage} to mutate the\n * persisted entry. Carried on edit events too (same handle as the original).\n */\n handle: number;\n message: Message;\n}\n\n/**\n * An inbound ephemeral signal — an application broadcast the server relays to\n * the room but never persists (no history). Rides the generic `pub` relay:\n * `subject` is an app-defined routing key, `data` is opaque app JSON, and\n * `from` is the server-authenticated sender. Typing indicators, presence pings,\n * live cursors, etc. are built on top of this in the app layer — the SDK and\n * server stay domain-agnostic.\n */\nexport interface EphemeralEvent {\n /** Server-stamped authenticated sender. */\n from: string;\n /** Application-defined routing key (e.g. \"typing\"). */\n subject: string;\n /** Opaque application payload. */\n data: unknown;\n}\n\n/** A server-authoritative deletion of the persisted message at `handle`. */\nexport interface MessageDeletedEvent {\n handle: number;\n}\n\nexport interface SpaceDeps {\n /** Transport room id. For fan-out spaces this is the encoded space pubkey. */\n name: string;\n wsBaseUrl: string;\n httpBaseUrl: string;\n /** Header-injecting fetch from the client's HttpClient. */\n fetch: typeof fetch;\n /** Resolves the user id used for the ratchet / member id (signed-in username). */\n myId: () => string;\n /** Resolves a short-lived WS upgrade ticket (or null when keyless). */\n fetchTicket: () => Promise<string | null>;\n /** Optional group-key keyring — required for the fan-out methods. */\n keyring?: SpaceKeyring;\n /** History policy for this space (advisory; defaults to static). */\n historyPolicy?: HistoryPolicy;\n /**\n * When true (default), a connected member that holds the group key\n * automatically wraps it for any newcomer that posts a join request —\n * the \"any online key-holder admits\" model. Set false to gate membership\n * yourself via `onJoinRequest` + `admit`.\n */\n autoAdmit?: boolean;\n /**\n * Test seam — defaults to constructing a real {@link BroadcastChannel}.\n * A test can inject an in-memory channel to exercise the fan-out wire\n * without a live websocket.\n */\n createChannel?: (url: string, myId: string) => SpaceChannelLike;\n}\n\n/** The subset of {@link BroadcastChannel} a {@link Space} drives. */\nexport interface SpaceChannelLike {\n on(event: string, handler: (e: CustomEvent) => void): void;\n off(event: string, handler: (e: CustomEvent) => void): void;\n connect(): Promise<void>;\n disconnect(): void;\n announce(): Promise<void>;\n send(plaintext: string): Promise<number>;\n sendRaw(frame: unknown): void;\n peers?(): string[];\n isConnected?(): boolean;\n}\n\nexport class Space {\n readonly name: string;\n readonly historyPolicy: HistoryPolicy;\n private channel: SpaceChannelLike | null = null;\n private readonly pending: Array<[string, Listener]> = [];\n private readonly cipher: SpacePacketCipher | null;\n /** Per-instance event bus for fan-out events (isolated across spaces). */\n private readonly events = new EventTarget();\n private rawWired = false;\n\n constructor(private readonly deps: SpaceDeps) {\n this.name = deps.name;\n this.historyPolicy = deps.historyPolicy ?? \"static\";\n this.cipher = deps.keyring ? new SpacePacketCipher(deps.keyring) : null;\n }\n\n /** The encoded space id (same as the transport name for fan-out spaces). */\n get id(): string {\n return this.name;\n }\n\n /** The keyring backing this space's group keys, if any. */\n get keyring(): SpaceKeyring | undefined {\n return this.deps.keyring;\n }\n\n // -- transport -------------------------------------------------------------\n\n /** Open the space websocket (resolves the ticket + identity lazily). */\n async connect(): Promise<void> {\n if (!this.channel) {\n // The WS upgrade ticket is single-use + short-TTL, so a reconnect\n // must mint a FRESH one — otherwise the socket drops (idle timeout,\n // network blip) and never comes back. `buildUrl` is handed to the\n // transport as a `urlProvider` it calls before each reconnect.\n const buildUrl = async () => {\n const ticket = await this.deps.fetchTicket();\n return (\n `${this.deps.wsBaseUrl}/api/spaces/${encodeURIComponent(this.name)}/websocket` +\n (ticket ? `?ticket=${encodeURIComponent(ticket)}` : \"\")\n );\n };\n const url = await buildUrl();\n this.channel = this.deps.createChannel\n ? this.deps.createChannel(url, this.deps.myId())\n : new BroadcastChannel({\n url,\n myId: this.deps.myId(),\n autoAnnounce: false,\n urlProvider: buildUrl,\n // Keep recovering across network flaps (each attempt mints a\n // fresh ticket); teardown calls disconnect() which stops it.\n maxReconnectAttempts: 0,\n });\n for (const [event, handler] of this.pending) this.channel.on(event, handler);\n this.pending.length = 0;\n // Fan-out spaces drive their own `{name}` handshake + frame routing.\n // Legacy (keyring-less) callers wire these themselves, so leave that\n // path byte-for-byte unchanged.\n if (this.deps.keyring) {\n this.channel.on(BroadcastChannelEvents.CONNECTED, () => {\n this.channel?.sendRaw({ name: this.deps.myId() });\n });\n this.wireFanout();\n }\n }\n await this.channel.connect();\n }\n\n disconnect(): void {\n this.channel?.disconnect();\n }\n\n /** Subscribe to a raw channel event. Buffered until `connect()` if early. */\n on(event: string, handler: Listener): void {\n if (this.channel) this.channel.on(event, handler);\n else this.pending.push([event, handler]);\n }\n\n off(event: string, handler: Listener): void {\n if (this.channel) this.channel.off(event, handler);\n else {\n const i = this.pending.findIndex(([e, h]) => e === event && h === handler);\n if (i >= 0) this.pending.splice(i, 1);\n }\n }\n\n // -- legacy Double Ratchet path (unchanged) --------------------------------\n\n /** Advertise our keyExchange to the room (idempotent per connection). */\n announce(): Promise<void> {\n return this.channel ? this.channel.announce() : Promise.resolve();\n }\n\n /** E2E-encrypt `text` to every peer via the Double Ratchet (no history). */\n send(text: string): Promise<number> {\n return this.channel ? this.channel.send(text) : Promise.resolve(0);\n }\n\n /** Send an arbitrary JSON frame (e.g. the `{name}` handshake). */\n sendRaw(frame: unknown): void {\n this.channel?.sendRaw(frame);\n }\n\n peers(): string[] {\n return this.channel?.peers ? this.channel.peers() : [];\n }\n\n isConnected(): boolean {\n return this.channel?.isConnected ? this.channel.isConnected() : false;\n }\n\n /** The underlying channel, for advanced use. `null` before `connect()`. */\n get raw(): SpaceChannelLike | null {\n return this.channel;\n }\n\n // -- fan-out group messaging -----------------------------------------------\n\n /**\n * Seal `payload` once with the current group key and broadcast it as a\n * persisted `spaceMessage`. Requires a keyring.\n */\n async sendMessage(\n payload: unknown,\n opts: { channel?: string; contentType?: string } = {},\n ): Promise<void> {\n this.sendRaw({ spaceMessage: await this.sealMessage(payload, opts.channel, opts.contentType) });\n }\n\n /** Subscribe to decrypted fan-out messages. Returns an unsubscribe fn. */\n onMessage(handler: (e: SpaceMessageEvent) => void): () => void {\n const listener = (e: Event) => handler((e as CustomEvent<SpaceMessageEvent>).detail);\n this.events.addEventListener(\"message\", listener);\n return () => this.events.removeEventListener(\"message\", listener);\n }\n\n /**\n * Edit a persisted message IN PLACE, addressed by its server\n * {@link SpaceMessageEvent.handle}. Re-seals `payload` and asks the server\n * to replace the stored entry; the server authorizes against the original\n * author. Receivers get an {@link onMessageEdited} event carrying the new\n * content at the same handle. This is a generic persisted-item edit — the\n * server has no notion of what the payload means.\n */\n async editMessage(handle: number, payload: unknown, opts: { channel?: string; contentType?: string } = {}): Promise<void> {\n const spaceMessage = await this.sealMessage(payload, opts.channel, opts.contentType);\n this.sendRaw({ editSpaceMessage: { ts: handle, spaceMessage } });\n }\n\n /**\n * Hard-delete a persisted message by its server {@link SpaceMessageEvent.handle}\n * — the ciphertext is removed from storage. Server authorizes against the\n * original author. Receivers get an {@link onMessageDeleted} event.\n */\n async deleteMessage(handle: number): Promise<void> {\n this.sendRaw({ deleteSpaceMessage: { ts: handle } });\n }\n\n /** Subscribe to in-place edits of persisted messages (new content at the same handle). */\n onMessageEdited(handler: (e: SpaceMessageEvent) => void): () => void {\n const listener = (e: Event) => handler((e as CustomEvent<SpaceMessageEvent>).detail);\n this.events.addEventListener(\"message-edited\", listener);\n return () => this.events.removeEventListener(\"message-edited\", listener);\n }\n\n /** Subscribe to deletions of persisted messages. */\n onMessageDeleted(handler: (e: MessageDeletedEvent) => void): () => void {\n const listener = (e: Event) => handler((e as CustomEvent<MessageDeletedEvent>).detail);\n this.events.addEventListener(\"message-deleted\", listener);\n return () => this.events.removeEventListener(\"message-deleted\", listener);\n }\n\n /**\n * Broadcast an ephemeral, never-persisted signal to the room over the\n * generic `pub` relay. `subject` is an app-defined routing key; `data` is\n * opaque. The transport stays domain-agnostic — app concepts like typing\n * indicators, presence, or live cursors are built on top of this. No-op if\n * the space isn't connected (ephemeral signals aren't worth queuing).\n */\n sendEphemeral(subject: string, data: unknown): void {\n if (!this.isConnected()) return;\n this.sendRaw({ pub: { subject, data } });\n }\n\n /** Subscribe to inbound ephemeral signals. `from` is the authenticated sender. */\n onEphemeral(handler: (e: EphemeralEvent) => void): () => void {\n const listener = (e: Event) => handler((e as CustomEvent<EphemeralEvent>).detail);\n this.events.addEventListener(\"ephemeral\", listener);\n return () => this.events.removeEventListener(\"ephemeral\", listener);\n }\n\n /** Subscribe to inbound join requests (for a key-holder to admit). */\n onJoinRequest(handler: (req: JoinRequest) => void): () => void {\n const listener = (e: Event) => handler((e as CustomEvent<JoinRequest>).detail);\n this.events.addEventListener(\"join-request\", listener);\n return () => this.events.removeEventListener(\"join-request\", listener);\n }\n\n /**\n * Fetch + decrypt persisted history beyond the live backlog.\n * `before` is an opaque cursor returned as `nextCursor`.\n */\n async history(\n opts: { before?: string; limit?: number } = {},\n ): Promise<{ messages: SpaceMessageEvent[]; nextCursor: string | null }> {\n const cipher = this.requireCipher();\n const params = new URLSearchParams();\n if (opts.before) params.set(\"before\", opts.before);\n if (opts.limit) params.set(\"limit\", String(opts.limit));\n const url =\n `${this.deps.httpBaseUrl}/api/spaces/${encodeURIComponent(this.name)}/history` +\n (params.toString() ? `?${params}` : \"\");\n const res = await this.deps.fetch(url);\n if (!res.ok) throw new Error(`Space.history: ${res.status} ${res.statusText}`);\n const body = (await res.json()) as { messages: string[]; nextCursor: string | null };\n // Warm the member directory once so historical senders' signatures verify.\n // (refreshDirectory swallows its own transport errors.)\n await this.deps.keyring?.refreshDirectory();\n const messages: SpaceMessageEvent[] = [];\n for (const raw of body.messages ?? []) {\n const decoded = await this.decodeFrame(raw, cipher);\n if (decoded) messages.push(decoded);\n }\n return { messages, nextCursor: body.nextCursor ?? null };\n }\n\n /**\n * Bring this member's group keys up to date: load from cache, and if we\n * hold nothing, request a key and poll until one arrives (or timeout).\n */\n async join(opts: { timeoutMs?: number; pollMs?: number } = {}): Promise<boolean> {\n const keyring = this.requireKeyring();\n await this.connect();\n if (await keyring.loadFromCache()) return true;\n if (keyring.hasAnyKey()) return true;\n await keyring.requestKey();\n const deadline = Date.now() + (opts.timeoutMs ?? 15000);\n const pollMs = opts.pollMs ?? 500;\n // eslint-disable-next-line no-constant-condition\n while (Date.now() < deadline) {\n if ((await keyring.pullKeys()) > 0) return true;\n await delay(pollMs);\n }\n return false;\n }\n\n /** Creator path: mint the initial group key, then connect. */\n async create(): Promise<void> {\n const keyring = this.requireKeyring();\n await keyring.bootstrapNew();\n await this.connect();\n // Publish our identity in the member directory so peers can verify our\n // message signatures (the creator never \"joins\", so register here).\n await keyring.requestKey().catch(() => {});\n // Admit anyone who requested a key before we were listening.\n if (this.deps.autoAdmit !== false) {\n await keyring.admitPending().catch(() => {});\n }\n }\n\n /** Wrap the group key for a newcomer and post it (key-holder action). */\n async admit(memberId: string, identityEcdhPub: string): Promise<void> {\n await this.requireKeyring().admit(memberId, identityEcdhPub);\n }\n\n /** Invite a user to this (private) channel's membership allowlist. */\n async invite(username: string): Promise<void> {\n await this.requireKeyring().invite(username);\n }\n\n /** Rotate to a fresh epoch and re-wrap to the roster (rotate spaces). */\n async rotate(roster?: Array<{ memberId: string; identityEcdhPub: string }>): Promise<number> {\n return this.requireKeyring().rotate(roster);\n }\n\n // -- room-scoped files (no websocket needed) -------------------------------\n\n async putFile(\n file: File | Blob | Uint8Array,\n metadata: SpaceFileMetadata,\n opts: { onProgress?: (completed: number, total: number) => void } = {},\n ): Promise<{ manifest: FileManifest; stat: FileStat }> {\n return this.fileStorage().writeFileToShards({ data: file, metadata, onProgress: opts.onProgress });\n }\n\n async getFile(manifest: FileManifest): Promise<{ data: Uint8Array; stat: FileStat }> {\n return this.fileStorage().readFileFromShards(manifest);\n }\n\n private fileStorage(): FileStorage {\n // Global, content-addressed shard store — same store `client.storage`\n // uses, so a file shared into a channel resolves from anywhere by\n // manifest. (Shards are encrypted ciphertext; the manifest is the\n // capability.)\n const shards = new ShardClient({\n baseUrl: this.deps.httpBaseUrl,\n pathPrefix: \"/api/shards\",\n fetch: this.deps.fetch,\n });\n return new FileStorage({ shards });\n }\n\n // -- internals -------------------------------------------------------------\n\n /** Wire the RAW_FRAME handler that drives fan-out events. */\n private wireFanout(): void {\n if (this.rawWired || !this.channel) return;\n this.rawWired = true;\n this.channel.on(BroadcastChannelEvents.RAW_FRAME, (e: CustomEvent) => {\n void this.onRawFrame(e.detail);\n });\n }\n\n private async onRawFrame(frame: unknown): Promise<void> {\n const f = frame as Record<string, unknown>;\n if (!f || typeof f !== \"object\") return;\n if (typeof f.spaceMessage === \"string\" && this.cipher) {\n const decoded = await this.decodeFrame(f.spaceMessage as string, this.cipher, /*raw*/ true, Number(f.timestamp ?? 0));\n if (decoded) this.emitEvent(\"message\", decoded);\n return;\n }\n if (f.editSpaceMessage && typeof f.editSpaceMessage === \"object\" && this.cipher) {\n // Server-authoritative in-place edit: new sealed content at the same\n // handle. Decode and surface it; the app replaces by `handle`.\n const e = f.editSpaceMessage as { ts?: number; spaceMessage?: string };\n if (typeof e.spaceMessage === \"string\") {\n const decoded = await this.decodeFrame(e.spaceMessage, this.cipher, /*raw*/ true, Number(e.ts ?? 0));\n if (decoded) this.emitEvent(\"message-edited\", decoded);\n }\n return;\n }\n if (f.deleteSpaceMessage && typeof f.deleteSpaceMessage === \"object\") {\n const d = f.deleteSpaceMessage as { ts?: number };\n this.emitEvent(\"message-deleted\", { handle: Number(d.ts ?? 0) });\n return;\n }\n if (f.pub && typeof f.pub === \"object\") {\n // Generic ephemeral relay frame. The server stamps the authenticated\n // sender as `name`; `pub` carries the app's {subject, data}. We\n // surface the authenticated `name` as `from` (not any client-set\n // value inside `pub`), so app signals can't spoof their sender.\n const p = f.pub as { subject?: unknown; data?: unknown };\n const from = typeof f.name === \"string\" ? f.name : \"\";\n if (from && typeof p.subject === \"string\") {\n this.emitEvent(\"ephemeral\", { from, subject: p.subject, data: p.data });\n }\n return;\n }\n if (f.joinRequest && typeof f.joinRequest === \"object\") {\n const req = f.joinRequest as JoinRequest;\n this.emitEvent(\"join-request\", req);\n // A new member appeared — refresh the directory so their future\n // messages verify, and (if we hold the key) auto-admit them.\n void this.deps.keyring?.refreshDirectory();\n if (this.deps.autoAdmit !== false && this.deps.keyring?.hasAnyKey() && req.memberId !== this.deps.myId()) {\n void this.deps.keyring.admit(req.memberId, req.identityEcdhPub).catch(() => {});\n }\n return;\n }\n if (f.keyringReady && this.deps.keyring) {\n // A key was wrapped for us — pull it.\n void this.deps.keyring.pullKeys().catch(() => {});\n }\n }\n\n /**\n * Seal `payload` once with the current group key + sign it, returning the\n * serialized `Packet` string. Shared by send (a new message) and edit\n * (replacement content for an existing handle). Requires a keyring.\n */\n private async sealMessage(payload: unknown, channel?: string, contentType?: string): Promise<string> {\n const cipher = this.requireCipher(contentType);\n const message = new Message(payload);\n const headers = await cipher.seal(message.serialize());\n const source = this.deps.myId();\n const subject = channel ?? \"default\";\n // Sign with our identity ECDSA key so receivers can verify authorship\n // end-to-end (independent of the relay's `source` stamp).\n const authPriv = KeyStore.getInstance().getAuthKeyPair(source)?.privateKey;\n if (authPriv) {\n const canonical = canonicalMessage({\n source, target: this.name, subject,\n epoch: Number(headers.epoch), iv: String(headers.iv), ciphertext: String(headers.ciphertext),\n });\n headers.sig = await signSpaceMessage(canonical, authPriv);\n }\n return new Packet({ subject, source, target: this.name, headers }).serialize();\n }\n\n /**\n * Decode one persisted/broadcast frame into a SpaceMessageEvent.\n * `isRawFrame` true means `input` is the already-extracted `spaceMessage`\n * packet string (and `serverTs` carries the message's storage handle from\n * the enclosing frame); false means `input` is the full\n * `{spaceMessage, name, timestamp}` frame and the handle is read from it.\n */\n private async decodeFrame(\n input: string,\n cipher: SpacePacketCipher,\n isRawFrame = false,\n serverTs = 0,\n ): Promise<SpaceMessageEvent | null> {\n try {\n let packetJson = input;\n let handle = serverTs;\n if (!isRawFrame) {\n const outer = JSON.parse(input) as { spaceMessage?: string; timestamp?: number };\n if (typeof outer.spaceMessage !== \"string\") return null;\n packetJson = outer.spaceMessage;\n handle = Number(outer.timestamp ?? 0);\n }\n const packet = Packet.deserialize(packetJson);\n if (!cipher.handles(packet.headers)) return null;\n\n // Verify sender authenticity end-to-end: the message must be signed\n // by `source`'s identity ECDSA key (looked up in the member\n // directory). Drop anything unsigned, signed by an unknown member,\n // or whose signature doesn't match — this defeats both member\n // impersonation and a relay rewriting `source`.\n if (!(await this.verifySender(packet))) return null;\n\n const serialized = await cipher.open(packet.headers);\n if (serialized === null) return null; // epoch key we don't hold\n const message = Message.deserialize(serialized);\n return {\n from: packet.source,\n channel: packet.subject,\n epoch: Number(packet.headers?.epoch ?? 0),\n contentType: packet.headers?.contentType as string | undefined,\n handle,\n message,\n };\n } catch (err) {\n this.emitEvent(\"error\", err);\n return null;\n }\n }\n\n /**\n * True if `packet` carries a valid signature by `source`'s identity key.\n * On a directory cache miss, refresh once (a new member may have just\n * joined) before giving up. Without a keyring (legacy handle) there's\n * nothing to verify against → reject.\n */\n private async verifySender(packet: Packet): Promise<boolean> {\n // Trust our OWN messages — we sent them, so there's nothing to prove\n // against the roster. This also keeps a returning member (who loaded a\n // cached key and never re-published a join-request) from dropping the\n // echo of their own messages when their `ecdsaPub` isn't in the roster.\n if (packet.source === this.deps.myId()) return true;\n const keyring = this.deps.keyring;\n const sig = packet.headers?.sig;\n if (!keyring || typeof sig !== \"string\") return false;\n let key = keyring.ecdsaKeyFor(packet.source);\n if (!key) {\n await keyring.refreshDirectory();\n key = keyring.ecdsaKeyFor(packet.source);\n if (!key) return false;\n }\n const canonical = canonicalMessage({\n source: packet.source,\n target: packet.target,\n subject: packet.subject,\n epoch: Number(packet.headers?.epoch ?? 0),\n iv: String(packet.headers?.iv ?? \"\"),\n ciphertext: String(packet.headers?.ciphertext ?? \"\"),\n });\n return verifySpaceMessage(canonical, sig, key);\n }\n\n private emitEvent(type: string, detail: unknown): void {\n this.events.dispatchEvent(new CustomEvent(type, { detail }));\n }\n\n private requireKeyring(): SpaceKeyring {\n if (!this.deps.keyring) {\n throw new Error(\"Space: this operation requires a keyring (open via client.space).\");\n }\n return this.deps.keyring;\n }\n\n private requireCipher(contentType?: string): SpacePacketCipher {\n if (!this.deps.keyring) {\n throw new Error(\"Space: fan-out messaging requires a keyring (open via client.space).\");\n }\n return contentType ? new SpacePacketCipher(this.deps.keyring, contentType) : this.cipher!;\n }\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nexport default Space;\n","/**\n * `client.message` — realtime messaging over the shared-space primitive.\n *\n * const sub = client.message.subscribe('todos', e => …) // pub/sub feed\n * await client.message.publish('todos', data)\n * await client.message.send('user:abc', { text: 'Hello!' }) // E2E DM\n *\n * Two distinct modes, one transport (a shared-space room websocket via\n * {@link BroadcastChannel}):\n *\n * - **pub/sub** — `publish`/`subscribe(subject)` ride plaintext `pub` frames\n * the accelerator blind-relays to everyone in the room `pub:<subject>`.\n * - **direct messages** — `send('user:x', …)` is end-to-end encrypted via the\n * Double Ratchet, fanned out in the recipient's inbox room `inbox:x`;\n * the recipient receives them by `subscribe('user:x', …)` (their own id).\n *\n * Every room websocket is opened with a short-lived signed ticket fetched from\n * `POST /api/ws-ticket` (browsers can't set the app-key header on\n * `new WebSocket()`), then completes the room's `{name}` → `{ready}` handshake\n * before any frame is sent.\n */\n\nimport type { HttpClient } from \"../HttpClient\";\nimport type { SessionState } from \"../Session\";\nimport { BroadcastChannel, BroadcastChannelEvents } from \"../../sessions/BroadcastChannel\";\nimport { Room } from \"../Room\";\n\n/** The subset of {@link BroadcastChannel} this namespace drives (test seam). */\nexport interface ChannelLike {\n on(event: string, handler: (e: CustomEvent) => void): void;\n off(event: string, handler: (e: CustomEvent) => void): void;\n connect(): Promise<void>;\n disconnect(): void;\n announce(): Promise<void>;\n send(plaintext: string): Promise<number>;\n sendRaw(frame: unknown): void;\n}\n\nexport interface MessageNamespaceDeps {\n http: HttpClient;\n session: SessionState;\n /** WebSocket base (ws/wss); derived from the accelerator baseUrl. */\n wsBaseUrl: string;\n /** Test seam — defaults to constructing a real {@link BroadcastChannel}. */\n createChannel?: (url: string, myId: string) => ChannelLike;\n}\n\nexport interface MuhkooMessageEvent<T = unknown> {\n subject: string;\n from: string;\n data: T;\n}\n\n/** Handle returned by `subscribe`; call `.unsubscribe()` to detach. */\nexport interface MessageSubscription {\n subject: string;\n unsubscribe(): void;\n}\n\ninterface RoomConn {\n channel: ChannelLike;\n /** Resolves once the room handshake (`{name}` → `{ready}`) completes. */\n ready: Promise<void>;\n}\n\nexport class MessageNamespace {\n /** One connection per room, memoized. */\n private readonly rooms = new Map<string, Promise<RoomConn>>();\n\n constructor(private readonly deps: MessageNamespaceDeps) {}\n\n /**\n * Subscribe to a subject (pub/sub) or to this user's own id (`user:<me>`)\n * to receive direct messages. Returns an unsubscribe handle.\n */\n subscribe<T = unknown>(subject: string, handler: (e: MuhkooMessageEvent<T>) => void): MessageSubscription {\n const isDM = subject.startsWith(\"user:\");\n const room = isDM ? `inbox:${subject.slice(\"user:\".length)}` : `pub:${subject}`;\n const connP = this.getRoom(room, isDM);\n\n let detach = () => {};\n void connP.then(({ channel }) => {\n if (isDM) {\n const onMsg = (e: CustomEvent) => {\n const { from, text } = (e.detail ?? {}) as { from: string; text: string };\n handler({ subject, from, data: parseMaybeJson<T>(text) });\n };\n channel.on(BroadcastChannelEvents.MESSAGE, onMsg);\n detach = () => channel.off(BroadcastChannelEvents.MESSAGE, onMsg);\n } else {\n const onRaw = (e: CustomEvent) => {\n const f = e.detail as { pub?: { subject: string; from?: string; data: T }; name?: string };\n if (f?.pub && f.pub.subject === subject) {\n handler({ subject, from: f.pub.from ?? f.name ?? \"\", data: f.pub.data });\n }\n };\n channel.on(BroadcastChannelEvents.RAW_FRAME, onRaw);\n detach = () => channel.off(BroadcastChannelEvents.RAW_FRAME, onRaw);\n }\n });\n\n return { subject, unsubscribe: () => detach() };\n }\n\n /** Publish `data` to every subscriber of `subject` (plaintext fan-out). */\n async publish<T = unknown>(subject: string, data: T): Promise<void> {\n const { channel, ready } = await this.getRoom(`pub:${subject}`, false);\n await ready;\n channel.sendRaw({ pub: { subject, from: this.myId(), data } });\n }\n\n /**\n * Send an end-to-end-encrypted direct message to `user:<id>`. Delivered in\n * the recipient's inbox room; the recipient must be subscribed\n * (`subscribe('user:<id>')`) and online to receive it (E2E requires a live\n * ratchet between both parties).\n */\n async send<T = unknown>(target: string, payload: T): Promise<void> {\n if (!target.startsWith(\"user:\")) {\n throw new Error(\"client.message.send: target must be 'user:<id>' (use publish() for pub/sub).\");\n }\n const { channel, ready } = await this.getRoom(`inbox:${target.slice(\"user:\".length)}`, true);\n await ready;\n await channel.announce();\n await channel.send(JSON.stringify(payload));\n }\n\n /**\n * Mint a new private shared-space id, server-side. The id MUST come from\n * the accelerator: it's a 64-hex string that embeds the spaces DO class\n * hash, which the worker validates on every subsequent request — client-\n * generated ids would be rejected. Pass the returned id to {@link room}\n * (or share it) to open the space.\n */\n async createRoom(): Promise<string> {\n const body = await this.deps.http.post<{ spaceId?: string }>(\"/api/spaces\");\n if (!body?.spaceId || !/^[0-9a-f]{64}$/.test(body.spaceId)) {\n throw new Error(\"createRoom: malformed server response (expected a 64-hex spaceId)\");\n }\n return body.spaceId;\n }\n\n /**\n * Open a handle to a shared-space room — group E2E messaging plus\n * room-scoped file storage. The websocket isn't opened until\n * `room.connect()`; `room.putFile`/`getFile` work without it. This is the\n * primitive group chat is built on (`publish`/`subscribe`/`send` are the\n * higher-level conveniences layered over the same space transport).\n */\n room(roomName: string): Room {\n return new Room({\n name: roomName,\n wsBaseUrl: this.deps.wsBaseUrl,\n httpBaseUrl: this.deps.http.baseUrl,\n fetch: this.deps.http.fetch,\n myId: () => this.myId(),\n fetchTicket: () => this.fetchTicket(),\n });\n }\n\n /** Close every open room connection (e.g. on logout). */\n disconnect(): void {\n for (const p of this.rooms.values()) {\n void p.then(({ channel }) => channel.disconnect()).catch(() => {});\n }\n this.rooms.clear();\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private getRoom(room: string, e2e: boolean): Promise<RoomConn> {\n let p = this.rooms.get(room);\n if (!p) {\n p = this.openRoom(room, e2e);\n this.rooms.set(room, p);\n }\n return p;\n }\n\n private async openRoom(room: string, _e2e: boolean): Promise<RoomConn> {\n const myId = this.myId();\n const ticket = await this.fetchTicket();\n const url =\n `${this.deps.wsBaseUrl}/api/spaces/${encodeURIComponent(room)}/websocket` +\n (ticket ? `?ticket=${encodeURIComponent(ticket)}` : \"\");\n\n const channel = (this.deps.createChannel ?? defaultCreateChannel)(url, myId);\n\n let resolveReady!: () => void;\n const ready = new Promise<void>((r) => { resolveReady = r; });\n\n // Room handshake: identify with `{name}` on every (re)connect, and\n // mark ready once the server echoes `{ready:true}`.\n channel.on(BroadcastChannelEvents.CONNECTED, () => channel.sendRaw({ name: myId }));\n channel.on(BroadcastChannelEvents.RAW_FRAME, (e: CustomEvent) => {\n if ((e.detail as { ready?: boolean })?.ready) resolveReady();\n });\n\n await channel.connect();\n return { channel, ready };\n }\n\n /** Fetch a short-lived WS upgrade ticket scoped to this app key. */\n private async fetchTicket(): Promise<string | null> {\n try {\n const res = await this.deps.http.post<{ ticket: string }>(\"/api/ws-ticket\", {});\n return res?.ticket ?? null;\n } catch {\n return null;\n }\n }\n\n private myId(): string {\n const id = this.deps.session.username;\n if (!id) throw new Error(\"client.message: not signed in — call client.auth.zk.login() first.\");\n return id;\n }\n}\n\n/** Default channel factory — a real `BroadcastChannel` over the room socket. */\nfunction defaultCreateChannel(url: string, myId: string): ChannelLike {\n return new BroadcastChannel({ url, myId, autoAnnounce: false });\n}\n\n/** Parse a DM payload back from its JSON string, tolerating plain strings. */\nfunction parseMaybeJson<T>(text: string): T {\n try {\n return JSON.parse(text) as T;\n } catch {\n return text as unknown as T;\n }\n}\n\nexport default MessageNamespace;\n","/**\n * SpaceKeyring — the client's view of a space's group keys.\n *\n * Holds the per-epoch group keys this member possesses (in memory, optionally\n * mirrored to PersonalSpace), and orchestrates the server-blind distribution\n * dance against a {@link KeyringTransport}:\n *\n * - a newcomer posts a join request and pulls the wrapped key blob addressed\n * to it, unwrapping with its identity private key;\n * - an existing key-holder wraps the group key for a newcomer (ECIES to the\n * newcomer's identity public key) and posts the opaque blob;\n * - on membership change (rotate spaces) a fresh epoch key is minted and\n * re-wrapped to the current roster.\n *\n * The server only ever stores opaque {@link WrappedKey} blobs — it cannot read\n * the group key. Implements {@link EpochKeyProvider} so it can back a\n * {@link SpacePacketCipher} directly.\n */\n\nimport type { WrappedKey, JoinRequest, HistoryPolicy, SpaceMetadata, RosterMember } from \"./types\";\nimport {\n generateSpaceKey,\n wrapSpaceKey,\n unwrapSpaceKey,\n importEcdhPublicKey,\n importEcdsaPublicKey,\n} from \"./SpaceCipher\";\nimport type { EpochKeyProvider } from \"./SpacePacketCipher\";\nimport { toBase64, fromBase64 } from \"../utilities\";\n\n/**\n * Reserved member id for the app's \"keeper\" — a trusted always-available member\n * (the accelerator's AppDOv1) that holds the group key and re-issues it to\n * newcomers, so a channel is joinable with no human online. Admitting this id\n * at channel creation hands the key to the keeper. MUST match the accelerator's\n * `KEEPER_MEMBER_ID`.\n */\nexport const KEEPER_MEMBER_ID = \"__keeper__\";\n\n/** Opaque-blob transport to the space's keyring (HTTP or in-memory test seam). */\nexport interface KeyringTransport {\n postJoinRequest(req: JoinRequest): Promise<void>;\n /** All wrapped blobs addressed to `memberId` (any epoch). */\n fetchBlobs(memberId: string): Promise<WrappedKey[]>;\n /** Post a wrapped key blob for `targetMemberId`. */\n postWrappedKey(targetMemberId: string, wrapped: WrappedKey, fromMemberId: string): Promise<void>;\n /** Outstanding join requests (for an online key-holder to fulfill). */\n fetchPending(): Promise<JoinRequest[]>;\n /** Current roster: member ids + their identity ECDH/ECDSA public keys. */\n fetchRoster(): Promise<RosterMember[]>;\n /** Advisory epoch bump; returns the agreed new epoch. */\n rotate(nextEpoch: number): Promise<{ epoch: number }>;\n /** Add `username` to a private channel's membership allowlist. */\n invite(username: string): Promise<void>;\n fetchMetadata(): Promise<SpaceMetadata | null>;\n}\n\n/** PersonalSpace-backed cache of this member's group keys (epoch → base64 key). */\nexport interface SpaceKeyCache {\n loadKeys(spaceId: string): Promise<Record<string, string> | null>;\n saveKeys(spaceId: string, keys: Record<string, string>): Promise<void>;\n}\n\nexport interface SpaceKeyringDeps {\n spaceId: string;\n memberId: string;\n /** This member's identity ECDH public key, base64url JWK (for join requests). */\n identityEcdhPub: string;\n /** This member's identity ECDSA public key, base64url JWK (published for\n * sender-signature verification). */\n identityEcdsaPub?: string;\n /** Resolves this member's identity ECDH private key (for unwrapping). */\n ownPrivateKey: () => CryptoKey | null;\n transport: KeyringTransport;\n cache?: SpaceKeyCache;\n historyPolicy?: HistoryPolicy;\n}\n\nexport class SpaceKeyring implements EpochKeyProvider {\n private readonly keys = new Map<number, Uint8Array>();\n private epoch = 0;\n private readonly policy: HistoryPolicy;\n /** Cached member directory: memberId → imported ECDSA verify key. */\n private readonly memberEcdsa = new Map<string, CryptoKey>();\n\n constructor(private readonly deps: SpaceKeyringDeps) {\n this.policy = deps.historyPolicy ?? \"static\";\n }\n\n // -- member directory (for verifying sender signatures) -------------------\n\n /** The cached ECDSA verify key for a member, if known. */\n ecdsaKeyFor(memberId: string): CryptoKey | undefined {\n return this.memberEcdsa.get(memberId);\n }\n\n /** Refresh the member directory (memberId → ECDSA key) from the roster. */\n async refreshDirectory(): Promise<void> {\n let roster: RosterMember[];\n try {\n roster = await this.deps.transport.fetchRoster();\n } catch {\n return;\n }\n for (const m of roster) {\n if (!m.identityEcdsaPub || this.memberEcdsa.has(m.memberId)) continue;\n try {\n this.memberEcdsa.set(m.memberId, await importEcdsaPublicKey(m.identityEcdsaPub));\n } catch {\n /* skip malformed entries */\n }\n }\n }\n\n // -- EpochKeyProvider ------------------------------------------------------\n\n currentEpoch(): number {\n return this.epoch;\n }\n\n keyForEpoch(epoch: number): Uint8Array | undefined {\n return this.keys.get(epoch);\n }\n\n hasAnyKey(): boolean {\n return this.keys.size > 0;\n }\n\n // -- lifecycle -------------------------------------------------------------\n\n /** Hydrate keys from the PersonalSpace cache, if available. Best-effort —\n * a cache miss/failure (e.g. not unlocked) must not block joining. */\n async loadFromCache(): Promise<boolean> {\n if (!this.deps.cache) return false;\n let cached: Record<string, string> | null;\n try {\n cached = await this.deps.cache.loadKeys(this.deps.spaceId);\n } catch {\n return false;\n }\n if (!cached) return false;\n for (const [epochStr, b64] of Object.entries(cached)) {\n this.keys.set(Number(epochStr), fromBase64(b64));\n }\n this.epoch = Math.max(0, ...Array.from(this.keys.keys()));\n return this.keys.size > 0;\n }\n\n private async persist(): Promise<void> {\n if (!this.deps.cache) return;\n const out: Record<string, string> = {};\n for (const [epoch, key] of this.keys) out[String(epoch)] = toBase64(key);\n // Best-effort: caching is an optimization; a write failure (e.g. locked\n // storage) must not break key acquisition.\n try {\n await this.deps.cache.saveKeys(this.deps.spaceId, out);\n } catch {\n /* ignore */\n }\n }\n\n /** Creator path: mint epoch-0 group key for a brand-new space. */\n async bootstrapNew(): Promise<void> {\n this.keys.set(0, generateSpaceKey());\n this.epoch = 0;\n await this.persist();\n }\n\n // -- newcomer: request + pull ---------------------------------------------\n\n /**\n * Post a join request so an online key-holder can wrap a key for us. Also\n * publishes our identity keys in the member directory (so others can verify\n * our message signatures, and the keeper can wrap to us).\n */\n async requestKey(desiredEpoch?: number): Promise<void> {\n await this.deps.transport.postJoinRequest({\n memberId: this.deps.memberId,\n identityEcdhPub: this.deps.identityEcdhPub,\n identityEcdsaPub: this.deps.identityEcdsaPub,\n desiredEpoch,\n });\n }\n\n /**\n * Pull and unwrap any blobs addressed to us. Returns the number of new\n * epoch keys obtained. Safe to call repeatedly (idempotent).\n */\n async pullKeys(): Promise<number> {\n const priv = this.deps.ownPrivateKey();\n if (!priv) throw new Error(\"SpaceKeyring: no identity private key to unwrap with\");\n const blobs = await this.deps.transport.fetchBlobs(this.deps.memberId);\n let added = 0;\n for (const blob of blobs) {\n if (this.keys.has(blob.epoch)) continue;\n try {\n const key = await unwrapSpaceKey(blob, priv);\n this.keys.set(blob.epoch, key);\n added++;\n } catch {\n // Not for us / tampered — skip this blob.\n }\n }\n if (added > 0) {\n this.epoch = Math.max(this.epoch, ...Array.from(this.keys.keys()));\n await this.persist();\n }\n return added;\n }\n\n // -- key-holder: admit + rotate -------------------------------------------\n\n /**\n * Wrap our group key(s) for a newcomer and post the blobs. In a `static`\n * space the newcomer receives every epoch we hold (full history); in a\n * `rotate` space they receive only the current epoch.\n */\n async admit(targetMemberId: string, identityEcdhPub: string): Promise<void> {\n const recipient = await importEcdhPublicKey(identityEcdhPub);\n const epochs = this.policy === \"static\"\n ? Array.from(this.keys.keys())\n : [this.epoch];\n for (const epoch of epochs) {\n const key = this.keys.get(epoch);\n if (!key) continue;\n const wrapped = await wrapSpaceKey(key, epoch, recipient);\n await this.deps.transport.postWrappedKey(targetMemberId, wrapped, this.deps.memberId);\n }\n }\n\n /**\n * Admit every outstanding join request (an online key-holder fulfilling\n * pending newcomers). Returns the ids admitted.\n */\n async admitPending(): Promise<string[]> {\n const pending = await this.deps.transport.fetchPending();\n const admitted: string[] = [];\n for (const req of pending) {\n if (req.memberId === this.deps.memberId) continue;\n await this.admit(req.memberId, req.identityEcdhPub);\n admitted.push(req.memberId);\n }\n return admitted;\n }\n\n /**\n * Rotate to a fresh epoch (rotate spaces). Mints a new group key, advances\n * the epoch, and re-wraps it to every member in `roster` (plus ourselves).\n */\n async rotate(roster?: Array<{ memberId: string; identityEcdhPub: string }>): Promise<number> {\n const members = roster ?? (await this.deps.transport.fetchRoster());\n const { epoch: nextEpoch } = await this.deps.transport.rotate(this.epoch + 1);\n const newKey = generateSpaceKey();\n this.keys.set(nextEpoch, newKey);\n this.epoch = nextEpoch;\n for (const m of members) {\n if (m.memberId === this.deps.memberId) continue;\n const recipient = await importEcdhPublicKey(m.identityEcdhPub);\n const wrapped = await wrapSpaceKey(newKey, nextEpoch, recipient);\n await this.deps.transport.postWrappedKey(m.memberId, wrapped, this.deps.memberId);\n }\n await this.persist();\n return nextEpoch;\n }\n\n /** Add `username` to a private channel's membership allowlist (member-only). */\n async invite(username: string): Promise<void> {\n await this.deps.transport.invite(username);\n }\n}\n","/**\n * KeyringClient — HTTP implementation of {@link KeyringTransport} against the\n * accelerator's per-space keyring endpoints. All blobs are opaque to the\n * server; this client just moves them.\n *\n * POST /api/spaces/:id/keyring/join-request { ...JoinRequest }\n * GET /api/spaces/:id/keyring/blobs/:member -> WrappedKey[]\n * POST /api/spaces/:id/keyring/wrap { targetMemberId, fromMemberId, wrapped }\n * GET /api/spaces/:id/keyring/pending -> JoinRequest[]\n * GET /api/spaces/:id/keyring/roster -> { memberId, identityEcdhPub }[]\n * POST /api/spaces/:id/keyring/rotate { nextEpoch } -> { epoch }\n * GET /api/spaces/:id/metadata -> SpaceMetadata\n */\n\nimport type { KeyringTransport } from \"./SpaceKeyring\";\nimport type { WrappedKey, JoinRequest, SpaceMetadata, RosterMember, InviteLink } from \"./types\";\n\nexport interface KeyringClientDeps {\n spaceId: string;\n httpBaseUrl: string;\n /** Header-injecting fetch from the client's HttpClient. */\n fetch: typeof fetch;\n}\n\nexport class KeyringClient implements KeyringTransport {\n constructor(private readonly deps: KeyringClientDeps) {}\n\n private url(suffix: string): string {\n return `${this.deps.httpBaseUrl}/api/spaces/${encodeURIComponent(this.deps.spaceId)}${suffix}`;\n }\n\n private async post<T>(suffix: string, body: unknown): Promise<T> {\n const res = await this.deps.fetch(this.url(suffix), {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (!res.ok) throw new Error(`KeyringClient POST ${suffix}: ${res.status} ${res.statusText}`);\n return (await res.json().catch(() => ({}))) as T;\n }\n\n private async get<T>(suffix: string): Promise<T> {\n const res = await this.deps.fetch(this.url(suffix));\n if (!res.ok) throw new Error(`KeyringClient GET ${suffix}: ${res.status} ${res.statusText}`);\n return (await res.json()) as T;\n }\n\n async postJoinRequest(req: JoinRequest): Promise<void> {\n await this.post(\"/keyring/join-request\", req);\n }\n\n async fetchBlobs(memberId: string): Promise<WrappedKey[]> {\n const body = await this.get<{ blobs?: WrappedKey[] }>(\n `/keyring/blobs/${encodeURIComponent(memberId)}`,\n );\n return body.blobs ?? [];\n }\n\n async postWrappedKey(targetMemberId: string, wrapped: WrappedKey, fromMemberId: string): Promise<void> {\n await this.post(\"/keyring/wrap\", { targetMemberId, fromMemberId, wrapped });\n }\n\n async fetchPending(): Promise<JoinRequest[]> {\n const body = await this.get<{ pending?: JoinRequest[] }>(\"/keyring/pending\");\n return body.pending ?? [];\n }\n\n async fetchRoster(): Promise<RosterMember[]> {\n const body = await this.get<{ roster?: RosterMember[] }>(\"/keyring/roster\");\n return body.roster ?? [];\n }\n\n async rotate(nextEpoch: number): Promise<{ epoch: number }> {\n return this.post<{ epoch: number }>(\"/keyring/rotate\", { nextEpoch });\n }\n\n async invite(username: string): Promise<void> {\n await this.post(\"/keyring/invite\", { username });\n }\n\n // -- Shareable invite links ----------------------------------------------\n // A capability token tied to this space. Redeeming it allowlists the holder\n // so the keeper admits them — the link IS the invitation. Mint/list/revoke\n // require the caller to be the creator or an existing member.\n\n async createInviteLink(opts: { expiresInSec?: number; maxUses?: number; role?: string } = {}): Promise<InviteLink> {\n return this.post<InviteLink>(\"/keyring/link\", opts);\n }\n\n async listInviteLinks(): Promise<InviteLink[]> {\n const body = await this.get<{ links?: InviteLink[] }>(\"/keyring/links\");\n return body.links ?? [];\n }\n\n /** Set a member's role (\"viewer\" | \"editor\"). Owner-only on the server. */\n async setMemberRole(username: string, role: string): Promise<void> {\n await this.post(\"/keyring/role\", { username, role });\n }\n\n /** Roster with roles (owner/members only). */\n async members(): Promise<Array<{ memberId: string; role: string }>> {\n const body = await this.get<{ members?: Array<{ memberId: string; role: string }> }>(\"/keyring/members\");\n return body.members ?? [];\n }\n\n async revokeInviteLink(token: string): Promise<void> {\n await this.post(\"/keyring/link-revoke\", { token });\n }\n\n /** Redeem a link: the server allowlists this member and asks the keeper to\n * wrap the group key for their identity. Caller must be authenticated. */\n async redeemInvite(req: { token: string; identityEcdhPub: string; identityEcdsaPub?: string; desiredEpoch?: number }): Promise<void> {\n await this.post(\"/keyring/redeem\", req);\n }\n\n async fetchMetadata(): Promise<SpaceMetadata | null> {\n try {\n return await this.get<SpaceMetadata>(\"/metadata\");\n } catch {\n return null;\n }\n }\n}\n","/**\n * `client.space` — the fan-out group-encryption surface.\n *\n * const space = await client.space.createSpace({ historyPolicy: \"static\" });\n * await space.sendMessage({ text: \"hello\" });\n * space.onMessage(e => …);\n *\n * const joined = await client.space.joinSpace(space.id); // newcomer\n *\n * A space owns a client-generated keypair whose public key is its id, a\n * symmetric group key distributed server-blind via the keyring, and a\n * persisted message log. This namespace wires the {@link Space} handle to the\n * HTTP {@link KeyringClient}, the member's identity keys (from {@link KeyStore},\n * shared with the Double Ratchet path), and a PersonalSpace-backed key cache.\n */\n\nimport type { HttpClient } from \"../HttpClient\";\nimport { HttpError } from \"../HttpClient\";\nimport type { SessionState } from \"../Session\";\nimport { KeyStore } from \"../../crypto/KeyStore\";\nimport { Space } from \"../../spaces/Space\";\nimport { SpaceKeyring, KEEPER_MEMBER_ID, type SpaceKeyCache } from \"../../spaces/SpaceKeyring\";\nimport { KeyringClient } from \"../../spaces/KeyringClient\";\nimport { generateSpaceIdentity, exportEcdhPublicKey, exportEcdsaPublicKey } from \"../../spaces/SpaceCipher\";\nimport type { HistoryPolicy, InviteLink } from \"../../spaces/types\";\n\n/** Thrown by `joinChannel` when no channel with that name is registered. */\nexport class ChannelNotFoundError extends Error {\n constructor(readonly channelName: string) {\n super(`Channel \"${channelName}\" does not exist. Create it first.`);\n this.name = \"ChannelNotFoundError\";\n }\n}\n\n/** Thrown by `createChannel` when the name is already registered. */\nexport class ChannelExistsError extends Error {\n constructor(readonly channelName: string) {\n super(`Channel \"${channelName}\" already exists.`);\n this.name = \"ChannelExistsError\";\n }\n}\n\nexport interface SpaceNamespaceDeps {\n http: HttpClient;\n session: SessionState;\n /** WebSocket base (ws/wss); derived from the accelerator baseUrl. */\n wsBaseUrl: string;\n /** Optional PersonalSpace-backed cache of group keys (encrypted at rest). */\n cache?: SpaceKeyCache;\n}\n\nexport class SpaceNamespace {\n constructor(private readonly deps: SpaceNamespaceDeps) {}\n\n /**\n * Create a new space: generate its keypair (public key = id), register\n * metadata, mint the initial group key, and connect. Returns the open Space.\n */\n async createSpace(opts: { historyPolicy?: HistoryPolicy; private?: boolean } = {}): Promise<Space> {\n const historyPolicy = opts.historyPolicy ?? \"static\";\n const identity = await generateSpaceIdentity();\n // Register the space (server records pubkey + policy; the DO is lazy).\n // For a private space the server also records the creator (this user) as\n // its first member — so the metadata POST must carry the user session.\n await this.deps.http.post(\n `/api/spaces/${encodeURIComponent(identity.id)}/metadata`,\n { spacePubKey: identity.id, historyPolicy, visibility: opts.private ? \"private\" : \"public\" },\n );\n const space = await this.build(identity.id, historyPolicy);\n await space.create();\n return space;\n }\n\n /** Join an existing space by id (its public key). Resolves once a key arrives. */\n async joinSpace(spaceId: string, opts: { timeoutMs?: number } = {}): Promise<Space> {\n const policy = await this.fetchPolicy(spaceId);\n const space = await this.build(spaceId, policy);\n await space.join({ timeoutMs: opts.timeoutMs });\n return space;\n }\n\n /** A handle to a space without auto-connecting (uses cached keys on demand). */\n async get(spaceId: string, historyPolicy: HistoryPolicy = \"static\"): Promise<Space> {\n return this.build(spaceId, historyPolicy);\n }\n\n // -------------------------------------------------------------------------\n // Channels — named, app-scoped pointers to spaces. The name → space-id\n // directory is app-public config (server-readable, scoped to this app via\n // its key); the channel CONTENTS stay fan-out E2E-encrypted. Lets chat use\n // human room names (`general`) instead of raw pubkey ids.\n // -------------------------------------------------------------------------\n\n /** List this app's channels (name → space-id) for the key's environment. */\n async listChannels(): Promise<Array<{ name: string; spaceId: string }>> {\n const body = await this.deps.http.get<{ channels?: Array<{ name: string; spaceId: string }> }>(\n \"/api/app/channels\",\n );\n return body.channels ?? [];\n }\n\n /** Resolve a channel name to its space id, or null if it doesn't exist. */\n async resolveChannel(name: string): Promise<string | null> {\n try {\n const body = await this.deps.http.get<{ spaceId: string }>(\n `/api/app/channels/${encodeURIComponent(name)}`,\n );\n return body.spaceId ?? null;\n } catch (err) {\n if (err instanceof HttpError && err.status === 404) return null;\n throw err;\n }\n }\n\n /**\n * Create a new channel: mint a fan-out space (the caller becomes its first\n * key-holder) and register `name → spaceId` in the app directory. Throws\n * {@link ChannelExistsError} if the name is already taken.\n */\n async createChannel(name: string, opts: { historyPolicy?: HistoryPolicy; private?: boolean } = {}): Promise<Space> {\n const space = await this.createSpace(opts);\n // Register name → id first so a name clash doesn't leave an admitted keeper.\n try {\n await this.deps.http.post(\"/api/app/channels\", { name, spaceId: space.id, visibility: opts.private ? \"private\" : \"public\" });\n } catch (err) {\n if (err instanceof HttpError && err.status === 409) {\n throw new ChannelExistsError(name);\n }\n throw err;\n }\n // Admit the app keeper so the channel is joinable with no member online.\n // Best-effort: a channel still works (members admit each other) without it.\n try {\n const { pubkey } = await this.deps.http.get<{ pubkey?: string }>(\"/api/app/keeper\");\n if (pubkey && space.keyring) await space.keyring.admit(KEEPER_MEMBER_ID, pubkey);\n } catch (err) {\n console.warn(\"[client.space] keeper admit failed (channel still usable):\", err);\n }\n return space;\n }\n\n /**\n * Join an existing channel by name. Throws {@link ChannelNotFoundError} if\n * no channel with that name is registered (use {@link createChannel} first).\n */\n async joinChannel(name: string, opts: { timeoutMs?: number } = {}): Promise<Space> {\n const spaceId = await this.resolveChannel(name);\n if (!spaceId) throw new ChannelNotFoundError(name);\n return this.joinSpace(spaceId, opts);\n }\n\n // -------------------------------------------------------------------------\n // Invite links — shareable, keeper-gated invitations to a space. The token\n // is a capability: anyone signed in who redeems it is admitted by the\n // keeper. Mint/list/revoke require the caller to be the space's creator or\n // an existing member.\n // -------------------------------------------------------------------------\n\n /** Mint a shareable invite link for a space. `opts.expiresInSec` / `maxUses`\n * bound it (0/undefined = unlimited); `opts.role` (\"viewer\"|\"editor\") is the\n * access granted to redeemers (default viewer). Returns the link. */\n async createInviteLink(spaceId: string, opts: { expiresInSec?: number; maxUses?: number; role?: string } = {}): Promise<InviteLink> {\n return this.keyringFor(spaceId).createInviteLink(opts);\n }\n\n /** Set a member's role on a space (\"viewer\" | \"editor\"). Owner-only. */\n async setMemberRole(spaceId: string, username: string, role: string): Promise<void> {\n await this.keyringFor(spaceId).setMemberRole(username, role);\n }\n\n /** Roster with roles (owner/members only). */\n async members(spaceId: string): Promise<Array<{ memberId: string; role: string }>> {\n return this.keyringFor(spaceId).members();\n }\n\n /** List a space's active invite links (creator/members only). */\n async listInviteLinks(spaceId: string): Promise<InviteLink[]> {\n return this.keyringFor(spaceId).listInviteLinks();\n }\n\n /** Revoke an invite link by token. */\n async revokeInviteLink(spaceId: string, token: string): Promise<void> {\n await this.keyringFor(spaceId).revokeInviteLink(token);\n }\n\n /**\n * Join a space using an invite link: redeem the token (the keeper admits\n * this member), then connect and resolve once the group key arrives.\n * Returns the open {@link Space}.\n */\n async joinByInvite(spaceId: string, token: string, opts: { timeoutMs?: number } = {}): Promise<Space> {\n const memberId = this.myId();\n const { ecdhPub, ecdsaPub } = await this.ensureIdentity(memberId);\n await this.keyringFor(spaceId).redeemInvite({ token, identityEcdhPub: ecdhPub, identityEcdsaPub: ecdsaPub });\n return this.joinSpace(spaceId, opts);\n }\n\n /** The current member roster of a space (member id → identity public keys). */\n async roster(spaceId: string): Promise<Array<{ memberId: string; identityEcdhPub: string; identityEcdsaPub?: string }>> {\n return this.keyringFor(spaceId).fetchRoster();\n }\n\n private keyringFor(spaceId: string): KeyringClient {\n return new KeyringClient({\n spaceId,\n httpBaseUrl: this.deps.http.baseUrl,\n fetch: this.deps.http.fetch,\n });\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private async build(spaceId: string, historyPolicy: HistoryPolicy): Promise<Space> {\n const memberId = this.myId();\n const { ecdhPub, ecdsaPub } = await this.ensureIdentity(memberId);\n const transport = new KeyringClient({\n spaceId,\n httpBaseUrl: this.deps.http.baseUrl,\n fetch: this.deps.http.fetch,\n });\n const keyring = new SpaceKeyring({\n spaceId,\n memberId,\n identityEcdhPub: ecdhPub,\n identityEcdsaPub: ecdsaPub,\n ownPrivateKey: () => KeyStore.getInstance().getKeyPair(memberId)?.privateKey ?? null,\n transport,\n cache: this.deps.cache,\n historyPolicy,\n });\n return new Space({\n name: spaceId,\n wsBaseUrl: this.deps.wsBaseUrl,\n httpBaseUrl: this.deps.http.baseUrl,\n fetch: this.deps.http.fetch,\n myId: () => memberId,\n fetchTicket: () => this.fetchTicket(),\n keyring,\n historyPolicy,\n });\n }\n\n /** Ensure the member has an identity keypair; return its public ECDH + ECDSA keys. */\n private async ensureIdentity(memberId: string): Promise<{ ecdhPub: string; ecdsaPub: string }> {\n const store = KeyStore.getInstance();\n if (!store.getKeyPair(memberId)) {\n await store.generateOwnKeyPair(memberId);\n }\n const ecdhPub = await exportEcdhPublicKey(store.getKeyPair(memberId)!.publicKey);\n const ecdsaPub = await exportEcdsaPublicKey(store.getAuthKeyPair(memberId)!.publicKey);\n return { ecdhPub, ecdsaPub };\n }\n\n private async fetchPolicy(spaceId: string): Promise<HistoryPolicy> {\n const meta = await new KeyringClient({\n spaceId,\n httpBaseUrl: this.deps.http.baseUrl,\n fetch: this.deps.http.fetch,\n }).fetchMetadata();\n return meta?.historyPolicy ?? \"static\";\n }\n\n private async fetchTicket(): Promise<string | null> {\n try {\n const res = await this.deps.http.post<{ ticket: string }>(\"/api/ws-ticket\", {});\n return res?.ticket ?? null;\n } catch {\n return null;\n }\n }\n\n private myId(): string {\n const id = this.deps.session.username;\n if (!id) throw new Error(\"client.space: not signed in — call client.auth.zk.login() first.\");\n return id;\n }\n}\n\nexport default SpaceNamespace;\n","/**\n * `client.agents` — manage an app's **Programmable Agents** (server-side\n * \"virtual users\" backed by Workers AI).\n *\n * const { config } = await client.agents.create(appId, {\n * handle: '@assistant', displayName: 'Assistant',\n * systemPrompt: 'You are a helpful teammate in this Space.',\n * triggers: [{ type: 'mention' }],\n * });\n * await client.agents.enable(appId, config.agentId, spaceId); // per-Space opt-in\n *\n * These are MANAGEMENT calls — the agent itself runs on the accelerator. Only an\n * app's owner or an editor of its shared Space may create/update/enable an agent\n * (viewers can read). Authorization rides the user session token; non-owner\n * editors pass their management Space via `opts.space`.\n *\n * An agent is \"prompts + persona\": a system prompt, a model, named prompt\n * `skills`, and `triggers` that decide when it speaks — plus optional `tools`\n * that let it act on the app (query/write its database, call its functions,\n * resolve its channels) via a server-side function-calling loop. See\n * {@link AgentToolsConfig}. Pair with the `@MuhkooAgent`/`@MuhkooSpace`/\n * `@MuhkooDB`/`@MuhkooFunction` decorators + `ejectAgentPrompt`/`ejectAgentTools`\n * to generate `systemPrompt` and `tools` straight from your app's surface.\n */\n\nimport type { HttpClient } from \"../HttpClient\";\n\nexport type AgentTriggerType = \"mention\" | \"keyword\" | \"regex\" | \"always\";\n\n/** How much database access the agent's tool-use has. */\nexport type AgentDbToolMode = \"off\" | \"read\" | \"write\";\n\n/**\n * Tool-use config — lets the agent act on the app through a function-calling\n * loop. Opt-in and conservatively gated server-side: a fresh agent has tools\n * off, the DB is read-only and per-table allowlisted, functions are per-name\n * allowlisted, and channels are off. **Enabling tools requires a\n * function-calling `model` in the same create/update payload** (the server\n * rejects `enabled: true` otherwise). `ejectAgentTools` produces this shape.\n */\nexport interface AgentToolsConfig {\n enabled: boolean;\n db: {\n /** `off` = no DB tools; `read` = query/get; `write` = + insert/update/delete. */\n mode: AgentDbToolMode;\n /** Allowlisted table names the agent may touch. */\n tables: string[];\n };\n /** Allowlisted serverless-function names the agent may call. */\n functions: string[];\n /** Whether the agent may resolve the app's PUBLIC channels. */\n channels: boolean;\n /** Max tool-call rounds per reply (1..6). */\n maxIterations: number;\n}\n\nexport interface AgentTrigger {\n type: AgentTriggerType;\n /** Required for `keyword` (case-insensitive substring) and `regex`. */\n pattern?: string;\n /** Name of a {@link AgentSkill} to run on match. */\n skill?: string;\n}\n\nexport interface AgentSkill {\n name: string;\n prompt: string;\n}\n\nexport interface AgentConfig {\n agentId: string;\n /** @-mention target, e.g. \"@assistant\". */\n handle: string;\n displayName: string;\n model: string;\n systemPrompt: string;\n skills: AgentSkill[];\n triggers: AgentTrigger[];\n /** Space ids this agent is enabled on (per-Space opt-in). */\n enabledSpaces: string[];\n caps: { dailyTokenBudget: number };\n /** Tool-use config (absent / `enabled: false` = prompt-only). */\n tools?: AgentToolsConfig;\n createdAt: number;\n updatedAt: number;\n}\n\n/** The editor-settable fields when creating an agent. */\nexport interface AgentCreateInput {\n handle: string;\n displayName: string;\n systemPrompt: string;\n model?: string;\n skills?: AgentSkill[];\n triggers?: AgentTrigger[];\n caps?: { dailyTokenBudget: number };\n /** Grant tool-use. Requires `model` to be a function-calling model. */\n tools?: AgentToolsConfig;\n}\n\nexport type AgentUpdateInput = Partial<AgentCreateInput>;\n\n/** Create/get response — the config plus the agent's published identity keys. */\nexport interface AgentProvisioned {\n config: AgentConfig;\n /** The agent's Space member id (`__agent__:<agentId>`). */\n memberId: string;\n /** base64url-JWK identity ECDH public key (null until provisioned). */\n ecdhPub: string | null;\n /** base64url-JWK identity ECDSA public key — verifies the agent's messages. */\n ecdsaPub: string | null;\n}\n\nexport interface AgentsNamespaceDeps {\n http: HttpClient;\n}\n\n/** Common option: a management Space for delegated (non-owner) access. */\nexport interface AgentScopeOpts {\n space?: string;\n}\n\nexport class AgentsNamespace {\n constructor(private readonly deps: AgentsNamespaceDeps) {}\n\n /** List the app's agents. */\n async list(appId: string, opts: AgentScopeOpts = {}): Promise<AgentConfig[]> {\n const res = await this.deps.http.get<{ agents: AgentConfig[] }>(this.path(appId, \"\", opts));\n return res.agents ?? [];\n }\n\n /** Read one agent (config + identity keys). */\n async get(appId: string, agentId: string, opts: AgentScopeOpts = {}): Promise<AgentProvisioned> {\n return this.deps.http.get<AgentProvisioned>(this.path(appId, `/${encodeURIComponent(agentId)}`, opts));\n }\n\n /** Create an agent (owner/editor only). */\n async create(appId: string, input: AgentCreateInput, opts: AgentScopeOpts = {}): Promise<AgentProvisioned> {\n return this.deps.http.post<AgentProvisioned>(this.path(appId, \"\", {}), { ...input, space: opts.space });\n }\n\n /** Update an agent's editor-settable fields (owner/editor only). */\n async update(appId: string, agentId: string, patch: AgentUpdateInput, opts: AgentScopeOpts = {}): Promise<{ config: AgentConfig }> {\n return this.deps.http.patch<{ config: AgentConfig }>(\n this.path(appId, `/${encodeURIComponent(agentId)}`, {}),\n { ...patch, space: opts.space },\n );\n }\n\n /** Delete an agent (owner/editor only). */\n async delete(appId: string, agentId: string, opts: AgentScopeOpts = {}): Promise<{ deleted: boolean }> {\n return this.deps.http.del<{ deleted: boolean }>(\n this.path(appId, `/${encodeURIComponent(agentId)}`, {}),\n { space: opts.space },\n );\n }\n\n /** Enable the agent on a Space (per-Space opt-in). */\n async enable(appId: string, agentId: string, spaceId: string, opts: AgentScopeOpts = {}): Promise<{ config: AgentConfig }> {\n return this.deps.http.post<{ config: AgentConfig }>(\n this.path(appId, `/${encodeURIComponent(agentId)}/enable`, {}),\n { targetSpaceId: spaceId, space: opts.space },\n );\n }\n\n /** Disable the agent on a Space. */\n async disable(appId: string, agentId: string, spaceId: string, opts: AgentScopeOpts = {}): Promise<{ config: AgentConfig }> {\n return this.deps.http.post<{ config: AgentConfig }>(\n this.path(appId, `/${encodeURIComponent(agentId)}/disable`, {}),\n { targetSpaceId: spaceId, space: opts.space },\n );\n }\n\n private path(appId: string, suffix: string, opts: AgentScopeOpts): string {\n const q = opts.space ? `?space=${encodeURIComponent(opts.space)}` : \"\";\n return `/api/apps/${encodeURIComponent(appId)}/agents${suffix}${q}`;\n }\n}\n\nexport default AgentsNamespace;\n","/**\n * `client.functions` — manage an app's **serverless functions** (developer-\n * authored code that runs on the accelerator).\n *\n * const { config } = await client.functions.deploy(appId, {\n * name: 'hello', displayName: 'Hello',\n * code: `export default { fetch: () => new Response('hi') }`,\n * triggers: { http: { enabled: true } },\n * });\n * // HTTP-reachable at hello--<slug>.fns.muhkoo.dev\n * await client.functions.enable(appId, config.functionId, spaceId); // Space-bound\n *\n * These are MANAGEMENT calls — the function itself runs on the accelerator\n * (uploaded just-in-time, decrypted only at invocation). Only an app's owner or\n * an editor of its shared Space may deploy/update/enable (viewers read).\n * Authorization rides the user session token; non-owner editors pass their\n * management Space via `opts.space`.\n *\n * v1 is \"compute-only\": a function is an untrusted single-module ES worker\n * (`export default { fetch }`) with NO platform bindings — it reaches the\n * platform as an external client (the end-user session is passed through). Two\n * triggers: `http` (its own subdomain) and `space` (invoked on Space messages,\n * like a Programmable Agent).\n */\n\nimport type { HttpClient } from \"../HttpClient\";\n\nexport type FunctionTriggerType = \"keyword\" | \"regex\" | \"always\";\n\nexport interface FunctionTrigger {\n type: FunctionTriggerType;\n /** Required for `keyword` (case-insensitive substring) and `regex`. */\n pattern?: string;\n}\n\nexport interface FunctionTriggers {\n /** HTTP-invocable at `<name>--<slug>.fns.<zone>`. */\n http?: { enabled: boolean; methods?: string[] };\n /** Invoked on matching Space messages (per-Space opt-in via enable). */\n space?: { match: FunctionTrigger[] };\n}\n\nexport interface FunctionCaps {\n /** Per-invocation CPU ceiling (ms). */\n cpuMs: number;\n /** Per-invocation subrequest ceiling. */\n subRequests: number;\n /** Hard daily invocation cap (0 = unlimited). */\n dailyInvocationBudget: number;\n}\n\nexport interface FunctionConfig {\n functionId: string;\n /** DNS-safe slug — the function's subdomain label + WfP script name part. */\n name: string;\n displayName: string;\n triggers: FunctionTriggers;\n /** Space ids this function is enabled on (per-Space opt-in for `space`). */\n enabledSpaces: string[];\n caps: FunctionCaps;\n scriptName: string;\n /** sha-256 of the last-deployed source. */\n codeHash?: string;\n /** When the source was last (re)deployed. */\n deployedAt?: number;\n createdAt: number;\n updatedAt: number;\n}\n\n/** The editor-settable fields when deploying a function. */\nexport interface FunctionDeployInput {\n name: string;\n displayName: string;\n /** Raw single-module ES worker source (`export default { fetch }`). */\n code: string;\n triggers?: FunctionTriggers;\n caps?: Partial<FunctionCaps>;\n}\n\n/** Update input — any subset, including new `code` to redeploy. */\nexport type FunctionUpdateInput = Partial<FunctionDeployInput>;\n\nexport interface FunctionsNamespaceDeps {\n http: HttpClient;\n}\n\n/** Common option: a management Space for delegated (non-owner) access. */\nexport interface FunctionScopeOpts {\n space?: string;\n}\n\nexport class FunctionsNamespace {\n constructor(private readonly deps: FunctionsNamespaceDeps) {}\n\n /** List the app's functions. */\n async list(appId: string, opts: FunctionScopeOpts = {}): Promise<FunctionConfig[]> {\n const res = await this.deps.http.get<{ functions: FunctionConfig[] }>(this.path(appId, \"\", opts));\n return res.functions ?? [];\n }\n\n /** Read one function's config. */\n async get(appId: string, functionId: string, opts: FunctionScopeOpts = {}): Promise<{ config: FunctionConfig }> {\n return this.deps.http.get<{ config: FunctionConfig }>(this.path(appId, `/${encodeURIComponent(functionId)}`, opts));\n }\n\n /** Read a function's decrypted source (owner/editor; for the editor UI). */\n async code(appId: string, functionId: string, opts: FunctionScopeOpts = {}): Promise<{ functionId: string; code: string; codeHash: string | null }> {\n return this.deps.http.get<{ functionId: string; code: string; codeHash: string | null }>(\n this.path(appId, `/${encodeURIComponent(functionId)}/code`, opts),\n );\n }\n\n /** Deploy (create) a function (owner/editor only). */\n async deploy(appId: string, input: FunctionDeployInput, opts: FunctionScopeOpts = {}): Promise<{ config: FunctionConfig }> {\n return this.deps.http.post<{ config: FunctionConfig }>(this.path(appId, \"\", {}), { ...input, space: opts.space });\n }\n\n /** Update a function's editor-settable fields and/or redeploy its `code`. */\n async update(appId: string, functionId: string, patch: FunctionUpdateInput, opts: FunctionScopeOpts = {}): Promise<{ config: FunctionConfig }> {\n return this.deps.http.patch<{ config: FunctionConfig }>(\n this.path(appId, `/${encodeURIComponent(functionId)}`, {}),\n { ...patch, space: opts.space },\n );\n }\n\n /** Delete a function (owner/editor only). */\n async delete(appId: string, functionId: string, opts: FunctionScopeOpts = {}): Promise<{ deleted: boolean }> {\n return this.deps.http.del<{ deleted: boolean }>(\n this.path(appId, `/${encodeURIComponent(functionId)}`, {}),\n { space: opts.space },\n );\n }\n\n /** Enable the function on a Space (per-Space opt-in for the `space` trigger). */\n async enable(appId: string, functionId: string, spaceId: string, opts: FunctionScopeOpts = {}): Promise<{ config: FunctionConfig }> {\n return this.deps.http.post<{ config: FunctionConfig }>(\n this.path(appId, `/${encodeURIComponent(functionId)}/enable`, {}),\n { targetSpaceId: spaceId, space: opts.space },\n );\n }\n\n /** Disable the function on a Space. */\n async disable(appId: string, functionId: string, spaceId: string, opts: FunctionScopeOpts = {}): Promise<{ config: FunctionConfig }> {\n return this.deps.http.post<{ config: FunctionConfig }>(\n this.path(appId, `/${encodeURIComponent(functionId)}/disable`, {}),\n { targetSpaceId: spaceId, space: opts.space },\n );\n }\n\n private path(appId: string, suffix: string, opts: FunctionScopeOpts): string {\n const q = opts.space ? `?space=${encodeURIComponent(opts.space)}` : \"\";\n return `/api/apps/${encodeURIComponent(appId)}/functions${suffix}${q}`;\n }\n}\n\nexport default FunctionsNamespace;\n","/**\n * `Client` — the single entry point to the Muhkoo SDK.\n *\n * Everything an app does flows through namespaces hanging off one client:\n *\n * const client = new Client({ apiKey, baseUrl });\n * const user = await client.auth.zk.login(username, password);\n * await client.storage.set('todos', id, { title, completed: false });\n * client.message.subscribe('todos', e => …);\n * await client.message.send('user:abc', { text: 'Hello!' });\n *\n * The client owns:\n * - an {@link HttpClient} that stamps the app key + session token onto every\n * request to the accelerator;\n * - a {@link SessionState} shared across namespaces (auth writes it; storage\n * and message read identity + token from it);\n * - the three namespaces: {@link AuthNamespace}, {@link StorageNamespace},\n * {@link MessageNamespace}.\n *\n * The lower-level building blocks (`AuthClient`, `PersonalSpaceClient`,\n * `FileStorage`, `EncryptedSession`, `Network`, …) remain exported and usable\n * directly, but the client is the supported, ergonomic surface.\n */\n\nimport { AuthClient } from \"../auth\";\nimport { defaultCircuitUrls, type CircuitUrls } from \"../auth/proof\";\nimport { HttpClient } from \"./HttpClient\";\nimport { SessionState, defaultSessionStore, type SessionStore } from \"./Session\";\nimport { AuthNamespace } from \"./namespaces/AuthNamespace\";\nimport { KvNamespace } from \"./namespaces/KvNamespace\";\nimport { DbNamespace } from \"./namespaces/DbNamespace\";\nimport { StorageNamespace } from \"./namespaces/FileNamespace\";\nimport { MessageNamespace } from \"./namespaces/MessageNamespace\";\nimport { SpaceNamespace } from \"./namespaces/SpaceNamespace\";\nimport { AgentsNamespace } from \"./namespaces/AgentsNamespace\";\nimport { FunctionsNamespace } from \"./namespaces/FunctionsNamespace\";\nimport type { SpaceKeyCache } from \"../spaces/SpaceKeyring\";\n\n/** The hosted Muhkoo Accelerator — the default {@link ClientOptions.baseUrl}. */\nexport const DEFAULT_BASE_URL = \"https://api.muhkoo.dev\";\n\nexport interface ClientOptions {\n /**\n * App / publishable key issued by the accelerator (e.g. `mk_test_pk_…`).\n *\n * TRANSITIONALLY optional: auth + storage currently function without it so\n * the in-tree web app can migrate before a key is provisioned. The product\n * direction is that the app key becomes REQUIRED — it's how every app\n * authenticates to the Accelerator and gets attributed for metering/billing.\n * New integrations should always pass one.\n */\n apiKey?: string;\n /**\n * Absolute URL of the accelerator (trailing slash optional). Defaults to\n * the hosted Muhkoo Accelerator ({@link DEFAULT_BASE_URL}); override to\n * point at staging, a local `wrangler dev`, or a self-hosted deployment.\n */\n baseUrl?: string;\n /**\n * URLs of the `preimagePoK` circuit assets used for ZK login proofs.\n * Defaults to {@link defaultCircuitUrls} anchored at `baseUrl` — i.e.\n * `${baseUrl}/circuits/build/preimagePoK_js/preimagePoK.wasm` and\n * `…/preimagePoK_0001.zkey`, where the accelerator serves them.\n */\n circuits?: CircuitUrls;\n /** Pluggable session-token persistence. Defaults to in-memory. */\n sessionStore?: SessionStore;\n /** Custom fetch — defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n /** Optional log level for the SDK logger. */\n logLevel?: string;\n}\n\n/**\n * Turn the HTTP base URL into a websocket base (`http(s)://` → `ws(s)://`).\n * The accelerator serves spaces over both on the same origin.\n */\nfunction toWsBase(baseUrl: string): string {\n return baseUrl.replace(/\\/+$/, \"\").replace(/^http/, \"ws\");\n}\n\nexport class Client {\n readonly baseUrl: string;\n\n /** Authentication — `client.auth.zk.login(...)`, etc. */\n readonly auth: AuthNamespace;\n /** Per-user key/value storage — `client.kv.set(...)`, etc. */\n readonly kv: KvNamespace;\n /** App scalable database — `client.db.table('todos').query(...)`, etc. */\n readonly db: DbNamespace;\n /** File storage — `client.storage.writeFile(...)`, etc. */\n readonly storage: StorageNamespace;\n /** Realtime messaging — `client.message.subscribe(...)`, etc. */\n readonly message: MessageNamespace;\n /** Fan-out group spaces — `client.space.createSpace(...)`, etc. */\n readonly space: SpaceNamespace;\n /** Programmable Agents — `client.agents.create(appId, …)`, etc. */\n readonly agents: AgentsNamespace;\n /** Serverless functions — `client.functions.deploy(appId, …)`, etc. */\n readonly functions: FunctionsNamespace;\n\n private readonly session: SessionState;\n private readonly http: HttpClient;\n\n /** Subscribers notified when a session expires and can't be recovered. */\n private readonly sessionExpiredHandlers = new Set<() => void>();\n /** Shared in-flight recovery so a burst of 401s triggers one re-auth. */\n private recoverInFlight: Promise<boolean> | null = null;\n\n constructor(options: ClientOptions = {}) {\n if (options.logLevel && typeof globalThis.appLogger?.setLevel === \"function\") {\n globalThis.appLogger.setLevel(options.logLevel);\n }\n\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n this.session = new SessionState(options.sessionStore ?? defaultSessionStore());\n\n this.http = new HttpClient({\n baseUrl: this.baseUrl,\n apiKey: options.apiKey,\n getSessionToken: () => this.session.token,\n fetch: options.fetch,\n // Self-heal stale sessions: on a 401, try a silent re-auth (only\n // works while unlocked). If it can't, `recoverSession` fires the\n // session-expired event so the app can redirect to login.\n onUnauthorized: () => this.recoverSession(),\n });\n\n const circuits = options.circuits ?? defaultCircuitUrls(this.baseUrl);\n const authClient = new AuthClient({ baseUrl: this.baseUrl, fetch: this.http.fetch });\n\n const wsBaseUrl = toWsBase(this.baseUrl);\n this.auth = new AuthNamespace({ auth: authClient, circuits, session: this.session });\n this.kv = new KvNamespace({ http: this.http, session: this.session, wsBaseUrl });\n this.db = new DbNamespace({ http: this.http });\n this.storage = new StorageNamespace({ http: this.http, baseUrl: this.baseUrl, kv: this.kv });\n this.message = new MessageNamespace({ http: this.http, session: this.session, wsBaseUrl });\n\n // Group keys are cached in the user's PersonalSpace (encrypted at rest\n // by client.kv), so a returning member hydrates without a fresh keyring\n // round-trip. The server only ever sees the ciphertext.\n const spaceKeyCache: SpaceKeyCache = {\n loadKeys: (spaceId) => this.kv.get<Record<string, string>>(\"space-keys\", spaceId),\n saveKeys: (spaceId, keys) => this.kv.set(\"space-keys\", spaceId, keys),\n };\n this.space = new SpaceNamespace({\n http: this.http,\n session: this.session,\n wsBaseUrl,\n cache: spaceKeyCache,\n });\n this.agents = new AgentsNamespace({ http: this.http });\n this.functions = new FunctionsNamespace({ http: this.http });\n }\n\n /** The currently signed-in user, or `null`. */\n get user() {\n return this.auth.user;\n }\n\n /** Whether a token-bearing session is active. */\n get isAuthenticated(): boolean {\n return this.session.isAuthenticated;\n }\n\n /**\n * Subscribe to session expiry that couldn't be silently recovered (the\n * user's identity wasn't in memory to re-prove — typically after a reload\n * where only the token was persisted, and that token has since gone stale).\n * This is the signal to send the user back to the login screen.\n *\n * Returns an unsubscribe function.\n *\n * const off = client.onSessionExpired(() => router.push('/login'));\n */\n onSessionExpired(handler: () => void): () => void {\n this.sessionExpiredHandlers.add(handler);\n return () => this.sessionExpiredHandlers.delete(handler);\n }\n\n /**\n * Attempt a silent re-auth of the current user. Concurrent callers share a\n * single in-flight attempt (a stale token usually 401s several requests at\n * once — we re-auth once, not once per request). On failure the\n * session-expired event fires so the app can react. Exposed so apps can\n * also drive recovery proactively (e.g. on `visibilitychange`).\n */\n recoverSession(): Promise<boolean> {\n if (this.recoverInFlight) return this.recoverInFlight;\n this.recoverInFlight = this.auth.zk\n .recover()\n .then((ok) => {\n if (!ok) {\n for (const handler of this.sessionExpiredHandlers) {\n try { handler(); } catch { /* a bad listener mustn't break recovery */ }\n }\n }\n return ok;\n })\n .finally(() => {\n this.recoverInFlight = null;\n });\n return this.recoverInFlight;\n }\n}\n\nexport default Client;\n","/**\n * Muhkoo app decorators — declare your app's agent-facing surface in code, then\n * \"eject\" a system prompt you hand to a Programmable Agent.\n *\n * You annotate a plain class with `@MuhkooAgent` (the app's identity + how the\n * agent should behave) plus per-surface decorators — `@MuhkooSpace`,\n * `@MuhkooDB`, `@MuhkooFunction` — that describe what each channel, table, and\n * function is *for*. {@link ejectAgentPrompt} reads those annotations and\n * produces a `systemPrompt` string:\n *\n * ```ts\n * @MuhkooAgent({\n * name: \"Chat Assistant\",\n * purpose: \"A helpful assistant inside a real-time team chat.\",\n * guidance: [\"Keep replies short.\", \"Only chime in when relevant.\"],\n * })\n * class ChatAssistant {\n * @MuhkooSpace({ description: \"Main team discussion.\" }) general!: string;\n * @MuhkooDB({ access: \"read\", description: \"Chat message history.\" }) messages!: unknown;\n * @MuhkooFunction({ description: \"Open a support ticket.\" }) openTicket!: () => void;\n * }\n *\n * const systemPrompt = ejectAgentPrompt(ChatAssistant);\n * await client.agents.create({ handle: \"assistant\", displayName: \"Assistant\", systemPrompt });\n * ```\n *\n * The ejected prompt owns the **semantic** layer — what the app is, how to act,\n * and what each surface means. The Muhkoo runtime separately appends the\n * **authoritative** roster (exact columns, function parameters, and the closed\n * list of callable tools), so the prompt here never needs to restate schema and\n * can't drift from it. Decorators only describe; they never change runtime\n * behavior, so they're safe to apply to a throwaway descriptor class.\n *\n * Requires `experimentalDecorators` (already enabled in this package). Metadata\n * is captured in a per-class registry — no `reflect-metadata` dependency.\n */\n\nimport type { AgentToolsConfig } from \"../namespaces/AgentsNamespace\";\n\n/** Whether the agent may only read a table, or read and write it. */\nexport type MuhkooDBAccess = \"read\" | \"write\";\n\n/** App-level identity + behavioral guidance — the heart of the ejected prompt. */\nexport interface MuhkooAgentMeta {\n /** The agent persona's name (e.g. \"Chat Assistant\"). */\n name: string;\n /** What the app is and the agent's role in it. One or two sentences. */\n purpose: string;\n /** Short behavioral rules, rendered as a bulleted list. */\n guidance?: string[];\n /** Optional free-form instructions appended verbatim after the surface. */\n instructions?: string;\n}\n\n/** A channel/Space the agent can resolve and post into. */\nexport interface MuhkooSpaceMeta {\n /** Channel name. Defaults to the decorated member's name. */\n name?: string;\n description: string;\n}\n\n/** An app database table the agent can query (and optionally mutate). */\nexport interface MuhkooDBMeta {\n /** Table name. Defaults to the decorated member's name. */\n table?: string;\n /** Read-only by default. */\n access?: MuhkooDBAccess;\n description: string;\n}\n\n/** A serverless function the agent can invoke via `call_function`. */\nexport interface MuhkooFunctionMeta {\n /** Function name. Defaults to the decorated member's name. */\n name?: string;\n description: string;\n}\n\ninterface SpaceEntry { name: string; description: string; }\ninterface TableEntry { table: string; access: MuhkooDBAccess; description: string; }\ninterface FunctionEntry { name: string; description: string; }\n\n/** The full annotated surface gathered from one decorated class. */\nexport interface MuhkooAppDescriptor {\n agent?: MuhkooAgentMeta;\n spaces: SpaceEntry[];\n tables: TableEntry[];\n functions: FunctionEntry[];\n}\n\n// Per-class metadata store, keyed by the class constructor. Member decorators\n// run during class-body evaluation (before the class decorator), so each\n// decorator get-or-creates the descriptor and they all converge on one entry.\nconst REGISTRY = new WeakMap<object, MuhkooAppDescriptor>();\n\nfunction descriptorFor(ctor: object): MuhkooAppDescriptor {\n let d = REGISTRY.get(ctor);\n if (!d) {\n d = { spaces: [], tables: [], functions: [] };\n REGISTRY.set(ctor, d);\n }\n return d;\n}\n\n/** Resolve the owning class constructor from a decorator `target` — the\n * prototype for instance members, the constructor itself for static ones. */\nfunction ctorOf(target: object): object {\n return typeof target === \"function\" ? target : (target as { constructor: object }).constructor;\n}\n\n/**\n * Class decorator. Declares the app's agent identity, purpose, and behavioral\n * guidance. Apply it to the class whose members carry the surface decorators.\n */\nexport function MuhkooAgent(meta: MuhkooAgentMeta): ClassDecorator {\n return (target) => {\n descriptorFor(target as unknown as object).agent = meta;\n };\n}\n\n/** Member decorator. Marks a channel/Space the agent can resolve and post to. */\nexport function MuhkooSpace(meta: MuhkooSpaceMeta): PropertyDecorator & MethodDecorator {\n return ((target: object, propertyKey: string | symbol) => {\n descriptorFor(ctorOf(target)).spaces.push({\n name: meta.name ?? String(propertyKey),\n description: meta.description,\n });\n }) as PropertyDecorator & MethodDecorator;\n}\n\n/** Member decorator. Marks an app database table the agent can query/mutate. */\nexport function MuhkooDB(meta: MuhkooDBMeta): PropertyDecorator & MethodDecorator {\n return ((target: object, propertyKey: string | symbol) => {\n descriptorFor(ctorOf(target)).tables.push({\n table: meta.table ?? String(propertyKey),\n access: meta.access ?? \"read\",\n description: meta.description,\n });\n }) as PropertyDecorator & MethodDecorator;\n}\n\n/** Member decorator. Marks a serverless function the agent can call. */\nexport function MuhkooFunction(meta: MuhkooFunctionMeta): PropertyDecorator & MethodDecorator {\n return ((target: object, propertyKey: string | symbol) => {\n descriptorFor(ctorOf(target)).functions.push({\n name: meta.name ?? String(propertyKey),\n description: meta.description,\n });\n }) as PropertyDecorator & MethodDecorator;\n}\n\n/** Read back the raw descriptor a class accumulated (for tooling/tests). */\nexport function getMuhkooAppDescriptor(appClass: Function): MuhkooAppDescriptor | undefined {\n return REGISTRY.get(appClass);\n}\n\n/**\n * Compose the agent system prompt from a `@MuhkooAgent`-decorated class. Throws\n * if the class isn't decorated. The result is the semantic layer only — the\n * runtime appends exact schema + the closed tool list at invocation time.\n */\nexport function ejectAgentPrompt(appClass: Function): string {\n const d = REGISTRY.get(appClass);\n if (!d || !d.agent) {\n throw new Error(\"ejectAgentPrompt: the class must be decorated with @MuhkooAgent\");\n }\n const { agent } = d;\n const lines: string[] = [];\n lines.push(`You are ${agent.name}. ${agent.purpose}`.trim());\n\n if (agent.guidance?.length) {\n lines.push(\"\", \"Guidance:\");\n for (const g of agent.guidance) lines.push(`- ${g}`);\n }\n\n if (d.spaces.length) {\n lines.push(\"\", \"Channels (Spaces) you can resolve with resolve_channel and post messages into:\");\n for (const s of d.spaces) lines.push(`- ${s.name}: ${s.description}`);\n }\n\n if (d.tables.length) {\n lines.push(\"\", \"App database tables:\");\n for (const t of d.tables) {\n const verbs = t.access === \"write\"\n ? \"read & write — db_query/db_get/db_insert/db_update/db_delete\"\n : \"read-only — db_query/db_get\";\n lines.push(`- ${t.table} (${verbs}): ${t.description}`);\n }\n }\n\n if (d.functions.length) {\n lines.push(\"\", \"Functions you can invoke with call_function:\");\n for (const f of d.functions) lines.push(`- ${f.name}: ${f.description}`);\n }\n\n if (agent.instructions?.trim()) {\n lines.push(\"\", agent.instructions.trim());\n }\n\n // How to respond — the load-bearing behavioral contract. Without this, models\n // (especially gpt-oss) tend to run tool calls and then end their turn with no\n // user-facing message, so the user sees the work happen but gets no reply.\n const hasTools = d.tables.length > 0 || d.functions.length > 0;\n lines.push(\"\", \"How to respond:\");\n if (hasTools) {\n lines.push(\n \"- When you need information or need to make a change, call your tools immediately — don't ask the user to do it, and don't describe or name the tools to them.\",\n \"- After your tool calls return, you MUST send one final reply to the channel, in plain language, that answers the request using the results.\",\n );\n }\n lines.push(\n \"- Always end your turn with a short written reply (one or two sentences). Never finish with only tool calls and no message, and never reply with an empty message.\",\n \"- Don't restate function names, parameters, JSON, or your list of tools to the user — just give them the answer.\",\n );\n\n lines.push(\n \"\",\n \"The exact columns, function parameters, and the full list of callable tools are supplied to you by the runtime. Follow that authoritative list — never invent tables, columns, functions, or tools.\",\n );\n\n return lines.join(\"\\n\");\n}\n\n/**\n * The tools-config shape the Muhkoo platform uses to gate an agent. Alias of\n * `client.agents`' {@link AgentToolsConfig} so {@link ejectAgentTools} output\n * drops straight into `client.agents.create({ tools })`.\n */\nexport type MuhkooAgentToolsConfig = AgentToolsConfig;\n\n/**\n * Derive a suggested tools allowlist from a decorated class — the db tables\n * (and whether any are writable), the callable functions, and whether channels\n * are in play. Pair with {@link ejectAgentPrompt} when configuring the agent.\n *\n * If any tables/functions are present the result has `enabled: true`; to\n * actually grant tools you must also pass a function-calling `model` in the same\n * `client.agents.create`/`update` call (the server enforces this).\n */\nexport function ejectAgentTools(appClass: Function, opts?: { maxIterations?: number }): AgentToolsConfig {\n const d = REGISTRY.get(appClass);\n if (!d) {\n throw new Error(\"ejectAgentTools: the class must be decorated with @MuhkooAgent\");\n }\n const anyWrite = d.tables.some((t) => t.access === \"write\");\n const mode = d.tables.length === 0 ? \"off\" : anyWrite ? \"write\" : \"read\";\n return {\n enabled: d.tables.length > 0 || d.functions.length > 0 || d.spaces.length > 0,\n db: { mode, tables: d.tables.map((t) => t.table) },\n functions: d.functions.map((f) => f.name),\n channels: d.spaces.length > 0,\n maxIterations: opts?.maxIterations ?? 6,\n };\n}\n","import Client from \"./Client\";\nimport { Logger } from \"../utilities/Logger\";\n\ndeclare global {\n var appLogger: InstanceType<typeof Logger>;\n}\n\nconst appLogger = new Logger(\"connect\", 'ERROR');\nglobalThis.appLogger = appLogger;\n\nexport {\n appLogger,\n Logger,\n Client,\n};\n\n// Unified client surface.\nexport { DEFAULT_BASE_URL } from \"./Client\";\nexport type { ClientOptions } from \"./Client\";\nexport { HttpClient, HttpError } from \"./HttpClient\";\nexport type { HttpClientOptions } from \"./HttpClient\";\nexport { SessionState, MemorySessionStore, LocalStorageSessionStore, defaultSessionStore } from \"./Session\";\nexport type { SessionStore, StoredSession } from \"./Session\";\nexport { Room } from \"./Room\";\nexport type { RoomDeps, RoomFileMetadata } from \"./Room\";\nexport { Space } from \"../spaces/Space\";\nexport type { SpaceDeps, SpaceFileMetadata, SpaceMessageEvent, EphemeralEvent, MessageDeletedEvent } from \"../spaces/Space\";\nexport { AuthNamespace, ZkAuth } from \"./namespaces/AuthNamespace\";\nexport type { AuthUser, RegisterParams, LoginOptions } from \"./namespaces/AuthNamespace\";\nexport { KvNamespace } from \"./namespaces/KvNamespace\";\nexport type { SetOptions, StorageChangeEvent } from \"./namespaces/KvNamespace\";\nexport { DbNamespace, DbTable } from \"./namespaces/DbNamespace\";\nexport type { DbFilterOp, DbWhereCondition, DbQuery, DbQueryResult } from \"./namespaces/DbNamespace\";\nexport { StorageNamespace } from \"./namespaces/FileNamespace\";\nexport type { WriteFileOptions } from \"./namespaces/FileNamespace\";\nexport { MessageNamespace } from \"./namespaces/MessageNamespace\";\nexport type { MessageSubscription } from \"./namespaces/MessageNamespace\";\nexport { SpaceNamespace, ChannelNotFoundError, ChannelExistsError } from \"./namespaces/SpaceNamespace\";\nexport type { SpaceNamespaceDeps } from \"./namespaces/SpaceNamespace\";\nexport { AgentsNamespace } from \"./namespaces/AgentsNamespace\";\nexport type {\n AgentConfig,\n AgentCreateInput,\n AgentUpdateInput,\n AgentProvisioned,\n AgentSkill,\n AgentTrigger,\n AgentTriggerType,\n AgentToolsConfig,\n AgentDbToolMode,\n AgentScopeOpts,\n AgentsNamespaceDeps,\n} from \"./namespaces/AgentsNamespace\";\nexport { FunctionsNamespace } from \"./namespaces/FunctionsNamespace\";\nexport type {\n FunctionConfig,\n FunctionDeployInput,\n FunctionUpdateInput,\n FunctionTriggers,\n FunctionTrigger,\n FunctionTriggerType,\n FunctionCaps,\n FunctionScopeOpts,\n FunctionsNamespaceDeps,\n} from \"./namespaces/FunctionsNamespace\";\n\n// App-describing decorators — declare your agent-facing surface in code and\n// eject a system prompt for a Programmable Agent.\nexport {\n MuhkooAgent,\n MuhkooSpace,\n MuhkooDB,\n MuhkooFunction,\n ejectAgentPrompt,\n ejectAgentTools,\n getMuhkooAppDescriptor,\n} from \"./agents/describe\";\nexport type {\n MuhkooAgentMeta,\n MuhkooSpaceMeta,\n MuhkooDBMeta,\n MuhkooFunctionMeta,\n MuhkooDBAccess,\n MuhkooAppDescriptor,\n MuhkooAgentToolsConfig,\n} from \"./agents/describe\";\n","/**\n * Cloudflare-Workers-compatible Groth16 ZK proof verifier.\n *\n * Drives the BN128 WASM module's exported pairing functions directly. Does NOT\n * use snarkjs/ffjavascript — those depend on runtime features (most notably\n * `URL.createObjectURL`) that CF Workers don't expose. See ROADMAP / CLAUDE.md.\n *\n * Two ways to initialize:\n * 1. `await initBn128Wasm()` — uses the bundled bn128.wasm (base64-inlined at\n * build time via `@rollup/plugin-wasm`). Works in any modern JS runtime\n * that allows runtime `WebAssembly.compile()` — Node, browsers, most\n * Workers configurations.\n * 2. `await initBn128Wasm(myWasmModule)` — accepts a pre-compiled\n * `WebAssembly.Module`. Lets a CF-Workers consumer keep the native pattern\n * of importing `.wasm` so wrangler precompiles it at deploy time and the\n * worker never pays for runtime compilation.\n */\n\nimport loadBundledBn128 from \"./wasm/bn128.wasm\";\nimport type { Groth16Proof, VerificationKey } from \"../types/zk\";\n\n// Re-export the shared ZK types so workers consumers can pull everything from\n// one place: `import { verifyGroth16, type Groth16Proof } from \"@muhkoo/connect\"`.\nexport type { Groth16Proof, VerificationKey } from \"../types/zk\";\nexport { PREIMAGE_POK_VERIFICATION_KEY } from \"../types/zk\";\n\n// BN128 curve sizing\nconst n8q = 32;\nconst n8r = 32;\nconst f1size = n8q;\nconst g1size = f1size * 3;\nconst g2size = f1size * 6;\nconst ftsize = f1size * 12;\n\n// Field modulus q (base field) and r (scalar field)\nconst q = BigInt(\"21888242871839275222246405745257275088696311157297823662689037894645226208583\");\nconst r = BigInt(\"21888242871839275222246405745257275088548364400416034343698204186575808495617\");\n\n// Initial linear memory: 25 * 64KB = 1.6MB\nconst MEM_SIZE = 25;\n\nexport interface Bn128WasmInstance {\n instance: WebAssembly.Instance;\n memory: WebAssembly.Memory;\n initialPFree: number;\n}\n\n/**\n * Initialize the BN128 WASM module.\n *\n * @param wasmModule Optional pre-compiled `WebAssembly.Module`. If omitted, the\n * bundled bn128.wasm (base64-inlined by `@rollup/plugin-wasm` at build time)\n * is used. Passing your own module is the recommended path inside CF Workers,\n * where wrangler can precompile a `.wasm` import at deploy time and avoid the\n * runtime compile cost.\n */\nexport async function initBn128Wasm(wasmModule?: WebAssembly.Module): Promise<Bn128WasmInstance> {\n const memory = new WebAssembly.Memory({ initial: MEM_SIZE, maximum: 32767 });\n const imports = { env: { memory } };\n\n let instance: WebAssembly.Instance;\n if (wasmModule) {\n instance = await WebAssembly.instantiate(wasmModule, imports);\n } else {\n // Bundled fallback: the rollup plugin returns a loader function that takes\n // an import object and resolves to an instantiated WebAssembly.Instance.\n instance = await loadBundledBn128(imports as Record<string, Record<string, unknown>>);\n }\n\n // The first u32 in linear memory is the heap free pointer (set by the module\n // during static initialization). Remember it so we can reset between calls.\n const u32 = new Uint32Array(memory.buffer);\n const initialPFree = u32[0];\n return { instance, memory, initialPFree };\n}\n\n/**\n * Verify a Groth16 proof.\n *\n * Returns `false` (rather than throwing) for any structural problem — malformed\n * proof, out-of-range field elements, off-curve points, or a failed pairing.\n * Throws only for runtime/WASM faults.\n */\nexport async function verifyGroth16(\n wasmInstance: WebAssembly.Instance,\n memory: WebAssembly.Memory,\n initialPFree: number,\n verificationKey: VerificationKey,\n proof: Groth16Proof,\n publicSignals: string[]\n): Promise<boolean> {\n try {\n const vk = unstringifyBigInts(verificationKey);\n const p = unstringifyBigInts(proof);\n const signals: bigint[] = unstringifyBigInts(publicSignals);\n\n // Validate proof coordinates are within the base field\n if (!validateG1InField(p.pi_a)) return false;\n if (!validateG1InField(p.pi_c)) return false;\n for (let i = 0; i < 2; i++) {\n for (let j = 0; j < 2; j++) {\n const val = typeof p.pi_b[i][j] === \"bigint\" ? p.pi_b[i][j] : BigInt(String(p.pi_b[i][j]));\n if (val >= q) return false;\n }\n }\n\n // Validate public signals are within the scalar field\n for (const signal of signals) {\n if (signal >= r) return false;\n }\n\n const exports = wasmInstance.exports;\n const u8 = new Uint8Array(memory.buffer);\n const u32 = new Uint32Array(memory.buffer);\n\n // Reset the WASM allocator's heap pointer between invocations\n u32[0] = initialPFree;\n\n const g1m_add = exports[\"g1m_add\"] as CallableFunction;\n const g1m_timesScalar = exports[\"g1m_timesScalar\"] as CallableFunction;\n const g1m_neg = exports[\"g1m_neg\"] as CallableFunction;\n const g1m_inCurve = exports[\"g1m_inCurve\"] as CallableFunction;\n const g2m_inCurve = exports[\"g2m_inCurve\"] as CallableFunction;\n const ftm_one = exports[\"ftm_one\"] as CallableFunction;\n const bn128_pairingEq4 = exports[\"bn128_pairingEq4\"] as CallableFunction;\n\n // Compute vk_x = IC[0] + sum(IC[i+1] * signal[i])\n const pVkX = alloc(u32, g1size);\n const pIC0 = alloc(u32, g1size);\n writeG1Point(u8, pIC0, vk.IC[0], exports);\n u8.set(u8.slice(pIC0, pIC0 + g1size), pVkX);\n\n const pTemp = alloc(u32, g1size);\n const pScalar = alloc(u32, n8r);\n\n for (let i = 0; i < signals.length; i++) {\n const pICi = alloc(u32, g1size);\n writeG1Point(u8, pICi, vk.IC[i + 1], exports);\n\n u8.set(bigIntToLE(signals[i], n8r), pScalar);\n g1m_timesScalar(pICi, pScalar, n8r, pTemp);\n\n const pSum = alloc(u32, g1size);\n g1m_add(pVkX, pTemp, pSum);\n u8.set(u8.slice(pSum, pSum + g1size), pVkX);\n }\n\n // Allocate proof points\n const pA = alloc(u32, g1size);\n const pNegA = alloc(u32, g1size);\n const pB = alloc(u32, g2size);\n const pC = alloc(u32, g1size);\n\n writeG1Point(u8, pA, p.pi_a, exports);\n writeG2Point(u8, pB, p.pi_b, exports);\n writeG1Point(u8, pC, p.pi_c, exports);\n\n // Subgroup / on-curve checks\n if (!g1m_inCurve(pA)) return false;\n if (!g2m_inCurve(pB)) return false;\n if (!g1m_inCurve(pC)) return false;\n\n g1m_neg(pA, pNegA);\n\n // Verification key points\n const pAlpha = alloc(u32, g1size);\n const pBeta = alloc(u32, g2size);\n const pGamma = alloc(u32, g2size);\n const pDelta = alloc(u32, g2size);\n\n writeG1Point(u8, pAlpha, vk.vk_alpha_1, exports);\n writeG2Point(u8, pBeta, vk.vk_beta_2, exports);\n writeG2Point(u8, pGamma, vk.vk_gamma_2, exports);\n writeG2Point(u8, pDelta, vk.vk_delta_2, exports);\n\n // Target: F12 element representing 1\n const pOne = alloc(u32, ftsize);\n ftm_one(pOne);\n\n // e(-A, B) * e(alpha, beta) * e(vk_x, gamma) * e(C, delta) == 1\n const result = bn128_pairingEq4(\n pNegA, pB,\n pAlpha, pBeta,\n pVkX, pGamma,\n pC, pDelta,\n pOne\n );\n\n return result === 1;\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\nfunction parseToBigInt(value: bigint | string | number): bigint {\n if (typeof value === \"string\") {\n if (/^0x[0-9a-fA-F]+$/.test(value)) return BigInt(value);\n if (/^[0-9a-fA-F]+$/.test(value) && /[a-fA-F]/.test(value)) return BigInt(\"0x\" + value);\n if (/^[0-9]+$/.test(value)) return BigInt(value);\n throw new Error(`Cannot convert ${value} to BigInt`);\n }\n if (typeof value === \"number\") return BigInt(value);\n return value;\n}\n\nfunction bigIntToLE(value: bigint | string | number, size: number): Uint8Array {\n const result = new Uint8Array(size);\n let v = parseToBigInt(value);\n for (let i = 0; i < size; i++) {\n result[i] = Number(v & 0xffn);\n v = v >> 8n;\n }\n return result;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction unstringifyBigInts(o: any): any {\n if (typeof o === \"string\") {\n try {\n if (/^[0-9]+$/.test(o) || /^0x[0-9a-fA-F]+$/.test(o) ||\n (/^[0-9a-fA-F]+$/.test(o) && /[a-fA-F]/.test(o))) {\n return parseToBigInt(o);\n }\n } catch {\n // fall through\n }\n return o;\n }\n if (Array.isArray(o)) return o.map(unstringifyBigInts);\n if (typeof o === \"object\" && o !== null) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const res: any = {};\n for (const k of Object.keys(o)) res[k] = unstringifyBigInts(o[k]);\n return res;\n }\n return o;\n}\n\nfunction validateG1InField(point: (bigint | string | number)[]): boolean {\n const x = typeof point[0] === \"bigint\" ? point[0] : BigInt(String(point[0]));\n const y = typeof point[1] === \"bigint\" ? point[1] : BigInt(String(point[1]));\n return x < q && y < q;\n}\n\nfunction writeG1Point(\n u8: Uint8Array,\n offset: number,\n point: (bigint | string | number)[],\n exports: WebAssembly.Exports\n): void {\n const x = point[0];\n const y = point[1];\n const z = point.length > 2 ? point[2] : 1n;\n\n u8.set(bigIntToLE(x, f1size), offset);\n u8.set(bigIntToLE(y, f1size), offset + f1size);\n u8.set(bigIntToLE(z, f1size), offset + 2 * f1size);\n\n const f1m_toMontgomery = exports[\"f1m_toMontgomery\"] as CallableFunction;\n f1m_toMontgomery(offset, offset);\n f1m_toMontgomery(offset + f1size, offset + f1size);\n f1m_toMontgomery(offset + 2 * f1size, offset + 2 * f1size);\n}\n\nfunction writeG2Point(\n u8: Uint8Array,\n offset: number,\n point: (bigint | string | number)[][],\n exports: WebAssembly.Exports\n): void {\n const x = point[0];\n const y = point[1];\n const z = point.length > 2 ? point[2] : [1n, 0n];\n\n u8.set(bigIntToLE(x[0], f1size), offset);\n u8.set(bigIntToLE(x[1], f1size), offset + f1size);\n u8.set(bigIntToLE(y[0], f1size), offset + 2 * f1size);\n u8.set(bigIntToLE(y[1], f1size), offset + 3 * f1size);\n u8.set(bigIntToLE(z[0], f1size), offset + 4 * f1size);\n u8.set(bigIntToLE(z[1], f1size), offset + 5 * f1size);\n\n const f1m_toMontgomery = exports[\"f1m_toMontgomery\"] as CallableFunction;\n for (let i = 0; i < 6; i++) {\n f1m_toMontgomery(offset + i * f1size, offset + i * f1size);\n }\n}\n\nfunction alloc(u32: Uint32Array, size: number): number {\n while (u32[0] & 3) u32[0]++;\n const ptr = u32[0];\n u32[0] += size;\n return ptr;\n}\n","/**\n * `PersonalSpaceClient` — the client-side counterpart to the accelerator's\n * `PersonalSpaceDO`. Wraps the `/api/personal/:commitment/*` HTTP protocol so\n * callers can `put` / `get` / `delete` / `list` per-user KV blobs without\n * thinking about challenges, nonces, or Groth16 proof generation.\n *\n * Every gated operation:\n * 1. Requests a one-shot challenge from the DO (`POST /challenge`).\n * 2. Converts the returned hex nonce into a BN254 field element.\n * 3. Generates a fresh Groth16 proof for the `preimagePoK` circuit using\n * snarkjs, with the user's secret/salt/ecdsaPub as private inputs and\n * `{commitment, nonce, ecdsaPubHash}` as public signals.\n * 4. POSTs the proof + publicSignals + (optional) value to the gated endpoint.\n *\n * snarkjs is loaded lazily (dynamic `import`) the first time a proof is\n * generated — it's an optional peer dependency that only the ZK-proof path\n * needs, so importing this module (or constructing a `Client`) never requires\n * it. Consumers using the proof path install `snarkjs`, or provide it via an\n * import map in the browser (see the README).\n *\n * Encryption of the stored values is the caller's responsibility — the DO\n * sees only opaque JSON. The companion `wrap.ts` helpers in this folder are\n * a convenient way to passphrase-encrypt a payload before putting it.\n */\n\nimport type { Groth16Proof } from \"../types/zk\";\n\ntype Snarkjs = {\n groth16: {\n fullProve: (\n input: unknown,\n wasm: string,\n zkey: string,\n ) => Promise<{ proof: unknown; publicSignals: string[] }>;\n };\n};\nlet _snarkjs: Snarkjs | null = null;\nasync function loadSnarkjs(): Promise<Snarkjs> {\n if (_snarkjs) return _snarkjs;\n _snarkjs = (await import(\"snarkjs\")) as unknown as Snarkjs;\n return _snarkjs;\n}\n\n/**\n * BN254 scalar field modulus. The DO's challenge endpoint returns a 32-byte\n * random hex nonce — but the Circom circuit expects a field element, so the\n * nonce is reduced mod this prime before being fed into the witness.\n *\n * Must stay in sync with the `nonce` public-signal width used by both\n * accelerator's `verifyZkAuthProof` and the `preimagePoK` circuit.\n */\nconst FIELD_SIZE = 21888242871839275222246405745257275088548364400416034343698204186575808495617n;\n\n/**\n * Constructor options for {@link PersonalSpaceClient}.\n *\n * All of `secret`, `salt`, `ecdsaPub`, and `ecdsaPubHash` are decimal-encoded\n * BigInt strings (snarkjs convention). `commitment` is likewise decimal — it's\n * the Poseidon hash of `(secret, salt, ecdsaPubHash)`.\n */\nexport interface PersonalSpaceClientOptions {\n /** Base URL of the accelerator, e.g. `http://localhost:8787`. */\n baseUrl: string;\n /** The user's Poseidon commitment as a decimal string (~78 digits). */\n commitment: string;\n /** ZK identity material — private inputs to the proof. Decimal BigInt string. */\n secret: string;\n /** ZK identity salt. Decimal BigInt string. */\n salt: string;\n /** Raw ECDSA public-key field representation. Decimal BigInt string. */\n ecdsaPub: string;\n /** Poseidon hash of `ecdsaPub`, used as a public signal. Decimal BigInt string. */\n ecdsaPubHash: string;\n /** Where the runtime can fetch the compiled circuit assets. */\n circuits: {\n /** URL of the `preimagePoK.wasm` witness generator. */\n wasmUrl: string;\n /** URL of the `preimagePoK_0001.zkey` proving key. */\n zkeyUrl: string;\n };\n}\n\n/** Shape of the DO's `/challenge` response. */\ninterface ChallengeResponse {\n challengeId: string;\n nonce: string; // hex\n commitment: string;\n}\n\n/** Body shape sent to every gated endpoint. `value` is only used by PUT. */\ninterface GatedBody {\n challengeId: string;\n proof: Groth16Proof;\n publicSignals: string[];\n value?: unknown;\n}\n\n/**\n * Reduce a hex nonce into a BN254 field-element decimal string, matching what\n * the Circom circuit expects as the `nonce` public signal.\n */\nfunction nonceHexToFieldString(nonceHex: string): string {\n const hex = nonceHex.startsWith(\"0x\") ? nonceHex : \"0x\" + nonceHex;\n return (BigInt(hex) % FIELD_SIZE).toString();\n}\n\n/**\n * Read the response body as JSON, falling back to text for the error message\n * when the body isn't JSON. Centralized so every method handles failures the\n * same way.\n */\nasync function parseOrThrow<T>(response: Response, label: string): Promise<T> {\n if (!response.ok) {\n let detail = \"\";\n try {\n const text = await response.text();\n detail = text ? `: ${text}` : \"\";\n } catch {\n // ignore — we'll just use the status code\n }\n throw new Error(`PersonalSpaceClient ${label} failed (${response.status})${detail}`);\n }\n return (await response.json()) as T;\n}\n\nexport class PersonalSpaceClient {\n private readonly baseUrl: string;\n private readonly commitment: string;\n private readonly secret: string;\n private readonly salt: string;\n private readonly ecdsaPub: string;\n private readonly ecdsaPubHash: string;\n private readonly wasmUrl: string;\n private readonly zkeyUrl: string;\n\n constructor(opts: PersonalSpaceClientOptions) {\n if (!opts.baseUrl) throw new Error(\"PersonalSpaceClient: `baseUrl` is required\");\n if (!opts.commitment) throw new Error(\"PersonalSpaceClient: `commitment` is required\");\n if (!opts.secret) throw new Error(\"PersonalSpaceClient: `secret` is required\");\n if (!opts.salt) throw new Error(\"PersonalSpaceClient: `salt` is required\");\n if (!opts.ecdsaPub) throw new Error(\"PersonalSpaceClient: `ecdsaPub` is required\");\n if (!opts.ecdsaPubHash) throw new Error(\"PersonalSpaceClient: `ecdsaPubHash` is required\");\n if (!opts.circuits?.wasmUrl || !opts.circuits?.zkeyUrl) {\n throw new Error(\"PersonalSpaceClient: `circuits.wasmUrl` and `circuits.zkeyUrl` are required\");\n }\n\n // Strip trailing slash so concatenation stays clean regardless of how\n // the caller formatted the base URL.\n this.baseUrl = opts.baseUrl.replace(/\\/+$/, \"\");\n this.commitment = opts.commitment;\n this.secret = opts.secret;\n this.salt = opts.salt;\n this.ecdsaPub = opts.ecdsaPub;\n this.ecdsaPubHash = opts.ecdsaPubHash;\n this.wasmUrl = opts.circuits.wasmUrl;\n this.zkeyUrl = opts.circuits.zkeyUrl;\n }\n\n /** Store `value` under `key`, replacing any prior value. */\n async put(key: string, value: unknown): Promise<void> {\n const { challengeId, proof, publicSignals } = await this.proveFreshChallenge();\n const url = `${this.baseUrl}/api/personal/${encodeURIComponent(this.commitment)}/kv/${encodeURIComponent(key)}`;\n const body: GatedBody = { challengeId, proof, publicSignals, value };\n const response = await this.fetch(url, \"POST\", body);\n await parseOrThrow<{ ok: true }>(response, `put(${key})`);\n }\n\n /** Fetch the value stored under `key`. Returns `null` if absent. */\n async get<T = unknown>(key: string): Promise<T | null> {\n const { challengeId, proof, publicSignals } = await this.proveFreshChallenge();\n const url = `${this.baseUrl}/api/personal/${encodeURIComponent(this.commitment)}/kv/${encodeURIComponent(key)}/get`;\n const body: GatedBody = { challengeId, proof, publicSignals };\n const response = await this.fetch(url, \"POST\", body);\n const data = await parseOrThrow<{ key: string; value: T | null }>(response, `get(${key})`);\n return data.value ?? null;\n }\n\n /** Remove `key` from the user's space. Returns whether the key existed. */\n async delete(key: string): Promise<boolean> {\n const { challengeId, proof, publicSignals } = await this.proveFreshChallenge();\n const url = `${this.baseUrl}/api/personal/${encodeURIComponent(this.commitment)}/kv/${encodeURIComponent(key)}`;\n const body: GatedBody = { challengeId, proof, publicSignals };\n const response = await this.fetch(url, \"DELETE\", body);\n const data = await parseOrThrow<{ ok: true; existed: boolean }>(response, `delete(${key})`);\n return data.existed;\n }\n\n /** List every key currently stored in the user's space. */\n async list(): Promise<string[]> {\n const { challengeId, proof, publicSignals } = await this.proveFreshChallenge();\n const url = `${this.baseUrl}/api/personal/${encodeURIComponent(this.commitment)}/list`;\n const body: GatedBody = { challengeId, proof, publicSignals };\n const response = await this.fetch(url, \"POST\", body);\n const data = await parseOrThrow<{ keys: string[] }>(response, \"list()\");\n return Array.isArray(data.keys) ? data.keys : [];\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n /**\n * Run the full pre-flight: ask the DO for a challenge, reduce the nonce to\n * a field element, and generate a fresh Groth16 proof. Returns everything\n * the gated endpoints need in their body.\n */\n private async proveFreshChallenge(): Promise<{\n challengeId: string;\n proof: Groth16Proof;\n publicSignals: string[];\n }> {\n const challenge = await this.requestChallenge();\n const nonceField = nonceHexToFieldString(challenge.nonce);\n\n // Inputs to the `preimagePoK` circuit. Public signals are\n // `[commitment, nonce, ecdsaPubHash]`; the rest are private witnesses.\n const input = {\n commitment: this.commitment,\n nonce: nonceField,\n ecdsaPubHash: this.ecdsaPubHash,\n secret: this.secret,\n salt: this.salt,\n ecdsaPub: this.ecdsaPub,\n };\n\n const snarkjs = await loadSnarkjs();\n const { proof, publicSignals } = await snarkjs.groth16.fullProve(\n input,\n this.wasmUrl,\n this.zkeyUrl,\n );\n\n return {\n challengeId: challenge.challengeId,\n proof: proof as unknown as Groth16Proof,\n publicSignals: publicSignals as string[],\n };\n }\n\n /** Hit `POST /challenge` and return the issued nonce + ID. */\n private async requestChallenge(): Promise<ChallengeResponse> {\n const url = `${this.baseUrl}/api/personal/${encodeURIComponent(this.commitment)}/challenge`;\n const response = await this.fetch(url, \"POST\", {});\n return await parseOrThrow<ChallengeResponse>(response, \"challenge\");\n }\n\n /**\n * Thin wrapper over `globalThis.fetch` so all methods share a single set of\n * headers and body-encoding behaviour. `globalThis.fetch` is available in\n * modern browsers, Node 18+, Workers, and Bun.\n */\n private async fetch(url: string, method: string, body: unknown): Promise<Response> {\n const fetchFn = globalThis.fetch;\n if (typeof fetchFn !== \"function\") {\n throw new Error(\n \"PersonalSpaceClient: `globalThis.fetch` is not available. \" +\n \"On older Node versions, install a fetch polyfill (e.g. undici).\",\n );\n }\n return await fetchFn(url, {\n method,\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body ?? {}),\n });\n }\n}\n","/**\n * PacketCipher — the strategy `Network` uses to seal/open a packet's payload.\n *\n * `Network` owns the wire shape (Message ↔ Packet, header placement, transport,\n * reconnect, checksum). The *encryption* is pluggable: the default\n * {@link DoubleRatchetCipher} reproduces the per-peer Double Ratchet behavior\n * Network has always had, while the Space layer supplies a group-key cipher.\n *\n * The sealed ciphertext always rides in `Packet.headers` (cleartext routing\n * fields stay readable to the server); `Packet.message` is left undefined on\n * the wire so the server never sees the real payload.\n */\n\nimport type { Packet } from \"../messaging/Packet\";\nimport type { DoubleRatchetManager, CipherMessage } from \"../crypto/DoubleRatchetManager\";\n\nexport type PacketHeaders = Packet[\"headers\"];\n\n/** Header fields a cipher merges into the outgoing packet. */\nexport type SealedHeaders = Record<string, string | number | boolean>;\n\nexport interface PacketCipher {\n /**\n * Seal the serialized `Message`. Returns the header fields to merge into\n * the outgoing packet (these carry the ciphertext). `Network` clears\n * `packet.message` after calling this.\n */\n seal(serializedMessage: string, packet: Packet): Promise<SealedHeaders>;\n\n /** True if the inbound headers look like this cipher's sealed form. */\n handles(headers: PacketHeaders): boolean;\n\n /**\n * Open an inbound packet's headers back into a serialized `Message` string.\n * Returns `null` when the packet is not sealed for / not decryptable by us\n * (e.g. an epoch key we don't hold) — `Network` then leaves `packet.message`\n * untouched rather than throwing.\n */\n open(headers: PacketHeaders): Promise<string | null>;\n}\n\nexport interface DoubleRatchetCipherDeps {\n ratchetManager: DoubleRatchetManager;\n clientId: string;\n serverId: string;\n sessionType: \"global\" | \"specific\";\n /** Resolves the live session id (Network manages the session lifecycle). */\n getSessionId: () => string | null;\n /** Whether this side is the ratchet \"client\" (default true). */\n isClient?: boolean;\n}\n\n/**\n * Default cipher: per-peer Double Ratchet. Reproduces Network's original\n * `{ encrypted: true, cipherMessage: <json> }` header convention exactly so\n * existing consumers are unaffected.\n */\nexport class DoubleRatchetCipher implements PacketCipher {\n constructor(private readonly deps: DoubleRatchetCipherDeps) {}\n\n async seal(serializedMessage: string): Promise<SealedHeaders> {\n const sessionId = this.deps.getSessionId();\n if (!sessionId) {\n throw new Error(\"DoubleRatchetCipher: no active session to seal under\");\n }\n const cipherMessage = await this.deps.ratchetManager.encrypt(\n this.deps.clientId,\n this.deps.serverId,\n sessionId,\n serializedMessage,\n false, // newDhKey — let the ratchet manage key rotation\n this.deps.sessionType,\n );\n return { encrypted: true, cipherMessage: JSON.stringify(cipherMessage) };\n }\n\n handles(headers: PacketHeaders): boolean {\n return !!(headers?.encrypted && headers?.cipherMessage);\n }\n\n async open(headers: PacketHeaders): Promise<string | null> {\n if (!this.handles(headers)) return null;\n const cipherMessage = JSON.parse(headers!.cipherMessage as string) as CipherMessage;\n return this.deps.ratchetManager.decrypt(cipherMessage, this.deps.isClient ?? true);\n }\n}\n","/**\n * Bundled-WASM loader for the RS codec.\n *\n * Isolated in its own module so the rollup-plugin-wasm `import` of `.wasm` is\n * only encountered when this file is actually evaluated. The main `rs.ts`\n * file dynamically imports this module only on the fallback path (no\n * pre-compiled `WebAssembly.Module` provided), which lets tools that can't\n * parse the `.wasm` import (vitest under vite, without `vite-plugin-wasm`)\n * import `rs.ts` cleanly as long as callers always supply a module.\n *\n * Production builds (rollup) hit this path via the bundled loader; tests\n * skip it entirely by passing a fs-loaded module to `initRsWasm`.\n */\n\nimport loadRsWasm from \"./wasm_reed_solomon_erasure_bg.wasm\";\n\n/** Re-exports the rollup-plugin-wasm loader shape. */\nexport default loadRsWasm;\n"],"names":["loadPoseidon","groth16Prove","groth16Verify","bytesToBase64","_snarkjs","loadSnarkjs","FIELD_SIZE","wasmEncode","wasmReconstruct","parseOrThrow","Room","appLogger"],"mappings":";;;;AAAA;;;;;;;AAOG;SAEa,SAAS,GAAA;AACrB,IAAA,MAAM,CAAC,GAA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