@muhkoo/connect 0.2.0-alpha.1 → 0.3.0-alpha.0

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.
@@ -1 +1 @@
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/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/workers/index.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}","/**\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}\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\nexport interface WSTransportOptions {\n /** WebSocket URL, e.g. `ws://localhost:8787/foo`. */\n url: 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\nexport class WSTransport extends EventCore {\n emit = EventCore.emit;\n on = EventCore.on;\n off = EventCore.off;\n\n private url: string;\n private socket: WebSocket | null = null;\n private _isConnected = false;\n private _isConnecting = false;\n\n // Reconnect state\n private autoReconnect: boolean;\n private reconnectDelay: number;\n private maxReconnectAttempts: number;\n private reconnectAttempts = 0;\n private reconnectTimeout: ReturnType<typeof setTimeout> | null = null;\n\n // Outbound queue (raw frame strings — already serialized by caller)\n private outboundQueue: string[] = [];\n private maxQueueSize: number;\n\n 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.autoReconnect = opts.autoReconnect ?? true;\n this.reconnectDelay = opts.reconnectDelay ?? 3000;\n this.maxReconnectAttempts = opts.maxReconnectAttempts ?? 5;\n this.maxQueueSize = opts.maxQueueSize ?? 100;\n }\n\n /** Open the socket. Resolves when CONNECTED fires. Rejects on first error. */\n async connect(): Promise<void> {\n if (this._isConnected || this._isConnecting) {\n throw new Error(\"WSTransport: already connected or connecting\");\n }\n this._isConnecting = true;\n\n return new Promise<void>((resolve, reject) => {\n try {\n const socket = new WebSocket(this.url);\n this.socket = socket;\n\n socket.onopen = () => {\n this._isConnected = true;\n this._isConnecting = false;\n this.reconnectAttempts = 0;\n this.emit(EventCoreEvents.CONNECTED, undefined);\n this.flushQueue();\n resolve();\n };\n\n socket.onmessage = (event: MessageEvent) => {\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.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.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 private scheduleReconnect(): void {\n if (\n this.maxReconnectAttempts > 0 &&\n this.reconnectAttempts >= this.maxReconnectAttempts\n ) {\n this.emit(\n EventCoreEvents.ERROR,\n new Error(\"WSTransport: max reconnect attempts reached\"),\n );\n return;\n }\n this.reconnectAttempts++;\n this.emit(EventCoreEvents.RECONNECTING, { attempt: this.reconnectAttempts });\n this.reconnectTimeout = setTimeout(async () => {\n try {\n await this.connect();\n } catch {\n // scheduleReconnect will fire again from onclose\n }\n }, this.reconnectDelay);\n }\n\n private flushQueue(): void {\n if (this.outboundQueue.length === 0 || !this.socket) return;\n const pending = this.outboundQueue;\n this.outboundQueue = [];\n for (const frame of pending) {\n try {\n this.socket.send(frame);\n } catch {\n // re-queue if a flush fails\n this.outboundQueue.push(frame);\n }\n }\n }\n}\n\nexport default WSTransport;\n","/**\n * 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","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\";\n// Export only crypto modules that don't depend on snarkjs/ZeroKnowledge\n// (snarkjs/ffjavascript use URL.createObjectURL which is incompatible with Workers).\n// Excluded: ZeroKnowledge, Authenticator, DoubleRatchetManager (all depend on snarkjs).\nexport * from \"../crypto/primitives\";\nexport * from \"../crypto/KeyStore\";\nexport * from \"../crypto/DoubleRatchet\";\nexport * from \"../crypto/ChunkCipher\";\nexport * from \"../crypto/PassphraseWrap\";\nexport * from \"../events\";\nexport * from \"../sessions\";\nexport * from \"../transport\";\n\n// Workers-compatible Groth16 verification. Drives bn128.wasm directly; does\n// not pull in @zk-kit/groth16, snarkjs, or ffjavascript (all incompatible with\n// CF Workers — see src/workers/groth16-verifier.ts).\nexport * from \"./groth16-verifier\";\n"],"names":["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,C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,GAAG,MAAM,CAAC;IAC5D;AACF;AAEA,SAAS,KAAK,CAAC,GAAgB,EAAE,IAAY,EAAA;AAC3C,IAAA,OAAO,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;AAAE,QAAA,GAAG,CAAC,CAAC,CAAC,EAAE;AAC3B,IAAA,MAAM,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC;AAClB,IAAA,GAAG,CAAC,CAAC,CAAC,IAAI,IAAI;AACd,IAAA,OAAO,GAAG;AACZ;;ACtSA,MAAMA,WAAS,GAAG,IAAI,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC;AAChD,UAAU,CAAC,SAAS,GAAGA,WAAS;;;;"}
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/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/workers/index.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}","/**\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}\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 * Stable identifier for this connection (a channel / space / personal-space\n * id). Lifecycle + MESSAGE events are namespaced by it on the shared\n * `EventCore` bus so concurrent transports (chat room A, room B, the storage\n * feed, …) never receive each other's frames. Optional — a unique id is\n * generated when omitted; pass a semantic one for clearer debugging.\n */\n id?: string;\n /** Reconnect automatically after unexpected disconnect (default `true`). */\n autoReconnect?: boolean;\n /** Delay between reconnect attempts in ms (default `3000`). */\n reconnectDelay?: number;\n /** Cap on reconnect attempts (default `5`; `0` means unlimited). */\n maxReconnectAttempts?: number;\n /**\n * Max outbound frames buffered while disconnected. Sending past this caps\n * throws synchronously. Default `100`.\n */\n maxQueueSize?: number;\n /**\n * Heartbeat interval in ms. While connected, a `pingFrame` is sent every\n * interval to keep the socket warm (long-lived WebSockets get dropped by CF\n * / intermediaries when idle) and to detect a silently-dead connection.\n * Default `30000`. Set `0` to disable the heartbeat entirely.\n */\n heartbeatInterval?: number;\n /**\n * How long (ms) to wait for a `pongFrame` after sending a ping before\n * treating the connection as dead and forcing a reconnect. Should be well\n * under `heartbeatInterval`. Default `10000`.\n */\n heartbeatTimeout?: number;\n /** Outbound keep-alive frame. Default `\"ping\"`. */\n pingFrame?: string;\n /**\n * Inbound keep-alive ack. Matching frames are swallowed (never surfaced as a\n * `MESSAGE`) and reset the liveness timer. Must match the server's\n * auto-response. Default `\"pong\"`.\n */\n pongFrame?: string;\n}\n\nexport class WSTransport extends EventCore {\n /**\n * Per-instance event scope. `EventCore` is a process-global static emitter,\n * so without namespacing every WSTransport would hear every other one's\n * frames. We prefix each event with this transport's `id` and expose\n * `on`/`off`/`emit` that scope transparently — callers still use the plain\n * `EventCoreEvents` enum and only ever see their own connection's events.\n */\n readonly id: string;\n\n readonly emit = (event: EventCoreEvents, data: unknown): void => {\n EventCore.emit(this.scopedEvent(event), data);\n };\n readonly on = (event: EventCoreEvents, handler: EventListener | CallableFunction): void => {\n EventCore.on(this.scopedEvent(event), handler);\n };\n readonly off = (event: EventCoreEvents, handler: EventListener | CallableFunction): void => {\n EventCore.off(this.scopedEvent(event), handler);\n };\n\n private scopedEvent(event: EventCoreEvents): EventCoreEvents {\n return `${this.id}:${event}` as EventCoreEvents;\n }\n\n private url: string;\n private socket: WebSocket | null = null;\n private _isConnected = false;\n private _isConnecting = false;\n\n // Reconnect state\n private autoReconnect: boolean;\n private reconnectDelay: number;\n private maxReconnectAttempts: number;\n private reconnectAttempts = 0;\n private reconnectTimeout: ReturnType<typeof setTimeout> | null = null;\n\n // Outbound queue (raw frame strings — already serialized by caller)\n private outboundQueue: string[] = [];\n private maxQueueSize: number;\n\n // Heartbeat / liveness state\n private heartbeatInterval: number;\n private heartbeatTimeout: number;\n private pingFrame: string;\n private pongFrame: string;\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n private pongTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(opts: WSTransportOptions) {\n super();\n if (!opts || !opts.url) {\n throw new Error(\"WSTransport: `url` is required\");\n }\n this.url = opts.url;\n this.id = opts.id ?? `ws${++__wsInstanceSeq}`;\n this.autoReconnect = opts.autoReconnect ?? true;\n this.reconnectDelay = opts.reconnectDelay ?? 3000;\n this.maxReconnectAttempts = opts.maxReconnectAttempts ?? 5;\n this.maxQueueSize = opts.maxQueueSize ?? 100;\n this.heartbeatInterval = opts.heartbeatInterval ?? 30000;\n this.heartbeatTimeout = opts.heartbeatTimeout ?? 10000;\n this.pingFrame = opts.pingFrame ?? \"ping\";\n this.pongFrame = opts.pongFrame ?? \"pong\";\n }\n\n /** Open the socket. Resolves when CONNECTED fires. Rejects on first error. */\n async connect(): Promise<void> {\n if (this._isConnected || this._isConnecting) {\n throw new Error(\"WSTransport: already connected or connecting\");\n }\n this._isConnecting = true;\n\n return new Promise<void>((resolve, reject) => {\n try {\n const socket = new WebSocket(this.url);\n this.socket = socket;\n\n socket.onopen = () => {\n this._isConnected = true;\n this._isConnecting = false;\n this.reconnectAttempts = 0;\n this.emit(EventCoreEvents.CONNECTED, undefined);\n this.flushQueue();\n this.startHeartbeat();\n resolve();\n };\n\n socket.onmessage = (event: MessageEvent) => {\n // Heartbeat ack — swallow it (don't surface as a MESSAGE) and clear\n // the liveness deadline. The layer above never sees keep-alive frames.\n if (event.data === this.pongFrame) {\n if (this.pongTimer) {\n clearTimeout(this.pongTimer);\n this.pongTimer = null;\n }\n return;\n }\n // Raw inbound frame — layer above is responsible for parsing.\n this.emit(EventCoreEvents.MESSAGE, event.data);\n };\n\n socket.onerror = (err) => {\n this.emit(EventCoreEvents.ERROR, err);\n if (this._isConnecting) {\n this._isConnecting = false;\n reject(err);\n }\n };\n\n socket.onclose = () => {\n const wasConnected = this._isConnected;\n this._isConnected = false;\n this._isConnecting = false;\n this.stopHeartbeat();\n this.emit(EventCoreEvents.DISCONNECTED, undefined);\n if (this.autoReconnect && wasConnected) {\n this.scheduleReconnect();\n }\n };\n } catch (err) {\n this._isConnecting = false;\n reject(err);\n }\n });\n }\n\n /** Close the socket and stop reconnecting. */\n disconnect(): void {\n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n }\n this.stopHeartbeat();\n this.autoReconnect = false;\n if (this.socket) {\n try { this.socket.close(); } catch { /* ignore */ }\n this.socket = null;\n }\n this._isConnected = false;\n this._isConnecting = false;\n }\n\n /**\n * Send a raw frame. If currently disconnected, the frame is queued and sent\n * after the next successful reconnect (up to `maxQueueSize`).\n */\n send(frame: string): void {\n if (this._isConnected && this.socket) {\n this.socket.send(frame);\n return;\n }\n if (this.outboundQueue.length >= this.maxQueueSize) {\n throw new Error(\n `WSTransport: outbound queue full (${this.maxQueueSize}); drop or wait for reconnect`,\n );\n }\n this.outboundQueue.push(frame);\n }\n\n isConnected(): boolean { return this._isConnected; }\n isConnecting(): boolean { return this._isConnecting; }\n queuedFrames(): number { return this.outboundQueue.length; }\n reconnectAttemptCount(): number { return this.reconnectAttempts; }\n\n // -- internals -------------------------------------------------------------\n\n /** Begin the keep-alive loop (no-op when disabled). */\n private startHeartbeat(): void {\n if (this.heartbeatInterval <= 0) return;\n this.stopHeartbeat();\n this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.heartbeatInterval);\n }\n\n /** Stop the keep-alive loop and clear any pending liveness deadline. */\n private stopHeartbeat(): void {\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n if (this.pongTimer) {\n clearTimeout(this.pongTimer);\n this.pongTimer = null;\n }\n }\n\n /**\n * Send one ping and arm a liveness deadline. If no `pongFrame` arrives before\n * `heartbeatTimeout`, the connection is considered dead and we force a\n * reconnect — this is what catches a silently-dropped TCP connection that\n * never fired `onclose` (the failure mode that \"loses connection with the\n * Accelerator\" on long sessions).\n */\n private sendHeartbeat(): void {\n if (!this._isConnected || !this.socket) return;\n try {\n this.socket.send(this.pingFrame);\n } catch {\n this.forceReconnect();\n return;\n }\n // A still-pending deadline means the previous pong never came back.\n if (this.pongTimer) return;\n this.pongTimer = setTimeout(() => {\n this.pongTimer = null;\n this.forceReconnect();\n }, this.heartbeatTimeout);\n }\n\n /**\n * Tear down a connection we believe is dead and kick off reconnect, without\n * waiting on the OS/browser to eventually fire `onclose` (which a half-open\n * socket may never do). We detach the handlers first so the normal close path\n * can't double-fire the reconnect.\n */\n private forceReconnect(): void {\n this.stopHeartbeat();\n const sock = this.socket;\n const wasConnected = this._isConnected;\n this.socket = null;\n this._isConnected = false;\n this._isConnecting = false;\n if (sock) {\n sock.onopen = null;\n sock.onmessage = null;\n sock.onerror = null;\n sock.onclose = null;\n try { sock.close(); } catch { /* already gone */ }\n }\n this.emit(EventCoreEvents.ERROR, new Error(\"WSTransport: heartbeat timeout\"));\n this.emit(EventCoreEvents.DISCONNECTED, undefined);\n if (this.autoReconnect && wasConnected) {\n this.scheduleReconnect();\n }\n }\n\n private scheduleReconnect(): void {\n if (\n this.maxReconnectAttempts > 0 &&\n this.reconnectAttempts >= this.maxReconnectAttempts\n ) {\n this.emit(\n EventCoreEvents.ERROR,\n new Error(\"WSTransport: max reconnect attempts reached\"),\n );\n return;\n }\n this.reconnectAttempts++;\n this.emit(EventCoreEvents.RECONNECTING, { attempt: this.reconnectAttempts });\n this.reconnectTimeout = setTimeout(async () => {\n try {\n await this.connect();\n } catch {\n // scheduleReconnect will fire again from onclose\n }\n }, this.reconnectDelay);\n }\n\n private flushQueue(): void {\n if (this.outboundQueue.length === 0 || !this.socket) return;\n const pending = this.outboundQueue;\n this.outboundQueue = [];\n for (const frame of pending) {\n try {\n this.socket.send(frame);\n } catch {\n // re-queue if a flush fails\n this.outboundQueue.push(frame);\n }\n }\n }\n}\n\nexport default WSTransport;\n","/**\n * 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","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\";\n// Export only crypto modules that don't depend on snarkjs/ZeroKnowledge\n// (snarkjs/ffjavascript use URL.createObjectURL which is incompatible with Workers).\n// Excluded: ZeroKnowledge, Authenticator, DoubleRatchetManager (all depend on snarkjs).\nexport * from \"../crypto/primitives\";\nexport * from \"../crypto/KeyStore\";\nexport * from \"../crypto/DoubleRatchet\";\nexport * from \"../crypto/ChunkCipher\";\nexport * from \"../crypto/PassphraseWrap\";\nexport * from \"../events\";\nexport * from \"../sessions\";\nexport * from \"../transport\";\n\n// Workers-compatible Groth16 verification. Drives bn128.wasm directly; does\n// not pull in @zk-kit/groth16, snarkjs, or ffjavascript (all incompatible with\n// CF Workers — see src/workers/groth16-verifier.ts).\nexport * from \"./groth16-verifier\";\n"],"names":["appLogger"],"mappings":"AAKA,MAAM,MAAM,GAAY,CAAC,MAAK;AAC5B,IAAA,IAAI;AACF,QAAA,MAAM,IAAI,GAAI,UAA6D,CAAC,OAAO;AACnF,QAAA,OAAO,CAAC,CAAC,IAA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