@prson/login-sdk 0.1.0 → 0.2.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.
- package/README.md +18 -2
- package/dist/api.js +3 -2
- package/dist/csp.d.ts +39 -0
- package/dist/csp.js +125 -0
- package/dist/errors.d.ts +40 -0
- package/dist/errors.js +28 -0
- package/dist/index.d.ts +32 -14
- package/dist/index.js +207 -31
- package/dist/index.js.map +3 -3
- package/dist/point_phone_overlay.js +4 -0
- package/dist/select_overlay.js +4 -0
- package/dist/session.d.ts +8 -2
- package/dist/session.js +21 -2
- package/dist/signaling.d.ts +0 -10
- package/dist/signaling.js +4 -3
- package/dist/transport.d.ts +17 -12
- package/dist/transport.js +39 -10
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../node_modules/@stablelib/random/source/browser.ts", "../node_modules/@stablelib/wipe/wipe.ts", "../node_modules/@stablelib/random/source/node.ts", "../node_modules/@stablelib/random/source/system.ts", "../node_modules/@stablelib/int/int.ts", "../node_modules/@stablelib/binary/binary.ts", "../node_modules/@stablelib/random/random.ts", "../node_modules/@stablelib/x25519/x25519.ts", "../node_modules/@stablelib/salsa20/salsa20.ts", "../node_modules/@stablelib/xsalsa20/xsalsa20.ts", "../node_modules/@stablelib/constant-time/constant-time.ts", "../node_modules/@stablelib/poly1305/poly1305.ts", "../node_modules/@stablelib/nacl/secretbox.ts", "../node_modules/@stablelib/nacl/box.ts", "../node_modules/@stablelib/nacl/nacl.ts", "../node_modules/@stablelib/base64/base64.ts", "../src/crypto.ts", "../src/status.ts", "../src/verify.ts", "../src/requests.ts", "../src/session.ts", "../src/api.ts", "../src/signaling.ts", "../src/transport.ts", "../src/qr.ts", "../src/notify.ts", "../src/select_overlay.ts", "../src/point_phone_overlay.ts", "../src/bind.ts", "../src/verification.ts", "../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\n\nconst QUOTA = 65536;\n\nexport class BrowserRandomSource implements RandomSource {\n isAvailable = false;\n isInstantiated = false;\n\n private _crypto?: { getRandomValues: typeof window.crypto.getRandomValues };\n\n constructor() {\n const browserCrypto = typeof self !== 'undefined'\n ? (self.crypto || (self as { msCrypto?: any }).msCrypto) // IE11 has msCrypto\n : null;\n\n if (browserCrypto && browserCrypto.getRandomValues !== undefined) {\n this._crypto = browserCrypto;\n this.isAvailable = true;\n this.isInstantiated = true;\n }\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable || !this._crypto) {\n throw new Error(\"Browser random byte generator is not available.\");\n }\n const out = new Uint8Array(length);\n for (let i = 0; i < out.length; i += QUOTA) {\n this._crypto.getRandomValues(out.subarray(i, i + Math.min(out.length - i, QUOTA)));\n }\n return out;\n }\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package wipe implements functions for zeroing arrays.\n */\n\nexport type NumericArray = number[] | Uint8Array | Int8Array | Uint16Array\n | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array;\n\n/**\n * Sets all values in the given array to zero and returns it.\n *\n * The fact that it sets bytes to zero can be relied on.\n *\n * There is no guarantee that this function makes data disappear from memory,\n * as runtime implementation can, for example, have copying garbage collector\n * that will make copies of sensitive data before we wipe it. Or that an\n * operating system will write our data to swap or sleep image. Another thing\n * is that an optimizing compiler can remove calls to this function or make it\n * no-op. There's nothing we can do with it, so we just do our best and hope\n * that everything will be okay and good will triumph over evil.\n */\nexport function wipe(array: NumericArray): NumericArray {\n // Right now it's similar to array.fill(0). If it turns\n // out that runtimes optimize this call away, maybe\n // we can try something else.\n for (let i = 0; i < array.length; i++) {\n array[i] = 0;\n }\n return array;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\nimport { wipe } from \"@stablelib/wipe\";\n\ndeclare function require(name: string): any;\n\nexport class NodeRandomSource implements RandomSource {\n isAvailable = false;\n isInstantiated = false;\n\n private _crypto: { randomBytes(n: number): Uint8Array } | undefined;\n\n constructor() {\n if (typeof require !== \"undefined\") {\n const nodeCrypto = require(\"crypto\");\n if (nodeCrypto && nodeCrypto.randomBytes) {\n this._crypto = nodeCrypto;\n this.isAvailable = true;\n this.isInstantiated = true;\n }\n }\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable || !this._crypto) {\n throw new Error(\"Node.js random byte generator is not available.\");\n }\n\n // Get random bytes (result is Buffer).\n let buffer = this._crypto.randomBytes(length);\n\n // Make sure we got the length that we requested.\n if (buffer.length !== length) {\n throw new Error(\"NodeRandomSource: got fewer bytes than requested\");\n }\n\n // Allocate output array.\n const out = new Uint8Array(length);\n\n // Copy bytes from buffer to output.\n for (let i = 0; i < out.length; i++) {\n out[i] = buffer[i];\n }\n\n // Cleanup.\n wipe(buffer);\n\n return out;\n }\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\nimport { BrowserRandomSource } from \"./browser\";\nimport { NodeRandomSource } from \"./node\";\n\nexport class SystemRandomSource implements RandomSource {\n isAvailable = false;\n name = \"\";\n private _source: RandomSource;\n\n constructor() {\n // Try browser.\n this._source = new BrowserRandomSource();\n if (this._source.isAvailable) {\n this.isAvailable = true;\n this.name = \"Browser\";\n return;\n }\n\n // If no browser source, try Node.\n this._source = new NodeRandomSource();\n if (this._source.isAvailable) {\n this.isAvailable = true;\n this.name = \"Node\";\n return;\n }\n\n // No sources, we're out of options.\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable) {\n throw new Error(\"System random byte generator is not available.\");\n }\n return this._source.randomBytes(length);\n }\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package int provides helper functions for integerss.\n */\n\n// Shim using 16-bit pieces.\nfunction imulShim(a: number, b: number): number {\n const ah = (a >>> 16) & 0xffff, al = a & 0xffff;\n const bh = (b >>> 16) & 0xffff, bl = b & 0xffff;\n return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);\n}\n\n/** 32-bit integer multiplication. */\n// Use system Math.imul if available, otherwise use our shim.\nexport const mul = (Math as { imul?(a: number, b: number): number }).imul || imulShim;\n\n/** 32-bit integer addition. */\nexport function add(a: number, b: number): number {\n return (a + b) | 0;\n}\n\n/** 32-bit integer subtraction. */\nexport function sub(a: number, b: number): number {\n return (a - b) | 0;\n}\n\n/** 32-bit integer left rotation */\nexport function rotl(x: number, n: number): number {\n return x << n | x >>> (32 - n);\n}\n\n/** 32-bit integer left rotation */\nexport function rotr(x: number, n: number): number {\n return x << (32 - n) | x >>> n;\n}\n\nfunction isIntegerShim(n: number): boolean {\n return typeof n === \"number\" && isFinite(n) && Math.floor(n) === n;\n}\n\n/**\n * Returns true if the argument is an integer number.\n *\n * In ES2015, Number.isInteger.\n */\nexport const isInteger = (Number as { isInteger?(n: number): boolean }).isInteger || isIntegerShim;\n\n/**\n * Math.pow(2, 53) - 1\n *\n * In ES2015 Number.MAX_SAFE_INTEGER.\n */\nexport const MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Returns true if the argument is a safe integer number\n * (-MIN_SAFE_INTEGER < number <= MAX_SAFE_INTEGER)\n *\n * In ES2015, Number.isSafeInteger.\n */\nexport const isSafeInteger = (n: number): boolean =>\n isInteger(n) && (n >= -MAX_SAFE_INTEGER && n <= MAX_SAFE_INTEGER);\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package binary provides functions for encoding and decoding numbers in byte arrays.\n */\n\nimport { isSafeInteger } from \"@stablelib/int\";\n\n// TODO(dchest): add asserts for correct value ranges and array offsets.\n\n/**\n * Reads 2 bytes from array starting at offset as big-endian\n * signed 16-bit integer and returns it.\n */\nexport function readInt16BE(array: Uint8Array, offset = 0): number {\n return (((array[offset + 0] << 8) | array[offset + 1]) << 16) >> 16;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as big-endian\n * unsigned 16-bit integer and returns it.\n */\nexport function readUint16BE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 0] << 8) | array[offset + 1]) >>> 0;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as little-endian\n * signed 16-bit integer and returns it.\n */\nexport function readInt16LE(array: Uint8Array, offset = 0): number {\n return (((array[offset + 1] << 8) | array[offset]) << 16) >> 16;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as little-endian\n * unsigned 16-bit integer and returns it.\n */\nexport function readUint16LE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 1] << 8) | array[offset]) >>> 0;\n}\n\n/**\n * Writes 2-byte big-endian representation of 16-bit unsigned\n * value to byte array starting at offset.\n *\n * If byte array is not given, creates a new 2-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint16BE(value: number, out = new Uint8Array(2), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 8;\n out[offset + 1] = value >>> 0;\n return out;\n}\n\nexport const writeInt16BE = writeUint16BE;\n\n/**\n * Writes 2-byte little-endian representation of 16-bit unsigned\n * value to array starting at offset.\n *\n * If byte array is not given, creates a new 2-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint16LE(value: number, out = new Uint8Array(2), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 0;\n out[offset + 1] = value >>> 8;\n return out;\n}\n\nexport const writeInt16LE = writeUint16LE;\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * signed 32-bit integer and returns it.\n */\nexport function readInt32BE(array: Uint8Array, offset = 0): number {\n return (array[offset] << 24) |\n (array[offset + 1] << 16) |\n (array[offset + 2] << 8) |\n array[offset + 3];\n}\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * unsigned 32-bit integer and returns it.\n */\nexport function readUint32BE(array: Uint8Array, offset = 0): number {\n return ((array[offset] << 24) |\n (array[offset + 1] << 16) |\n (array[offset + 2] << 8) |\n array[offset + 3]) >>> 0;\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * signed 32-bit integer and returns it.\n */\nexport function readInt32LE(array: Uint8Array, offset = 0): number {\n return (array[offset + 3] << 24) |\n (array[offset + 2] << 16) |\n (array[offset + 1] << 8) |\n array[offset];\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * unsigned 32-bit integer and returns it.\n */\nexport function readUint32LE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 3] << 24) |\n (array[offset + 2] << 16) |\n (array[offset + 1] << 8) |\n array[offset]) >>> 0;\n}\n\n/**\n * Writes 4-byte big-endian representation of 32-bit unsigned\n * value to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint32BE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 24;\n out[offset + 1] = value >>> 16;\n out[offset + 2] = value >>> 8;\n out[offset + 3] = value >>> 0;\n return out;\n}\n\nexport const writeInt32BE = writeUint32BE;\n\n/**\n * Writes 4-byte little-endian representation of 32-bit unsigned\n * value to array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint32LE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 0;\n out[offset + 1] = value >>> 8;\n out[offset + 2] = value >>> 16;\n out[offset + 3] = value >>> 24;\n return out;\n}\n\n\nexport const writeInt32LE = writeUint32LE;\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * signed 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports exact\n * numbers in range -9007199254740991 to 9007199254740991.\n * If the number stored in the byte array is outside this range,\n * the result is not exact.\n */\nexport function readInt64BE(array: Uint8Array, offset = 0): number {\n const hi = readInt32BE(array, offset);\n const lo = readInt32BE(array, offset + 4);\n return hi * 0x100000000 + lo - ((lo>>31) * 0x100000000);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * unsigned 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports values up to 2^53-1.\n */\nexport function readUint64BE(array: Uint8Array, offset = 0): number {\n const hi = readUint32BE(array, offset);\n const lo = readUint32BE(array, offset + 4);\n return hi * 0x100000000 + lo;\n}\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * signed 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports exact\n * numbers in range -9007199254740991 to 9007199254740991.\n * If the number stored in the byte array is outside this range,\n * the result is not exact.\n */\nexport function readInt64LE(array: Uint8Array, offset = 0): number {\n const lo = readInt32LE(array, offset);\n const hi = readInt32LE(array, offset + 4);\n return hi * 0x100000000 + lo - ((lo>>31) * 0x100000000);\n}\n\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * unsigned 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports values up to 2^53-1.\n */\nexport function readUint64LE(array: Uint8Array, offset = 0): number {\n const lo = readUint32LE(array, offset);\n const hi = readUint32LE(array, offset + 4);\n return hi * 0x100000000 + lo;\n}\n\n/**\n * Writes 8-byte big-endian representation of 64-bit unsigned\n * value to byte array starting at offset.\n *\n * Due to JavaScript limitation, supports values up to 2^53-1.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint64BE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n writeUint32BE(value / 0x100000000 >>> 0, out, offset);\n writeUint32BE(value >>> 0, out, offset + 4);\n return out;\n}\n\nexport const writeInt64BE = writeUint64BE;\n\n/**\n * Writes 8-byte little-endian representation of 64-bit unsigned\n * value to byte array starting at offset.\n *\n * Due to JavaScript limitation, supports values up to 2^53-1.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint64LE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n writeUint32LE(value >>> 0, out, offset);\n writeUint32LE(value / 0x100000000 >>> 0, out, offset + 4);\n return out;\n}\n\nexport const writeInt64LE = writeUint64LE;\n\n/**\n * Reads bytes from array starting at offset as big-endian\n * unsigned bitLen-bit integer and returns it.\n *\n * Supports bit lengths divisible by 8, up to 48.\n */\nexport function readUintBE(bitLength: number, array: Uint8Array, offset = 0): number {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"readUintBE supports only bitLengths divisible by 8\");\n }\n if (bitLength / 8 > array.length - offset) {\n throw new Error(\"readUintBE: array is too short for the given bitLength\");\n }\n let result = 0;\n let mul = 1;\n for (let i = bitLength / 8 + offset - 1; i >= offset; i--) {\n result += array[i] * mul;\n mul *= 256;\n }\n return result;\n}\n\n/**\n * Reads bytes from array starting at offset as little-endian\n * unsigned bitLen-bit integer and returns it.\n *\n * Supports bit lengths divisible by 8, up to 48.\n */\nexport function readUintLE(bitLength: number, array: Uint8Array, offset = 0): number {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"readUintLE supports only bitLengths divisible by 8\");\n }\n if (bitLength / 8 > array.length - offset) {\n throw new Error(\"readUintLE: array is too short for the given bitLength\");\n }\n let result = 0;\n let mul = 1;\n for (let i = offset; i < offset + bitLength / 8; i++) {\n result += array[i] * mul;\n mul *= 256;\n }\n return result;\n}\n\n/**\n * Writes a big-endian representation of bitLen-bit unsigned\n * value to array starting at offset.\n *\n * Supports bit lengths divisible by 8, up to 48.\n *\n * If byte array is not given, creates a new one.\n *\n * Returns the output byte array.\n */\nexport function writeUintBE(bitLength: number, value: number,\n out = new Uint8Array(bitLength / 8), offset = 0): Uint8Array {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"writeUintBE supports only bitLengths divisible by 8\");\n }\n if (!isSafeInteger(value)) {\n throw new Error(\"writeUintBE value must be an integer\");\n }\n let div = 1;\n for (let i = bitLength / 8 + offset - 1; i >= offset; i--) {\n out[i] = (value / div) & 0xff;\n div *= 256;\n }\n return out;\n}\n\n/**\n * Writes a little-endian representation of bitLen-bit unsigned\n * value to array starting at offset.\n *\n * Supports bit lengths divisible by 8, up to 48.\n *\n * If byte array is not given, creates a new one.\n *\n * Returns the output byte array.\n */\nexport function writeUintLE(bitLength: number, value: number,\n out = new Uint8Array(bitLength / 8), offset = 0): Uint8Array {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"writeUintLE supports only bitLengths divisible by 8\");\n }\n if (!isSafeInteger(value)) {\n throw new Error(\"writeUintLE value must be an integer\");\n }\n let div = 1;\n for (let i = offset; i < offset + bitLength / 8; i++) {\n out[i] = (value / div) & 0xff;\n div *= 256;\n }\n return out;\n}\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * 32-bit floating-point number and returns it.\n */\nexport function readFloat32BE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat32(offset);\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * 32-bit floating-point number and returns it.\n */\nexport function readFloat32LE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat32(offset, true);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * 64-bit floating-point number (\"double\") and returns it.\n */\nexport function readFloat64BE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat64(offset);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * 64-bit floating-point number (\"double\") and returns it.\n */\nexport function readFloat64LE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat64(offset, true);\n}\n\n/**\n * Writes 4-byte big-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat32BE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat32(offset, value);\n return out;\n}\n\n/**\n * Writes 4-byte little-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat32LE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat32(offset, value, true);\n return out;\n}\n\n/**\n * Writes 8-byte big-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat64BE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat64(offset, value);\n return out;\n}\n\n/**\n * Writes 8-byte little-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat64LE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat64(offset, value, true);\n return out;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package random provides functions to access system's\n * cryptographically secure random byte generator.\n */\n\nimport { RandomSource } from \"./source\";\nimport { SystemRandomSource } from \"./source/system\";\nimport { readUint32LE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport { RandomSource } from \"./source\";\n\nexport const defaultRandomSource = new SystemRandomSource();\n\nexport function randomBytes(length: number, prng: RandomSource = defaultRandomSource): Uint8Array {\n return prng.randomBytes(length);\n}\n\n/**\n * Returns a uniformly random unsigned 32-bit integer.\n */\nexport function randomUint32(prng: RandomSource = defaultRandomSource): number {\n // Generate 4-byte random buffer.\n const buf = randomBytes(4, prng);\n\n // Convert bytes from buffer into a 32-bit integer.\n // It's not important which byte order to use, since\n // the result is random.\n const result = readUint32LE(buf);\n\n // Clean the buffer.\n wipe(buf);\n\n return result;\n}\n\n/** 62 alphanumeric characters for default charset of randomString() */\nconst ALPHANUMERIC = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n/**\n * Returns a uniform random string of the given length\n * with characters from the given charset.\n *\n * Charset must not have more than 256 characters.\n *\n * Default charset generates case-sensitive alphanumeric\n * strings (0-9, A-Z, a-z).\n */\nexport function randomString(\n length: number,\n charset = ALPHANUMERIC,\n prng: RandomSource = defaultRandomSource\n): string {\n if (charset.length < 2) {\n throw new Error(\"randomString charset is too short\");\n }\n if (charset.length > 256) {\n throw new Error(\"randomString charset is too long\");\n }\n let out = '';\n const charsLen = charset.length;\n const maxByte = 256 - (256 % charsLen);\n while (length > 0) {\n const buf = randomBytes(Math.ceil(length * 256 / maxByte), prng);\n for (let i = 0; i < buf.length && length > 0; i++) {\n const randomByte = buf[i];\n if (randomByte < maxByte) {\n out += charset.charAt(randomByte % charsLen);\n length--;\n }\n }\n wipe(buf);\n }\n return out;\n}\n\n/**\n * Returns uniform random string containing at least the given\n * number of bits of entropy.\n *\n * For example, randomStringForEntropy(128) will return a 22-character\n * alphanumeric string, while randomStringForEntropy(128, \"0123456789\")\n * will return a 39-character numeric string, both will contain at\n * least 128 bits of entropy.\n *\n * Default charset generates case-sensitive alphanumeric\n * strings (0-9, A-Z, a-z).\n */\nexport function randomStringForEntropy(\n bits: number,\n charset = ALPHANUMERIC,\n prng: RandomSource = defaultRandomSource\n): string {\n const length = Math.ceil(bits / (Math.log(charset.length) / Math.LN2));\n return randomString(length, charset, prng);\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package x25519 implements X25519 key agreement.\n */\n\nimport { randomBytes, RandomSource } from \"@stablelib/random\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 32;\nexport const SHARED_KEY_LENGTH = 32;\n\n// TODO(dchest): some functions are copies of ../sign/ed25519.\n// Find a way to combine them without opening up to public.\n\n// Ported from TweetNaCl.js, which is ported from TweetNaCl\n// by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n// https://tweetnacl.js.org\n\n// TweetNaCl contributors:\n// Daniel J. Bernstein, Bernard van Gastel, Wesley Janssen,\n// Tanja Lange, Peter Schwabe, Sjaak Smetsers.\n// Public domain.\n// https://tweetnacl.cr.yp.to/\n\ntype GF = Float64Array;\n\n// Returns new zero-filled 16-element GF (Float64Array).\n// If passed an array of numbers, prefills the returned\n// array with them.\n//\n// We use Float64Array, because we need 48-bit numbers\n// for this implementation.\nfunction gf(init?: number[]): GF {\n const r = new Float64Array(16);\n if (init) {\n for (let i = 0; i < init.length; i++) {\n r[i] = init[i];\n }\n }\n return r;\n}\n\n// Base point.\nconst _9 = new Uint8Array(32); _9[0] = 9;\n\nconst _121665 = gf([0xdb41, 1]);\n\nfunction car25519(o: GF) {\n let c = 1;\n for (let i = 0; i < 16; i++) {\n let v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c - 1 + 37 * (c - 1);\n}\n\nfunction sel25519(p: GF, q: GF, b: number) {\n const c = ~(b - 1);\n for (let i = 0; i < 16; i++) {\n const t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o: Uint8Array, n: GF) {\n const m = gf();\n const t = gf();\n for (let i = 0; i < 16; i++) {\n t[i] = n[i];\n }\n car25519(t);\n car25519(t);\n car25519(t);\n for (let j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (let i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);\n m[i - 1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);\n const b = (m[15] >> 16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1 - b);\n }\n for (let i = 0; i < 16; i++) {\n o[2 * i] = t[i] & 0xff;\n o[2 * i + 1] = t[i] >> 8;\n }\n}\n\nfunction unpack25519(o: GF, n: Uint8Array) {\n for (let i = 0; i < 16; i++) {\n o[i] = n[2 * i] + (n[2 * i + 1] << 8);\n }\n o[15] &= 0x7fff;\n}\n\nfunction add(o: GF, a: GF, b: GF) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] + b[i];\n }\n}\n\nfunction sub(o: GF, a: GF, b: GF) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] - b[i];\n }\n}\n\nfunction mul(o: GF, a: GF, b: GF) {\n let v: number, c: number,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n\n o[0] = t0;\n o[1] = t1;\n o[2] = t2;\n o[3] = t3;\n o[4] = t4;\n o[5] = t5;\n o[6] = t6;\n o[7] = t7;\n o[8] = t8;\n o[9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction square(o: GF, a: GF) {\n mul(o, a, a);\n}\n\nfunction inv25519(o: GF, inp: GF) {\n const c = gf();\n for (let i = 0; i < 16; i++) {\n c[i] = inp[i];\n }\n for (let i = 253; i >= 0; i--) {\n square(c, c);\n if (i !== 2 && i !== 4) {\n mul(c, c, inp);\n }\n }\n for (let i = 0; i < 16; i++) {\n o[i] = c[i];\n }\n}\n\nexport function scalarMult(n: Uint8Array, p: Uint8Array): Uint8Array {\n const z = new Uint8Array(32);\n const x = new Float64Array(80);\n const a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n\n for (let i = 0; i < 31; i++) {\n z[i] = n[i];\n }\n z[31] = (n[31] & 127) | 64;\n z[0] &= 248;\n\n unpack25519(x, p);\n\n for (let i = 0; i < 16; i++) {\n b[i] = x[i];\n }\n\n a[0] = d[0] = 1;\n\n for (let i = 254; i >= 0; --i) {\n const r = (z[i >>> 3] >>> (i & 7)) & 1;\n sel25519(a, b, r);\n sel25519(c, d, r);\n add(e, a, c);\n sub(a, a, c);\n add(c, b, d);\n sub(b, b, d);\n square(d, e);\n square(f, a);\n mul(a, c, a);\n mul(c, b, e);\n add(e, a, c);\n sub(a, a, c);\n square(b, a);\n sub(c, d, f);\n mul(a, c, _121665);\n add(a, a, d);\n mul(c, c, a);\n mul(a, d, f);\n mul(d, b, x);\n square(b, e);\n sel25519(a, b, r);\n sel25519(c, d, r);\n }\n for (let i = 0; i < 16; i++) {\n x[i + 16] = a[i];\n x[i + 32] = c[i];\n x[i + 48] = b[i];\n x[i + 64] = d[i];\n }\n const x32 = x.subarray(32);\n const x16 = x.subarray(16);\n inv25519(x32, x32);\n mul(x16, x16, x32);\n const q = new Uint8Array(32);\n pack25519(q, x16);\n return q;\n}\n\nexport function scalarMultBase(n: Uint8Array): Uint8Array {\n return scalarMult(n, _9);\n}\n\nexport interface KeyPair {\n publicKey: Uint8Array;\n secretKey: Uint8Array;\n}\n\nexport function generateKeyPairFromSeed(seed: Uint8Array): KeyPair {\n if (seed.length !== SECRET_KEY_LENGTH) {\n throw new Error(`x25519: seed must be ${SECRET_KEY_LENGTH} bytes`);\n }\n const secretKey = new Uint8Array(seed);\n const publicKey = scalarMultBase(secretKey);\n return {\n publicKey,\n secretKey\n };\n}\n\nexport function generateKeyPair(prng?: RandomSource): KeyPair {\n const seed = randomBytes(32, prng);\n const result = generateKeyPairFromSeed(seed);\n wipe(seed);\n return result;\n}\n\n/**\n * Returns a shared key between our secret key and a peer's public key.\n *\n * Throws an error if the given keys are of wrong length.\n *\n * If rejectZero is true throws if the calculated shared key is all-zero.\n * From RFC 7748:\n *\n * > Protocol designers using Diffie-Hellman over the curves defined in\n * > this document must not assume \"contributory behavior\". Specially,\n * > contributory behavior means that both parties' private keys\n * > contribute to the resulting shared key. Since curve25519 and\n * > curve448 have cofactors of 8 and 4 (respectively), an input point of\n * > small order will eliminate any contribution from the other party's\n * > private key. This situation can be detected by checking for the all-\n * > zero output, which implementations MAY do, as specified in Section 6.\n * > However, a large number of existing implementations do not do this.\n *\n * IMPORTANT: the returned key is a raw result of scalar multiplication.\n * To use it as a key material, hash it with a cryptographic hash function.\n */\nexport function sharedKey(mySecretKey: Uint8Array, theirPublicKey: Uint8Array, rejectZero = false): Uint8Array {\n if (mySecretKey.length !== PUBLIC_KEY_LENGTH) {\n throw new Error(\"X25519: incorrect secret key length\");\n }\n if (theirPublicKey.length !== PUBLIC_KEY_LENGTH) {\n throw new Error(\"X25519: incorrect public key length\");\n }\n\n const result = scalarMult(mySecretKey, theirPublicKey);\n\n if (rejectZero) {\n let zeros = 0;\n for (let i = 0; i < result.length; i++) {\n zeros |= result[i];\n }\n if (zeros === 0) {\n throw new Error(\"X25519: invalid shared key\");\n }\n }\n\n return result;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package salsa20 implements Salsa20 stream cipher.\n */\n\nimport { writeUint32LE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\n// Number of Salsa20 rounds (Salsa20/20).\nconst ROUNDS = 20;\n\n/**\n * Applies the Salsa20 core function to 16-byte input,\n * 32-byte key key, and puts the result into 64-byte array out.\n */\nfunction core(out: Uint8Array, input: Uint8Array, key: Uint8Array): void {\n let j0 = 0x61707865; // \"expa\"\n let j1 = (key[3] << 24) | (key[2] << 16) | (key[1] << 8) | key[0];\n let j2 = (key[7] << 24) | (key[6] << 16) | (key[5] << 8) | key[4];\n let j3 = (key[11] << 24) | (key[10] << 16) | (key[9] << 8) | key[8];\n let j4 = (key[15] << 24) | (key[14] << 16) | (key[13] << 8) | key[12];\n let j5 = 0x3320646E; // \"nd 3\"\n let j6 = (input[3] << 24) | (input[2] << 16) | (input[1] << 8) | input[0];\n let j7 = (input[7] << 24) | (input[6] << 16) | (input[5] << 8) | input[4];\n let j8 = (input[11] << 24) | (input[10] << 16) | (input[9] << 8) | input[8];\n let j9 = (input[15] << 24) | (input[14] << 16) | (input[13] << 8) | input[12];\n let j10 = 0x79622D32; // \"2-by\"\n let j11 = (key[19] << 24) | (key[18] << 16) | (key[17] << 8) | key[16];\n let j12 = (key[23] << 24) | (key[22] << 16) | (key[21] << 8) | key[20];\n let j13 = (key[27] << 24) | (key[26] << 16) | (key[25] << 8) | key[24];\n let j14 = (key[31] << 24) | (key[30] << 16) | (key[29] << 8) | key[28];\n let j15 = 0x6B206574; // \"te k\"\n\n let x0 = j0;\n let x1 = j1;\n let x2 = j2;\n let x3 = j3;\n let x4 = j4;\n let x5 = j5;\n let x6 = j6;\n let x7 = j7;\n let x8 = j8;\n let x9 = j9;\n let x10 = j10;\n let x11 = j11;\n let x12 = j12;\n let x13 = j13;\n let x14 = j14;\n let x15 = j15;\n let u: number;\n\n for (let i = 0; i < ROUNDS; i += 2) {\n u = x0 + x12 | 0;\n x4 ^= u << 7 | u >>> (32 - 7);\n u = x4 + x0 | 0;\n x8 ^= u << 9 | u >>> (32 - 9);\n u = x8 + x4 | 0;\n x12 ^= u << 13 | u >>> (32 - 13);\n u = x12 + x8 | 0;\n x0 ^= u << 18 | u >>> (32 - 18);\n\n u = x5 + x1 | 0;\n x9 ^= u << 7 | u >>> (32 - 7);\n u = x9 + x5 | 0;\n x13 ^= u << 9 | u >>> (32 - 9);\n u = x13 + x9 | 0;\n x1 ^= u << 13 | u >>> (32 - 13);\n u = x1 + x13 | 0;\n x5 ^= u << 18 | u >>> (32 - 18);\n\n u = x10 + x6 | 0;\n x14 ^= u << 7 | u >>> (32 - 7);\n u = x14 + x10 | 0;\n x2 ^= u << 9 | u >>> (32 - 9);\n u = x2 + x14 | 0;\n x6 ^= u << 13 | u >>> (32 - 13);\n u = x6 + x2 | 0;\n x10 ^= u << 18 | u >>> (32 - 18);\n\n u = x15 + x11 | 0;\n x3 ^= u << 7 | u >>> (32 - 7);\n u = x3 + x15 | 0;\n x7 ^= u << 9 | u >>> (32 - 9);\n u = x7 + x3 | 0;\n x11 ^= u << 13 | u >>> (32 - 13);\n u = x11 + x7 | 0;\n x15 ^= u << 18 | u >>> (32 - 18);\n\n u = x0 + x3 | 0;\n x1 ^= u << 7 | u >>> (32 - 7);\n u = x1 + x0 | 0;\n x2 ^= u << 9 | u >>> (32 - 9);\n u = x2 + x1 | 0;\n x3 ^= u << 13 | u >>> (32 - 13);\n u = x3 + x2 | 0;\n x0 ^= u << 18 | u >>> (32 - 18);\n\n u = x5 + x4 | 0;\n x6 ^= u << 7 | u >>> (32 - 7);\n u = x6 + x5 | 0;\n x7 ^= u << 9 | u >>> (32 - 9);\n u = x7 + x6 | 0;\n x4 ^= u << 13 | u >>> (32 - 13);\n u = x4 + x7 | 0;\n x5 ^= u << 18 | u >>> (32 - 18);\n\n u = x10 + x9 | 0;\n x11 ^= u << 7 | u >>> (32 - 7);\n u = x11 + x10 | 0;\n x8 ^= u << 9 | u >>> (32 - 9);\n u = x8 + x11 | 0;\n x9 ^= u << 13 | u >>> (32 - 13);\n u = x9 + x8 | 0;\n x10 ^= u << 18 | u >>> (32 - 18);\n\n u = x15 + x14 | 0;\n x12 ^= u << 7 | u >>> (32 - 7);\n u = x12 + x15 | 0;\n x13 ^= u << 9 | u >>> (32 - 9);\n u = x13 + x12 | 0;\n x14 ^= u << 13 | u >>> (32 - 13);\n u = x14 + x13 | 0;\n x15 ^= u << 18 | u >>> (32 - 18);\n }\n writeUint32LE(x0 + j0 | 0, out, 0);\n writeUint32LE(x1 + j1 | 0, out, 4);\n writeUint32LE(x2 + j2 | 0, out, 8);\n writeUint32LE(x3 + j3 | 0, out, 12);\n writeUint32LE(x4 + j4 | 0, out, 16);\n writeUint32LE(x5 + j5 | 0, out, 20);\n writeUint32LE(x6 + j6 | 0, out, 24);\n writeUint32LE(x7 + j7 | 0, out, 28);\n writeUint32LE(x8 + j8 | 0, out, 32);\n writeUint32LE(x9 + j9 | 0, out, 36);\n writeUint32LE(x10 + j10 | 0, out, 40);\n writeUint32LE(x11 + j11 | 0, out, 44);\n writeUint32LE(x12 + j12 | 0, out, 48);\n writeUint32LE(x13 + j13 | 0, out, 52);\n writeUint32LE(x14 + j14 | 0, out, 56);\n writeUint32LE(x15 + j15 | 0, out, 60);\n}\n\n/**\n * Encrypt src with Salsa20/20 stream generated for the given 32-byte key\n * and 8-byte and write the result into dst and return it.\n *\n * dst and src may be the same, but otherwise must not overlap.\n *\n * Never use the same key and nonce to encrypt more than one message.\n *\n * If nonceInplaceCounterLength is not 0, the nonce is assumed to be a 16-byte\n * array with stream counter in first nonceInplaceCounterLength bytes and nonce\n * in the last remaining bytes. The counter will be incremented inplace for\n * each Salsa20 block. This is useful if you need to encrypt one stream of data\n * in chunks.\n */\nexport function streamXOR(key: Uint8Array, nonce: Uint8Array,\n src: Uint8Array, dst: Uint8Array, nonceInplaceCounterLength = 0): Uint8Array {\n // We only support 256-bit keys.\n if (key.length !== 32) {\n throw new Error(\"Salsa20: key size must be 32 bytes\");\n }\n\n if (dst.length < src.length) {\n throw new Error(\"Salsa20: destination is shorter than source\");\n }\n\n let nc: Uint8Array;\n let counterStart: number;\n\n if (nonceInplaceCounterLength === 0) {\n if (nonce.length !== 8) {\n throw new Error(\"Salsa20 nonce must be 8 bytes\");\n }\n nc = new Uint8Array(16);\n // First bytes of nc are nonce, set it.\n nc.set(nonce);\n // Last bytes are counter.\n counterStart = nonce.length;\n } else {\n if (nonce.length !== 16) {\n throw new Error(\"Salsa20 nonce with counter must be 16 bytes\");\n }\n // This will update passed nonce with counter inplace.\n nc = nonce;\n counterStart = 16 - nonceInplaceCounterLength;\n }\n\n // Allocate temporary space for Salsa20 block.\n const block = new Uint8Array(64);\n\n for (let i = 0; i < src.length; i += 64) {\n // Generate a block.\n core(block, nc, key);\n\n // XOR block bytes with src into dst.\n for (let j = i; j < i + 64 && j < src.length; j++) {\n dst[j] = src[j] ^ block[j - i];\n }\n\n // Increment counter.\n incrementCounter(nc, counterStart, nc.length - counterStart);\n }\n\n // Cleanup temporary space.\n wipe(block);\n\n if (nonceInplaceCounterLength === 0) {\n // Cleanup counter.\n wipe(nc);\n }\n\n return dst;\n}\n\n/**\n * Generate Salsa20/20 stream for the given 32-byte key and 8-byte nonce\n * and write it into dst and return it.\n *\n * Never use the same key and nonce to generate more than one stream.\n *\n * If nonceInplaceCounterLength is not 0, it behaves the same\n * with respect to the nonce as described in streamXOR documentation.\n *\n * stream is like streamXOR with all-zero src.\n */\nexport function stream(key: Uint8Array, nonce: Uint8Array,\n dst: Uint8Array, nonceInplaceCounterLength = 0): Uint8Array {\n wipe(dst);\n return streamXOR(key, nonce, dst, dst, nonceInplaceCounterLength);\n}\n\nfunction incrementCounter(counter: Uint8Array, pos: number, len: number) {\n let carry = 1;\n while (len--) {\n carry = carry + (counter[pos] & 0xff) | 0;\n counter[pos] = carry & 0xff;\n carry >>>= 8;\n pos++;\n }\n if (carry > 0) {\n throw new Error(\"Salsa20: counter overflow\");\n }\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package xsalsa20 implements XSalsa20 stream cipher.\n */\n\nimport { writeUint32LE } from \"@stablelib/binary\";\nimport { streamXOR as salsaStreamXOR } from \"@stablelib/salsa20\";\nimport { wipe } from \"@stablelib/wipe\";\n\n/**\n * Encrypt src with Salsa20/20 stream generated for the given 32-byte key\n * and 24-byte and write the result into dst and return it.\n *\n * dst and src may be the same, but otherwise must not overlap.\n *\n * Never use the same key and nonce to encrypt more than one message.\n */\nexport function streamXOR(key: Uint8Array, nonce: Uint8Array, src: Uint8Array,\n dst: Uint8Array, nonceInplaceCounterLength = 0): Uint8Array {\n\n if (nonceInplaceCounterLength === 0) {\n if (nonce.length !== 24) {\n throw new Error(\"XSalsa20 nonce must be 24 bytes\");\n }\n } else {\n if (nonce.length !== 32) {\n throw new Error(\"XSalsa20 nonce with counter must be 32 bytes\");\n }\n }\n\n // Use HSalsa one-way function to transform first 16 bytes of\n // 24-byte extended nonce and key into a new key for Salsa\n // stream -- \"subkey\".\n const subkey = hsalsa(key, nonce.subarray(0, 16), new Uint8Array(32));\n\n // Use last 8 bytes of 24-byte extended nonce as an actual nonce,\n // and a subkey derived in the previous step as key to encrypt.\n //\n // If nonceInplaceCounterLength > 0, we'll still pass the correct\n // nonce || counter, as we don't limit the end of nonce subarray.\n const result = salsaStreamXOR(subkey, nonce.subarray(16), src, dst,\n nonceInplaceCounterLength);\n\n // Clean subkey.\n wipe(subkey);\n\n return result;\n}\n\n/**\n * Generate Salsa20/20 stream for the given 32-byte key and\n * 24-byte nonce and write it into dst and return it.\n *\n * Never use the same key and nonce to generate more than one stream.\n *\n * stream is like streamXOR with all-zero src.\n */\nexport function stream(key: Uint8Array, nonce: Uint8Array, dst: Uint8Array,\n nonceInplaceCounterLength = 0): Uint8Array {\n\n wipe(dst);\n return streamXOR(key, nonce, dst, dst, nonceInplaceCounterLength);\n}\n\n// Number of Salsa20 rounds (Salsa20/20).\nconst ROUNDS = 20;\n\n/**\n * HSalsa20 is a one-way function used in XSalsa20 to extend nonce,\n * and in NaCl to hash X25519 shared keys. It takes 32-byte key and\n * 16-byte src and writes 32-byte result into dst and returns it.\n */\nexport function hsalsa(key: Uint8Array, src: Uint8Array, dst: Uint8Array): Uint8Array {\n let x0 = 0x61707865; // \"expa\"\n let x1 = (key[3] << 24) | (key[2] << 16) | (key[1] << 8) | key[0];\n let x2 = (key[7] << 24) | (key[6] << 16) | (key[5] << 8) | key[4];\n let x3 = (key[11] << 24) | (key[10] << 16) | (key[9] << 8) | key[8];\n let x4 = (key[15] << 24) | (key[14] << 16) | (key[13] << 8) | key[12];\n let x5 = 0x3320646E; // \"nd 3\"\n let x6 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];\n let x7 = (src[7] << 24) | (src[6] << 16) | (src[5] << 8) | src[4];\n let x8 = (src[11] << 24) | (src[10] << 16) | (src[9] << 8) | src[8];\n let x9 = (src[15] << 24) | (src[14] << 16) | (src[13] << 8) | src[12];\n let x10 = 0x79622D32; // \"2-by\"\n let x11 = (key[19] << 24) | (key[18] << 16) | (key[17] << 8) | key[16];\n let x12 = (key[23] << 24) | (key[22] << 16) | (key[21] << 8) | key[20];\n let x13 = (key[27] << 24) | (key[26] << 16) | (key[25] << 8) | key[24];\n let x14 = (key[31] << 24) | (key[30] << 16) | (key[29] << 8) | key[28];\n let x15 = 0x6B206574; // \"te k\"\n\n let u: number;\n\n for (let i = 0; i < ROUNDS; i += 2) {\n u = x0 + x12 | 0;\n x4 ^= u << 7 | u >>> (32 - 7);\n u = x4 + x0 | 0;\n x8 ^= u << 9 | u >>> (32 - 9);\n u = x8 + x4 | 0;\n x12 ^= u << 13 | u >>> (32 - 13);\n u = x12 + x8 | 0;\n x0 ^= u << 18 | u >>> (32 - 18);\n\n u = x5 + x1 | 0;\n x9 ^= u << 7 | u >>> (32 - 7);\n u = x9 + x5 | 0;\n x13 ^= u << 9 | u >>> (32 - 9);\n u = x13 + x9 | 0;\n x1 ^= u << 13 | u >>> (32 - 13);\n u = x1 + x13 | 0;\n x5 ^= u << 18 | u >>> (32 - 18);\n\n u = x10 + x6 | 0;\n x14 ^= u << 7 | u >>> (32 - 7);\n u = x14 + x10 | 0;\n x2 ^= u << 9 | u >>> (32 - 9);\n u = x2 + x14 | 0;\n x6 ^= u << 13 | u >>> (32 - 13);\n u = x6 + x2 | 0;\n x10 ^= u << 18 | u >>> (32 - 18);\n\n u = x15 + x11 | 0;\n x3 ^= u << 7 | u >>> (32 - 7);\n u = x3 + x15 | 0;\n x7 ^= u << 9 | u >>> (32 - 9);\n u = x7 + x3 | 0;\n x11 ^= u << 13 | u >>> (32 - 13);\n u = x11 + x7 | 0;\n x15 ^= u << 18 | u >>> (32 - 18);\n\n u = x0 + x3 | 0;\n x1 ^= u << 7 | u >>> (32 - 7);\n u = x1 + x0 | 0;\n x2 ^= u << 9 | u >>> (32 - 9);\n u = x2 + x1 | 0;\n x3 ^= u << 13 | u >>> (32 - 13);\n u = x3 + x2 | 0;\n x0 ^= u << 18 | u >>> (32 - 18);\n\n u = x5 + x4 | 0;\n x6 ^= u << 7 | u >>> (32 - 7);\n u = x6 + x5 | 0;\n x7 ^= u << 9 | u >>> (32 - 9);\n u = x7 + x6 | 0;\n x4 ^= u << 13 | u >>> (32 - 13);\n u = x4 + x7 | 0;\n x5 ^= u << 18 | u >>> (32 - 18);\n\n u = x10 + x9 | 0;\n x11 ^= u << 7 | u >>> (32 - 7);\n u = x11 + x10 | 0;\n x8 ^= u << 9 | u >>> (32 - 9);\n u = x8 + x11 | 0;\n x9 ^= u << 13 | u >>> (32 - 13);\n u = x9 + x8 | 0;\n x10 ^= u << 18 | u >>> (32 - 18);\n\n u = x15 + x14 | 0;\n x12 ^= u << 7 | u >>> (32 - 7);\n u = x12 + x15 | 0;\n x13 ^= u << 9 | u >>> (32 - 9);\n u = x13 + x12 | 0;\n x14 ^= u << 13 | u >>> (32 - 13);\n u = x14 + x13 | 0;\n x15 ^= u << 18 | u >>> (32 - 18);\n }\n writeUint32LE(x0, dst, 0);\n writeUint32LE(x5, dst, 4);\n writeUint32LE(x10, dst, 8);\n writeUint32LE(x15, dst, 12);\n writeUint32LE(x6, dst, 16);\n writeUint32LE(x7, dst, 20);\n writeUint32LE(x8, dst, 24);\n writeUint32LE(x9, dst, 28);\n return dst;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package constant-time provides functions for performing algorithmically constant-time operations.\n */\n\n/**\n * NOTE! Due to the inability to guarantee real constant time evaluation of\n * anything in JavaScript VM, this is module is the best effort.\n */\n\n/**\n * Returns resultIfOne if subject is 1, or resultIfZero if subject is 0.\n *\n * Supports only 32-bit integers, so resultIfOne or resultIfZero are not\n * integers, they'll be converted to them with bitwise operations.\n */\nexport function select(subject: number, resultIfOne: number, resultIfZero: number): number {\n return (~(subject - 1) & resultIfOne) | ((subject - 1) & resultIfZero);\n}\n\n/**\n * Returns 1 if a <= b, or 0 if not.\n * Arguments must be positive 32-bit integers less than or equal to 2^31 - 1.\n */\nexport function lessOrEqual(a: number, b: number): number {\n return (((a | 0) - (b | 0) - 1) >>> 31) & 1;\n}\n\n/**\n * Returns 1 if a and b are of equal length and their contents\n * are equal, or 0 otherwise.\n *\n * Note that unlike in equal(), zero-length inputs are considered\n * the same, so this function will return 1.\n */\nexport function compare(a: Uint8Array, b: Uint8Array): number {\n if (a.length !== b.length) {\n return 0;\n }\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a[i] ^ b[i];\n }\n return (1 & ((result - 1) >>> 8));\n}\n\n/**\n * Returns true if a and b are of equal non-zero length,\n * and their contents are equal, or false otherwise.\n *\n * Note that unlike in compare() zero-length inputs are considered\n * _not_ equal, so this function will return false.\n */\nexport function equal(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length === 0 || b.length === 0) {\n return false;\n }\n return compare(a, b) !== 0;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package poly1305 implements Poly1305 one-time message authentication algorithm.\n */\n\nimport { equal as constantTimeEqual } from \"@stablelib/constant-time\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const DIGEST_LENGTH = 16;\n\n// Port of Andrew Moon's Poly1305-donna-16. Public domain.\n// https://github.com/floodyberry/poly1305-donna\n\n/**\n * Poly1305 computes 16-byte authenticator of message using\n * a one-time 32-byte key.\n *\n * Important: key should be used for only one message,\n * it should never repeat.\n */\nexport class Poly1305 {\n readonly digestLength = DIGEST_LENGTH;\n\n private _buffer = new Uint8Array(16);\n private _r = new Uint16Array(10);\n private _h = new Uint16Array(10);\n private _pad = new Uint16Array(8);\n private _leftover = 0;\n private _fin = 0;\n private _finished = false;\n\n constructor(key: Uint8Array) {\n let t0 = key[0] | key[1] << 8; this._r[0] = (t0) & 0x1fff;\n let t1 = key[2] | key[3] << 8; this._r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n let t2 = key[4] | key[5] << 8; this._r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n let t3 = key[6] | key[7] << 8; this._r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n let t4 = key[8] | key[9] << 8; this._r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this._r[5] = ((t4 >>> 1)) & 0x1ffe;\n let t5 = key[10] | key[11] << 8; this._r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n let t6 = key[12] | key[13] << 8; this._r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n let t7 = key[14] | key[15] << 8; this._r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this._r[9] = ((t7 >>> 5)) & 0x007f;\n\n this._pad[0] = key[16] | key[17] << 8;\n this._pad[1] = key[18] | key[19] << 8;\n this._pad[2] = key[20] | key[21] << 8;\n this._pad[3] = key[22] | key[23] << 8;\n this._pad[4] = key[24] | key[25] << 8;\n this._pad[5] = key[26] | key[27] << 8;\n this._pad[6] = key[28] | key[29] << 8;\n this._pad[7] = key[30] | key[31] << 8;\n }\n\n private _blocks(m: Uint8Array, mpos: number, bytes: number) {\n let hibit = this._fin ? 0 : 1 << 11;\n\n let h0 = this._h[0],\n h1 = this._h[1],\n h2 = this._h[2],\n h3 = this._h[3],\n h4 = this._h[4],\n h5 = this._h[5],\n h6 = this._h[6],\n h7 = this._h[7],\n h8 = this._h[8],\n h9 = this._h[9];\n\n let r0 = this._r[0],\n r1 = this._r[1],\n r2 = this._r[2],\n r3 = this._r[3],\n r4 = this._r[4],\n r5 = this._r[5],\n r6 = this._r[6],\n r7 = this._r[7],\n r8 = this._r[8],\n r9 = this._r[9];\n\n while (bytes >= 16) {\n let t0 = m[mpos + 0] | m[mpos + 1] << 8; h0 += (t0) & 0x1fff;\n let t1 = m[mpos + 2] | m[mpos + 3] << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n let t2 = m[mpos + 4] | m[mpos + 5] << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;\n let t3 = m[mpos + 6] | m[mpos + 7] << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n let t4 = m[mpos + 8] | m[mpos + 9] << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;\n h5 += ((t4 >>> 1)) & 0x1fff;\n let t5 = m[mpos + 10] | m[mpos + 11] << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n let t6 = m[mpos + 12] | m[mpos + 13] << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;\n let t7 = m[mpos + 14] | m[mpos + 15] << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n h9 += ((t7 >>> 5)) | hibit;\n\n let c = 0;\n\n let d0 = c;\n d0 += h0 * r0;\n d0 += h1 * (5 * r9);\n d0 += h2 * (5 * r8);\n d0 += h3 * (5 * r7);\n d0 += h4 * (5 * r6);\n c = (d0 >>> 13); d0 &= 0x1fff;\n d0 += h5 * (5 * r5);\n d0 += h6 * (5 * r4);\n d0 += h7 * (5 * r3);\n d0 += h8 * (5 * r2);\n d0 += h9 * (5 * r1);\n c += (d0 >>> 13); d0 &= 0x1fff;\n\n let d1 = c;\n d1 += h0 * r1;\n d1 += h1 * r0;\n d1 += h2 * (5 * r9);\n d1 += h3 * (5 * r8);\n d1 += h4 * (5 * r7);\n c = (d1 >>> 13); d1 &= 0x1fff;\n d1 += h5 * (5 * r6);\n d1 += h6 * (5 * r5);\n d1 += h7 * (5 * r4);\n d1 += h8 * (5 * r3);\n d1 += h9 * (5 * r2);\n c += (d1 >>> 13); d1 &= 0x1fff;\n\n let d2 = c;\n d2 += h0 * r2;\n d2 += h1 * r1;\n d2 += h2 * r0;\n d2 += h3 * (5 * r9);\n d2 += h4 * (5 * r8);\n c = (d2 >>> 13); d2 &= 0x1fff;\n d2 += h5 * (5 * r7);\n d2 += h6 * (5 * r6);\n d2 += h7 * (5 * r5);\n d2 += h8 * (5 * r4);\n d2 += h9 * (5 * r3);\n c += (d2 >>> 13); d2 &= 0x1fff;\n\n let d3 = c;\n d3 += h0 * r3;\n d3 += h1 * r2;\n d3 += h2 * r1;\n d3 += h3 * r0;\n d3 += h4 * (5 * r9);\n c = (d3 >>> 13); d3 &= 0x1fff;\n d3 += h5 * (5 * r8);\n d3 += h6 * (5 * r7);\n d3 += h7 * (5 * r6);\n d3 += h8 * (5 * r5);\n d3 += h9 * (5 * r4);\n c += (d3 >>> 13); d3 &= 0x1fff;\n\n let d4 = c;\n d4 += h0 * r4;\n d4 += h1 * r3;\n d4 += h2 * r2;\n d4 += h3 * r1;\n d4 += h4 * r0;\n c = (d4 >>> 13); d4 &= 0x1fff;\n d4 += h5 * (5 * r9);\n d4 += h6 * (5 * r8);\n d4 += h7 * (5 * r7);\n d4 += h8 * (5 * r6);\n d4 += h9 * (5 * r5);\n c += (d4 >>> 13); d4 &= 0x1fff;\n\n let d5 = c;\n d5 += h0 * r5;\n d5 += h1 * r4;\n d5 += h2 * r3;\n d5 += h3 * r2;\n d5 += h4 * r1;\n c = (d5 >>> 13); d5 &= 0x1fff;\n d5 += h5 * r0;\n d5 += h6 * (5 * r9);\n d5 += h7 * (5 * r8);\n d5 += h8 * (5 * r7);\n d5 += h9 * (5 * r6);\n c += (d5 >>> 13); d5 &= 0x1fff;\n\n let d6 = c;\n d6 += h0 * r6;\n d6 += h1 * r5;\n d6 += h2 * r4;\n d6 += h3 * r3;\n d6 += h4 * r2;\n c = (d6 >>> 13); d6 &= 0x1fff;\n d6 += h5 * r1;\n d6 += h6 * r0;\n d6 += h7 * (5 * r9);\n d6 += h8 * (5 * r8);\n d6 += h9 * (5 * r7);\n c += (d6 >>> 13); d6 &= 0x1fff;\n\n let d7 = c;\n d7 += h0 * r7;\n d7 += h1 * r6;\n d7 += h2 * r5;\n d7 += h3 * r4;\n d7 += h4 * r3;\n c = (d7 >>> 13); d7 &= 0x1fff;\n d7 += h5 * r2;\n d7 += h6 * r1;\n d7 += h7 * r0;\n d7 += h8 * (5 * r9);\n d7 += h9 * (5 * r8);\n c += (d7 >>> 13); d7 &= 0x1fff;\n\n let d8 = c;\n d8 += h0 * r8;\n d8 += h1 * r7;\n d8 += h2 * r6;\n d8 += h3 * r5;\n d8 += h4 * r4;\n c = (d8 >>> 13); d8 &= 0x1fff;\n d8 += h5 * r3;\n d8 += h6 * r2;\n d8 += h7 * r1;\n d8 += h8 * r0;\n d8 += h9 * (5 * r9);\n c += (d8 >>> 13); d8 &= 0x1fff;\n\n let d9 = c;\n d9 += h0 * r9;\n d9 += h1 * r8;\n d9 += h2 * r7;\n d9 += h3 * r6;\n d9 += h4 * r5;\n c = (d9 >>> 13); d9 &= 0x1fff;\n d9 += h5 * r4;\n d9 += h6 * r3;\n d9 += h7 * r2;\n d9 += h8 * r1;\n d9 += h9 * r0;\n c += (d9 >>> 13); d9 &= 0x1fff;\n\n c = (((c << 2) + c)) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = (c >>> 13);\n d1 += c;\n\n h0 = d0;\n h1 = d1;\n h2 = d2;\n h3 = d3;\n h4 = d4;\n h5 = d5;\n h6 = d6;\n h7 = d7;\n h8 = d8;\n h9 = d9;\n\n mpos += 16;\n bytes -= 16;\n }\n this._h[0] = h0;\n this._h[1] = h1;\n this._h[2] = h2;\n this._h[3] = h3;\n this._h[4] = h4;\n this._h[5] = h5;\n this._h[6] = h6;\n this._h[7] = h7;\n this._h[8] = h8;\n this._h[9] = h9;\n }\n\n finish(mac: Uint8Array, macpos = 0): this {\n const g = new Uint16Array(10);\n let c: number;\n let mask: number;\n let f: number;\n let i: number;\n\n if (this._leftover) {\n i = this._leftover;\n this._buffer[i++] = 1;\n for (; i < 16; i++) {\n this._buffer[i] = 0;\n }\n this._fin = 1;\n this._blocks(this._buffer, 0, 16);\n }\n\n c = this._h[1] >>> 13;\n this._h[1] &= 0x1fff;\n for (i = 2; i < 10; i++) {\n this._h[i] += c;\n c = this._h[i] >>> 13;\n this._h[i] &= 0x1fff;\n }\n this._h[0] += (c * 5);\n c = this._h[0] >>> 13;\n this._h[0] &= 0x1fff;\n this._h[1] += c;\n c = this._h[1] >>> 13;\n this._h[1] &= 0x1fff;\n this._h[2] += c;\n\n g[0] = this._h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (i = 1; i < 10; i++) {\n g[i] = this._h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= (1 << 13);\n\n mask = (c ^ 1) - 1;\n for (i = 0; i < 10; i++) {\n g[i] &= mask;\n }\n mask = ~mask;\n for (i = 0; i < 10; i++) {\n this._h[i] = (this._h[i] & mask) | g[i];\n }\n\n this._h[0] = ((this._h[0]) | (this._h[1] << 13)) & 0xffff;\n this._h[1] = ((this._h[1] >>> 3) | (this._h[2] << 10)) & 0xffff;\n this._h[2] = ((this._h[2] >>> 6) | (this._h[3] << 7)) & 0xffff;\n this._h[3] = ((this._h[3] >>> 9) | (this._h[4] << 4)) & 0xffff;\n this._h[4] = ((this._h[4] >>> 12) | (this._h[5] << 1) | (this._h[6] << 14)) & 0xffff;\n this._h[5] = ((this._h[6] >>> 2) | (this._h[7] << 11)) & 0xffff;\n this._h[6] = ((this._h[7] >>> 5) | (this._h[8] << 8)) & 0xffff;\n this._h[7] = ((this._h[8] >>> 8) | (this._h[9] << 5)) & 0xffff;\n\n f = this._h[0] + this._pad[0];\n this._h[0] = f & 0xffff;\n for (i = 1; i < 8; i++) {\n f = (((this._h[i] + this._pad[i]) | 0) + (f >>> 16)) | 0;\n this._h[i] = f & 0xffff;\n }\n\n mac[macpos + 0] = this._h[0] >>> 0;\n mac[macpos + 1] = this._h[0] >>> 8;\n mac[macpos + 2] = this._h[1] >>> 0;\n mac[macpos + 3] = this._h[1] >>> 8;\n mac[macpos + 4] = this._h[2] >>> 0;\n mac[macpos + 5] = this._h[2] >>> 8;\n mac[macpos + 6] = this._h[3] >>> 0;\n mac[macpos + 7] = this._h[3] >>> 8;\n mac[macpos + 8] = this._h[4] >>> 0;\n mac[macpos + 9] = this._h[4] >>> 8;\n mac[macpos + 10] = this._h[5] >>> 0;\n mac[macpos + 11] = this._h[5] >>> 8;\n mac[macpos + 12] = this._h[6] >>> 0;\n mac[macpos + 13] = this._h[6] >>> 8;\n mac[macpos + 14] = this._h[7] >>> 0;\n mac[macpos + 15] = this._h[7] >>> 8;\n\n this._finished = true;\n return this;\n }\n\n update(m: Uint8Array): this {\n let mpos = 0;\n let bytes = m.length;\n let want: number;\n\n if (this._leftover) {\n want = (16 - this._leftover);\n if (want > bytes) {\n want = bytes;\n }\n for (let i = 0; i < want; i++) {\n this._buffer[this._leftover + i] = m[mpos + i];\n }\n bytes -= want;\n mpos += want;\n this._leftover += want;\n if (this._leftover < 16) {\n return this;\n }\n this._blocks(this._buffer, 0, 16);\n this._leftover = 0;\n }\n\n if (bytes >= 16) {\n want = bytes - (bytes % 16);\n this._blocks(m, mpos, want);\n mpos += want;\n bytes -= want;\n }\n\n if (bytes) {\n for (let i = 0; i < bytes; i++) {\n this._buffer[this._leftover + i] = m[mpos + i];\n }\n this._leftover += bytes;\n }\n\n return this;\n }\n\n digest(): Uint8Array {\n // TODO(dchest): it behaves differently than other hashes/HMAC,\n // because it throws when finished \u2014 others just return saved result.\n if (this._finished) {\n throw new Error(\"Poly1305 was finished\");\n }\n let mac = new Uint8Array(16);\n this.finish(mac);\n return mac;\n }\n\n clean(): this {\n wipe(this._buffer);\n wipe(this._r);\n wipe(this._h);\n wipe(this._pad);\n this._leftover = 0;\n this._fin = 0;\n this._finished = true; // mark as finished even if not\n return this;\n }\n}\n\n/**\n * Returns 16-byte authenticator of data using a one-time 32-byte key.\n *\n * Important: key should be used for only one message, it should never repeat.\n */\nexport function oneTimeAuth(key: Uint8Array, data: Uint8Array): Uint8Array {\n const h = new Poly1305(key);\n h.update(data);\n const digest = h.digest();\n h.clean();\n return digest;\n}\n\n/**\n * Returns true if two authenticators are 16-byte long and equal.\n * Uses contant-time comparison to avoid leaking timing information.\n */\nexport function equal(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== DIGEST_LENGTH || b.length !== DIGEST_LENGTH) {\n return false;\n }\n return constantTimeEqual(a, b);\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { streamXOR, stream } from \"@stablelib/xsalsa20\";\nimport { oneTimeAuth, equal as authEqual } from \"@stablelib/poly1305\";\nimport { wipe } from \"@stablelib/wipe\";\nimport { randomBytes, RandomSource } from \"@stablelib/random\";\n\nexport function secretBox(key: Uint8Array, nonce: Uint8Array, data: Uint8Array): Uint8Array {\n if (nonce.length !== 24) {\n throw new Error(\"secretBox nonce must be 24 bytes\");\n }\n const firstBlock = new Uint8Array(64);\n\n // Allocate place for nonce and counter.\n const nonceCounter = new Uint8Array(24 + 8);\n\n // Set first bytes to nonce. Last 8 bytes will be counter.\n nonceCounter.set(nonce);\n\n // Generate first block of XSalsa20 stream, of which\n // first 32 bytes will be authentication key, and the rest\n // will be used for encryption.\n stream(key, nonceCounter, firstBlock, 8);\n\n // Allocate result, which will contain 16-byte authenticator\n // concatenated with ciphertext.\n const result = new Uint8Array(16 + data.length);\n\n // Encrypt first 32 bytes of data with last 32 bytes of generated stream.\n for (let i = 0; i < 32 && i < data.length; i++) {\n result[16 + i] = data[i] ^ firstBlock[32 + i];\n }\n\n // Encrypt the rest of data.\n if (data.length > 32) {\n streamXOR(key, nonceCounter, data.subarray(32), result.subarray(16 + 32), 8);\n }\n\n // Calculate Poly1305 authenticator of encrypted data using\n // authentication key in the first block of XSalsa20 stream.\n const auth = oneTimeAuth(firstBlock.subarray(0, 32), result.subarray(16));\n\n // Copy authenticator to the beginning of result.\n for (let i = 0; i < auth.length; i++) {\n result[i] = auth[i];\n }\n\n // Clean auth.\n wipe(auth);\n\n // Clean first block.\n wipe(firstBlock);\n\n // Clean nonceCounter.\n wipe(nonceCounter);\n\n return result;\n}\n\nexport function openSecretBox(key: Uint8Array, nonce: Uint8Array, box: Uint8Array): Uint8Array | null {\n if (nonce.length !== 24) {\n throw new Error(\"secretBox nonce must be 24 bytes\");\n }\n if (box.length < 16) {\n throw new Error(\"secretBox data must be at least 16 bytes\");\n }\n const firstBlock = new Uint8Array(64);\n\n // Allocate place for nonce and counter.\n const nonceCounter = new Uint8Array(24 + 8);\n\n // Set first bytes to nonce. Last 8 bytes will be counter.\n nonceCounter.set(nonce);\n\n // Generate first block of XSalsa20 stream, of which\n // first 32 bytes will be authentication key, and the rest\n // will be used for encryption.\n stream(key, nonceCounter, firstBlock, 8);\n\n // Calculate Poly1305 authenticator of encrypted data using\n // authentication key in the first block of XSalsa20 stream.\n const auth = oneTimeAuth(firstBlock.subarray(0, 32), box.subarray(16));\n\n // Check authenticator.\n if (!authEqual(auth, box.subarray(0, 16))) {\n // Authenticator is incorrect: ciphertext or authenticator\n // was corrupted, maybe maliciously.\n return null;\n }\n\n // Authenticator verifies, so we can decrypt ciphertext.\n const ciphertext = box.subarray(16);\n\n // Allocate result array.\n const result = new Uint8Array(ciphertext.length);\n\n // Decrypt first 32 bytes of box with last 32 bytes of generated stream.\n for (let i = 0; i < 32 && i < ciphertext.length; i++) {\n result[i] = ciphertext[i] ^ firstBlock[32 + i];\n }\n\n // Decrypt the rest of data.\n if (ciphertext.length > 32) {\n streamXOR(key, nonceCounter, ciphertext.subarray(32), result.subarray(32), 8);\n }\n\n // Clean auth.\n wipe(auth);\n\n // Clean first block.\n wipe(firstBlock);\n\n // Clean nonceCounter.\n wipe(nonceCounter);\n\n return result;\n}\n\n/** Generates a 32-byte random secret key. */\nexport function generateKey(prng?: RandomSource): Uint8Array {\n return randomBytes(32, prng);\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { scalarMult } from \"@stablelib/x25519\";\nimport { hsalsa } from \"@stablelib/xsalsa20\";\nimport { secretBox, openSecretBox } from \"./secretbox\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport { generateKeyPair } from \"@stablelib/x25519\";\n\nconst zeros16 = new Uint8Array(16);\n\nexport function precomputeSharedKey(theirPublicKey: Uint8Array, mySecretKey: Uint8Array): Uint8Array {\n // Compute scalar multiplication result.\n const key = scalarMult(mySecretKey, theirPublicKey);\n\n // Hash key with HSalsa function.\n hsalsa(key, zeros16, key);\n\n return key;\n}\n\nexport function box(theirPublicKey: Uint8Array, mySecretKey: Uint8Array,\n nonce: Uint8Array, data: Uint8Array): Uint8Array {\n const sharedKey = precomputeSharedKey(theirPublicKey, mySecretKey);\n const result = secretBox(sharedKey, nonce, data);\n wipe(sharedKey);\n return result;\n}\n\nexport function openBox(theirPublicKey: Uint8Array, mySecretKey: Uint8Array,\n nonce: Uint8Array, data: Uint8Array): Uint8Array | null {\n const sharedKey = precomputeSharedKey(theirPublicKey, mySecretKey);\n const result = openSecretBox(sharedKey, nonce, data);\n wipe(sharedKey);\n return result;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package nacl implements NaCl (Networking and Cryptography library) cryptography.\n */\n\nexport * from \"./box\";\nexport * from \"./secretbox\";\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package base64 implements Base64 encoding and decoding.\n */\n\n// Invalid character used in decoding to indicate\n// that the character to decode is out of range of\n// alphabet and cannot be decoded.\nconst INVALID_BYTE = 256;\n\n/**\n * Implements standard Base64 encoding.\n *\n * Operates in constant time.\n */\nexport class Coder {\n // TODO(dchest): methods to encode chunk-by-chunk.\n\n constructor(private _paddingCharacter = \"=\") { }\n\n encodedLength(length: number): number {\n if (!this._paddingCharacter) {\n return (length * 8 + 5) / 6 | 0;\n }\n return (length + 2) / 3 * 4 | 0;\n }\n\n encode(data: Uint8Array): string {\n let out = \"\";\n\n let i = 0;\n for (; i < data.length - 2; i += 3) {\n let c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);\n out += this._encodeByte((c >>> 3 * 6) & 63);\n out += this._encodeByte((c >>> 2 * 6) & 63);\n out += this._encodeByte((c >>> 1 * 6) & 63);\n out += this._encodeByte((c >>> 0 * 6) & 63);\n }\n\n const left = data.length - i;\n if (left > 0) {\n let c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);\n out += this._encodeByte((c >>> 3 * 6) & 63);\n out += this._encodeByte((c >>> 2 * 6) & 63);\n if (left === 2) {\n out += this._encodeByte((c >>> 1 * 6) & 63);\n } else {\n out += this._paddingCharacter || \"\";\n }\n out += this._paddingCharacter || \"\";\n }\n\n return out;\n }\n\n maxDecodedLength(length: number): number {\n if (!this._paddingCharacter) {\n return (length * 6 + 7) / 8 | 0;\n }\n return length / 4 * 3 | 0;\n }\n\n decodedLength(s: string): number {\n return this.maxDecodedLength(s.length - this._getPaddingLength(s));\n }\n\n decode(s: string): Uint8Array {\n if (s.length === 0) {\n return new Uint8Array(0);\n }\n const paddingLength = this._getPaddingLength(s);\n const length = s.length - paddingLength;\n const out = new Uint8Array(this.maxDecodedLength(length));\n let op = 0;\n let i = 0;\n let haveBad = 0;\n let v0 = 0, v1 = 0, v2 = 0, v3 = 0;\n for (; i < length - 4; i += 4) {\n v0 = this._decodeChar(s.charCodeAt(i + 0));\n v1 = this._decodeChar(s.charCodeAt(i + 1));\n v2 = this._decodeChar(s.charCodeAt(i + 2));\n v3 = this._decodeChar(s.charCodeAt(i + 3));\n out[op++] = (v0 << 2) | (v1 >>> 4);\n out[op++] = (v1 << 4) | (v2 >>> 2);\n out[op++] = (v2 << 6) | v3;\n haveBad |= v0 & INVALID_BYTE;\n haveBad |= v1 & INVALID_BYTE;\n haveBad |= v2 & INVALID_BYTE;\n haveBad |= v3 & INVALID_BYTE;\n }\n if (i < length - 1) {\n v0 = this._decodeChar(s.charCodeAt(i));\n v1 = this._decodeChar(s.charCodeAt(i + 1));\n out[op++] = (v0 << 2) | (v1 >>> 4);\n haveBad |= v0 & INVALID_BYTE;\n haveBad |= v1 & INVALID_BYTE;\n }\n if (i < length - 2) {\n v2 = this._decodeChar(s.charCodeAt(i + 2));\n out[op++] = (v1 << 4) | (v2 >>> 2);\n haveBad |= v2 & INVALID_BYTE;\n }\n if (i < length - 3) {\n v3 = this._decodeChar(s.charCodeAt(i + 3));\n out[op++] = (v2 << 6) | v3;\n haveBad |= v3 & INVALID_BYTE;\n }\n if (haveBad !== 0) {\n throw new Error(\"Base64Coder: incorrect characters for decoding\");\n }\n return out;\n }\n\n // Standard encoding have the following encoded/decoded ranges,\n // which we need to convert between.\n //\n // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /\n // Index: 0 - 25 26 - 51 52 - 61 62 63\n // ASCII: 65 - 90 97 - 122 48 - 57 43 47\n //\n\n // Encode 6 bits in b into a new character.\n protected _encodeByte(b: number): string {\n // Encoding uses constant time operations as follows:\n //\n // 1. Define comparison of A with B using (A - B) >>> 8:\n // if A > B, then result is positive integer\n // if A <= B, then result is 0\n //\n // 2. Define selection of C or 0 using bitwise AND: X & C:\n // if X == 0, then result is 0\n // if X != 0, then result is C\n //\n // 3. Start with the smallest comparison (b >= 0), which is always\n // true, so set the result to the starting ASCII value (65).\n //\n // 4. Continue comparing b to higher ASCII values, and selecting\n // zero if comparison isn't true, otherwise selecting a value\n // to add to result, which:\n //\n // a) undoes the previous addition\n // b) provides new value to add\n //\n let result = b;\n // b >= 0\n result += 65;\n // b > 25\n result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);\n // b > 51\n result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);\n // b > 61\n result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);\n // b > 62\n result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);\n\n return String.fromCharCode(result);\n }\n\n // Decode a character code into a byte.\n // Must return 256 if character is out of alphabet range.\n protected _decodeChar(c: number): number {\n // Decoding works similar to encoding: using the same comparison\n // function, but now it works on ranges: result is always incremented\n // by value, but this value becomes zero if the range is not\n // satisfied.\n //\n // Decoding starts with invalid value, 256, which is then\n // subtracted when the range is satisfied. If none of the ranges\n // apply, the function returns 256, which is then checked by\n // the caller to throw error.\n let result = INVALID_BYTE; // start with invalid character\n\n // c == 43 (c > 42 and c < 44)\n result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);\n // c == 47 (c > 46 and c < 48)\n result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);\n // c > 47 and c < 58\n result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);\n // c > 64 and c < 91\n result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);\n // c > 96 and c < 123\n result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);\n\n return result;\n }\n\n private _getPaddingLength(s: string): number {\n let paddingLength = 0;\n if (this._paddingCharacter) {\n for (let i = s.length - 1; i >= 0; i--) {\n if (s[i] !== this._paddingCharacter) {\n break;\n }\n paddingLength++;\n }\n if (s.length < 4 || paddingLength > 2) {\n throw new Error(\"Base64Coder: incorrect padding\");\n }\n }\n return paddingLength;\n }\n\n}\n\nconst stdCoder = new Coder();\n\nexport function encode(data: Uint8Array): string {\n return stdCoder.encode(data);\n}\n\nexport function decode(s: string): Uint8Array {\n return stdCoder.decode(s);\n}\n\n/**\n * Implements URL-safe Base64 encoding.\n * (Same as Base64, but '+' is replaced with '-', and '/' with '_').\n *\n * Operates in constant time.\n */\nexport class URLSafeCoder extends Coder {\n // URL-safe encoding have the following encoded/decoded ranges:\n //\n // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _\n // Index: 0 - 25 26 - 51 52 - 61 62 63\n // ASCII: 65 - 90 97 - 122 48 - 57 45 95\n //\n\n protected _encodeByte(b: number): string {\n let result = b;\n // b >= 0\n result += 65;\n // b > 25\n result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);\n // b > 51\n result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);\n // b > 61\n result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);\n // b > 62\n result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);\n\n return String.fromCharCode(result);\n }\n\n protected _decodeChar(c: number): number {\n let result = INVALID_BYTE;\n\n // c == 45 (c > 44 and c < 46)\n result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);\n // c == 95 (c > 94 and c < 96)\n result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);\n // c > 47 and c < 58\n result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);\n // c > 64 and c < 91\n result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);\n // c > 96 and c < 123\n result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);\n\n return result;\n }\n}\n\nconst urlSafeCoder = new URLSafeCoder();\n\nexport function encodeURLSafe(data: Uint8Array): string {\n return urlSafeCoder.encode(data);\n}\n\nexport function decodeURLSafe(s: string): Uint8Array {\n return urlSafeCoder.decode(s);\n}\n\n\nexport const encodedLength = (length: number) =>\n stdCoder.encodedLength(length);\n\nexport const maxDecodedLength = (length: number) =>\n stdCoder.maxDecodedLength(length);\n\nexport const decodedLength = (s: string) =>\n stdCoder.decodedLength(s);\n", "/**\n * Browser-side crypto for the login SDK:\n *\n * \u2022 generateEphemeralKeypair \u2014 X25519 keypair for the duration of\n * one sign-in. Held in memory; discarded on session.close() or page\n * unload. The public key is the value the wallet boxes its envelope\n * to.\n *\n * \u2022 decryptEnvelope \u2014 open the wallet's NaCl `box` ciphertext\n * and parse the resulting JSON. Once the wallet's session key is\n * pinned (see session.ts), only envelopes boxed BY that key open.\n *\n * \u2022 boxToWallet \u2014 box a JSON envelope to the wallet's\n * session key, sent by this browser's session key.\n *\n * Envelope v2 (both directions): NaCl `box` between the two session\n * keys \u2014 the browser's per-sign-in X25519 key (`browserPk`, in the QR)\n * and the wallet's per-session X25519 key (`walletSessionPk`, bound\n * into the signed presentation as the KB-JWT `prson_wsk` claim). The\n * wire field `ephPk` keeps its name for compatibility but now carries\n * the SENDER's session key, so the recipient can check who sent it:\n * a box only opens with the matching sender key, which makes it mutual\n * authentication, not just confidentiality.\n *\n * Uses `@stablelib/nacl` for the box / open primitives \u2014 a reviewed\n * pure-JS implementation that runs in every browser without WebCrypto\n * dependency gaps (Web Crypto doesn't ship X25519 in all engines).\n */\nimport { box, openBox } from \"@stablelib/nacl\";\nimport { generateKeyPair } from \"@stablelib/x25519\";\nimport { randomBytes } from \"@stablelib/random\";\nimport { decodeURLSafe as b64uDecode, encodeURLSafe as b64uEncode } from \"@stablelib/base64\";\n\nexport type EphemeralKeys = {\n /** The X25519 secret key (32 bytes). Never serialised; never logged. */\n secretKey: Uint8Array;\n /** The matching public key (32 bytes). */\n publicKey: Uint8Array;\n /** Base64url-encoded public key for use in QRs + the verifier request. */\n publicKeyB64u: string;\n};\n\nexport async function generateEphemeralKeypair(): Promise<EphemeralKeys> {\n // @stablelib's generateKeyPair pulls entropy from a CSPRNG (window.crypto\n // via @stablelib/random). For environments without crypto.getRandomValues\n // (none we support), this would throw \u2014 that's correct behaviour.\n void randomBytes(1); // touch the entropy source so a misconfigured browser fails fast\n const kp = generateKeyPair();\n return {\n secretKey: kp.secretKey,\n publicKey: kp.publicKey,\n publicKeyB64u: stripPad(b64uEncode(kp.publicKey)),\n };\n}\n\n/** Wire shape (matches what the wallet emits \u2014 see ARCHITECTURE.md \u00A74.2). */\nexport type EncryptedEnvelope = {\n /** The sender's X25519 session pk, base64url. Envelope v2: always the\n * sender's session key (`walletSessionPk` from the wallet, `browserPk`\n * from the browser). Older wallets put a fresh per-message key here. */\n ephPk: string;\n /** 24-byte nonce, base64url. */\n nonce24: string;\n /** Boxed ciphertext + Poly1305 tag, base64url. */\n ct: string;\n};\n\n/** Decrypted plaintext envelope \u2014 see ARCHITECTURE.md \u00A74.2.\n *\n * Three of the `msg` types are post-sign-in lifecycle events\n * (`claim-update`, `display-update`, `credential-revoked`) per the\n * roadmap \u00A71. They flow on the same WebRTC channel as the initial\n * `presentation` + renewals, framed with the same NaCl-boxed\n * envelope so the wallet doesn't need a separate transport for live\n * profile / claim updates.\n *\n * Important: any event whose payload includes claim VALUES (today\n * only `claim-update`) MUST carry a `presentation` field, and the\n * SDK MUST re-verify that presentation before firing any listener.\n * Bare claim deltas without a fresh SD-JWT-VC backing them are NOT\n * trusted \u2014 see ROADMAP \u00A71.3 and SECURITY.md \u00A77.\n */\nexport type DecryptedEnvelope = {\n v: string;\n msg:\n | \"presentation\"\n | \"renewal\"\n | \"revoke\"\n | \"decline\"\n | \"claim-update\"\n | \"display-update\"\n | \"credential-revoked\"\n | \"response\"\n | \"mouse-update\"\n | \"nav\"\n | \"value\"\n | \"logout\"\n /**\n * Browser\u2192wallet pause-state notification. Fired on\n * `window.blur` / `window.focus` so the wallet's mouse\n * controller can show \"Remote control paused\" while the page\n * is in the background. Body: `paused: boolean`.\n */\n | \"control-status\"\n /**\n * Browser\u2192wallet \"I'm going away\" signal. Fired synchronously\n * from `window.pagehide` (refresh, tab close, navigation)\n * before the transport collapses, so the wallet can close the\n * session immediately instead of waiting for the slower\n * `peer-gone` / WS-close pathway. Body: `reason: string`\n * (free-form short code, currently always `\"page_unload\"`).\n */\n | \"browser-revoke\"\n /**\n * File-transfer wire grammar. Wallet\u2192browser; used when the\n * host's focused element is `<input type=\"file\">` and the user\n * picks something on the phone. The three-stage envelope keeps\n * memory pressure low \u2014 neither peer ever materialises the full\n * file in a contiguous buffer:\n *\n * * `file-begin` \u2014 metadata: `name`, `mimeType`, `size`,\n * `totalChunks`, `chunkSize`, plus an\n * optional `attestation` SD-JWT-VC for\n * identity-bound files (see notes below\n * on VC MIME standards).\n * * `file-chunk` \u2014 one chunk: `index` (0-based) +\n * base64-encoded `data`. The wallet\n * stream-reads the source file, so chunks\n * leave the device one at a time without\n * ever loading the whole thing.\n * * `file-end` \u2014 `sha256` over the whole file, hex-encoded.\n * The browser verifies the assembled Blob\n * against this digest before assigning to\n * the focused input.\n *\n * Per-chunk ack via the existing reliability layer gives\n * natural backpressure: the wallet doesn't queue chunk N+1\n * until chunk N is confirmed. Loss of any one chunk retries\n * just that chunk, not the file.\n *\n * VC MIME context (host integrators occasionally ask):\n * * `application/vc+ld+json` \u2014 W3C VCDM JSON-LD form\n * * `application/vc+jwt` \u2014 W3C VCDM JWT form\n * * `application/vc+sd-jwt` \u2014 IETF SD-JWT-VC (what the\n * Prson identity stack issues)\n * * `application/pdf` + PAdES \u2014 signed-PDF form\n * * C2PA bundles for media (image / video provenance)\n *\n * There is no widely-deployed standard MIME for \"binary file\n * with an attached presentation\". The `attestation` field on\n * `file-begin` is our convention for piggy-backing one \u2014 the\n * wallet sends the file bytes AND a separate SD-JWT-VC whose\n * disclosed claims include the file's SHA-256. The verifier\n * (host page) re-hashes the received bytes and checks the\n * digest matches the disclosed claim before trusting the\n * provenance metadata.\n */\n | \"file-begin\"\n | \"file-chunk\"\n | \"file-end\"\n /** Transport-layer reliability primitive: the peer's confirmation\n * that the envelope with id [ackOf] was received. The session\n * layer auto-emits these for inbound messages carrying an `id`\n * (other than ping / pong / ack themselves) and resolves\n * pending-ack promises on the sender side. See session.ts. */\n | \"ack\"\n /** Liveness probe. Sender keeps a fresh `id` per ping and times\n * the matching pong to derive RTT. The receiver echoes as\n * `pong` with `ackOf` set to the ping's `id`. */\n | \"ping\"\n /** Liveness echo. `ackOf` references the ping's id; `recvTs`\n * is the peer's wall-clock receipt time. Recipient computes\n * RTT = now \u2212 sendTs cached against [ackOf]. */\n | \"pong\";\n issuedAt: number;\n ttlMinutes?: number;\n domain?: string;\n\n /** Transport-layer envelope id (UUID v4). Present on every wire\n * message that is ack-tracked or dedupe-tracked; absent on\n * mouse-update (high-frequency broadcast where loss is OK) and\n * on the protocol primitives `ack` / `pong` (which carry\n * [ackOf] instead). The receiver dedupes by this id; the sender\n * retransmits until the matching [ack] arrives. */\n id?: string;\n\n /** Reference to the originating envelope's [id]. Set on `ack`,\n * `pong`, and `response` envelopes. */\n ackOf?: string;\n\n /** Ping send-time wall-clock (epoch ms). The pong copies this\n * verbatim so the sender doesn't need to maintain a separate\n * ts cache for an RTT calculation. */\n ts?: number;\n\n /** Pong-only: the responder's wall-clock receipt time (epoch ms).\n * Useful for one-way delay estimates if the host wants finer\n * diagnostics than RTT alone. */\n recvTs?: number;\n\n /** Present for `presentation`, `renewal`, and `claim-update`. */\n presentation?: string;\n fragments?: unknown[];\n\n /**\n * Wallet's session-long X25519 public key (base64url, 32 bytes).\n * Present only in the INITIAL `presentation` envelope at sign-in\n * (and on `renewal` if the wallet rotates its session key). The\n * browser SDK extracts + caches this on the session so subsequent\n * outbound `request` envelopes can NaCl-box to it. Without this\n * the browser\u2192wallet direction has no destination key and the\n * request channel can't open.\n *\n * Advisory only: the key the SDK pins is the one the signed\n * presentation binds (KB-JWT `prson_wsk`, or the anonymous\n * credential's `prson_wsk`). This field must agree with it, and a\n * value on any later envelope is ignored \u2014 a rotation is accepted\n * only from a verified renewal presentation carrying the new key.\n */\n walletSessionPk?: string;\n\n /**\n * User's preferred UI language as a BCP-47 language tag (e.g.\n * `\"en\"`, `\"pt-PT\"`, `\"fr-CA\"`). The wallet sets this from the\n * device's active locale on the initial `presentation` envelope\n * and may rotate it on `renewal` if the device language changes\n * mid-session. The host site can read it via\n * `session.preferredLanguage` to localise its UI without an\n * extra round-trip.\n *\n * Same convention applies to the `displayName` + `avatar` fields\n * below: they originated as the `display-update` envelope body,\n * but the wallet stamps them onto the initial `presentation`\n * envelope too so the host has them on first paint without a\n * separate round-trip.\n */\n preferredLanguage?: string;\n\n /** `claim-update` body: per-claim **name-only** delta. The\n * wallet MUST NOT include claim values here \u2014 the SDK ignores\n * the delta entirely and recomputes from the re-verified VC\n * for correctness, and emits name-only events to keep raw\n * claim values out of telemetry/log surfaces. The wire field\n * is kept (typed as name-only) so future wallets can hint at\n * what changed without an SDK bump, but the SDK never trusts\n * the hint as authoritative. */\n delta?: {\n added?: string[];\n removed?: string[];\n updated?: string[];\n };\n\n /** `display-update` body. Either field independently optional;\n * absent means \"no change\". Pass `null` to clear. No crypto\n * re-verify required \u2014 display-only hints for the host UI. */\n displayName?: string | null;\n avatar?: { url: string; hash: string } | null;\n\n /** `credential-revoked` body. Closes the session with the\n * matching ExpiryReason. */\n reason?: \"alias_transferred\" | \"user_revoked\" | \"key_compromised\";\n\n /** `response` body. The wallet's reply to an earlier outbound\n * `request` envelope. Paired by `requestId` (RFC-4122 v4 UUID,\n * echoed verbatim from the request). Either `result` (success\n * payload, kind-dependent shape) or `error` (short string code)\n * is set; both being absent is treated as `error: \"unsupported\"`. */\n requestId?: string;\n result?: unknown;\n error?: string;\n\n /**\n * `mouse-update` body. Streamed continuously by the wallet while\n * a `kind: \"mouse\"` drawer is open, paired by `requestId` to the\n * originating request. The browser SDK's `bindMouse` helper\n * consumes these and applies them to a CSS-positioned virtual\n * cursor on the page.\n *\n * Coordinates are deltas \u2014 pixels relative to the previous\n * position \u2014 rather than absolute, so phone resolution and page\n * resolution don't need to match. `event` distinguishes\n * pointer-motion frames (`move`) from discrete actions\n * (`click` / `double-click` / `scroll`); `scroll.dy` is positive\n * for downward scroll, matching `WheelEvent.deltaY`.\n */\n mouse?: {\n /**\n * Pointer-stream events.\n *\n * * `move` / `click` / `double-click` / `scroll` \u2014 pointer\n * events that move the on-page cursor or fire synthetic\n * mouse events.\n * * `begin` / `end` \u2014 wallet-side stream lifecycle markers\n * for the pre-grant flow (`SignInOptions.mouseControl`).\n * Subscribers ignore them as no-op pointer events.\n * * `hide` / `show` \u2014 visibility toggles. The wallet emits\n * `hide` when the user lifts the phone into a non-pointing\n * pose (gravity-based pose detector) and re-emits `show`\n * when wand pose returns. The browser pulls the cursor\n * off the page on `hide` AND surfaces a \"point your phone\n * at the screen\" hint with a soft blue glow on the\n * viewport edge.\n */\n event:\n | \"move\"\n | \"click\"\n | \"double-click\"\n | \"scroll\"\n | \"begin\"\n | \"end\"\n | \"show\"\n | \"hide\";\n dx?: number;\n dy?: number;\n /** Active mode at the time of the event (the wallet drawer can\n * toggle mid-session). */\n mode?: \"touch\" | \"magic\";\n };\n\n /**\n * `control-status` body. Browser-emitted; the wallet listens via\n * `LoginSession.inbound` and dims its controller surface while\n * `paused: true`. Fired on `window.blur` / `window.focus` so the\n * user can see, on the phone, that the page is no longer\n * accepting their cursor input.\n */\n paused?: boolean;\n\n /**\n * `file-begin` body. Sent ONCE per file transfer right before the\n * `file-chunk` stream starts. `chunkSize` is the wallet's raw\n * (pre-base64) bytes-per-chunk so the browser can preallocate\n * timing buffers; `totalChunks` lets it render a progress bar\n * without listening for `file-end`. `attestation` is reserved\n * for the future SD-JWT-VC piggy-back contract \u2014 host code\n * should treat the field as opaque until the verifier-side\n * verification path lands.\n */\n fileBegin?: {\n name: string;\n mimeType: string;\n size: number;\n totalChunks: number;\n chunkSize: number;\n /** Optional SD-JWT-VC bound to the file's SHA-256 \u2014 see the\n * `file-begin` msg comment. */\n attestation?: string;\n };\n\n /**\n * `file-chunk` body. `data` is the chunk's raw bytes base64-\n * encoded (URL-safe, padded \u2014 same convention the rest of the\n * wire grammar uses). `index` is the zero-based ordinal.\n */\n fileChunk?: {\n index: number;\n data: string;\n };\n\n /**\n * `file-end` body. `sha256` is hex-encoded (64 lowercase chars).\n * The browser verifies the assembled Blob against this digest\n * before assigning to the focused `<input type=\"file\">`.\n */\n fileEnd?: {\n sha256: string;\n };\n\n /**\n * `nav` body \u2014 wallet's remote-navigation command. Sent when the\n * user taps Prev / Next / Submit on the persistent banner drawer.\n *\n * * `\"prev\"` / `\"next\"` \u2014 move DOM focus to the previous /\n * next tabbable input on the page. Semantically equivalent\n * to Shift+Tab / Tab. SDK fires the matching `focus` event\n * on the new element so reactive UIs pick up the move.\n * * `\"submit\"` \u2014 fire `requestSubmit()` on the closest enclosing\n * `<form>` of the currently focused element. Semantically\n * equivalent to Enter.\n *\n * Only meaningful when the verifier opted in to\n * `remoteNavigation: true` at sign-in time AND the SDK side called\n * `enableRemoteNavigation(session)`.\n */\n action?: \"prev\" | \"next\" | \"submit\";\n\n /**\n * `value` body \u2014 wallet's edit of the currently-focused input. The\n * SDK applies it via `el.value = ...` + an `input` / `change`\n * event pair. The wallet streams these on every keystroke so the\n * page updates live.\n *\n * Empty string is a valid \"clear the field\" message and is\n * propagated as-is. A `null` `value` means \"no change\" \u2014 the SDK\n * ignores it; used by the wallet to ack a focus push without\n * actually editing.\n */\n value?: string | null;\n};\n\n/**\n * Open a wallet envelope. With [expectedSenderPkB64u] (the pinned\n * `walletSessionPk`), only an envelope whose `ephPk` is that key AND\n * whose box opens with it is accepted: anything else (another key, a\n * forged `ephPk`) throws. Without it, any sender is accepted \u2014 used for\n * the first envelope, whose sender is checked against the verified\n * presentation afterwards (index.ts), and for old wallets.\n */\nexport async function decryptEnvelope(\n raw: string,\n keys: EphemeralKeys,\n expectedSenderPkB64u?: string,\n): Promise<DecryptedEnvelope> {\n return (await openEnvelope(raw, keys, expectedSenderPkB64u)).envelope;\n}\n\n/** [decryptEnvelope], also returning the sender key the box opened with. */\nexport async function openEnvelope(\n raw: string,\n keys: EphemeralKeys,\n expectedSenderPkB64u?: string,\n): Promise<{ envelope: DecryptedEnvelope; senderPk: string }> {\n let parsed: EncryptedEnvelope;\n try {\n parsed = JSON.parse(raw) as EncryptedEnvelope;\n } catch {\n throw new Error(\"decryptEnvelope: not a JSON envelope\");\n }\n if (typeof parsed.ephPk !== \"string\" || typeof parsed.nonce24 !== \"string\" || typeof parsed.ct !== \"string\") {\n throw new Error(\"decryptEnvelope: missing required fields {ephPk, nonce24, ct}\");\n }\n const ephPk = b64uDecode(addPad(parsed.ephPk));\n const nonce = b64uDecode(addPad(parsed.nonce24));\n const ct = b64uDecode(addPad(parsed.ct));\n if (ephPk.length !== 32) throw new Error(\"decryptEnvelope: bad ephPk length\");\n if (nonce.length !== 24) throw new Error(\"decryptEnvelope: bad nonce length\");\n let senderPk = ephPk;\n if (expectedSenderPkB64u !== undefined) {\n const expected = b64uDecode(addPad(expectedSenderPkB64u));\n if (expected.length !== 32 || !bytesEqual(expected, ephPk)) {\n throw new Error(\"decryptEnvelope: not sent by the pinned wallet key\");\n }\n senderPk = expected;\n }\n // NaCl `openBox` returns null on bad ciphertext / wrong key \u2014 never\n // throws. We must check + raise ourselves. A box only opens with the\n // sender key it was made with, so a pinned sender is authenticated.\n const pt = openBox(senderPk, keys.secretKey, nonce, ct);\n if (!pt) throw new Error(\"decryptEnvelope: authentication failed (wrong key or tampered ciphertext)\");\n let envelope: DecryptedEnvelope;\n try {\n envelope = JSON.parse(new TextDecoder().decode(pt)) as DecryptedEnvelope;\n } catch {\n throw new Error(\"decryptEnvelope: decrypted but not JSON\");\n }\n return { envelope, senderPk: stripPad(b64uEncode(senderPk)) };\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!;\n return diff === 0;\n}\n\nfunction stripPad(s: string): string {\n return s.replace(/=+$/, \"\");\n}\n\nfunction addPad(s: string): string {\n const mod = s.length % 4;\n return mod === 0 ? s : s + \"=\".repeat(4 - mod);\n}\n\n/**\n * Box a JSON-serialisable [plaintext] to the wallet's session X25519\n * public key. Mirror of the wallet's `LoginEnvelope.encryptToBrowser`\n * primitive (NaCl `box`, XSalsa20-Poly1305, random 24-byte nonce) \u2014\n * the wallet decrypts with its stored session secret. Returns the same\n * JSON-encoded envelope shape the browser already RECEIVES from the\n * wallet:\n *\n * { ephPk: <base64url>, nonce24: <base64url>, ct: <base64url> }\n *\n * Envelope v2: with [sender] (this sign-in's browser keys \u2014 the\n * `browserPk` the QR carried), the box is made BY that key, so `ephPk`\n * is the browser's session key and the wallet can check the envelope\n * came from the browser that showed the code. Without [sender] (legacy),\n * a fresh per-message keypair is used.\n *\n * Both session keys are themselves fresh for each sign-in and live only\n * in memory, so a leaked key exposes that one session, never another.\n *\n * [walletSessionPkB64u] is the wallet's session key, pinned from the\n * verified sign-in presentation (KB-JWT `prson_wsk`).\n */\nexport function boxToWallet(\n walletSessionPkB64u: string,\n plaintext: string,\n sender?: Pick<EphemeralKeys, \"secretKey\" | \"publicKey\">,\n): string {\n const recipientPk = b64uDecode(addPad(walletSessionPkB64u));\n if (recipientPk.length !== 32) {\n throw new Error(\"boxToWallet: bad walletSessionPk length\");\n }\n const ephemeral = sender ?? generateKeyPair();\n const nonce = randomBytes(24);\n const pt = new TextEncoder().encode(plaintext);\n // `@stablelib/nacl` box signature is\n // box(theirPublicKey, mySecretKey, nonce, data)\n // \u2014 RECIPIENT pk first, SENDER sk second. Mirror of `openBox` (which\n // we already call correctly in `decryptEnvelope`). An earlier draft\n // had these swapped, producing a junk shared key that PineNaCl's\n // `Box.decrypt` could never match \u2014 every browser\u2192wallet envelope\n // failed Poly1305 authentication on the wallet side. Keep the\n // argument names explicit at the call site so the bug can't recur.\n const ct = box(\n /* theirPublicKey */ recipientPk,\n /* mySecretKey */ ephemeral.secretKey,\n nonce,\n pt,\n );\n return JSON.stringify({\n ephPk: stripPad(b64uEncode(ephemeral.publicKey)),\n nonce24: stripPad(b64uEncode(nonce)),\n ct: stripPad(b64uEncode(ct)),\n });\n}\n", "/**\n * Revocation check: IETF Token Status List (draft-ietf-oauth-status-list).\n *\n * Every credential Prson issues carries\n * status: { status_list: { idx, uri } }\n * and `uri` serves a Status List Token: a JWT (typ statuslist+jwt) signed by\n * the same issuer key as the credential, whose status_list.lst is a\n * base64url, DEFLATE (ZLIB) compressed bitstring (`bits` bits per entry,\n * index 0 in the lowest bits of byte 0). 0 = VALID; anything else (1\n * INVALID, 2 SUSPENDED) means the credential must not be accepted.\n *\n * Lists are cached briefly (default 60 s, never longer than the token's own\n * ttl). When the list can't be fetched or checked, `onUnavailable` decides:\n * \"fail-closed\" rejects, \"fail-open\" accepts. The default is closed for\n * verified humans (verification_level 5 or more, or verified_human: true)\n * and open below that.\n */\n\nexport type StatusPolicy = \"fail-open\" | \"fail-closed\";\n\nexport type StatusCheckOptions = {\n /** What to do when the status list can't be fetched or verified. Default: closed at level 5+, open below. */\n onUnavailable?: StatusPolicy;\n /** How long a fetched list is reused (seconds, default 60; capped by the token's ttl). */\n cacheSeconds?: number;\n /** The issuer's key for a kid (the same keys that sign credentials). */\n resolveKey: (kid: string) => Promise<JsonWebKey | null>;\n /** Override fetch (tests, proxies). */\n fetch?: (uri: string) => Promise<{ ok: boolean; status: number; text(): Promise<string> }>;\n /** Clock override (ms). */\n now?: () => number;\n};\n\nexport type StatusCheckResult =\n | { ok: true; checked: boolean; unavailable?: string }\n | { ok: false; reason: \"vc_revoked\" | \"status_unavailable\"; detail?: string };\n\ntype CachedList = { fetchedAt: number; ttlMs: number; exp: number | null; bits: number; list: Uint8Array };\nconst cache = new Map<string, CachedList>();\n\n/** Tests: forget cached lists. */\nexport function clearStatusCache(): void {\n cache.clear();\n}\n\n/** Whether the credential's claims describe a verified human (where an unknown status fails closed by default). */\nexport function isStrongCredential(payload: Record<string, unknown>): boolean {\n return payload.verified_human === true || (typeof payload.verification_level === \"number\" && payload.verification_level >= 5);\n}\n\nexport async function checkCredentialStatus(payload: Record<string, unknown>, opts: StatusCheckOptions): Promise<StatusCheckResult> {\n const ref = (payload.status as { status_list?: { idx?: unknown; uri?: unknown } } | undefined)?.status_list;\n if (!ref) return { ok: true, checked: false };\n const policy: StatusPolicy = opts.onUnavailable ?? (isStrongCredential(payload) ? \"fail-closed\" : \"fail-open\");\n const unavailable = (detail: string): StatusCheckResult =>\n policy === \"fail-open\" ? { ok: true, checked: false, unavailable: detail } : { ok: false, reason: \"status_unavailable\", detail };\n const idx = ref.idx;\n const uri = ref.uri;\n if (typeof idx !== \"number\" || !Number.isInteger(idx) || idx < 0 || typeof uri !== \"string\" || !/^https:\\/\\//.test(uri)) {\n return { ok: false, reason: \"status_unavailable\", detail: \"malformed status reference\" };\n }\n let entry: CachedList;\n try {\n entry = await statusList(uri, opts);\n } catch (e) {\n return unavailable((e as Error).message);\n }\n const bitOffset = idx * entry.bits;\n const byte = entry.list[bitOffset >> 3];\n if (byte === undefined) return unavailable(\"index outside the list\");\n const value = (byte >> (bitOffset & 7)) & ((1 << entry.bits) - 1);\n if (value !== 0) return { ok: false, reason: \"vc_revoked\", detail: value === 2 ? \"suspended\" : \"invalid\" };\n return { ok: true, checked: true };\n}\n\nasync function statusList(uri: string, opts: StatusCheckOptions): Promise<CachedList> {\n const now = opts.now?.() ?? Date.now();\n const cached = cache.get(uri);\n if (cached && now - cached.fetchedAt < cached.ttlMs && (cached.exp === null || cached.exp * 1000 > now)) return cached;\n const doFetch = opts.fetch ?? ((u: string) => fetch(u, { headers: { Accept: \"application/statuslist+jwt\" } }));\n const res = await doFetch(uri);\n if (!res.ok) throw new Error(`status list HTTP ${res.status}`);\n const jwt = (await res.text()).trim();\n const [h, p, s] = jwt.split(\".\");\n if (!h || !p || !s) throw new Error(\"status list token malformed\");\n const header = JSON.parse(utf8(b64uBytes(h))) as { alg?: string; kid?: string; typ?: string };\n const payload = JSON.parse(utf8(b64uBytes(p))) as { sub?: string; exp?: number; ttl?: number; status_list?: { bits?: number; lst?: string } };\n if (header.typ !== \"statuslist+jwt\" || header.alg !== \"RS256\" || !header.kid) throw new Error(\"status list token header\");\n const jwk = await opts.resolveKey(header.kid);\n if (!jwk) throw new Error(\"status list key unknown\");\n const key = await crypto.subtle.importKey(\"jwk\", jwk, { name: \"RSASSA-PKCS1-v1_5\", hash: \"SHA-256\" }, false, [\"verify\"]);\n if (!(await crypto.subtle.verify(\"RSASSA-PKCS1-v1_5\", key, b64uBytes(s), new TextEncoder().encode(`${h}.${p}`)))) throw new Error(\"status list signature\");\n if (payload.sub !== uri) throw new Error(\"status list subject\");\n if (typeof payload.exp === \"number\" && payload.exp * 1000 <= now) throw new Error(\"status list expired\");\n const bits = payload.status_list?.bits;\n if (bits !== 1 && bits !== 2 && bits !== 4 && bits !== 8) throw new Error(\"status list bits\");\n if (typeof payload.status_list?.lst !== \"string\") throw new Error(\"status list lst\");\n const list = await inflate(b64uBytes(payload.status_list.lst));\n const want = (opts.cacheSeconds ?? 60) * 1000;\n const ttlMs = typeof payload.ttl === \"number\" ? Math.min(want, payload.ttl * 1000) : want;\n const entry: CachedList = { fetchedAt: now, ttlMs, exp: typeof payload.exp === \"number\" ? payload.exp : null, bits, list };\n cache.set(uri, entry);\n return entry;\n}\n\nasync function inflate(bytes: Uint8Array<ArrayBuffer>): Promise<Uint8Array> {\n const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream(\"deflate\"));\n return new Uint8Array(await new Response(stream).arrayBuffer());\n}\n\nconst utf8 = (b: Uint8Array) => new TextDecoder().decode(b);\n\nfunction b64uBytes(s: string): Uint8Array<ArrayBuffer> {\n const pad = (4 - (s.length % 4)) % 4;\n const bin = atob((s + \"=\".repeat(pad)).replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const out = new Uint8Array(new ArrayBuffer(bin.length));\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n", "/**\n * Browser-side SD-JWT-VC verification. The SDK enforces all five rules\n * from SECURITY.md \u00A77 before resolving signIn(); the verifier-node\n * package re-enforces them server-side.\n *\n * We do this in the browser too \u2014 even though the host site must\n * re-verify on its backend \u2014 because:\n *\n * (a) failing fast in the SDK gives partners better DX (clear errors\n * before anything reaches their backend); and\n * (b) the cnf.jwk we expose to the host as the user identifier MUST\n * have actually signed the presentation we deliver, otherwise\n * sloppy callers could be tricked into trusting a forged cnf.\n *\n * Implementation uses Web Crypto for RS256 + Ed25519 verification.\n * Web Crypto's Ed25519 support landed in all major browsers in 2023+;\n * for older targets we'd polyfill with `@stablelib/ed25519`.\n */\nimport type { CnfJwk } from \"./index.js\";\nimport { checkCredentialStatus, type StatusPolicy } from \"./status.js\";\n\nexport type VerifyOptions = {\n expectedAudience: string;\n expectedNonce: string;\n acceptedVcts: string[];\n trustedIssuer: string; // e.g. \"did:web:app.prson.net\"\n maxKbAgeSeconds?: number; // default 60\n jwksUri?: string; // override (default: derived from trustedIssuer)\n /**\n * Revocation (the credential's Token Status List entry, status.ts).\n * onUnavailable: when the list can't be fetched or verified; default\n * \"fail-closed\" for verified humans (level 5+), \"fail-open\" below.\n * cacheSeconds: how long a list is reused (default 60).\n */\n status?: { onUnavailable?: StatusPolicy; cacheSeconds?: number };\n};\n\nexport type VerifyOk = {\n ok: true;\n claims: Record<string, unknown>;\n cnf: { jwk: CnfJwk };\n /**\n * The holder-signed binding: what the cnf key signed for THIS\n * presentation (the KB-JWT, or the anonymous credential's payload).\n * `walletSessionPk` is the `prson_wsk` claim \u2014 the wallet's X25519\n * session key the data channel must come from; absent from wallets\n * that predate it.\n */\n binding: { iat: number; nonce: string; walletSessionPk?: string };\n credential: {\n vct: string;\n iss: string;\n kid: string;\n expiresAt: number;\n };\n};\n\nexport type VerifyErr = {\n ok: false;\n reason:\n | \"malformed\"\n | \"issuer_key_resolve_failed\"\n | \"issuer_sig_invalid\"\n | \"vc_expired\"\n | \"vct_not_accepted\"\n | \"typ_not_accepted\"\n | \"disclosure_unmatched\"\n | \"kb_missing\"\n | \"kb_sig_invalid\"\n | \"aud_mismatch\"\n | \"nonce_mismatch\"\n | \"sd_hash_mismatch\"\n | \"kb_iat_stale\"\n | \"vc_revoked\"\n | \"status_unavailable\";\n};\n\nexport type VerifyResult = VerifyOk | VerifyErr;\n\n/** VCT for the self-signed anonymous-wallet credential \u2014 kept here as\n * well as in index.ts so verifier callers don't have to import both. */\nconst ANONYMOUS_WALLET_VCT =\n \"https://app.prson.net/credentials/anonymous-wallet/v1\";\n\nexport async function verifyPresentation(\n sdJwt: string,\n opts: VerifyOptions,\n): Promise<VerifyResult> {\n // \u2500\u2500 Anonymous-wallet credential path \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // No SD-JWT tildes \u2014 it's a plain JWS. We accept this ONLY when the\n // calling site opted in via `acceptedVcts` containing the anonymous\n // VCT. Verification is structurally simpler: cnf.jwk IS the signer,\n // so the JWS signature + cnf-binding check collapse into one step.\n if (!sdJwt.includes(\"~\") && opts.acceptedVcts.includes(ANONYMOUS_WALLET_VCT)) {\n return verifyAnonymousWallet(sdJwt, opts);\n }\n const parts = sdJwt.split(\"~\");\n if (parts.length < 2) return { ok: false, reason: \"malformed\" };\n\n const jws = parts[0]!;\n const tail = parts.slice(1);\n const last = tail[tail.length - 1];\n let kbJwt: string | undefined;\n let discTokens: string[];\n if (last === \"\" || last === undefined) {\n discTokens = tail.slice(0, -1);\n return { ok: false, reason: \"kb_missing\" };\n } else if (last.includes(\".\")) {\n kbJwt = last;\n discTokens = tail.slice(0, -1);\n } else {\n return { ok: false, reason: \"kb_missing\" };\n }\n\n // \u2500\u2500 1. Parse the issuer JWS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const [hB64, pB64, sigB64] = jws.split(\".\");\n if (!hB64 || !pB64 || !sigB64) return { ok: false, reason: \"malformed\" };\n let header: { alg?: string; kid?: string; typ?: string };\n let payload: Record<string, unknown>;\n try {\n header = JSON.parse(new TextDecoder().decode(b64uBytes(hB64)));\n payload = JSON.parse(new TextDecoder().decode(b64uBytes(pB64)));\n } catch {\n return { ok: false, reason: \"malformed\" };\n }\n // SD-JWT VC media type (draft-ietf-oauth-sd-jwt-vc): dc+sd-jwt, or the older vc+sd-jwt.\n if (header.typ !== \"dc+sd-jwt\" && header.typ !== \"vc+sd-jwt\") {\n return { ok: false, reason: \"typ_not_accepted\" };\n }\n if (typeof payload.iss !== \"string\" || payload.iss !== opts.trustedIssuer) {\n return { ok: false, reason: \"issuer_key_resolve_failed\" };\n }\n if (typeof payload.vct !== \"string\" || !opts.acceptedVcts.includes(payload.vct)) {\n return { ok: false, reason: \"vct_not_accepted\" };\n }\n // Prson always sets an expiry; a credential without one is not Prson's.\n if (typeof payload.exp !== \"number\") return { ok: false, reason: \"malformed\" };\n if (payload.exp * 1000 < Date.now()) {\n return { ok: false, reason: \"vc_expired\" };\n }\n\n // \u2500\u2500 2. Resolve the issuer JWK + verify the JWS signature \u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const issuerJwk = await resolveIssuerJwk(header.kid ?? \"\", opts);\n if (!issuerJwk) return { ok: false, reason: \"issuer_key_resolve_failed\" };\n const issuerKey = await crypto.subtle.importKey(\n \"jwk\",\n issuerJwk as JsonWebKey,\n { name: \"RSASSA-PKCS1-v1_5\", hash: \"SHA-256\" },\n false,\n [\"verify\"],\n );\n const issuerOk = await crypto.subtle.verify(\n \"RSASSA-PKCS1-v1_5\",\n issuerKey,\n b64uBytes(sigB64),\n new TextEncoder().encode(`${hB64}.${pB64}`),\n );\n if (!issuerOk) return { ok: false, reason: \"issuer_sig_invalid\" };\n\n // \u2500\u2500 2b. Not revoked (the issuer's Token Status List) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const status = await checkCredentialStatus(payload, {\n resolveKey: (kid) => resolveIssuerJwk(kid, opts),\n onUnavailable: opts.status?.onUnavailable,\n cacheSeconds: opts.status?.cacheSeconds,\n });\n if (!status.ok) return { ok: false, reason: status.reason };\n\n // \u2500\u2500 3. Verify every Disclosure digest is in the JWS's _sd \u2500\u2500\u2500\u2500\u2500\u2500\n const sdSet = collectSdDigests(payload);\n const disclosed: Array<{ name: string; value: unknown }> = [];\n for (const t of discTokens) {\n if (!t) continue;\n const arr = JSON.parse(new TextDecoder().decode(b64uBytes(t))) as unknown[];\n if (!Array.isArray(arr) || arr.length < 2) {\n return { ok: false, reason: \"disclosure_unmatched\" };\n }\n const digest = b64uEncode(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(t))));\n if (!sdSet.has(digest)) return { ok: false, reason: \"disclosure_unmatched\" };\n if (arr.length === 3 && typeof arr[1] === \"string\") {\n disclosed.push({ name: arr[1], value: arr[2] });\n }\n }\n\n // \u2500\u2500 4. Verify the KB-JWT \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (!kbJwt) return { ok: false, reason: \"kb_missing\" };\n const cnf = (payload.cnf as { jwk?: CnfJwk } | undefined)?.jwk;\n if (!cnf || cnf.kty !== \"OKP\" || cnf.crv !== \"Ed25519\") {\n return { ok: false, reason: \"kb_missing\" };\n }\n const [kbH, kbP, kbS] = kbJwt.split(\".\");\n if (!kbH || !kbP || !kbS) return { ok: false, reason: \"kb_sig_invalid\" };\n let kbHeader: { alg?: string; typ?: string };\n let kbPayload: { aud?: string; nonce?: string; sd_hash?: string; iat?: number; prson_wsk?: unknown };\n try {\n kbHeader = JSON.parse(new TextDecoder().decode(b64uBytes(kbH)));\n kbPayload = JSON.parse(new TextDecoder().decode(b64uBytes(kbP)));\n } catch {\n return { ok: false, reason: \"kb_sig_invalid\" };\n }\n if (kbHeader.alg !== \"EdDSA\" || kbHeader.typ !== \"kb+jwt\") {\n return { ok: false, reason: \"kb_sig_invalid\" };\n }\n if (kbPayload.aud !== opts.expectedAudience) return { ok: false, reason: \"aud_mismatch\" };\n if (kbPayload.nonce !== opts.expectedNonce) return { ok: false, reason: \"nonce_mismatch\" };\n if (typeof kbPayload.iat !== \"number\") return { ok: false, reason: \"kb_iat_stale\" };\n const maxAge = opts.maxKbAgeSeconds ?? 60;\n if (Math.abs(Date.now() / 1000 - kbPayload.iat) > maxAge) {\n return { ok: false, reason: \"kb_iat_stale\" };\n }\n // Per SD-JWT-VC: prefix is \"<JWS>~<D_1>~...~<D_n>~\" with exactly\n // ONE trailing tilde \u2014 N tildes total for N-1 disclosures. The\n // naive `${jws}~${discTokens.join(\"~\")}~` produces TWO trailing\n // tildes when `discTokens.length === 0` (since `[].join === \"\"`),\n // breaking every no-disclosure presentation (verified-human only,\n // anonymous, anything where the holder filtered out all\n // disclosures). Build it from parts directly so it stays correct\n // at n=0.\n const prefixParts = discTokens.length === 0\n ? [jws]\n : [jws, ...discTokens];\n const presentationPrefix = `${prefixParts.join(\"~\")}~`;\n const sdHash = b64uEncode(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(presentationPrefix))));\n if (kbPayload.sd_hash !== sdHash) return { ok: false, reason: \"sd_hash_mismatch\" };\n\n const holderKey = await crypto.subtle.importKey(\n \"jwk\",\n cnf as JsonWebKey,\n { name: \"Ed25519\" },\n false,\n [\"verify\"],\n );\n const kbOk = await crypto.subtle.verify(\n \"Ed25519\",\n holderKey,\n b64uBytes(kbS),\n new TextEncoder().encode(`${kbH}.${kbP}`),\n );\n if (!kbOk) return { ok: false, reason: \"kb_sig_invalid\" };\n\n // \u2500\u2500 5. Reassemble disclosed claims \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const claims: Record<string, unknown> = {};\n // Always-visible top-level claims from the JWS (minus SD internals).\n for (const [k, v] of Object.entries(payload)) {\n if (k === \"_sd\" || k === \"_sd_alg\" || k === \"cnf\") continue;\n if ([\"iss\", \"vct\", \"iat\", \"exp\"].includes(k)) continue;\n claims[k] = v;\n }\n for (const d of disclosed) claims[d.name] = d.value;\n\n return {\n ok: true,\n claims,\n cnf: { jwk: cnf },\n binding: {\n iat: kbPayload.iat,\n nonce: kbPayload.nonce as string,\n ...walletSessionKeyClaim(kbPayload.prson_wsk),\n },\n credential: {\n vct: payload.vct as string,\n iss: payload.iss as string,\n kid: (header.kid ?? \"\") as string,\n expiresAt: typeof payload.exp === \"number\" ? payload.exp * 1000 : 0,\n },\n };\n}\n\n/**\n * The `prson_wsk` claim: the wallet's X25519 session key (32 bytes,\n * base64url without padding), signed by the cnf key so the data channel\n * can be tied to the holder. Anything malformed counts as absent.\n */\nfunction walletSessionKeyClaim(v: unknown): { walletSessionPk?: string } {\n if (typeof v !== \"string\" || !/^[A-Za-z0-9_-]{43}$/.test(v)) return {};\n return { walletSessionPk: v };\n}\n\n/** Lazy in-memory cache of the Prson issuer JWKS. 1 h TTL. */\nconst jwksCache = new Map<string, { fetchedAt: number; keys: Record<string, JsonWebKey> }>();\n\nasync function resolveIssuerJwk(\n kid: string,\n opts: VerifyOptions,\n): Promise<JsonWebKey | null> {\n if (!kid) return null;\n // did:web:app.prson.net \u2192 https://app.prson.net/.well-known/jwt-vc-issuer.\n const host = opts.trustedIssuer.replace(/^did:web:/, \"\");\n const uri = opts.jwksUri ?? `https://${host}/.well-known/jwt-vc-issuer`;\n const cached = jwksCache.get(uri);\n if (cached && Date.now() - cached.fetchedAt < 60 * 60 * 1000) {\n return cached.keys[kid] ?? null;\n }\n const res = await fetch(uri);\n if (!res.ok) return null;\n const body = (await res.json()) as { jwks?: { keys: JsonWebKey[] }; keys?: JsonWebKey[] };\n const keys = body.jwks?.keys ?? body.keys ?? [];\n const map: Record<string, JsonWebKey> = {};\n for (const k of keys) {\n const id = (k as { kid?: string }).kid;\n if (id) map[id] = k;\n }\n jwksCache.set(uri, { fetchedAt: Date.now(), keys: map });\n return map[kid] ?? null;\n}\n\nfunction collectSdDigests(payload: unknown, out = new Set<string>()): Set<string> {\n if (!payload || typeof payload !== \"object\") return out;\n if (Array.isArray(payload)) {\n for (const v of payload) collectSdDigests(v, out);\n return out;\n }\n const obj = payload as Record<string, unknown>;\n for (const [k, v] of Object.entries(obj)) {\n if (k === \"_sd\" && Array.isArray(v)) {\n for (const digest of v) {\n if (typeof digest === \"string\") out.add(digest);\n }\n } else if (typeof v === \"object\") {\n collectSdDigests(v, out);\n }\n }\n return out;\n}\n\n// Returns an ArrayBuffer-backed Uint8Array so it's `BufferSource`-typed\n// under TypeScript 5.7+'s stricter typings (SharedArrayBuffer-backed\n// views are rejected by SubtleCrypto's `verify` signature).\nfunction b64uBytes(s: string): Uint8Array<ArrayBuffer> {\n const pad = (4 - (s.length % 4)) % 4;\n const std = (s + \"=\".repeat(pad)).replace(/-/g, \"+\").replace(/_/g, \"/\");\n const bin = atob(std);\n const buf = new ArrayBuffer(bin.length);\n const out = new Uint8Array(buf);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nfunction b64uEncode(bytes: Uint8Array): string {\n let s = \"\";\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]!);\n return btoa(s).replace(/=+$/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n}\n\n/**\n * Verify a self-signed anonymous-wallet credential. Spec:\n *\n * header = { typ: \"anon-wallet+jwt\", alg: \"EdDSA\" }\n * payload = { iss: <domain>, aud, nonce, iat, exp,\n * vct: ANONYMOUS_WALLET_VCT,\n * cnf: { jwk: <Ed25519 OKP JWK> } }\n *\n * The signing key IS cnf.jwk \u2014 there's no separate issuer key to\n * resolve. The verifier checks aud/nonce/exp and the Ed25519 sig.\n *\n * This is only accepted by [verifyPresentation] when `acceptedVcts`\n * includes ANONYMOUS_WALLET_VCT, which only happens when the host\n * site passed `allowAnonymous: true` to PrsonLogin.signIn().\n */\nasync function verifyAnonymousWallet(\n jws: string,\n opts: VerifyOptions,\n): Promise<VerifyResult> {\n const [hB64, pB64, sigB64] = jws.split(\".\");\n if (!hB64 || !pB64 || !sigB64) return { ok: false, reason: \"malformed\" };\n let header: { alg?: string; typ?: string };\n let payload: Record<string, unknown>;\n try {\n header = JSON.parse(new TextDecoder().decode(b64uBytes(hB64)));\n payload = JSON.parse(new TextDecoder().decode(b64uBytes(pB64)));\n } catch {\n return { ok: false, reason: \"malformed\" };\n }\n if (header.alg !== \"EdDSA\" || header.typ !== \"anon-wallet+jwt\") {\n return { ok: false, reason: \"malformed\" };\n }\n if (payload.vct !== ANONYMOUS_WALLET_VCT) {\n return { ok: false, reason: \"vct_not_accepted\" };\n }\n const cnf = (payload.cnf as { jwk?: CnfJwk } | undefined)?.jwk;\n if (!cnf || cnf.kty !== \"OKP\" || cnf.crv !== \"Ed25519\") {\n return { ok: false, reason: \"kb_missing\" };\n }\n if (payload.aud !== opts.expectedAudience) {\n return { ok: false, reason: \"aud_mismatch\" };\n }\n if (payload.nonce !== opts.expectedNonce) {\n return { ok: false, reason: \"nonce_mismatch\" };\n }\n const nowSec = Math.floor(Date.now() / 1000);\n if (typeof payload.exp !== \"number\" || payload.exp < nowSec) {\n return { ok: false, reason: \"vc_expired\" };\n }\n if (typeof payload.iat !== \"number\" || Math.abs(nowSec - payload.iat) > (opts.maxKbAgeSeconds ?? 60)) {\n return { ok: false, reason: \"kb_iat_stale\" };\n }\n // The signing key is cnf.jwk itself \u2014 no separate issuer key to\n // resolve. A correct signature here proves the holder controls the\n // pk they're claiming.\n const key = await crypto.subtle.importKey(\n \"jwk\",\n cnf as JsonWebKey,\n { name: \"Ed25519\" },\n false,\n [\"verify\"],\n );\n const ok = await crypto.subtle.verify(\n \"Ed25519\",\n key,\n b64uBytes(sigB64),\n new TextEncoder().encode(`${hB64}.${pB64}`),\n );\n if (!ok) return { ok: false, reason: \"issuer_sig_invalid\" };\n\n return {\n ok: true,\n claims: {\n // Anonymous credentials carry no profile data \u2014 just the marker\n // that the user controls the signing key. The host site treats\n // cnf.jwk.x as the stable per-user id on this domain.\n anonymous: true,\n },\n cnf: { jwk: cnf },\n binding: {\n iat: payload.iat as number,\n nonce: payload.nonce as string,\n ...walletSessionKeyClaim(payload.prson_wsk),\n },\n credential: {\n vct: ANONYMOUS_WALLET_VCT,\n iss: typeof payload.iss === \"string\" ? payload.iss : opts.trustedIssuer,\n kid: \"\",\n expiresAt: (payload.exp as number) * 1000,\n },\n };\n}\n", "/**\n * Verifier \u2192 wallet REQUEST channel.\n *\n * After sign-in the host site can ask the wallet for things that\n * weren't part of the initial disclosure (a specific claim value, a\n * predicate check, a document presence assertion, a document\n * signature, a free-form input typed on the phone). Each request\n * carries a UUID; the wallet replies with a matching `response`\n * envelope whose `requestId` references it.\n *\n * Three protocol invariants the wallet enforces:\n *\n * * **At most one request per second** \u2014 inter-arrival throttle on\n * the wallet side. Inbound requests that violate this are silently\n * dropped (no response sent); the browser SDK's per-call timeout\n * surfaces them as `error: \"timeout\"`.\n *\n * * **At most five outstanding requests** in the wallet's queue.\n * Once five drawers are open, further incoming requests are\n * ignored on the floor.\n *\n * * **Requests fire ONLY while a web session is active.** No\n * background requests, no pre-sign-in requests. The session's\n * transport going away invalidates every pending request with\n * `error: \"no-active-session\"`.\n *\n * Browser SDK shape (this file): public types + the in-flight\n * controller that pairs outbound requests with their wallet replies.\n * The session's `_sendToWallet` is the cipher path.\n */\n\nimport type { DecryptedEnvelope } from \"./crypto.js\";\n\n// \u2500\u2500\u2500 Public request shapes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Output wire format for a signed predicate (fragment). See\n * `functions/utils/predicateFormatters.js` for the formatter registry\n * the server uses; the verifier-node package decodes the matching\n * shape with `verifySignedFragment` / `verifyFragmentCredential`.\n */\nexport type PredicateFormat = \"native\" | \"vc+jwt\" | \"vc+sd-jwt\";\n\n/**\n * Free-form text/numeric input typed on the phone \u2014 the \"kiosk\n * companion\" use case. Mirrors a subset of the HTML input element\n * so the wallet UI can pick a sensible keyboard / validator.\n *\n * `select` is included to cover `<select>` elements: the wallet UI\n * renders an options picker (radio-style on phone) and returns the\n * chosen option's `value`.\n */\nexport type InputType =\n | \"text\"\n | \"search\"\n | \"email\"\n | \"tel\"\n | \"url\"\n | \"number\"\n | \"password\"\n | \"select\";\n\n/** One choice in a `select` field. */\nexport interface InputOption {\n /** Wire value \u2014 what the wallet returns and the host fills. */\n value: string;\n /** Display label shown in the wallet picker. Defaults to `value`. */\n label?: string;\n}\n\n/**\n * One field inside a multi-input `input-form` request. Same surface\n * as a single `kind: \"input\"` request, plus an optional `name` (used\n * as the reply key) and a `defaultValue` (pre-fill).\n *\n * Two shapes \u2014 the discriminator is `inputType`:\n *\n * * Text/numeric inputs: `text` | `search` | `email` | `tel` |\n * `url` | `number` | `password` \u2014 validation knobs match the\n * HTML5 attribute set the host can read off a DOM `<input>`.\n *\n * * Select picker: `inputType: \"select\"` requires `options` and\n * ignores the validation knobs that don't apply (`pattern`,\n * `minLength`, `maxLength`).\n */\nexport type InputFormField =\n | {\n name: string;\n inputType: Exclude<InputType, \"select\">;\n label: string;\n placeholder?: string;\n defaultValue?: string;\n minLength?: number;\n maxLength?: number;\n min?: number;\n max?: number;\n pattern?: string;\n required?: boolean;\n }\n | {\n name: string;\n inputType: \"select\";\n label: string;\n options: InputOption[];\n defaultValue?: string;\n required?: boolean;\n };\n\nexport type LoginRequest =\n /**\n * Ask the wallet to reveal the raw value of a single claim. Used\n * by host sites that want a stale claim refreshed without a\n * full re-sign-in \u2014 e.g. \"what's your current verification\n * level?\". The wallet prompts the user before answering.\n */\n | {\n kind: \"claim-value\";\n name: string;\n /** Human-readable reason shown in the wallet drawer. */\n reason?: string;\n }\n\n /**\n * Predicate check against a fragment the wallet has signed.\n * Returns the matching signed fragment so the verifier can\n * re-verify the signature server-side.\n *\n * `format` selects the wire shape the wallet asks the notary to\n * mint:\n * * `native` \u2014 Prson-flat shape (RSA-SHA256 over the canonical\n * bytes). Smallest, default for back-compat.\n * * `vc+jwt` \u2014 W3C VC Data Model 2.0 JWS.\n * * `vc+sd-jwt` \u2014 IETF SD-JWT-VC with one disclosure.\n * The choice flows server-side via the\n * `signPropertyFragment` Cloud Function's `format` parameter and is\n * verified browser-side by `@prson/login-verifier`'s\n * `verifySignedFragment` (native) / `verifyFragmentCredential` (jwt).\n */\n | {\n kind: \"fragment-check\";\n fragmentName: string;\n format?: PredicateFormat;\n reason?: string;\n }\n\n /**\n * Ask the wallet whether a verified document of the given shape\n * is present. The user can also pick a document; if none\n * matches, the wallet may offer to scan one via NFC (if the\n * device is compatible). Reply carries either the document's\n * notarised metadata or an error.\n */\n | {\n kind: \"document-presence\";\n /** Filter \u2014 `\"passport\"`, `\"national_id\"`, etc. */\n type?: string;\n /** ISO-3 country code, optional. */\n country?: string;\n reason?: string;\n }\n\n /**\n * Document signing \u2014 the host hands the wallet either the raw\n * bytes (for tiny files) or a short-lived upload URL. The wallet\n * signs with the identity's PAdES-bound EC key (see\n * `mobile-app/prson_app/docs/identity_pdf_signing.md`).\n */\n | {\n kind: \"document-sign\";\n document:\n | { bytes: Uint8Array }\n | { uploadUrl: string; size?: number; sha256?: string };\n visibleCue?: string;\n reason?: string;\n }\n\n /**\n * Generic single input request \u2014 kiosk pattern. The wallet shows\n * a keyboard sized to the type + the constraints, returns the\n * typed value. No notary signature \u2014 the host trusts the\n * channel + the user.\n *\n * For `inputType: \"select\"`, supply `options`. The wallet\n * renders a radio-style picker on the phone and the reply's\n * `value` is the chosen option's `value` string.\n */\n | {\n kind: \"input\";\n inputType: InputType;\n label: string;\n placeholder?: string;\n defaultValue?: string;\n /** HTML5-style validation constraints \u2014 wallet enforces. */\n minLength?: number;\n maxLength?: number;\n /** For `inputType: \"number\"`. */\n min?: number;\n max?: number;\n /** Regex; wallet uses to gate the submit button. */\n pattern?: string;\n required?: boolean;\n /** Required when `inputType === \"select\"`. */\n options?: InputOption[];\n reason?: string;\n }\n\n /**\n * Multi-input form \u2014 one wallet drawer, prev/next/send\n * navigation, fills every field at once when the user taps\n * Send. The reply's `value` is `Record<fieldName, string>`.\n *\n * Drives the `session.bindForm(...)` helper, which walks a\n * `<form>` / container element and synthesises one of these\n * requests from the DOM. The host can also build them by\n * hand \u2014 useful for verifier-side flows where the inputs are\n * decided at runtime rather than rendered on the page.\n */\n | {\n kind: \"input-form\";\n fields: InputFormField[];\n /** Label on the final \"Send\" button. Defaults to \"Send\". */\n submitLabel?: string;\n reason?: string;\n }\n\n /**\n * Virtual pointer / cursor. The wallet sources pointer events\n * from the phone and streams them through `mouse-update`\n * envelopes (paired by `requestId`) until the user closes the\n * drawer; the final `response` carries the session totals.\n *\n * Two modes:\n *\n * * `\"touch\"` \u2014 the phone screen becomes a touchpad. Drag the\n * finger to move the cursor; single-tap = click;\n * double-tap = double-click; two-finger drag = scroll. The\n * [`bindMouse`] helper renders a small circular cursor over\n * the page and applies the streamed deltas.\n *\n * * `\"magic\"` \u2014 phone gyro + accelerometer drive a \"magic\n * wand\". Tap on the phone screen = click; double-tap =\n * double-click; swipe up / down on the phone = scroll.\n * Bigger learning curve but no thumb-on-screen\n * drag \u2014 useful for hands-free presentation control.\n *\n * The host requests a mode; the wallet UI honours it but may\n * surface a toggle to switch mid-session (in which case the\n * streamed envelopes carry the actual mode in `mode`).\n */\n | {\n kind: \"mouse\";\n mode: \"touch\" | \"magic\";\n reason?: string;\n };\n\nexport type LoginResponse =\n /** Success \u2014 `value` shape depends on the request kind. */\n | { ok: true; value: unknown }\n /** Failure \u2014 `error` is a short machine-readable code. */\n | {\n ok: false;\n error:\n | \"declined\"\n | \"not-present\"\n | \"expired\"\n | \"rate-limited\"\n | \"queue-full\"\n | \"no-active-session\"\n | \"timeout\"\n | \"session-closed\"\n | \"unsupported\"\n | string;\n };\n\nexport interface RequestOptions {\n /**\n * Hard deadline for the wallet reply. Default 60 s \u2014 generous\n * because the wallet drawer is on the user's phone and they may\n * need to scan an NFC document. Callers expecting a fast reply\n * (e.g. kiosk text input) can tighten this.\n */\n timeoutMs?: number;\n}\n\n// \u2500\u2500\u2500 In-flight controller \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface Pending {\n requestId: string;\n resolve: (r: LoginResponse) => void;\n timer: ReturnType<typeof setTimeout> | null;\n}\n\n/**\n * Pairs outbound `request` envelopes with their matching\n * `response` envelopes by UUID. Held privately on a\n * `PrsonLoginSession`; not part of the public surface.\n */\nexport class RequestController {\n private _pending = new Map<string, Pending>();\n private _closed = false;\n\n /**\n * Wire up a new outbound request. Returns the requestId to put in\n * the envelope + a `promise` that resolves when the wallet replies\n * (or times out / the session closes).\n */\n enqueue(timeoutMs: number): { requestId: string; promise: Promise<LoginResponse> } {\n const requestId = newUuid();\n // `setTimeout` accepts up to int32-max milliseconds (~24.8 days)\n // before silently overflowing and firing on the next tick. Any\n // caller passing a credential-exp-derived budget (90-day VC\n // credentials yield ~7.8 billion ms) would otherwise see an\n // immediate `error: \"timeout\"`. Clamp defensively here so the\n // contract holds regardless of caller hygiene.\n const MAX_SAFE_TIMEOUT = 2_147_483_000;\n const safeTimeoutMs = Math.min(\n Math.max(0, timeoutMs),\n MAX_SAFE_TIMEOUT,\n );\n const promise = new Promise<LoginResponse>((resolve) => {\n if (this._closed) {\n resolve({ ok: false, error: \"session-closed\" });\n return;\n }\n const entry: Pending = {\n requestId,\n resolve,\n timer: setTimeout(() => {\n const p = this._pending.get(requestId);\n if (!p) return;\n this._pending.delete(requestId);\n resolve({ ok: false, error: \"timeout\" });\n }, safeTimeoutMs),\n };\n this._pending.set(requestId, entry);\n });\n return { requestId, promise };\n }\n\n /** Resolve a pending request when a wallet `response` envelope arrives. */\n resolve(envelope: DecryptedEnvelope): void {\n if (envelope.msg !== \"response\") return;\n const requestId = envelope.requestId;\n if (!requestId) return;\n const entry = this._pending.get(requestId);\n if (!entry) return; // unknown id \u2014 late reply after timeout, ignore\n this._pending.delete(requestId);\n if (entry.timer) clearTimeout(entry.timer);\n if (envelope.error) {\n entry.resolve({ ok: false, error: envelope.error });\n } else {\n entry.resolve({ ok: true, value: envelope.result });\n }\n }\n\n /**\n * Reject every in-flight request with the given reason. Typically\n * called with `\"session-closed\"` from session teardown.\n */\n closeAll(reason: string): void {\n if (this._closed) return;\n this._closed = true;\n for (const entry of this._pending.values()) {\n if (entry.timer) clearTimeout(entry.timer);\n entry.resolve({ ok: false, error: reason });\n }\n this._pending.clear();\n }\n}\n\n/**\n * RFC-4122 v4 UUID via `crypto.randomUUID` when present, else a\n * `getRandomValues`-based fallback for older browsers. The wire\n * carries the canonical hex-with-dashes form.\n */\nfunction newUuid(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const b = new Uint8Array(16);\n crypto.getRandomValues(b);\n // version + variant bits per RFC 4122\n b[6] = (b[6]! & 0x0f) | 0x40;\n b[8] = (b[8]! & 0x3f) | 0x80;\n const h = Array.from(b, (x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n}\n", "/**\n * PrsonLoginSession \u2014 the live handle the SDK returns from\n * `signIn()`. Owns the established WebRTC transport + ephemeral\n * keys; dispatches a typed event stream as the wallet pushes\n * post-sign-in updates; tears everything down when the credential\n * expires or the host calls `close()`.\n *\n * Event taxonomy (see [ROADMAP \u00A71](../../ROADMAP.md)):\n *\n * Identity lifecycle:\n * signed_in \u2014 fires once, right after `signIn()`\n * resolves (via a microtask so listeners\n * attached synchronously after the await\n * still receive it).\n * signed_out \u2014 terminal; fires once with an\n * ExpiryReason.\n * renewed \u2014 wallet pushed a fresh VC + KB-JWT.\n *\n * Claim updates (require a re-verified SD-JWT-VC in the same\n * envelope):\n * claim_added \u2014 a claim name appeared that wasn't in\n * the prior snapshot.\n * claim_removed \u2014 a prior claim name is no longer\n * present.\n * claim_updated \u2014 same name, different value.\n *\n * Display hints (no crypto re-verify; the host should treat the\n * payload as advisory and ignore it for any privileged decision):\n * display_name_changed\n * avatar_changed\n *\n * Compliance:\n * credential_revoked \u2014 followed by signed_out with reason\n * \"credential_revoked\".\n *\n * Wire grammar lives in `crypto.ts:DecryptedEnvelope`.\n */\nimport type { CnfJwk, SignInResult } from \"./index.js\";\nimport type { DecryptedEnvelope, EphemeralKeys } from \"./crypto.js\";\nimport { boxToWallet, decryptEnvelope } from \"./crypto.js\";\nimport type { Transport } from \"./transport.js\";\nimport { verifyPresentation, type VerifyOptions } from \"./verify.js\";\nimport {\n RequestController,\n type LoginRequest,\n type LoginResponse,\n type RequestOptions,\n} from \"./requests.js\";\n\nexport type { LoginRequest, LoginResponse, RequestOptions, InputType } from \"./requests.js\";\n\nexport type ExpiryReason =\n | \"ttl_reached\"\n | \"wallet_signed_out\"\n | \"user_revoked\"\n | \"network_loss\"\n | \"credential_revoked\";\n\nexport type CredentialRevokedReason =\n | \"alias_transferred\"\n | \"user_revoked\"\n | \"key_compromised\";\n\n/**\n * Coarse health of the wallet \u2194 browser data channel as observed via\n * the periodic ping/pong loop. Drives the connection-status dot the\n * wallet renders on its remote-nav banner; partner sites can mirror\n * the same signal by reading [PrsonLoginSession.connectionStatus] /\n * subscribing via [PrsonLoginSession.onConnectionStatus].\n *\n * * `unknown` \u2014 before the first pong has landed.\n * * `stable` \u2014 last RTT under [CONNECTION_UNSTABLE_THRESHOLD_MS].\n * * `unstable` \u2014 last RTT crossed the threshold.\n * * `offline` \u2014 no pong for [CONNECTION_OFFLINE_AFTER_MS]; the\n * channel is either dead or paused.\n */\nexport type ConnectionStatus = \"unknown\" | \"stable\" | \"unstable\" | \"offline\";\n\n/** RTT above this (ms) flips connectionStatus to `unstable`. */\nconst CONNECTION_UNSTABLE_THRESHOLD_MS = 1000;\n/** No pong observed for this long (ms) flips status to `offline`. */\nconst CONNECTION_OFFLINE_AFTER_MS = 5000;\n/** Cadence of the local ping loop (ms). */\nconst PING_INTERVAL_MS = 2000;\n/** Delay before retransmitting an ack-required envelope (ms). */\nconst ACK_RETRY_DELAY_MS = 2000;\n/** Maximum retransmissions before giving up on an ack-required envelope. */\nconst ACK_MAX_ATTEMPTS = 3;\n/** LRU cap on the seen-id dedupe set. ~500 ids \u2248 16 min of pings\n * on the 2 s loop, far longer than any realistic re-send window. */\nconst SEEN_IDS_CAPACITY = 500;\n\n/**\n * Generate a UUID v4. Browsers shipping `crypto.randomUUID` use it\n * directly; older engines fall back to a `getRandomValues`-based\n * implementation that produces the same on-the-wire shape.\n */\n/**\n * Detach a timer handle from Node's \"keep the event loop alive\"\n * accounting. In browsers `setTimeout` / `setInterval` return a\n * number with no `unref` method, so the test is a harmless no-op.\n * In Node the returned `Timeout` object has `unref()` and this is\n * what stops unit tests from hanging until their hour-scale expiry\n * timer would otherwise fire.\n */\nfunction _unrefTimer(\n t: ReturnType<typeof setTimeout> | ReturnType<typeof setInterval> | null,\n): void {\n if (t === null) return;\n const maybe = t as unknown as { unref?: () => void };\n if (typeof maybe.unref === \"function\") maybe.unref();\n}\n\n/**\n * Map a transport-layer close reason string onto the SDK's typed\n * [ExpiryReason]. The transport emits a small vocabulary:\n *\n * * `\"ttl_reached\"` \u2014 Worker DO alarm fired at session TTL\n * * `\"wallet_signed_out\"` \u2014 wallet sent a `peer-gone` signaling\n * message (revoked) before the wire\n * died\n * * `\"network_loss\"` \u2014 anything else (signaling WS dropped\n * for a transport reason, data channel\n * closed on its own, etc.)\n *\n * Anything we don't recognise degrades to `network_loss` \u2014\n * preserving the host's invariant that a `signed_out` event always\n * carries a known reason.\n */\nfunction _mapTransportCloseReason(reason: string): ExpiryReason {\n if (reason === \"ttl_reached\") return \"ttl_reached\";\n if (reason === \"wallet_signed_out\") return \"wallet_signed_out\";\n if (reason === \"user_revoked\") return \"user_revoked\";\n if (reason === \"credential_revoked\") return \"credential_revoked\";\n return \"network_loss\";\n}\n\nfunction uuidv4(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const buf = new Uint8Array(16);\n crypto.getRandomValues(buf);\n buf[6] = (buf[6]! & 0x0f) | 0x40; // version 4\n buf[8] = (buf[8]! & 0x3f) | 0x80; // variant 10\n const h: string[] = [];\n for (let i = 0; i < 16; i++) h.push(buf[i]!.toString(16).padStart(2, \"0\"));\n return (\n h.slice(0, 4).join(\"\") +\n \"-\" +\n h.slice(4, 6).join(\"\") +\n \"-\" +\n h.slice(6, 8).join(\"\") +\n \"-\" +\n h.slice(8, 10).join(\"\") +\n \"-\" +\n h.slice(10, 16).join(\"\")\n );\n}\n\n/** Convenience alias kept for callers that consumed the old shape. */\nexport type Renewal = Pick<SignInResult, \"sdJwtVc\" | \"claims\" | \"credential\">;\n\n/**\n * Discriminated union of every lifecycle event the SDK emits during\n * a live session. Each variant carries exactly the fields a\n * subscriber needs \u2014 no shared base envelope, so `e.type` is the\n * only discriminator and the TS compiler narrows the rest.\n *\n * The `signed_in` event also rides this union for uniform\n * subscription, even though `signIn()` already returns the result\n * synchronously. Useful for `onAny` listeners that want a single\n * log line per lifecycle transition.\n *\n * **Privacy policy: claim events never carry raw values.**\n * `claim_added` / `claim_updated` / `claim_removed` deliver only\n * the changed claim **name**. The actual value lives in\n * `session.claims` (the verified snapshot the SDK keeps in sync\n * with the latest SD-JWT-VC) and is read on-demand by the host.\n *\n * Why: `onAny` is the natural attachment point for telemetry\n * (analytics, error reporters, ML feature pipes, \u2026). Any of those\n * trivially capture entire event objects. Putting `value` into the\n * event payload would silently leak raw identity data \u2014 name,\n * birthdate, verification level \u2014 through every such pipe without\n * the host owner noticing. Name-only events let telemetry log\n * **that** a claim changed without ever seeing **what** it changed\n * to. The host reads `session.claims[name]` when (and only when)\n * it needs the value, and is free to scrub that read site\n * independently of the event surface.\n *\n * The exceptions are the explicitly-public display fields\n * (`display_name_changed`, `avatar_changed`) \u2014 those carry their\n * values directly because they're meant to drive UI without an\n * extra read step.\n */\nexport type LoginEvent =\n | { type: \"signed_in\"; result: SignInResult }\n | { type: \"signed_out\"; reason: ExpiryReason }\n | { type: \"renewed\"; result: SignInResult }\n /**\n * Claim added / updated. `newHash` is a hex-encoded SHA-256 of the\n * canonical-JSON encoding of the NEW value \u2014 the host can compare\n * against a precomputed `sha256(canonical(expected))` to confirm\n * what the new value is without ever seeing the value travel\n * through the event payload. The full value lives in\n * `session.claims[name]` for callers that need it.\n */\n | { type: \"claim_added\"; name: string; newHash: string }\n | { type: \"claim_updated\"; name: string; newHash: string }\n | { type: \"claim_removed\"; name: string }\n | { type: \"display_name_changed\"; displayName: string | null }\n | { type: \"avatar_changed\"; avatar: { url: string; hash: string } | null }\n | { type: \"credential_revoked\"; reason: CredentialRevokedReason };\n\nexport type LoginEventType = LoginEvent[\"type\"];\n\n/** Function returned by `on()` / `onAny()` to remove the listener. */\nexport type Unsubscribe = () => void;\n\nexport class PrsonLoginSession {\n private _expiresAt: number;\n private _cnf: { jwk: CnfJwk };\n private _claimsSnapshot: Record<string, unknown>;\n private _transport: Transport;\n private _ephKeys: EphemeralKeys;\n private _verifierContext: VerifierContext;\n private _expiryTimer: ReturnType<typeof setTimeout> | null = null;\n private _closed = false;\n\n /**\n * Wallet's session X25519 public key, PINNED from the verified\n * sign-in presentation (its KB-JWT `prson_wsk` claim, signed by the\n * cnf key). Every inbound envelope must be boxed by this key or it is\n * dropped, and every outbound one is boxed to it. It changes only when\n * a verified `renewal` presentation carries a new `prson_wsk`. Null\n * when the wallet published none \u2014 calls to `request()` then resolve\n * with `{ ok: false, error: \"no-active-session\" }`.\n */\n private _walletSessionPk: string | null = null;\n\n /**\n * True when the sign-in presentation didn't bind a session key (a\n * wallet older than envelope v2). The sender of inbound envelopes\n * can't be checked then, so envelopes that act on the page (`nav`,\n * `value`, `mouse-update`, file transfer) are ignored; everything\n * else still works. See SECURITY.md \u00A74.\n */\n private _legacyChannel = false;\n\n /** `iat` of the newest verified presentation (sign-in or renewal).\n * A renewal / claim-update must be strictly newer. */\n private _lastPresentationIat = 0;\n\n /** SHA-256 of every presentation this session accepted, so a replay\n * of an earlier one (even with a still-fresh `iat`) is refused. */\n private _seenPresentations: Set<string> = new Set();\n\n /** Pairs outbound `request` envelopes with inbound `response`s. */\n private _requestController = new RequestController();\n\n /**\n * Per-`requestId` mouse-update subscribers. Populated by\n * [`bindMouse`] when it opens a `kind: \"mouse\"` request and torn\n * down when the controller disposes or the wallet's final\n * `response` arrives. Keys are RFC-4122 v4 UUIDs (the request id);\n * values get a stream of decoded `mouse` bodies.\n */\n private _mouseSubscribers: Map<string, (mouse: NonNullable<DecryptedEnvelope[\"mouse\"]>) => void> = new Map();\n\n /**\n * Ambient mouse-update handler. Used when the wallet starts a\n * mouse stream WITHOUT a prior `kind: \"mouse\"` request \u2014 i.e.\n * the pre-grant flow enabled by [SignInOptions.mouseControl].\n * [`bindMouse`] registers itself here; any inbound\n * `mouse-update` frame whose `requestId` doesn't match a\n * specific subscriber falls through to this handler so the\n * cursor moves regardless of who initiated the stream.\n *\n * Null when no [`bindMouse`] is mounted; only one ambient\n * handler is active at a time (last call wins, mirroring the\n * remote-nav listener semantics).\n */\n private _ambientMouseHandler: ((mouse: NonNullable<DecryptedEnvelope[\"mouse\"]>) => void) | null = null;\n\n /**\n * File-transfer envelope handler. [`enableRemoteNavigation`]\n * installs one of these to receive `file-begin` / `file-chunk` /\n * `file-end` envelopes and reassemble the bytes into a `File`\n * the focused `<input type=\"file\">` accepts. The session layer\n * just dispatches \u2014 assembly logic lives in `bind.ts` so the\n * DOM dependency stays out of the protocol layer.\n */\n private _fileEnvelopeHandler: ((envelope: DecryptedEnvelope) => void) | null = null;\n\n /**\n * Remote-navigation listener \u2014 installed by\n * [`enableRemoteNavigation`]. Receives every inbound `nav`,\n * `value`, and `logout` envelope. Only one listener at a time\n * (later registrations replace the prior). Null when remote-nav\n * is not active for this session.\n */\n private _remoteNavListener:\n | ((\n envelope:\n | { msg: \"nav\"; action: \"prev\" | \"next\" | \"submit\" }\n | { msg: \"value\"; value: string }\n | { msg: \"logout\" },\n ) => void)\n | null = null;\n\n /**\n * User's preferred UI language as a BCP-47 tag. Captured from the\n * initial `presentation` envelope's `preferredLanguage` field;\n * updated whenever a fresh envelope arrives with a new value.\n * Null until the first envelope lands. The host page reads this\n * to localise its own UI without an extra round-trip.\n */\n private _preferredLanguage: string | null = null;\n\n /**\n * Public-profile display name (cosmetic \u2014 host should treat as\n * untrusted). Seeded from the wallet's initial `presentation`\n * envelope and updated via `display-update` envelopes; mirrored\n * by the `display_name_changed` event.\n */\n private _displayName: string | null = null;\n\n /**\n * Public-profile avatar pointer (cosmetic). Same trust model as\n * `_displayName`. Updated via `display-update` envelopes; mirrored\n * by `avatar_changed`.\n */\n private _avatar: { url: string; hash: string } | null = null;\n\n /** Per-type listener map. */\n private _listeners: Map<LoginEventType, Set<(e: LoginEvent) => void>> =\n new Map();\n /** \"Fire on every event\" subscribers \u2014 for logging / telemetry. */\n private _anyListeners: Set<(e: LoginEvent) => void> = new Set();\n\n // \u2500\u2500\u2500 Transport-layer reliability state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n //\n // Mirrors the wallet's LoginSession protocol (see\n // mobile-app/.../login_session_service.dart):\n //\n // * `_seenIds` + `_seenIdsOrder` \u2014 LRU dedupe of inbound `id`s.\n // * `_pendingAcks` \u2014 outbound ack-tracked sends.\n // * `_pingSendTimes` \u2014 RTT correlation by ping id.\n // * `_pingTimer` + `_offlineTimer` \u2014 liveness loop.\n //\n // Browser-side critical sends are: `request`, `focus`, `ack`,\n // `pong`. Of those only `request` already has its own\n // RequestController/timeout contract; the rest are fire-and-forget\n // today. To keep the surface small AND match the wallet, we add\n // ack tracking on outbound `focus` only (high signal-to-noise for\n // remote-nav UX). `request` keeps its existing semantics; `ack`\n // and `pong` are never themselves ack-tracked (would loop).\n private _seenIds: Set<string> = new Set();\n private _seenIdsOrder: string[] = [];\n private _pendingAcks: Map<\n string,\n { encoded: string; attempts: number; timer: ReturnType<typeof setTimeout> | null }\n > = new Map();\n private _pingSendTimes: Map<string, number> = new Map();\n private _pingTimer: ReturnType<typeof setInterval> | null = null;\n private _offlineTimer: ReturnType<typeof setTimeout> | null = null;\n private _connectionStatus: ConnectionStatus = \"unknown\";\n private _lastRttMs: number | null = null;\n private _connectionListeners: Set<(s: ConnectionStatus, rttMs: number | null) => void> =\n new Set();\n /**\n * `pagehide` handler reference. Held so we can deregister at\n * teardown without anchoring `this` to the global listener\n * forever \u2014 important because the SDK can outlive multiple\n * sign-in / sign-out cycles in a single tab.\n */\n private _onPageHide: ((e: Event) => void) | null = null;\n\n constructor(opts: {\n cnf: { jwk: CnfJwk };\n credential: { expiresAt: number };\n transport: Transport;\n ephKeys: EphemeralKeys;\n verifierContext: VerifierContext;\n /**\n * The verified-claim map from the initial sign-in. Cached so\n * `claim-update` events can compute a real diff (and so\n * `claim_added` / `claim_updated` carry old + new values). Optional\n * for back-compat; if absent the first `claim-update` treats\n * every claim as `claim_added`, which is the safe direction.\n */\n initialClaims?: Record<string, unknown>;\n /**\n * The `SignInResult` to deliver as the payload of the\n * `signed_in` event fired via microtask. Optional \u2014 pass to\n * enable `signed_in` dispatch; omit to leave the event silent.\n */\n initialSignedInResult?: SignInResult;\n /**\n * The wallet's session X25519 public key from the initial\n * `presentation` envelope. Required to open the browser\u2192wallet\n * request channel (`session.request(...)`). Optional only for\n * back-compat with older wallets that don't yet publish it.\n */\n walletSessionPk?: string;\n /**\n * True when the sign-in presentation didn't bind [walletSessionPk]\n * (wallet older than envelope v2): inbound senders can't be checked,\n * so page-acting envelopes are ignored. Default false.\n */\n legacyChannel?: boolean;\n /**\n * The verified sign-in presentation and its holder-signed `iat`:\n * the baseline for renewal anti-replay (a renewal must carry a\n * strictly newer `iat` and must not repeat an accepted presentation).\n */\n initialPresentation?: { presentation: string; iat: number };\n /**\n * Initial `preferredLanguage` value from the wallet's first\n * envelope. The session's own `_handleMessage` only sees\n * envelopes that arrive AFTER signIn() has consumed the\n * presentation, so the language tag on the first envelope is\n * otherwise lost \u2014 leaving `session.preferredLanguage` null\n * until a later renewal envelope. Seeded here so the value\n * is available immediately when the host inspects it after\n * `signIn()` resolves.\n */\n initialPreferredLanguage?: string;\n /**\n * Initial `displayName` from the wallet's first envelope.\n * Cosmetic public-profile data; see [displayName] getter for\n * the trust model. Seeded here so the host sees the name\n * immediately after `signIn()` resolves rather than waiting for\n * the first `display-update`.\n */\n initialDisplayName?: string | null;\n /** Initial `avatar` from the wallet's first envelope (same\n * rationale as [initialDisplayName]). */\n initialAvatar?: { url: string; hash: string } | null;\n }) {\n this._cnf = opts.cnf;\n this._expiresAt = opts.credential.expiresAt;\n this._transport = opts.transport;\n this._ephKeys = opts.ephKeys;\n this._verifierContext = opts.verifierContext;\n this._claimsSnapshot = { ...(opts.initialClaims ?? {}) };\n this._walletSessionPk = opts.walletSessionPk ?? null;\n this._legacyChannel = opts.legacyChannel === true;\n if (opts.initialPresentation) {\n this._lastPresentationIat = opts.initialPresentation.iat;\n void presentationDigest(opts.initialPresentation.presentation).then((d) => this._seenPresentations.add(d));\n }\n this._preferredLanguage = opts.initialPreferredLanguage ?? null;\n this._displayName = opts.initialDisplayName ?? null;\n this._avatar = opts.initialAvatar ?? null;\n this._armExpiryTimer();\n this._installUnloadGuard();\n this._transport.onMessage((raw) => void this._handleMessage(raw));\n // Transport teardown fan-out \u2192 `signed_out`. The credential's\n // exp timer (`_armExpiryTimer`) covers credential-side TTL, but\n // the Worker's session DO has a separate, MUCH shorter TTL \u2014\n // when its alarm fires, both signaling WSes close with code\n // 4000 / reason `ttl_reached`, the data channel goes silent,\n // and without this hook the host would keep showing \"signed\n // in\" forever. The transport collapses every termination\n // (signaling close, peer-gone, DC close) onto one notification;\n // we map the reason string to the SDK's `ExpiryReason` union\n // and tear down.\n this._transport.onClose((reason) => {\n if (this._closed) return;\n const mapped = _mapTransportCloseReason(reason);\n this._teardown(mapped);\n });\n // Start the wallet\u2192browser liveness loop. The wallet runs the\n // same loop on its side; either peer's ping triggers a pong on\n // the other. Both sides independently track their own RTT view.\n this._pingTimer = setInterval(() => this._sendPing(), PING_INTERVAL_MS);\n _unrefTimer(this._pingTimer);\n\n // Fire `signed_in` via microtask so listeners attached\n // synchronously after `await signIn()` still receive it.\n // Without the microtask the event would race against the\n // caller's first `on()` registration.\n if (opts.initialSignedInResult) {\n const result = opts.initialSignedInResult;\n queueMicrotask(() => this._dispatch({ type: \"signed_in\", result }));\n }\n }\n\n // \u2500\u2500\u2500 Public getters \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n get expiresAt(): number {\n return this._expiresAt;\n }\n get cnf(): { jwk: CnfJwk } {\n return this._cnf;\n }\n /** Snapshot of the most recent verified claims (since last renew / update). */\n get claims(): Readonly<Record<string, unknown>> {\n return this._claimsSnapshot;\n }\n\n /**\n * Who is signed in: the person's Prson ID for this site (`cnf.jwk.x`,\n * the same value as `SignInResult.prsonId`). Show it \u2014 or a name your\n * backend maps it to \u2014 on the page, so the person can see it's them\n * and not someone who scanned the code first.\n */\n get prsonId(): string {\n return this._cnf.jwk.x;\n }\n\n /** The wallet's pinned X25519 session key (base64url), or null. */\n get walletSessionPk(): string | null {\n return this._walletSessionPk;\n }\n\n /** User's preferred UI language (BCP-47 tag) or null if the\n * wallet hasn't published one yet. */\n get preferredLanguage(): string | null {\n return this._preferredLanguage;\n }\n\n /** Public-profile display name from the wallet's identity record,\n * or null if the wallet hasn't published one yet (anonymous\n * identity, etc.). Cosmetic \u2014 do not gate privileged actions on\n * this value. */\n get displayName(): string | null {\n return this._displayName;\n }\n\n /** Public-profile avatar pointer, or null. Same cosmetic-only\n * trust model as [displayName]. */\n get avatar(): { url: string; hash: string } | null {\n return this._avatar;\n }\n\n /** Coarse health of the wallet \u2194 browser data channel as observed\n * via the periodic ping/pong loop. `unknown` until the first pong\n * lands; `offline` after 5 s of no pong; `unstable` when the most\n * recent RTT crossed 1 s; otherwise `stable`. */\n get connectionStatus(): ConnectionStatus {\n return this._connectionStatus;\n }\n\n /** Most recently observed RTT in milliseconds, or null until the\n * first pong lands. */\n get lastRttMs(): number | null {\n return this._lastRttMs;\n }\n\n /** Subscribe to connection-status changes. Fires on every transition\n * with the new status + the RTT that triggered it (null on the\n * `offline` transition). Returns an unsubscribe handle. */\n onConnectionStatus(\n cb: (status: ConnectionStatus, rttMs: number | null) => void,\n ): Unsubscribe {\n this._connectionListeners.add(cb);\n return () => this._connectionListeners.delete(cb);\n }\n\n // \u2500\u2500\u2500 Subscription API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Subscribe to a single event type. The callback is invoked with\n * the typed event variant (TS narrows on the `type` discriminant).\n * Returns an unsubscribe handle.\n *\n * const off = session.on(\"claim_updated\", (e) => {\n * if (e.name === \"verification_level\") refreshBadge(e.newValue);\n * });\n * // later:\n * off();\n */\n on<T extends LoginEventType>(\n type: T,\n cb: (event: Extract<LoginEvent, { type: T }>) => void,\n ): Unsubscribe {\n let set = this._listeners.get(type);\n if (!set) {\n set = new Set();\n this._listeners.set(type, set);\n }\n const wrapped = cb as unknown as (e: LoginEvent) => void;\n set.add(wrapped);\n return () => set!.delete(wrapped);\n }\n\n /** Subscribe to every event. Returns an unsubscribe handle. */\n onAny(cb: (event: LoginEvent) => void): Unsubscribe {\n this._anyListeners.add(cb);\n return () => this._anyListeners.delete(cb);\n }\n\n // \u2500\u2500\u2500 Back-compat shims \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n //\n // The original SDK exposed `onRenewed(cb)` and `onExpiry(cb)`.\n // We keep them as thin wrappers around the typed `on()` so\n // existing host pages compile without changes. New code should\n // prefer `on()` / `onAny()`.\n\n /** @deprecated Use `on(\"renewed\", e => cb(e.result))` instead. */\n onRenewed(cb: (fresh: SignInResult) => void): Unsubscribe {\n return this.on(\"renewed\", (e) => cb(e.result));\n }\n\n /** @deprecated Use `on(\"signed_out\", e => cb(e.reason))` instead. */\n onExpiry(cb: (reason: ExpiryReason) => void): Unsubscribe {\n return this.on(\"signed_out\", (e) => cb(e.reason));\n }\n\n close(): void {\n this._teardown(\"user_revoked\");\n }\n\n // \u2500\u2500\u2500 Request channel \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Send a [request] to the wallet and resolve with the wallet's\n * reply. The wallet shows a bottom drawer for the user to\n * approve / decline / pick a matching fragment or document; the\n * promise resolves when the user acts (or the [timeoutMs]\n * elapses, or the session closes).\n *\n * Common error codes:\n * * `no-active-session` \u2014 request issued before the wallet has\n * published its session pk (race against the initial\n * `presentation` envelope) or after the session closed.\n * * `declined` \u2014 user tapped Decline in the wallet drawer.\n * * `not-present` \u2014 no matching fragment / document on the\n * device AND the user declined to acquire one.\n * * `queue-full` \u2014 wallet is sitting at the 5-in-flight cap and\n * isn't accepting more requests. Try later.\n * * `rate-limited` \u2014 wallet's 1-request-per-second throttle\n * rejected this one.\n * * `timeout` \u2014 the [timeoutMs] elapsed before the wallet\n * replied. Defaults to 60 s.\n * * `session-closed` \u2014 the session shut down with this request\n * in flight.\n *\n * Wire grammar: outbound envelope shape is\n * `{ v, msg: \"request\", issuedAt, domain, requestId, kind, ...kindFields }`,\n * NaCl-boxed to the wallet's session pk. Reply is a matching\n * `{ msg: \"response\", requestId, result | error }`.\n */\n async request(req: LoginRequest, opts?: RequestOptions): Promise<LoginResponse> {\n return this._sendRequest(req, opts);\n }\n\n /**\n * Streaming variant of [request] for `kind: \"mouse\"`. Identical\n * to `request()` except [onFrame] is invoked for every\n * `mouse-update` envelope the wallet emits against the request's\n * UUID until the terminating `response` arrives. The returned\n * promise resolves with the final response (i.e. when the user\n * closes the wallet drawer). Used by [`bindMouse`].\n *\n * Separated from `request()` because the subscriber MUST be\n * attached against the requestId BEFORE the envelope is sent \u2014\n * otherwise the first `mouse-update` frame can race ahead of the\n * subscription. `request()` doesn't expose its requestId, so we\n * provide this dedicated entry point rather than leak the id.\n */\n async requestMouse(\n req: Extract<LoginRequest, { kind: \"mouse\" }>,\n onFrame: (mouse: NonNullable<DecryptedEnvelope[\"mouse\"]>) => void,\n opts?: RequestOptions,\n ): Promise<LoginResponse> {\n return this._sendRequest(req, opts, onFrame);\n }\n\n /**\n * Push the currently-focused input's metadata + value to the\n * wallet so the user can edit it on the phone. Pass `null` to\n * clear the wallet's focus mirror (blur, page change, etc.).\n *\n * Used by [`enableRemoteNavigation`]; not part of the documented\n * public API but exposed so the helper lives in a separate module\n * without reaching into private fields. NaCl-boxed to the wallet's\n * session pk on the way out.\n *\n * @internal\n */\n async _sendFocus(\n focus:\n | {\n name: string;\n label?: string;\n inputType?: string;\n value?: string;\n placeholder?: string;\n minLength?: number;\n maxLength?: number;\n min?: number;\n max?: number;\n pattern?: string;\n required?: boolean;\n options?: { value: string; label?: string }[];\n /** Navigation-row visibility hints. Computed by\n * `enableRemoteNavigation`'s `computeNavMeta` from the\n * current tabbable pool and the focused element's\n * surrounding form. The wallet renders only the buttons\n * that match. See `bind.ts:computeNavMeta` + the wallet's\n * `_navigationRow`. */\n hasPrev?: boolean;\n hasNext?: boolean;\n isLastInForm?: boolean;\n isButton?: boolean;\n /** File-input attributes. Present only when the focused\n * element is `<input type=\"file\">`; drives the wallet's\n * picker UI (camera vs gallery vs files filtered by\n * MIME). `accept` is the raw `accept` attribute string\n * (e.g. `\"image/*,application/pdf\"`); the wallet\n * normalises it. `multiple` enables multi-select on the\n * picker. `capture` (`\"user\"` / `\"environment\"`) hints\n * which camera the host expects when the user opens the\n * camera mode. */\n accept?: string;\n multiple?: boolean;\n capture?: string;\n }\n | null,\n ): Promise<void> {\n if (this._closed) return;\n if (!this._walletSessionPk) return;\n // Focus updates drive the wallet drawer's mirrored input \u2014 the\n // user can't edit a value the wallet never received, so we\n // ack-track these. The promise is awaited only by tests; the\n // common path (remote-nav helper firing on DOM focus events) is\n // fire-and-forget.\n await this._sendWithAck({\n msg: \"focus\",\n focus,\n });\n }\n\n /**\n * Install a `pagehide` listener that fires a synchronous\n * `browser-revoke` envelope at the wallet right before the tab\n * closes / refreshes / navigates away. Without this the wallet\n * has to wait for the slower transport-collapse pathway\n * (`peer-gone` over the signaling WS + ICE failure on the data\n * channel) to learn the browser is gone \u2014 long enough for the\n * connection-status dot to oscillate and any in-flight ack\n * promises to time out.\n *\n * `pagehide` is preferred over `beforeunload` because:\n * * it fires for bfcache evictions (back/forward navigation\n * on iOS Safari), tab closes, AND refreshes\n * * `beforeunload` is increasingly restricted by browsers\n * for non-blocking-prompt use\n *\n * The envelope itself rides through the same NaCl box as every\n * other browser\u2192wallet message. We can't await the ack \u2014 the\n * page is being torn down \u2014 so this is a true fire-and-forget;\n * the wallet's [LoginSession.inbound] handler treats receipt\n * as the trigger to close.\n */\n private _installUnloadGuard(): void {\n if (typeof window === \"undefined\") return;\n this._onPageHide = (_e: Event) => {\n if (this._closed || !this._walletSessionPk) return;\n const body = JSON.stringify({\n v: \"prson_vp_v1\",\n msg: \"browser-revoke\",\n issuedAt: Math.floor(Date.now() / 1000),\n domain: this._verifierContext.expectedAudience.replace(/^https?:\\/\\//, \"\"),\n reason: \"page_unload\",\n });\n try {\n this._transport.send(boxToWallet(this._walletSessionPk, body, this._ephKeys));\n } catch {\n /* swallow \u2014 the channel is on its way out anyway */\n }\n };\n window.addEventListener(\"pagehide\", this._onPageHide);\n }\n\n /**\n * Browser\u2192wallet pause-state notification. The wallet's mouse\n * controller dims its surface + shows \"Remote control paused\"\n * while the page is in the background. Fire-and-forget over\n * NaCl-box to the wallet's session pk; loss is acceptable\n * (we re-fire on every focus / blur).\n *\n * @internal\n */\n async _sendControlStatus(paused: boolean): Promise<void> {\n if (this._closed) return;\n if (!this._walletSessionPk) return;\n const payload = JSON.stringify({\n v: \"prson_vp_v1\",\n msg: \"control-status\",\n issuedAt: Math.floor(Date.now() / 1000),\n domain: this._verifierContext.expectedAudience.replace(/^https?:\\/\\//, \"\"),\n paused,\n });\n try {\n this._transport.send(boxToWallet(this._walletSessionPk, payload, this._ephKeys));\n } catch {\n /* swallow \u2014 channel down */\n }\n }\n\n /**\n * Install the ambient `mouse-update` handler. Mirrors\n * [`_setRemoteNavListener`] \u2014 only one ambient subscriber at a\n * time (last call wins). Used by [`bindMouse`] when the\n * session was pre-granted mouse control at sign-in\n * ([SignInOptions.mouseControl]).\n *\n * @internal\n */\n _setAmbientMouseHandler(\n cb: ((mouse: NonNullable<DecryptedEnvelope[\"mouse\"]>) => void) | null,\n ): Unsubscribe {\n this._ambientMouseHandler = cb;\n return () => {\n if (this._ambientMouseHandler === cb) this._ambientMouseHandler = null;\n };\n }\n\n /**\n * Install the file-envelope handler. Mirrors\n * [`_setAmbientMouseHandler`] \u2014 only one handler at a time;\n * [`enableRemoteNavigation`] owns it during its lifetime and\n * tears it down on disposal so the next mount can install a\n * fresh one. The handler receives `file-begin` / `file-chunk` /\n * `file-end` envelopes in arrival order; assembly + DOM\n * dispatch lives in [`bind.ts`].\n *\n * @internal\n */\n _setFileEnvelopeHandler(\n cb: ((envelope: DecryptedEnvelope) => void) | null,\n ): Unsubscribe {\n this._fileEnvelopeHandler = cb;\n return () => {\n if (this._fileEnvelopeHandler === cb) this._fileEnvelopeHandler = null;\n };\n }\n\n /**\n * Install the remote-navigation listener. Replaces any prior\n * listener \u2014 only one is active at a time. Returns an unsubscribe\n * handle. Used by [`enableRemoteNavigation`].\n *\n * @internal\n */\n _setRemoteNavListener(\n cb:\n | ((\n envelope:\n | { msg: \"nav\"; action: \"prev\" | \"next\" | \"submit\" }\n | { msg: \"value\"; value: string }\n | { msg: \"logout\" },\n ) => void)\n | null,\n ): Unsubscribe {\n this._remoteNavListener = cb;\n return () => {\n if (this._remoteNavListener === cb) this._remoteNavListener = null;\n };\n }\n\n private async _sendRequest(\n req: LoginRequest,\n opts?: RequestOptions,\n onMouseFrame?: (mouse: NonNullable<DecryptedEnvelope[\"mouse\"]>) => void,\n ): Promise<LoginResponse> {\n if (this._closed) return { ok: false, error: \"session-closed\" };\n const recipientPk = this._walletSessionPk;\n if (!recipientPk) return { ok: false, error: \"no-active-session\" };\n\n const timeoutMs = opts?.timeoutMs ?? 60_000;\n const { requestId, promise } = this._requestController.enqueue(timeoutMs);\n\n // Attach the streaming subscriber BEFORE sending so the first\n // mouse-update frame can never race ahead of the subscription.\n if (onMouseFrame) this._mouseSubscribers.set(requestId, onMouseFrame);\n\n const envelope: Record<string, unknown> = {\n v: \"prson_vp_v1\",\n msg: \"request\",\n issuedAt: Math.floor(Date.now() / 1000),\n domain: this._verifierContext.expectedAudience.replace(/^https?:\\/\\//, \"\"),\n requestId,\n kind: req.kind,\n };\n // Per-kind body \u2014 flat keys for simplicity, matches the wallet's\n // existing wire-decoder pattern.\n switch (req.kind) {\n case \"claim-value\":\n envelope.name = req.name;\n if (req.reason) envelope.reason = req.reason;\n break;\n case \"fragment-check\":\n envelope.fragmentName = req.fragmentName;\n // `format` selects the wire shape the wallet asks the notary\n // for (native / vc+jwt / vc+sd-jwt). Omitted means native, so\n // we only put it on the envelope when the host opted in \u2014 the\n // wallet treats an absent field as legacy behaviour.\n if (req.format) envelope.format = req.format;\n if (req.reason) envelope.reason = req.reason;\n break;\n case \"document-presence\":\n if (req.type) envelope.type = req.type;\n if (req.country) envelope.country = req.country;\n if (req.reason) envelope.reason = req.reason;\n break;\n case \"document-sign\":\n // Bytes get base64'd in the envelope; large docs should use\n // `uploadUrl` to keep the WebRTC message size down.\n if (\"bytes\" in req.document) {\n envelope.document = {\n bytes: u8ToB64(req.document.bytes),\n };\n } else {\n envelope.document = req.document;\n }\n if (req.visibleCue) envelope.visibleCue = req.visibleCue;\n if (req.reason) envelope.reason = req.reason;\n break;\n case \"input\":\n envelope.inputType = req.inputType;\n envelope.label = req.label;\n if (req.placeholder !== undefined) envelope.placeholder = req.placeholder;\n // A password's current value never goes to the phone.\n if (req.defaultValue !== undefined && req.inputType !== \"password\") envelope.defaultValue = req.defaultValue;\n if (req.minLength !== undefined) envelope.minLength = req.minLength;\n if (req.maxLength !== undefined) envelope.maxLength = req.maxLength;\n if (req.min !== undefined) envelope.min = req.min;\n if (req.max !== undefined) envelope.max = req.max;\n if (req.pattern !== undefined) envelope.pattern = req.pattern;\n if (req.required !== undefined) envelope.required = req.required;\n if (req.options !== undefined) envelope.options = req.options;\n if (req.reason) envelope.reason = req.reason;\n break;\n case \"input-form\":\n envelope.fields = req.fields.map((f) =>\n f.inputType === \"password\" && f.defaultValue !== undefined ? { ...f, defaultValue: undefined } : f,\n );\n if (req.submitLabel !== undefined) envelope.submitLabel = req.submitLabel;\n if (req.reason) envelope.reason = req.reason;\n break;\n case \"mouse\":\n envelope.mode = req.mode;\n if (req.reason) envelope.reason = req.reason;\n break;\n }\n\n try {\n const boxed = boxToWallet(recipientPk, JSON.stringify(envelope), this._ephKeys);\n this._transport.send(boxed);\n } catch {\n // Network down, channel closed, encoding bug \u2014 surface as\n // session-closed; the timeout would also fire eventually.\n if (onMouseFrame) this._mouseSubscribers.delete(requestId);\n return { ok: false, error: \"session-closed\" };\n }\n return promise;\n }\n\n // \u2500\u2500\u2500 internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Fire a single event to per-type listeners + onAny subscribers.\n * Listener errors are swallowed so one buggy host listener can't\n * break the rest of the dispatch (or close the session).\n */\n private _dispatch(event: LoginEvent): void {\n const set = this._listeners.get(event.type);\n if (set) {\n for (const cb of set) {\n try {\n cb(event);\n } catch {\n /* swallow \u2014 host bug shouldn't bring down the session */\n }\n }\n }\n for (const cb of this._anyListeners) {\n try {\n cb(event);\n } catch {\n /* swallow */\n }\n }\n }\n\n private _armExpiryTimer() {\n if (this._expiryTimer) clearTimeout(this._expiryTimer);\n const delta = this._expiresAt - Date.now();\n // 60-second skew/sanity budget on BOTH sides:\n //\n // * If `expiresAt === 0`: the credential's JWS had no numeric\n // `exp`. Skip the timer.\n // * If `delta` is in `[-60_000, +60_000]`: the credential\n // \"expires\" within a one-minute window of \"now\". Almost\n // always one of: clock skew between server and browser,\n // network latency between issuance and verify, or a\n // server-side TTL bug that issued an essentially-zero-TTL\n // credential. Tearing down on this signal causes a visible\n // \"signed_in immediately followed by signed_out\" UX bug;\n // skip the timer and let the wallet (or host) close.\n // * Otherwise: legitimate future expiry \u2014 arm the timer.\n // * Otherwise (genuinely past, >60s ago): real expiry,\n // teardown immediately.\n const skewBudgetMs = 60_000;\n if (this._expiresAt <= 0 || Math.abs(delta) < skewBudgetMs) {\n // eslint-disable-next-line no-console\n console.warn(\n `[@prson/login-sdk] credential expiresAt ${\n this._expiresAt <= 0\n ? \"missing/zero\"\n : delta < 0\n ? `${(-delta / 1000).toFixed(1)}s in the past`\n : `only ${(delta / 1000).toFixed(1)}s in the future`\n } \u2014 leaving session open without a TTL timer.` +\n \" Host should set its own deadline.\",\n );\n return;\n }\n if (delta <= 0) {\n this._teardown(\"ttl_reached\");\n return;\n }\n // `setTimeout` clamps delays > 2^31-1 ms (~24.8 days) to a 32-bit\n // int and effectively fires immediately. A verified-human VC has\n // a 90-day TTL \u2014 delta is ~7.8 billion ms \u2014 so a naive\n // `setTimeout(..., delta)` would trip the teardown on the very\n // next tick. Re-arm in chunks \u2264 MAX_TIMEOUT and re-evaluate.\n const MAX_TIMEOUT = 2_147_483_000; // a hair under int32 max\n const chunk = delta > MAX_TIMEOUT ? MAX_TIMEOUT : delta;\n this._expiryTimer = setTimeout(() => {\n if (this._closed) return;\n // Re-check against the current clock \u2014 if we still haven't\n // reached `_expiresAt`, re-arm. Otherwise teardown.\n if (Date.now() >= this._expiresAt) {\n this._teardown(\"ttl_reached\");\n } else {\n this._armExpiryTimer();\n }\n }, chunk);\n _unrefTimer(this._expiryTimer);\n }\n\n private async _handleMessage(raw: string) {\n if (this._closed) return;\n let envelope: DecryptedEnvelope;\n try {\n // Only the pinned wallet key may talk to us. A legacy session (no\n // key bound in the presentation) can't check the sender, so it\n // accepts any box and ignores page-acting messages instead.\n envelope = await decryptEnvelope(\n raw,\n this._ephKeys,\n this._legacyChannel ? undefined : (this._walletSessionPk ?? undefined),\n );\n } catch {\n // Garbage on the wire, or a box from a key other than the pinned\n // wallet key (an injected envelope) \u2014 ignore it.\n return;\n }\n\n // \u2500\u2500 Transport-layer protocol: dedupe + auto-ack + ping/pong \u2500\u2500\n if (typeof envelope.id === \"string\") {\n if (this._seenIds.has(envelope.id)) {\n // Duplicate \u2014 our prior ack likely got lost. Re-ack so the\n // wallet stops retransmitting, then drop locally.\n void this._sendAckFor(envelope);\n return;\n }\n this._markSeen(envelope.id);\n void this._sendAckFor(envelope);\n }\n\n if (envelope.msg === \"ack\") {\n this._handleAck(envelope.ackOf);\n return;\n }\n if (envelope.msg === \"ping\") {\n void this._sendPong(envelope);\n return;\n }\n if (envelope.msg === \"pong\") {\n this._handlePong(envelope);\n return;\n }\n\n await this._dispatchDecryptedForTest(envelope);\n }\n\n // \u2500\u2500\u2500 Transport-layer protocol helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private _markSeen(id: string): void {\n this._seenIds.add(id);\n this._seenIdsOrder.push(id);\n if (this._seenIdsOrder.length > SEEN_IDS_CAPACITY) {\n const evict = this._seenIdsOrder.shift();\n if (evict) this._seenIds.delete(evict);\n }\n }\n\n /** Auto-ack any inbound envelope that carries an `id`, except\n * protocol primitives. `ping` is implicitly acked by `pong`;\n * `pong` and `ack` would loop. */\n private async _sendAckFor(envelope: DecryptedEnvelope): Promise<void> {\n if (typeof envelope.id !== \"string\") return;\n if (envelope.msg === \"ack\" || envelope.msg === \"ping\" || envelope.msg === \"pong\") {\n return;\n }\n if (!this._walletSessionPk) return;\n const body = JSON.stringify({\n v: \"prson_vp_v1\",\n msg: \"ack\",\n ackOf: envelope.id,\n issuedAt: Math.floor(Date.now() / 1000),\n domain: this._verifierContext.expectedAudience.replace(/^https?:\\/\\//, \"\"),\n });\n try {\n this._transport.send(boxToWallet(this._walletSessionPk, body, this._ephKeys));\n } catch {\n /* channel down \u2014 wallet will time out its retry budget */\n }\n }\n\n private _handleAck(ackOf: string | undefined): void {\n if (!ackOf) return;\n const pending = this._pendingAcks.get(ackOf);\n if (!pending) return;\n if (pending.timer) clearTimeout(pending.timer);\n this._pendingAcks.delete(ackOf);\n }\n\n private async _sendPing(): Promise<void> {\n if (this._closed) return;\n if (!this._walletSessionPk) return;\n const id = uuidv4();\n const ts = Date.now();\n this._pingSendTimes.set(id, ts);\n const body = JSON.stringify({\n v: \"prson_vp_v1\",\n msg: \"ping\",\n id,\n ts,\n domain: this._verifierContext.expectedAudience.replace(/^https?:\\/\\//, \"\"),\n });\n try {\n this._transport.send(boxToWallet(this._walletSessionPk, body, this._ephKeys));\n } catch {\n /* swallow */\n }\n this._armOfflineTimer();\n }\n\n private async _sendPong(ping: DecryptedEnvelope): Promise<void> {\n if (!this._walletSessionPk) return;\n if (typeof ping.id !== \"string\") return;\n const body = JSON.stringify({\n v: \"prson_vp_v1\",\n msg: \"pong\",\n ackOf: ping.id,\n ts: ping.ts,\n recvTs: Date.now(),\n domain: this._verifierContext.expectedAudience.replace(/^https?:\\/\\//, \"\"),\n });\n try {\n this._transport.send(boxToWallet(this._walletSessionPk, body, this._ephKeys));\n } catch {\n /* swallow */\n }\n }\n\n private _handlePong(envelope: DecryptedEnvelope): void {\n if (typeof envelope.ackOf !== \"string\") return;\n const sent = this._pingSendTimes.get(envelope.ackOf);\n if (sent === undefined) return;\n this._pingSendTimes.delete(envelope.ackOf);\n const rtt = Date.now() - sent;\n this._lastRttMs = rtt;\n if (this._offlineTimer) {\n clearTimeout(this._offlineTimer);\n this._offlineTimer = null;\n }\n this._setConnectionStatus(\n rtt > CONNECTION_UNSTABLE_THRESHOLD_MS ? \"unstable\" : \"stable\",\n rtt,\n );\n }\n\n private _armOfflineTimer(): void {\n if (this._offlineTimer) clearTimeout(this._offlineTimer);\n this._offlineTimer = setTimeout(() => {\n if (this._closed) return;\n this._setConnectionStatus(\"offline\", null);\n }, CONNECTION_OFFLINE_AFTER_MS);\n _unrefTimer(this._offlineTimer);\n }\n\n private _setConnectionStatus(s: ConnectionStatus, rttMs: number | null): void {\n if (this._connectionStatus === s && this._lastRttMs === rttMs) return;\n this._connectionStatus = s;\n if (rttMs !== null) this._lastRttMs = rttMs;\n for (const cb of this._connectionListeners) {\n try {\n cb(s, rttMs);\n } catch {\n /* swallow \u2014 host bug shouldn't kill the loop */\n }\n }\n }\n\n /** Send a JSON envelope with ack tracking + retry. Stamps a fresh\n * `id` onto [body] and retransmits every [ACK_RETRY_DELAY_MS]\n * until the matching ack lands or [ACK_MAX_ATTEMPTS] is reached.\n * Resolves with `true` on ack, `false` on exhaustion. */\n private async _sendWithAck(body: Record<string, unknown>): Promise<boolean> {\n if (this._closed) return false;\n if (!this._walletSessionPk) return false;\n const id = uuidv4();\n body.id = id;\n body.v = body.v ?? \"prson_vp_v1\";\n body.issuedAt = body.issuedAt ?? Math.floor(Date.now() / 1000);\n body.domain =\n body.domain ?? this._verifierContext.expectedAudience.replace(/^https?:\\/\\//, \"\");\n const encoded = JSON.stringify(body);\n const pending = { encoded, attempts: 0, timer: null as ReturnType<typeof setTimeout> | null };\n this._pendingAcks.set(id, pending);\n return new Promise<boolean>((resolve) => {\n const attempt = () => {\n if (this._closed) {\n this._pendingAcks.delete(id);\n resolve(false);\n return;\n }\n pending.attempts += 1;\n try {\n this._transport.send(boxToWallet(this._walletSessionPk!, encoded, this._ephKeys));\n } catch {\n /* channel down \u2014 keep retrying; offline timer will fire */\n }\n pending.timer = setTimeout(() => {\n if (!this._pendingAcks.has(id)) {\n // Ack already arrived between attempts; the success path\n // cleared the map entry.\n resolve(true);\n return;\n }\n if (pending.attempts >= ACK_MAX_ATTEMPTS) {\n this._pendingAcks.delete(id);\n resolve(false);\n return;\n }\n attempt();\n }, ACK_RETRY_DELAY_MS);\n _unrefTimer(pending.timer);\n };\n attempt();\n });\n }\n\n /**\n * Pure dispatch entry-point \u2014 takes an already-decrypted envelope\n * and routes it through the same per-message handlers\n * `_handleMessage` does after decryption. Public-but-prefixed so\n * unit tests can exercise the dispatch contract without\n * constructing real NaCl-boxed ciphertext.\n *\n * NOT part of the documented public API; treat as @internal.\n */\n async _dispatchDecryptedForTest(envelope: DecryptedEnvelope): Promise<void> {\n if (this._closed) return;\n // `walletSessionPk` on an envelope is NOT trusted: the key is pinned\n // from the signed presentation and only a verified renewal can\n // rotate it (see _handleRenewal).\n // Same treatment for the user's preferred language \u2014 the wallet\n // re-stamps this on every envelope so a mid-session locale\n // change propagates without an explicit event.\n if (typeof envelope.preferredLanguage === \"string\") {\n this._preferredLanguage = envelope.preferredLanguage;\n }\n\n switch (envelope.msg) {\n case \"revoke\":\n this._teardown(\"wallet_signed_out\");\n return;\n case \"presentation\":\n case \"renewal\":\n await this._handleRenewal(envelope);\n return;\n case \"claim-update\":\n await this._handleClaimUpdate(envelope);\n return;\n case \"display-update\":\n this._handleDisplayUpdate(envelope);\n return;\n case \"credential-revoked\":\n this._handleCredentialRevoked(envelope);\n return;\n case \"response\":\n // Wallet replied to an outbound `request`. Match by UUID\n // and resolve the matching promise. Late replies (after\n // timeout) silently no-op \u2014 the controller already\n // delivered the timeout error.\n this._requestController.resolve(envelope);\n // If the request was a streaming `mouse` request, the final\n // `response` also closes the stream \u2014 drop the subscriber so\n // the controller can be reused.\n if (envelope.requestId) this._mouseSubscribers.delete(envelope.requestId);\n return;\n case \"mouse-update\":\n // An unauthenticated sender must not drive the page.\n if (this._legacyChannel) return;\n // Wallet is streaming pointer events. Two routing paths:\n //\n // 1. **Per-request** \u2014 there's a pending `requestMouse`\n // subscriber keyed by this `requestId`. Used when the\n // host explicitly opened a `kind: \"mouse\"` request.\n //\n // 2. **Ambient** \u2014 no such subscriber exists. Used by the\n // pre-grant flow (`SignInOptions.mouseControl: true`)\n // where the wallet's banner drawer starts a stream\n // with a wallet-minted id the host never saw. Falls\n // through to `_ambientMouseHandler`, which [`bindMouse`]\n // installs so its on-page cursor still moves.\n if (envelope.mouse) {\n const perRequest = envelope.requestId\n ? this._mouseSubscribers.get(envelope.requestId)\n : undefined;\n const target = perRequest ?? this._ambientMouseHandler;\n if (target) {\n try {\n target(envelope.mouse);\n } catch {\n /* swallow \u2014 host bug shouldn't kill the stream */\n }\n }\n }\n return;\n case \"nav\":\n case \"logout\":\n if (envelope.msg === \"nav\" && this._legacyChannel) return;\n // Remote-navigation commands from the wallet's persistent\n // banner. Without an installed listener (i.e. the host\n // didn't call `enableRemoteNavigation`), `nav` is silently\n // dropped and `logout` falls through to the default teardown\n // below \u2014 the user tapping logout MUST sign the session out\n // even if the host never wired the optional helper.\n if (this._remoteNavListener) {\n try {\n if (envelope.msg === \"nav\" && envelope.action) {\n this._remoteNavListener({ msg: \"nav\", action: envelope.action });\n return;\n }\n if (envelope.msg === \"logout\") {\n this._remoteNavListener({ msg: \"logout\" });\n // Logout also tears the session down \u2014 the helper may\n // have already done it, but tearing again is a no-op.\n this._teardown(\"user_revoked\");\n return;\n }\n } catch {\n /* swallow */\n }\n }\n if (envelope.msg === \"logout\") this._teardown(\"user_revoked\");\n return;\n case \"value\":\n if (this._legacyChannel) return;\n // Wallet edited the value of the focused field. The remote-\n // nav helper is the only consumer; without it the edit is\n // silently dropped (the host page never asked for remote\n // input control). `value: null` is \"no change\" \u2014 we ignore.\n if (\n this._remoteNavListener &&\n typeof envelope.value === \"string\"\n ) {\n try {\n this._remoteNavListener({ msg: \"value\", value: envelope.value });\n } catch {\n /* swallow */\n }\n }\n return;\n case \"file-begin\":\n case \"file-chunk\":\n case \"file-end\":\n if (this._legacyChannel) return;\n // File-transfer envelopes flow through the remote-nav\n // helper's file receiver \u2014 bytes are reassembled into a\n // `File` object that the focused `<input type=\"file\">`\n // accepts. Without the helper mounted these envelopes are\n // silently dropped (the host page never asked for remote\n // file input).\n if (this._fileEnvelopeHandler) {\n try {\n this._fileEnvelopeHandler(envelope);\n } catch {\n /* swallow \u2014 one buggy receiver shouldn't kill the\n * channel for everyone */\n }\n }\n return;\n default:\n // Forward-compatible: unknown msg types are ignored, not\n // errors. A future wallet build can ship new events that\n // older SDK builds simply don't surface.\n return;\n }\n }\n\n private async _handleRenewal(envelope: DecryptedEnvelope) {\n if (!envelope.presentation) return;\n const verified = await this._verifyFresh(envelope.presentation);\n if (!verified) return;\n // Key rotation: only a verified renewal presentation can move the\n // pinned wallet key, and only to the key it signs (`prson_wsk`).\n // The next envelope must then come from the new key.\n const rotated = verified.binding.walletSessionPk;\n if (envelope.msg === \"renewal\" && rotated && !this._legacyChannel) {\n this._walletSessionPk = rotated;\n }\n this._expiresAt = verified.credential.expiresAt;\n this._claimsSnapshot = { ...verified.claims };\n this._armExpiryTimer();\n const fresh: SignInResult = {\n sdJwtVc: envelope.presentation,\n // The wallet picks a renewal's nonce, so a backend can't have issued it.\n nonce: verified.binding.nonce,\n prsonId: verified.cnf.jwk.x,\n claims: verified.claims,\n cnf: verified.cnf,\n credential: verified.credential,\n session: this,\n };\n this._dispatch({ type: \"renewed\", result: fresh });\n }\n\n /**\n * Verify a renewal / claim-update presentation and enforce in-session\n * anti-replay: same holder key, a holder-signed `iat` strictly newer\n * than the last accepted presentation, and never a presentation this\n * session already accepted. Returns null (drop it) otherwise.\n */\n private async _verifyFresh(presentation: string) {\n const verifierOpts: VerifyOptions = {\n ...this._verifierContext,\n // The wallet signs the sign-in nonce again, or one of its own; the\n // freshness checks below are what stop a replay either way.\n expectedNonce: extractKbNonce(presentation) ?? this._verifierContext.expectedNonceFactory(),\n };\n const digest = await presentationDigest(presentation);\n if (this._seenPresentations.has(digest)) return null;\n const verified = await verifyPresentation(presentation, verifierOpts);\n if (!verified.ok) return null;\n if (verified.cnf.jwk.x !== this._cnf.jwk.x) return null; // wallet swapped under us; ignore\n if (verified.binding.iat <= this._lastPresentationIat) return null;\n if (this._closed || this._seenPresentations.has(digest)) return null;\n this._seenPresentations.add(digest);\n this._lastPresentationIat = verified.binding.iat;\n return verified;\n }\n\n /**\n * Verify the embedded presentation, then diff its claims against\n * the cached snapshot and emit name-only per-claim events. The\n * actual claim values land in `this._claimsSnapshot` (accessible\n * via `session.claims`) but **never** in the event payloads \u2014\n * see the privacy note on the [LoginEvent] type.\n *\n * Re-verifies against the same audience + accepted-VCT set as the\n * initial sign-in. A `claim-update` whose presentation fails\n * verification is dropped silently \u2014 fail-closed. Same for a\n * cnf-mismatch (the wallet swapped per-domain key under us).\n *\n * The wire-level `envelope.delta` is intentionally ignored \u2014 we\n * recompute the diff from the verified SD-JWT so a malicious\n * wallet can't lie about which claim changed. The wallet should\n * not include values in `envelope.delta` at all (the wire\n * grammar in `crypto.ts` documents this as name-only); we'd\n * ignore them even if it did.\n */\n private async _handleClaimUpdate(envelope: DecryptedEnvelope) {\n if (!envelope.presentation) return;\n const verified = await this._verifyFresh(envelope.presentation);\n if (!verified) return;\n\n const oldClaims = this._claimsSnapshot;\n const newClaims = verified.claims;\n this._claimsSnapshot = { ...newClaims };\n\n // Added + updated \u2014 emit name + canonical hash of the new\n // value (NOT the raw value). The host reads the actual value\n // via `session.claims[name]` when needed; the hash lets\n // callers do an `==`-style check against a precomputed digest\n // (\"did verification_level become 5?\") without ever letting\n // the raw value cross the event surface.\n for (const [name, newValue] of Object.entries(newClaims)) {\n if (!(name in oldClaims)) {\n this._dispatch({\n type: \"claim_added\",\n name,\n newHash: await canonicalSha256Hex(newValue),\n });\n } else if (!_deepEqual(oldClaims[name], newValue)) {\n this._dispatch({\n type: \"claim_updated\",\n name,\n newHash: await canonicalSha256Hex(newValue),\n });\n }\n }\n // Removed\n for (const name of Object.keys(oldClaims)) {\n if (!(name in newClaims)) {\n this._dispatch({ type: \"claim_removed\", name });\n }\n }\n }\n\n /**\n * Display-only update. Fires `display_name_changed` and/or\n * `avatar_changed` based on which fields the envelope carries.\n * NOT cryptographically verified \u2014 partner sites should treat\n * the payload as advisory (refresh the cosmetic UI) and not\n * grant any privileged access on the basis of these values.\n */\n private _handleDisplayUpdate(envelope: DecryptedEnvelope) {\n if (envelope.displayName !== undefined) {\n // Mirror onto the session getter so a host that reads\n // `session.displayName` lazily after the update event sees\n // the new value.\n this._displayName = envelope.displayName;\n this._dispatch({\n type: \"display_name_changed\",\n displayName: envelope.displayName,\n });\n }\n if (envelope.avatar !== undefined) {\n this._avatar = envelope.avatar;\n this._dispatch({ type: \"avatar_changed\", avatar: envelope.avatar });\n }\n }\n\n /**\n * Credential-revoked. Fires `credential_revoked` with the\n * wallet-supplied reason, then tears the session down with\n * `signed_out / reason=\"credential_revoked\"`. Both events land\n * before the transport closes.\n */\n private _handleCredentialRevoked(envelope: DecryptedEnvelope) {\n const reason: CredentialRevokedReason = envelope.reason ?? \"user_revoked\";\n this._dispatch({ type: \"credential_revoked\", reason });\n this._teardown(\"credential_revoked\");\n }\n\n private _teardown(reason: ExpiryReason) {\n if (this._closed) return;\n this._closed = true;\n if (this._expiryTimer) clearTimeout(this._expiryTimer);\n if (this._pingTimer) clearInterval(this._pingTimer);\n if (this._offlineTimer) clearTimeout(this._offlineTimer);\n if (this._onPageHide && typeof window !== \"undefined\") {\n window.removeEventListener(\"pagehide\", this._onPageHide);\n this._onPageHide = null;\n }\n for (const p of this._pendingAcks.values()) {\n if (p.timer) clearTimeout(p.timer);\n }\n this._pendingAcks.clear();\n this._pingSendTimes.clear();\n try {\n this._transport.close();\n } catch {\n /* */\n }\n // Reject every in-flight request so callers awaiting\n // `session.request(...)` don't hang past the teardown.\n this._requestController.closeAll(\"session-closed\");\n // Drop any open mouse-update subscribers \u2014 the wallet won't be\n // sending more frames, and `bindMouse` will clean up its\n // DOM-side state via the `signed_out` event.\n this._mouseSubscribers.clear();\n this._dispatch({ type: \"signed_out\", reason });\n // Clear listener sets after dispatch so a host that calls\n // `session.on(...)` after teardown doesn't accumulate forever.\n this._listeners.clear();\n this._anyListeners.clear();\n this._connectionListeners.clear();\n }\n}\n\ntype VerifierContext = Omit<VerifyOptions, \"expectedNonce\"> & {\n expectedNonceFactory: () => string;\n};\n\n/**\n * Best-effort nonce extraction from a KB-JWT. Used at renewal /\n * update time so we accept the wallet's fresh nonce without forcing\n * a coordination round-trip. The verifier still checks aud +\n * sd_hash + Ed25519 signature \u2014 nonce skew only relaxes anti-replay\n * across the session.\n */\nfunction extractKbNonce(presentation: string): string | undefined {\n // SD-JWT: the KB-JWT is the last `~` part. Anonymous credential: one\n // plain JWS, whose payload carries the nonce itself.\n const parts = presentation.split(\"~\");\n const last = parts[parts.length - 1];\n if (!last || !last.includes(\".\")) return undefined;\n const [, kbP] = last.split(\".\");\n if (!kbP) return undefined;\n try {\n const pad = (4 - (kbP.length % 4)) % 4;\n const std = (kbP + \"=\".repeat(pad)).replace(/-/g, \"+\").replace(/_/g, \"/\");\n const decoded = JSON.parse(atob(std)) as { nonce?: string };\n return decoded.nonce;\n } catch {\n return undefined;\n }\n}\n\n/** SHA-256 (hex) of a presentation string \u2014 the replay-set key. */\nasync function presentationDigest(presentation: string): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(presentation));\n const view = new Uint8Array(digest);\n let out = \"\";\n for (let i = 0; i < view.length; i++) out += view[i]!.toString(16).padStart(2, \"0\");\n return out;\n}\n\n/**\n * `Uint8Array` \u2192 standard base64 (with `=` padding) for inclusion\n * inside a JSON envelope. Used by the request channel's\n * `document-sign` payload when the document arrives as raw bytes.\n */\nfunction u8ToB64(bytes: Uint8Array): string {\n let s = \"\";\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]!);\n return btoa(s);\n}\n\n/**\n * Canonical-JSON encoder: stable key ordering at every nesting\n * depth, no whitespace, arrays preserve insertion order. Used as\n * the input to the SHA-256 that becomes `claim_added.newHash` /\n * `claim_updated.newHash`. Matches the wallet's\n * `canonicalStringify` byte-for-byte, so both sides hash to the\n * same digest \u2014 the host can precompute a known-value digest and\n * compare.\n */\nfunction canonicalJson(value: unknown): string {\n if (value === undefined) return \"null\";\n if (value === null) return \"null\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return \"[\" + value.map(canonicalJson).join(\",\") + \"]\";\n }\n if (typeof value === \"object\") {\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n return (\n \"{\" +\n keys\n .map((k) => JSON.stringify(k) + \":\" + canonicalJson(obj[k]))\n .join(\",\") +\n \"}\"\n );\n }\n return JSON.stringify(String(value));\n}\n\n/**\n * SHA-256 over `canonicalJson(value)` returned as 64-char lowercase\n * hex. Uses the browser-native WebCrypto API \u2014 no dependency. Async\n * because `crypto.subtle.digest` is async.\n */\nasync function canonicalSha256Hex(value: unknown): Promise<string> {\n const bytes = new TextEncoder().encode(canonicalJson(value));\n const digest = await crypto.subtle.digest(\"SHA-256\", bytes);\n const view = new Uint8Array(digest);\n let s = \"\";\n for (let i = 0; i < view.length; i++) {\n s += view[i]!.toString(16).padStart(2, \"0\");\n }\n return s;\n}\n\n/**\n * Structural equality for claim values. The verifier emits plain\n * JSON shapes (strings, numbers, booleans, arrays of those, objects\n * of those) so a value-equal comparison via JSON round-trip is\n * correct and ~25 ns for the sizes we see in practice. Avoids\n * pulling in a deep-equal dep for one call site.\n */\nfunction _deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\") return false;\n if (a === null || b === null) return false;\n try {\n return JSON.stringify(a) === JSON.stringify(b);\n } catch {\n return false;\n }\n}\n", "/**\n * Typed HTTPS wrappers around the Cloudflare Worker's session API.\n *\n * The SDK does NOT depend on Firebase. The Worker is the single API\n * surface: anonymous /session/draft for the browser, wallet-signed\n * /session/claim for the wallet. See `../../../../cloudflare-workers/signaling-worker`\n * for the server impl and `../../ARCHITECTURE.md` for the spec.\n */\nimport { SIGNALING_BASE } from \"./index.js\";\n\n/** The verifier-side request blob the SDK assembles + sends to /session/draft. */\nexport type VerifierRequest = {\n domain: string;\n nonce: string;\n browserPk: string;\n required: {\n /** 0 = pseudonymous (unverified identity) accepted; omitted \u21D2 1. */\n minVerificationLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6;\n requiredClaims?: string[];\n predicates?: string[];\n identityType?: \"personal\" | \"organization\";\n /** Require a domain-scoped unique-human id (document-anchored). */\n uniqueHumanId?: boolean;\n };\n ttlMaxMinutes: number;\n /** Data-channel envelope version the SDK speaks (2 = sender-authenticated). */\n envelopeVersion?: number;\n};\n\nexport type DraftResult = {\n reqId: string;\n /** Bearer used on the WS upgrade `Sec-WebSocket-Protocol` header. */\n draftToken: string;\n /** wss URL the SDK opens to join the Durable Object as the browser peer. */\n signalingWss: string;\n /** Epoch s \u2014 caller has until this moment for a wallet to claim. */\n draftExpiresAt: number;\n /**\n * **Server-issued timestamp** (epoch seconds, M-3 / v2). The Worker\n * stamped it at draft creation and stored it in the DO. The wallet\n * MUST echo this value verbatim in its `prson-login-claim/v2`\n * signature \u2014 the Worker rebuilds the canonical bytes using its\n * stored copy, so any tamper breaks the signature. The SDK threads\n * it through the QR (`t=` param).\n */\n serverTs: number;\n /**\n * OLDER relays only: Cloudflare TURN credentials for the browser side,\n * minted at draft time. Current relays omit this and instead send\n * `{ \"type\": \"ice\", \"iceServers\": [...] }` over the WebSocket once a\n * wallet has claimed the code, so no relay capacity is minted for a\n * code nobody scans. Either way the browser runs relay-only (see\n * transport.ts `rtcConfigFor`). Wire grammar matches `RTCIceServer`.\n */\n turn?: {\n urls: string | string[];\n username: string;\n credential: string;\n expiresAt?: number;\n };\n};\n\n/**\n * POST /session/draft on the Cloudflare Worker. Anonymous + IP rate-\n * limited at 30 drafts/IP/min (no TURN allocated yet \u2014 the Worker\n * waits for a wallet to claim before issuing any relay capacity).\n */\nexport async function createDraft(\n request: VerifierRequest,\n opts: { signalingBase?: string; fetchImpl?: typeof fetch } = {},\n): Promise<DraftResult> {\n const base = opts.signalingBase ?? SIGNALING_BASE;\n const fetchImpl = opts.fetchImpl ?? fetch;\n const res = await fetchImpl(`${base}/session/draft`, {\n method: \"POST\",\n mode: \"cors\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ request }),\n });\n if (!res.ok) {\n const text = await safeText(res);\n if (res.status === 429) {\n throw new Error(\"Too many login sessions from this network \u2014 please retry shortly.\");\n }\n throw new Error(`createDraft failed: HTTP ${res.status} ${text || res.statusText}`);\n }\n return (await res.json()) as DraftResult;\n}\n\nasync function safeText(res: Response): Promise<string> {\n try { return await res.text(); } catch { return \"\"; }\n}\n", "/**\n * Browser-side WebSocket client for the Cloudflare Worker signaling\n * Durable Object. The wallet talks to the same Worker; the DO fans\n * messages between us.\n *\n * Wire format mirrors the Worker's `SignalingMessage` discriminated\n * union (see cloudflare-workers/signaling-worker/src/index.ts). We don't import\n * those types directly because cross-package type sharing would\n * bloat the SDK; the two definitions are kept in sync by the spec.\n */\n\nconst WS_SUBPROTOCOL = \"prson-login-v1\";\n\nexport type SignalingMessage =\n | { msg: \"offer\"; sdp: string }\n | { msg: \"answer\"; sdp: string }\n | { msg: \"candidate\"; candidate: unknown }\n | { msg: \"peer-ready\" }\n | { msg: \"peer-gone\" }\n | { msg: \"error\"; reason: string };\n\n/**\n * Relay \u2192 browser, once a wallet has claimed the code:\n * `{ \"type\": \"ice\", \"iceServers\": [...] }` \u2014 the TURN servers the\n * browser must use (relay-only, so its addresses never reach the\n * phone). Newer relays send no TURN at draft time; older ones put it\n * in the draft response instead and never send this.\n */\nexport type IceMessage = { type: \"ice\"; iceServers: RTCIceServer[] };\n\nexport interface SignalingConnection {\n /** Push a message to the other peer through the relay. */\n send(m: SignalingMessage): void;\n /** Subscribe to messages from the other peer. */\n onMessage(cb: (m: SignalingMessage) => void): void;\n /** Subscribe to terminal-close events from either side or the worker. */\n onClose(cb: (reason: string) => void): void;\n /**\n * Resolves with the relay's `ice` servers (the first `ice` message,\n * buffered if it arrived before this was called). Rejects if the\n * socket closes first.\n */\n awaitIce(): Promise<RTCIceServer[]>;\n /** Close the WS. Does not tear down the underlying RTCPeerConnection. */\n close(): void;\n}\n\nexport async function connectSignaling(opts: {\n url: string;\n role: \"browser\";\n sigToken: string;\n}): Promise<SignalingConnection> {\n const ws = new WebSocket(opts.url, [WS_SUBPROTOCOL, opts.sigToken]);\n const msgListeners: Array<(m: SignalingMessage) => void> = [];\n const closeListeners: Array<(reason: string) => void> = [];\n let ice: RTCIceServer[] | null = null;\n let closedReason: string | null = null;\n const iceWaiters: Array<{ resolve: (s: RTCIceServer[]) => void; reject: (e: Error) => void }> = [];\n\n await new Promise<void>((resolve, reject) => {\n const onOpen = () => {\n ws.removeEventListener(\"open\", onOpen);\n ws.removeEventListener(\"error\", onErrorBefore);\n resolve();\n };\n const onErrorBefore = () => {\n ws.removeEventListener(\"open\", onOpen);\n ws.removeEventListener(\"error\", onErrorBefore);\n reject(new Error(\"signaling: WS upgrade failed (auth?)\"));\n };\n ws.addEventListener(\"open\", onOpen);\n ws.addEventListener(\"error\", onErrorBefore);\n });\n\n ws.addEventListener(\"message\", (evt) => {\n let parsed: SignalingMessage | IceMessage;\n try {\n parsed = JSON.parse(String(evt.data)) as SignalingMessage | IceMessage;\n } catch {\n return; // bad frame from the Worker; ignore\n }\n if (parsed && (parsed as IceMessage).type === \"ice\") {\n // Only the first one counts: the peer connection is built from it.\n const servers = (parsed as IceMessage).iceServers;\n if (ice || !Array.isArray(servers)) return;\n ice = servers.filter((x) => x && (typeof x.urls === \"string\" || Array.isArray(x.urls)));\n for (const w of iceWaiters.splice(0)) w.resolve(ice);\n return;\n }\n if (!parsed || typeof (parsed as SignalingMessage).msg !== \"string\") return;\n for (const cb of msgListeners) cb(parsed as SignalingMessage);\n });\n\n ws.addEventListener(\"close\", (evt) => {\n const reason = evt.reason || `code-${evt.code}`;\n closedReason = reason;\n for (const w of iceWaiters.splice(0)) w.reject(new Error(`signaling: closed before the code was claimed (${reason})`));\n for (const cb of closeListeners) cb(reason);\n });\n\n return {\n send(m: SignalingMessage) {\n if (ws.readyState !== WebSocket.OPEN) return;\n ws.send(JSON.stringify(m));\n },\n onMessage(cb) {\n msgListeners.push(cb);\n },\n onClose(cb) {\n closeListeners.push(cb);\n },\n awaitIce() {\n if (ice) return Promise.resolve(ice);\n if (closedReason !== null) {\n return Promise.reject(new Error(`signaling: closed before the code was claimed (${closedReason})`));\n }\n return new Promise((resolve, reject) => iceWaiters.push({ resolve, reject }));\n },\n close() {\n try { ws.close(1000, \"client_close\"); } catch { /* */ }\n },\n };\n}\n", "/**\n * Browser-side WebRTC transport. Orchestrates the SDP offer / answer +\n * ICE exchange via the Cloudflare Worker signaling, and exposes a\n * tiny event-stream interface over the established data channel.\n */\nimport type { SignalingConnection } from \"./signaling.js\";\n\nexport interface Transport {\n /** Await the next data-channel message as a UTF-8 string. */\n awaitNextMessage(): Promise<string>;\n /** Await the first data-channel message; convenience wrapper. */\n awaitFirstMessage(): Promise<string>;\n /** Subscribe to all data-channel messages as they arrive. */\n onMessage(cb: (raw: string) => void): void;\n /** Subscribe to terminal-close events from either side or the\n * Worker. Fires exactly once per transport with a short string\n * reason \u2014 the SDK's session layer maps this to the matching\n * `signed_out` reason code so the host gets a lifecycle event\n * the moment the wire dies (rather than waiting for the\n * credential's exp timer, which runs days from now and never\n * matches the much-shorter session TTL). */\n onClose(cb: (reason: string) => void): void;\n /** Send a UTF-8 string over the data channel (used by `revoke` etc.). */\n send(raw: string): void;\n /** Close the RTCPeerConnection + the data channel. */\n close(): void;\n}\n\n/**\n * RTCPeerConnection config for the browser side. With TURN available\n * the browser is relay-only (`iceTransportPolicy: \"relay\"`, no STUN):\n * it gathers only relay candidates, so none of its own addresses (LAN,\n * public) reach the phone \u2014 the wallet has done the same since M-4.\n * A dev relay without TURN credentials hands out STUN only; relay-only\n * would find no candidates, so that case falls back to `\"all\"`.\n */\nexport function rtcConfigFor(iceServers: RTCIceServer[]): RTCConfiguration {\n const urls = (s: RTCIceServer) => (Array.isArray(s.urls) ? s.urls : [s.urls]);\n const isTurn = (u: string) => /^turns?:/i.test(u);\n const turn = iceServers\n .map((s) => ({ ...s, urls: urls(s).filter(isTurn) }))\n .filter((s) => s.urls.length > 0);\n if (turn.length > 0) return { iceServers: turn, iceTransportPolicy: \"relay\" };\n return { iceServers, iceTransportPolicy: \"all\" };\n}\n\n/** How long a live data channel must stay silent after a `peer-gone`\n * before we believe it. The wallet pings every 2 s. */\nconst PEER_GONE_CONFIRM_MS = 6000;\n\nexport async function establishTransport(opts: {\n signaling: SignalingConnection;\n role: \"browser\";\n /**\n * ICE servers from the relay: the `ice` message it sends once a wallet\n * claimed the code, or (older relays) the draft response's `turn`.\n * See [rtcConfigFor] and ../../SECURITY.md \u00A76.\n */\n iceServers: RTCIceServer[];\n}): Promise<Transport> {\n const pc = new RTCPeerConnection(rtcConfigFor(opts.iceServers));\n\n // Browser is the initiator \u2192 opens the data channel before the\n // offer. Negotiated=false so the wallet sees `ondatachannel`.\n const dc = pc.createDataChannel(\"prson-login\", { ordered: true });\n\n // Trickle ICE \u2192 signaling.\n pc.addEventListener(\"icecandidate\", (e) => {\n if (e.candidate) opts.signaling.send({ msg: \"candidate\", candidate: e.candidate.toJSON() });\n });\n\n // Bridge inbound signaling \u2192 peer connection.\n opts.signaling.onMessage(async (m) => {\n if (m.msg === \"answer\") {\n await pc.setRemoteDescription({ type: \"answer\", sdp: m.sdp });\n } else if (m.msg === \"candidate\") {\n try {\n await pc.addIceCandidate(m.candidate as RTCIceCandidateInit);\n } catch {\n // Late or duplicate candidates can be ignored \u2014 the SDP path\n // covered the gathered ones.\n }\n } else if (m.msg === \"peer-gone\") {\n // `peer-gone` is the relay's word that the wallet's socket went\n // away. It travels the same socket as the wallet's own messages,\n // so it isn't proof: once the data channel is up, the channel\n // itself decides \u2014 if the wallet stays silent (it pings every\n // 2 s), it's gone; if it keeps talking, the notice is ignored.\n // `error` frames are never acted on.\n if (dc.readyState === \"open\") {\n confirmPeerGone();\n return;\n }\n // Wallet vanished \u2014 close the data channel so the host knows.\n // Fire the explicit teardown FIRST with a wallet-side reason\n // so the SDK maps it to `wallet_signed_out` (the dc close\n // alone would degrade to the generic `network_loss`).\n fireClose(\"wallet_signed_out\");\n try { dc.close(); } catch { /* */ }\n }\n });\n\n let lastDcMessageAt = 0;\n let peerGoneTimer: ReturnType<typeof setTimeout> | null = null;\n function confirmPeerGone() {\n if (peerGoneTimer) return;\n const noticeAt = Date.now();\n peerGoneTimer = setTimeout(() => {\n peerGoneTimer = null;\n if (lastDcMessageAt >= noticeAt) return; // still talking: not gone\n fireClose(\"wallet_signed_out\");\n try { dc.close(); } catch { /* */ }\n }, PEER_GONE_CONFIRM_MS);\n }\n\n // Generate + post the SDP offer.\n const offer = await pc.createOffer();\n await pc.setLocalDescription(offer);\n opts.signaling.send({ msg: \"offer\", sdp: offer.sdp! });\n\n // Wait for the data channel to open.\n await new Promise<void>((resolve, reject) => {\n if (dc.readyState === \"open\") return resolve();\n const onOpen = () => {\n dc.removeEventListener(\"open\", onOpen);\n dc.removeEventListener(\"error\", onError);\n resolve();\n };\n const onError = () => {\n dc.removeEventListener(\"open\", onOpen);\n dc.removeEventListener(\"error\", onError);\n reject(new Error(\"transport: data channel failed to open\"));\n };\n dc.addEventListener(\"open\", onOpen);\n dc.addEventListener(\"error\", onError);\n });\n\n // Message bookkeeping: split between one-shot waiters (the initial\n // presentation) and steady-state subscribers (renewals).\n const oneShotWaiters: Array<(raw: string) => void> = [];\n const allListeners: Array<(raw: string) => void> = [];\n // Terminal-close fan-out. Three triggers map onto the same\n // notification: signaling close (WS code 4000 = Worker DO alarm\n // fired at session TTL), peer-gone signaling message (wallet\n // revoked), and the data channel itself closing for any other\n // reason. Fired at most once \u2014 the latch prevents duplicate\n // signed_out events in the SDK's session layer.\n const closeListeners: Array<(reason: string) => void> = [];\n let closeFired = false;\n function fireClose(reason: string) {\n if (closeFired) return;\n closeFired = true;\n for (const cb of closeListeners) {\n try { cb(reason); } catch { /* swallow */ }\n }\n }\n opts.signaling.onClose((reason) => fireClose(reason));\n dc.addEventListener(\"close\", () => fireClose(\"network_loss\"));\n dc.addEventListener(\"message\", (evt) => {\n lastDcMessageAt = Date.now();\n const raw = typeof evt.data === \"string\"\n ? evt.data\n : new TextDecoder().decode(evt.data as ArrayBuffer);\n while (oneShotWaiters.length > 0) {\n const cb = oneShotWaiters.shift()!;\n cb(raw);\n }\n for (const cb of allListeners) cb(raw);\n });\n\n return {\n awaitNextMessage() {\n return new Promise((resolve) => oneShotWaiters.push(resolve));\n },\n awaitFirstMessage() {\n return new Promise((resolve) => oneShotWaiters.push(resolve));\n },\n onMessage(cb) {\n allListeners.push(cb);\n },\n onClose(cb) {\n // Late subscribers still get the notification: if the close\n // already fired, dispatch on the next microtask so the\n // subscriber's await chain sees a single deterministic\n // ordering (analogous to `signed_in` being microtask-deferred).\n if (closeFired) {\n queueMicrotask(() => cb(\"network_loss\"));\n } else {\n closeListeners.push(cb);\n }\n },\n send(raw: string) {\n if (dc.readyState === \"open\") dc.send(raw);\n },\n close() {\n if (peerGoneTimer) clearTimeout(peerGoneTimer);\n try { dc.close(); } catch { /* */ }\n try { pc.close(); } catch { /* */ }\n opts.signaling.close();\n },\n };\n}\n", "/**\n * Minimal QR rendering surface. We deliberately don't bundle a full\n * QR library here \u2014 the SDK is tiny and most sites already have one.\n * Instead, we expose a render adapter that the host page can override.\n *\n * Default behaviour: render a placeholder `<div>` with the URL as\n * text + a copy-to-clipboard affordance, and emit a `console.warn`\n * pointing partners at the QR-renderer hook. Production deployments\n * pass a real QR renderer (e.g. `qrcode-svg`, `qr-creator`) via\n * `PrsonLogin.signIn({ ui: { mountQrInto } })` + a global override\n * on `window.__prsonLoginQrRenderer`.\n */\n\nexport interface LoginQrHandle {\n /** Tear the QR down (called automatically when the SDK no longer needs it). */\n dispose(): void;\n /**\n * Optional (renderers written before 0.2 don't have it): the SDK\n * reports progress so the UI can show it. For `\"success\"` the renderer\n * may return a promise; the SDK waits for it (at most 1.5 s) before\n * tearing the UI down, so a check animation can finish.\n */\n update?(state: LoginUiState): void | Promise<void>;\n}\n\n/**\n * What the sign-in is doing, as far as the browser can tell:\n *\n * waiting the code is on screen\n * scanned a wallet claimed the code (the person approved on the\n * phone, which is now connecting)\n * approving the encrypted channel to the phone is open; the phone is\n * preparing its signed proof\n * verifying the proof arrived; the SDK is checking it\n * success checked; the UI is about to close\n * error something failed; `message` says what, in plain words\n *\n * Expiry isn't sent: the renderer runs the countdown from the code's own\n * server timestamp (`t=`).\n */\nexport type LoginUiState =\n | { state: \"waiting\" }\n | { state: \"scanned\" }\n | { state: \"approving\" }\n | { state: \"verifying\" }\n | { state: \"success\"; domain: string }\n | { state: \"error\"; message: string };\n\n/** The optional fourth argument the SDK passes to a renderer. */\nexport interface LoginQrContext {\n /** `\"modal\"`: inside the SDK's own dialog. `\"inline\"`: in the host's `mountQrInto`. */\n mode: \"modal\" | \"inline\";\n /** The domain the person is signing in to (the same as the code's `d=`). */\n domain: string;\n /**\n * Ask for a fresh code (after expiry or an error): the SDK makes a new\n * draft and renders again, and `signIn()` keeps waiting. The renderer\n * should first dispatch the bubbling `prson-login-refresh-requested`\n * DOM event (the 0.1 contract); if the host re-called `signIn()` from\n * that event, this is a no-op.\n */\n refresh?: () => void;\n /** Close the sign-in: `signIn()` rejects with `LoginAbortedError`. */\n cancel?: () => void;\n /** Where \"Don't have Prson? Get it\" points. */\n getAppUrl: string;\n /** The id the card's title should carry, so the modal is labelled by it. */\n titleId: string;\n}\n\nexport type LoginQrRenderer = (\n url: string,\n mount: HTMLElement,\n theme: \"light\" | \"dark\" | \"auto\",\n context?: LoginQrContext,\n) => LoginQrHandle;\n\n/**\n * Create a centred modal scrim and return the inner mount element +\n * a dispose handle. Used as the default QR presentation when the\n * host page didn't pass `mountQrInto` \u2014 the SDK calls this, then\n * hands the inner mount to `renderLoginQr` exactly like an inline\n * mount.\n *\n * The scrim:\n * * darkens the page with a 50%-black overlay + a 4 px backdrop\n * blur (so the partner UI fades into the background but stays\n * contextual),\n * * dismisses on **Esc** (any focused field is bypassed via\n * capture-phase listener \u2014 works even with another input\n * focused),\n * * dismisses on **click outside** the card,\n * * sits above every layout via `z-index: 2147483647`.\n *\n * Dismissing fires [onDismiss] \u2014 the SDK wires this to abort the\n * in-flight `signIn()` so the host's `await signIn(...)` rejects\n * with `LoginAbortedError` rather than hanging.\n */\nexport function createModalQrMount(opts: {\n onDismiss: () => void;\n /** The id of the card's title: the dialog is labelled by it. */\n titleId?: string;\n}): { mount: HTMLElement; dispose: () => void } {\n const scrim = document.createElement(\"div\");\n scrim.setAttribute(\"data-prson-login-modal\", \"1\");\n // Phones get a bottom sheet (thumb-reachable); larger screens a centred card.\n const sheet = typeof window.matchMedia === \"function\" && window.matchMedia(\"(max-width: 480px)\").matches;\n scrim.style.cssText =\n \"position:fixed;inset:0;background:rgba(10,10,10,0.45);\" +\n \"backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);\" +\n \"z-index:2147483647;display:flex;overflow-y:auto;box-sizing:border-box;\" +\n \"justify-content:center;\" +\n (sheet ? \"align-items:flex-end;padding:0;\" : \"align-items:center;padding:24px 16px;\");\n\n // An accessible dialog: role, aria-modal, labelled by the card's title,\n // focus moved in and kept there (Tab wraps), restored on close.\n const mount = document.createElement(\"div\");\n mount.setAttribute(\"data-prson-login-modal-mount\", \"1\");\n mount.setAttribute(\"role\", \"dialog\");\n mount.setAttribute(\"aria-modal\", \"true\");\n if (opts.titleId) mount.setAttribute(\"aria-labelledby\", opts.titleId);\n else mount.setAttribute(\"aria-label\", \"Sign in with Prson\");\n mount.tabIndex = -1;\n // The QR card renderer manages its own width via CSS \u2014 give it\n // the natural sizing it expects.\n mount.style.cssText =\n \"display:flex;align-items:center;justify-content:center;outline:none;max-width:100%;\" +\n (sheet ? \"width:100%;\" : \"margin:auto 0;\");\n\n scrim.append(mount);\n const previouslyFocused = document.activeElement instanceof HTMLElement ? document.activeElement : null;\n const root = document.documentElement;\n const prevOverflow = root.style.overflow;\n root.style.overflow = \"hidden\";\n document.body.append(scrim);\n // Focus the dialog itself, so a screen reader starts at its title and a\n // stray Enter doesn't press anything.\n setTimeout(() => {\n if (!disposed && !mount.contains(document.activeElement)) mount.focus({ preventScroll: true });\n }, 0);\n\n let disposed = false;\n\n function dispose() {\n if (disposed) return;\n disposed = true;\n document.removeEventListener(\"keydown\", onKey, true);\n scrim.remove();\n root.style.overflow = prevOverflow;\n try {\n previouslyFocused?.focus({ preventScroll: true });\n } catch {\n /* gone from the page */\n }\n }\n\n function onKey(e: KeyboardEvent) {\n if (e.key === \"Escape\" || e.key === \"Esc\") {\n e.preventDefault();\n e.stopPropagation();\n opts.onDismiss();\n return;\n }\n if (e.key !== \"Tab\") return;\n const focusable = Array.from(\n mount.querySelectorAll<HTMLElement>('a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex=\"-1\"])'),\n ).filter((el) => el.getClientRects().length > 0);\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (!first || !last) {\n e.preventDefault();\n mount.focus();\n return;\n }\n const active = document.activeElement;\n if (e.shiftKey && (active === first || active === mount || !mount.contains(active))) {\n e.preventDefault();\n last.focus();\n } else if (!e.shiftKey && (active === last || !mount.contains(active))) {\n e.preventDefault();\n first.focus();\n }\n }\n\n scrim.addEventListener(\"click\", (e) => {\n // Click directly on the scrim (not the card) dismisses. Card\n // taps bubble up from the inner mount; we ignore them.\n if (e.target === scrim || e.target === mount) {\n opts.onDismiss();\n }\n });\n\n document.addEventListener(\"keydown\", onKey, true);\n\n return { mount, dispose };\n}\n\nexport function renderLoginQr(\n url: string,\n mount: HTMLElement,\n theme: \"light\" | \"dark\" | \"auto\",\n context?: LoginQrContext,\n): LoginQrHandle {\n const override = (window as unknown as { __prsonLoginQrRenderer?: LoginQrRenderer })\n .__prsonLoginQrRenderer;\n if (override) return override(url, mount, theme, context);\n\n // Fallback: text + click-to-copy. Good enough for development;\n // partners should install a real QR renderer.\n // eslint-disable-next-line no-console\n console.warn(\n \"[@prson/login-sdk] No QR renderer installed. Set window.__prsonLoginQrRenderer \" +\n \"to a function (url, mount, theme) => { dispose: () => void } before calling signIn().\",\n );\n\n const root = document.createElement(\"div\");\n root.setAttribute(\"data-prson-qr-fallback\", \"1\");\n root.style.cssText = \"font-family:system-ui,sans-serif;font-size:12px;padding:12px;border:1px dashed currentColor;border-radius:8px;word-break:break-all;cursor:pointer;\";\n root.textContent = url;\n root.title = \"Click to copy. Install a real QR renderer for the production UX.\";\n root.addEventListener(\"click\", () => {\n void navigator.clipboard?.writeText(url);\n });\n mount.append(root);\n\n return {\n dispose() {\n root.remove();\n },\n };\n}\n", "// Website notifications (SignInOptions.notifications): the wallet answers an\n// opted-in sign-in with a handle, random per wallet and site, that the site's\n// backend uses with POST https://api.prson.net/v1/notify (an API key with\n// notify:write). See documentation/SITE_NOTIFICATIONS.md.\n\n/** What a notification handle looks like: `nh_` and 32 random bytes, base64url. */\nexport const NOTIFY_HANDLE = /^nh_[A-Za-z0-9_-]{43}$/;\n\n/**\n * The handle in the wallet's sign-in envelope, or null when the person didn't\n * tick \"Let {site} send you notifications\" (or the wallet is older). Anything\n * that isn't a well-formed handle reads as null.\n */\nexport function notifyHandleFrom(envelope: unknown): string | null {\n if (!envelope || typeof envelope !== \"object\") return null;\n const value = (envelope as { notifyHandle?: unknown }).notifyHandle;\n return typeof value === \"string\" && NOTIFY_HANDLE.test(value) ? value : null;\n}\n", "/**\n * Virtual-cursor-friendly overlay for native `<select>` elements.\n *\n * Why this exists: native `<select>` dropdowns are rendered by the OS\n * shell, not the DOM. Synthetic `click` events from `bindMouse`'s\n * virtual cursor cannot open them, and even if they did the OS-drawn\n * option list is outside the page's coordinate system \u2014 the virtual\n * cursor couldn't navigate it. We replace the native dropdown with a\n * pure-DOM overlay sized for cursor accuracy:\n *\n * * Each option is a large (\u226556 px tall) button \u2014 easy to land on\n * with the wand or trackpad.\n * * \"Previous page\" / \"Next page\" buttons step through long option\n * lists one viewport-sized chunk at a time.\n * * An \"X\" button closes without committing a choice.\n * * The overlay sits at the top of the body z-index stack and\n * traps clicks: while it's open, the rest of the page is\n * non-interactive \u2014 the cursor's click router only considers\n * overlay elements.\n * * The overlay is rendered inside a Shadow DOM root with\n * `:host { all: initial; }` so the host page's stylesheets\n * cannot bleed in. The page can neither restyle nor read the\n * overlay (closed-mode shadow), beyond what we deliberately\n * expose via attributes.\n *\n * Wiring from `bindMouse`:\n *\n * * Move frames re-route the snap target into the overlay via\n * [findNearestClickableInOverlay] when the overlay is open.\n * * Click frames detect `<select>` snap targets and open the\n * overlay instead of dispatching a click. When the overlay is\n * open, subsequent clicks route through it.\n * * `bindMouse.dispose()` calls [closeAllOverlays] so a torn-down\n * cursor doesn't leave the overlay orphaned.\n */\n\ninterface OverlayHandle {\n host: HTMLElement;\n shadow: ShadowRoot;\n close: () => void;\n}\n\nlet activeOverlay: OverlayHandle | null = null;\n\n/** True when a select overlay is currently open + accepting input. */\nexport function isSelectOverlayActive(): boolean {\n return activeOverlay !== null;\n}\n\n/** Close any currently-open overlay. No-op when none is open. */\nexport function closeAllOverlays(): void {\n activeOverlay?.close();\n}\n\n/**\n * Mount the overlay for [select]. Replaces any existing overlay.\n * Returns the handle so callers can close it programmatically (e.g.\n * if the cursor disposes while the overlay is still up). The\n * overlay self-closes when the user picks an option or taps X.\n */\nexport function openSelectOverlay(select: HTMLSelectElement): OverlayHandle {\n if (activeOverlay) activeOverlay.close();\n\n const host = document.createElement(\"div\");\n host.setAttribute(\"data-prson-select-overlay\", \"\");\n // Pin the host to the viewport. Inline styles win over any page\n // CSS that might try to position `div` differently (Shadow DOM\n // protects the inside; the host element itself is still in the\n // light tree).\n host.style.position = \"fixed\";\n host.style.inset = \"0\";\n // z-index sits just below the virtual cursor (2147483647) so the\n // cursor still paints on top of the overlay.\n host.style.zIndex = \"2147483646\";\n document.body.appendChild(host);\n\n const shadow = host.attachShadow({ mode: \"open\" });\n\n const style = document.createElement(\"style\");\n style.textContent = OVERLAY_CSS;\n shadow.appendChild(style);\n\n // Title label: prefer the matching `<label>`, then aria-label,\n // then name, then a generic string. Done once at open time so\n // late `label` mutations don't change the title mid-life.\n const title = pickTitle(select);\n\n const backdrop = document.createElement(\"div\");\n backdrop.className = \"backdrop\";\n backdrop.setAttribute(\"data-prson-select-backdrop\", \"\");\n\n const panel = document.createElement(\"div\");\n panel.className = \"panel\";\n\n // \u2500\u2500 header \u2500\u2500\u2500\u2500\n const header = document.createElement(\"div\");\n header.className = \"header\";\n const titleEl = document.createElement(\"div\");\n titleEl.className = \"title\";\n titleEl.textContent = title;\n const closeBtn = document.createElement(\"button\");\n closeBtn.className = \"close\";\n closeBtn.setAttribute(\"type\", \"button\");\n closeBtn.setAttribute(\"data-prson-select-close\", \"\");\n closeBtn.setAttribute(\"aria-label\", \"Close\");\n closeBtn.textContent = \"\u2715\";\n header.appendChild(titleEl);\n header.appendChild(closeBtn);\n panel.appendChild(header);\n\n // \u2500\u2500 pagination row + options \u2500\u2500\u2500\u2500\n const optionsWrap = document.createElement(\"div\");\n optionsWrap.className = \"options-wrap\";\n\n const pageUp = document.createElement(\"button\");\n pageUp.className = \"page-btn\";\n pageUp.setAttribute(\"type\", \"button\");\n pageUp.setAttribute(\"data-prson-select-page\", \"up\");\n pageUp.innerHTML = '<span class=\"chev\">\u25B2</span> Previous';\n\n const list = document.createElement(\"div\");\n list.className = \"options-list\";\n\n const pageDown = document.createElement(\"button\");\n pageDown.className = \"page-btn\";\n pageDown.setAttribute(\"type\", \"button\");\n pageDown.setAttribute(\"data-prson-select-page\", \"down\");\n pageDown.innerHTML = 'Next <span class=\"chev\">\u25BC</span>';\n\n optionsWrap.appendChild(pageUp);\n optionsWrap.appendChild(list);\n optionsWrap.appendChild(pageDown);\n panel.appendChild(optionsWrap);\n\n backdrop.appendChild(panel);\n shadow.appendChild(backdrop);\n\n // \u2500\u2500 options paging \u2500\u2500\u2500\u2500\n const options = Array.from(select.options);\n const PAGE_SIZE = 6;\n const numPages = Math.max(1, Math.ceil(options.length / PAGE_SIZE));\n let currentPage = pageOfValue(select.value, options, PAGE_SIZE);\n\n function renderPage(): void {\n list.replaceChildren();\n const start = currentPage * PAGE_SIZE;\n const end = Math.min(start + PAGE_SIZE, options.length);\n for (let i = start; i < end; i++) {\n const opt = options[i]!;\n const btn = document.createElement(\"button\");\n btn.className = \"option\";\n btn.setAttribute(\"type\", \"button\");\n btn.setAttribute(\"data-prson-select-option\", String(i));\n btn.textContent = opt.label || opt.value || `Option ${i + 1}`;\n if (opt.value === select.value) {\n btn.setAttribute(\"data-selected\", \"\");\n }\n list.appendChild(btn);\n }\n // Toggle paging button state. Visible-but-disabled rather than\n // removed so the layout stays stable (cursor doesn't have to\n // re-find the button when there's more to page through).\n if (currentPage <= 0) {\n pageUp.setAttribute(\"disabled\", \"\");\n } else {\n pageUp.removeAttribute(\"disabled\");\n }\n if (currentPage >= numPages - 1) {\n pageDown.setAttribute(\"disabled\", \"\");\n } else {\n pageDown.removeAttribute(\"disabled\");\n }\n }\n renderPage();\n\n const handle: OverlayHandle = {\n host,\n shadow,\n close: () => {\n host.remove();\n if (activeOverlay === handle) activeOverlay = null;\n },\n };\n\n // Click handler \u2014 works for both real-finger taps AND synthetic\n // events from the virtual cursor. `composedPath()` is required to\n // reach into the shadow tree from the listener on `shadow` itself.\n shadow.addEventListener(\"click\", (e) => {\n const path = (e as Event).composedPath();\n for (const node of path) {\n if (!(node instanceof Element)) continue;\n // Close button.\n if (node.getAttribute?.(\"data-prson-select-close\") !== null) {\n handle.close();\n return;\n }\n // Page buttons.\n const page = node.getAttribute?.(\"data-prson-select-page\");\n if (page === \"up\") {\n if (currentPage > 0) {\n currentPage -= 1;\n renderPage();\n }\n return;\n }\n if (page === \"down\") {\n if (currentPage < numPages - 1) {\n currentPage += 1;\n renderPage();\n }\n return;\n }\n // Option.\n const optAttr = node.getAttribute?.(\"data-prson-select-option\");\n if (optAttr !== null && optAttr !== undefined) {\n const idx = Number.parseInt(optAttr, 10);\n const chosen = options[idx];\n if (chosen) {\n select.value = chosen.value;\n select.dispatchEvent(new Event(\"input\", { bubbles: true }));\n select.dispatchEvent(new Event(\"change\", { bubbles: true }));\n }\n handle.close();\n return;\n }\n // Backdrop tap (anywhere outside the panel) closes too \u2014 the\n // virtual cursor can't escape to it easily, but a real finger\n // can.\n if (node.getAttribute?.(\"data-prson-select-backdrop\") !== null) {\n handle.close();\n return;\n }\n }\n });\n\n activeOverlay = handle;\n return handle;\n}\n\n/**\n * Snap-target lookup *inside* the active overlay. Bind.ts swaps\n * the regular `findNearestClickable` for this when an overlay is\n * open so the magic-mode highlight tracks the overlay's option\n * buttons instead of the (no-longer-interactive) page underneath.\n *\n * No radius cap \u2014 when the overlay is open the cursor MUST land on\n * something useful, so we always return a snap target if any\n * candidate exists.\n */\nexport function findNearestClickableInOverlay(\n x: number,\n y: number,\n): Element | null {\n if (!activeOverlay) return null;\n const candidates = activeOverlay.shadow.querySelectorAll(\n \"[data-prson-select-close],\" +\n \"[data-prson-select-page]:not([disabled]),\" +\n \"[data-prson-select-option]\",\n );\n let best: Element | null = null;\n let bestDist = Infinity;\n for (const el of Array.from(candidates)) {\n const rect = el.getBoundingClientRect();\n if (rect.width === 0 || rect.height === 0) continue;\n const dx = x < rect.left ? rect.left - x : x > rect.right ? x - rect.right : 0;\n const dy = y < rect.top ? rect.top - y : y > rect.bottom ? y - rect.bottom : 0;\n const dist = Math.sqrt(dx * dx + dy * dy);\n if (dist < bestDist) {\n bestDist = dist;\n best = el;\n }\n }\n return best;\n}\n\n/**\n * Highlight an element inside the active overlay by setting the\n * shared `data-prson-magic-snap` attribute. The overlay's own CSS\n * (inside the shadow) provides the visible style \u2014 the page's\n * stylesheet for that attribute cannot reach in.\n */\nexport function setOverlaySnap(target: Element | null): void {\n if (!activeOverlay) return;\n activeOverlay.shadow\n .querySelectorAll(\"[data-prson-magic-snap]\")\n .forEach((el) => el.removeAttribute(\"data-prson-magic-snap\"));\n if (target) target.setAttribute(\"data-prson-magic-snap\", \"\");\n}\n\n// \u2500\u2500\u2500 internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction pickTitle(select: HTMLSelectElement): string {\n // Prefer an explicit label[for=id] OR a wrapping <label>.\n if (select.id) {\n const lbl = document.querySelector(\n `label[for=\"${cssEscapeLocal(select.id)}\"]`,\n );\n if (lbl?.textContent) return lbl.textContent.trim();\n }\n const wrap = select.closest(\"label\");\n if (wrap && wrap.textContent) {\n // Strip out the select's own rendered text from the label's\n // text content; label.textContent concatenates everything.\n const txt = wrap.textContent\n .replace(select.textContent ?? \"\", \"\")\n .trim();\n if (txt) return txt;\n }\n const aria = select.getAttribute(\"aria-label\");\n if (aria) return aria;\n const name = select.getAttribute(\"name\");\n if (name) return name;\n return \"Select an option\";\n}\n\nfunction pageOfValue(\n current: string,\n options: HTMLOptionElement[],\n pageSize: number,\n): number {\n const idx = options.findIndex((o) => o.value === current);\n if (idx < 0) return 0;\n return Math.floor(idx / pageSize);\n}\n\nfunction cssEscapeLocal(s: string): string {\n if (typeof CSS !== \"undefined\" && typeof (CSS as { escape?: (s: string) => string }).escape === \"function\") {\n return (CSS as { escape: (s: string) => string }).escape(s);\n }\n return s.replace(/[^a-zA-Z0-9_-]/g, \"\\\\$&\");\n}\n\n// All overlay styling is in the shadow root, so it cannot collide\n// with the host page's CSS and the host page cannot override it\n// without explicitly piercing the shadow boundary. Sized for thumb\n// + virtual-cursor accuracy: every interactive element is at least\n// 56 px tall and 44 px wide.\nconst OVERLAY_CSS = `\n :host {\n all: initial;\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n color: #0f172a;\n }\n * { box-sizing: border-box; }\n .backdrop {\n position: fixed;\n inset: 0;\n background: rgba(15, 23, 42, 0.55);\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 24px;\n }\n .panel {\n width: min(440px, 100%);\n max-height: 88vh;\n background: #ffffff;\n border-radius: 20px;\n overflow: hidden;\n display: flex;\n flex-direction: column;\n box-shadow: 0 24px 56px rgba(15, 23, 42, 0.32);\n }\n .header {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 18px 20px;\n border-bottom: 1px solid #e2e8f0;\n }\n .title {\n flex: 1;\n font-size: 18px;\n font-weight: 700;\n color: #0f172a;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n .close {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n border: 1px solid #e2e8f0;\n background: #f1f5f9;\n color: #475569;\n font-size: 18px;\n font-weight: 700;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .close:hover { background: #e2e8f0; }\n .options-wrap {\n display: flex;\n flex-direction: column;\n overflow: hidden;\n }\n .page-btn {\n width: 100%;\n padding: 18px 20px;\n border: none;\n background: #f8fafc;\n color: #475569;\n font-size: 15px;\n font-weight: 600;\n cursor: pointer;\n border-bottom: 1px solid #e2e8f0;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n }\n .page-btn .chev { font-size: 13px; opacity: 0.8; }\n .page-btn:hover { background: #f1f5f9; color: #1e293b; }\n .page-btn[disabled] {\n opacity: 0.35;\n cursor: default;\n background: #f8fafc;\n color: #475569;\n }\n .options-list {\n display: flex;\n flex-direction: column;\n overflow-y: auto;\n }\n .option {\n appearance: none;\n width: 100%;\n padding: 18px 20px;\n border: none;\n background: #ffffff;\n color: #0f172a;\n font-size: 16px;\n font-weight: 500;\n text-align: left;\n cursor: pointer;\n border-bottom: 1px solid #f1f5f9;\n min-height: 60px;\n }\n .option:hover { background: #eff6ff; color: #1d4ed8; }\n .option[data-selected] {\n background: #dbeafe;\n color: #1d4ed8;\n font-weight: 700;\n }\n /* Snap-preview highlight, shared attribute name with the cursor.\n Lives inside the shadow root so the page's selector (if any)\n can't override it. */\n [data-prson-magic-snap] {\n outline: 3px solid #3b82f6;\n outline-offset: -3px;\n background: #eff6ff;\n }\n .option[data-prson-magic-snap] { color: #1d4ed8; }\n`;\n", "/**\n * \"Point your phone at the screen\" overlay shown when the wallet's\n * magic wand emits a `hide` event (the phone is in a non-pointing\n * pose). The visual signals to the user that the cursor is paused\n * and what to do to resume it.\n *\n * Design:\n * * Full-viewport, fixed-position shadow-DOM container \u2014 page\n * stylesheets cannot leak in.\n * * A soft inner blue glow on the viewport edge (inset box-shadow\n * + a thin border) signals \"the page is in remote-control mode,\n * waiting for input\".\n * * A black pill centred in the viewport with the prompt text.\n * * Auto-dismisses on three triggers:\n * 1. Wallet emits the matching `show` event (handled by\n * `bindMouse` directly \u2014 it calls `close()`).\n * 2. The user moves the real (OS) mouse \u2014 `mousemove`\n * listener calls `close()`.\n * 3. 15-second timeout elapses, so a forgotten controller\n * doesn't leave the glow on indefinitely.\n * * `pointer-events: none` on the container so clicks behind it\n * hit the page normally \u2014 the overlay is purely cosmetic.\n */\n\ninterface OverlayHandle {\n host: HTMLElement;\n close: () => void;\n}\n\nlet active: OverlayHandle | null = null;\n\n/** True when the overlay is currently visible. */\nexport function isPointPhoneOverlayActive(): boolean {\n return active !== null;\n}\n\n/** Close any active overlay. Safe to call from anywhere. */\nexport function closePointPhoneOverlay(): void {\n active?.close();\n}\n\n/**\n * Mount the \"point your phone\" overlay. Replaces any prior overlay\n * so re-firing `hide` while one is up is a no-op visually.\n *\n * Returns the handle so the caller can close it programmatically;\n * the overlay also self-closes on real mouse movement or after the\n * 15-second timeout.\n */\nexport function openPointPhoneOverlay(): OverlayHandle {\n if (active) return active;\n\n const host = document.createElement(\"div\");\n host.setAttribute(\"data-prson-point-phone-overlay\", \"\");\n host.style.position = \"fixed\";\n host.style.inset = \"0\";\n host.style.zIndex = \"2147483645\"; // below the cursor (-1) and below the select overlay (-1)\n host.style.pointerEvents = \"none\";\n document.body.appendChild(host);\n\n const shadow = host.attachShadow({ mode: \"open\" });\n const style = document.createElement(\"style\");\n style.textContent = OVERLAY_CSS;\n shadow.appendChild(style);\n\n const glow = document.createElement(\"div\");\n glow.className = \"glow\";\n shadow.appendChild(glow);\n\n const pill = document.createElement(\"div\");\n pill.className = \"pill\";\n pill.innerHTML = `\n <span class=\"dot\"></span>\n <span class=\"text\">Point your phone at the screen to use Magic wand</span>\n `;\n shadow.appendChild(pill);\n\n let closed = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n function close(): void {\n if (closed) return;\n closed = true;\n if (timer) clearTimeout(timer);\n window.removeEventListener(\"mousemove\", onRealMouseMove);\n // Tiny fade for polish.\n host.style.transition = \"opacity 180ms ease\";\n host.style.opacity = \"0\";\n setTimeout(() => host.remove(), 200);\n if (active && active.host === host) active = null;\n }\n\n function onRealMouseMove(_e: MouseEvent): void {\n // Any real OS mouse motion \u2192 user is no longer relying on the\n // wand; dismiss so the page doesn't keep nagging.\n close();\n }\n\n window.addEventListener(\"mousemove\", onRealMouseMove);\n timer = setTimeout(close, 15_000);\n\n const handle: OverlayHandle = { host, close };\n active = handle;\n return handle;\n}\n\n// Shadow-DOM CSS. Sized for clear legibility on any host page;\n// values picked to match the blue accent of the virtual cursor +\n// the snap-preview outline so the user reads the overlay as part\n// of the same \"remote control\" UI family.\nconst OVERLAY_CSS = `\n :host { all: initial; }\n * { box-sizing: border-box; }\n /* Inner-glow viewport border. Two stacked inset shadows: the\n wide soft halo + a thin defined edge. */\n .glow {\n position: fixed;\n inset: 0;\n pointer-events: none;\n box-shadow:\n inset 0 0 0 2px rgba(59, 130, 246, 0.75),\n inset 0 0 28px 6px rgba(59, 130, 246, 0.35),\n inset 0 0 80px 24px rgba(59, 130, 246, 0.18);\n animation: prson-glow-pulse 2.4s ease-in-out infinite;\n }\n @keyframes prson-glow-pulse {\n 0%, 100% { opacity: 0.85; }\n 50% { opacity: 1; }\n }\n .pill {\n position: fixed;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n display: flex;\n align-items: center;\n gap: 14px;\n padding: 18px 28px;\n border-radius: 999px;\n background: #0f172a;\n color: #ffffff;\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n font-size: 16px;\n font-weight: 600;\n letter-spacing: 0.1px;\n box-shadow:\n 0 18px 40px rgba(15, 23, 42, 0.45),\n 0 0 0 1px rgba(255, 255, 255, 0.06) inset;\n /* Pulse-fade in so the pill doesn't pop harshly. */\n animation: prson-pill-fade-in 240ms ease-out both;\n }\n @keyframes prson-pill-fade-in {\n from { opacity: 0; transform: translate(-50%, calc(-50% + 6px)); }\n to { opacity: 1; transform: translate(-50%, -50%); }\n }\n .dot {\n width: 10px;\n height: 10px;\n border-radius: 50%;\n background: rgba(59, 130, 246, 1);\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.25);\n animation: prson-dot-pulse 1.4s ease-in-out infinite;\n flex: none;\n }\n @keyframes prson-dot-pulse {\n 0%, 100% { transform: scale(1); opacity: 1; }\n 50% { transform: scale(1.3); opacity: 0.65; }\n }\n .text {\n line-height: 1.25;\n }\n`;\n", "/**\n * DOM binding helpers \u2014 drive a `session.request(...)` from a\n * page's existing form elements.\n *\n * Two entry points:\n *\n * * [`bindInput`] \u2014 for a single `<input>` / `<textarea>` /\n * `<select>` element. Reads the element's `type`, `name`,\n * `placeholder`, `required`, `min`/`max`/`minlength`/`maxlength`\n * /`pattern`, and (for `<select>`) `<option>` children. Returns\n * a controller whose `.request()` method synthesises a single\n * `kind: \"input\"` request and, on a successful wallet reply,\n * writes the value back into the element and dispatches\n * `input` + `change` events so reactive frameworks pick it up.\n *\n * * [`bindForm`] \u2014 for a `<form>` (or any container holding\n * inputs). Walks descendant `<input>`/`<textarea>`/`<select>`\n * elements in document order, synthesises one\n * `kind: \"input-form\"` request carrying every field, opens\n * a single wallet drawer that paginates prev / next / send,\n * fills every element on reply, and (when the bind target is\n * a `<form>`) calls `requestSubmit()` so the page's existing\n * submit handlers fire.\n *\n * Neither helper auto-fires. The host wires the controller's\n * `.request()` to whatever trigger they prefer \u2014 a button click,\n * focus, route change, etc. Keeps the SDK out of UX decisions\n * about WHEN to ask.\n */\n\nimport type { PrsonLoginSession } from \"./session.js\";\nimport {\n closeAllOverlays,\n findNearestClickableInOverlay,\n isSelectOverlayActive,\n openSelectOverlay,\n setOverlaySnap,\n} from \"./select_overlay.js\";\nimport {\n closePointPhoneOverlay,\n openPointPhoneOverlay,\n} from \"./point_phone_overlay.js\";\nimport type {\n InputFormField,\n InputOption,\n InputType,\n LoginRequest,\n LoginResponse,\n RequestOptions,\n} from \"./requests.js\";\n\n// \u2500\u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface BindController {\n /**\n * Synthesise a request from the bound element + send it. Resolves\n * with whatever the wallet replied (already written into the\n * element(s) on success). Multiple concurrent calls share the\n * same controller; the wallet's queue / rate-limit policy\n * decides whether the second one is accepted.\n */\n request(opts?: RequestOptions & { reason?: string }): Promise<LoginResponse>;\n /** Drop any per-bind state. The helpers are stateless today, but\n * the contract is reserved for future expansion (e.g. a\n * focus-triggered auto-bind). */\n dispose(): void;\n}\n\n/**\n * Bind to a single input-shaped element. Accepted nodes:\n *\n * * `<input>` (type \u2208 text/search/email/tel/url/number/password\n * \u2014 falls back to `text` for unsupported types like `date`),\n * * `<textarea>` (treated as a `text` input),\n * * `<select>` (with `<option>` children).\n *\n * The element's `aria-label`, label-for, or closest `<label>` text\n * becomes the wallet's prompt label. `placeholder` rides through.\n * Numeric / pattern constraints become wallet-side validation.\n *\n * Reply: the wallet's `value` is written via `element.value = ...`\n * + `input` + `change` events. For `<select>`, the value is matched\n * against the option `value` attributes.\n */\nexport function bindInput(\n session: PrsonLoginSession,\n element: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,\n): BindController {\n return {\n async request(opts) {\n // Passwords and one-time codes never cross the live channel, in\n // either direction: whoever holds the phone end may not be the\n // person at this screen (see isSensitiveField).\n if (isSensitiveField(element)) return { ok: false, error: \"unsupported\" } as LoginResponse;\n const req = inputRequestFromElement(element, opts?.reason);\n const reply = await session.request(req, opts);\n if (reply.ok) writeValueIntoElement(element, reply.value);\n return reply;\n },\n dispose() {/* no-op for now */},\n };\n}\n\n/**\n * Bind to a `<form>` or any container element. Walks descendant\n * input-shaped elements in document order, sends ONE\n * `kind: \"input-form\"` request, and on reply fills every matching\n * field + dispatches events.\n *\n * Field name resolution:\n *\n * 1. `element.name` \u2014 the canonical key.\n * 2. `element.id` \u2014 fallback for label-less inputs.\n * 3. `_field_<index>` \u2014 synthetic fallback so the reply still\n * finds its target.\n *\n * If the bound container IS a `<form>`, a successful reply also\n * fires `form.requestSubmit()` so the host's existing submit\n * handler picks up. Containers that aren't forms skip the submit\n * step.\n *\n * Buttons/checkboxes/hidden inputs are ignored on purpose \u2014 they\n * don't fit the kiosk-input shape and confuse the wallet drawer.\n */\nexport function bindForm(\n session: PrsonLoginSession,\n container: HTMLElement,\n): BindController {\n return {\n async request(opts) {\n const elements = collectFieldElements(container);\n if (elements.length === 0) {\n return {\n ok: false,\n error: \"unsupported\",\n } as LoginResponse;\n }\n // Single-element shortcut \u2014 friendlier UX (one focused drawer,\n // smaller envelope) than wrapping a lone input in an input-form.\n if (elements.length === 1) {\n const reply = await session.request(\n inputRequestFromElement(elements[0]!, opts?.reason),\n opts,\n );\n if (reply.ok) writeValueIntoElement(elements[0]!, reply.value);\n if (reply.ok && container instanceof HTMLFormElement) {\n tryRequestSubmit(container);\n }\n return reply;\n }\n const fields = elements.map((el, i) => fieldFromElement(el, i));\n const req: LoginRequest = {\n kind: \"input-form\",\n fields,\n submitLabel: container instanceof HTMLFormElement ? \"Send\" : \"Done\",\n reason: opts?.reason,\n };\n const reply = await session.request(req, opts);\n if (reply.ok && reply.value && typeof reply.value === \"object\") {\n const values = reply.value as Record<string, unknown>;\n for (const el of elements) {\n const name = nameForElement(el, elements.indexOf(el));\n if (name in values) writeValueIntoElement(el, values[name]);\n }\n if (container instanceof HTMLFormElement) tryRequestSubmit(container);\n }\n return reply;\n },\n dispose() {/* no-op */},\n };\n}\n\n// \u2500\u2500\u2500 DOM \u2192 request synthesis \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction inputRequestFromElement(\n el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,\n reason: string | undefined,\n): LoginRequest {\n if (el instanceof HTMLSelectElement) {\n return {\n kind: \"input\",\n inputType: \"select\",\n label: resolveLabel(el),\n options: readOptions(el),\n defaultValue: el.value || undefined,\n required: el.required,\n reason,\n };\n }\n const inputType = resolveInputType(el);\n const base = {\n kind: \"input\" as const,\n inputType,\n label: resolveLabel(el),\n placeholder: el.placeholder || undefined,\n defaultValue: el.value || undefined,\n required: el instanceof HTMLInputElement ? el.required : false,\n reason,\n };\n return {\n ...base,\n ...textConstraints(el),\n ...(el instanceof HTMLInputElement && inputType === \"number\"\n ? numericConstraints(el)\n : {}),\n ...(el instanceof HTMLInputElement && el.pattern\n ? { pattern: el.pattern }\n : {}),\n };\n}\n\nfunction fieldFromElement(\n el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,\n index: number,\n): InputFormField {\n const name = nameForElement(el, index);\n if (el instanceof HTMLSelectElement) {\n return {\n name,\n inputType: \"select\",\n label: resolveLabel(el),\n options: readOptions(el),\n defaultValue: el.value || undefined,\n required: el.required,\n };\n }\n const inputType = resolveInputType(el);\n return {\n name,\n inputType,\n label: resolveLabel(el),\n placeholder: el.placeholder || undefined,\n defaultValue: el.value || undefined,\n required: el instanceof HTMLInputElement ? el.required : false,\n ...textConstraints(el),\n ...(el instanceof HTMLInputElement && inputType === \"number\"\n ? numericConstraints(el)\n : {}),\n ...(el instanceof HTMLInputElement && el.pattern\n ? { pattern: el.pattern }\n : {}),\n };\n}\n\nfunction collectFieldElements(\n container: HTMLElement,\n): Array<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement> {\n const out: Array<\n HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement\n > = [];\n const all = container.querySelectorAll<HTMLElement>(\n \"input, textarea, select\",\n );\n // Filter: skip non-bindable inputs (button, submit, hidden,\n // checkbox, radio, file). Those don't map to the kiosk pattern\n // and would confuse the drawer's prev/next navigation.\n const SKIPPED = new Set([\n \"button\",\n \"submit\",\n \"reset\",\n \"image\",\n \"hidden\",\n \"file\",\n \"checkbox\",\n \"radio\",\n ]);\n for (let i = 0; i < all.length; i++) {\n const el = all[i]!;\n if (isSensitiveField(el)) continue; // passwords / one-time codes stay on this page\n if (el instanceof HTMLInputElement) {\n const t = (el.type || \"text\").toLowerCase();\n if (SKIPPED.has(t)) continue;\n if (el.disabled || el.readOnly) continue;\n out.push(el);\n } else if (el instanceof HTMLTextAreaElement) {\n if (el.disabled || el.readOnly) continue;\n out.push(el);\n } else if (el instanceof HTMLSelectElement) {\n if (el.disabled) continue;\n out.push(el);\n }\n }\n return out;\n}\n\n/**\n * Fields whose value must never travel over the live channel: password\n * inputs and anything marked `autocomplete` current-password /\n * new-password / one-time-code. Anyone who scans a sign-in code first\n * holds the phone end of the channel, so the SDK neither mirrors these\n * values to the phone nor lets the phone fill them: bindInput refuses,\n * bindForm and remote navigation skip them.\n */\nexport function isSensitiveField(el: Element): boolean {\n const tokens = (el.getAttribute(\"autocomplete\") ?? \"\").toLowerCase().split(/\\s+/);\n if (tokens.some((t) => t === \"current-password\" || t === \"new-password\" || t === \"one-time-code\")) return true;\n if (typeof HTMLInputElement !== \"undefined\" && el instanceof HTMLInputElement) {\n return (el.type || \"text\").toLowerCase() === \"password\";\n }\n return (el.getAttribute(\"type\") ?? \"\").toLowerCase() === \"password\";\n}\n\nfunction resolveInputType(\n el: HTMLInputElement | HTMLTextAreaElement,\n): Exclude<InputType, \"select\"> {\n if (el instanceof HTMLTextAreaElement) return \"text\";\n const t = (el.type || \"text\").toLowerCase();\n switch (t) {\n case \"text\":\n case \"search\":\n case \"email\":\n case \"tel\":\n case \"url\":\n case \"number\":\n case \"password\":\n return t as Exclude<InputType, \"select\">;\n // HTML5 types we don't have a wallet-side keyboard for \u2014 fall\n // back to `text` so the drawer still renders something useful.\n case \"date\":\n case \"datetime-local\":\n case \"time\":\n case \"month\":\n case \"week\":\n case \"color\":\n case \"range\":\n default:\n return \"text\";\n }\n}\n\nfunction resolveLabel(\n el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | HTMLButtonElement,\n): string {\n // Priority: aria-label > <label for> > parent <label> text >\n // placeholder > name > tag-name.\n const aria = el.getAttribute(\"aria-label\");\n if (aria && aria.trim()) return aria.trim();\n if (el.id) {\n const lbl = el.ownerDocument.querySelector<HTMLLabelElement>(\n `label[for=\"${cssEscape(el.id)}\"]`,\n );\n if (lbl && lbl.textContent && lbl.textContent.trim()) {\n return lbl.textContent.trim();\n }\n }\n const closestLabel = el.closest(\"label\");\n if (closestLabel && closestLabel.textContent) {\n // Strip the input's own text content from the label string\n // so a wrapping `<label>Email <input></label>` doesn't include\n // the input's value.\n const ownText =\n \"value\" in el && typeof (el as { value?: unknown }).value === \"string\"\n ? (el as { value: string }).value\n : (el.textContent ?? \"\");\n const raw = closestLabel.textContent.replace(ownText, \"\").trim();\n if (raw) return raw;\n }\n if (\n \"placeholder\" in el &&\n (el as HTMLInputElement).placeholder &&\n (el as HTMLInputElement).placeholder.trim()\n ) {\n return (el as HTMLInputElement).placeholder.trim();\n }\n if (el.name) return prettyName(el.name);\n return prettyName(el.tagName.toLowerCase());\n}\n\nfunction readOptions(el: HTMLSelectElement): InputOption[] {\n const out: InputOption[] = [];\n for (let i = 0; i < el.options.length; i++) {\n const opt = el.options[i]!;\n out.push({\n value: opt.value,\n label: opt.label || opt.textContent || opt.value,\n });\n }\n return out;\n}\n\nfunction textConstraints(\n el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,\n): { minLength?: number; maxLength?: number } {\n const out: { minLength?: number; maxLength?: number } = {};\n if (\"minLength\" in el && el.minLength > 0) out.minLength = el.minLength;\n if (\"maxLength\" in el && el.maxLength > 0) out.maxLength = el.maxLength;\n return out;\n}\n\nfunction numericConstraints(\n el: HTMLInputElement,\n): { min?: number; max?: number } {\n const out: { min?: number; max?: number } = {};\n const minStr = el.getAttribute(\"min\");\n const maxStr = el.getAttribute(\"max\");\n if (minStr !== null && minStr !== \"\") {\n const n = Number(minStr);\n if (Number.isFinite(n)) out.min = n;\n }\n if (maxStr !== null && maxStr !== \"\") {\n const n = Number(maxStr);\n if (Number.isFinite(n)) out.max = n;\n }\n return out;\n}\n\nfunction nameForElement(\n el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | HTMLButtonElement,\n index: number,\n): string {\n if (el.name) return el.name;\n if (el.id) return el.id;\n return `_field_${index}`;\n}\n\nfunction prettyName(s: string): string {\n return s.replace(/[_-]+/g, \" \").replace(/\\s+/g, \" \").trim();\n}\n\n// \u2500\u2500\u2500 Byte / encoding helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Decode a base64url-padded chunk string into a fresh `Uint8Array`.\n * Returns null on bad input so the receiver can drop the envelope\n * without crashing. Used by the file-transfer reassembly path \u2014\n * each chunk is decoded once, written into the per-transfer\n * `Uint8Array[]` slot, and the source string is dropped.\n */\nfunction b64uToBytes(s: string): Uint8Array | null {\n // Normalise to standard base64 with padding so `atob` accepts it.\n const pad = (4 - (s.length % 4)) % 4;\n const std = (s + \"=\".repeat(pad)).replace(/-/g, \"+\").replace(/_/g, \"/\");\n try {\n const bin = atob(std);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n } catch {\n return null;\n }\n}\n\n/** Hex-encode a Uint8Array (lowercase, no separators). */\nfunction bytesToHex(b: Uint8Array): string {\n let s = \"\";\n for (let i = 0; i < b.length; i++) s += b[i]!.toString(16).padStart(2, \"0\");\n return s;\n}\n\n// \u2500\u2500\u2500 Reply \u2192 DOM \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction writeValueIntoElement(\n el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,\n value: unknown,\n): void {\n if (value === undefined || value === null) return;\n const str = String(value);\n if (el instanceof HTMLSelectElement) {\n // Match by value first, then by visible label.\n let matched = false;\n for (let i = 0; i < el.options.length; i++) {\n if (el.options[i]!.value === str) {\n el.selectedIndex = i;\n matched = true;\n break;\n }\n }\n if (!matched) {\n for (let i = 0; i < el.options.length; i++) {\n if (el.options[i]!.label === str) {\n el.selectedIndex = i;\n break;\n }\n }\n }\n } else {\n el.value = str;\n }\n // Reactive frameworks (React, Vue, etc.) listen for `input` /\n // `change` to pick up the new value. Dispatch both so we don't\n // miss either bucket.\n el.dispatchEvent(new Event(\"input\", { bubbles: true }));\n el.dispatchEvent(new Event(\"change\", { bubbles: true }));\n}\n\nfunction tryRequestSubmit(form: HTMLFormElement): void {\n // `requestSubmit` runs the form's existing submit handler +\n // validation; `submit` skips both. Always prefer\n // `requestSubmit` when available \u2014 guards against pre-2020\n // browsers via the typeof check.\n if (typeof form.requestSubmit === \"function\") {\n form.requestSubmit();\n } else {\n form.submit();\n }\n}\n\n// \u2500\u2500\u2500 Remote navigation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface RemoteNavController {\n /**\n * Stop pushing focus events to the wallet + stop listening for\n * inbound nav/value/logout commands. The session itself stays\n * live; only the helper detaches.\n */\n dispose(): void;\n}\n\nexport interface RemoteNavOptions {\n /**\n * Root to scan for tabbable inputs. Defaults to `document.body`.\n * Limit to a region (e.g. a checkout form) if the page has\n * unrelated inputs you don't want the wallet to step through.\n */\n root?: HTMLElement;\n /**\n * Override the default tab order. By default we use a generous\n * `:is(input, textarea, select)` filter excluding hidden / disabled\n * / readonly / type=hidden / type=submit. Return your own\n * NodeList-like array to take full control.\n */\n collectFields?: () => Array<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>;\n}\n\n/**\n * Wire up **remote navigation**. Pushes the page's currently-focused\n * input to the wallet (metadata + current value) and applies inbound\n * `nav` / `value` / `logout` commands as the user interacts with the\n * wallet's persistent navigation banner.\n *\n * Wiring summary:\n *\n * * `focusin` on any tabbable input \u2192 `session._sendFocus(focus)`.\n * * `focusout` on the same \u2192 `session._sendFocus(null)`.\n * * `input` on the focused element \u2192 push the new value to the\n * wallet so the phone mirror stays in sync if the user typed on\n * the desktop. Debounced to one frame to avoid flooding.\n * * Inbound `nav: \"prev\" | \"next\"` \u2192 move DOM focus along the\n * tabbable-input order from the focused element.\n * * Inbound `nav: \"submit\"` \u2192 `form.requestSubmit()` on the closest\n * enclosing form.\n * * Inbound `value` \u2192 write to the focused element + dispatch\n * `input` + `change`. Reactive frameworks pick it up.\n * * Inbound `logout` \u2192 session already torn down by the dispatcher;\n * helper just detaches.\n *\n * Call this once after `signIn()` resolves when you passed\n * `remoteNavigation: true`. The returned controller's `dispose()` is\n * idempotent and runs on `signed_out` automatically.\n */\nexport function enableRemoteNavigation(\n session: PrsonLoginSession,\n opts?: RemoteNavOptions,\n): RemoteNavController {\n const root = opts?.root ?? document.body;\n let currentFocused:\n | HTMLInputElement\n | HTMLTextAreaElement\n | HTMLSelectElement\n | HTMLButtonElement\n | null = null;\n let disposed = false;\n\n function isBindable(\n el: Element,\n ): el is HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement {\n // Passwords and one-time codes are never mirrored to the phone.\n if (isSensitiveField(el)) return false;\n if (el instanceof HTMLInputElement) {\n const t = (el.type || \"text\").toLowerCase();\n if (\n t === \"hidden\" || t === \"submit\" || t === \"button\" ||\n t === \"reset\" || t === \"image\" ||\n t === \"checkbox\" || t === \"radio\"\n ) return false;\n // `type=\"file\"` IS bindable \u2014 the wallet shows a picker UI\n // and streams the chosen bytes back. Handled by the\n // file-transfer reassembly path in `_handleMessage`; the\n // `readOnly` check below doesn't apply (file inputs ignore\n // it but expose the property as `false` regardless).\n if (t === \"file\") return !el.disabled;\n return !el.disabled && !el.readOnly;\n }\n if (el instanceof HTMLTextAreaElement) {\n return !el.disabled && !el.readOnly;\n }\n if (el instanceof HTMLSelectElement) {\n return !el.disabled;\n }\n return false;\n }\n\n /** Buttons + button-type inputs. Tracked separately from\n * [isBindable] so prev/next navigation only walks the\n * input-like pool, but focus envelopes still fire for buttons\n * (so the wallet can show the Enter row). */\n function isFocusableButton(\n el: Element,\n ): el is HTMLButtonElement | HTMLInputElement {\n if (el instanceof HTMLButtonElement) return !el.disabled;\n if (el instanceof HTMLInputElement) {\n const t = (el.type || \"text\").toLowerCase();\n return (t === \"submit\" || t === \"button\" || t === \"reset\") && !el.disabled;\n }\n return el.getAttribute(\"role\") === \"button\";\n }\n\n function collectFields(): Array<\n HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement\n > {\n if (opts?.collectFields) return opts.collectFields().filter((el) => !isSensitiveField(el));\n const out: Array<\n HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement\n > = [];\n const all = root.querySelectorAll<HTMLElement>(\"input, textarea, select\");\n for (let i = 0; i < all.length; i++) {\n const el = all[i]!;\n if (isBindable(el)) out.push(el);\n }\n return out;\n }\n\n /**\n * Compute the prev / next / submit / enter visibility hints the\n * wallet's banner drawer needs to render only the buttons that\n * make sense for the page's current state.\n *\n * Rules (mirrored on the wallet \u2014 see `_navigationRow`):\n *\n * * `hasPrev` \u2014 there's at least one bindable input *before*\n * this one in the tabbing pool.\n * * `hasNext` \u2014 there's at least one bindable input *after*\n * this one.\n * * `isLastInForm`\u2014 this element is the last bindable input\n * inside its enclosing `<form>`. Mutually\n * exclusive with `hasNext` when the form\n * ends the bindable pool; only true for input-\n * like elements, never for buttons.\n * * `isButton` \u2014 the focused element is a click target\n * (`<button>`, `<input type=submit|button>`,\n * `role=\"button\"`). The wallet shows an\n * \"Enter\" button that dispatches `nav: \"submit\"`,\n * and the helper here treats that action as a\n * synthetic click rather than a form submit.\n */\n function computeNavMeta(\n el: Element,\n ): { hasPrev: boolean; hasNext: boolean; isLastInForm: boolean; isButton: boolean } {\n const isButton =\n el instanceof HTMLButtonElement ||\n (el instanceof HTMLInputElement &&\n (el.type === \"submit\" || el.type === \"button\" || el.type === \"reset\")) ||\n el.getAttribute(\"role\") === \"button\";\n if (isButton) {\n // A focused button has no concept of \"prev/next input\" \u2014 the\n // wallet hides those rows entirely and shows just Enter.\n return { hasPrev: false, hasNext: false, isLastInForm: false, isButton: true };\n }\n const fields = collectFields();\n const idx = fields.indexOf(el as HTMLInputElement);\n const hasPrev = idx > 0;\n const hasNext = idx >= 0 && idx < fields.length - 1;\n let isLastInForm = false;\n const form = (el as HTMLElement).closest?.(\"form\");\n if (form instanceof HTMLFormElement) {\n const fieldsInForm = fields.filter((f) => f.closest(\"form\") === form);\n isLastInForm =\n fieldsInForm.length > 0 &&\n fieldsInForm[fieldsInForm.length - 1] === el;\n }\n return { hasPrev, hasNext, isLastInForm, isButton: false };\n }\n\n function focusPayloadFor(\n el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | HTMLButtonElement,\n ): Parameters<PrsonLoginSession[\"_sendFocus\"]>[0] {\n const name = nameForElement(el, 0);\n const meta = computeNavMeta(el);\n if (el instanceof HTMLButtonElement || (el instanceof HTMLInputElement &&\n (el.type === \"submit\" || el.type === \"button\" || el.type === \"reset\"))) {\n // Button focus \u2014 the wallet renders just the Enter row.\n return {\n name,\n label: resolveLabel(el),\n inputType: \"button\",\n value: el instanceof HTMLButtonElement ? (el.textContent ?? \"\").trim() : (el as HTMLInputElement).value,\n ...meta,\n };\n }\n if (el instanceof HTMLSelectElement) {\n return {\n name,\n label: resolveLabel(el),\n inputType: \"select\",\n value: el.value,\n options: readOptions(el),\n required: el.required,\n ...meta,\n };\n }\n if (el instanceof HTMLInputElement && el.type === \"file\") {\n // File picker: surface `accept` / `multiple` / `capture` so the\n // wallet UI can render the right entry points (camera vs\n // gallery vs files) and validate the user's pick against the\n // host's MIME filter. Value stays empty \u2014 we don't try to\n // mirror the picked-file metadata back as text.\n return {\n name,\n label: resolveLabel(el),\n inputType: \"file\",\n value: \"\",\n required: el.required,\n accept: el.accept || undefined,\n multiple: el.multiple || undefined,\n capture: el.getAttribute(\"capture\") || undefined,\n ...meta,\n };\n }\n const inputType = resolveInputType(el);\n return {\n name,\n label: resolveLabel(el),\n inputType,\n value: el.value,\n placeholder:\n \"placeholder\" in el ? (el as HTMLInputElement).placeholder || undefined : undefined,\n required: el instanceof HTMLInputElement ? el.required : false,\n ...textConstraints(el),\n ...(el instanceof HTMLInputElement && inputType === \"number\"\n ? numericConstraints(el)\n : {}),\n ...(el instanceof HTMLInputElement && el.pattern\n ? { pattern: el.pattern }\n : {}),\n ...meta,\n };\n }\n\n // Debounced \"current value changed locally\" notifier \u2014 keeps the\n // wallet mirror in sync if the user types on the desktop while the\n // wallet drawer is open. requestAnimationFrame caps push rate\n // at ~60 Hz which is well below the wallet's processing budget.\n let pendingFrame: number | null = null;\n function scheduleValuePush() {\n if (pendingFrame !== null) return;\n pendingFrame = requestAnimationFrame(() => {\n pendingFrame = null;\n if (disposed || !currentFocused) return;\n void session._sendFocus(focusPayloadFor(currentFocused));\n });\n }\n\n function onFocusIn(ev: Event) {\n const t = ev.target;\n if (!(t instanceof Element)) return;\n if (isSensitiveField(t)) {\n // Focus moved to a password / one-time code: clear the phone's\n // mirror, and don't let a `value` from the phone land here.\n if (currentFocused) void session._sendFocus(null);\n currentFocused = null;\n return;\n }\n if (isBindable(t)) {\n currentFocused = t;\n void session._sendFocus(focusPayloadFor(t));\n return;\n }\n if (isFocusableButton(t)) {\n currentFocused = t as HTMLButtonElement | HTMLInputElement;\n void session._sendFocus(focusPayloadFor(t as HTMLButtonElement));\n }\n }\n\n function onFocusOut(ev: Event) {\n const t = ev.target;\n if (t !== currentFocused) return;\n currentFocused = null;\n void session._sendFocus(null);\n }\n\n function onInputChange(ev: Event) {\n if (ev.target !== currentFocused) return;\n scheduleValuePush();\n }\n\n function applyNav(action: \"prev\" | \"next\" | \"submit\") {\n if (action === \"submit\") {\n // Two semantics on one wire action:\n //\n // * focused element IS a button \u2192 click it. Wallet shows\n // this as \"Enter\" when [isButton: true] in the focus\n // envelope, and the user expects pressing it on the\n // phone to fire the button's click handler.\n // * else \u2192 submit the enclosing form. Wallet shows this as\n // \"Submit\" when [isLastInForm: true].\n //\n // We use one nav action for both so the wire grammar stays\n // narrow; the contextual UX is decided on the wallet side\n // (different label / icon) and the dispatch routes correctly\n // by inspecting `currentFocused`.\n const focused = currentFocused;\n if (\n focused instanceof HTMLButtonElement ||\n (focused instanceof HTMLInputElement &&\n (focused.type === \"submit\" ||\n focused.type === \"button\" ||\n focused.type === \"reset\")) ||\n focused?.getAttribute(\"role\") === \"button\"\n ) {\n try {\n (focused as HTMLElement).click();\n } catch {\n /* swallow */\n }\n return;\n }\n const form =\n currentFocused?.closest(\"form\") ?? root.querySelector(\"form\");\n if (form instanceof HTMLFormElement) tryRequestSubmit(form);\n return;\n }\n const fields = collectFields();\n if (fields.length === 0) return;\n let idx = currentFocused ? fields.indexOf(currentFocused as never) : -1;\n if (idx === -1) idx = action === \"prev\" ? fields.length : -1;\n const target =\n action === \"next\"\n ? fields[(idx + 1) % fields.length]!\n : fields[(idx - 1 + fields.length) % fields.length]!;\n target.focus();\n if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {\n const len = target.value.length;\n try { target.setSelectionRange(len, len); } catch { /* select-type inputs don't support it */ }\n }\n }\n\n function applyValue(value: string) {\n if (!currentFocused || isSensitiveField(currentFocused)) return;\n // Value pushes only make sense for input-like fields. If a\n // button is focused (no editable value) just drop the push.\n if (\n currentFocused instanceof HTMLInputElement ||\n currentFocused instanceof HTMLTextAreaElement ||\n currentFocused instanceof HTMLSelectElement\n ) {\n writeValueIntoElement(currentFocused, value);\n }\n }\n\n const unsubscribe = session._setRemoteNavListener((envelope) => {\n if (envelope.msg === \"nav\") applyNav(envelope.action);\n else if (envelope.msg === \"value\") applyValue(envelope.value);\n else if (envelope.msg === \"logout\") dispose();\n });\n\n // \u2500\u2500 File-transfer reassembly \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n //\n // The wallet streams chunks for a chosen file as a sequence of\n // `file-begin` \u2192 N \u00D7 `file-chunk` \u2192 `file-end` envelopes,\n // correlated by `requestId`. We keep ONE pending transfer per id\n // and never materialise the whole file as a contiguous buffer \u2014\n // each chunk's bytes go straight onto an Array<Uint8Array>; the\n // final assembly is `new Blob(parts)` which the browser doesn't\n // copy. The SHA-256 verifier runs incrementally over the same\n // Uint8Array references via WebCrypto's `crypto.subtle.digest`\n // on the assembled Blob's ArrayBuffer (single allocation only at\n // the verify-then-discard moment).\n //\n // Memory profile (per in-flight transfer): ~`size` bytes total\n // (the Uint8Arrays for chunks), plus an Array<Uint8Array> header.\n // No double buffering, no string-side base64 retained beyond\n // each chunk's decode-then-drop cycle.\n interface PendingTransfer {\n name: string;\n mimeType: string;\n size: number;\n totalChunks: number;\n received: number;\n parts: Uint8Array[];\n targetInput: HTMLInputElement | null;\n }\n const transfers = new Map<string, PendingTransfer>();\n\n const offFile = session._setFileEnvelopeHandler((envelope) => {\n const reqId = envelope.requestId;\n if (!reqId) return;\n if (envelope.msg === \"file-begin\") {\n const begin = envelope.fileBegin;\n if (!begin) return;\n // Resolve the target input AT BEGIN time so a focusout that\n // races the transfer doesn't leave us assigning to a\n // disposed element.\n const target =\n currentFocused instanceof HTMLInputElement && currentFocused.type === \"file\"\n ? currentFocused\n : null;\n transfers.set(reqId, {\n name: begin.name,\n mimeType: begin.mimeType,\n size: begin.size,\n totalChunks: begin.totalChunks,\n received: 0,\n parts: new Array<Uint8Array>(begin.totalChunks),\n targetInput: target,\n });\n return;\n }\n if (envelope.msg === \"file-chunk\") {\n const xfer = transfers.get(reqId);\n const chunk = envelope.fileChunk;\n if (!xfer || !chunk) return;\n const bytes = b64uToBytes(chunk.data);\n if (!bytes) return;\n // Slot the chunk in by index \u2014 chunks arrive in order through\n // the ack-tracked layer but indexing defensively keeps the\n // contract obvious to a reader (and would survive a future\n // sliding-window sender).\n xfer.parts[chunk.index] = bytes;\n xfer.received += 1;\n return;\n }\n if (envelope.msg === \"file-end\") {\n const xfer = transfers.get(reqId);\n const end = envelope.fileEnd;\n if (!xfer || !end) return;\n transfers.delete(reqId);\n void assembleAndCommit(xfer, end.sha256);\n return;\n }\n });\n\n async function assembleAndCommit(\n xfer: PendingTransfer,\n expectedSha256Hex: string,\n ): Promise<void> {\n if (xfer.received !== xfer.totalChunks) return;\n // Blob does NOT copy its parts; this is the only assembly step.\n // The `as unknown as BlobPart[]` cast sidesteps an over-strict\n // type definition where `Uint8Array<ArrayBufferLike>` is not\n // recognised as `BlobPart` even though it always is at runtime.\n const blob = new Blob(xfer.parts as unknown as BlobPart[], { type: xfer.mimeType });\n // Verify SHA-256. `crypto.subtle.digest` runs over the Blob's\n // ArrayBuffer \u2014 one transient allocation, then the buffer is\n // released back to the GC.\n const buf = await blob.arrayBuffer();\n const digestBuf = await crypto.subtle.digest(\"SHA-256\", buf);\n const actual = bytesToHex(new Uint8Array(digestBuf));\n if (actual !== expectedSha256Hex.toLowerCase()) {\n // Hash mismatch \u2014 drop silently. A future revision can\n // surface this to the host via an event; today the wallet's\n // ack-tracked retransmit covers the common error case (a\n // dropped chunk).\n return;\n }\n const target = xfer.targetInput;\n if (!target || disposed) return;\n const file = new File([blob], xfer.name, {\n type: xfer.mimeType,\n lastModified: Date.now(),\n });\n // `HTMLInputElement.files` is read-only by default \u2014 the\n // standard idiom is to build a `DataTransfer`, attach the\n // file(s), and assign the `.files` reference.\n try {\n const dt = new DataTransfer();\n dt.items.add(file);\n target.files = dt.files;\n } catch {\n // Browsers without `DataTransfer` (very old) can't accept a\n // programmatic file. Nothing else we can do.\n return;\n }\n // Dispatch `input` + `change` so reactive frameworks pick the\n // selection up. Bubbles + cancelable matches the native\n // dispatch profile.\n target.dispatchEvent(new Event(\"input\", { bubbles: true }));\n target.dispatchEvent(new Event(\"change\", { bubbles: true }));\n }\n\n // `signed_out` cleanup \u2014 the dispatcher's `logout` case also tears\n // the session down; this catches every other terminal path (TTL,\n // wallet-side revoke, transport loss).\n const offSignedOut = session.on(\"signed_out\", () => dispose());\n\n root.addEventListener(\"focusin\", onFocusIn, true);\n root.addEventListener(\"focusout\", onFocusOut, true);\n root.addEventListener(\"input\", onInputChange, true);\n root.addEventListener(\"change\", onInputChange, true);\n\n function dispose() {\n if (disposed) return;\n disposed = true;\n if (pendingFrame !== null) cancelAnimationFrame(pendingFrame);\n pendingFrame = null;\n root.removeEventListener(\"focusin\", onFocusIn, true);\n root.removeEventListener(\"focusout\", onFocusOut, true);\n root.removeEventListener(\"input\", onInputChange, true);\n root.removeEventListener(\"change\", onInputChange, true);\n unsubscribe();\n offFile();\n offSignedOut();\n transfers.clear();\n }\n\n return { dispose };\n}\n\n// \u2500\u2500\u2500 Mouse / virtual cursor \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Options for [`bindMouse`].\n */\nexport interface BindMouseOptions extends RequestOptions {\n /**\n * Input mode the wallet should default to. The wallet UI may still\n * surface a toggle to switch mid-session \u2014 frames received then\n * carry the actual mode in `mouse.mode`. Defaults to `\"touch\"`.\n */\n mode?: \"touch\" | \"magic\";\n /** Cursor diameter in CSS pixels. Default 28. */\n size?: number;\n /**\n * Cursor background colour (any CSS colour). Default a translucent\n * blue that's visible on both light and dark pages.\n */\n color?: string;\n /**\n * Optional reason shown in the wallet drawer (\"Tap to control the\n * page\", etc.).\n */\n reason?: string;\n /**\n * Initial cursor position. Defaults to viewport centre. Pass\n * `{ x: 0, y: 0 }` to anchor in the top-left.\n */\n initialPosition?: { x: number; y: number };\n /**\n * Optional callback fired on every applied frame. Useful for\n * sites that want to highlight the hovered element or show a\n * trail. Receives the cursor's new viewport coordinates.\n */\n onMove?: (pos: { x: number; y: number }) => void;\n /**\n * Optional click handler \u2014 receives the element under the cursor\n * at the moment of the click. The default behaviour (dispatching\n * a synthetic `click` event on that element) still runs unless\n * the callback returns `false`.\n */\n onClick?: (target: Element | null) => void | boolean;\n}\n\n/**\n * Bind a virtual mouse to the session. Opens a `kind: \"mouse\"`\n * request on the wallet, then subscribes to the streamed\n * `mouse-update` envelopes and applies them to a CSS-positioned\n * cursor on top of the page.\n *\n * Two modes (the wallet may toggle them mid-session):\n *\n * * `\"touch\"` \u2014 the phone is a touchpad. Drag = move (delta in\n * CSS px), tap = click, double-tap = double-click, two-finger\n * drag = scroll.\n * * `\"magic\"` \u2014 phone gyro + accelerometer drive a \"magic wand\".\n * Tap on the phone = click; swipe up/down = scroll.\n *\n * The cursor is a `<div>` fixed-positioned at z-index `2147483647`\n * (the max 32-bit signed int \u2014 same trick browser extension\n * overlays use to outrank page chrome). `pointer-events: none` so\n * it never intercepts real clicks; we use `elementFromPoint` +\n * synthetic events to forward clicks to the page underneath.\n *\n * Returns a [`BindController`] \u2014 call `dispose()` to detach the\n * cursor and stop applying frames. The wallet drawer stays open\n * until the user closes it; disposing the controller silently\n * drops further frames but doesn't tell the wallet to stop.\n *\n * @example\n * const mouse = bindMouse(session, { mode: \"touch\" });\n * await mouse.request();\n * // later\n * mouse.dispose();\n */\nexport function bindMouse(\n session: PrsonLoginSession,\n opts?: BindMouseOptions,\n): BindController {\n const mode = opts?.mode ?? \"touch\";\n const size = Math.max(6, opts?.size ?? 28);\n const color = opts?.color ?? \"rgba(59, 130, 246, 0.65)\";\n const onMove = opts?.onMove;\n const onClick = opts?.onClick;\n\n // DOM-side state. The cursor element is created lazily on the\n // first `request()` call so a host that builds the controller\n // up-front but never calls request doesn't pollute the page.\n let cursor: HTMLDivElement | null = null;\n let pos = opts?.initialPosition ?? {\n x: typeof window !== \"undefined\" ? window.innerWidth / 2 : 0,\n y: typeof window !== \"undefined\" ? window.innerHeight / 2 : 0,\n };\n let disposed = false;\n /**\n * The currently-previewed snap target, if any. Only populated\n * while magic mode is active \u2014 every move frame finds the\n * nearest interactive element and rewires this state so the\n * page can style \"what would be clicked if I tapped now\":\n *\n * [data-prson-magic-snap] { outline: 2px solid #3b82f6; }\n *\n * The data-attribute is the public contract; the corresponding\n * class is added too as a convenience for selector-shy host\n * stylesheets. Cleared on dispose / mode-change so a left-over\n * highlight can't outlive the controller.\n */\n let snapTarget: Element | null = null;\n /** Active mode for the current frame stream \u2014 kept in sync with\n * `mouse.mode` on every applied envelope so snap-preview turns\n * itself off when the wallet flips back to touch. */\n let activeMode: \"touch\" | \"magic\" = mode;\n\n // Install the ambient mouse-update handler so wallet-initiated\n // streams (the pre-grant flow \u2014 `signIn({mouseControl: true})`)\n // land on `applyFrame` even when there's no pending\n // `requestMouse` promise to key the subscriber by. `bindMouse`\n // owns the handler for its lifetime; `dispose()` removes it.\n // The handler is installed eagerly (not on first `request()`) so\n // the wallet can start streaming the moment the user taps\n // Touchpad / Magic on the banner drawer \u2014 even if the host hasn't\n // called `.request()` at all.\n // Window focus \u2192 `control-status` for the wallet. When the page\n // tab loses focus the wallet drops into a \"Remote control paused\"\n // state so the user can see, on the phone, that motion isn't\n // landing anywhere. Listeners are torn down in `detach()`.\n function onWindowBlur(): void {\n if (disposed) return;\n void session._sendControlStatus(true);\n }\n function onWindowFocus(): void {\n if (disposed) return;\n void session._sendControlStatus(false);\n // Real OS focus also implies the user is back at the keyboard\n // \u2192 drop the \"point your phone\" hint if it was still up.\n closePointPhoneOverlay();\n }\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"blur\", onWindowBlur);\n window.addEventListener(\"focus\", onWindowFocus);\n // Initial state \u2014 fire once so a session created while the tab\n // is hidden lands on the wallet correctly.\n if (typeof document !== \"undefined\" && document.hasFocus && !document.hasFocus()) {\n void session._sendControlStatus(true);\n }\n }\n\n const offAmbient = session._setAmbientMouseHandler((mouseBody) => {\n if (disposed) return;\n // `begin` / `end` are protocol pairing tokens \u2014 they just need to\n // make sure the cursor element exists (so the first real `move`\n // frame doesn't race the lazy initialiser) and are otherwise\n // no-ops. **Every other event** \u2014 including the visibility\n // toggles `show` / `hide` \u2014 must be forwarded to `applyFrame`,\n // which is what opens / closes the \"point your phone\" overlay\n // and re-centres the cursor on resume.\n if (mouseBody.event === \"begin\" || mouseBody.event === \"end\") {\n ensureCursor();\n return;\n }\n applyFrame(mouseBody);\n });\n\n function ensureCursor(): HTMLDivElement {\n if (cursor) return cursor;\n // Dedupe across multiple `bindMouse` calls. If another instance\n // already created a cursor (e.g. the long-lived ambient bind\n // from sign-in + a per-request bind from a host button click),\n // adopt the existing element instead of stacking a second one.\n // We still own its position state from this controller \u2014 the\n // last `bindMouse` to call `ensureCursor` becomes the visible\n // owner. (Prior owners just stop applying frames.)\n const existing = document.querySelector<HTMLDivElement>(\n '[data-prson-virtual-cursor]',\n );\n if (existing) {\n cursor = existing;\n // Update size/colour to match our opts so a second mount can\n // restyle the cursor without flicker.\n existing.style.width = `${size}px`;\n existing.style.height = `${size}px`;\n existing.style.background = color;\n existing.style.display = \"block\";\n applyCursorPosition(existing, pos);\n return existing;\n }\n const el = document.createElement(\"div\");\n el.setAttribute(\"data-prson-virtual-cursor\", \"\");\n el.style.position = \"fixed\";\n el.style.width = `${size}px`;\n el.style.height = `${size}px`;\n el.style.borderRadius = \"50%\";\n el.style.background = color;\n el.style.border = \"2px solid rgba(255, 255, 255, 0.9)\";\n el.style.boxShadow = \"0 2px 8px rgba(0, 0, 0, 0.25)\";\n el.style.pointerEvents = \"none\";\n el.style.zIndex = \"2147483647\";\n el.style.transform = \"translate(-50%, -50%)\";\n el.style.transition = \"background 120ms ease, opacity 120ms ease\";\n applyCursorPosition(el, pos);\n document.body.appendChild(el);\n cursor = el;\n return el;\n }\n\n function applyCursorPosition(el: HTMLDivElement, p: { x: number; y: number }) {\n el.style.left = `${p.x}px`;\n el.style.top = `${p.y}px`;\n }\n\n function clamp(value: number, min: number, max: number): number {\n return value < min ? min : value > max ? max : value;\n }\n\n function setSnapTarget(next: Element | null): void {\n if (next === snapTarget) return;\n if (snapTarget) {\n snapTarget.removeAttribute(\"data-prson-magic-snap\");\n (snapTarget as Element).classList.remove(\"prson-magic-snap\");\n }\n snapTarget = next;\n if (snapTarget) {\n snapTarget.setAttribute(\"data-prson-magic-snap\", \"\");\n (snapTarget as Element).classList.add(\"prson-magic-snap\");\n }\n }\n\n function applyFrame(mouse: NonNullable<import(\"./crypto.js\").DecryptedEnvelope[\"mouse\"]>): void {\n if (disposed) return;\n const el = ensureCursor();\n // The wallet may toggle mode mid-stream. Track the active mode\n // here so move frames know whether to maintain the snap-target\n // highlight (magic) or drop it (touch).\n if (mouse.mode === \"touch\" || mouse.mode === \"magic\") {\n if (mouse.mode !== activeMode) {\n activeMode = mouse.mode;\n if (activeMode === \"touch\") setSnapTarget(null);\n }\n }\n switch (mouse.event) {\n case \"move\": {\n pos = {\n x: clamp(pos.x + (mouse.dx ?? 0), 0, window.innerWidth),\n y: clamp(pos.y + (mouse.dy ?? 0), 0, window.innerHeight),\n };\n applyCursorPosition(el, pos);\n if (onMove) {\n try { onMove(pos); } catch { /* swallow */ }\n }\n // Magic-mode snap preview. Refreshed on every move frame so\n // the highlight tracks the cursor. The DOM query + N rect\n // measurements run at most once per browser repaint\n // (`mouse-update` is already wallet-throttled to ~60 Hz),\n // which is acceptable on every page we ship for.\n if (activeMode === \"magic\") {\n if (isSelectOverlayActive()) {\n // Page-side highlight stays cleared; the snap visual\n // lives inside the overlay's own shadow root (the page\n // can't reach it, and the page's selector can't\n // accidentally override the option styling).\n setSnapTarget(null);\n setOverlaySnap(findNearestClickableInOverlay(pos.x, pos.y));\n } else {\n setOverlaySnap(null);\n setSnapTarget(findNearestClickable(pos.x, pos.y));\n }\n }\n break;\n }\n case \"click\":\n case \"double-click\": {\n // Visual feedback \u2014 briefly pulse the cursor so the user\n // sees the click landed even if the underlying element\n // doesn't repaint.\n const prev = el.style.background;\n el.style.background = \"rgba(59, 130, 246, 1)\";\n setTimeout(() => { if (cursor === el) el.style.background = prev; }, 140);\n // Custom-overlay route. While a select overlay is open the\n // page beneath is non-interactive \u2014 clicks land ONLY on\n // overlay elements (close button, page-up / page-down,\n // option buttons). The overlay's shadow-DOM listener\n // handles the actual semantics (close vs. paginate vs.\n // commit option); we just need to dispatch a click event\n // on the right inner element.\n if (isSelectOverlayActive()) {\n const overlayTarget =\n (snapTarget && (snapTarget as Element).closest?.(\n \"[data-prson-select-close],[data-prson-select-page],[data-prson-select-option]\",\n )) ??\n findNearestClickableInOverlay(pos.x, pos.y);\n if (overlayTarget) {\n const init: MouseEventInit = {\n bubbles: true,\n cancelable: true,\n composed: true,\n clientX: pos.x,\n clientY: pos.y,\n view: window,\n };\n overlayTarget.dispatchEvent(new MouseEvent(\"mousedown\", init));\n overlayTarget.dispatchEvent(new MouseEvent(\"mouseup\", init));\n overlayTarget.dispatchEvent(new MouseEvent(\"click\", init));\n }\n break;\n }\n // Click-area enlargement: a virtual cursor is harder to land\n // precisely than a touch finger or a mouse, especially for a\n // gyro-driven wand. Search for the NEAREST interactive\n // element within [SNAP_RADIUS_PX] of the cursor and target\n // that, even if the cursor isn't strictly on top of it.\n // Falls back to whatever's at the cursor coordinate when no\n // candidate is within range (so clicks on free space, scroll\n // areas, etc. still work normally).\n //\n // Magic mode already maintains `snapTarget` via the move-\n // frame preview; touch mode skips the highlight but still\n // gets snap-on-click. Re-query in touch mode so the click\n // semantic stays identical across modes.\n const snapped =\n activeMode === \"magic\"\n ? snapTarget\n : findNearestClickable(pos.x, pos.y);\n // Native <select>s open an OS-drawn list that the virtual\n // cursor can't reach. Replace the click with a custom\n // shadow-DOM overlay the cursor CAN drive.\n if (snapped instanceof HTMLSelectElement) {\n openSelectOverlay(snapped);\n // Clear the page-side snap highlight on the select so the\n // overlay's own snap visuals take over cleanly.\n setSnapTarget(null);\n break;\n }\n const direct = document.elementFromPoint(pos.x, pos.y);\n const target = snapped ?? direct;\n // When we snapped, dispatch at the SNAPPED element's centre\n // so any positional logic inside the page (e.g. a custom\n // dropdown computing position from `clientX`) sees a hit\n // ON the element rather than in dead space next to it.\n const clickPoint = snapped\n ? rectCenter((snapped as Element).getBoundingClientRect())\n : { x: pos.x, y: pos.y };\n let allowDefault: boolean = true;\n if (onClick) {\n try {\n const ret = onClick(target);\n if (ret === false) allowDefault = false;\n } catch { /* swallow */ }\n }\n if (allowDefault && target) {\n const init: MouseEventInit = {\n bubbles: true,\n cancelable: true,\n clientX: clickPoint.x,\n clientY: clickPoint.y,\n view: window,\n };\n target.dispatchEvent(new MouseEvent(\"mousedown\", init));\n target.dispatchEvent(new MouseEvent(\"mouseup\", init));\n target.dispatchEvent(new MouseEvent(\"click\", init));\n if (mouse.event === \"double-click\") {\n target.dispatchEvent(new MouseEvent(\"dblclick\", init));\n }\n // Inputs and other focusable elements don't always auto-\n // focus from synthetic `mousedown`. Explicitly focus the\n // snapped target so the page sees the same focus state it\n // would after a real touch.\n if (\n snapped &&\n typeof (target as HTMLElement).focus === \"function\"\n ) {\n try {\n (target as HTMLElement).focus({ preventScroll: true });\n } catch {\n /* swallow \u2014 some host elements throw on focus */\n }\n }\n }\n break;\n }\n case \"scroll\": {\n // `dy` matches WheelEvent.deltaY \u2014 positive = scroll down.\n window.scrollBy({ left: mouse.dx ?? 0, top: mouse.dy ?? 0 });\n break;\n }\n case \"hide\": {\n // Wallet's pose detector says the phone is no longer\n // pointing at the screen. Pull the cursor off the page so\n // the user gets immediate feedback, and surface a soft\n // blue-glow + \"point your phone\" pill so they know how to\n // resume. The overlay auto-dismisses after 15 s or on real\n // OS mouse movement (whichever first).\n if (cursor) {\n cursor.style.opacity = \"0\";\n cursor.style.pointerEvents = \"none\";\n }\n setSnapTarget(null);\n setOverlaySnap(null);\n openPointPhoneOverlay();\n break;\n }\n case \"show\": {\n // Wand pose restored \u2014 bring the cursor back and clear the\n // \"point your phone\" hint regardless of which trigger\n // (timeout / mousemove / show) wins the race.\n //\n // **Re-centre the cursor.** After a pause the user has lost\n // mental track of where the cursor was; pinning it at the\n // viewport centre gives them a known starting point and\n // matches the \"wand on / wand off\" mental model (each\n // session begins at the middle). Position resets via\n // `applyCursorPosition` so subsequent move frames integrate\n // from the centre.\n const el = ensureCursor();\n el.style.opacity = \"1\";\n if (typeof window !== \"undefined\") {\n pos = {\n x: window.innerWidth / 2,\n y: window.innerHeight / 2,\n };\n applyCursorPosition(el, pos);\n }\n closePointPhoneOverlay();\n break;\n }\n case \"begin\":\n case \"end\": {\n // Wallet-side stream lifecycle markers (pre-grant flow).\n // Nothing for the cursor renderer to do \u2014 `_setAmbientMouseHandler`\n // already calls `ensureCursor()` on these so a real `move`\n // frame doesn't race the lazy initialiser.\n break;\n }\n }\n }\n\n function detach() {\n if (cursor) {\n cursor.remove();\n cursor = null;\n }\n // Clear any lingering magic-mode highlight so the page doesn't\n // keep a `data-prson-magic-snap` attribute on whichever input\n // happened to be the last preview target.\n setSnapTarget(null);\n setOverlaySnap(null);\n // Close any active select overlay so a disposing cursor doesn't\n // leave the dropdown orphaned on the page.\n closeAllOverlays();\n closePointPhoneOverlay();\n // Drop window-focus listeners so a torn-down controller doesn't\n // keep pushing control-status envelopes onto a closed channel.\n if (typeof window !== \"undefined\") {\n window.removeEventListener(\"blur\", onWindowBlur);\n window.removeEventListener(\"focus\", onWindowFocus);\n }\n // Tear down the ambient subscription so the session stops\n // holding a ref to our (now-disposed) handler.\n offAmbient();\n }\n\n return {\n async request(callerOpts) {\n if (disposed) return { ok: false, error: \"session-closed\" };\n ensureCursor();\n // `requestMouse` atomically registers the subscriber under the\n // requestId before the envelope leaves the wire, so the very\n // first `mouse-update` frame can never race ahead of us. The\n // session also drops the subscriber on the terminating\n // `response` so we don't need to manage that side ourselves.\n // Mouse requests stay open as long as the user is driving the\n // wallet's controller \u2014 that can easily be longer than the\n // generic `request()` default of 60 s. Pick the smaller of\n // (a) the session's hard expiry and (b) the `setTimeout`\n // int32 ceiling (~24.8 days). The credential's exp can sit\n // weeks out, but `setTimeout(fn, > 2^31-1)` overflows and\n // fires on the next tick \u2014 exactly the bug that caused\n // `bindMouse` to resolve with `error: \"timeout\"` the moment\n // it was awaited.\n const MAX_SAFE_TIMEOUT = 2_147_483_000;\n const credentialBudget = session.expiresAt - Date.now() + 1_000;\n const sessionEndMs = Math.max(\n 60_000,\n Math.min(credentialBudget, MAX_SAFE_TIMEOUT),\n );\n const reply = await session.requestMouse(\n { kind: \"mouse\", mode, reason: callerOpts?.reason ?? opts?.reason },\n applyFrame,\n { timeoutMs: sessionEndMs, ...callerOpts },\n );\n // Drawer closed (or timed out) \u2014 pull the cursor off the page\n // so it doesn't sit there orphaned. Host can call request()\n // again to spawn another session.\n if (!disposed) {\n if (cursor) {\n cursor.remove();\n cursor = null;\n }\n }\n return reply;\n },\n dispose() {\n disposed = true;\n detach();\n },\n };\n}\n\n// \u2500\u2500\u2500 Click-area enlargement (virtual-cursor snap) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// CSS selector covering every realistic click target on a page \u2014\n// form controls + anchor-style affordances. The query runs once per\n// click (low frequency relative to move frames), so the cost is\n// acceptable even on a long page; we do NOT walk the DOM on every\n// move frame.\nconst SNAP_SELECTOR =\n 'input:not([type=\"hidden\"]):not([disabled]),' +\n 'textarea:not([disabled]),' +\n 'select:not([disabled]),' +\n 'button:not([disabled]),' +\n 'a[href],' +\n '[role=\"button\"],' +\n '[role=\"link\"],' +\n '[role=\"checkbox\"],' +\n '[role=\"radio\"],' +\n 'label[for],' +\n '[tabindex]:not([tabindex=\"-1\"])';\n\n/** Snap radius in CSS pixels. A click further than this from any\n * interactive element falls through to whatever's at the cursor\n * coordinate. Tuned so a comfortable wand flick lands in the\n * right input without over-reaching across the page. */\nconst SNAP_RADIUS_PX = 60;\n\nfunction rectCenter(r: DOMRect): { x: number; y: number } {\n return { x: r.left + r.width / 2, y: r.top + r.height / 2 };\n}\n\n/**\n * Find the closest interactive element to the cursor whose bounding\n * box lies within [SNAP_RADIUS_PX]. Distance is measured to the\n * nearest edge of the element's rect (0 if inside), so wide elements\n * \"win\" over narrow ones at the same centre distance. Returns null\n * when nothing qualifies \u2014 the caller then falls back to\n * `document.elementFromPoint`.\n *\n * If multiple inputs sit equally close (tie), the one earliest in\n * the DOM wins \u2014 `querySelectorAll` iterates in document order, so\n * the strictly-less-than comparison preserves it.\n */\nfunction findNearestClickable(x: number, y: number): Element | null {\n if (typeof document === \"undefined\") return null;\n const candidates = document.querySelectorAll(SNAP_SELECTOR);\n let best: Element | null = null;\n let bestDist = Infinity;\n for (const el of Array.from(candidates)) {\n const rect = (el as Element).getBoundingClientRect();\n if (rect.width === 0 || rect.height === 0) continue; // hidden / collapsed\n // Distance from (x,y) to rect: 0 if inside, else Euclidean from\n // the nearest edge / corner.\n const dx = x < rect.left ? rect.left - x : x > rect.right ? x - rect.right : 0;\n const dy = y < rect.top ? rect.top - y : y > rect.bottom ? y - rect.bottom : 0;\n const dist = Math.sqrt(dx * dx + dy * dy);\n if (dist < bestDist) {\n bestDist = dist;\n best = el;\n }\n }\n return bestDist <= SNAP_RADIUS_PX ? best : null;\n}\n\n// `CSS.escape` polyfill \u2014 older Safari versions sometimes ship\n// without it. Hand-rolled escape covers our identifier characters.\nfunction cssEscape(s: string): string {\n if (\n typeof CSS !== \"undefined\" &&\n typeof (CSS as { escape?: (s: string) => string }).escape === \"function\"\n ) {\n return CSS.escape(s);\n }\n return s.replace(/([\"\\\\#.>+~*$^|=:()\\[\\] ])/g, \"\\\\$1\");\n}\n", "/**\n * Show a person a Prson **verification** (an organisation's request made\n * with POST /v1/verifications \u2014 prove your age, show your ID, sign this\n * PDF with your verified name) and wait until they answer it.\n *\n * The verification is created by YOUR SERVER with your API key; the key\n * never reaches the browser. Your page gets the `share_url` from your\n * server, and `checkStatus` asks your server for the status (your server\n * calls GET /v1/verifications/{id}, or keeps what the verification.*\n * webhooks told it). On a computer the link shows as a QR code to scan\n * with the phone; on a phone, as a button that opens the Prson app.\n *\n * const { share_url, id } = await (await fetch(\"/api/contract/sign\", { method: \"POST\" })).json();\n * await awaitVerification({\n * shareUrl: share_url,\n * title: \"Sign the rental agreement\",\n * checkStatus: async (signal) => (await (await fetch(`/api/verifications/${id}`, { signal })).json()).status,\n * });\n * // fulfilled: your server downloads the signed PDF (the response's signature.download_path).\n *\n * Resolves with the status once `until` holds (default: \"fulfilled\");\n * rejects with VerificationClosedError when it was cancelled or expired,\n * and VerificationAbortedError when the person closes the dialog or\n * `signal` aborts.\n */\n\nimport { createModalQrMount, renderLoginQr, type LoginQrHandle } from \"./qr.js\";\n\nexport type VerificationStatus = \"open\" | \"partially_fulfilled\" | \"fulfilled\" | \"cancelled\" | \"expired\";\n\nexport interface AwaitVerificationOptions {\n /** The verification's `share_url`, from your server. */\n shareUrl: string;\n /** Your server's view of the verification's status. Called every `intervalMs`; a throw is retried. */\n checkStatus: (signal: AbortSignal) => Promise<VerificationStatus | string>;\n /** Shown above the code: what the person is asked for (e.g. \"Sign the rental agreement\"). */\n title?: string;\n /** Where to render; default: a modal over the page (Esc or a click outside closes it). */\n mountInto?: string | HTMLElement;\n /** How often to call `checkStatus`, in ms (default 3000, at least 1000). */\n intervalMs?: number;\n /** Stop after this long (ms) with VerificationAbortedError; default: wait until it closes. */\n timeoutMs?: number;\n /** When to stop waiting (default: status === \"fulfilled\"). */\n until?: (status: string) => boolean;\n signal?: AbortSignal;\n theme?: \"light\" | \"dark\" | \"auto\";\n /** Force the phone (button) or computer (QR) layout; default: guessed from the pointer. */\n layout?: \"phone\" | \"computer\";\n}\n\nexport class VerificationAbortedError extends Error {\n constructor(message = \"The verification dialog was closed\") {\n super(message);\n this.name = \"VerificationAbortedError\";\n }\n}\n\nexport class VerificationClosedError extends Error {\n constructor(readonly status: \"cancelled\" | \"expired\") {\n super(`The verification is ${status}`);\n this.name = \"VerificationClosedError\";\n }\n}\n\nfunction checkShareUrl(url: string): string {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`shareUrl is not a URL: ${url}`);\n }\n if (parsed.protocol !== \"https:\") throw new Error(\"shareUrl must be https:// (the share_url Prson returned)\");\n return parsed.toString();\n}\n\nfunction isPhone(): boolean {\n try {\n return window.matchMedia(\"(pointer: coarse)\").matches && window.matchMedia(\"(max-width: 820px)\").matches;\n } catch {\n return false;\n }\n}\n\n/** The card: title, the QR (computer) or an \"Open in Prson\" button (phone), and a status line. */\nfunction renderCard(mount: HTMLElement, o: { url: string; title?: string; phone: boolean; theme: \"light\" | \"dark\" | \"auto\" }) {\n const dark = o.theme === \"dark\" || (o.theme === \"auto\" && window.matchMedia?.(\"(prefers-color-scheme: dark)\").matches);\n const card = document.createElement(\"div\");\n card.setAttribute(\"data-prson-verification\", \"1\");\n card.style.cssText =\n \"box-sizing:border-box;max-width:360px;width:100%;padding:24px;border-radius:16px;font-family:system-ui,-apple-system,sans-serif;text-align:center;\" +\n (dark ? \"background:#14161b;color:#f2f3f5;\" : \"background:#fff;color:#14161b;\") +\n \"box-shadow:0 12px 40px rgba(0,0,0,0.25);\";\n if (o.title) {\n const h = document.createElement(\"div\");\n h.style.cssText = \"font-size:17px;font-weight:600;margin-bottom:6px;line-height:1.3;\";\n h.textContent = o.title;\n card.append(h);\n }\n const hint = document.createElement(\"div\");\n hint.style.cssText = \"font-size:14px;opacity:0.75;margin-bottom:16px;line-height:1.4;\";\n hint.textContent = o.phone ? \"Open the request in the Prson app on this phone.\" : \"Scan with your phone's camera to open it in the Prson app.\";\n card.append(hint);\n\n let qr: LoginQrHandle | null = null;\n if (o.phone) {\n const a = document.createElement(\"a\");\n a.href = o.url;\n a.rel = \"noopener\";\n a.textContent = \"Open in Prson\";\n a.style.cssText = \"display:inline-block;padding:12px 20px;border-radius:999px;background:#2949b8;color:#fff;font-weight:600;text-decoration:none;font-size:15px;\";\n card.append(a);\n } else {\n const qrMount = document.createElement(\"div\");\n qrMount.style.cssText = \"display:flex;justify-content:center;margin:4px 0 8px;\";\n card.append(qrMount);\n qr = renderLoginQr(o.url, qrMount, o.theme);\n const link = document.createElement(\"a\");\n link.href = o.url;\n link.target = \"_blank\";\n link.rel = \"noopener\";\n link.textContent = \"On this device? Open the link\";\n link.style.cssText = \"display:inline-block;margin-top:4px;font-size:13px;color:inherit;opacity:0.7;\";\n card.append(link);\n }\n const status = document.createElement(\"div\");\n status.setAttribute(\"role\", \"status\");\n status.style.cssText = \"font-size:13px;opacity:0.7;margin-top:16px;\";\n status.textContent = \"Waiting for an answer\u2026\";\n card.append(status);\n mount.append(card);\n return {\n setStatus: (s: string) => {\n status.textContent = s === \"partially_fulfilled\" ? \"Partly answered, waiting for the rest\u2026\" : \"Waiting for an answer\u2026\";\n },\n dispose: () => {\n qr?.dispose();\n card.remove();\n },\n };\n}\n\nexport async function awaitVerification(opts: AwaitVerificationOptions): Promise<{ status: string }> {\n const url = checkShareUrl(opts.shareUrl);\n const interval = Math.max(1000, opts.intervalMs ?? 3000);\n const until = opts.until ?? ((s: string) => s === \"fulfilled\");\n const controller = new AbortController();\n const abort = (reason: Error) => controller.abort(reason);\n opts.signal?.addEventListener(\"abort\", () => abort(new VerificationAbortedError(\"Aborted\")), { once: true });\n\n let modal: { mount: HTMLElement; dispose: () => void } | null = null;\n let mount: HTMLElement | null = null;\n if (opts.mountInto) mount = typeof opts.mountInto === \"string\" ? document.querySelector(opts.mountInto) : opts.mountInto;\n if (!mount) {\n modal = createModalQrMount({ onDismiss: () => abort(new VerificationAbortedError()) });\n mount = modal.mount;\n }\n const card = renderCard(mount, { url, title: opts.title, phone: opts.layout ? opts.layout === \"phone\" : isPhone(), theme: opts.theme ?? \"auto\" });\n const timer = opts.timeoutMs ? setTimeout(() => abort(new VerificationAbortedError(\"Timed out waiting for an answer\")), opts.timeoutMs) : null;\n\n const sleep = (ms: number) =>\n new Promise<void>((resolve, reject) => {\n if (controller.signal.aborted) return reject(controller.signal.reason);\n const t = setTimeout(resolve, ms);\n controller.signal.addEventListener(\"abort\", () => (clearTimeout(t), reject(controller.signal.reason)), { once: true });\n });\n\n try {\n for (;;) {\n if (controller.signal.aborted) throw controller.signal.reason;\n let status: string | null = null;\n try {\n status = String(await opts.checkStatus(controller.signal));\n } catch (e) {\n if (controller.signal.aborted) throw controller.signal.reason;\n // A failed check (network, your server) is retried at the next tick.\n }\n if (status !== null) {\n if (until(status)) return { status };\n if (status === \"cancelled\" || status === \"expired\") throw new VerificationClosedError(status);\n card.setStatus(status);\n }\n await sleep(interval);\n }\n } finally {\n if (timer) clearTimeout(timer);\n card.dispose();\n modal?.dispose();\n }\n}\n", "/**\n * @prson/login-sdk \u2014 browser runtime.\n *\n * Top-level entry point: `PrsonLogin.signIn(opts)` orchestrates the\n * whole flow. The pieces underneath are:\n *\n * \u250C\u2500\u2500 ./session.ts \u2014 PrsonLoginSession (state machine + events)\n * \u251C\u2500\u2500 ./signaling.ts \u2014 WebSocket to the Cloudflare Worker\n * \u251C\u2500\u2500 ./transport.ts \u2014 RTCPeerConnection + data channel\n * \u251C\u2500\u2500 ./crypto.ts \u2014 X25519 ephemeral keypair + NaCl box decrypt\n * \u251C\u2500\u2500 ./verify.ts \u2014 verify issuer JWS + KB-JWT in the browser\n * \u251C\u2500\u2500 ./qr.ts \u2014 render the https://app.prson.net/login/v1?... QR\n * \u2514\u2500\u2500 ./api.ts \u2014 typed createLoginSession + resolveLoginSession\n *\n * See ../../README.md for integration. See ../../../ARCHITECTURE.md\n * for the wire spec.\n */\nimport {\n PrsonLoginSession,\n type ExpiryReason,\n type Renewal,\n} from \"./session.js\";\nimport { createDraft } from \"./api.js\";\nimport { generateEphemeralKeypair, openEnvelope } from \"./crypto.js\";\nimport { connectSignaling } from \"./signaling.js\";\nimport { establishTransport } from \"./transport.js\";\nimport {\n renderLoginQr,\n createModalQrMount,\n type LoginQrContext,\n type LoginQrHandle,\n} from \"./qr.js\";\nimport type { DraftResult } from \"./api.js\";\nimport { verifyPresentation } from \"./verify.js\";\nimport { notifyHandleFrom } from \"./notify.js\";\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Public types \u2014 these mirror the contract in this folder's README.\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type SignInOptions = {\n domain?: string;\n\n /**\n * A one-time value your BACKEND made for this sign-in (at least 16 random\n * bytes, base64url: 22-128 characters of `A-Z a-z 0-9 - _`). Store it\n * server-side, then verify the presentation there with\n * `verifyPresentation(presentation, { expectedNonce, expectedAudience })`\n * and delete it, so a captured presentation can't be replayed to your\n * backend. Omitted: the SDK makes one in the browser, which only protects\n * the in-browser check \u2014 not enough for a backend that trusts the result.\n *\n * May also be a function returning one (sync or async). The SDK then\n * calls it once per code it shows, so a refreshed code (after expiry or\n * an error) gets a fresh backend nonce without your page calling\n * `signIn()` again. `SignInResult.nonce` says which one the presentation\n * is bound to.\n */\n nonce?: string | (() => string | Promise<string>);\n\n /**\n * Which Prson backend environment to sign in against. `\"dev\"` points\n * the flow at the dev signaling Worker (`signaling-dev.prson.net`);\n * omit (or `\"production\"`) for the live environment. For a custom /\n * local Worker, set `signalingBase` instead (it takes precedence).\n * Default `\"production\"`.\n */\n environment?: \"production\" | \"dev\";\n\n /**\n * Explicit signaling Worker base URL \u2014 overrides `environment`. Use\n * for a local Worker (`https://localhost:8787`) or any non-standard\n * deployment. The Worker returns the matching WebSocket URL in its\n * draft response, so this single value steers the whole flow.\n */\n signalingBase?: string;\n\n required?: {\n /**\n * Minimum identity verification level (0\u20136). Omitted \u21D2 1.\n *\n * `0` opts into **pseudonymous identity sign-in**: the wallet may\n * present an UNVERIFIED identity, and the minted credential\n * honestly claims `verified_human: false` / `verification_level: 0`.\n * You still get the stable per-domain `sub` (cnf.jwk continuity) \u2014\n * what you give up is any assurance a real, unique human is behind\n * it. Distinct from `allowAnonymous`, which is identity-less: a\n * level-0 identity sign-in carries the user's chosen identity and\n * survives across sessions; anonymous carries only a key.\n */\n minVerificationLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6;\n requiredClaims?: string[];\n predicates?: string[];\n identityType?: \"personal\" | \"organization\";\n /**\n * Require a **domain-scoped unique-human id**: a notary-signed\n * pairwise identifier anchored to the user's verified government\n * document. Proves \"one unique, document-verified human at YOUR\n * domain\" (sybil resistance) without any cross-site correlation\n * handle. The wallet only offers document-backed identities\n * (level \u2265 4) when this is set; the result carries\n * `uniqueHumanId` for SERVER-SIDE verification.\n */\n uniqueHumanId?: boolean;\n };\n /**\n * If `true`, the SDK ALSO accepts an **anonymous-wallet** credential\n * \u2014 a self-signed JWT issued by the wallet's per-domain Ed25519 key,\n * with no notary involvement. The wallet's login drawer surfaces an\n * \"Sign in anonymously\" option to the user. The credential carries\n * only `cnf.jwk` + `aud` + `nonce` + `iat` + `exp` (no\n * `verified_human`, no document fields, no predicates). The\n * verifier treats `cnf.jwk.x` as the stable per-user identifier on\n * this domain.\n *\n * If a verified credential is presented when `allowAnonymous: true`\n * AND `required.*` constraints are set, the verified credential is\n * still checked against those constraints \u2014 the relaxation only\n * applies to the anonymous fallback. Default false.\n */\n allowAnonymous?: boolean;\n\n /**\n * If `true`, the wallet generates a **fresh random Ed25519 keypair**\n * for this single login instead of the deterministic per-domain\n * HKDF derivation. The credential's `cnf.jwk` is therefore\n * **different on every sign-in attempt** \u2014 there is no stable per-\n * user id, and a future mnemonic compromise cannot retroactively\n * link the user across sessions on this site.\n *\n * Trade-off: `cnf.jwk.x` is no longer a per-user identifier on this\n * domain. Sites that key sessions off `cnf.jwk.x` must derive a\n * usable account id by some other means (e.g. a user-chosen\n * username on first visit). Best fit for read-only / single-use\n * flows where re-identification on return is irrelevant.\n *\n * Combine with `allowAnonymous: true` for a fully unlinkable\n * anonymous flow. Default false.\n *\n * Closes [SECURITY-AUDIT \u00A7M-5](../../SECURITY-AUDIT-2026-05-28.md).\n */\n ephemeralIdentity?: boolean;\n\n /**\n * Sponsorship: pay for premium verifications your users need.\n *\n * If your `required.predicates` include facts that need a PAID\n * verification the user may not have yet (e.g. `phone_verified` \u2014\n * SMS costs credits), create a **sponsorship grant** from your\n * company wallet (Prson app \u2192 `createSponsorshipGrant`) and put its\n * id here. The user's wallet then routes those verification costs\n * to your grant instead of the user.\n *\n * Safe to expose in page source: the grantId authorises nothing by\n * itself. Every redemption is validated server-side against the\n * STORED grant \u2014 bound to YOUR domain, capped per user (default\n * once), capped in total budget, expiring, and instantly revocable.\n */\n sponsorship?: { grantId: string };\n\n /**\n * **App-to-app return leg** (same-device native flows). An HTTPS URL\n * on YOUR login domain that the wallet opens after the credential\n * has been delivered \u2014 typically your Universal Link / Android App\n * Link, so the OS bounces the user straight back into your native\n * app (only the app your domain vouches for via AASA /\n * assetlinks.json receives it).\n *\n * Constraints (enforced both here and in the wallet):\n * - `https://` only \u2014 custom schemes are refused (any installed\n * app could claim a custom scheme; app links are domain-proven).\n * - The URL's host MUST equal the login domain exactly.\n *\n * Only set this for same-device flows (your site opened inside a\n * Custom Tab / SFSafariViewController from your app). In cross-device\n * QR flows the wallet is on a different phone \u2014 it would open your\n * site there, which is harmless but pointless.\n */\n returnUrl?: string;\n\n ttlMinutes?: number;\n ui?: {\n /**\n * Render the code inline in this element instead of the SDK's own\n * dialog. The dialog is the default and the recommended experience.\n */\n mountQrInto?: string | HTMLElement;\n /** `\"auto\"` (default) follows `prefers-color-scheme`. The code itself is always dark on white. */\n theme?: \"light\" | \"dark\" | \"auto\";\n /** Where \"Don't have Prson? Get it\" points. Default https://app.prson.net/. */\n getAppUrl?: string;\n };\n defer?: boolean;\n\n /**\n * QR-mode only: opt in to **remote navigation**. The wallet shows a\n * persistent banner that opens a bottom drawer with Prev / Next /\n * Submit (Enter) / Logout / (optional) Mouse buttons. The host\n * page's currently-focused input is mirrored on the phone so the\n * user can edit / clear / replace the value with the phone\n * keyboard, and edits stream back into the DOM in real time.\n *\n * Auto-wires when the SDK detects a QR-mode sign-in (the QR encodes\n * `remoteNavigation: true` for the wallet to honour). Same-device\n * universal-link flows ignore the flag \u2014 the banner would be\n * redundant when the wallet is on the same device as the page.\n *\n * Pair with [`enableRemoteNavigation`] to install the DOM focus\n * listeners that mirror the active input. Default false.\n */\n remoteNavigation?: boolean;\n\n /**\n * **Mouse control pre-granted at sign-in.** When true, the wallet's\n * persistent banner drawer enables the Touchpad / Magic wand\n * buttons from the moment the session lands, so the user can\n * start driving the cursor without the host ever issuing a\n * `kind: \"mouse\"` request.\n *\n * The capability **persists** for the session lifetime \u2014 closing\n * the controller doesn't revoke it; the user can re-open it from\n * the drawer at any time. The host still calls [`bindMouse`] to\n * mount the on-page cursor; when this flag is set, that call\n * installs an *ambient* mouse-update subscriber so wallet-\n * initiated streams (which carry no `requestId` matched to a\n * pending `request()`) land correctly. Existing `requestMouse`\n * round-trips still work in parallel.\n *\n * The wallet shows a chip in the sign-in drawer so the user\n * sees mouse control will be active before they approve.\n *\n * Default false.\n */\n mouseControl?: boolean;\n\n /**\n * **Ask to send notifications.** The wallet's sign-in sheet shows an\n * unticked \"Let {site} send you notifications\" row; nothing is sent\n * unless the person ticks it. When they do, `SignInResult.notifications`\n * carries a handle for this person at your domain: random, so it can't\n * be linked to the same person's handle on any other site. Send it to\n * your backend with the presentation and call\n * `POST https://api.prson.net/v1/notify { handle, title, body, url? }`\n * with an API key that has `notify:write`, for an app whose registered\n * domains include this one. Plain text only (title up to 60\n * characters, body up to 180), `url` only on this sign-in domain itself\n * (the app asks the person before opening it), about 3\n * a day per person. A 410 means the person turned you off: forget the\n * handle. Default false.\n */\n notifications?: boolean;\n};\n\nexport type CnfJwk = {\n kty: \"OKP\";\n crv: \"Ed25519\";\n x: string;\n};\n\nexport type SignInResult = {\n sdJwtVc: string;\n /** The nonce the presentation is bound to (yours when you passed `nonce`). */\n nonce: string;\n /**\n * The person's Prson ID for your site: stable across sign-ins, different on\n * every other site. Check the presentation on your server and use the\n * verifier's `prsonId` there; this copy is for your page. (`cnf.jwk.x`.)\n *\n * Show who is signed in (this ID, or the account/name your backend maps\n * it to) right after sign-in, also from the `signed_in` event: whoever\n * scans the code first signs in, so the person at the screen must be able\n * to see it's them.\n */\n prsonId: string;\n claims: Record<string, unknown>;\n cnf: { jwk: CnfJwk };\n credential: {\n vct: string;\n iss: string;\n kid: string;\n expiresAt: number;\n };\n /**\n * Present when the host set `required.uniqueHumanId: true`: a\n * notary-signed, domain-scoped uniqueness credential. OPAQUE\n * pass-through \u2014 verify it SERVER-SIDE with\n * `@prson/login-verifier`'s `verifyUniqueHumanId({...},\n * { expectedAudience: \"your.host\" })`, then use\n * `envelope.uniqueIdHash` as the sybil-resistant account key.\n * Stable for this human at your domain; uncorrelatable anywhere else.\n */\n uniqueHumanId?: {\n envelope: Record<string, unknown>;\n signature: string;\n kid: string;\n } | null;\n /**\n * Present when you set `notifications: true` and the person ticked \"Let\n * {site} send you notifications\": the handle your backend sends with\n * (see SignInOptions.notifications). null when they didn't.\n */\n notifications?: { handle: string } | null;\n session: PrsonLoginSession;\n};\n\nexport type { ExpiryReason } from \"./session.js\";\n\n// Constants exported for verifier-side consumers + diagnostics.\nexport const PROTOCOL_VERSION = \"prson_vp_v1\";\n/**\n * Data-channel envelope version this SDK speaks, announced to the wallet\n * in the request (`envelopeVersion`). 2 = both sides box with their\n * session keys (sender-authenticated), and the wallet binds its session\n * key into the signed presentation (`prson_wsk`). See SECURITY.md \u00A74.\n */\nexport const ENVELOPE_VERSION = 2;\nexport const TRUSTED_ISSUER = \"did:web:app.prson.net\";\nexport const KNOWN_VCTS = [\n \"https://app.prson.net/credentials/verified-human/v1\",\n \"https://app.prson.net/credentials/verified-identity/v1\",\n] as const;\n/** Self-signed wallet credential \u2014 accepted only when the SDK is\n * invoked with `allowAnonymous: true`. Carries only `cnf.jwk` + the\n * KB-JWT fields; no notary signature. */\nexport const ANONYMOUS_WALLET_VCT =\n \"https://app.prson.net/credentials/anonymous-wallet/v1\";\n// Testing pass: 2-minute sessions surface expiry / renewal bugs\n// quickly. Production target is 10 / 15. Keep these in sync with\n// `SESSION_TTL_SECONDS` in `cloudflare-workers/signaling-worker/src/index.ts`.\nexport const DEFAULT_TTL_MINUTES = 2;\nexport const MAX_TTL_MINUTES = 2;\n/** Cloudflare Worker single-API-surface base URL (production). */\nexport const SIGNALING_BASE = \"https://signaling.prson.net\";\n\n/** Dev environment Worker base. Selected via `signIn({ environment: \"dev\" })`,\n * or override either env with an explicit `signalingBase` (e.g. a local\n * Worker at `https://localhost:8787`). */\nexport const SIGNALING_BASE_DEV = \"https://signaling-dev.prson.net\";\n\n/** Map an `environment` shorthand to its Worker base URL. */\nexport function resolveSignalingBase(opts: {\n environment?: \"production\" | \"dev\";\n signalingBase?: string;\n}): string {\n if (opts.signalingBase) return opts.signalingBase;\n return opts.environment === \"dev\" ? SIGNALING_BASE_DEV : SIGNALING_BASE;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Concurrency guard \u2014 one in-flight sign-in at a time\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// A user who clicks \"Sign in\" twice in quick succession (because the\n// first click felt slow, or the QR scrolled out of view) would\n// otherwise spawn two parallel sign-in flows, each holding its own\n// draftToken / WS / RTCPeerConnection / QR card. The second sign-in's\n// QR would stack on top of the first; both wallets would try to\n// claim; the verifier might commit the wrong identity.\n//\n// Semantics:\n// * Only the PHASE BEFORE signIn() resolves is treated as\n// \"in-flight\". Once signIn() has resolved into a live session,\n// that session is no longer in-flight; a fresh signIn() does\n// NOT terminate the live session it just supersedes (the host\n// page can keep the prior session handle if it needs to).\n// * A second signIn() while a first is in-flight calls the first\n// one's abort(), which runs the registered teardowns in LIFO\n// order (latest resource first). The first signIn() then sees\n// the abort signal on its next `await` and throws\n// `LoginAbortedError`.\n//\n// Implementation: module-scoped current-inflight slot + per-call\n// disposer chain that the displacement awaits.\n\n/**\n * Thrown by `PrsonLogin.signIn()` when a NEWER `signIn()` call\n * displaces the current in-flight one. Host pages typically ignore\n * this \u2014 the user's second click is the cancellation signal \u2014 but\n * the typed error lets you distinguish it from real failures.\n */\nexport class LoginAbortedError extends Error {\n constructor(message = \"sign-in aborted by a newer signIn() call\") {\n super(message);\n this.name = \"LoginAbortedError\";\n }\n}\n\ninterface InflightSignIn {\n /** True once a newer signIn() has called `abort()`. */\n aborted: boolean;\n /**\n * Run the registered teardowns in LIFO order and mark\n * `aborted = true`. Resolves after every teardown has settled.\n */\n abort(message?: string): Promise<void>;\n /** Push a teardown thunk; runs once on `abort()` or normal exit. */\n pushTeardown(t: () => void | Promise<void>): void;\n /**\n * Rejects with `LoginAbortedError` the moment `abort()` is called. The\n * flow races its waits against it, so a closed dialog or a newer\n * `signIn()` settles this one at once instead of leaving it waiting\n * for a wallet that will never come.\n */\n whenAborted: Promise<never>;\n}\n\nlet _inflight: InflightSignIn | null = null;\n\nfunction makeInflight(): InflightSignIn {\n const teardowns: Array<() => void | Promise<void>> = [];\n let rejectAborted: (e: Error) => void = () => {};\n const whenAborted = new Promise<never>((_, reject) => {\n rejectAborted = reject;\n });\n whenAborted.catch(() => {\n /* only an error for whoever races it */\n });\n const self: InflightSignIn = {\n aborted: false,\n whenAborted,\n pushTeardown(t) {\n teardowns.push(t);\n },\n async abort(message?: string) {\n if (self.aborted) return;\n self.aborted = true;\n rejectAborted(new LoginAbortedError(message));\n // LIFO so we close the most-recently-acquired resource first\n // \u2014 typically the transport / RTCPeerConnection \u2014 and unwind\n // backwards through signaling, QR, draft state.\n while (teardowns.length) {\n const t = teardowns.pop();\n try {\n await t?.();\n } catch {\n /* swallow \u2014 best-effort cleanup */\n }\n }\n },\n };\n return self;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Public fa\u00E7ade\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport class PrsonLogin {\n /**\n * Drive a full sign-in. The promise resolves once the wallet has\n * delivered a verified SD-JWT-VC; the returned session lives until\n * one of the four `ExpiryReason` triggers.\n *\n * Without `ui.mountQrInto` the SDK shows its own dialog and handles\n * everything in it: an expired code or a failure offers a fresh code\n * (a new draft, and a new nonce when `nonce` is a function) while this\n * promise keeps waiting; closing the dialog rejects with\n * `LoginAbortedError` (or with the error on screen, if one was shown).\n */\n static async signIn(opts: SignInOptions = {}): Promise<SignInResult> {\n // \u2500\u2500\u2500 concurrency guard \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Tear down any prior in-flight sign-in BEFORE we mint a fresh\n // draft. Awaited so the prior's QR / signaling are gone before\n // the new one mounts \u2014 gives the user immediate visual\n // confirmation that the second click cancelled the first. If\n // there's no prior, `prior?.abort()` is a cheap no-op.\n const prior = _inflight;\n if (prior) await prior.abort();\n const me = makeInflight();\n _inflight = me;\n\n try {\n const domain = opts.domain ?? window.location.origin.replace(/^https?:\\/\\//, \"\");\n const theme = opts.ui?.theme ?? \"auto\";\n const titleId = `prson-login-title-${b64u(crypto.getRandomValues(new Uint8Array(6)))}`;\n const explicitMount = resolveMount(opts.ui?.mountQrInto);\n\n // No mount supplied \u2192 the SDK's own dialog, opened when the first\n // code is ready (no empty scrim while the draft is made). Esc /\n // click-outside / its close button abort the in-flight signIn so\n // `await signIn(...)` rejects with `LoginAbortedError`. Zero-config\n // for the partner.\n const dialog: { current: { mount: HTMLElement; dispose: () => void } | null } = { current: null };\n const getMount = (): HTMLElement => {\n if (explicitMount) return explicitMount;\n if (!dialog.current) {\n const m = createModalQrMount({ titleId, onDismiss: () => void me.abort(\"sign-in closed\") });\n dialog.current = m;\n me.pushTeardown(() => m.dispose());\n }\n return dialog.current.mount;\n };\n\n // One attempt per code shown; a refresh (expiry, \"Try again\")\n // starts the next.\n for (;;) {\n const attempt = makeInflight();\n me.pushTeardown(() => attempt.abort());\n let requestRestart: () => void = () => {};\n const restart = new Promise<\"restart\">((resolve) => {\n requestRestart = () => resolve(\"restart\");\n });\n const context: LoginQrContext = {\n mode: explicitMount ? \"inline\" : \"modal\",\n domain,\n titleId,\n getAppUrl: opts.ui?.getAppUrl ?? GET_APP_URL,\n // A no-op once this sign-in is over or the host re-called\n // signIn() from the `prson-login-refresh-requested` event.\n refresh: () => {\n if (!me.aborted && !attempt.aborted && _inflight === me) requestRestart();\n },\n cancel: () => void me.abort(\"sign-in closed\"),\n };\n const ui: AttemptUi = { handle: null };\n const run = runAttempt(opts, { domain, getMount, theme, context, attempt, me, ui });\n run.catch(() => {\n /* raced below; an abandoned attempt may fail later, quietly */\n });\n\n try {\n const out = await Promise.race([run, restart, me.whenAborted]);\n if (out === \"restart\") {\n await attempt.abort();\n continue;\n }\n // Success: the code (and dialog) go; the transport stays for the session.\n ui.handle?.dispose();\n dialog.current?.dispose();\n return out;\n } catch (err) {\n if (err instanceof LoginAbortedError) throw err;\n // Show what went wrong where the person is looking.\n ui.handle?.update?.({ state: \"error\", message: friendlyError(err) });\n if (!dialog.current || !ui.handle?.update) {\n // Inline (the host owns the page and keeps the card, as 0.1\n // did), a renderer that can't show errors, or a failure\n // before any code was shown: reject now.\n if (dialog.current) await me.abort();\n throw err;\n }\n // In the dialog: wait for \"Try again\" (a new attempt) or close\n // (reject with this error rather than a bare \"aborted\").\n try {\n await Promise.race([restart, me.whenAborted]);\n } catch {\n throw err;\n }\n await attempt.abort();\n }\n }\n } finally {\n // Release the slot ONLY if we still own it. If a newer signIn()\n // displaced us mid-flight, `_inflight` already points at\n // someone else; we mustn't clobber their entry. The displacing\n // signIn() already called our `abort()`, so the teardowns ran.\n if (_inflight === me) _inflight = null;\n }\n }\n\n /**\n * Rebind to a session that was previously established for the same\n * holder pk. Phase 2 placeholder \u2014 the SDK has no cross-page-load\n * state today; callers should redirect through `signIn` on each\n * page load (the cookie-on-the-server is the source of truth).\n */\n static async restore(_opts: {\n cnfJwk: CnfJwk;\n onExpiry?: (reason: ExpiryReason) => void;\n }): Promise<PrsonLoginSession | null> {\n return null;\n }\n}\n\n/** Where \"Don't have Prson? Get it\" points unless `ui.getAppUrl` says otherwise. */\nexport const GET_APP_URL = \"https://app.prson.net/\";\n\ntype AttemptUi = { handle: LoginQrHandle | null };\n\n/**\n * One code on screen, from the draft to a verified presentation. Every\n * wait is raced against both this attempt's and the whole sign-in's\n * abort, so a refresh or a closed dialog ends it at once.\n */\nasync function runAttempt(\n opts: SignInOptions,\n env: {\n domain: string;\n getMount: () => HTMLElement;\n theme: \"light\" | \"dark\" | \"auto\";\n context: LoginQrContext;\n attempt: InflightSignIn;\n me: InflightSignIn;\n ui: AttemptUi;\n },\n): Promise<SignInResult> {\n const { domain, attempt, me } = env;\n const guard = <T>(p: Promise<T>): Promise<T> => Promise.race([p, attempt.whenAborted, me.whenAborted]);\n /** Throw `LoginAbortedError` if a newer signIn() (or a refresh) has displaced us. */\n const checkAborted = () => {\n if (me.aborted || attempt.aborted) throw new LoginAbortedError();\n };\n\n const ttlMaxMinutes = Math.min(\n Math.max(opts.ttlMinutes ?? DEFAULT_TTL_MINUTES, 1),\n MAX_TTL_MINUTES,\n );\n\n // 1. Generate the ephemeral X25519 keypair the wallet will encrypt\n // its envelope to. Stays in memory only \u2014 never written to\n // storage, never crosses any network boundary.\n const ephKeys = await guard(generateEphemeralKeypair());\n checkAborted();\n\n // 2. Build the verifier request blob. The reqId is content-bound\n // so the wallet sees the same canonical bytes the Worker stored\n // (anti-tamper, see SECURITY.md \u00A73).\n const given = typeof opts.nonce === \"function\" ? await guard(Promise.resolve(opts.nonce())) : opts.nonce;\n checkAborted();\n if (given !== undefined && (typeof given !== \"string\" || !/^[A-Za-z0-9_-]{22,128}$/.test(given))) {\n throw new Error(\"nonce must be 22-128 base64url characters (at least 16 random bytes)\");\n }\n const nonce = given ?? b64u(crypto.getRandomValues(new Uint8Array(32)));\n const request = {\n domain,\n nonce,\n browserPk: ephKeys.publicKeyB64u,\n required: opts.required ?? {},\n // Carried into the wallet's drawer so an \"Anonymous\" option is\n // offered. The SDK side enforces acceptance below at verify time;\n // the wallet enforces drawer UX based on this flag.\n allowAnonymous: opts.allowAnonymous === true,\n // Sponsorship offer (advisory on the wire \u2014 the server enforces\n // the stored grant's domain/caps/budget at charge time).\n ...(opts.sponsorship?.grantId ? { sponsorship: { grantId: opts.sponsorship.grantId } } : {}),\n // If set, instructs the wallet to mint a fresh random Ed25519\n // keypair for this single sign-in (no deterministic per-domain\n // HKDF). Closes M-5; see SignInOptions.ephemeralIdentity.\n ephemeralIdentity: opts.ephemeralIdentity === true,\n // QR-mode remote navigation \u2014 wallet surfaces Prev / Next /\n // Submit / Logout / Mouse on a persistent banner. See\n // SignInOptions.remoteNavigation + bind.ts:enableRemoteNavigation.\n remoteNavigation: opts.remoteNavigation === true,\n // Pre-grant mouse control \u2014 wallet enables the Touchpad /\n // Magic wand buttons on the banner drawer from session start.\n // See SignInOptions.mouseControl + bindMouse's ambient\n // subscriber path.\n mouseControl: opts.mouseControl === true,\n // Website notifications: the wallet offers an unticked opt-in row.\n // See SignInOptions.notifications.\n ...(opts.notifications === true ? { notifications: true } : {}),\n // App-to-app return leg \u2014 validated here (fail fast at the\n // integrator's desk) AND in the wallet (the enforcing side).\n ...(opts.returnUrl ? { returnUrl: validateReturnUrl(opts.returnUrl, domain) } : {}),\n ttlMaxMinutes,\n // Envelope v2: the wallet boxes every message with its session key\n // and binds that key into the presentation; it may then insist our\n // messages come from browserPk. Older wallets ignore the field.\n envelopeVersion: ENVELOPE_VERSION,\n };\n\n // 3. Register the draft directly with the Cloudflare Worker.\n // Anonymous + IP rate-limited. No TURN allocation (current relays):\n // relay capacity is minted only after a wallet claims the code.\n const draft: DraftResult = await guard(\n createDraft(request, {\n signalingBase: resolveSignalingBase(opts),\n }),\n );\n checkAborted();\n\n // 4. Render the QR encoding the deep-link URL the wallet scans /\n // the mobile browser taps. Register its teardown FIRST so an\n // abort during signaling/connect immediately removes the\n // on-screen artefact even before the network resources close.\n const qrUrl = buildDeepLinkUrl({\n reqId: draft.reqId,\n browserPk: ephKeys.publicKeyB64u,\n nonce,\n domain,\n request,\n serverTs: draft.serverTs,\n });\n const handle = renderLoginQr(qrUrl, env.getMount(), env.theme, env.context);\n env.ui.handle = handle;\n attempt.pushTeardown(() => handle.dispose());\n const show = (s: Parameters<NonNullable<LoginQrHandle[\"update\"]>>[0]) => {\n if (!attempt.aborted && !me.aborted) void handle.update?.(s);\n };\n\n // 5. Open the WS to the Cloudflare Worker. The DO is in DRAFT until\n // a wallet's /session/claim flips it to ACTIVE; we'll still\n // receive cached SDP/ICE from the wallet at that point.\n const signaling = await guard(\n connectSignaling({\n url: draft.signalingWss,\n role: \"browser\",\n sigToken: draft.draftToken,\n }),\n );\n attempt.pushTeardown(() => signaling.close());\n checkAborted();\n // The relay's `ice` (a wallet claimed the code) or the wallet's first\n // message: the person scanned and is approving on the phone. If they\n // didn't scan it, someone else did \u2014 the page says so.\n let scanned = false;\n const markScanned = () => {\n if (scanned) return;\n scanned = true;\n show({ state: \"scanned\" });\n };\n signaling.onMessage((m) => {\n if (m.msg === \"answer\" || m.msg === \"peer-ready\") markScanned();\n });\n\n // 6. Bring up the RTCPeerConnection + data channel, relay-only: the\n // browser gathers only TURN candidates, so its own addresses never\n // reach the phone (the wallet is relay-only too). Current relays\n // send the TURN servers over the socket once a wallet has claimed\n // the code (`{type:\"ice\"}`), so nothing is allocated for a QR\n // nobody scans; older relays put them in the draft response.\n let iceServers: RTCIceServer[];\n if (draft.turn) {\n iceServers = [{ urls: draft.turn.urls, username: draft.turn.username, credential: draft.turn.credential }];\n } else {\n iceServers = await guard(signaling.awaitIce());\n checkAborted();\n markScanned();\n }\n const transport = await guard(\n establishTransport({\n signaling,\n role: \"browser\",\n iceServers,\n }),\n );\n // From here on, `transport` owns the signaling channel \u2014 its\n // close() will close the WS too.\n attempt.pushTeardown(() => transport.close());\n checkAborted();\n show({ state: \"approving\" });\n\n // 7. Wait for the wallet's encrypted envelope on the data channel.\n // The wallet emits exactly one `prson_vp_v1 / msg=presentation`\n // on initial sign-in; renewals come later via the session handle.\n const first = await guard(transport.awaitFirstMessage());\n checkAborted();\n show({ state: \"verifying\" });\n const { envelope, senderPk } = await openEnvelope(first, ephKeys);\n if (envelope.v !== PROTOCOL_VERSION || envelope.msg !== \"presentation\") {\n throw new Error(`Unexpected first message: ${envelope.v}/${envelope.msg}`);\n }\n // After the post-ROADMAP-\u00A71 envelope grammar made `presentation`\n // optional (so it can be absent on `display-update` /\n // `credential-revoked`), the narrowed `msg === \"presentation\"`\n // branch still has it as `string | undefined` to TypeScript.\n // Defensive runtime check + local rebind for type narrowing.\n const presentationStr = envelope.presentation;\n if (!presentationStr) {\n throw new Error(\"Initial presentation envelope had no presentation field\");\n }\n\n // 8. Verify the presentation cryptographically before we hand it\n // to the host application. The five rules in SECURITY.md \u00A77\n // are enforced here. When allowAnonymous is set, we also accept\n // the self-signed anonymous-wallet VCT (different verification\n // path: cnf.jwk == issuer, no notary signature to check).\n const acceptedVcts = opts.allowAnonymous\n ? [...KNOWN_VCTS, ANONYMOUS_WALLET_VCT]\n : [...KNOWN_VCTS];\n const verified = await verifyPresentation(presentationStr, {\n expectedAudience: `https://${domain}`,\n expectedNonce: nonce,\n acceptedVcts,\n trustedIssuer: TRUSTED_ISSUER,\n });\n if (!verified.ok) {\n throw new Error(`Presentation rejected: ${verified.reason}`);\n }\n\n // Envelope v2: the holder signed its session key into the\n // presentation (`prson_wsk`). The envelope must have been boxed by\n // that very key \u2014 then nobody else (a relay, someone who saw the QR)\n // can talk to this page as the wallet, or swap the key the page\n // sends to. A wallet that predates it gets a legacy session: it\n // works, but page-acting messages are ignored (see session.ts).\n const boundKey = verified.binding.walletSessionPk;\n if (boundKey) {\n if (senderPk !== boundKey) {\n throw new Error(\"Presentation rejected: envelope not sent by the wallet's signed session key\");\n }\n if (envelope.walletSessionPk !== undefined && envelope.walletSessionPk !== boundKey) {\n throw new Error(\"Presentation rejected: walletSessionPk differs from the signed one\");\n }\n } else if (typeof console !== \"undefined\") {\n // eslint-disable-next-line no-console\n console.warn(\n \"[@prson/login-sdk] This Prson app predates sender-authenticated envelopes;\" +\n \" remote navigation, mouse and file input are off for this session. Ask the person to update the app.\",\n );\n }\n\n // Enforce the level floor against the VERIFIED claims (the wallet\n // already gates UX-side, but the host's policy must not depend on\n // the wallet's good behaviour). Anonymous-wallet credentials carry\n // no level claim and are governed by `allowAnonymous` alone.\n // Default floor is 1 \u2014 a `verified_human: false` (level-0)\n // credential is only accepted when the host explicitly set\n // `required.minVerificationLevel: 0`.\n if (verified.credential.vct !== ANONYMOUS_WALLET_VCT) {\n const minLevel = opts.required?.minVerificationLevel ?? 1;\n const claimedLevel =\n typeof verified.claims.verification_level === \"number\"\n ? verified.claims.verification_level\n : 0;\n if (claimedLevel < minLevel) {\n throw new Error(\n `Presentation rejected: verification_level ${claimedLevel} below required ${minLevel}`,\n );\n }\n }\n\n // Unique-human id (when required): the wallet attaches it to the\n // initial envelope; we gate on presence here and pass it through\n // OPAQUE \u2014 cryptographic verification belongs on the host's server\n // (verifier-node `verifyUniqueHumanId`), since a browser-side check\n // could be bypassed by the page's own code anyway.\n const uniqueHumanId =\n (envelope as { uniqueHumanId?: SignInResult[\"uniqueHumanId\"] }).uniqueHumanId ?? null;\n if (opts.required?.uniqueHumanId === true && !uniqueHumanId) {\n throw new Error(\"Presentation rejected: required uniqueHumanId credential missing\");\n }\n // Notification handle (when asked for and the person opted in):\n // opaque, like uniqueHumanId; the API checks it when the site sends.\n const notifyHandle = opts.notifications === true ? notifyHandleFrom(envelope) : null;\n checkAborted();\n\n // 9. Success: let the UI show it (a short check animation, skipped\n // under reduced motion), then the caller tears the code down. The\n // transport stays open for renewals; the session handle owns it\n // from here on.\n const hold = handle.update?.({ state: \"success\", domain });\n if (hold && typeof (hold as Promise<void>).then === \"function\") {\n await Promise.race([hold, new Promise((r) => setTimeout(r, 1500))]);\n }\n checkAborted();\n\n // The host needs both the SignInResult (returned synchronously\n // below) AND a `signed_in` event on the typed event stream (so\n // `onAny` listeners get a uniform lifecycle log). We build the\n // result first, hand it to the session as the initial-signed-in\n // payload (the session fires `signed_in` via microtask), and\n // return the same object.\n const result: SignInResult = {\n sdJwtVc: presentationStr,\n nonce,\n prsonId: verified.cnf.jwk.x,\n claims: verified.claims,\n cnf: verified.cnf,\n credential: verified.credential,\n uniqueHumanId,\n ...(opts.notifications === true ? { notifications: notifyHandle ? { handle: notifyHandle } : null } : {}),\n // session is filled in below \u2014 temporary placeholder cast\n // avoids a circular-self-reference in the literal.\n session: undefined as unknown as PrsonLoginSession,\n };\n\n const session = new PrsonLoginSession({\n cnf: verified.cnf,\n credential: verified.credential,\n transport,\n ephKeys,\n verifierContext: {\n expectedAudience: `https://${domain}`,\n expectedNonceFactory: () => nonce, // renewals carry a fresh nonce; see session.ts\n // The same set as the sign-in, so an anonymous session can renew.\n acceptedVcts,\n trustedIssuer: TRUSTED_ISSUER,\n },\n // Renewal anti-replay baseline: a renewal must be strictly newer.\n initialPresentation: { presentation: presentationStr, iat: verified.binding.iat },\n // Cache the verified claims so the session can diff them\n // against future `claim-update` envelopes \u2014 see ROADMAP \u00A71.\n initialClaims: verified.claims,\n // Fire `signed_in` on the typed event stream. Microtask-\n // deferred inside the constructor, so listeners attached\n // synchronously after this `signIn()` resolves still\n // receive it.\n initialSignedInResult: result,\n // Forward `walletSessionPk` + `preferredLanguage` from the\n // FIRST envelope (which `signIn()` consumed before the session\n // existed) so they're available immediately on the session\n // handle. Without this seed the session would have\n // `walletSessionPk: null` (breaking the request channel) and\n // `preferredLanguage: null` (host can't localise on first\n // paint) until a subsequent envelope arrives.\n // Pinned from the signed presentation; for a legacy wallet, the\n // first envelope's field (nothing better exists).\n walletSessionPk: boundKey ?? envelope.walletSessionPk,\n legacyChannel: !boundKey,\n initialPreferredLanguage: envelope.preferredLanguage,\n // Public-profile fields the wallet may stamp onto the first\n // envelope. They aren't part of the verified-human VC (which\n // carries verification facts only), so without seeding here\n // the host's `session.displayName` would stay null until a\n // later `display-update` envelope.\n initialDisplayName: envelope.displayName,\n initialAvatar: envelope.avatar,\n });\n result.session = session;\n\n return result;\n}\n\n/** A failure in words the person signing in can act on. */\nfunction friendlyError(err: unknown): string {\n const m = err instanceof Error ? err.message : String(err);\n if (/Too many login sessions/i.test(m)) return \"Too many sign-ins from this network. Wait a moment and try again.\";\n if (/createDraft failed|Failed to fetch|NetworkError|signaling: WS/i.test(m)) {\n return \"Couldn't reach Prson. Check your connection and try again.\";\n }\n if (/uniqueHumanId/i.test(m)) return \"This site needs a passport or ID card verified in the Prson app.\";\n if (/verification_level/i.test(m)) return \"This site needs a more verified identity than the one chosen.\";\n if (/data channel/i.test(m)) return \"Your phone couldn't connect to this browser. Try again.\";\n return \"Sign-in didn't finish. Try again.\";\n}\n\n// Re-export for verifier-only consumers + custom UIs.\nexport { PrsonLoginSession };\nexport { NOTIFY_HANDLE, notifyHandleFrom } from \"./notify.js\";\nexport type { LoginQrContext, LoginQrHandle, LoginQrRenderer, LoginUiState } from \"./qr.js\";\nexport type { Renewal };\n\n// Request channel \u2014 types + DOM-binding helpers. `bindInput` /\n// `bindForm` are the kiosk-companion entry points; they synthesise\n// a `session.request(...)` call from a DOM element and write the\n// wallet's reply back into the page.\nexport type {\n LoginRequest,\n LoginResponse,\n RequestOptions,\n InputType,\n InputOption,\n InputFormField,\n} from \"./requests.js\";\nexport {\n bindInput,\n bindForm,\n bindMouse,\n enableRemoteNavigation,\n isSensitiveField,\n type BindController,\n type BindMouseOptions,\n type RemoteNavController,\n type RemoteNavOptions,\n} from \"./bind.js\";\n\n// Verifications (an organisation's request, e.g. \"sign this PDF with your\n// verified name\"): show the share_url and wait until it's answered.\nexport {\n awaitVerification,\n VerificationAbortedError,\n VerificationClosedError,\n type AwaitVerificationOptions,\n type VerificationStatus,\n} from \"./verification.js\";\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Internal helpers\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction b64u(bytes: Uint8Array): string {\n let s = \"\";\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]!);\n return btoa(s).replace(/=+$/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n}\n\n/**\n * Validate SignInOptions.returnUrl: HTTPS, and its host (incl. any\n * explicit port) must equal the login domain exactly. The wallet\n * re-validates independently \u2014 this copy exists so a misconfigured\n * integration fails at the integrator's desk, not on the user's phone.\n */\nfunction validateReturnUrl(returnUrl: string, domain: string): string {\n let parsed: URL;\n try {\n parsed = new URL(returnUrl);\n } catch {\n throw new Error(`returnUrl is not a valid URL: ${returnUrl}`);\n }\n if (parsed.protocol !== \"https:\") {\n throw new Error(\n \"returnUrl must be https:// (custom schemes are refused \u2014 any app \" +\n \"could claim them; use a Universal Link / App Link on your domain)\"\n );\n }\n if (parsed.host.toLowerCase() !== domain.toLowerCase()) {\n throw new Error(\n `returnUrl host (${parsed.host}) must equal the login domain (${domain})`\n );\n }\n return returnUrl;\n}\n\nfunction resolveMount(into: string | HTMLElement | undefined): HTMLElement | null {\n if (!into) return null;\n if (typeof into === \"string\") return document.querySelector(into);\n return into;\n}\n\n/**\n * Build the deep-link URL the QR encodes. We emit the **universal-link\n * form** (`https://app.prson.net/login/v1?\u2026`) \u2014 see\n * [SECURITY-AUDIT-2026-05-28.md \u00A7C-2](../../SECURITY-AUDIT-2026-05-28.md).\n *\n * Custom URI schemes (`prson://\u2026`) have no cryptographic app-binding;\n * any installed app can register the same scheme and intercept the\n * tap. Universal Links (iOS) + App Links (Android) are bound to our\n * domain via `apple-app-site-association` + `assetlinks.json`, which\n * are signed against the wallet's signing-cert hash + our TLS cert.\n * A malicious app cannot register a competing handler.\n *\n * The wallet accepts only this form for sign-in; it no longer opens\n * `prson://login/v1` links at all.\n */\nfunction buildDeepLinkUrl(args: {\n reqId: string;\n browserPk: string;\n nonce: string;\n domain: string;\n request: object;\n serverTs: number;\n}): string {\n const params = new URLSearchParams({\n s: args.reqId,\n p: args.browserPk,\n n: args.nonce,\n d: args.domain,\n req: b64u(new TextEncoder().encode(JSON.stringify(args.request))),\n // M-3 / v2: the server-issued timestamp the wallet must fold into\n // its claim signature. The Worker uses its own stored copy at\n // verify time; tampering this in the QR breaks the signature.\n t: String(args.serverTs),\n });\n return `https://app.prson.net/login/v1?${params.toString()}`;\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,QAAM,QAAQ;AAEd,QAAa,sBAAb,MAAgC;MAM5B,cAAA;AALA,aAAA,cAAc;AACd,aAAA,iBAAiB;AAKb,cAAM,gBAAgB,OAAO,SAAS,cAC/B,KAAK,UAAW,KAA4B,WAC7C;AAEN,YAAI,iBAAiB,cAAc,oBAAoB,QAAW;AAC9D,eAAK,UAAU;AACf,eAAK,cAAc;AACnB,eAAK,iBAAiB;;MAE9B;MAEA,YAAY,QAAc;AACtB,YAAI,CAAC,KAAK,eAAe,CAAC,KAAK,SAAS;AACpC,gBAAM,IAAI,MAAM,iDAAiD;;AAErE,cAAM,MAAM,IAAI,WAAW,MAAM;AACjC,iBAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,OAAO;AACxC,eAAK,QAAQ,gBAAgB,IAAI,SAAS,GAAG,IAAI,KAAK,IAAI,IAAI,SAAS,GAAG,KAAK,CAAC,CAAC;;AAErF,eAAO;MACX;;AA3BJ,YAAA,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"../node_modules/@stablelib/wipe/wipe.ts", "../node_modules/@stablelib/random/source/node.ts", "../node_modules/@stablelib/random/source/system.ts", "../node_modules/@stablelib/int/int.ts", "../node_modules/@stablelib/binary/binary.ts", "../node_modules/@stablelib/random/random.ts", "../node_modules/@stablelib/x25519/x25519.ts", "../node_modules/@stablelib/salsa20/salsa20.ts", "../node_modules/@stablelib/xsalsa20/xsalsa20.ts", "../node_modules/@stablelib/constant-time/constant-time.ts", "../node_modules/@stablelib/poly1305/poly1305.ts", "../node_modules/@stablelib/nacl/secretbox.ts", "../node_modules/@stablelib/nacl/box.ts", "../node_modules/@stablelib/nacl/nacl.ts", "../node_modules/@stablelib/base64/base64.ts", "../src/crypto.ts", "../src/status.ts", "../src/verify.ts", "../src/requests.ts", "../src/session.ts", "../src/errors.ts", "../src/api.ts", "../src/signaling.ts", "../src/transport.ts", "../src/qr.ts", "../src/csp.ts", "../src/notify.ts", "../src/select_overlay.ts", "../src/point_phone_overlay.ts", "../src/bind.ts", "../src/verification.ts", "../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\n\nconst QUOTA = 65536;\n\nexport class BrowserRandomSource implements RandomSource {\n isAvailable = false;\n isInstantiated = false;\n\n private _crypto?: { getRandomValues: typeof window.crypto.getRandomValues };\n\n constructor() {\n const browserCrypto = typeof self !== 'undefined'\n ? (self.crypto || (self as { msCrypto?: any }).msCrypto) // IE11 has msCrypto\n : null;\n\n if (browserCrypto && browserCrypto.getRandomValues !== undefined) {\n this._crypto = browserCrypto;\n this.isAvailable = true;\n this.isInstantiated = true;\n }\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable || !this._crypto) {\n throw new Error(\"Browser random byte generator is not available.\");\n }\n const out = new Uint8Array(length);\n for (let i = 0; i < out.length; i += QUOTA) {\n this._crypto.getRandomValues(out.subarray(i, i + Math.min(out.length - i, QUOTA)));\n }\n return out;\n }\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package wipe implements functions for zeroing arrays.\n */\n\nexport type NumericArray = number[] | Uint8Array | Int8Array | Uint16Array\n | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array;\n\n/**\n * Sets all values in the given array to zero and returns it.\n *\n * The fact that it sets bytes to zero can be relied on.\n *\n * There is no guarantee that this function makes data disappear from memory,\n * as runtime implementation can, for example, have copying garbage collector\n * that will make copies of sensitive data before we wipe it. Or that an\n * operating system will write our data to swap or sleep image. Another thing\n * is that an optimizing compiler can remove calls to this function or make it\n * no-op. There's nothing we can do with it, so we just do our best and hope\n * that everything will be okay and good will triumph over evil.\n */\nexport function wipe(array: NumericArray): NumericArray {\n // Right now it's similar to array.fill(0). If it turns\n // out that runtimes optimize this call away, maybe\n // we can try something else.\n for (let i = 0; i < array.length; i++) {\n array[i] = 0;\n }\n return array;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\nimport { wipe } from \"@stablelib/wipe\";\n\ndeclare function require(name: string): any;\n\nexport class NodeRandomSource implements RandomSource {\n isAvailable = false;\n isInstantiated = false;\n\n private _crypto: { randomBytes(n: number): Uint8Array } | undefined;\n\n constructor() {\n if (typeof require !== \"undefined\") {\n const nodeCrypto = require(\"crypto\");\n if (nodeCrypto && nodeCrypto.randomBytes) {\n this._crypto = nodeCrypto;\n this.isAvailable = true;\n this.isInstantiated = true;\n }\n }\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable || !this._crypto) {\n throw new Error(\"Node.js random byte generator is not available.\");\n }\n\n // Get random bytes (result is Buffer).\n let buffer = this._crypto.randomBytes(length);\n\n // Make sure we got the length that we requested.\n if (buffer.length !== length) {\n throw new Error(\"NodeRandomSource: got fewer bytes than requested\");\n }\n\n // Allocate output array.\n const out = new Uint8Array(length);\n\n // Copy bytes from buffer to output.\n for (let i = 0; i < out.length; i++) {\n out[i] = buffer[i];\n }\n\n // Cleanup.\n wipe(buffer);\n\n return out;\n }\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\nimport { BrowserRandomSource } from \"./browser\";\nimport { NodeRandomSource } from \"./node\";\n\nexport class SystemRandomSource implements RandomSource {\n isAvailable = false;\n name = \"\";\n private _source: RandomSource;\n\n constructor() {\n // Try browser.\n this._source = new BrowserRandomSource();\n if (this._source.isAvailable) {\n this.isAvailable = true;\n this.name = \"Browser\";\n return;\n }\n\n // If no browser source, try Node.\n this._source = new NodeRandomSource();\n if (this._source.isAvailable) {\n this.isAvailable = true;\n this.name = \"Node\";\n return;\n }\n\n // No sources, we're out of options.\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable) {\n throw new Error(\"System random byte generator is not available.\");\n }\n return this._source.randomBytes(length);\n }\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package int provides helper functions for integerss.\n */\n\n// Shim using 16-bit pieces.\nfunction imulShim(a: number, b: number): number {\n const ah = (a >>> 16) & 0xffff, al = a & 0xffff;\n const bh = (b >>> 16) & 0xffff, bl = b & 0xffff;\n return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);\n}\n\n/** 32-bit integer multiplication. */\n// Use system Math.imul if available, otherwise use our shim.\nexport const mul = (Math as { imul?(a: number, b: number): number }).imul || imulShim;\n\n/** 32-bit integer addition. */\nexport function add(a: number, b: number): number {\n return (a + b) | 0;\n}\n\n/** 32-bit integer subtraction. */\nexport function sub(a: number, b: number): number {\n return (a - b) | 0;\n}\n\n/** 32-bit integer left rotation */\nexport function rotl(x: number, n: number): number {\n return x << n | x >>> (32 - n);\n}\n\n/** 32-bit integer left rotation */\nexport function rotr(x: number, n: number): number {\n return x << (32 - n) | x >>> n;\n}\n\nfunction isIntegerShim(n: number): boolean {\n return typeof n === \"number\" && isFinite(n) && Math.floor(n) === n;\n}\n\n/**\n * Returns true if the argument is an integer number.\n *\n * In ES2015, Number.isInteger.\n */\nexport const isInteger = (Number as { isInteger?(n: number): boolean }).isInteger || isIntegerShim;\n\n/**\n * Math.pow(2, 53) - 1\n *\n * In ES2015 Number.MAX_SAFE_INTEGER.\n */\nexport const MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Returns true if the argument is a safe integer number\n * (-MIN_SAFE_INTEGER < number <= MAX_SAFE_INTEGER)\n *\n * In ES2015, Number.isSafeInteger.\n */\nexport const isSafeInteger = (n: number): boolean =>\n isInteger(n) && (n >= -MAX_SAFE_INTEGER && n <= MAX_SAFE_INTEGER);\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package binary provides functions for encoding and decoding numbers in byte arrays.\n */\n\nimport { isSafeInteger } from \"@stablelib/int\";\n\n// TODO(dchest): add asserts for correct value ranges and array offsets.\n\n/**\n * Reads 2 bytes from array starting at offset as big-endian\n * signed 16-bit integer and returns it.\n */\nexport function readInt16BE(array: Uint8Array, offset = 0): number {\n return (((array[offset + 0] << 8) | array[offset + 1]) << 16) >> 16;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as big-endian\n * unsigned 16-bit integer and returns it.\n */\nexport function readUint16BE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 0] << 8) | array[offset + 1]) >>> 0;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as little-endian\n * signed 16-bit integer and returns it.\n */\nexport function readInt16LE(array: Uint8Array, offset = 0): number {\n return (((array[offset + 1] << 8) | array[offset]) << 16) >> 16;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as little-endian\n * unsigned 16-bit integer and returns it.\n */\nexport function readUint16LE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 1] << 8) | array[offset]) >>> 0;\n}\n\n/**\n * Writes 2-byte big-endian representation of 16-bit unsigned\n * value to byte array starting at offset.\n *\n * If byte array is not given, creates a new 2-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint16BE(value: number, out = new Uint8Array(2), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 8;\n out[offset + 1] = value >>> 0;\n return out;\n}\n\nexport const writeInt16BE = writeUint16BE;\n\n/**\n * Writes 2-byte little-endian representation of 16-bit unsigned\n * value to array starting at offset.\n *\n * If byte array is not given, creates a new 2-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint16LE(value: number, out = new Uint8Array(2), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 0;\n out[offset + 1] = value >>> 8;\n return out;\n}\n\nexport const writeInt16LE = writeUint16LE;\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * signed 32-bit integer and returns it.\n */\nexport function readInt32BE(array: Uint8Array, offset = 0): number {\n return (array[offset] << 24) |\n (array[offset + 1] << 16) |\n (array[offset + 2] << 8) |\n array[offset + 3];\n}\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * unsigned 32-bit integer and returns it.\n */\nexport function readUint32BE(array: Uint8Array, offset = 0): number {\n return ((array[offset] << 24) |\n (array[offset + 1] << 16) |\n (array[offset + 2] << 8) |\n array[offset + 3]) >>> 0;\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * signed 32-bit integer and returns it.\n */\nexport function readInt32LE(array: Uint8Array, offset = 0): number {\n return (array[offset + 3] << 24) |\n (array[offset + 2] << 16) |\n (array[offset + 1] << 8) |\n array[offset];\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * unsigned 32-bit integer and returns it.\n */\nexport function readUint32LE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 3] << 24) |\n (array[offset + 2] << 16) |\n (array[offset + 1] << 8) |\n array[offset]) >>> 0;\n}\n\n/**\n * Writes 4-byte big-endian representation of 32-bit unsigned\n * value to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint32BE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 24;\n out[offset + 1] = value >>> 16;\n out[offset + 2] = value >>> 8;\n out[offset + 3] = value >>> 0;\n return out;\n}\n\nexport const writeInt32BE = writeUint32BE;\n\n/**\n * Writes 4-byte little-endian representation of 32-bit unsigned\n * value to array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint32LE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 0;\n out[offset + 1] = value >>> 8;\n out[offset + 2] = value >>> 16;\n out[offset + 3] = value >>> 24;\n return out;\n}\n\n\nexport const writeInt32LE = writeUint32LE;\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * signed 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports exact\n * numbers in range -9007199254740991 to 9007199254740991.\n * If the number stored in the byte array is outside this range,\n * the result is not exact.\n */\nexport function readInt64BE(array: Uint8Array, offset = 0): number {\n const hi = readInt32BE(array, offset);\n const lo = readInt32BE(array, offset + 4);\n return hi * 0x100000000 + lo - ((lo>>31) * 0x100000000);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * unsigned 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports values up to 2^53-1.\n */\nexport function readUint64BE(array: Uint8Array, offset = 0): number {\n const hi = readUint32BE(array, offset);\n const lo = readUint32BE(array, offset + 4);\n return hi * 0x100000000 + lo;\n}\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * signed 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports exact\n * numbers in range -9007199254740991 to 9007199254740991.\n * If the number stored in the byte array is outside this range,\n * the result is not exact.\n */\nexport function readInt64LE(array: Uint8Array, offset = 0): number {\n const lo = readInt32LE(array, offset);\n const hi = readInt32LE(array, offset + 4);\n return hi * 0x100000000 + lo - ((lo>>31) * 0x100000000);\n}\n\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * unsigned 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports values up to 2^53-1.\n */\nexport function readUint64LE(array: Uint8Array, offset = 0): number {\n const lo = readUint32LE(array, offset);\n const hi = readUint32LE(array, offset + 4);\n return hi * 0x100000000 + lo;\n}\n\n/**\n * Writes 8-byte big-endian representation of 64-bit unsigned\n * value to byte array starting at offset.\n *\n * Due to JavaScript limitation, supports values up to 2^53-1.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint64BE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n writeUint32BE(value / 0x100000000 >>> 0, out, offset);\n writeUint32BE(value >>> 0, out, offset + 4);\n return out;\n}\n\nexport const writeInt64BE = writeUint64BE;\n\n/**\n * Writes 8-byte little-endian representation of 64-bit unsigned\n * value to byte array starting at offset.\n *\n * Due to JavaScript limitation, supports values up to 2^53-1.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint64LE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n writeUint32LE(value >>> 0, out, offset);\n writeUint32LE(value / 0x100000000 >>> 0, out, offset + 4);\n return out;\n}\n\nexport const writeInt64LE = writeUint64LE;\n\n/**\n * Reads bytes from array starting at offset as big-endian\n * unsigned bitLen-bit integer and returns it.\n *\n * Supports bit lengths divisible by 8, up to 48.\n */\nexport function readUintBE(bitLength: number, array: Uint8Array, offset = 0): number {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"readUintBE supports only bitLengths divisible by 8\");\n }\n if (bitLength / 8 > array.length - offset) {\n throw new Error(\"readUintBE: array is too short for the given bitLength\");\n }\n let result = 0;\n let mul = 1;\n for (let i = bitLength / 8 + offset - 1; i >= offset; i--) {\n result += array[i] * mul;\n mul *= 256;\n }\n return result;\n}\n\n/**\n * Reads bytes from array starting at offset as little-endian\n * unsigned bitLen-bit integer and returns it.\n *\n * Supports bit lengths divisible by 8, up to 48.\n */\nexport function readUintLE(bitLength: number, array: Uint8Array, offset = 0): number {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"readUintLE supports only bitLengths divisible by 8\");\n }\n if (bitLength / 8 > array.length - offset) {\n throw new Error(\"readUintLE: array is too short for the given bitLength\");\n }\n let result = 0;\n let mul = 1;\n for (let i = offset; i < offset + bitLength / 8; i++) {\n result += array[i] * mul;\n mul *= 256;\n }\n return result;\n}\n\n/**\n * Writes a big-endian representation of bitLen-bit unsigned\n * value to array starting at offset.\n *\n * Supports bit lengths divisible by 8, up to 48.\n *\n * If byte array is not given, creates a new one.\n *\n * Returns the output byte array.\n */\nexport function writeUintBE(bitLength: number, value: number,\n out = new Uint8Array(bitLength / 8), offset = 0): Uint8Array {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"writeUintBE supports only bitLengths divisible by 8\");\n }\n if (!isSafeInteger(value)) {\n throw new Error(\"writeUintBE value must be an integer\");\n }\n let div = 1;\n for (let i = bitLength / 8 + offset - 1; i >= offset; i--) {\n out[i] = (value / div) & 0xff;\n div *= 256;\n }\n return out;\n}\n\n/**\n * Writes a little-endian representation of bitLen-bit unsigned\n * value to array starting at offset.\n *\n * Supports bit lengths divisible by 8, up to 48.\n *\n * If byte array is not given, creates a new one.\n *\n * Returns the output byte array.\n */\nexport function writeUintLE(bitLength: number, value: number,\n out = new Uint8Array(bitLength / 8), offset = 0): Uint8Array {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"writeUintLE supports only bitLengths divisible by 8\");\n }\n if (!isSafeInteger(value)) {\n throw new Error(\"writeUintLE value must be an integer\");\n }\n let div = 1;\n for (let i = offset; i < offset + bitLength / 8; i++) {\n out[i] = (value / div) & 0xff;\n div *= 256;\n }\n return out;\n}\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * 32-bit floating-point number and returns it.\n */\nexport function readFloat32BE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat32(offset);\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * 32-bit floating-point number and returns it.\n */\nexport function readFloat32LE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat32(offset, true);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * 64-bit floating-point number (\"double\") and returns it.\n */\nexport function readFloat64BE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat64(offset);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * 64-bit floating-point number (\"double\") and returns it.\n */\nexport function readFloat64LE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat64(offset, true);\n}\n\n/**\n * Writes 4-byte big-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat32BE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat32(offset, value);\n return out;\n}\n\n/**\n * Writes 4-byte little-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat32LE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat32(offset, value, true);\n return out;\n}\n\n/**\n * Writes 8-byte big-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat64BE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat64(offset, value);\n return out;\n}\n\n/**\n * Writes 8-byte little-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat64LE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat64(offset, value, true);\n return out;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package random provides functions to access system's\n * cryptographically secure random byte generator.\n */\n\nimport { RandomSource } from \"./source\";\nimport { SystemRandomSource } from \"./source/system\";\nimport { readUint32LE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport { RandomSource } from \"./source\";\n\nexport const defaultRandomSource = new SystemRandomSource();\n\nexport function randomBytes(length: number, prng: RandomSource = defaultRandomSource): Uint8Array {\n return prng.randomBytes(length);\n}\n\n/**\n * Returns a uniformly random unsigned 32-bit integer.\n */\nexport function randomUint32(prng: RandomSource = defaultRandomSource): number {\n // Generate 4-byte random buffer.\n const buf = randomBytes(4, prng);\n\n // Convert bytes from buffer into a 32-bit integer.\n // It's not important which byte order to use, since\n // the result is random.\n const result = readUint32LE(buf);\n\n // Clean the buffer.\n wipe(buf);\n\n return result;\n}\n\n/** 62 alphanumeric characters for default charset of randomString() */\nconst ALPHANUMERIC = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n/**\n * Returns a uniform random string of the given length\n * with characters from the given charset.\n *\n * Charset must not have more than 256 characters.\n *\n * Default charset generates case-sensitive alphanumeric\n * strings (0-9, A-Z, a-z).\n */\nexport function randomString(\n length: number,\n charset = ALPHANUMERIC,\n prng: RandomSource = defaultRandomSource\n): string {\n if (charset.length < 2) {\n throw new Error(\"randomString charset is too short\");\n }\n if (charset.length > 256) {\n throw new Error(\"randomString charset is too long\");\n }\n let out = '';\n const charsLen = charset.length;\n const maxByte = 256 - (256 % charsLen);\n while (length > 0) {\n const buf = randomBytes(Math.ceil(length * 256 / maxByte), prng);\n for (let i = 0; i < buf.length && length > 0; i++) {\n const randomByte = buf[i];\n if (randomByte < maxByte) {\n out += charset.charAt(randomByte % charsLen);\n length--;\n }\n }\n wipe(buf);\n }\n return out;\n}\n\n/**\n * Returns uniform random string containing at least the given\n * number of bits of entropy.\n *\n * For example, randomStringForEntropy(128) will return a 22-character\n * alphanumeric string, while randomStringForEntropy(128, \"0123456789\")\n * will return a 39-character numeric string, both will contain at\n * least 128 bits of entropy.\n *\n * Default charset generates case-sensitive alphanumeric\n * strings (0-9, A-Z, a-z).\n */\nexport function randomStringForEntropy(\n bits: number,\n charset = ALPHANUMERIC,\n prng: RandomSource = defaultRandomSource\n): string {\n const length = Math.ceil(bits / (Math.log(charset.length) / Math.LN2));\n return randomString(length, charset, prng);\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package x25519 implements X25519 key agreement.\n */\n\nimport { randomBytes, RandomSource } from \"@stablelib/random\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 32;\nexport const SHARED_KEY_LENGTH = 32;\n\n// TODO(dchest): some functions are copies of ../sign/ed25519.\n// Find a way to combine them without opening up to public.\n\n// Ported from TweetNaCl.js, which is ported from TweetNaCl\n// by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n// https://tweetnacl.js.org\n\n// TweetNaCl contributors:\n// Daniel J. Bernstein, Bernard van Gastel, Wesley Janssen,\n// Tanja Lange, Peter Schwabe, Sjaak Smetsers.\n// Public domain.\n// https://tweetnacl.cr.yp.to/\n\ntype GF = Float64Array;\n\n// Returns new zero-filled 16-element GF (Float64Array).\n// If passed an array of numbers, prefills the returned\n// array with them.\n//\n// We use Float64Array, because we need 48-bit numbers\n// for this implementation.\nfunction gf(init?: number[]): GF {\n const r = new Float64Array(16);\n if (init) {\n for (let i = 0; i < init.length; i++) {\n r[i] = init[i];\n }\n }\n return r;\n}\n\n// Base point.\nconst _9 = new Uint8Array(32); _9[0] = 9;\n\nconst _121665 = gf([0xdb41, 1]);\n\nfunction car25519(o: GF) {\n let c = 1;\n for (let i = 0; i < 16; i++) {\n let v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c - 1 + 37 * (c - 1);\n}\n\nfunction sel25519(p: GF, q: GF, b: number) {\n const c = ~(b - 1);\n for (let i = 0; i < 16; i++) {\n const t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o: Uint8Array, n: GF) {\n const m = gf();\n const t = gf();\n for (let i = 0; i < 16; i++) {\n t[i] = n[i];\n }\n car25519(t);\n car25519(t);\n car25519(t);\n for (let j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (let i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);\n m[i - 1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);\n const b = (m[15] >> 16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1 - b);\n }\n for (let i = 0; i < 16; i++) {\n o[2 * i] = t[i] & 0xff;\n o[2 * i + 1] = t[i] >> 8;\n }\n}\n\nfunction unpack25519(o: GF, n: Uint8Array) {\n for (let i = 0; i < 16; i++) {\n o[i] = n[2 * i] + (n[2 * i + 1] << 8);\n }\n o[15] &= 0x7fff;\n}\n\nfunction add(o: GF, a: GF, b: GF) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] + b[i];\n }\n}\n\nfunction sub(o: GF, a: GF, b: GF) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] - b[i];\n }\n}\n\nfunction mul(o: GF, a: GF, b: GF) {\n let v: number, c: number,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n\n o[0] = t0;\n o[1] = t1;\n o[2] = t2;\n o[3] = t3;\n o[4] = t4;\n o[5] = t5;\n o[6] = t6;\n o[7] = t7;\n o[8] = t8;\n o[9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction square(o: GF, a: GF) {\n mul(o, a, a);\n}\n\nfunction inv25519(o: GF, inp: GF) {\n const c = gf();\n for (let i = 0; i < 16; i++) {\n c[i] = inp[i];\n }\n for (let i = 253; i >= 0; i--) {\n square(c, c);\n if (i !== 2 && i !== 4) {\n mul(c, c, inp);\n }\n }\n for (let i = 0; i < 16; i++) {\n o[i] = c[i];\n }\n}\n\nexport function scalarMult(n: Uint8Array, p: Uint8Array): Uint8Array {\n const z = new Uint8Array(32);\n const x = new Float64Array(80);\n const a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n\n for (let i = 0; i < 31; i++) {\n z[i] = n[i];\n }\n z[31] = (n[31] & 127) | 64;\n z[0] &= 248;\n\n unpack25519(x, p);\n\n for (let i = 0; i < 16; i++) {\n b[i] = x[i];\n }\n\n a[0] = d[0] = 1;\n\n for (let i = 254; i >= 0; --i) {\n const r = (z[i >>> 3] >>> (i & 7)) & 1;\n sel25519(a, b, r);\n sel25519(c, d, r);\n add(e, a, c);\n sub(a, a, c);\n add(c, b, d);\n sub(b, b, d);\n square(d, e);\n square(f, a);\n mul(a, c, a);\n mul(c, b, e);\n add(e, a, c);\n sub(a, a, c);\n square(b, a);\n sub(c, d, f);\n mul(a, c, _121665);\n add(a, a, d);\n mul(c, c, a);\n mul(a, d, f);\n mul(d, b, x);\n square(b, e);\n sel25519(a, b, r);\n sel25519(c, d, r);\n }\n for (let i = 0; i < 16; i++) {\n x[i + 16] = a[i];\n x[i + 32] = c[i];\n x[i + 48] = b[i];\n x[i + 64] = d[i];\n }\n const x32 = x.subarray(32);\n const x16 = x.subarray(16);\n inv25519(x32, x32);\n mul(x16, x16, x32);\n const q = new Uint8Array(32);\n pack25519(q, x16);\n return q;\n}\n\nexport function scalarMultBase(n: Uint8Array): Uint8Array {\n return scalarMult(n, _9);\n}\n\nexport interface KeyPair {\n publicKey: Uint8Array;\n secretKey: Uint8Array;\n}\n\nexport function generateKeyPairFromSeed(seed: Uint8Array): KeyPair {\n if (seed.length !== SECRET_KEY_LENGTH) {\n throw new Error(`x25519: seed must be ${SECRET_KEY_LENGTH} bytes`);\n }\n const secretKey = new Uint8Array(seed);\n const publicKey = scalarMultBase(secretKey);\n return {\n publicKey,\n secretKey\n };\n}\n\nexport function generateKeyPair(prng?: RandomSource): KeyPair {\n const seed = randomBytes(32, prng);\n const result = generateKeyPairFromSeed(seed);\n wipe(seed);\n return result;\n}\n\n/**\n * Returns a shared key between our secret key and a peer's public key.\n *\n * Throws an error if the given keys are of wrong length.\n *\n * If rejectZero is true throws if the calculated shared key is all-zero.\n * From RFC 7748:\n *\n * > Protocol designers using Diffie-Hellman over the curves defined in\n * > this document must not assume \"contributory behavior\". Specially,\n * > contributory behavior means that both parties' private keys\n * > contribute to the resulting shared key. Since curve25519 and\n * > curve448 have cofactors of 8 and 4 (respectively), an input point of\n * > small order will eliminate any contribution from the other party's\n * > private key. This situation can be detected by checking for the all-\n * > zero output, which implementations MAY do, as specified in Section 6.\n * > However, a large number of existing implementations do not do this.\n *\n * IMPORTANT: the returned key is a raw result of scalar multiplication.\n * To use it as a key material, hash it with a cryptographic hash function.\n */\nexport function sharedKey(mySecretKey: Uint8Array, theirPublicKey: Uint8Array, rejectZero = false): Uint8Array {\n if (mySecretKey.length !== PUBLIC_KEY_LENGTH) {\n throw new Error(\"X25519: incorrect secret key length\");\n }\n if (theirPublicKey.length !== PUBLIC_KEY_LENGTH) {\n throw new Error(\"X25519: incorrect public key length\");\n }\n\n const result = scalarMult(mySecretKey, theirPublicKey);\n\n if (rejectZero) {\n let zeros = 0;\n for (let i = 0; i < result.length; i++) {\n zeros |= result[i];\n }\n if (zeros === 0) {\n throw new Error(\"X25519: invalid shared key\");\n }\n }\n\n return result;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package salsa20 implements Salsa20 stream cipher.\n */\n\nimport { writeUint32LE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\n// Number of Salsa20 rounds (Salsa20/20).\nconst ROUNDS = 20;\n\n/**\n * Applies the Salsa20 core function to 16-byte input,\n * 32-byte key key, and puts the result into 64-byte array out.\n */\nfunction core(out: Uint8Array, input: Uint8Array, key: Uint8Array): void {\n let j0 = 0x61707865; // \"expa\"\n let j1 = (key[3] << 24) | (key[2] << 16) | (key[1] << 8) | key[0];\n let j2 = (key[7] << 24) | (key[6] << 16) | (key[5] << 8) | key[4];\n let j3 = (key[11] << 24) | (key[10] << 16) | (key[9] << 8) | key[8];\n let j4 = (key[15] << 24) | (key[14] << 16) | (key[13] << 8) | key[12];\n let j5 = 0x3320646E; // \"nd 3\"\n let j6 = (input[3] << 24) | (input[2] << 16) | (input[1] << 8) | input[0];\n let j7 = (input[7] << 24) | (input[6] << 16) | (input[5] << 8) | input[4];\n let j8 = (input[11] << 24) | (input[10] << 16) | (input[9] << 8) | input[8];\n let j9 = (input[15] << 24) | (input[14] << 16) | (input[13] << 8) | input[12];\n let j10 = 0x79622D32; // \"2-by\"\n let j11 = (key[19] << 24) | (key[18] << 16) | (key[17] << 8) | key[16];\n let j12 = (key[23] << 24) | (key[22] << 16) | (key[21] << 8) | key[20];\n let j13 = (key[27] << 24) | (key[26] << 16) | (key[25] << 8) | key[24];\n let j14 = (key[31] << 24) | (key[30] << 16) | (key[29] << 8) | key[28];\n let j15 = 0x6B206574; // \"te k\"\n\n let x0 = j0;\n let x1 = j1;\n let x2 = j2;\n let x3 = j3;\n let x4 = j4;\n let x5 = j5;\n let x6 = j6;\n let x7 = j7;\n let x8 = j8;\n let x9 = j9;\n let x10 = j10;\n let x11 = j11;\n let x12 = j12;\n let x13 = j13;\n let x14 = j14;\n let x15 = j15;\n let u: number;\n\n for (let i = 0; i < ROUNDS; i += 2) {\n u = x0 + x12 | 0;\n x4 ^= u << 7 | u >>> (32 - 7);\n u = x4 + x0 | 0;\n x8 ^= u << 9 | u >>> (32 - 9);\n u = x8 + x4 | 0;\n x12 ^= u << 13 | u >>> (32 - 13);\n u = x12 + x8 | 0;\n x0 ^= u << 18 | u >>> (32 - 18);\n\n u = x5 + x1 | 0;\n x9 ^= u << 7 | u >>> (32 - 7);\n u = x9 + x5 | 0;\n x13 ^= u << 9 | u >>> (32 - 9);\n u = x13 + x9 | 0;\n x1 ^= u << 13 | u >>> (32 - 13);\n u = x1 + x13 | 0;\n x5 ^= u << 18 | u >>> (32 - 18);\n\n u = x10 + x6 | 0;\n x14 ^= u << 7 | u >>> (32 - 7);\n u = x14 + x10 | 0;\n x2 ^= u << 9 | u >>> (32 - 9);\n u = x2 + x14 | 0;\n x6 ^= u << 13 | u >>> (32 - 13);\n u = x6 + x2 | 0;\n x10 ^= u << 18 | u >>> (32 - 18);\n\n u = x15 + x11 | 0;\n x3 ^= u << 7 | u >>> (32 - 7);\n u = x3 + x15 | 0;\n x7 ^= u << 9 | u >>> (32 - 9);\n u = x7 + x3 | 0;\n x11 ^= u << 13 | u >>> (32 - 13);\n u = x11 + x7 | 0;\n x15 ^= u << 18 | u >>> (32 - 18);\n\n u = x0 + x3 | 0;\n x1 ^= u << 7 | u >>> (32 - 7);\n u = x1 + x0 | 0;\n x2 ^= u << 9 | u >>> (32 - 9);\n u = x2 + x1 | 0;\n x3 ^= u << 13 | u >>> (32 - 13);\n u = x3 + x2 | 0;\n x0 ^= u << 18 | u >>> (32 - 18);\n\n u = x5 + x4 | 0;\n x6 ^= u << 7 | u >>> (32 - 7);\n u = x6 + x5 | 0;\n x7 ^= u << 9 | u >>> (32 - 9);\n u = x7 + x6 | 0;\n x4 ^= u << 13 | u >>> (32 - 13);\n u = x4 + x7 | 0;\n x5 ^= u << 18 | u >>> (32 - 18);\n\n u = x10 + x9 | 0;\n x11 ^= u << 7 | u >>> (32 - 7);\n u = x11 + x10 | 0;\n x8 ^= u << 9 | u >>> (32 - 9);\n u = x8 + x11 | 0;\n x9 ^= u << 13 | u >>> (32 - 13);\n u = x9 + x8 | 0;\n x10 ^= u << 18 | u >>> (32 - 18);\n\n u = x15 + x14 | 0;\n x12 ^= u << 7 | u >>> (32 - 7);\n u = x12 + x15 | 0;\n x13 ^= u << 9 | u >>> (32 - 9);\n u = x13 + x12 | 0;\n x14 ^= u << 13 | u >>> (32 - 13);\n u = x14 + x13 | 0;\n x15 ^= u << 18 | u >>> (32 - 18);\n }\n writeUint32LE(x0 + j0 | 0, out, 0);\n writeUint32LE(x1 + j1 | 0, out, 4);\n writeUint32LE(x2 + j2 | 0, out, 8);\n writeUint32LE(x3 + j3 | 0, out, 12);\n writeUint32LE(x4 + j4 | 0, out, 16);\n writeUint32LE(x5 + j5 | 0, out, 20);\n writeUint32LE(x6 + j6 | 0, out, 24);\n writeUint32LE(x7 + j7 | 0, out, 28);\n writeUint32LE(x8 + j8 | 0, out, 32);\n writeUint32LE(x9 + j9 | 0, out, 36);\n writeUint32LE(x10 + j10 | 0, out, 40);\n writeUint32LE(x11 + j11 | 0, out, 44);\n writeUint32LE(x12 + j12 | 0, out, 48);\n writeUint32LE(x13 + j13 | 0, out, 52);\n writeUint32LE(x14 + j14 | 0, out, 56);\n writeUint32LE(x15 + j15 | 0, out, 60);\n}\n\n/**\n * Encrypt src with Salsa20/20 stream generated for the given 32-byte key\n * and 8-byte and write the result into dst and return it.\n *\n * dst and src may be the same, but otherwise must not overlap.\n *\n * Never use the same key and nonce to encrypt more than one message.\n *\n * If nonceInplaceCounterLength is not 0, the nonce is assumed to be a 16-byte\n * array with stream counter in first nonceInplaceCounterLength bytes and nonce\n * in the last remaining bytes. The counter will be incremented inplace for\n * each Salsa20 block. This is useful if you need to encrypt one stream of data\n * in chunks.\n */\nexport function streamXOR(key: Uint8Array, nonce: Uint8Array,\n src: Uint8Array, dst: Uint8Array, nonceInplaceCounterLength = 0): Uint8Array {\n // We only support 256-bit keys.\n if (key.length !== 32) {\n throw new Error(\"Salsa20: key size must be 32 bytes\");\n }\n\n if (dst.length < src.length) {\n throw new Error(\"Salsa20: destination is shorter than source\");\n }\n\n let nc: Uint8Array;\n let counterStart: number;\n\n if (nonceInplaceCounterLength === 0) {\n if (nonce.length !== 8) {\n throw new Error(\"Salsa20 nonce must be 8 bytes\");\n }\n nc = new Uint8Array(16);\n // First bytes of nc are nonce, set it.\n nc.set(nonce);\n // Last bytes are counter.\n counterStart = nonce.length;\n } else {\n if (nonce.length !== 16) {\n throw new Error(\"Salsa20 nonce with counter must be 16 bytes\");\n }\n // This will update passed nonce with counter inplace.\n nc = nonce;\n counterStart = 16 - nonceInplaceCounterLength;\n }\n\n // Allocate temporary space for Salsa20 block.\n const block = new Uint8Array(64);\n\n for (let i = 0; i < src.length; i += 64) {\n // Generate a block.\n core(block, nc, key);\n\n // XOR block bytes with src into dst.\n for (let j = i; j < i + 64 && j < src.length; j++) {\n dst[j] = src[j] ^ block[j - i];\n }\n\n // Increment counter.\n incrementCounter(nc, counterStart, nc.length - counterStart);\n }\n\n // Cleanup temporary space.\n wipe(block);\n\n if (nonceInplaceCounterLength === 0) {\n // Cleanup counter.\n wipe(nc);\n }\n\n return dst;\n}\n\n/**\n * Generate Salsa20/20 stream for the given 32-byte key and 8-byte nonce\n * and write it into dst and return it.\n *\n * Never use the same key and nonce to generate more than one stream.\n *\n * If nonceInplaceCounterLength is not 0, it behaves the same\n * with respect to the nonce as described in streamXOR documentation.\n *\n * stream is like streamXOR with all-zero src.\n */\nexport function stream(key: Uint8Array, nonce: Uint8Array,\n dst: Uint8Array, nonceInplaceCounterLength = 0): Uint8Array {\n wipe(dst);\n return streamXOR(key, nonce, dst, dst, nonceInplaceCounterLength);\n}\n\nfunction incrementCounter(counter: Uint8Array, pos: number, len: number) {\n let carry = 1;\n while (len--) {\n carry = carry + (counter[pos] & 0xff) | 0;\n counter[pos] = carry & 0xff;\n carry >>>= 8;\n pos++;\n }\n if (carry > 0) {\n throw new Error(\"Salsa20: counter overflow\");\n }\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package xsalsa20 implements XSalsa20 stream cipher.\n */\n\nimport { writeUint32LE } from \"@stablelib/binary\";\nimport { streamXOR as salsaStreamXOR } from \"@stablelib/salsa20\";\nimport { wipe } from \"@stablelib/wipe\";\n\n/**\n * Encrypt src with Salsa20/20 stream generated for the given 32-byte key\n * and 24-byte and write the result into dst and return it.\n *\n * dst and src may be the same, but otherwise must not overlap.\n *\n * Never use the same key and nonce to encrypt more than one message.\n */\nexport function streamXOR(key: Uint8Array, nonce: Uint8Array, src: Uint8Array,\n dst: Uint8Array, nonceInplaceCounterLength = 0): Uint8Array {\n\n if (nonceInplaceCounterLength === 0) {\n if (nonce.length !== 24) {\n throw new Error(\"XSalsa20 nonce must be 24 bytes\");\n }\n } else {\n if (nonce.length !== 32) {\n throw new Error(\"XSalsa20 nonce with counter must be 32 bytes\");\n }\n }\n\n // Use HSalsa one-way function to transform first 16 bytes of\n // 24-byte extended nonce and key into a new key for Salsa\n // stream -- \"subkey\".\n const subkey = hsalsa(key, nonce.subarray(0, 16), new Uint8Array(32));\n\n // Use last 8 bytes of 24-byte extended nonce as an actual nonce,\n // and a subkey derived in the previous step as key to encrypt.\n //\n // If nonceInplaceCounterLength > 0, we'll still pass the correct\n // nonce || counter, as we don't limit the end of nonce subarray.\n const result = salsaStreamXOR(subkey, nonce.subarray(16), src, dst,\n nonceInplaceCounterLength);\n\n // Clean subkey.\n wipe(subkey);\n\n return result;\n}\n\n/**\n * Generate Salsa20/20 stream for the given 32-byte key and\n * 24-byte nonce and write it into dst and return it.\n *\n * Never use the same key and nonce to generate more than one stream.\n *\n * stream is like streamXOR with all-zero src.\n */\nexport function stream(key: Uint8Array, nonce: Uint8Array, dst: Uint8Array,\n nonceInplaceCounterLength = 0): Uint8Array {\n\n wipe(dst);\n return streamXOR(key, nonce, dst, dst, nonceInplaceCounterLength);\n}\n\n// Number of Salsa20 rounds (Salsa20/20).\nconst ROUNDS = 20;\n\n/**\n * HSalsa20 is a one-way function used in XSalsa20 to extend nonce,\n * and in NaCl to hash X25519 shared keys. It takes 32-byte key and\n * 16-byte src and writes 32-byte result into dst and returns it.\n */\nexport function hsalsa(key: Uint8Array, src: Uint8Array, dst: Uint8Array): Uint8Array {\n let x0 = 0x61707865; // \"expa\"\n let x1 = (key[3] << 24) | (key[2] << 16) | (key[1] << 8) | key[0];\n let x2 = (key[7] << 24) | (key[6] << 16) | (key[5] << 8) | key[4];\n let x3 = (key[11] << 24) | (key[10] << 16) | (key[9] << 8) | key[8];\n let x4 = (key[15] << 24) | (key[14] << 16) | (key[13] << 8) | key[12];\n let x5 = 0x3320646E; // \"nd 3\"\n let x6 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];\n let x7 = (src[7] << 24) | (src[6] << 16) | (src[5] << 8) | src[4];\n let x8 = (src[11] << 24) | (src[10] << 16) | (src[9] << 8) | src[8];\n let x9 = (src[15] << 24) | (src[14] << 16) | (src[13] << 8) | src[12];\n let x10 = 0x79622D32; // \"2-by\"\n let x11 = (key[19] << 24) | (key[18] << 16) | (key[17] << 8) | key[16];\n let x12 = (key[23] << 24) | (key[22] << 16) | (key[21] << 8) | key[20];\n let x13 = (key[27] << 24) | (key[26] << 16) | (key[25] << 8) | key[24];\n let x14 = (key[31] << 24) | (key[30] << 16) | (key[29] << 8) | key[28];\n let x15 = 0x6B206574; // \"te k\"\n\n let u: number;\n\n for (let i = 0; i < ROUNDS; i += 2) {\n u = x0 + x12 | 0;\n x4 ^= u << 7 | u >>> (32 - 7);\n u = x4 + x0 | 0;\n x8 ^= u << 9 | u >>> (32 - 9);\n u = x8 + x4 | 0;\n x12 ^= u << 13 | u >>> (32 - 13);\n u = x12 + x8 | 0;\n x0 ^= u << 18 | u >>> (32 - 18);\n\n u = x5 + x1 | 0;\n x9 ^= u << 7 | u >>> (32 - 7);\n u = x9 + x5 | 0;\n x13 ^= u << 9 | u >>> (32 - 9);\n u = x13 + x9 | 0;\n x1 ^= u << 13 | u >>> (32 - 13);\n u = x1 + x13 | 0;\n x5 ^= u << 18 | u >>> (32 - 18);\n\n u = x10 + x6 | 0;\n x14 ^= u << 7 | u >>> (32 - 7);\n u = x14 + x10 | 0;\n x2 ^= u << 9 | u >>> (32 - 9);\n u = x2 + x14 | 0;\n x6 ^= u << 13 | u >>> (32 - 13);\n u = x6 + x2 | 0;\n x10 ^= u << 18 | u >>> (32 - 18);\n\n u = x15 + x11 | 0;\n x3 ^= u << 7 | u >>> (32 - 7);\n u = x3 + x15 | 0;\n x7 ^= u << 9 | u >>> (32 - 9);\n u = x7 + x3 | 0;\n x11 ^= u << 13 | u >>> (32 - 13);\n u = x11 + x7 | 0;\n x15 ^= u << 18 | u >>> (32 - 18);\n\n u = x0 + x3 | 0;\n x1 ^= u << 7 | u >>> (32 - 7);\n u = x1 + x0 | 0;\n x2 ^= u << 9 | u >>> (32 - 9);\n u = x2 + x1 | 0;\n x3 ^= u << 13 | u >>> (32 - 13);\n u = x3 + x2 | 0;\n x0 ^= u << 18 | u >>> (32 - 18);\n\n u = x5 + x4 | 0;\n x6 ^= u << 7 | u >>> (32 - 7);\n u = x6 + x5 | 0;\n x7 ^= u << 9 | u >>> (32 - 9);\n u = x7 + x6 | 0;\n x4 ^= u << 13 | u >>> (32 - 13);\n u = x4 + x7 | 0;\n x5 ^= u << 18 | u >>> (32 - 18);\n\n u = x10 + x9 | 0;\n x11 ^= u << 7 | u >>> (32 - 7);\n u = x11 + x10 | 0;\n x8 ^= u << 9 | u >>> (32 - 9);\n u = x8 + x11 | 0;\n x9 ^= u << 13 | u >>> (32 - 13);\n u = x9 + x8 | 0;\n x10 ^= u << 18 | u >>> (32 - 18);\n\n u = x15 + x14 | 0;\n x12 ^= u << 7 | u >>> (32 - 7);\n u = x12 + x15 | 0;\n x13 ^= u << 9 | u >>> (32 - 9);\n u = x13 + x12 | 0;\n x14 ^= u << 13 | u >>> (32 - 13);\n u = x14 + x13 | 0;\n x15 ^= u << 18 | u >>> (32 - 18);\n }\n writeUint32LE(x0, dst, 0);\n writeUint32LE(x5, dst, 4);\n writeUint32LE(x10, dst, 8);\n writeUint32LE(x15, dst, 12);\n writeUint32LE(x6, dst, 16);\n writeUint32LE(x7, dst, 20);\n writeUint32LE(x8, dst, 24);\n writeUint32LE(x9, dst, 28);\n return dst;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package constant-time provides functions for performing algorithmically constant-time operations.\n */\n\n/**\n * NOTE! Due to the inability to guarantee real constant time evaluation of\n * anything in JavaScript VM, this is module is the best effort.\n */\n\n/**\n * Returns resultIfOne if subject is 1, or resultIfZero if subject is 0.\n *\n * Supports only 32-bit integers, so resultIfOne or resultIfZero are not\n * integers, they'll be converted to them with bitwise operations.\n */\nexport function select(subject: number, resultIfOne: number, resultIfZero: number): number {\n return (~(subject - 1) & resultIfOne) | ((subject - 1) & resultIfZero);\n}\n\n/**\n * Returns 1 if a <= b, or 0 if not.\n * Arguments must be positive 32-bit integers less than or equal to 2^31 - 1.\n */\nexport function lessOrEqual(a: number, b: number): number {\n return (((a | 0) - (b | 0) - 1) >>> 31) & 1;\n}\n\n/**\n * Returns 1 if a and b are of equal length and their contents\n * are equal, or 0 otherwise.\n *\n * Note that unlike in equal(), zero-length inputs are considered\n * the same, so this function will return 1.\n */\nexport function compare(a: Uint8Array, b: Uint8Array): number {\n if (a.length !== b.length) {\n return 0;\n }\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a[i] ^ b[i];\n }\n return (1 & ((result - 1) >>> 8));\n}\n\n/**\n * Returns true if a and b are of equal non-zero length,\n * and their contents are equal, or false otherwise.\n *\n * Note that unlike in compare() zero-length inputs are considered\n * _not_ equal, so this function will return false.\n */\nexport function equal(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length === 0 || b.length === 0) {\n return false;\n }\n return compare(a, b) !== 0;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package poly1305 implements Poly1305 one-time message authentication algorithm.\n */\n\nimport { equal as constantTimeEqual } from \"@stablelib/constant-time\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const DIGEST_LENGTH = 16;\n\n// Port of Andrew Moon's Poly1305-donna-16. Public domain.\n// https://github.com/floodyberry/poly1305-donna\n\n/**\n * Poly1305 computes 16-byte authenticator of message using\n * a one-time 32-byte key.\n *\n * Important: key should be used for only one message,\n * it should never repeat.\n */\nexport class Poly1305 {\n readonly digestLength = DIGEST_LENGTH;\n\n private _buffer = new Uint8Array(16);\n private _r = new Uint16Array(10);\n private _h = new Uint16Array(10);\n private _pad = new Uint16Array(8);\n private _leftover = 0;\n private _fin = 0;\n private _finished = false;\n\n constructor(key: Uint8Array) {\n let t0 = key[0] | key[1] << 8; this._r[0] = (t0) & 0x1fff;\n let t1 = key[2] | key[3] << 8; this._r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n let t2 = key[4] | key[5] << 8; this._r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n let t3 = key[6] | key[7] << 8; this._r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n let t4 = key[8] | key[9] << 8; this._r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this._r[5] = ((t4 >>> 1)) & 0x1ffe;\n let t5 = key[10] | key[11] << 8; this._r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n let t6 = key[12] | key[13] << 8; this._r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n let t7 = key[14] | key[15] << 8; this._r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this._r[9] = ((t7 >>> 5)) & 0x007f;\n\n this._pad[0] = key[16] | key[17] << 8;\n this._pad[1] = key[18] | key[19] << 8;\n this._pad[2] = key[20] | key[21] << 8;\n this._pad[3] = key[22] | key[23] << 8;\n this._pad[4] = key[24] | key[25] << 8;\n this._pad[5] = key[26] | key[27] << 8;\n this._pad[6] = key[28] | key[29] << 8;\n this._pad[7] = key[30] | key[31] << 8;\n }\n\n private _blocks(m: Uint8Array, mpos: number, bytes: number) {\n let hibit = this._fin ? 0 : 1 << 11;\n\n let h0 = this._h[0],\n h1 = this._h[1],\n h2 = this._h[2],\n h3 = this._h[3],\n h4 = this._h[4],\n h5 = this._h[5],\n h6 = this._h[6],\n h7 = this._h[7],\n h8 = this._h[8],\n h9 = this._h[9];\n\n let r0 = this._r[0],\n r1 = this._r[1],\n r2 = this._r[2],\n r3 = this._r[3],\n r4 = this._r[4],\n r5 = this._r[5],\n r6 = this._r[6],\n r7 = this._r[7],\n r8 = this._r[8],\n r9 = this._r[9];\n\n while (bytes >= 16) {\n let t0 = m[mpos + 0] | m[mpos + 1] << 8; h0 += (t0) & 0x1fff;\n let t1 = m[mpos + 2] | m[mpos + 3] << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n let t2 = m[mpos + 4] | m[mpos + 5] << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;\n let t3 = m[mpos + 6] | m[mpos + 7] << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n let t4 = m[mpos + 8] | m[mpos + 9] << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;\n h5 += ((t4 >>> 1)) & 0x1fff;\n let t5 = m[mpos + 10] | m[mpos + 11] << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n let t6 = m[mpos + 12] | m[mpos + 13] << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;\n let t7 = m[mpos + 14] | m[mpos + 15] << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n h9 += ((t7 >>> 5)) | hibit;\n\n let c = 0;\n\n let d0 = c;\n d0 += h0 * r0;\n d0 += h1 * (5 * r9);\n d0 += h2 * (5 * r8);\n d0 += h3 * (5 * r7);\n d0 += h4 * (5 * r6);\n c = (d0 >>> 13); d0 &= 0x1fff;\n d0 += h5 * (5 * r5);\n d0 += h6 * (5 * r4);\n d0 += h7 * (5 * r3);\n d0 += h8 * (5 * r2);\n d0 += h9 * (5 * r1);\n c += (d0 >>> 13); d0 &= 0x1fff;\n\n let d1 = c;\n d1 += h0 * r1;\n d1 += h1 * r0;\n d1 += h2 * (5 * r9);\n d1 += h3 * (5 * r8);\n d1 += h4 * (5 * r7);\n c = (d1 >>> 13); d1 &= 0x1fff;\n d1 += h5 * (5 * r6);\n d1 += h6 * (5 * r5);\n d1 += h7 * (5 * r4);\n d1 += h8 * (5 * r3);\n d1 += h9 * (5 * r2);\n c += (d1 >>> 13); d1 &= 0x1fff;\n\n let d2 = c;\n d2 += h0 * r2;\n d2 += h1 * r1;\n d2 += h2 * r0;\n d2 += h3 * (5 * r9);\n d2 += h4 * (5 * r8);\n c = (d2 >>> 13); d2 &= 0x1fff;\n d2 += h5 * (5 * r7);\n d2 += h6 * (5 * r6);\n d2 += h7 * (5 * r5);\n d2 += h8 * (5 * r4);\n d2 += h9 * (5 * r3);\n c += (d2 >>> 13); d2 &= 0x1fff;\n\n let d3 = c;\n d3 += h0 * r3;\n d3 += h1 * r2;\n d3 += h2 * r1;\n d3 += h3 * r0;\n d3 += h4 * (5 * r9);\n c = (d3 >>> 13); d3 &= 0x1fff;\n d3 += h5 * (5 * r8);\n d3 += h6 * (5 * r7);\n d3 += h7 * (5 * r6);\n d3 += h8 * (5 * r5);\n d3 += h9 * (5 * r4);\n c += (d3 >>> 13); d3 &= 0x1fff;\n\n let d4 = c;\n d4 += h0 * r4;\n d4 += h1 * r3;\n d4 += h2 * r2;\n d4 += h3 * r1;\n d4 += h4 * r0;\n c = (d4 >>> 13); d4 &= 0x1fff;\n d4 += h5 * (5 * r9);\n d4 += h6 * (5 * r8);\n d4 += h7 * (5 * r7);\n d4 += h8 * (5 * r6);\n d4 += h9 * (5 * r5);\n c += (d4 >>> 13); d4 &= 0x1fff;\n\n let d5 = c;\n d5 += h0 * r5;\n d5 += h1 * r4;\n d5 += h2 * r3;\n d5 += h3 * r2;\n d5 += h4 * r1;\n c = (d5 >>> 13); d5 &= 0x1fff;\n d5 += h5 * r0;\n d5 += h6 * (5 * r9);\n d5 += h7 * (5 * r8);\n d5 += h8 * (5 * r7);\n d5 += h9 * (5 * r6);\n c += (d5 >>> 13); d5 &= 0x1fff;\n\n let d6 = c;\n d6 += h0 * r6;\n d6 += h1 * r5;\n d6 += h2 * r4;\n d6 += h3 * r3;\n d6 += h4 * r2;\n c = (d6 >>> 13); d6 &= 0x1fff;\n d6 += h5 * r1;\n d6 += h6 * r0;\n d6 += h7 * (5 * r9);\n d6 += h8 * (5 * r8);\n d6 += h9 * (5 * r7);\n c += (d6 >>> 13); d6 &= 0x1fff;\n\n let d7 = c;\n d7 += h0 * r7;\n d7 += h1 * r6;\n d7 += h2 * r5;\n d7 += h3 * r4;\n d7 += h4 * r3;\n c = (d7 >>> 13); d7 &= 0x1fff;\n d7 += h5 * r2;\n d7 += h6 * r1;\n d7 += h7 * r0;\n d7 += h8 * (5 * r9);\n d7 += h9 * (5 * r8);\n c += (d7 >>> 13); d7 &= 0x1fff;\n\n let d8 = c;\n d8 += h0 * r8;\n d8 += h1 * r7;\n d8 += h2 * r6;\n d8 += h3 * r5;\n d8 += h4 * r4;\n c = (d8 >>> 13); d8 &= 0x1fff;\n d8 += h5 * r3;\n d8 += h6 * r2;\n d8 += h7 * r1;\n d8 += h8 * r0;\n d8 += h9 * (5 * r9);\n c += (d8 >>> 13); d8 &= 0x1fff;\n\n let d9 = c;\n d9 += h0 * r9;\n d9 += h1 * r8;\n d9 += h2 * r7;\n d9 += h3 * r6;\n d9 += h4 * r5;\n c = (d9 >>> 13); d9 &= 0x1fff;\n d9 += h5 * r4;\n d9 += h6 * r3;\n d9 += h7 * r2;\n d9 += h8 * r1;\n d9 += h9 * r0;\n c += (d9 >>> 13); d9 &= 0x1fff;\n\n c = (((c << 2) + c)) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = (c >>> 13);\n d1 += c;\n\n h0 = d0;\n h1 = d1;\n h2 = d2;\n h3 = d3;\n h4 = d4;\n h5 = d5;\n h6 = d6;\n h7 = d7;\n h8 = d8;\n h9 = d9;\n\n mpos += 16;\n bytes -= 16;\n }\n this._h[0] = h0;\n this._h[1] = h1;\n this._h[2] = h2;\n this._h[3] = h3;\n this._h[4] = h4;\n this._h[5] = h5;\n this._h[6] = h6;\n this._h[7] = h7;\n this._h[8] = h8;\n this._h[9] = h9;\n }\n\n finish(mac: Uint8Array, macpos = 0): this {\n const g = new Uint16Array(10);\n let c: number;\n let mask: number;\n let f: number;\n let i: number;\n\n if (this._leftover) {\n i = this._leftover;\n this._buffer[i++] = 1;\n for (; i < 16; i++) {\n this._buffer[i] = 0;\n }\n this._fin = 1;\n this._blocks(this._buffer, 0, 16);\n }\n\n c = this._h[1] >>> 13;\n this._h[1] &= 0x1fff;\n for (i = 2; i < 10; i++) {\n this._h[i] += c;\n c = this._h[i] >>> 13;\n this._h[i] &= 0x1fff;\n }\n this._h[0] += (c * 5);\n c = this._h[0] >>> 13;\n this._h[0] &= 0x1fff;\n this._h[1] += c;\n c = this._h[1] >>> 13;\n this._h[1] &= 0x1fff;\n this._h[2] += c;\n\n g[0] = this._h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (i = 1; i < 10; i++) {\n g[i] = this._h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= (1 << 13);\n\n mask = (c ^ 1) - 1;\n for (i = 0; i < 10; i++) {\n g[i] &= mask;\n }\n mask = ~mask;\n for (i = 0; i < 10; i++) {\n this._h[i] = (this._h[i] & mask) | g[i];\n }\n\n this._h[0] = ((this._h[0]) | (this._h[1] << 13)) & 0xffff;\n this._h[1] = ((this._h[1] >>> 3) | (this._h[2] << 10)) & 0xffff;\n this._h[2] = ((this._h[2] >>> 6) | (this._h[3] << 7)) & 0xffff;\n this._h[3] = ((this._h[3] >>> 9) | (this._h[4] << 4)) & 0xffff;\n this._h[4] = ((this._h[4] >>> 12) | (this._h[5] << 1) | (this._h[6] << 14)) & 0xffff;\n this._h[5] = ((this._h[6] >>> 2) | (this._h[7] << 11)) & 0xffff;\n this._h[6] = ((this._h[7] >>> 5) | (this._h[8] << 8)) & 0xffff;\n this._h[7] = ((this._h[8] >>> 8) | (this._h[9] << 5)) & 0xffff;\n\n f = this._h[0] + this._pad[0];\n this._h[0] = f & 0xffff;\n for (i = 1; i < 8; i++) {\n f = (((this._h[i] + this._pad[i]) | 0) + (f >>> 16)) | 0;\n this._h[i] = f & 0xffff;\n }\n\n mac[macpos + 0] = this._h[0] >>> 0;\n mac[macpos + 1] = this._h[0] >>> 8;\n mac[macpos + 2] = this._h[1] >>> 0;\n mac[macpos + 3] = this._h[1] >>> 8;\n mac[macpos + 4] = this._h[2] >>> 0;\n mac[macpos + 5] = this._h[2] >>> 8;\n mac[macpos + 6] = this._h[3] >>> 0;\n mac[macpos + 7] = this._h[3] >>> 8;\n mac[macpos + 8] = this._h[4] >>> 0;\n mac[macpos + 9] = this._h[4] >>> 8;\n mac[macpos + 10] = this._h[5] >>> 0;\n mac[macpos + 11] = this._h[5] >>> 8;\n mac[macpos + 12] = this._h[6] >>> 0;\n mac[macpos + 13] = this._h[6] >>> 8;\n mac[macpos + 14] = this._h[7] >>> 0;\n mac[macpos + 15] = this._h[7] >>> 8;\n\n this._finished = true;\n return this;\n }\n\n update(m: Uint8Array): this {\n let mpos = 0;\n let bytes = m.length;\n let want: number;\n\n if (this._leftover) {\n want = (16 - this._leftover);\n if (want > bytes) {\n want = bytes;\n }\n for (let i = 0; i < want; i++) {\n this._buffer[this._leftover + i] = m[mpos + i];\n }\n bytes -= want;\n mpos += want;\n this._leftover += want;\n if (this._leftover < 16) {\n return this;\n }\n this._blocks(this._buffer, 0, 16);\n this._leftover = 0;\n }\n\n if (bytes >= 16) {\n want = bytes - (bytes % 16);\n this._blocks(m, mpos, want);\n mpos += want;\n bytes -= want;\n }\n\n if (bytes) {\n for (let i = 0; i < bytes; i++) {\n this._buffer[this._leftover + i] = m[mpos + i];\n }\n this._leftover += bytes;\n }\n\n return this;\n }\n\n digest(): Uint8Array {\n // TODO(dchest): it behaves differently than other hashes/HMAC,\n // because it throws when finished \u2014 others just return saved result.\n if (this._finished) {\n throw new Error(\"Poly1305 was finished\");\n }\n let mac = new Uint8Array(16);\n this.finish(mac);\n return mac;\n }\n\n clean(): this {\n wipe(this._buffer);\n wipe(this._r);\n wipe(this._h);\n wipe(this._pad);\n this._leftover = 0;\n this._fin = 0;\n this._finished = true; // mark as finished even if not\n return this;\n }\n}\n\n/**\n * Returns 16-byte authenticator of data using a one-time 32-byte key.\n *\n * Important: key should be used for only one message, it should never repeat.\n */\nexport function oneTimeAuth(key: Uint8Array, data: Uint8Array): Uint8Array {\n const h = new Poly1305(key);\n h.update(data);\n const digest = h.digest();\n h.clean();\n return digest;\n}\n\n/**\n * Returns true if two authenticators are 16-byte long and equal.\n * Uses contant-time comparison to avoid leaking timing information.\n */\nexport function equal(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== DIGEST_LENGTH || b.length !== DIGEST_LENGTH) {\n return false;\n }\n return constantTimeEqual(a, b);\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { streamXOR, stream } from \"@stablelib/xsalsa20\";\nimport { oneTimeAuth, equal as authEqual } from \"@stablelib/poly1305\";\nimport { wipe } from \"@stablelib/wipe\";\nimport { randomBytes, RandomSource } from \"@stablelib/random\";\n\nexport function secretBox(key: Uint8Array, nonce: Uint8Array, data: Uint8Array): Uint8Array {\n if (nonce.length !== 24) {\n throw new Error(\"secretBox nonce must be 24 bytes\");\n }\n const firstBlock = new Uint8Array(64);\n\n // Allocate place for nonce and counter.\n const nonceCounter = new Uint8Array(24 + 8);\n\n // Set first bytes to nonce. Last 8 bytes will be counter.\n nonceCounter.set(nonce);\n\n // Generate first block of XSalsa20 stream, of which\n // first 32 bytes will be authentication key, and the rest\n // will be used for encryption.\n stream(key, nonceCounter, firstBlock, 8);\n\n // Allocate result, which will contain 16-byte authenticator\n // concatenated with ciphertext.\n const result = new Uint8Array(16 + data.length);\n\n // Encrypt first 32 bytes of data with last 32 bytes of generated stream.\n for (let i = 0; i < 32 && i < data.length; i++) {\n result[16 + i] = data[i] ^ firstBlock[32 + i];\n }\n\n // Encrypt the rest of data.\n if (data.length > 32) {\n streamXOR(key, nonceCounter, data.subarray(32), result.subarray(16 + 32), 8);\n }\n\n // Calculate Poly1305 authenticator of encrypted data using\n // authentication key in the first block of XSalsa20 stream.\n const auth = oneTimeAuth(firstBlock.subarray(0, 32), result.subarray(16));\n\n // Copy authenticator to the beginning of result.\n for (let i = 0; i < auth.length; i++) {\n result[i] = auth[i];\n }\n\n // Clean auth.\n wipe(auth);\n\n // Clean first block.\n wipe(firstBlock);\n\n // Clean nonceCounter.\n wipe(nonceCounter);\n\n return result;\n}\n\nexport function openSecretBox(key: Uint8Array, nonce: Uint8Array, box: Uint8Array): Uint8Array | null {\n if (nonce.length !== 24) {\n throw new Error(\"secretBox nonce must be 24 bytes\");\n }\n if (box.length < 16) {\n throw new Error(\"secretBox data must be at least 16 bytes\");\n }\n const firstBlock = new Uint8Array(64);\n\n // Allocate place for nonce and counter.\n const nonceCounter = new Uint8Array(24 + 8);\n\n // Set first bytes to nonce. Last 8 bytes will be counter.\n nonceCounter.set(nonce);\n\n // Generate first block of XSalsa20 stream, of which\n // first 32 bytes will be authentication key, and the rest\n // will be used for encryption.\n stream(key, nonceCounter, firstBlock, 8);\n\n // Calculate Poly1305 authenticator of encrypted data using\n // authentication key in the first block of XSalsa20 stream.\n const auth = oneTimeAuth(firstBlock.subarray(0, 32), box.subarray(16));\n\n // Check authenticator.\n if (!authEqual(auth, box.subarray(0, 16))) {\n // Authenticator is incorrect: ciphertext or authenticator\n // was corrupted, maybe maliciously.\n return null;\n }\n\n // Authenticator verifies, so we can decrypt ciphertext.\n const ciphertext = box.subarray(16);\n\n // Allocate result array.\n const result = new Uint8Array(ciphertext.length);\n\n // Decrypt first 32 bytes of box with last 32 bytes of generated stream.\n for (let i = 0; i < 32 && i < ciphertext.length; i++) {\n result[i] = ciphertext[i] ^ firstBlock[32 + i];\n }\n\n // Decrypt the rest of data.\n if (ciphertext.length > 32) {\n streamXOR(key, nonceCounter, ciphertext.subarray(32), result.subarray(32), 8);\n }\n\n // Clean auth.\n wipe(auth);\n\n // Clean first block.\n wipe(firstBlock);\n\n // Clean nonceCounter.\n wipe(nonceCounter);\n\n return result;\n}\n\n/** Generates a 32-byte random secret key. */\nexport function generateKey(prng?: RandomSource): Uint8Array {\n return randomBytes(32, prng);\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { scalarMult } from \"@stablelib/x25519\";\nimport { hsalsa } from \"@stablelib/xsalsa20\";\nimport { secretBox, openSecretBox } from \"./secretbox\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport { generateKeyPair } from \"@stablelib/x25519\";\n\nconst zeros16 = new Uint8Array(16);\n\nexport function precomputeSharedKey(theirPublicKey: Uint8Array, mySecretKey: Uint8Array): Uint8Array {\n // Compute scalar multiplication result.\n const key = scalarMult(mySecretKey, theirPublicKey);\n\n // Hash key with HSalsa function.\n hsalsa(key, zeros16, key);\n\n return key;\n}\n\nexport function box(theirPublicKey: Uint8Array, mySecretKey: Uint8Array,\n nonce: Uint8Array, data: Uint8Array): Uint8Array {\n const sharedKey = precomputeSharedKey(theirPublicKey, mySecretKey);\n const result = secretBox(sharedKey, nonce, data);\n wipe(sharedKey);\n return result;\n}\n\nexport function openBox(theirPublicKey: Uint8Array, mySecretKey: Uint8Array,\n nonce: Uint8Array, data: Uint8Array): Uint8Array | null {\n const sharedKey = precomputeSharedKey(theirPublicKey, mySecretKey);\n const result = openSecretBox(sharedKey, nonce, data);\n wipe(sharedKey);\n return result;\n}\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package nacl implements NaCl (Networking and Cryptography library) cryptography.\n */\n\nexport * from \"./box\";\nexport * from \"./secretbox\";\n", "// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package base64 implements Base64 encoding and decoding.\n */\n\n// Invalid character used in decoding to indicate\n// that the character to decode is out of range of\n// alphabet and cannot be decoded.\nconst INVALID_BYTE = 256;\n\n/**\n * Implements standard Base64 encoding.\n *\n * Operates in constant time.\n */\nexport class Coder {\n // TODO(dchest): methods to encode chunk-by-chunk.\n\n constructor(private _paddingCharacter = \"=\") { }\n\n encodedLength(length: number): number {\n if (!this._paddingCharacter) {\n return (length * 8 + 5) / 6 | 0;\n }\n return (length + 2) / 3 * 4 | 0;\n }\n\n encode(data: Uint8Array): string {\n let out = \"\";\n\n let i = 0;\n for (; i < data.length - 2; i += 3) {\n let c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);\n out += this._encodeByte((c >>> 3 * 6) & 63);\n out += this._encodeByte((c >>> 2 * 6) & 63);\n out += this._encodeByte((c >>> 1 * 6) & 63);\n out += this._encodeByte((c >>> 0 * 6) & 63);\n }\n\n const left = data.length - i;\n if (left > 0) {\n let c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);\n out += this._encodeByte((c >>> 3 * 6) & 63);\n out += this._encodeByte((c >>> 2 * 6) & 63);\n if (left === 2) {\n out += this._encodeByte((c >>> 1 * 6) & 63);\n } else {\n out += this._paddingCharacter || \"\";\n }\n out += this._paddingCharacter || \"\";\n }\n\n return out;\n }\n\n maxDecodedLength(length: number): number {\n if (!this._paddingCharacter) {\n return (length * 6 + 7) / 8 | 0;\n }\n return length / 4 * 3 | 0;\n }\n\n decodedLength(s: string): number {\n return this.maxDecodedLength(s.length - this._getPaddingLength(s));\n }\n\n decode(s: string): Uint8Array {\n if (s.length === 0) {\n return new Uint8Array(0);\n }\n const paddingLength = this._getPaddingLength(s);\n const length = s.length - paddingLength;\n const out = new Uint8Array(this.maxDecodedLength(length));\n let op = 0;\n let i = 0;\n let haveBad = 0;\n let v0 = 0, v1 = 0, v2 = 0, v3 = 0;\n for (; i < length - 4; i += 4) {\n v0 = this._decodeChar(s.charCodeAt(i + 0));\n v1 = this._decodeChar(s.charCodeAt(i + 1));\n v2 = this._decodeChar(s.charCodeAt(i + 2));\n v3 = this._decodeChar(s.charCodeAt(i + 3));\n out[op++] = (v0 << 2) | (v1 >>> 4);\n out[op++] = (v1 << 4) | (v2 >>> 2);\n out[op++] = (v2 << 6) | v3;\n haveBad |= v0 & INVALID_BYTE;\n haveBad |= v1 & INVALID_BYTE;\n haveBad |= v2 & INVALID_BYTE;\n haveBad |= v3 & INVALID_BYTE;\n }\n if (i < length - 1) {\n v0 = this._decodeChar(s.charCodeAt(i));\n v1 = this._decodeChar(s.charCodeAt(i + 1));\n out[op++] = (v0 << 2) | (v1 >>> 4);\n haveBad |= v0 & INVALID_BYTE;\n haveBad |= v1 & INVALID_BYTE;\n }\n if (i < length - 2) {\n v2 = this._decodeChar(s.charCodeAt(i + 2));\n out[op++] = (v1 << 4) | (v2 >>> 2);\n haveBad |= v2 & INVALID_BYTE;\n }\n if (i < length - 3) {\n v3 = this._decodeChar(s.charCodeAt(i + 3));\n out[op++] = (v2 << 6) | v3;\n haveBad |= v3 & INVALID_BYTE;\n }\n if (haveBad !== 0) {\n throw new Error(\"Base64Coder: incorrect characters for decoding\");\n }\n return out;\n }\n\n // Standard encoding have the following encoded/decoded ranges,\n // which we need to convert between.\n //\n // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /\n // Index: 0 - 25 26 - 51 52 - 61 62 63\n // ASCII: 65 - 90 97 - 122 48 - 57 43 47\n //\n\n // Encode 6 bits in b into a new character.\n protected _encodeByte(b: number): string {\n // Encoding uses constant time operations as follows:\n //\n // 1. Define comparison of A with B using (A - B) >>> 8:\n // if A > B, then result is positive integer\n // if A <= B, then result is 0\n //\n // 2. Define selection of C or 0 using bitwise AND: X & C:\n // if X == 0, then result is 0\n // if X != 0, then result is C\n //\n // 3. Start with the smallest comparison (b >= 0), which is always\n // true, so set the result to the starting ASCII value (65).\n //\n // 4. Continue comparing b to higher ASCII values, and selecting\n // zero if comparison isn't true, otherwise selecting a value\n // to add to result, which:\n //\n // a) undoes the previous addition\n // b) provides new value to add\n //\n let result = b;\n // b >= 0\n result += 65;\n // b > 25\n result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);\n // b > 51\n result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);\n // b > 61\n result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);\n // b > 62\n result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);\n\n return String.fromCharCode(result);\n }\n\n // Decode a character code into a byte.\n // Must return 256 if character is out of alphabet range.\n protected _decodeChar(c: number): number {\n // Decoding works similar to encoding: using the same comparison\n // function, but now it works on ranges: result is always incremented\n // by value, but this value becomes zero if the range is not\n // satisfied.\n //\n // Decoding starts with invalid value, 256, which is then\n // subtracted when the range is satisfied. If none of the ranges\n // apply, the function returns 256, which is then checked by\n // the caller to throw error.\n let result = INVALID_BYTE; // start with invalid character\n\n // c == 43 (c > 42 and c < 44)\n result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);\n // c == 47 (c > 46 and c < 48)\n result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);\n // c > 47 and c < 58\n result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);\n // c > 64 and c < 91\n result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);\n // c > 96 and c < 123\n result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);\n\n return result;\n }\n\n private _getPaddingLength(s: string): number {\n let paddingLength = 0;\n if (this._paddingCharacter) {\n for (let i = s.length - 1; i >= 0; i--) {\n if (s[i] !== this._paddingCharacter) {\n break;\n }\n paddingLength++;\n }\n if (s.length < 4 || paddingLength > 2) {\n throw new Error(\"Base64Coder: incorrect padding\");\n }\n }\n return paddingLength;\n }\n\n}\n\nconst stdCoder = new Coder();\n\nexport function encode(data: Uint8Array): string {\n return stdCoder.encode(data);\n}\n\nexport function decode(s: string): Uint8Array {\n return stdCoder.decode(s);\n}\n\n/**\n * Implements URL-safe Base64 encoding.\n * (Same as Base64, but '+' is replaced with '-', and '/' with '_').\n *\n * Operates in constant time.\n */\nexport class URLSafeCoder extends Coder {\n // URL-safe encoding have the following encoded/decoded ranges:\n //\n // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _\n // Index: 0 - 25 26 - 51 52 - 61 62 63\n // ASCII: 65 - 90 97 - 122 48 - 57 45 95\n //\n\n protected _encodeByte(b: number): string {\n let result = b;\n // b >= 0\n result += 65;\n // b > 25\n result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);\n // b > 51\n result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);\n // b > 61\n result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);\n // b > 62\n result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);\n\n return String.fromCharCode(result);\n }\n\n protected _decodeChar(c: number): number {\n let result = INVALID_BYTE;\n\n // c == 45 (c > 44 and c < 46)\n result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);\n // c == 95 (c > 94 and c < 96)\n result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);\n // c > 47 and c < 58\n result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);\n // c > 64 and c < 91\n result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);\n // c > 96 and c < 123\n result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);\n\n return result;\n }\n}\n\nconst urlSafeCoder = new URLSafeCoder();\n\nexport function encodeURLSafe(data: Uint8Array): string {\n return urlSafeCoder.encode(data);\n}\n\nexport function decodeURLSafe(s: string): Uint8Array {\n return urlSafeCoder.decode(s);\n}\n\n\nexport const encodedLength = (length: number) =>\n stdCoder.encodedLength(length);\n\nexport const maxDecodedLength = (length: number) =>\n stdCoder.maxDecodedLength(length);\n\nexport const decodedLength = (s: string) =>\n stdCoder.decodedLength(s);\n", "/**\n * Browser-side crypto for the login SDK:\n *\n * \u2022 generateEphemeralKeypair \u2014 X25519 keypair for the duration of\n * one sign-in. Held in memory; discarded on session.close() or page\n * unload. The public key is the value the wallet boxes its envelope\n * to.\n *\n * \u2022 decryptEnvelope \u2014 open the wallet's NaCl `box` ciphertext\n * and parse the resulting JSON. Once the wallet's session key is\n * pinned (see session.ts), only envelopes boxed BY that key open.\n *\n * \u2022 boxToWallet \u2014 box a JSON envelope to the wallet's\n * session key, sent by this browser's session key.\n *\n * Envelope v2 (both directions): NaCl `box` between the two session\n * keys \u2014 the browser's per-sign-in X25519 key (`browserPk`, in the QR)\n * and the wallet's per-session X25519 key (`walletSessionPk`, bound\n * into the signed presentation as the KB-JWT `prson_wsk` claim). The\n * wire field `ephPk` keeps its name for compatibility but now carries\n * the SENDER's session key, so the recipient can check who sent it:\n * a box only opens with the matching sender key, which makes it mutual\n * authentication, not just confidentiality.\n *\n * Uses `@stablelib/nacl` for the box / open primitives \u2014 a reviewed\n * pure-JS implementation that runs in every browser without WebCrypto\n * dependency gaps (Web Crypto doesn't ship X25519 in all engines).\n */\nimport { box, openBox } from \"@stablelib/nacl\";\nimport { generateKeyPair } from \"@stablelib/x25519\";\nimport { randomBytes } from \"@stablelib/random\";\nimport { decodeURLSafe as b64uDecode, encodeURLSafe as b64uEncode } from \"@stablelib/base64\";\n\nexport type EphemeralKeys = {\n /** The X25519 secret key (32 bytes). Never serialised; never logged. */\n secretKey: Uint8Array;\n /** The matching public key (32 bytes). */\n publicKey: Uint8Array;\n /** Base64url-encoded public key for use in QRs + the verifier request. */\n publicKeyB64u: string;\n};\n\nexport async function generateEphemeralKeypair(): Promise<EphemeralKeys> {\n // @stablelib's generateKeyPair pulls entropy from a CSPRNG (window.crypto\n // via @stablelib/random). For environments without crypto.getRandomValues\n // (none we support), this would throw \u2014 that's correct behaviour.\n void randomBytes(1); // touch the entropy source so a misconfigured browser fails fast\n const kp = generateKeyPair();\n return {\n secretKey: kp.secretKey,\n publicKey: kp.publicKey,\n publicKeyB64u: stripPad(b64uEncode(kp.publicKey)),\n };\n}\n\n/** Wire shape (matches what the wallet emits \u2014 see ARCHITECTURE.md \u00A74.2). */\nexport type EncryptedEnvelope = {\n /** The sender's X25519 session pk, base64url. Envelope v2: always the\n * sender's session key (`walletSessionPk` from the wallet, `browserPk`\n * from the browser). Older wallets put a fresh per-message key here. */\n ephPk: string;\n /** 24-byte nonce, base64url. */\n nonce24: string;\n /** Boxed ciphertext + Poly1305 tag, base64url. */\n ct: string;\n};\n\n/** Decrypted plaintext envelope \u2014 see ARCHITECTURE.md \u00A74.2.\n *\n * Three of the `msg` types are post-sign-in lifecycle events\n * (`claim-update`, `display-update`, `credential-revoked`) per the\n * roadmap \u00A71. They flow on the same WebRTC channel as the initial\n * `presentation` + renewals, framed with the same NaCl-boxed\n * envelope so the wallet doesn't need a separate transport for live\n * profile / claim updates.\n *\n * Important: any event whose payload includes claim VALUES (today\n * only `claim-update`) MUST carry a `presentation` field, and the\n * SDK MUST re-verify that presentation before firing any listener.\n * Bare claim deltas without a fresh SD-JWT-VC backing them are NOT\n * trusted \u2014 see ROADMAP \u00A71.3 and SECURITY.md \u00A77.\n */\nexport type DecryptedEnvelope = {\n v: string;\n msg:\n | \"presentation\"\n | \"renewal\"\n | \"revoke\"\n | \"decline\"\n | \"claim-update\"\n | \"display-update\"\n | \"credential-revoked\"\n | \"response\"\n | \"mouse-update\"\n | \"nav\"\n | \"value\"\n | \"logout\"\n /**\n * Browser\u2192wallet pause-state notification. Fired on\n * `window.blur` / `window.focus` so the wallet's mouse\n * controller can show \"Remote control paused\" while the page\n * is in the background. Body: `paused: boolean`.\n */\n | \"control-status\"\n /**\n * Browser\u2192wallet \"I'm going away\" signal. Fired synchronously\n * from `window.pagehide` (refresh, tab close, navigation)\n * before the transport collapses, so the wallet can close the\n * session immediately instead of waiting for the slower\n * `peer-gone` / WS-close pathway. Body: `reason: string`\n * (free-form short code, currently always `\"page_unload\"`).\n */\n | \"browser-revoke\"\n /**\n * File-transfer wire grammar. Wallet\u2192browser; used when the\n * host's focused element is `<input type=\"file\">` and the user\n * picks something on the phone. The three-stage envelope keeps\n * memory pressure low \u2014 neither peer ever materialises the full\n * file in a contiguous buffer:\n *\n * * `file-begin` \u2014 metadata: `name`, `mimeType`, `size`,\n * `totalChunks`, `chunkSize`, plus an\n * optional `attestation` SD-JWT-VC for\n * identity-bound files (see notes below\n * on VC MIME standards).\n * * `file-chunk` \u2014 one chunk: `index` (0-based) +\n * base64-encoded `data`. The wallet\n * stream-reads the source file, so chunks\n * leave the device one at a time without\n * ever loading the whole thing.\n * * `file-end` \u2014 `sha256` over the whole file, hex-encoded.\n * The browser verifies the assembled Blob\n * against this digest before assigning to\n * the focused input.\n *\n * Per-chunk ack via the existing reliability layer gives\n * natural backpressure: the wallet doesn't queue chunk N+1\n * until chunk N is confirmed. Loss of any one chunk retries\n * just that chunk, not the file.\n *\n * VC MIME context (host integrators occasionally ask):\n * * `application/vc+ld+json` \u2014 W3C VCDM JSON-LD form\n * * `application/vc+jwt` \u2014 W3C VCDM JWT form\n * * `application/vc+sd-jwt` \u2014 IETF SD-JWT-VC (what the\n * Prson identity stack issues)\n * * `application/pdf` + PAdES \u2014 signed-PDF form\n * * C2PA bundles for media (image / video provenance)\n *\n * There is no widely-deployed standard MIME for \"binary file\n * with an attached presentation\". The `attestation` field on\n * `file-begin` is our convention for piggy-backing one \u2014 the\n * wallet sends the file bytes AND a separate SD-JWT-VC whose\n * disclosed claims include the file's SHA-256. The verifier\n * (host page) re-hashes the received bytes and checks the\n * digest matches the disclosed claim before trusting the\n * provenance metadata.\n */\n | \"file-begin\"\n | \"file-chunk\"\n | \"file-end\"\n /** Transport-layer reliability primitive: the peer's confirmation\n * that the envelope with id [ackOf] was received. The session\n * layer auto-emits these for inbound messages carrying an `id`\n * (other than ping / pong / ack themselves) and resolves\n * pending-ack promises on the sender side. See session.ts. */\n | \"ack\"\n /** Liveness probe. Sender keeps a fresh `id` per ping and times\n * the matching pong to derive RTT. The receiver echoes as\n * `pong` with `ackOf` set to the ping's `id`. */\n | \"ping\"\n /** Liveness echo. `ackOf` references the ping's id; `recvTs`\n * is the peer's wall-clock receipt time. Recipient computes\n * RTT = now \u2212 sendTs cached against [ackOf]. */\n | \"pong\";\n issuedAt: number;\n ttlMinutes?: number;\n domain?: string;\n\n /** Transport-layer envelope id (UUID v4). Present on every wire\n * message that is ack-tracked or dedupe-tracked; absent on\n * mouse-update (high-frequency broadcast where loss is OK) and\n * on the protocol primitives `ack` / `pong` (which carry\n * [ackOf] instead). The receiver dedupes by this id; the sender\n * retransmits until the matching [ack] arrives. */\n id?: string;\n\n /** Reference to the originating envelope's [id]. Set on `ack`,\n * `pong`, and `response` envelopes. */\n ackOf?: string;\n\n /** Ping send-time wall-clock (epoch ms). The pong copies this\n * verbatim so the sender doesn't need to maintain a separate\n * ts cache for an RTT calculation. */\n ts?: number;\n\n /** Pong-only: the responder's wall-clock receipt time (epoch ms).\n * Useful for one-way delay estimates if the host wants finer\n * diagnostics than RTT alone. */\n recvTs?: number;\n\n /** Present for `presentation`, `renewal`, and `claim-update`. */\n presentation?: string;\n fragments?: unknown[];\n\n /**\n * Wallet's session-long X25519 public key (base64url, 32 bytes).\n * Present only in the INITIAL `presentation` envelope at sign-in\n * (and on `renewal` if the wallet rotates its session key). The\n * browser SDK extracts + caches this on the session so subsequent\n * outbound `request` envelopes can NaCl-box to it. Without this\n * the browser\u2192wallet direction has no destination key and the\n * request channel can't open.\n *\n * Advisory only: the key the SDK pins is the one the signed\n * presentation binds (KB-JWT `prson_wsk`, or the anonymous\n * credential's `prson_wsk`). This field must agree with it, and a\n * value on any later envelope is ignored \u2014 a rotation is accepted\n * only from a verified renewal presentation carrying the new key.\n */\n walletSessionPk?: string;\n\n /**\n * User's preferred UI language as a BCP-47 language tag (e.g.\n * `\"en\"`, `\"pt-PT\"`, `\"fr-CA\"`). The wallet sets this from the\n * device's active locale on the initial `presentation` envelope\n * and may rotate it on `renewal` if the device language changes\n * mid-session. The host site can read it via\n * `session.preferredLanguage` to localise its UI without an\n * extra round-trip.\n *\n * Same convention applies to the `displayName` + `avatar` fields\n * below: they originated as the `display-update` envelope body,\n * but the wallet stamps them onto the initial `presentation`\n * envelope too so the host has them on first paint without a\n * separate round-trip.\n */\n preferredLanguage?: string;\n\n /** `claim-update` body: per-claim **name-only** delta. The\n * wallet MUST NOT include claim values here \u2014 the SDK ignores\n * the delta entirely and recomputes from the re-verified VC\n * for correctness, and emits name-only events to keep raw\n * claim values out of telemetry/log surfaces. The wire field\n * is kept (typed as name-only) so future wallets can hint at\n * what changed without an SDK bump, but the SDK never trusts\n * the hint as authoritative. */\n delta?: {\n added?: string[];\n removed?: string[];\n updated?: string[];\n };\n\n /** `display-update` body. Either field independently optional;\n * absent means \"no change\". Pass `null` to clear. No crypto\n * re-verify required \u2014 display-only hints for the host UI. */\n displayName?: string | null;\n avatar?: { url: string; hash: string } | null;\n\n /** `credential-revoked` body. Closes the session with the\n * matching ExpiryReason. */\n reason?: \"alias_transferred\" | \"user_revoked\" | \"key_compromised\";\n\n /** `response` body. The wallet's reply to an earlier outbound\n * `request` envelope. Paired by `requestId` (RFC-4122 v4 UUID,\n * echoed verbatim from the request). Either `result` (success\n * payload, kind-dependent shape) or `error` (short string code)\n * is set; both being absent is treated as `error: \"unsupported\"`. */\n requestId?: string;\n result?: unknown;\n error?: string;\n\n /**\n * `mouse-update` body. Streamed continuously by the wallet while\n * a `kind: \"mouse\"` drawer is open, paired by `requestId` to the\n * originating request. The browser SDK's `bindMouse` helper\n * consumes these and applies them to a CSS-positioned virtual\n * cursor on the page.\n *\n * Coordinates are deltas \u2014 pixels relative to the previous\n * position \u2014 rather than absolute, so phone resolution and page\n * resolution don't need to match. `event` distinguishes\n * pointer-motion frames (`move`) from discrete actions\n * (`click` / `double-click` / `scroll`); `scroll.dy` is positive\n * for downward scroll, matching `WheelEvent.deltaY`.\n */\n mouse?: {\n /**\n * Pointer-stream events.\n *\n * * `move` / `click` / `double-click` / `scroll` \u2014 pointer\n * events that move the on-page cursor or fire synthetic\n * mouse events.\n * * `begin` / `end` \u2014 wallet-side stream lifecycle markers\n * for the pre-grant flow (`SignInOptions.mouseControl`).\n * Subscribers ignore them as no-op pointer events.\n * * `hide` / `show` \u2014 visibility toggles. The wallet emits\n * `hide` when the user lifts the phone into a non-pointing\n * pose (gravity-based pose detector) and re-emits `show`\n * when wand pose returns. The browser pulls the cursor\n * off the page on `hide` AND surfaces a \"point your phone\n * at the screen\" hint with a soft blue glow on the\n * viewport edge.\n */\n event:\n | \"move\"\n | \"click\"\n | \"double-click\"\n | \"scroll\"\n | \"begin\"\n | \"end\"\n | \"show\"\n | \"hide\";\n dx?: number;\n dy?: number;\n /** Active mode at the time of the event (the wallet drawer can\n * toggle mid-session). */\n mode?: \"touch\" | \"magic\";\n };\n\n /**\n * `control-status` body. Browser-emitted; the wallet listens via\n * `LoginSession.inbound` and dims its controller surface while\n * `paused: true`. Fired on `window.blur` / `window.focus` so the\n * user can see, on the phone, that the page is no longer\n * accepting their cursor input.\n */\n paused?: boolean;\n\n /**\n * `file-begin` body. Sent ONCE per file transfer right before the\n * `file-chunk` stream starts. `chunkSize` is the wallet's raw\n * (pre-base64) bytes-per-chunk so the browser can preallocate\n * timing buffers; `totalChunks` lets it render a progress bar\n * without listening for `file-end`. `attestation` is reserved\n * for the future SD-JWT-VC piggy-back contract \u2014 host code\n * should treat the field as opaque until the verifier-side\n * verification path lands.\n */\n fileBegin?: {\n name: string;\n mimeType: string;\n size: number;\n totalChunks: number;\n chunkSize: number;\n /** Optional SD-JWT-VC bound to the file's SHA-256 \u2014 see the\n * `file-begin` msg comment. */\n attestation?: string;\n };\n\n /**\n * `file-chunk` body. `data` is the chunk's raw bytes base64-\n * encoded (URL-safe, padded \u2014 same convention the rest of the\n * wire grammar uses). `index` is the zero-based ordinal.\n */\n fileChunk?: {\n index: number;\n data: string;\n };\n\n /**\n * `file-end` body. `sha256` is hex-encoded (64 lowercase chars).\n * The browser verifies the assembled Blob against this digest\n * before assigning to the focused `<input type=\"file\">`.\n */\n fileEnd?: {\n sha256: string;\n };\n\n /**\n * `nav` body \u2014 wallet's remote-navigation command. Sent when the\n * user taps Prev / Next / Submit on the persistent banner drawer.\n *\n * * `\"prev\"` / `\"next\"` \u2014 move DOM focus to the previous /\n * next tabbable input on the page. Semantically equivalent\n * to Shift+Tab / Tab. SDK fires the matching `focus` event\n * on the new element so reactive UIs pick up the move.\n * * `\"submit\"` \u2014 fire `requestSubmit()` on the closest enclosing\n * `<form>` of the currently focused element. Semantically\n * equivalent to Enter.\n *\n * Only meaningful when the verifier opted in to\n * `remoteNavigation: true` at sign-in time AND the SDK side called\n * `enableRemoteNavigation(session)`.\n */\n action?: \"prev\" | \"next\" | \"submit\";\n\n /**\n * `value` body \u2014 wallet's edit of the currently-focused input. The\n * SDK applies it via `el.value = ...` + an `input` / `change`\n * event pair. The wallet streams these on every keystroke so the\n * page updates live.\n *\n * Empty string is a valid \"clear the field\" message and is\n * propagated as-is. A `null` `value` means \"no change\" \u2014 the SDK\n * ignores it; used by the wallet to ack a focus push without\n * actually editing.\n */\n value?: string | null;\n};\n\n/**\n * Open a wallet envelope. With [expectedSenderPkB64u] (the pinned\n * `walletSessionPk`), only an envelope whose `ephPk` is that key AND\n * whose box opens with it is accepted: anything else (another key, a\n * forged `ephPk`) throws. Without it, any sender is accepted \u2014 used for\n * the first envelope, whose sender is checked against the verified\n * presentation afterwards (index.ts), and for old wallets.\n */\nexport async function decryptEnvelope(\n raw: string,\n keys: EphemeralKeys,\n expectedSenderPkB64u?: string,\n): Promise<DecryptedEnvelope> {\n return (await openEnvelope(raw, keys, expectedSenderPkB64u)).envelope;\n}\n\n/** [decryptEnvelope], also returning the sender key the box opened with. */\nexport async function openEnvelope(\n raw: string,\n keys: EphemeralKeys,\n expectedSenderPkB64u?: string,\n): Promise<{ envelope: DecryptedEnvelope; senderPk: string }> {\n let parsed: EncryptedEnvelope;\n try {\n parsed = JSON.parse(raw) as EncryptedEnvelope;\n } catch {\n throw new Error(\"decryptEnvelope: not a JSON envelope\");\n }\n if (typeof parsed.ephPk !== \"string\" || typeof parsed.nonce24 !== \"string\" || typeof parsed.ct !== \"string\") {\n throw new Error(\"decryptEnvelope: missing required fields {ephPk, nonce24, ct}\");\n }\n const ephPk = b64uDecode(addPad(parsed.ephPk));\n const nonce = b64uDecode(addPad(parsed.nonce24));\n const ct = b64uDecode(addPad(parsed.ct));\n if (ephPk.length !== 32) throw new Error(\"decryptEnvelope: bad ephPk length\");\n if (nonce.length !== 24) throw new Error(\"decryptEnvelope: bad nonce length\");\n let senderPk = ephPk;\n if (expectedSenderPkB64u !== undefined) {\n const expected = b64uDecode(addPad(expectedSenderPkB64u));\n if (expected.length !== 32 || !bytesEqual(expected, ephPk)) {\n throw new Error(\"decryptEnvelope: not sent by the pinned wallet key\");\n }\n senderPk = expected;\n }\n // NaCl `openBox` returns null on bad ciphertext / wrong key \u2014 never\n // throws. We must check + raise ourselves. A box only opens with the\n // sender key it was made with, so a pinned sender is authenticated.\n const pt = openBox(senderPk, keys.secretKey, nonce, ct);\n if (!pt) throw new Error(\"decryptEnvelope: authentication failed (wrong key or tampered ciphertext)\");\n let envelope: DecryptedEnvelope;\n try {\n envelope = JSON.parse(new TextDecoder().decode(pt)) as DecryptedEnvelope;\n } catch {\n throw new Error(\"decryptEnvelope: decrypted but not JSON\");\n }\n return { envelope, senderPk: stripPad(b64uEncode(senderPk)) };\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!;\n return diff === 0;\n}\n\nfunction stripPad(s: string): string {\n return s.replace(/=+$/, \"\");\n}\n\nfunction addPad(s: string): string {\n const mod = s.length % 4;\n return mod === 0 ? s : s + \"=\".repeat(4 - mod);\n}\n\n/**\n * Box a JSON-serialisable [plaintext] to the wallet's session X25519\n * public key. Mirror of the wallet's `LoginEnvelope.encryptToBrowser`\n * primitive (NaCl `box`, XSalsa20-Poly1305, random 24-byte nonce) \u2014\n * the wallet decrypts with its stored session secret. Returns the same\n * JSON-encoded envelope shape the browser already RECEIVES from the\n * wallet:\n *\n * { ephPk: <base64url>, nonce24: <base64url>, ct: <base64url> }\n *\n * Envelope v2: with [sender] (this sign-in's browser keys \u2014 the\n * `browserPk` the QR carried), the box is made BY that key, so `ephPk`\n * is the browser's session key and the wallet can check the envelope\n * came from the browser that showed the code. Without [sender] (legacy),\n * a fresh per-message keypair is used.\n *\n * Both session keys are themselves fresh for each sign-in and live only\n * in memory, so a leaked key exposes that one session, never another.\n *\n * [walletSessionPkB64u] is the wallet's session key, pinned from the\n * verified sign-in presentation (KB-JWT `prson_wsk`).\n */\nexport function boxToWallet(\n walletSessionPkB64u: string,\n plaintext: string,\n sender?: Pick<EphemeralKeys, \"secretKey\" | \"publicKey\">,\n): string {\n const recipientPk = b64uDecode(addPad(walletSessionPkB64u));\n if (recipientPk.length !== 32) {\n throw new Error(\"boxToWallet: bad walletSessionPk length\");\n }\n const ephemeral = sender ?? generateKeyPair();\n const nonce = randomBytes(24);\n const pt = new TextEncoder().encode(plaintext);\n // `@stablelib/nacl` box signature is\n // box(theirPublicKey, mySecretKey, nonce, data)\n // \u2014 RECIPIENT pk first, SENDER sk second. Mirror of `openBox` (which\n // we already call correctly in `decryptEnvelope`). An earlier draft\n // had these swapped, producing a junk shared key that PineNaCl's\n // `Box.decrypt` could never match \u2014 every browser\u2192wallet envelope\n // failed Poly1305 authentication on the wallet side. Keep the\n // argument names explicit at the call site so the bug can't recur.\n const ct = box(\n /* theirPublicKey */ recipientPk,\n /* mySecretKey */ ephemeral.secretKey,\n nonce,\n pt,\n );\n return JSON.stringify({\n ephPk: stripPad(b64uEncode(ephemeral.publicKey)),\n nonce24: stripPad(b64uEncode(nonce)),\n ct: stripPad(b64uEncode(ct)),\n });\n}\n", "/**\n * Revocation check: IETF Token Status List (draft-ietf-oauth-status-list).\n *\n * Every credential Prson issues carries\n * status: { status_list: { idx, uri } }\n * and `uri` serves a Status List Token: a JWT (typ statuslist+jwt) signed by\n * the same issuer key as the credential, whose status_list.lst is a\n * base64url, DEFLATE (ZLIB) compressed bitstring (`bits` bits per entry,\n * index 0 in the lowest bits of byte 0). 0 = VALID; anything else (1\n * INVALID, 2 SUSPENDED) means the credential must not be accepted.\n *\n * Lists are cached briefly (default 60 s, never longer than the token's own\n * ttl). When the list can't be fetched or checked, `onUnavailable` decides:\n * \"fail-closed\" rejects, \"fail-open\" accepts. The default is closed for\n * verified humans (verification_level 5 or more, or verified_human: true)\n * and open below that.\n */\n\nexport type StatusPolicy = \"fail-open\" | \"fail-closed\";\n\nexport type StatusCheckOptions = {\n /** What to do when the status list can't be fetched or verified. Default: closed at level 5+, open below. */\n onUnavailable?: StatusPolicy;\n /** How long a fetched list is reused (seconds, default 60; capped by the token's ttl). */\n cacheSeconds?: number;\n /** The issuer's key for a kid (the same keys that sign credentials). */\n resolveKey: (kid: string) => Promise<JsonWebKey | null>;\n /** Override fetch (tests, proxies). */\n fetch?: (uri: string) => Promise<{ ok: boolean; status: number; text(): Promise<string> }>;\n /** Clock override (ms). */\n now?: () => number;\n};\n\nexport type StatusCheckResult =\n | { ok: true; checked: boolean; unavailable?: string }\n | { ok: false; reason: \"vc_revoked\" | \"status_unavailable\"; detail?: string };\n\ntype CachedList = { fetchedAt: number; ttlMs: number; exp: number | null; bits: number; list: Uint8Array };\nconst cache = new Map<string, CachedList>();\n\n/** Tests: forget cached lists. */\nexport function clearStatusCache(): void {\n cache.clear();\n}\n\n/** Whether the credential's claims describe a verified human (where an unknown status fails closed by default). */\nexport function isStrongCredential(payload: Record<string, unknown>): boolean {\n return payload.verified_human === true || (typeof payload.verification_level === \"number\" && payload.verification_level >= 5);\n}\n\nexport async function checkCredentialStatus(payload: Record<string, unknown>, opts: StatusCheckOptions): Promise<StatusCheckResult> {\n const ref = (payload.status as { status_list?: { idx?: unknown; uri?: unknown } } | undefined)?.status_list;\n if (!ref) return { ok: true, checked: false };\n const policy: StatusPolicy = opts.onUnavailable ?? (isStrongCredential(payload) ? \"fail-closed\" : \"fail-open\");\n const unavailable = (detail: string): StatusCheckResult =>\n policy === \"fail-open\" ? { ok: true, checked: false, unavailable: detail } : { ok: false, reason: \"status_unavailable\", detail };\n const idx = ref.idx;\n const uri = ref.uri;\n if (typeof idx !== \"number\" || !Number.isInteger(idx) || idx < 0 || typeof uri !== \"string\" || !/^https:\\/\\//.test(uri)) {\n return { ok: false, reason: \"status_unavailable\", detail: \"malformed status reference\" };\n }\n let entry: CachedList;\n try {\n entry = await statusList(uri, opts);\n } catch (e) {\n return unavailable((e as Error).message);\n }\n const bitOffset = idx * entry.bits;\n const byte = entry.list[bitOffset >> 3];\n if (byte === undefined) return unavailable(\"index outside the list\");\n const value = (byte >> (bitOffset & 7)) & ((1 << entry.bits) - 1);\n if (value !== 0) return { ok: false, reason: \"vc_revoked\", detail: value === 2 ? \"suspended\" : \"invalid\" };\n return { ok: true, checked: true };\n}\n\nasync function statusList(uri: string, opts: StatusCheckOptions): Promise<CachedList> {\n const now = opts.now?.() ?? Date.now();\n const cached = cache.get(uri);\n if (cached && now - cached.fetchedAt < cached.ttlMs && (cached.exp === null || cached.exp * 1000 > now)) return cached;\n const doFetch = opts.fetch ?? ((u: string) => fetch(u, { headers: { Accept: \"application/statuslist+jwt\" } }));\n const res = await doFetch(uri);\n if (!res.ok) throw new Error(`status list HTTP ${res.status}`);\n const jwt = (await res.text()).trim();\n const [h, p, s] = jwt.split(\".\");\n if (!h || !p || !s) throw new Error(\"status list token malformed\");\n const header = JSON.parse(utf8(b64uBytes(h))) as { alg?: string; kid?: string; typ?: string };\n const payload = JSON.parse(utf8(b64uBytes(p))) as { sub?: string; exp?: number; ttl?: number; status_list?: { bits?: number; lst?: string } };\n if (header.typ !== \"statuslist+jwt\" || header.alg !== \"RS256\" || !header.kid) throw new Error(\"status list token header\");\n const jwk = await opts.resolveKey(header.kid);\n if (!jwk) throw new Error(\"status list key unknown\");\n const key = await crypto.subtle.importKey(\"jwk\", jwk, { name: \"RSASSA-PKCS1-v1_5\", hash: \"SHA-256\" }, false, [\"verify\"]);\n if (!(await crypto.subtle.verify(\"RSASSA-PKCS1-v1_5\", key, b64uBytes(s), new TextEncoder().encode(`${h}.${p}`)))) throw new Error(\"status list signature\");\n if (payload.sub !== uri) throw new Error(\"status list subject\");\n if (typeof payload.exp === \"number\" && payload.exp * 1000 <= now) throw new Error(\"status list expired\");\n const bits = payload.status_list?.bits;\n if (bits !== 1 && bits !== 2 && bits !== 4 && bits !== 8) throw new Error(\"status list bits\");\n if (typeof payload.status_list?.lst !== \"string\") throw new Error(\"status list lst\");\n const list = await inflate(b64uBytes(payload.status_list.lst));\n const want = (opts.cacheSeconds ?? 60) * 1000;\n const ttlMs = typeof payload.ttl === \"number\" ? Math.min(want, payload.ttl * 1000) : want;\n const entry: CachedList = { fetchedAt: now, ttlMs, exp: typeof payload.exp === \"number\" ? payload.exp : null, bits, list };\n cache.set(uri, entry);\n return entry;\n}\n\nasync function inflate(bytes: Uint8Array<ArrayBuffer>): Promise<Uint8Array> {\n const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream(\"deflate\"));\n return new Uint8Array(await new Response(stream).arrayBuffer());\n}\n\nconst utf8 = (b: Uint8Array) => new TextDecoder().decode(b);\n\nfunction b64uBytes(s: string): Uint8Array<ArrayBuffer> {\n const pad = (4 - (s.length % 4)) % 4;\n const bin = atob((s + \"=\".repeat(pad)).replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const out = new Uint8Array(new ArrayBuffer(bin.length));\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n", "/**\n * Browser-side SD-JWT-VC verification. The SDK enforces all five rules\n * from SECURITY.md \u00A77 before resolving signIn(); the verifier-node\n * package re-enforces them server-side.\n *\n * We do this in the browser too \u2014 even though the host site must\n * re-verify on its backend \u2014 because:\n *\n * (a) failing fast in the SDK gives partners better DX (clear errors\n * before anything reaches their backend); and\n * (b) the cnf.jwk we expose to the host as the user identifier MUST\n * have actually signed the presentation we deliver, otherwise\n * sloppy callers could be tricked into trusting a forged cnf.\n *\n * Implementation uses Web Crypto for RS256 + Ed25519 verification.\n * Web Crypto's Ed25519 support landed in all major browsers in 2023+;\n * for older targets we'd polyfill with `@stablelib/ed25519`.\n */\nimport type { CnfJwk } from \"./index.js\";\nimport { checkCredentialStatus, type StatusPolicy } from \"./status.js\";\n\nexport type VerifyOptions = {\n expectedAudience: string;\n expectedNonce: string;\n acceptedVcts: string[];\n trustedIssuer: string; // e.g. \"did:web:app.prson.net\"\n maxKbAgeSeconds?: number; // default 60\n jwksUri?: string; // override (default: derived from trustedIssuer)\n /**\n * Revocation (the credential's Token Status List entry, status.ts).\n * onUnavailable: when the list can't be fetched or verified; default\n * \"fail-closed\" for verified humans (level 5+), \"fail-open\" below.\n * cacheSeconds: how long a list is reused (default 60).\n */\n status?: { onUnavailable?: StatusPolicy; cacheSeconds?: number };\n};\n\nexport type VerifyOk = {\n ok: true;\n claims: Record<string, unknown>;\n cnf: { jwk: CnfJwk };\n /**\n * The holder-signed binding: what the cnf key signed for THIS\n * presentation (the KB-JWT, or the anonymous credential's payload).\n * `walletSessionPk` is the `prson_wsk` claim \u2014 the wallet's X25519\n * session key the data channel must come from; absent from wallets\n * that predate it.\n */\n binding: { iat: number; nonce: string; walletSessionPk?: string };\n credential: {\n vct: string;\n iss: string;\n kid: string;\n expiresAt: number;\n };\n};\n\nexport type VerifyErr = {\n ok: false;\n reason:\n | \"malformed\"\n | \"issuer_key_resolve_failed\"\n | \"issuer_sig_invalid\"\n | \"vc_expired\"\n | \"vct_not_accepted\"\n | \"typ_not_accepted\"\n | \"disclosure_unmatched\"\n | \"kb_missing\"\n | \"kb_sig_invalid\"\n | \"aud_mismatch\"\n | \"nonce_mismatch\"\n | \"sd_hash_mismatch\"\n | \"kb_iat_stale\"\n | \"vc_revoked\"\n | \"status_unavailable\";\n};\n\nexport type VerifyResult = VerifyOk | VerifyErr;\n\n/** VCT for the self-signed anonymous-wallet credential \u2014 kept here as\n * well as in index.ts so verifier callers don't have to import both. */\nconst ANONYMOUS_WALLET_VCT =\n \"https://app.prson.net/credentials/anonymous-wallet/v1\";\n\nexport async function verifyPresentation(\n sdJwt: string,\n opts: VerifyOptions,\n): Promise<VerifyResult> {\n // \u2500\u2500 Anonymous-wallet credential path \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // No SD-JWT tildes \u2014 it's a plain JWS. We accept this ONLY when the\n // calling site opted in via `acceptedVcts` containing the anonymous\n // VCT. Verification is structurally simpler: cnf.jwk IS the signer,\n // so the JWS signature + cnf-binding check collapse into one step.\n if (!sdJwt.includes(\"~\") && opts.acceptedVcts.includes(ANONYMOUS_WALLET_VCT)) {\n return verifyAnonymousWallet(sdJwt, opts);\n }\n const parts = sdJwt.split(\"~\");\n if (parts.length < 2) return { ok: false, reason: \"malformed\" };\n\n const jws = parts[0]!;\n const tail = parts.slice(1);\n const last = tail[tail.length - 1];\n let kbJwt: string | undefined;\n let discTokens: string[];\n if (last === \"\" || last === undefined) {\n discTokens = tail.slice(0, -1);\n return { ok: false, reason: \"kb_missing\" };\n } else if (last.includes(\".\")) {\n kbJwt = last;\n discTokens = tail.slice(0, -1);\n } else {\n return { ok: false, reason: \"kb_missing\" };\n }\n\n // \u2500\u2500 1. Parse the issuer JWS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const [hB64, pB64, sigB64] = jws.split(\".\");\n if (!hB64 || !pB64 || !sigB64) return { ok: false, reason: \"malformed\" };\n let header: { alg?: string; kid?: string; typ?: string };\n let payload: Record<string, unknown>;\n try {\n header = JSON.parse(new TextDecoder().decode(b64uBytes(hB64)));\n payload = JSON.parse(new TextDecoder().decode(b64uBytes(pB64)));\n } catch {\n return { ok: false, reason: \"malformed\" };\n }\n // SD-JWT VC media type (draft-ietf-oauth-sd-jwt-vc): dc+sd-jwt, or the older vc+sd-jwt.\n if (header.typ !== \"dc+sd-jwt\" && header.typ !== \"vc+sd-jwt\") {\n return { ok: false, reason: \"typ_not_accepted\" };\n }\n if (typeof payload.iss !== \"string\" || payload.iss !== opts.trustedIssuer) {\n return { ok: false, reason: \"issuer_key_resolve_failed\" };\n }\n if (typeof payload.vct !== \"string\" || !opts.acceptedVcts.includes(payload.vct)) {\n return { ok: false, reason: \"vct_not_accepted\" };\n }\n // Prson always sets an expiry; a credential without one is not Prson's.\n if (typeof payload.exp !== \"number\") return { ok: false, reason: \"malformed\" };\n if (payload.exp * 1000 < Date.now()) {\n return { ok: false, reason: \"vc_expired\" };\n }\n\n // \u2500\u2500 2. Resolve the issuer JWK + verify the JWS signature \u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const issuerJwk = await resolveIssuerJwk(header.kid ?? \"\", opts);\n if (!issuerJwk) return { ok: false, reason: \"issuer_key_resolve_failed\" };\n const issuerKey = await crypto.subtle.importKey(\n \"jwk\",\n issuerJwk as JsonWebKey,\n { name: \"RSASSA-PKCS1-v1_5\", hash: \"SHA-256\" },\n false,\n [\"verify\"],\n );\n const issuerOk = await crypto.subtle.verify(\n \"RSASSA-PKCS1-v1_5\",\n issuerKey,\n b64uBytes(sigB64),\n new TextEncoder().encode(`${hB64}.${pB64}`),\n );\n if (!issuerOk) return { ok: false, reason: \"issuer_sig_invalid\" };\n\n // \u2500\u2500 2b. Not revoked (the issuer's Token Status List) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const status = await checkCredentialStatus(payload, {\n resolveKey: (kid) => resolveIssuerJwk(kid, opts),\n onUnavailable: opts.status?.onUnavailable,\n cacheSeconds: opts.status?.cacheSeconds,\n });\n if (!status.ok) return { ok: false, reason: status.reason };\n\n // \u2500\u2500 3. Verify every Disclosure digest is in the JWS's _sd \u2500\u2500\u2500\u2500\u2500\u2500\n const sdSet = collectSdDigests(payload);\n const disclosed: Array<{ name: string; value: unknown }> = [];\n for (const t of discTokens) {\n if (!t) continue;\n const arr = JSON.parse(new TextDecoder().decode(b64uBytes(t))) as unknown[];\n if (!Array.isArray(arr) || arr.length < 2) {\n return { ok: false, reason: \"disclosure_unmatched\" };\n }\n const digest = b64uEncode(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(t))));\n if (!sdSet.has(digest)) return { ok: false, reason: \"disclosure_unmatched\" };\n if (arr.length === 3 && typeof arr[1] === \"string\") {\n disclosed.push({ name: arr[1], value: arr[2] });\n }\n }\n\n // \u2500\u2500 4. Verify the KB-JWT \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (!kbJwt) return { ok: false, reason: \"kb_missing\" };\n const cnf = (payload.cnf as { jwk?: CnfJwk } | undefined)?.jwk;\n if (!cnf || cnf.kty !== \"OKP\" || cnf.crv !== \"Ed25519\") {\n return { ok: false, reason: \"kb_missing\" };\n }\n const [kbH, kbP, kbS] = kbJwt.split(\".\");\n if (!kbH || !kbP || !kbS) return { ok: false, reason: \"kb_sig_invalid\" };\n let kbHeader: { alg?: string; typ?: string };\n let kbPayload: { aud?: string; nonce?: string; sd_hash?: string; iat?: number; prson_wsk?: unknown };\n try {\n kbHeader = JSON.parse(new TextDecoder().decode(b64uBytes(kbH)));\n kbPayload = JSON.parse(new TextDecoder().decode(b64uBytes(kbP)));\n } catch {\n return { ok: false, reason: \"kb_sig_invalid\" };\n }\n if (kbHeader.alg !== \"EdDSA\" || kbHeader.typ !== \"kb+jwt\") {\n return { ok: false, reason: \"kb_sig_invalid\" };\n }\n if (kbPayload.aud !== opts.expectedAudience) return { ok: false, reason: \"aud_mismatch\" };\n if (kbPayload.nonce !== opts.expectedNonce) return { ok: false, reason: \"nonce_mismatch\" };\n if (typeof kbPayload.iat !== \"number\") return { ok: false, reason: \"kb_iat_stale\" };\n const maxAge = opts.maxKbAgeSeconds ?? 60;\n if (Math.abs(Date.now() / 1000 - kbPayload.iat) > maxAge) {\n return { ok: false, reason: \"kb_iat_stale\" };\n }\n // Per SD-JWT-VC: prefix is \"<JWS>~<D_1>~...~<D_n>~\" with exactly\n // ONE trailing tilde \u2014 N tildes total for N-1 disclosures. The\n // naive `${jws}~${discTokens.join(\"~\")}~` produces TWO trailing\n // tildes when `discTokens.length === 0` (since `[].join === \"\"`),\n // breaking every no-disclosure presentation (verified-human only,\n // anonymous, anything where the holder filtered out all\n // disclosures). Build it from parts directly so it stays correct\n // at n=0.\n const prefixParts = discTokens.length === 0\n ? [jws]\n : [jws, ...discTokens];\n const presentationPrefix = `${prefixParts.join(\"~\")}~`;\n const sdHash = b64uEncode(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(presentationPrefix))));\n if (kbPayload.sd_hash !== sdHash) return { ok: false, reason: \"sd_hash_mismatch\" };\n\n const holderKey = await crypto.subtle.importKey(\n \"jwk\",\n cnf as JsonWebKey,\n { name: \"Ed25519\" },\n false,\n [\"verify\"],\n );\n const kbOk = await crypto.subtle.verify(\n \"Ed25519\",\n holderKey,\n b64uBytes(kbS),\n new TextEncoder().encode(`${kbH}.${kbP}`),\n );\n if (!kbOk) return { ok: false, reason: \"kb_sig_invalid\" };\n\n // \u2500\u2500 5. Reassemble disclosed claims \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const claims: Record<string, unknown> = {};\n // Always-visible top-level claims from the JWS (minus SD internals).\n for (const [k, v] of Object.entries(payload)) {\n if (k === \"_sd\" || k === \"_sd_alg\" || k === \"cnf\") continue;\n if ([\"iss\", \"vct\", \"iat\", \"exp\"].includes(k)) continue;\n claims[k] = v;\n }\n for (const d of disclosed) claims[d.name] = d.value;\n\n return {\n ok: true,\n claims,\n cnf: { jwk: cnf },\n binding: {\n iat: kbPayload.iat,\n nonce: kbPayload.nonce as string,\n ...walletSessionKeyClaim(kbPayload.prson_wsk),\n },\n credential: {\n vct: payload.vct as string,\n iss: payload.iss as string,\n kid: (header.kid ?? \"\") as string,\n expiresAt: typeof payload.exp === \"number\" ? payload.exp * 1000 : 0,\n },\n };\n}\n\n/**\n * The `prson_wsk` claim: the wallet's X25519 session key (32 bytes,\n * base64url without padding), signed by the cnf key so the data channel\n * can be tied to the holder. Anything malformed counts as absent.\n */\nfunction walletSessionKeyClaim(v: unknown): { walletSessionPk?: string } {\n if (typeof v !== \"string\" || !/^[A-Za-z0-9_-]{43}$/.test(v)) return {};\n return { walletSessionPk: v };\n}\n\n/** Lazy in-memory cache of the Prson issuer JWKS. 1 h TTL. */\nconst jwksCache = new Map<string, { fetchedAt: number; keys: Record<string, JsonWebKey> }>();\n\nasync function resolveIssuerJwk(\n kid: string,\n opts: VerifyOptions,\n): Promise<JsonWebKey | null> {\n if (!kid) return null;\n // did:web:app.prson.net \u2192 https://app.prson.net/.well-known/jwt-vc-issuer.\n const host = opts.trustedIssuer.replace(/^did:web:/, \"\");\n const uri = opts.jwksUri ?? `https://${host}/.well-known/jwt-vc-issuer`;\n const cached = jwksCache.get(uri);\n if (cached && Date.now() - cached.fetchedAt < 60 * 60 * 1000) {\n return cached.keys[kid] ?? null;\n }\n const res = await fetch(uri);\n if (!res.ok) return null;\n const body = (await res.json()) as { jwks?: { keys: JsonWebKey[] }; keys?: JsonWebKey[] };\n const keys = body.jwks?.keys ?? body.keys ?? [];\n const map: Record<string, JsonWebKey> = {};\n for (const k of keys) {\n const id = (k as { kid?: string }).kid;\n if (id) map[id] = k;\n }\n jwksCache.set(uri, { fetchedAt: Date.now(), keys: map });\n return map[kid] ?? null;\n}\n\nfunction collectSdDigests(payload: unknown, out = new Set<string>()): Set<string> {\n if (!payload || typeof payload !== \"object\") return out;\n if (Array.isArray(payload)) {\n for (const v of payload) collectSdDigests(v, out);\n return out;\n }\n const obj = payload as Record<string, unknown>;\n for (const [k, v] of Object.entries(obj)) {\n if (k === \"_sd\" && Array.isArray(v)) {\n for (const digest of v) {\n if (typeof digest === \"string\") out.add(digest);\n }\n } else if (typeof v === \"object\") {\n collectSdDigests(v, out);\n }\n }\n return out;\n}\n\n// Returns an ArrayBuffer-backed Uint8Array so it's `BufferSource`-typed\n// under TypeScript 5.7+'s stricter typings (SharedArrayBuffer-backed\n// views are rejected by SubtleCrypto's `verify` signature).\nfunction b64uBytes(s: string): Uint8Array<ArrayBuffer> {\n const pad = (4 - (s.length % 4)) % 4;\n const std = (s + \"=\".repeat(pad)).replace(/-/g, \"+\").replace(/_/g, \"/\");\n const bin = atob(std);\n const buf = new ArrayBuffer(bin.length);\n const out = new Uint8Array(buf);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nfunction b64uEncode(bytes: Uint8Array): string {\n let s = \"\";\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]!);\n return btoa(s).replace(/=+$/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n}\n\n/**\n * Verify a self-signed anonymous-wallet credential. Spec:\n *\n * header = { typ: \"anon-wallet+jwt\", alg: \"EdDSA\" }\n * payload = { iss: <domain>, aud, nonce, iat, exp,\n * vct: ANONYMOUS_WALLET_VCT,\n * cnf: { jwk: <Ed25519 OKP JWK> } }\n *\n * The signing key IS cnf.jwk \u2014 there's no separate issuer key to\n * resolve. The verifier checks aud/nonce/exp and the Ed25519 sig.\n *\n * This is only accepted by [verifyPresentation] when `acceptedVcts`\n * includes ANONYMOUS_WALLET_VCT, which only happens when the host\n * site passed `allowAnonymous: true` to PrsonLogin.signIn().\n */\nasync function verifyAnonymousWallet(\n jws: string,\n opts: VerifyOptions,\n): Promise<VerifyResult> {\n const [hB64, pB64, sigB64] = jws.split(\".\");\n if (!hB64 || !pB64 || !sigB64) return { ok: false, reason: \"malformed\" };\n let header: { alg?: string; typ?: string };\n let payload: Record<string, unknown>;\n try {\n header = JSON.parse(new TextDecoder().decode(b64uBytes(hB64)));\n payload = JSON.parse(new TextDecoder().decode(b64uBytes(pB64)));\n } catch {\n return { ok: false, reason: \"malformed\" };\n }\n if (header.alg !== \"EdDSA\" || header.typ !== \"anon-wallet+jwt\") {\n return { ok: false, reason: \"malformed\" };\n }\n if (payload.vct !== ANONYMOUS_WALLET_VCT) {\n return { ok: false, reason: \"vct_not_accepted\" };\n }\n const cnf = (payload.cnf as { jwk?: CnfJwk } | undefined)?.jwk;\n if (!cnf || cnf.kty !== \"OKP\" || cnf.crv !== \"Ed25519\") {\n return { ok: false, reason: \"kb_missing\" };\n }\n if (payload.aud !== opts.expectedAudience) {\n return { ok: false, reason: \"aud_mismatch\" };\n }\n if (payload.nonce !== opts.expectedNonce) {\n return { ok: false, reason: \"nonce_mismatch\" };\n }\n const nowSec = Math.floor(Date.now() / 1000);\n if (typeof payload.exp !== \"number\" || payload.exp < nowSec) {\n return { ok: false, reason: \"vc_expired\" };\n }\n if (typeof payload.iat !== \"number\" || Math.abs(nowSec - payload.iat) > (opts.maxKbAgeSeconds ?? 60)) {\n return { ok: false, reason: \"kb_iat_stale\" };\n }\n // The signing key is cnf.jwk itself \u2014 no separate issuer key to\n // resolve. A correct signature here proves the holder controls the\n // pk they're claiming.\n const key = await crypto.subtle.importKey(\n \"jwk\",\n cnf as JsonWebKey,\n { name: \"Ed25519\" },\n false,\n [\"verify\"],\n );\n const ok = await crypto.subtle.verify(\n \"Ed25519\",\n key,\n b64uBytes(sigB64),\n new TextEncoder().encode(`${hB64}.${pB64}`),\n );\n if (!ok) return { ok: false, reason: \"issuer_sig_invalid\" };\n\n return {\n ok: true,\n claims: {\n // Anonymous credentials carry no profile data \u2014 just the marker\n // that the user controls the signing key. The host site treats\n // cnf.jwk.x as the stable per-user id on this domain.\n anonymous: true,\n },\n cnf: { jwk: cnf },\n binding: {\n iat: payload.iat as number,\n nonce: payload.nonce as string,\n ...walletSessionKeyClaim(payload.prson_wsk),\n },\n credential: {\n vct: ANONYMOUS_WALLET_VCT,\n iss: typeof payload.iss === \"string\" ? payload.iss : opts.trustedIssuer,\n kid: \"\",\n expiresAt: (payload.exp as number) * 1000,\n },\n };\n}\n", "/**\n * Verifier \u2192 wallet REQUEST channel.\n *\n * After sign-in the host site can ask the wallet for things that\n * weren't part of the initial disclosure (a specific claim value, a\n * predicate check, a document presence assertion, a document\n * signature, a free-form input typed on the phone). Each request\n * carries a UUID; the wallet replies with a matching `response`\n * envelope whose `requestId` references it.\n *\n * Three protocol invariants the wallet enforces:\n *\n * * **At most one request per second** \u2014 inter-arrival throttle on\n * the wallet side. Inbound requests that violate this are silently\n * dropped (no response sent); the browser SDK's per-call timeout\n * surfaces them as `error: \"timeout\"`.\n *\n * * **At most five outstanding requests** in the wallet's queue.\n * Once five drawers are open, further incoming requests are\n * ignored on the floor.\n *\n * * **Requests fire ONLY while a web session is active.** No\n * background requests, no pre-sign-in requests. The session's\n * transport going away invalidates every pending request with\n * `error: \"no-active-session\"`.\n *\n * Browser SDK shape (this file): public types + the in-flight\n * controller that pairs outbound requests with their wallet replies.\n * The session's `_sendToWallet` is the cipher path.\n */\n\nimport type { DecryptedEnvelope } from \"./crypto.js\";\n\n// \u2500\u2500\u2500 Public request shapes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Output wire format for a signed predicate (fragment). See\n * `functions/utils/predicateFormatters.js` for the formatter registry\n * the server uses; the verifier-node package decodes the matching\n * shape with `verifySignedFragment` / `verifyFragmentCredential`.\n */\nexport type PredicateFormat = \"native\" | \"vc+jwt\" | \"vc+sd-jwt\";\n\n/**\n * Free-form text/numeric input typed on the phone \u2014 the \"kiosk\n * companion\" use case. Mirrors a subset of the HTML input element\n * so the wallet UI can pick a sensible keyboard / validator.\n *\n * `select` is included to cover `<select>` elements: the wallet UI\n * renders an options picker (radio-style on phone) and returns the\n * chosen option's `value`.\n */\nexport type InputType =\n | \"text\"\n | \"search\"\n | \"email\"\n | \"tel\"\n | \"url\"\n | \"number\"\n | \"password\"\n | \"select\";\n\n/** One choice in a `select` field. */\nexport interface InputOption {\n /** Wire value \u2014 what the wallet returns and the host fills. */\n value: string;\n /** Display label shown in the wallet picker. Defaults to `value`. */\n label?: string;\n}\n\n/**\n * One field inside a multi-input `input-form` request. Same surface\n * as a single `kind: \"input\"` request, plus an optional `name` (used\n * as the reply key) and a `defaultValue` (pre-fill).\n *\n * Two shapes \u2014 the discriminator is `inputType`:\n *\n * * Text/numeric inputs: `text` | `search` | `email` | `tel` |\n * `url` | `number` | `password` \u2014 validation knobs match the\n * HTML5 attribute set the host can read off a DOM `<input>`.\n *\n * * Select picker: `inputType: \"select\"` requires `options` and\n * ignores the validation knobs that don't apply (`pattern`,\n * `minLength`, `maxLength`).\n */\nexport type InputFormField =\n | {\n name: string;\n inputType: Exclude<InputType, \"select\">;\n label: string;\n placeholder?: string;\n defaultValue?: string;\n minLength?: number;\n maxLength?: number;\n min?: number;\n max?: number;\n pattern?: string;\n required?: boolean;\n }\n | {\n name: string;\n inputType: \"select\";\n label: string;\n options: InputOption[];\n defaultValue?: string;\n required?: boolean;\n };\n\nexport type LoginRequest =\n /**\n * Ask the wallet to reveal the raw value of a single claim. Used\n * by host sites that want a stale claim refreshed without a\n * full re-sign-in \u2014 e.g. \"what's your current verification\n * level?\". The wallet prompts the user before answering.\n */\n | {\n kind: \"claim-value\";\n name: string;\n /** Human-readable reason shown in the wallet drawer. */\n reason?: string;\n }\n\n /**\n * Predicate check against a fragment the wallet has signed.\n * Returns the matching signed fragment so the verifier can\n * re-verify the signature server-side.\n *\n * `format` selects the wire shape the wallet asks the notary to\n * mint:\n * * `native` \u2014 Prson-flat shape (RSA-SHA256 over the canonical\n * bytes). Smallest, default for back-compat.\n * * `vc+jwt` \u2014 W3C VC Data Model 2.0 JWS.\n * * `vc+sd-jwt` \u2014 IETF SD-JWT-VC with one disclosure.\n * The choice flows server-side via the\n * `signPropertyFragment` Cloud Function's `format` parameter and is\n * verified browser-side by `@prson/login-verifier`'s\n * `verifySignedFragment` (native) / `verifyFragmentCredential` (jwt).\n */\n | {\n kind: \"fragment-check\";\n fragmentName: string;\n format?: PredicateFormat;\n reason?: string;\n }\n\n /**\n * Ask the wallet whether a verified document of the given shape\n * is present. The user can also pick a document; if none\n * matches, the wallet may offer to scan one via NFC (if the\n * device is compatible). Reply carries either the document's\n * notarised metadata or an error.\n */\n | {\n kind: \"document-presence\";\n /** Filter \u2014 `\"passport\"`, `\"national_id\"`, etc. */\n type?: string;\n /** ISO-3 country code, optional. */\n country?: string;\n reason?: string;\n }\n\n /**\n * Document signing \u2014 the host hands the wallet either the raw\n * bytes (for tiny files) or a short-lived upload URL. The wallet\n * signs with the identity's PAdES-bound EC key (see\n * `mobile-app/prson_app/docs/identity_pdf_signing.md`).\n */\n | {\n kind: \"document-sign\";\n document:\n | { bytes: Uint8Array }\n | { uploadUrl: string; size?: number; sha256?: string };\n visibleCue?: string;\n reason?: string;\n }\n\n /**\n * Generic single input request \u2014 kiosk pattern. The wallet shows\n * a keyboard sized to the type + the constraints, returns the\n * typed value. No notary signature \u2014 the host trusts the\n * channel + the user.\n *\n * For `inputType: \"select\"`, supply `options`. The wallet\n * renders a radio-style picker on the phone and the reply's\n * `value` is the chosen option's `value` string.\n */\n | {\n kind: \"input\";\n inputType: InputType;\n label: string;\n placeholder?: string;\n defaultValue?: string;\n /** HTML5-style validation constraints \u2014 wallet enforces. */\n minLength?: number;\n maxLength?: number;\n /** For `inputType: \"number\"`. */\n min?: number;\n max?: number;\n /** Regex; wallet uses to gate the submit button. */\n pattern?: string;\n required?: boolean;\n /** Required when `inputType === \"select\"`. */\n options?: InputOption[];\n reason?: string;\n }\n\n /**\n * Multi-input form \u2014 one wallet drawer, prev/next/send\n * navigation, fills every field at once when the user taps\n * Send. The reply's `value` is `Record<fieldName, string>`.\n *\n * Drives the `session.bindForm(...)` helper, which walks a\n * `<form>` / container element and synthesises one of these\n * requests from the DOM. The host can also build them by\n * hand \u2014 useful for verifier-side flows where the inputs are\n * decided at runtime rather than rendered on the page.\n */\n | {\n kind: \"input-form\";\n fields: InputFormField[];\n /** Label on the final \"Send\" button. Defaults to \"Send\". */\n submitLabel?: string;\n reason?: string;\n }\n\n /**\n * Virtual pointer / cursor. The wallet sources pointer events\n * from the phone and streams them through `mouse-update`\n * envelopes (paired by `requestId`) until the user closes the\n * drawer; the final `response` carries the session totals.\n *\n * Two modes:\n *\n * * `\"touch\"` \u2014 the phone screen becomes a touchpad. Drag the\n * finger to move the cursor; single-tap = click;\n * double-tap = double-click; two-finger drag = scroll. The\n * [`bindMouse`] helper renders a small circular cursor over\n * the page and applies the streamed deltas.\n *\n * * `\"magic\"` \u2014 phone gyro + accelerometer drive a \"magic\n * wand\". Tap on the phone screen = click; double-tap =\n * double-click; swipe up / down on the phone = scroll.\n * Bigger learning curve but no thumb-on-screen\n * drag \u2014 useful for hands-free presentation control.\n *\n * The host requests a mode; the wallet UI honours it but may\n * surface a toggle to switch mid-session (in which case the\n * streamed envelopes carry the actual mode in `mode`).\n */\n | {\n kind: \"mouse\";\n mode: \"touch\" | \"magic\";\n reason?: string;\n };\n\nexport type LoginResponse =\n /** Success \u2014 `value` shape depends on the request kind. */\n | { ok: true; value: unknown }\n /** Failure \u2014 `error` is a short machine-readable code. */\n | {\n ok: false;\n error:\n | \"declined\"\n | \"not-present\"\n | \"expired\"\n | \"rate-limited\"\n | \"queue-full\"\n | \"no-active-session\"\n | \"timeout\"\n | \"session-closed\"\n | \"unsupported\"\n | string;\n };\n\nexport interface RequestOptions {\n /**\n * Hard deadline for the wallet reply. Default 60 s \u2014 generous\n * because the wallet drawer is on the user's phone and they may\n * need to scan an NFC document. Callers expecting a fast reply\n * (e.g. kiosk text input) can tighten this.\n */\n timeoutMs?: number;\n}\n\n// \u2500\u2500\u2500 In-flight controller \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface Pending {\n requestId: string;\n resolve: (r: LoginResponse) => void;\n timer: ReturnType<typeof setTimeout> | null;\n}\n\n/**\n * Pairs outbound `request` envelopes with their matching\n * `response` envelopes by UUID. Held privately on a\n * `PrsonLoginSession`; not part of the public surface.\n */\nexport class RequestController {\n private _pending = new Map<string, Pending>();\n private _closed = false;\n\n /**\n * Wire up a new outbound request. Returns the requestId to put in\n * the envelope + a `promise` that resolves when the wallet replies\n * (or times out / the session closes).\n */\n enqueue(timeoutMs: number): { requestId: string; promise: Promise<LoginResponse> } {\n const requestId = newUuid();\n // `setTimeout` accepts up to int32-max milliseconds (~24.8 days)\n // before silently overflowing and firing on the next tick. Any\n // caller passing a credential-exp-derived budget (90-day VC\n // credentials yield ~7.8 billion ms) would otherwise see an\n // immediate `error: \"timeout\"`. Clamp defensively here so the\n // contract holds regardless of caller hygiene.\n const MAX_SAFE_TIMEOUT = 2_147_483_000;\n const safeTimeoutMs = Math.min(\n Math.max(0, timeoutMs),\n MAX_SAFE_TIMEOUT,\n );\n const promise = new Promise<LoginResponse>((resolve) => {\n if (this._closed) {\n resolve({ ok: false, error: \"session-closed\" });\n return;\n }\n const entry: Pending = {\n requestId,\n resolve,\n timer: setTimeout(() => {\n const p = this._pending.get(requestId);\n if (!p) return;\n this._pending.delete(requestId);\n resolve({ ok: false, error: \"timeout\" });\n }, safeTimeoutMs),\n };\n this._pending.set(requestId, entry);\n });\n return { requestId, promise };\n }\n\n /** Resolve a pending request when a wallet `response` envelope arrives. */\n resolve(envelope: DecryptedEnvelope): void {\n if (envelope.msg !== \"response\") return;\n const requestId = envelope.requestId;\n if (!requestId) return;\n const entry = this._pending.get(requestId);\n if (!entry) return; // unknown id \u2014 late reply after timeout, ignore\n this._pending.delete(requestId);\n if (entry.timer) clearTimeout(entry.timer);\n if (envelope.error) {\n entry.resolve({ ok: false, error: envelope.error });\n } else {\n entry.resolve({ ok: true, value: envelope.result });\n }\n }\n\n /**\n * Reject every in-flight request with the given reason. Typically\n * called with `\"session-closed\"` from session teardown.\n */\n closeAll(reason: string): void {\n if (this._closed) return;\n this._closed = true;\n for (const entry of this._pending.values()) {\n if (entry.timer) clearTimeout(entry.timer);\n entry.resolve({ ok: false, error: reason });\n }\n this._pending.clear();\n }\n}\n\n/**\n * RFC-4122 v4 UUID via `crypto.randomUUID` when present, else a\n * `getRandomValues`-based fallback for older browsers. The wire\n * carries the canonical hex-with-dashes form.\n */\nfunction newUuid(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const b = new Uint8Array(16);\n crypto.getRandomValues(b);\n // version + variant bits per RFC 4122\n b[6] = (b[6]! & 0x0f) | 0x40;\n b[8] = (b[8]! & 0x3f) | 0x80;\n const h = Array.from(b, (x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n}\n", "/**\n * PrsonLoginSession \u2014 the live handle the SDK returns from\n * `signIn()`. Owns the established WebRTC transport + ephemeral\n * keys; dispatches a typed event stream as the wallet pushes\n * post-sign-in updates; tears everything down when the credential\n * expires or the host calls `close()`.\n *\n * Event taxonomy (see [ROADMAP \u00A71](../../ROADMAP.md)):\n *\n * Identity lifecycle:\n * signed_in \u2014 fires once, right after `signIn()`\n * resolves (via a microtask so listeners\n * attached synchronously after the await\n * still receive it).\n * signed_out \u2014 terminal; fires once with an\n * ExpiryReason.\n * renewed \u2014 wallet pushed a fresh VC + KB-JWT.\n *\n * Claim updates (require a re-verified SD-JWT-VC in the same\n * envelope):\n * claim_added \u2014 a claim name appeared that wasn't in\n * the prior snapshot.\n * claim_removed \u2014 a prior claim name is no longer\n * present.\n * claim_updated \u2014 same name, different value.\n *\n * Display hints (no crypto re-verify; the host should treat the\n * payload as advisory and ignore it for any privileged decision):\n * display_name_changed\n * avatar_changed\n *\n * Compliance:\n * credential_revoked \u2014 followed by signed_out with reason\n * \"credential_revoked\".\n *\n * Wire grammar lives in `crypto.ts:DecryptedEnvelope`.\n */\nimport type { CnfJwk, SignInResult } from \"./index.js\";\nimport type { DecryptedEnvelope, EphemeralKeys } from \"./crypto.js\";\nimport { boxToWallet, decryptEnvelope } from \"./crypto.js\";\nimport type { Transport } from \"./transport.js\";\nimport { verifyPresentation, type VerifyOptions } from \"./verify.js\";\nimport {\n RequestController,\n type LoginRequest,\n type LoginResponse,\n type RequestOptions,\n} from \"./requests.js\";\n\nexport type { LoginRequest, LoginResponse, RequestOptions, InputType } from \"./requests.js\";\n\nexport type ExpiryReason =\n | \"ttl_reached\"\n | \"wallet_signed_out\"\n | \"user_revoked\"\n | \"network_loss\"\n | \"credential_revoked\";\n\nexport type CredentialRevokedReason =\n | \"alias_transferred\"\n | \"user_revoked\"\n | \"key_compromised\";\n\n/**\n * Coarse health of the wallet \u2194 browser data channel as observed via\n * the periodic ping/pong loop. Drives the connection-status dot the\n * wallet renders on its remote-nav banner; partner sites can mirror\n * the same signal by reading [PrsonLoginSession.connectionStatus] /\n * subscribing via [PrsonLoginSession.onConnectionStatus].\n *\n * * `unknown` \u2014 before the first pong has landed.\n * * `stable` \u2014 last RTT under [CONNECTION_UNSTABLE_THRESHOLD_MS].\n * * `unstable` \u2014 last RTT crossed the threshold.\n * * `offline` \u2014 no pong for [CONNECTION_OFFLINE_AFTER_MS]; the\n * channel is either dead or paused.\n */\nexport type ConnectionStatus = \"unknown\" | \"stable\" | \"unstable\" | \"offline\";\n\n/** RTT above this (ms) flips connectionStatus to `unstable`. */\nconst CONNECTION_UNSTABLE_THRESHOLD_MS = 1000;\n/** No pong observed for this long (ms) flips status to `offline`. */\nconst CONNECTION_OFFLINE_AFTER_MS = 5000;\n/** Cadence of the local ping loop (ms). */\nconst PING_INTERVAL_MS = 2000;\n/** Delay before retransmitting an ack-required envelope (ms). */\nconst ACK_RETRY_DELAY_MS = 2000;\n/** Maximum retransmissions before giving up on an ack-required envelope. */\nconst ACK_MAX_ATTEMPTS = 3;\n/** LRU cap on the seen-id dedupe set. ~500 ids \u2248 16 min of pings\n * on the 2 s loop, far longer than any realistic re-send window. */\nconst SEEN_IDS_CAPACITY = 500;\n\n/**\n * Generate a UUID v4. Browsers shipping `crypto.randomUUID` use it\n * directly; older engines fall back to a `getRandomValues`-based\n * implementation that produces the same on-the-wire shape.\n */\n/**\n * Detach a timer handle from Node's \"keep the event loop alive\"\n * accounting. In browsers `setTimeout` / `setInterval` return a\n * number with no `unref` method, so the test is a harmless no-op.\n * In Node the returned `Timeout` object has `unref()` and this is\n * what stops unit tests from hanging until their hour-scale expiry\n * timer would otherwise fire.\n */\nfunction _unrefTimer(\n t: ReturnType<typeof setTimeout> | ReturnType<typeof setInterval> | null,\n): void {\n if (t === null) return;\n const maybe = t as unknown as { unref?: () => void };\n if (typeof maybe.unref === \"function\") maybe.unref();\n}\n\n/**\n * Map a transport-layer close reason string onto the SDK's typed\n * [ExpiryReason]. The transport emits a small vocabulary:\n *\n * * `\"ttl_reached\"` \u2014 Worker DO alarm fired at session TTL\n * * `\"wallet_signed_out\"` \u2014 wallet sent a `peer-gone` signaling\n * message (revoked) before the wire\n * died\n * * `\"network_loss\"` \u2014 anything else (signaling WS dropped\n * for a transport reason, data channel\n * closed on its own, etc.)\n *\n * Anything we don't recognise degrades to `network_loss` \u2014\n * preserving the host's invariant that a `signed_out` event always\n * carries a known reason.\n */\nfunction _mapTransportCloseReason(reason: string): ExpiryReason {\n if (reason === \"ttl_reached\") return \"ttl_reached\";\n if (reason === \"wallet_signed_out\") return \"wallet_signed_out\";\n if (reason === \"user_revoked\") return \"user_revoked\";\n if (reason === \"credential_revoked\") return \"credential_revoked\";\n return \"network_loss\";\n}\n\nfunction uuidv4(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const buf = new Uint8Array(16);\n crypto.getRandomValues(buf);\n buf[6] = (buf[6]! & 0x0f) | 0x40; // version 4\n buf[8] = (buf[8]! & 0x3f) | 0x80; // variant 10\n const h: string[] = [];\n for (let i = 0; i < 16; i++) h.push(buf[i]!.toString(16).padStart(2, \"0\"));\n return (\n h.slice(0, 4).join(\"\") +\n \"-\" +\n h.slice(4, 6).join(\"\") +\n \"-\" +\n h.slice(6, 8).join(\"\") +\n \"-\" +\n h.slice(8, 10).join(\"\") +\n \"-\" +\n h.slice(10, 16).join(\"\")\n );\n}\n\n/** Convenience alias kept for callers that consumed the old shape. */\nexport type Renewal = Pick<SignInResult, \"sdJwtVc\" | \"claims\" | \"credential\">;\n\n/**\n * Discriminated union of every lifecycle event the SDK emits during\n * a live session. Each variant carries exactly the fields a\n * subscriber needs \u2014 no shared base envelope, so `e.type` is the\n * only discriminator and the TS compiler narrows the rest.\n *\n * The `signed_in` event also rides this union for uniform\n * subscription, even though `signIn()` already returns the result\n * synchronously. Useful for `onAny` listeners that want a single\n * log line per lifecycle transition.\n *\n * **Privacy policy: claim events never carry raw values.**\n * `claim_added` / `claim_updated` / `claim_removed` deliver only\n * the changed claim **name**. The actual value lives in\n * `session.claims` (the verified snapshot the SDK keeps in sync\n * with the latest SD-JWT-VC) and is read on-demand by the host.\n *\n * Why: `onAny` is the natural attachment point for telemetry\n * (analytics, error reporters, ML feature pipes, \u2026). Any of those\n * trivially capture entire event objects. Putting `value` into the\n * event payload would silently leak raw identity data \u2014 name,\n * birthdate, verification level \u2014 through every such pipe without\n * the host owner noticing. Name-only events let telemetry log\n * **that** a claim changed without ever seeing **what** it changed\n * to. The host reads `session.claims[name]` when (and only when)\n * it needs the value, and is free to scrub that read site\n * independently of the event surface.\n *\n * The exceptions are the explicitly-public display fields\n * (`display_name_changed`, `avatar_changed`) \u2014 those carry their\n * values directly because they're meant to drive UI without an\n * extra read step.\n */\nexport type LoginEvent =\n | { type: \"signed_in\"; result: SignInResult }\n | { type: \"signed_out\"; reason: ExpiryReason }\n | { type: \"renewed\"; result: SignInResult }\n /**\n * Claim added / updated. `newHash` is a hex-encoded SHA-256 of the\n * canonical-JSON encoding of the NEW value \u2014 the host can compare\n * against a precomputed `sha256(canonical(expected))` to confirm\n * what the new value is without ever seeing the value travel\n * through the event payload. The full value lives in\n * `session.claims[name]` for callers that need it.\n */\n | { type: \"claim_added\"; name: string; newHash: string }\n | { type: \"claim_updated\"; name: string; newHash: string }\n | { type: \"claim_removed\"; name: string }\n | { type: \"display_name_changed\"; displayName: string | null }\n | { type: \"avatar_changed\"; avatar: { url: string; hash: string } | null }\n | { type: \"credential_revoked\"; reason: CredentialRevokedReason };\n\nexport type LoginEventType = LoginEvent[\"type\"];\n\n/** Function returned by `on()` / `onAny()` to remove the listener. */\nexport type Unsubscribe = () => void;\n\nexport class PrsonLoginSession {\n private _expiresAt: number;\n private _cnf: { jwk: CnfJwk };\n private _claimsSnapshot: Record<string, unknown>;\n private _transport: Transport;\n private _ephKeys: EphemeralKeys;\n private _verifierContext: VerifierContext;\n private _expiryTimer: ReturnType<typeof setTimeout> | null = null;\n private _closed = false;\n\n /**\n * Wallet's session X25519 public key, PINNED from the verified\n * sign-in presentation (its KB-JWT `prson_wsk` claim, signed by the\n * cnf key). Every inbound envelope must be boxed by this key or it is\n * dropped, and every outbound one is boxed to it. It changes only when\n * a verified `renewal` presentation carries a new `prson_wsk`. Null\n * when the wallet published none \u2014 calls to `request()` then resolve\n * with `{ ok: false, error: \"no-active-session\" }`.\n */\n private _walletSessionPk: string | null = null;\n\n /**\n * True when the sign-in presentation didn't bind a session key (a\n * wallet older than envelope v2). The sender of inbound envelopes\n * can't be checked then, so envelopes that act on the page (`nav`,\n * `value`, `mouse-update`, file transfer) and request replies\n * (`response`) are ignored, `request()` resolves with\n * `{ ok: false, error: \"unsupported\" }` and no field values are sent\n * (`focus`). Sign-in, renewals and claim updates (all verified\n * presentations) and sign-out still work. See SECURITY.md \u00A74.\n */\n private _legacyChannel = false;\n\n /** `iat` of the newest verified presentation (sign-in or renewal).\n * A renewal / claim-update must be strictly newer. */\n private _lastPresentationIat = 0;\n\n /** SHA-256 of every presentation this session accepted, so a replay\n * of an earlier one (even with a still-fresh `iat`) is refused. */\n private _seenPresentations: Set<string> = new Set();\n\n /** Pairs outbound `request` envelopes with inbound `response`s. */\n private _requestController = new RequestController();\n\n /**\n * Per-`requestId` mouse-update subscribers. Populated by\n * [`bindMouse`] when it opens a `kind: \"mouse\"` request and torn\n * down when the controller disposes or the wallet's final\n * `response` arrives. Keys are RFC-4122 v4 UUIDs (the request id);\n * values get a stream of decoded `mouse` bodies.\n */\n private _mouseSubscribers: Map<string, (mouse: NonNullable<DecryptedEnvelope[\"mouse\"]>) => void> = new Map();\n\n /**\n * Ambient mouse-update handler. Used when the wallet starts a\n * mouse stream WITHOUT a prior `kind: \"mouse\"` request \u2014 i.e.\n * the pre-grant flow enabled by [SignInOptions.mouseControl].\n * [`bindMouse`] registers itself here; any inbound\n * `mouse-update` frame whose `requestId` doesn't match a\n * specific subscriber falls through to this handler so the\n * cursor moves regardless of who initiated the stream.\n *\n * Null when no [`bindMouse`] is mounted; only one ambient\n * handler is active at a time (last call wins, mirroring the\n * remote-nav listener semantics).\n */\n private _ambientMouseHandler: ((mouse: NonNullable<DecryptedEnvelope[\"mouse\"]>) => void) | null = null;\n\n /**\n * File-transfer envelope handler. [`enableRemoteNavigation`]\n * installs one of these to receive `file-begin` / `file-chunk` /\n * `file-end` envelopes and reassemble the bytes into a `File`\n * the focused `<input type=\"file\">` accepts. The session layer\n * just dispatches \u2014 assembly logic lives in `bind.ts` so the\n * DOM dependency stays out of the protocol layer.\n */\n private _fileEnvelopeHandler: ((envelope: DecryptedEnvelope) => void) | null = null;\n\n /**\n * Remote-navigation listener \u2014 installed by\n * [`enableRemoteNavigation`]. Receives every inbound `nav`,\n * `value`, and `logout` envelope. Only one listener at a time\n * (later registrations replace the prior). Null when remote-nav\n * is not active for this session.\n */\n private _remoteNavListener:\n | ((\n envelope:\n | { msg: \"nav\"; action: \"prev\" | \"next\" | \"submit\" }\n | { msg: \"value\"; value: string }\n | { msg: \"logout\" },\n ) => void)\n | null = null;\n\n /**\n * User's preferred UI language as a BCP-47 tag. Captured from the\n * initial `presentation` envelope's `preferredLanguage` field;\n * updated whenever a fresh envelope arrives with a new value.\n * Null until the first envelope lands. The host page reads this\n * to localise its own UI without an extra round-trip.\n */\n private _preferredLanguage: string | null = null;\n\n /**\n * Public-profile display name (cosmetic \u2014 host should treat as\n * untrusted). Seeded from the wallet's initial `presentation`\n * envelope and updated via `display-update` envelopes; mirrored\n * by the `display_name_changed` event.\n */\n private _displayName: string | null = null;\n\n /**\n * Public-profile avatar pointer (cosmetic). Same trust model as\n * `_displayName`. Updated via `display-update` envelopes; mirrored\n * by `avatar_changed`.\n */\n private _avatar: { url: string; hash: string } | null = null;\n\n /** Per-type listener map. */\n private _listeners: Map<LoginEventType, Set<(e: LoginEvent) => void>> =\n new Map();\n /** \"Fire on every event\" subscribers \u2014 for logging / telemetry. */\n private _anyListeners: Set<(e: LoginEvent) => void> = new Set();\n\n // \u2500\u2500\u2500 Transport-layer reliability state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n //\n // Mirrors the wallet's LoginSession protocol (see\n // mobile-app/.../login_session_service.dart):\n //\n // * `_seenIds` + `_seenIdsOrder` \u2014 LRU dedupe of inbound `id`s.\n // * `_pendingAcks` \u2014 outbound ack-tracked sends.\n // * `_pingSendTimes` \u2014 RTT correlation by ping id.\n // * `_pingTimer` + `_offlineTimer` \u2014 liveness loop.\n //\n // Browser-side critical sends are: `request`, `focus`, `ack`,\n // `pong`. Of those only `request` already has its own\n // RequestController/timeout contract; the rest are fire-and-forget\n // today. To keep the surface small AND match the wallet, we add\n // ack tracking on outbound `focus` only (high signal-to-noise for\n // remote-nav UX). `request` keeps its existing semantics; `ack`\n // and `pong` are never themselves ack-tracked (would loop).\n private _seenIds: Set<string> = new Set();\n private _seenIdsOrder: string[] = [];\n private _pendingAcks: Map<\n string,\n { encoded: string; attempts: number; timer: ReturnType<typeof setTimeout> | null }\n > = new Map();\n private _pingSendTimes: Map<string, number> = new Map();\n private _pingTimer: ReturnType<typeof setInterval> | null = null;\n private _offlineTimer: ReturnType<typeof setTimeout> | null = null;\n private _connectionStatus: ConnectionStatus = \"unknown\";\n private _lastRttMs: number | null = null;\n private _connectionListeners: Set<(s: ConnectionStatus, rttMs: number | null) => void> =\n new Set();\n /**\n * `pagehide` handler reference. Held so we can deregister at\n * teardown without anchoring `this` to the global listener\n * forever \u2014 important because the SDK can outlive multiple\n * sign-in / sign-out cycles in a single tab.\n */\n private _onPageHide: ((e: Event) => void) | null = null;\n\n constructor(opts: {\n cnf: { jwk: CnfJwk };\n credential: { expiresAt: number };\n transport: Transport;\n ephKeys: EphemeralKeys;\n verifierContext: VerifierContext;\n /**\n * The verified-claim map from the initial sign-in. Cached so\n * `claim-update` events can compute a real diff (and so\n * `claim_added` / `claim_updated` carry old + new values). Optional\n * for back-compat; if absent the first `claim-update` treats\n * every claim as `claim_added`, which is the safe direction.\n */\n initialClaims?: Record<string, unknown>;\n /**\n * The `SignInResult` to deliver as the payload of the\n * `signed_in` event fired via microtask. Optional \u2014 pass to\n * enable `signed_in` dispatch; omit to leave the event silent.\n */\n initialSignedInResult?: SignInResult;\n /**\n * The wallet's session X25519 public key from the initial\n * `presentation` envelope. Required to open the browser\u2192wallet\n * request channel (`session.request(...)`). Optional only for\n * back-compat with older wallets that don't yet publish it.\n */\n walletSessionPk?: string;\n /**\n * True when the sign-in presentation didn't bind [walletSessionPk]\n * (wallet older than envelope v2): inbound senders can't be checked,\n * so page-acting envelopes are ignored. Default false.\n */\n legacyChannel?: boolean;\n /**\n * The verified sign-in presentation and its holder-signed `iat`:\n * the baseline for renewal anti-replay (a renewal must carry a\n * strictly newer `iat` and must not repeat an accepted presentation).\n */\n initialPresentation?: { presentation: string; iat: number };\n /**\n * Initial `preferredLanguage` value from the wallet's first\n * envelope. The session's own `_handleMessage` only sees\n * envelopes that arrive AFTER signIn() has consumed the\n * presentation, so the language tag on the first envelope is\n * otherwise lost \u2014 leaving `session.preferredLanguage` null\n * until a later renewal envelope. Seeded here so the value\n * is available immediately when the host inspects it after\n * `signIn()` resolves.\n */\n initialPreferredLanguage?: string;\n /**\n * Initial `displayName` from the wallet's first envelope.\n * Cosmetic public-profile data; see [displayName] getter for\n * the trust model. Seeded here so the host sees the name\n * immediately after `signIn()` resolves rather than waiting for\n * the first `display-update`.\n */\n initialDisplayName?: string | null;\n /** Initial `avatar` from the wallet's first envelope (same\n * rationale as [initialDisplayName]). */\n initialAvatar?: { url: string; hash: string } | null;\n }) {\n this._cnf = opts.cnf;\n this._expiresAt = opts.credential.expiresAt;\n this._transport = opts.transport;\n this._ephKeys = opts.ephKeys;\n this._verifierContext = opts.verifierContext;\n this._claimsSnapshot = { ...(opts.initialClaims ?? {}) };\n this._walletSessionPk = opts.walletSessionPk ?? null;\n this._legacyChannel = opts.legacyChannel === true;\n if (opts.initialPresentation) {\n this._lastPresentationIat = opts.initialPresentation.iat;\n void presentationDigest(opts.initialPresentation.presentation).then((d) => this._seenPresentations.add(d));\n }\n this._preferredLanguage = opts.initialPreferredLanguage ?? null;\n this._displayName = opts.initialDisplayName ?? null;\n this._avatar = opts.initialAvatar ?? null;\n this._armExpiryTimer();\n this._installUnloadGuard();\n this._transport.onMessage((raw) => void this._handleMessage(raw));\n // Transport teardown fan-out \u2192 `signed_out`. The credential's\n // exp timer (`_armExpiryTimer`) covers credential-side TTL, but\n // the Worker's session DO has a separate, MUCH shorter TTL \u2014\n // when its alarm fires, both signaling WSes close with code\n // 4000 / reason `ttl_reached`, the data channel goes silent,\n // and without this hook the host would keep showing \"signed\n // in\" forever. The transport collapses every termination\n // (signaling close, peer-gone, DC close) onto one notification;\n // we map the reason string to the SDK's `ExpiryReason` union\n // and tear down.\n this._transport.onClose((reason) => {\n if (this._closed) return;\n const mapped = _mapTransportCloseReason(reason);\n this._teardown(mapped);\n });\n // Start the wallet\u2192browser liveness loop. The wallet runs the\n // same loop on its side; either peer's ping triggers a pong on\n // the other. Both sides independently track their own RTT view.\n this._pingTimer = setInterval(() => this._sendPing(), PING_INTERVAL_MS);\n _unrefTimer(this._pingTimer);\n\n // Fire `signed_in` via microtask so listeners attached\n // synchronously after `await signIn()` still receive it.\n // Without the microtask the event would race against the\n // caller's first `on()` registration.\n if (opts.initialSignedInResult) {\n const result = opts.initialSignedInResult;\n queueMicrotask(() => this._dispatch({ type: \"signed_in\", result }));\n }\n }\n\n // \u2500\u2500\u2500 Public getters \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n get expiresAt(): number {\n return this._expiresAt;\n }\n get cnf(): { jwk: CnfJwk } {\n return this._cnf;\n }\n /** Snapshot of the most recent verified claims (since last renew / update). */\n get claims(): Readonly<Record<string, unknown>> {\n return this._claimsSnapshot;\n }\n\n /**\n * Who is signed in: the person's Prson ID for this site (`cnf.jwk.x`,\n * the same value as `SignInResult.prsonId`). Show it \u2014 or a name your\n * backend maps it to \u2014 on the page, so the person can see it's them\n * and not someone who scanned the code first.\n */\n get prsonId(): string {\n return this._cnf.jwk.x;\n }\n\n /** The wallet's pinned X25519 session key (base64url), or null. */\n get walletSessionPk(): string | null {\n return this._walletSessionPk;\n }\n\n /** User's preferred UI language (BCP-47 tag) or null if the\n * wallet hasn't published one yet. */\n get preferredLanguage(): string | null {\n return this._preferredLanguage;\n }\n\n /** Public-profile display name from the wallet's identity record,\n * or null if the wallet hasn't published one yet (anonymous\n * identity, etc.). Cosmetic \u2014 do not gate privileged actions on\n * this value. */\n get displayName(): string | null {\n return this._displayName;\n }\n\n /** Public-profile avatar pointer, or null. Same cosmetic-only\n * trust model as [displayName]. */\n get avatar(): { url: string; hash: string } | null {\n return this._avatar;\n }\n\n /** Coarse health of the wallet \u2194 browser data channel as observed\n * via the periodic ping/pong loop. `unknown` until the first pong\n * lands; `offline` after 5 s of no pong; `unstable` when the most\n * recent RTT crossed 1 s; otherwise `stable`. */\n get connectionStatus(): ConnectionStatus {\n return this._connectionStatus;\n }\n\n /** Most recently observed RTT in milliseconds, or null until the\n * first pong lands. */\n get lastRttMs(): number | null {\n return this._lastRttMs;\n }\n\n /** Subscribe to connection-status changes. Fires on every transition\n * with the new status + the RTT that triggered it (null on the\n * `offline` transition). Returns an unsubscribe handle. */\n onConnectionStatus(\n cb: (status: ConnectionStatus, rttMs: number | null) => void,\n ): Unsubscribe {\n this._connectionListeners.add(cb);\n return () => this._connectionListeners.delete(cb);\n }\n\n // \u2500\u2500\u2500 Subscription API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Subscribe to a single event type. The callback is invoked with\n * the typed event variant (TS narrows on the `type` discriminant).\n * Returns an unsubscribe handle.\n *\n * const off = session.on(\"claim_updated\", (e) => {\n * if (e.name === \"verification_level\") refreshBadge(e.newValue);\n * });\n * // later:\n * off();\n */\n on<T extends LoginEventType>(\n type: T,\n cb: (event: Extract<LoginEvent, { type: T }>) => void,\n ): Unsubscribe {\n let set = this._listeners.get(type);\n if (!set) {\n set = new Set();\n this._listeners.set(type, set);\n }\n const wrapped = cb as unknown as (e: LoginEvent) => void;\n set.add(wrapped);\n return () => set!.delete(wrapped);\n }\n\n /** Subscribe to every event. Returns an unsubscribe handle. */\n onAny(cb: (event: LoginEvent) => void): Unsubscribe {\n this._anyListeners.add(cb);\n return () => this._anyListeners.delete(cb);\n }\n\n // \u2500\u2500\u2500 Back-compat shims \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n //\n // The original SDK exposed `onRenewed(cb)` and `onExpiry(cb)`.\n // We keep them as thin wrappers around the typed `on()` so\n // existing host pages compile without changes. New code should\n // prefer `on()` / `onAny()`.\n\n /** @deprecated Use `on(\"renewed\", e => cb(e.result))` instead. */\n onRenewed(cb: (fresh: SignInResult) => void): Unsubscribe {\n return this.on(\"renewed\", (e) => cb(e.result));\n }\n\n /** @deprecated Use `on(\"signed_out\", e => cb(e.reason))` instead. */\n onExpiry(cb: (reason: ExpiryReason) => void): Unsubscribe {\n return this.on(\"signed_out\", (e) => cb(e.reason));\n }\n\n close(): void {\n this._teardown(\"user_revoked\");\n }\n\n // \u2500\u2500\u2500 Request channel \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Send a [request] to the wallet and resolve with the wallet's\n * reply. The wallet shows a bottom drawer for the user to\n * approve / decline / pick a matching fragment or document; the\n * promise resolves when the user acts (or the [timeoutMs]\n * elapses, or the session closes).\n *\n * Common error codes:\n * * `no-active-session` \u2014 request issued before the wallet has\n * published its session pk (race against the initial\n * `presentation` envelope) or after the session closed.\n * * `declined` \u2014 user tapped Decline in the wallet drawer.\n * * `not-present` \u2014 no matching fragment / document on the\n * device AND the user declined to acquire one.\n * * `queue-full` \u2014 wallet is sitting at the 5-in-flight cap and\n * isn't accepting more requests. Try later.\n * * `rate-limited` \u2014 wallet's 1-request-per-second throttle\n * rejected this one.\n * * `timeout` \u2014 the [timeoutMs] elapsed before the wallet\n * replied. Defaults to 60 s.\n * * `session-closed` \u2014 the session shut down with this request\n * in flight.\n * * `unsupported` \u2014 the wallet predates envelope v2 (it bound no\n * session key into the sign-in), so its replies couldn't be told\n * apart from anyone else's. Nothing is sent to it.\n *\n * Wire grammar: outbound envelope shape is\n * `{ v, msg: \"request\", issuedAt, domain, requestId, kind, ...kindFields }`,\n * NaCl-boxed to the wallet's session pk. Reply is a matching\n * `{ msg: \"response\", requestId, result | error }`.\n */\n async request(req: LoginRequest, opts?: RequestOptions): Promise<LoginResponse> {\n return this._sendRequest(req, opts);\n }\n\n /**\n * Streaming variant of [request] for `kind: \"mouse\"`. Identical\n * to `request()` except [onFrame] is invoked for every\n * `mouse-update` envelope the wallet emits against the request's\n * UUID until the terminating `response` arrives. The returned\n * promise resolves with the final response (i.e. when the user\n * closes the wallet drawer). Used by [`bindMouse`].\n *\n * Separated from `request()` because the subscriber MUST be\n * attached against the requestId BEFORE the envelope is sent \u2014\n * otherwise the first `mouse-update` frame can race ahead of the\n * subscription. `request()` doesn't expose its requestId, so we\n * provide this dedicated entry point rather than leak the id.\n */\n async requestMouse(\n req: Extract<LoginRequest, { kind: \"mouse\" }>,\n onFrame: (mouse: NonNullable<DecryptedEnvelope[\"mouse\"]>) => void,\n opts?: RequestOptions,\n ): Promise<LoginResponse> {\n return this._sendRequest(req, opts, onFrame);\n }\n\n /**\n * Push the currently-focused input's metadata + value to the\n * wallet so the user can edit it on the phone. Pass `null` to\n * clear the wallet's focus mirror (blur, page change, etc.).\n *\n * Used by [`enableRemoteNavigation`]; not part of the documented\n * public API but exposed so the helper lives in a separate module\n * without reaching into private fields. NaCl-boxed to the wallet's\n * session pk on the way out.\n *\n * @internal\n */\n async _sendFocus(\n focus:\n | {\n name: string;\n label?: string;\n inputType?: string;\n value?: string;\n placeholder?: string;\n minLength?: number;\n maxLength?: number;\n min?: number;\n max?: number;\n pattern?: string;\n required?: boolean;\n options?: { value: string; label?: string }[];\n /** Navigation-row visibility hints. Computed by\n * `enableRemoteNavigation`'s `computeNavMeta` from the\n * current tabbable pool and the focused element's\n * surrounding form. The wallet renders only the buttons\n * that match. See `bind.ts:computeNavMeta` + the wallet's\n * `_navigationRow`. */\n hasPrev?: boolean;\n hasNext?: boolean;\n isLastInForm?: boolean;\n isButton?: boolean;\n /** File-input attributes. Present only when the focused\n * element is `<input type=\"file\">`; drives the wallet's\n * picker UI (camera vs gallery vs files filtered by\n * MIME). `accept` is the raw `accept` attribute string\n * (e.g. `\"image/*,application/pdf\"`); the wallet\n * normalises it. `multiple` enables multi-select on the\n * picker. `capture` (`\"user\"` / `\"environment\"`) hints\n * which camera the host expects when the user opens the\n * camera mode. */\n accept?: string;\n multiple?: boolean;\n capture?: string;\n }\n | null,\n ): Promise<void> {\n if (this._closed) return;\n if (!this._walletSessionPk) return;\n // A legacy wallet's key isn't bound to the sign-in, and its edits\n // (`value`) are ignored anyway: don't send it the page's fields.\n if (this._legacyChannel) return;\n // Focus updates drive the wallet drawer's mirrored input \u2014 the\n // user can't edit a value the wallet never received, so we\n // ack-track these. The promise is awaited only by tests; the\n // common path (remote-nav helper firing on DOM focus events) is\n // fire-and-forget.\n await this._sendWithAck({\n msg: \"focus\",\n focus,\n });\n }\n\n /**\n * Install a `pagehide` listener that fires a synchronous\n * `browser-revoke` envelope at the wallet right before the tab\n * closes / refreshes / navigates away. Without this the wallet\n * has to wait for the slower transport-collapse pathway\n * (`peer-gone` over the signaling WS + ICE failure on the data\n * channel) to learn the browser is gone \u2014 long enough for the\n * connection-status dot to oscillate and any in-flight ack\n * promises to time out.\n *\n * `pagehide` is preferred over `beforeunload` because:\n * * it fires for bfcache evictions (back/forward navigation\n * on iOS Safari), tab closes, AND refreshes\n * * `beforeunload` is increasingly restricted by browsers\n * for non-blocking-prompt use\n *\n * The envelope itself rides through the same NaCl box as every\n * other browser\u2192wallet message. We can't await the ack \u2014 the\n * page is being torn down \u2014 so this is a true fire-and-forget;\n * the wallet's [LoginSession.inbound] handler treats receipt\n * as the trigger to close.\n */\n private _installUnloadGuard(): void {\n if (typeof window === \"undefined\") return;\n this._onPageHide = (_e: Event) => {\n if (this._closed || !this._walletSessionPk) return;\n const body = JSON.stringify({\n v: \"prson_vp_v1\",\n msg: \"browser-revoke\",\n issuedAt: Math.floor(Date.now() / 1000),\n domain: this._verifierContext.expectedAudience.replace(/^https?:\\/\\//, \"\"),\n reason: \"page_unload\",\n });\n try {\n this._transport.send(boxToWallet(this._walletSessionPk, body, this._ephKeys));\n } catch {\n /* swallow \u2014 the channel is on its way out anyway */\n }\n };\n window.addEventListener(\"pagehide\", this._onPageHide);\n }\n\n /**\n * Browser\u2192wallet pause-state notification. The wallet's mouse\n * controller dims its surface + shows \"Remote control paused\"\n * while the page is in the background. Fire-and-forget over\n * NaCl-box to the wallet's session pk; loss is acceptable\n * (we re-fire on every focus / blur).\n *\n * @internal\n */\n async _sendControlStatus(paused: boolean): Promise<void> {\n if (this._closed) return;\n if (!this._walletSessionPk) return;\n const payload = JSON.stringify({\n v: \"prson_vp_v1\",\n msg: \"control-status\",\n issuedAt: Math.floor(Date.now() / 1000),\n domain: this._verifierContext.expectedAudience.replace(/^https?:\\/\\//, \"\"),\n paused,\n });\n try {\n this._transport.send(boxToWallet(this._walletSessionPk, payload, this._ephKeys));\n } catch {\n /* swallow \u2014 channel down */\n }\n }\n\n /**\n * Install the ambient `mouse-update` handler. Mirrors\n * [`_setRemoteNavListener`] \u2014 only one ambient subscriber at a\n * time (last call wins). Used by [`bindMouse`] when the\n * session was pre-granted mouse control at sign-in\n * ([SignInOptions.mouseControl]).\n *\n * @internal\n */\n _setAmbientMouseHandler(\n cb: ((mouse: NonNullable<DecryptedEnvelope[\"mouse\"]>) => void) | null,\n ): Unsubscribe {\n this._ambientMouseHandler = cb;\n return () => {\n if (this._ambientMouseHandler === cb) this._ambientMouseHandler = null;\n };\n }\n\n /**\n * Install the file-envelope handler. Mirrors\n * [`_setAmbientMouseHandler`] \u2014 only one handler at a time;\n * [`enableRemoteNavigation`] owns it during its lifetime and\n * tears it down on disposal so the next mount can install a\n * fresh one. The handler receives `file-begin` / `file-chunk` /\n * `file-end` envelopes in arrival order; assembly + DOM\n * dispatch lives in [`bind.ts`].\n *\n * @internal\n */\n _setFileEnvelopeHandler(\n cb: ((envelope: DecryptedEnvelope) => void) | null,\n ): Unsubscribe {\n this._fileEnvelopeHandler = cb;\n return () => {\n if (this._fileEnvelopeHandler === cb) this._fileEnvelopeHandler = null;\n };\n }\n\n /**\n * Install the remote-navigation listener. Replaces any prior\n * listener \u2014 only one is active at a time. Returns an unsubscribe\n * handle. Used by [`enableRemoteNavigation`].\n *\n * @internal\n */\n _setRemoteNavListener(\n cb:\n | ((\n envelope:\n | { msg: \"nav\"; action: \"prev\" | \"next\" | \"submit\" }\n | { msg: \"value\"; value: string }\n | { msg: \"logout\" },\n ) => void)\n | null,\n ): Unsubscribe {\n this._remoteNavListener = cb;\n return () => {\n if (this._remoteNavListener === cb) this._remoteNavListener = null;\n };\n }\n\n private async _sendRequest(\n req: LoginRequest,\n opts?: RequestOptions,\n onMouseFrame?: (mouse: NonNullable<DecryptedEnvelope[\"mouse\"]>) => void,\n ): Promise<LoginResponse> {\n if (this._closed) return { ok: false, error: \"session-closed\" };\n // A legacy session can't check who sent a `response` (no session\n // key bound in the presentation), so anyone able to box to us could\n // answer. Refuse the request instead of trusting the reply.\n if (this._legacyChannel) return { ok: false, error: \"unsupported\" };\n const recipientPk = this._walletSessionPk;\n if (!recipientPk) return { ok: false, error: \"no-active-session\" };\n\n const timeoutMs = opts?.timeoutMs ?? 60_000;\n const { requestId, promise } = this._requestController.enqueue(timeoutMs);\n\n // Attach the streaming subscriber BEFORE sending so the first\n // mouse-update frame can never race ahead of the subscription.\n if (onMouseFrame) this._mouseSubscribers.set(requestId, onMouseFrame);\n\n const envelope: Record<string, unknown> = {\n v: \"prson_vp_v1\",\n msg: \"request\",\n issuedAt: Math.floor(Date.now() / 1000),\n domain: this._verifierContext.expectedAudience.replace(/^https?:\\/\\//, \"\"),\n requestId,\n kind: req.kind,\n };\n // Per-kind body \u2014 flat keys for simplicity, matches the wallet's\n // existing wire-decoder pattern.\n switch (req.kind) {\n case \"claim-value\":\n envelope.name = req.name;\n if (req.reason) envelope.reason = req.reason;\n break;\n case \"fragment-check\":\n envelope.fragmentName = req.fragmentName;\n // `format` selects the wire shape the wallet asks the notary\n // for (native / vc+jwt / vc+sd-jwt). Omitted means native, so\n // we only put it on the envelope when the host opted in \u2014 the\n // wallet treats an absent field as legacy behaviour.\n if (req.format) envelope.format = req.format;\n if (req.reason) envelope.reason = req.reason;\n break;\n case \"document-presence\":\n if (req.type) envelope.type = req.type;\n if (req.country) envelope.country = req.country;\n if (req.reason) envelope.reason = req.reason;\n break;\n case \"document-sign\":\n // Bytes get base64'd in the envelope; large docs should use\n // `uploadUrl` to keep the WebRTC message size down.\n if (\"bytes\" in req.document) {\n envelope.document = {\n bytes: u8ToB64(req.document.bytes),\n };\n } else {\n envelope.document = req.document;\n }\n if (req.visibleCue) envelope.visibleCue = req.visibleCue;\n if (req.reason) envelope.reason = req.reason;\n break;\n case \"input\":\n envelope.inputType = req.inputType;\n envelope.label = req.label;\n if (req.placeholder !== undefined) envelope.placeholder = req.placeholder;\n // A password's current value never goes to the phone.\n if (req.defaultValue !== undefined && req.inputType !== \"password\") envelope.defaultValue = req.defaultValue;\n if (req.minLength !== undefined) envelope.minLength = req.minLength;\n if (req.maxLength !== undefined) envelope.maxLength = req.maxLength;\n if (req.min !== undefined) envelope.min = req.min;\n if (req.max !== undefined) envelope.max = req.max;\n if (req.pattern !== undefined) envelope.pattern = req.pattern;\n if (req.required !== undefined) envelope.required = req.required;\n if (req.options !== undefined) envelope.options = req.options;\n if (req.reason) envelope.reason = req.reason;\n break;\n case \"input-form\":\n envelope.fields = req.fields.map((f) =>\n f.inputType === \"password\" && f.defaultValue !== undefined ? { ...f, defaultValue: undefined } : f,\n );\n if (req.submitLabel !== undefined) envelope.submitLabel = req.submitLabel;\n if (req.reason) envelope.reason = req.reason;\n break;\n case \"mouse\":\n envelope.mode = req.mode;\n if (req.reason) envelope.reason = req.reason;\n break;\n }\n\n try {\n const boxed = boxToWallet(recipientPk, JSON.stringify(envelope), this._ephKeys);\n this._transport.send(boxed);\n } catch {\n // Network down, channel closed, encoding bug \u2014 surface as\n // session-closed; the timeout would also fire eventually.\n if (onMouseFrame) this._mouseSubscribers.delete(requestId);\n return { ok: false, error: \"session-closed\" };\n }\n return promise;\n }\n\n // \u2500\u2500\u2500 internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Fire a single event to per-type listeners + onAny subscribers.\n * Listener errors are swallowed so one buggy host listener can't\n * break the rest of the dispatch (or close the session).\n */\n private _dispatch(event: LoginEvent): void {\n const set = this._listeners.get(event.type);\n if (set) {\n for (const cb of set) {\n try {\n cb(event);\n } catch {\n /* swallow \u2014 host bug shouldn't bring down the session */\n }\n }\n }\n for (const cb of this._anyListeners) {\n try {\n cb(event);\n } catch {\n /* swallow */\n }\n }\n }\n\n private _armExpiryTimer() {\n if (this._expiryTimer) clearTimeout(this._expiryTimer);\n const delta = this._expiresAt - Date.now();\n // 60-second skew/sanity budget on BOTH sides:\n //\n // * If `expiresAt === 0`: the credential's JWS had no numeric\n // `exp`. Skip the timer.\n // * If `delta` is in `[-60_000, +60_000]`: the credential\n // \"expires\" within a one-minute window of \"now\". Almost\n // always one of: clock skew between server and browser,\n // network latency between issuance and verify, or a\n // server-side TTL bug that issued an essentially-zero-TTL\n // credential. Tearing down on this signal causes a visible\n // \"signed_in immediately followed by signed_out\" UX bug;\n // skip the timer and let the wallet (or host) close.\n // * Otherwise: legitimate future expiry \u2014 arm the timer.\n // * Otherwise (genuinely past, >60s ago): real expiry,\n // teardown immediately.\n const skewBudgetMs = 60_000;\n if (this._expiresAt <= 0 || Math.abs(delta) < skewBudgetMs) {\n // eslint-disable-next-line no-console\n console.warn(\n `[@prson/login-sdk] credential expiresAt ${\n this._expiresAt <= 0\n ? \"missing/zero\"\n : delta < 0\n ? `${(-delta / 1000).toFixed(1)}s in the past`\n : `only ${(delta / 1000).toFixed(1)}s in the future`\n } \u2014 leaving session open without a TTL timer.` +\n \" Host should set its own deadline.\",\n );\n return;\n }\n if (delta <= 0) {\n this._teardown(\"ttl_reached\");\n return;\n }\n // `setTimeout` clamps delays > 2^31-1 ms (~24.8 days) to a 32-bit\n // int and effectively fires immediately. A verified-human VC has\n // a 90-day TTL \u2014 delta is ~7.8 billion ms \u2014 so a naive\n // `setTimeout(..., delta)` would trip the teardown on the very\n // next tick. Re-arm in chunks \u2264 MAX_TIMEOUT and re-evaluate.\n const MAX_TIMEOUT = 2_147_483_000; // a hair under int32 max\n const chunk = delta > MAX_TIMEOUT ? MAX_TIMEOUT : delta;\n this._expiryTimer = setTimeout(() => {\n if (this._closed) return;\n // Re-check against the current clock \u2014 if we still haven't\n // reached `_expiresAt`, re-arm. Otherwise teardown.\n if (Date.now() >= this._expiresAt) {\n this._teardown(\"ttl_reached\");\n } else {\n this._armExpiryTimer();\n }\n }, chunk);\n _unrefTimer(this._expiryTimer);\n }\n\n private async _handleMessage(raw: string) {\n if (this._closed) return;\n let envelope: DecryptedEnvelope;\n try {\n // Only the pinned wallet key may talk to us. A legacy session (no\n // key bound in the presentation) can't check the sender, so it\n // accepts any box and ignores page-acting messages instead.\n envelope = await decryptEnvelope(\n raw,\n this._ephKeys,\n this._legacyChannel ? undefined : (this._walletSessionPk ?? undefined),\n );\n } catch {\n // Garbage on the wire, or a box from a key other than the pinned\n // wallet key (an injected envelope) \u2014 ignore it.\n return;\n }\n\n // \u2500\u2500 Transport-layer protocol: dedupe + auto-ack + ping/pong \u2500\u2500\n if (typeof envelope.id === \"string\") {\n if (this._seenIds.has(envelope.id)) {\n // Duplicate \u2014 our prior ack likely got lost. Re-ack so the\n // wallet stops retransmitting, then drop locally.\n void this._sendAckFor(envelope);\n return;\n }\n this._markSeen(envelope.id);\n void this._sendAckFor(envelope);\n }\n\n if (envelope.msg === \"ack\") {\n this._handleAck(envelope.ackOf);\n return;\n }\n if (envelope.msg === \"ping\") {\n void this._sendPong(envelope);\n return;\n }\n if (envelope.msg === \"pong\") {\n this._handlePong(envelope);\n return;\n }\n\n await this._dispatchDecryptedForTest(envelope);\n }\n\n // \u2500\u2500\u2500 Transport-layer protocol helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private _markSeen(id: string): void {\n this._seenIds.add(id);\n this._seenIdsOrder.push(id);\n if (this._seenIdsOrder.length > SEEN_IDS_CAPACITY) {\n const evict = this._seenIdsOrder.shift();\n if (evict) this._seenIds.delete(evict);\n }\n }\n\n /** Auto-ack any inbound envelope that carries an `id`, except\n * protocol primitives. `ping` is implicitly acked by `pong`;\n * `pong` and `ack` would loop. */\n private async _sendAckFor(envelope: DecryptedEnvelope): Promise<void> {\n if (typeof envelope.id !== \"string\") return;\n if (envelope.msg === \"ack\" || envelope.msg === \"ping\" || envelope.msg === \"pong\") {\n return;\n }\n if (!this._walletSessionPk) return;\n const body = JSON.stringify({\n v: \"prson_vp_v1\",\n msg: \"ack\",\n ackOf: envelope.id,\n issuedAt: Math.floor(Date.now() / 1000),\n domain: this._verifierContext.expectedAudience.replace(/^https?:\\/\\//, \"\"),\n });\n try {\n this._transport.send(boxToWallet(this._walletSessionPk, body, this._ephKeys));\n } catch {\n /* channel down \u2014 wallet will time out its retry budget */\n }\n }\n\n private _handleAck(ackOf: string | undefined): void {\n if (!ackOf) return;\n const pending = this._pendingAcks.get(ackOf);\n if (!pending) return;\n if (pending.timer) clearTimeout(pending.timer);\n this._pendingAcks.delete(ackOf);\n }\n\n private async _sendPing(): Promise<void> {\n if (this._closed) return;\n if (!this._walletSessionPk) return;\n const id = uuidv4();\n const ts = Date.now();\n this._pingSendTimes.set(id, ts);\n const body = JSON.stringify({\n v: \"prson_vp_v1\",\n msg: \"ping\",\n id,\n ts,\n domain: this._verifierContext.expectedAudience.replace(/^https?:\\/\\//, \"\"),\n });\n try {\n this._transport.send(boxToWallet(this._walletSessionPk, body, this._ephKeys));\n } catch {\n /* swallow */\n }\n this._armOfflineTimer();\n }\n\n private async _sendPong(ping: DecryptedEnvelope): Promise<void> {\n if (!this._walletSessionPk) return;\n if (typeof ping.id !== \"string\") return;\n const body = JSON.stringify({\n v: \"prson_vp_v1\",\n msg: \"pong\",\n ackOf: ping.id,\n ts: ping.ts,\n recvTs: Date.now(),\n domain: this._verifierContext.expectedAudience.replace(/^https?:\\/\\//, \"\"),\n });\n try {\n this._transport.send(boxToWallet(this._walletSessionPk, body, this._ephKeys));\n } catch {\n /* swallow */\n }\n }\n\n private _handlePong(envelope: DecryptedEnvelope): void {\n if (typeof envelope.ackOf !== \"string\") return;\n const sent = this._pingSendTimes.get(envelope.ackOf);\n if (sent === undefined) return;\n this._pingSendTimes.delete(envelope.ackOf);\n const rtt = Date.now() - sent;\n this._lastRttMs = rtt;\n if (this._offlineTimer) {\n clearTimeout(this._offlineTimer);\n this._offlineTimer = null;\n }\n this._setConnectionStatus(\n rtt > CONNECTION_UNSTABLE_THRESHOLD_MS ? \"unstable\" : \"stable\",\n rtt,\n );\n }\n\n private _armOfflineTimer(): void {\n if (this._offlineTimer) clearTimeout(this._offlineTimer);\n this._offlineTimer = setTimeout(() => {\n if (this._closed) return;\n this._setConnectionStatus(\"offline\", null);\n }, CONNECTION_OFFLINE_AFTER_MS);\n _unrefTimer(this._offlineTimer);\n }\n\n private _setConnectionStatus(s: ConnectionStatus, rttMs: number | null): void {\n if (this._connectionStatus === s && this._lastRttMs === rttMs) return;\n this._connectionStatus = s;\n if (rttMs !== null) this._lastRttMs = rttMs;\n for (const cb of this._connectionListeners) {\n try {\n cb(s, rttMs);\n } catch {\n /* swallow \u2014 host bug shouldn't kill the loop */\n }\n }\n }\n\n /** Send a JSON envelope with ack tracking + retry. Stamps a fresh\n * `id` onto [body] and retransmits every [ACK_RETRY_DELAY_MS]\n * until the matching ack lands or [ACK_MAX_ATTEMPTS] is reached.\n * Resolves with `true` on ack, `false` on exhaustion. */\n private async _sendWithAck(body: Record<string, unknown>): Promise<boolean> {\n if (this._closed) return false;\n if (!this._walletSessionPk) return false;\n const id = uuidv4();\n body.id = id;\n body.v = body.v ?? \"prson_vp_v1\";\n body.issuedAt = body.issuedAt ?? Math.floor(Date.now() / 1000);\n body.domain =\n body.domain ?? this._verifierContext.expectedAudience.replace(/^https?:\\/\\//, \"\");\n const encoded = JSON.stringify(body);\n const pending = { encoded, attempts: 0, timer: null as ReturnType<typeof setTimeout> | null };\n this._pendingAcks.set(id, pending);\n return new Promise<boolean>((resolve) => {\n const attempt = () => {\n if (this._closed) {\n this._pendingAcks.delete(id);\n resolve(false);\n return;\n }\n pending.attempts += 1;\n try {\n this._transport.send(boxToWallet(this._walletSessionPk!, encoded, this._ephKeys));\n } catch {\n /* channel down \u2014 keep retrying; offline timer will fire */\n }\n pending.timer = setTimeout(() => {\n if (!this._pendingAcks.has(id)) {\n // Ack already arrived between attempts; the success path\n // cleared the map entry.\n resolve(true);\n return;\n }\n if (pending.attempts >= ACK_MAX_ATTEMPTS) {\n this._pendingAcks.delete(id);\n resolve(false);\n return;\n }\n attempt();\n }, ACK_RETRY_DELAY_MS);\n _unrefTimer(pending.timer);\n };\n attempt();\n });\n }\n\n /**\n * Pure dispatch entry-point \u2014 takes an already-decrypted envelope\n * and routes it through the same per-message handlers\n * `_handleMessage` does after decryption. Public-but-prefixed so\n * unit tests can exercise the dispatch contract without\n * constructing real NaCl-boxed ciphertext.\n *\n * NOT part of the documented public API; treat as @internal.\n */\n async _dispatchDecryptedForTest(envelope: DecryptedEnvelope): Promise<void> {\n if (this._closed) return;\n // `walletSessionPk` on an envelope is NOT trusted: the key is pinned\n // from the signed presentation and only a verified renewal can\n // rotate it (see _handleRenewal).\n // Same treatment for the user's preferred language \u2014 the wallet\n // re-stamps this on every envelope so a mid-session locale\n // change propagates without an explicit event.\n if (typeof envelope.preferredLanguage === \"string\") {\n this._preferredLanguage = envelope.preferredLanguage;\n }\n\n switch (envelope.msg) {\n case \"revoke\":\n this._teardown(\"wallet_signed_out\");\n return;\n case \"presentation\":\n case \"renewal\":\n await this._handleRenewal(envelope);\n return;\n case \"claim-update\":\n await this._handleClaimUpdate(envelope);\n return;\n case \"display-update\":\n this._handleDisplayUpdate(envelope);\n return;\n case \"credential-revoked\":\n this._handleCredentialRevoked(envelope);\n return;\n case \"response\":\n // Legacy sessions never send requests (see _sendRequest); a\n // `response` there is unauthenticated, so it resolves nothing.\n if (this._legacyChannel) return;\n // Wallet replied to an outbound `request`. Match by UUID\n // and resolve the matching promise. Late replies (after\n // timeout) silently no-op \u2014 the controller already\n // delivered the timeout error.\n this._requestController.resolve(envelope);\n // If the request was a streaming `mouse` request, the final\n // `response` also closes the stream \u2014 drop the subscriber so\n // the controller can be reused.\n if (envelope.requestId) this._mouseSubscribers.delete(envelope.requestId);\n return;\n case \"mouse-update\":\n // An unauthenticated sender must not drive the page.\n if (this._legacyChannel) return;\n // Wallet is streaming pointer events. Two routing paths:\n //\n // 1. **Per-request** \u2014 there's a pending `requestMouse`\n // subscriber keyed by this `requestId`. Used when the\n // host explicitly opened a `kind: \"mouse\"` request.\n //\n // 2. **Ambient** \u2014 no such subscriber exists. Used by the\n // pre-grant flow (`SignInOptions.mouseControl: true`)\n // where the wallet's banner drawer starts a stream\n // with a wallet-minted id the host never saw. Falls\n // through to `_ambientMouseHandler`, which [`bindMouse`]\n // installs so its on-page cursor still moves.\n if (envelope.mouse) {\n const perRequest = envelope.requestId\n ? this._mouseSubscribers.get(envelope.requestId)\n : undefined;\n const target = perRequest ?? this._ambientMouseHandler;\n if (target) {\n try {\n target(envelope.mouse);\n } catch {\n /* swallow \u2014 host bug shouldn't kill the stream */\n }\n }\n }\n return;\n case \"nav\":\n case \"logout\":\n if (envelope.msg === \"nav\" && this._legacyChannel) return;\n // Remote-navigation commands from the wallet's persistent\n // banner. Without an installed listener (i.e. the host\n // didn't call `enableRemoteNavigation`), `nav` is silently\n // dropped and `logout` falls through to the default teardown\n // below \u2014 the user tapping logout MUST sign the session out\n // even if the host never wired the optional helper.\n if (this._remoteNavListener) {\n try {\n if (envelope.msg === \"nav\" && envelope.action) {\n this._remoteNavListener({ msg: \"nav\", action: envelope.action });\n return;\n }\n if (envelope.msg === \"logout\") {\n this._remoteNavListener({ msg: \"logout\" });\n // Logout also tears the session down \u2014 the helper may\n // have already done it, but tearing again is a no-op.\n this._teardown(\"user_revoked\");\n return;\n }\n } catch {\n /* swallow */\n }\n }\n if (envelope.msg === \"logout\") this._teardown(\"user_revoked\");\n return;\n case \"value\":\n if (this._legacyChannel) return;\n // Wallet edited the value of the focused field. The remote-\n // nav helper is the only consumer; without it the edit is\n // silently dropped (the host page never asked for remote\n // input control). `value: null` is \"no change\" \u2014 we ignore.\n if (\n this._remoteNavListener &&\n typeof envelope.value === \"string\"\n ) {\n try {\n this._remoteNavListener({ msg: \"value\", value: envelope.value });\n } catch {\n /* swallow */\n }\n }\n return;\n case \"file-begin\":\n case \"file-chunk\":\n case \"file-end\":\n if (this._legacyChannel) return;\n // File-transfer envelopes flow through the remote-nav\n // helper's file receiver \u2014 bytes are reassembled into a\n // `File` object that the focused `<input type=\"file\">`\n // accepts. Without the helper mounted these envelopes are\n // silently dropped (the host page never asked for remote\n // file input).\n if (this._fileEnvelopeHandler) {\n try {\n this._fileEnvelopeHandler(envelope);\n } catch {\n /* swallow \u2014 one buggy receiver shouldn't kill the\n * channel for everyone */\n }\n }\n return;\n default:\n // Forward-compatible: unknown msg types are ignored, not\n // errors. A future wallet build can ship new events that\n // older SDK builds simply don't surface.\n return;\n }\n }\n\n private async _handleRenewal(envelope: DecryptedEnvelope) {\n if (!envelope.presentation) return;\n const verified = await this._verifyFresh(envelope.presentation);\n if (!verified) return;\n // Key rotation: only a verified renewal presentation can move the\n // pinned wallet key, and only to the key it signs (`prson_wsk`).\n // The next envelope must then come from the new key.\n const rotated = verified.binding.walletSessionPk;\n if (envelope.msg === \"renewal\" && rotated && !this._legacyChannel) {\n this._walletSessionPk = rotated;\n }\n this._expiresAt = verified.credential.expiresAt;\n this._claimsSnapshot = { ...verified.claims };\n this._armExpiryTimer();\n const fresh: SignInResult = {\n sdJwtVc: envelope.presentation,\n // The wallet picks a renewal's nonce, so a backend can't have issued it.\n nonce: verified.binding.nonce,\n prsonId: verified.cnf.jwk.x,\n claims: verified.claims,\n cnf: verified.cnf,\n credential: verified.credential,\n session: this,\n };\n this._dispatch({ type: \"renewed\", result: fresh });\n }\n\n /**\n * Verify a renewal / claim-update presentation and enforce in-session\n * anti-replay: same holder key, a holder-signed `iat` strictly newer\n * than the last accepted presentation, and never a presentation this\n * session already accepted. Returns null (drop it) otherwise.\n */\n private async _verifyFresh(presentation: string) {\n const verifierOpts: VerifyOptions = {\n ...this._verifierContext,\n // The wallet signs the sign-in nonce again, or one of its own; the\n // freshness checks below are what stop a replay either way.\n expectedNonce: extractKbNonce(presentation) ?? this._verifierContext.expectedNonceFactory(),\n };\n const digest = await presentationDigest(presentation);\n if (this._seenPresentations.has(digest)) return null;\n const verified = await verifyPresentation(presentation, verifierOpts);\n if (!verified.ok) return null;\n if (verified.cnf.jwk.x !== this._cnf.jwk.x) return null; // wallet swapped under us; ignore\n if (verified.binding.iat <= this._lastPresentationIat) return null;\n if (this._closed || this._seenPresentations.has(digest)) return null;\n this._seenPresentations.add(digest);\n this._lastPresentationIat = verified.binding.iat;\n return verified;\n }\n\n /**\n * Verify the embedded presentation, then diff its claims against\n * the cached snapshot and emit name-only per-claim events. The\n * actual claim values land in `this._claimsSnapshot` (accessible\n * via `session.claims`) but **never** in the event payloads \u2014\n * see the privacy note on the [LoginEvent] type.\n *\n * Re-verifies against the same audience + accepted-VCT set as the\n * initial sign-in. A `claim-update` whose presentation fails\n * verification is dropped silently \u2014 fail-closed. Same for a\n * cnf-mismatch (the wallet swapped per-domain key under us).\n *\n * The wire-level `envelope.delta` is intentionally ignored \u2014 we\n * recompute the diff from the verified SD-JWT so a malicious\n * wallet can't lie about which claim changed. The wallet should\n * not include values in `envelope.delta` at all (the wire\n * grammar in `crypto.ts` documents this as name-only); we'd\n * ignore them even if it did.\n */\n private async _handleClaimUpdate(envelope: DecryptedEnvelope) {\n if (!envelope.presentation) return;\n const verified = await this._verifyFresh(envelope.presentation);\n if (!verified) return;\n\n const oldClaims = this._claimsSnapshot;\n const newClaims = verified.claims;\n this._claimsSnapshot = { ...newClaims };\n\n // Added + updated \u2014 emit name + canonical hash of the new\n // value (NOT the raw value). The host reads the actual value\n // via `session.claims[name]` when needed; the hash lets\n // callers do an `==`-style check against a precomputed digest\n // (\"did verification_level become 5?\") without ever letting\n // the raw value cross the event surface.\n for (const [name, newValue] of Object.entries(newClaims)) {\n if (!(name in oldClaims)) {\n this._dispatch({\n type: \"claim_added\",\n name,\n newHash: await canonicalSha256Hex(newValue),\n });\n } else if (!_deepEqual(oldClaims[name], newValue)) {\n this._dispatch({\n type: \"claim_updated\",\n name,\n newHash: await canonicalSha256Hex(newValue),\n });\n }\n }\n // Removed\n for (const name of Object.keys(oldClaims)) {\n if (!(name in newClaims)) {\n this._dispatch({ type: \"claim_removed\", name });\n }\n }\n }\n\n /**\n * Display-only update. Fires `display_name_changed` and/or\n * `avatar_changed` based on which fields the envelope carries.\n * NOT cryptographically verified \u2014 partner sites should treat\n * the payload as advisory (refresh the cosmetic UI) and not\n * grant any privileged access on the basis of these values.\n */\n private _handleDisplayUpdate(envelope: DecryptedEnvelope) {\n if (envelope.displayName !== undefined) {\n // Mirror onto the session getter so a host that reads\n // `session.displayName` lazily after the update event sees\n // the new value.\n this._displayName = envelope.displayName;\n this._dispatch({\n type: \"display_name_changed\",\n displayName: envelope.displayName,\n });\n }\n if (envelope.avatar !== undefined) {\n this._avatar = envelope.avatar;\n this._dispatch({ type: \"avatar_changed\", avatar: envelope.avatar });\n }\n }\n\n /**\n * Credential-revoked. Fires `credential_revoked` with the\n * wallet-supplied reason, then tears the session down with\n * `signed_out / reason=\"credential_revoked\"`. Both events land\n * before the transport closes.\n */\n private _handleCredentialRevoked(envelope: DecryptedEnvelope) {\n const reason: CredentialRevokedReason = envelope.reason ?? \"user_revoked\";\n this._dispatch({ type: \"credential_revoked\", reason });\n this._teardown(\"credential_revoked\");\n }\n\n private _teardown(reason: ExpiryReason) {\n if (this._closed) return;\n this._closed = true;\n if (this._expiryTimer) clearTimeout(this._expiryTimer);\n if (this._pingTimer) clearInterval(this._pingTimer);\n if (this._offlineTimer) clearTimeout(this._offlineTimer);\n if (this._onPageHide && typeof window !== \"undefined\") {\n window.removeEventListener(\"pagehide\", this._onPageHide);\n this._onPageHide = null;\n }\n for (const p of this._pendingAcks.values()) {\n if (p.timer) clearTimeout(p.timer);\n }\n this._pendingAcks.clear();\n this._pingSendTimes.clear();\n try {\n this._transport.close();\n } catch {\n /* */\n }\n // Reject every in-flight request so callers awaiting\n // `session.request(...)` don't hang past the teardown.\n this._requestController.closeAll(\"session-closed\");\n // Drop any open mouse-update subscribers \u2014 the wallet won't be\n // sending more frames, and `bindMouse` will clean up its\n // DOM-side state via the `signed_out` event.\n this._mouseSubscribers.clear();\n this._dispatch({ type: \"signed_out\", reason });\n // Clear listener sets after dispatch so a host that calls\n // `session.on(...)` after teardown doesn't accumulate forever.\n this._listeners.clear();\n this._anyListeners.clear();\n this._connectionListeners.clear();\n }\n}\n\ntype VerifierContext = Omit<VerifyOptions, \"expectedNonce\"> & {\n expectedNonceFactory: () => string;\n};\n\n/**\n * Best-effort nonce extraction from a KB-JWT. Used at renewal /\n * update time so we accept the wallet's fresh nonce without forcing\n * a coordination round-trip. The verifier still checks aud +\n * sd_hash + Ed25519 signature \u2014 nonce skew only relaxes anti-replay\n * across the session.\n */\nfunction extractKbNonce(presentation: string): string | undefined {\n // SD-JWT: the KB-JWT is the last `~` part. Anonymous credential: one\n // plain JWS, whose payload carries the nonce itself.\n const parts = presentation.split(\"~\");\n const last = parts[parts.length - 1];\n if (!last || !last.includes(\".\")) return undefined;\n const [, kbP] = last.split(\".\");\n if (!kbP) return undefined;\n try {\n const pad = (4 - (kbP.length % 4)) % 4;\n const std = (kbP + \"=\".repeat(pad)).replace(/-/g, \"+\").replace(/_/g, \"/\");\n const decoded = JSON.parse(atob(std)) as { nonce?: string };\n return decoded.nonce;\n } catch {\n return undefined;\n }\n}\n\n/** SHA-256 (hex) of a presentation string \u2014 the replay-set key. */\nasync function presentationDigest(presentation: string): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(presentation));\n const view = new Uint8Array(digest);\n let out = \"\";\n for (let i = 0; i < view.length; i++) out += view[i]!.toString(16).padStart(2, \"0\");\n return out;\n}\n\n/**\n * `Uint8Array` \u2192 standard base64 (with `=` padding) for inclusion\n * inside a JSON envelope. Used by the request channel's\n * `document-sign` payload when the document arrives as raw bytes.\n */\nfunction u8ToB64(bytes: Uint8Array): string {\n let s = \"\";\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]!);\n return btoa(s);\n}\n\n/**\n * Canonical-JSON encoder: stable key ordering at every nesting\n * depth, no whitespace, arrays preserve insertion order. Used as\n * the input to the SHA-256 that becomes `claim_added.newHash` /\n * `claim_updated.newHash`. Matches the wallet's\n * `canonicalStringify` byte-for-byte, so both sides hash to the\n * same digest \u2014 the host can precompute a known-value digest and\n * compare.\n */\nfunction canonicalJson(value: unknown): string {\n if (value === undefined) return \"null\";\n if (value === null) return \"null\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return \"[\" + value.map(canonicalJson).join(\",\") + \"]\";\n }\n if (typeof value === \"object\") {\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n return (\n \"{\" +\n keys\n .map((k) => JSON.stringify(k) + \":\" + canonicalJson(obj[k]))\n .join(\",\") +\n \"}\"\n );\n }\n return JSON.stringify(String(value));\n}\n\n/**\n * SHA-256 over `canonicalJson(value)` returned as 64-char lowercase\n * hex. Uses the browser-native WebCrypto API \u2014 no dependency. Async\n * because `crypto.subtle.digest` is async.\n */\nasync function canonicalSha256Hex(value: unknown): Promise<string> {\n const bytes = new TextEncoder().encode(canonicalJson(value));\n const digest = await crypto.subtle.digest(\"SHA-256\", bytes);\n const view = new Uint8Array(digest);\n let s = \"\";\n for (let i = 0; i < view.length; i++) {\n s += view[i]!.toString(16).padStart(2, \"0\");\n }\n return s;\n}\n\n/**\n * Structural equality for claim values. The verifier emits plain\n * JSON shapes (strings, numbers, booleans, arrays of those, objects\n * of those) so a value-equal comparison via JSON round-trip is\n * correct and ~25 ns for the sizes we see in practice. Avoids\n * pulling in a deep-equal dep for one call site.\n */\nfunction _deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\") return false;\n if (a === null || b === null) return false;\n try {\n return JSON.stringify(a) === JSON.stringify(b);\n } catch {\n return false;\n }\n}\n", "/**\n * Every error `signIn()` rejects with carries a stable `code`, so a site\n * can branch on it instead of matching message text. Messages may change;\n * codes don't (new codes may be added).\n */\n\nexport type PrsonLoginErrorCode =\n /** A newer signIn() call, or the person closed the dialog. */\n | \"aborted\"\n /** The page's Content-Security-Policy blocked a Prson host (PrsonCspError). */\n | \"csp_blocked\"\n /** The code ran out before anyone approved it. */\n | \"expired\"\n /** Too many sign-ins from this network; retry shortly. */\n | \"rate_limited\"\n /** Prson's relay or the phone couldn't be reached. */\n | \"network\"\n /** The credential failed a check; `reason` says which (verifier reasons, e.g. aud_mismatch). */\n | \"presentation_rejected\"\n /** The person's verification level is below `required.minVerificationLevel`. */\n | \"level_too_low\"\n /** `required.uniqueHumanId` was set and no unique-human id came back. */\n | \"unique_human_missing\"\n /** The phone sent something the SDK doesn't understand. */\n | \"protocol\"\n /** A signIn() option is wrong (nonce, returnUrl). */\n | \"invalid_options\"\n /** Anything else; `cause` holds the original error. */\n | \"unknown\";\n\nexport class PrsonLoginError extends Error {\n readonly code: PrsonLoginErrorCode;\n /** For presentation_rejected: the verifier's reason, such as \"nonce_mismatch\". */\n readonly reason?: string;\n /** For \"unknown\" (and wrapped errors): the original error. */\n readonly cause?: unknown;\n constructor(code: PrsonLoginErrorCode, message: string, reason?: string, cause?: unknown) {\n super(message);\n this.name = \"PrsonLoginError\";\n this.code = code;\n if (reason !== undefined) this.reason = reason;\n if (cause !== undefined) this.cause = cause;\n }\n}\n\n/** The code for an error from the relay or the connection (signaling closes name a reason). */\nexport function closedCode(reason: string): PrsonLoginErrorCode {\n return /expir/i.test(reason) ? \"expired\" : \"network\";\n}\n\n/** Any error as a PrsonLoginError: a failed fetch is \"network\", anything else \"unknown\" (the original is its cause). */\nexport function asLoginError(e: unknown): PrsonLoginError {\n if (e instanceof PrsonLoginError) return e;\n const message = e instanceof Error ? e.message : String(e);\n const code: PrsonLoginErrorCode = /Failed to fetch|NetworkError|Load failed/i.test(message) ? \"network\" : \"unknown\";\n return new PrsonLoginError(code, message, undefined, e);\n}\n", "/**\n * Typed HTTPS wrappers around the Cloudflare Worker's session API.\n *\n * The SDK does NOT depend on Firebase. The Worker is the single API\n * surface: anonymous /session/draft for the browser, wallet-signed\n * /session/claim for the wallet. See `../../../../cloudflare-workers/signaling-worker`\n * for the server impl and `../../ARCHITECTURE.md` for the spec.\n */\nimport { PrsonLoginError } from \"./errors.js\";\nimport { SIGNALING_BASE } from \"./index.js\";\n\n/** The verifier-side request blob the SDK assembles + sends to /session/draft. */\nexport type VerifierRequest = {\n domain: string;\n nonce: string;\n browserPk: string;\n required: {\n /** 0 = pseudonymous (unverified identity) accepted; omitted \u21D2 1. */\n minVerificationLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6;\n requiredClaims?: string[];\n predicates?: string[];\n identityType?: \"personal\" | \"organization\";\n /** Require a domain-scoped unique-human id (document-anchored). */\n uniqueHumanId?: boolean;\n };\n ttlMaxMinutes: number;\n /** Data-channel envelope version the SDK speaks (2 = sender-authenticated). */\n envelopeVersion?: number;\n};\n\nexport type DraftResult = {\n reqId: string;\n /** Bearer used on the WS upgrade `Sec-WebSocket-Protocol` header. */\n draftToken: string;\n /** wss URL the SDK opens to join the Durable Object as the browser peer. */\n signalingWss: string;\n /** Epoch s \u2014 caller has until this moment for a wallet to claim. */\n draftExpiresAt: number;\n /**\n * **Server-issued timestamp** (epoch seconds, M-3 / v2). The Worker\n * stamped it at draft creation and stored it in the DO. The wallet\n * MUST echo this value verbatim in its `prson-login-claim/v2`\n * signature \u2014 the Worker rebuilds the canonical bytes using its\n * stored copy, so any tamper breaks the signature. The SDK threads\n * it through the QR (`t=` param).\n */\n serverTs: number;\n /**\n * OLDER relays only: Cloudflare TURN credentials for the browser side,\n * minted at draft time. Current relays omit this and instead send\n * `{ \"type\": \"ice\", \"iceServers\": [...] }` over the WebSocket once a\n * wallet has claimed the code, so no relay capacity is minted for a\n * code nobody scans. Either way the browser runs relay-only (see\n * transport.ts `rtcConfigFor`). Wire grammar matches `RTCIceServer`.\n */\n turn?: {\n urls: string | string[];\n username: string;\n credential: string;\n expiresAt?: number;\n };\n};\n\n/**\n * POST /session/draft on the Cloudflare Worker. Anonymous + IP rate-\n * limited at 30 drafts/IP/min (no TURN allocated yet \u2014 the Worker\n * waits for a wallet to claim before issuing any relay capacity).\n */\nexport async function createDraft(\n request: VerifierRequest,\n opts: { signalingBase?: string; fetchImpl?: typeof fetch } = {},\n): Promise<DraftResult> {\n const base = opts.signalingBase ?? SIGNALING_BASE;\n const fetchImpl = opts.fetchImpl ?? fetch;\n const res = await fetchImpl(`${base}/session/draft`, {\n method: \"POST\",\n mode: \"cors\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ request }),\n });\n if (!res.ok) {\n const text = await safeText(res);\n if (res.status === 429) {\n throw new PrsonLoginError(\"rate_limited\", \"Too many login sessions from this network \u2014 please retry shortly.\");\n }\n throw new PrsonLoginError(\"network\", `createDraft failed: HTTP ${res.status} ${text || res.statusText}`);\n }\n return (await res.json()) as DraftResult;\n}\n\nasync function safeText(res: Response): Promise<string> {\n try { return await res.text(); } catch { return \"\"; }\n}\n", "/**\n * Browser-side WebSocket client for the Cloudflare Worker signaling\n * Durable Object. The wallet talks to the same Worker; the DO fans\n * messages between us.\n *\n * Wire format mirrors the Worker's `SignalingMessage` discriminated\n * union (see cloudflare-workers/signaling-worker/src/index.ts). We don't import\n * those types directly because cross-package type sharing would\n * bloat the SDK; the two definitions are kept in sync by the spec.\n */\nimport { PrsonLoginError, closedCode } from \"./errors.js\";\n\nconst WS_SUBPROTOCOL = \"prson-login-v1\";\n\nexport type SignalingMessage =\n | { msg: \"offer\"; sdp: string }\n | { msg: \"answer\"; sdp: string }\n | { msg: \"candidate\"; candidate: unknown }\n | { msg: \"peer-ready\" }\n | { msg: \"peer-gone\" }\n | { msg: \"error\"; reason: string };\n\n/**\n * Relay \u2192 browser, once a wallet has claimed the code:\n * `{ \"type\": \"ice\", \"iceServers\": [...] }` \u2014 the TURN servers the\n * browser must use (relay-only, so its addresses never reach the\n * phone). Newer relays send no TURN at draft time; older ones put it\n * in the draft response instead and never send this.\n */\nexport type IceMessage = { type: \"ice\"; iceServers: RTCIceServer[] };\n\nexport interface SignalingConnection {\n /** Push a message to the other peer through the relay. */\n send(m: SignalingMessage): void;\n /** Subscribe to messages from the other peer. */\n onMessage(cb: (m: SignalingMessage) => void): void;\n /** Subscribe to terminal-close events from either side or the worker. */\n onClose(cb: (reason: string) => void): void;\n /**\n * Resolves with the relay's `ice` servers (the first `ice` message,\n * buffered if it arrived before this was called). Rejects if the\n * socket closes first.\n */\n awaitIce(): Promise<RTCIceServer[]>;\n /** Close the WS. Does not tear down the underlying RTCPeerConnection. */\n close(): void;\n}\n\nexport async function connectSignaling(opts: {\n url: string;\n role: \"browser\";\n sigToken: string;\n}): Promise<SignalingConnection> {\n const ws = new WebSocket(opts.url, [WS_SUBPROTOCOL, opts.sigToken]);\n const msgListeners: Array<(m: SignalingMessage) => void> = [];\n const closeListeners: Array<(reason: string) => void> = [];\n let ice: RTCIceServer[] | null = null;\n let closedReason: string | null = null;\n const iceWaiters: Array<{ resolve: (s: RTCIceServer[]) => void; reject: (e: Error) => void }> = [];\n\n await new Promise<void>((resolve, reject) => {\n const onOpen = () => {\n ws.removeEventListener(\"open\", onOpen);\n ws.removeEventListener(\"error\", onErrorBefore);\n resolve();\n };\n const onErrorBefore = () => {\n ws.removeEventListener(\"open\", onOpen);\n ws.removeEventListener(\"error\", onErrorBefore);\n reject(new PrsonLoginError(\"network\", \"signaling: WS upgrade failed (auth?)\"));\n };\n ws.addEventListener(\"open\", onOpen);\n ws.addEventListener(\"error\", onErrorBefore);\n });\n\n ws.addEventListener(\"message\", (evt) => {\n let parsed: SignalingMessage | IceMessage;\n try {\n parsed = JSON.parse(String(evt.data)) as SignalingMessage | IceMessage;\n } catch {\n return; // bad frame from the Worker; ignore\n }\n if (parsed && (parsed as IceMessage).type === \"ice\") {\n // Only the first one counts: the peer connection is built from it.\n const servers = (parsed as IceMessage).iceServers;\n if (ice || !Array.isArray(servers)) return;\n ice = servers.filter((x) => x && (typeof x.urls === \"string\" || Array.isArray(x.urls)));\n for (const w of iceWaiters.splice(0)) w.resolve(ice);\n return;\n }\n if (!parsed || typeof (parsed as SignalingMessage).msg !== \"string\") return;\n for (const cb of msgListeners) cb(parsed as SignalingMessage);\n });\n\n ws.addEventListener(\"close\", (evt) => {\n const reason = evt.reason || `code-${evt.code}`;\n closedReason = reason;\n for (const w of iceWaiters.splice(0)) w.reject(new PrsonLoginError(closedCode(reason), `signaling: closed before the code was claimed (${reason})`));\n for (const cb of closeListeners) cb(reason);\n });\n\n return {\n send(m: SignalingMessage) {\n if (ws.readyState !== WebSocket.OPEN) return;\n ws.send(JSON.stringify(m));\n },\n onMessage(cb) {\n msgListeners.push(cb);\n },\n onClose(cb) {\n closeListeners.push(cb);\n },\n awaitIce() {\n if (ice) return Promise.resolve(ice);\n if (closedReason !== null) {\n return Promise.reject(new PrsonLoginError(closedCode(closedReason), `signaling: closed before the code was claimed (${closedReason})`));\n }\n return new Promise((resolve, reject) => iceWaiters.push({ resolve, reject }));\n },\n close() {\n try { ws.close(1000, \"client_close\"); } catch { /* */ }\n },\n };\n}\n", "/**\n * Browser-side WebRTC transport. Orchestrates the SDP offer / answer +\n * ICE exchange via the Cloudflare Worker signaling, and exposes a\n * tiny event-stream interface over the established data channel.\n */\nimport { PrsonLoginError } from \"./errors.js\";\nimport type { SignalingConnection } from \"./signaling.js\";\n\nexport interface Transport {\n /** Await the next data-channel message as a UTF-8 string. */\n awaitNextMessage(): Promise<string>;\n /** Await the first data-channel message; convenience wrapper. */\n awaitFirstMessage(): Promise<string>;\n /** Subscribe to all data-channel messages as they arrive. */\n onMessage(cb: (raw: string) => void): void;\n /** Subscribe to terminal-close events from either side or the\n * Worker. Fires exactly once per transport with a short string\n * reason \u2014 the SDK's session layer maps this to the matching\n * `signed_out` reason code so the host gets a lifecycle event\n * the moment the wire dies (rather than waiting for the\n * credential's exp timer, which runs days from now and never\n * matches the much-shorter session TTL). */\n onClose(cb: (reason: string) => void): void;\n /** Send a UTF-8 string over the data channel (used by `revoke` etc.). */\n send(raw: string): void;\n /** Close the RTCPeerConnection + the data channel. */\n close(): void;\n}\n\n/**\n * RTCPeerConnection config for the browser side. The browser is always\n * relay-only (`iceTransportPolicy: \"relay\"`, no STUN): it gathers only\n * relay candidates, so none of its own addresses (LAN, public) reach the\n * phone \u2014 the wallet has done the same since M-4.\n *\n * A relay that sends no TURN server would leave nothing to relay\n * through, and the old fallback (`\"all\"`) leaked the browser's\n * addresses. That now fails closed: the sign-in stops with an error.\n * The one exception is a page on loopback ([allowDirect], for a local\n * relay without TURN credentials during development), where the direct\n * candidates stay on the developer's own machine and network.\n */\nexport function rtcConfigFor(iceServers: RTCIceServer[], opts?: { allowDirect?: boolean }): RTCConfiguration {\n const urls = (s: RTCIceServer) => (Array.isArray(s.urls) ? s.urls : [s.urls]);\n const isTurn = (u: string) => /^turns?:/i.test(u);\n const turn = iceServers\n .map((s) => ({ ...s, urls: urls(s).filter(isTurn) }))\n .filter((s) => s.urls.length > 0);\n if (turn.length > 0) return { iceServers: turn, iceTransportPolicy: \"relay\" };\n if (opts?.allowDirect === true) return { iceServers, iceTransportPolicy: \"all\" };\n throw new PrsonLoginError(\"network\", \"transport: the relay sent no TURN server; refusing a direct connection\");\n}\n\n/** True when [hostname] is this machine: `localhost` (and `*.localhost`),\n * 127.0.0.0/8 or `::1`. */\nexport function isLoopbackHost(hostname: string | undefined | null): boolean {\n if (!hostname) return false;\n const h = hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n if (h === \"localhost\" || h.endsWith(\".localhost\")) return true;\n if (h === \"::1\") return true;\n return /^127(?:\\.\\d{1,3}){3}$/.test(h);\n}\n\nfunction pageIsLoopback(): boolean {\n const loc = (globalThis as { location?: { hostname?: string } }).location;\n return isLoopbackHost(loc?.hostname);\n}\n\n/** How long a live data channel must stay silent after a `peer-gone`\n * before we believe it. The wallet pings every 2 s. */\nconst PEER_GONE_CONFIRM_MS = 6000;\n\nexport async function establishTransport(opts: {\n signaling: SignalingConnection;\n role: \"browser\";\n /**\n * ICE servers from the relay: the `ice` message it sends once a wallet\n * claimed the code, or (older relays) the draft response's `turn`.\n * See [rtcConfigFor] and ../../SECURITY.md \u00A76.\n */\n iceServers: RTCIceServer[];\n}): Promise<Transport> {\n const pc = new RTCPeerConnection(rtcConfigFor(opts.iceServers, { allowDirect: pageIsLoopback() }));\n\n // Browser is the initiator \u2192 opens the data channel before the\n // offer. Negotiated=false so the wallet sees `ondatachannel`.\n const dc = pc.createDataChannel(\"prson-login\", { ordered: true });\n\n // Trickle ICE \u2192 signaling.\n pc.addEventListener(\"icecandidate\", (e) => {\n if (e.candidate) opts.signaling.send({ msg: \"candidate\", candidate: e.candidate.toJSON() });\n });\n\n // Bridge inbound signaling \u2192 peer connection.\n opts.signaling.onMessage(async (m) => {\n if (m.msg === \"answer\") {\n await pc.setRemoteDescription({ type: \"answer\", sdp: m.sdp });\n } else if (m.msg === \"candidate\") {\n try {\n await pc.addIceCandidate(m.candidate as RTCIceCandidateInit);\n } catch {\n // Late or duplicate candidates can be ignored \u2014 the SDP path\n // covered the gathered ones.\n }\n } else if (m.msg === \"peer-gone\") {\n // `peer-gone` is the relay's word that the wallet's socket went\n // away. It travels the same socket as the wallet's own messages,\n // so it isn't proof: once the data channel is up, the channel\n // itself decides \u2014 if the wallet stays silent (it pings every\n // 2 s), it's gone; if it keeps talking, the notice is ignored.\n // `error` frames are never acted on.\n if (dc.readyState === \"open\") {\n confirmPeerGone();\n return;\n }\n // Wallet vanished \u2014 close the data channel so the host knows.\n // Fire the explicit teardown FIRST with a wallet-side reason\n // so the SDK maps it to `wallet_signed_out` (the dc close\n // alone would degrade to the generic `network_loss`).\n fireClose(\"wallet_signed_out\");\n try { dc.close(); } catch { /* */ }\n }\n });\n\n let lastDcMessageAt = 0;\n let peerGoneTimer: ReturnType<typeof setTimeout> | null = null;\n function confirmPeerGone() {\n if (peerGoneTimer) return;\n const noticeAt = Date.now();\n peerGoneTimer = setTimeout(() => {\n peerGoneTimer = null;\n if (lastDcMessageAt >= noticeAt) return; // still talking: not gone\n fireClose(\"wallet_signed_out\");\n try { dc.close(); } catch { /* */ }\n }, PEER_GONE_CONFIRM_MS);\n }\n\n // Generate + post the SDP offer.\n const offer = await pc.createOffer();\n await pc.setLocalDescription(offer);\n opts.signaling.send({ msg: \"offer\", sdp: offer.sdp! });\n\n // Wait for the data channel to open.\n await new Promise<void>((resolve, reject) => {\n if (dc.readyState === \"open\") return resolve();\n const onOpen = () => {\n dc.removeEventListener(\"open\", onOpen);\n dc.removeEventListener(\"error\", onError);\n resolve();\n };\n const onError = () => {\n dc.removeEventListener(\"open\", onOpen);\n dc.removeEventListener(\"error\", onError);\n reject(new PrsonLoginError(\"network\", \"transport: data channel failed to open\"));\n };\n dc.addEventListener(\"open\", onOpen);\n dc.addEventListener(\"error\", onError);\n });\n\n // Message bookkeeping: split between one-shot waiters (the initial\n // presentation) and steady-state subscribers (renewals).\n const oneShotWaiters: Array<(raw: string) => void> = [];\n const allListeners: Array<(raw: string) => void> = [];\n // Terminal-close fan-out. Three triggers map onto the same\n // notification: signaling close (WS code 4000 = Worker DO alarm\n // fired at session TTL), peer-gone signaling message (wallet\n // revoked), and the data channel itself closing for any other\n // reason. Fired at most once \u2014 the latch prevents duplicate\n // signed_out events in the SDK's session layer.\n const closeListeners: Array<(reason: string) => void> = [];\n let closeFired = false;\n function fireClose(reason: string) {\n if (closeFired) return;\n closeFired = true;\n for (const cb of closeListeners) {\n try { cb(reason); } catch { /* swallow */ }\n }\n }\n opts.signaling.onClose((reason) => fireClose(reason));\n dc.addEventListener(\"close\", () => fireClose(\"network_loss\"));\n dc.addEventListener(\"message\", (evt) => {\n lastDcMessageAt = Date.now();\n const raw = typeof evt.data === \"string\"\n ? evt.data\n : new TextDecoder().decode(evt.data as ArrayBuffer);\n while (oneShotWaiters.length > 0) {\n const cb = oneShotWaiters.shift()!;\n cb(raw);\n }\n for (const cb of allListeners) cb(raw);\n });\n\n return {\n awaitNextMessage() {\n return new Promise((resolve) => oneShotWaiters.push(resolve));\n },\n awaitFirstMessage() {\n return new Promise((resolve) => oneShotWaiters.push(resolve));\n },\n onMessage(cb) {\n allListeners.push(cb);\n },\n onClose(cb) {\n // Late subscribers still get the notification: if the close\n // already fired, dispatch on the next microtask so the\n // subscriber's await chain sees a single deterministic\n // ordering (analogous to `signed_in` being microtask-deferred).\n if (closeFired) {\n queueMicrotask(() => cb(\"network_loss\"));\n } else {\n closeListeners.push(cb);\n }\n },\n send(raw: string) {\n if (dc.readyState === \"open\") dc.send(raw);\n },\n close() {\n if (peerGoneTimer) clearTimeout(peerGoneTimer);\n try { dc.close(); } catch { /* */ }\n try { pc.close(); } catch { /* */ }\n opts.signaling.close();\n },\n };\n}\n", "/**\n * Minimal QR rendering surface. We deliberately don't bundle a full\n * QR library here \u2014 the SDK is tiny and most sites already have one.\n * Instead, we expose a render adapter that the host page can override.\n *\n * Default behaviour: render a placeholder `<div>` with the URL as\n * text + a copy-to-clipboard affordance, and emit a `console.warn`\n * pointing partners at the QR-renderer hook. Production deployments\n * pass a real QR renderer (e.g. `qrcode-svg`, `qr-creator`) via\n * `PrsonLogin.signIn({ ui: { mountQrInto } })` + a global override\n * on `window.__prsonLoginQrRenderer`.\n */\n\nexport interface LoginQrHandle {\n /** Tear the QR down (called automatically when the SDK no longer needs it). */\n dispose(): void;\n /**\n * Optional (renderers written before 0.2 don't have it): the SDK\n * reports progress so the UI can show it. For `\"success\"` the renderer\n * may return a promise; the SDK waits for it (at most 1.5 s) before\n * tearing the UI down, so a check animation can finish.\n */\n update?(state: LoginUiState): void | Promise<void>;\n}\n\n/**\n * What the sign-in is doing, as far as the browser can tell:\n *\n * waiting the code is on screen\n * scanned a wallet claimed the code (the person approved on the\n * phone, which is now connecting)\n * approving the encrypted channel to the phone is open; the phone is\n * preparing its signed proof\n * verifying the proof arrived; the SDK is checking it\n * success checked; the UI is about to close\n * error something failed; `message` says what, in plain words\n *\n * Expiry isn't sent: the renderer runs the countdown from the code's own\n * server timestamp (`t=`).\n */\nexport type LoginUiState =\n | { state: \"waiting\" }\n | { state: \"scanned\" }\n | { state: \"approving\" }\n | { state: \"verifying\" }\n | { state: \"success\"; domain: string }\n | { state: \"error\"; message: string };\n\n/** The optional fourth argument the SDK passes to a renderer. */\nexport interface LoginQrContext {\n /** `\"modal\"`: inside the SDK's own dialog. `\"inline\"`: in the host's `mountQrInto`. */\n mode: \"modal\" | \"inline\";\n /** The domain the person is signing in to (the same as the code's `d=`). */\n domain: string;\n /**\n * Ask for a fresh code (after expiry or an error): the SDK makes a new\n * draft and renders again, and `signIn()` keeps waiting. The renderer\n * should first dispatch the bubbling `prson-login-refresh-requested`\n * DOM event (the 0.1 contract); if the host re-called `signIn()` from\n * that event, this is a no-op.\n */\n refresh?: () => void;\n /** Close the sign-in: `signIn()` rejects with `LoginAbortedError`. */\n cancel?: () => void;\n /** Where \"Don't have Prson? Get it\" points. */\n getAppUrl: string;\n /** The id the card's title should carry, so the modal is labelled by it. */\n titleId: string;\n}\n\nexport type LoginQrRenderer = (\n url: string,\n mount: HTMLElement,\n theme: \"light\" | \"dark\" | \"auto\",\n context?: LoginQrContext,\n) => LoginQrHandle;\n\n/**\n * Create a centred modal scrim and return the inner mount element +\n * a dispose handle. Used as the default QR presentation when the\n * host page didn't pass `mountQrInto` \u2014 the SDK calls this, then\n * hands the inner mount to `renderLoginQr` exactly like an inline\n * mount.\n *\n * The scrim:\n * * darkens the page with a 50%-black overlay + a 4 px backdrop\n * blur (so the partner UI fades into the background but stays\n * contextual),\n * * dismisses on **Esc** (any focused field is bypassed via\n * capture-phase listener \u2014 works even with another input\n * focused),\n * * dismisses on **click outside** the card,\n * * sits above every layout via `z-index: 2147483647`.\n *\n * Dismissing fires [onDismiss] \u2014 the SDK wires this to abort the\n * in-flight `signIn()` so the host's `await signIn(...)` rejects\n * with `LoginAbortedError` rather than hanging.\n */\nexport function createModalQrMount(opts: {\n onDismiss: () => void;\n /** The id of the card's title: the dialog is labelled by it. */\n titleId?: string;\n}): { mount: HTMLElement; dispose: () => void } {\n const scrim = document.createElement(\"div\");\n scrim.setAttribute(\"data-prson-login-modal\", \"1\");\n // Phones get a bottom sheet (thumb-reachable); larger screens a centred card.\n const sheet = typeof window.matchMedia === \"function\" && window.matchMedia(\"(max-width: 480px)\").matches;\n scrim.style.cssText =\n \"position:fixed;inset:0;background:rgba(10,10,10,0.45);\" +\n \"backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);\" +\n \"z-index:2147483647;display:flex;overflow-y:auto;box-sizing:border-box;\" +\n \"justify-content:center;\" +\n (sheet ? \"align-items:flex-end;padding:0;\" : \"align-items:center;padding:24px 16px;\");\n\n // An accessible dialog: role, aria-modal, labelled by the card's title,\n // focus moved in and kept there (Tab wraps), restored on close.\n const mount = document.createElement(\"div\");\n mount.setAttribute(\"data-prson-login-modal-mount\", \"1\");\n mount.setAttribute(\"role\", \"dialog\");\n mount.setAttribute(\"aria-modal\", \"true\");\n if (opts.titleId) mount.setAttribute(\"aria-labelledby\", opts.titleId);\n else mount.setAttribute(\"aria-label\", \"Sign in with Prson\");\n mount.tabIndex = -1;\n // The QR card renderer manages its own width via CSS \u2014 give it\n // the natural sizing it expects.\n mount.style.cssText =\n \"display:flex;align-items:center;justify-content:center;outline:none;max-width:100%;\" +\n (sheet ? \"width:100%;\" : \"margin:auto 0;\");\n\n scrim.append(mount);\n const previouslyFocused = document.activeElement instanceof HTMLElement ? document.activeElement : null;\n const root = document.documentElement;\n const prevOverflow = root.style.overflow;\n root.style.overflow = \"hidden\";\n document.body.append(scrim);\n // Focus the dialog itself, so a screen reader starts at its title and a\n // stray Enter doesn't press anything.\n setTimeout(() => {\n if (!disposed && !mount.contains(document.activeElement)) mount.focus({ preventScroll: true });\n }, 0);\n\n let disposed = false;\n\n function dispose() {\n if (disposed) return;\n disposed = true;\n document.removeEventListener(\"keydown\", onKey, true);\n scrim.remove();\n root.style.overflow = prevOverflow;\n try {\n previouslyFocused?.focus({ preventScroll: true });\n } catch {\n /* gone from the page */\n }\n }\n\n function onKey(e: KeyboardEvent) {\n if (e.key === \"Escape\" || e.key === \"Esc\") {\n e.preventDefault();\n e.stopPropagation();\n opts.onDismiss();\n return;\n }\n if (e.key !== \"Tab\") return;\n const focusable = Array.from(\n mount.querySelectorAll<HTMLElement>('a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex=\"-1\"])'),\n ).filter((el) => el.getClientRects().length > 0);\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (!first || !last) {\n e.preventDefault();\n mount.focus();\n return;\n }\n const active = document.activeElement;\n if (e.shiftKey && (active === first || active === mount || !mount.contains(active))) {\n e.preventDefault();\n last.focus();\n } else if (!e.shiftKey && (active === last || !mount.contains(active))) {\n e.preventDefault();\n first.focus();\n }\n }\n\n scrim.addEventListener(\"click\", (e) => {\n // Click directly on the scrim (not the card) dismisses. Card\n // taps bubble up from the inner mount; we ignore them.\n if (e.target === scrim || e.target === mount) {\n opts.onDismiss();\n }\n });\n\n document.addEventListener(\"keydown\", onKey, true);\n\n return { mount, dispose };\n}\n\nexport function renderLoginQr(\n url: string,\n mount: HTMLElement,\n theme: \"light\" | \"dark\" | \"auto\",\n context?: LoginQrContext,\n): LoginQrHandle {\n const override = (window as unknown as { __prsonLoginQrRenderer?: LoginQrRenderer })\n .__prsonLoginQrRenderer;\n if (override) return override(url, mount, theme, context);\n\n // Fallback: text + click-to-copy. Good enough for development;\n // partners should install a real QR renderer.\n // eslint-disable-next-line no-console\n console.warn(\n \"[@prson/login-sdk] No QR renderer installed. Set window.__prsonLoginQrRenderer \" +\n \"to a function (url, mount, theme) => { dispose: () => void } before calling signIn().\",\n );\n\n const root = document.createElement(\"div\");\n root.setAttribute(\"data-prson-qr-fallback\", \"1\");\n root.style.cssText = \"font-family:system-ui,sans-serif;font-size:12px;padding:12px;border:1px dashed currentColor;border-radius:8px;word-break:break-all;cursor:pointer;\";\n root.textContent = url;\n root.title = \"Click to copy. Install a real QR renderer for the production UX.\";\n root.addEventListener(\"click\", () => {\n void navigator.clipboard?.writeText(url);\n });\n mount.append(root);\n\n return {\n dispose() {\n root.remove();\n },\n };\n}\n", "/**\n * Content-Security-Policy help.\n *\n * A page whose CSP doesn't allow Prson's hosts sees a plain \"Failed to\n * fetch\" or a WebSocket error. While a sign-in runs, the SDK listens for\n * the browser's `securitypolicyviolation` events; when one names a Prson\n * host, the failure is reported as a `PrsonCspError` that says which\n * directive blocked what and which sources to add.\n */\nimport { PrsonLoginError } from \"./errors.js\";\n\n/** Hosts the browser SDK talks to in production (see the README's CSP section). */\nexport const PRSON_CONNECT_SRC = [\n \"https://signaling.prson.net\",\n \"wss://signaling.prson.net\",\n \"https://app.prson.net\",\n \"https://api.prson.net\",\n] as const;\n\n/** Thrown by `signIn()` when the page's Content-Security-Policy blocked Prson. */\nexport class PrsonCspError extends PrsonLoginError {\n readonly directive: string;\n readonly blockedUri: string;\n readonly allow: string[];\n constructor(directive: string, blockedUri: string, allow: string[]) {\n super(\n \"csp_blocked\",\n `This page's Content-Security-Policy blocked Prson sign-in: ${directive} doesn't allow ${blockedUri}. ` +\n `Add to connect-src: ${allow.join(\" \")}`,\n );\n this.name = \"PrsonCspError\";\n this.directive = directive;\n this.blockedUri = blockedUri;\n this.allow = allow;\n }\n}\n\n/** The connect-src sources a sign-in against `signalingBase` needs. */\nexport function connectSourcesFor(signalingBase: string, issuerJwksUri?: string): string[] {\n const out = new Set<string>();\n try {\n const u = new URL(signalingBase);\n out.add(u.origin);\n out.add(`${u.protocol === \"http:\" ? \"ws\" : \"wss\"}://${u.host}`);\n } catch {\n /* a bad base fails elsewhere with its own error */\n }\n if (issuerJwksUri) {\n // The dev issuer: its keys and revocation lists are on the dev API.\n try {\n out.add(new URL(issuerJwksUri).origin);\n } catch {\n /* ignore a bad override */\n }\n } else {\n out.add(\"https://app.prson.net\");\n out.add(\"https://api.prson.net\");\n }\n return [...out];\n}\n\nfunction hostOf(uri: string): string | null {\n try {\n return new URL(uri).host;\n } catch {\n return null;\n }\n}\n\nfunction originOf(uri: string): string {\n try {\n const u = new URL(uri);\n return `${u.protocol}//${u.host}`;\n } catch {\n return \"(unknown)\";\n }\n}\n\nexport type CspWatch = {\n /** The error to throw instead of `err` when a CSP block explains it, else `err`. */\n explain(err: unknown): Promise<unknown>;\n stop(): void;\n};\n\n/**\n * Watch for CSP blocks of Prson hosts during a sign-in. A no-op outside\n * a browser.\n */\nexport function watchCsp(signalingBase: string, issuerJwksUri?: string): CspWatch {\n if (typeof document === \"undefined\" || typeof document.addEventListener !== \"function\") {\n return { explain: async (e) => e, stop: () => {} };\n }\n const allow = connectSourcesFor(signalingBase, issuerJwksUri);\n const prsonHosts = new Set(allow.map(hostOf).filter((h): h is string => !!h));\n let seen: { directive: string; blockedUri: string } | null = null;\n const onViolation = (ev: Event) => {\n // Only the browser's own reports: a page script can dispatch a fake one.\n if (!ev.isTrusted) return;\n const e = ev as SecurityPolicyViolationEvent;\n const host = hostOf(e.blockedURI);\n if (!seen && host && (prsonHosts.has(host) || host.endsWith(\".prson.net\"))) {\n // The origin only: the path can carry a request id.\n seen = { directive: e.effectiveDirective || e.violatedDirective, blockedUri: originOf(e.blockedURI) };\n }\n };\n document.addEventListener(\"securitypolicyviolation\", onViolation);\n return {\n async explain(err) {\n // The violation event can arrive just after the failed fetch or\n // WebSocket rejects: give it a turn of the event loop.\n if (!seen) await new Promise((r) => setTimeout(r, 0));\n if (!seen) return err;\n const s = seen as { directive: string; blockedUri: string };\n return new PrsonCspError(s.directive, s.blockedUri, allow);\n },\n stop() {\n document.removeEventListener(\"securitypolicyviolation\", onViolation);\n },\n };\n}\n\n/**\n * The nonce for injected `<style>` elements, for pages whose `style-src`\n * uses a nonce. Read from the `nonce` attribute of\n * `<meta property=\"csp-nonce\" nonce=\"\u2026\">` (the convention Vite uses).\n * Only the `nonce` attribute: browsers hide it from CSS selectors, while a\n * nonce in `content` could be read out by injected CSS.\n */\nexport function cspStyleNonce(): string | undefined {\n if (typeof document === \"undefined\") return undefined;\n const m = document.querySelector<HTMLMetaElement>('meta[property=\"csp-nonce\"]');\n if (!m) return undefined;\n return m.nonce || m.getAttribute(\"nonce\") || undefined;\n}\n", "// Website notifications (SignInOptions.notifications): the wallet answers an\n// opted-in sign-in with a handle, random per wallet and site, that the site's\n// backend uses with POST https://api.prson.net/v1/notify (an API key with\n// notify:write). See documentation/SITE_NOTIFICATIONS.md.\n\n/** What a notification handle looks like: `nh_` and 32 random bytes, base64url. */\nexport const NOTIFY_HANDLE = /^nh_[A-Za-z0-9_-]{43}$/;\n\n/**\n * The handle in the wallet's sign-in envelope, or null when the person didn't\n * tick \"Let {site} send you notifications\" (or the wallet is older). Anything\n * that isn't a well-formed handle reads as null.\n */\nexport function notifyHandleFrom(envelope: unknown): string | null {\n if (!envelope || typeof envelope !== \"object\") return null;\n const value = (envelope as { notifyHandle?: unknown }).notifyHandle;\n return typeof value === \"string\" && NOTIFY_HANDLE.test(value) ? value : null;\n}\n", "/**\n * Virtual-cursor-friendly overlay for native `<select>` elements.\n *\n * Why this exists: native `<select>` dropdowns are rendered by the OS\n * shell, not the DOM. Synthetic `click` events from `bindMouse`'s\n * virtual cursor cannot open them, and even if they did the OS-drawn\n * option list is outside the page's coordinate system \u2014 the virtual\n * cursor couldn't navigate it. We replace the native dropdown with a\n * pure-DOM overlay sized for cursor accuracy:\n *\n * * Each option is a large (\u226556 px tall) button \u2014 easy to land on\n * with the wand or trackpad.\n * * \"Previous page\" / \"Next page\" buttons step through long option\n * lists one viewport-sized chunk at a time.\n * * An \"X\" button closes without committing a choice.\n * * The overlay sits at the top of the body z-index stack and\n * traps clicks: while it's open, the rest of the page is\n * non-interactive \u2014 the cursor's click router only considers\n * overlay elements.\n * * The overlay is rendered inside a Shadow DOM root with\n * `:host { all: initial; }` so the host page's stylesheets\n * cannot bleed in. The page can neither restyle nor read the\n * overlay (closed-mode shadow), beyond what we deliberately\n * expose via attributes.\n *\n * Wiring from `bindMouse`:\n *\n * * Move frames re-route the snap target into the overlay via\n * [findNearestClickableInOverlay] when the overlay is open.\n * * Click frames detect `<select>` snap targets and open the\n * overlay instead of dispatching a click. When the overlay is\n * open, subsequent clicks route through it.\n * * `bindMouse.dispose()` calls [closeAllOverlays] so a torn-down\n * cursor doesn't leave the overlay orphaned.\n */\n\nimport { cspStyleNonce } from \"./csp.js\";\n\ninterface OverlayHandle {\n host: HTMLElement;\n shadow: ShadowRoot;\n close: () => void;\n}\n\nlet activeOverlay: OverlayHandle | null = null;\n\n/** True when a select overlay is currently open + accepting input. */\nexport function isSelectOverlayActive(): boolean {\n return activeOverlay !== null;\n}\n\n/** Close any currently-open overlay. No-op when none is open. */\nexport function closeAllOverlays(): void {\n activeOverlay?.close();\n}\n\n/**\n * Mount the overlay for [select]. Replaces any existing overlay.\n * Returns the handle so callers can close it programmatically (e.g.\n * if the cursor disposes while the overlay is still up). The\n * overlay self-closes when the user picks an option or taps X.\n */\nexport function openSelectOverlay(select: HTMLSelectElement): OverlayHandle {\n if (activeOverlay) activeOverlay.close();\n\n const host = document.createElement(\"div\");\n host.setAttribute(\"data-prson-select-overlay\", \"\");\n // Pin the host to the viewport. Inline styles win over any page\n // CSS that might try to position `div` differently (Shadow DOM\n // protects the inside; the host element itself is still in the\n // light tree).\n host.style.position = \"fixed\";\n host.style.inset = \"0\";\n // z-index sits just below the virtual cursor (2147483647) so the\n // cursor still paints on top of the overlay.\n host.style.zIndex = \"2147483646\";\n document.body.appendChild(host);\n\n const shadow = host.attachShadow({ mode: \"open\" });\n\n const style = document.createElement(\"style\");\n const nonce = cspStyleNonce();\n if (nonce) style.nonce = nonce;\n style.textContent = OVERLAY_CSS;\n shadow.appendChild(style);\n\n // Title label: prefer the matching `<label>`, then aria-label,\n // then name, then a generic string. Done once at open time so\n // late `label` mutations don't change the title mid-life.\n const title = pickTitle(select);\n\n const backdrop = document.createElement(\"div\");\n backdrop.className = \"backdrop\";\n backdrop.setAttribute(\"data-prson-select-backdrop\", \"\");\n\n const panel = document.createElement(\"div\");\n panel.className = \"panel\";\n\n // \u2500\u2500 header \u2500\u2500\u2500\u2500\n const header = document.createElement(\"div\");\n header.className = \"header\";\n const titleEl = document.createElement(\"div\");\n titleEl.className = \"title\";\n titleEl.textContent = title;\n const closeBtn = document.createElement(\"button\");\n closeBtn.className = \"close\";\n closeBtn.setAttribute(\"type\", \"button\");\n closeBtn.setAttribute(\"data-prson-select-close\", \"\");\n closeBtn.setAttribute(\"aria-label\", \"Close\");\n closeBtn.textContent = \"\u2715\";\n header.appendChild(titleEl);\n header.appendChild(closeBtn);\n panel.appendChild(header);\n\n // \u2500\u2500 pagination row + options \u2500\u2500\u2500\u2500\n const optionsWrap = document.createElement(\"div\");\n optionsWrap.className = \"options-wrap\";\n\n const pageUp = document.createElement(\"button\");\n pageUp.className = \"page-btn\";\n pageUp.setAttribute(\"type\", \"button\");\n pageUp.setAttribute(\"data-prson-select-page\", \"up\");\n pageUp.innerHTML = '<span class=\"chev\">\u25B2</span> Previous';\n\n const list = document.createElement(\"div\");\n list.className = \"options-list\";\n\n const pageDown = document.createElement(\"button\");\n pageDown.className = \"page-btn\";\n pageDown.setAttribute(\"type\", \"button\");\n pageDown.setAttribute(\"data-prson-select-page\", \"down\");\n pageDown.innerHTML = 'Next <span class=\"chev\">\u25BC</span>';\n\n optionsWrap.appendChild(pageUp);\n optionsWrap.appendChild(list);\n optionsWrap.appendChild(pageDown);\n panel.appendChild(optionsWrap);\n\n backdrop.appendChild(panel);\n shadow.appendChild(backdrop);\n\n // \u2500\u2500 options paging \u2500\u2500\u2500\u2500\n const options = Array.from(select.options);\n const PAGE_SIZE = 6;\n const numPages = Math.max(1, Math.ceil(options.length / PAGE_SIZE));\n let currentPage = pageOfValue(select.value, options, PAGE_SIZE);\n\n function renderPage(): void {\n list.replaceChildren();\n const start = currentPage * PAGE_SIZE;\n const end = Math.min(start + PAGE_SIZE, options.length);\n for (let i = start; i < end; i++) {\n const opt = options[i]!;\n const btn = document.createElement(\"button\");\n btn.className = \"option\";\n btn.setAttribute(\"type\", \"button\");\n btn.setAttribute(\"data-prson-select-option\", String(i));\n btn.textContent = opt.label || opt.value || `Option ${i + 1}`;\n if (opt.value === select.value) {\n btn.setAttribute(\"data-selected\", \"\");\n }\n list.appendChild(btn);\n }\n // Toggle paging button state. Visible-but-disabled rather than\n // removed so the layout stays stable (cursor doesn't have to\n // re-find the button when there's more to page through).\n if (currentPage <= 0) {\n pageUp.setAttribute(\"disabled\", \"\");\n } else {\n pageUp.removeAttribute(\"disabled\");\n }\n if (currentPage >= numPages - 1) {\n pageDown.setAttribute(\"disabled\", \"\");\n } else {\n pageDown.removeAttribute(\"disabled\");\n }\n }\n renderPage();\n\n const handle: OverlayHandle = {\n host,\n shadow,\n close: () => {\n host.remove();\n if (activeOverlay === handle) activeOverlay = null;\n },\n };\n\n // Click handler \u2014 works for both real-finger taps AND synthetic\n // events from the virtual cursor. `composedPath()` is required to\n // reach into the shadow tree from the listener on `shadow` itself.\n shadow.addEventListener(\"click\", (e) => {\n const path = (e as Event).composedPath();\n for (const node of path) {\n if (!(node instanceof Element)) continue;\n // Close button.\n if (node.getAttribute?.(\"data-prson-select-close\") !== null) {\n handle.close();\n return;\n }\n // Page buttons.\n const page = node.getAttribute?.(\"data-prson-select-page\");\n if (page === \"up\") {\n if (currentPage > 0) {\n currentPage -= 1;\n renderPage();\n }\n return;\n }\n if (page === \"down\") {\n if (currentPage < numPages - 1) {\n currentPage += 1;\n renderPage();\n }\n return;\n }\n // Option.\n const optAttr = node.getAttribute?.(\"data-prson-select-option\");\n if (optAttr !== null && optAttr !== undefined) {\n const idx = Number.parseInt(optAttr, 10);\n const chosen = options[idx];\n if (chosen) {\n select.value = chosen.value;\n select.dispatchEvent(new Event(\"input\", { bubbles: true }));\n select.dispatchEvent(new Event(\"change\", { bubbles: true }));\n }\n handle.close();\n return;\n }\n // Backdrop tap (anywhere outside the panel) closes too \u2014 the\n // virtual cursor can't escape to it easily, but a real finger\n // can.\n if (node.getAttribute?.(\"data-prson-select-backdrop\") !== null) {\n handle.close();\n return;\n }\n }\n });\n\n activeOverlay = handle;\n return handle;\n}\n\n/**\n * Snap-target lookup *inside* the active overlay. Bind.ts swaps\n * the regular `findNearestClickable` for this when an overlay is\n * open so the magic-mode highlight tracks the overlay's option\n * buttons instead of the (no-longer-interactive) page underneath.\n *\n * No radius cap \u2014 when the overlay is open the cursor MUST land on\n * something useful, so we always return a snap target if any\n * candidate exists.\n */\nexport function findNearestClickableInOverlay(\n x: number,\n y: number,\n): Element | null {\n if (!activeOverlay) return null;\n const candidates = activeOverlay.shadow.querySelectorAll(\n \"[data-prson-select-close],\" +\n \"[data-prson-select-page]:not([disabled]),\" +\n \"[data-prson-select-option]\",\n );\n let best: Element | null = null;\n let bestDist = Infinity;\n for (const el of Array.from(candidates)) {\n const rect = el.getBoundingClientRect();\n if (rect.width === 0 || rect.height === 0) continue;\n const dx = x < rect.left ? rect.left - x : x > rect.right ? x - rect.right : 0;\n const dy = y < rect.top ? rect.top - y : y > rect.bottom ? y - rect.bottom : 0;\n const dist = Math.sqrt(dx * dx + dy * dy);\n if (dist < bestDist) {\n bestDist = dist;\n best = el;\n }\n }\n return best;\n}\n\n/**\n * Highlight an element inside the active overlay by setting the\n * shared `data-prson-magic-snap` attribute. The overlay's own CSS\n * (inside the shadow) provides the visible style \u2014 the page's\n * stylesheet for that attribute cannot reach in.\n */\nexport function setOverlaySnap(target: Element | null): void {\n if (!activeOverlay) return;\n activeOverlay.shadow\n .querySelectorAll(\"[data-prson-magic-snap]\")\n .forEach((el) => el.removeAttribute(\"data-prson-magic-snap\"));\n if (target) target.setAttribute(\"data-prson-magic-snap\", \"\");\n}\n\n// \u2500\u2500\u2500 internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction pickTitle(select: HTMLSelectElement): string {\n // Prefer an explicit label[for=id] OR a wrapping <label>.\n if (select.id) {\n const lbl = document.querySelector(\n `label[for=\"${cssEscapeLocal(select.id)}\"]`,\n );\n if (lbl?.textContent) return lbl.textContent.trim();\n }\n const wrap = select.closest(\"label\");\n if (wrap && wrap.textContent) {\n // Strip out the select's own rendered text from the label's\n // text content; label.textContent concatenates everything.\n const txt = wrap.textContent\n .replace(select.textContent ?? \"\", \"\")\n .trim();\n if (txt) return txt;\n }\n const aria = select.getAttribute(\"aria-label\");\n if (aria) return aria;\n const name = select.getAttribute(\"name\");\n if (name) return name;\n return \"Select an option\";\n}\n\nfunction pageOfValue(\n current: string,\n options: HTMLOptionElement[],\n pageSize: number,\n): number {\n const idx = options.findIndex((o) => o.value === current);\n if (idx < 0) return 0;\n return Math.floor(idx / pageSize);\n}\n\nfunction cssEscapeLocal(s: string): string {\n if (typeof CSS !== \"undefined\" && typeof (CSS as { escape?: (s: string) => string }).escape === \"function\") {\n return (CSS as { escape: (s: string) => string }).escape(s);\n }\n return s.replace(/[^a-zA-Z0-9_-]/g, \"\\\\$&\");\n}\n\n// All overlay styling is in the shadow root, so it cannot collide\n// with the host page's CSS and the host page cannot override it\n// without explicitly piercing the shadow boundary. Sized for thumb\n// + virtual-cursor accuracy: every interactive element is at least\n// 56 px tall and 44 px wide.\nconst OVERLAY_CSS = `\n :host {\n all: initial;\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n color: #0f172a;\n }\n * { box-sizing: border-box; }\n .backdrop {\n position: fixed;\n inset: 0;\n background: rgba(15, 23, 42, 0.55);\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 24px;\n }\n .panel {\n width: min(440px, 100%);\n max-height: 88vh;\n background: #ffffff;\n border-radius: 20px;\n overflow: hidden;\n display: flex;\n flex-direction: column;\n box-shadow: 0 24px 56px rgba(15, 23, 42, 0.32);\n }\n .header {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 18px 20px;\n border-bottom: 1px solid #e2e8f0;\n }\n .title {\n flex: 1;\n font-size: 18px;\n font-weight: 700;\n color: #0f172a;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n .close {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n border: 1px solid #e2e8f0;\n background: #f1f5f9;\n color: #475569;\n font-size: 18px;\n font-weight: 700;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .close:hover { background: #e2e8f0; }\n .options-wrap {\n display: flex;\n flex-direction: column;\n overflow: hidden;\n }\n .page-btn {\n width: 100%;\n padding: 18px 20px;\n border: none;\n background: #f8fafc;\n color: #475569;\n font-size: 15px;\n font-weight: 600;\n cursor: pointer;\n border-bottom: 1px solid #e2e8f0;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n }\n .page-btn .chev { font-size: 13px; opacity: 0.8; }\n .page-btn:hover { background: #f1f5f9; color: #1e293b; }\n .page-btn[disabled] {\n opacity: 0.35;\n cursor: default;\n background: #f8fafc;\n color: #475569;\n }\n .options-list {\n display: flex;\n flex-direction: column;\n overflow-y: auto;\n }\n .option {\n appearance: none;\n width: 100%;\n padding: 18px 20px;\n border: none;\n background: #ffffff;\n color: #0f172a;\n font-size: 16px;\n font-weight: 500;\n text-align: left;\n cursor: pointer;\n border-bottom: 1px solid #f1f5f9;\n min-height: 60px;\n }\n .option:hover { background: #eff6ff; color: #1d4ed8; }\n .option[data-selected] {\n background: #dbeafe;\n color: #1d4ed8;\n font-weight: 700;\n }\n /* Snap-preview highlight, shared attribute name with the cursor.\n Lives inside the shadow root so the page's selector (if any)\n can't override it. */\n [data-prson-magic-snap] {\n outline: 3px solid #3b82f6;\n outline-offset: -3px;\n background: #eff6ff;\n }\n .option[data-prson-magic-snap] { color: #1d4ed8; }\n`;\n", "/**\n * \"Point your phone at the screen\" overlay shown when the wallet's\n * magic wand emits a `hide` event (the phone is in a non-pointing\n * pose). The visual signals to the user that the cursor is paused\n * and what to do to resume it.\n *\n * Design:\n * * Full-viewport, fixed-position shadow-DOM container \u2014 page\n * stylesheets cannot leak in.\n * * A soft inner blue glow on the viewport edge (inset box-shadow\n * + a thin border) signals \"the page is in remote-control mode,\n * waiting for input\".\n * * A black pill centred in the viewport with the prompt text.\n * * Auto-dismisses on three triggers:\n * 1. Wallet emits the matching `show` event (handled by\n * `bindMouse` directly \u2014 it calls `close()`).\n * 2. The user moves the real (OS) mouse \u2014 `mousemove`\n * listener calls `close()`.\n * 3. 15-second timeout elapses, so a forgotten controller\n * doesn't leave the glow on indefinitely.\n * * `pointer-events: none` on the container so clicks behind it\n * hit the page normally \u2014 the overlay is purely cosmetic.\n */\n\nimport { cspStyleNonce } from \"./csp.js\";\n\ninterface OverlayHandle {\n host: HTMLElement;\n close: () => void;\n}\n\nlet active: OverlayHandle | null = null;\n\n/** True when the overlay is currently visible. */\nexport function isPointPhoneOverlayActive(): boolean {\n return active !== null;\n}\n\n/** Close any active overlay. Safe to call from anywhere. */\nexport function closePointPhoneOverlay(): void {\n active?.close();\n}\n\n/**\n * Mount the \"point your phone\" overlay. Replaces any prior overlay\n * so re-firing `hide` while one is up is a no-op visually.\n *\n * Returns the handle so the caller can close it programmatically;\n * the overlay also self-closes on real mouse movement or after the\n * 15-second timeout.\n */\nexport function openPointPhoneOverlay(): OverlayHandle {\n if (active) return active;\n\n const host = document.createElement(\"div\");\n host.setAttribute(\"data-prson-point-phone-overlay\", \"\");\n host.style.position = \"fixed\";\n host.style.inset = \"0\";\n host.style.zIndex = \"2147483645\"; // below the cursor (-1) and below the select overlay (-1)\n host.style.pointerEvents = \"none\";\n document.body.appendChild(host);\n\n const shadow = host.attachShadow({ mode: \"open\" });\n const style = document.createElement(\"style\");\n const nonce = cspStyleNonce();\n if (nonce) style.nonce = nonce;\n style.textContent = OVERLAY_CSS;\n shadow.appendChild(style);\n\n const glow = document.createElement(\"div\");\n glow.className = \"glow\";\n shadow.appendChild(glow);\n\n const pill = document.createElement(\"div\");\n pill.className = \"pill\";\n pill.innerHTML = `\n <span class=\"dot\"></span>\n <span class=\"text\">Point your phone at the screen to use Magic wand</span>\n `;\n shadow.appendChild(pill);\n\n let closed = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n function close(): void {\n if (closed) return;\n closed = true;\n if (timer) clearTimeout(timer);\n window.removeEventListener(\"mousemove\", onRealMouseMove);\n // Tiny fade for polish.\n host.style.transition = \"opacity 180ms ease\";\n host.style.opacity = \"0\";\n setTimeout(() => host.remove(), 200);\n if (active && active.host === host) active = null;\n }\n\n function onRealMouseMove(_e: MouseEvent): void {\n // Any real OS mouse motion \u2192 user is no longer relying on the\n // wand; dismiss so the page doesn't keep nagging.\n close();\n }\n\n window.addEventListener(\"mousemove\", onRealMouseMove);\n timer = setTimeout(close, 15_000);\n\n const handle: OverlayHandle = { host, close };\n active = handle;\n return handle;\n}\n\n// Shadow-DOM CSS. Sized for clear legibility on any host page;\n// values picked to match the blue accent of the virtual cursor +\n// the snap-preview outline so the user reads the overlay as part\n// of the same \"remote control\" UI family.\nconst OVERLAY_CSS = `\n :host { all: initial; }\n * { box-sizing: border-box; }\n /* Inner-glow viewport border. Two stacked inset shadows: the\n wide soft halo + a thin defined edge. */\n .glow {\n position: fixed;\n inset: 0;\n pointer-events: none;\n box-shadow:\n inset 0 0 0 2px rgba(59, 130, 246, 0.75),\n inset 0 0 28px 6px rgba(59, 130, 246, 0.35),\n inset 0 0 80px 24px rgba(59, 130, 246, 0.18);\n animation: prson-glow-pulse 2.4s ease-in-out infinite;\n }\n @keyframes prson-glow-pulse {\n 0%, 100% { opacity: 0.85; }\n 50% { opacity: 1; }\n }\n .pill {\n position: fixed;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n display: flex;\n align-items: center;\n gap: 14px;\n padding: 18px 28px;\n border-radius: 999px;\n background: #0f172a;\n color: #ffffff;\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n font-size: 16px;\n font-weight: 600;\n letter-spacing: 0.1px;\n box-shadow:\n 0 18px 40px rgba(15, 23, 42, 0.45),\n 0 0 0 1px rgba(255, 255, 255, 0.06) inset;\n /* Pulse-fade in so the pill doesn't pop harshly. */\n animation: prson-pill-fade-in 240ms ease-out both;\n }\n @keyframes prson-pill-fade-in {\n from { opacity: 0; transform: translate(-50%, calc(-50% + 6px)); }\n to { opacity: 1; transform: translate(-50%, -50%); }\n }\n .dot {\n width: 10px;\n height: 10px;\n border-radius: 50%;\n background: rgba(59, 130, 246, 1);\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.25);\n animation: prson-dot-pulse 1.4s ease-in-out infinite;\n flex: none;\n }\n @keyframes prson-dot-pulse {\n 0%, 100% { transform: scale(1); opacity: 1; }\n 50% { transform: scale(1.3); opacity: 0.65; }\n }\n .text {\n line-height: 1.25;\n }\n`;\n", "/**\n * DOM binding helpers \u2014 drive a `session.request(...)` from a\n * page's existing form elements.\n *\n * Two entry points:\n *\n * * [`bindInput`] \u2014 for a single `<input>` / `<textarea>` /\n * `<select>` element. Reads the element's `type`, `name`,\n * `placeholder`, `required`, `min`/`max`/`minlength`/`maxlength`\n * /`pattern`, and (for `<select>`) `<option>` children. Returns\n * a controller whose `.request()` method synthesises a single\n * `kind: \"input\"` request and, on a successful wallet reply,\n * writes the value back into the element and dispatches\n * `input` + `change` events so reactive frameworks pick it up.\n *\n * * [`bindForm`] \u2014 for a `<form>` (or any container holding\n * inputs). Walks descendant `<input>`/`<textarea>`/`<select>`\n * elements in document order, synthesises one\n * `kind: \"input-form\"` request carrying every field, opens\n * a single wallet drawer that paginates prev / next / send,\n * fills every element on reply, and (when the bind target is\n * a `<form>`) calls `requestSubmit()` so the page's existing\n * submit handlers fire.\n *\n * Neither helper auto-fires. The host wires the controller's\n * `.request()` to whatever trigger they prefer \u2014 a button click,\n * focus, route change, etc. Keeps the SDK out of UX decisions\n * about WHEN to ask.\n */\n\nimport type { PrsonLoginSession } from \"./session.js\";\nimport {\n closeAllOverlays,\n findNearestClickableInOverlay,\n isSelectOverlayActive,\n openSelectOverlay,\n setOverlaySnap,\n} from \"./select_overlay.js\";\nimport {\n closePointPhoneOverlay,\n openPointPhoneOverlay,\n} from \"./point_phone_overlay.js\";\nimport type {\n InputFormField,\n InputOption,\n InputType,\n LoginRequest,\n LoginResponse,\n RequestOptions,\n} from \"./requests.js\";\n\n// \u2500\u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface BindController {\n /**\n * Synthesise a request from the bound element + send it. Resolves\n * with whatever the wallet replied (already written into the\n * element(s) on success). Multiple concurrent calls share the\n * same controller; the wallet's queue / rate-limit policy\n * decides whether the second one is accepted.\n */\n request(opts?: RequestOptions & { reason?: string }): Promise<LoginResponse>;\n /** Drop any per-bind state. The helpers are stateless today, but\n * the contract is reserved for future expansion (e.g. a\n * focus-triggered auto-bind). */\n dispose(): void;\n}\n\n/**\n * Bind to a single input-shaped element. Accepted nodes:\n *\n * * `<input>` (type \u2208 text/search/email/tel/url/number/password\n * \u2014 falls back to `text` for unsupported types like `date`),\n * * `<textarea>` (treated as a `text` input),\n * * `<select>` (with `<option>` children).\n *\n * The element's `aria-label`, label-for, or closest `<label>` text\n * becomes the wallet's prompt label. `placeholder` rides through.\n * Numeric / pattern constraints become wallet-side validation.\n *\n * Reply: the wallet's `value` is written via `element.value = ...`\n * + `input` + `change` events. For `<select>`, the value is matched\n * against the option `value` attributes.\n */\nexport function bindInput(\n session: PrsonLoginSession,\n element: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,\n): BindController {\n return {\n async request(opts) {\n // Passwords and one-time codes never cross the live channel, in\n // either direction: whoever holds the phone end may not be the\n // person at this screen (see isSensitiveField).\n if (isSensitiveField(element)) return { ok: false, error: \"unsupported\" } as LoginResponse;\n const req = inputRequestFromElement(element, opts?.reason);\n const reply = await session.request(req, opts);\n if (reply.ok) writeValueIntoElement(element, reply.value);\n return reply;\n },\n dispose() {/* no-op for now */},\n };\n}\n\n/**\n * Bind to a `<form>` or any container element. Walks descendant\n * input-shaped elements in document order, sends ONE\n * `kind: \"input-form\"` request, and on reply fills every matching\n * field + dispatches events.\n *\n * Field name resolution:\n *\n * 1. `element.name` \u2014 the canonical key.\n * 2. `element.id` \u2014 fallback for label-less inputs.\n * 3. `_field_<index>` \u2014 synthetic fallback so the reply still\n * finds its target.\n *\n * If the bound container IS a `<form>`, a successful reply also\n * fires `form.requestSubmit()` so the host's existing submit\n * handler picks up. Containers that aren't forms skip the submit\n * step.\n *\n * Buttons/checkboxes/hidden inputs are ignored on purpose \u2014 they\n * don't fit the kiosk-input shape and confuse the wallet drawer.\n */\nexport function bindForm(\n session: PrsonLoginSession,\n container: HTMLElement,\n): BindController {\n return {\n async request(opts) {\n const elements = collectFieldElements(container);\n if (elements.length === 0) {\n return {\n ok: false,\n error: \"unsupported\",\n } as LoginResponse;\n }\n // Single-element shortcut \u2014 friendlier UX (one focused drawer,\n // smaller envelope) than wrapping a lone input in an input-form.\n if (elements.length === 1) {\n const reply = await session.request(\n inputRequestFromElement(elements[0]!, opts?.reason),\n opts,\n );\n if (reply.ok) writeValueIntoElement(elements[0]!, reply.value);\n if (reply.ok && container instanceof HTMLFormElement) {\n tryRequestSubmit(container);\n }\n return reply;\n }\n const fields = elements.map((el, i) => fieldFromElement(el, i));\n const req: LoginRequest = {\n kind: \"input-form\",\n fields,\n submitLabel: container instanceof HTMLFormElement ? \"Send\" : \"Done\",\n reason: opts?.reason,\n };\n const reply = await session.request(req, opts);\n if (reply.ok && reply.value && typeof reply.value === \"object\") {\n const values = reply.value as Record<string, unknown>;\n for (const el of elements) {\n const name = nameForElement(el, elements.indexOf(el));\n if (name in values) writeValueIntoElement(el, values[name]);\n }\n if (container instanceof HTMLFormElement) tryRequestSubmit(container);\n }\n return reply;\n },\n dispose() {/* no-op */},\n };\n}\n\n// \u2500\u2500\u2500 DOM \u2192 request synthesis \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction inputRequestFromElement(\n el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,\n reason: string | undefined,\n): LoginRequest {\n if (el instanceof HTMLSelectElement) {\n return {\n kind: \"input\",\n inputType: \"select\",\n label: resolveLabel(el),\n options: readOptions(el),\n defaultValue: el.value || undefined,\n required: el.required,\n reason,\n };\n }\n const inputType = resolveInputType(el);\n const base = {\n kind: \"input\" as const,\n inputType,\n label: resolveLabel(el),\n placeholder: el.placeholder || undefined,\n defaultValue: el.value || undefined,\n required: el instanceof HTMLInputElement ? el.required : false,\n reason,\n };\n return {\n ...base,\n ...textConstraints(el),\n ...(el instanceof HTMLInputElement && inputType === \"number\"\n ? numericConstraints(el)\n : {}),\n ...(el instanceof HTMLInputElement && el.pattern\n ? { pattern: el.pattern }\n : {}),\n };\n}\n\nfunction fieldFromElement(\n el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,\n index: number,\n): InputFormField {\n const name = nameForElement(el, index);\n if (el instanceof HTMLSelectElement) {\n return {\n name,\n inputType: \"select\",\n label: resolveLabel(el),\n options: readOptions(el),\n defaultValue: el.value || undefined,\n required: el.required,\n };\n }\n const inputType = resolveInputType(el);\n return {\n name,\n inputType,\n label: resolveLabel(el),\n placeholder: el.placeholder || undefined,\n defaultValue: el.value || undefined,\n required: el instanceof HTMLInputElement ? el.required : false,\n ...textConstraints(el),\n ...(el instanceof HTMLInputElement && inputType === \"number\"\n ? numericConstraints(el)\n : {}),\n ...(el instanceof HTMLInputElement && el.pattern\n ? { pattern: el.pattern }\n : {}),\n };\n}\n\nfunction collectFieldElements(\n container: HTMLElement,\n): Array<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement> {\n const out: Array<\n HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement\n > = [];\n const all = container.querySelectorAll<HTMLElement>(\n \"input, textarea, select\",\n );\n // Filter: skip non-bindable inputs (button, submit, hidden,\n // checkbox, radio, file). Those don't map to the kiosk pattern\n // and would confuse the drawer's prev/next navigation.\n const SKIPPED = new Set([\n \"button\",\n \"submit\",\n \"reset\",\n \"image\",\n \"hidden\",\n \"file\",\n \"checkbox\",\n \"radio\",\n ]);\n for (let i = 0; i < all.length; i++) {\n const el = all[i]!;\n if (isSensitiveField(el)) continue; // passwords / one-time codes stay on this page\n if (el instanceof HTMLInputElement) {\n const t = (el.type || \"text\").toLowerCase();\n if (SKIPPED.has(t)) continue;\n if (el.disabled || el.readOnly) continue;\n out.push(el);\n } else if (el instanceof HTMLTextAreaElement) {\n if (el.disabled || el.readOnly) continue;\n out.push(el);\n } else if (el instanceof HTMLSelectElement) {\n if (el.disabled) continue;\n out.push(el);\n }\n }\n return out;\n}\n\n/**\n * Fields whose value must never travel over the live channel: password\n * inputs and anything marked `autocomplete` current-password /\n * new-password / one-time-code. Anyone who scans a sign-in code first\n * holds the phone end of the channel, so the SDK neither mirrors these\n * values to the phone nor lets the phone fill them: bindInput refuses,\n * bindForm and remote navigation skip them.\n */\nexport function isSensitiveField(el: Element): boolean {\n const tokens = (el.getAttribute(\"autocomplete\") ?? \"\").toLowerCase().split(/\\s+/);\n if (tokens.some((t) => t === \"current-password\" || t === \"new-password\" || t === \"one-time-code\")) return true;\n if (typeof HTMLInputElement !== \"undefined\" && el instanceof HTMLInputElement) {\n return (el.type || \"text\").toLowerCase() === \"password\";\n }\n return (el.getAttribute(\"type\") ?? \"\").toLowerCase() === \"password\";\n}\n\nfunction resolveInputType(\n el: HTMLInputElement | HTMLTextAreaElement,\n): Exclude<InputType, \"select\"> {\n if (el instanceof HTMLTextAreaElement) return \"text\";\n const t = (el.type || \"text\").toLowerCase();\n switch (t) {\n case \"text\":\n case \"search\":\n case \"email\":\n case \"tel\":\n case \"url\":\n case \"number\":\n case \"password\":\n return t as Exclude<InputType, \"select\">;\n // HTML5 types we don't have a wallet-side keyboard for \u2014 fall\n // back to `text` so the drawer still renders something useful.\n case \"date\":\n case \"datetime-local\":\n case \"time\":\n case \"month\":\n case \"week\":\n case \"color\":\n case \"range\":\n default:\n return \"text\";\n }\n}\n\nfunction resolveLabel(\n el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | HTMLButtonElement,\n): string {\n // Priority: aria-label > <label for> > parent <label> text >\n // placeholder > name > tag-name.\n const aria = el.getAttribute(\"aria-label\");\n if (aria && aria.trim()) return aria.trim();\n if (el.id) {\n const lbl = el.ownerDocument.querySelector<HTMLLabelElement>(\n `label[for=\"${cssEscape(el.id)}\"]`,\n );\n if (lbl && lbl.textContent && lbl.textContent.trim()) {\n return lbl.textContent.trim();\n }\n }\n const closestLabel = el.closest(\"label\");\n if (closestLabel && closestLabel.textContent) {\n // Strip the input's own text content from the label string\n // so a wrapping `<label>Email <input></label>` doesn't include\n // the input's value.\n const ownText =\n \"value\" in el && typeof (el as { value?: unknown }).value === \"string\"\n ? (el as { value: string }).value\n : (el.textContent ?? \"\");\n const raw = closestLabel.textContent.replace(ownText, \"\").trim();\n if (raw) return raw;\n }\n if (\n \"placeholder\" in el &&\n (el as HTMLInputElement).placeholder &&\n (el as HTMLInputElement).placeholder.trim()\n ) {\n return (el as HTMLInputElement).placeholder.trim();\n }\n if (el.name) return prettyName(el.name);\n return prettyName(el.tagName.toLowerCase());\n}\n\nfunction readOptions(el: HTMLSelectElement): InputOption[] {\n const out: InputOption[] = [];\n for (let i = 0; i < el.options.length; i++) {\n const opt = el.options[i]!;\n out.push({\n value: opt.value,\n label: opt.label || opt.textContent || opt.value,\n });\n }\n return out;\n}\n\nfunction textConstraints(\n el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,\n): { minLength?: number; maxLength?: number } {\n const out: { minLength?: number; maxLength?: number } = {};\n if (\"minLength\" in el && el.minLength > 0) out.minLength = el.minLength;\n if (\"maxLength\" in el && el.maxLength > 0) out.maxLength = el.maxLength;\n return out;\n}\n\nfunction numericConstraints(\n el: HTMLInputElement,\n): { min?: number; max?: number } {\n const out: { min?: number; max?: number } = {};\n const minStr = el.getAttribute(\"min\");\n const maxStr = el.getAttribute(\"max\");\n if (minStr !== null && minStr !== \"\") {\n const n = Number(minStr);\n if (Number.isFinite(n)) out.min = n;\n }\n if (maxStr !== null && maxStr !== \"\") {\n const n = Number(maxStr);\n if (Number.isFinite(n)) out.max = n;\n }\n return out;\n}\n\nfunction nameForElement(\n el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | HTMLButtonElement,\n index: number,\n): string {\n if (el.name) return el.name;\n if (el.id) return el.id;\n return `_field_${index}`;\n}\n\nfunction prettyName(s: string): string {\n return s.replace(/[_-]+/g, \" \").replace(/\\s+/g, \" \").trim();\n}\n\n// \u2500\u2500\u2500 Byte / encoding helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Decode a base64url-padded chunk string into a fresh `Uint8Array`.\n * Returns null on bad input so the receiver can drop the envelope\n * without crashing. Used by the file-transfer reassembly path \u2014\n * each chunk is decoded once, written into the per-transfer\n * `Uint8Array[]` slot, and the source string is dropped.\n */\nfunction b64uToBytes(s: string): Uint8Array | null {\n // Normalise to standard base64 with padding so `atob` accepts it.\n const pad = (4 - (s.length % 4)) % 4;\n const std = (s + \"=\".repeat(pad)).replace(/-/g, \"+\").replace(/_/g, \"/\");\n try {\n const bin = atob(std);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n } catch {\n return null;\n }\n}\n\n/** Hex-encode a Uint8Array (lowercase, no separators). */\nfunction bytesToHex(b: Uint8Array): string {\n let s = \"\";\n for (let i = 0; i < b.length; i++) s += b[i]!.toString(16).padStart(2, \"0\");\n return s;\n}\n\n// \u2500\u2500\u2500 Reply \u2192 DOM \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction writeValueIntoElement(\n el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,\n value: unknown,\n): void {\n if (value === undefined || value === null) return;\n const str = String(value);\n if (el instanceof HTMLSelectElement) {\n // Match by value first, then by visible label.\n let matched = false;\n for (let i = 0; i < el.options.length; i++) {\n if (el.options[i]!.value === str) {\n el.selectedIndex = i;\n matched = true;\n break;\n }\n }\n if (!matched) {\n for (let i = 0; i < el.options.length; i++) {\n if (el.options[i]!.label === str) {\n el.selectedIndex = i;\n break;\n }\n }\n }\n } else {\n el.value = str;\n }\n // Reactive frameworks (React, Vue, etc.) listen for `input` /\n // `change` to pick up the new value. Dispatch both so we don't\n // miss either bucket.\n el.dispatchEvent(new Event(\"input\", { bubbles: true }));\n el.dispatchEvent(new Event(\"change\", { bubbles: true }));\n}\n\nfunction tryRequestSubmit(form: HTMLFormElement): void {\n // `requestSubmit` runs the form's existing submit handler +\n // validation; `submit` skips both. Always prefer\n // `requestSubmit` when available \u2014 guards against pre-2020\n // browsers via the typeof check.\n if (typeof form.requestSubmit === \"function\") {\n form.requestSubmit();\n } else {\n form.submit();\n }\n}\n\n// \u2500\u2500\u2500 Remote navigation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface RemoteNavController {\n /**\n * Stop pushing focus events to the wallet + stop listening for\n * inbound nav/value/logout commands. The session itself stays\n * live; only the helper detaches.\n */\n dispose(): void;\n}\n\nexport interface RemoteNavOptions {\n /**\n * Root to scan for tabbable inputs. Defaults to `document.body`.\n * Limit to a region (e.g. a checkout form) if the page has\n * unrelated inputs you don't want the wallet to step through.\n */\n root?: HTMLElement;\n /**\n * Override the default tab order. By default we use a generous\n * `:is(input, textarea, select)` filter excluding hidden / disabled\n * / readonly / type=hidden / type=submit. Return your own\n * NodeList-like array to take full control.\n */\n collectFields?: () => Array<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>;\n}\n\n/**\n * Wire up **remote navigation**. Pushes the page's currently-focused\n * input to the wallet (metadata + current value) and applies inbound\n * `nav` / `value` / `logout` commands as the user interacts with the\n * wallet's persistent navigation banner.\n *\n * Wiring summary:\n *\n * * `focusin` on any tabbable input \u2192 `session._sendFocus(focus)`.\n * * `focusout` on the same \u2192 `session._sendFocus(null)`.\n * * `input` on the focused element \u2192 push the new value to the\n * wallet so the phone mirror stays in sync if the user typed on\n * the desktop. Debounced to one frame to avoid flooding.\n * * Inbound `nav: \"prev\" | \"next\"` \u2192 move DOM focus along the\n * tabbable-input order from the focused element.\n * * Inbound `nav: \"submit\"` \u2192 `form.requestSubmit()` on the closest\n * enclosing form.\n * * Inbound `value` \u2192 write to the focused element + dispatch\n * `input` + `change`. Reactive frameworks pick it up.\n * * Inbound `logout` \u2192 session already torn down by the dispatcher;\n * helper just detaches.\n *\n * Call this once after `signIn()` resolves when you passed\n * `remoteNavigation: true`. The returned controller's `dispose()` is\n * idempotent and runs on `signed_out` automatically.\n */\nexport function enableRemoteNavigation(\n session: PrsonLoginSession,\n opts?: RemoteNavOptions,\n): RemoteNavController {\n const root = opts?.root ?? document.body;\n let currentFocused:\n | HTMLInputElement\n | HTMLTextAreaElement\n | HTMLSelectElement\n | HTMLButtonElement\n | null = null;\n let disposed = false;\n\n function isBindable(\n el: Element,\n ): el is HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement {\n // Passwords and one-time codes are never mirrored to the phone.\n if (isSensitiveField(el)) return false;\n if (el instanceof HTMLInputElement) {\n const t = (el.type || \"text\").toLowerCase();\n if (\n t === \"hidden\" || t === \"submit\" || t === \"button\" ||\n t === \"reset\" || t === \"image\" ||\n t === \"checkbox\" || t === \"radio\"\n ) return false;\n // `type=\"file\"` IS bindable \u2014 the wallet shows a picker UI\n // and streams the chosen bytes back. Handled by the\n // file-transfer reassembly path in `_handleMessage`; the\n // `readOnly` check below doesn't apply (file inputs ignore\n // it but expose the property as `false` regardless).\n if (t === \"file\") return !el.disabled;\n return !el.disabled && !el.readOnly;\n }\n if (el instanceof HTMLTextAreaElement) {\n return !el.disabled && !el.readOnly;\n }\n if (el instanceof HTMLSelectElement) {\n return !el.disabled;\n }\n return false;\n }\n\n /** Buttons + button-type inputs. Tracked separately from\n * [isBindable] so prev/next navigation only walks the\n * input-like pool, but focus envelopes still fire for buttons\n * (so the wallet can show the Enter row). */\n function isFocusableButton(\n el: Element,\n ): el is HTMLButtonElement | HTMLInputElement {\n if (el instanceof HTMLButtonElement) return !el.disabled;\n if (el instanceof HTMLInputElement) {\n const t = (el.type || \"text\").toLowerCase();\n return (t === \"submit\" || t === \"button\" || t === \"reset\") && !el.disabled;\n }\n return el.getAttribute(\"role\") === \"button\";\n }\n\n function collectFields(): Array<\n HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement\n > {\n if (opts?.collectFields) return opts.collectFields().filter((el) => !isSensitiveField(el));\n const out: Array<\n HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement\n > = [];\n const all = root.querySelectorAll<HTMLElement>(\"input, textarea, select\");\n for (let i = 0; i < all.length; i++) {\n const el = all[i]!;\n if (isBindable(el)) out.push(el);\n }\n return out;\n }\n\n /**\n * Compute the prev / next / submit / enter visibility hints the\n * wallet's banner drawer needs to render only the buttons that\n * make sense for the page's current state.\n *\n * Rules (mirrored on the wallet \u2014 see `_navigationRow`):\n *\n * * `hasPrev` \u2014 there's at least one bindable input *before*\n * this one in the tabbing pool.\n * * `hasNext` \u2014 there's at least one bindable input *after*\n * this one.\n * * `isLastInForm`\u2014 this element is the last bindable input\n * inside its enclosing `<form>`. Mutually\n * exclusive with `hasNext` when the form\n * ends the bindable pool; only true for input-\n * like elements, never for buttons.\n * * `isButton` \u2014 the focused element is a click target\n * (`<button>`, `<input type=submit|button>`,\n * `role=\"button\"`). The wallet shows an\n * \"Enter\" button that dispatches `nav: \"submit\"`,\n * and the helper here treats that action as a\n * synthetic click rather than a form submit.\n */\n function computeNavMeta(\n el: Element,\n ): { hasPrev: boolean; hasNext: boolean; isLastInForm: boolean; isButton: boolean } {\n const isButton =\n el instanceof HTMLButtonElement ||\n (el instanceof HTMLInputElement &&\n (el.type === \"submit\" || el.type === \"button\" || el.type === \"reset\")) ||\n el.getAttribute(\"role\") === \"button\";\n if (isButton) {\n // A focused button has no concept of \"prev/next input\" \u2014 the\n // wallet hides those rows entirely and shows just Enter.\n return { hasPrev: false, hasNext: false, isLastInForm: false, isButton: true };\n }\n const fields = collectFields();\n const idx = fields.indexOf(el as HTMLInputElement);\n const hasPrev = idx > 0;\n const hasNext = idx >= 0 && idx < fields.length - 1;\n let isLastInForm = false;\n const form = (el as HTMLElement).closest?.(\"form\");\n if (form instanceof HTMLFormElement) {\n const fieldsInForm = fields.filter((f) => f.closest(\"form\") === form);\n isLastInForm =\n fieldsInForm.length > 0 &&\n fieldsInForm[fieldsInForm.length - 1] === el;\n }\n return { hasPrev, hasNext, isLastInForm, isButton: false };\n }\n\n function focusPayloadFor(\n el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | HTMLButtonElement,\n ): Parameters<PrsonLoginSession[\"_sendFocus\"]>[0] {\n const name = nameForElement(el, 0);\n const meta = computeNavMeta(el);\n if (el instanceof HTMLButtonElement || (el instanceof HTMLInputElement &&\n (el.type === \"submit\" || el.type === \"button\" || el.type === \"reset\"))) {\n // Button focus \u2014 the wallet renders just the Enter row.\n return {\n name,\n label: resolveLabel(el),\n inputType: \"button\",\n value: el instanceof HTMLButtonElement ? (el.textContent ?? \"\").trim() : (el as HTMLInputElement).value,\n ...meta,\n };\n }\n if (el instanceof HTMLSelectElement) {\n return {\n name,\n label: resolveLabel(el),\n inputType: \"select\",\n value: el.value,\n options: readOptions(el),\n required: el.required,\n ...meta,\n };\n }\n if (el instanceof HTMLInputElement && el.type === \"file\") {\n // File picker: surface `accept` / `multiple` / `capture` so the\n // wallet UI can render the right entry points (camera vs\n // gallery vs files) and validate the user's pick against the\n // host's MIME filter. Value stays empty \u2014 we don't try to\n // mirror the picked-file metadata back as text.\n return {\n name,\n label: resolveLabel(el),\n inputType: \"file\",\n value: \"\",\n required: el.required,\n accept: el.accept || undefined,\n multiple: el.multiple || undefined,\n capture: el.getAttribute(\"capture\") || undefined,\n ...meta,\n };\n }\n const inputType = resolveInputType(el);\n return {\n name,\n label: resolveLabel(el),\n inputType,\n value: el.value,\n placeholder:\n \"placeholder\" in el ? (el as HTMLInputElement).placeholder || undefined : undefined,\n required: el instanceof HTMLInputElement ? el.required : false,\n ...textConstraints(el),\n ...(el instanceof HTMLInputElement && inputType === \"number\"\n ? numericConstraints(el)\n : {}),\n ...(el instanceof HTMLInputElement && el.pattern\n ? { pattern: el.pattern }\n : {}),\n ...meta,\n };\n }\n\n // Debounced \"current value changed locally\" notifier \u2014 keeps the\n // wallet mirror in sync if the user types on the desktop while the\n // wallet drawer is open. requestAnimationFrame caps push rate\n // at ~60 Hz which is well below the wallet's processing budget.\n let pendingFrame: number | null = null;\n function scheduleValuePush() {\n if (pendingFrame !== null) return;\n pendingFrame = requestAnimationFrame(() => {\n pendingFrame = null;\n if (disposed || !currentFocused) return;\n void session._sendFocus(focusPayloadFor(currentFocused));\n });\n }\n\n function onFocusIn(ev: Event) {\n const t = ev.target;\n if (!(t instanceof Element)) return;\n if (isSensitiveField(t)) {\n // Focus moved to a password / one-time code: clear the phone's\n // mirror, and don't let a `value` from the phone land here.\n if (currentFocused) void session._sendFocus(null);\n currentFocused = null;\n return;\n }\n if (isBindable(t)) {\n currentFocused = t;\n void session._sendFocus(focusPayloadFor(t));\n return;\n }\n if (isFocusableButton(t)) {\n currentFocused = t as HTMLButtonElement | HTMLInputElement;\n void session._sendFocus(focusPayloadFor(t as HTMLButtonElement));\n }\n }\n\n function onFocusOut(ev: Event) {\n const t = ev.target;\n if (t !== currentFocused) return;\n currentFocused = null;\n void session._sendFocus(null);\n }\n\n function onInputChange(ev: Event) {\n if (ev.target !== currentFocused) return;\n scheduleValuePush();\n }\n\n function applyNav(action: \"prev\" | \"next\" | \"submit\") {\n if (action === \"submit\") {\n // Two semantics on one wire action:\n //\n // * focused element IS a button \u2192 click it. Wallet shows\n // this as \"Enter\" when [isButton: true] in the focus\n // envelope, and the user expects pressing it on the\n // phone to fire the button's click handler.\n // * else \u2192 submit the enclosing form. Wallet shows this as\n // \"Submit\" when [isLastInForm: true].\n //\n // We use one nav action for both so the wire grammar stays\n // narrow; the contextual UX is decided on the wallet side\n // (different label / icon) and the dispatch routes correctly\n // by inspecting `currentFocused`.\n const focused = currentFocused;\n if (\n focused instanceof HTMLButtonElement ||\n (focused instanceof HTMLInputElement &&\n (focused.type === \"submit\" ||\n focused.type === \"button\" ||\n focused.type === \"reset\")) ||\n focused?.getAttribute(\"role\") === \"button\"\n ) {\n try {\n (focused as HTMLElement).click();\n } catch {\n /* swallow */\n }\n return;\n }\n const form =\n currentFocused?.closest(\"form\") ?? root.querySelector(\"form\");\n if (form instanceof HTMLFormElement) tryRequestSubmit(form);\n return;\n }\n const fields = collectFields();\n if (fields.length === 0) return;\n let idx = currentFocused ? fields.indexOf(currentFocused as never) : -1;\n if (idx === -1) idx = action === \"prev\" ? fields.length : -1;\n const target =\n action === \"next\"\n ? fields[(idx + 1) % fields.length]!\n : fields[(idx - 1 + fields.length) % fields.length]!;\n target.focus();\n if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {\n const len = target.value.length;\n try { target.setSelectionRange(len, len); } catch { /* select-type inputs don't support it */ }\n }\n }\n\n function applyValue(value: string) {\n if (!currentFocused || isSensitiveField(currentFocused)) return;\n // Value pushes only make sense for input-like fields. If a\n // button is focused (no editable value) just drop the push.\n if (\n currentFocused instanceof HTMLInputElement ||\n currentFocused instanceof HTMLTextAreaElement ||\n currentFocused instanceof HTMLSelectElement\n ) {\n writeValueIntoElement(currentFocused, value);\n }\n }\n\n const unsubscribe = session._setRemoteNavListener((envelope) => {\n if (envelope.msg === \"nav\") applyNav(envelope.action);\n else if (envelope.msg === \"value\") applyValue(envelope.value);\n else if (envelope.msg === \"logout\") dispose();\n });\n\n // \u2500\u2500 File-transfer reassembly \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n //\n // The wallet streams chunks for a chosen file as a sequence of\n // `file-begin` \u2192 N \u00D7 `file-chunk` \u2192 `file-end` envelopes,\n // correlated by `requestId`. We keep ONE pending transfer per id\n // and never materialise the whole file as a contiguous buffer \u2014\n // each chunk's bytes go straight onto an Array<Uint8Array>; the\n // final assembly is `new Blob(parts)` which the browser doesn't\n // copy. The SHA-256 verifier runs incrementally over the same\n // Uint8Array references via WebCrypto's `crypto.subtle.digest`\n // on the assembled Blob's ArrayBuffer (single allocation only at\n // the verify-then-discard moment).\n //\n // Memory profile (per in-flight transfer): ~`size` bytes total\n // (the Uint8Arrays for chunks), plus an Array<Uint8Array> header.\n // No double buffering, no string-side base64 retained beyond\n // each chunk's decode-then-drop cycle.\n interface PendingTransfer {\n name: string;\n mimeType: string;\n size: number;\n totalChunks: number;\n received: number;\n parts: Uint8Array[];\n targetInput: HTMLInputElement | null;\n }\n const transfers = new Map<string, PendingTransfer>();\n\n const offFile = session._setFileEnvelopeHandler((envelope) => {\n const reqId = envelope.requestId;\n if (!reqId) return;\n if (envelope.msg === \"file-begin\") {\n const begin = envelope.fileBegin;\n if (!begin) return;\n // Resolve the target input AT BEGIN time so a focusout that\n // races the transfer doesn't leave us assigning to a\n // disposed element.\n const target =\n currentFocused instanceof HTMLInputElement && currentFocused.type === \"file\"\n ? currentFocused\n : null;\n transfers.set(reqId, {\n name: begin.name,\n mimeType: begin.mimeType,\n size: begin.size,\n totalChunks: begin.totalChunks,\n received: 0,\n parts: new Array<Uint8Array>(begin.totalChunks),\n targetInput: target,\n });\n return;\n }\n if (envelope.msg === \"file-chunk\") {\n const xfer = transfers.get(reqId);\n const chunk = envelope.fileChunk;\n if (!xfer || !chunk) return;\n const bytes = b64uToBytes(chunk.data);\n if (!bytes) return;\n // Slot the chunk in by index \u2014 chunks arrive in order through\n // the ack-tracked layer but indexing defensively keeps the\n // contract obvious to a reader (and would survive a future\n // sliding-window sender).\n xfer.parts[chunk.index] = bytes;\n xfer.received += 1;\n return;\n }\n if (envelope.msg === \"file-end\") {\n const xfer = transfers.get(reqId);\n const end = envelope.fileEnd;\n if (!xfer || !end) return;\n transfers.delete(reqId);\n void assembleAndCommit(xfer, end.sha256);\n return;\n }\n });\n\n async function assembleAndCommit(\n xfer: PendingTransfer,\n expectedSha256Hex: string,\n ): Promise<void> {\n if (xfer.received !== xfer.totalChunks) return;\n // Blob does NOT copy its parts; this is the only assembly step.\n // The `as unknown as BlobPart[]` cast sidesteps an over-strict\n // type definition where `Uint8Array<ArrayBufferLike>` is not\n // recognised as `BlobPart` even though it always is at runtime.\n const blob = new Blob(xfer.parts as unknown as BlobPart[], { type: xfer.mimeType });\n // Verify SHA-256. `crypto.subtle.digest` runs over the Blob's\n // ArrayBuffer \u2014 one transient allocation, then the buffer is\n // released back to the GC.\n const buf = await blob.arrayBuffer();\n const digestBuf = await crypto.subtle.digest(\"SHA-256\", buf);\n const actual = bytesToHex(new Uint8Array(digestBuf));\n if (actual !== expectedSha256Hex.toLowerCase()) {\n // Hash mismatch \u2014 drop silently. A future revision can\n // surface this to the host via an event; today the wallet's\n // ack-tracked retransmit covers the common error case (a\n // dropped chunk).\n return;\n }\n const target = xfer.targetInput;\n if (!target || disposed) return;\n const file = new File([blob], xfer.name, {\n type: xfer.mimeType,\n lastModified: Date.now(),\n });\n // `HTMLInputElement.files` is read-only by default \u2014 the\n // standard idiom is to build a `DataTransfer`, attach the\n // file(s), and assign the `.files` reference.\n try {\n const dt = new DataTransfer();\n dt.items.add(file);\n target.files = dt.files;\n } catch {\n // Browsers without `DataTransfer` (very old) can't accept a\n // programmatic file. Nothing else we can do.\n return;\n }\n // Dispatch `input` + `change` so reactive frameworks pick the\n // selection up. Bubbles + cancelable matches the native\n // dispatch profile.\n target.dispatchEvent(new Event(\"input\", { bubbles: true }));\n target.dispatchEvent(new Event(\"change\", { bubbles: true }));\n }\n\n // `signed_out` cleanup \u2014 the dispatcher's `logout` case also tears\n // the session down; this catches every other terminal path (TTL,\n // wallet-side revoke, transport loss).\n const offSignedOut = session.on(\"signed_out\", () => dispose());\n\n root.addEventListener(\"focusin\", onFocusIn, true);\n root.addEventListener(\"focusout\", onFocusOut, true);\n root.addEventListener(\"input\", onInputChange, true);\n root.addEventListener(\"change\", onInputChange, true);\n\n function dispose() {\n if (disposed) return;\n disposed = true;\n if (pendingFrame !== null) cancelAnimationFrame(pendingFrame);\n pendingFrame = null;\n root.removeEventListener(\"focusin\", onFocusIn, true);\n root.removeEventListener(\"focusout\", onFocusOut, true);\n root.removeEventListener(\"input\", onInputChange, true);\n root.removeEventListener(\"change\", onInputChange, true);\n unsubscribe();\n offFile();\n offSignedOut();\n transfers.clear();\n }\n\n return { dispose };\n}\n\n// \u2500\u2500\u2500 Mouse / virtual cursor \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Options for [`bindMouse`].\n */\nexport interface BindMouseOptions extends RequestOptions {\n /**\n * Input mode the wallet should default to. The wallet UI may still\n * surface a toggle to switch mid-session \u2014 frames received then\n * carry the actual mode in `mouse.mode`. Defaults to `\"touch\"`.\n */\n mode?: \"touch\" | \"magic\";\n /** Cursor diameter in CSS pixels. Default 28. */\n size?: number;\n /**\n * Cursor background colour (any CSS colour). Default a translucent\n * blue that's visible on both light and dark pages.\n */\n color?: string;\n /**\n * Optional reason shown in the wallet drawer (\"Tap to control the\n * page\", etc.).\n */\n reason?: string;\n /**\n * Initial cursor position. Defaults to viewport centre. Pass\n * `{ x: 0, y: 0 }` to anchor in the top-left.\n */\n initialPosition?: { x: number; y: number };\n /**\n * Optional callback fired on every applied frame. Useful for\n * sites that want to highlight the hovered element or show a\n * trail. Receives the cursor's new viewport coordinates.\n */\n onMove?: (pos: { x: number; y: number }) => void;\n /**\n * Optional click handler \u2014 receives the element under the cursor\n * at the moment of the click. The default behaviour (dispatching\n * a synthetic `click` event on that element) still runs unless\n * the callback returns `false`.\n */\n onClick?: (target: Element | null) => void | boolean;\n}\n\n/**\n * Bind a virtual mouse to the session. Opens a `kind: \"mouse\"`\n * request on the wallet, then subscribes to the streamed\n * `mouse-update` envelopes and applies them to a CSS-positioned\n * cursor on top of the page.\n *\n * Two modes (the wallet may toggle them mid-session):\n *\n * * `\"touch\"` \u2014 the phone is a touchpad. Drag = move (delta in\n * CSS px), tap = click, double-tap = double-click, two-finger\n * drag = scroll.\n * * `\"magic\"` \u2014 phone gyro + accelerometer drive a \"magic wand\".\n * Tap on the phone = click; swipe up/down = scroll.\n *\n * The cursor is a `<div>` fixed-positioned at z-index `2147483647`\n * (the max 32-bit signed int \u2014 same trick browser extension\n * overlays use to outrank page chrome). `pointer-events: none` so\n * it never intercepts real clicks; we use `elementFromPoint` +\n * synthetic events to forward clicks to the page underneath.\n *\n * Returns a [`BindController`] \u2014 call `dispose()` to detach the\n * cursor and stop applying frames. The wallet drawer stays open\n * until the user closes it; disposing the controller silently\n * drops further frames but doesn't tell the wallet to stop.\n *\n * @example\n * const mouse = bindMouse(session, { mode: \"touch\" });\n * await mouse.request();\n * // later\n * mouse.dispose();\n */\nexport function bindMouse(\n session: PrsonLoginSession,\n opts?: BindMouseOptions,\n): BindController {\n const mode = opts?.mode ?? \"touch\";\n const size = Math.max(6, opts?.size ?? 28);\n const color = opts?.color ?? \"rgba(59, 130, 246, 0.65)\";\n const onMove = opts?.onMove;\n const onClick = opts?.onClick;\n\n // DOM-side state. The cursor element is created lazily on the\n // first `request()` call so a host that builds the controller\n // up-front but never calls request doesn't pollute the page.\n let cursor: HTMLDivElement | null = null;\n let pos = opts?.initialPosition ?? {\n x: typeof window !== \"undefined\" ? window.innerWidth / 2 : 0,\n y: typeof window !== \"undefined\" ? window.innerHeight / 2 : 0,\n };\n let disposed = false;\n /**\n * The currently-previewed snap target, if any. Only populated\n * while magic mode is active \u2014 every move frame finds the\n * nearest interactive element and rewires this state so the\n * page can style \"what would be clicked if I tapped now\":\n *\n * [data-prson-magic-snap] { outline: 2px solid #3b82f6; }\n *\n * The data-attribute is the public contract; the corresponding\n * class is added too as a convenience for selector-shy host\n * stylesheets. Cleared on dispose / mode-change so a left-over\n * highlight can't outlive the controller.\n */\n let snapTarget: Element | null = null;\n /** Active mode for the current frame stream \u2014 kept in sync with\n * `mouse.mode` on every applied envelope so snap-preview turns\n * itself off when the wallet flips back to touch. */\n let activeMode: \"touch\" | \"magic\" = mode;\n\n // Install the ambient mouse-update handler so wallet-initiated\n // streams (the pre-grant flow \u2014 `signIn({mouseControl: true})`)\n // land on `applyFrame` even when there's no pending\n // `requestMouse` promise to key the subscriber by. `bindMouse`\n // owns the handler for its lifetime; `dispose()` removes it.\n // The handler is installed eagerly (not on first `request()`) so\n // the wallet can start streaming the moment the user taps\n // Touchpad / Magic on the banner drawer \u2014 even if the host hasn't\n // called `.request()` at all.\n // Window focus \u2192 `control-status` for the wallet. When the page\n // tab loses focus the wallet drops into a \"Remote control paused\"\n // state so the user can see, on the phone, that motion isn't\n // landing anywhere. Listeners are torn down in `detach()`.\n function onWindowBlur(): void {\n if (disposed) return;\n void session._sendControlStatus(true);\n }\n function onWindowFocus(): void {\n if (disposed) return;\n void session._sendControlStatus(false);\n // Real OS focus also implies the user is back at the keyboard\n // \u2192 drop the \"point your phone\" hint if it was still up.\n closePointPhoneOverlay();\n }\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"blur\", onWindowBlur);\n window.addEventListener(\"focus\", onWindowFocus);\n // Initial state \u2014 fire once so a session created while the tab\n // is hidden lands on the wallet correctly.\n if (typeof document !== \"undefined\" && document.hasFocus && !document.hasFocus()) {\n void session._sendControlStatus(true);\n }\n }\n\n const offAmbient = session._setAmbientMouseHandler((mouseBody) => {\n if (disposed) return;\n // `begin` / `end` are protocol pairing tokens \u2014 they just need to\n // make sure the cursor element exists (so the first real `move`\n // frame doesn't race the lazy initialiser) and are otherwise\n // no-ops. **Every other event** \u2014 including the visibility\n // toggles `show` / `hide` \u2014 must be forwarded to `applyFrame`,\n // which is what opens / closes the \"point your phone\" overlay\n // and re-centres the cursor on resume.\n if (mouseBody.event === \"begin\" || mouseBody.event === \"end\") {\n ensureCursor();\n return;\n }\n applyFrame(mouseBody);\n });\n\n function ensureCursor(): HTMLDivElement {\n if (cursor) return cursor;\n // Dedupe across multiple `bindMouse` calls. If another instance\n // already created a cursor (e.g. the long-lived ambient bind\n // from sign-in + a per-request bind from a host button click),\n // adopt the existing element instead of stacking a second one.\n // We still own its position state from this controller \u2014 the\n // last `bindMouse` to call `ensureCursor` becomes the visible\n // owner. (Prior owners just stop applying frames.)\n const existing = document.querySelector<HTMLDivElement>(\n '[data-prson-virtual-cursor]',\n );\n if (existing) {\n cursor = existing;\n // Update size/colour to match our opts so a second mount can\n // restyle the cursor without flicker.\n existing.style.width = `${size}px`;\n existing.style.height = `${size}px`;\n existing.style.background = color;\n existing.style.display = \"block\";\n applyCursorPosition(existing, pos);\n return existing;\n }\n const el = document.createElement(\"div\");\n el.setAttribute(\"data-prson-virtual-cursor\", \"\");\n el.style.position = \"fixed\";\n el.style.width = `${size}px`;\n el.style.height = `${size}px`;\n el.style.borderRadius = \"50%\";\n el.style.background = color;\n el.style.border = \"2px solid rgba(255, 255, 255, 0.9)\";\n el.style.boxShadow = \"0 2px 8px rgba(0, 0, 0, 0.25)\";\n el.style.pointerEvents = \"none\";\n el.style.zIndex = \"2147483647\";\n el.style.transform = \"translate(-50%, -50%)\";\n el.style.transition = \"background 120ms ease, opacity 120ms ease\";\n applyCursorPosition(el, pos);\n document.body.appendChild(el);\n cursor = el;\n return el;\n }\n\n function applyCursorPosition(el: HTMLDivElement, p: { x: number; y: number }) {\n el.style.left = `${p.x}px`;\n el.style.top = `${p.y}px`;\n }\n\n function clamp(value: number, min: number, max: number): number {\n return value < min ? min : value > max ? max : value;\n }\n\n function setSnapTarget(next: Element | null): void {\n if (next === snapTarget) return;\n if (snapTarget) {\n snapTarget.removeAttribute(\"data-prson-magic-snap\");\n (snapTarget as Element).classList.remove(\"prson-magic-snap\");\n }\n snapTarget = next;\n if (snapTarget) {\n snapTarget.setAttribute(\"data-prson-magic-snap\", \"\");\n (snapTarget as Element).classList.add(\"prson-magic-snap\");\n }\n }\n\n function applyFrame(mouse: NonNullable<import(\"./crypto.js\").DecryptedEnvelope[\"mouse\"]>): void {\n if (disposed) return;\n const el = ensureCursor();\n // The wallet may toggle mode mid-stream. Track the active mode\n // here so move frames know whether to maintain the snap-target\n // highlight (magic) or drop it (touch).\n if (mouse.mode === \"touch\" || mouse.mode === \"magic\") {\n if (mouse.mode !== activeMode) {\n activeMode = mouse.mode;\n if (activeMode === \"touch\") setSnapTarget(null);\n }\n }\n switch (mouse.event) {\n case \"move\": {\n pos = {\n x: clamp(pos.x + (mouse.dx ?? 0), 0, window.innerWidth),\n y: clamp(pos.y + (mouse.dy ?? 0), 0, window.innerHeight),\n };\n applyCursorPosition(el, pos);\n if (onMove) {\n try { onMove(pos); } catch { /* swallow */ }\n }\n // Magic-mode snap preview. Refreshed on every move frame so\n // the highlight tracks the cursor. The DOM query + N rect\n // measurements run at most once per browser repaint\n // (`mouse-update` is already wallet-throttled to ~60 Hz),\n // which is acceptable on every page we ship for.\n if (activeMode === \"magic\") {\n if (isSelectOverlayActive()) {\n // Page-side highlight stays cleared; the snap visual\n // lives inside the overlay's own shadow root (the page\n // can't reach it, and the page's selector can't\n // accidentally override the option styling).\n setSnapTarget(null);\n setOverlaySnap(findNearestClickableInOverlay(pos.x, pos.y));\n } else {\n setOverlaySnap(null);\n setSnapTarget(findNearestClickable(pos.x, pos.y));\n }\n }\n break;\n }\n case \"click\":\n case \"double-click\": {\n // Visual feedback \u2014 briefly pulse the cursor so the user\n // sees the click landed even if the underlying element\n // doesn't repaint.\n const prev = el.style.background;\n el.style.background = \"rgba(59, 130, 246, 1)\";\n setTimeout(() => { if (cursor === el) el.style.background = prev; }, 140);\n // Custom-overlay route. While a select overlay is open the\n // page beneath is non-interactive \u2014 clicks land ONLY on\n // overlay elements (close button, page-up / page-down,\n // option buttons). The overlay's shadow-DOM listener\n // handles the actual semantics (close vs. paginate vs.\n // commit option); we just need to dispatch a click event\n // on the right inner element.\n if (isSelectOverlayActive()) {\n const overlayTarget =\n (snapTarget && (snapTarget as Element).closest?.(\n \"[data-prson-select-close],[data-prson-select-page],[data-prson-select-option]\",\n )) ??\n findNearestClickableInOverlay(pos.x, pos.y);\n if (overlayTarget) {\n const init: MouseEventInit = {\n bubbles: true,\n cancelable: true,\n composed: true,\n clientX: pos.x,\n clientY: pos.y,\n view: window,\n };\n overlayTarget.dispatchEvent(new MouseEvent(\"mousedown\", init));\n overlayTarget.dispatchEvent(new MouseEvent(\"mouseup\", init));\n overlayTarget.dispatchEvent(new MouseEvent(\"click\", init));\n }\n break;\n }\n // Click-area enlargement: a virtual cursor is harder to land\n // precisely than a touch finger or a mouse, especially for a\n // gyro-driven wand. Search for the NEAREST interactive\n // element within [SNAP_RADIUS_PX] of the cursor and target\n // that, even if the cursor isn't strictly on top of it.\n // Falls back to whatever's at the cursor coordinate when no\n // candidate is within range (so clicks on free space, scroll\n // areas, etc. still work normally).\n //\n // Magic mode already maintains `snapTarget` via the move-\n // frame preview; touch mode skips the highlight but still\n // gets snap-on-click. Re-query in touch mode so the click\n // semantic stays identical across modes.\n const snapped =\n activeMode === \"magic\"\n ? snapTarget\n : findNearestClickable(pos.x, pos.y);\n // Native <select>s open an OS-drawn list that the virtual\n // cursor can't reach. Replace the click with a custom\n // shadow-DOM overlay the cursor CAN drive.\n if (snapped instanceof HTMLSelectElement) {\n openSelectOverlay(snapped);\n // Clear the page-side snap highlight on the select so the\n // overlay's own snap visuals take over cleanly.\n setSnapTarget(null);\n break;\n }\n const direct = document.elementFromPoint(pos.x, pos.y);\n const target = snapped ?? direct;\n // When we snapped, dispatch at the SNAPPED element's centre\n // so any positional logic inside the page (e.g. a custom\n // dropdown computing position from `clientX`) sees a hit\n // ON the element rather than in dead space next to it.\n const clickPoint = snapped\n ? rectCenter((snapped as Element).getBoundingClientRect())\n : { x: pos.x, y: pos.y };\n let allowDefault: boolean = true;\n if (onClick) {\n try {\n const ret = onClick(target);\n if (ret === false) allowDefault = false;\n } catch { /* swallow */ }\n }\n if (allowDefault && target) {\n const init: MouseEventInit = {\n bubbles: true,\n cancelable: true,\n clientX: clickPoint.x,\n clientY: clickPoint.y,\n view: window,\n };\n target.dispatchEvent(new MouseEvent(\"mousedown\", init));\n target.dispatchEvent(new MouseEvent(\"mouseup\", init));\n target.dispatchEvent(new MouseEvent(\"click\", init));\n if (mouse.event === \"double-click\") {\n target.dispatchEvent(new MouseEvent(\"dblclick\", init));\n }\n // Inputs and other focusable elements don't always auto-\n // focus from synthetic `mousedown`. Explicitly focus the\n // snapped target so the page sees the same focus state it\n // would after a real touch.\n if (\n snapped &&\n typeof (target as HTMLElement).focus === \"function\"\n ) {\n try {\n (target as HTMLElement).focus({ preventScroll: true });\n } catch {\n /* swallow \u2014 some host elements throw on focus */\n }\n }\n }\n break;\n }\n case \"scroll\": {\n // `dy` matches WheelEvent.deltaY \u2014 positive = scroll down.\n window.scrollBy({ left: mouse.dx ?? 0, top: mouse.dy ?? 0 });\n break;\n }\n case \"hide\": {\n // Wallet's pose detector says the phone is no longer\n // pointing at the screen. Pull the cursor off the page so\n // the user gets immediate feedback, and surface a soft\n // blue-glow + \"point your phone\" pill so they know how to\n // resume. The overlay auto-dismisses after 15 s or on real\n // OS mouse movement (whichever first).\n if (cursor) {\n cursor.style.opacity = \"0\";\n cursor.style.pointerEvents = \"none\";\n }\n setSnapTarget(null);\n setOverlaySnap(null);\n openPointPhoneOverlay();\n break;\n }\n case \"show\": {\n // Wand pose restored \u2014 bring the cursor back and clear the\n // \"point your phone\" hint regardless of which trigger\n // (timeout / mousemove / show) wins the race.\n //\n // **Re-centre the cursor.** After a pause the user has lost\n // mental track of where the cursor was; pinning it at the\n // viewport centre gives them a known starting point and\n // matches the \"wand on / wand off\" mental model (each\n // session begins at the middle). Position resets via\n // `applyCursorPosition` so subsequent move frames integrate\n // from the centre.\n const el = ensureCursor();\n el.style.opacity = \"1\";\n if (typeof window !== \"undefined\") {\n pos = {\n x: window.innerWidth / 2,\n y: window.innerHeight / 2,\n };\n applyCursorPosition(el, pos);\n }\n closePointPhoneOverlay();\n break;\n }\n case \"begin\":\n case \"end\": {\n // Wallet-side stream lifecycle markers (pre-grant flow).\n // Nothing for the cursor renderer to do \u2014 `_setAmbientMouseHandler`\n // already calls `ensureCursor()` on these so a real `move`\n // frame doesn't race the lazy initialiser.\n break;\n }\n }\n }\n\n function detach() {\n if (cursor) {\n cursor.remove();\n cursor = null;\n }\n // Clear any lingering magic-mode highlight so the page doesn't\n // keep a `data-prson-magic-snap` attribute on whichever input\n // happened to be the last preview target.\n setSnapTarget(null);\n setOverlaySnap(null);\n // Close any active select overlay so a disposing cursor doesn't\n // leave the dropdown orphaned on the page.\n closeAllOverlays();\n closePointPhoneOverlay();\n // Drop window-focus listeners so a torn-down controller doesn't\n // keep pushing control-status envelopes onto a closed channel.\n if (typeof window !== \"undefined\") {\n window.removeEventListener(\"blur\", onWindowBlur);\n window.removeEventListener(\"focus\", onWindowFocus);\n }\n // Tear down the ambient subscription so the session stops\n // holding a ref to our (now-disposed) handler.\n offAmbient();\n }\n\n return {\n async request(callerOpts) {\n if (disposed) return { ok: false, error: \"session-closed\" };\n ensureCursor();\n // `requestMouse` atomically registers the subscriber under the\n // requestId before the envelope leaves the wire, so the very\n // first `mouse-update` frame can never race ahead of us. The\n // session also drops the subscriber on the terminating\n // `response` so we don't need to manage that side ourselves.\n // Mouse requests stay open as long as the user is driving the\n // wallet's controller \u2014 that can easily be longer than the\n // generic `request()` default of 60 s. Pick the smaller of\n // (a) the session's hard expiry and (b) the `setTimeout`\n // int32 ceiling (~24.8 days). The credential's exp can sit\n // weeks out, but `setTimeout(fn, > 2^31-1)` overflows and\n // fires on the next tick \u2014 exactly the bug that caused\n // `bindMouse` to resolve with `error: \"timeout\"` the moment\n // it was awaited.\n const MAX_SAFE_TIMEOUT = 2_147_483_000;\n const credentialBudget = session.expiresAt - Date.now() + 1_000;\n const sessionEndMs = Math.max(\n 60_000,\n Math.min(credentialBudget, MAX_SAFE_TIMEOUT),\n );\n const reply = await session.requestMouse(\n { kind: \"mouse\", mode, reason: callerOpts?.reason ?? opts?.reason },\n applyFrame,\n { timeoutMs: sessionEndMs, ...callerOpts },\n );\n // Drawer closed (or timed out) \u2014 pull the cursor off the page\n // so it doesn't sit there orphaned. Host can call request()\n // again to spawn another session.\n if (!disposed) {\n if (cursor) {\n cursor.remove();\n cursor = null;\n }\n }\n return reply;\n },\n dispose() {\n disposed = true;\n detach();\n },\n };\n}\n\n// \u2500\u2500\u2500 Click-area enlargement (virtual-cursor snap) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// CSS selector covering every realistic click target on a page \u2014\n// form controls + anchor-style affordances. The query runs once per\n// click (low frequency relative to move frames), so the cost is\n// acceptable even on a long page; we do NOT walk the DOM on every\n// move frame.\nconst SNAP_SELECTOR =\n 'input:not([type=\"hidden\"]):not([disabled]),' +\n 'textarea:not([disabled]),' +\n 'select:not([disabled]),' +\n 'button:not([disabled]),' +\n 'a[href],' +\n '[role=\"button\"],' +\n '[role=\"link\"],' +\n '[role=\"checkbox\"],' +\n '[role=\"radio\"],' +\n 'label[for],' +\n '[tabindex]:not([tabindex=\"-1\"])';\n\n/** Snap radius in CSS pixels. A click further than this from any\n * interactive element falls through to whatever's at the cursor\n * coordinate. Tuned so a comfortable wand flick lands in the\n * right input without over-reaching across the page. */\nconst SNAP_RADIUS_PX = 60;\n\nfunction rectCenter(r: DOMRect): { x: number; y: number } {\n return { x: r.left + r.width / 2, y: r.top + r.height / 2 };\n}\n\n/**\n * Find the closest interactive element to the cursor whose bounding\n * box lies within [SNAP_RADIUS_PX]. Distance is measured to the\n * nearest edge of the element's rect (0 if inside), so wide elements\n * \"win\" over narrow ones at the same centre distance. Returns null\n * when nothing qualifies \u2014 the caller then falls back to\n * `document.elementFromPoint`.\n *\n * If multiple inputs sit equally close (tie), the one earliest in\n * the DOM wins \u2014 `querySelectorAll` iterates in document order, so\n * the strictly-less-than comparison preserves it.\n */\nfunction findNearestClickable(x: number, y: number): Element | null {\n if (typeof document === \"undefined\") return null;\n const candidates = document.querySelectorAll(SNAP_SELECTOR);\n let best: Element | null = null;\n let bestDist = Infinity;\n for (const el of Array.from(candidates)) {\n const rect = (el as Element).getBoundingClientRect();\n if (rect.width === 0 || rect.height === 0) continue; // hidden / collapsed\n // Distance from (x,y) to rect: 0 if inside, else Euclidean from\n // the nearest edge / corner.\n const dx = x < rect.left ? rect.left - x : x > rect.right ? x - rect.right : 0;\n const dy = y < rect.top ? rect.top - y : y > rect.bottom ? y - rect.bottom : 0;\n const dist = Math.sqrt(dx * dx + dy * dy);\n if (dist < bestDist) {\n bestDist = dist;\n best = el;\n }\n }\n return bestDist <= SNAP_RADIUS_PX ? best : null;\n}\n\n// `CSS.escape` polyfill \u2014 older Safari versions sometimes ship\n// without it. Hand-rolled escape covers our identifier characters.\nfunction cssEscape(s: string): string {\n if (\n typeof CSS !== \"undefined\" &&\n typeof (CSS as { escape?: (s: string) => string }).escape === \"function\"\n ) {\n return CSS.escape(s);\n }\n return s.replace(/([\"\\\\#.>+~*$^|=:()\\[\\] ])/g, \"\\\\$1\");\n}\n", "/**\n * Show a person a Prson **verification** (an organisation's request made\n * with POST /v1/verifications \u2014 prove your age, show your ID, sign this\n * PDF with your verified name) and wait until they answer it.\n *\n * The verification is created by YOUR SERVER with your API key; the key\n * never reaches the browser. Your page gets the `share_url` from your\n * server, and `checkStatus` asks your server for the status (your server\n * calls GET /v1/verifications/{id}, or keeps what the verification.*\n * webhooks told it). On a computer the link shows as a QR code to scan\n * with the phone; on a phone, as a button that opens the Prson app.\n *\n * const { share_url, id } = await (await fetch(\"/api/contract/sign\", { method: \"POST\" })).json();\n * await awaitVerification({\n * shareUrl: share_url,\n * title: \"Sign the rental agreement\",\n * checkStatus: async (signal) => (await (await fetch(`/api/verifications/${id}`, { signal })).json()).status,\n * });\n * // fulfilled: your server downloads the signed PDF (the response's signature.download_path).\n *\n * Resolves with the status once `until` holds (default: \"fulfilled\");\n * rejects with VerificationClosedError when it was cancelled or expired,\n * and VerificationAbortedError when the person closes the dialog or\n * `signal` aborts.\n */\n\nimport { createModalQrMount, renderLoginQr, type LoginQrHandle } from \"./qr.js\";\n\nexport type VerificationStatus = \"open\" | \"partially_fulfilled\" | \"fulfilled\" | \"cancelled\" | \"expired\";\n\nexport interface AwaitVerificationOptions {\n /** The verification's `share_url`, from your server. */\n shareUrl: string;\n /** Your server's view of the verification's status. Called every `intervalMs`; a throw is retried. */\n checkStatus: (signal: AbortSignal) => Promise<VerificationStatus | string>;\n /** Shown above the code: what the person is asked for (e.g. \"Sign the rental agreement\"). */\n title?: string;\n /** Where to render; default: a modal over the page (Esc or a click outside closes it). */\n mountInto?: string | HTMLElement;\n /** How often to call `checkStatus`, in ms (default 3000, at least 1000). */\n intervalMs?: number;\n /** Stop after this long (ms) with VerificationAbortedError; default: wait until it closes. */\n timeoutMs?: number;\n /** When to stop waiting (default: status === \"fulfilled\"). */\n until?: (status: string) => boolean;\n signal?: AbortSignal;\n theme?: \"light\" | \"dark\" | \"auto\";\n /** Force the phone (button) or computer (QR) layout; default: guessed from the pointer. */\n layout?: \"phone\" | \"computer\";\n}\n\nexport class VerificationAbortedError extends Error {\n constructor(message = \"The verification dialog was closed\") {\n super(message);\n this.name = \"VerificationAbortedError\";\n }\n}\n\nexport class VerificationClosedError extends Error {\n constructor(readonly status: \"cancelled\" | \"expired\") {\n super(`The verification is ${status}`);\n this.name = \"VerificationClosedError\";\n }\n}\n\nfunction checkShareUrl(url: string): string {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`shareUrl is not a URL: ${url}`);\n }\n if (parsed.protocol !== \"https:\") throw new Error(\"shareUrl must be https:// (the share_url Prson returned)\");\n return parsed.toString();\n}\n\nfunction isPhone(): boolean {\n try {\n return window.matchMedia(\"(pointer: coarse)\").matches && window.matchMedia(\"(max-width: 820px)\").matches;\n } catch {\n return false;\n }\n}\n\n/** The card: title, the QR (computer) or an \"Open in Prson\" button (phone), and a status line. */\nfunction renderCard(mount: HTMLElement, o: { url: string; title?: string; phone: boolean; theme: \"light\" | \"dark\" | \"auto\" }) {\n const dark = o.theme === \"dark\" || (o.theme === \"auto\" && window.matchMedia?.(\"(prefers-color-scheme: dark)\").matches);\n const card = document.createElement(\"div\");\n card.setAttribute(\"data-prson-verification\", \"1\");\n card.style.cssText =\n \"box-sizing:border-box;max-width:360px;width:100%;padding:24px;border-radius:16px;font-family:system-ui,-apple-system,sans-serif;text-align:center;\" +\n (dark ? \"background:#14161b;color:#f2f3f5;\" : \"background:#fff;color:#14161b;\") +\n \"box-shadow:0 12px 40px rgba(0,0,0,0.25);\";\n if (o.title) {\n const h = document.createElement(\"div\");\n h.style.cssText = \"font-size:17px;font-weight:600;margin-bottom:6px;line-height:1.3;\";\n h.textContent = o.title;\n card.append(h);\n }\n const hint = document.createElement(\"div\");\n hint.style.cssText = \"font-size:14px;opacity:0.75;margin-bottom:16px;line-height:1.4;\";\n hint.textContent = o.phone ? \"Open the request in the Prson app on this phone.\" : \"Scan with your phone's camera to open it in the Prson app.\";\n card.append(hint);\n\n let qr: LoginQrHandle | null = null;\n if (o.phone) {\n const a = document.createElement(\"a\");\n a.href = o.url;\n a.rel = \"noopener\";\n a.textContent = \"Open in Prson\";\n a.style.cssText = \"display:inline-block;padding:12px 20px;border-radius:999px;background:#2949b8;color:#fff;font-weight:600;text-decoration:none;font-size:15px;\";\n card.append(a);\n } else {\n const qrMount = document.createElement(\"div\");\n qrMount.style.cssText = \"display:flex;justify-content:center;margin:4px 0 8px;\";\n card.append(qrMount);\n qr = renderLoginQr(o.url, qrMount, o.theme);\n const link = document.createElement(\"a\");\n link.href = o.url;\n link.target = \"_blank\";\n link.rel = \"noopener\";\n link.textContent = \"On this device? Open the link\";\n link.style.cssText = \"display:inline-block;margin-top:4px;font-size:13px;color:inherit;opacity:0.7;\";\n card.append(link);\n }\n const status = document.createElement(\"div\");\n status.setAttribute(\"role\", \"status\");\n status.style.cssText = \"font-size:13px;opacity:0.7;margin-top:16px;\";\n status.textContent = \"Waiting for an answer\u2026\";\n card.append(status);\n mount.append(card);\n return {\n setStatus: (s: string) => {\n status.textContent = s === \"partially_fulfilled\" ? \"Partly answered, waiting for the rest\u2026\" : \"Waiting for an answer\u2026\";\n },\n dispose: () => {\n qr?.dispose();\n card.remove();\n },\n };\n}\n\nexport async function awaitVerification(opts: AwaitVerificationOptions): Promise<{ status: string }> {\n const url = checkShareUrl(opts.shareUrl);\n const interval = Math.max(1000, opts.intervalMs ?? 3000);\n const until = opts.until ?? ((s: string) => s === \"fulfilled\");\n const controller = new AbortController();\n const abort = (reason: Error) => controller.abort(reason);\n opts.signal?.addEventListener(\"abort\", () => abort(new VerificationAbortedError(\"Aborted\")), { once: true });\n\n let modal: { mount: HTMLElement; dispose: () => void } | null = null;\n let mount: HTMLElement | null = null;\n if (opts.mountInto) mount = typeof opts.mountInto === \"string\" ? document.querySelector(opts.mountInto) : opts.mountInto;\n if (!mount) {\n modal = createModalQrMount({ onDismiss: () => abort(new VerificationAbortedError()) });\n mount = modal.mount;\n }\n const card = renderCard(mount, { url, title: opts.title, phone: opts.layout ? opts.layout === \"phone\" : isPhone(), theme: opts.theme ?? \"auto\" });\n const timer = opts.timeoutMs ? setTimeout(() => abort(new VerificationAbortedError(\"Timed out waiting for an answer\")), opts.timeoutMs) : null;\n\n const sleep = (ms: number) =>\n new Promise<void>((resolve, reject) => {\n if (controller.signal.aborted) return reject(controller.signal.reason);\n const t = setTimeout(resolve, ms);\n controller.signal.addEventListener(\"abort\", () => (clearTimeout(t), reject(controller.signal.reason)), { once: true });\n });\n\n try {\n for (;;) {\n if (controller.signal.aborted) throw controller.signal.reason;\n let status: string | null = null;\n try {\n status = String(await opts.checkStatus(controller.signal));\n } catch (e) {\n if (controller.signal.aborted) throw controller.signal.reason;\n // A failed check (network, your server) is retried at the next tick.\n }\n if (status !== null) {\n if (until(status)) return { status };\n if (status === \"cancelled\" || status === \"expired\") throw new VerificationClosedError(status);\n card.setStatus(status);\n }\n await sleep(interval);\n }\n } finally {\n if (timer) clearTimeout(timer);\n card.dispose();\n modal?.dispose();\n }\n}\n", "/**\n * @prson/login-sdk \u2014 browser runtime.\n *\n * Top-level entry point: `PrsonLogin.signIn(opts)` orchestrates the\n * whole flow. The pieces underneath are:\n *\n * \u250C\u2500\u2500 ./session.ts \u2014 PrsonLoginSession (state machine + events)\n * \u251C\u2500\u2500 ./signaling.ts \u2014 WebSocket to the Cloudflare Worker\n * \u251C\u2500\u2500 ./transport.ts \u2014 RTCPeerConnection + data channel\n * \u251C\u2500\u2500 ./crypto.ts \u2014 X25519 ephemeral keypair + NaCl box decrypt\n * \u251C\u2500\u2500 ./verify.ts \u2014 verify issuer JWS + KB-JWT in the browser\n * \u251C\u2500\u2500 ./qr.ts \u2014 render the https://app.prson.net/login/v1?... QR\n * \u2514\u2500\u2500 ./api.ts \u2014 typed createLoginSession + resolveLoginSession\n *\n * See ../../README.md for integration. See ../../../ARCHITECTURE.md\n * for the wire spec.\n */\nimport {\n PrsonLoginSession,\n type ExpiryReason,\n type Renewal,\n} from \"./session.js\";\nimport { createDraft } from \"./api.js\";\nimport { generateEphemeralKeypair, openEnvelope } from \"./crypto.js\";\nimport { connectSignaling } from \"./signaling.js\";\nimport { establishTransport } from \"./transport.js\";\nimport {\n renderLoginQr,\n createModalQrMount,\n type LoginQrContext,\n type LoginQrHandle,\n} from \"./qr.js\";\nimport type { DraftResult } from \"./api.js\";\nimport { verifyPresentation } from \"./verify.js\";\nimport { PrsonCspError, watchCsp } from \"./csp.js\";\nimport { PrsonLoginError, asLoginError } from \"./errors.js\";\nimport { notifyHandleFrom } from \"./notify.js\";\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Public types \u2014 these mirror the contract in this folder's README.\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type SignInOptions = {\n domain?: string;\n\n /**\n * A one-time value your BACKEND made for this sign-in (at least 16 random\n * bytes, base64url: 22-128 characters of `A-Z a-z 0-9 - _`). Store it\n * server-side, then verify the presentation there with\n * `verifyPresentation(presentation, { expectedNonce, expectedAudience })`\n * and delete it, so a captured presentation can't be replayed to your\n * backend. Omitted: the SDK makes one in the browser, which only protects\n * the in-browser check \u2014 not enough for a backend that trusts the result.\n *\n * May also be a function returning one (sync or async). The SDK then\n * calls it once per code it shows, so a refreshed code (after expiry or\n * an error) gets a fresh backend nonce without your page calling\n * `signIn()` again. `SignInResult.nonce` says which one the presentation\n * is bound to.\n */\n nonce?: string | (() => string | Promise<string>);\n\n /**\n * Which Prson backend environment to sign in against. `\"dev\"` points\n * the flow at the dev signaling Worker (`signaling-dev.prson.net`);\n * omit (or `\"production\"`) for the live environment. For a custom /\n * local Worker, set `signalingBase` instead (it takes precedence).\n * Default `\"production\"`.\n */\n environment?: \"production\" | \"dev\";\n\n /**\n * Explicit signaling Worker base URL \u2014 overrides `environment`. Use\n * for a local Worker (`https://localhost:8787`) or any non-standard\n * deployment. The Worker returns the matching WebSocket URL in its\n * draft response, so this single value steers the whole flow.\n */\n signalingBase?: string;\n\n required?: {\n /**\n * Minimum identity verification level (0\u20136). Omitted \u21D2 1.\n *\n * `0` opts into **pseudonymous identity sign-in**: the wallet may\n * present an UNVERIFIED identity, and the minted credential\n * honestly claims `verified_human: false` / `verification_level: 0`.\n * You still get the stable per-domain `sub` (cnf.jwk continuity) \u2014\n * what you give up is any assurance a real, unique human is behind\n * it. Distinct from `allowAnonymous`, which is identity-less: a\n * level-0 identity sign-in carries the user's chosen identity and\n * survives across sessions; anonymous carries only a key.\n */\n minVerificationLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6;\n requiredClaims?: string[];\n predicates?: string[];\n identityType?: \"personal\" | \"organization\";\n /**\n * Require a **domain-scoped unique-human id**: a notary-signed\n * pairwise identifier anchored to the user's verified government\n * document. Proves \"one unique, document-verified human at YOUR\n * domain\" (sybil resistance) without any cross-site correlation\n * handle. The wallet only offers document-backed identities\n * (level \u2265 4) when this is set; the result carries\n * `uniqueHumanId` for SERVER-SIDE verification.\n */\n uniqueHumanId?: boolean;\n };\n /**\n * If `true`, the SDK ALSO accepts an **anonymous-wallet** credential\n * \u2014 a self-signed JWT issued by the wallet's per-domain Ed25519 key,\n * with no notary involvement. The wallet's login drawer surfaces an\n * \"Sign in anonymously\" option to the user. The credential carries\n * only `cnf.jwk` + `aud` + `nonce` + `iat` + `exp` (no\n * `verified_human`, no document fields, no predicates). The\n * verifier treats `cnf.jwk.x` as the stable per-user identifier on\n * this domain.\n *\n * If a verified credential is presented when `allowAnonymous: true`\n * AND `required.*` constraints are set, the verified credential is\n * still checked against those constraints \u2014 the relaxation only\n * applies to the anonymous fallback. Default false.\n */\n allowAnonymous?: boolean;\n\n /**\n * If `true`, the wallet signs in with a **device-only key for your\n * site** instead of the per-site key derived from the person's\n * recovery phrase. The wallet makes a random Ed25519 keypair on the\n * first sign-in to your domain, keeps its seed in this phone's secure\n * storage only, and reuses it on later sign-ins from the same phone,\n * so `cnf.jwk.x` stays the same there and the person returns to the\n * same account. A new key is made after the person revokes your site\n * in the wallet, on another phone, or after reinstalling the app.\n *\n * What it buys: the key isn't derived from the recovery phrase, so a\n * future phrase compromise can't retroactively link the person to\n * your site, and no notification handle (one per wallet and site) is\n * offered. What it doesn't: sign-ins from the same phone are linkable\n * by `cnf.jwk.x`, like the default \u2014 it is not a one-time key.\n *\n * Trade-off: the account is tied to the phone. Losing the phone or\n * the app loses the key, so pair it with your own recovery path.\n * Combine with `allowAnonymous: true` for an account that carries no\n * identity at all. Default false.\n *\n * Closes [SECURITY-AUDIT \u00A7M-5](../../SECURITY-AUDIT-2026-05-28.md).\n */\n ephemeralIdentity?: boolean;\n\n /**\n * Sponsorship: pay for premium verifications your users need.\n *\n * If your `required.predicates` include facts that need a PAID\n * verification the user may not have yet (e.g. `phone_verified` \u2014\n * SMS costs credits), create a **sponsorship grant** from your\n * company wallet (Prson app \u2192 `createSponsorshipGrant`) and put its\n * id here. The user's wallet then routes those verification costs\n * to your grant instead of the user.\n *\n * Safe to expose in page source: the grantId authorises nothing by\n * itself. Every redemption is validated server-side against the\n * STORED grant \u2014 bound to YOUR domain, capped per user (default\n * once), capped in total budget, expiring, and instantly revocable.\n */\n sponsorship?: { grantId: string };\n\n /**\n * **App-to-app return leg** (same-device native flows). An HTTPS URL\n * on YOUR login domain that the wallet opens after the credential\n * has been delivered \u2014 typically your Universal Link / Android App\n * Link, so the OS bounces the user straight back into your native\n * app (only the app your domain vouches for via AASA /\n * assetlinks.json receives it).\n *\n * Constraints (enforced both here and in the wallet):\n * - `https://` only \u2014 custom schemes are refused (any installed\n * app could claim a custom scheme; app links are domain-proven).\n * - The URL's host MUST equal the login domain exactly.\n *\n * Only set this for same-device flows (your site opened inside a\n * Custom Tab / SFSafariViewController from your app). In cross-device\n * QR flows the wallet is on a different phone \u2014 it would open your\n * site there, which is harmless but pointless.\n */\n returnUrl?: string;\n\n ttlMinutes?: number;\n ui?: {\n /**\n * Render the code inline in this element instead of the SDK's own\n * dialog. The dialog is the default and the recommended experience.\n */\n mountQrInto?: string | HTMLElement;\n /** `\"auto\"` (default) follows `prefers-color-scheme`. The code itself is always dark on white. */\n theme?: \"light\" | \"dark\" | \"auto\";\n /** Where \"Don't have Prson? Get it\" points. Default https://app.prson.net/. */\n getAppUrl?: string;\n };\n defer?: boolean;\n\n /**\n * QR-mode only: opt in to **remote navigation**. The wallet shows a\n * persistent banner that opens a bottom drawer with Prev / Next /\n * Submit (Enter) / Logout / (optional) Mouse buttons. The host\n * page's currently-focused input is mirrored on the phone so the\n * user can edit / clear / replace the value with the phone\n * keyboard, and edits stream back into the DOM in real time.\n *\n * Auto-wires when the SDK detects a QR-mode sign-in (the QR encodes\n * `remoteNavigation: true` for the wallet to honour). Same-device\n * universal-link flows ignore the flag \u2014 the banner would be\n * redundant when the wallet is on the same device as the page.\n *\n * Pair with [`enableRemoteNavigation`] to install the DOM focus\n * listeners that mirror the active input. Default false.\n */\n remoteNavigation?: boolean;\n\n /**\n * **Mouse control pre-granted at sign-in.** When true, the wallet's\n * persistent banner drawer enables the Touchpad / Magic wand\n * buttons from the moment the session lands, so the user can\n * start driving the cursor without the host ever issuing a\n * `kind: \"mouse\"` request.\n *\n * The capability **persists** for the session lifetime \u2014 closing\n * the controller doesn't revoke it; the user can re-open it from\n * the drawer at any time. The host still calls [`bindMouse`] to\n * mount the on-page cursor; when this flag is set, that call\n * installs an *ambient* mouse-update subscriber so wallet-\n * initiated streams (which carry no `requestId` matched to a\n * pending `request()`) land correctly. Existing `requestMouse`\n * round-trips still work in parallel.\n *\n * The wallet shows a chip in the sign-in drawer so the user\n * sees mouse control will be active before they approve.\n *\n * Default false.\n */\n mouseControl?: boolean;\n\n /**\n * **Ask to send notifications.** The wallet's sign-in sheet shows an\n * unticked \"Let {site} send you notifications\" row; nothing is sent\n * unless the person ticks it. When they do, `SignInResult.notifications`\n * carries a handle for this person at your domain: random, so it can't\n * be linked to the same person's handle on any other site. Send it to\n * your backend with the presentation and call\n * `POST https://api.prson.net/v1/notify { handle, title, body, url? }`\n * with an API key that has `notify:write`, for an app whose registered\n * domains include this one. Plain text only (title up to 60\n * characters, body up to 180), `url` only on this sign-in domain itself\n * (the app asks the person before opening it), about 3\n * a day per person. A 410 means the person turned you off: forget the\n * handle. Default false.\n */\n notifications?: boolean;\n};\n\nexport type CnfJwk = {\n kty: \"OKP\";\n crv: \"Ed25519\";\n x: string;\n};\n\nexport type SignInResult = {\n sdJwtVc: string;\n /** The nonce the presentation is bound to (yours when you passed `nonce`). */\n nonce: string;\n /**\n * The person's Prson ID for your site: stable across sign-ins, different on\n * every other site. Check the presentation on your server and use the\n * verifier's `prsonId` there; this copy is for your page. (`cnf.jwk.x`.)\n *\n * Show who is signed in (this ID, or the account/name your backend maps\n * it to) right after sign-in, also from the `signed_in` event: whoever\n * scans the code first signs in, so the person at the screen must be able\n * to see it's them.\n */\n prsonId: string;\n claims: Record<string, unknown>;\n cnf: { jwk: CnfJwk };\n credential: {\n vct: string;\n iss: string;\n kid: string;\n expiresAt: number;\n };\n /**\n * Present when the host set `required.uniqueHumanId: true`: a\n * notary-signed, domain-scoped uniqueness credential. OPAQUE\n * pass-through \u2014 verify it SERVER-SIDE with\n * `@prson/login-verifier`'s `verifyUniqueHumanId({...},\n * { expectedAudience: \"your.host\" })`, then use\n * `envelope.uniqueIdHash` as the sybil-resistant account key.\n * Stable for this human at your domain; uncorrelatable anywhere else.\n */\n uniqueHumanId?: {\n envelope: Record<string, unknown>;\n signature: string;\n kid: string;\n } | null;\n /**\n * Present when you set `notifications: true` and the person ticked \"Let\n * {site} send you notifications\": the handle your backend sends with\n * (see SignInOptions.notifications). null when they didn't.\n */\n notifications?: { handle: string } | null;\n session: PrsonLoginSession;\n};\n\nexport type { ExpiryReason } from \"./session.js\";\n\n// Constants exported for verifier-side consumers + diagnostics.\nexport const PROTOCOL_VERSION = \"prson_vp_v1\";\n/**\n * Data-channel envelope version this SDK speaks, announced to the wallet\n * in the request (`envelopeVersion`). 2 = both sides box with their\n * session keys (sender-authenticated), and the wallet binds its session\n * key into the signed presentation (`prson_wsk`). See SECURITY.md \u00A74.\n */\nexport const ENVELOPE_VERSION = 2;\nexport const TRUSTED_ISSUER = \"did:web:app.prson.net\";\n/** The dev API's issuer and where it publishes its keys. Trusted only with\n * `environment: \"dev\"`; never accept dev credentials in production. */\nexport const TRUSTED_ISSUER_DEV = \"did:web:prson-app-dev.web.app:.well-known:dev\";\nexport const ISSUER_JWKS_DEV = \"https://prson-api-dev.powerhouse.workers.dev/.well-known/jwt-vc-issuer\";\n\n/** Which issuer a sign-in trusts: production's, or the dev API's with `environment: \"dev\"`. */\nexport function issuerFor(opts: { environment?: \"production\" | \"dev\" }): { trustedIssuer: string; jwksUri?: string } {\n return opts.environment === \"dev\" ? { trustedIssuer: TRUSTED_ISSUER_DEV, jwksUri: ISSUER_JWKS_DEV } : { trustedIssuer: TRUSTED_ISSUER };\n}\nexport const KNOWN_VCTS = [\n \"https://app.prson.net/credentials/verified-human/v1\",\n \"https://app.prson.net/credentials/verified-identity/v1\",\n] as const;\n/** Self-signed wallet credential \u2014 accepted only when the SDK is\n * invoked with `allowAnonymous: true`. Carries only `cnf.jwk` + the\n * KB-JWT fields; no notary signature. */\nexport const ANONYMOUS_WALLET_VCT =\n \"https://app.prson.net/credentials/anonymous-wallet/v1\";\n// Testing pass: 2-minute sessions surface expiry / renewal bugs\n// quickly. Production target is 10 / 15. Keep these in sync with\n// `SESSION_TTL_SECONDS` in `cloudflare-workers/signaling-worker/src/index.ts`.\nexport const DEFAULT_TTL_MINUTES = 2;\nexport const MAX_TTL_MINUTES = 2;\n/** Cloudflare Worker single-API-surface base URL (production). */\nexport const SIGNALING_BASE = \"https://signaling.prson.net\";\n\n/** Dev environment Worker base. Selected via `signIn({ environment: \"dev\" })`,\n * or override either env with an explicit `signalingBase` (e.g. a local\n * Worker at `https://localhost:8787`). */\nexport const SIGNALING_BASE_DEV = \"https://signaling-dev.prson.net\";\n\n/** Map an `environment` shorthand to its Worker base URL. */\nexport function resolveSignalingBase(opts: {\n environment?: \"production\" | \"dev\";\n signalingBase?: string;\n}): string {\n if (opts.signalingBase) return opts.signalingBase;\n return opts.environment === \"dev\" ? SIGNALING_BASE_DEV : SIGNALING_BASE;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Concurrency guard \u2014 one in-flight sign-in at a time\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// A user who clicks \"Sign in\" twice in quick succession (because the\n// first click felt slow, or the QR scrolled out of view) would\n// otherwise spawn two parallel sign-in flows, each holding its own\n// draftToken / WS / RTCPeerConnection / QR card. The second sign-in's\n// QR would stack on top of the first; both wallets would try to\n// claim; the verifier might commit the wrong identity.\n//\n// Semantics:\n// * Only the PHASE BEFORE signIn() resolves is treated as\n// \"in-flight\". Once signIn() has resolved into a live session,\n// that session is no longer in-flight; a fresh signIn() does\n// NOT terminate the live session it just supersedes (the host\n// page can keep the prior session handle if it needs to).\n// * A second signIn() while a first is in-flight calls the first\n// one's abort(), which runs the registered teardowns in LIFO\n// order (latest resource first). The first signIn() then sees\n// the abort signal on its next `await` and throws\n// `LoginAbortedError`.\n//\n// Implementation: module-scoped current-inflight slot + per-call\n// disposer chain that the displacement awaits.\n\n/**\n * Thrown by `PrsonLogin.signIn()` when a NEWER `signIn()` call\n * displaces the current in-flight one. Host pages typically ignore\n * this \u2014 the user's second click is the cancellation signal \u2014 but\n * the typed error lets you distinguish it from real failures.\n */\nexport class LoginAbortedError extends PrsonLoginError {\n constructor(message = \"sign-in aborted by a newer signIn() call\") {\n super(\"aborted\", message);\n this.name = \"LoginAbortedError\";\n }\n}\n\ninterface InflightSignIn {\n /** True once a newer signIn() has called `abort()`. */\n aborted: boolean;\n /**\n * Run the registered teardowns in LIFO order and mark\n * `aborted = true`. Resolves after every teardown has settled.\n */\n abort(message?: string): Promise<void>;\n /** Push a teardown thunk; runs once on `abort()` or normal exit. */\n pushTeardown(t: () => void | Promise<void>): void;\n /**\n * Rejects with `LoginAbortedError` the moment `abort()` is called. The\n * flow races its waits against it, so a closed dialog or a newer\n * `signIn()` settles this one at once instead of leaving it waiting\n * for a wallet that will never come.\n */\n whenAborted: Promise<never>;\n}\n\nlet _inflight: InflightSignIn | null = null;\n\nfunction makeInflight(): InflightSignIn {\n const teardowns: Array<() => void | Promise<void>> = [];\n let rejectAborted: (e: Error) => void = () => {};\n const whenAborted = new Promise<never>((_, reject) => {\n rejectAborted = reject;\n });\n whenAborted.catch(() => {\n /* only an error for whoever races it */\n });\n const self: InflightSignIn = {\n aborted: false,\n whenAborted,\n pushTeardown(t) {\n teardowns.push(t);\n },\n async abort(message?: string) {\n if (self.aborted) return;\n self.aborted = true;\n rejectAborted(new LoginAbortedError(message));\n // LIFO so we close the most-recently-acquired resource first\n // \u2014 typically the transport / RTCPeerConnection \u2014 and unwind\n // backwards through signaling, QR, draft state.\n while (teardowns.length) {\n const t = teardowns.pop();\n try {\n await t?.();\n } catch {\n /* swallow \u2014 best-effort cleanup */\n }\n }\n },\n };\n return self;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Public fa\u00E7ade\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport class PrsonLogin {\n /**\n * Drive a full sign-in. The promise resolves once the wallet has\n * delivered a verified SD-JWT-VC; the returned session lives until\n * one of the four `ExpiryReason` triggers.\n *\n * Without `ui.mountQrInto` the SDK shows its own dialog and handles\n * everything in it: an expired code or a failure offers a fresh code\n * (a new draft, and a new nonce when `nonce` is a function) while this\n * promise keeps waiting; closing the dialog rejects with\n * `LoginAbortedError` (or with the error on screen, if one was shown).\n */\n static async signIn(opts: SignInOptions = {}): Promise<SignInResult> {\n // \u2500\u2500\u2500 concurrency guard \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Tear down any prior in-flight sign-in BEFORE we mint a fresh\n // draft. Awaited so the prior's QR / signaling are gone before\n // the new one mounts \u2014 gives the user immediate visual\n // confirmation that the second click cancelled the first. If\n // there's no prior, `prior?.abort()` is a cheap no-op.\n const prior = _inflight;\n if (prior) await prior.abort();\n const me = makeInflight();\n _inflight = me;\n // Turn a CSP block of Prson's hosts into an error that says what to allow.\n const csp = watchCsp(resolveSignalingBase(opts), issuerFor(opts).jwksUri);\n // Dev mode trusts the dev issuer, whose test identities anyone can make: say so on a real site.\n if (opts.environment === \"dev\" && typeof location !== \"undefined\" && !/^(localhost|127\\.0\\.0\\.1|\\[::1\\])$|\\.localhost$|\\.test$/.test(location.hostname)) {\n console.warn(`Prson sign-in is in dev mode on ${location.hostname}: it accepts dev credentials. Remove environment: \"dev\" before going live.`);\n }\n me.pushTeardown(() => csp.stop());\n\n try {\n const domain = opts.domain ?? window.location.origin.replace(/^https?:\\/\\//, \"\");\n const theme = opts.ui?.theme ?? \"auto\";\n const titleId = `prson-login-title-${b64u(crypto.getRandomValues(new Uint8Array(6)))}`;\n const explicitMount = resolveMount(opts.ui?.mountQrInto);\n\n // No mount supplied \u2192 the SDK's own dialog, opened when the first\n // code is ready (no empty scrim while the draft is made). Esc /\n // click-outside / its close button abort the in-flight signIn so\n // `await signIn(...)` rejects with `LoginAbortedError`. Zero-config\n // for the partner.\n const dialog: { current: { mount: HTMLElement; dispose: () => void } | null } = { current: null };\n const getMount = (): HTMLElement => {\n if (explicitMount) return explicitMount;\n if (!dialog.current) {\n const m = createModalQrMount({ titleId, onDismiss: () => void me.abort(\"sign-in closed\") });\n dialog.current = m;\n me.pushTeardown(() => m.dispose());\n }\n return dialog.current.mount;\n };\n\n // One attempt per code shown; a refresh (expiry, \"Try again\")\n // starts the next.\n for (;;) {\n const attempt = makeInflight();\n me.pushTeardown(() => attempt.abort());\n let requestRestart: () => void = () => {};\n const restart = new Promise<\"restart\">((resolve) => {\n requestRestart = () => resolve(\"restart\");\n });\n const context: LoginQrContext = {\n mode: explicitMount ? \"inline\" : \"modal\",\n domain,\n titleId,\n getAppUrl: opts.ui?.getAppUrl ?? GET_APP_URL,\n // A no-op once this sign-in is over or the host re-called\n // signIn() from the `prson-login-refresh-requested` event.\n refresh: () => {\n if (!me.aborted && !attempt.aborted && _inflight === me) requestRestart();\n },\n cancel: () => void me.abort(\"sign-in closed\"),\n };\n const ui: AttemptUi = { handle: null };\n const run = runAttempt(opts, { domain, getMount, theme, context, attempt, me, ui });\n run.catch(() => {\n /* raced below; an abandoned attempt may fail later, quietly */\n });\n\n try {\n const out = await Promise.race([run, restart, me.whenAborted]);\n if (out === \"restart\") {\n await attempt.abort();\n continue;\n }\n // Success: the code (and dialog) go; the transport stays for the session.\n ui.handle?.dispose();\n dialog.current?.dispose();\n return out;\n } catch (caught) {\n if (caught instanceof LoginAbortedError) throw caught;\n const err = asLoginError(await csp.explain(caught));\n if (err instanceof PrsonCspError && typeof console !== \"undefined\") console.error(err.message);\n // Show what went wrong where the person is looking.\n ui.handle?.update?.({ state: \"error\", message: friendlyError(err) });\n if (!dialog.current || !ui.handle?.update) {\n // Inline (the host owns the page and keeps the card, as 0.1\n // did), a renderer that can't show errors, or a failure\n // before any code was shown: reject now.\n if (dialog.current) await me.abort();\n throw err;\n }\n // In the dialog: wait for \"Try again\" (a new attempt) or close\n // (reject with this error rather than a bare \"aborted\").\n try {\n await Promise.race([restart, me.whenAborted]);\n } catch {\n throw err;\n }\n await attempt.abort();\n }\n }\n } finally {\n csp.stop();\n // Release the slot ONLY if we still own it. If a newer signIn()\n // displaced us mid-flight, `_inflight` already points at\n // someone else; we mustn't clobber their entry. The displacing\n // signIn() already called our `abort()`, so the teardowns ran.\n if (_inflight === me) _inflight = null;\n }\n }\n\n /**\n * Rebind to a session that was previously established for the same\n * holder pk. Phase 2 placeholder \u2014 the SDK has no cross-page-load\n * state today; callers should redirect through `signIn` on each\n * page load (the cookie-on-the-server is the source of truth).\n */\n static async restore(_opts: {\n cnfJwk: CnfJwk;\n onExpiry?: (reason: ExpiryReason) => void;\n }): Promise<PrsonLoginSession | null> {\n return null;\n }\n}\n\n/** Where \"Don't have Prson? Get it\" points unless `ui.getAppUrl` says otherwise. */\nexport const GET_APP_URL = \"https://app.prson.net/\";\n\ntype AttemptUi = { handle: LoginQrHandle | null };\n\n/**\n * One code on screen, from the draft to a verified presentation. Every\n * wait is raced against both this attempt's and the whole sign-in's\n * abort, so a refresh or a closed dialog ends it at once.\n */\nasync function runAttempt(\n opts: SignInOptions,\n env: {\n domain: string;\n getMount: () => HTMLElement;\n theme: \"light\" | \"dark\" | \"auto\";\n context: LoginQrContext;\n attempt: InflightSignIn;\n me: InflightSignIn;\n ui: AttemptUi;\n },\n): Promise<SignInResult> {\n const { domain, attempt, me } = env;\n const guard = <T>(p: Promise<T>): Promise<T> => Promise.race([p, attempt.whenAborted, me.whenAborted]);\n /** Throw `LoginAbortedError` if a newer signIn() (or a refresh) has displaced us. */\n const checkAborted = () => {\n if (me.aborted || attempt.aborted) throw new LoginAbortedError();\n };\n\n const ttlMaxMinutes = Math.min(\n Math.max(opts.ttlMinutes ?? DEFAULT_TTL_MINUTES, 1),\n MAX_TTL_MINUTES,\n );\n\n // 1. Generate the ephemeral X25519 keypair the wallet will encrypt\n // its envelope to. Stays in memory only \u2014 never written to\n // storage, never crosses any network boundary.\n const ephKeys = await guard(generateEphemeralKeypair());\n checkAborted();\n\n // 2. Build the verifier request blob. The reqId is content-bound\n // so the wallet sees the same canonical bytes the Worker stored\n // (anti-tamper, see SECURITY.md \u00A73).\n const given = typeof opts.nonce === \"function\" ? await guard(Promise.resolve(opts.nonce())) : opts.nonce;\n checkAborted();\n if (given !== undefined && (typeof given !== \"string\" || !/^[A-Za-z0-9_-]{22,128}$/.test(given))) {\n throw new PrsonLoginError(\"invalid_options\", \"nonce must be 22-128 base64url characters (at least 16 random bytes)\");\n }\n const nonce = given ?? b64u(crypto.getRandomValues(new Uint8Array(32)));\n const request = {\n domain,\n nonce,\n browserPk: ephKeys.publicKeyB64u,\n required: opts.required ?? {},\n // Carried into the wallet's drawer so an \"Anonymous\" option is\n // offered. The SDK side enforces acceptance below at verify time;\n // the wallet enforces drawer UX based on this flag.\n allowAnonymous: opts.allowAnonymous === true,\n // Sponsorship offer (advisory on the wire \u2014 the server enforces\n // the stored grant's domain/caps/budget at charge time).\n ...(opts.sponsorship?.grantId ? { sponsorship: { grantId: opts.sponsorship.grantId } } : {}),\n // If set, the wallet signs in with a random, device-only key for\n // this site (kept on that phone and reused there; not derived from\n // the recovery phrase). Closes M-5; see SignInOptions.ephemeralIdentity.\n ephemeralIdentity: opts.ephemeralIdentity === true,\n // QR-mode remote navigation \u2014 wallet surfaces Prev / Next /\n // Submit / Logout / Mouse on a persistent banner. See\n // SignInOptions.remoteNavigation + bind.ts:enableRemoteNavigation.\n remoteNavigation: opts.remoteNavigation === true,\n // Pre-grant mouse control \u2014 wallet enables the Touchpad /\n // Magic wand buttons on the banner drawer from session start.\n // See SignInOptions.mouseControl + bindMouse's ambient\n // subscriber path.\n mouseControl: opts.mouseControl === true,\n // Website notifications: the wallet offers an unticked opt-in row.\n // See SignInOptions.notifications.\n ...(opts.notifications === true ? { notifications: true } : {}),\n // App-to-app return leg \u2014 validated here (fail fast at the\n // integrator's desk) AND in the wallet (the enforcing side).\n ...(opts.returnUrl ? { returnUrl: validateReturnUrl(opts.returnUrl, domain) } : {}),\n ttlMaxMinutes,\n // Envelope v2: the wallet boxes every message with its session key\n // and binds that key into the presentation; it may then insist our\n // messages come from browserPk. Older wallets ignore the field.\n envelopeVersion: ENVELOPE_VERSION,\n };\n\n // 3. Register the draft directly with the Cloudflare Worker.\n // Anonymous + IP rate-limited. No TURN allocation (current relays):\n // relay capacity is minted only after a wallet claims the code.\n const draft: DraftResult = await guard(\n createDraft(request, {\n signalingBase: resolveSignalingBase(opts),\n }),\n );\n checkAborted();\n\n // 4. Render the QR encoding the deep-link URL the wallet scans /\n // the mobile browser taps. Register its teardown FIRST so an\n // abort during signaling/connect immediately removes the\n // on-screen artefact even before the network resources close.\n const qrUrl = buildDeepLinkUrl({\n reqId: draft.reqId,\n browserPk: ephKeys.publicKeyB64u,\n nonce,\n domain,\n request,\n serverTs: draft.serverTs,\n });\n const handle = renderLoginQr(qrUrl, env.getMount(), env.theme, env.context);\n env.ui.handle = handle;\n attempt.pushTeardown(() => handle.dispose());\n const show = (s: Parameters<NonNullable<LoginQrHandle[\"update\"]>>[0]) => {\n if (!attempt.aborted && !me.aborted) void handle.update?.(s);\n };\n\n // 5. Open the WS to the Cloudflare Worker. The DO is in DRAFT until\n // a wallet's /session/claim flips it to ACTIVE; we'll still\n // receive cached SDP/ICE from the wallet at that point.\n const signaling = await guard(\n connectSignaling({\n url: draft.signalingWss,\n role: \"browser\",\n sigToken: draft.draftToken,\n }),\n );\n attempt.pushTeardown(() => signaling.close());\n checkAborted();\n // The relay's `ice` (a wallet claimed the code) or the wallet's first\n // message: the person scanned and is approving on the phone. If they\n // didn't scan it, someone else did \u2014 the page says so.\n let scanned = false;\n const markScanned = () => {\n if (scanned) return;\n scanned = true;\n show({ state: \"scanned\" });\n };\n signaling.onMessage((m) => {\n if (m.msg === \"answer\" || m.msg === \"peer-ready\") markScanned();\n });\n\n // 6. Bring up the RTCPeerConnection + data channel, relay-only: the\n // browser gathers only TURN candidates, so its own addresses never\n // reach the phone (the wallet is relay-only too). Current relays\n // send the TURN servers over the socket once a wallet has claimed\n // the code (`{type:\"ice\"}`), so nothing is allocated for a QR\n // nobody scans; older relays put them in the draft response.\n let iceServers: RTCIceServer[];\n if (draft.turn) {\n iceServers = [{ urls: draft.turn.urls, username: draft.turn.username, credential: draft.turn.credential }];\n } else {\n iceServers = await guard(signaling.awaitIce());\n checkAborted();\n markScanned();\n }\n const transport = await guard(\n establishTransport({\n signaling,\n role: \"browser\",\n iceServers,\n }),\n );\n // From here on, `transport` owns the signaling channel \u2014 its\n // close() will close the WS too.\n attempt.pushTeardown(() => transport.close());\n checkAborted();\n show({ state: \"approving\" });\n\n // 7. Wait for the wallet's encrypted envelope on the data channel.\n // The wallet emits exactly one `prson_vp_v1 / msg=presentation`\n // on initial sign-in; renewals come later via the session handle.\n const first = await guard(transport.awaitFirstMessage());\n checkAborted();\n show({ state: \"verifying\" });\n const { envelope, senderPk } = await openEnvelope(first, ephKeys);\n if (envelope.v !== PROTOCOL_VERSION || envelope.msg !== \"presentation\") {\n throw new PrsonLoginError(\"protocol\", `Unexpected first message: ${envelope.v}/${envelope.msg}`);\n }\n // After the post-ROADMAP-\u00A71 envelope grammar made `presentation`\n // optional (so it can be absent on `display-update` /\n // `credential-revoked`), the narrowed `msg === \"presentation\"`\n // branch still has it as `string | undefined` to TypeScript.\n // Defensive runtime check + local rebind for type narrowing.\n const presentationStr = envelope.presentation;\n if (!presentationStr) {\n throw new PrsonLoginError(\"protocol\", \"Initial presentation envelope had no presentation field\");\n }\n\n // 8. Verify the presentation cryptographically before we hand it\n // to the host application. The five rules in SECURITY.md \u00A77\n // are enforced here. When allowAnonymous is set, we also accept\n // the self-signed anonymous-wallet VCT (different verification\n // path: cnf.jwk == issuer, no notary signature to check).\n const acceptedVcts = opts.allowAnonymous\n ? [...KNOWN_VCTS, ANONYMOUS_WALLET_VCT]\n : [...KNOWN_VCTS];\n const verified = await verifyPresentation(presentationStr, {\n expectedAudience: `https://${domain}`,\n expectedNonce: nonce,\n acceptedVcts,\n ...issuerFor(opts),\n });\n if (!verified.ok) {\n throw new PrsonLoginError(\"presentation_rejected\", `Presentation rejected: ${verified.reason}`, verified.reason);\n }\n\n // Envelope v2: the holder signed its session key into the\n // presentation (`prson_wsk`). The envelope must have been boxed by\n // that very key \u2014 then nobody else (a relay, someone who saw the QR)\n // can talk to this page as the wallet, or swap the key the page\n // sends to. A wallet that predates it gets a legacy session: sign-in\n // and renewals work, but page-acting messages and request replies are\n // ignored and `request()` resolves \"unsupported\" (see session.ts).\n const boundKey = verified.binding.walletSessionPk;\n if (boundKey) {\n if (senderPk !== boundKey) {\n throw new PrsonLoginError(\"presentation_rejected\", \"Presentation rejected: envelope not sent by the wallet's signed session key\", \"session_key_mismatch\");\n }\n if (envelope.walletSessionPk !== undefined && envelope.walletSessionPk !== boundKey) {\n throw new PrsonLoginError(\"presentation_rejected\", \"Presentation rejected: walletSessionPk differs from the signed one\", \"session_key_mismatch\");\n }\n } else if (typeof console !== \"undefined\") {\n // eslint-disable-next-line no-console\n console.warn(\n \"[@prson/login-sdk] This Prson app predates sender-authenticated envelopes;\" +\n \" remote navigation, mouse and file input are off for this session. Ask the person to update the app.\",\n );\n }\n\n // Enforce the level floor against the VERIFIED claims (the wallet\n // already gates UX-side, but the host's policy must not depend on\n // the wallet's good behaviour). Anonymous-wallet credentials carry\n // no level claim and are governed by `allowAnonymous` alone.\n // Default floor is 1 \u2014 a `verified_human: false` (level-0)\n // credential is only accepted when the host explicitly set\n // `required.minVerificationLevel: 0`.\n if (verified.credential.vct !== ANONYMOUS_WALLET_VCT) {\n const minLevel = opts.required?.minVerificationLevel ?? 1;\n const claimedLevel =\n typeof verified.claims.verification_level === \"number\"\n ? verified.claims.verification_level\n : 0;\n if (claimedLevel < minLevel) {\n throw new PrsonLoginError(\n \"level_too_low\",\n `Presentation rejected: verification_level ${claimedLevel} below required ${minLevel}`,\n );\n }\n }\n\n // Unique-human id (when required): the wallet attaches it to the\n // initial envelope; we gate on presence here and pass it through\n // OPAQUE \u2014 cryptographic verification belongs on the host's server\n // (verifier-node `verifyUniqueHumanId`), since a browser-side check\n // could be bypassed by the page's own code anyway.\n const uniqueHumanId =\n (envelope as { uniqueHumanId?: SignInResult[\"uniqueHumanId\"] }).uniqueHumanId ?? null;\n if (opts.required?.uniqueHumanId === true && !uniqueHumanId) {\n throw new PrsonLoginError(\"unique_human_missing\", \"Presentation rejected: required uniqueHumanId credential missing\");\n }\n // Notification handle (when asked for and the person opted in):\n // opaque, like uniqueHumanId; the API checks it when the site sends.\n const notifyHandle = opts.notifications === true ? notifyHandleFrom(envelope) : null;\n checkAborted();\n\n // 9. Success: let the UI show it (a short check animation, skipped\n // under reduced motion), then the caller tears the code down. The\n // transport stays open for renewals; the session handle owns it\n // from here on.\n const hold = handle.update?.({ state: \"success\", domain });\n if (hold && typeof (hold as Promise<void>).then === \"function\") {\n await Promise.race([hold, new Promise((r) => setTimeout(r, 1500))]);\n }\n checkAborted();\n\n // The host needs both the SignInResult (returned synchronously\n // below) AND a `signed_in` event on the typed event stream (so\n // `onAny` listeners get a uniform lifecycle log). We build the\n // result first, hand it to the session as the initial-signed-in\n // payload (the session fires `signed_in` via microtask), and\n // return the same object.\n const result: SignInResult = {\n sdJwtVc: presentationStr,\n nonce,\n prsonId: verified.cnf.jwk.x,\n claims: verified.claims,\n cnf: verified.cnf,\n credential: verified.credential,\n uniqueHumanId,\n ...(opts.notifications === true ? { notifications: notifyHandle ? { handle: notifyHandle } : null } : {}),\n // session is filled in below \u2014 temporary placeholder cast\n // avoids a circular-self-reference in the literal.\n session: undefined as unknown as PrsonLoginSession,\n };\n\n const session = new PrsonLoginSession({\n cnf: verified.cnf,\n credential: verified.credential,\n transport,\n ephKeys,\n verifierContext: {\n expectedAudience: `https://${domain}`,\n expectedNonceFactory: () => nonce, // renewals carry a fresh nonce; see session.ts\n // The same set as the sign-in, so an anonymous session can renew.\n acceptedVcts,\n ...issuerFor(opts),\n },\n // Renewal anti-replay baseline: a renewal must be strictly newer.\n initialPresentation: { presentation: presentationStr, iat: verified.binding.iat },\n // Cache the verified claims so the session can diff them\n // against future `claim-update` envelopes \u2014 see ROADMAP \u00A71.\n initialClaims: verified.claims,\n // Fire `signed_in` on the typed event stream. Microtask-\n // deferred inside the constructor, so listeners attached\n // synchronously after this `signIn()` resolves still\n // receive it.\n initialSignedInResult: result,\n // Forward `walletSessionPk` + `preferredLanguage` from the\n // FIRST envelope (which `signIn()` consumed before the session\n // existed) so they're available immediately on the session\n // handle. Without this seed the session would have\n // `walletSessionPk: null` (breaking the request channel) and\n // `preferredLanguage: null` (host can't localise on first\n // paint) until a subsequent envelope arrives.\n // Pinned from the signed presentation; for a legacy wallet, the\n // first envelope's field (nothing better exists).\n walletSessionPk: boundKey ?? envelope.walletSessionPk,\n legacyChannel: !boundKey,\n initialPreferredLanguage: envelope.preferredLanguage,\n // Public-profile fields the wallet may stamp onto the first\n // envelope. They aren't part of the verified-human VC (which\n // carries verification facts only), so without seeding here\n // the host's `session.displayName` would stay null until a\n // later `display-update` envelope.\n initialDisplayName: envelope.displayName,\n initialAvatar: envelope.avatar,\n });\n result.session = session;\n\n return result;\n}\n\n/** A failure in words the person signing in can act on. */\nfunction friendlyError(err: unknown): string {\n if (err instanceof PrsonLoginError) {\n switch (err.code) {\n case \"csp_blocked\":\n return \"This site's security settings blocked Prson. The site's owner needs to allow Prson in its Content-Security-Policy.\";\n case \"rate_limited\":\n return \"Too many sign-ins from this network. Wait a moment and try again.\";\n case \"network\":\n return \"Couldn't reach Prson. Check your connection and try again.\";\n case \"expired\":\n return \"This code expired. Get a new code and try again.\";\n case \"unique_human_missing\":\n return \"This site needs a passport or ID card verified in the Prson app.\";\n case \"level_too_low\":\n return \"This site needs a more verified identity than the one chosen.\";\n default:\n break;\n }\n }\n const m = err instanceof Error ? err.message : String(err);\n if (/Too many login sessions/i.test(m)) return \"Too many sign-ins from this network. Wait a moment and try again.\";\n if (/createDraft failed|Failed to fetch|NetworkError|signaling: WS/i.test(m)) {\n return \"Couldn't reach Prson. Check your connection and try again.\";\n }\n if (/uniqueHumanId/i.test(m)) return \"This site needs a passport or ID card verified in the Prson app.\";\n if (/verification_level/i.test(m)) return \"This site needs a more verified identity than the one chosen.\";\n if (/data channel/i.test(m)) return \"Your phone couldn't connect to this browser. Try again.\";\n return \"Sign-in didn't finish. Try again.\";\n}\n\n// Re-export for verifier-only consumers + custom UIs.\nexport { PrsonLoginSession };\nexport { PrsonCspError, PRSON_CONNECT_SRC, connectSourcesFor, cspStyleNonce } from \"./csp.js\";\nexport { PrsonLoginError, type PrsonLoginErrorCode } from \"./errors.js\";\nexport { NOTIFY_HANDLE, notifyHandleFrom } from \"./notify.js\";\nexport type { LoginQrContext, LoginQrHandle, LoginQrRenderer, LoginUiState } from \"./qr.js\";\nexport type { Renewal };\n\n// Request channel \u2014 types + DOM-binding helpers. `bindInput` /\n// `bindForm` are the kiosk-companion entry points; they synthesise\n// a `session.request(...)` call from a DOM element and write the\n// wallet's reply back into the page.\nexport type {\n LoginRequest,\n LoginResponse,\n RequestOptions,\n InputType,\n InputOption,\n InputFormField,\n} from \"./requests.js\";\nexport {\n bindInput,\n bindForm,\n bindMouse,\n enableRemoteNavigation,\n isSensitiveField,\n type BindController,\n type BindMouseOptions,\n type RemoteNavController,\n type RemoteNavOptions,\n} from \"./bind.js\";\n\n// Verifications (an organisation's request, e.g. \"sign this PDF with your\n// verified name\"): show the share_url and wait until it's answered.\nexport {\n awaitVerification,\n VerificationAbortedError,\n VerificationClosedError,\n type AwaitVerificationOptions,\n type VerificationStatus,\n} from \"./verification.js\";\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Internal helpers\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction b64u(bytes: Uint8Array): string {\n let s = \"\";\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]!);\n return btoa(s).replace(/=+$/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n}\n\n/**\n * Validate SignInOptions.returnUrl: HTTPS, and its host (incl. any\n * explicit port) must equal the login domain exactly. The wallet\n * re-validates independently \u2014 this copy exists so a misconfigured\n * integration fails at the integrator's desk, not on the user's phone.\n */\nfunction validateReturnUrl(returnUrl: string, domain: string): string {\n let parsed: URL;\n try {\n parsed = new URL(returnUrl);\n } catch {\n throw new PrsonLoginError(\"invalid_options\", `returnUrl is not a valid URL: ${returnUrl}`);\n }\n if (parsed.protocol !== \"https:\") {\n throw new PrsonLoginError(\n \"invalid_options\",\n \"returnUrl must be https:// (custom schemes are refused \u2014 any app \" +\n \"could claim them; use a Universal Link / App Link on your domain)\"\n );\n }\n if (parsed.host.toLowerCase() !== domain.toLowerCase()) {\n throw new PrsonLoginError(\n \"invalid_options\",\n `returnUrl host (${parsed.host}) must equal the login domain (${domain})`\n );\n }\n return returnUrl;\n}\n\nfunction resolveMount(into: string | HTMLElement | undefined): HTMLElement | null {\n if (!into) return null;\n if (typeof into === \"string\") return document.querySelector(into);\n return into;\n}\n\n/**\n * Build the deep-link URL the QR encodes. We emit the **universal-link\n * form** (`https://app.prson.net/login/v1?\u2026`) \u2014 see\n * [SECURITY-AUDIT-2026-05-28.md \u00A7C-2](../../SECURITY-AUDIT-2026-05-28.md).\n *\n * Custom URI schemes (`prson://\u2026`) have no cryptographic app-binding;\n * any installed app can register the same scheme and intercept the\n * tap. Universal Links (iOS) + App Links (Android) are bound to our\n * domain via `apple-app-site-association` + `assetlinks.json`, which\n * are signed against the wallet's signing-cert hash + our TLS cert.\n * A malicious app cannot register a competing handler.\n *\n * The wallet accepts only this form for sign-in; it no longer opens\n * `prson://login/v1` links at all.\n */\nfunction buildDeepLinkUrl(args: {\n reqId: string;\n browserPk: string;\n nonce: string;\n domain: string;\n request: object;\n serverTs: number;\n}): string {\n const params = new URLSearchParams({\n s: args.reqId,\n p: args.browserPk,\n n: args.nonce,\n d: args.domain,\n req: b64u(new TextEncoder().encode(JSON.stringify(args.request))),\n // M-3 / v2: the server-issued timestamp the wallet must fold into\n // its claim signature. The Worker uses its own stored copy at\n // verify time; tampering this in the QR breaks the signature.\n t: String(args.serverTs),\n });\n return `https://app.prson.net/login/v1?${params.toString()}`;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,QAAM,QAAQ;AAEd,QAAa,sBAAb,MAAgC;MAM5B,cAAA;AALA,aAAA,cAAc;AACd,aAAA,iBAAiB;AAKb,cAAM,gBAAgB,OAAO,SAAS,cAC/B,KAAK,UAAW,KAA4B,WAC7C;AAEN,YAAI,iBAAiB,cAAc,oBAAoB,QAAW;AAC9D,eAAK,UAAU;AACf,eAAK,cAAc;AACnB,eAAK,iBAAiB;;MAE9B;MAEA,YAAY,QAAc;AACtB,YAAI,CAAC,KAAK,eAAe,CAAC,KAAK,SAAS;AACpC,gBAAM,IAAI,MAAM,iDAAiD;;AAErE,cAAM,MAAM,IAAI,WAAW,MAAM;AACjC,iBAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,OAAO;AACxC,eAAK,QAAQ,gBAAgB,IAAI,SAAS,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G;AAC3E;AAQA,SAAS,kBAAkB,WAAmB,QAAwB;AACpE,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,SAAS;AAAA,EAC5B,QAAQ;AACN,UAAM,IAAI,gBAAgB,mBAAmB,iCAAiC,SAAS,EAAE;AAAA,EAC3F;AACA,MAAI,OAAO,aAAa,UAAU;AAChC,UAAM,IAAI;AAAA,MACR;AAAA,MACA;AAAA,IAEF;AAAA,EACF;AACA,MAAI,OAAO,KAAK,YAAY,MAAM,OAAO,YAAY,GAAG;AACtD,UAAM,IAAI;AAAA,MACR;AAAA,MACA,mBAAmB,OAAO,IAAI,kCAAkC,MAAM;AAAA,IACxE;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,aAAa,MAA4D;AAChF,MAAI,CAAC,KAAM,QAAO;AAClB,MAAI,OAAO,SAAS,SAAU,QAAO,SAAS,cAAc,IAAI;AAChE,SAAO;AACT;AAiBA,SAAS,iBAAiB,MAOf;AACT,QAAM,SAAS,IAAI,gBAAgB;AAAA,IACjC,GAAG,KAAK;AAAA,IACR,GAAG,KAAK;AAAA,IACR,GAAG,KAAK;AAAA,IACR,GAAG,KAAK;AAAA,IACR,KAAK,KAAK,IAAI,YAAY,EAAE,OAAO,KAAK,UAAU,KAAK,OAAO,CAAC,CAAC;AAAA;AAAA;AAAA;AAAA,IAIhE,GAAG,OAAO,KAAK,QAAQ;AAAA,EACzB,CAAC;AACD,SAAO,kCAAkC,OAAO,SAAS,CAAC;AAC5D;",
|
|
6
6
|
"names": ["randomBytes", "generateKeyPair", "Poly1305", "box", "box", "openBox", "Coder", "URLSafeCoder", "b64uEncode", "b64uDecode", "b64uBytes", "b64uEncode", "active", "OVERLAY_CSS", "reply", "el", "ANONYMOUS_WALLET_VCT", "self"]
|
|
7
7
|
}
|