@muhkoo/connect 0.14.0-alpha.1 → 0.14.0-alpha.3
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/package.json +1 -1
- package/dist/browser/blockEngine.worker.js +0 -349
- package/dist/browser/blockEngine.worker.js.map +0 -1
- package/dist/browser/index.js +0 -15716
- package/dist/browser/index.js.map +0 -1
- package/dist/connect.d.ts +0 -7518
- package/dist/server/index.js +0 -15917
- package/dist/server/index.js.map +0 -1
- package/dist/workers/index.js +0 -2670
- package/dist/workers/index.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../src/utilities/Logger.ts","../../src/utilities/bytes.ts","../../src/utilities/index.ts","../../src/messaging/Message.ts","../../src/messaging/Packet.ts","../../src/messaging/decorators.ts","../../src/messaging/index.ts","../../src/types/zk.ts","../../src/crypto/primitives/subtle.ts","../../src/crypto/primitives/random.ts","../../src/crypto/primitives/aes-gcm.ts","../../src/crypto/primitives/kdf.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/events/EventCore.ts","../../src/sessions/EncryptedSession.ts","../../src/transport/WSTransport.ts","../../src/sessions/BroadcastChannel.ts","../../src/workers/groth16-verifier.ts","../../src/personal/PersonalSpaceClient.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/auth/AuthClient.ts","../../src/auth/identity.ts","../../src/auth/poseidon.ts","../../src/auth/proof.ts","../../src/auth/keys.ts","../../src/auth/vault.ts","../../src/auth/hostedHandoff.ts","../../src/version.ts","../../src/core/HttpClient.ts","../../src/core/Session.ts","../../src/auth/recoveryPhrase.ts","../../src/auth/oprf.ts","../../src/auth/gatedFactor.ts","../../src/auth/passkey.ts","../../src/auth/deviceStore.ts","../../src/core/namespaces/HostedAuth.ts","../../src/core/namespaces/AuthNamespace.ts","../../src/crypto/StorageCipher.ts","../../src/core/namespaces/KvNamespace.ts","../../src/core/namespaces/DbNamespace.ts","../../src/core/namespaces/FileNamespace.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/offline/crdt/MessageLog.ts","../../src/offline/SpaceCache.ts","../../src/offline/cache/ShardCache.ts","../../src/p2p/PeerExchange.ts","../../src/p2p/signaling/SpaceSignaler.ts","../../src/p2p/transport/WebRtcTransport.ts","../../src/p2p/transport/PeerTransport.ts","../../src/p2p/worker/protocol.ts","../../src/p2p/worker/blockEngine.ts","../../src/p2p/worker/engineHost.ts","../../src/p2p/worker/engineClient.ts","../../src/p2p/PeerNetwork.ts","../../src/p2p/detect.ts","../../src/core/namespaces/SpaceNamespace.ts","../../src/core/namespaces/AgentsNamespace.ts","../../src/core/namespaces/FunctionsNamespace.ts","../../src/core/namespaces/AccessTokensNamespace.ts","../../src/vfs/types.ts","../../src/vfs/recordCipher.ts","../../src/vfs/paths.ts","../../src/vfs/glob.ts","../../src/vfs/VfsNamespace.ts","../../src/vcs/hash.ts","../../src/vcs/merge3.ts","../../src/vcs/types.ts","../../src/vcs/VcsNamespace.ts","../../src/core/ChatKeyVault.ts","../../src/offline/clock/HlcTimestamp.ts","../../src/offline/clock/HLC.ts","../../src/offline/ConnectivityManager.ts","../../src/offline/OutboundQueue.ts","../../src/offline/SyncEngine.ts","../../src/offline/errors.ts","../../src/offline/namespaces/SnapshotNamespace.ts","../../src/offline/store/schema.ts","../../src/offline/OfflineManager.ts","../../src/offline/detect.ts","../../src/offline/store/idb.ts","../../src/offline/store/IndexedDbStore.ts","../../src/offline/store/NoopStore.ts","../../src/offline/crdt/LWWRegister.ts","../../src/offline/KvCache.ts","../../src/offline/DbCache.ts","../../src/core/Client.ts","../../src/core/agents/describe.ts","../../src/offline/crdt/LWWMap.ts","../../src/offline/crdt/ORSet.ts","../../src/network/PacketCipher.ts","../../src/browser/index.ts","../../src/storage/encoding/ReedSolomon/wasm/bundled-loader.ts"],"sourcesContent":["// 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 { _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 * 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","/**\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","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 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 this.registeredUsers.set(clientId, { commitment, salt });\n // NB: never log `secret`, `salt`, or `commitment` — `salt` is a private\n // witness for the ZK circuit and `commitment` is the user's stable id.\n appLogger.debug(`Registered ZK identity for ${clientId}`);\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","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 // Offline layer — connectivity + background sync lifecycle. Emitted by the\n // ConnectivityManager / SyncEngine; apps subscribe to drive a status UI.\n ONLINE = \"online\",\n OFFLINE = \"offline\",\n SYNCING = \"syncing\",\n SYNC_PROGRESS = \"sync_progress\",\n SYNC_COMPLETE = \"sync_complete\",\n SYNC_ERROR = \"sync_error\",\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;","/**\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 * 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 * 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 * 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 * 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\n/** Peer head-start (ms) before origin joins the race in {@link ShardClient.getShard}. */\nconst HEDGE_MS = 500;\n\n/**\n * A content-addressed byte cache for shards (the offline layer's `ShardCache`\n * satisfies this structurally). Declared here as a minimal interface so the\n * storage layer doesn't import the offline module — keeping the dependency\n * arrow one-way (offline → storage).\n */\nexport interface ShardByteCache {\n get(hash: string): Promise<Uint8Array | null>;\n put(hash: string, bytes: Uint8Array): Promise<void>;\n}\n\n/**\n * A peer block source (the p2p layer's `PeerExchange` satisfies this\n * structurally). Consulted between the local cache and origin: a block fetched\n * from a peer is verified by hash before use. Declared here so the storage layer\n * doesn't import the p2p module (dependency arrow stays p2p → storage).\n */\nexport interface PeerBlockSource {\n getBlock(hash: string, opts?: { timeoutMs?: number }): Promise<Uint8Array | null>;\n announce(hash: string): void;\n}\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 * Optional offline byte cache. When present, GETs are served cache-first and\n * populated on success, and PUTs write the cache before the network so a\n * just-uploaded file reads back offline. See {@link ShardByteCache}.\n */\n cache?: ShardByteCache;\n /**\n * Called when a PUT can't reach the network (offline). Lets the caller queue\n * the upload for replay on reconnect; the bytes are already in {@link cache}\n * keyed by `hash`, so only the hash needs recording.\n */\n deferUpload?: (hash: string) => Promise<void>;\n /**\n * Optional peer block source. When present, GETs try peers between the local\n * cache and origin (peer blocks are verified by hash); PUTs announce the new\n * block to peers. Best-effort — any failure falls through to origin.\n */\n peers?: PeerBlockSource;\n /**\n * When true, {@link ShardClient.putShard} returns as soon as the shard is\n * written to {@link cache} and announced to {@link peers} — the origin PUT is\n * fired in the BACKGROUND rather than awaited. This makes a large write's\n * manifest available immediately (so a peer/worker can start pulling the\n * shards over P2P right away) while origin catches up as a durable fallback.\n * On a background-PUT failure the shard is handed to {@link deferUpload} (if\n * present) for replay. Requires a {@link cache} so the bytes survive locally\n * until the background upload lands. No-op without a cache.\n */\n backgroundUpload?: boolean;\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 private readonly cache?: ShardByteCache;\n private readonly deferUpload?: (hash: string) => Promise<void>;\n private readonly peers?: PeerBlockSource;\n private readonly backgroundUpload: boolean;\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 this.cache = opts.cache;\n this.deferUpload = opts.deferUpload;\n this.peers = opts.peers;\n // Background upload needs a local cache to hold the bytes until the PUT\n // lands; without one it would race the reader against a not-yet-uploaded\n // origin, so we quietly ignore the flag when there's no cache.\n this.backgroundUpload = Boolean(opts.backgroundUpload && opts.cache);\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 // Write the cache first so a just-uploaded file reads back even if the\n // network PUT then fails (offline). The bytes are content-addressed, so\n // this is safe to keep regardless of upload outcome.\n if (this.cache) await this.cache.put(hash, bytes);\n // Tell the swarm we now hold this block, so peers can pull it from us.\n if (this.peers) this.peers.announce(hash);\n // Background mode: the bytes are cached + announced, so return now and let\n // origin catch up asynchronously (a peer can already pull this block). The\n // PUT is enqueued through a bounded worker pool so a big file doesn't fire\n // hundreds of concurrent uploads at once.\n if (this.backgroundUpload) {\n this.enqueueBackgroundUpload(url, hash);\n return { dedup: false };\n }\n let response: Response;\n try {\n 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 } catch (err) {\n // Network unreachable (offline). If a defer hook is wired, queue the\n // upload for replay and report success — the bytes are cached.\n if (this.deferUpload) {\n await this.deferUpload(hash);\n return { dedup: false };\n }\n throw err;\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 // ── bounded background-upload pool (backgroundUpload mode) ──\n private bgActive = 0;\n private readonly bgQueue: Array<() => void> = [];\n private static readonly BG_CONCURRENCY = 6;\n\n /** Queue a shard's origin PUT to run in the background under a concurrency\n * cap. Bytes are re-read from {@link cache} at upload time (not held in the\n * queue) so a large file's backlog doesn't pin a second copy in memory. */\n private enqueueBackgroundUpload(url: string, hash: string): void {\n const run = async () => {\n this.bgActive++;\n try {\n const bytes = this.cache ? await this.cache.get(hash) : null;\n if (bytes) await this.uploadToOrigin(url, hash, bytes);\n } catch {\n // Origin unreachable/failed — queue for replay if we can; otherwise\n // the block is still cached + peer-served, so a later re-PUT covers it.\n if (this.deferUpload) { try { await this.deferUpload(hash); } catch { /* best-effort */ } }\n } finally {\n this.bgActive--;\n const next = this.bgQueue.shift();\n if (next) next();\n }\n };\n if (this.bgActive < ShardClient.BG_CONCURRENCY) void run();\n else this.bgQueue.push(() => void run());\n }\n\n /** PUT the shard bytes to origin, verifying the server accepted them.\n * Used by the background-upload path; throws on network/HTTP failure. */\n private async uploadToOrigin(url: string, hash: string, bytes: Uint8Array): Promise<void> {\n const response = await this.fetchFn(url, {\n method: \"PUT\",\n headers: { \"content-type\": \"application/octet-stream\" },\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 }\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 // Cache-first: a hit is content-verified by construction (key == hash).\n if (this.cache) {\n const cached = await this.cache.get(hash);\n if (cached) return cached;\n }\n // No peers → straight to origin.\n if (!this.peers) return this.fetchFromOrigin(hash);\n\n // HEDGED RACE: prefer a peer (saves origin egress) but never let a slow\n // or missing peer stall delivery — give the peer a short head start, then\n // start origin in parallel and take whichever returns the block first.\n const peers = this.peers;\n return new Promise<Uint8Array | null>((resolve, reject) => {\n let done = false;\n let originStarted = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const win = (b: Uint8Array | null) => {\n if (done) return;\n done = true;\n if (timer) clearTimeout(timer);\n resolve(b);\n };\n const fail = (e: unknown) => {\n if (!done) { done = true; reject(e); }\n };\n const startOrigin = () => {\n if (originStarted || done) return;\n originStarted = true;\n if (timer) { clearTimeout(timer); timer = null; }\n this.fetchFromOrigin(hash).then(win, fail);\n };\n timer = setTimeout(startOrigin, HEDGE_MS);\n peers.getBlock(hash).then(\n (b) => {\n if (b) {\n if (this.cache) void this.cache.put(hash, b);\n win(b); // peer delivered first\n } else {\n startOrigin(); // peer miss → don't wait out the hedge\n }\n },\n () => startOrigin(), // peer error → origin now\n );\n });\n }\n\n /** Fetch a shard from origin. Returns `null` for 404 (or offline when a\n * cache is present, so RS recovery can proceed); throws otherwise. */\n private async fetchFromOrigin(hash: string): Promise<Uint8Array | null> {\n const url = this.urlForHash(hash);\n let response: Response;\n try {\n response = await this.fetchFn(url, { method: \"GET\" });\n } catch (err) {\n if (this.cache) return null;\n throw err;\n }\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 bytes = new Uint8Array(await response.arrayBuffer());\n if (this.cache) void this.cache.put(hash, bytes);\n return bytes;\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 fileId = input.fileId ?? generateId();\n const createdAt = Date.now();\n const chunks: ChunkManifest[] = [];\n\n // Read the source per-chunk so the peak memory footprint stays at\n // ~chunkSize even for multi-GB files. A Blob/File is sliced lazily (only\n // the current chunk's bytes are materialized) — reading the whole thing\n // up front would blow past the browser's ~2GB ArrayBuffer cap and throw\n // \"the file could not be read\". A caller that already has the bytes in a\n // Uint8Array just gets zero-copy subarray views.\n const asBytes = input.data instanceof Uint8Array ? input.data : null;\n const size = asBytes ? asBytes.length : (input.data as Blob).size;\n const readChunk = async (start: number, end: number): Promise<Uint8Array> =>\n asBytes ? asBytes.subarray(start, end)\n : new Uint8Array(await (input.data as Blob).slice(start, end).arrayBuffer());\n\n const totalChunks = Math.max(1, Math.ceil(size / this.chunkSize));\n input.onProgress?.(0, totalChunks);\n\n // Within a chunk, the shard uploads are parallelized up to `this.concurrency`.\n for (let chunkIndex = 0; chunkIndex * this.chunkSize < Math.max(1, size); chunkIndex++) {\n const start = chunkIndex * this.chunkSize;\n const end = Math.min(start + this.chunkSize, size);\n const plaintext = await readChunk(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 (size === 0) break;\n }\n\n const manifest: FileManifest = {\n id: fileId,\n name: input.metadata.name,\n size,\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 * Streaming inverse of {@link writeFileToShards}: yields each chunk's\n * decrypted plaintext in order WITHOUT concatenating. Peak memory stays at\n * ~one chunk, so multi-GB files (which overflow a single `Uint8Array`) can be\n * piped straight to a file/socket. Same shard sourcing (cache → peers →\n * origin) and per-chunk auth as {@link readFileFromShards}.\n */\n async *readChunksFromShards(manifest: FileManifest): AsyncGenerator<Uint8Array> {\n await this.codec.ready(this.rsWasmModule);\n for (const chunkManifest of [...manifest.chunks].sort((a, b) => a.chunkIndex - b.chunkIndex)) {\n yield await this.readChunk(chunkManifest);\n }\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\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 * 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/** A vault factor record (M1.0 + M2 gated types). Wrap/iv are base64 AES-GCM; absent for phrase. */\nexport interface VaultFactor {\n id: string;\n type: \"password\" | \"passkey\" | \"phrase-marker\" | \"email\" | \"google\" | \"device\";\n wrap?: string;\n iv?: string;\n params?: Record<string, unknown>;\n label?: string;\n createdAt?: number;\n /** Display hint for gated factors (\"m•••@gmail.com\") — list responses only. */\n masked?: string;\n /** Passkey's origin (RP id) — list responses only. A passkey only unlocks\n * from this host or a subdomain of it, so apps on several hosts enroll one\n * per origin. */\n rpId?: 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 // ---- Identity vault (M1.0) ----------------------------------------------\n\n /** Blinded OPRF evaluation — the server-gated half of a password/recovery wrap key. */\n async oprfEvaluate(username: string, blinded: string): Promise<{ evaluated: string }> {\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/oprf`, this.json(\"POST\", { username, blinded }));\n return await this.parse<{ evaluated: string }>(\"oprfEvaluate\", res);\n }\n\n /**\n * Gated split-key OPRF evaluation (M2 — email/google factors). Requires a\n * live `verifyToken` from {@link emailOtpVerify}; returns BOTH trust\n * domains' evaluations. The recover token is consumed by this call.\n */\n async oprfEvaluateGated(\n username: string,\n blinded: string,\n factorType: \"email\" | \"google\",\n purpose: \"enroll\" | \"recover\",\n verifyToken: string,\n ): Promise<{ evaluated: string; evaluated2: string }> {\n const res = await this.fetchFn(\n `${this.baseUrl}/api/auth/oprf`,\n this.json(\"POST\", { username, blinded, factorType, purpose, verifyToken }),\n );\n return await this.parse<{ evaluated: string; evaluated2: string }>(\"oprfEvaluateGated\", res);\n }\n\n /**\n * Request an email OTP. With a session `token` this is the ENROLL flow\n * (code sent to `email`); without one it's RECOVER (code sent to the\n * account's enrolled address — the response is uniform either way).\n */\n async emailOtpStart(opts: { token?: string; email?: string; username?: string }): Promise<void> {\n const init = this.json(\"POST\", { email: opts.email, username: opts.username });\n if (opts.token) (init.headers as Record<string, string>)[\"X-Muhkoo-Session\"] = opts.token;\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/email/start`, init);\n await this.parse<{ sent: boolean }>(\"emailOtpStart\", res);\n }\n\n /** Trade an emailed code for a single-use verifyToken (+ the proven address). */\n async emailOtpVerify(opts: { code: string; token?: string; username?: string }): Promise<{ verifyToken: string; email: string }> {\n const init = this.json(\"POST\", { code: opts.code, username: opts.username });\n if (opts.token) (init.headers as Record<string, string>)[\"X-Muhkoo-Session\"] = opts.token;\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/email/verify`, init);\n return await this.parse<{ verifyToken: string; email: string }>(\"emailOtpVerify\", res);\n }\n\n /**\n * Verify a Google ID token (M2.3). With a session `token` it's the ENROLL\n * gate; without, it's RECOVER/LOGIN (the Google account must already be\n * linked). Returns a single-use verifyToken bound to the account's `sub`.\n */\n async googleVerify(opts: { idToken: string; token?: string; username?: string }): Promise<{ verifyToken: string; sub: string; emailHint: string | null }> {\n const init = this.json(\"POST\", { idToken: opts.idToken, username: opts.username });\n if (opts.token) (init.headers as Record<string, string>)[\"X-Muhkoo-Session\"] = opts.token;\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/google/verify`, init);\n return await this.parse<{ verifyToken: string; sub: string; emailHint: string | null }>(\"googleVerify\", res);\n }\n\n // ---- Hosted-auth authorization-code flow (H0) ---------------------------\n\n /** Mint a single-use authorization code for an app (called by the hosted page; session-authed). */\n async grant(token: string, body: { appId: string; redirectUri: string; codeChallenge: string; sealedKeys: string }): Promise<{ code: string }> {\n const init = this.json(\"POST\", body);\n (init.headers as Record<string, string>)[\"X-Muhkoo-Session\"] = token;\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/grant`, init);\n return await this.parse<{ code: string }>(\"grant\", res);\n }\n\n /** Exchange an authorization code + PKCE verifier for the session + sealed key material. */\n async token(body: { code: string; codeVerifier: string; appId?: string }): Promise<{ sessionToken: string; username: string; commitment: string; sealedKeys: string; appId: string }> {\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/token`, this.json(\"POST\", body));\n return await this.parse<{ sessionToken: string; username: string; commitment: string; sealedKeys: string; appId: string }>(\"token\", res);\n }\n\n /**\n * Read a factor record for `username` (returns an indistinguishable decoy if\n * absent). Gated types (email) require the recover `verifyToken`.\n */\n async vaultRead(\n username: string,\n factorType: VaultFactor[\"type\"],\n verifyToken?: string,\n /** Passkeys are per-origin: naming the caller's host returns THAT origin's\n * passkey instead of whichever was enrolled first (which WebAuthn would\n * refuse). Ignored for other factor types. */\n rpId?: string,\n /** Device factors are selected by id — a user may have many machines. */\n factorId?: string,\n ): Promise<{ factor: VaultFactor | null }> {\n const res = await this.fetchFn(\n `${this.baseUrl}/api/auth/vault`,\n this.json(\"POST\", { username, factorType, verifyToken, rpId, factorId }),\n );\n return await this.parse<{ factor: VaultFactor | null }>(\"vaultRead\", res);\n }\n\n /**\n * Add/replace a factor (session-authed; the seed is already wrapped\n * client-side). Email factors additionally require (and consume) the\n * enroll `verifyToken`; the stored address must be the verified one.\n */\n async vaultPutFactor(token: string, factor: VaultFactor, verifyToken?: string): Promise<{ ok: boolean; id: string }> {\n const init = this.json(\"PUT\", { factor, verifyToken });\n (init.headers as Record<string, string>)[\"Authorization\"] = `Bearer ${token}`;\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/vault/factor`, init);\n return await this.parse<{ ok: boolean; id: string }>(\"vaultPutFactor\", res);\n }\n\n /** List the user's factor metadata (no ciphertext). Session-authed. */\n async vaultFactors(token: string): Promise<{ factors: VaultFactor[]; migrated: boolean }> {\n const init: RequestInit = { method: \"GET\", headers: { Authorization: `Bearer ${token}` } };\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/vault/factors`, init);\n return await this.parse<{ factors: VaultFactor[]; migrated: boolean }>(\"vaultFactors\", res);\n }\n\n /** Remove a factor by id (can't remove the last one). Session-authed. */\n async vaultDeleteFactor(token: string, id: string): Promise<{ deleted: boolean }> {\n const res = await this.fetchFn(`${this.baseUrl}/api/auth/vault/factor`, {\n method: \"DELETE\",\n headers: { \"Content-Type\": \"application/json\", Authorization: `Bearer ${token}` },\n body: JSON.stringify({ id }),\n });\n return await this.parse<{ deleted: boolean }>(\"vaultDeleteFactor\", 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 const seed = await deriveMasterSeedFromPassword(username, password);\n return deriveIdentityFromSeed(seed);\n}\n\n/**\n * Legacy master-seed derivation: `PBKDF2(password, \"muhkoo-zk-v1:\"||username)`.\n *\n * This was the *only* path pre-vault, where the identity descended directly from\n * the password. It's kept so existing accounts still re-derive their seed (and\n * the vault can adopt that exact seed on migration, preserving the commitment).\n * New accounts use a random seed (`vault.randomSeed`) instead, so their identity\n * is no longer a function of the password.\n */\nexport async function deriveMasterSeedFromPassword(username: string, password: string): Promise<Uint8Array> {\n return pbkdf2Bytes(password, \"muhkoo-zk-v1:\" + username, SCALAR_BYTES);\n}\n\n/**\n * Derive the (unchanged) ZK identity from a 32-byte **master seed**. The seed is\n * HKDF-expanded into secret/salt + the P-256 ECDSA & ECDH keypairs exactly as\n * before — so the resulting commitment is byte-identical for a given seed. The\n * vault wraps THIS seed under each recovery factor.\n */\nexport async function deriveIdentityFromSeed(seed: Uint8Array): Promise<ZkIdentity> {\n if (!(seed instanceof Uint8Array) || seed.length !== SCALAR_BYTES) {\n throw new Error(`deriveIdentityFromSeed: expected a ${SCALAR_BYTES}-byte seed`);\n }\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 * Identity vault primitives (M1.0).\n *\n * The vault decouples the identity from the password: a random 32-byte **master\n * seed** yields the (unchanged) ZK identity via {@link deriveIdentityFromSeed},\n * and that seed is AES-256-GCM-wrapped under one key *per factor* (password,\n * passkey, recovery phrase). Server stores only ciphertext.\n *\n * This module holds the PURE primitives (seed gen, the memory-hard password\n * pre-hash, AES-GCM wrap/unwrap, the OPRF -> wrap-key HKDF). The networked\n * orchestration (calling the server's OPRF endpoint, fetching/storing factor\n * records) lives in the AuthNamespace, which has transport access.\n *\n * Memory-hard KDF: we use **scrypt** (vetted, in `@noble/hashes`, runs in\n * browser + Workers + Node - no wasm dependency) instead of argon2id; it is the\n * pre-hash fed into the OPRF, so even if the OPRF key ever leaked, guesses still\n * pay the scrypt cost.\n */\n\nimport { scrypt } from \"@noble/hashes/scrypt.js\";\n\nconst TE = new TextEncoder();\n\n// Interactive-login scrypt params (~100ms on a laptop). N must be a power of 2.\nconst SCRYPT = { N: 1 << 15, r: 8, p: 1, dkLen: 32 } as const;\n\n/** 32 random bytes - the master seed for a brand-new identity. */\nexport function randomSeed(): Uint8Array {\n return crypto.getRandomValues(new Uint8Array(32));\n}\n\n/** Memory-hard pre-hash of the password - the OPRF input. Salted by username. */\nexport function passwordPreHash(username: string, password: string): Uint8Array {\n return scrypt(TE.encode(password), TE.encode(\"muhkoo-vault-v1:\" + username.toLowerCase()), SCRYPT);\n}\n\n/** HKDF the 64-byte OPRF output into a non-extractable AES-256-GCM wrap key. */\nexport async function wrapKeyFromOprf(oprfOutput: Uint8Array): Promise<CryptoKey> {\n const prk = await crypto.subtle.importKey(\"raw\", oprfOutput as BufferSource, { name: \"HKDF\" }, false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey(\n { name: \"HKDF\", hash: \"SHA-256\", salt: new Uint8Array() as BufferSource, info: TE.encode(\"muhkoo-vault-wrap\") as BufferSource },\n prk,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"encrypt\", \"decrypt\"],\n );\n}\n\n/** HKDF arbitrary 32-byte key material (e.g. a passkey PRF output) into an AES-GCM wrap key. */\nexport async function wrapKeyFromBytes(keyMaterial: Uint8Array, info: string): Promise<CryptoKey> {\n const prk = await crypto.subtle.importKey(\"raw\", keyMaterial as BufferSource, { name: \"HKDF\" }, false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey(\n { name: \"HKDF\", hash: \"SHA-256\", salt: new Uint8Array() as BufferSource, info: TE.encode(info) as BufferSource },\n prk,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"encrypt\", \"decrypt\"],\n );\n}\n\n/** A seed wrapped under a factor key - what the server stores (base64). */\nexport interface WrappedSeed {\n iv: string;\n ct: string;\n}\n\nexport async function wrapSeed(seed: Uint8Array, key: CryptoKey): Promise<WrappedSeed> {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = await crypto.subtle.encrypt({ name: \"AES-GCM\", iv }, key, seed as BufferSource);\n return { iv: toBase64(iv), ct: toBase64(new Uint8Array(ct)) };\n}\n\n/** Decrypt a wrapped seed. Throws (AES-GCM tag failure) on a wrong key. */\nexport async function unwrapSeed(wrapped: WrappedSeed, key: CryptoKey): Promise<Uint8Array> {\n const pt = await crypto.subtle.decrypt(\n { name: \"AES-GCM\", iv: fromBase64(wrapped.iv) as BufferSource },\n key,\n fromBase64(wrapped.ct) as BufferSource,\n );\n return new Uint8Array(pt);\n}\n\nexport function toBase64(bytes: Uint8Array): string {\n let s = \"\";\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);\n return btoa(s);\n}\n\nexport function fromBase64(b64: string): Uint8Array {\n const s = atob(b64);\n const out = new Uint8Array(s.length);\n for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);\n return out;\n}\n","/**\n * Hosted-auth handoff crypto (auth.muhkoo.dev — AUTH_HOSTED_PLAN.md §3).\n *\n * The hosted page authenticates the user and ends up holding the master seed.\n * To pass it to the developer's app without it ever sitting server-readable or\n * landing in browser history:\n *\n * 1. {@link sealSeed} generates a one-time key K_t, AES-256-GCM-seals the seed\n * under it, and returns the ciphertext envelope (`sealedKeys`, stored in\n * the grant the server relays but can't read) plus K_t (`fragmentKey`,\n * placed ONLY in the redirect URL fragment — fragments never hit a server).\n * 2. The app exchanges the code for `sealedKeys`, reads K_t from the fragment,\n * and {@link unsealSeed} recovers the seed, then strips the fragment.\n *\n * Trust-equivalent to today's embedded SDK (the app still ends up with the\n * seed) while moving credential entry onto the Muhkoo origin. The envelope is\n * versioned so a future per-app-key handoff (v2) can swap in without a protocol\n * change.\n *\n * ## v2 — device pairing (TV / no-redirect handoff)\n *\n * v1's K_t rides in the redirect URL *fragment*, which works only because the\n * receiving app is a browser page that can read `location.hash`. A TV app has\n * no redirect to receive: it polls. So v2 keeps the *entire* v1 shape — the\n * server relays a sealed envelope it cannot read — and replaces only the key\n * agreement:\n *\n * - the TV generates an ephemeral P-256 ECDH keypair in memory and publishes\n * the public half ({@link generateDevicePairingKeypair});\n * - the hosted page (the component that already holds the unlocked seed and\n * already owns sealing) seals *to that public key* with a fresh ephemeral\n * keypair of its own ({@link sealSeedToDevice}) — ECDH → HKDF-SHA256 →\n * AES-256-GCM;\n * - the TV recovers the seed with its private key\n * ({@link unsealSeedFromDevice}).\n *\n * The server stores and relays the v2 envelope byte-for-byte, exactly as it\n * does for v1, and can read neither. The one thing ECDH cannot supply is proof\n * that the public key the hosted page sealed to is *the TV's* rather than an\n * attacker's — that is what {@link pairingVerificationCode} is for, and it is\n * the only MITM defence in the flow (see the entropy note on that function).\n */\n\nimport { toBase64, fromBase64 } from \"./vault\";\n\nconst TE = new TextEncoder();\nconst TD = new TextDecoder();\n\ninterface SealedEnvelope {\n v: 1;\n iv: string; // base64\n ct: string; // base64\n}\n\ninterface SealedEnvelopeV2 {\n v: 2;\n /** base64 raw (SEC1 uncompressed) P-256 public key of the SEALER's ephemeral keypair. */\n epk: string;\n iv: string; // base64\n ct: string; // base64\n}\n\nexport interface SealedHandoff {\n /** base64 JSON envelope — relayed by the server in the grant; server-opaque. */\n sealedKeys: string;\n /** base64url one-time key — rides ONLY in the redirect URL fragment. */\n fragmentKey: string;\n}\n\n/** Seal the master seed under a fresh one-time key for the redirect handoff. */\nexport async function sealSeed(seed: Uint8Array): Promise<SealedHandoff> {\n const ktRaw = crypto.getRandomValues(new Uint8Array(32));\n const key = await crypto.subtle.importKey(\"raw\", ktRaw as BufferSource, { name: \"AES-GCM\" }, false, [\"encrypt\"]);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv: iv as BufferSource }, key, seed as BufferSource));\n const envelope: SealedEnvelope = { v: 1, iv: toBase64(iv), ct: toBase64(ct) };\n return {\n sealedKeys: toBase64(TE.encode(JSON.stringify(envelope))),\n fragmentKey: base64UrlEncode(ktRaw),\n };\n}\n\n/** Recover the master seed from the sealed envelope + the fragment key. */\nexport async function unsealSeed(sealedKeys: string, fragmentKey: string): Promise<Uint8Array> {\n const envelope = JSON.parse(TD.decode(fromBase64(sealedKeys))) as SealedEnvelope;\n if (envelope.v !== 1) throw new Error(`Unsupported handoff envelope version ${envelope.v}`);\n const ktRaw = base64UrlDecode(fragmentKey);\n const key = await crypto.subtle.importKey(\"raw\", ktRaw as BufferSource, { name: \"AES-GCM\" }, false, [\"decrypt\"]);\n const seed = await crypto.subtle.decrypt(\n { name: \"AES-GCM\", iv: fromBase64(envelope.iv) as BufferSource },\n key,\n fromBase64(envelope.ct) as BufferSource,\n );\n return new Uint8Array(seed);\n}\n\n// ---- v2: ECDH device pairing ----------------------------------------------\n//\n// Deliberately a SEPARATE unseal entry point rather than one `unsealSeed` that\n// dispatches on `envelope.v`. The two versions do not just differ in envelope\n// shape — their *second argument* is a different kind of thing entirely (v1: a\n// base64url string plucked out of a URL fragment; v2: a non-extractable\n// `CryptoKey`). Overloading one function on a `string | CryptoKey` union would\n// buy nothing at the call sites (each caller statically knows which flow it is\n// in) while adding a narrowing branch to the v1 path, which is live in\n// production hosted auth. Each function still validates `v` and rejects the\n// other version's envelope, so a mis-routed envelope fails loudly rather than\n// being interpreted under the wrong scheme.\n\n/** P-256 curve parameters for the pairing ECDH. */\nconst PAIRING_CURVE: EcKeyGenParams & EcKeyImportParams = { name: \"ECDH\", namedCurve: \"P-256\" };\n\n/**\n * HKDF `info` for the v2 seal. Versioned and domain-separated: v1 derives no\n * key at all (K_t is raw random), so no v1 key can ever collide with this, and\n * a future v3 must pick a new label rather than reuse this one.\n */\nconst HKDF_INFO_V2 = \"muhkoo/hosted-handoff/v2/device-seal\";\n\n/** Domain separator for {@link pairingVerificationCode} — distinct from the seal KDF. */\nconst PAIRING_CODE_DOMAIN = \"muhkoo/hosted-handoff/v2/pairing-code\";\n\n/**\n * Alphabet for the pairing verification code: 30 symbols, every confusable pair\n * removed in BOTH directions — no `0`/`O`, no `1`/`I`/`L`, and no `U` (which is\n * read as `V` on the low-resolution, far-viewed type a TV renders). Because the\n * user compares this string across two screens by eye, unambiguity beats the\n * convenience of a power-of-two alphabet; the derivation below rejection-samples\n * to avoid the modulo bias that costs us.\n */\nexport const PAIRING_CODE_ALPHABET = \"ABCDEFGHJKMNPQRSTVWXYZ23456789\";\n\n/** Length of the pairing verification code, in characters. 30^8 ≈ 39.3 bits. */\nexport const PAIRING_CODE_LENGTH = 8;\n\n/**\n * PBKDF2 iterations for the verification code. This is NOT protecting a\n * password — it is a deliberate work factor on an attacker precomputing codes.\n * See {@link pairingVerificationCode}.\n */\nconst PAIRING_CODE_ITERATIONS = 200_000;\n\n/** An ephemeral ECDH keypair generated by the pairing device (the TV). */\nexport interface DevicePairingKeypair {\n /** base64 raw (SEC1 uncompressed, 65 bytes) public key — safe to publish. */\n publicKeyB64: string;\n /**\n * Non-extractable private half. In-memory only, one per pairing attempt:\n * it is never persisted and never leaves the device, so a captured pairing\n * transcript is undecryptable once the attempt ends.\n */\n privateKey: CryptoKey;\n}\n\n/**\n * (Device side) Generate the ephemeral P-256 ECDH keypair for one pairing\n * attempt. Call this once per attempt and throw it away when the attempt ends —\n * reusing a keypair across attempts would let an old, observed ciphertext be\n * decrypted by whoever later obtains the key.\n */\nexport async function generateDevicePairingKeypair(): Promise<DevicePairingKeypair> {\n const pair = (await crypto.subtle.generateKey(PAIRING_CURVE, false, [\"deriveBits\"])) as CryptoKeyPair;\n const raw = new Uint8Array(await crypto.subtle.exportKey(\"raw\", pair.publicKey));\n return { publicKeyB64: toBase64(raw), privateKey: pair.privateKey };\n}\n\n/**\n * (Hosted-page side) Seal the master seed *to a device's* pairing public key.\n *\n * A fresh ephemeral keypair is generated per call and its public half is\n * carried in the envelope (`epk`), so sealing the same seed to the same device\n * twice yields unrelated ciphertext — and the sealer retains nothing that could\n * later reopen the envelope.\n *\n * Returns the v2 `sealedKeys` string, which slots into exactly the same server\n * field as v1: relayed verbatim, never read.\n */\nexport async function sealSeedToDevice(seed: Uint8Array, devicePublicKeyB64: string): Promise<string> {\n const devicePubRaw = decodePairingPublicKey(devicePublicKeyB64);\n const devicePub = await importPairingPublicKey(devicePubRaw);\n\n const ephemeral = (await crypto.subtle.generateKey(PAIRING_CURVE, false, [\"deriveBits\"])) as CryptoKeyPair;\n const epkRaw = new Uint8Array(await crypto.subtle.exportKey(\"raw\", ephemeral.publicKey));\n\n const key = await deriveDeviceSealKey(ephemeral.privateKey, devicePub, epkRaw, devicePubRaw, [\"encrypt\"]);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(\n await crypto.subtle.encrypt({ name: \"AES-GCM\", iv: iv as BufferSource }, key, seed as BufferSource),\n );\n\n const envelope: SealedEnvelopeV2 = { v: 2, epk: toBase64(epkRaw), iv: toBase64(iv), ct: toBase64(ct) };\n return toBase64(TE.encode(JSON.stringify(envelope)));\n}\n\n/**\n * (Device side) Recover the master seed from a v2 envelope using the ephemeral\n * private key from {@link generateDevicePairingKeypair}.\n *\n * Throws on any tamper: a substituted `epk` yields a different shared secret\n * (or fails point validation outright), and any edit to `iv`/`ct` fails the\n * AES-GCM tag. There is no path that returns partially-authenticated bytes.\n *\n * `devicePublicKeyB64` is the caller's OWN public half (from\n * {@link generateDevicePairingKeypair}). It is required, not optional, because\n * it is mixed into the KDF — see {@link deriveDeviceSealKey} for why binding the\n * recipient matters. A device always holds both halves, so this costs nothing.\n */\nexport async function unsealSeedFromDevice(\n sealedKeys: string,\n privateKey: CryptoKey,\n devicePublicKeyB64: string,\n): Promise<Uint8Array> {\n const envelope = JSON.parse(TD.decode(fromBase64Loose(sealedKeys))) as SealedEnvelopeV2;\n if (envelope.v !== 2) throw new Error(`Unsupported device-handoff envelope version ${envelope.v}`);\n\n const devicePubRaw = decodePairingPublicKey(devicePublicKeyB64);\n const epkRaw = decodePairingPublicKey(envelope.epk);\n const epk = await importPairingPublicKey(epkRaw);\n\n const key = await deriveDeviceSealKey(privateKey, epk, epkRaw, devicePubRaw, [\"decrypt\"]);\n const seed = await crypto.subtle.decrypt(\n { name: \"AES-GCM\", iv: fromBase64Loose(envelope.iv) as BufferSource },\n key,\n fromBase64Loose(envelope.ct) as BufferSource,\n );\n return new Uint8Array(seed);\n}\n\n/**\n * Short code derived deterministically from the device's pairing public key,\n * displayed on BOTH the TV and the approving browser so the human can confirm\n * they match before approving.\n *\n * ## What this is worth (be honest about it)\n *\n * ~39.3 bits (30^8), rendered in an unambiguous 30-symbol alphabet and grouped\n * as `XXXX-XXXX` for comparison. Alongside the recipient-key binding in\n * {@link deriveDeviceSealKey}, this is what stops a substituted device key: the\n * KDF rejects a *negated* key, and this code is what a human uses to reject a\n * wholly *attacker-generated* one, which the crypto cannot detect on its own —\n * ECDH proves nothing about WHOSE public key it is.\n *\n * Two attacks, and what each actually costs:\n *\n * 1. **Online grind.** Generate keypairs until one's code equals the honest\n * TV's. ~2^39 trials. Naively that reads as \"keygen + hash\", but a real\n * attacker never generates keys: walking `P_{i+1} = P_i + G` while tracking\n * `d_i = d_0 + i` makes each trial one point-add plus one derivation. With\n * a plain hash that is well under a core-day — which is why this uses\n * PBKDF2-SHA256 at {@link PAIRING_CODE_ITERATIONS} iterations instead. The\n * work factor applies per trial, pushing the same grind to the order of\n * 10^5 core-days. The target is also only learned when pairing starts, so\n * the grind is online against the pairing TTL (keep it minutes).\n * 2. **Precomputed table.** The reason this is not a plain hash. A table over\n * candidate keys is computed once and reused forever; with SHA-256 that is\n * cheap enough to be the preferred attack. The iteration count multiplies\n * the table's build cost by the same 2 * 10^5.\n *\n * Neither is a proof of security, and an adversary with ASIC-scale hardware\n * changes these numbers. If the margin is ever judged insufficient, raise\n * {@link PAIRING_CODE_LENGTH} — 10 characters buys ~49 bits for two more\n * characters of human comparison, and is display-only: it does not touch the\n * envelope or the wire format.\n *\n * The cost is paid once per pairing, on two idle devices, so ~200k iterations\n * is imperceptible here in a way it would not be on a hot path.\n */\nexport async function pairingVerificationCode(devicePublicKeyB64: string): Promise<string> {\n const pubRaw = decodePairingPublicKey(devicePublicKeyB64);\n const material = await crypto.subtle.importKey(\"raw\", pubRaw as BufferSource, { name: \"PBKDF2\" }, false, [\n \"deriveBits\",\n ]);\n // Enough bytes that rejection sampling (below) effectively never runs dry:\n // each byte is rejected with p = 16/256, so 32 bytes yields 8 symbols with\n // overwhelming probability.\n const bits = new Uint8Array(\n await crypto.subtle.deriveBits(\n {\n name: \"PBKDF2\",\n hash: \"SHA-256\",\n salt: TE.encode(PAIRING_CODE_DOMAIN) as BufferSource,\n iterations: PAIRING_CODE_ITERATIONS,\n },\n material,\n 256,\n ),\n );\n\n // Rejection-sample so all 30 symbols are equally likely. 256 is not a\n // multiple of 30, so a plain modulo would over-weight the first 16 symbols.\n const n = PAIRING_CODE_ALPHABET.length;\n const limit = Math.floor(256 / n) * n; // 240\n let out = \"\";\n for (let i = 0; i < bits.length && out.length < PAIRING_CODE_LENGTH; i++) {\n if (bits[i] >= limit) continue;\n out += PAIRING_CODE_ALPHABET[bits[i] % n];\n }\n if (out.length < PAIRING_CODE_LENGTH) {\n // Astronomically unlikely (p < 2^-40); fail loudly rather than return a\n // short code that two screens would still \"agree\" on.\n throw new Error(\"Pairing code derivation ran out of entropy.\");\n }\n // Grouped for human comparison — the format the spec and both UIs display.\n return out.slice(0, 4) + \"-\" + out.slice(4);\n}\n\n// ---- v2 internals ----------------------------------------------------------\n\n/**\n * ECDH → HKDF-SHA256 → AES-256-GCM key.\n *\n * The raw ECDH output is never used as a key directly; it is extracted+expanded\n * with BOTH public keys mixed in:\n *\n * - the sender's ephemeral key as HKDF **salt**, and\n * - the recipient's device key appended to the HKDF **info**.\n *\n * Binding the recipient is not decoration. P-256 ECDH returns only the shared\n * point's x-coordinate, and negating a public key — `(x, y)` → `(x, p−y)`, which\n * is still on the curve and which ANYONE can compute from the published key —\n * yields the SAME x. So without the recipient in the KDF, a seal addressed to\n * the negated key still decrypts under the honest private key, even though that\n * negated key displays a DIFFERENT {@link pairingVerificationCode}. That would\n * leave the human code as the only thing rejecting a substituted recipient.\n * Mixing `devicePubRaw` in makes the substitution fail in the crypto layer,\n * where it belongs.\n *\n * (The salt is load-bearing for the same reason — it is what makes a swapped\n * `epk` derive a different key. Do not \"simplify\" either input away.)\n */\nasync function deriveDeviceSealKey(\n priv: CryptoKey,\n pub: CryptoKey,\n epkRaw: Uint8Array,\n devicePubRaw: Uint8Array,\n usages: KeyUsage[],\n): Promise<CryptoKey> {\n const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: \"ECDH\", public: pub }, priv, 256));\n const prk = await crypto.subtle.importKey(\"raw\", shared as BufferSource, { name: \"HKDF\" }, false, [\"deriveBits\"]);\n const label = TE.encode(HKDF_INFO_V2);\n const info = new Uint8Array(label.length + devicePubRaw.length);\n info.set(label, 0);\n info.set(devicePubRaw, label.length);\n const okm = await crypto.subtle.deriveBits(\n {\n name: \"HKDF\",\n hash: \"SHA-256\",\n salt: epkRaw as BufferSource,\n info: info as BufferSource,\n },\n prk,\n 256,\n );\n return crypto.subtle.importKey(\"raw\", okm, { name: \"AES-GCM\" }, false, usages);\n}\n\n/** Decode + shape-check a raw SEC1 uncompressed P-256 public key. */\nfunction decodePairingPublicKey(b64: string): Uint8Array {\n if (typeof b64 !== \"string\" || b64.length === 0) {\n throw new Error(\"Pairing public key must be a non-empty base64 string.\");\n }\n const raw = fromBase64Loose(b64);\n if (raw.length !== 65 || raw[0] !== 0x04) {\n throw new Error(\"Pairing public key must be a 65-byte uncompressed P-256 point.\");\n }\n return raw;\n}\n\n/** Import a raw P-256 point for ECDH. Rejects points that are not on the curve. */\nfunction importPairingPublicKey(raw: Uint8Array): Promise<CryptoKey> {\n return crypto.subtle.importKey(\"raw\", raw as BufferSource, PAIRING_CURVE, false, []);\n}\n\n/**\n * Base64 decode that also accepts the URL-safe alphabet and missing padding —\n * pairing public keys may travel through query strings, QR payloads, or JSON\n * depending on the client, and rejecting a key over `-` vs `+` would be a\n * miserable failure mode to debug.\n */\nfunction fromBase64Loose(s: string): Uint8Array {\n const norm = s.replace(/-/g, \"+\").replace(/_/g, \"/\");\n return fromBase64(norm.padEnd(Math.ceil(norm.length / 4) * 4, \"=\"));\n}\n\n// ---- PKCE (RFC 7636, S256) -------------------------------------------------\n\nexport interface Pkce {\n codeVerifier: string;\n codeChallenge: string;\n}\n\n/** Generate a PKCE verifier + S256 challenge for the authorize→token exchange. */\nexport async function generatePkce(): Promise<Pkce> {\n const codeVerifier = base64UrlEncode(crypto.getRandomValues(new Uint8Array(32)));\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", TE.encode(codeVerifier)));\n return { codeVerifier, codeChallenge: base64UrlEncode(digest) };\n}\n\n/** A random URL-safe value for the OAuth `state` (CSRF binding on the callback). */\nexport function randomState(): string {\n return base64UrlEncode(crypto.getRandomValues(new Uint8Array(16)));\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n return toBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\nfunction base64UrlDecode(s: string): Uint8Array {\n return fromBase64(s.replace(/-/g, \"+\").replace(/_/g, \"/\").padEnd(Math.ceil(s.length / 4) * 4, \"=\"));\n}\n","/**\n * SDK build version — stamped to the console when a {@link Client} is created.\n *\n * During active development, bump the `-alpha.N` suffix whenever we ship a build\n * so we can confirm in the browser console that the page is running the build we\n * expect (and isn't serving a stale cached bundle). Keep this in sync with\n * `package.json` `version`.\n */\nexport const VERSION = \"0.14.0-alpha.1\";\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 /**\n * A scoped, expiring **access token** (`mk_<env>_at_…`) — the non-ZK\n * machine-to-machine credential. It resolves through the SAME accelerator\n * path as an app key and rides the same `X-Muhkoo-Key` header; when present\n * it takes precedence over {@link apiKey}. Use it for server-side / CI\n * callers that shouldn't carry the app's publishable key.\n */\n accessToken?: 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/** Per-request timing logs, enabled on staging only (temporary diagnostic). */\nconst HTTP_DEBUG = (() => {\n try {\n return typeof location !== \"undefined\" && /(^|\\.)staging\\./.test(location.hostname);\n } catch {\n return false;\n }\n})();\n\n/** Short, readable request path (pathname + search) for the timing log. */\nfunction reqPath(input: RequestInfo | URL): string {\n try {\n const u = typeof input === \"string\" ? input : input instanceof URL ? input.href : (input as Request).url;\n if (!/^https?:\\/\\//i.test(u)) return u;\n const parsed = new URL(u);\n return parsed.pathname + parsed.search;\n } catch {\n return \"?\";\n }\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 /** Origin of {@link baseUrl} — credentials are only attached same-origin. */\n private readonly baseOrigin: string;\n private readonly apiKey: string | null;\n /** Scoped machine access token — takes precedence over {@link apiKey} on `X-Muhkoo-Key`. */\n private readonly accessToken: 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 try { this.baseOrigin = new URL(this.baseUrl).origin; } catch { this.baseOrigin = \"\"; }\n this.apiKey = opts.apiKey ?? null;\n this.accessToken = opts.accessToken ?? 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 // Only attach credentials when the request stays on the accelerator's\n // origin. An absolute URL pointing elsewhere (e.g. a caller-supplied or\n // server-reflected path that escapes `baseUrl`) must NOT receive the app\n // key or session token, or it becomes a token-exfiltration vector.\n if (this.isSameOrigin(input)) {\n // Access token and app key resolve through the same accelerator path\n // and ride the same header; the access token takes precedence.\n const key = this.accessToken ?? this.apiKey;\n if (key) headers.set(\"X-Muhkoo-Key\", key);\n const token = this.getSessionToken();\n if (token) headers.set(\"X-Muhkoo-Session\", token);\n }\n const finalInit = { ...init, headers };\n if (!HTTP_DEBUG) return this.fetchFn(input, finalInit);\n // Staging diagnostic: time every accelerator request (this `fetch` is the\n // single chokepoint — JSON helpers + the roster/shard fetches ride it).\n const t = performance.now();\n const tag = `${init?.method ?? \"GET\"} ${reqPath(input)}`;\n return this.fetchFn(input, finalInit).then(\n (res) => { console.info(`[muhkoo:http] ${tag} → ${res.status} ${Math.round(performance.now() - t)}ms`); return res; },\n (err) => { console.info(`[muhkoo:http] ${tag} → ERROR ${Math.round(performance.now() - t)}ms`); throw err; },\n );\n };\n\n /** True when `input` resolves to {@link baseOrigin} (relative URLs always do). */\n private isSameOrigin(input: RequestInfo | URL): boolean {\n try {\n const urlStr =\n typeof input === \"string\" ? input\n : input instanceof URL ? input.href\n : (input as Request).url;\n // Relative URLs are resolved against baseUrl downstream → same origin.\n if (!/^https?:\\/\\//i.test(urlStr)) return true;\n return new URL(urlStr).origin === this.baseOrigin;\n } catch {\n return true;\n }\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 /** The 32-byte master seed, in-memory only (never persisted). Held after\n * login/register so additional recovery factors (passkey, phrase) can be\n * enrolled, and a password can be changed, without re-deriving. */\n private _seed: Uint8Array | 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 /** The in-memory master seed (or null when locked / not held). */\n get seed(): Uint8Array | null {\n return this._seed;\n }\n\n /** Hold the master seed in memory (set on login/register when available). */\n setSeed(seed: Uint8Array | null): void {\n this._seed = seed;\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 if (this._seed) this._seed.fill(0); // wipe the master seed\n this._seed = null;\n await this.store.clear();\n }\n}\n\nexport default SessionState;\n","/**\n * Recovery phrase (M1.2) — a 24-word BIP39 mnemonic that ENCODES the 32-byte\n * master seed directly. Nothing is stored server-side (the phrase *is* the seed),\n * so it's a fully offline, self-sovereign recovery factor: enter the phrase →\n * decode → master seed → identity. A `phrase-marker` factor is kept in the vault\n * only so the UI can show \"recovery phrase: enabled\".\n */\n\nimport { entropyToMnemonic, mnemonicToEntropy, validateMnemonic } from \"@scure/bip39\";\nimport { wordlist } from \"@scure/bip39/wordlists/english.js\";\n\n/** Encode a 32-byte master seed as a 24-word BIP39 recovery phrase. */\nexport function seedToMnemonic(seed: Uint8Array): string {\n if (!(seed instanceof Uint8Array) || seed.length !== 32) {\n throw new Error(\"seedToMnemonic: expected a 32-byte seed\");\n }\n return entropyToMnemonic(seed, wordlist);\n}\n\nfunction normalize(mnemonic: string): string {\n return mnemonic.trim().toLowerCase().replace(/\\s+/g, \" \");\n}\n\n/** Decode a recovery phrase back to the 32-byte master seed. Throws if invalid. */\nexport function mnemonicToSeed(mnemonic: string): Uint8Array {\n const m = normalize(mnemonic);\n if (!validateMnemonic(m, wordlist)) throw new Error(\"Invalid recovery phrase.\");\n return mnemonicToEntropy(m, wordlist);\n}\n\n/** Whether `mnemonic` is a well-formed BIP39 phrase (checksum valid). */\nexport function isValidPhrase(mnemonic: string): boolean {\n try {\n return validateMnemonic(normalize(mnemonic), wordlist);\n } catch {\n return false;\n }\n}\n","/**\n * OPRF (Oblivious PRF) — RFC 9497, ristretto255-SHA512, mode 0x00.\n *\n * Used to gate the password/recovery factors of the identity vault\n * ({@link ./vault}). The wrap key for a password factor is\n * `HKDF(OPRF(serverKey, scrypt(password)))`, so:\n * - the client cannot derive the wrap key offline (it needs the server's\n * secret-keyed evaluation), and\n * - the server learns nothing — it only ever sees a *blinded* group element,\n * never the password or the resulting key.\n *\n * Net effect: a stolen vault blob is NOT offline-crackable; every guess costs a\n * round-trip to a rate-limited server endpoint. The same OPRF backs the M2\n * Google/email factors.\n *\n * Thin wrapper over `@noble/curves`' vetted `ristretto255_oprf` so the protocol\n * (blind / blindEvaluate / finalize) lives in one named place. CLIENT uses\n * {@link oprfBlind} + {@link oprfFinalize}; SERVER uses {@link oprfDeriveKey} +\n * {@link oprfBlindEvaluate} (imported by the accelerator's VaultDO).\n */\n\nimport { ristretto255_oprf } from \"@noble/curves/ed25519.js\";\n\nconst OPRF = ristretto255_oprf.oprf;\n// Domain separation for the server key derivation (RFC 9497 `info`).\nconst KEY_INFO = new TextEncoder().encode(\"muhkoo-oprf-v1\");\n\nexport interface OprfBlind {\n /** Secret blind scalar — stays on the client; needed to finalize. */\n blind: Uint8Array;\n /** Blinded group element — sent to the server for evaluation. */\n blinded: Uint8Array;\n}\n\n/** CLIENT: blind `input` (e.g. `scrypt(password)`) before the server eval. */\nexport function oprfBlind(input: Uint8Array): OprfBlind {\n const { blind, blinded } = OPRF.blind(input);\n return { blind, blinded };\n}\n\n/** CLIENT: fold the server's blinded evaluation into the final 64-byte OPRF output. */\nexport function oprfFinalize(input: Uint8Array, blind: Uint8Array, evaluated: Uint8Array): Uint8Array {\n return OPRF.finalize(input, blind, evaluated);\n}\n\n/** SERVER: derive the stable OPRF secret key from a seed (a Worker secret). */\nexport function oprfDeriveKey(seed: Uint8Array): Uint8Array {\n return OPRF.deriveKeyPair(seed, KEY_INFO).secretKey;\n}\n\n/** SERVER: evaluate a blinded element with the secret key (learns nothing about input). */\nexport function oprfBlindEvaluate(secretKey: Uint8Array, blinded: Uint8Array): Uint8Array {\n return OPRF.blindEvaluate(secretKey, blinded);\n}\n\n/** Direct (unblinded) OPRF evaluation — for tests / equivalence checks only.\n * (`evaluate` exists at runtime in `ristretto255_oprf.oprf` but isn't in the\n * published type, so we reach it through a narrow cast.) */\nexport function oprfEvaluate(secretKey: Uint8Array, input: Uint8Array): Uint8Array {\n return (OPRF as unknown as { evaluate(sk: Uint8Array, input: Uint8Array): Uint8Array }).evaluate(secretKey, input);\n}\n","/**\n * Verification-gated vault factors (M2 — email, later Google).\n *\n * These factors have NO client-side secret: the user proves *channel control*\n * (an email OTP) and the server releases a split-key OPRF evaluation —\n * `wrapKey = HKDF( OPRF(K1, input) ‖ OPRF(K2, input) )` where K1 lives on the\n * accelerator and K2 in a separate trust domain, so no single server-side\n * compromise can derive the wrap key offline. See accelerator\n * `AUTH_M2_PLAN.md` §1; the canonical reference implementation is\n * accelerator `tests/gated-oprf.test.ts` — keep these derivations in\n * byte-exact lockstep with it.\n */\n\nimport { oprfBlind, oprfFinalize, type OprfBlind } from \"./oprf\";\nimport { wrapKeyFromBytes, fromBase64 } from \"./vault\";\n\nexport type GatedPurpose = \"enroll\" | \"recover\";\n\n/**\n * Deterministic OPRF input for an email factor. Public-ish by design (the\n * verification gate, not the input, is what protects the eval) — but it must\n * be stable forever: username + address are lowercased, the tag is versioned.\n */\nexport async function emailFactorInput(username: string, email: string): Promise<Uint8Array> {\n const tag = `muhkoo/factor:email:v1:${username.toLowerCase()}:${email.toLowerCase()}`;\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(tag));\n return new Uint8Array(digest);\n}\n\n/**\n * Deterministic OPRF input for a google factor — keyed on the stable Google\n * account id (`sub`), not the email (which can change). Same versioning rules\n * as {@link emailFactorInput}.\n */\nexport async function googleFactorInput(username: string, sub: string): Promise<Uint8Array> {\n const tag = `muhkoo/factor:google:v1:${username.toLowerCase()}:${sub}`;\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(tag));\n return new Uint8Array(digest);\n}\n\n/** Blind a gated input for the split eval (same blind serves both domains). */\nexport function gatedBlind(input: Uint8Array): OprfBlind {\n return oprfBlind(input);\n}\n\n/**\n * Fold the two domains' evaluations into the AES-256-GCM wrap key:\n * unblind each, concatenate, HKDF with the gated-factor domain separation.\n */\nexport async function gatedWrapKey(\n input: Uint8Array,\n blind: Uint8Array,\n evaluatedB64: string,\n evaluated2B64: string,\n): Promise<CryptoKey> {\n const out1 = oprfFinalize(input, blind, fromBase64(evaluatedB64));\n const out2 = oprfFinalize(input, blind, fromBase64(evaluated2B64));\n const ikm = new Uint8Array(out1.length + out2.length);\n ikm.set(out1);\n ikm.set(out2, out1.length);\n return wrapKeyFromBytes(ikm, \"muhkoo-gated-wrap-v1\");\n}\n","/**\n * Passkey factor (M1.1) — WebAuthn with the **PRF extension**.\n *\n * A passkey becomes a device-bound, platform-synced source of a stable secret:\n * for a fixed salt, the authenticator's PRF returns the same 32 bytes, which we\n * HKDF into an AES key that wraps the master seed. The server never sees the\n * passkey — it's purely a local key source; the ZK proof remains the server auth.\n *\n * BROWSER ONLY (`navigator.credentials`). The PRF extension fields aren't in the\n * standard DOM types yet, so they're reached through narrow casts.\n */\n\nfunction rand(n: number): Uint8Array {\n return crypto.getRandomValues(new Uint8Array(n));\n}\n\n/** Whether this environment can do WebAuthn at all. (PRF support is checked at enroll.) */\nexport function passkeySupported(): boolean {\n return (\n typeof navigator !== \"undefined\" &&\n !!navigator.credentials &&\n typeof PublicKeyCredential !== \"undefined\"\n );\n}\n\n/**\n * Whether this browser's authenticator can do the **PRF extension** our passkey\n * factor needs. A browser can save passkeys (e.g. for password autofill) yet not\n * expose PRF — PRF is what derives the stable secret we wrap the seed under, so a\n * passkey without it is useless to us.\n *\n * Uses `PublicKeyCredential.getClientCapabilities()` (the `extension:prf` cap)\n * where available. Returns:\n * - `true` — PRF is supported,\n * - `false` — definitively NOT supported (hide the option),\n * - `null` — couldn't determine (older browser without the capabilities API);\n * the caller may optimistically allow and let enroll surface a real\n * error if it turns out PRF isn't there.\n */\nexport async function passkeyPrfCapable(): Promise<boolean | null> {\n if (!passkeySupported()) return false;\n const PC = PublicKeyCredential as unknown as {\n getClientCapabilities?: () => Promise<Record<string, boolean>>;\n };\n if (typeof PC.getClientCapabilities !== \"function\") return null;\n try {\n const caps = await PC.getClientCapabilities();\n // The spec keys extension caps as `extension:<name>`; tolerate variants.\n const prf = caps[\"extension:prf\"] ?? caps[\"extensions:prf\"] ?? caps[\"prf\"];\n return typeof prf === \"boolean\" ? prf : null;\n } catch {\n return null;\n }\n}\n\n/** Best-effort registrable RP id — the host. Apps spanning subdomains should pass\n * the parent domain (e.g. \"muhkoo.dev\") explicitly. */\nexport function defaultRpId(): string {\n return typeof location !== \"undefined\" ? location.hostname : \"\";\n}\n\n/**\n * Can a passkey enrolled under `rpId` be used from the CURRENT origin?\n *\n * WebAuthn only accepts an RP id that is the origin's own host or a registrable\n * *parent* of it — so a passkey enrolled on `app.example.com` is unusable on\n * `app.example.net`, and one enrolled on a full host is unusable from a sibling\n * host. An app served on BOTH a custom domain and the platform host therefore\n * needs one passkey per origin.\n *\n * Call this BEFORE `navigator.credentials.get()`: passing a foreign rpId throws\n * a raw \"The requested RPID did not match the origin or related origins\", which\n * is a dead end for the user. Checking first lets the caller fall back to normal\n * sign-in (and offer to enroll a passkey for this origin) instead.\n */\nexport function rpIdUsableForOrigin(rpId: string | undefined | null, host?: string): boolean {\n const h = host ?? (typeof location !== \"undefined\" ? location.hostname : \"\");\n if (!rpId || !h) return false;\n return h === rpId || h.endsWith(`.${rpId}`);\n}\n\n/**\n * Would {@link AuthNamespace.loginWithPasskey} accept a factor recorded with\n * this `rpId`, from `host`?\n *\n * This is deliberately NOT the same as {@link rpIdUsableForOrigin}. That answers\n * a raw WebAuthn question and is `false` for a missing rpId. But a factor with\n * NO recorded rpId predates per-origin enrolment, and `loginWithPasskey`\n * resolves it as `params.rpId ?? host` — so it IS usable, from anywhere.\n *\n * Callers deciding \"should I even try a passkey here?\" must use this one.\n * Reaching for `rpIdUsableForOrigin` instead silently excludes every legacy\n * passkey holder, which has locked real users out of production twice.\n *\n * The `?? host` fallback applies to nullish only, matching `loginWithPasskey`:\n * an empty-string rpId stays unusable rather than resolving to the host.\n */\nexport function passkeyUsableFromOrigin(rpId: string | undefined | null, host?: string): boolean {\n const h = host ?? defaultRpId();\n if (!h) return false;\n if (rpId == null) return true;\n return rpIdUsableForOrigin(rpId, h);\n}\n\n/** Thrown when the account's passkey belongs to a different origin. Callers\n * should treat this as \"no passkey here\" and fall back to another factor. */\nexport class PasskeyOriginError extends Error {\n readonly code = \"passkey_wrong_origin\";\n constructor(message = \"No passkey is enrolled for this site. Sign in another way, then add one for this device.\") {\n super(message);\n this.name = \"PasskeyOriginError\";\n }\n}\n\nexport interface PasskeyEnrollment {\n credentialId: Uint8Array;\n prfSalt: Uint8Array;\n prfOutput: Uint8Array;\n}\n\n/**\n * Create a passkey with PRF and return its credential id, a fresh PRF salt, and\n * the PRF output for that salt. Throws if the authenticator can't do PRF.\n */\nexport async function createPasskeyWithPrf(opts: { rpId: string; rpName: string; username: string }): Promise<PasskeyEnrollment> {\n if (!passkeySupported()) throw new Error(\"Passkeys aren't supported in this browser.\");\n const created = (await navigator.credentials.create({\n publicKey: {\n rp: { id: opts.rpId, name: opts.rpName },\n user: { id: rand(16) as BufferSource, name: opts.username, displayName: opts.username },\n challenge: rand(32) as BufferSource,\n pubKeyCredParams: [{ type: \"public-key\", alg: -7 }, { type: \"public-key\", alg: -257 }],\n // Force the PLATFORM authenticator (Touch ID / Windows Hello / iCloud\n // Keychain). Our factor needs the PRF extension to wrap the seed, and\n // third-party browser password-manager extensions register as cross-platform\n // authenticators that often DON'T implement PRF — letting one handle the\n // request is the main cause of \"didn't return a PRF result\" failures. Pinning\n // to platform routes it to the OS authenticator, which supports PRF.\n authenticatorSelection: { authenticatorAttachment: \"platform\", residentKey: \"preferred\", userVerification: \"preferred\" },\n extensions: { prf: {} } as AuthenticationExtensionsClientInputs,\n },\n })) as PublicKeyCredential | null;\n if (!created) throw new Error(\"Passkey creation was cancelled.\");\n const credentialId = new Uint8Array(created.rawId);\n // Don't trust `prf.enabled` from create() alone — several browsers only report\n // PRF support on the first get() eval, so a precheck false-negatives. Try the\n // actual PRF eval; if it yields a result, PRF works.\n const prfSalt = rand(32);\n let prfOutput: Uint8Array;\n try {\n prfOutput = await evaluatePasskeyPrf(opts.rpId, credentialId, prfSalt);\n } catch {\n // Empty PRF result almost always means a third-party credential manager\n // (e.g. a browser password-manager extension) handled the request instead of\n // the platform authenticator, and that manager doesn't implement PRF. The\n // device's built-in passkey (Touch ID / Windows Hello / iCloud Keychain)\n // normally does — so steer the user there rather than blaming the device.\n throw new Error(\n \"That passkey can't be used for recovery — it didn't return a PRF result. \" +\n \"A browser password-manager extension may have handled it; try again and \" +\n \"pick your device's built-in passkey (Touch ID / Windows Hello), or use a \" +\n \"recovery phrase instead.\",\n );\n }\n return { credentialId, prfSalt, prfOutput };\n}\n\n/** Evaluate a passkey's PRF for `salt` → 32 bytes. Used at recover/login. */\nexport async function evaluatePasskeyPrf(rpId: string, credentialId: Uint8Array, salt: Uint8Array): Promise<Uint8Array> {\n if (!passkeySupported()) throw new Error(\"Passkeys aren't supported in this browser.\");\n const assertion = (await navigator.credentials.get({\n publicKey: {\n rpId,\n challenge: rand(32) as BufferSource,\n allowCredentials: [{ type: \"public-key\", id: credentialId as BufferSource }],\n userVerification: \"preferred\",\n extensions: { prf: { eval: { first: salt } } } as AuthenticationExtensionsClientInputs,\n },\n })) as PublicKeyCredential | null;\n if (!assertion) throw new Error(\"Passkey authentication was cancelled.\");\n const results = (assertion.getClientExtensionResults() as { prf?: { results?: { first?: ArrayBuffer } } })?.prf?.results;\n if (!results?.first) throw new Error(\"Your passkey didn't return a PRF result.\");\n return new Uint8Array(results.first);\n}\n","/**\n * `deviceStore` — at-rest persistence for a paired device (the TV).\n *\n * A device that has completed {@link HostedAuth.startDevicePairing} holds the\n * account's **master seed**. Android WebView has no WebAuthn, so the passkey\n * wrapping used elsewhere isn't available, and re-pairing on every cold start\n * is not acceptable UX for a set-top box. So the seed is persisted, encrypted:\n *\n * | Item | Where | Form |\n * | ------------------------ | ------------------------------------ | ---- |\n * | wrapping key | IndexedDB (`muhkoo.device.v1`) | `CryptoKey`, AES-GCM-256, **non-extractable** |\n * | device identity keypair | IndexedDB (`muhkoo.device.v1`) | `CryptoKeyPair`, ECDSA P-256, private half **non-extractable** |\n * | sealed identity blob | localStorage `muhkoo.tv.identity.v1` | `{\"v\":1,\"iv\":…,\"ct\":…}` over `JSON{username, commitment, seed(b64), pairedAt}` |\n *\n * The split is deliberate — ciphertext in one backend, key in another, and the\n * key non-extractable so JS can *use* it but not export it.\n *\n * ## Be honest about what this is worth\n *\n * **This is obfuscation, not protection.** It raises the cost of a casual\n * `localStorage` dump to \"nothing useful\", and that is all:\n *\n * - **XSS on the device origin** cannot *exfiltrate* the wrapping key (it is\n * non-extractable) but can absolutely call `decrypt` and read the seed. The\n * only mitigation is that there is no third-party script in the shell —\n * enforce a strict CSP with no `unsafe-inline`, no CDN, no remote fonts.\n * - **ADB / root / a backup extraction / a forensic image recovers the seed.**\n * The IndexedDB LevelDB files hold the AES key bytes in the clear; WebCrypto\n * \"non-extractable\" is a JS-API boundary, not an OS one. **A stolen device is\n * a stolen identity.**\n *\n * That is not an implementation shortcut, it is the shape of the problem: any\n * wrapping key usable without user interaction lives somewhere equally readable\n * on a keyboard-less device with no hardware key store exposed to WebView.\n * Reduce the blast radius with `android:allowBackup=\"false\"`,\n * `android:debuggable=\"false\"`, a strict CSP, and by storing *only* the 32-byte\n * seed + username + commitment (never a session token, never a recovery phrase).\n *\n * ## Documented upgrade path — no protocol change\n *\n * If the native shell exposes a Keystore bridge:\n *\n * ```java\n * @JavascriptInterface public String wrap(String b64plain); // AES-GCM, StrongBox when present\n * @JavascriptInterface public String unwrap(String b64cipher);\n * ```\n *\n * this module prefers `globalThis.MuhkooKeystore` automatically and falls back\n * to the WebCrypto scheme otherwise. The Keystore key is hardware-backed and\n * non-exportable at the OS level, so a copied filesystem image alone becomes\n * useless. Nothing on the wire, in the endpoint contracts, or in the SDK surface\n * changes — only the two functions below do, internally.\n *\n * ## Degradation\n *\n * Nothing here throws at import time. On a runtime with neither backend (SSR,\n * Workers, Node) the module still loads: {@link loadDeviceIdentity} returns\n * `null`, {@link persistDeviceIdentity} throws a typed\n * {@link DeviceStoreUnavailableError} the caller can swallow, and\n * {@link deviceIdentityKey} falls back to an **in-memory** keypair for the\n * lifetime of the process (so pairing still works; the device is just never\n * recognised as \"known\" on a later run).\n */\n\nimport { toBase64, fromBase64 } from \"./vault\";\n\nconst TE = new TextEncoder();\nconst TD = new TextDecoder();\n\n/** localStorage key holding the AES-GCM-sealed identity blob. */\nexport const DEVICE_IDENTITY_STORAGE_KEY = \"muhkoo.tv.identity.v1\";\n/** IndexedDB database holding the non-extractable keys. */\nexport const DEVICE_KEY_DB_NAME = \"muhkoo.device.v1\";\nconst DEVICE_KEY_STORE = \"keys\";\nconst WRAP_KEY_ID = \"wrap\";\nconst IDENTITY_KEY_ID = \"identity\";\n\n/** What a paired device persists. The seed **is** the identity — treat it as such. */\nexport interface PersistedDeviceIdentity {\n username: string;\n /** Decimal-string Poseidon commitment. Pinned: a later pairing that yields a\n * different commitment for this device must be refused, not adopted. */\n commitment: string;\n /** The 32-byte master seed. */\n seed: Uint8Array;\n pairedAt: number;\n}\n\n/** Thrown when persistence is impossible (no IndexedDB and/or no localStorage). */\nexport class DeviceStoreUnavailableError extends Error {\n constructor(what: string) {\n super(\n `Device identity can't be persisted here: ${what}. ` +\n \"Pairing still works, but this device will have to pair again after a restart.\",\n );\n this.name = \"DeviceStoreUnavailableError\";\n }\n}\n\n// ---- pluggable backends ----------------------------------------------------\n//\n// Both backends are injectable. This is a TEST SEAM (a `CryptoKey` round-trips\n// through IndexedDB by structured clone, which no in-process IndexedDB shim\n// reproduces faithfully) and doubles as the hook an embedder would use to point\n// the store at its own storage. Apps should never need to call\n// `configureDeviceStore`.\n\n/** Key/value store for live `CryptoKey` objects (IndexedDB in the browser). */\nexport interface DeviceKeyVault {\n get(id: string): Promise<unknown | null>;\n put(id: string, value: unknown): Promise<void>;\n /** Delete the entire store — used by `clearDeviceIdentity`. */\n destroy(): Promise<void>;\n}\n\n/** String store for the sealed blob (localStorage in the browser). */\nexport interface DeviceBlobStore {\n get(key: string): string | null;\n set(key: string, value: string): void;\n remove(key: string): void;\n}\n\n/** The native Keystore bridge, when the shell provides one (see module docs). */\nexport interface MuhkooKeystoreBridge {\n wrap(b64plain: string): string | Promise<string>;\n unwrap(b64cipher: string): string | Promise<string>;\n}\n\nlet injectedKeys: DeviceKeyVault | null | undefined;\nlet injectedBlobs: DeviceBlobStore | null | undefined;\nlet injectedKeystore: MuhkooKeystoreBridge | null | undefined;\n\n/** Memoized so a pairing attempt and its follow-up touch use one keypair. */\nlet identityMemo: Promise<CryptoKeyPair> | null = null;\nlet identityEphemeral = false;\n\n/**\n * Point the store at explicit backends (or `null` to force \"unavailable\"), and\n * reset the memoized device keypair. Testing / embedding seam — pass `{}` to\n * restore the default browser backends.\n */\nexport function configureDeviceStore(opts: {\n keys?: DeviceKeyVault | null;\n blobs?: DeviceBlobStore | null;\n keystore?: MuhkooKeystoreBridge | null;\n} = {}): void {\n injectedKeys = opts.keys;\n injectedBlobs = opts.blobs;\n injectedKeystore = opts.keystore;\n identityMemo = null;\n identityEphemeral = false;\n}\n\n/**\n * True when {@link deviceIdentityKey} had to fall back to an in-memory keypair\n * because no key vault was available. Such a device can pair, but will never be\n * recognised as \"known\" afterwards (so approval always needs a fresh factor).\n */\nexport function deviceIdentityIsEphemeral(): boolean {\n return identityEphemeral;\n}\n\n// ---- public API ------------------------------------------------------------\n\n/**\n * The device's **persistent** ECDSA P-256 identity keypair, created on first\n * call. This is not a browser fingerprint — it is a key, and every\n * `POST /api/auth/device/code` proves possession of it. Without that proof,\n * \"known device\" would be an unauthenticated string anyone could claim in order\n * to skip the approver's re-authentication.\n *\n * The private half is non-extractable and never leaves IndexedDB as bytes.\n */\nexport async function deviceIdentityKey(): Promise<CryptoKeyPair> {\n if (!identityMemo) identityMemo = loadOrCreateIdentityKey();\n try {\n return await identityMemo;\n } catch (e) {\n identityMemo = null; // don't cache a failure\n throw e;\n }\n}\n\n/** `base64url(SHA-256(raw SEC1 device identity public key))` — 43 chars. */\nexport async function deviceFingerprint(): Promise<string> {\n const pair = await deviceIdentityKey();\n return fingerprintOf(pair.publicKey);\n}\n\n/** Whether a sealed identity blob exists. Cheap: no crypto, no IndexedDB, no network. */\nexport async function hasDeviceIdentity(): Promise<boolean> {\n return blobStore()?.get(DEVICE_IDENTITY_STORAGE_KEY) != null;\n}\n\n/**\n * Seal and store the identity. Throws {@link DeviceStoreUnavailableError} when\n * there is nowhere to put it — callers should treat that as \"this device won't\n * resume\", not as a pairing failure.\n */\nexport async function persistDeviceIdentity(v: PersistedDeviceIdentity): Promise<void> {\n if (!(v?.seed instanceof Uint8Array) || v.seed.length !== 32) {\n throw new Error(\"persistDeviceIdentity: expected a 32-byte seed.\");\n }\n const blobs = blobStore();\n if (!blobs) throw new DeviceStoreUnavailableError(\"no localStorage\");\n\n const plain = TE.encode(JSON.stringify({\n username: v.username,\n commitment: v.commitment,\n seed: toBase64(v.seed),\n pairedAt: v.pairedAt,\n }));\n\n const bridge = keystoreBridge();\n let envelope: SealedIdentityBlob;\n if (bridge) {\n envelope = { v: 1, ks: 1, ct: await bridge.wrap(toBase64(plain)) };\n } else {\n const key = await wrapKey(true);\n if (!key) throw new DeviceStoreUnavailableError(\"no IndexedDB for the wrapping key\");\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(\n await crypto.subtle.encrypt({ name: \"AES-GCM\", iv: iv as BufferSource }, key, plain as BufferSource),\n );\n envelope = { v: 1, iv: toBase64(iv), ct: toBase64(ct) };\n }\n blobs.set(DEVICE_IDENTITY_STORAGE_KEY, JSON.stringify(envelope));\n}\n\n/**\n * Recover the persisted identity, or `null` when there is none / it can't be\n * opened (wiped IndexedDB, a different browser profile, a corrupted blob).\n * Never throws — a cold start with unreadable storage must fall back to a fresh\n * pairing, not to an error screen.\n */\nexport async function loadDeviceIdentity(): Promise<PersistedDeviceIdentity | null> {\n const blobs = blobStore();\n const raw = blobs?.get(DEVICE_IDENTITY_STORAGE_KEY);\n if (!raw) return null;\n try {\n const envelope = JSON.parse(raw) as SealedIdentityBlob;\n if (envelope?.v !== 1) return null;\n\n let plain: Uint8Array;\n const bridge = keystoreBridge();\n if (envelope.ks === 1) {\n if (!bridge) return null; // sealed by the native shell; nothing else can open it\n plain = fromBase64(await bridge.unwrap(envelope.ct));\n } else {\n const key = await wrapKey(false);\n if (!key || !envelope.iv) return null;\n plain = new Uint8Array(await crypto.subtle.decrypt(\n { name: \"AES-GCM\", iv: fromBase64(envelope.iv) as BufferSource },\n key,\n fromBase64(envelope.ct) as BufferSource,\n ));\n }\n\n const parsed = JSON.parse(TD.decode(plain)) as {\n username?: string; commitment?: string; seed?: string; pairedAt?: number;\n };\n if (!parsed?.username || !parsed?.commitment || !parsed?.seed) return null;\n const seed = fromBase64(parsed.seed);\n if (seed.length !== 32) return null;\n return {\n username: parsed.username,\n commitment: parsed.commitment,\n seed,\n pairedAt: typeof parsed.pairedAt === \"number\" ? parsed.pairedAt : 0,\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Wipe everything: the sealed blob **and** the whole key database — so the\n * wrapping key never outlives the ciphertext it opens, and the device identity\n * key is regenerated (a re-pair is then correctly treated as a new device).\n */\nexport async function clearDeviceIdentity(): Promise<void> {\n identityMemo = null;\n identityEphemeral = false;\n try { blobStore()?.remove(DEVICE_IDENTITY_STORAGE_KEY); } catch { /* nothing to remove */ }\n try { await keyVault()?.destroy(); } catch { /* already gone */ }\n}\n\n// ---- internals -------------------------------------------------------------\n\ninterface SealedIdentityBlob {\n v: 1;\n /** Present (and `1`) when the native Keystore bridge produced `ct`. */\n ks?: 1;\n /** base64 12-byte AES-GCM IV. Absent for keystore-sealed blobs. */\n iv?: string;\n /** base64 ciphertext‖tag (WebCrypto) or the bridge's opaque wrap output. */\n ct: string;\n}\n\nasync function fingerprintOf(publicKey: CryptoKey): Promise<string> {\n const raw = new Uint8Array(await crypto.subtle.exportKey(\"raw\", publicKey));\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", raw as BufferSource));\n return toBase64(digest).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nasync function loadOrCreateIdentityKey(): Promise<CryptoKeyPair> {\n const vault = keyVault();\n if (vault) {\n const existing = (await vault.get(IDENTITY_KEY_ID)) as CryptoKeyPair | null;\n if (existing?.privateKey && existing?.publicKey) {\n identityEphemeral = false;\n return existing;\n }\n }\n // `extractable: false` applies to the PRIVATE half only — WebCrypto always\n // allows exporting a public key, which is what the fingerprint needs.\n const pair = (await crypto.subtle.generateKey(\n { name: \"ECDSA\", namedCurve: \"P-256\" },\n false,\n [\"sign\", \"verify\"],\n )) as CryptoKeyPair;\n if (vault) {\n try {\n await vault.put(IDENTITY_KEY_ID, pair);\n identityEphemeral = false;\n return pair;\n } catch { /* structured clone refused / quota — fall through */ }\n }\n // No durable home: keep it for this process only. Pairing still works; the\n // device just won't be recognised next boot.\n identityEphemeral = true;\n return pair;\n}\n\n/**\n * The AES-GCM wrapping key. `create` generates + stores one when absent;\n * otherwise a missing key means the blob is unopenable (return null, not throw).\n */\nasync function wrapKey(create: boolean): Promise<CryptoKey | null> {\n const vault = keyVault();\n if (!vault) return null;\n const existing = (await vault.get(WRAP_KEY_ID)) as CryptoKey | null;\n if (existing) return existing;\n if (!create) return null;\n const key = await crypto.subtle.generateKey({ name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\"]);\n await vault.put(WRAP_KEY_ID, key);\n return key;\n}\n\nfunction keystoreBridge(): MuhkooKeystoreBridge | null {\n if (injectedKeystore !== undefined) return injectedKeystore;\n const ks = (globalThis as { MuhkooKeystore?: MuhkooKeystoreBridge }).MuhkooKeystore;\n return typeof ks?.wrap === \"function\" && typeof ks?.unwrap === \"function\" ? ks : null;\n}\n\nfunction blobStore(): DeviceBlobStore | null {\n if (injectedBlobs !== undefined) return injectedBlobs;\n try {\n const ls = (globalThis as { localStorage?: Storage }).localStorage;\n if (!ls) return null;\n ls.getItem(\"muhkoo.__probe__\"); // Safari private mode throws on access, not on typeof\n return {\n get: (k) => ls.getItem(k),\n set: (k, v) => ls.setItem(k, v),\n remove: (k) => ls.removeItem(k),\n };\n } catch {\n return null;\n }\n}\n\nfunction keyVault(): DeviceKeyVault | null {\n if (injectedKeys !== undefined) return injectedKeys;\n const idb = (globalThis as { indexedDB?: IDBFactory }).indexedDB;\n if (!idb) return null;\n return indexedDbVault(idb);\n}\n\n/** Minimal promise wrapper over one object store. Opened per operation — these\n * are cold-start-rare calls, and holding a connection open would block the\n * `deleteDatabase` that `clearDeviceIdentity` needs to win. */\nfunction indexedDbVault(idb: IDBFactory): DeviceKeyVault {\n const open = () => new Promise<IDBDatabase>((resolve, reject) => {\n const req = idb.open(DEVICE_KEY_DB_NAME, 1);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains(DEVICE_KEY_STORE)) db.createObjectStore(DEVICE_KEY_STORE);\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n req.onblocked = () => reject(new Error(\"IndexedDB open blocked\"));\n });\n\n return {\n async get(id) {\n const db = await open();\n try {\n return await new Promise((resolve, reject) => {\n const req = db.transaction(DEVICE_KEY_STORE, \"readonly\").objectStore(DEVICE_KEY_STORE).get(id);\n req.onsuccess = () => resolve(req.result ?? null);\n req.onerror = () => reject(req.error);\n });\n } finally { db.close(); }\n },\n async put(id, value) {\n const db = await open();\n try {\n await new Promise<void>((resolve, reject) => {\n const tx = db.transaction(DEVICE_KEY_STORE, \"readwrite\");\n tx.objectStore(DEVICE_KEY_STORE).put(value, id);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n tx.onabort = () => reject(tx.error);\n });\n } finally { db.close(); }\n },\n destroy() {\n return new Promise<void>((resolve, reject) => {\n const req = idb.deleteDatabase(DEVICE_KEY_DB_NAME);\n req.onsuccess = () => resolve();\n req.onerror = () => reject(req.error);\n // A live connection elsewhere would block the delete; the blob is\n // already gone by then, so don't hang the sign-out on it.\n req.onblocked = () => resolve();\n });\n },\n };\n}\n","/**\n * `client.auth.hosted` — centralized hosted auth (auth.muhkoo.dev).\n * AUTH_HOSTED_PLAN.md; TV device pairing per `muhkoo/auth/docs/tv-device-pairing-spec.md`.\n *\n * Two sides share this class:\n * - **Developer apps** call {@link login} (redirect to the hosted page) and\n * {@link handleCallback} (exchange the returned code → session + seed). The\n * app carries no snarkjs and never sees the user's credentials.\n * - **The hosted page** (the muhkoo/auth SPA), once it has authenticated the\n * user via the normal `client.auth.zk.*` flow, calls\n * {@link completeAuthorize} to seal the seed, mint the grant, and build the\n * redirect-back URL.\n *\n * Flow (authorization-code + PKCE + sealed-seed handoff):\n * app → GET auth.muhkoo.dev/authorize?app_id&redirect_uri&state&code_challenge\n * page → (user authenticates) → POST /api/auth/grant → redirect_uri?code&state#k=<K_t>\n * app → POST /api/auth/token {code, code_verifier} → {sessionToken, sealedKeys}\n * → unseal sealedKeys with K_t → master seed → session ready\n *\n * ## Device pairing (v2 — TVs and other keyboard-less devices)\n *\n * The redirect flow above is unchanged and remains the fallback for anything\n * with a browser and a keyboard. A device with no redirect to receive instead\n * displays a code and **polls**:\n *\n * TV → {@link startDevicePairing} → shows `userCode` + `verificationCode`\n * user → opens auth.muhkoo.dev/link, signs in, {@link lookupDevicePairing}\n * user → compares the verification code on both screens,\n * {@link approveDevicePairing} seals the seed TO the TV's public key\n * TV → {@link waitForDevicePairing} → unseal → own ZK session → persisted\n *\n * Same invariant as v1: the accelerator relays a sealed envelope it cannot read.\n * Only the key agreement changes (ECDH to a key the TV generated, instead of a\n * one-time key delivered in a URL fragment a TV can't receive).\n */\n\nimport type { AuthClient } from \"../../auth/AuthClient\";\nimport type { SessionState } from \"../Session\";\nimport type { AuthUser, LoginOptions } from \"./AuthNamespace\";\nimport { deriveIdentityFromSeed, type ZkIdentity } from \"../../auth/identity\";\nimport { exportPublicKeyHex, exportPublicKeyBase64, signMessage } from \"../../auth/keys\";\nimport { buildCommitment, generateAuthProof, defaultCircuitUrls, type CircuitUrls } from \"../../auth/proof\";\nimport {\n sealSeed, unsealSeed, generatePkce, randomState,\n generateDevicePairingKeypair, sealSeedToDevice, unsealSeedFromDevice, pairingVerificationCode,\n PAIRING_CODE_ALPHABET, PAIRING_CODE_LENGTH,\n} from \"../../auth/hostedHandoff\";\nimport {\n deviceIdentityKey, deviceFingerprint, persistDeviceIdentity, loadDeviceIdentity,\n clearDeviceIdentity, hasDeviceIdentity,\n} from \"../../auth/deviceStore\";\n\nexport interface HostedAuthDeps {\n auth: AuthClient;\n session: SessionState;\n /** Base URL of the hosted auth SPA (e.g. https://auth.muhkoo.dev). */\n authBaseUrl: string;\n /**\n * Absolute URL of the accelerator (e.g. https://api.muhkoo.dev) — the origin\n * the `/api/auth/device*` endpoints live on.\n *\n * Optional for backwards compatibility: `AuthNamespace` does not pass it\n * today, so it is resolved from the {@link AuthClient} at call time (see\n * `apiBase`). Pass it explicitly whenever you construct `HostedAuth` yourself.\n */\n apiBaseUrl?: string;\n /**\n * `preimagePoK` circuit assets, used when a paired device mints its OWN ZK\n * session. Defaults to {@link defaultCircuitUrls} anchored at `apiBaseUrl` —\n * which matches `Client`'s own default. Supply it if the app overrode\n * `ClientOptions.circuits`.\n */\n circuits?: CircuitUrls;\n /** Custom fetch — defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n /** Sleep used by the poll loop. Injectable so tests don't burn wall-clock. */\n sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;\n}\n\nconst PKCE_STORE_KEY = \"muhkoo.hosted.pkce\";\n\n// ---- device pairing: constants (tv-device-pairing-spec.md §4.5, §9) --------\n\n/** RFC-8628-style backoff step applied on every `slow_down` (spec §9.1). */\nconst SLOW_DOWN_STEP_S = 5;\n/** Ceiling for the transport-failure backoff, so a flaky TV Wi-Fi still recovers. */\nconst MAX_BACKOFF_INTERVAL_S = 30;\n/** Consecutive transport failures tolerated before giving up on a pairing. */\nconst MAX_CONSECUTIVE_NETWORK_ERRORS = 5;\n/** Server-sanitized anyway; clipped here so the request is never rejected for it. */\nconst DEVICE_LABEL_MAX = 64;\n/** §4.4 signing-input prefixes. Changing either breaks server verification. */\nconst DEVICE_PAIR_SIG_PREFIX = \"muhkoo-device-pair-v1\";\nconst DEVICE_TOUCH_SIG_PREFIX = \"muhkoo-device-touch-v1\";\n\n// ---- device pairing: types (tv-device-pairing-spec.md §7) ------------------\n\n/** One in-flight pairing attempt. Hold it; pass it back into poll/wait/cancel. */\nexport interface DevicePairingSession {\n /** Opaque; carry it back into poll/wait/cancel. Never render it. */\n deviceCode: string;\n /** Show this, large. Formatted `\"XXXX-XXXX\"`. */\n userCode: string;\n /**\n * Show this too, and tell the user it must match the browser. Computed\n * LOCALLY from this device's own public key — the server's copy is never\n * trusted (that binding is the only MITM defence in the flow).\n */\n verificationCode: string;\n verificationUri: string;\n /** Same URI with the code pre-filled — render as a QR code. */\n verificationUriComplete: string;\n /** Absolute epoch-ms. */\n expiresAt: number;\n /** Server-recommended seconds between polls; may grow via `slow_down`. */\n interval: number;\n /** Ephemeral private key for this attempt. In memory only, never persisted. */\n privateKey: CryptoKey;\n /**\n * This attempt's own public half, base64 raw SEC1.\n *\n * NOT in the spec's §7 listing, but REQUIRED: `unsealSeedFromDevice` takes\n * the recipient key as a third argument because it is mixed into the KDF to\n * defeat a point-negation substitution. The shipped crypto is authoritative;\n * carrying the public half here costs nothing (a device always holds both).\n */\n devicePublicKeyB64: string;\n}\n\n/** The result of one poll. Discriminated on `status`. */\nexport type DevicePairingPoll =\n | { status: \"pending\"; interval: number; expiresIn: number }\n | { status: \"slow_down\"; interval: number; retryAfter: number }\n | { status: \"approved\"; user: AuthUser }\n | { status: \"denied\" }\n | { status: \"expired\" };\n\nexport interface StartDevicePairingOptions {\n appId: string;\n /** Human label shown to the approver. Default: a UA-derived guess. */\n label?: string;\n}\n\nexport interface WaitForDevicePairingOptions {\n signal?: AbortSignal;\n /** Called before each sleep — drive a countdown / \"waiting…\" UI. */\n onTick?: (remainingMs: number, interval: number) => void;\n}\n\n/** A pending pairing, resolved by the approver from the typed `user_code`. */\nexport interface DevicePairingRequest {\n userCode: string;\n devicePublicKeyB64: string;\n /** Recomputed locally by the SDK; compare with what the TV shows. */\n verificationCode: string;\n deviceFingerprint: string;\n deviceLabel: string;\n appId: string;\n appLabel: string;\n isKnownDevice: boolean;\n requiresReauth: boolean;\n expiresAt: number;\n}\n\n/** A device the account has paired, as listed on the security page. */\nexport interface PairedDevice {\n id: string;\n label: string;\n appId: string;\n pairedAt: number;\n lastSeenAt: number;\n activeSession: boolean;\n}\n\n/**\n * Why a pairing ended.\n *\n * `denied` / `expired` / `aborted` / `rate_limited` are the four the spec names\n * for {@link HostedAuth.waitForDevicePairing}. The rest are additive and exist\n * because the flow genuinely produces them:\n * - `network` — the reference loop in spec §9.2 throws it after 5 consecutive\n * transport failures;\n * - `commitment_mismatch` — spec §10.8's MANDATORY client check failed (the\n * seed does not derive the commitment the server sent). This is what turns\n * §10.2's substitution attack from silent into loud;\n * - `account_mismatch` — spec §10.2 detection 2: this device was previously\n * paired to a DIFFERENT account. Refuse rather than silently adopt;\n * - `reauth_required` — see {@link ReauthRequiredError};\n * - `invalid_user_code` — client-side canonicalization rejected the input;\n * - `error` — anything else; read `.code` for the server's machine code.\n */\nexport type DevicePairingErrorReason =\n | \"denied\" | \"expired\" | \"aborted\" | \"rate_limited\" | \"network\"\n | \"commitment_mismatch\" | \"account_mismatch\" | \"reauth_required\"\n | \"invalid_user_code\" | \"error\";\n\n/**\n * Any terminal failure of the pairing flow.\n *\n * `.reason` drives the device's UI state machine; `.code` carries the server's\n * machine error code verbatim (spec §6.7) for the cases the reason collapses —\n * e.g. `consent_required`, `too_many_devices`, `key_mismatch` all arrive as\n * `reason: \"error\"` with a distinct `.code`.\n */\nexport class DevicePairingError extends Error {\n readonly reason: DevicePairingErrorReason;\n /** Machine code from the error envelope (`{error, message}`), when there was one. */\n readonly code?: string;\n readonly status?: number;\n /** Seconds, from `Retry-After`, when the server sent one. */\n readonly retryAfter?: number;\n /** Any extra fields the error envelope carried (e.g. `version`). */\n readonly details?: Record<string, unknown>;\n\n constructor(\n reason: DevicePairingErrorReason,\n opts: {\n message?: string;\n code?: string;\n status?: number;\n retryAfter?: number;\n details?: Record<string, unknown>;\n cause?: unknown;\n } = {},\n ) {\n super(opts.message ?? DEFAULT_PAIRING_MESSAGES[reason]);\n this.name = \"DevicePairingError\";\n this.reason = reason;\n this.code = opts.code;\n this.status = opts.status;\n this.retryAfter = opts.retryAfter;\n this.details = opts.details;\n if (opts.cause !== undefined) (this as Error & { cause?: unknown }).cause = opts.cause;\n }\n}\n\nconst DEFAULT_PAIRING_MESSAGES: Record<DevicePairingErrorReason, string> = {\n denied: \"Sign-in was declined on the other device.\",\n expired: \"That code expired. Get a new code and try again.\",\n aborted: \"Pairing was cancelled.\",\n rate_limited: \"Too many attempts — wait a moment and start again.\",\n network: \"Couldn't reach Muhkoo. Check the connection and try again.\",\n commitment_mismatch:\n \"The account handed back doesn't match the key material — pairing aborted. \" +\n \"Do not sign in on this device; report it.\",\n account_mismatch: \"This device was previously signed in as a different account.\",\n reauth_required: \"Confirm it's you before approving a new device.\",\n invalid_user_code: `Codes are ${PAIRING_CODE_LENGTH} characters from ${PAIRING_CODE_ALPHABET} — no O, I, L, U, 0 or 1.`,\n error: \"Device pairing failed.\",\n};\n\n/**\n * Approving a **new** device needs a recently authenticated approver (spec\n * §10.7, `FRESH_AUTH_MAX_AGE_MS`). The hosted page catches this, prompts for a\n * password / passkey / Google factor, and retries the approval.\n *\n * Server-enforced, not a UI convention — `requiresReauth` on\n * {@link DevicePairingRequest} is only the hint.\n */\nexport class ReauthRequiredError extends DevicePairingError {\n /** How long ago the approver's session authenticated, in seconds. */\n readonly authAgeSeconds?: number;\n /** The freshness window the server enforces, in seconds. */\n readonly maxAgeSeconds?: number;\n\n constructor(opts: { message?: string; authAgeSeconds?: number; maxAgeSeconds?: number; status?: number } = {}) {\n super(\"reauth_required\", { message: opts.message, code: \"reauth_required\", status: opts.status ?? 401 });\n this.name = \"ReauthRequiredError\";\n this.authAgeSeconds = opts.authAgeSeconds;\n this.maxAgeSeconds = opts.maxAgeSeconds;\n }\n}\n\nexport class HostedAuth {\n constructor(private readonly deps: HostedAuthDeps) {}\n\n /**\n * (App side) Begin hosted login: stash a PKCE verifier + state, then send\n * the browser to the hosted authorize page. Returns the URL it redirects to\n * (also useful for popup mode / tests). `redirectUri` must be registered for\n * the app in the portal.\n */\n async login(opts: { appId: string; redirectUri: string; redirect?: boolean; prompt?: \"login\" }): Promise<string> {\n const { codeVerifier, codeChallenge } = await generatePkce();\n const state = randomState();\n this.store({ codeVerifier, state, appId: opts.appId, redirectUri: opts.redirectUri });\n const params: Record<string, string> = {\n app_id: opts.appId,\n redirect_uri: opts.redirectUri,\n state,\n code_challenge: codeChallenge,\n code_challenge_method: \"S256\",\n };\n // `prompt=login` forces the credential screen even when the browser is\n // remembered. Without it, an app's own \"sign out\" would be undone on the\n // very next sign-in click: single sign-on means the hosted page still\n // knows you, so the app must be able to say \"ask anyway\". Named after the\n // OIDC parameter that solves the same problem.\n if (opts.prompt) params.prompt = opts.prompt;\n const url = `${this.deps.authBaseUrl}/authorize?` + new URLSearchParams(params).toString();\n if (opts.redirect !== false) this.location().assign(url);\n return url;\n }\n\n /**\n * (App side) Send the user to centralized account & security management on\n * the hosted page (auth.muhkoo.dev/security) — manage passkeys, recovery\n * phrase, email, Google, change password, and remove login methods, all in\n * one place. `returnUri` (default: the current URL) gives the hosted page a\n * \"Back to app\" target. Redirects the browser; resolves to the URL.\n */\n async manageAccount(opts: { returnUri?: string } = {}): Promise<string> {\n const ret = opts.returnUri ?? this.location().href;\n const url = `${this.deps.authBaseUrl}/security?` + new URLSearchParams({ return: ret }).toString();\n this.location().assign(url);\n return url;\n }\n\n /** Whether the current URL looks like a hosted-auth callback (has code + state). */\n isCallback(): boolean {\n try {\n const q = new URLSearchParams(this.location().search);\n return q.has(\"code\") && q.has(\"state\");\n } catch { return false; }\n }\n\n /**\n * (App side) Complete login on the callback URL: verify state, exchange the\n * code (+ PKCE verifier) for the session, unseal the seed from the fragment,\n * establish the session, and scrub the URL. Returns the signed-in user.\n */\n async handleCallback(): Promise<AuthUser> {\n const loc = this.location();\n const query = new URLSearchParams(loc.search);\n const code = query.get(\"code\");\n const state = query.get(\"state\");\n const fragmentKey = new URLSearchParams(loc.hash.replace(/^#/, \"\")).get(\"k\");\n if (!code || !state) throw new Error(\"Not a hosted-auth callback.\");\n if (!fragmentKey) throw new Error(\"Missing handoff key — the login link was altered.\");\n\n const stash = this.take();\n if (!stash || stash.state !== state) throw new Error(\"State mismatch — possible CSRF; start login again.\");\n\n const res = await this.deps.auth.token({ code, codeVerifier: stash.codeVerifier, appId: stash.appId });\n const seed = await unsealSeed(res.sealedKeys, fragmentKey);\n const identity = await deriveIdentityFromSeed(seed);\n await this.deps.session.setSession({ token: res.sessionToken, username: res.username, commitment: res.commitment });\n this.deps.session.setIdentity(identity);\n this.deps.session.setSeed(seed);\n\n this.scrubUrl();\n return { username: res.username, commitment: res.commitment };\n }\n\n /**\n * (Hosted-page side) Finish an /authorize request after the user has\n * authenticated here: seal the in-memory seed, mint the grant, and return\n * the URL to redirect the browser back to. The seed must be held (the user\n * just signed in via `client.auth.zk.*`).\n */\n async completeAuthorize(opts: { appId: string; redirectUri: string; codeChallenge: string; state: string }): Promise<string> {\n const token = this.deps.session.token;\n const seed = this.deps.session.seed;\n if (!token || !seed) throw new Error(\"Authenticate the user before completing authorization.\");\n const { sealedKeys, fragmentKey } = await sealSeed(seed);\n const { code } = await this.deps.auth.grant(token, {\n appId: opts.appId, redirectUri: opts.redirectUri, codeChallenge: opts.codeChallenge, sealedKeys,\n });\n const url = new URL(opts.redirectUri);\n url.searchParams.set(\"code\", code);\n url.searchParams.set(\"state\", opts.state);\n url.hash = `k=${fragmentKey}`;\n return url.toString();\n }\n\n // =========================================================================\n // Device pairing — device (TV) side\n // =========================================================================\n\n /**\n * (Device side) Begin pairing. Generates the ephemeral ECDH keypair, ensures\n * a persistent device identity key exists, signs a possession proof over it,\n * and calls `POST /api/auth/device/code`.\n *\n * Display `userCode` (large, monospace) **and** `verificationCode`, then call\n * {@link waitForDevicePairing}. The verification code returned here is\n * computed locally from this device's own public key — the server also\n * returns a copy, which is ignored on purpose: trusting it would forfeit the\n * entire MITM binding (spec §6.1, §10.1).\n */\n async startDevicePairing(opts: StartDevicePairingOptions): Promise<DevicePairingSession> {\n if (!opts?.appId) throw new DevicePairingError(\"error\", { message: \"startDevicePairing: `appId` is required.\" });\n\n const pairing = await generateDevicePairingKeypair();\n const identityKey = await deviceIdentityKey();\n const deviceIdentityKeyB64 = await exportPublicKeyBase64(identityKey.publicKey);\n const issuedAt = Date.now();\n const signature = await signMessage(\n [DEVICE_PAIR_SIG_PREFIX, opts.appId, pairing.publicKeyB64, String(issuedAt)].join(\"|\"),\n identityKey.privateKey,\n );\n\n const res = await this.deviceApi(\"POST\", \"/api/auth/device/code\", {\n app_id: opts.appId,\n device_public_key: pairing.publicKeyB64,\n device_identity_key: deviceIdentityKeyB64,\n device_signature: signature,\n issued_at: issuedAt,\n device_label: (opts.label ?? defaultDeviceLabel()).slice(0, DEVICE_LABEL_MAX),\n });\n this.throwForStatus(res);\n\n const body = res.body as {\n device_code: string; user_code: string;\n verification_uri?: string; verification_uri_complete?: string;\n expires_in?: number; interval?: number;\n };\n if (!body?.device_code || !body?.user_code) {\n throw new DevicePairingError(\"error\", { message: \"Device pairing start returned no code.\" });\n }\n\n const expiresIn = numberOr(body.expires_in, 600);\n const verificationUri = body.verification_uri || `${this.deps.authBaseUrl}/link`;\n return {\n deviceCode: body.device_code,\n userCode: body.user_code,\n // LOCAL derivation — never `body.verification_code`.\n verificationCode: await pairingVerificationCode(pairing.publicKeyB64),\n verificationUri,\n verificationUriComplete: body.verification_uri_complete\n || `${verificationUri}?code=${encodeURIComponent(body.user_code)}`,\n expiresAt: Date.now() + expiresIn * 1000,\n interval: numberOr(body.interval, 5),\n privateKey: pairing.privateKey,\n devicePublicKeyB64: pairing.publicKeyB64,\n };\n }\n\n /**\n * (Device side) One poll of `POST /api/auth/device/token`.\n *\n * On `\"approved\"` this does the whole tail of the flow before returning: it\n * unseals the envelope with the ephemeral private key, derives the identity,\n * **verifies the commitment matches** (spec §10.8 — mandatory, and the check\n * that makes a substituted seed loud rather than silent), mints the device's\n * OWN long-lived ZK session, registers the device via `PUT /api/auth/devices`,\n * and persists the identity for cold starts.\n *\n * Prefer {@link waitForDevicePairing}; use this only for a custom loop. A\n * transport failure REJECTS (the caller decides whether to retry); protocol\n * outcomes resolve as a status.\n */\n async pollDevicePairing(session: DevicePairingSession): Promise<DevicePairingPoll> {\n this.assertLive(session);\n const res = await this.deviceApi(\"POST\", \"/api/auth/device/token\", { device_code: session.deviceCode });\n\n if (res.status === 429 && res.code === \"slow_down\") {\n const interval = numberOr((res.body as { interval?: number })?.interval, session.interval + SLOW_DOWN_STEP_S);\n return { status: \"slow_down\", interval, retryAfter: res.retryAfter ?? interval };\n }\n // `expired_token` is deliberately uniform server-side for unknown /\n // expired / already-redeemed codes, so all three land here.\n if (res.status === 401 && res.code === \"expired_token\") return { status: \"expired\" };\n if (res.status === 403 && res.code === \"access_denied\") return { status: \"denied\" };\n this.throwForStatus(res);\n\n const body = res.body as {\n status?: string; interval?: number; expires_in?: number;\n sealed_keys?: string; username?: string; commitment?: string; device_fingerprint?: string;\n };\n if (body?.status === \"pending\") {\n return {\n status: \"pending\",\n interval: numberOr(body.interval, session.interval),\n expiresIn: numberOr(body.expires_in, Math.max(0, Math.round((session.expiresAt - Date.now()) / 1000))),\n };\n }\n if (body?.status === \"denied\") return { status: \"denied\" };\n if (body?.status === \"expired\") return { status: \"expired\" };\n if (body?.status !== \"approved\") {\n throw new DevicePairingError(\"error\", { message: `Unexpected pairing status \"${body?.status}\".` });\n }\n if (!body.sealed_keys || !body.username || !body.commitment) {\n throw new DevicePairingError(\"error\", { message: \"Approved pairing was missing its sealed payload.\" });\n }\n\n const user = await this.adoptSealedSeed(session, {\n sealedKeys: body.sealed_keys,\n username: body.username,\n commitment: body.commitment,\n });\n return { status: \"approved\", user };\n }\n\n /**\n * (Device side) Poll to completion with the interval + `slow_down` backoff of\n * spec §9.\n *\n * The server's `interval` is authoritative: on `slow_down` the client moves to\n * `max(serverInterval, own + 5, retryAfter)` so the two can't drift into a\n * permanent slow_down loop. Sleeps carry ±10 % jitter so a rack of devices\n * restarted together doesn't synchronise, and the loop stops at `expiresAt`\n * without waiting for the server to say so.\n *\n * Resolves with the signed-in user, or rejects with {@link DevicePairingError}.\n */\n async waitForDevicePairing(\n session: DevicePairingSession,\n opts: WaitForDevicePairingOptions = {},\n ): Promise<AuthUser> {\n let interval = session.interval;\n let consecutiveNetworkErrors = 0;\n\n for (;;) {\n if (opts.signal?.aborted) throw new DevicePairingError(\"aborted\");\n this.assertLive(session);\n\n const remaining = session.expiresAt - Date.now();\n if (remaining <= 0) throw new DevicePairingError(\"expired\");\n opts.onTick?.(remaining, interval);\n\n const jitter = 1 + (Math.random() * 0.2 - 0.1);\n await this.sleep(Math.min(interval * 1000 * jitter, remaining), opts.signal);\n\n let result: DevicePairingPoll;\n try {\n result = await this.pollDevicePairing(session);\n consecutiveNetworkErrors = 0;\n } catch (e) {\n // A protocol verdict (denied, budget exhausted, a failed\n // commitment check) is terminal — it must NOT be swallowed by the\n // transport-retry arm the way the spec's reference loop would.\n if (e instanceof DevicePairingError) throw e;\n // Transport failure: a TV's Wi-Fi drops constantly, and the\n // pairing stays valid server-side until it expires. Back off.\n if (++consecutiveNetworkErrors > MAX_CONSECUTIVE_NETWORK_ERRORS) {\n throw new DevicePairingError(\"network\", { cause: e });\n }\n interval = Math.min(interval * 2, MAX_BACKOFF_INTERVAL_S);\n continue;\n }\n\n switch (result.status) {\n case \"pending\":\n interval = result.interval; // server-authoritative\n break;\n case \"slow_down\":\n interval = Math.max(result.interval, interval + SLOW_DOWN_STEP_S, result.retryAfter);\n break;\n case \"approved\":\n return result.user;\n case \"denied\":\n throw new DevicePairingError(\"denied\");\n case \"expired\":\n throw new DevicePairingError(\"expired\");\n }\n }\n }\n\n /**\n * (Device side) Abandon an attempt. Marks the session dead so an in-flight\n * {@link waitForDevicePairing} rejects with `aborted` on its next tick, and\n * clears the device code.\n *\n * The ephemeral `CryptoKey` cannot be zeroed from JS — dropping the last\n * reference to `session` is what makes it unrecoverable, so don't keep the\n * object around. Deliberately does NOT notify the server: the pairing is\n * single-use and expires on its own, and an unauthenticated \"cancel\" endpoint\n * would just be another way to grief someone else's pending code.\n */\n cancelDevicePairing(session: DevicePairingSession): void {\n if (!session) return;\n cancelledPairings.add(session);\n session.deviceCode = \"\";\n }\n\n /**\n * (Device side) Cold-start path. Reads the persisted device identity,\n * re-derives the ZK identity from the stored seed, mints a fresh session, and\n * touches `PUT /api/auth/devices`.\n *\n * Returns `null` when nothing is persisted, when the blob doesn't derive its\n * own pinned commitment (corrupt/tampered storage), or when the account no\n * longer accepts the identity — call {@link startDevicePairing} then.\n */\n async resumeDeviceSession(): Promise<AuthUser | null> {\n const persisted = await loadDeviceIdentity();\n if (!persisted) return null;\n try {\n const identity = await deriveIdentityFromSeed(persisted.seed);\n const commitment = await commitmentFor(identity);\n // Storage integrity: the seed must still derive the commitment it was\n // stored with. A mismatch means the blob was swapped, not that the\n // account changed — refuse it rather than authenticate as someone else.\n if (commitment !== persisted.commitment) return null;\n const user = await this.mintSession(persisted.username, identity, persisted.seed, { rememberMe: true });\n await this.touchPairedDevice();\n return user;\n } catch {\n return null;\n }\n }\n\n /** (Device side) Wipe the persisted seed, the device identity key, and the session. */\n async forgetDeviceSession(): Promise<void> {\n await clearDeviceIdentity();\n await this.deps.session.clear();\n }\n\n /** (Device side) Whether a persisted device identity exists. Cheap: no crypto, no network. */\n async hasDeviceSession(): Promise<boolean> {\n return hasDeviceIdentity();\n }\n\n // =========================================================================\n // Device pairing — approver (hosted page) side\n // =========================================================================\n\n /**\n * (Hosted page) Resolve a typed `user_code` into the pending request.\n * Session-authed.\n *\n * `verificationCode` is recomputed here from the returned device key — the\n * server's copy is discarded. Both screens must show independently derived\n * values or the comparison proves nothing.\n */\n async lookupDevicePairing(userCode: string): Promise<DevicePairingRequest> {\n const code = formatUserCode(canonicalUserCode(userCode));\n const res = await this.deviceApi(\"POST\", \"/api/auth/device/lookup\", { user_code: code }, true);\n this.throwForStatus(res);\n\n const body = res.body as {\n user_code?: string; device_public_key?: string; device_fingerprint?: string;\n device_label?: string; app_id?: string; app_label?: string;\n is_known_device?: boolean; requires_reauth?: boolean; expires_in?: number;\n };\n if (!body?.device_public_key) {\n throw new DevicePairingError(\"error\", { message: \"Pairing lookup returned no device key.\" });\n }\n const isKnown = body.is_known_device === true;\n return {\n userCode: body.user_code || code,\n devicePublicKeyB64: body.device_public_key,\n verificationCode: await pairingVerificationCode(body.device_public_key),\n deviceFingerprint: body.device_fingerprint ?? \"\",\n deviceLabel: body.device_label ?? \"TV\",\n appId: body.app_id ?? \"\",\n appLabel: body.app_label ?? \"\",\n isKnownDevice: isKnown,\n requiresReauth: body.requires_reauth ?? !isKnown,\n expiresAt: Date.now() + numberOr(body.expires_in, 0) * 1000,\n };\n }\n\n /**\n * (Hosted page) Seal the in-memory seed to the device's public key and post\n * the ciphertext. Requires an unlocked seed — the user just authenticated\n * here — exactly like {@link completeAuthorize}. The server stores and relays\n * the envelope verbatim and can't read it.\n *\n * Show the user the verification code and the device label FIRST, and only\n * call this on an explicit tap. Throws {@link ReauthRequiredError} when the\n * account's last authentication is too old for a new device; the page should\n * prompt for a factor and retry. A stale legal agreement arrives as\n * `DevicePairingError` with `.code === \"consent_required\"` and\n * `.details.version`.\n */\n async approveDevicePairing(req: DevicePairingRequest, opts: { label?: string } = {}): Promise<{ deviceId: string }> {\n const seed = this.deps.session.seed;\n if (!this.deps.session.token || !seed) {\n throw new DevicePairingError(\"error\", { message: \"Authenticate the user before approving a device.\" });\n }\n if (!req?.devicePublicKeyB64) {\n throw new DevicePairingError(\"error\", { message: \"approveDevicePairing: the request has no device key.\" });\n }\n const code = formatUserCode(canonicalUserCode(req.userCode));\n const sealedKeys = await sealSeedToDevice(seed, req.devicePublicKeyB64);\n\n const res = await this.deviceApi(\"POST\", \"/api/auth/device/approve\", {\n user_code: code,\n device_public_key: req.devicePublicKeyB64,\n sealed_keys: sealedKeys,\n device_label: (opts.label ?? req.deviceLabel ?? \"\").slice(0, DEVICE_LABEL_MAX) || undefined,\n }, true);\n this.throwForStatus(res);\n\n return { deviceId: String((res.body as { device_id?: string })?.device_id ?? req.deviceFingerprint ?? \"\") };\n }\n\n /**\n * (Hosted page) Refuse a pairing. No re-auth and no consent gate — declining\n * must never be harder than accepting. Leaves a tombstone so the device is\n * told \"declined\" rather than an indistinguishable \"expired\".\n */\n async denyDevicePairing(userCode: string): Promise<void> {\n const code = formatUserCode(canonicalUserCode(userCode));\n const res = await this.deviceApi(\"POST\", \"/api/auth/device/deny\", { user_code: code }, true);\n this.throwForStatus(res);\n }\n\n // =========================================================================\n // Device pairing — paired-device management\n // =========================================================================\n\n /**\n * The account's paired devices. Session-authed.\n *\n * UI copy note (spec §10.6): removing a device forces a full re-approval next\n * time, but be careful what you promise. It does NOT sign the device out —\n * the server returns `session_revoked: false`, and that session runs until it\n * expires — and it cannot take back the master seed the device already holds.\n * Users assume \"remove\" means \"locked out immediately\"; it does not.\n */\n async listPairedDevices(): Promise<PairedDevice[]> {\n const res = await this.deviceApi(\"GET\", \"/api/auth/devices\", undefined, true);\n this.throwForStatus(res);\n const rows = (res.body as { devices?: unknown[] })?.devices ?? [];\n return rows.map((raw) => {\n const d = raw as {\n id?: string; label?: string; app_id?: string;\n paired_at?: number; last_seen_at?: number; active_session?: boolean;\n };\n return {\n id: d.id ?? \"\",\n label: d.label ?? \"\",\n appId: d.app_id ?? \"\",\n pairedAt: numberOr(d.paired_at, 0),\n lastSeenAt: numberOr(d.last_seen_at, 0),\n activeSession: d.active_session === true,\n };\n });\n }\n\n /**\n * Un-pair a device. Session-authed.\n *\n * It stops being a \"known\" device, so pairing it again needs full approval\n * with a fresh factor. It does NOT end that device's current session — the\n * server reports `session_revoked: false` — and it cannot take back the\n * master seed the device already holds. Do not write UI copy promising an\n * immediate sign-out; users will assume it and be wrong.\n */\n async revokePairedDevice(id: string): Promise<void> {\n if (!id) throw new DevicePairingError(\"error\", { message: \"revokePairedDevice: `id` is required.\" });\n const res = await this.deviceApi(\"DELETE\", \"/api/auth/devices\", { id }, true);\n this.throwForStatus(res);\n }\n\n // ---- device pairing internals -------------------------------------------\n\n /**\n * The whole tail of an approved pairing: unseal → derive → **verify** →\n * authenticate → register → persist. Split out of `pollDevicePairing` so the\n * ordering (and the two refusals) stay readable.\n */\n private async adoptSealedSeed(\n session: DevicePairingSession,\n payload: { sealedKeys: string; username: string; commitment: string },\n ): Promise<AuthUser> {\n let seed: Uint8Array;\n try {\n seed = await unsealSeedFromDevice(payload.sealedKeys, session.privateKey, session.devicePublicKeyB64);\n } catch (e) {\n throw new DevicePairingError(\"commitment_mismatch\", {\n message: \"The sealed key material couldn't be opened on this device — pairing aborted.\",\n cause: e,\n });\n }\n\n const identity = await deriveIdentityFromSeed(seed);\n const commitment = await commitmentFor(identity);\n // §10.8, mandatory: the seed we were handed must derive the commitment the\n // server claims. A compromised API can seal an attacker-controlled seed to\n // this device (§10.2) — this is the check that makes that loud.\n if (commitment !== payload.commitment) {\n throw new DevicePairingError(\"commitment_mismatch\", {\n details: { expected: payload.commitment, derived: commitment },\n });\n }\n // §10.2 detection 2 — commitment pinning across re-pairs. A device that\n // was signed in as someone else must fail closed, not silently switch.\n const pinned = await loadDeviceIdentity();\n if (pinned && pinned.commitment !== commitment) {\n throw new DevicePairingError(\"account_mismatch\", {\n details: { pinnedUsername: pinned.username, offeredUsername: payload.username },\n });\n }\n\n // The device mints its OWN session rather than sharing the approver's, so\n // revoking the TV doesn't sign out the phone that approved it.\n const user = await this.mintSession(payload.username, identity, seed, { rememberMe: true });\n\n // Both are best-effort: the user IS signed in at this point, and failing\n // the whole pairing over a bookkeeping call would be worse than degrading.\n await this.touchPairedDevice();\n try {\n await persistDeviceIdentity({ username: user.username, commitment, seed, pairedAt: Date.now() });\n } catch (e) {\n appLoggerWarn(\"device identity could not be persisted; this device will pair again after a restart\", e);\n }\n return user;\n }\n\n /**\n * Run the standard ZK challenge → Groth16 proof → authenticate round-trip for\n * an identity derived from a seed the caller already holds, and store the\n * resulting session.\n *\n * Identical to `ZkAuth.login()`'s tail (`proveAndStore`) — same challenge,\n * same circuit, same signature — so the commitment is byte-identical to\n * `zk.login(username, password)` by construction. No new endpoint, no circuit\n * change, no alternative derivation.\n *\n * (Spec §7 puts this on `AuthNamespace` as `loginWithSeed`; see the report —\n * it lives here because `AuthNamespace.ts` was out of scope for this change,\n * and `proveAndStore` is private.)\n */\n private async mintSession(\n username: string,\n identity: ZkIdentity,\n seed: Uint8Array,\n opts: LoginOptions = {},\n ): Promise<AuthUser> {\n const ecdsaPubHex = await exportPublicKeyHex(identity.ecdsaKeyPair.publicKey);\n const challenge = await this.deps.auth.getChallenge(username);\n const { proof, publicSignals, commitment } = await generateAuthProof({\n secretHex: identity.secretHex,\n saltHex: identity.saltHex,\n ecdsaPubHex,\n nonceHex: challenge.nonce,\n circuits: this.circuits(),\n });\n const signature = await signMessage(JSON.stringify(proof), identity.ecdsaKeyPair.privateKey);\n const result = await this.deps.auth.authenticate({\n challengeId: challenge.challengeId,\n proof: {\n commitment,\n // The accelerator expects the original hex nonce, 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 await this.deps.session.setSession({ token: result.token, username: result.username, commitment });\n this.deps.session.setIdentity(identity);\n this.deps.session.setSeed(seed);\n return { username: result.username, commitment };\n }\n\n /**\n * `PUT /api/auth/devices` — the device checks in after each self-login so the\n * security page can show \"last seen\" and revoke the right session. Never\n * creates a record (only approve does), so a 404 here is expected on a device\n * whose pairing was revoked. Best-effort by design.\n */\n private async touchPairedDevice(): Promise<void> {\n try {\n const identityKey = await deviceIdentityKey();\n const fingerprint = await deviceFingerprint();\n const issuedAt = Date.now();\n const signature = await signMessage(\n [DEVICE_TOUCH_SIG_PREFIX, fingerprint, String(issuedAt)].join(\"|\"),\n identityKey.privateKey,\n );\n await this.deviceApi(\"PUT\", \"/api/auth/devices\", {\n fingerprint,\n issued_at: issuedAt,\n device_signature: signature,\n }, true);\n } catch (e) {\n appLoggerWarn(\"device check-in failed\", e);\n }\n }\n\n /** Reject a session that {@link cancelDevicePairing} has retired. */\n private assertLive(session: DevicePairingSession): void {\n if (!session || cancelledPairings.has(session) || !session.deviceCode) {\n throw new DevicePairingError(\"aborted\");\n }\n }\n\n private sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (this.deps.sleep) return this.deps.sleep(ms, signal);\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(new DevicePairingError(\"aborted\"));\n };\n if (signal?.aborted) return onAbort();\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n\n /**\n * One round-trip to a `/api/auth/device*` endpoint. Never throws on a non-2xx\n * — the poll path has to inspect 401/403/429 itself — so callers that don't\n * want that follow up with {@link throwForStatus}.\n */\n private async deviceApi(\n method: string,\n path: string,\n body?: unknown,\n withSession = false,\n ): Promise<DeviceApiResponse> {\n const headers: Record<string, string> = {};\n if (body !== undefined) headers[\"Content-Type\"] = \"application/json\";\n if (withSession) {\n const token = this.deps.session.token;\n if (!token) throw new DevicePairingError(\"error\", { code: \"unauthorized\", status: 401, message: \"Sign in first.\" });\n // X-Muhkoo-Session, not `Authorization: Bearer` — the accelerator's\n // session resolver prefers it and raw SPA fetches must use it.\n headers[\"X-Muhkoo-Session\"] = token;\n }\n const fetchFn = this.deps.fetch ?? globalThis.fetch?.bind(globalThis);\n if (typeof fetchFn !== \"function\") throw new Error(\"HostedAuth: no fetch available.\");\n\n const res = await fetchFn(`${this.apiBase()}${path}`, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n\n let parsed: unknown = null;\n try { parsed = await res.json(); } catch { /* empty or non-JSON body */ }\n const envelope = (parsed ?? {}) as { error?: unknown; message?: unknown };\n const retryAfterHeader = Number(res.headers?.get?.(\"Retry-After\"));\n\n return {\n status: res.status,\n ok: res.ok,\n body: parsed,\n code: res.ok || typeof envelope.error !== \"string\" ? undefined : envelope.error,\n message: typeof envelope.message === \"string\"\n ? envelope.message\n : typeof envelope.error === \"string\" ? envelope.error : undefined,\n retryAfter: Number.isFinite(retryAfterHeader) && retryAfterHeader > 0 ? retryAfterHeader : null,\n };\n }\n\n /** Turn a non-2xx device-endpoint response into the right typed error. */\n private throwForStatus(res: DeviceApiResponse): void {\n if (res.ok) return;\n const details = (res.body ?? undefined) as Record<string, unknown> | undefined;\n if (res.code === \"reauth_required\") {\n throw new ReauthRequiredError({\n message: res.message,\n status: res.status,\n authAgeSeconds: numberOrUndefined(details?.auth_age_seconds),\n maxAgeSeconds: numberOrUndefined(details?.max_age_seconds),\n });\n }\n throw new DevicePairingError(reasonForCode(res.code, res.status), {\n message: res.message,\n code: res.code,\n status: res.status,\n retryAfter: res.retryAfter ?? undefined,\n details,\n });\n }\n\n /**\n * Accelerator origin for the device endpoints.\n *\n * Prefers the explicit dep. Falls back to the {@link AuthClient}'s own base\n * URL, because `AuthNamespace` builds `HostedAuth` without one today and a\n * hard-coded default would silently point a staging or local build at\n * production. Last resort: map the auth SPA host (`auth.…` → `api.…`).\n */\n private apiBase(): string {\n const explicit = this.deps.apiBaseUrl;\n if (explicit) return explicit.replace(/\\/+$/, \"\");\n const fromAuthClient = (this.deps.auth as unknown as { baseUrl?: string })?.baseUrl;\n if (typeof fromAuthClient === \"string\" && fromAuthClient) return fromAuthClient.replace(/\\/+$/, \"\");\n try {\n const url = new URL(this.deps.authBaseUrl);\n url.hostname = url.hostname.replace(/^auth\\./, \"api.\");\n url.pathname = \"\";\n return url.toString().replace(/\\/+$/, \"\");\n } catch {\n throw new Error(\"HostedAuth: can't resolve the accelerator base URL — pass `apiBaseUrl`.\");\n }\n }\n\n private circuits(): CircuitUrls {\n return this.deps.circuits ?? defaultCircuitUrls(this.apiBase());\n }\n\n // ---- internals ----------------------------------------------------------\n\n private location(): Location {\n const loc = (globalThis as { location?: Location }).location;\n if (!loc) throw new Error(\"Hosted auth requires a browser environment.\");\n return loc;\n }\n\n private store(v: { codeVerifier: string; state: string; appId: string; redirectUri: string }): void {\n const ss = (globalThis as { sessionStorage?: Storage }).sessionStorage;\n if (!ss) throw new Error(\"Hosted auth requires sessionStorage.\");\n ss.setItem(PKCE_STORE_KEY, JSON.stringify(v));\n }\n\n private take(): { codeVerifier: string; state: string; appId: string; redirectUri: string } | null {\n const ss = (globalThis as { sessionStorage?: Storage }).sessionStorage;\n if (!ss) return null;\n const raw = ss.getItem(PKCE_STORE_KEY);\n if (!raw) return null;\n ss.removeItem(PKCE_STORE_KEY);\n try { return JSON.parse(raw); } catch { return null; }\n }\n\n /** Drop `code`, `state`, and the `#k` fragment from the address bar. */\n private scrubUrl(): void {\n const h = (globalThis as { history?: History }).history;\n const loc = this.location();\n if (h?.replaceState) h.replaceState(null, \"\", loc.pathname);\n }\n}\n\n// ---- device pairing: module helpers ----------------------------------------\n\n/** Sessions retired by {@link HostedAuth.cancelDevicePairing}. Weak so a dropped\n * session is collectable — this must not become a leak on a device that runs\n * for months. */\nconst cancelledPairings = new WeakSet<DevicePairingSession>();\n\ninterface DeviceApiResponse {\n status: number;\n ok: boolean;\n body: unknown;\n /** Machine code from `{error, message}`. Undefined on 2xx. */\n code?: string;\n /** Human sentence — `message`, falling back to `error` for the older shape. */\n message?: string;\n retryAfter: number | null;\n}\n\n/**\n * Map a server error code to the reason the device's state machine branches on.\n * Codes with no dedicated reason land on `\"error\"` and stay readable through\n * {@link DevicePairingError.code}.\n */\nfunction reasonForCode(code: string | undefined, status: number): DevicePairingErrorReason {\n switch (code) {\n case \"expired_token\":\n case \"pairing_not_found\":\n return \"expired\";\n case \"access_denied\":\n return \"denied\";\n case \"slow_down\":\n case \"rate_limited\":\n case \"too_many_requests\":\n return \"rate_limited\";\n case \"reauth_required\":\n return \"reauth_required\";\n case \"invalid_user_code\":\n return \"invalid_user_code\";\n default:\n return status === 429 ? \"rate_limited\" : \"error\";\n }\n}\n\n/**\n * Canonicalize a typed `user_code`: uppercase, drop whitespace and `-`.\n *\n * We deliberately do NOT guess (`O → 0`, `I → 1`, …). Both members of every\n * confusable pair are excluded from the alphabet, so a typed `O` is a genuine\n * misread — telling the user is more useful than silently resolving it.\n */\nexport function canonicalUserCode(input: string): string {\n const code = String(input ?? \"\").toUpperCase().replace(/[\\s-]/g, \"\");\n if (code.length !== PAIRING_CODE_LENGTH) throw new DevicePairingError(\"invalid_user_code\");\n for (const ch of code) {\n if (!PAIRING_CODE_ALPHABET.includes(ch)) throw new DevicePairingError(\"invalid_user_code\");\n }\n return code;\n}\n\n/** Group a canonical code for display and for the wire: `\"K7QD3MXR\"` → `\"K7QD-3MXR\"`. */\nexport function formatUserCode(canonical: string): string {\n const half = Math.ceil(canonical.length / 2);\n return `${canonical.slice(0, half)}-${canonical.slice(half)}`;\n}\n\n/** Poseidon commitment for an identity — the value the server stores. */\nasync function commitmentFor(identity: ZkIdentity): Promise<string> {\n const ecdsaPubHex = await exportPublicKeyHex(identity.ecdsaKeyPair.publicKey);\n return buildCommitment(identity.secretHex, identity.saltHex, ecdsaPubHex);\n}\n\n/**\n * A label the approver can recognise, guessed from the user agent. Android TV\n * user agents are famously uninformative, so this is a coarse family name —\n * §6.4 lets the approver rename the device at approval time.\n */\nfunction defaultDeviceLabel(): string {\n const ua = (globalThis as { navigator?: { userAgent?: string } }).navigator?.userAgent ?? \"\";\n if (/AFT[A-Z]/i.test(ua)) return \"Fire TV\";\n if (/Android.*TV|GoogleTV|Chromecast/i.test(ua)) return \"Android TV\";\n if (/AppleTV|tvOS/i.test(ua)) return \"Apple TV\";\n if (/Tizen|Web0S|WebOS|SMART-TV|BRAVIA|HbbTV|NetCast/i.test(ua)) return \"Smart TV\";\n return \"TV\";\n}\n\nfunction numberOr(v: unknown, fallback: number): number {\n return typeof v === \"number\" && Number.isFinite(v) ? v : fallback;\n}\n\nfunction numberOrUndefined(v: unknown): number | undefined {\n return typeof v === \"number\" && Number.isFinite(v) ? v : undefined;\n}\n\n/** Non-fatal diagnostics. The SDK logger is optional, so never let it throw. */\nfunction appLoggerWarn(message: string, err: unknown): void {\n try {\n (globalThis as { appLogger?: { warn?: (...a: unknown[]) => void } }).appLogger?.warn?.(\n `[hosted-auth] ${message}:`, err instanceof Error ? err.message : err,\n );\n } catch { /* diagnostics must never break the flow */ }\n}\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, deriveIdentityFromSeed, deriveMasterSeedFromPassword, type ZkIdentity } from \"../../auth/identity\";\nimport { seedToMnemonic, mnemonicToSeed } from \"../../auth/recoveryPhrase\";\nimport { generateAuthProof, buildCommitment, type CircuitUrls } from \"../../auth/proof\";\nimport { exportPublicKeyHex, exportPublicKeyBase64, signMessage } from \"../../auth/keys\";\nimport {\n randomSeed, passwordPreHash, wrapKeyFromOprf, wrapKeyFromBytes, wrapSeed, unwrapSeed, toBase64, fromBase64,\n} from \"../../auth/vault\";\nimport { oprfBlind, oprfFinalize } from \"../../auth/oprf\";\nimport { emailFactorInput, googleFactorInput, gatedBlind, gatedWrapKey } from \"../../auth/gatedFactor\";\nimport { passkeySupported, passkeyPrfCapable, createPasskeyWithPrf, evaluatePasskeyPrf, defaultRpId, rpIdUsableForOrigin, passkeyUsableFromOrigin, PasskeyOriginError } from \"../../auth/passkey\";\nimport type { SessionState } from \"../Session\";\nimport { HostedAuth } from \"./HostedAuth\";\n\n/**\n * Thrown when the identity vault can't be reached to unlock the seed — a network\n * failure, a 5xx, or the per-user rate limit (429). This is distinct from a wrong\n * password, and is surfaced so `login`/`unlock` do NOT silently fall back to the\n * legacy password derivation (which, for a vault account, yields a misleading\n * \"commitment mismatch\"). Callers should ask the user to retry, not re-enter a\n * password.\n */\nexport class VaultUnavailableError extends Error {\n constructor(cause?: unknown) {\n const detail = cause instanceof Error ? cause.message : String(cause ?? \"\");\n super(\n /too many|rate.?limit|\\b429\\b/i.test(detail)\n ? \"Too many attempts — please wait a moment and try again.\"\n : \"Couldn't reach the secure vault. Check your connection and try again.\",\n );\n this.name = \"VaultUnavailableError\";\n (this as Error & { cause?: unknown }).cause = cause;\n }\n}\n\n/**\n * A stored device pairing that the account has since revoked.\n *\n * Typed rather than a bare Error because the right response is specific and the\n * wrong one is harmful: the caller must DISCARD its stored key and fall back to\n * a password. Retrying is futile (the factor is gone from the vault), and\n * silently re-pairing would undo the revocation that a user performed\n * deliberately — the whole point of a revocable pairing is that withdrawing it\n * stays withdrawn.\n *\n * Distinct from a wrong key, which fails to decrypt rather than failing to\n * resolve. A machine whose access was withdrawn should be able to say so.\n */\nexport class DeviceRevokedError extends Error {\n constructor() {\n super(\"This device is no longer paired — its access was revoked. Sign in again to re-pair.\");\n this.name = \"DeviceRevokedError\";\n }\n}\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 */\n/** HKDF label separating a device wrap key from every other use of the seed. */\nconst DEVICE_WRAP_INFO = \"muhkoo-device-key-v1\";\n\nexport class ZkAuth {\n constructor(private readonly deps: ZkAuthDeps) {}\n\n /**\n * Register a new user, then (by default) sign them in.\n *\n * M1.0: the identity now descends from a **random master seed** (not the\n * password), so it's recoverable + the password can be changed. We register\n * the commitment, sign in with the in-memory identity to get a token, then\n * enroll the OPRF-gated **password factor** (the seed wrapped under a key the\n * server can't derive offline). Future logins unlock the seed via that factor.\n */\n async register(params: RegisterParams): Promise<AuthUser> {\n const { username, password, email = null, login = true } = params;\n const seed = randomSeed();\n const identity = await deriveIdentityFromSeed(seed);\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 // Sign in with the in-memory (random-seed) identity to obtain a session\n // token, then enroll the password factor so the next login can recover\n // the seed. (A token is required to write the factor.)\n const user = await this.proveAndStore(username, identity, {});\n await this.enrollPasswordFactor(username, password, seed, this.deps.session.token!);\n this.deps.session.setSeed(seed); // held so a passkey/phrase can be enrolled next\n\n if (!login) await this.logout();\n return user;\n }\n\n /**\n * Sign in. M1.0 is **vault-first**: read the password factor and OPRF-unwrap\n * the master seed → identity. If that fails (a pre-vault account, whose factor\n * is absent so the server returns a decoy, or a wrong password), fall back to\n * the legacy password-derived identity. Either way we then prove knowledge of\n * the identity and trade it for a session token.\n */\n async login(username: string, password: string, opts: LoginOptions = {}): Promise<AuthUser> {\n // Vault-first; fall back to the legacy password-derived seed (pre-vault\n // accounts). Either way we end up with the master seed, which we hold so\n // recovery factors can be enrolled.\n const vaultSeed = await this.tryUnlockSeed(username, password);\n const seed = vaultSeed ?? await deriveMasterSeedFromPassword(username, password);\n const identity = await deriveIdentityFromSeed(seed);\n const user = await this.proveAndStore(username, identity, opts);\n this.deps.session.setSeed(seed);\n // Migrate a legacy account into the vault on first vault-aware login: it has\n // no password factor (`vaultSeed` is null), so enroll one now — wrapping the\n // exact legacy-derived seed the proof just validated, so the commitment is\n // preserved. Best-effort; the legacy path still works if this fails.\n if (!vaultSeed) await this.migrateLegacyPasswordFactor(username, password, seed);\n return user;\n }\n\n /** Enroll the password factor for a legacy (pre-vault) account. Idempotent +\n * best-effort; failure just means we retry on the next login. */\n private async migrateLegacyPasswordFactor(username: string, password: string, seed: Uint8Array): Promise<void> {\n const token = this.deps.session.token;\n if (!token) return;\n try {\n await this.enrollPasswordFactor(username, password, seed, token);\n } catch {\n /* migrate next time */\n }\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 * Boot helper — call this once on app start. Restores the session AND, when a\n * passkey is enrolled, silently unlocks the identity via WebAuthn (recovering\n * the master seed so the ratchet keypair rehydrates and `client.kv` works).\n * The seed is never persisted, so a passkey (or password) is the only way to\n * unlock after a reload — this keeps that off the app's plate.\n *\n * Returns `{ user, unlocked }`. When `unlocked` is false (no passkey, the\n * user cancelled, or the browser required a gesture), prompt for a password\n * and call {@link unlock}. Apps need no key-management scaffolding beyond this.\n */\n async resume(): Promise<{ user: AuthUser | null; unlocked: boolean }> {\n const user = await this.restore();\n if (!user) return { user: null, unlocked: false };\n if (this.deps.session.isUnlocked) return { user, unlocked: true };\n try {\n const factors = await this.listFactors();\n // Only auto-attempt when a passkey is usable from THIS origin.\n //\n // Passkeys are per-origin, and an account's passkey may belong to a\n // different host entirely (hosted-auth enrolment records\n // `auth.muhkoo.dev`, so a user who added a passkey there is\n // mismatched on every app host). Attempting anyway means\n // `loginWithPasskey` does an unauthenticated vault read for a\n // passkey this origin doesn't have. Today that returns a decoy with\n // no `prfSalt`, so it fails the guard before touching WebAuthn — the\n // silence is incidental. Once the decoy is reshaped to be\n // indistinguishable (it must carry `prfSalt` to stop being an\n // account-enumeration oracle) that same call would sail through and\n // fire a modal `navigator.credentials.get()` at page load, on every\n // boot, for a credential that does not exist. `resume()` is awaited\n // inside every app's readiness gate, so that dialog lands on the\n // splash screen before the user has asked for anything.\n //\n // `listFactors` is session-authenticated and returns real records,\n // so decoys never appear here — this reads true rpIds.\n //\n // `passkeyUsableFromOrigin`, NOT `rpIdUsableForOrigin`: a factor\n // with no recorded rpId predates per-origin enrolment and is still\n // usable (`loginWithPasskey` resolves it as `params.rpId ?? host`).\n // The raw predicate is false for undefined, so using it here would\n // skip exactly those users — the regression that locked legacy\n // passkey holders out of production twice.\n const host = defaultRpId();\n if (factors.some((f) => f.type === \"passkey\" && passkeyUsableFromOrigin(f.rpId, host))) {\n await this.loginWithPasskey(user.username);\n }\n } catch {\n /* no passkey / cancelled / no user gesture — leave locked for a prompt */\n }\n return { user, unlocked: this.deps.session.isUnlocked };\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 vaultSeed = await this.tryUnlockSeed(username, password);\n const seed = vaultSeed ?? await deriveMasterSeedFromPassword(username, password);\n const identity = await deriveIdentityFromSeed(seed);\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 this.deps.session.setSeed(seed);\n // Migrate a legacy account into the vault if it has no password factor.\n if (!vaultSeed) await this.migrateLegacyPasswordFactor(username, password, seed);\n }\n\n /**\n * Generate a 24-word **recovery phrase** that encodes the master seed, and\n * record a marker in the vault so the UI knows one exists. Show the returned\n * phrase to the user ONCE — it's never stored server-side (the phrase *is* the\n * seed). Requires being signed in (the seed must be held in memory).\n */\n async enrollRecoveryPhrase(): Promise<string> {\n const seed = this.deps.session.seed;\n const token = this.deps.session.token;\n if (!seed || !token) {\n throw new Error(\"Sign in first to set up a recovery phrase.\");\n }\n const mnemonic = seedToMnemonic(seed);\n await this.deps.auth.vaultPutFactor(token, { id: \"phrase\", type: \"phrase-marker\", createdAt: Date.now() });\n return mnemonic;\n }\n\n /**\n * Recover an account with its recovery phrase (the \"forgot password\" path).\n * Decodes the phrase to the master seed → identity → session. After this,\n * call {@link changePassword} to set a new password. No server lookup needed.\n */\n async recoverWithPhrase(username: string, mnemonic: string, opts: LoginOptions = {}): Promise<AuthUser> {\n const seed = mnemonicToSeed(mnemonic);\n const identity = await deriveIdentityFromSeed(seed);\n const user = await this.proveAndStore(username, identity, opts);\n this.deps.session.setSeed(seed);\n return user;\n }\n\n /**\n * Add an **email** as a recovery + login factor (M2 verification-gated:\n * the server only releases the split-key OPRF eval after the address is\n * OTP-verified). Sends the code, then returns a `confirm` continuation:\n *\n * const { confirm } = await client.auth.zk.enrollEmailFactor(\"me@x.com\");\n * await confirm(codeFromInbox);\n *\n * Requires being signed in with the seed held (like the other enrolls).\n * Custody note: gated factors trade some custody for recoverability — the\n * trade-off should be disclosed in the enroll UI.\n */\n async enrollEmailFactor(email: string): Promise<{ email: string; confirm: (code: string) => Promise<void> }> {\n const seed = this.deps.session.seed;\n const token = this.deps.session.token;\n const username = this.deps.session.username;\n if (!seed || !token || !username) {\n throw new Error(\"Sign in first to add a recovery email.\");\n }\n await this.deps.auth.emailOtpStart({ token, email });\n return {\n email,\n confirm: async (code: string) => {\n const { verifyToken, email: verified } = await this.deps.auth.emailOtpVerify({ token, code });\n const input = await emailFactorInput(username, verified);\n const { blind, blinded } = gatedBlind(input);\n const evals = await this.deps.auth.oprfEvaluateGated(username, toBase64(blinded), \"email\", \"enroll\", verifyToken);\n const key = await gatedWrapKey(input, blind, evals.evaluated, evals.evaluated2);\n const wrapped = await wrapSeed(seed, key);\n await this.deps.auth.vaultPutFactor(\n token,\n { id: \"email\", type: \"email\", wrap: wrapped.ct, iv: wrapped.iv, params: { email: verified }, createdAt: Date.now() },\n verifyToken,\n );\n },\n };\n }\n\n /**\n * Recover an account via its enrolled **email** factor. Sends a code to the\n * enrolled address (the response never reveals whether one exists), then\n * `confirm(code)` completes: gated read + split-key eval → unwrap seed →\n * normal ZK login. After this, call {@link changePassword} to set a new\n * password.\n *\n * const { confirm } = await client.auth.zk.recoverWithEmail(\"alice\");\n * const user = await confirm(codeFromInbox);\n */\n async recoverWithEmail(username: string, opts: LoginOptions = {}): Promise<{ confirm: (code: string) => Promise<AuthUser> }> {\n await this.deps.auth.emailOtpStart({ username });\n return {\n confirm: async (code: string) => {\n const { verifyToken, email } = await this.deps.auth.emailOtpVerify({ username, code });\n const { factor } = await this.deps.auth.vaultRead(username, \"email\", verifyToken);\n if (!factor?.wrap || !factor?.iv) {\n throw new Error(\"This account has no email recovery set up.\");\n }\n const input = await emailFactorInput(username, email);\n const { blind, blinded } = gatedBlind(input);\n const evals = await this.deps.auth.oprfEvaluateGated(username, toBase64(blinded), \"email\", \"recover\", verifyToken);\n const key = await gatedWrapKey(input, blind, evals.evaluated, evals.evaluated2);\n const seed = await unwrapSeed({ iv: factor.iv, ct: factor.wrap }, key);\n const identity = await deriveIdentityFromSeed(seed);\n const user = await this.proveAndStore(username, identity, opts);\n this.deps.session.setSeed(seed);\n return user;\n },\n };\n }\n\n // --- Google factor (M2.3) ------------------------------------------------\n // Google is pure authentication UX: its verified ID token gates the\n // split-key OPRF eval that releases the master seed. The ZK identity layer\n // is unchanged. The app obtains `idToken` via Google Identity Services and\n // passes it in; the SDK never renders Google UI.\n\n /**\n * Link a Google account as a recovery + login factor. Requires being signed\n * in with the seed held. `idToken` is a fresh Google ID token (GIS).\n */\n async enrollGoogleFactor(idToken: string): Promise<void> {\n const seed = this.deps.session.seed;\n const token = this.deps.session.token;\n const username = this.deps.session.username;\n if (!seed || !token || !username) throw new Error(\"Sign in first to link a Google account.\");\n const { verifyToken, sub, emailHint } = await this.deps.auth.googleVerify({ idToken, token });\n const input = await googleFactorInput(username, sub);\n const { blind, blinded } = gatedBlind(input);\n const evals = await this.deps.auth.oprfEvaluateGated(username, toBase64(blinded), \"google\", \"enroll\", verifyToken);\n const key = await gatedWrapKey(input, blind, evals.evaluated, evals.evaluated2);\n const wrapped = await wrapSeed(seed, key);\n await this.deps.auth.vaultPutFactor(\n token,\n { id: \"google\", type: \"google\", wrap: wrapped.ct, iv: wrapped.iv, params: { sub, emailHint: emailHint ?? undefined }, createdAt: Date.now() },\n verifyToken,\n );\n }\n\n /**\n * Sign in with Google — verify the ID token, unlock the seed via the gated\n * split-key eval, and establish a session. Same machinery serves \"Sign in\n * with Google\" and \"recover with Google\"; the account must have linked the\n * factor first.\n */\n async loginWithGoogle(username: string, idToken: string, opts: LoginOptions = {}): Promise<AuthUser> {\n const { verifyToken, sub } = await this.deps.auth.googleVerify({ idToken, username });\n const { factor } = await this.deps.auth.vaultRead(username, \"google\", verifyToken);\n if (!factor?.wrap || !factor?.iv) throw new Error(\"No Google account is linked to this username.\");\n const input = await googleFactorInput(username, sub);\n const { blind, blinded } = gatedBlind(input);\n const evals = await this.deps.auth.oprfEvaluateGated(username, toBase64(blinded), \"google\", \"recover\", verifyToken);\n const key = await gatedWrapKey(input, blind, evals.evaluated, evals.evaluated2);\n const seed = await unwrapSeed({ iv: factor.iv, ct: factor.wrap }, key);\n const identity = await deriveIdentityFromSeed(seed);\n const user = await this.proveAndStore(username, identity, opts);\n this.deps.session.setSeed(seed);\n return user;\n }\n\n /**\n * Register a brand-new, **passwordless** account whose only factor is Google.\n * A random master seed is generated and wrapped under the Google-gated key;\n * the user can add a password / passkey / phrase later. The ZK registration\n * is identical to a password signup.\n */\n async registerWithGoogle(username: string, idToken: string): Promise<AuthUser> {\n const seed = randomSeed();\n const identity = await deriveIdentityFromSeed(seed);\n const commitment = await this.commitmentFor(identity);\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: null,\n });\n const user = await this.proveAndStore(username, identity, {});\n this.deps.session.setSeed(seed);\n // Enroll Google as the sole factor (session + seed are now in hand).\n await this.enrollGoogleFactor(idToken);\n return user;\n }\n\n /**\n * Change the password — re-wraps the (unchanged) master seed under the new\n * password's OPRF-gated key. The identity/commitment never moves. Requires\n * being signed in (or freshly recovered) so the seed is held.\n */\n async changePassword(newPassword: string): Promise<void> {\n const seed = this.deps.session.seed;\n const username = this.deps.session.username;\n const token = this.deps.session.token;\n if (!seed || !username || !token) {\n throw new Error(\"Sign in first to change your password.\");\n }\n await this.enrollPasswordFactor(username, newPassword, seed, token);\n }\n\n /** Whether this browser can use passkeys (WebAuthn) at all. */\n passkeyAvailable(): boolean {\n return passkeySupported();\n }\n\n /**\n * Whether this browser's authenticator can do the **PRF extension** our\n * passkey factor requires. A browser may support passkeys generally but not\n * PRF — in which case enrolling one would fail. Resolves `true`/`false`, or\n * `null` when it can't be determined (no capabilities API). Use this to gate\n * the passkey UI so users don't hit a dead-end error.\n */\n async passkeyPrfAvailable(): Promise<boolean | null> {\n return passkeyPrfCapable();\n }\n\n /**\n * Add a **passkey** recovery factor. Creates a WebAuthn passkey with PRF,\n * wraps the master seed under its PRF output, and stores the factor. The\n * passkey (synced via the platform's keychain) then unlocks the account on\n * any device — no password. Requires being signed in (seed held in memory).\n */\n async enrollPasskey(opts?: { rpId?: string; rpName?: string; label?: string }): Promise<void> {\n const seed = this.deps.session.seed;\n const token = this.deps.session.token;\n const username = this.deps.session.username;\n if (!seed || !token || !username) {\n throw new Error(\"Sign in first to add a passkey.\");\n }\n const rpId = opts?.rpId ?? defaultRpId();\n const { credentialId, prfSalt, prfOutput } = await createPasskeyWithPrf({\n rpId,\n rpName: opts?.rpName ?? \"Muhkoo\",\n username,\n });\n const key = await wrapKeyFromBytes(prfOutput, \"muhkoo-passkey-wrap\");\n const wrapped = await wrapSeed(seed, key);\n await this.deps.auth.vaultPutFactor(token, {\n id: `passkey:${toBase64(credentialId).slice(0, 16)}`,\n type: \"passkey\",\n wrap: wrapped.ct,\n iv: wrapped.iv,\n params: { credentialId: toBase64(credentialId), prfSalt: toBase64(prfSalt), rpId },\n label: opts?.label ?? \"Passkey\",\n createdAt: Date.now(),\n });\n }\n\n /**\n * Sign in with a passkey (no password). Reads the passkey factor, evaluates\n * its PRF, unwraps the master seed → identity → session.\n */\n async loginWithPasskey(username: string, opts: LoginOptions = {}): Promise<AuthUser> {\n // Ask for THIS origin's passkey — they're enrolled per-origin, so the\n // account's first passkey may belong to a different host entirely.\n const host = defaultRpId();\n const { factor } = await this.deps.auth.vaultRead(username, \"passkey\", undefined, host);\n const params = factor?.params as { credentialId?: string; prfSalt?: string; rpId?: string } | undefined;\n if (!factor?.wrap || !factor?.iv || !params?.credentialId || !params?.prfSalt) {\n throw new Error(\"No passkey is set up for this account.\");\n }\n const rpId = params.rpId ?? host;\n // Refuse a foreign rpId up front: WebAuthn would throw a raw \"requested\n // RPID did not match the origin\", which reads as a hard failure to the\n // user. A typed error lets the app fall back to another factor and offer\n // to enroll a passkey for this origin.\n if (!rpIdUsableForOrigin(rpId, host)) throw new PasskeyOriginError();\n const prfOutput = await evaluatePasskeyPrf(\n rpId,\n fromBase64(params.credentialId),\n fromBase64(params.prfSalt),\n );\n const key = await wrapKeyFromBytes(prfOutput, \"muhkoo-passkey-wrap\");\n const seed = await unwrapSeed({ iv: factor.iv, ct: factor.wrap }, key);\n const identity = await deriveIdentityFromSeed(seed);\n const user = await this.proveAndStore(username, identity, opts);\n this.deps.session.setSeed(seed);\n return user;\n }\n\n /**\n * List the user's enrolled login methods (metadata only). Session-authed.\n * Gated factors (email/google) carry a `masked` display hint\n * (\"m•••@gmail.com\"); the full value is never returned.\n */\n async listFactors(): Promise<Array<{ id: string; type: string; label?: string; createdAt?: number; masked?: string; rpId?: string }>> {\n const token = this.deps.session.token;\n if (!token) throw new Error(\"Sign in first to view your login methods.\");\n const { factors } = await this.deps.auth.vaultFactors(token);\n return factors;\n }\n\n /**\n * Is a passkey enrolled that can unlock from THIS origin?\n *\n * Passkeys are origin-bound, so an app served on both a custom domain and the\n * platform host needs one per host. Use this to decide whether to offer\n * \"Unlock with passkey\" or go straight to sign-in — prompting with another\n * origin's passkey fails with a raw WebAuthn error. Requires a session\n * (metadata read); returns false when signed out or unsupported.\n */\n async hasPasskeyForThisOrigin(): Promise<boolean> {\n if (!passkeySupported()) return false;\n try {\n const host = defaultRpId();\n const factors = await this.listFactors();\n return factors.some((f) => f.type === \"passkey\" && rpIdUsableForOrigin(f.rpId, host));\n } catch {\n return false;\n }\n }\n\n /** Remove a login method by id (can't remove your only one). Session-authed. */\n async removeFactor(id: string): Promise<void> {\n const token = this.deps.session.token;\n if (!token) throw new Error(\"Sign in first to manage your login methods.\");\n await this.deps.auth.vaultDeleteFactor(token, id);\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 * The master seed as base64, or `null` when locked. The host app uses this to\n * wrap app-level data (e.g. chat ratchet keys) to the **seed** instead of the\n * password — so that data survives password changes and can be unlocked by a\n * passwordless (passkey) login, both of which recover the same seed.\n */\n get seedBase64(): string | null {\n const seed = this.deps.session.seed;\n return seed ? toBase64(seed) : null;\n }\n\n /**\n * Pair this machine, so it can unlock the account later without a password.\n *\n * Generates a random 32-byte key, wraps the master seed under it, and stores\n * only the CIPHERTEXT in the vault as a `device` factor. The key is returned\n * for the caller to persist locally and is never sent anywhere.\n *\n * The split is the point: the seed itself never lands on disk, and the\n * server holds a blob it cannot open. Revoking the factor\n * ({@link revokeDevice}) makes the local key inert immediately — which a\n * stored master seed can never be, because nothing can reach out and\n * un-store it.\n *\n * Returns the factor id and the key, both base64. Losing the key just means\n * re-pairing; leaking it is equivalent to leaking the seed for as long as\n * the factor exists, so store it with the tightest permissions available.\n */\n async enrollDevice(label: string): Promise<{ factorId: string; deviceKey: string }> {\n const seed = this.deps.session.seed;\n const token = this.deps.session.token;\n if (!seed || !token) throw new Error(\"Sign in first to pair this device.\");\n\n const keyBytes = randomSeed(); // 32 bytes of CSPRNG\n const key = await wrapKeyFromBytes(keyBytes, DEVICE_WRAP_INFO);\n const wrapped = await wrapSeed(seed, key);\n // 128 bits of id, so reading a factor by id is not an enumeration surface.\n const factorId = `device:${toBase64(randomSeed()).replace(/[+/=]/g, \"\").slice(0, 22)}`;\n\n await this.deps.auth.vaultPutFactor(token, {\n id: factorId,\n type: \"device\",\n wrap: wrapped.ct,\n iv: wrapped.iv,\n label,\n createdAt: Date.now(),\n });\n return { factorId, deviceKey: toBase64(keyBytes) };\n }\n\n /**\n * Unlock using a key stored by {@link enrollDevice}.\n *\n * Fetches the wrapped seed and opens it locally. Establishes the encryption\n * identity only — pair it with a session for calls that need one.\n *\n * Throws distinguishably: a REVOKED factor is gone from the vault and says\n * so, where a wrong key fails to decrypt. A machine that has had its access\n * withdrawn should be able to tell you that, not just \"decryption failed\".\n */\n async unlockWithDevice(username: string, factorId: string, deviceKey: string): Promise<void> {\n const seed = await this.openDeviceFactor(username, factorId, deviceKey);\n this.deps.session.setSeed(seed);\n }\n\n /**\n * Sign in using a key stored by {@link enrollDevice} — session AND seed.\n *\n * {@link unlockWithDevice} recovers only the encryption identity, which suits\n * a CLI that already holds a session token on disk. A browser generally does\n * not: its session expires while the device pairing is still perfectly valid,\n * and at that point it holds the means to decrypt everything but no way to\n * make an authenticated call. So this derives the ZK identity from the\n * recovered seed and proves it, exactly as {@link recoverWithPhrase} does —\n * the seed has always been sufficient to authenticate, and withholding that\n * here just meant re-typing a password to prove something already known.\n *\n * This is what makes single sign-on possible without any credential at rest:\n * the seed is never stored, only a key that opens a server-held blob, and\n * revoking the factor ({@link revokeDevice}) severs it immediately.\n *\n * Throws distinguishably on a revoked pairing, so a caller can clear its\n * stored key and fall back to a password rather than retrying forever.\n */\n async loginWithDevice(username: string, factorId: string, deviceKey: string, opts: LoginOptions = {}): Promise<AuthUser> {\n const seed = await this.openDeviceFactor(username, factorId, deviceKey);\n const identity = await deriveIdentityFromSeed(seed);\n const user = await this.proveAndStore(username, identity, opts);\n this.deps.session.setSeed(seed);\n return user;\n }\n\n /** Fetch and open a `device` factor. Shared by the unlock and login paths so\n * the two can never disagree about what a revoked pairing looks like. */\n private async openDeviceFactor(username: string, factorId: string, deviceKey: string): Promise<Uint8Array> {\n const { factor } = await this.deps.auth.vaultRead(username, \"device\", undefined, undefined, factorId);\n if (!factor) {\n throw new DeviceRevokedError();\n }\n if (!factor.wrap || !factor.iv) throw new Error(\"The stored device factor is incomplete; re-pair this device.\");\n const key = await wrapKeyFromBytes(fromBase64(deviceKey), DEVICE_WRAP_INFO);\n return unwrapSeed({ iv: factor.iv, ct: factor.wrap }, key);\n }\n\n /** Paired machines, newest first. Metadata only — never the ciphertext. */\n async listDevices(): Promise<Array<{ id: string; label?: string; createdAt?: number }>> {\n const token = this.deps.session.token;\n if (!token) throw new Error(\"Sign in first to list paired devices.\");\n const { factors } = await this.deps.auth.vaultFactors(token);\n return factors\n .filter((f) => f.type === \"device\")\n .map((f) => ({ id: f.id, label: f.label, createdAt: f.createdAt }))\n .sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0));\n }\n\n /** Withdraw a machine's access. Its stored key stops working immediately. */\n async revokeDevice(factorId: string): Promise<boolean> {\n const token = this.deps.session.token;\n if (!token) throw new Error(\"Sign in first to revoke a device.\");\n const { deleted } = await this.deps.auth.vaultDeleteFactor(token, factorId);\n return deleted;\n }\n\n /**\n * Restore an unlocked identity from a seed you already hold.\n *\n * The inverse of {@link seedBase64}, for hosts that persist the seed\n * themselves rather than re-deriving it from a password: a CLI holding it in\n * a 0600 file, a server-side tool, a test. Without this the seed is a\n * one-way export and anything outside a browser has to run a full ZK login —\n * circuits download and proof — on every single invocation.\n *\n * Establishes the ENCRYPTION identity only. It does not authenticate: pair\n * it with a session token (`sessionStore`) for calls that need one.\n *\n * Treat a persisted seed as the master credential it is. It is not scoped\n * and cannot be revoked server-side the way a session token can — rotating\n * it means moving the identity.\n */\n unlockWithSeed(seedBase64: string): void {\n const seed = fromBase64(seedBase64);\n if (seed.length !== 32) {\n throw new Error(`auth.zk.unlockWithSeed: expected a 32-byte seed, got ${seed.length}`);\n }\n this.deps.session.setSeed(seed);\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 // ---- Identity vault (M1.0) ----------------------------------------------\n\n /**\n * Derive the OPRF-gated wrap key for the password factor: `scrypt(password)`\n * is blinded, evaluated by the server's secret OPRF key (so it can't be\n * derived offline), unblinded, then HKDF'd into an AES-GCM key.\n */\n private async passwordWrapKey(username: string, password: string): Promise<CryptoKey> {\n const pre = passwordPreHash(username, password);\n const { blind, blinded } = oprfBlind(pre);\n const { evaluated } = await this.deps.auth.oprfEvaluate(username, toBase64(blinded));\n return wrapKeyFromOprf(oprfFinalize(pre, blind, fromBase64(evaluated)));\n }\n\n /**\n * Try to recover the master seed from the password factor.\n *\n * Returns `null` only when the vault read SUCCEEDS but the seed can't be\n * unwrapped — i.e. there's no real factor (a pre-vault/legacy account, whose\n * read returns a decoy that won't unwrap) or the password is wrong. The caller\n * then legitimately falls back to the legacy password-derived identity.\n *\n * Throws {@link VaultUnavailableError} when the vault itself can't be reached\n * (network / 5xx / rate-limit) — so a *transient* failure is NOT silently\n * turned into a legacy fallback (which would surface as \"commitment mismatch\").\n */\n private async tryUnlockSeed(username: string, password: string): Promise<Uint8Array | null> {\n const read = await this.deps.auth\n .vaultRead(username, \"password\")\n .catch((e) => { throw new VaultUnavailableError(e); });\n const factor = read.factor;\n if (!factor?.wrap || !factor?.iv) return null; // genuinely no factor → legacy account\n\n const key = await this\n .passwordWrapKey(username, password)\n .catch((e) => { throw new VaultUnavailableError(e); }); // OPRF eval unreachable / rate-limited\n\n try {\n return await unwrapSeed({ iv: factor.iv, ct: factor.wrap }, key);\n } catch {\n return null; // factor present but won't unwrap → wrong password, or a decoy\n }\n }\n\n /**\n * Enroll/replace the password factor for `username` — wraps `seed` under the\n * OPRF-gated key and stores it (needs a session `token`).\n *\n * Retries: this is the step that persists the (otherwise in-memory-only)\n * master seed. If it fails after a fresh registration the account would be\n * unrecoverable, so we retry a few times before surfacing the error.\n */\n private async enrollPasswordFactor(username: string, password: string, seed: Uint8Array, token: string): Promise<void> {\n const key = await this.passwordWrapKey(username, password);\n const wrapped = await wrapSeed(seed, key);\n const factor = { id: \"password\", type: \"password\" as const, wrap: wrapped.ct, iv: wrapped.iv, createdAt: Date.now() };\n\n let lastErr: unknown;\n for (let attempt = 0; attempt < 3; attempt++) {\n try {\n await this.deps.auth.vaultPutFactor(token, factor);\n return;\n } catch (err) {\n lastErr = err;\n await new Promise((r) => setTimeout(r, 200 * (attempt + 1)));\n }\n }\n throw new Error(\n \"Registration could not finish securing your account (vault enrollment failed). \" +\n \"Please try again. \" + (lastErr instanceof Error ? lastErr.message : \"\"),\n );\n }\n}\n\n/** `client.auth` — the auth namespace. Strategies hang off here. */\nexport class AuthNamespace {\n readonly zk: ZkAuth;\n /** Centralized hosted auth (auth.muhkoo.dev) — `client.auth.hosted.login(...)`. */\n readonly hosted: HostedAuth;\n constructor(deps: ZkAuthDeps & { authBaseUrl: string; apiBaseUrl?: string }) {\n this.zk = new ZkAuth(deps);\n this.hosted = new HostedAuth({\n auth: deps.auth,\n session: deps.session,\n authBaseUrl: deps.authBaseUrl,\n // Forwarded explicitly so device pairing resolves the accelerator\n // origin and the circuit assets the SAME way the rest of the client\n // does. Without these, `HostedAuth` falls back to reading\n // `AuthClient.baseUrl` reflectively and to `defaultCircuitUrls`,\n // which silently ignores an app's `ClientOptions.circuits` override.\n apiBaseUrl: deps.apiBaseUrl,\n circuits: deps.circuits,\n });\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 * `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 { HttpClient, HttpError } 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\";\nimport type { KvCache } from \"../../offline/KvCache\";\nimport type { QueueEntry } from \"../../offline/store/OfflineStore\";\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 /** Offline cache + queue. Undefined ⇒ no offline behavior (network-only). */\n offline?: KvCache;\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 /** HLC stamp (present once the accelerator's LWW support is deployed). */\n hlc?: string;\n}\n\nexport class KvNamespace {\n /** One personal-space socket, shared by every subscriber. */\n private feed: {\n transport: WSTransport;\n handlers: Set<(frame: unknown) => void>;\n onMessage: (e: CustomEvent) => void;\n } | null = null;\n\n private cipher: StorageCipher | null = null;\n private cipherIdentity: ZkIdentity | null = null;\n\n constructor(private readonly deps: KvNamespaceDeps) {\n // Replay queued kv writes on reconnect by re-issuing the original request.\n if (deps.offline?.enabled) {\n // Registration is on the manager via the cache's manager handle; the\n // Client wires the replayer (it owns the manager) — see Client.ts.\n }\n }\n\n /** Replay one queued kv mutation (called by the sync engine). */\n async replay(entry: QueueEntry): Promise<void> {\n const a = entry.args as { collection: string; id: string; stored?: unknown; hlc: string };\n if (entry.method === \"set\") {\n await this.deps.http.post(this.kvPath(a.collection, a.id), { value: a.stored, hlc: a.hlc });\n } else {\n await this.deps.http.del(this.kvPath(a.collection, a.id), { hlc: a.hlc });\n }\n }\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 const offline = this.deps.offline;\n if (!offline?.enabled) {\n await this.deps.http.post(this.kvPath(collection, id), { value: stored });\n return;\n }\n const fullKey = `${collection}/${id}`;\n const hlc = await offline.nextHlc();\n await offline.writeLocal(this.commitment(), fullKey, stored, hlc);\n try {\n await this.deps.http.post(this.kvPath(collection, id), { value: stored, hlc });\n } catch (err) {\n if (err instanceof HttpError) throw err; // server reachable + refused\n await offline.enqueue(\"set\", { collection, id, stored, hlc }, hlc, offline.newClientId());\n }\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 offline = this.deps.offline;\n if (!offline?.enabled) {\n const res = await this.deps.http.post<{ value: unknown }>(`${this.kvPath(collection, id)}/get`, {});\n return this.decode<T>(res.value);\n }\n const fullKey = `${collection}/${id}`;\n try {\n const res = await this.deps.http.post<{ value: unknown; hlc?: string }>(\n `${this.kvPath(collection, id)}/get`,\n {},\n );\n // Refresh the cache from the authoritative read (merge by HLC).\n await offline.mergeRemote(\n this.commitment(),\n fullKey,\n res.value ?? null,\n res.value == null ? \"delete\" : \"set\",\n res.hlc,\n );\n return this.decode<T>(res.value);\n } catch (err) {\n if (err instanceof HttpError) throw err; // a real server error, not offline\n const entry = await offline.read(this.commitment(), fullKey);\n if (!entry || entry.deleted) return null;\n return this.decode<T>(entry.value);\n }\n }\n\n /** Delete `collection`/`id`. Returns whether the key existed. */\n async delete(collection: string, id: string): Promise<boolean> {\n const offline = this.deps.offline;\n if (!offline?.enabled) {\n const res = await this.deps.http.del<{ ok: boolean; existed: boolean }>(this.kvPath(collection, id), {});\n return Boolean(res.existed);\n }\n const fullKey = `${collection}/${id}`;\n const hlc = await offline.nextHlc();\n await offline.deleteLocal(this.commitment(), fullKey, hlc);\n try {\n const res = await this.deps.http.del<{ ok: boolean; existed: boolean }>(this.kvPath(collection, id), { hlc });\n return Boolean(res.existed);\n } catch (err) {\n if (err instanceof HttpError) throw err;\n await offline.enqueue(\"delete\", { collection, id, hlc }, hlc, offline.newClientId());\n return true; // optimistic\n }\n }\n\n /** List the ids present in `collection`. */\n async list(collection: string): Promise<string[]> {\n const prefix = `${collection}/`;\n const offline = this.deps.offline;\n const fromKeys = (keys: string[]) =>\n keys.filter((k) => k.startsWith(prefix)).map((k) => k.slice(prefix.length));\n if (!offline?.enabled) {\n const res = await this.deps.http.post<{ keys: string[] }>(this.spacePath(\"/list\"), {});\n return fromKeys(res.keys ?? []);\n }\n try {\n const res = await this.deps.http.post<{ keys: string[] }>(this.spacePath(\"/list\"), {});\n // Union with cached live keys so un-synced offline creates still show.\n const cached = await offline.liveKeys(this.commitment());\n return [...new Set([...(res.keys ?? []), ...cached].filter((k) => k.startsWith(prefix)))].map((k) =>\n k.slice(prefix.length),\n );\n } catch (err) {\n if (err instanceof HttpError) throw err;\n return fromKeys(await offline.liveKeys(this.commitment()));\n }\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 return this.onRaw((raw) => {\n void this.dispatchChange<T>(raw, handler);\n });\n }\n\n /**\n * Subscribe to the personal space's raw change feed.\n *\n * Every key this user owns crosses this socket, not only `client.kv`\n * collections — the VFS keeps its directory records here too. Consumers get\n * the frame untouched: no decryption, no offline-cache merge, because the\n * value's meaning depends on which subsystem wrote it.\n *\n * The transport is SHARED and reference-counted. `WSTransport` namespaces\n * its events by `id`, so two transports with the same id would cross wires\n * on the shared event bus — and a second socket to the same Durable Object\n * would be pure waste besides.\n */\n onRaw(handler: (frame: unknown) => void): () => void {\n if (typeof (globalThis as { WebSocket?: typeof WebSocket }).WebSocket !== \"function\") {\n throw new Error(\"client.kv.onRaw: no `WebSocket` global available in this runtime.\");\n }\n const token = this.deps.session.token;\n if (!token) throw new Error(\"client.kv.onRaw: not signed in.\");\n const commitment = this.commitment();\n\n if (!this.feed) {\n const url = `${this.deps.wsBaseUrl}/api/personal/${encodeURIComponent(commitment)}/websocket?session=${encodeURIComponent(token)}`;\n // Ride a WSTransport rather than a bare socket: it keeps the\n // (otherwise idle) feed warm with heartbeat pings, auto-reconnects\n // if it drops, and namespaces its events by `id`.\n const transport = new WSTransport({ url, id: `personal:${commitment}` });\n const handlers = new Set<(frame: unknown) => void>();\n const onMessage = (e: CustomEvent) => {\n for (const fn of handlers) fn(e.detail);\n };\n transport.on(EventCoreEvents.MESSAGE, onMessage);\n // Fire-and-forget: the feed is best-effort, and the transport queues\n // nothing it needs before CONNECTED (server→client only).\n void transport.connect();\n this.feed = { transport, handlers, onMessage };\n }\n\n const feed = this.feed;\n feed.handlers.add(handler);\n return () => {\n feed.handlers.delete(handler);\n // Last subscriber out closes the socket, so an app that unsubscribes\n // everything is not left holding an open connection.\n if (feed.handlers.size === 0 && this.feed === feed) {\n feed.transport.off(EventCoreEvents.MESSAGE, feed.onMessage);\n feed.transport.disconnect();\n this.feed = null;\n }\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 // Keep the offline cache warm from the realtime feed (merge by HLC).\n if (this.deps.offline?.enabled) {\n await this.deps.offline.mergeRemote(\n this.commitment(),\n frame.key,\n frame.op === \"set\" ? frame.value ?? null : null,\n frame.op,\n frame.hlc,\n );\n }\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 { HttpClient, HttpError } from \"../HttpClient\";\nimport type { DbCache } from \"../../offline/DbCache\";\nimport type { QueueEntry } from \"../../offline/store/OfflineStore\";\n\nexport interface DbNamespaceDeps {\n http: HttpClient;\n /** Offline row/query cache + write queue. Undefined ⇒ network-only. */\n offline?: DbCache;\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(\n private readonly http: HttpClient,\n private readonly name: string,\n private readonly offline?: DbCache,\n ) {}\n\n private base(): string {\n return `/api/db/${encodeURIComponent(this.name)}`;\n }\n private rowUrl(id: string | number): string {\n return `${this.base()}/${encodeURIComponent(String(id))}`;\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 if (!this.offline?.enabled) return this.http.post(this.base(), { values });\n const hlc = await this.offline.nextHlc();\n const _hlc = this.offline.columnStamps(values as Record<string, unknown>, hlc);\n try {\n const res = await this.http.post<{ row: T; id: unknown }>(this.base(), { values, _hlc });\n await this.offline.writeRow(this.name, String(res.id), res.row as Record<string, unknown>);\n return res;\n } catch (err) {\n if (err instanceof HttpError) throw err;\n // Offline: queue for replay. No server pk yet — return a provisional\n // client id so the caller has a stable handle until sync.\n const clientId = this.offline.newClientId();\n await this.offline.enqueue(\"insert\", { table: this.name, values, _hlc }, hlc, clientId);\n return { row: values as T, id: clientId };\n }\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.rowUrl(id));\n if (this.offline?.enabled) await this.offline.writeRow(this.name, String(id), res.row as Record<string, unknown>);\n return res.row;\n } catch (e) {\n if ((e as { status?: number })?.status === 404) return null;\n if (this.offline?.enabled && !(e instanceof HttpError)) {\n return (await this.offline.readRow(this.name, String(id))) as T | null;\n }\n throw e;\n }\n }\n\n /** Query rows with filters, ordering, and keyset pagination. */\n async query(query: DbQuery = {}): Promise<DbQueryResult<T>> {\n if (!this.offline?.enabled) return this.http.post(`${this.base()}/query`, query);\n try {\n const res = await this.http.post<DbQueryResult<T>>(`${this.base()}/query`, query);\n await this.offline.writeQuery(this.name, query, res as { rows: Array<Record<string, unknown>>; nextCursor: string | null });\n return res;\n } catch (e) {\n if (e instanceof HttpError) throw e;\n const cached = await this.offline.readQuery(this.name, query);\n return (cached as DbQueryResult<T> | null) ?? { rows: [], nextCursor: null };\n }\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 if (!this.offline?.enabled) return this.http.patch(this.rowUrl(id), { values });\n const hlc = await this.offline.nextHlc();\n const _hlc = this.offline.columnStamps(values as Record<string, unknown>, hlc);\n await this.offline.patchRow(this.name, String(id), values as Record<string, unknown>); // optimistic\n try {\n const res = await this.http.patch<{ row: T }>(this.rowUrl(id), { values, _hlc });\n await this.offline.writeRow(this.name, String(id), res.row as Record<string, unknown>);\n return res;\n } catch (err) {\n if (err instanceof HttpError) throw err;\n await this.offline.enqueue(\"update\", { table: this.name, id, values, _hlc }, hlc, this.offline.newClientId());\n return { row: (await this.offline.readRow(this.name, String(id))) as T };\n }\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 if (!this.offline?.enabled) {\n const res = await this.http.del<{ deleted: number }>(this.rowUrl(id));\n return res.deleted ?? 0;\n }\n const hlc = await this.offline.nextHlc();\n await this.offline.deleteRow(this.name, String(id)); // optimistic\n try {\n const res = await this.http.del<{ deleted: number }>(this.rowUrl(id), { _hlc: hlc });\n return res.deleted ?? 0;\n } catch (err) {\n if (err instanceof HttpError) throw err;\n await this.offline.enqueue(\"delete\", { table: this.name, id, hlc }, hlc, this.offline.newClientId());\n return 1; // optimistic\n }\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, this.deps.offline);\n }\n\n /** Replay one queued db mutation (called by the sync engine). */\n async replay(entry: QueueEntry): Promise<void> {\n const a = entry.args as {\n table: string;\n id?: string | number;\n values?: Record<string, unknown>;\n _hlc?: Record<string, string>;\n hlc?: string;\n };\n const base = `/api/db/${encodeURIComponent(a.table)}`;\n if (entry.method === \"insert\") {\n await this.deps.http.post(base, { values: a.values, _hlc: a._hlc });\n } else if (entry.method === \"update\") {\n await this.deps.http.patch(`${base}/${encodeURIComponent(String(a.id))}`, { values: a.values, _hlc: a._hlc });\n } else if (entry.method === \"delete\") {\n await this.deps.http.del(`${base}/${encodeURIComponent(String(a.id))}`, { _hlc: a.hlc });\n }\n }\n}\n\nexport default DbNamespace;\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, type ShardByteCache } 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 /** Offline shard-byte cache (browser). Enables offline reads of cached files. */\n shardCache?: ShardByteCache;\n /** Queue a shard PUT that couldn't reach the network (offline). */\n deferShardUpload?: (hash: string) => Promise<void>;\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 cache: this.deps.shardCache,\n deferUpload: this.deps.deferShardUpload,\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 * 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, type ShardByteCache, type PeerBlockSource } 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\n/**\n * A P2P swarm attached to a Space (the p2p layer's `PeerNetwork` satisfies this\n * structurally — Space never imports the p2p module). `exchange` is consulted by\n * the Space's file `ShardClient`; `start` runs peer discovery on connect; `close`\n * tears the mesh down.\n */\nexport interface AttachedPeerNetwork {\n readonly exchange: PeerBlockSource;\n start(): void;\n close(): void;\n gossip(data: Uint8Array): void;\n onGossip(cb: (from: string, data: Uint8Array) => void): () => void;\n}\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 * Sender-generated id, present on locally-originated messages (carried in the\n * cleartext `cid` header). Lets the UI dedupe an optimistic send against its\n * server echo, and the offline cache replace a pending entry with the real one.\n */\n clientId?: string;\n /** True for an optimistic local send not yet acknowledged by the server. */\n pending?: boolean;\n}\n\n/**\n * One sealed message frame as cached for offline use. The `packet` is the\n * ciphertext-bearing serialized {@link Packet} (decrypted lazily on read), so\n * nothing readable is persisted. Structurally matches the offline layer's\n * `MessageEntry`; declared here so the spaces module doesn't import `../offline`.\n */\nexport interface CachedSpaceMessage {\n handle: string;\n packet: string | null;\n op: \"msg\" | \"edit\" | \"delete\";\n clientId?: string;\n hlc?: string;\n pending?: boolean;\n deleted?: boolean;\n}\n\n/** The offline adapter a {@link Space} drives. Implemented by `SpaceCache`. */\nexport interface SpaceOfflineAdapter {\n readonly enabled: boolean;\n newClientId(): string;\n nextHlc(): Promise<string>;\n putMessage(spaceId: string, entry: CachedSpaceMessage): Promise<void>;\n putDeleted(spaceId: string, handle: number): Promise<void>;\n dropPending(spaceId: string, clientId: string): Promise<void>;\n loadMessages(spaceId: string): Promise<CachedSpaceMessage[]>;\n getCursor(spaceId: string): Promise<{ lastSeenHandle: number; oldestHandle: number } | null>;\n observeHandle(spaceId: string, handle: number): Promise<void>;\n enqueueFrame(spaceId: string, frame: unknown, clientId: string, hlc: string): Promise<void>;\n registerCatchUp(task: () => Promise<void>): () => void;\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 /** Offline shard-byte cache for room files (browser). */\n shardCache?: ShardByteCache;\n /** Queue a room-file shard PUT that couldn't reach the network. */\n deferShardUpload?: (hash: string) => Promise<void>;\n /** Offline message cache + send queue. Undefined ⇒ no offline behavior. */\n offline?: SpaceOfflineAdapter;\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 private catchUpUnsub: (() => void) | null = null;\n /** Optional P2P swarm for this Space (block exchange among members). */\n private peerNet: AttachedPeerNetwork | null = null;\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 // Kick P2P peer discovery now the signaling channel is live\n // (re-runs on each reconnect to re-form the mesh).\n this.peerNet?.start();\n });\n this.wireFanout();\n // Register offline catch-up once: on each reconnect the sync\n // engine pages history forward to fill any gap we missed.\n if (this.deps.offline?.enabled && !this.catchUpUnsub) {\n this.catchUpUnsub = this.deps.offline.registerCatchUp(() => this.catchUp());\n }\n }\n }\n await this.channel.connect();\n }\n\n disconnect(): void {\n this.channel?.disconnect();\n this.catchUpUnsub?.();\n this.catchUpUnsub = null;\n this.peerNet?.close();\n this.peerNet = null;\n }\n\n /** Attach a P2P swarm so this Space's file reads/writes can use peers. */\n attachPeerNetwork(net: AttachedPeerNetwork): void {\n this.peerNet = net;\n }\n\n /**\n * Broadcast an app payload directly to connected Space peers over P2P,\n * **bypassing the server** — for CRDT ops / high-frequency state (live\n * cursors, presence, collaborative edits) you don't want to push through the\n * relay. No-op when no P2P mesh is active (requires `client` `p2p`).\n * Unlike {@link sendEphemeral} (server-relayed, metered, size-limited), this\n * is peer-direct and fragments large payloads.\n */\n gossipToPeers(data: Uint8Array): void {\n this.peerNet?.gossip(data);\n }\n\n /** Subscribe to peer gossip ({@link gossipToPeers}). Returns an unsubscribe fn. */\n onPeerGossip(handler: (from: string, data: Uint8Array) => void): () => void {\n return this.peerNet?.onGossip(handler) ?? (() => {});\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 const offline = this.deps.offline;\n if (!offline?.enabled) {\n this.sendRaw({ spaceMessage: await this.sealMessage(payload, opts.channel, opts.contentType) });\n return;\n }\n // Offline-aware path: stamp the message, cache it optimistically (so the\n // UI can show it instantly via cachedMessages), then send if connected\n // or durably queue it for replay on reconnect.\n const clientId = offline.newClientId();\n const hlc = await offline.nextHlc();\n const packet = await this.sealMessage(payload, opts.channel, opts.contentType, clientId);\n const frame = { spaceMessage: packet };\n const entry = {\n handle: provisionalSpaceKey(clientId),\n packet,\n op: \"msg\" as const,\n clientId,\n hlc,\n pending: true,\n };\n if (this.isConnected()) {\n this.sendRaw(frame); // send first — don't block the wire on IndexedDB\n void offline.putMessage(this.id, entry); // optimistic cache off the hot path\n } else {\n // Offline: persist the optimistic entry + durable replay queue.\n void offline.putMessage(this.id, entry);\n await offline.enqueueFrame(this.id, frame, clientId, hlc);\n }\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 const frame = { editSpaceMessage: { ts: handle, spaceMessage } };\n const offline = this.deps.offline;\n if (offline?.enabled) {\n await offline.putMessage(this.id, {\n handle: padSpaceHandle(handle),\n packet: spaceMessage,\n op: \"edit\",\n hlc: await offline.nextHlc(),\n });\n if (this.isConnected()) this.sendRaw(frame);\n else await offline.enqueueFrame(this.id, frame, offline.newClientId(), await offline.nextHlc());\n return;\n }\n this.sendRaw(frame);\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 const frame = { deleteSpaceMessage: { ts: handle } };\n const offline = this.deps.offline;\n if (offline?.enabled) {\n await offline.putDeleted(this.id, handle);\n if (this.isConnected()) this.sendRaw(frame);\n else await offline.enqueueFrame(this.id, frame, offline.newClientId(), await offline.nextHlc());\n return;\n }\n this.sendRaw(frame);\n }\n\n /**\n * Decrypt and return the locally-cached message log for this space, in\n * handle order (pending sends last). Works offline — the source is the\n * IndexedDB cache populated by live frames + {@link history}. Apps call this\n * on boot to paint instantly, then subscribe to {@link onMessage} for live\n * updates. Returns `[]` when offline support is off.\n */\n async cachedMessages(): Promise<SpaceMessageEvent[]> {\n const offline = this.deps.offline;\n if (!offline?.enabled || !this.cipher) return [];\n const entries = (await offline.loadMessages(this.id)).filter((e) => !e.deleted && e.packet);\n // Decode in parallel (already verified when cached → skipVerify).\n const decodedAll = await Promise.all(\n entries.map((e) =>\n this.decodeFrame(e.packet!, this.cipher!, /*isRawFrame*/ true, e.pending ? 0 : Number(e.handle), /*skipVerify*/ true),\n ),\n );\n const out: SpaceMessageEvent[] = [];\n for (let i = 0; i < decodedAll.length; i++) {\n const decoded = decodedAll[i];\n if (decoded) {\n decoded.pending = entries[i].pending;\n out.push(decoded);\n }\n }\n return out;\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, to?: string): void {\n if (!this.isConnected()) return;\n // `to` (a member id) lets the server unicast a *directed* ephemeral\n // instead of broadcasting; omitted ⇒ broadcast to the room (unchanged).\n this.sendRaw({ pub: to ? { subject, data, to } : { 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 // Temporary staging diagnostic: split fetch / directory / decode time.\n const dbg = (() => { try { return globalThis.location?.hostname?.includes(\"staging\"); } catch { return false; } })();\n const mark = () => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n const t0 = mark();\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 const tFetch = mark();\n // Warm the member directory once so historical senders' signatures verify.\n // Force past the cooldown — a history load is an explicit \"get fresh\".\n await this.deps.keyring?.refreshDirectory({ force: true });\n const tDir = mark();\n // Decode the whole page in PARALLEL — each frame is an AES-GCM decrypt +\n // ECDSA verify on the WebCrypto thread; doing them sequentially (await\n // per message) serializes ~100 main↔crypto round-trips and dominates\n // load time. Promise.all preserves input order.\n const raws = body.messages ?? [];\n const decodedAll = await Promise.all(raws.map((raw) => this.decodeFrame(raw, cipher)));\n if (dbg) {\n console.info(\n `[muhkoo:space] history n=${raws.length} | fetch ${Math.round(tFetch - t0)}ms | dir ${Math.round(tDir - tFetch)}ms | decode ${Math.round(mark() - tDir)}ms`,\n );\n }\n const messages: SpaceMessageEvent[] = [];\n for (let i = 0; i < decodedAll.length; i++) {\n const decoded = decodedAll[i];\n if (!decoded) continue;\n messages.push(decoded);\n // Warm the offline cache off the hot path (best-effort, non-blocking).\n if (this.deps.offline?.enabled) {\n try {\n const outer = JSON.parse(raws[i]) as { spaceMessage?: string };\n if (typeof outer.spaceMessage === \"string\") {\n void this.cacheFrame(outer.spaceMessage, decoded, \"msg\");\n }\n } catch {\n /* unparseable history row — skip caching, still surfaced above */\n }\n }\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: {\n onProgress?: (completed: number, total: number) => void;\n /**\n * Return the manifest as soon as shards are cached + announced to the\n * mesh, uploading to origin in the background. Lets a peer/worker start\n * pulling the file over P2P immediately instead of waiting out the full\n * origin upload. Requires an offline cache (browser); ignored without.\n */\n backgroundUpload?: boolean;\n } = {},\n ): Promise<{ manifest: FileManifest; stat: FileStat }> {\n const result = await this.fileStorage(opts.backgroundUpload)\n .writeFileToShards({ data: file, metadata, onProgress: opts.onProgress });\n // Declare this manifest's shards to the accelerator: attributes the stored\n // bytes to the owning app (so storage is never unmetered) and reference-\n // counts the shards for GC. Public shard hashes only — the per-chunk keys\n // stay inside the manifest, which the caller keeps in a vault/Space.\n await this.commitShards(result.manifest, \"commit\");\n return result;\n }\n\n async getFile(manifest: FileManifest): Promise<{ data: Uint8Array; stat: FileStat }> {\n return this.fileStorage().readFileFromShards(manifest);\n }\n\n /** Streaming read: async-iterate a stored file's decrypted chunks in order,\n * never holding the whole file in memory. Use for multi-GB files (a single\n * `Uint8Array` can't hold them) — e.g. a transcoder piping the raw to a temp\n * file. Same peer/origin shard sourcing as {@link getFile}. */\n getFileStream(manifest: FileManifest): AsyncGenerator<Uint8Array> {\n return this.fileStorage().readChunksFromShards(manifest);\n }\n\n /** Declare a file's shards (ref++ + meter) for a manifest already stored —\n * used to back-fill accounting for files written before commit existed, or to\n * register a manifest received via sharing. `putFile` already commits new\n * writes automatically; this is the explicit form. */\n async commitFile(manifest: FileManifest): Promise<void> {\n await this.commitShards(manifest, \"commit\");\n }\n\n /** Release a file's shards (ref--) when the owner deletes or unshares it. At\n * zero references a shard enters a retention window, then is GC'd. Idempotent-\n * ish: safe to call once per manifest the owner drops. */\n async releaseFile(manifest: FileManifest): Promise<void> {\n await this.commitShards(manifest, \"release\");\n }\n\n /** Commit/release a manifest's shards with the accelerator (metering + refcount). */\n private async commitShards(manifest: FileManifest, action: \"commit\" | \"release\"): Promise<void> {\n const hashes = manifest.chunks.flatMap((c) => c.shardHashes);\n if (hashes.length === 0) return;\n const body = JSON.stringify({ hashes, bytes: manifest.size });\n for (let attempt = 0; attempt < 3; attempt++) {\n try {\n const res = await this.deps.fetch(`${this.deps.httpBaseUrl}/api/storage/${action}`, {\n method: \"POST\", headers: { \"Content-Type\": \"application/json\" }, body,\n });\n if (res.ok) return;\n } catch { /* retry */ }\n await new Promise((r) => setTimeout(r, 400 * (attempt + 1)));\n }\n // Best-effort: a missed commit leaves the shards to orphan-GC (still not\n // durable-unmetered long-term); a missed release just delays GC. Reconciled\n // by the platform sweep. Don't fail the caller's write on a metering hiccup.\n console.warn(`[muhkoo] storage ${action} did not confirm for ${hashes.length} shard(s)`);\n }\n\n private fileStorage(backgroundUpload = false): 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 cache: this.deps.shardCache,\n deferUpload: this.deps.deferShardUpload,\n peers: this.peerNet?.exchange,\n backgroundUpload,\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 handle = Number(f.timestamp ?? 0);\n const decoded = await this.decodeFrame(f.spaceMessage as string, this.cipher, /*raw*/ true, handle);\n if (decoded) {\n this.emitEvent(\"message\", decoded); // UI first\n void this.cacheFrame(f.spaceMessage as string, decoded, \"msg\"); // cache off the hot path\n }\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) {\n this.emitEvent(\"message-edited\", decoded);\n void this.cacheFrame(e.spaceMessage, decoded, \"edit\");\n }\n }\n return;\n }\n if (f.deleteSpaceMessage && typeof f.deleteSpaceMessage === \"object\") {\n const d = f.deleteSpaceMessage as { ts?: number };\n const handle = Number(d.ts ?? 0);\n this.emitEvent(\"message-deleted\", { handle });\n if (this.deps.offline?.enabled) {\n // Cache the tombstone off the hot path.\n void this.deps.offline.putDeleted(this.id, handle).then(() =>\n this.deps.offline?.observeHandle(this.id, handle),\n );\n }\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({ force: true });\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, clientId?: 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 // Cleartext dedupe hint — lets the sender match its optimistic entry to\n // the server echo. Not part of the signed canonical form (it carries no\n // authority); worst case a stale hint just shows a transient duplicate.\n if (clientId) headers.cid = clientId;\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 skipVerify = false,\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`. Skipped only when\n // re-reading from the local cache (already verified before caching).\n if (!skipVerify && !(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 clientId: packet.headers?.cid as string | undefined,\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 /** Persist a decoded live/history/edit frame to the offline cache. */\n private async cacheFrame(packet: string, decoded: SpaceMessageEvent, op: \"msg\" | \"edit\"): Promise<void> {\n const offline = this.deps.offline;\n if (!offline?.enabled) return;\n // An incoming real message supersedes any optimistic pending entry.\n if (decoded.clientId) await offline.dropPending(this.id, decoded.clientId);\n await offline.putMessage(this.id, {\n handle: padSpaceHandle(decoded.handle),\n packet,\n op,\n clientId: decoded.clientId,\n });\n await offline.observeHandle(this.id, decoded.handle);\n }\n\n /**\n * Inbound reconciliation run on reconnect: page the server's forward delta\n * (`?since=<lastSeenHandle>`) to the head, pulling exactly the messages that\n * landed while we were offline into the cache. Bounded so a long absence\n * can't page forever. Falls back gracefully if the endpoint is unavailable.\n */\n private async catchUp(): Promise<void> {\n const offline = this.deps.offline;\n if (!offline?.enabled || !this.cipher) return;\n const cursor = await offline.getCursor(this.id);\n let since = String(cursor?.lastSeenHandle ?? 0);\n // Warm the member directory once so historical senders' signatures verify.\n await this.deps.keyring?.refreshDirectory({ force: true });\n for (let page = 0; page < 50; page++) {\n const url =\n `${this.deps.httpBaseUrl}/api/spaces/${encodeURIComponent(this.name)}/history` +\n `?since=${encodeURIComponent(since)}&limit=100`;\n const res = await this.deps.fetch(url);\n if (!res.ok) break;\n const body = (await res.json()) as { messages: string[]; nextCursor: string | null };\n for (const raw of body.messages ?? []) {\n const decoded = await this.decodeFrame(raw, this.cipher);\n if (!decoded) continue;\n try {\n const outer = JSON.parse(raw) as { spaceMessage?: string };\n if (typeof outer.spaceMessage === \"string\") {\n await this.cacheFrame(outer.spaceMessage, decoded, \"msg\");\n }\n } catch {\n /* unparseable row — skip */\n }\n }\n if (!body.nextCursor) break;\n since = body.nextCursor;\n }\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\n/**\n * Zero-pad a numeric server handle for use as a cache key, so string-ordered\n * keys sort in handle order. Must match the offline layer's `padHandle`.\n */\nfunction padSpaceHandle(handle: number): string {\n return String(Math.max(0, Math.floor(handle))).padStart(16, \"0\");\n}\n\n/** Cache key for an un-acked optimistic send. Must match the offline layer's\n * `provisionalHandle` (sorts after every real, zero-padded handle). */\nfunction provisionalSpaceKey(clientId: string): string {\n return `~local:${clientId}`;\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\";\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/** Staging-only keyring diagnostics (group-key cache hit/miss, persist, pulls). */\nconst KEYRING_DEBUG = (() => {\n try {\n return typeof location !== \"undefined\" && /(^|\\.)staging\\./.test(location.hostname);\n } catch {\n return false;\n }\n})();\nfunction klog(msg: string): void {\n if (KEYRING_DEBUG) console.info(`[muhkoo:keyring] ${msg}`);\n}\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 /** Coalesce concurrent roster refreshes (the parallel history/backlog decode\n * would otherwise fire one `roster` fetch PER message — a thundering herd). */\n private dirInFlight: Promise<void> | null = null;\n private dirRefreshedAt = 0;\n /** Min gap between non-forced roster refreshes. A miss that persists within\n * this window won't re-fetch (the roster hasn't changed that fast); genuine\n * membership changes use `{ force: true }` (join requests / history loads). */\n private static readonly DIR_COOLDOWN_MS = 5000;\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 /**\n * Refresh the member directory (memberId → ECDSA key) from the roster.\n * Coalesces concurrent callers into ONE fetch, and skips a fetch when one\n * completed within {@link DIR_COOLDOWN_MS} (unless `force`). Without this, a\n * page of N messages decoded in parallel — each missing the cold directory —\n * fires N simultaneous `roster` requests that queue behind the browser's\n * connection limit and take many seconds.\n */\n async refreshDirectory(opts?: { force?: boolean }): Promise<void> {\n if (this.dirInFlight) return this.dirInFlight; // a refresh is already running\n if (!opts?.force && Date.now() - this.dirRefreshedAt < SpaceKeyring.DIR_COOLDOWN_MS) {\n return; // refreshed very recently — the roster won't have changed\n }\n this.dirInFlight = this.doRefreshDirectory().finally(() => {\n this.dirRefreshedAt = Date.now();\n this.dirInFlight = null;\n });\n return this.dirInFlight;\n }\n\n private async doRefreshDirectory(): 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 // The cache entries are ECIES-wrapped to our identity key, so we unwrap\n // with the keyring's OWN private key — available whenever chat works,\n // unlike client.kv's StorageCipher which needs the full unlocked identity.\n const priv = this.deps.ownPrivateKey();\n if (!priv) {\n klog(\"loadFromCache: no private key available yet\");\n return false;\n }\n let cached: Record<string, string> | null;\n try {\n cached = await this.deps.cache.loadKeys(this.deps.spaceId);\n } catch (e) {\n klog(`loadFromCache: ERROR reading cache — ${e instanceof Error ? e.message : e}`);\n return false;\n }\n if (!cached) {\n klog(\"loadFromCache: cache empty\");\n return false;\n }\n for (const [epochStr, serialized] of Object.entries(cached)) {\n try {\n const blob = JSON.parse(serialized) as WrappedKey;\n this.keys.set(Number(epochStr), await unwrapSpaceKey(blob, priv));\n } catch {\n /* stale / old-format entry — skip; we'll re-admit and re-persist */\n }\n }\n if (this.keys.size === 0) {\n klog(\"loadFromCache: no usable entries (stale format → will re-admit)\");\n return false;\n }\n this.epoch = Math.max(0, ...Array.from(this.keys.keys()));\n klog(`loadFromCache: HIT ${this.keys.size} epoch(s), current=${this.epoch}`);\n return true;\n }\n\n private async persist(): Promise<void> {\n if (!this.deps.cache || this.keys.size === 0) return;\n // Best-effort: caching is an optimization; a write failure must not break\n // key acquisition.\n try {\n // Wrap each epoch key to our OWN identity key (ECIES-to-self). The\n // cache stays server-blind (the kv layer stores it with encrypt:false\n // — it's already encrypted) AND readable with the keyring private key\n // alone, so it works while the full identity is locked (post-reload).\n const selfPub = await importEcdhPublicKey(this.deps.identityEcdhPub);\n const out: Record<string, string> = {};\n for (const [epoch, key] of this.keys) {\n out[String(epoch)] = JSON.stringify(await wrapSpaceKey(key, epoch, selfPub));\n }\n await this.deps.cache.saveKeys(this.deps.spaceId, out);\n klog(`persist: saved ${Object.keys(out).length} epoch(s)`);\n } catch (e) {\n klog(`persist: FAILED — ${e instanceof Error ? e.message : e}`);\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 klog(`pullKeys: +${added} epoch(s) (now hold ${this.keys.size}, current=${this.epoch})`);\n return added;\n }\n\n /**\n * Background freshness check for the cache-hit fast path: confirm we hold the\n * current epoch (picks up a rotation / our removal) WITHOUT the full newcomer\n * admit handshake. Cheap + idempotent; never blocks first paint. Returns the\n * number of newly-obtained epoch keys (0 = already current).\n */\n async reconcile(): Promise<number> {\n await this.refreshDirectory({ force: true });\n try {\n return await this.pullKeys();\n } catch {\n return 0; // best-effort — the live keyringReady frame is the backstop\n }\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 * Message-log helpers — the conflict model for a Space's message history.\n *\n * Messages are the easy CRDT: the accelerator assigns every persisted message a\n * monotonic, zero-padded `handle` that already totally-orders the log, and the\n * sealed body is immutable. So the \"log\" is just a grow-only set keyed by\n * `handle`, and convergence is structural — no server change needed.\n *\n * The only subtleties this module encodes:\n * - **Optimistic sends** have no server handle yet. We key them by a\n * provisional handle that sorts *after* every real one, and tag them with\n * the sender's `clientId` so the real frame (carrying the same `clientId`)\n * can replace the placeholder instead of duplicating it.\n * - **Edits** are a per-message LWW register on the body (greater HLC wins).\n * - **Deletes** are a tombstone at the message's handle.\n */\n\nexport type MessageOp = \"msg\" | \"edit\" | \"delete\";\n\nexport interface MessageEntry {\n /** Server-assigned handle, or a {@link provisionalHandle} while pending. */\n handle: string;\n /** Sealed packet string (ciphertext at rest); `null` for a delete tombstone. */\n packet: string | null;\n op: MessageOp;\n /** Sender-generated id, present on locally-originated sends for dedupe. */\n clientId?: string;\n /** HLC stamp — orders edits to the same message. */\n hlc?: string;\n /** True while an optimistic send has not yet been acked by the server. */\n pending?: boolean;\n deleted?: boolean;\n}\n\n/** IndexedDB key for a message within a space. */\nexport function messageKey(spaceId: string, handle: string): string {\n return `${spaceId}|${handle}`;\n}\n\n/**\n * A handle for an un-acked optimistic message. Prefixed with `\"~\"` (0x7E),\n * which sorts after every digit, so pending sends always appear at the tail of\n * the handle-ordered log until the real handle arrives.\n */\nexport function provisionalHandle(clientId: string): string {\n return `~local:${clientId}`;\n}\n\nexport function isProvisional(handle: string): boolean {\n return handle.startsWith(\"~local:\");\n}\n\n/**\n * Merge two entries for the SAME handle. A delete always wins (tombstone); an\n * edit wins over the entry it supersedes when its HLC is greater; otherwise the\n * existing entry stands (a re-delivered `msg` is idempotent).\n */\nexport function mergeMessage(local: MessageEntry | null, incoming: MessageEntry): MessageEntry {\n if (!local) return incoming;\n if (incoming.op === \"delete\" || local.deleted) {\n return { ...local, op: \"delete\", packet: null, deleted: true };\n }\n if (incoming.op === \"edit\") {\n if (!local.hlc || (incoming.hlc && incoming.hlc > local.hlc)) {\n return { ...local, packet: incoming.packet, hlc: incoming.hlc, op: \"edit\" };\n }\n return local;\n }\n // incoming.op === \"msg\": keep the already-stored (de-pending) entry.\n return { ...local, pending: false };\n}\n","/**\n * `SpaceCache` — the offline adapter a {@link ../spaces/Space} talks to. It\n * persists sealed message frames (ciphertext at rest), tracks per-space sync\n * cursors, and records offline sends in the durable queue. Kept as its own\n * object (rather than wiring the Space straight to the store + clock) so the\n * Space stays decoupled from IndexedDB and so the no-op path is a single\n * `enabled` check.\n *\n * Messages are the structural CRDT (see {@link ./crdt/MessageLog}): the server\n * assigns a monotonic `handle` that totally-orders the log, so the cache just\n * stores frames keyed by a zero-padded handle (real) or a provisional key\n * (pending sends, which sort to the tail until their echo arrives).\n */\n\nimport {\n messageKey,\n provisionalHandle,\n type MessageEntry,\n type MessageOp,\n} from \"./crdt/MessageLog\";\nimport type { OfflineManager } from \"./OfflineManager\";\nimport type { OfflineStore } from \"./store/OfflineStore\";\n\n/** Zero-pad a numeric server handle so string keys sort in handle order. */\nexport function padHandle(handle: number): string {\n return String(Math.max(0, Math.floor(handle))).padStart(16, \"0\");\n}\n\nexport interface SpaceCursor {\n lastSeenHandle: number;\n oldestHandle: number;\n fullyBackfilled: boolean;\n}\n\n/**\n * The surface a {@link ../spaces/Space} uses. Declared structurally on the\n * Space side too (as `SpaceOfflineAdapter`) so the spaces module never imports\n * the offline module.\n */\nexport class SpaceCache {\n private readonly store: OfflineStore;\n\n constructor(private readonly manager: OfflineManager) {\n this.store = manager.store;\n }\n\n get enabled(): boolean {\n return this.manager.enabled;\n }\n\n newClientId(): string {\n return this.manager.newClientId();\n }\n\n nextHlc(): Promise<string> {\n return this.manager.nextHlc();\n }\n\n /** Persist a sealed message frame keyed by its (real or provisional) handle. */\n async putMessage(spaceId: string, entry: MessageEntry): Promise<void> {\n await this.store.put(\"space-messages\", messageKey(spaceId, entry.handle), entry);\n }\n\n /** Tombstone the message at `handle`. */\n async putDeleted(spaceId: string, handle: number): Promise<void> {\n const key = messageKey(spaceId, padHandle(handle));\n const existing = await this.store.get<MessageEntry>(\"space-messages\", key);\n await this.store.put(\"space-messages\", key, {\n handle: padHandle(handle),\n packet: null,\n op: \"delete\" as MessageOp,\n deleted: true,\n clientId: existing?.clientId,\n });\n }\n\n /** Drop a pending (optimistic) entry once its real echo has been stored. */\n async dropPending(spaceId: string, clientId: string): Promise<void> {\n await this.store.delete(\"space-messages\", messageKey(spaceId, provisionalHandle(clientId)));\n }\n\n /** All cached frames for a space, in handle order (pending ones last). */\n async loadMessages(spaceId: string): Promise<MessageEntry[]> {\n const rows = await this.store.range<MessageEntry>(\n \"space-messages\",\n `${spaceId}|`,\n `${spaceId}|`,\n );\n return rows.map((r) => r.value);\n }\n\n async getCursor(spaceId: string): Promise<SpaceCursor | null> {\n return this.store.get<SpaceCursor>(\"space-cursors\", spaceId);\n }\n\n /** Advance the last-seen handle (monotonic) and track the oldest fetched. */\n async observeHandle(spaceId: string, handle: number): Promise<void> {\n if (!handle) return;\n const cur = (await this.getCursor(spaceId)) ?? {\n lastSeenHandle: 0,\n oldestHandle: handle,\n fullyBackfilled: false,\n };\n const next: SpaceCursor = {\n lastSeenHandle: Math.max(cur.lastSeenHandle, handle),\n oldestHandle: cur.oldestHandle ? Math.min(cur.oldestHandle, handle) : handle,\n fullyBackfilled: cur.fullyBackfilled,\n };\n await this.store.put(\"space-cursors\", spaceId, next);\n }\n\n /** Queue a raw space frame for replay when the connection returns. */\n async enqueueFrame(spaceId: string, frame: unknown, clientId: string, hlc: string): Promise<void> {\n await this.manager.enqueue({\n hlc,\n clientId,\n domain: \"space\",\n method: \"sendRaw\",\n args: { spaceId, frame },\n });\n }\n\n /** Register an inbound catch-up task (forward/back history paging). */\n registerCatchUp(task: () => Promise<void>): () => void {\n return this.manager.registerCatchUp(task);\n }\n}\n\nexport default SpaceCache;\n","/**\n * `ShardCache` — a Cache-API-backed store for file-shard bytes. Shards are\n * content-addressed (the key IS the SHA-256 of the ciphertext), so caching them\n * is uniquely safe: a cache hit is self-validating, immutable, and shareable\n * across files. The Cache API (rather than IndexedDB) is the right home for\n * large binary blobs — it streams, it's purpose-built for response bodies, and\n * it has its own eviction.\n *\n * Keys are SYNTHETIC absolute URLs (`https://shard.muhkoo.local/<hash>`) rather\n * than the real shard endpoint, so the cache is addressable by hash alone — the\n * sync engine can re-PUT a deferred shard knowing only its hash, without\n * reconstructing the accelerator URL. We never fetch these synthetic URLs; they\n * exist only as cache keys.\n *\n * Every method degrades to a no-op / null where the Cache API is unavailable\n * (Node, Workers, insecure contexts), so callers don't need to branch.\n */\n\nconst CACHE_NAME = \"muhkoo-shards-v1\";\n\nexport class ShardCache {\n static available(): boolean {\n try {\n return typeof caches !== \"undefined\";\n } catch {\n return false;\n }\n }\n\n private key(hash: string): string {\n return `https://shard.muhkoo.local/${encodeURIComponent(hash)}`;\n }\n\n private open(): Promise<Cache> {\n return caches.open(CACHE_NAME);\n }\n\n /** Cached shard bytes, or `null` on miss / when unavailable. */\n async get(hash: string): Promise<Uint8Array | null> {\n if (!ShardCache.available()) return null;\n try {\n const cache = await this.open();\n const res = await cache.match(this.key(hash));\n if (!res) return null;\n return new Uint8Array(await res.arrayBuffer());\n } catch {\n return null;\n }\n }\n\n /** Store shard bytes under their hash. Best-effort. */\n async put(hash: string, bytes: Uint8Array): Promise<void> {\n if (!ShardCache.available()) return;\n try {\n const cache = await this.open();\n await cache.put(\n this.key(hash),\n new Response(bytes as BodyInit, {\n headers: { \"content-type\": \"application/octet-stream\" },\n }),\n );\n } catch {\n /* quota / unavailable — degrade to online-only for this shard */\n }\n }\n\n /** Whether a shard is present in the cache. */\n async has(hash: string): Promise<boolean> {\n if (!ShardCache.available()) return false;\n try {\n const cache = await this.open();\n return Boolean(await cache.match(this.key(hash)));\n } catch {\n return false;\n }\n }\n}\n\nexport default ShardCache;\n","/**\n * `PeerExchange` — the thin façade the storage layer consults to try fetching a\n * block from peers before falling back to origin. It satisfies the structural\n * `PeerBlockSource` interface that {@link ../storage/transport/ShardClient}\n * declares (so storage never imports the p2p module — the dependency arrow stays\n * one-way, p2p → storage).\n *\n * It delegates to an {@link EngineHandle} — either an in-process {@link\n * ./worker/blockEngine.BlockEngine} or the Web Worker proxy — so the same façade\n * works whether the block engine runs on the main thread or off it.\n */\n\nimport type { PeerBlockSource } from \"../storage/transport/ShardClient\";\n\n/** The subset of a block engine (in-process or worker-proxied) PeerExchange drives. */\nexport interface EngineHandle {\n want(hash: string, timeoutMs: number): Promise<Uint8Array | null>;\n announce(hash: string): void;\n}\n\nexport interface PeerExchangeOptions {\n /** How long to wait for a peer before giving up to origin. Default 2500ms. */\n timeoutMs?: number;\n /** Log peer-served vs origin-fallback per block to the console. */\n debug?: boolean;\n}\n\nexport class PeerExchange implements PeerBlockSource {\n private readonly timeoutMs: number;\n private readonly debug: boolean;\n\n constructor(private readonly engine: EngineHandle, opts: PeerExchangeOptions = {}) {\n this.timeoutMs = opts.timeoutMs ?? 2500;\n this.debug = opts.debug ?? false;\n }\n\n async getBlock(hash: string, opts?: { timeoutMs?: number }): Promise<Uint8Array | null> {\n const bytes = await this.engine.want(hash, opts?.timeoutMs ?? this.timeoutMs);\n if (this.debug) {\n console.info(\n `%c[muhkoo:p2p] ${bytes ? \"✓ peer-served\" : \"✗ miss → origin\"} shard ${hash.slice(0, 10)}…`,\n `color:${bytes ? \"#58da7d\" : \"#888\"}`,\n );\n }\n return bytes;\n }\n\n announce(hash: string): void {\n if (this.debug) console.info(`[muhkoo:p2p] announce shard ${hash.slice(0, 10)}…`);\n this.engine.announce(hash);\n }\n}\n\nexport default PeerExchange;\n","/**\n * `SpaceSignaler` — WebRTC signaling carried over the Space's existing ephemeral\n * relay. No new server channel: `Space.sendEphemeral`/`onEphemeral` already\n * blind-relay `pub` frames stamped with the authenticated sender, so SDP\n * offers/answers and ICE candidates ride a reserved subject (`__p2p__`) scoped\n * to Space membership. The sender (`from`) is server-stamped and can't be\n * spoofed; the payload is opaque to the server.\n *\n * Peers are identified by a unique **peer id** (per device/connection), carried\n * in the envelope's `from`/`to` — NOT by the server-stamped member id. This is\n * essential: one user's own devices share a member id, so the server's `from`\n * can't tell them apart (and would make each treat the others' signals as its\n * own echo). We therefore route entirely on the envelope peer ids and broadcast\n * to the whole Space, filtering client-side. The server `from` still guarantees\n * the sender is an authenticated Space member.\n */\n\nexport const P2P_SUBJECT = \"__p2p__\";\n\nexport type SignalKind = \"hello\" | \"bye\" | \"offer\" | \"answer\" | \"ice\";\n\nexport interface SignalEnvelope {\n /** Sender's unique PEER id (per device/connection). */\n from: string;\n /** Target peer id, or `\"*\"` to broadcast (discovery / departure). */\n to: string;\n kind: SignalKind;\n data?: unknown;\n}\n\n/** The slice of {@link ../../spaces/Space.Space} the signaler needs. */\nexport interface SignalingSpace {\n sendEphemeral(subject: string, data: unknown, to?: string): void;\n onEphemeral(handler: (e: { from: string; subject: string; data: unknown }) => void): () => void;\n}\n\nexport class SpaceSignaler {\n constructor(\n private readonly space: SignalingSpace,\n private readonly myId: string,\n ) {}\n\n /** Send a signal to one peer (or `\"*\"`). */\n send(to: string, kind: SignalKind, data?: unknown): void {\n const env: SignalEnvelope = { from: this.myId, to, kind, data };\n // Always broadcast to the Space: the server can't unicast to a specific\n // DEVICE (a user's devices share a member id), so we route client-side on\n // the envelope peer id. Signaling frames are tiny.\n this.space.sendEphemeral(P2P_SUBJECT, env);\n }\n\n /** Announce/withdraw P2P availability to all Space members. */\n broadcast(kind: SignalKind, data?: unknown): void {\n this.send(\"*\", kind, data);\n }\n\n /**\n * Subscribe to inbound signals addressed to us (or broadcast). Skips our own\n * echoes. Returns an unsubscribe function. Routing is entirely by the envelope\n * peer id (`env.from`/`env.to`), so a user's own devices — which share the\n * server-stamped `e.from` — are correctly distinguished.\n */\n onSignal(cb: (from: string, kind: SignalKind, data: unknown) => void): () => void {\n return this.space.onEphemeral((e) => {\n if (e.subject !== P2P_SUBJECT) return;\n const env = e.data as SignalEnvelope | undefined;\n if (!env || typeof env.kind !== \"string\" || typeof env.from !== \"string\") return;\n if (env.from === this.myId) return; // our own device's echo\n if (env.to !== this.myId && env.to !== \"*\") return;\n cb(env.from, env.kind, env.data);\n });\n }\n}\n\nexport default SpaceSignaler;\n","/**\n * `WebRtcTransport` — a {@link ./PeerTransport.PeerTransport} over RTCDataChannels,\n * signaled by {@link ../signaling/SpaceSignaler}. Runs on the **main thread**\n * (`RTCPeerConnection` is Window-only — not available in Workers), so the block\n * engine lives in a Worker and this only shuttles bytes.\n *\n * Connection setup uses a deterministic initiator (the peer with the smaller id\n * dials) to avoid offer/answer glare. STUN handles NAT traversal; there is no\n * TURN — an unreachable peer simply never connects and the caller falls back to\n * origin (P2P is best-effort).\n *\n * Frames (up to a 4 MiB shard) exceed an RTCDataChannel's max message size, so\n * each frame is fragmented into `CHUNK`-sized pieces with a 12-byte header\n * `[msgId u32][index u32][total u32]` and reassembled per peer.\n */\n\nimport type { PeerId, PeerTransport } from \"./PeerTransport\";\nimport type { SpaceSignaler, SignalKind } from \"../signaling/SpaceSignaler\";\n\nconst CHUNK = 16 * 1024;\n// [msgId u32][index u32][total u32][channel u32]\nconst HEADER = 16;\n/** Pause sends when a channel has this many bytes buffered (backpressure). */\nconst MAX_BUFFERED = 4 * 1024 * 1024;\n\nconst DEFAULT_ICE: RTCIceServer[] = [{ urls: \"stun:stun.cloudflare.com:3478\" }];\n\ninterface Reassembly {\n chunks: Array<Uint8Array | undefined>;\n received: number;\n total: number;\n size: number;\n channel: number;\n}\n\ninterface PeerConn {\n pc: RTCPeerConnection;\n dc?: RTCDataChannel;\n reasm: Map<number, Reassembly>;\n /** Has setRemoteDescription completed? ICE can't be added before it. */\n remoteSet: boolean;\n /** ICE candidates that arrived before SRD — flushed once remoteSet. */\n pendingIce: RTCIceCandidateInit[];\n}\n\nexport interface WebRtcTransportOptions {\n iceServers?: RTCIceServer[];\n /** Cap on simultaneous peer connections (mesh size). Default 8. */\n maxPeers?: number;\n /** Log ICE/connection state transitions for diagnosing peer connectivity. */\n debug?: boolean;\n}\n\nexport class WebRtcTransport implements PeerTransport {\n private readonly conns = new Map<PeerId, PeerConn>();\n private readonly msgCbs = new Set<(peer: PeerId, data: Uint8Array, channel: number) => void>();\n private readonly peerCbs = new Set<(peers: PeerId[]) => void>();\n private readonly offSignal: () => void;\n private readonly iceServers: RTCIceServer[];\n private readonly maxPeers: number;\n private readonly debug: boolean;\n private nextMsgId = 1;\n\n constructor(\n private readonly signaler: SpaceSignaler,\n private readonly myId: PeerId,\n opts: WebRtcTransportOptions = {},\n ) {\n this.iceServers = opts.iceServers ?? DEFAULT_ICE;\n this.maxPeers = opts.maxPeers ?? 8;\n this.debug = opts.debug ?? false;\n this.offSignal = this.signaler.onSignal((from, kind, data) => this.onSignal(from, kind, data));\n }\n\n private log(...a: unknown[]): void {\n if (this.debug) console.info(\"[muhkoo:p2p]\", ...a);\n }\n\n peers(): PeerId[] {\n return [...this.conns].filter(([, c]) => c.dc?.readyState === \"open\").map(([id]) => id);\n }\n\n /** Dial a peer (no-op unless we're the deterministic initiator for the pair). */\n connectTo(peerId: PeerId): void {\n if (peerId === this.myId || this.conns.has(peerId)) return;\n if (this.conns.size >= this.maxPeers) return; // mesh cap\n if (this.myId < peerId) void this.initiate(peerId); // smaller id dials\n }\n\n send(peer: PeerId, data: Uint8Array, channel = 0): void {\n const dc = this.conns.get(peer)?.dc;\n if (dc?.readyState === \"open\") void this.sendFragmented(dc, data, channel);\n }\n\n broadcast(data: Uint8Array, channel = 0): void {\n for (const [, c] of this.conns) {\n if (c.dc?.readyState === \"open\") void this.sendFragmented(c.dc, data, channel);\n }\n }\n\n onMessage(cb: (peer: PeerId, data: Uint8Array, channel: number) => void): () => void {\n this.msgCbs.add(cb);\n return () => this.msgCbs.delete(cb);\n }\n\n onPeerChange(cb: (peers: PeerId[]) => void): () => void {\n this.peerCbs.add(cb);\n return () => this.peerCbs.delete(cb);\n }\n\n close(): void {\n this.offSignal();\n for (const [, c] of this.conns) {\n try { c.dc?.close(); } catch { /* already closing */ }\n try { c.pc.close(); } catch { /* already closing */ }\n }\n this.conns.clear();\n this.msgCbs.clear();\n this.peerCbs.clear();\n }\n\n // -- internals -----------------------------------------------------------\n\n private newPc(peerId: PeerId): PeerConn {\n const pc = new RTCPeerConnection({ iceServers: this.iceServers });\n const conn: PeerConn = { pc, reasm: new Map(), remoteSet: false, pendingIce: [] };\n this.conns.set(peerId, conn);\n const short = String(peerId).slice(0, 8);\n pc.onicecandidate = (e) => {\n if (e.candidate) {\n this.log(`${short} local candidate ${e.candidate.type ?? \"?\"} ${(e.candidate.address ?? e.candidate.candidate).toString().slice(0, 40)}`);\n this.signaler.send(peerId, \"ice\", e.candidate.toJSON());\n }\n };\n pc.onconnectionstatechange = () => {\n this.log(`${short} connection=${pc.connectionState}`);\n if ([\"failed\", \"closed\", \"disconnected\"].includes(pc.connectionState)) this.drop(peerId);\n };\n if (this.debug) {\n pc.oniceconnectionstatechange = () => this.log(`${short} ice=${pc.iceConnectionState}`);\n pc.onicegatheringstatechange = () => this.log(`${short} gathering=${pc.iceGatheringState}`);\n }\n pc.ondatachannel = (e) => this.bindChannel(peerId, conn, e.channel);\n return conn;\n }\n\n /** Mark a peer's remote description as set and apply any ICE candidates that\n * arrived before it (dropping them, the old behavior, breaks LAN dials). */\n private async markRemoteSet(conn: PeerConn): Promise<void> {\n conn.remoteSet = true;\n const pending = conn.pendingIce;\n conn.pendingIce = [];\n for (const cand of pending) {\n try { await conn.pc.addIceCandidate(cand); } catch { /* stale/duplicate */ }\n }\n if (pending.length) this.log(`flushed ${pending.length} queued ICE candidate(s)`);\n }\n\n private async initiate(peerId: PeerId): Promise<void> {\n const conn = this.newPc(peerId);\n const dc = conn.pc.createDataChannel(\"blocks\");\n this.bindChannel(peerId, conn, dc);\n const offer = await conn.pc.createOffer();\n await conn.pc.setLocalDescription(offer);\n this.signaler.send(peerId, \"offer\", offer);\n }\n\n private bindChannel(peerId: PeerId, conn: PeerConn, dc: RTCDataChannel): void {\n dc.binaryType = \"arraybuffer\";\n conn.dc = dc;\n dc.onopen = () => this.firePeerChange();\n dc.onclose = () => this.drop(peerId);\n dc.onmessage = (e) => this.onChunk(peerId, conn, new Uint8Array(e.data as ArrayBuffer));\n }\n\n private async onSignal(from: PeerId, kind: SignalKind, data: unknown): Promise<void> {\n if (kind === \"offer\") {\n if (!this.conns.has(from) && this.conns.size >= this.maxPeers) return; // mesh cap\n const conn = this.conns.get(from) ?? this.newPc(from);\n await conn.pc.setRemoteDescription(data as RTCSessionDescriptionInit);\n await this.markRemoteSet(conn);\n const answer = await conn.pc.createAnswer();\n await conn.pc.setLocalDescription(answer);\n this.signaler.send(from, \"answer\", answer);\n } else if (kind === \"answer\") {\n const conn = this.conns.get(from);\n if (conn) {\n await conn.pc.setRemoteDescription(data as RTCSessionDescriptionInit);\n await this.markRemoteSet(conn);\n }\n } else if (kind === \"ice\") {\n const conn = this.conns.get(from);\n if (conn && data) {\n // Queue candidates that arrive before setRemoteDescription — adding\n // them early throws and (previously) dropped them, which killed the\n // connection on fast LANs where ICE beats the SDP answer.\n if (!conn.remoteSet) { conn.pendingIce.push(data as RTCIceCandidateInit); return; }\n try { await conn.pc.addIceCandidate(data as RTCIceCandidateInit); } catch { /* stale */ }\n }\n } else if (kind === \"bye\") {\n this.drop(from);\n }\n }\n\n private drop(peerId: PeerId): void {\n const conn = this.conns.get(peerId);\n if (!conn) return;\n this.conns.delete(peerId);\n try { conn.dc?.close(); } catch { /* already closing */ }\n try { conn.pc.close(); } catch { /* already closing */ }\n this.firePeerChange();\n }\n\n private firePeerChange(): void {\n const peers = this.peers();\n for (const cb of this.peerCbs) cb(peers);\n }\n\n // -- fragmentation -------------------------------------------------------\n\n private async sendFragmented(dc: RTCDataChannel, data: Uint8Array, channel: number): Promise<void> {\n const msgId = this.nextMsgId++ >>> 0;\n const total = Math.max(1, Math.ceil(data.length / CHUNK));\n for (let i = 0; i < total; i++) {\n const slice = data.subarray(i * CHUNK, (i + 1) * CHUNK);\n const frame = new Uint8Array(HEADER + slice.length);\n const dv = new DataView(frame.buffer);\n dv.setUint32(0, msgId);\n dv.setUint32(4, i);\n dv.setUint32(8, total);\n dv.setUint32(12, channel);\n frame.set(slice, HEADER);\n if (dc.bufferedAmount > MAX_BUFFERED) await this.drain(dc);\n dc.send(frame);\n }\n }\n\n private drain(dc: RTCDataChannel): Promise<void> {\n return new Promise((resolve) => {\n dc.bufferedAmountLowThreshold = MAX_BUFFERED / 2;\n const onLow = () => { dc.removeEventListener(\"bufferedamountlow\", onLow); resolve(); };\n dc.addEventListener(\"bufferedamountlow\", onLow);\n });\n }\n\n private onChunk(peerId: PeerId, conn: PeerConn, frame: Uint8Array): void {\n if (frame.length < HEADER) return;\n const dv = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);\n const msgId = dv.getUint32(0);\n const index = dv.getUint32(4);\n const total = dv.getUint32(8);\n const channel = dv.getUint32(12);\n const chunk = frame.slice(HEADER);\n\n let r = conn.reasm.get(msgId);\n if (!r) {\n r = { chunks: new Array(total), received: 0, total, size: 0, channel };\n conn.reasm.set(msgId, r);\n }\n if (r.chunks[index]) return; // dup\n r.chunks[index] = chunk;\n r.received++;\n r.size += chunk.length;\n if (r.received < r.total) return;\n\n conn.reasm.delete(msgId);\n const out = new Uint8Array(r.size);\n let off = 0;\n for (const c of r.chunks) {\n if (!c) return; // gap — shouldn't happen on reliable ordered\n out.set(c, off);\n off += c.length;\n }\n for (const cb of this.msgCbs) cb(peerId, out, r.channel);\n }\n}\n\nexport default WebRtcTransport;\n","/**\n * `PeerTransport` — the pluggable wire under the block engine. It moves opaque\n * frames between Space peers; it knows nothing about blocks, hashes, or the\n * protocol. {@link ./WebRtcTransport} implements it over RTCDataChannels today;\n * a future libp2p/Helia transport can implement the same interface without the\n * block engine or `ShardClient` changing.\n *\n * Implementations are responsible for fragmenting/ reassembling frames larger\n * than the underlying channel's max message size (a 4 MiB shard won't fit in one\n * `RTCDataChannel.send`); the engine always deals in whole frames.\n */\n\nexport type PeerId = string;\n\n/**\n * Logical channels multiplexed over the one data link. `0` is block exchange\n * (the engine), `1` is gossip (app/CRDT data). The tag rides the framing header\n * so payloads aren't copied to prepend it.\n */\nexport const CHANNEL_BLOCK = 0;\nexport const CHANNEL_GOSSIP = 1;\n\nexport interface PeerTransport {\n /** Currently connected peer ids. */\n peers(): PeerId[];\n /** Dial a discovered peer (optional — some transports connect implicitly). */\n connectTo?(peer: PeerId): void;\n /** Send a whole frame to one peer on `channel` (fragmented internally if needed). */\n send(peer: PeerId, data: Uint8Array, channel?: number): void;\n /** Send a whole frame to every connected peer on `channel`. */\n broadcast(data: Uint8Array, channel?: number): void;\n /** Subscribe to inbound (reassembled) frames. Returns an unsubscribe fn. */\n onMessage(cb: (peer: PeerId, data: Uint8Array, channel: number) => void): () => void;\n /** Subscribe to the connected-peer set changing. Returns an unsubscribe fn. */\n onPeerChange(cb: (peers: PeerId[]) => void): () => void;\n /** Tear down all connections. */\n close(): void;\n}\n","/**\n * Bitswap-lite wire protocol for peer block exchange. Four frame types over a\n * {@link ../transport/PeerTransport} data channel:\n *\n * WANT(hash) — \"does anyone have this block?\" / \"send it to me\"\n * HAVE(hash) — \"I hold this block\" (announce / reply to a WANT)\n * BLOCK(hash, bytes) — the block itself (verified by hash on receipt)\n * CANCEL(hash) — \"stop, I got it elsewhere\"\n *\n * Frames are compact binary so a 4 MiB shard isn't base64-bloated through JSON:\n *\n * byte 0 : type (0 WANT | 1 HAVE | 2 BLOCK | 3 CANCEL)\n * bytes 1..33 : 32-byte raw SHA-256 of the block (our shard hash, hex-decoded)\n * bytes 33.. : payload (BLOCK only)\n *\n * Blocks are AES-GCM ciphertext, so a frame carries nothing readable; the hash\n * is the capability check (the receiver re-hashes the payload and drops a\n * mismatch). See {@link ./blockEngine}.\n */\n\nexport enum FrameType {\n WANT = 0,\n HAVE = 1,\n BLOCK = 2,\n CANCEL = 3,\n}\n\nexport interface DecodedFrame {\n type: FrameType;\n /** Lowercase hex SHA-256 (matches `shardHash`). */\n hash: string;\n /** Present only for {@link FrameType.BLOCK}. */\n payload?: Uint8Array;\n}\n\nconst HASH_BYTES = 32;\nconst HEADER = 1 + HASH_BYTES; // type + hash\n\nfunction hexToBytes(hex: string): Uint8Array {\n if (hex.length !== HASH_BYTES * 2) {\n throw new Error(`protocol: expected a ${HASH_BYTES}-byte hex hash, got ${hex.length / 2} bytes`);\n }\n const out = new Uint8Array(HASH_BYTES);\n for (let i = 0; i < HASH_BYTES; i++) out[i] = parseInt(hex.substr(i * 2, 2), 16);\n return out;\n}\n\nconst HEX = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, \"0\"));\nfunction bytesToHex(bytes: Uint8Array): string {\n let s = \"\";\n for (let i = 0; i < bytes.length; i++) s += HEX[bytes[i]];\n return s;\n}\n\nfunction header(type: FrameType, hash: string, extra = 0): { buf: Uint8Array; offset: number } {\n const buf = new Uint8Array(HEADER + extra);\n buf[0] = type;\n buf.set(hexToBytes(hash), 1);\n return { buf, offset: HEADER };\n}\n\nexport function encodeWant(hash: string): Uint8Array {\n return header(FrameType.WANT, hash).buf;\n}\n\nexport function encodeHave(hash: string): Uint8Array {\n return header(FrameType.HAVE, hash).buf;\n}\n\nexport function encodeCancel(hash: string): Uint8Array {\n return header(FrameType.CANCEL, hash).buf;\n}\n\nexport function encodeBlock(hash: string, payload: Uint8Array): Uint8Array {\n const { buf, offset } = header(FrameType.BLOCK, hash, payload.length);\n buf.set(payload, offset);\n return buf;\n}\n\nexport function decode(frame: Uint8Array): DecodedFrame {\n if (frame.length < HEADER) throw new Error(\"protocol: frame too short\");\n const type = frame[0] as FrameType;\n const hash = bytesToHex(frame.subarray(1, HEADER));\n if (type === FrameType.BLOCK) {\n // Copy the payload out so it doesn't alias a transferred/pooled buffer.\n return { type, hash, payload: frame.slice(HEADER) };\n }\n return { type, hash };\n}\n","/**\n * `BlockEngine` — the bitswap-lite want/have ledger. Host-agnostic: it speaks\n * only to a {@link BlockStore} (get/put/has) and an `out` sink that ships\n * encoded frames to a peer (or `\"*\"` to broadcast). The host wires `out` and\n * `handleFrame` to a real transport — on the main thread or inside the Web\n * Worker (see {@link ./engineClient}) — so this class is pure and unit-testable.\n *\n * It never sees keys: blocks are AES-GCM ciphertext, addressed by SHA-256. The\n * one trust check is integrity — an inbound BLOCK is re-hashed and dropped on\n * mismatch, so a malicious peer can't poison the store (the requester just\n * falls back to origin).\n */\n\nimport {\n FrameType,\n decode,\n encodeWant,\n encodeHave,\n encodeBlock,\n encodeCancel,\n} from \"./protocol\";\n\nexport interface BlockStore {\n get(hash: string): Promise<Uint8Array | null>;\n put(hash: string, bytes: Uint8Array): Promise<void>;\n has(hash: string): Promise<boolean>;\n}\n\n/** Ship an encoded frame to one peer, or `\"*\"` for every connected peer. */\nexport type OutSink = (target: string | \"*\", frame: Uint8Array) => void;\n\n/** Lowercase hex SHA-256 of `bytes` — injected so tests can stub it. */\nexport type Hasher = (bytes: Uint8Array) => Promise<string>;\n\ninterface PendingWant {\n resolvers: Array<(b: Uint8Array | null) => void>;\n timer: ReturnType<typeof setTimeout>;\n}\n\nexport class BlockEngine {\n private readonly wants = new Map<string, PendingWant>();\n\n constructor(\n private readonly store: BlockStore,\n private readonly out: OutSink,\n private readonly hash: Hasher,\n ) {}\n\n /**\n * Ask the swarm for a block. Resolves with the verified bytes, or `null` on\n * timeout (caller then falls back to origin). Returns immediately if we\n * already hold it; concurrent wants for the same hash share one request.\n */\n want(hash: string, timeoutMs: number): Promise<Uint8Array | null> {\n return new Promise((resolve) => {\n void this.store.get(hash).then((local) => {\n if (local) return resolve(local);\n const existing = this.wants.get(hash);\n if (existing) {\n existing.resolvers.push(resolve);\n return;\n }\n const timer = setTimeout(() => {\n const w = this.wants.get(hash);\n this.wants.delete(hash);\n this.out(\"*\", encodeCancel(hash));\n w?.resolvers.forEach((r) => r(null));\n }, timeoutMs);\n this.wants.set(hash, { resolvers: [resolve], timer });\n this.out(\"*\", encodeWant(hash));\n });\n });\n }\n\n /** Tell the swarm we now hold `hash` (so peers wanting it can pull from us). */\n announce(hash: string): void {\n this.out(\"*\", encodeHave(hash));\n }\n\n /** Handle one inbound frame from `peer`. */\n async handleFrame(peer: string, frame: Uint8Array): Promise<void> {\n let f;\n try {\n f = decode(frame);\n } catch {\n return; // malformed — ignore\n }\n switch (f.type) {\n case FrameType.WANT: {\n const bytes = await this.store.get(f.hash);\n if (bytes) this.out(peer, encodeBlock(f.hash, bytes));\n return;\n }\n case FrameType.HAVE: {\n // A peer announced a block we're still waiting for → pull from them.\n if (this.wants.has(f.hash)) this.out(peer, encodeWant(f.hash));\n return;\n }\n case FrameType.BLOCK: {\n const pending = this.wants.get(f.hash);\n if (!pending || !f.payload) return; // unsolicited / empty — ignore\n // Integrity: a peer can't poison the store. Drop a mismatch and\n // keep waiting (the timeout will fall back to origin).\n const got = await this.hash(f.payload);\n if (got !== f.hash) return;\n await this.store.put(f.hash, f.payload);\n this.wants.delete(f.hash);\n clearTimeout(pending.timer);\n this.out(\"*\", encodeCancel(f.hash)); // others can stop sending\n pending.resolvers.forEach((r) => r(f.payload!));\n return;\n }\n case FrameType.CANCEL:\n // We serve WANTs synchronously, so there's nothing in flight to\n // cancel yet. Reserved for chunked-send cancellation later.\n return;\n }\n }\n\n /** Drop all pending waits (resolve null) — on teardown. */\n close(): void {\n for (const [, w] of this.wants) {\n clearTimeout(w.timer);\n w.resolvers.forEach((r) => r(null));\n }\n this.wants.clear();\n }\n}\n\nexport default BlockEngine;\n","/**\n * `EngineHost` — the boundary {@link ../PeerNetwork} wires a transport to. It\n * abstracts *where* the {@link ./blockEngine.BlockEngine} runs:\n * - {@link LocalEngineHost} runs it on the calling thread (tests, or a\n * fallback when the Web Worker can't be built by a consumer's bundler);\n * - the Worker proxy ({@link ./engineClient}) runs it off-thread.\n *\n * Either way the host exposes the same surface: drive `want`/`announce`, feed it\n * inbound frames via `handleFrame`, and receive its outbound frames via\n * `onOutbound` (which the network forwards to the transport).\n */\n\nimport { BlockEngine, type BlockStore, type Hasher } from \"./blockEngine\";\n\nexport interface EngineHost {\n want(hash: string, timeoutMs: number): Promise<Uint8Array | null>;\n announce(hash: string): void;\n /** Feed an inbound frame received from `peer` on the transport. */\n handleFrame(peer: string, frame: Uint8Array): void;\n /** Receive frames the engine wants to send (`\"*\"` = broadcast). */\n onOutbound(cb: (target: string, frame: Uint8Array) => void): () => void;\n close(): void;\n}\n\n/** Runs the engine in-process (main thread or test). */\nexport class LocalEngineHost implements EngineHost {\n private readonly engine: BlockEngine;\n private readonly cbs = new Set<(target: string, frame: Uint8Array) => void>();\n\n constructor(store: BlockStore, hasher: Hasher) {\n this.engine = new BlockEngine(\n store,\n (target, frame) => {\n for (const cb of this.cbs) cb(target, frame);\n },\n hasher,\n );\n }\n\n want(hash: string, timeoutMs: number): Promise<Uint8Array | null> {\n return this.engine.want(hash, timeoutMs);\n }\n announce(hash: string): void {\n this.engine.announce(hash);\n }\n handleFrame(peer: string, frame: Uint8Array): void {\n void this.engine.handleFrame(peer, frame);\n }\n onOutbound(cb: (target: string, frame: Uint8Array) => void): () => void {\n this.cbs.add(cb);\n return () => this.cbs.delete(cb);\n }\n close(): void {\n this.engine.close();\n this.cbs.clear();\n }\n}\n\nexport default LocalEngineHost;\n","/**\n * `WorkerEngineHost` — the main-thread proxy to a {@link ./blockEngine.BlockEngine}\n * running inside a dedicated Web Worker (so hashing, blockstore I/O, and the\n * protocol codec stay off the main thread). It speaks the small message protocol\n * in {@link ./blockEngine.worker} and satisfies {@link ./engineHost.EngineHost},\n * so {@link ../PeerNetwork} treats it identically to the in-process host.\n *\n * Block bytes cross the worker boundary as **transferable** ArrayBuffers\n * (zero-copy). Only encrypted blocks ever cross — keys never enter the worker.\n */\n\nimport type { EngineHost } from \"./engineHost\";\n\ntype WorkerOut =\n | { t: \"out\"; target: string; data: ArrayBuffer }\n | { t: \"want-result\"; id: number; data: ArrayBuffer | null };\n\nexport class WorkerEngineHost implements EngineHost {\n private readonly wants = new Map<number, (b: Uint8Array | null) => void>();\n private readonly cbs = new Set<(target: string, frame: Uint8Array) => void>();\n private nextId = 1;\n\n constructor(private readonly worker: Worker) {\n this.worker.onmessage = (e: MessageEvent<WorkerOut>) => {\n const m = e.data;\n if (m.t === \"out\") {\n const frame = new Uint8Array(m.data);\n for (const cb of this.cbs) cb(m.target, frame);\n } else if (m.t === \"want-result\") {\n const resolve = this.wants.get(m.id);\n if (resolve) {\n this.wants.delete(m.id);\n resolve(m.data ? new Uint8Array(m.data) : null);\n }\n }\n };\n }\n\n want(hash: string, timeoutMs: number): Promise<Uint8Array | null> {\n return new Promise((resolve) => {\n const id = this.nextId++;\n this.wants.set(id, resolve);\n this.worker.postMessage({ t: \"want\", id, hash, timeout: timeoutMs });\n });\n }\n\n announce(hash: string): void {\n this.worker.postMessage({ t: \"announce\", hash });\n }\n\n handleFrame(peer: string, frame: Uint8Array): void {\n // Transfer an exact-size buffer; copy if the view doesn't own the whole buffer.\n const buf =\n frame.byteOffset === 0 && frame.byteLength === frame.buffer.byteLength\n ? frame.buffer\n : frame.slice().buffer;\n this.worker.postMessage({ t: \"frame\", peer, data: buf }, [buf]);\n }\n\n onOutbound(cb: (target: string, frame: Uint8Array) => void): () => void {\n this.cbs.add(cb);\n return () => this.cbs.delete(cb);\n }\n\n close(): void {\n try { this.worker.postMessage({ t: \"close\" }); } catch { /* already gone */ }\n this.worker.terminate();\n this.wants.forEach((r) => r(null));\n this.wants.clear();\n this.cbs.clear();\n }\n}\n\nexport default WorkerEngineHost;\n","/**\n * `PeerNetwork` — the per-Space orchestrator that ties the pieces together on\n * the main thread:\n *\n * transport (WebRTC) ⇄ engine host (Worker or in-process) → PeerExchange\n * ▲ │\n * └────────────── signaling over the Space relay ─────────────┘\n *\n * It owns one {@link ./transport/WebRtcTransport} + one {@link\n * ./worker/engineHost.EngineHost}, wires inbound frames to the engine and the\n * engine's outbound frames back to the transport, runs peer discovery over the\n * Space's ephemeral channel, and exposes a {@link ./PeerExchange.PeerExchange}\n * for `ShardClient` to consult. Scope is one Space (private swarm).\n *\n * `engineHost` defaults to in-process; pass `workerFactory` to run the block\n * engine off the main thread (the consumer's bundler resolves the worker URL).\n */\n\nimport { ShardCache } from \"../offline/cache/ShardCache\";\nimport { shardHash } from \"../storage/transport/ShardClient\";\nimport { PeerExchange } from \"./PeerExchange\";\nimport { SpaceSignaler, type SignalingSpace } from \"./signaling/SpaceSignaler\";\nimport { WebRtcTransport } from \"./transport/WebRtcTransport\";\nimport { CHANNEL_BLOCK, CHANNEL_GOSSIP, type PeerTransport } from \"./transport/PeerTransport\";\nimport { LocalEngineHost, type EngineHost } from \"./worker/engineHost\";\nimport { WorkerEngineHost } from \"./worker/engineClient\";\nimport type { BlockStore } from \"./worker/blockEngine\";\n\nexport interface PeerNetworkOptions {\n /** The Space (used for signaling over its ephemeral relay). */\n space: SignalingSpace;\n /** Our authenticated member id (the Space's `myId`). */\n myId: string;\n /** Blockstore for the in-process engine. Defaults to a `ShardCache`. */\n store?: BlockStore;\n /** Run the block engine in a Worker — `() => new Worker(new URL(...))`. */\n workerFactory?: () => Worker;\n iceServers?: RTCIceServer[];\n maxPeers?: number;\n /** Peer fetch timeout passed to PeerExchange. */\n timeoutMs?: number;\n /** Inject a transport (tests / a future libp2p transport). Default WebRTC. */\n transport?: PeerTransport;\n /** Log mesh + block-exchange activity to the console (use on staging/dev). */\n debug?: boolean;\n}\n\n/**\n * Build the engine host, preferring an off-thread Web Worker:\n * 1. an explicit `workerFactory` (most reliable in app bundlers), else\n * 2. the bundled worker resolved relative to this module (works where the\n * bundler supports `new Worker(new URL(...))`, e.g. Vite builds), else\n * 3. the in-process engine (always works; tests + non-worker runtimes).\n * Any worker construction failure degrades to in-process.\n */\nfunction buildEngineHost(opts: PeerNetworkOptions): EngineHost {\n try {\n const worker = opts.workerFactory ? opts.workerFactory() : defaultWorker();\n if (worker) return new WorkerEngineHost(worker);\n } catch {\n /* no Worker global / bundler can't resolve it → in-process */\n }\n return new LocalEngineHost(opts.store ?? new ShardCache(), shardHash);\n}\n\n/** Construct the bundled worker if the runtime + bundler support it, else null. */\nfunction defaultWorker(): Worker | null {\n try {\n if (typeof Worker === \"undefined\") return null;\n // The string is resolved by the consumer's bundler relative to the\n // built connect module (sibling of dist/browser/index.js).\n return new Worker(new URL(\"./blockEngine.worker.js\", import.meta.url), { type: \"module\" });\n } catch {\n return null;\n }\n}\n\nexport class PeerNetwork {\n /** Pass this to a `ShardClient` as `peers`. */\n readonly exchange: PeerExchange;\n private readonly transport: PeerTransport;\n private readonly host: EngineHost;\n private readonly signaler: SpaceSignaler;\n private readonly offs: Array<() => void> = [];\n private readonly gossipCbs = new Set<(from: string, data: Uint8Array) => void>();\n private closed = false;\n\n constructor(opts: PeerNetworkOptions) {\n this.signaler = new SpaceSignaler(opts.space, opts.myId);\n this.transport =\n opts.transport ??\n new WebRtcTransport(this.signaler, opts.myId, {\n iceServers: opts.iceServers,\n maxPeers: opts.maxPeers,\n debug: opts.debug,\n });\n this.host = buildEngineHost(opts);\n\n // Wire transport ⇄ engine, demuxing block (engine) from gossip (app).\n this.offs.push(\n this.transport.onMessage((peer, data, channel) => {\n if (channel === CHANNEL_GOSSIP) {\n for (const cb of this.gossipCbs) cb(peer, data);\n } else {\n this.host.handleFrame(peer, data);\n }\n }),\n );\n this.offs.push(\n this.host.onOutbound((target, frame) =>\n target === \"*\"\n ? this.transport.broadcast(frame, CHANNEL_BLOCK)\n : this.transport.send(target, frame, CHANNEL_BLOCK),\n ),\n );\n\n // Discovery: a broadcast hello triggers a unicast hello back (so a\n // newcomer learns existing members); both sides connectTo (the smaller\n // id actually dials). Deterministic + idempotent.\n this.offs.push(\n this.signaler.onSignal((from, kind, data) => {\n if (kind !== \"hello\") return;\n this.transport.connectTo?.(from);\n if ((data as { broadcast?: boolean } | undefined)?.broadcast) {\n this.signaler.send(from, \"hello\", { broadcast: false });\n }\n }),\n );\n\n this.exchange = new PeerExchange(this.host, { timeoutMs: opts.timeoutMs, debug: opts.debug });\n\n if (opts.debug) {\n console.info(\"[muhkoo:p2p] mesh attached for space; awaiting peers…\");\n this.offs.push(\n this.transport.onPeerChange((peers) =>\n console.info(`%c[muhkoo:p2p] connected peers: ${peers.length}`, \"color:#58da7d\", peers),\n ),\n );\n }\n }\n\n /**\n * Begin peer discovery — broadcast a hello so existing members dial us and\n * we learn them. Call once the signaling channel is live (the Space fires\n * this on CONNECTED); safe to call again on reconnect.\n */\n start(): void {\n if (this.closed) return;\n this.signaler.broadcast(\"hello\", { broadcast: true });\n }\n\n /**\n * Broadcast an app payload to all connected peers over the gossip channel —\n * a direct, server-bypassing data path for CRDT ops / high-frequency state\n * (cursors, presence, collaborative edits). Single-hop (no re-forwarding).\n */\n gossip(data: Uint8Array): void {\n this.transport.broadcast(data, CHANNEL_GOSSIP);\n }\n\n /** Subscribe to gossip from peers. Returns an unsubscribe function. */\n onGossip(cb: (from: string, data: Uint8Array) => void): () => void {\n this.gossipCbs.add(cb);\n return () => this.gossipCbs.delete(cb);\n }\n\n /** Connected peer count (open data channels). */\n peerCount(): number {\n return this.transport.peers().length;\n }\n\n close(): void {\n if (this.closed) return;\n this.closed = true;\n try { this.signaler.broadcast(\"bye\"); } catch { /* socket may be gone */ }\n for (const off of this.offs) off();\n this.transport.close();\n this.host.close();\n }\n}\n\nexport default PeerNetwork;\n","/**\n * Whether this environment can do WebRTC peering. `RTCPeerConnection` is\n * Window-only (absent in Node/Workers/SSR), so this gates whether a\n * {@link ./PeerNetwork} can be built at all.\n */\nexport function isP2pCapable(): boolean {\n try {\n return typeof RTCPeerConnection !== \"undefined\";\n } catch {\n return false;\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\";\nimport type { OfflineManager } from \"../../offline/OfflineManager\";\nimport { SpaceCache } from \"../../offline/SpaceCache\";\nimport { PeerNetwork } from \"../../p2p/PeerNetwork\";\nimport { isP2pCapable } from \"../../p2p/detect\";\nimport type { ChatKeyVault } from \"../ChatKeyVault\";\nimport { toBase64 } from \"../../utilities\";\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 /** Offline manager — enables message caching + offline send replay. */\n offline?: OfflineManager;\n /** SDK-owned ratchet-keypair vault — gives a STABLE member keypair across\n * reloads (rehydrate-or-provision) instead of a fresh one each session. */\n chatKeys?: ChatKeyVault;\n /** P2P swarm config — enables peer block exchange among Space members. */\n p2p?: {\n enabled?: boolean;\n /** `() => new Worker(new URL(...))` to run the block engine off-thread. */\n workerFactory?: () => Worker;\n iceServers?: RTCIceServer[];\n maxPeers?: number;\n debug?: boolean;\n };\n}\n\nexport class SpaceNamespace {\n private spaceCache?: SpaceCache;\n /** Spaces built this session, by id — used to route offline send replays. */\n private readonly openSpaces = new Map<string, Space>();\n /** Unique id for THIS device/session — the P2P peer identity. A user's own\n * devices share a member id, so the mesh MUST distinguish them by this or a\n * device treats its siblings' signals as its own echo and never connects. */\n private readonly deviceId =\n `peer-${globalThis.crypto?.randomUUID?.() ?? Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2)}`;\n\n constructor(private readonly deps: SpaceNamespaceDeps) {\n if (deps.offline?.enabled) {\n this.spaceCache = new SpaceCache(deps.offline);\n // Replay queued space frames on reconnect: route each to its space\n // (reopening + connecting it if needed), then re-send the raw frame.\n deps.offline.registerReplayer(\"space\", async (entry) => {\n const { spaceId, frame } = entry.args as { spaceId: string; frame: unknown };\n let space = this.openSpaces.get(spaceId);\n if (!space) space = await this.get(spaceId);\n await space.connect();\n if (!space.isConnected()) throw new Error(`space ${spaceId} not connected for replay`);\n space.sendRaw(frame);\n });\n }\n }\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 /**\n * Create a space.\n *\n * `messaging: false` registers the space and stops there — no group-key\n * bootstrap and no WebSocket. Use it for a space that only ever holds\n * FILES: each chunk carries its own key inside its manifest, so the group\n * keyring buys nothing, and opening a socket makes the write path depend on\n * a live connection. That dependency is wrong for a CLI, and it is what made\n * the first VFS write hang forever instead of failing.\n */\n async createSpace(\n opts: { historyPolicy?: HistoryPolicy; private?: boolean; messaging?: boolean } = {},\n ): 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 if (opts.messaging !== false) 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 const space = 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 offline: this.spaceCache,\n shardCache: this.deps.offline?.fileCache,\n deferShardUpload: this.deps.offline\n ? (hash: string) => this.deps.offline!.deferShardUpload(hash)\n : undefined,\n });\n this.openSpaces.set(spaceId, space);\n // Attach a private P2P swarm scoped to this Space (block exchange among\n // members; signaled over the Space relay). Discovery starts on connect.\n if (this.deps.p2p?.enabled && isP2pCapable()) {\n space.attachPeerNetwork(\n new PeerNetwork({\n space,\n myId: this.deviceId, // per-device peer id, NOT the shared member id\n workerFactory: this.deps.p2p.workerFactory,\n iceServers: this.deps.p2p.iceServers,\n maxPeers: this.deps.p2p.maxPeers,\n debug: this.deps.p2p.debug,\n }),\n );\n }\n return space;\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 // Unlocked (seed in hand): rehydrate the member's STABLE keypair from\n // the vault, or provision + persist one on first use. This keeps the\n // member the same identity across reloads — no re-admit each session,\n // and the group-key cache round-trips. Best-effort: a personal-space\n // hiccup falls through to an ephemeral keypair (today's behavior).\n const seed = this.deps.session.seed;\n const staging = (() => { try { return typeof location !== \"undefined\" && /(^|\\.)staging\\./.test(location.hostname); } catch { return false; } })();\n if (staging) console.info(`[muhkoo:vault] ensureIdentity: unlocked=${!!seed} vault=${!!this.deps.chatKeys}`);\n if (this.deps.chatKeys && seed) {\n try {\n await this.deps.chatKeys.ensure(memberId, toBase64(seed));\n } catch (e) {\n if (staging) console.info(`[muhkoo:vault] ensureIdentity: vault.ensure failed — ${e instanceof Error ? e.message : e}`);\n }\n }\n if (!store.getKeyPair(memberId)) {\n if (staging) console.info(\"[muhkoo:vault] ensureIdentity: EPHEMERAL keypair (locked / no vault) → will re-admit\");\n await store.generateOwnKeyPair(memberId);\n }\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 * const out = await client.functions.invoke({ name: 'hello', slug }, { body: { q: 1 } });\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 { HttpError, 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 * Wildcard zone HTTP functions are served from\n * (`<name>--<slug>.<suffix>`). Defaults to the hosted platform's\n * {@link DEFAULT_FN_HOST_SUFFIX}; override for staging / self-hosted.\n */\n fnHostSuffix?: string;\n}\n\n/** The hosted platform's HTTP-function zone. */\nexport const DEFAULT_FN_HOST_SUFFIX = \"fns.muhkoo.dev\";\n\n/** Options for {@link FunctionsNamespace.invoke}. */\nexport interface FunctionInvokeOptions {\n /** HTTP method. Defaults to `POST` when `body` is present, else `GET`. */\n method?: string;\n /**\n * Request body. Plain objects/arrays are JSON-encoded (with\n * `Content-Type: application/json`); strings, `FormData`, `Blob`,\n * `ArrayBuffer`/views and `URLSearchParams` are sent as-is.\n */\n body?: unknown;\n /** Extra headers, merged over the SDK's credential headers. */\n headers?: HeadersInit;\n /** Sub-path (and query) on the function's host, e.g. `/reports?from=...`. */\n path?: string;\n}\n\n/** Bodies `fetch` accepts natively — everything else is JSON-encoded. */\nfunction isRawBody(body: unknown): body is BodyInit {\n return (\n typeof body === \"string\" ||\n body instanceof FormData ||\n body instanceof Blob ||\n body instanceof ArrayBuffer ||\n ArrayBuffer.isView(body) ||\n body instanceof URLSearchParams ||\n (typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream)\n );\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 /**\n * Invoke an HTTP-triggered function and parse its JSON response.\n *\n * const out = await client.functions.invoke({ name: 'hello', slug: 'myapp' });\n * const out = await client.functions.invoke('hello--myapp', { body: { q: 1 } });\n * const out = await client.functions.invoke('https://hello--myapp.fns.muhkoo.dev/x');\n *\n * The request carries the SDK's credentials (`X-Muhkoo-Key` and, when a\n * user is signed in, `X-Muhkoo-Session`) — the platform passes the session\n * token through to the function, which can verify it server-side via\n * `POST /api/auth/verify` to establish the caller's identity.\n *\n * Non-2xx responses throw {@link HttpError}. For functions that return\n * something other than JSON, use {@link invokeRaw}.\n */\n async invoke<T = unknown>(\n target: string | { name: string; slug: string },\n opts: FunctionInvokeOptions = {},\n ): Promise<T> {\n const res = await this.invokeRaw(target, opts);\n let parsed: unknown = null;\n try {\n parsed = await res.json();\n } catch {\n // Non-JSON body — fall through to the status-only error below.\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 /** Invoke an HTTP-triggered function and return the raw `Response`. */\n async invokeRaw(\n target: string | { name: string; slug: string },\n opts: FunctionInvokeOptions = {},\n ): Promise<Response> {\n const init: RequestInit = {\n method: opts.method ?? (opts.body !== undefined ? \"POST\" : \"GET\"),\n };\n const headers = new Headers(opts.headers);\n if (opts.body !== undefined) {\n if (isRawBody(opts.body)) {\n init.body = opts.body;\n } else {\n init.body = JSON.stringify(opts.body);\n if (!headers.has(\"Content-Type\")) headers.set(\"Content-Type\", \"application/json\");\n }\n }\n init.headers = headers;\n return this.deps.http.fetch(this.invokeUrl(target, opts.path), init);\n }\n\n /** Resolve an invoke target to the function's absolute URL. */\n invokeUrl(target: string | { name: string; slug: string }, path = \"\"): string {\n const suffix = this.deps.fnHostSuffix ?? DEFAULT_FN_HOST_SUFFIX;\n let base: string;\n if (typeof target === \"string\") {\n base = /^https?:\\/\\//.test(target) ? target : `https://${target}.${suffix}`;\n } else {\n base = `https://${target.name}--${target.slug}.${suffix}`;\n }\n if (!path) return base;\n return `${base.replace(/\\/+$/, \"\")}${path.startsWith(\"/\") ? \"\" : \"/\"}${path}`;\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.accessTokens` — manage an app's **access tokens**: scoped, expiring,\n * non-ZK machine-to-machine credentials (`mk_<env>_at_…`).\n *\n * const { plaintext } = await client.accessTokens.create(appId, {\n * scopes: [\"db:read\", \"db:write\"], env: \"live\", expiresInDays: 30,\n * label: \"ci-runner\",\n * });\n * // hand `plaintext` to the machine caller as its ClientOptions.accessToken\n *\n * These are MANAGEMENT calls — creating/listing/revoking tokens is authorized by\n * the developer session (same as the `agents`/`functions` namespaces). The token\n * itself resolves through the SAME accelerator path as an app key (the\n * `X-Muhkoo-Key` header), but is scoped to a fixed vocabulary of permissions and\n * expires. The plaintext is returned ONCE, on create — store it then; it can't\n * be read back.\n */\n\nimport type { HttpClient } from \"../HttpClient\";\n\n/** The fixed vocabulary of permissions an access token can be granted. */\nexport type Scope =\n | \"db:read\"\n | \"db:write\"\n | \"kv:read\"\n | \"kv:write\"\n | \"storage:read\"\n | \"storage:write\"\n | \"messages:read\"\n | \"messages:write\"\n | \"functions:invoke\"\n | \"ai:infer\";\n\n/** All valid {@link Scope}s, in canonical order. */\nexport const ACCESS_TOKEN_SCOPES: Scope[] = [\n \"db:read\",\n \"db:write\",\n \"kv:read\",\n \"kv:write\",\n \"storage:read\",\n \"storage:write\",\n \"messages:read\",\n \"messages:write\",\n \"functions:invoke\",\n \"ai:infer\",\n];\n\n/** A token as returned by {@link AccessTokensNamespace.list} (never the plaintext). */\nexport interface AccessTokenInfo {\n keyId: string;\n env: \"live\" | \"test\";\n scopes: string[];\n /** Epoch ms, or absent if the token never expires. */\n expiresAt?: number;\n label?: string;\n createdAt: number;\n revoked: boolean;\n /** True once past {@link expiresAt}. */\n expired: boolean;\n}\n\n/** The editor-settable fields when minting an access token. */\nexport interface CreateAccessTokenInput {\n scopes: string[];\n /** Defaults to `live` on the accelerator. */\n env?: \"live\" | \"test\";\n /** Omit for a non-expiring token. */\n expiresInDays?: number;\n label?: string;\n}\n\n/** Create response — includes the one-time {@link plaintext} secret. */\nexport interface CreatedAccessToken {\n keyId: string;\n env: \"live\" | \"test\";\n /** The `mk_<env>_at_…` secret. Returned ONCE — store it now. */\n plaintext: string;\n scopes: string[];\n expiresAt: number;\n label?: string;\n createdAt: number;\n}\n\nexport interface AccessTokensNamespaceDeps {\n http: HttpClient;\n}\n\nexport class AccessTokensNamespace {\n constructor(private readonly deps: AccessTokensNamespaceDeps) {}\n\n /** List the app's access tokens (metadata only — never the plaintext). */\n async list(appId: string): Promise<AccessTokenInfo[]> {\n const res = await this.deps.http.get<{ tokens: AccessTokenInfo[] }>(this.path(appId, \"\"));\n return res.tokens ?? [];\n }\n\n /** Mint an access token (owner/editor only). The plaintext is returned once. */\n async create(appId: string, input: CreateAccessTokenInput): Promise<CreatedAccessToken> {\n return this.deps.http.post<CreatedAccessToken>(this.path(appId, \"\"), input);\n }\n\n /** Revoke an access token by its `keyId`. */\n async revoke(appId: string, keyId: string): Promise<{ revoked: boolean }> {\n return this.deps.http.del<{ revoked: boolean }>(this.path(appId, `/${encodeURIComponent(keyId)}`));\n }\n\n private path(appId: string, suffix: string): string {\n return `/api/apps/${encodeURIComponent(appId)}/access-tokens${suffix}`;\n }\n}\n\nexport default AccessTokensNamespace;\n","/**\n * Wire types for the VFS metadata layer.\n *\n * ## What is stored where\n *\n * The filesystem is a graph of **directory records**, one per directory, each\n * held under a personal-space KV key and encrypted client-side. A record lists\n * only its immediate children — so listing a directory is one fetch, and you\n * only ever pay for the subtrees you actually open.\n *\n * File CONTENT is not here. Bytes are written with `client.storage.writeFile`\n * exactly as any other file — into a real Space, with a real gated manifest —\n * and the entry keeps the returned `FileManifest` as its handle.\n * `client.storage.readByManifest(manifest)` then reconstructs the bytes from\n * the content-addressed shard store with no space membership or directory\n * lookup needed, which is what makes a file shareable by handing over the\n * handle alone.\n *\n * This supersedes the flat personal mirror `writeFile` already maintains\n * (`{spaceId, manifest}` keyed by manifest id): the same metadata, in the same\n * personal space, arranged as a tree you can actually navigate.\n *\n * ## Why directories have stable random ids, not content hashes\n *\n * A git-style tree keys each directory by the hash of its contents, so writing\n * one file rewrites every ancestor up to the root. Here a directory's id is\n * random and permanent, so a file write touches exactly ONE record — its\n * parent — and renaming or moving a directory edits only the parent entry\n * while the whole subtree underneath stays byte-identical and untouched.\n *\n * ## Why a directory's key lives in its parent\n *\n * Only the root key is derived from the master seed. Every other directory has\n * a random key stored in its parent's entry, which chains capabilities\n * downward: handing someone `{id, key}` for `/apps/my-app` lets them walk that\n * subtree and nothing else, because no key can be derived upward. That is the\n * seam group-sharing hangs off later without re-encrypting the filesystem.\n */\n\nimport type { FileManifest } from \"../storage/types\";\n\n/** Personal-space KV key holding a directory record. */\nexport const dirKey = (id: string): string => `vfs/d/${id}`;\n/** Personal-space KV key holding one file's prior versions. */\nexport const historyKey = (id: string): string => `vfs/h/${id}`;\n\n/** The root directory's id is fixed — it is the one node reached without a parent. */\nexport const ROOT_ID = \"root\";\n/** HKDF label for the seed-derived root key. Sits alongside `muhkoo-storage-v1`. */\nexport const VFS_ROOT_INFO = \"muhkoo-vfs-v1\";\n\nexport interface FileEntry {\n kind: \"file\";\n /**\n * Stable identity, independent of name and location. Renaming a file keeps\n * its id, so its version history follows it rather than being orphaned.\n */\n id: string;\n /** The handle: everything needed to read the current bytes back. */\n manifest: FileManifest;\n /** Plaintext byte length. */\n size: number;\n mtime: number;\n /**\n * Count of prior versions in the file's history record.\n *\n * Denormalised on purpose: the file tree wants to show \"3 versions\" while\n * listing a directory, and fetching every history record to answer that\n * would defeat the point of keeping history out of the directory record.\n */\n versions?: number;\n}\n\nexport interface DirEntry {\n kind: \"dir\";\n /** Record id — `dirKey(id)` locates it. Permanent for the directory's life. */\n id: string;\n /** Base64 AES-256 key for that record. See the capability note above. */\n key: string;\n mtime: number;\n}\n\nexport type Entry = FileEntry | DirEntry;\n\n/** One directory record, as stored (before encryption). */\nexport interface DirNode {\n v: 1;\n /** Child name → entry. Names are unique within a directory, per filesystem. */\n entries: Record<string, Entry>;\n mtime: number;\n}\n\n/** A file's prior versions, newest first. Fetched only when asked for. */\nexport interface HistoryRecord {\n v: 1;\n versions: Array<{ manifest: FileManifest; size: number; mtime: number }>;\n}\n\n/** What `stat` and `list` hand back — a path-addressed view of an entry. */\nexport interface VfsStat {\n path: string;\n name: string;\n kind: \"file\" | \"dir\";\n size: number;\n mtime: number;\n versions: number;\n}\n\n/** The encrypted envelope every record is stored in. */\nexport interface SealedRecord {\n v: 1;\n /** Base64 12-byte AES-GCM IV. */\n iv: string;\n /** Base64 ciphertext with the 16-byte tag appended. */\n ct: string;\n}\n\n/** The personal-space blob store the VFS persists through. */\nexport interface VfsStore {\n get(key: string): Promise<unknown | null>;\n put(key: string, value: unknown): Promise<void>;\n delete(key: string): Promise<void>;\n /** Every key in the store — the personal space is shared, so this is NOT VFS-only. */\n list(): Promise<string[]>;\n}\n\n/** Raised when the master seed is not held, so the root key cannot be derived. */\nexport class VfsLockedError extends Error {\n constructor() {\n // Named rather than generic because the caller's remedy is specific and\n // not guessable from a failed decrypt: re-authenticate to recover the\n // seed. A page reload alone loses it — it is memory-only, never stored.\n super(\"VFS is locked: the master seed is not in memory. Sign in again to unlock.\");\n this.name = \"VfsLockedError\";\n }\n}\n\n/** Raised for a path that does not exist. */\nexport class VfsNotFoundError extends Error {\n constructor(path: string) {\n super(`VFS: ${path} does not exist`);\n this.name = \"VfsNotFoundError\";\n }\n}\n\n/** Raised when an operation would clobber or misuse an existing entry. */\nexport class VfsConflictError extends Error {\n constructor(message: string) {\n super(`VFS: ${message}`);\n this.name = \"VfsConflictError\";\n }\n}\n","/**\n * Sealing for VFS metadata records.\n *\n * Every directory and history record is AES-256-GCM encrypted before it leaves\n * the process, so the server holds ciphertext and never learns a filename, a\n * directory shape, or a file size. The manifests inside carry their own chunk\n * keys, which is why the metadata must be sealed too: a readable directory\n * record would hand over the keys to its files.\n */\n\nimport { encryptAesGcm, decryptAesGcm } from \"../crypto/primitives/aes-gcm\";\nimport { deriveBitsHkdf } from \"../crypto/primitives/kdf\";\nimport { randomBytes } from \"../crypto/primitives/random\";\nimport { VFS_ROOT_INFO, type SealedRecord } from \"./types\";\n\nconst AES_GCM_IV_BYTES = 12;\nconst AES_KEY_BYTES = 32;\n\nexport function toBase64(bytes: Uint8Array): string {\n let s = \"\";\n for (const b of bytes) s += String.fromCharCode(b);\n return btoa(s);\n}\n\nexport function fromBase64(b64: string): Uint8Array {\n const s = atob(b64);\n const out = new Uint8Array(s.length);\n for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);\n return out;\n}\n\n/** A fresh random key for a newly created directory. */\nexport function newDirKey(): Uint8Array {\n return randomBytes(AES_KEY_BYTES);\n}\n\n/**\n * A fresh random id.\n *\n * Ids are opaque and never derived from names or contents — a predictable id\n * would leak the directory structure through the KV key, which is the one part\n * of a record the server does see.\n */\nexport function newId(): string {\n return toBase64(randomBytes(16)).replace(/[+/=]/g, \"\").slice(0, 22);\n}\n\n/** The root key, derived from the master seed. The only key not stored in a parent. */\n/**\n * The key a project's repository objects are sealed with.\n *\n * Per project, not one key for everything: commits, trees and refs describe a\n * single project's history, and deriving per slug keeps that blast radius small\n * if a key is ever shared to collaborate on one project.\n */\nexport async function deriveRepoKey(seed: Uint8Array, slug: string): Promise<Uint8Array> {\n return deriveBitsHkdf(seed, `${VFS_ROOT_INFO}:vcs:${slug}`, AES_KEY_BYTES);\n}\n\nexport async function deriveRootKey(seed: Uint8Array): Promise<Uint8Array> {\n return deriveBitsHkdf(seed, VFS_ROOT_INFO, AES_KEY_BYTES);\n}\n\nexport async function seal(key: Uint8Array, value: unknown): Promise<SealedRecord> {\n const iv = randomBytes(AES_GCM_IV_BYTES);\n const plaintext = new TextEncoder().encode(JSON.stringify(value));\n const ct = await encryptAesGcm(key, iv, plaintext);\n return { v: 1, iv: toBase64(iv), ct: toBase64(ct) };\n}\n\n/**\n * Open a sealed record. Returns null for anything that is not a well-formed\n * envelope, so a missing or corrupt record reads as \"absent\" rather than\n * throwing — the caller can then rebuild it. A WRONG KEY still throws, because\n * silently treating an undecryptable directory as empty would present the user\n * with an empty filesystem and then let a write overwrite the real one.\n */\nexport async function unseal<T>(key: Uint8Array, record: unknown): Promise<T | null> {\n if (!record || typeof record !== \"object\") return null;\n const r = record as Partial<SealedRecord>;\n if (typeof r.iv !== \"string\" || typeof r.ct !== \"string\") return null;\n const plaintext = await decryptAesGcm(key, fromBase64(r.iv), fromBase64(r.ct));\n return JSON.parse(new TextDecoder().decode(plaintext)) as T;\n}\n","/**\n * Absolute POSIX paths for the VFS.\n *\n * A path is a lookup route, not a stored value: nothing in the metadata records\n * a full path, only a name inside its parent directory. That is what makes\n * renaming or moving a directory a single-record edit instead of a rewrite of\n * every descendant.\n */\n\n/** Absolute, single leading slash, no `.` / `..`, no trailing slash. Root is `/`. */\nexport function normalizePath(input: string): string {\n const out: string[] = [];\n for (const part of input.split(\"/\")) {\n if (part === \"\" || part === \".\") continue;\n if (part === \"..\") out.pop();\n else out.push(part);\n }\n return \"/\" + out.join(\"/\");\n}\n\n/** Path split into its segments. `/` yields `[]`. */\nexport function segments(path: string): string[] {\n return normalizePath(path).split(\"/\").filter(Boolean);\n}\n\n/**\n * Resolve `path` against a working directory, POSIX-style.\n *\n * An absolute path ignores the cwd; a relative one hangs off it; `..` climbs\n * and stops at the root rather than escaping it. This is the single place\n * relativity is interpreted, so every VFS method behaves the same way — a\n * filesystem where `cat a.txt` and `list(\"a\")` disagreed about what \"here\"\n * means would be worse than having no cwd at all.\n */\nexport function resolveFrom(cwd: string, path: string): string {\n if (path.startsWith(\"/\")) return normalizePath(path);\n return normalizePath(`${cwd}/${path}`);\n}\n\nexport function dirname(path: string): string {\n const p = normalizePath(path);\n const i = p.lastIndexOf(\"/\");\n return i <= 0 ? \"/\" : p.slice(0, i);\n}\n\nexport function basename(path: string): string {\n const p = normalizePath(path);\n return p.slice(p.lastIndexOf(\"/\") + 1);\n}\n\nexport function join(...parts: string[]): string {\n return normalizePath(parts.join(\"/\"));\n}\n\n/**\n * Is `path` inside `dir` (at any depth)? A directory is never \"under\" itself,\n * which is what makes it usable as the guard against moving a directory into\n * its own subtree.\n */\nexport function isUnder(path: string, dir: string): boolean {\n const p = normalizePath(path);\n const d = normalizePath(dir);\n if (p === d) return false;\n return d === \"/\" ? true : p.startsWith(d + \"/\");\n}\n\n/**\n * Reject names that would make a path ambiguous or unrepresentable.\n *\n * `/` would forge a nesting level, and `.` / `..` would resolve to a different\n * directory on the next lookup — a file literally named `..` could never be\n * addressed again.\n */\n/** The longest a single entry name may be. Matches the common filesystem limit. */\nexport const MAX_NAME_BYTES = 255;\n\n/**\n * Is this a name we are willing to store, and to hand back as a path segment?\n *\n * This is the READ-side check as much as the write-side one, and the read side\n * is the one that matters: a directory record is sealed with a key that any\n * holder of the master seed can derive, so its contents are not necessarily\n * something this SDK wrote. A name arriving from a record is input.\n *\n * What each rule is for:\n * - `/` and backslash would become path structure. Backslash is a separator on\n * Windows, which makes it traversal there and an odd filename elsewhere.\n * - `.` and `..` navigate rather than name.\n * - NUL terminates a path in every syscall that takes one.\n * - Other control characters and bidi overrides let a name print as something\n * other than what it is - the classic way a file passes review.\n * - A length cap, because nothing else imposes one.\n */\nexport function isSafeName(name: string): boolean {\n if (!name || name === \".\" || name === \"..\") return false;\n if (name.includes(\"/\") || name.includes(String.fromCharCode(92))) return false;\n const CONTROL_OR_BIDI = new RegExp(\"[\\\\u0000-\\\\u001f\\\\u007f-\\\\u009f\\\\u202a-\\\\u202e\\\\u2066-\\\\u2069]\");\n if (CONTROL_OR_BIDI.test(name)) return false;\n return new TextEncoder().encode(name).length <= MAX_NAME_BYTES;\n}\n\nexport function assertValidName(name: string): void {\n if (!name) throw new Error(\"VFS: name cannot be empty\");\n if (!isSafeName(name)) throw new Error(`VFS: ${JSON.stringify(name)} is not a usable name`);\n}\n\n/**\n * MIME type for a filename.\n *\n * Stored with the content rather than guessed at read time, because whatever\n * eventually serves these bytes — a preview, a static host — sends this as the\n * `Content-Type`, and a browser will refuse to run a module or apply a\n * stylesheet labelled `application/octet-stream`.\n */\nexport function contentTypeFor(name: string): string {\n const ext = name.slice(name.lastIndexOf(\".\") + 1).toLowerCase();\n switch (ext) {\n case \"html\": case \"htm\": return \"text/html; charset=utf-8\";\n case \"css\": return \"text/css; charset=utf-8\";\n case \"js\": case \"mjs\": case \"jsx\": return \"text/javascript; charset=utf-8\";\n case \"ts\": case \"tsx\": return \"text/typescript; charset=utf-8\";\n case \"json\": return \"application/json; charset=utf-8\";\n case \"md\": return \"text/markdown; charset=utf-8\";\n case \"txt\": return \"text/plain; charset=utf-8\";\n case \"svg\": return \"image/svg+xml\";\n case \"png\": return \"image/png\";\n case \"jpg\": case \"jpeg\": return \"image/jpeg\";\n case \"gif\": return \"image/gif\";\n case \"webp\": return \"image/webp\";\n case \"avif\": return \"image/avif\";\n case \"ico\": return \"image/x-icon\";\n case \"woff2\": return \"font/woff2\";\n case \"woff\": return \"font/woff\";\n case \"wasm\": return \"application/wasm\";\n case \"map\": return \"application/json\";\n default: return \"application/octet-stream\";\n }\n}\n","/**\n * Glob matching for VFS paths.\n *\n * A deliberately small dialect — `*`, `**`, `?`, and `{a,b}` — because these\n * cover what a project actually asks for (`**\\/*.tsx`, `src/*.css`) and every\n * addition beyond them is a new way for a pattern to mean something the caller\n * did not expect.\n */\n\n/** `*` stops at a separator; `**` crosses them. That distinction is the whole point. */\nexport function globToRegExp(pattern: string): RegExp {\n let out = \"\";\n for (let i = 0; i < pattern.length; i++) {\n const c = pattern[i];\n if (c === \"*\") {\n if (pattern[i + 1] === \"*\") {\n // `**/` should also match zero directories, so `/**/x` finds `/x`.\n if (pattern[i + 2] === \"/\") {\n out += \"(?:.*/)?\";\n i += 2;\n } else {\n out += \".*\";\n i += 1;\n }\n } else {\n out += \"[^/]*\";\n }\n } else if (c === \"?\") {\n out += \"[^/]\";\n } else if (c === \"{\") {\n const close = pattern.indexOf(\"}\", i);\n if (close === -1) {\n out += \"\\\\{\";\n } else {\n const alts = pattern.slice(i + 1, close).split(\",\");\n out += `(?:${alts.map(escapeLiteral).join(\"|\")})`;\n i = close;\n }\n } else {\n out += escapeLiteral(c);\n }\n }\n return new RegExp(`^${out}$`);\n}\n\nfunction escapeLiteral(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","/**\n * `client.vfs` — a real filesystem over Muhkoo primitives.\n *\n * Metadata is a graph of encrypted directory records in the user's personal\n * space; file content is chunked, encrypted and stored in the global\n * content-addressed shard store, referenced by manifest. See `types.ts` for\n * why directories carry stable random ids and why each key lives in its parent.\n *\n * ## Consistency\n *\n * Every mutation is a read-modify-write of exactly ONE directory record, so a\n * write cannot leave the tree half-updated: either the parent names the new\n * child or it does not. Two tabs writing different directories never conflict;\n * two tabs writing the SAME directory resolve last-writer-wins at the personal\n * space, which carries an HLC per key. Orphaned records (a directory whose\n * parent entry lost the race) are unreachable rather than corrupting — they\n * cost storage until a future sweep, which is the trade this shape makes in\n * exchange for single-record writes.\n */\n\nimport type { FileManifest } from \"../storage/types\";\nimport {\n dirKey,\n historyKey,\n ROOT_ID,\n VfsConflictError,\n VfsLockedError,\n VfsNotFoundError,\n type DirEntry,\n type DirNode,\n type Entry,\n type FileEntry,\n type HistoryRecord,\n type VfsStat,\n type VfsStore,\n} from \"./types\";\nimport { deriveRootKey, fromBase64, newDirKey, newId, seal, toBase64, unseal } from \"./recordCipher\";\nimport {\n assertValidName, basename, contentTypeFor, dirname, isSafeName, isUnder, join, normalizePath, resolveFrom, segments,\n} from \"./paths\";\nimport { globToRegExp } from \"./glob\";\n\n/**\n * The slice of content storage the VFS needs.\n *\n * Narrow on purpose: the VFS knows how to name and arrange things, not how to\n * shard them. The adapter in `Client` resolves the content space and calls\n * `client.storage.writeFile` unchanged — the file still lands in a real Space\n * with a real gated manifest, and the VFS just keeps the handle somewhere\n * better than a flat mirror.\n */\nexport interface VfsContentStore {\n write(\n data: Uint8Array | Blob,\n meta: { name: string; type: string },\n ): Promise<{ manifest: FileManifest; size: number }>;\n read(manifest: FileManifest): Promise<Uint8Array>;\n /**\n * Drop a reference to a manifest's shards.\n *\n * Shards are content-addressed and reference-counted, so deleting a file is\n * not enough to reclaim the bytes — without this, every version ever\n * written stays on disk and billed forever. Best-effort: a failure here\n * leaks storage but must not block the delete.\n */\n release(manifest: FileManifest): Promise<void>;\n /**\n * Take an ADDITIONAL reference to shards that already exist.\n *\n * Needed when a manifest gains a second owner without new bytes being\n * written — copying a file. Without it the copy holds a handle to shards\n * with a refcount of one, and deleting the original frees the bytes out\n * from under it.\n */\n retain(manifest: FileManifest): Promise<void>;\n}\n\nexport interface VfsNamespaceDeps {\n store: VfsStore;\n /**\n * Subscribe to the personal space's raw change feed, if the runtime has one.\n * Optional so the VFS works headlessly (a CLI, a test) with no socket.\n */\n subscribe?: (handler: (frame: unknown) => void) => () => void;\n content: VfsContentStore;\n /** The in-memory master seed, or null when locked. Read per call — it can change. */\n seed: () => Uint8Array | null;\n /** Versions retained per file. */\n historyLimit?: number;\n}\n\n/** A directory record plus the key it was opened with. */\ninterface OpenDir {\n id: string;\n key: Uint8Array;\n node: DirNode;\n}\n\n/**\n * How deep a tree may be before we stop walking it.\n *\n * Well past anything a real project needs, and low enough that a malformed or\n * hostile record cannot spend the caller's memory before the cycle guard sees a\n * repeat.\n */\nconst MAX_DEPTH = 64;\n\n/**\n * How many directories `walk` lists at once.\n *\n * Enough to hide per-request latency on a wide tree; low enough that a big\n * project does not open a request per directory. Browsers cap concurrency per\n * origin anyway, so a larger number mostly moves the queue.\n */\nconst WALK_CONCURRENCY = 8;\n\n/**\n * `Promise.all` with a ceiling, preserving input order.\n *\n * Results are written back BY INDEX rather than pushed as they settle, so the\n * output order matches the input regardless of which finishes first — which is\n * what lets `walk` parallelise without changing what it returns.\n */\nasync function mapLimit<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {\n if (items.length <= 1) return items.length ? [await fn(items[0])] : [];\n const out = new Array<R>(items.length);\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(limit, items.length) }, async () => {\n for (let i = next++; i < items.length; i = next++) out[i] = await fn(items[i]);\n }),\n );\n return out;\n}\n\nconst DEFAULT_HISTORY_LIMIT = 20;\n\nexport class VfsNamespace {\n private rootKey: Uint8Array | null = null;\n /**\n * Decrypted directory records, by id.\n *\n * The file tree re-lists constantly while typing, and every miss is a\n * network round trip plus a decrypt. Invalidated precisely on write rather\n * than by TTL — a stale directory listing shows files that are not there.\n */\n private cache = new Map<string, Promise<OpenDir>>();\n private readonly historyLimit: number;\n\n constructor(private readonly deps: VfsNamespaceDeps) {\n this.historyLimit = deps.historyLimit ?? DEFAULT_HISTORY_LIMIT;\n }\n\n /**\n * The working directory relative paths resolve against.\n *\n * Kept here rather than left to each caller so that a CLI, a script and the\n * SDK all agree on what \"here\" means — the alternative is every consumer\n * re-implementing `cd`, and disagreeing about `..`.\n */\n private _cwd = \"/\";\n\n /** The current working directory. Always absolute. */\n get cwd(): string {\n return this._cwd;\n }\n\n /**\n * Change the working directory.\n *\n * Verifies the target is a real directory, so a typo fails here — where the\n * message can name the path — rather than turning every later relative path\n * into a confusing \"does not exist\".\n */\n async cd(path: string): Promise<string> {\n const target = this.resolve(path);\n if (target !== \"/\") {\n const found = await this.find(target);\n if (!found) throw new VfsNotFoundError(target);\n if (found.entry.kind !== \"dir\") throw new VfsConflictError(`${target} is not a directory`);\n }\n this._cwd = target;\n return target;\n }\n\n /** Resolve a path against the working directory. Absolute paths pass through. */\n resolve(path: string): string {\n return resolveFrom(this._cwd, path);\n }\n\n /** True when the master seed is held, so the root key can be derived. */\n get unlocked(): boolean {\n return this.deps.seed() !== null;\n }\n\n /**\n * Drop every cached record.\n *\n * Call after signing in as someone else — the cache is keyed by directory\n * id with no notion of whose filesystem it came from, and serving one\n * identity's directories to another would be the worst possible bug here.\n */\n clearCache(): void {\n this.cache.clear();\n this.rootKey = null;\n this._cwd = \"/\"; // a different identity's tree has different directories\n }\n\n /**\n * Call `handler` when this filesystem changes somewhere else — another tab,\n * another machine, the CLI.\n *\n * Deliberately a NOTIFICATION, not a diff: the frame names a record id, and\n * a record id is not a path (paths are resolved by walking, and the walk is\n * what the change may have invalidated). So the cache is dropped and the\n * caller re-reads whatever it is actually showing. Trying to translate a\n * record id back into a path would mean maintaining a reverse index that\n * could itself go stale.\n *\n * Returns an unsubscribe function. A runtime with no socket (a CLI) gets a\n * no-op rather than an error — watching is an optimisation, never required\n * for correctness.\n */\n watch(handler: () => void): () => void {\n if (!this.deps.subscribe) return () => {};\n return this.deps.subscribe((raw) => {\n let frame: { _t?: string; key?: string };\n try {\n frame = typeof raw === \"string\" ? JSON.parse(raw) : (raw as typeof frame);\n } catch {\n return;\n }\n if (frame?._t !== \"change\" || typeof frame.key !== \"string\") return;\n if (!frame.key.startsWith(\"vfs/\")) return; // someone else's data on the shared feed\n\n // Drop only the record that changed.\n //\n // Clearing everything looked cheap and is not: our own writes echo\n // back, so a sync that writes a few hundred files emptied the cache\n // a few hundred times, and every path resolution in flight went back\n // to the network for the root and every directory below it. The key\n // names the record, so there is no need to guess.\n const id = frame.key.startsWith(\"vfs/d/\") ? frame.key.slice(\"vfs/d/\".length) : null;\n if (id) this.cache.delete(id);\n else this.cache.clear(); // a shape we do not recognise: be safe\n handler();\n });\n }\n\n // ---- reads --------------------------------------------------------------\n\n async exists(path: string): Promise<boolean> {\n return (await this.find(path)) !== null;\n }\n\n async stat(path: string): Promise<VfsStat> {\n const found = await this.find(path);\n if (!found) throw new VfsNotFoundError(this.resolve(path));\n return toStat(this.resolve(path), found.name, found.entry);\n }\n\n /** Immediate children of a directory. One record fetch. */\n async list(path = \".\"): Promise<VfsStat[]> {\n const dir = await this.openDir(path);\n const base = this.resolve(path);\n return Object.entries(dir.node.entries)\n // Validate the name HERE, where it is read.\n //\n // A directory record is sealed under a key derivable from the master\n // seed, so its contents are not necessarily something this SDK\n // wrote, and the write-side check never sees them. An unusable name\n // is dropped rather than thrown on: one bad entry must not make the\n // whole directory unlistable, and callers walk this output straight\n // into filesystem paths.\n .filter(([name]) => {\n if (isSafeName(name)) return true;\n this.warn(`ignoring entry with an unusable name in ${base}`);\n return false;\n })\n .map(([name, entry]) => toStat(join(base, name), name, entry))\n .sort(byDirsThenName);\n }\n\n private warn(message: string): void {\n // Kept quiet by default in a browser console that the user cannot act\n // on, but never silent: a dropped entry is a real difference between\n // what is stored and what is shown.\n console.warn(`[muhkoo/vfs] ${message}`);\n }\n\n /**\n * Every file path under a prefix, depth-first.\n *\n * Deliberately separate from `list`: this walks the whole subtree, which is\n * one fetch per directory. Fine for a project, wrong as a default.\n */\n async walk(path = \".\"): Promise<string[]> {\n /**\n * Sibling directories are listed CONCURRENTLY.\n *\n * Each `list` is a round trip for one directory record, and walking them\n * one after another cost the sum of those latencies: measured against a\n * real project, the walk alone was 1–2.1s before a single file had been\n * read. Directories are independent, so there was never a reason to\n * queue them.\n *\n * Order is preserved exactly. Each entry maps to its own slice of the\n * result and the slices are concatenated in listing order, so the output\n * is identical to the depth-first version — callers and tests that\n * depend on it are unaffected, and only the timing changes.\n */\n const seen = new Set<string>();\n\n const visit = async (dirPath: string, depth: number): Promise<string[]> => {\n if (depth > MAX_DEPTH) {\n this.warn(`stopping at ${dirPath}: deeper than ${MAX_DEPTH} levels`);\n return [];\n }\n // Claimed BEFORE the first await, so two concurrent visits to the\n // same directory cannot both get past this. A record whose entry\n // points back at an ancestor would otherwise recurse forever, and\n // nothing in the format prevents one.\n if (seen.has(dirPath)) {\n this.warn(`stopping at ${dirPath}: already visited (the tree contains a cycle)`);\n return [];\n }\n seen.add(dirPath);\n\n const entries = await this.list(dirPath);\n const slices = await mapLimit(entries, WALK_CONCURRENCY, async (entry) =>\n entry.kind === \"dir\" ? visit(entry.path, depth + 1) : [entry.path],\n );\n return slices.flat();\n };\n\n return visit(this.resolve(path), 0);\n }\n\n async readFile(path: string): Promise<Uint8Array> {\n const entry = await this.expectFile(path);\n return this.deps.content.read(entry.manifest);\n }\n\n async readText(path: string): Promise<string> {\n return new TextDecoder().decode(await this.readFile(path));\n }\n\n /**\n * A file's manifest — the handle itself, without reading the bytes.\n *\n * Version control records manifests rather than content, so a commit costs\n * a hash and a reference, not a copy.\n */\n async statManifest(path: string): Promise<{ manifest: FileManifest; size: number }> {\n const entry = await this.expectFile(path);\n return { manifest: entry.manifest, size: entry.size };\n }\n\n /**\n * Read content by its manifest, wherever it came from.\n *\n * A merge needs the COMMON ANCESTOR's version of a file, which by definition\n * is not in the working tree any more. The manifest is the whole capability,\n * so no path lookup is involved.\n */\n async readByManifest(manifest: FileManifest): Promise<Uint8Array> {\n return this.deps.content.read(manifest);\n }\n\n /**\n * Pin content that something other than the working tree depends on.\n *\n * A commit references a manifest, so it is an OWNER of that content — without\n * a reference of its own, deleting the file from the working tree would free\n * shards the history still needs, and checking out an older commit would find\n * the content gone. (It did, in test.)\n */\n async retainManifest(manifest: FileManifest): Promise<void> {\n await this.deps.content.retain(manifest);\n }\n\n /**\n * Point a path at content that already exists.\n *\n * This is how a checkout restores a file: the bytes are in the shard store\n * already, so nothing is uploaded or downloaded — only the directory record\n * changes. Takes a reference, because a second path now depends on those\n * shards.\n */\n async writeManifest(path: string, manifest: FileManifest, size: number): Promise<VfsStat> {\n const target = this.resolve(path);\n const name = basename(target);\n assertValidName(name);\n await this.mkdir(dirname(target), { recursive: true });\n\n const parent = await this.openDir(dirname(target));\n const prior = parent.node.entries[name];\n if (prior?.kind === \"dir\") throw new VfsConflictError(`${target} is a directory`);\n\n await this.deps.content.retain(manifest);\n const entry: FileEntry = {\n kind: \"file\",\n id: prior?.id ?? newId(),\n manifest,\n size,\n mtime: Date.now(),\n versions: prior?.versions ?? 0,\n };\n await this.mutate(parent, (node) => {\n node.entries[name] = entry;\n });\n return toStat(target, name, entry);\n }\n\n // ---- writes -------------------------------------------------------------\n\n /**\n * Create a directory. `recursive` creates missing parents and tolerates an\n * existing target, matching `mkdir -p`.\n */\n async mkdir(path: string, opts: { recursive?: boolean } = {}): Promise<void> {\n const target = this.resolve(path);\n if (target === \"/\") return;\n const parts = segments(target);\n\n let current = \"/\";\n for (let i = 0; i < parts.length; i++) {\n const name = parts[i];\n const isLast = i === parts.length - 1;\n const next = join(current, name);\n const existing = (await this.openDir(current)).node.entries[name];\n\n if (existing) {\n if (existing.kind === \"file\") throw new VfsConflictError(`${next} is a file`);\n if (isLast && !opts.recursive) throw new VfsConflictError(`${next} already exists`);\n } else {\n if (!isLast && !opts.recursive) throw new VfsNotFoundError(current);\n await this.createDir(current, name);\n }\n current = next;\n }\n }\n\n /**\n * Write a file, creating parent directories as needed.\n *\n * The previous version is pushed onto the file's history record before the\n * directory entry is replaced, so an interrupted write can lose the new\n * version but never the old one.\n */\n async writeFile(\n path: string,\n data: Uint8Array | string | Blob,\n opts: { type?: string } = {},\n ): Promise<VfsStat> {\n const target = this.resolve(path);\n const name = basename(target);\n assertValidName(name);\n const parentPath = dirname(target);\n await this.mkdir(parentPath, { recursive: true });\n\n const bytes = typeof data === \"string\" ? new TextEncoder().encode(data) : data;\n const { manifest, size } = await this.deps.content.write(bytes, {\n name,\n type: opts.type ?? contentTypeFor(name),\n });\n\n const parent = await this.openDir(parentPath);\n const prior = parent.node.entries[name];\n if (prior?.kind === \"dir\") throw new VfsConflictError(`${target} is a directory`);\n\n const id = prior?.id ?? newId();\n let versions = prior?.versions ?? 0;\n if (prior) versions = await this.pushHistory(parent, id, prior as FileEntry);\n\n const entry: FileEntry = { kind: \"file\", id, manifest, size, mtime: Date.now(), versions };\n await this.mutate(parent, (node) => {\n node.entries[name] = entry;\n });\n return toStat(target, name, entry);\n }\n\n /**\n * Delete a file, or a directory when `recursive`.\n *\n * `keepContent` removes the entry WITHOUT releasing its shards. A checkout\n * needs that: the file is leaving the working tree, but commits still\n * reference the same manifest, and releasing would free content history\n * depends on.\n */\n async delete(path: string, opts: { recursive?: boolean; keepContent?: boolean } = {}): Promise<void> {\n const target = this.resolve(path);\n if (target === \"/\") throw new VfsConflictError(\"the root directory cannot be deleted\");\n const name = basename(target);\n const parent = await this.openDir(dirname(target));\n const entry = parent.node.entries[name];\n if (!entry) throw new VfsNotFoundError(target);\n\n if (entry.kind === \"dir\") {\n const child = await this.openDirById(entry.id, fromBase64(entry.key));\n const empty = Object.keys(child.node.entries).length === 0;\n if (!empty && !opts.recursive) throw new VfsConflictError(`${target} is not empty`);\n await this.purge(child);\n } else if (opts.keepContent) {\n await this.deps.store.delete(historyKey(entry.id)).catch(() => {});\n } else {\n await this.releaseFile(parent, entry);\n }\n\n await this.mutate(parent, (node) => {\n delete node.entries[name];\n });\n }\n\n /**\n * Move or rename. Works across directories, which is the same operation:\n * detach the entry from one parent and attach it to another.\n *\n * A directory move is O(1) regardless of how much is inside it — the\n * subtree records are not touched at all, because nothing in them records\n * its own path.\n */\n async rename(from: string, to: string): Promise<void> {\n const src = this.resolve(from);\n const dst = this.resolve(to);\n if (src === dst) return;\n if (src === \"/\") throw new VfsConflictError(\"the root directory cannot be moved\");\n if (isUnder(dst, src)) throw new VfsConflictError(`cannot move ${src} into itself`);\n\n const dstName = basename(dst);\n assertValidName(dstName);\n\n const srcParent = await this.openDir(dirname(src));\n const entry = srcParent.node.entries[basename(src)];\n if (!entry) throw new VfsNotFoundError(src);\n\n await this.mkdir(dirname(dst), { recursive: true });\n const dstParent = await this.openDir(dirname(dst));\n if (dstParent.node.entries[dstName]) throw new VfsConflictError(`${dst} already exists`);\n\n // Attach before detaching. If the second write fails the entry is\n // reachable from both parents — visible and fixable. The other order\n // would lose the subtree entirely.\n const moved: Entry = { ...entry, mtime: Date.now() };\n await this.mutate(dstParent, (node) => {\n node.entries[dstName] = moved;\n });\n\n // Re-open: same-parent moves mutated the record we are about to edit.\n const detachFrom = await this.openDir(dirname(src));\n await this.mutate(detachFrom, (node) => {\n delete node.entries[basename(src)];\n });\n }\n\n /**\n * Copy a file or a directory tree.\n *\n * Copying a FILE moves no bytes: content is immutable and content-addressed,\n * so the new entry simply points at the same manifest. A 200 MB asset\n * duplicates in one small metadata write, and the shard store already holds\n * exactly one copy of it.\n *\n * The copy gets a NEW file id, so it does not inherit or share history —\n * two paths sharing an id would mean saving one silently pushed a version\n * onto the other.\n */\n async copy(from: string, to: string): Promise<VfsStat> {\n const src = this.resolve(from);\n const dst = this.resolve(to);\n if (src === \"/\") throw new VfsConflictError(\"the root directory cannot be copied\");\n if (src === dst) throw new VfsConflictError(`${dst} already exists`);\n if (isUnder(dst, src)) throw new VfsConflictError(`cannot copy ${src} into itself`);\n\n const found = await this.find(src);\n if (!found) throw new VfsNotFoundError(src);\n\n const dstName = basename(dst);\n assertValidName(dstName);\n await this.mkdir(dirname(dst), { recursive: true });\n const dstParent = await this.openDir(dirname(dst));\n if (dstParent.node.entries[dstName]) throw new VfsConflictError(`${dst} already exists`);\n\n const copied = await this.cloneEntry(found.entry);\n await this.mutate(dstParent, (node) => {\n node.entries[dstName] = copied;\n });\n return toStat(dst, dstName, copied);\n }\n\n /**\n * Paths matching a glob, relative to the whole filesystem.\n *\n * Matching happens on the client over a walk of the tree, so the cost is one\n * record fetch per directory — cheap for a project, and worth knowing before\n * pointing it at the root of a large filesystem. Use `walk` when the prefix\n * already narrows it.\n */\n async glob(pattern: string, opts: { from?: string } = {}): Promise<string[]> {\n const re = globToRegExp(this.resolve(pattern));\n return (await this.walk(opts.from ?? \".\")).filter((path) => re.test(path));\n }\n\n /**\n * Delete metadata records no longer reachable from the root.\n *\n * These accumulate because every write touches exactly one record: if two\n * tabs edit the same directory, last-writer-wins at the personal space can\n * leave a child whose parent entry lost the race. Unreachable is harmless —\n * it is invisible and undecryptable-by-nobody — but it costs storage, so\n * this reclaims it.\n *\n * Deliberately explicit, never automatic: a sweep racing another tab's\n * in-flight write could delete a record that is about to be referenced.\n * Run it when the filesystem is idle.\n */\n async sweep(opts: { force?: boolean } = {}): Promise<{ removed: string[] }> {\n const root = await this.root();\n const reachable = new Set<string>();\n const visit = async (dir: OpenDir): Promise<void> => {\n // `reachable` was already the visited set - it just was not being\n // TESTED before recursing, so a cycle looped forever. Here the\n // consequence would have been worse than a hang: sweep decides what\n // to delete, and it never got as far as deciding.\n if (reachable.has(dirKey(dir.id))) return;\n reachable.add(dirKey(dir.id));\n for (const entry of Object.values(dir.node.entries)) {\n if (entry.kind === \"dir\") {\n await visit(await this.openDirById(entry.id, fromBase64(entry.key)));\n } else {\n reachable.add(historyKey(entry.id));\n }\n }\n };\n await visit(root);\n\n // Only ever consider OUR records: the personal space is shared with\n // chat keys, space keys and the legacy file mirror, and a sweep that\n // reached beyond its own namespace would be a data-loss bug.\n const mine = (await this.deps.store.list()).filter((k) => /^vfs\\/[dh]\\//.test(k));\n const orphans = mine.filter((k) => !reachable.has(k));\n\n // A root that read as EMPTY while orphans exist is the shape of a failed\n // load, not of a fresh filesystem — deleting here would wipe a tree we\n // merely failed to reach. Refuse unless the caller insists.\n const rootEmpty = Object.keys(root.node.entries).length === 0;\n if (rootEmpty && orphans.length && !opts.force) {\n throw new VfsConflictError(\n `refusing to sweep ${orphans.length} record(s) with an empty root — ` +\n \"this looks like a failed load rather than an empty filesystem; pass { force: true } if it really is empty\",\n );\n }\n\n for (const key of orphans) await this.deps.store.delete(key).catch(() => {});\n return { removed: orphans };\n }\n\n // ---- history ------------------------------------------------------------\n\n /** Prior versions of a file, newest first. One record fetch. */\n async history(path: string): Promise<Array<{ size: number; mtime: number }>> {\n const entry = await this.expectFile(path);\n const record = await this.readHistory(await this.openDir(dirname(path)), entry.id);\n return record.versions.map(({ size, mtime }) => ({ size, mtime }));\n }\n\n /**\n * Restore a prior version, where 0 is the most recent one.\n *\n * The current version is pushed onto history first, so restoring is itself\n * undoable rather than a one-way door.\n */\n async restore(path: string, index = 0): Promise<VfsStat> {\n const target = this.resolve(path);\n const name = basename(target);\n const parent = await this.openDir(dirname(target));\n const entry = parent.node.entries[name];\n if (!entry || entry.kind !== \"file\") throw new VfsNotFoundError(target);\n\n const record = await this.readHistory(parent, entry.id);\n const version = record.versions[index];\n if (!version) throw new VfsNotFoundError(`${target} version ${index}`);\n\n const versions = await this.pushHistory(parent, entry.id, entry);\n const restored: FileEntry = {\n kind: \"file\",\n id: entry.id,\n manifest: version.manifest,\n size: version.size,\n mtime: Date.now(),\n versions,\n };\n await this.mutate(parent, (node) => {\n node.entries[name] = restored;\n });\n return toStat(target, name, restored);\n }\n\n // ---- internals ----------------------------------------------------------\n\n private async expectFile(path: string): Promise<FileEntry> {\n const found = await this.find(path);\n if (!found) throw new VfsNotFoundError(this.resolve(path));\n if (found.entry.kind !== \"file\") throw new VfsConflictError(`${this.resolve(path)} is a directory`);\n return found.entry;\n }\n\n /** Resolve a path to its entry, or null. Root has no entry of its own. */\n private async find(path: string): Promise<{ name: string; entry: Entry } | null> {\n const target = this.resolve(path);\n if (target === \"/\") return null;\n const parent = await this.openDirOrNull(dirname(target));\n if (!parent) return null;\n const name = basename(target);\n const entry = parent.node.entries[name];\n return entry ? { name, entry } : null;\n }\n\n private async root(): Promise<OpenDir> {\n const seed = this.deps.seed();\n if (!seed) throw new VfsLockedError();\n if (!this.rootKey) this.rootKey = await deriveRootKey(seed);\n return this.openDirById(ROOT_ID, this.rootKey);\n }\n\n /** Open a directory by path, creating nothing. Throws if it is missing. */\n private async openDir(path: string): Promise<OpenDir> {\n const dir = await this.openDirOrNull(path);\n if (!dir) throw new VfsNotFoundError(this.resolve(path));\n return dir;\n }\n\n private async openDirOrNull(path: string): Promise<OpenDir | null> {\n let dir = await this.root();\n for (const name of segments(this.resolve(path))) {\n const entry: Entry | undefined = dir.node.entries[name];\n if (!entry || entry.kind !== \"dir\") return null;\n dir = await this.openDirById(entry.id, fromBase64(entry.key));\n }\n return dir;\n }\n\n private openDirById(id: string, key: Uint8Array): Promise<OpenDir> {\n const hit = this.cache.get(id);\n if (hit) return hit;\n\n // The PROMISE goes in the cache, not the resolved value.\n //\n // Reading a project means resolving hundreds of paths that share the\n // same handful of directories. Caching only the settled value leaves\n // every concurrent reader to miss and fire its own request for the same\n // record — which is how loading one project turned into thousands of\n // identical `vfs/d/<id>` fetches, most of them in flight at once.\n const pending = (async () => {\n const raw = await this.deps.store.get(dirKey(id));\n // An absent record is an EMPTY directory, not an error: the root\n // exists before anything has been written to it, and a directory is\n // created by its parent naming it rather than by its own record\n // appearing.\n const node = (await unseal<DirNode>(key, raw)) ?? { v: 1, entries: {}, mtime: Date.now() };\n return { id, key, node } satisfies OpenDir;\n })().catch((err) => {\n // A failed read must not be remembered, or one blip poisons the\n // directory for the life of the session.\n if (this.cache.get(id) === pending) this.cache.delete(id);\n throw err;\n });\n\n this.cache.set(id, pending);\n return pending;\n }\n\n /** Apply an edit to a directory record and persist it. */\n private async mutate(dir: OpenDir, edit: (node: DirNode) => void): Promise<void> {\n edit(dir.node);\n dir.node.mtime = Date.now();\n await this.deps.store.put(dirKey(dir.id), await seal(dir.key, dir.node));\n this.cache.set(dir.id, Promise.resolve(dir));\n }\n\n private async createDir(parentPath: string, name: string): Promise<void> {\n assertValidName(name);\n const parent = await this.openDir(parentPath);\n const entry: DirEntry = { kind: \"dir\", id: newId(), key: toBase64(newDirKey()), mtime: Date.now() };\n await this.mutate(parent, (node) => {\n node.entries[name] = entry;\n });\n }\n\n /** Recursively remove a subtree's records. Best-effort: unreachable ≠ fatal. */\n private async purge(dir: OpenDir, seen = new Set<string>()): Promise<void> {\n // A record that references an ancestor would otherwise recurse forever:\n // the id is only removed from the cache AFTER the loop, so re-entering\n // it hits the same cached record every time.\n if (seen.has(dir.id)) return;\n seen.add(dir.id);\n for (const entry of Object.values(dir.node.entries)) {\n if (entry.kind === \"dir\") {\n await this.purge(await this.openDirById(entry.id, fromBase64(entry.key)), seen);\n } else {\n await this.releaseFile(dir, entry);\n }\n }\n this.cache.delete(dir.id);\n await this.deps.store.delete(dirKey(dir.id)).catch(() => {});\n }\n\n /**\n * Deep-copy an entry. Files reuse their manifest (no bytes move); each\n * directory gets a fresh id and key, so the copy is independent of the\n * original — writing into one must never appear in the other.\n */\n private async cloneEntry(entry: Entry, seen = new Set<string>()): Promise<Entry> {\n if (entry.kind === \"file\") {\n // Same bytes, second owner: take a reference so deleting either one\n // leaves the other readable.\n await this.deps.content.retain(entry.manifest);\n return { kind: \"file\", id: newId(), manifest: entry.manifest, size: entry.size, mtime: Date.now(), versions: 0 };\n }\n // The most expensive walker to leave unguarded: it mints a NEW id, key\n // and stored record at every level, so a cyclic tree does not merely\n // hang - it writes records to the store, and to the user's bill, in an\n // unbounded loop.\n if (seen.has(entry.id) || seen.size > MAX_DEPTH) {\n throw new VfsConflictError(\"VFS: refusing to copy a directory that contains a cycle\");\n }\n seen.add(entry.id);\n const source = await this.openDirById(entry.id, fromBase64(entry.key));\n const clone: DirEntry = { kind: \"dir\", id: newId(), key: toBase64(newDirKey()), mtime: Date.now() };\n const node: DirNode = { v: 1, entries: {}, mtime: Date.now() };\n for (const [name, child] of Object.entries(source.node.entries)) {\n // Names are validated on read everywhere else; a copy must not be\n // the way a bad one is carried into a fresh record.\n if (!isSafeName(name)) {\n this.warn(`skipping entry with an unusable name while copying`);\n continue;\n }\n node.entries[name] = await this.cloneEntry(child, seen);\n }\n const open: OpenDir = { id: clone.id, key: fromBase64(clone.key), node };\n await this.deps.store.put(dirKey(open.id), await seal(open.key, node));\n this.cache.set(open.id, Promise.resolve(open));\n return clone;\n }\n\n /**\n * Let go of a file's bytes: the current manifest and every retained\n * version, then the history record itself.\n */\n private async releaseFile(parent: OpenDir, entry: FileEntry): Promise<void> {\n const record = await this.readHistory(parent, entry.id).catch(() => ({ v: 1, versions: [] } as HistoryRecord));\n const manifests = [entry.manifest, ...record.versions.map((v) => v.manifest)];\n for (const manifest of manifests) await this.deps.content.release(manifest).catch(() => {});\n await this.deps.store.delete(historyKey(entry.id)).catch(() => {});\n }\n\n private async readHistory(parent: OpenDir, fileId: string): Promise<HistoryRecord> {\n const raw = await this.deps.store.get(historyKey(fileId));\n return (await unseal<HistoryRecord>(parent.key, raw)) ?? { v: 1, versions: [] };\n }\n\n /** Push `entry` onto its history record. Returns the new version count. */\n private async pushHistory(parent: OpenDir, fileId: string, entry: FileEntry): Promise<number> {\n const record = await this.readHistory(parent, fileId);\n record.versions.unshift({ manifest: entry.manifest, size: entry.size, mtime: entry.mtime });\n // Bounded, because this is a single stored value. Unchanged chunks are\n // deduped by the content-addressed shard store, so the cost of keeping\n // versions is this record's own growth — which is what the cap bounds.\n const evicted = record.versions.slice(this.historyLimit);\n record.versions = record.versions.slice(0, this.historyLimit);\n // A version that falls off the end is unreachable — release its shards\n // or the cap bounds the record's size while the storage grows forever.\n for (const v of evicted) await this.deps.content.release(v.manifest).catch(() => {});\n await this.deps.store.put(historyKey(fileId), await seal(parent.key, record));\n return record.versions.length;\n }\n}\n\nfunction toStat(path: string, name: string, entry: Entry): VfsStat {\n return {\n path,\n name,\n kind: entry.kind,\n size: entry.kind === \"file\" ? entry.size : 0,\n mtime: entry.mtime,\n versions: entry.kind === \"file\" ? (entry.versions ?? 0) : 0,\n };\n}\n\n/** Directories first, then alphabetical — what every file explorer does. */\nfunction byDirsThenName(a: VfsStat, b: VfsStat): number {\n if (a.kind !== b.kind) return a.kind === \"dir\" ? -1 : 1;\n return a.name.localeCompare(b.name);\n}\n","/**\n * Content addressing for repository objects.\n *\n * The hash must depend only on MEANING, never on serialisation accidents — two\n * clients that build the same tree have to agree on its hash, or history forks\n * for no reason. So keys are sorted and the encoding is fixed here rather than\n * left to `JSON.stringify`'s insertion order.\n */\n\n/** Canonical JSON: object keys sorted, recursively. */\nexport function canonical(value: unknown): string {\n if (value === null || typeof value !== \"object\") return JSON.stringify(value) ?? \"null\";\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(\",\")}}`;\n}\n\n/** SHA-256 of an object's canonical form, hex. */\nexport async function hashObject(value: unknown): Promise<string> {\n const bytes = new TextEncoder().encode(canonical(value));\n const digest = await crypto.subtle.digest(\"SHA-256\", bytes as BufferSource);\n return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n","/**\n * Three-way line merge.\n *\n * Given a common ancestor and two descendants, produce the combined text — or\n * report the regions where both sides changed the same lines differently.\n *\n * The server cannot do any of this: it holds ciphertext and cannot compare\n * versions, so merging is entirely a client concern and has to be exact here.\n */\n\nexport interface MergeRegionConflict {\n /** 1-based line where the conflict begins in the merged output. */\n line: number;\n ours: string[];\n theirs: string[];\n}\n\nexport interface Merge3Result {\n lines: string[];\n conflicts: MergeRegionConflict[];\n}\n\n/**\n * Longest common subsequence, as a list of matched index pairs.\n *\n * Classic dynamic programming. Fine for source files; a file with hundreds of\n * thousands of lines would want a smarter algorithm, and would also be a strange\n * thing to merge.\n */\nfunction lcs(a: string[], b: string[]): Array<[number, number]> {\n const n = a.length;\n const m = b.length;\n const table: number[][] = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));\n for (let i = n - 1; i >= 0; i--) {\n for (let j = m - 1; j >= 0; j--) {\n table[i][j] = a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]);\n }\n }\n const pairs: Array<[number, number]> = [];\n let i = 0;\n let j = 0;\n while (i < n && j < m) {\n if (a[i] === b[j]) {\n pairs.push([i, j]);\n i++;\n j++;\n } else if (table[i + 1][j] >= table[i][j + 1]) i++;\n else j++;\n }\n return pairs;\n}\n\n/**\n * Lines of `base` that BOTH sides left untouched.\n *\n * These are the anchors the merge is built around: between two consecutive\n * anchors, each side has some (possibly empty) replacement, and comparing those\n * replacements is the entire decision.\n */\nfunction stableAnchors(base: string[], ours: string[], theirs: string[]): Array<[number, number, number]> {\n const ourMatch = new Map(lcs(base, ours));\n const theirMatch = new Map(lcs(base, theirs));\n const anchors: Array<[number, number, number]> = [];\n for (let b = 0; b < base.length; b++) {\n const o = ourMatch.get(b);\n const t = theirMatch.get(b);\n if (o !== undefined && t !== undefined) anchors.push([b, o, t]);\n }\n return anchors;\n}\n\nconst same = (a: string[], b: string[]): boolean => a.length === b.length && a.every((x, i) => x === b[i]);\n\n/**\n * Merge `ours` and `theirs` over their common ancestor `base`.\n *\n * A region where only one side changed takes that side. A region where both\n * made the SAME change takes it once — two people fixing the same typo is not a\n * conflict. Only genuinely divergent edits conflict.\n */\nexport function merge3(base: string[], ours: string[], theirs: string[]): Merge3Result {\n const anchors = stableAnchors(base, ours, theirs);\n const out: string[] = [];\n const conflicts: MergeRegionConflict[] = [];\n\n let b = 0;\n let o = 0;\n let t = 0;\n\n const settle = (ourSlice: string[], theirSlice: string[], baseSlice: string[]): void => {\n if (same(ourSlice, theirSlice)) {\n out.push(...ourSlice); // identical edits, or no edit\n } else if (same(ourSlice, baseSlice)) {\n out.push(...theirSlice); // only they changed it\n } else if (same(theirSlice, baseSlice)) {\n out.push(...ourSlice); // only we changed it\n } else {\n conflicts.push({ line: out.length + 1, ours: ourSlice, theirs: theirSlice });\n out.push(...ourSlice); // markers are added by the caller\n }\n };\n\n for (const [ab, ao, at] of anchors) {\n settle(ours.slice(o, ao), theirs.slice(t, at), base.slice(b, ab));\n out.push(base[ab]);\n b = ab + 1;\n o = ao + 1;\n t = at + 1;\n }\n settle(ours.slice(o), theirs.slice(t), base.slice(b));\n\n return { lines: out, conflicts };\n}\n\n/**\n * Merge to text, writing conflict markers where the sides diverged.\n *\n * Markers rather than a bespoke format: they are what every developer already\n * knows how to resolve, and resolving becomes ordinary editing.\n */\nexport function merge3Text(\n base: string,\n ours: string,\n theirs: string,\n labels: { ours: string; theirs: string } = { ours: \"ours\", theirs: \"theirs\" },\n): { text: string; conflicted: boolean } {\n const split = (s: string) => (s === \"\" ? [] : s.split(\"\\n\"));\n const anchors = stableAnchors(split(base), split(ours), split(theirs));\n const B = split(base);\n const O = split(ours);\n const T = split(theirs);\n\n const out: string[] = [];\n let conflicted = false;\n let b = 0;\n let o = 0;\n let t = 0;\n\n const settle = (ourSlice: string[], theirSlice: string[], baseSlice: string[]): void => {\n if (same(ourSlice, theirSlice)) out.push(...ourSlice);\n else if (same(ourSlice, baseSlice)) out.push(...theirSlice);\n else if (same(theirSlice, baseSlice)) out.push(...ourSlice);\n else {\n conflicted = true;\n out.push(`<<<<<<< ${labels.ours}`, ...ourSlice, \"=======\", ...theirSlice, `>>>>>>> ${labels.theirs}`);\n }\n };\n\n for (const [ab, ao, at] of anchors) {\n settle(O.slice(o, ao), T.slice(t, at), B.slice(b, ab));\n out.push(B[ab]);\n b = ab + 1;\n o = ao + 1;\n t = at + 1;\n }\n settle(O.slice(o), T.slice(t), B.slice(b));\n\n return { text: out.join(\"\\n\"), conflicted };\n}\n","/**\n * Object model for version control over the VFS. See `docs/VCS_DESIGN.md`.\n *\n * Two spaces, deliberately: the WORKING TREE (`/apps/<slug>`) uses mutable\n * random directory ids so a file write touches one record; the REPOSITORY\n * (here) is content-addressed so a commit means the same thing forever. Git\n * makes the same split, for the same reason.\n */\nimport type { FileManifest } from \"../storage/types\";\n\n/** A file in a commit. The manifest IS the content — there are no blob objects. */\nexport interface TreeFile {\n kind: \"file\";\n manifest: FileManifest;\n size: number;\n}\n\n/** A subdirectory, by the hash of its own tree object. */\nexport interface TreeDir {\n kind: \"tree\";\n hash: string;\n}\n\nexport type TreeEntry = TreeFile | TreeDir;\n\n/**\n * One directory, frozen.\n *\n * Addressed by the hash of its canonical form, so an unchanged directory has\n * the same hash in every commit containing it — a deep project costs one new\n * tree per CHANGED directory, not one per commit.\n */\nexport interface Tree {\n v: 1;\n entries: Record<string, TreeEntry>;\n}\n\nexport interface Commit {\n v: 1;\n /** Hash of the root tree. */\n tree: string;\n /**\n * Ancestors. An ARRAY because a merge has two; the first commit has none.\n * Order matters: `parents[0]` is the branch being committed onto.\n */\n parents: string[];\n message: string;\n author: string;\n at: number;\n}\n\n/** Where a branch points, or a specific commit when detached. */\nexport type Head = { branch: string } | { detached: string };\n\n/** A single change between two trees. */\nexport interface Change {\n path: string;\n kind: \"added\" | \"removed\" | \"modified\";\n}\n\n/** A path the merge could not settle on its own. */\nexport interface Conflict {\n path: string;\n /** `binary` cannot be merged at all — the user picks a side. */\n reason: \"content\" | \"binary\" | \"modify-delete\";\n}\n\nexport interface MergeResult {\n /** \"up-to-date\" and \"fast-forward\" do no three-way work at all. */\n kind: \"up-to-date\" | \"fast-forward\" | \"merged\" | \"conflicted\";\n commit?: string;\n conflicts: Conflict[];\n}\n\nexport interface LogEntry {\n hash: string;\n message: string;\n author: string;\n at: number;\n parents: string[];\n}\n\n/** Storage keys. Namespaced per project so repositories cannot collide. */\nexport const objectKey = (slug: string, hash: string): string => `vcs/${slug}/obj/${hash}`;\nexport const refKey = (slug: string, name: string): string => `vcs/${slug}/refs/${name}`;\nexport const headKey = (slug: string): string => `vcs/${slug}/HEAD`;\nexport const refsIndexKey = (slug: string): string => `vcs/${slug}/refs`;\n/** An in-progress merge: what to make the second parent when it is committed. */\nexport const mergeKey = (slug: string): string => `vcs/${slug}/MERGE`;\n\nexport const DEFAULT_BRANCH = \"main\";\n\nexport class VcsError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"VcsError\";\n }\n}\n","/**\n * `client.vcs` — version control for a project in the VFS.\n *\n * Phase 1: objects, commit, log, checkout, diff. Branches and merge build on\n * this; see `docs/VCS_DESIGN.md` for the whole shape and for why the repository\n * is content-addressed while the working tree is not.\n */\nimport type { VfsNamespace } from \"../vfs/VfsNamespace\";\nimport type { VfsStore } from \"../vfs/types\";\nimport { deriveRepoKey, seal, unseal } from \"../vfs/recordCipher\";\nimport { hashObject } from \"./hash\";\nimport { merge3Text } from \"./merge3\";\nimport {\n DEFAULT_BRANCH,\n VcsError,\n headKey,\n mergeKey,\n objectKey,\n refKey,\n refsIndexKey,\n type Change,\n type Commit,\n type Conflict,\n type Head,\n type LogEntry,\n type MergeResult,\n type Tree,\n type TreeEntry,\n type TreeFile,\n} from \"./types\";\n\nexport interface VcsNamespaceDeps {\n vfs: VfsNamespace;\n store: VfsStore;\n /** The key repository objects are sealed with — the project's own. */\n key: () => Promise<Uint8Array>;\n /** Who to record as the author. */\n author: () => string;\n}\n\n/** A project's repository. One per `/apps/<slug>`. */\n/**\n * Types never worth attempting a three-way merge on.\n *\n * NOT application/octet-stream: that is the UNKNOWN case, which is what every\n * extensionless text file gets labelled, so it must reach the content sniff\n * rather than being rejected on the label.\n */\nconst BINARY_TYPE = /^(image|audio|video|font)\\/|^application\\/(wasm|zip|pdf|x-tar|gzip)/;\n\n/**\n * Does this look like text a person could resolve conflict markers in?\n *\n * A NUL byte is the classic tell and the one git uses — no textual encoding we\n * care about produces one. Invalid UTF-8 is the other: decoding it would\n * corrupt the file on write-back even if the merge itself succeeded.\n */\nfunction looksTextual(bytes: Uint8Array): boolean {\n if (bytes.includes(0)) return false;\n try {\n new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Compare two path → entry maps into a change list. */\nfunction comparePaths(before: Map<string, TreeFile>, after: Map<string, TreeFile>): Change[] {\n const changes: Change[] = [];\n for (const [path, entry] of after) {\n const was = before.get(path);\n if (!was) changes.push({ path, kind: \"added\" });\n else if (was.manifest.id !== entry.manifest.id) changes.push({ path, kind: \"modified\" });\n }\n for (const path of before.keys()) if (!after.has(path)) changes.push({ path, kind: \"removed\" });\n return changes.sort((a, b) => (a.path < b.path ? -1 : 1));\n}\n\nexport class Repo {\n constructor(\n private readonly slug: string,\n private readonly deps: VcsNamespaceDeps,\n ) {}\n\n private get root(): string {\n return `/apps/${this.slug}`;\n }\n\n // ---- objects ------------------------------------------------------------\n\n /** Store an object, returning its hash and whether it was new. */\n private async put(value: unknown): Promise<{ hash: string; created: boolean }> {\n const hash = await hashObject(value);\n // Content-addressed, so re-writing an identical object is a no-op —\n // worth skipping because an unchanged directory is written on every\n // commit that touches any of its siblings.\n const existing = await this.deps.store.get(objectKey(this.slug, hash));\n if (existing) return { hash, created: false };\n await this.deps.store.put(objectKey(this.slug, hash), await seal(await this.deps.key(), value));\n return { hash, created: true };\n }\n\n private async get<T>(hash: string): Promise<T> {\n const raw = await this.deps.store.get(objectKey(this.slug, hash));\n const value = raw ? await unseal<T>(await this.deps.key(), raw) : null;\n if (!value) throw new VcsError(`object ${hash.slice(0, 8)} is missing from this repository`);\n return value;\n }\n\n // ---- refs ---------------------------------------------------------------\n\n private async head(): Promise<Head> {\n const raw = await this.deps.store.get(headKey(this.slug));\n const value = raw ? await unseal<Head>(await this.deps.key(), raw) : null;\n return value ?? { branch: DEFAULT_BRANCH };\n }\n\n private async setHead(head: Head): Promise<void> {\n await this.deps.store.put(headKey(this.slug), await seal(await this.deps.key(), head));\n }\n\n private async readRef(name: string): Promise<string | null> {\n const raw = await this.deps.store.get(refKey(this.slug, name));\n return raw ? await unseal<{ commit: string }>(await this.deps.key(), raw).then((v) => v?.commit ?? null) : null;\n }\n\n private async writeRef(name: string, commit: string): Promise<void> {\n await this.deps.store.put(refKey(this.slug, name), await seal(await this.deps.key(), { commit }));\n // The personal space has no prefix listing, so branches are tracked in\n // an index. Kept append-only-ish: losing a name here loses the branch.\n const names = new Set(await this.branches());\n names.add(name);\n await this.deps.store.put(\n refsIndexKey(this.slug),\n await seal(await this.deps.key(), { names: [...names].sort() }),\n );\n }\n\n /** Every branch name in this repository. */\n async branches(): Promise<string[]> {\n const raw = await this.deps.store.get(refsIndexKey(this.slug));\n const value = raw ? await unseal<{ names: string[] }>(await this.deps.key(), raw) : null;\n return value?.names ?? [];\n }\n\n /** The commit HEAD resolves to, or null in an empty repository. */\n async current(): Promise<string | null> {\n const head = await this.head();\n return \"detached\" in head ? head.detached : this.readRef(head.branch);\n }\n\n // ---- commit -------------------------------------------------------------\n\n /**\n * Freeze the working tree as a commit.\n *\n * Trees are written bottom-up so a directory's hash is known before its\n * parent references it. Nothing is written to the shard store: file entries\n * carry the manifest the VFS already holds.\n */\n async commit(message: string, parents?: string[]): Promise<string> {\n if (!message.trim()) throw new VcsError(\"a commit needs a message\");\n const tree = await this.writeTree(this.root);\n const parent = await this.current();\n\n // Finish an interrupted merge: the recorded other side becomes the\n // second parent. Losing this would produce a single-parent commit, and\n // the merge would look as though it never happened — the branches would\n // still appear diverged.\n const pending = parents ? null : await this.pendingMerge();\n const resolved = parents ?? (pending ? [parent!, pending.theirs] : parent ? [parent] : []);\n\n if (!parents && !pending && parent) {\n const previous = await this.get<Commit>(parent);\n // An empty commit is almost always a mistake — the user believes\n // they saved something they did not.\n if (previous.tree === tree) throw new VcsError(\"nothing to commit — the project is unchanged\");\n }\n\n const commit: Commit = {\n v: 1,\n tree,\n parents: resolved,\n message: message.trim(),\n author: this.deps.author(),\n at: Date.now(),\n };\n const { hash } = await this.put(commit);\n await this.advance(hash);\n if (pending) await this.deps.store.delete(mergeKey(this.slug)).catch(() => {});\n return hash;\n }\n\n /** Move whatever HEAD points at onto a new commit. */\n private async advance(hash: string): Promise<void> {\n const head = await this.head();\n if (\"detached\" in head) await this.setHead({ detached: hash });\n else await this.writeRef(head.branch, hash);\n }\n\n /** The other side of a merge that stopped for conflicts, if any. */\n async pendingMerge(): Promise<{ theirs: string; name: string } | null> {\n const raw = await this.deps.store.get(mergeKey(this.slug));\n return raw ? await unseal<{ theirs: string; name: string }>(await this.deps.key(), raw) : null;\n }\n\n /** Write a directory and everything under it, returning the tree's hash. */\n private async writeTree(path: string): Promise<string> {\n const entries: Record<string, TreeEntry> = {};\n for (const entry of await this.deps.vfs.list(path)) {\n if (entry.kind === \"dir\") {\n entries[entry.name] = { kind: \"tree\", hash: await this.writeTree(entry.path) };\n } else {\n const stat = await this.deps.vfs.statManifest(entry.path);\n entries[entry.name] = { kind: \"file\", manifest: stat.manifest, size: entry.size };\n }\n }\n const { hash, created } = await this.put({ v: 1, entries } satisfies Tree);\n\n // A NEW tree means this directory's contents are newly recorded, so the\n // repository takes its own reference to their content. Without it, a\n // later working-tree delete frees shards the commit still needs and the\n // history becomes unreadable.\n //\n // Retaining per new tree rather than per changed FILE slightly\n // over-retains — an unchanged file in a directory whose sibling changed\n // gets a second reference. That errs towards keeping content, which is\n // the correct direction to err in.\n if (created) {\n for (const entry of Object.values(entries)) {\n if (entry.kind === \"file\") await this.deps.vfs.retainManifest(entry.manifest);\n }\n }\n return hash;\n }\n\n // ---- history ------------------------------------------------------------\n\n /** Commits reachable from HEAD, newest first. */\n async log(limit = 50): Promise<LogEntry[]> {\n const start = await this.current();\n if (!start) return [];\n\n const out: LogEntry[] = [];\n const seen = new Set<string>();\n // Breadth-first over parents so a merge's two sides both appear, and\n // `seen` keeps a diamond from listing the shared history twice.\n const queue = [start];\n while (queue.length && out.length < limit) {\n const hash = queue.shift()!;\n if (seen.has(hash)) continue;\n seen.add(hash);\n const commit = await this.get<Commit>(hash);\n out.push({\n hash,\n message: commit.message,\n author: commit.author,\n at: commit.at,\n parents: commit.parents,\n });\n queue.push(...commit.parents);\n }\n return out.sort((a, b) => b.at - a.at);\n }\n\n // ---- diff ---------------------------------------------------------------\n\n /**\n * What changed between two commits.\n *\n * Identical subtree hashes prune the walk: an untouched directory is one\n * comparison regardless of how much is inside it. That is the payoff for\n * content-addressing the trees.\n */\n async diff(fromHash: string | null, toHash: string): Promise<Change[]> {\n const from = fromHash ? (await this.get<Commit>(fromHash)).tree : null;\n const to = (await this.get<Commit>(toHash)).tree;\n const changes: Change[] = [];\n await this.diffTrees(from, to, \"\", changes);\n return changes.sort((a, b) => (a.path < b.path ? -1 : 1));\n }\n\n private async diffTrees(\n fromHash: string | null,\n toHash: string | null,\n prefix: string,\n out: Change[],\n ): Promise<void> {\n if (fromHash === toHash) return; // identical subtrees: nothing below can differ\n const from = fromHash ? await this.get<Tree>(fromHash) : { v: 1 as const, entries: {} };\n const to = toHash ? await this.get<Tree>(toHash) : { v: 1 as const, entries: {} };\n\n for (const name of new Set([...Object.keys(from.entries), ...Object.keys(to.entries)])) {\n const a = from.entries[name];\n const b = to.entries[name];\n const path = `${prefix}/${name}`;\n\n if (a && b && a.kind === \"tree\" && b.kind === \"tree\") {\n await this.diffTrees(a.hash, b.hash, path, out);\n } else if (a?.kind === \"tree\" || b?.kind === \"tree\") {\n // A directory replaced by a file (or the reverse) — recurse both\n // sides so every affected path is reported, not just the name.\n await this.diffTrees(a?.kind === \"tree\" ? a.hash : null, b?.kind === \"tree\" ? b.hash : null, path, out);\n if (a?.kind === \"file\") out.push({ path, kind: \"removed\" });\n if (b?.kind === \"file\") out.push({ path, kind: \"added\" });\n } else if (!a && b) {\n out.push({ path, kind: \"added\" });\n } else if (a && !b) {\n out.push({ path, kind: \"removed\" });\n } else if (a?.kind === \"file\" && b?.kind === \"file\" && a.manifest.id !== b.manifest.id) {\n out.push({ path, kind: \"modified\" });\n }\n }\n }\n\n // ---- checkout -----------------------------------------------------------\n\n /**\n * Replace the working tree with a commit's.\n *\n * Moves no file content: entries carry manifests the shard store already\n * holds, so this rewrites directory records only.\n */\n /**\n * What has changed since the last commit.\n *\n * Compares the WORKING TREE against HEAD without writing any objects: the\n * common case is answering \"anything to commit?\", and a `status` that\n * quietly stored a tree object every time would litter the repository with\n * trees for states nobody chose to keep.\n */\n async status(): Promise<Change[]> {\n const head = await this.current();\n const before = head ? await this.filesOf(head) : new Map<string, TreeFile>();\n const after = await this.workingFiles();\n return comparePaths(before, after);\n }\n\n /** The working tree as a path → entry map, mirroring `filesOf`. */\n private async workingFiles(): Promise<Map<string, TreeFile>> {\n const out = new Map<string, TreeFile>();\n for (const abs of await this.deps.vfs.walk(this.root)) {\n const stat = await this.deps.vfs.statManifest(abs);\n out.set(abs.slice(this.root.length), { kind: \"file\", manifest: stat.manifest, size: stat.size });\n }\n return out;\n }\n\n /**\n * Turn what a person typed into a commit hash.\n *\n * Accepts a branch name, `HEAD`, a full or abbreviated hash, and trailing\n * `^` / `~n` to walk back through parents — so `show abc123^` means \"the\n * commit before that one\" the way anyone who has used git expects.\n */\n async resolve(rev: string): Promise<string> {\n const m = /^(.*?)((?:\\^|~\\d+)*)$/.exec(rev.trim());\n if (!m) throw new VcsError(`cannot understand \"${rev}\"`);\n const [, base, steps] = m;\n\n let hash: string | null = null;\n if (!base || base === \"HEAD\") hash = await this.current();\n else if (await this.readRef(base)) hash = await this.readRef(base);\n else hash = await this.expand(base);\n if (!hash) throw new VcsError(`no commit matches \"${rev}\"`);\n\n for (const step of steps.match(/\\^|~\\d+/g) ?? []) {\n const back = step === \"^\" ? 1 : Number(step.slice(1));\n for (let i = 0; i < back; i++) {\n const parents: string[] = (await this.get<Commit>(hash!)).parents;\n if (!parents.length) throw new VcsError(`\"${rev}\" reaches past the first commit`);\n hash = parents[0]; // first parent: the branch you were on\n }\n }\n return hash!;\n }\n\n /** A hash prefix a person typed → the one commit it names. */\n private async expand(prefix: string): Promise<string | null> {\n if (!/^[0-9a-f]{4,}$/.test(prefix)) return null;\n const keys = await this.deps.store.list();\n const wanted = objectKey(this.slug, prefix);\n const hits = keys.filter((k) => k.startsWith(wanted));\n // Ambiguous is an error, not a coin toss — acting on the wrong commit\n // is exactly the kind of mistake version control exists to prevent.\n if (hits.length > 1) throw new VcsError(`\"${prefix}\" matches ${hits.length} objects — use more characters`);\n if (!hits.length) return null;\n const hash = hits[0].slice(objectKey(this.slug, \"\").length);\n // Objects include trees; only a commit is a valid revision.\n const object = await this.get<{ v: number; tree?: string }>(hash);\n return object && \"tree\" in object ? hash : null;\n }\n\n /**\n * Put one file back to the way it was in a commit.\n *\n * Scoped to a path on purpose — recovering one file you broke should not\n * mean rewinding everything else you have done since.\n */\n async restore(path: string, rev = \"HEAD\"): Promise<void> {\n const hash = await this.resolve(rev);\n const files = await this.filesOf(hash);\n const key = path.startsWith(this.root) ? path.slice(this.root.length) : path.startsWith(\"/\") ? path : `/${path}`;\n const entry = files.get(key);\n if (!entry) throw new VcsError(`${key} is not in ${rev}`);\n await this.deps.vfs.writeManifest(this.abs(key), entry.manifest, entry.size);\n }\n\n async checkout(commitHash: string, opts: { discardChanges?: boolean } = {}): Promise<void> {\n await this.guardWorkingTree(opts.discardChanges);\n await this.materialise(commitHash);\n // DETACHED on purpose: committing from a historical state must not\n // silently rewrite whichever branch you happened to be on. `switchTo`\n // is how you re-attach.\n await this.setHead({ detached: commitHash });\n }\n\n /** Make the working tree match a commit, leaving HEAD alone. */\n private async materialise(commitHash: string): Promise<void> {\n const commit = await this.get<Commit>(commitHash);\n const wanted = new Map<string, TreeFile>();\n await this.collect(commit.tree, \"\", wanted);\n\n // Remove what the commit does not have BEFORE writing what it does —\n // otherwise a file replaced by a directory of the same name collides.\n for (const abs of await this.deps.vfs.walk(this.root)) {\n const path = abs.slice(this.root.length);\n // keepContent: history still references these manifests.\n if (!wanted.has(path)) await this.deps.vfs.delete(abs, { keepContent: true }).catch(() => {});\n }\n for (const [path, entry] of wanted) {\n await this.deps.vfs.writeManifest(this.abs(path), entry.manifest, entry.size);\n }\n }\n\n /** Project-relative path → absolute VFS path. */\n private abs(path: string): string {\n return `${this.root}${path}`;\n }\n\n private async collect(\n treeHash: string,\n prefix: string,\n out: Map<string, TreeFile>,\n ): Promise<void> {\n const tree = await this.get<Tree>(treeHash);\n for (const [name, entry] of Object.entries(tree.entries)) {\n const path = `${prefix}/${name}`;\n if (entry.kind === \"tree\") await this.collect(entry.hash, path, out);\n else out.set(path, entry);\n }\n }\n\n // ---- branches -----------------------------------------------------------\n\n /** Create a branch at a commit (HEAD by default). Does not switch to it. */\n async branch(name: string, at?: string): Promise<string> {\n if (!/^[A-Za-z0-9][A-Za-z0-9._\\/-]*$/.test(name)) throw new VcsError(`\"${name}\" is not a usable branch name`);\n if (await this.readRef(name)) throw new VcsError(`branch \"${name}\" already exists`);\n const commit = at ?? (await this.current());\n if (!commit) throw new VcsError(\"cannot branch an empty repository — commit something first\");\n await this.writeRef(name, commit);\n return commit;\n }\n\n /**\n * Move onto a branch, bringing the working tree with it.\n *\n * Unlike {@link checkout}, this ATTACHES head: later commits advance the\n * branch. Checking out a bare commit deliberately does not, so that\n * committing from a historical state cannot silently rewrite a branch.\n */\n async switchTo(name: string, opts: { discardChanges?: boolean } = {}): Promise<void> {\n const commit = await this.readRef(name);\n if (!commit) throw new VcsError(`no branch named \"${name}\"`);\n await this.guardWorkingTree(opts.discardChanges);\n await this.materialise(commit);\n await this.setHead({ branch: name });\n }\n\n /**\n * Refuse to overwrite work that was never recorded.\n *\n * Moving between commits REPLACES the working tree, so uncommitted edits\n * are gone — and unlike an ordinary overwrite, the person did not ask for\n * anything to be written. Naming the files is the point: \"you have changes\"\n * with no list leaves them guessing what they are about to lose.\n */\n private async guardWorkingTree(discard?: boolean): Promise<void> {\n if (discard) return;\n const pending = await this.status();\n if (!pending.length) return;\n const names = pending.slice(0, 5).map((c) => c.path).join(\", \");\n const more = pending.length > 5 ? `, and ${pending.length - 5} more` : \"\";\n throw new VcsError(\n `${pending.length} uncommitted change(s) would be lost: ${names}${more}. ` +\n \"Commit them first, or pass { discardChanges: true } to throw them away.\",\n );\n }\n\n /** The branch HEAD is on, or null when detached. */\n async currentBranch(): Promise<string | null> {\n const head = await this.head();\n return \"detached\" in head ? null : head.branch;\n }\n\n // ---- merge --------------------------------------------------------------\n\n /**\n * Merge another branch into the current one.\n *\n * Every part of this is client-side by necessity: the server holds\n * ciphertext and cannot compare versions, so base, ours and theirs are all\n * fetched and decrypted here.\n */\n async merge(name: string, opts: { discardChanges?: boolean } = {}): Promise<MergeResult> {\n const theirs = await this.readRef(name);\n if (!theirs) throw new VcsError(`no branch named \"${name}\"`);\n // A merge writes to the working tree as freely as a switch does.\n await this.guardWorkingTree(opts.discardChanges);\n const ours = await this.current();\n if (!ours) throw new VcsError(\"nothing to merge into — commit something first\");\n if (ours === theirs) return { kind: \"up-to-date\", conflicts: [] };\n\n const base = await this.mergeBase(ours, theirs);\n if (base === theirs) return { kind: \"up-to-date\", conflicts: [] };\n if (base === ours) {\n // Fast-forward: our history is contained in theirs, so there is\n // nothing to combine — just move.\n await this.materialise(theirs);\n await this.advance(theirs);\n return { kind: \"fast-forward\", commit: theirs, conflicts: [] };\n }\n\n const [baseFiles, ourFiles, theirFiles] = await Promise.all([\n base ? this.filesOf(base) : new Map<string, TreeFile>(),\n this.filesOf(ours),\n this.filesOf(theirs),\n ]);\n\n const conflicts: Conflict[] = [];\n for (const path of new Set([...ourFiles.keys(), ...theirFiles.keys(), ...baseFiles.keys()])) {\n const b = baseFiles.get(path);\n const o = ourFiles.get(path);\n const t = theirFiles.get(path);\n const conflict = await this.settlePath(path, b, o, t);\n if (conflict) conflicts.push(conflict);\n }\n\n if (conflicts.length) {\n // Record what to merge with, so finishing is just: fix the files,\n // then commit. Losing this would silently produce a commit with one\n // parent, and the merge would appear never to have happened.\n await this.deps.store.put(mergeKey(this.slug), await seal(await this.deps.key(), { theirs, name }));\n return { kind: \"conflicted\", conflicts };\n }\n\n const commit = await this.commit(`Merge ${name}`, [ours, theirs]);\n return { kind: \"merged\", commit, conflicts: [] };\n }\n\n /** Decide one path. Returns a conflict when it cannot be settled. */\n private async settlePath(\n path: string,\n b: TreeFile | undefined,\n o: TreeFile | undefined,\n t: TreeFile | undefined,\n ): Promise<Conflict | null> {\n const id = (f?: TreeFile) => f?.manifest.id;\n if (id(o) === id(t)) return null; // already agree\n\n if (!o && !b && t) return this.take(path, t); // only they added it\n if (!t && !b && o) return null; // only we added it\n if (id(o) === id(b)) { // only they touched it\n if (!t) { await this.deps.vfs.delete(this.abs(path), { keepContent: true }).catch(() => {}); return null; }\n return this.take(path, t);\n }\n if (id(t) === id(b)) return null; // only we touched it\n\n // Both sides moved. A file one side deleted and the other edited is not\n // a merge decision a tool should make silently.\n if (!o || !t) return { path, reason: \"modify-delete\" };\n\n // Definitely-binary types are rejected WITHOUT reading them — merging\n // bytes line-by-line produces corruption, not a result, and these files\n // are exactly the large ones.\n if (BINARY_TYPE.test(o.manifest.type ?? \"\") || BINARY_TYPE.test(t.manifest.type ?? \"\")) {\n return { path, reason: \"binary\" };\n }\n\n const [baseBytes, ourBytes, theirBytes] = await Promise.all([\n b ? this.deps.vfs.readByManifest(b.manifest) : Promise.resolve(new Uint8Array()),\n this.deps.vfs.readByManifest(o.manifest),\n this.deps.vfs.readByManifest(t.manifest),\n ]);\n\n // Then judge by CONTENT, not by the declared type.\n //\n // The type is a hint we do not own: a content store may omit it, and\n // plenty of real text files carry no extension to derive one from\n // (Makefile, LICENSE, .gitignore, .env). Trusting it alone turned every\n // one of those into an unmergeable false conflict.\n if (![ourBytes, theirBytes, baseBytes].every(looksTextual)) return { path, reason: \"binary\" };\n\n const decode = (bytes: Uint8Array) => new TextDecoder().decode(bytes);\n const { text, conflicted } = merge3Text(decode(baseBytes), decode(ourBytes), decode(theirBytes));\n await this.deps.vfs.writeFile(this.abs(path), text);\n return conflicted ? { path, reason: \"content\" } : null;\n }\n\n private async take(path: string, entry: TreeFile): Promise<null> {\n await this.deps.vfs.writeManifest(this.abs(path), entry.manifest, entry.size);\n return null;\n }\n\n /**\n * The most recent commit reachable from both.\n *\n * Walks our ancestry into a set, then theirs breadth-first until it hits it —\n * so the first match is the nearest, which is what a three-way merge needs.\n */\n async mergeBase(a: string, b: string): Promise<string | null> {\n const ancestors = new Set<string>();\n const collect = async (start: string): Promise<void> => {\n const queue = [start];\n while (queue.length) {\n const hash = queue.shift()!;\n if (ancestors.has(hash)) continue;\n ancestors.add(hash);\n queue.push(...(await this.get<Commit>(hash)).parents);\n }\n };\n await collect(a);\n\n const queue = [b];\n const seen = new Set<string>();\n while (queue.length) {\n const hash = queue.shift()!;\n if (seen.has(hash)) continue;\n seen.add(hash);\n if (ancestors.has(hash)) return hash;\n queue.push(...(await this.get<Commit>(hash)).parents);\n }\n return null;\n }\n\n /** Every file in a commit, by path. */\n private async filesOf(commitHash: string): Promise<Map<string, TreeFile>> {\n const commit = await this.get<Commit>(commitHash);\n const out = new Map<string, TreeFile>();\n await this.collect(commit.tree, \"\", out);\n return out;\n }\n\n}\n\n/**\n * Version control over the VFS.\n *\n * One repository per project, addressed by slug — the same slug the VFS stores\n * that project's working tree under. `client.vcs.open(\"my-app\")` is the whole\n * entry point.\n */\nexport class VcsNamespace {\n private readonly repos = new Map<string, Repo>();\n\n constructor(private readonly deps: VcsNamespaceOptions) {}\n\n /** The repository for one project. Cheap and cached; creates nothing. */\n open(slug: string): Repo {\n let repo = this.repos.get(slug);\n if (!repo) {\n repo = new Repo(slug, {\n vfs: this.deps.vfs,\n store: this.deps.store,\n key: async () => {\n const seed = this.deps.seed();\n if (!seed) throw new VcsError(\"client.vcs: no session — sign in first.\");\n return deriveRepoKey(seed, slug);\n },\n author: this.deps.author,\n });\n this.repos.set(slug, repo);\n }\n return repo;\n }\n}\n\nexport interface VcsNamespaceOptions {\n vfs: VfsNamespace;\n store: VfsStore;\n /** The in-memory master seed, or null when locked. Read per call. */\n seed: () => Uint8Array | null;\n author: () => string;\n}\n","/**\n * `ChatKeyVault` — SDK-owned lifecycle for a member's long-lived ratchet/space\n * keypair (the connect `KeyStore` entry keyed by the member id / username).\n *\n * Historically each app hand-rolled this (see the web app's old\n * `personal/spaceLoader.ts`): generate a keypair at register, seed-wrap it, and\n * PUT it to the personal space; on login GET + unwrap + hydrate the `KeyStore`.\n * That scaffolding now lives here so ANY app gets a **stable** member keypair\n * across reloads for free — without which the member re-admits to every space on\n * every load and the group-key cache can never round-trip.\n *\n * Security invariant: the wrapping secret is the **master seed** (not the\n * password), so the blob survives password changes and unlocks under a passkey.\n * The seed is only ever held in memory (never persisted), so this vault can only\n * provision/rehydrate while the client is unlocked.\n */\n\nimport { KeyStore } from \"../crypto/KeyStore\";\nimport { wrapWithPassphrase, unwrapWithPassphrase, type WrappedPayload } from \"../crypto/PassphraseWrap\";\n\n/** Staging-only diagnostics: is the member keypair stable across reloads? */\nconst VAULT_DEBUG = (() => {\n try {\n return typeof location !== \"undefined\" && /(^|\\.)staging\\./.test(location.hostname);\n } catch {\n return false;\n }\n})();\nfunction vlog(msg: string): void {\n if (VAULT_DEBUG) console.info(`[muhkoo:vault] ${msg}`);\n}\n/** A short, stable fingerprint of the member's current keypair (ecdsa pub). */\nasync function fingerprint(memberId: string): Promise<string> {\n try {\n const raw = await KeyStore.getInstance().getRawEcdsaPublicKey(memberId);\n if (!raw) return \"none\";\n let s = 0;\n for (const b of raw) s = (s * 31 + b) >>> 0;\n return s.toString(16).padStart(8, \"0\");\n } catch {\n return \"err\";\n }\n}\n\n/** Opaque personal-space blob store (a `PersonalSpaceClient` or a kv-backed shim). */\nexport interface ChatKeyStore {\n get(key: string): Promise<WrappedPayload | null>;\n put(key: string, value: WrappedPayload): Promise<void>;\n}\n\n/** Personal-space key holding the seed-wrapped, dehydrated ratchet keypair. */\nexport const CHAT_KEYS_KEY = \"chat-keys\";\n\nexport class ChatKeyVault {\n constructor(private readonly store: ChatKeyStore) {}\n\n /**\n * Register-time: ensure a keypair exists for `memberId`, seed-wrap the\n * dehydrated form, and persist it to the personal space. Idempotent — reuses\n * an existing in-tab keypair rather than minting a second one.\n */\n async provision(memberId: string, seedSecret: string): Promise<void> {\n const ks = KeyStore.getInstance();\n if (!ks.getKeyPair(memberId)) {\n try {\n await ks.generateOwnKeyPair(memberId);\n } catch (e) {\n if (!String((e as Error)?.message ?? e).includes(\"already exists\")) throw e;\n }\n }\n const dehydrated = await ks.dehydrateKeyPair(memberId);\n const plaintext = new TextEncoder().encode(JSON.stringify(dehydrated));\n await this.store.put(CHAT_KEYS_KEY, await wrapWithPassphrase(seedSecret, plaintext));\n vlog(`provision: minted+persisted keypair fp=${await fingerprint(memberId)}`);\n }\n\n /**\n * Sign-in / unlock time: fetch the wrapped blob, unwrap with the seed, and\n * hydrate the `KeyStore` — restoring the SAME keypair the member had before.\n * Returns `true` when a keypair is now in hand (already present or hydrated),\n * `false` when there's no blob yet (a brand-new member → caller provisions).\n * Throws only on a genuine unwrap failure (wrong secret / tampered blob).\n */\n async rehydrate(memberId: string, seedSecret: string): Promise<boolean> {\n // Already unlocked in this tab — nothing to do.\n if (KeyStore.getInstance().getKeyPair(memberId)?.privateKey) return true;\n const wrapped = await this.store.get(CHAT_KEYS_KEY);\n if (!wrapped) {\n vlog(\"rehydrate: no chat-keys blob (new member → will provision)\");\n return false;\n }\n const bytes = await unwrapWithPassphrase(seedSecret, wrapped);\n const dehydrated = JSON.parse(new TextDecoder().decode(bytes));\n await KeyStore.getInstance().hydrateKeyPair(memberId, dehydrated);\n vlog(`rehydrate: HIT — restored stable keypair fp=${await fingerprint(memberId)}`);\n return true;\n }\n\n /**\n * Ensure a stable keypair is in hand: rehydrate from the vault if a blob\n * exists, otherwise mint one and persist it (so it's stable next session).\n * Used at register and lazily when a space is first opened.\n */\n async ensure(memberId: string, seedSecret: string): Promise<void> {\n if (await this.rehydrate(memberId, seedSecret)) return;\n await this.provision(memberId, seedSecret);\n }\n}\n\nexport default ChatKeyVault;\n","/**\n * `HlcTimestamp` — a Hybrid Logical Clock reading, packed into a single\n * lexicographically-sortable string so the whole offline layer (and the\n * accelerator) can compare causality with one plain string comparison.\n *\n * An HLC fuses a physical wall-clock millisecond with a logical `counter`\n * (breaks ties inside the same millisecond and lets the clock advance past a\n * remote event without the wall clock moving) and a stable `nodeId` (a final,\n * deterministic tiebreak so two devices never produce an \"equal but different\"\n * stamp). See {@link ./HLC}.\n *\n * The packed form is `\"{wall}:{counter}:{nodeId}\"` with `wall` and `counter`\n * zero-padded to a FIXED width. Fixed width is what makes lexicographic order\n * equal to numeric order — `\"0000000000123:...\"` < `\"0000000000124:...\"`. The\n * server only ever compares these strings; it never has to parse them.\n */\n\n/** Zero-padded width of the wall-clock field. 15 digits holds ms timestamps\n * past the year 5000, so `Date.now()` (currently 13 digits) never overflows. */\nexport const WALL_DIGITS = 15;\n\n/** Zero-padded width of the logical counter. 5 digits allows 100k events in a\n * single wall-clock millisecond before the clock is forced forward — far more\n * than any real burst. */\nexport const COUNTER_DIGITS = 5;\n\n/** The smallest possible stamp — used as the \"nothing stored yet\" sentinel so a\n * first real write always wins (`compareHlc(real, ZERO_HLC) > 0`). */\nexport const ZERO_HLC = pack(0, 0, \"\");\n\nexport interface HlcParts {\n /** Physical wall-clock time, milliseconds since the Unix epoch. */\n wall: number;\n /** Logical counter within `wall`. */\n counter: number;\n /** Stable per-install node id (tiebreak). */\n nodeId: string;\n}\n\nfunction padNum(n: number, width: number): string {\n const s = Math.max(0, Math.floor(n)).toString();\n return s.length >= width ? s : \"0\".repeat(width - s.length) + s;\n}\n\n/** Pack the three components into the sortable string form. */\nexport function pack(wall: number, counter: number, nodeId: string): string {\n return `${padNum(wall, WALL_DIGITS)}:${padNum(counter, COUNTER_DIGITS)}:${nodeId}`;\n}\n\n/** Pack from a {@link HlcParts}. */\nexport function packParts(parts: HlcParts): string {\n return pack(parts.wall, parts.counter, parts.nodeId);\n}\n\n/** Parse a packed stamp back into its components. Tolerates the empty/zero\n * sentinel. Throws on a malformed string so corruption surfaces loudly. */\nexport function unpack(stamp: string): HlcParts {\n const idx1 = stamp.indexOf(\":\");\n const idx2 = stamp.indexOf(\":\", idx1 + 1);\n if (idx1 < 0 || idx2 < 0) {\n throw new Error(`malformed HLC timestamp: ${JSON.stringify(stamp)}`);\n }\n return {\n wall: Number(stamp.slice(0, idx1)),\n counter: Number(stamp.slice(idx1 + 1, idx2)),\n nodeId: stamp.slice(idx2 + 1),\n };\n}\n\n/**\n * Total order over packed HLC strings: negative if `a < b`, positive if\n * `a > b`, `0` only when they are byte-identical. Because the fields are\n * fixed-width and ordered (wall, counter, nodeId), a single string comparison\n * already yields causal order — this helper just normalizes the result to the\n * `-1 | 0 | 1` shape callers expect.\n */\nexport function compareHlc(a: string, b: string): number {\n if (a === b) return 0;\n return a < b ? -1 : 1;\n}\n\n/** Convenience: is `a` strictly newer than `b`? */\nexport function isNewer(a: string, b: string): boolean {\n return compareHlc(a, b) > 0;\n}\n","/**\n * `HLC` — a Hybrid Logical Clock. Hands out monotonically increasing\n * {@link HlcTimestamp} stamps that (a) track real time closely enough to be\n * human-meaningful, yet (b) never go backwards, even across a reload or when a\n * peer's clock is ahead of ours.\n *\n * Two operations, both the textbook HLC algorithm (Kulkarni et al.):\n * - `now()` — stamp a local event.\n * - `update(remote)` — observe a remote stamp (e.g. arriving on the realtime\n * change feed) and advance our clock past it, so any event we generate\n * afterwards is causally `> remote`.\n *\n * State is just `{ wall, counter }`; `nodeId` is fixed for the install. The\n * owner ({@link ../OfflineManager}) seeds the clock from persisted state on\n * boot and persists `getState()` after each tick so monotonicity survives page\n * reloads — without that, a reload could mint a stamp that loses to one written\n * seconds earlier.\n */\n\nimport { pack, type HlcParts } from \"./HlcTimestamp\";\n\nexport interface HlcState {\n wall: number;\n counter: number;\n}\n\n/** Injected physical-time source — defaults to `Date.now`. Overridable so\n * tests can drive the clock deterministically. */\nexport type PhysicalClock = () => number;\n\nexport class HLC {\n private wall: number;\n private counter: number;\n private readonly nodeId: string;\n private readonly physical: PhysicalClock;\n\n constructor(nodeId: string, opts: { state?: HlcState | null; physical?: PhysicalClock } = {}) {\n this.nodeId = nodeId;\n this.physical = opts.physical ?? (() => Date.now());\n this.wall = opts.state?.wall ?? 0;\n this.counter = opts.state?.counter ?? 0;\n }\n\n /** Stamp a locally-generated event. Advances the clock. */\n now(): string {\n const pt = this.physical();\n const prevWall = this.wall;\n this.wall = Math.max(prevWall, pt);\n this.counter = this.wall === prevWall ? this.counter + 1 : 0;\n return this.current();\n }\n\n /**\n * Merge in an observed remote stamp and advance our clock strictly past it.\n * Call this for every inbound HLC (change-feed frames, history rows) so the\n * next `now()` is causally after anything we've seen.\n */\n update(remote: HlcParts): string {\n const pt = this.physical();\n const prevWall = this.wall;\n const newWall = Math.max(prevWall, remote.wall, pt);\n if (newWall === prevWall && newWall === remote.wall) {\n this.counter = Math.max(this.counter, remote.counter) + 1;\n } else if (newWall === prevWall) {\n this.counter = this.counter + 1;\n } else if (newWall === remote.wall) {\n this.counter = remote.counter + 1;\n } else {\n this.counter = 0;\n }\n this.wall = newWall;\n return this.current();\n }\n\n /** The current stamp without advancing the clock. */\n current(): string {\n return pack(this.wall, this.counter, this.nodeId);\n }\n\n /** Serializable `{ wall, counter }` for persistence. */\n getState(): HlcState {\n return { wall: this.wall, counter: this.counter };\n }\n}\n\nexport default HLC;\n","/**\n * `ConnectivityManager` — the single source of truth for \"are we online\", which\n * the offline layer needs to decide between a network call and a cache read, and\n * to know when to flush the durable outbound queue.\n *\n * `navigator.onLine` alone lies often (captive portals, VPN flaps, a laptop\n * that's \"connected\" to a network with no route), so we fuse three signals:\n * 1. the browser `online`/`offline` events (coarse but free),\n * 2. real fetch outcomes reported by {@link ../core/HttpClient} and the shard\n * client — a thrown `TypeError`/abort is the most reliable \"offline\" tell,\n * and a 2xx is the most reliable \"online\" tell,\n * 3. the sync engine, which flips us to `syncing` while it drains the queue.\n *\n * The offline→online edge fires `onReconnect` (wired to the sync engine) so\n * queued writes replay automatically. Transitions are debounced to avoid\n * flapping the UI on a brief blip. State changes also emit on {@link EventCore}\n * (`ONLINE`/`OFFLINE`/`SYNCING`) so apps can render a status indicator.\n */\n\nimport { EventCore, EventCoreEvents } from \"../events/EventCore\";\n\nexport type ConnectivityState = \"online\" | \"offline\" | \"syncing\";\n\nexport interface ConnectivityOptions {\n /** Called on each offline→online transition (drives queue replay). */\n onReconnect?: () => void;\n /** Debounce window for offline transitions, ms. Default 1500. */\n debounceMs?: number;\n}\n\nexport class ConnectivityManager {\n private state: ConnectivityState;\n private readonly listeners = new Set<(state: ConnectivityState) => void>();\n private readonly onReconnect?: () => void;\n private readonly debounceMs: number;\n private offlineTimer: ReturnType<typeof setTimeout> | null = null;\n private started = false;\n\n private readonly handleOnline = () => this.markOnline();\n private readonly handleOffline = () => this.scheduleOffline();\n\n constructor(opts: ConnectivityOptions = {}) {\n this.onReconnect = opts.onReconnect;\n this.debounceMs = opts.debounceMs ?? 1500;\n this.state =\n typeof navigator !== \"undefined\" && navigator.onLine === false ? \"offline\" : \"online\";\n }\n\n /** Attach to the browser online/offline events. Safe to call in Node (no-op). */\n start(): void {\n if (this.started || typeof window === \"undefined\") return;\n window.addEventListener(\"online\", this.handleOnline);\n window.addEventListener(\"offline\", this.handleOffline);\n this.started = true;\n }\n\n stop(): void {\n if (!this.started || typeof window === \"undefined\") return;\n window.removeEventListener(\"online\", this.handleOnline);\n window.removeEventListener(\"offline\", this.handleOffline);\n if (this.offlineTimer) clearTimeout(this.offlineTimer);\n this.started = false;\n }\n\n get current(): ConnectivityState {\n return this.state;\n }\n\n get isOnline(): boolean {\n return this.state !== \"offline\";\n }\n\n /** Subscribe to state changes. Returns an unsubscribe function. */\n onChange(cb: (state: ConnectivityState) => void): () => void {\n this.listeners.add(cb);\n return () => this.listeners.delete(cb);\n }\n\n /** Report a failed network attempt (thrown fetch / abort). */\n reportFetchFailure(): void {\n this.scheduleOffline();\n }\n\n /** Report a successful network round-trip — strongest \"we're online\" signal. */\n reportFetchSuccess(): void {\n this.markOnline();\n }\n\n /** The sync engine entering its drain phase. */\n markSyncing(): void {\n if (this.offlineTimer) {\n clearTimeout(this.offlineTimer);\n this.offlineTimer = null;\n }\n this.set(\"syncing\");\n }\n\n /** The sync engine finished — settle back to online. */\n markSynced(): void {\n this.set(\"online\");\n }\n\n private markOnline(): void {\n if (this.offlineTimer) {\n clearTimeout(this.offlineTimer);\n this.offlineTimer = null;\n }\n // The sync engine owns the syncing→online transition (via markSynced).\n // A request succeeding mid-drain must not cut the syncing state short.\n if (this.state === \"syncing\") return;\n const wasOffline = this.state === \"offline\";\n this.set(\"online\");\n if (wasOffline) {\n try {\n this.onReconnect?.();\n } catch {\n /* a reconnect handler must not break connectivity tracking */\n }\n }\n }\n\n private scheduleOffline(): void {\n if (this.state === \"offline\" || this.offlineTimer) return;\n this.offlineTimer = setTimeout(() => {\n this.offlineTimer = null;\n this.set(\"offline\");\n }, this.debounceMs);\n }\n\n private set(state: ConnectivityState): void {\n if (state === this.state) return;\n this.state = state;\n for (const cb of this.listeners) {\n try {\n cb(state);\n } catch {\n /* a bad listener mustn't break the others */\n }\n }\n const event =\n state === \"online\"\n ? EventCoreEvents.ONLINE\n : state === \"offline\"\n ? EventCoreEvents.OFFLINE\n : EventCoreEvents.SYNCING;\n EventCore.emit(event, { state });\n }\n}\n\nexport default ConnectivityManager;\n","/**\n * `OutboundQueue` — the durable record of writes made while offline (or that\n * failed mid-flight) plus the machinery to replay them on reconnect. This is\n * what makes offline writes *survive a reload*: unlike the in-memory buffer in\n * {@link ../transport/WSTransport}, every entry lives in IndexedDB until it has\n * been acknowledged by the server.\n *\n * Each domain registers a **replayer** — a function that re-applies one queued\n * mutation by re-invoking the real namespace method (with an `isReplay` flag so\n * it doesn't re-enqueue). `drain()` replays entries in HLC order:\n * - success → remove the entry;\n * - permanent failure (4xx) → drop it and surface a `SYNC_ERROR` (a write the\n * server will never accept must not wedge the queue forever);\n * - transient/network failure → stop draining and leave the rest for the next\n * reconnect.\n *\n * Replays are idempotent by construction (kv/db are LWW-by-key, messages dedupe\n * by `clientId`, file PUTs are content-addressed), so re-running a partially\n * drained queue is safe.\n */\n\nimport { EventCore, EventCoreEvents } from \"../events/EventCore\";\nimport { HttpError } from \"../core/HttpClient\";\nimport type { OfflineStore, QueueEntry } from \"./store/OfflineStore\";\n\nexport type Replayer = (entry: QueueEntry) => Promise<void>;\n\nexport class OutboundQueue {\n private readonly replayers = new Map<QueueEntry[\"domain\"], Replayer>();\n private draining: Promise<void> | null = null;\n\n constructor(private readonly store: OfflineStore) {}\n\n /** A domain registers how to replay its mutations. */\n register(domain: QueueEntry[\"domain\"], replayer: Replayer): void {\n this.replayers.set(domain, replayer);\n }\n\n /** Record a mutation for later replay; resolves with its assigned seq. */\n enqueue(entry: Omit<QueueEntry, \"seq\">): Promise<number> {\n return this.store.enqueue(entry);\n }\n\n /** Number of writes still awaiting sync. */\n async pending(): Promise<number> {\n return (await this.store.queued()).length;\n }\n\n /**\n * Replay queued mutations in HLC order. Coalesces concurrent calls into a\n * single in-flight drain. Stops on the first transient failure, leaving the\n * remaining entries for the next attempt.\n */\n drain(): Promise<void> {\n if (this.draining) return this.draining;\n this.draining = this.runDrain().finally(() => {\n this.draining = null;\n });\n return this.draining;\n }\n\n private async runDrain(): Promise<void> {\n const entries = await this.store.queued();\n for (const entry of entries) {\n const replayer = this.replayers.get(entry.domain);\n if (!replayer) {\n // No handler registered (namespace not wired) — drop it rather\n // than block the queue; nothing can ever replay it.\n await this.store.dequeue(entry.seq);\n continue;\n }\n try {\n await replayer(entry);\n await this.store.dequeue(entry.seq);\n EventCore.emit(EventCoreEvents.SYNC_PROGRESS, {\n domain: entry.domain,\n method: entry.method,\n });\n } catch (err) {\n if (isPermanent(err)) {\n await this.store.dequeue(entry.seq);\n EventCore.emit(EventCoreEvents.SYNC_ERROR, {\n domain: entry.domain,\n method: entry.method,\n error: String((err as Error)?.message ?? err),\n dropped: true,\n });\n continue;\n }\n // Transient (offline again, 5xx) — keep the entry, stop here.\n throw err;\n }\n }\n }\n}\n\n/** A 4xx is the server permanently refusing the write; anything else is worth\n * retrying on the next reconnect. */\nfunction isPermanent(err: unknown): boolean {\n return err instanceof HttpError && err.status >= 400 && err.status < 500;\n}\n\nexport default OutboundQueue;\n","/**\n * `SyncEngine` — orchestrates catch-up when the client comes back online. It's\n * the thing wired to the {@link ConnectivityManager}'s offline→online edge.\n *\n * One `run()` does, in order:\n * 1. **Guard** — only proceed when the session is authenticated and unlocked\n * (replays may need to re-seal/re-encrypt, and there's no point pushing\n * writes for a logged-out user).\n * 2. **Drain** the durable {@link OutboundQueue} — push every offline write.\n * 3. **Catch-up tasks** — domain-registered pulls that reconcile *inbound*\n * state we missed while offline (e.g. a Space paging history forward to its\n * last-seen handle). Registered by the namespaces.\n *\n * Concurrent triggers coalesce into a single in-flight run (a reconnect often\n * fires several signals at once), mirroring `Client.recoverInFlight`.\n */\n\nimport { EventCore, EventCoreEvents } from \"../events/EventCore\";\nimport type { ConnectivityManager } from \"./ConnectivityManager\";\nimport type { OutboundQueue } from \"./OutboundQueue\";\n\nexport interface SyncEngineDeps {\n queue: OutboundQueue;\n connectivity: ConnectivityManager;\n /** Proceed only when this returns true (authenticated + unlocked). */\n canSync: () => boolean;\n}\n\nexport class SyncEngine {\n private readonly catchUpTasks = new Set<() => Promise<void>>();\n private running: Promise<void> | null = null;\n\n constructor(private readonly deps: SyncEngineDeps) {}\n\n /** Register an inbound reconciliation task run after the queue drains. */\n registerCatchUp(task: () => Promise<void>): () => void {\n this.catchUpTasks.add(task);\n return () => this.catchUpTasks.delete(task);\n }\n\n /** Drain + catch up. Concurrent calls share one in-flight run. */\n run(): Promise<void> {\n if (this.running) return this.running;\n this.running = this.execute().finally(() => {\n this.running = null;\n });\n return this.running;\n }\n\n private async execute(): Promise<void> {\n if (!this.deps.canSync()) return;\n this.deps.connectivity.markSyncing();\n try {\n await this.deps.queue.drain();\n for (const task of this.catchUpTasks) {\n try {\n await task();\n } catch {\n // One domain's catch-up failing shouldn't abort the others\n // or wedge the sync; it'll retry on the next reconnect.\n }\n }\n EventCore.emit(EventCoreEvents.SYNC_COMPLETE, {});\n } finally {\n this.deps.connectivity.markSynced();\n }\n }\n}\n\nexport default SyncEngine;\n","/**\n * Errors specific to the offline layer.\n */\n\n/**\n * Thrown when an offline read/write needs the user's identity (to decrypt or\n * re-encrypt cached data) but the client is locked — typically right after a\n * reload, where only the session token was restored and `unlock()` hasn't run\n * yet. Distinct from the generic \"not signed in\" identity error so apps can\n * specifically prompt the user to unlock to see their offline data.\n */\nexport class OfflineLockedError extends Error {\n constructor(message = \"Unlock required to access encrypted offline data. Call client.auth.zk.unlock(password).\") {\n super(message);\n this.name = \"OfflineLockedError\";\n }\n}\n","/**\n * `client.offline.snapshot` — a small, encrypted, app-state cache. Apps stash\n * whatever they need to repaint instantly on a cold offline boot: the last open\n * Space, a draft message, scroll position, the current route. It's deliberately\n * separate from `client.kv`: snapshots are **local-only by default** (instant,\n * never metered, never leave the device) and hold view state rather than domain\n * data.\n *\n * await client.offline.snapshot.save('ui', { route, openSpaceId, draft })\n * const ui = await client.offline.snapshot.load<UiState>('ui')\n *\n * Values are encrypted at rest with the same identity-derived {@link StorageCipher}\n * as `client.kv`, so a snapshot is unreadable until the user unlocks — `load`\n * returns `null` when locked or absent, and `save` throws {@link OfflineLockedError}.\n * Conflict model is a single-writer LWW register (the latest save wins).\n */\n\nimport type { SessionState } from \"../../core/Session\";\nimport type { ZkIdentity } from \"../../auth/identity\";\nimport { StorageCipher, type EncryptedEnvelope } from \"../../crypto/StorageCipher\";\nimport type { OfflineStore } from \"../store/OfflineStore\";\nimport { OfflineLockedError } from \"../errors\";\n\nexport interface SnapshotNamespaceDeps {\n store: OfflineStore;\n session: SessionState;\n /** Stamp the saved record (LWW ordering); supplied by the OfflineManager. */\n nextHlc: () => Promise<string>;\n}\n\ninterface SnapshotRecord {\n envelope: EncryptedEnvelope;\n hlc: string;\n updatedAt: number;\n}\n\nexport class SnapshotNamespace {\n private cipher: StorageCipher | null = null;\n private cipherIdentity: ZkIdentity | null = null;\n\n constructor(private readonly deps: SnapshotNamespaceDeps) {}\n\n /** Persist `state` under `name` (encrypted). No-op when offline support is off. */\n async save<T = unknown>(name: string, state: T): Promise<void> {\n if (!this.deps.store.enabled) return;\n const envelope = await this.requireCipher().encrypt(state);\n const record: SnapshotRecord = {\n envelope,\n hlc: await this.deps.nextHlc(),\n updatedAt: Date.now(),\n };\n await this.deps.store.put(\"snapshots\", this.key(name), record);\n }\n\n /** Load and decrypt the snapshot `name`, or `null` if absent/locked. */\n async load<T = unknown>(name: string): Promise<T | null> {\n if (!this.deps.store.enabled) return null;\n const record = await this.deps.store.get<SnapshotRecord>(\"snapshots\", this.key(name));\n if (!record) return null;\n if (!this.deps.session.isUnlocked) return null;\n return this.requireCipher().decrypt<T>(record.envelope);\n }\n\n /** Remove the snapshot `name`. */\n async delete(name: string): Promise<void> {\n if (!this.deps.store.enabled) return;\n await this.deps.store.delete(\"snapshots\", this.key(name));\n }\n\n /** Names of all snapshots for the current user. */\n async list(): Promise<string[]> {\n if (!this.deps.store.enabled) return [];\n const prefix = `${this.commitment()}|`;\n const rows = await this.deps.store.prefix<SnapshotRecord>(\"snapshots\", prefix);\n return rows.map((r) => r.key.slice(prefix.length));\n }\n\n private key(name: string): string {\n return `${this.commitment()}|${name}`;\n }\n\n private commitment(): string {\n // Snapshots are scoped per user; before sign-in they share an \"anon\"\n // bucket so pre-auth UI state (e.g. a chosen theme) still persists.\n return this.deps.session.commitment ?? \"anon\";\n }\n\n private requireCipher(): StorageCipher {\n if (!this.deps.session.isUnlocked) throw new OfflineLockedError();\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 SnapshotNamespace;\n","/**\n * IndexedDB schema for the offline layer — the single source of truth for the\n * database name, version, and object stores. Bump {@link DB_VERSION} whenever\n * the store set changes; {@link ./idb}'s `onupgradeneeded` creates any store\n * that doesn't exist yet (additive migrations only — never drop\n * `outbound-queue`, it holds un-synced writes).\n *\n * One database per origin. Records are partitioned *by key* (most keys are\n * prefixed with the user's `commitment`) rather than by separate databases, so\n * a single connection serves every signed-in user on the origin and prefix\n * scans isolate a user's data.\n */\n\nexport const DB_NAME = \"muhkoo.offline\";\nexport const DB_VERSION = 1;\n\nexport type StoreName =\n | \"kv-cache\"\n | \"db-row-cache\"\n | \"db-query-cache\"\n | \"space-messages\"\n | \"space-cursors\"\n | \"outbound-queue\"\n | \"snapshots\"\n | \"hlc-state\"\n | \"meta\";\n\nexport interface StoreDef {\n name: StoreName;\n /** Auto-incrementing in-line key (used by the durable outbound queue). */\n autoIncrement?: boolean;\n /** Key path for an in-line key; omit for out-of-line (explicit) keys. */\n keyPath?: string;\n}\n\nexport const STORES: StoreDef[] = [\n { name: \"kv-cache\" },\n { name: \"db-row-cache\" },\n { name: \"db-query-cache\" },\n { name: \"space-messages\" },\n { name: \"space-cursors\" },\n { name: \"outbound-queue\", autoIncrement: true, keyPath: \"seq\" },\n { name: \"snapshots\" },\n { name: \"hlc-state\" },\n { name: \"meta\" },\n];\n\n/** Fixed keys in the `meta` store. */\nexport const META_NODE_ID = \"nodeId\";\nexport const META_SCHEMA_VERSION = \"schemaVersion\";\n","/**\n * `OfflineManager` — the object `client.offline` points at, and the single\n * owner of everything the offline layer needs at runtime: the {@link\n * OfflineStore}, the {@link HLC} (Hybrid Logical Clock), the {@link\n * ConnectivityManager}, the durable {@link OutboundQueue}, the {@link\n * SyncEngine}, and the {@link SnapshotNamespace}.\n *\n * The {@link ../core/Client} constructs one of these (always — it's a cheap\n * no-op when offline support is off) and hands the namespaces the small set of\n * primitives they need to participate: `nextHlc()` to stamp a write,\n * `observeHlc()` to fold in a remote stamp, `enqueue()` to record an offline\n * mutation, and `registerReplayer()`/`registerCatchUp()` to define how their\n * domain re-syncs on reconnect. Keeping that wiring here means the namespaces\n * stay decoupled from IndexedDB and the clock.\n */\n\nimport { generateId } from \"../utilities\";\nimport type { SessionState } from \"../core/Session\";\nimport { HLC, type HlcState } from \"./clock/HLC\";\nimport { unpack } from \"./clock/HlcTimestamp\";\nimport { ConnectivityManager, type ConnectivityState } from \"./ConnectivityManager\";\nimport { OutboundQueue, type Replayer } from \"./OutboundQueue\";\nimport { SyncEngine } from \"./SyncEngine\";\nimport { SnapshotNamespace } from \"./namespaces/SnapshotNamespace\";\nimport { ShardCache } from \"./cache/ShardCache\";\nimport type { OfflineStore, QueueEntry } from \"./store/OfflineStore\";\nimport { META_NODE_ID } from \"./store/schema\";\n\nexport interface OfflineManagerDeps {\n store: OfflineStore;\n session: SessionState;\n /** Whether offline support is active (browser) vs a no-op (Node/Workers). */\n enabled: boolean;\n}\n\nconst HLC_STATE_KEY = \"global\";\n\nexport class OfflineManager {\n /** True in browsers with IndexedDB; false when running over a NoopStore. */\n readonly enabled: boolean;\n readonly store: OfflineStore;\n readonly connectivity: ConnectivityManager;\n readonly queue: OutboundQueue;\n readonly sync: SyncEngine;\n /** `client.offline.snapshot` — encrypted app-state cache. */\n readonly snapshot: SnapshotNamespace;\n /** Cache-API store for file-shard bytes (browser only). */\n readonly fileCache?: ShardCache;\n\n private hlc: HLC | null = null;\n private nodeId = \"\";\n private readonly bootPromise: Promise<void>;\n private persistTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(deps: OfflineManagerDeps) {\n this.enabled = deps.enabled;\n this.store = deps.store;\n this.queue = new OutboundQueue(deps.store);\n this.connectivity = new ConnectivityManager({\n onReconnect: () => void this.sync.run(),\n });\n this.sync = new SyncEngine({\n queue: this.queue,\n connectivity: this.connectivity,\n // Replays may need to re-seal/re-encrypt, and there's no point\n // pushing a logged-out user's writes — gate on a usable session.\n canSync: () => deps.session.isAuthenticated && deps.session.isUnlocked,\n });\n this.snapshot = new SnapshotNamespace({\n store: deps.store,\n session: deps.session,\n nextHlc: () => this.nextHlc(),\n });\n\n if (this.enabled && ShardCache.available()) this.fileCache = new ShardCache();\n\n this.bootPromise = this.boot();\n if (this.enabled) this.connectivity.start();\n }\n\n /**\n * Queue a shard upload that couldn't reach the network. The bytes are\n * already cached (keyed by `hash`), so only the hash is recorded; the file\n * replayer re-PUTs from the cache on reconnect.\n */\n async deferShardUpload(hash: string): Promise<void> {\n await this.enqueue({\n hlc: await this.nextHlc(),\n clientId: this.newClientId(),\n domain: \"file\",\n method: \"putShard\",\n args: { hash },\n });\n }\n\n /** Resolve once the clock + node id are loaded. */\n ready(): Promise<void> {\n return this.bootPromise;\n }\n\n /** Current connectivity state (`online` | `offline` | `syncing`). */\n get status(): ConnectivityState {\n return this.connectivity.current;\n }\n\n /** Subscribe to connectivity changes. Returns an unsubscribe function. */\n onStatusChange(cb: (state: ConnectivityState) => void): () => void {\n return this.connectivity.onChange(cb);\n }\n\n /** Stamp a locally-generated write with a fresh, monotonic HLC. */\n async nextHlc(): Promise<string> {\n await this.bootPromise;\n const stamp = this.hlc!.now();\n this.schedulePersist();\n return stamp;\n }\n\n /** Fold an observed remote HLC into the clock (call for inbound stamps). */\n async observeHlc(remote: string): Promise<void> {\n await this.bootPromise;\n this.hlc!.update(unpack(remote));\n this.schedulePersist();\n }\n\n /** A fresh client-generated id (idempotent replay / message dedupe). */\n newClientId(): string {\n return generateId();\n }\n\n /** Record an offline mutation for replay on reconnect. */\n enqueue(entry: Omit<QueueEntry, \"seq\">): Promise<number> {\n return this.queue.enqueue(entry);\n }\n\n /** A domain registers how to replay its queued mutations. */\n registerReplayer(domain: QueueEntry[\"domain\"], replayer: Replayer): void {\n this.queue.register(domain, replayer);\n }\n\n /** A domain registers an inbound catch-up task (run after the queue drains). */\n registerCatchUp(task: () => Promise<void>): () => void {\n return this.sync.registerCatchUp(task);\n }\n\n /** Surface a network failure to connectivity tracking. */\n reportFetchFailure(): void {\n this.connectivity.reportFetchFailure();\n }\n\n /** Surface a successful round-trip to connectivity tracking. */\n reportFetchSuccess(): void {\n this.connectivity.reportFetchSuccess();\n }\n\n /** Tear down listeners (tests / hot-reload). */\n dispose(): void {\n this.connectivity.stop();\n if (this.persistTimer) clearTimeout(this.persistTimer);\n }\n\n private async boot(): Promise<void> {\n if (!this.enabled) {\n // In-memory clock only; nothing is persisted over a NoopStore.\n this.nodeId = generateId();\n this.hlc = new HLC(this.nodeId);\n return;\n }\n let nodeId = await this.store.get<string>(\"meta\", META_NODE_ID);\n if (!nodeId) {\n nodeId = generateId();\n await this.store.put(\"meta\", META_NODE_ID, nodeId);\n }\n this.nodeId = nodeId;\n const state = await this.store.get<HlcState>(\"hlc-state\", HLC_STATE_KEY);\n this.hlc = new HLC(nodeId, { state });\n }\n\n /** Coalesce HLC-state writes — a burst of stamps persists once. */\n private schedulePersist(): void {\n if (!this.enabled || this.persistTimer) return;\n this.persistTimer = setTimeout(() => {\n this.persistTimer = null;\n if (this.hlc) void this.store.put(\"hlc-state\", HLC_STATE_KEY, this.hlc.getState());\n }, 200);\n }\n}\n\nexport default OfflineManager;\n","/**\n * Environment probe deciding whether the offline layer turns itself on. Offline\n * support is **on by default in browsers** and a no-op everywhere else, so this\n * is the gate the {@link ../core/Client} consults to pick {@link\n * ./store/IndexedDbStore} vs {@link ./store/NoopStore}.\n *\n * We require all three web APIs the layer leans on — `indexedDB` (structured\n * cache + durable queue), the Cache API (file-shard bytes), and a `window`\n * (so we're in a real document with online/offline events) — and we *touch*\n * them inside a try/catch, because some sandboxed or private-mode contexts\n * expose the globals but throw on use (mirrors `defaultSessionStore`).\n */\n\nexport function isOfflineCapable(): boolean {\n try {\n return (\n typeof window !== \"undefined\" &&\n typeof indexedDB !== \"undefined\" &&\n typeof caches !== \"undefined\"\n );\n } catch {\n return false;\n }\n}\n","/**\n * A ~thin promise wrapper over the raw IndexedDB API — just enough surface for\n * {@link ./IndexedDbStore}: open-with-migration, get/put/delete, prefix and\n * range cursor scans, autoincrement append, and clear. We hand-roll this rather\n * than depend on `idb`/`dexie` because the access patterns are simple and\n * `@muhkoo/connect` keeps its runtime dependency surface minimal.\n *\n * Everything here assumes a browser (or a `fake-indexeddb` test shim) — callers\n * gate construction behind {@link ../detect}.\n */\n\nimport { DB_NAME, DB_VERSION, STORES, type StoreName } from \"./schema\";\n\nfunction req<T>(request: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n}\n\n/** Open (and migrate) the offline database. Creates any missing object store. */\nexport function openDatabase(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const open = indexedDB.open(DB_NAME, DB_VERSION);\n open.onupgradeneeded = () => {\n const db = open.result;\n for (const def of STORES) {\n if (db.objectStoreNames.contains(def.name)) continue;\n db.createObjectStore(\n def.name,\n def.autoIncrement ? { keyPath: def.keyPath, autoIncrement: true } : undefined,\n );\n }\n };\n open.onsuccess = () => resolve(open.result);\n open.onerror = () => reject(open.error);\n // A blocked upgrade means another tab holds an older version open; let\n // it surface as an error rather than hang forever.\n open.onblocked = () => reject(new Error(\"offline DB upgrade blocked by another tab\"));\n });\n}\n\nexport interface IdbEntry<T> {\n key: string;\n value: T;\n}\n\n/** Wraps an open connection with the typed operations the store needs. */\nexport class IdbConnection {\n constructor(private readonly db: IDBDatabase) {}\n\n private tx(store: StoreName, mode: IDBTransactionMode): IDBObjectStore {\n return this.db.transaction(store, mode).objectStore(store);\n }\n\n get<T>(store: StoreName, key: string): Promise<T | null> {\n return req<T | undefined>(this.tx(store, \"readonly\").get(key)).then((v) => v ?? null);\n }\n\n async put<T>(store: StoreName, key: string, value: T): Promise<void> {\n await req(this.tx(store, \"readwrite\").put(value as unknown, key));\n }\n\n async delete(store: StoreName, key: IDBValidKey): Promise<void> {\n await req(this.tx(store, \"readwrite\").delete(key));\n }\n\n async clear(store: StoreName): Promise<void> {\n await req(this.tx(store, \"readwrite\").clear());\n }\n\n /** Append to an autoincrement store; resolves with the generated key. */\n async append<T>(store: StoreName, value: T): Promise<number> {\n const key = await req(this.tx(store, \"readwrite\").add(value as unknown));\n return key as number;\n }\n\n /** All entries whose string key falls in `[lower, upper)`, in key order. */\n range<T>(store: StoreName, lower: string, upper: string): Promise<Array<IdbEntry<T>>> {\n return this.scan<T>(store, IDBKeyRange.bound(lower, upper, false, true));\n }\n\n /** All entries whose key starts with `prefix`, in key order. */\n prefix<T>(store: StoreName, prefix: string): Promise<Array<IdbEntry<T>>> {\n // \"\" is the largest BMP code unit, so `[prefix, prefix+)`\n // bounds every key that begins with `prefix`.\n return this.scan<T>(store, IDBKeyRange.bound(prefix, prefix + \"\", false, true));\n }\n\n /** Every entry in the store, in key order. */\n all<T>(store: StoreName): Promise<Array<IdbEntry<T>>> {\n return this.scan<T>(store, null);\n }\n\n private scan<T>(store: StoreName, range: IDBKeyRange | null): Promise<Array<IdbEntry<T>>> {\n return new Promise((resolve, reject) => {\n const out: Array<IdbEntry<T>> = [];\n const cursorReq = this.tx(store, \"readonly\").openCursor(range ?? undefined);\n cursorReq.onsuccess = () => {\n const cursor = cursorReq.result;\n if (!cursor) return resolve(out);\n out.push({ key: String(cursor.key), value: cursor.value as T });\n cursor.continue();\n };\n cursorReq.onerror = () => reject(cursorReq.error);\n });\n }\n}\n","/**\n * `IndexedDbStore` — the browser {@link OfflineStore}, backed by one IndexedDB\n * database per origin (see {@link ./schema}). It opens lazily on first use and\n * memoizes the connection. The queue methods sit on the autoincrement\n * `outbound-queue` store and return mutations in HLC order for the sync engine.\n *\n * Construct only where `indexedDB` exists — {@link ../detect.isOfflineCapable}\n * gates this, and the {@link ../../core/Client} falls back to {@link ./NoopStore}\n * everywhere else.\n */\n\nimport { compareHlc } from \"../clock/HlcTimestamp\";\nimport { IdbConnection, openDatabase } from \"./idb\";\nimport type { OfflineEntry, OfflineStore, QueueEntry } from \"./OfflineStore\";\nimport type { StoreName } from \"./schema\";\n\nexport class IndexedDbStore implements OfflineStore {\n readonly enabled = true;\n private conn: IdbConnection | null = null;\n private opening: Promise<IdbConnection> | null = null;\n\n private connect(): Promise<IdbConnection> {\n if (this.conn) return Promise.resolve(this.conn);\n if (!this.opening) {\n this.opening = openDatabase()\n .then((db) => {\n this.conn = new IdbConnection(db);\n return this.conn;\n })\n .finally(() => {\n this.opening = null;\n });\n }\n return this.opening;\n }\n\n async ready(): Promise<void> {\n await this.connect();\n }\n\n async get<T>(store: StoreName, key: string): Promise<T | null> {\n return (await this.connect()).get<T>(store, key);\n }\n\n async put<T>(store: StoreName, key: string, value: T): Promise<void> {\n await (await this.connect()).put(store, key, value);\n }\n\n async delete(store: StoreName, key: string): Promise<void> {\n await (await this.connect()).delete(store, key);\n }\n\n async prefix<T>(store: StoreName, prefix: string): Promise<Array<OfflineEntry<T>>> {\n return (await this.connect()).prefix<T>(store, prefix);\n }\n\n async range<T>(store: StoreName, lower: string, upper: string): Promise<Array<OfflineEntry<T>>> {\n return (await this.connect()).range<T>(store, lower, upper);\n }\n\n async all<T>(store: StoreName): Promise<Array<OfflineEntry<T>>> {\n return (await this.connect()).all<T>(store);\n }\n\n async clear(store: StoreName): Promise<void> {\n await (await this.connect()).clear(store);\n }\n\n async enqueue(entry: Omit<QueueEntry, \"seq\">): Promise<number> {\n // keyPath autoincrement writes the generated `seq` back into the record.\n return (await this.connect()).append(\"outbound-queue\", entry);\n }\n\n async dequeue(seq: number): Promise<void> {\n await (await this.connect()).delete(\"outbound-queue\", seq);\n }\n\n async queued(): Promise<QueueEntry[]> {\n const rows = await (await this.connect()).all<QueueEntry>(\"outbound-queue\");\n return rows.map((r) => r.value).sort((a, b) => compareHlc(a.hlc, b.hlc));\n }\n}\n\nexport default IndexedDbStore;\n","/**\n * `NoopStore` — the {@link OfflineStore} used wherever offline support is off\n * (Node, Workers, SSR, or when a consumer disables it). Every read returns\n * empty and every write is dropped, so the namespace hooks that call into it\n * behave exactly as they did before the offline layer existed. `enabled` is\n * `false` so hot paths can skip the call entirely.\n */\n\nimport type { OfflineEntry, OfflineStore, QueueEntry } from \"./OfflineStore\";\nimport type { StoreName } from \"./schema\";\n\nexport class NoopStore implements OfflineStore {\n readonly enabled = false;\n\n async ready(): Promise<void> {}\n async get<T>(_store: StoreName, _key: string): Promise<T | null> {\n return null;\n }\n async put<T>(_store: StoreName, _key: string, _value: T): Promise<void> {}\n async delete(_store: StoreName, _key: string): Promise<void> {}\n async prefix<T>(_store: StoreName, _prefix: string): Promise<Array<OfflineEntry<T>>> {\n return [];\n }\n async range<T>(_store: StoreName, _lower: string, _upper: string): Promise<Array<OfflineEntry<T>>> {\n return [];\n }\n async all<T>(_store: StoreName): Promise<Array<OfflineEntry<T>>> {\n return [];\n }\n async clear(_store: StoreName): Promise<void> {}\n async enqueue(_entry: Omit<QueueEntry, \"seq\">): Promise<number> {\n return -1;\n }\n async dequeue(_seq: number): Promise<void> {}\n async queued(): Promise<QueueEntry[]> {\n return [];\n }\n}\n\nexport default NoopStore;\n","/**\n * `LWWRegister` — a last-write-wins register CRDT, the conflict model for a\n * `kv` value and for an app-state snapshot. A register holds a single value\n * stamped with the {@link HlcTimestamp} of the write that produced it. Two\n * concurrent writes converge to the one with the greater HLC; the loser is\n * discarded. A delete is just a write that sets `deleted` (a tombstone), so a\n * stale write that arrives after a newer delete can't resurrect the value.\n *\n * Because the HLC total-orders every write deterministically (down to a nodeId\n * tiebreak), every replica that has seen the same set of writes lands on the\n * same value — that's the convergence guarantee.\n */\n\nimport { compareHlc, ZERO_HLC } from \"../clock/HlcTimestamp\";\n\nexport interface LwwRegister<T> {\n /** The current value, or `null` when tombstoned / never written. */\n value: T | null;\n /** HLC of the write that produced this state. */\n hlc: string;\n /** True when the latest write was a delete. */\n deleted: boolean;\n}\n\n/** An empty register that loses to any real write. */\nexport function emptyRegister<T>(): LwwRegister<T> {\n return { value: null, hlc: ZERO_HLC, deleted: true };\n}\n\n/**\n * Merge two register states, returning the winner (greater HLC). Pure: neither\n * input is mutated. Used identically on the inbound change feed and on\n * sync-replay reconciliation so there's exactly one definition of \"who wins\".\n */\nexport function mergeRegister<T>(a: LwwRegister<T>, b: LwwRegister<T>): LwwRegister<T> {\n return compareHlc(a.hlc, b.hlc) >= 0 ? a : b;\n}\n\n/** Build the register produced by a `set`. */\nexport function writeRegister<T>(value: T, hlc: string): LwwRegister<T> {\n return { value, hlc, deleted: false };\n}\n\n/** Build the register produced by a `delete` (a tombstone at `hlc`). */\nexport function deleteRegister<T>(hlc: string): LwwRegister<T> {\n return { value: null, hlc, deleted: true };\n}\n","/**\n * `KvCache` — the offline adapter for `client.kv`. Stores each value's\n * ciphertext envelope (never plaintext) under `${commitment}|${collection}/${id}`\n * as an LWW-Register stamped with an HLC, so reads work offline and concurrent\n * writes converge (see {@link ./crdt/LWWRegister}). Deletes are causal\n * tombstones — a stale write can't resurrect a key a newer delete removed.\n *\n * True cross-device convergence also needs the accelerator to honor the HLC\n * (see the server's `kvmeta` sidecar); this adapter embeds the stamp now and\n * degrades gracefully (last-writer-by-arrival) until that ships.\n */\n\nimport {\n emptyRegister,\n mergeRegister,\n writeRegister,\n deleteRegister,\n type LwwRegister,\n} from \"./crdt/LWWRegister\";\nimport type { OfflineManager } from \"./OfflineManager\";\nimport type { OfflineStore } from \"./store/OfflineStore\";\n\nexport type KvEntry = LwwRegister<unknown>;\n\nexport class KvCache {\n private readonly store: OfflineStore;\n constructor(private readonly manager: OfflineManager) {\n this.store = manager.store;\n }\n\n get enabled(): boolean {\n return this.manager.enabled;\n }\n\n nextHlc(): Promise<string> {\n return this.manager.nextHlc();\n }\n\n newClientId(): string {\n return this.manager.newClientId();\n }\n\n private key(commitment: string, fullKey: string): string {\n return `${commitment}|${fullKey}`;\n }\n\n /** Read the cached register for `collection/id`, or null when absent. */\n read(commitment: string, fullKey: string): Promise<KvEntry | null> {\n return this.store.get<KvEntry>(\"kv-cache\", this.key(commitment, fullKey));\n }\n\n /** Optimistically record a local `set` (ciphertext envelope + HLC). */\n async writeLocal(commitment: string, fullKey: string, envelope: unknown, hlc: string): Promise<void> {\n await this.store.put(\"kv-cache\", this.key(commitment, fullKey), writeRegister(envelope, hlc));\n }\n\n /** Optimistically record a local `delete` (tombstone at HLC). */\n async deleteLocal(commitment: string, fullKey: string, hlc: string): Promise<void> {\n await this.store.put(\"kv-cache\", this.key(commitment, fullKey), deleteRegister(hlc));\n }\n\n /**\n * Merge an authoritative value (from a GET refresh or a realtime frame) into\n * the cache by HLC. When the server doesn't supply an HLC yet, treat it as\n * \"now-ish\" by stamping our clock so a server value still beats stale local\n * state but a fresh local write wins.\n */\n async mergeRemote(\n commitment: string,\n fullKey: string,\n envelope: unknown | null,\n op: \"set\" | \"delete\",\n hlc?: string,\n ): Promise<void> {\n const k = this.key(commitment, fullKey);\n const incoming: KvEntry =\n op === \"delete\"\n ? deleteRegister(hlc ?? (await this.nextHlc()))\n : writeRegister(envelope, hlc ?? (await this.nextHlc()));\n const local = (await this.store.get<KvEntry>(\"kv-cache\", k)) ?? emptyRegister();\n await this.store.put(\"kv-cache\", k, mergeRegister(local, incoming));\n }\n\n /** Non-tombstoned full keys for a commitment (used for offline `list`). */\n async liveKeys(commitment: string): Promise<string[]> {\n const prefix = `${commitment}|`;\n const rows = await this.store.prefix<KvEntry>(\"kv-cache\", prefix);\n return rows.filter((r) => !r.value.deleted).map((r) => r.key.slice(prefix.length));\n }\n\n /** Queue a kv mutation for replay on reconnect. */\n async enqueue(method: \"set\" | \"delete\", args: unknown, hlc: string, clientId: string): Promise<void> {\n await this.manager.enqueue({ hlc, clientId, domain: \"kv\", method, args });\n }\n}\n\nexport default KvCache;\n","/**\n * `DbCache` — the offline adapter for `client.db`. Unlike kv, db rows are\n * server-plaintext, so they're cached as-is. The SDK doesn't know a table's\n * primary-key column, so it caches schema-agnostically:\n * - `get(id)` results keyed by the requested id (`${table}|row|${id}`),\n * - `query(q)` result pages keyed by a stable hash of the query.\n *\n * Writes carry per-column HLC stamps (`_hlc`) so the accelerator's per-column\n * LWW merge can converge concurrent edits; offline writes are queued and\n * replayed. Optimistic row patches keep `get` fresh between sync cycles.\n */\n\nimport type { OfflineManager } from \"./OfflineManager\";\nimport type { OfflineStore } from \"./store/OfflineStore\";\n\nexport interface DbQueryPage {\n rows: Array<Record<string, unknown>>;\n nextCursor: string | null;\n}\n\n/** Stable JSON for query-cache keys (sorted object keys → deterministic). */\nexport function stableStringify(value: unknown): string {\n if (value === null || typeof value !== \"object\") return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`;\n const obj = value as Record<string, unknown>;\n return `{${Object.keys(obj)\n .sort()\n .map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`)\n .join(\",\")}}`;\n}\n\nexport class DbCache {\n private readonly store: OfflineStore;\n constructor(private readonly manager: OfflineManager) {\n this.store = manager.store;\n }\n\n get enabled(): boolean {\n return this.manager.enabled;\n }\n nextHlc(): Promise<string> {\n return this.manager.nextHlc();\n }\n newClientId(): string {\n return this.manager.newClientId();\n }\n\n /** Build the `{ [col]: hlc }` map for a write (one stamp across its columns). */\n columnStamps(values: Record<string, unknown>, hlc: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const col of Object.keys(values)) out[col] = hlc;\n return out;\n }\n\n private rowKey(table: string, id: string): string {\n return `${table}|row|${id}`;\n }\n private queryKey(table: string, q: unknown): string {\n return `${table}|query|${stableStringify(q)}`;\n }\n\n async readRow(table: string, id: string): Promise<Record<string, unknown> | null> {\n return this.store.get(\"db-row-cache\", this.rowKey(table, id));\n }\n async writeRow(table: string, id: string, row: Record<string, unknown>): Promise<void> {\n await this.store.put(\"db-row-cache\", this.rowKey(table, id), row);\n }\n /** Shallow-merge a partial update into a cached row (optimistic). */\n async patchRow(table: string, id: string, values: Record<string, unknown>): Promise<void> {\n const existing = (await this.readRow(table, id)) ?? {};\n await this.writeRow(table, id, { ...existing, ...values });\n }\n async deleteRow(table: string, id: string): Promise<void> {\n await this.store.delete(\"db-row-cache\", this.rowKey(table, id));\n }\n\n async readQuery(table: string, q: unknown): Promise<DbQueryPage | null> {\n return this.store.get(\"db-query-cache\", this.queryKey(table, q));\n }\n async writeQuery(table: string, q: unknown, page: DbQueryPage): Promise<void> {\n await this.store.put(\"db-query-cache\", this.queryKey(table, q), page);\n }\n\n async enqueue(\n method: \"insert\" | \"update\" | \"delete\",\n args: unknown,\n hlc: string,\n clientId: string,\n ): Promise<void> {\n await this.manager.enqueue({ hlc, clientId, domain: \"db\", method, args });\n }\n}\n\nexport default DbCache;\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 { VERSION } from \"../version\";\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 { AccessTokensNamespace } from \"./namespaces/AccessTokensNamespace\";\nimport type { SpaceKeyCache } from \"../spaces/SpaceKeyring\";\nimport { VfsNamespace } from \"../vfs/VfsNamespace\";\nimport { VcsNamespace } from \"../vcs/VcsNamespace\";\n\n/** Personal-space key holding the id of the space VFS content is written to. */\nconst VFS_SPACE_KEY = \"vfs/space\";\nimport type { VfsStore } from \"../vfs/types\";\nimport type { Space } from \"../spaces/Space\";\nimport { ChatKeyVault, type ChatKeyStore } from \"./ChatKeyVault\";\nimport type { WrappedPayload } from \"../crypto/PassphraseWrap\";\nimport { OfflineManager } from \"../offline/OfflineManager\";\nimport { isOfflineCapable } from \"../offline/detect\";\nimport { IndexedDbStore } from \"../offline/store/IndexedDbStore\";\nimport { NoopStore } from \"../offline/store/NoopStore\";\nimport type { OfflineStore } from \"../offline/store/OfflineStore\";\nimport { KvCache } from \"../offline/KvCache\";\nimport { DbCache } from \"../offline/DbCache\";\nimport { ShardClient } from \"../storage/transport/ShardClient\";\n\n/** The hosted Muhkoo Accelerator — the default {@link ClientOptions.baseUrl}. */\nexport const DEFAULT_BASE_URL = \"https://api.muhkoo.dev\";\n\n/** The hosted auth SPA — the default {@link ClientOptions.authBaseUrl}. */\nexport const DEFAULT_AUTH_BASE_URL = \"https://auth.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 * A scoped, expiring **access token** (`mk_<env>_at_…`) — the non-ZK\n * machine-to-machine credential. It resolves through the SAME accelerator\n * path as {@link apiKey} (both ride the `X-Muhkoo-Key` header) and, when\n * set, takes precedence over it. Use it for server-side / CI callers that\n * shouldn't carry the app's publishable key. Mint one with\n * `client.accessTokens.create(...)`.\n */\n accessToken?: 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 * Wildcard zone HTTP serverless functions are served from\n * (`<name>--<slug>.<suffix>`), used by `client.functions.invoke(...)`.\n * Defaults to the hosted platform's zone (`fns.muhkoo.dev`); override for\n * staging or a self-hosted deployment.\n */\n functionsHostSuffix?: string;\n /**\n * Base URL of the centralized hosted auth SPA (`client.auth.hosted`).\n * Defaults to {@link DEFAULT_AUTH_BASE_URL} (`auth.muhkoo.dev`); override for\n * staging (`auth.staging.muhkoo.dev`) or a self-hosted deployment.\n */\n authBaseUrl?: string;\n /**\n * Offline support (`client.offline`) — transparent local caching + a durable\n * write queue + CRDT sync. **On by default in browsers** (IndexedDB + Cache\n * API present), a no-op everywhere else. Override to force it on/off or to\n * supply a custom {@link OfflineStore}.\n */\n offline?: {\n /** Force enable/disable. Default: auto-detect (browser on, Node off). */\n enabled?: boolean;\n /** Pluggable persistence. Default: IndexedDB in the browser. */\n store?: OfflineStore;\n /** Cache file-shard bytes in the Cache API. Default: true in the browser. */\n cacheShards?: boolean;\n /** Soft cap on durable-queue bytes before degrading to online-only. */\n maxQueueBytes?: number;\n };\n /**\n * Peer-to-peer block exchange (`client.space` files) among Space members,\n * over WebRTC signaled on the Space relay. Best-effort — falls back to\n * origin. **Opt-in** (browser only). Pass `workerFactory` to run the block\n * engine off the main thread.\n */\n p2p?: {\n enabled?: boolean;\n workerFactory?: () => Worker;\n iceServers?: RTCIceServer[];\n maxPeers?: number;\n /** Log P2P mesh + block-exchange activity to the console (staging/dev). */\n debug?: boolean;\n };\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\n /** Filesystem over the personal space: directories, versions, real paths. */\n readonly vfs: VfsNamespace;\n /** Version control over the VFS: commits, branches, merges — per project. */\n readonly vcs: VcsNamespace;\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 /** Access tokens — `client.accessTokens.create(appId, …)`, etc. */\n readonly accessTokens: AccessTokensNamespace;\n /** Offline cache + sync — `client.offline.status`, `client.offline.snapshot`, etc. */\n readonly offline: OfflineManager;\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 // Build stamp — always logged (independent of logLevel) so the running\n // build is identifiable in the console. Catches stale cached bundles\n // during development; bump `VERSION` (and package.json) each build.\n try {\n console.info(`[@muhkoo/connect] initialized — v${VERSION}`);\n } catch { /* console may be unavailable in some runtimes */ }\n\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 // Offline layer. On by default in browsers, a no-op (NoopStore) in Node,\n // Workers, and SSR — so existing consumers are unaffected unless they're\n // in a browser that can actually cache.\n const offlineEnabled = options.offline?.enabled ?? isOfflineCapable();\n const offlineStore: OfflineStore = offlineEnabled\n ? (options.offline?.store ?? new IndexedDbStore())\n : new NoopStore();\n this.offline = new OfflineManager({\n store: offlineStore,\n session: this.session,\n enabled: offlineEnabled,\n });\n\n // Wrap fetch so every accelerator round-trip feeds the connectivity\n // detector: a thrown fetch is the strongest \"offline\" signal, a 2xx the\n // strongest \"online\" one. Only when offline support is active.\n const baseFetch = options.fetch ?? globalThis.fetch?.bind(globalThis);\n const reportingFetch: typeof fetch | undefined =\n offlineEnabled && baseFetch\n ? async (input, init) => {\n try {\n const res = await baseFetch(input, init);\n this.offline.reportFetchSuccess();\n return res;\n } catch (err) {\n this.offline.reportFetchFailure();\n throw err;\n }\n }\n : options.fetch;\n\n this.http = new HttpClient({\n baseUrl: this.baseUrl,\n apiKey: options.apiKey,\n accessToken: options.accessToken,\n getSessionToken: () => this.session.token,\n fetch: reportingFetch,\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 const authBaseUrl = (options.authBaseUrl ?? DEFAULT_AUTH_BASE_URL).replace(/\\/+$/, \"\");\n this.auth = new AuthNamespace({\n auth: authClient, circuits, session: this.session, authBaseUrl,\n // The accelerator origin, for `auth.hosted`'s device-pairing endpoints.\n apiBaseUrl: this.baseUrl,\n });\n const deferShardUpload = offlineEnabled\n ? (hash: string) => this.offline.deferShardUpload(hash)\n : undefined;\n\n const kvCache = offlineEnabled ? new KvCache(this.offline) : undefined;\n this.kv = new KvNamespace({ http: this.http, session: this.session, wsBaseUrl, offline: kvCache });\n if (offlineEnabled) this.offline.registerReplayer(\"kv\", (e) => this.kv.replay(e));\n const dbCache = offlineEnabled ? new DbCache(this.offline) : undefined;\n this.db = new DbNamespace({ http: this.http, offline: dbCache });\n if (offlineEnabled) this.offline.registerReplayer(\"db\", (e) => this.db.replay(e));\n this.storage = new StorageNamespace({\n http: this.http,\n baseUrl: this.baseUrl,\n kv: this.kv,\n shardCache: this.offline.fileCache,\n deferShardUpload,\n });\n this.message = new MessageNamespace({ http: this.http, session: this.session, wsBaseUrl });\n\n // The VFS stores its metadata in the personal space — the same place\n // `storage.writeFile` already mirrors `{spaceId, manifest}` to, only\n // arranged as a navigable tree instead of a flat index keyed by file id.\n //\n // Content still goes through `storage.writeFile` untouched, into a real\n // Space with a real gated manifest. The space is created once, lazily,\n // and its id recorded in the personal space: a filesystem that has never\n // been written to should not cost a space.\n const personalStore: VfsStore = {\n get: async (key) => {\n const c = this.session.commitment;\n if (!c) throw new Error(\"client.vfs: no session — sign in first.\");\n const res = await this.http.post<{ value: unknown }>(\n `/api/personal/${encodeURIComponent(c)}/kv/${encodeURIComponent(key)}/get`,\n {},\n );\n return res?.value ?? null;\n },\n put: async (key, value) => {\n const c = this.session.commitment;\n if (!c) throw new Error(\"client.vfs: no session — sign in first.\");\n await this.http.post(`/api/personal/${encodeURIComponent(c)}/kv/${encodeURIComponent(key)}`, { value });\n },\n delete: async (key) => {\n const c = this.session.commitment;\n if (!c) throw new Error(\"client.vfs: no session — sign in first.\");\n await this.http.del(`/api/personal/${encodeURIComponent(c)}/kv/${encodeURIComponent(key)}`);\n },\n list: async () => {\n const c = this.session.commitment;\n if (!c) throw new Error(\"client.vfs: no session — sign in first.\");\n const res = await this.http.post<{ keys: string[] }>(\n `/api/personal/${encodeURIComponent(c)}/list`,\n {},\n );\n return res?.keys ?? [];\n },\n };\n\n let contentSpace: Promise<Space> | null = null;\n const resolveContentSpace = (): Promise<Space> => {\n // Cached as the PROMISE, not the value: two concurrent first writes\n // would otherwise each create a space and one would be orphaned.\n if (!contentSpace) {\n contentSpace = (async () => {\n const existing = await personalStore.get(VFS_SPACE_KEY);\n if (typeof existing === \"string\" && existing) return this.space.get(existing);\n // `messaging: false` — this space only ever holds files, and\n // file chunks carry their own keys, so it needs no group\n // keyring and no socket. Creating it the normal way opens a\n // WebSocket, which made the first write hang indefinitely.\n const space = await this.space.createSpace({ private: true, messaging: false });\n await personalStore.put(VFS_SPACE_KEY, space.id);\n return space;\n })().catch((err) => {\n contentSpace = null; // let the next write retry\n throw err;\n });\n }\n return contentSpace;\n };\n\n this.vfs = new VfsNamespace({\n store: personalStore,\n seed: () => this.session.seed,\n // Share the personal space's socket with `client.kv` rather than\n // opening a second one to the same Durable Object.\n subscribe: (handler) => this.kv.onRaw(handler),\n content: {\n // `putFile` needs no WebSocket and commits the shards, so the\n // bytes are metered to the owning app and reference-counted for\n // GC. `storage.writeFile` would additionally index the manifest\n // in the space — a second, diverging source of truth for a file\n // whose handle the VFS already holds.\n write: async (data, meta) => {\n const space = await resolveContentSpace();\n const { manifest, stat } = await space.putFile(data, { name: meta.name, type: meta.type });\n return { manifest, size: stat.size };\n },\n // Reads go through the manifest alone — no space needed. That is\n // the capability path, so it keeps working for a file whose\n // handle was shared from someone else's filesystem.\n read: async (manifest) => (await this.storage.readByManifest(manifest)).data,\n release: async (manifest) => {\n await (await resolveContentSpace()).releaseFile(manifest);\n },\n retain: async (manifest) => {\n await (await resolveContentSpace()).commitFile(manifest);\n },\n },\n });\n\n // Sealed into the SAME personal store as the VFS metadata, so a project\n // and its history live or die together — there is no way to end up with\n // commits whose working tree is gone, or the reverse.\n this.vcs = new VcsNamespace({\n vfs: this.vfs,\n store: personalStore,\n seed: () => this.session.seed,\n author: () => this.session.commitment ?? \"unknown\",\n });\n\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 ciphertext.\n //\n // `encrypt: false` is deliberate: the keyring already ECIES-wraps each\n // key to the member's identity (server-blind), and StorageCipher would\n // additionally require the FULL unlocked identity (`requireIdentity()`),\n // which is locked after a page reload — that coupling is exactly why the\n // cache previously never read or persisted. The wrapped blobs are opaque.\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, { encrypt: false }),\n };\n // SDK-owned vault for the member's long-lived ratchet/space keypair.\n // Stored at the personal-space `chat-keys` key (same key the app used to\n // manage by hand), seed-wrapped, session-token authed (no snarkjs). This\n // gives every app a STABLE keypair across reloads — no per-app scaffolding\n // — so members don't re-admit each load and the group-key cache works.\n const chatKeyStore: ChatKeyStore = {\n get: async (key) => {\n const c = this.session.commitment;\n if (!c) return null;\n const res = await this.http.post<{ value: unknown }>(\n `/api/personal/${encodeURIComponent(c)}/kv/${encodeURIComponent(key)}/get`,\n {},\n );\n return (res?.value ?? null) as WrappedPayload | null;\n },\n put: async (key, value) => {\n const c = this.session.commitment;\n if (!c) throw new Error(\"ChatKeyVault: no session — sign in first.\");\n await this.http.post(`/api/personal/${encodeURIComponent(c)}/kv/${encodeURIComponent(key)}`, { value });\n },\n };\n const chatKeys = new ChatKeyVault(chatKeyStore);\n\n this.space = new SpaceNamespace({\n http: this.http,\n session: this.session,\n wsBaseUrl,\n cache: spaceKeyCache,\n offline: this.offline,\n p2p: options.p2p,\n chatKeys,\n });\n this.agents = new AgentsNamespace({ http: this.http });\n this.functions = new FunctionsNamespace({ http: this.http, fnHostSuffix: options.functionsHostSuffix });\n this.accessTokens = new AccessTokensNamespace({ http: this.http });\n\n // Replay deferred shard uploads on reconnect. The bytes live in the\n // Cache API keyed by hash; re-PUT them through a (defer-free) shard\n // client so a failure surfaces as transient and the entry stays queued.\n if (offlineEnabled && this.offline.fileCache) {\n const replayShards = new ShardClient({\n baseUrl: this.baseUrl,\n pathPrefix: \"/api/shards\",\n fetch: this.http.fetch,\n cache: this.offline.fileCache,\n });\n this.offline.registerReplayer(\"file\", async (entry) => {\n const { hash } = entry.args as { hash: string };\n const bytes = await this.offline.fileCache!.get(hash);\n if (!bytes) return; // evicted from cache — nothing to replay\n await replayShards.putShard(hash, bytes);\n });\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","/**\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 /**\n * Backend-only table — omitted from {@link ejectAgentPrompt}. Use for tables\n * an agent should never be told about (server-managed / internal state).\n */\n backend?: boolean;\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; backend: boolean; }\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 backend: meta.backend ?? false,\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 // Backend-only tables are deliberately withheld — the agent should never be\n // told about server-managed / internal state it can't (and shouldn't) touch.\n const promptTables = d.tables.filter((t) => !t.backend);\n if (promptTables.length) {\n lines.push(\"\", \"App database tables:\");\n for (const t of promptTables) {\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 = promptTables.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","/**\n * `LWWMap` — a map of independent last-write-wins registers, one per column.\n * This is the conflict model for a `db` row: two devices that edit *different*\n * columns of the same row while offline both keep their edits (no lost update),\n * and two that edit the *same* column converge to the greater-HLC write. A row\n * delete is a causal tombstone (see {@link ./ORSet}); a later write to any\n * column resurrects the row with just the surviving columns.\n *\n * This mirrors, on the client, exactly what the accelerator's `_muhkoo_crdt`\n * sidecar does server-side — so a row materializes identically whether it was\n * merged locally (offline) or by the server on replay.\n */\n\nimport { compareHlc } from \"../clock/HlcTimestamp\";\n\nexport interface LwwMap {\n /** Per-column value of the winning write. */\n fields: Record<string, unknown>;\n /** Per-column HLC of the winning write. */\n columnHlc: Record<string, string>;\n /** Row-delete tombstone HLC, or `null` when the row was never deleted. */\n tombstone: string | null;\n}\n\nexport function emptyMap(): LwwMap {\n return { fields: {}, columnHlc: {}, tombstone: null };\n}\n\n/** Apply a local column write (insert/update) at the given per-column HLCs. */\nexport function writeColumns(map: LwwMap, values: Record<string, unknown>, hlc: string): LwwMap {\n const next: LwwMap = {\n fields: { ...map.fields },\n columnHlc: { ...map.columnHlc },\n tombstone: map.tombstone,\n };\n for (const [col, value] of Object.entries(values)) {\n const prev = next.columnHlc[col];\n if (!prev || compareHlc(hlc, prev) > 0) {\n next.fields[col] = value;\n next.columnHlc[col] = hlc;\n }\n }\n return next;\n}\n\n/** Apply a row delete at `hlc` (causal tombstone). */\nexport function tombstoneRow(map: LwwMap, hlc: string): LwwMap {\n const tombstone = !map.tombstone || compareHlc(hlc, map.tombstone) > 0 ? hlc : map.tombstone;\n return { fields: { ...map.fields }, columnHlc: { ...map.columnHlc }, tombstone };\n}\n\n/** Merge two row states column-by-column. Pure; neither input is mutated. */\nexport function mergeMap(a: LwwMap, b: LwwMap): LwwMap {\n const cols = new Set([...Object.keys(a.columnHlc), ...Object.keys(b.columnHlc)]);\n const out = emptyMap();\n for (const col of cols) {\n const ah = a.columnHlc[col];\n const bh = b.columnHlc[col];\n const aWins = ah && (!bh || compareHlc(ah, bh) >= 0);\n const winner = aWins ? a : b;\n out.fields[col] = winner.fields[col];\n out.columnHlc[col] = winner.columnHlc[col];\n }\n out.tombstone =\n a.tombstone && b.tombstone\n ? compareHlc(a.tombstone, b.tombstone) >= 0\n ? a.tombstone\n : b.tombstone\n : (a.tombstone ?? b.tombstone);\n return out;\n}\n\n/**\n * Materialize the visible row from merged state, or `null` when the row is\n * deleted. A column is visible only when its write is causally newer than the\n * tombstone — so a delete hides every prior column, but a post-delete write to\n * a column brings the row back with just that column populated.\n */\nexport function materializeRow(map: LwwMap): Record<string, unknown> | null {\n const visible: Record<string, unknown> = {};\n let any = false;\n for (const [col, hlc] of Object.entries(map.columnHlc)) {\n if (!map.tombstone || compareHlc(hlc, map.tombstone) > 0) {\n visible[col] = map.fields[col];\n any = true;\n }\n }\n return any ? visible : null;\n}\n","/**\n * Tombstone helpers shared by the LWW CRDTs. We don't need a full\n * observed-remove set — every domain that deletes (kv keys, db rows) does so\n * by stamping a delete with an HLC and keeping that stamp around. The only\n * rule that matters is the causal one:\n *\n * a delete at HLC `d` hides the value, but a *later* write at HLC `w > d`\n * resurrects it; a *stale* write at `w <= d` is dropped.\n *\n * Keeping the delete HLC (rather than physically forgetting the key) is what\n * prevents a delayed offline write from \"un-deleting\" something a peer already\n * removed. Callers GC tombstones older than any possible offline window.\n */\n\nimport { compareHlc } from \"../clock/HlcTimestamp\";\n\n/**\n * Does a write at `writeHlc` win against a tombstone at `tombstoneHlc`?\n * `true` ⇒ the write applies (resurrecting a deleted item if needed); `false`\n * ⇒ the tombstone still holds and the write is dropped. A missing tombstone\n * (`null`) means there's nothing suppressing the write.\n */\nexport function writeBeatsTombstone(writeHlc: string, tombstoneHlc: string | null): boolean {\n if (!tombstoneHlc) return true;\n return compareHlc(writeHlc, tombstoneHlc) > 0;\n}\n\n/**\n * Does a delete at `deleteHlc` win against the latest write at `writeHlc`?\n * `true` ⇒ the item is now tombstoned. Ties go to the delete (remove-wins) so\n * that a delete and a write stamped in the same instant resolve deterministically\n * toward removal.\n */\nexport function deleteBeatsWrite(deleteHlc: string, writeHlc: string | null): boolean {\n if (!writeHlc) return true;\n return compareHlc(deleteHlc, writeHlc) >= 0;\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","import { Logger } from \"../utilities/Logger\";\n\nconst appLogger = new Logger(\"connect\", 'ERROR');\nglobalThis.appLogger = appLogger;\n\nexport * from \"../messaging\";\nexport * from \"../messaging/Packet\";\nexport * from \"../types\";\nexport * from \"../crypto\";\nexport * from \"../events\";\nexport * from \"../sessions\";\nexport * from \"../transport\";\n// Universal Groth16 verifier (bn128.wasm-driven). Works anywhere WebAssembly\n// runs: Node, browsers, CF Workers. The same code path the workers build uses.\nexport * from \"../workers/groth16-verifier\";\n// PersonalSpaceClient + passphrase wrap helpers. Pulls in snarkjs as an\n// external — the consuming app's import map (or bundler) resolves it.\nexport * from \"../personal\";\n// FileStorage + ShardClient + SharedSpaceClient (session-based, no snarkjs).\n// Wrapped by `client.storage` on the unified Client.\nexport * from \"../storage\";\n// AuthClient — `/api/auth/*` HTTP wrapper. Browser + server only; the\n// workers build is the auth backend itself, no point importing the client.\nexport * from \"../auth\";\n// Unified Client facade — the supported entry point. These use the `export *`\n// form (not named `export { … } from`) because rollup-plugin-dts silently\n// drops named cross-module re-exports in this codebase's layout, which would\n// strip `Client` et al. from the rolled-up `connect.d.ts`. The class modules\n// don't re-run core's appLogger setup (that lives in `../core/index`, which we\n// deliberately don't import here).\nexport * from \"../core/Client\";\nexport * from \"../core/HttpClient\";\nexport * from \"../core/Session\";\nexport * from \"../core/Room\";\nexport * from \"../core/namespaces/AuthNamespace\";\n// Hosted auth (`client.auth.hosted`): the redirect flow + TV device pairing\n// (startDevicePairing / waitForDevicePairing / approveDevicePairing / …).\n// `HostedAuth` no longer declares its own `AuthUser` — it reuses the one from\n// AuthNamespace above — so these two `export *`s can't produce an ambiguous\n// (and therefore silently dropped) star export.\nexport * from \"../core/namespaces/HostedAuth\";\n// The paired device's at-rest identity store (encrypted localStorage blob +\n// non-extractable IndexedDB key). Read the module docs before relying on it:\n// it is obfuscation, not protection.\nexport * from \"../auth/deviceStore\";\nexport * from \"../core/namespaces/KvNamespace\";\nexport * from \"../core/namespaces/FileNamespace\";\nexport * from \"../core/namespaces/MessageNamespace\";\nexport * from \"../core/namespaces/SpaceNamespace\";\nexport * from \"../core/namespaces/AgentsNamespace\";\nexport * from \"../core/namespaces/FunctionsNamespace\";\nexport * from \"../core/namespaces/AccessTokensNamespace\";\n// The filesystem and its history. Flat `export *` for the same dts-plugin\n// reason as the Client exports above — named re-exports are silently dropped,\n// which would leave `client.vfs`/`client.vcs` usable but untypeable.\nexport * from \"../vfs/VfsNamespace\";\nexport * from \"../vfs/types\";\nexport * from \"../vcs/VcsNamespace\";\nexport * from \"../vcs/types\";\nexport * from \"../vcs/merge3\";\n// WebAuthn helpers — notably `PasskeyOriginError` / `rpIdUsableForOrigin`, so an\n// app can tell \"this passkey belongs to another origin\" from a cancelled prompt.\n// Flat `export *` so the dts plugin keeps the TYPES (named re-exports get dropped).\nexport * from \"../auth/passkey\";\n// App-describing decorators (@MuhkooAgent/@MuhkooSpace/@MuhkooDB/@MuhkooFunction\n// + ejectAgentPrompt). Cherry-picked like the rest of core for the dts plugin.\nexport * from \"../core/agents/describe\";\n// Offline layer — caching + durable write queue + CRDT sync (`client.offline`).\n// Flat `export *` for the same dts-plugin reason as the Client exports above.\nexport * from \"../offline\";\n// P2P layer — private Space-scoped peer block exchange over WebRTC. Opt-in.\nexport * from \"../p2p\";\n// Fan-out group-encryption layer (Space, keyring, cipher). Flat `export *`\n// for the same dts-plugin reason as the Client exports above.\nexport * from \"../spaces/Space\";\nexport * from \"../spaces/SpaceKeyring\";\nexport * from \"../spaces/SpacePacketCipher\";\nexport * from \"../spaces/KeyringClient\";\nexport * from \"../network/PacketCipher\";\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":["toBase64","fromBase64","AES_GCM_IV_BYTES","loadPoseidon","groth16Prove","groth16Verify","bytesToBase64","_snarkjs","loadSnarkjs","FIELD_SIZE","parseOrThrow","wasmEncode","wasmReconstruct","TE","TD","Room","HEADER","appLogger"],"mappings":";;;;;;;;AAKA,MAAM,MAAM,GAAY,CAAC,MAAK;AAC5B,IAAA,IAAI;AACF,QAAA,MAAM,IAAI,GAAI,UAA6D,CAAC,OAAO;AACnF,QAAA,OAAO,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK;IAC9B;AAAE,IAAA,MAAM;AAAE,QAAA,OAAO,KAAK;IAAE;AAC1B,CAAC,GAAG;AACJ,MAAM,KAAK,GAAG,CAAC,IAAY,KACzB,MAAM,GAAG,CAAC,CAAC,KAAK,CAAA,KAAA,EAAQ,IAAI,CAAA,CAAA,EAAI,CAAC,CAAA,OAAA,CAAS,GAAG,CAAC,CAAC,KAAK,CAAC;AACvD,MAAM,MAAM,GAAG;AACX,IAAA,IAAI,EAAK,KAAK,CAAC,IAAI,CAAC;AACpB,IAAA,GAAG,EAAM,KAAK,CAAC,IAAI,CAAC;AACpB,IAAA,KAAK,EAAI,KAAK,CAAC,IAAI,CAAC;AACpB,IAAA,MAAM,EAAG,KAAK,CAAC,IAAI,CAAC;AACpB,IAAA,IAAI,EAAK,KAAK,CAAC,IAAI,CAAC;AACpB,IAAA,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC;AACpB,IAAA,IAAI,EAAK,KAAK,CAAC,IAAI,CAAC;AACpB,IAAA,GAAG,EAAM,KAAK,CAAC,GAAG,CAAC;CACtB;AAED,IAAK,QAOJ;AAPD,CAAA,UAAK,QAA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