@tinycloud/operations 0.5.0-beta.0 → 0.5.0-beta.2
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/coverage.json +9 -1
- package/dist/artifacts.d.cts +1 -1
- package/dist/artifacts.d.ts +1 -1
- package/dist/cli-runtime.cjs +788 -180
- package/dist/cli-runtime.cjs.map +1 -1
- package/dist/cli-runtime.d.cts +1 -1
- package/dist/cli-runtime.d.ts +1 -1
- package/dist/cli-runtime.js +786 -179
- package/dist/cli-runtime.js.map +1 -1
- package/dist/{contract-DfyrluLB.d.cts → contract-zRklonbR.d.cts} +6 -3
- package/dist/{contract-DfyrluLB.d.ts → contract-zRklonbR.d.ts} +6 -3
- package/dist/delegation-binding.cjs +7 -0
- package/dist/delegation-binding.cjs.map +1 -1
- package/dist/delegation-binding.d.cts +15 -3
- package/dist/delegation-binding.d.ts +15 -3
- package/dist/delegation-binding.js +6 -0
- package/dist/delegation-binding.js.map +1 -1
- package/dist/index.cjs +816 -181
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +812 -178
- package/dist/index.js.map +1 -1
- package/dist/profile.cjs +5 -0
- package/dist/profile.cjs.map +1 -1
- package/dist/profile.d.cts +14 -2
- package/dist/profile.d.ts +14 -2
- package/dist/profile.js +4 -0
- package/dist/profile.js.map +1 -1
- package/dist/recovery.cjs +67 -0
- package/dist/recovery.cjs.map +1 -0
- package/dist/recovery.d.cts +38 -0
- package/dist/recovery.d.ts +38 -0
- package/dist/recovery.js +39 -0
- package/dist/recovery.js.map +1 -0
- package/dist/secret-request.cjs +271 -0
- package/dist/secret-request.cjs.map +1 -0
- package/dist/secret-request.d.cts +119 -0
- package/dist/secret-request.d.ts +119 -0
- package/dist/secret-request.js +222 -0
- package/dist/secret-request.js.map +1 -0
- package/generated/operations.json +1838 -89
- package/package.json +15 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/ms/index.js","../../../node_modules/@noble/hashes/src/_u64.ts","../../../node_modules/@noble/hashes/src/cryptoNode.ts","../../../node_modules/@noble/hashes/src/utils.ts","../../../node_modules/@noble/hashes/src/_md.ts","../../../node_modules/@noble/hashes/src/sha2.ts","../src/delegation-binding.ts","../../sdk-core/src/manifest.ts","../../sdk-core/src/capabilities.ts","../../../node_modules/@noble/hashes/src/blake3.ts","../../../node_modules/@noble/hashes/src/_blake.ts","../../../node_modules/@noble/hashes/src/blake2.ts","../../../node_modules/@noble/curves/src/ed25519.ts","../../../node_modules/@noble/curves/src/utils.ts","../../../node_modules/@noble/curves/src/abstract/modular.ts","../../../node_modules/@noble/curves/src/abstract/curve.ts","../../../node_modules/@noble/curves/src/abstract/edwards.ts","../../../node_modules/multiformats/src/bytes.ts","../../../node_modules/multiformats/src/vendor/base-x.js","../../../node_modules/multiformats/src/bases/base.ts","../../../node_modules/multiformats/src/bases/base32.ts","../../../node_modules/multiformats/src/bases/base36.ts","../../../node_modules/multiformats/src/bases/base58.ts","../../../node_modules/multiformats/src/vendor/varint.js","../../../node_modules/multiformats/src/varint.ts","../../../node_modules/multiformats/src/hashes/digest.ts","../../../node_modules/multiformats/src/cid.ts","../../sdk-core/src/policy/unified.ts","../src/artifacts.ts","../src/authority.ts","../src/state.ts","../src/contract.ts","../src/secrets.ts","../src/errors.ts"],"sourcesContent":["/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n","/**\n * Internal webcrypto alias.\n * We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.\n * Falls back to Node.js built-in crypto for Node.js <=v14.\n * See utils.ts for details.\n * @module\n */\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto: any =\n nc && typeof nc === 'object' && 'webcrypto' in nc\n ? (nc.webcrypto as any)\n : nc && typeof nc === 'object' && 'randomBytes' in nc\n ? nc\n : undefined;\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\nexport class SHA224 extends SHA256 {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD<SHA512> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA384 extends SHA512 {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\nexport class SHA512_224 extends SHA512 {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n","import { join } from \"node:path\";\nimport { parseSignedCompactUcanAttenuation } from \"@tinycloud/sdk-core\";\n\n// Keep the value import namespace-shaped so modules that import this one stay\n// compatible with lightweight node-sdk test doubles.\nimport * as nodeSdk from \"@tinycloud/node-sdk\";\nimport type {\n PermissionEntry,\n PortableDelegation,\n RuntimeDelegationActivator,\n ValidatedRuntimeDelegation,\n} from \"@tinycloud/node-sdk\";\n\nimport { DelegationRequestBindingSchema } from \"./artifacts.js\";\nimport { delegationWithinRequest, type OperationSpaceResolver } from \"./authority.js\";\nimport { DELEGATION_CID_PATTERN, STORED_GRANT_SKIP_REASONS, type OperationWarning, type StoredGrantSkipReason } from \"./contract.js\";\nimport {\n profilePath,\n readAdditionalDelegations,\n readJson,\n readSession,\n updateProfileStore,\n withProfileLock,\n writeJsonAtomic,\n} from \"./state.js\";\n\nexport { operationSpaceResolver } from \"./secrets.js\";\nexport { STORED_GRANT_SKIP_REASONS } from \"./contract.js\";\nexport type { OperationWarning, StoredGrantSkipReason } from \"./contract.js\";\n\n/**\n * Request bindings for delegations stored in `additional-delegations.json`.\n *\n * A compact-UCAN or signed-login (SIWE) record replays only when its\n * `authorityRequest` binding is valid and the capabilities its signed bytes\n * grant fit inside the binding's `requested`. Validated activation checks that\n * before anything is activated. Three writers produce bindings:\n *\n * - `tinycloud.auth.import`: the stored request the delegation was checked\n * against (`requestId` is that request's).\n * - `tc auth import` of an artifact with no request: exactly the delegation's\n * own signed capabilities (`unbound-import:<cid>`).\n * - The one-time migration of records stored before bindings existed: exactly\n * each record's own signed capabilities (`migrated:<cid>`).\n * - The CLI's own grants (`tc auth request --grant`, permission escalation),\n * once checked against the request they answer: exactly each grant's own\n * signed capabilities (`cli-grant:<cid>`). Their signed-login records carry\n * the `siweProof` replay verifies them from.\n *\n * Signed-login records the CLI stored without a `siweProof` cannot be\n * verified from signed bytes and are not installed by either runtime.\n *\n * The binding is local profile data. It stops records written by any other\n * path from granting authority. It does not stop someone who can write the\n * profile directory, who already holds the session key and the signed bytes.\n */\n\nexport type BindingSource = \"migration\" | \"unbound-import\" | \"cli-grant\";\n\nconst REQUEST_ID_PREFIX: Record<BindingSource, string> = {\n migration: \"migrated\",\n \"unbound-import\": \"unbound-import\",\n \"cli-grant\": \"cli-grant\",\n};\n\n/** The audit note written beside a binding the record's writer synthesized. */\nexport const BINDING_NOTES: Record<BindingSource, string> = {\n migration:\n \"Stored without a request binding before bindings were required. Bound at migration to exactly \" +\n \"its own signed capabilities, so replay refuses any delegation in this record that exceeds them.\",\n \"unbound-import\":\n \"Imported by `tc auth import` without a stored request. Bound to exactly its own signed \" +\n \"capabilities, so replay refuses any delegation in this record that exceeds them.\",\n \"cli-grant\":\n \"Granted to this CLI by `tc auth request --grant` or a permission escalation, and checked \" +\n \"against the request it answered. Bound to exactly its own signed capabilities, so replay \" +\n \"refuses any delegation in this record that exceeds them.\",\n};\n\n/** Short so a busy profile only defers migration to a later runtime. */\nconst MIGRATION_LOCK_TIMEOUT_MS = 250;\n\n/** The per-profile marker: present once that profile's unbound records were migrated. */\nexport function bindingMigrationPath(profile: string): string {\n return join(profilePath(profile), \"delegation-binding-migration.json\");\n}\n\n/**\n * Compact and signed-login records require a valid request binding and signed\n * proof. A legacy record with no proof is classified `other` only so replay\n * can report `proof_missing`; it never installs. Malformed headers are refused.\n *\n * A header must contain exactly one `Authorization` string key: other shapes\n * might reach the node as authorization bytes this rule never examined.\n */\nexport function storedDelegationKind(\n entry: unknown,\n): \"compact\" | \"signed-login\" | \"other\" | \"refused\" {\n // A stored element that is not an object is not a record at all.\n if (!isRecord(entry)) return \"refused\";\n const delegation = entry.delegation;\n if (!isRecord(delegation)) return \"refused\";\n const header = delegation.delegationHeader;\n if (\n !isRecord(header) ||\n Object.keys(header).length !== 1 ||\n !Object.prototype.hasOwnProperty.call(header, \"Authorization\") ||\n typeof header.Authorization !== \"string\"\n ) {\n return \"refused\";\n }\n if (\"siweProof\" in delegation) return \"signed-login\";\n if (header.Authorization.includes(\".\")) return \"compact\";\n return \"other\";\n}\n\n/** A record replays only within a valid stored request binding. */\nexport function replayLimit(entry: unknown): readonly PermissionEntry[] | undefined {\n const kind = storedDelegationKind(entry);\n if (!isRecord(entry) || (kind !== \"compact\" && kind !== \"signed-login\")) return undefined;\n const binding = DelegationRequestBindingSchema.safeParse(entry.authorityRequest);\n return binding.success ? binding.data.requested : undefined;\n}\n\n/** Match node-sdk's normalization before validating a compact signature. */\nexport function withoutBearer(authorization: string): string {\n return authorization.replace(/^Bearer /i, \"\");\n}\n\nexport type StoredDelegationSource = \"cli-grant\" | \"unbound-import\" | \"migration\" | \"request\" | \"legacy\" | \"unknown\";\n\n/** Constrained labels only; never publish untrusted request IDs or audit notes. */\nexport function storedDelegationSource(entry: unknown): StoredDelegationSource {\n if (!isRecord(entry) || storedDelegationKind(entry) === \"refused\") return \"unknown\";\n if (!(\"authorityRequest\" in entry)) return \"legacy\";\n const binding = DelegationRequestBindingSchema.safeParse(entry.authorityRequest);\n if (!binding.success) return \"unknown\";\n const cid = storedCid(entry);\n if (cid === undefined) return \"unknown\";\n if (binding.data.requestId === `cli-grant:${cid}`) return \"cli-grant\";\n if (binding.data.requestId === `unbound-import:${cid}`) return \"unbound-import\";\n if (binding.data.requestId === `migrated:${cid}`) return \"migration\";\n return \"request\";\n}\n\n/**\n * Binds a record to `requested`, with an audit note naming where the binding\n * came from. Throws when `requested` cannot form a valid binding.\n */\nfunction bindToRequest<T extends { readonly delegation: { readonly cid: string } }>(\n record: T,\n requested: readonly PermissionEntry[],\n source: BindingSource,\n recordedAt = new Date().toISOString(),\n): T & Record<\"authorityRequest\" | \"authorityRequestAudit\", unknown> {\n return {\n ...record,\n authorityRequest: DelegationRequestBindingSchema.parse({\n requestId: `${REQUEST_ID_PREFIX[source]}:${record.delegation.cid}`,\n requested: structuredClone(requested),\n }),\n authorityRequestAudit: { source, recordedAt, note: BINDING_NOTES[source] },\n };\n}\n\n/**\n * Binds the record of one of the CLI's own grants, already checked against\n * the request it answers, to exactly the capabilities its signed bytes grant.\n * They are read through the validated activation replay uses (nothing is\n * activated), so the binding is the authority replay will derive. Throws when\n * validated activation cannot read them for `node`'s session.\n */\nexport async function bindCliGrant<T extends { readonly delegation: PortableDelegation }>(\n node: RuntimeDelegationActivator,\n record: T,\n host: string,\n): Promise<T & Record<\"authorityRequest\" | \"authorityRequestAudit\", unknown>> {\n const signed = await signedCapabilities(node, record.delegation, host);\n if (signed === undefined) {\n throw new Error(\"The grant's signed authority could not be validated for this session.\");\n }\n return bindToRequest(record, signed, \"cli-grant\");\n}\n\n/**\n * Validates and activates an imported compact or signed-login delegation,\n * binding its record to exactly its verified signed capabilities.\n */\nexport async function activateUnboundImport(\n node: RuntimeDelegationActivator,\n delegation: PortableDelegation,\n host: string,\n): Promise<{ delegation: PortableDelegation; permissions: PermissionEntry[] } & Record<string, unknown>> {\n const activated = await nodeSdk.activateValidatedRuntimeDelegation(node, delegation, {\n host,\n authorize: () => {\n verifyCompactProof(delegation);\n return true;\n },\n });\n return bindToRequest(\n { delegation, permissions: [...activated.effectivePermissions] },\n activated.effectivePermissions,\n \"unbound-import\",\n );\n}\n\n/**\n * The stored records after adding records written without a stored request\n * (by `tc auth import` or a CLI grant). A stored record for the same CID that\n * carries an `authorityRequest` is kept as it is, so this route never drops,\n * replaces or weakens a binding; otherwise each record replaces every row for\n * its CID, at the first one's position, or is appended. Callers write the\n * result under the profile lock they already use for this store.\n */\nexport function mergeDelegationsWithoutRequest(\n stored: readonly unknown[],\n incoming: readonly ({ readonly delegation: { readonly cid: string } } & Record<string, unknown>)[],\n): unknown[] {\n let records = [...stored];\n for (const record of incoming) {\n const cid = record.delegation.cid;\n if (records.some((entry) => storedCid(entry) === cid && isRecord(entry) && \"authorityRequest\" in entry)) continue;\n const position = records.findIndex((entry) => storedCid(entry) === cid);\n const others = records.filter((entry) => storedCid(entry) !== cid);\n records = position === -1\n ? [...records, record]\n : [...others.slice(0, position), record, ...others.slice(position)];\n }\n return records;\n}\n\n/**\n * Runs migration before replay reads the profile's records. Returns whether\n * the marker exists; replay refuses unbound records either way.\n *\n * Migration runs under the profile lock, and only while the persisted session\n * is still the one `node` restored. Each unbound compact record is checked\n * without activation and bound to exactly its signed capabilities, or left\n * unbound when validation fails. `migrate` must be false unless the node\n * holds the profile's own restored session.\n *\n * Migration is best-effort and restartable. Bound records are written before\n * the marker; a busy lock or failure leaves migration for a later runtime.\n * Records already bound by an interrupted run keep their bindings.\n */\nexport async function prepareStoredDelegationReplay(\n profile: string,\n node: RuntimeDelegationActivator,\n options: { readonly host: string; readonly migrate: boolean },\n): Promise<boolean> {\n if (await bindingMigrationRecorded(profile)) return true;\n // A persisted session without a `verificationMethod`, or one this node did\n // not restore, never migrates here; skip the lock rather than take it for\n // nothing on every command.\n if (!options.migrate || !await holdsPersistedSession(profile, node)) return false;\n try {\n return await withProfileLock(profile, async () => {\n if (await bindingMigrationRecorded(profile)) return true;\n // Checked again under the lock: a session rotated since the restore\n // leaves migration to a runtime of the new session.\n if (!await holdsPersistedSession(profile, node)) return false;\n const recordedAt = new Date().toISOString();\n const bound = new Map<string, Record<string, unknown>>();\n const unbound: string[] = [];\n for (const entry of await readAdditionalDelegations<unknown>(profile)) {\n // Elements that are not objects are skipped: they install nothing.\n if (!isRecord(entry) || \"authorityRequest\" in entry || storedDelegationKind(entry) !== \"compact\" ||\n storedDelegationForAnotherKey(entry, node)) continue;\n const migrated = await migratedRecord(node, entry, options.host, recordedAt);\n if (migrated === undefined) unbound.push(String(storedCid(entry)));\n else bound.set(recordKey(entry)!, migrated);\n }\n if (bound.size > 0) {\n await updateProfileStore<unknown, void>(profile, \"additional-delegations\", (records) => ({\n records: records.map((entry) => {\n const key = !isRecord(entry) || \"authorityRequest\" in entry ? undefined : recordKey(entry);\n return (key === undefined ? undefined : bound.get(key)) ?? entry;\n }),\n result: undefined,\n }));\n }\n await writeJsonAtomic(bindingMigrationPath(profile), {\n formatVersion: 1,\n migratedAt: recordedAt,\n bound: [...bound.values()].map(storedCid),\n unbound,\n });\n return true;\n }, { timeoutMs: MIGRATION_LOCK_TIMEOUT_MS });\n } catch {\n return false;\n }\n}\n\n/** Whether the profile's persisted session is the one `node` restored. */\nasync function holdsPersistedSession(profile: string, node: RuntimeDelegationActivator): Promise<boolean> {\n try {\n const persisted = await readSession<Record<string, unknown>>(profile);\n return typeof persisted?.verificationMethod === \"string\" &&\n typeof node.sessionDid === \"string\" &&\n persisted.verificationMethod.split(\"#\", 1)[0] === node.sessionDid.split(\"#\", 1)[0];\n } catch {\n return false;\n }\n}\n\n/** One record's migration: bound to its own signed capabilities, or `undefined` if it cannot be. */\nasync function migratedRecord(\n node: RuntimeDelegationActivator,\n entry: Record<string, unknown>,\n host: string,\n recordedAt: string,\n): Promise<Record<string, unknown> | undefined> {\n const delegation = normalizeStoredDelegation(entry);\n if (delegation === undefined) return undefined;\n const signed = await signedCapabilities(node, delegation, host);\n if (signed === undefined) return undefined;\n try {\n // The stored delegation is kept exactly as it was; only the binding is added.\n return bindToRequest({ ...entry, delegation: { ...entry.delegation as object, cid: delegation.cid } }, signed, \"migration\", recordedAt);\n } catch {\n // Signed capabilities a request binding cannot hold (an empty action, say).\n return undefined;\n }\n}\n\n/**\n * What replay did with one stored record. `skipped` records grant nothing and\n * carry a fixed reason code that is safe to publish; `not-replayed` records\n * are routine (expired) and give nothing to act on.\n */\nexport type StoredDelegationReplay =\n | { readonly status: \"installed\"; readonly delegation: ValidatedRuntimeDelegation }\n | { readonly status: \"skipped\"; readonly reason: StoredGrantSkipReason }\n | { readonly status: \"not-replayed\" };\n\nconst NOT_REPLAYED: StoredDelegationReplay = { status: \"not-replayed\" };\n\nfunction skipped(reason: StoredGrantSkipReason): StoredDelegationReplay {\n return { status: \"skipped\", reason };\n}\n\n/**\n * The single stored-grant replay path for CLI and canonical runtimes.\n * Migration runs before the store read; CID deduplication affects authority\n * only, not the per-record fixed-code skip diagnostics.\n */\nexport async function replayProfileDelegations(\n profile: string,\n node: RuntimeDelegationActivator,\n options: { readonly host: string; readonly migrate: boolean; readonly resolveSpace: OperationSpaceResolver },\n): Promise<{ installed: ValidatedRuntimeDelegation[]; warnings: OperationWarning[] }> {\n await prepareStoredDelegationReplay(profile, node, { host: options.host, migrate: options.migrate });\n const installed: ValidatedRuntimeDelegation[] = [];\n const warnings: OperationWarning[] = [];\n const seen = new Set<string>();\n // Cross-user imports are retained for wallet-mode use, not replayed into\n // this session. They are neither broken bindings nor actionable skips.\n for (const entry of await readAdditionalDelegations<unknown>(profile)) {\n if (storedDelegationForAnotherKey(entry, node)) continue;\n const replay = await replayStoredDelegation(node, entry, options);\n if (replay.status === \"installed\") {\n if (!seen.has(replay.delegation.cid)) {\n seen.add(replay.delegation.cid);\n installed.push(replay.delegation);\n }\n } else if (replay.status === \"skipped\") {\n const grantCid = verifiedStoredCid(node, entry);\n warnings.push({\n code: \"STORED_GRANT_SKIPPED\",\n reason: replay.reason,\n ...(grantCid === undefined ? {} : { grantCid }),\n });\n }\n }\n return { installed, warnings };\n}\n\n/** Return an audience only after the exact compact bytes, CID and signature verify. */\nexport function verifiedCompactAudience(node: RuntimeDelegationActivator, delegation: PortableDelegation): string | undefined {\n const authorization = delegation.delegationHeader.Authorization;\n const token = withoutBearer(authorization);\n // Neither the CID helper nor the signature verifier may strip a second prefix.\n if (/^Bearer(?:\\s|$)/i.test(token)) return undefined;\n try {\n if (node.computeDelegationCid(authorization) !== delegation.cid) return undefined;\n return parseSignedCompactUcanAttenuation(token, delegation.cid).payload.aud;\n } catch {\n return undefined;\n }\n}\n\n/** Only a verified signed audience and matching transport audience can identify a foreign grant. */\nexport function storedDelegationForAnotherKey(entry: unknown, node: RuntimeDelegationActivator): boolean {\n if (storedDelegationKind(entry) !== \"compact\" || typeof node.sessionDid !== \"string\") return false;\n const delegation = normalizeStoredDelegation(entry);\n if (delegation === undefined) return false;\n const audience = verifiedCompactAudience(node, delegation);\n if (audience === undefined) return false;\n try {\n return nodeSdk.principalDidEquals(delegation.delegateDID, audience) &&\n !nodeSdk.principalDidEquals(audience, node.sessionDid);\n } catch {\n return false;\n }\n}\n\n/**\n * Publish a stored CID only when it matches the stored authorization bytes.\n * Free-text and even correctly shaped CIDs of different bytes stay private.\n */\nexport function verifiedStoredCid(node: RuntimeDelegationActivator, entry: unknown): string | undefined {\n const delegation = isRecord(entry) && isRecord(entry.delegation) ? entry.delegation : undefined;\n const header = isRecord(delegation?.delegationHeader) ? delegation.delegationHeader : undefined;\n const cid = delegation?.cid;\n if (typeof cid !== \"string\" || typeof header?.Authorization !== \"string\" ||\n typeof node.computeDelegationCid !== \"function\") return undefined;\n try {\n return node.computeDelegationCid(header.Authorization) === cid &&\n DELEGATION_CID.test(cid) ? cid : undefined;\n } catch {\n return undefined;\n }\n}\n\nconst DELEGATION_CID = new RegExp(DELEGATION_CID_PATTERN);\n\n/**\n * Replays one stored record under its binding, never installing an unbound or\n * unproven grant. Stored bytes and node messages are never published.\n */\nexport async function replayStoredDelegation(\n node: RuntimeDelegationActivator,\n entry: unknown,\n options: { readonly host: string; readonly resolveSpace: OperationSpaceResolver },\n): Promise<StoredDelegationReplay> {\n const result = await assess(node, entry, options, { activate: true });\n return result.status === \"verified\" ? skipped(\"invalid\") : result;\n}\n\nexport type StoredDelegationInspection =\n | { readonly local: \"verified\"; readonly cid: string; readonly effectivePermissions: readonly PermissionEntry[]; readonly expiry: Date }\n | { readonly local: \"refused\"; readonly reason: StoredGrantSkipReason }\n | { readonly local: \"not_checked\"; readonly because: \"expired\" | \"no_session\" };\n\n/**\n * Checks only local signed bytes, expiry, audience, resources and binding.\n * The node still decides delegation-chain validity and revocation at install.\n */\nexport async function inspectStoredDelegation(\n entry: unknown,\n options: { readonly node?: RuntimeDelegationActivator; readonly host?: string; readonly resolveSpace?: OperationSpaceResolver } = {},\n): Promise<StoredDelegationInspection> {\n const delegation = normalizeStoredDelegation(entry);\n if (storedDelegationKind(entry) === \"refused\" || delegation === undefined) {\n return { local: \"refused\", reason: \"malformed\" };\n }\n if (delegation.expiry.getTime() <= Date.now()) return { local: \"not_checked\", because: \"expired\" };\n if (options.node === undefined) return { local: \"not_checked\", because: \"no_session\" };\n const result = await assess(options.node, entry, {\n host: options.host ?? delegation.host ?? \"\",\n resolveSpace: options.resolveSpace,\n }, { activate: false });\n if (result.status === \"verified\") {\n return { local: \"verified\", cid: result.cid, effectivePermissions: result.effectivePermissions, expiry: result.expiry };\n }\n if (result.status === \"not-replayed\") return { local: \"not_checked\", because: \"expired\" };\n return { local: \"refused\", reason: result.status === \"skipped\" ? result.reason : \"invalid\" };\n}\n\ntype Assessment = StoredDelegationReplay |\n { readonly status: \"verified\"; readonly cid: string; readonly effectivePermissions: readonly PermissionEntry[]; readonly expiry: Date };\n\nasync function assess(\n node: RuntimeDelegationActivator,\n entry: unknown,\n options: { readonly host: string; readonly resolveSpace?: OperationSpaceResolver },\n mode: { readonly activate: boolean },\n): Promise<Assessment> {\n const kind = storedDelegationKind(entry);\n const delegation = normalizeStoredDelegation(entry);\n if (kind === \"refused\" || delegation === undefined) return skipped(\"malformed\");\n if (delegation.expiry.getTime() <= Date.now()) return NOT_REPLAYED;\n if (kind === \"other\") return skipped(\"proof_missing\");\n const limit = replayLimit(entry);\n if (limit === undefined) return skipped(\"unbound\");\n // Bearer is a storage/HTTP presentation prefix, not part of the signed\n // compact bytes. The node's invocation signer must receive the raw token.\n const authorization = withoutBearer(delegation.delegationHeader.Authorization);\n if (/^Bearer(?:\\s|$)/i.test(authorization)) return skipped(\"cid_mismatch\");\n const toActivate = authorization === delegation.delegationHeader.Authorization\n ? delegation\n : { ...delegation, delegationHeader: { Authorization: authorization }, authHeader: authorization };\n let outsideRequest = false;\n let effectivePermissions: readonly PermissionEntry[] | undefined;\n try {\n const installed = await nodeSdk.activateValidatedRuntimeDelegation(node, toActivate, {\n host: options.host,\n authorize: (effective) => {\n verifyCompactProof(toActivate);\n outsideRequest = !delegationWithinRequest(limit, effective, options.resolveSpace);\n if (outsideRequest) return false;\n effectivePermissions = effective;\n return mode.activate;\n },\n });\n return { status: \"installed\", delegation: installed };\n } catch (error) {\n if (outsideRequest) return skipped(\"outside_request\");\n if (effectivePermissions !== undefined && !mode.activate) {\n return { status: \"verified\", cid: delegation.cid, effectivePermissions, expiry: delegation.expiry };\n }\n // The node compares audiences before invoking `authorize`. A corrupted\n // compact signature must not be mislabeled as an audience mismatch when\n // its transport DID also differs from this session.\n if (kind === \"compact\" && rejectionReason(error) === \"audience_mismatch\") {\n try {\n verifyCompactProof(toActivate);\n } catch {\n return skipped(\"proof_invalid\");\n }\n }\n return skipped(rejectionReason(error));\n }\n}\n\n/** Compact grants must pass the strict local verifier before any installation. */\nfunction verifyCompactProof(delegation: PortableDelegation): void {\n const authorization = delegation.delegationHeader.Authorization;\n if (!withoutBearer(authorization).includes(\".\")) return;\n try {\n parseSignedCompactUcanAttenuation(withoutBearer(authorization), delegation.cid);\n } catch {\n throw new nodeSdk.RuntimeDelegationRejectedError(\"proof_invalid\", \"The compact delegation proof is invalid.\");\n }\n}\n\n/** The published reason node-sdk attached to a refused delegation, else `invalid`. */\nfunction rejectionReason(error: unknown): StoredGrantSkipReason {\n const reason = isRecord(error) ? error.reason : undefined;\n return typeof reason === \"string\" && (STORED_GRANT_SKIP_REASONS as readonly string[]).includes(reason)\n ? reason as StoredGrantSkipReason\n : \"invalid\";\n}\n\n/** An unreadable marker counts as migrated: a damaged marker never reopens migration. */\nexport async function bindingMigrationRecorded(profile: string): Promise<boolean> {\n try {\n return await readJson<unknown>(bindingMigrationPath(profile)) !== null;\n } catch {\n return true;\n }\n}\n\n/**\n * The capabilities a stored delegation's signed bytes grant, read through\n * validated activation, which `authorize` stops before anything is activated.\n */\nasync function signedCapabilities(\n node: RuntimeDelegationActivator,\n delegation: PortableDelegation,\n host: string,\n): Promise<readonly PermissionEntry[] | undefined> {\n let signed: readonly PermissionEntry[] | undefined;\n try {\n await nodeSdk.activateValidatedRuntimeDelegation(node, delegation, {\n // The transport host is not signed authority; check it at replay instead.\n host: delegation.host ?? host,\n authorize: (effective) => {\n verifyCompactProof(delegation);\n signed = effective;\n return false;\n },\n });\n } catch {\n // Refused by `authorize` once the capabilities were read, or failed a check before it.\n }\n return signed;\n}\n\nfunction normalizeStoredDelegation(entry: unknown): PortableDelegation | undefined {\n if (!isRecord(entry)) return undefined;\n const raw = entry.delegation;\n if (!isRecord(raw) || !isRecord(raw.delegationHeader)) return undefined;\n const expiry = raw.expiry instanceof Date\n ? raw.expiry\n : typeof raw.expiry === \"string\" ? new Date(raw.expiry) : undefined;\n if (\n expiry === undefined || Number.isNaN(expiry.getTime()) ||\n typeof raw.cid !== \"string\" ||\n typeof raw.spaceId !== \"string\" ||\n typeof raw.path !== \"string\" ||\n !Array.isArray(raw.actions) || !raw.actions.every((action) => typeof action === \"string\") ||\n typeof raw.delegateDID !== \"string\" ||\n typeof raw.ownerAddress !== \"string\" ||\n typeof raw.chainId !== \"number\" ||\n typeof raw.delegationHeader.Authorization !== \"string\"\n ) {\n return undefined;\n }\n return { ...raw, expiry } as PortableDelegation;\n}\n\nfunction storedCid(entry: unknown): string | undefined {\n const cid = isRecord(entry) && isRecord(entry.delegation) ? entry.delegation.cid : undefined;\n return typeof cid === \"string\" ? cid : undefined;\n}\n\n/** A record's CID and exact authorization bytes. */\nfunction recordKey(entry: Record<string, unknown>): string | undefined {\n const delegation = entry.delegation;\n if (!isRecord(delegation) || !isRecord(delegation.delegationHeader)) return undefined;\n return JSON.stringify([delegation.cid, delegation.delegationHeader.Authorization]);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","/**\n * TinyCloud App Manifest\n *\n * A declarative description of an app's identity and the capabilities it\n * needs. The manifest drives the SIWE recap at sign-in time, enabling a\n * single wallet prompt that covers the app's own permissions plus any\n * pre-declared delegations.\n *\n * The SDK does NOT fetch external manifests. Apps compose their own manifest\n * (optionally including backend or agent addenda) before handing it to the\n * SDK.\n *\n * Canonical spec: `.claude/specs/manifest.md`.\n *\n * @packageDocumentation\n */\n\nimport ms from \"ms\";\nimport { ACCOUNT_MANIFEST_PERMISSIONS } from \"@tinycloud/bootstrap\";\nimport { resolveSecretPath, SECRET_NAME_RE } from \"@tinycloud/sdk-services\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * A single permission entry inside a manifest. This is the shape apps write\n * in their `manifest.json` and the shape we compare against when performing\n * the capability-subset derivability check in the delegation flow.\n *\n * `service` uses the long form (e.g. `\"tinycloud.kv\"`, `\"tinycloud.sql\"`).\n * `\"tinycloud.vault\"` is an SDK-only shorthand that expands to the KV\n * resources the vault service uses; it is never encoded as a recap service.\n */\nexport interface PermissionEntry {\n /** Service namespace, e.g. \"tinycloud.kv\", \"tinycloud.sql\", \"tinycloud.duckdb\", \"tinycloud.capabilities\". */\n service: string;\n /** Space name or full space URI. Defaults to \"applications\" inside manifests. */\n space?: string;\n /**\n * Service-specific path.\n * - tinycloud.kv: hierarchical prefix. \"/\" = all, \"foo/\" = prefix match, \"foo\" = exact key\n * - tinycloud.sql: database name/file (e.g. \"data.sqlite\") or \"/\" for all\n * - tinycloud.duckdb: database name/file\n * - tinycloud.capabilities: capability key URI or \"/\" for all\n */\n path: string;\n /**\n * Short action names (e.g. \"get\", \"put\", \"read\", \"schema\"). The SDK expands\n * these to full URNs (e.g. `tinycloud.kv/get`) during resolution.\n * Already-expanded URNs are passed through unchanged.\n */\n actions: string[];\n /** Exact ReCap caveat branches when this authority came from a signed ReCap. */\n caveats?: Record<string, unknown>[];\n /** When true, the manifest prefix is NOT prepended to `path`. Default false. */\n skipPrefix?: boolean;\n /** Per-entry expiry override, ms-format. */\n expiry?: string;\n /** User/agent-facing context for why this permission is requested. */\n description?: string;\n}\n\nexport type ManifestSecretActions =\n | true\n | string\n | string[]\n | {\n /** Actual vault secret name. Defaults to the manifest object key. */\n name?: string;\n /** Optional scoped secret namespace. Omit for global secrets. */\n scope?: string;\n actions?: string | string[];\n expiry?: string;\n description?: string;\n };\n\n/**\n * The valid values for `Manifest.defaults`.\n *\n * - `false` → no auto-included permissions\n * - `true` → standard tier (KV + SQL read/write + capabilities:read)\n * - `\"admin\"` → standard + SQL schema\n * - `\"all\"` → everything the SDK supports (including DuckDB)\n *\n * Unknown string values silently fall back to `true`. Values are normalized\n * (lowercase + trim) before matching.\n */\nexport type ManifestDefaults = boolean | \"admin\" | \"all\";\n\n/**\n * Agent-readable app knowledge bundle pointer.\n *\n * - `true` means the default root: `knowledge/index.md`\n * - string values must point at a markdown root under `knowledge/`\n */\nexport type ManifestKnowledge = true | string;\n\n/** Default root used when `manifest.knowledge === true`. */\nexport const DEFAULT_KNOWLEDGE_ROOT = \"knowledge/index.md\";\n\n/**\n * The raw manifest shape an app declares. See `.claude/specs/manifest.md`.\n */\nexport interface Manifest {\n /** Schema version. Optional, defaults to 1. */\n manifest_version?: 1;\n /** Application identifier / namespace prefix. Required. */\n app_id: string;\n /** Display name. Required. */\n name: string;\n /** Description of what the app or delegate does. Optional. */\n description?: string;\n /** DID of this manifest's delegate target. Optional. Required only for delegation materialization. */\n did?: string;\n /** URL to app icon. Optional. */\n icon?: string;\n /** App version string. Optional. */\n appVersion?: string;\n /** Default expiry for permissions. ms-format (\"30d\", \"2h\", \"1y\"). Default \"30d\". */\n expiry?: string;\n /** Space name or full space URI. Optional, defaults to \"applications\". */\n space?: string;\n /**\n * Path prefix auto-prepended to permission paths. Optional, defaults to\n * `app_id`. Set to `\"\"` to disable entirely. Individual permissions can opt\n * out with `skipPrefix: true`.\n */\n prefix?: string;\n /**\n * Default permission set to auto-include. Optional, defaults to `true`.\n * See {@link ManifestDefaults}.\n */\n defaults?: ManifestDefaults | string;\n /** Whether to include the public-space companion delegation. Default `true`. */\n includePublicSpace?: boolean;\n /** Agent-readable knowledge bundle root. `true` means `knowledge/index.md`. */\n knowledge?: ManifestKnowledge;\n /**\n * Additional permissions beyond the defaults. Use for cross-space access,\n * DuckDB (opt-in), or `skipPrefix: true` entries.\n */\n permissions?: PermissionEntry[];\n /**\n * Secret name shorthand. Entries resolve to encrypted vault KV resources in\n * the `secrets` space.\n */\n secrets?: Record<string, ManifestSecretActions>;\n}\n\n/**\n * A resolved permission entry with fully-expanded paths and action URNs.\n * This is the shape the delegation flow compares against parsed recap\n * capabilities, and the shape the session-key delegation path actually uses.\n */\nexport interface ResourceCapability {\n /** Long-form service, e.g. \"tinycloud.kv\". */\n service: string;\n /** Space name or URI. Short names are resolved to full SpaceIds at sign-in time. */\n space: string;\n /** Path with the manifest prefix applied (or skipped per `skipPrefix`). */\n path: string;\n /** Full-URN actions, e.g. [\"tinycloud.kv/get\", \"tinycloud.kv/put\"]. */\n actions: string[];\n /** Per-entry expiry override in milliseconds. */\n expiryMs?: number;\n /** User/agent-facing context copied from the source permission entry. */\n description?: string;\n}\n\n/**\n * A resolved delegation entry with fully-expanded permissions.\n */\nexport interface ResolvedDelegate {\n /** DID of the delegate. */\n did: string;\n /** Informational display name. Optional. */\n name?: string;\n /** Expiry in milliseconds (per-delegation > manifest default > 30 days). */\n expiryMs: number;\n /** Fully resolved permissions. */\n permissions: ResourceCapability[];\n}\n\n/**\n * The output of {@link resolveManifest}: a fully-expanded capability set\n * ready to drive the SIWE recap.\n */\nexport interface ResolvedCapabilities {\n /** Application identifier copied from manifest.app_id. */\n app_id: string;\n /** Delegate DID copied from manifest.did, when present. */\n did?: string;\n /** Effective default space for this manifest. */\n space: string;\n /** All session-key resources with paths fully resolved (prefix applied). */\n resources: ResourceCapability[];\n /** Default expiry for the session, in milliseconds. */\n expiryMs: number;\n /** Whether to include the public-space companion. */\n includePublicSpace: boolean;\n /** Delegate targets derived from manifests that declare `did`. */\n additionalDelegates: ResolvedDelegate[];\n}\n\nexport interface ManifestRegistryRecord {\n /** KV key inside the account space. */\n key: string;\n /** App id this record describes. */\n app_id: string;\n /** Latest manifest payloads composed for this app id. */\n manifests: Manifest[];\n}\n\nexport interface ComposeManifestOptions {\n /** Include implicit account-space registry permissions. Default true. */\n includeAccountRegistryPermissions?: boolean;\n}\n\nexport interface ComposedManifestRequest {\n /** Validated manifests that were composed. */\n manifests: Manifest[];\n /** Full permission union requested from the user in one SIWE. */\n resources: ResourceCapability[];\n /** Delegations that can be materialized after sign-in. */\n delegationTargets: ResolvedDelegate[];\n /** Account-space registry records to write after successful sign-in. */\n registryRecords: ManifestRegistryRecord[];\n /** Effective session expiry, using the longest composed manifest expiry. */\n expiryMs: number;\n /** Whether to include the public-space companion behavior. */\n includePublicSpace: boolean;\n}\n\n/**\n * Thrown when the manifest fails validation (missing id/name, bad expiry,\n * empty actions on a permission, etc).\n */\nexport class ManifestValidationError extends Error {\n constructor(message: string) {\n super(`Manifest validation failed: ${message}`);\n this.name = \"ManifestValidationError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Default expiry when neither the manifest, delegation, nor permission\n * specifies one. APP tier — see `expiry.ts`. Spec: 30 days.\n *\n * Kept as an ms-format string because the manifest schema stores expiry\n * as a string and the parser is shared between this default and\n * caller-provided values; converting `EXPIRY.APP_MS` back to a string\n * here would duplicate that same `30d` literal in another form.\n */\nexport const DEFAULT_EXPIRY = \"30d\";\n\n/**\n * Default `defaults` value when the manifest omits it. Spec: standard tier.\n */\nexport const DEFAULT_DEFAULTS: ManifestDefaults = true;\n\n/** Default manifest schema version. */\nexport const DEFAULT_MANIFEST_VERSION = 1;\n\n/** Default space for manifest-declared app data. */\nexport const DEFAULT_MANIFEST_SPACE = \"applications\";\n\n/** Account-space name used for installed-application registry records. */\nexport const ACCOUNT_REGISTRY_SPACE = \"account\";\n\n/** Account-space KV prefix used for installed-application registry records. */\nexport const ACCOUNT_REGISTRY_PATH = \"applications/\";\n\nexport const SECRETS_SPACE = \"secrets\";\n\n/** SDK-only permission service for encrypted vault resources. */\nexport const VAULT_PERMISSION_SERVICE = \"tinycloud.vault\";\n\ntype VaultKVBase = \"vault\";\n\ninterface VaultActionExpansion {\n bases: readonly VaultKVBase[];\n action: string;\n}\n\n/**\n * Known services and their short-form (recap URI) names. The TinyCloud\n * node encodes the recap resource URI with the short service name, while\n * action URNs and manifest entries use the long `tinycloud.<short>` form.\n * This table is the canonical bridge between the two.\n */\nexport const SERVICE_SHORT_TO_LONG: Readonly<Record<string, string>> =\n Object.freeze({\n kv: \"tinycloud.kv\",\n sql: \"tinycloud.sql\",\n duckdb: \"tinycloud.duckdb\",\n capabilities: \"tinycloud.capabilities\",\n hooks: \"tinycloud.hooks\",\n encryption: \"tinycloud.encryption\",\n delegation: \"tinycloud.delegation\",\n });\n\n/**\n * Manifest service identifier for TinyCloud encryption network grants.\n *\n * Encryption permissions live on a network id URN\n * (`urn:tinycloud:encryption:<ownerDid>:<network>`), not on a space.\n * The `path` field is the literal networkId; `actions` are\n * `[\"decrypt\"]` (expanded to `[\"tinycloud.encryption/decrypt\"]`).\n *\n * Apps should omit `space` for encryption permissions. The SDK may emit\n * an internal `\"encryption\"` compatibility label after expansion so the\n * older `PermissionEntry`/`ResourceCapability` shape can still carry the\n * raw network URN through subset checks.\n */\nexport const ENCRYPTION_PERMISSION_SERVICE = \"tinycloud.encryption\";\n\n/** Synthetic space label used by encryption manifest entries. */\nexport const ENCRYPTION_MANIFEST_SPACE = \"encryption\";\n\n/**\n * Inverse of {@link SERVICE_SHORT_TO_LONG}.\n */\nexport const SERVICE_LONG_TO_SHORT: Readonly<Record<string, string>> =\n Object.freeze(\n Object.fromEntries(\n Object.entries(SERVICE_SHORT_TO_LONG).map(([s, l]) => [l, s]),\n ),\n );\n\n/**\n * Default permission entries for the `true` / standard tier.\n *\n * `tinycloud.capabilities/read` is added separately for every requested\n * space, without the app path prefix. That keeps capability introspection\n * space-scoped instead of app-data scoped.\n */\nconst DEFAULT_STANDARD_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\"],\n },\n];\n\n/**\n * Default permission entries for the `\"admin\"` tier: standard + sql/schema.\n */\nconst DEFAULT_ADMIN_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\", \"schema\"],\n },\n];\n\n/**\n * Default permission entries for the `\"all\"` tier: admin + DuckDB.\n *\n * DuckDB is opt-in and only appears in this tier or in explicit manifest\n * `permissions` entries.\n */\nconst DEFAULT_ALL_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\", \"schema\"],\n },\n {\n service: \"tinycloud.duckdb\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\"],\n },\n];\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Parse an ms-format duration string (e.g. \"30d\", \"2h\", \"1y\") into\n * milliseconds.\n *\n * @throws {ManifestValidationError} on empty string, non-string input, or\n * any input `ms()` cannot parse.\n */\nexport function parseExpiry(duration: string): number {\n if (typeof duration !== \"string\" || duration.length === 0) {\n throw new ManifestValidationError(\n `expiry must be a non-empty duration string (got ${JSON.stringify(duration)})`,\n );\n }\n // `ms` returns `undefined` for unparseable input and can return a number\n // or a string depending on the call signature; cast explicitly.\n const parsed = (ms as unknown as (v: string) => number | undefined)(duration);\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new ManifestValidationError(\n `invalid expiry duration: ${JSON.stringify(duration)}`,\n );\n }\n return parsed;\n}\n\n/**\n * Expand a list of action short names (or already-expanded URNs) into full\n * ability URNs of the form `<service>/<action>`.\n *\n * Examples:\n * `expandActionShortNames(\"tinycloud.kv\", [\"get\", \"put\"])`\n * → `[\"tinycloud.kv/get\", \"tinycloud.kv/put\"]`\n * `expandActionShortNames(\"tinycloud.kv\", [\"tinycloud.kv/get\"])`\n * → `[\"tinycloud.kv/get\"]` (passed through unchanged)\n */\nexport function expandActionShortNames(\n service: string,\n actions: readonly string[],\n): string[] {\n return actions.map((a) => {\n if (a.includes(\"/\")) {\n // Already a full URN — pass through.\n return a;\n }\n return `${service}/${a}`;\n });\n}\n\n/**\n * Expand SDK virtual permission services into concrete recap-capable services.\n *\n * Today this handles `\"tinycloud.vault\"`, which is backed by inline\n * network-encrypted KV records:\n * - read/get: `vault/<path>` with `tinycloud.kv/get`\n * - write/put: `vault/<path>` with `tinycloud.kv/put`\n * - delete/del: `vault/<path>` with `tinycloud.kv/del`\n * - list: `vault/<path>` with `tinycloud.kv/list`\n * - head: `vault/<path>` with `tinycloud.kv/get`\n * - metadata: `vault/<path>` with `tinycloud.kv/metadata`\n */\nexport function expandPermissionEntry(entry: PermissionEntry): PermissionEntry[] {\n if (entry.service === ENCRYPTION_PERMISSION_SERVICE) {\n return expandEncryptionPermissionEntry(entry);\n }\n if (entry.service !== VAULT_PERMISSION_SERVICE) {\n return [\n {\n ...entry,\n actions: expandActionShortNames(entry.service, entry.actions),\n },\n ];\n }\n\n return expandVaultPermissionEntry(entry);\n}\n\n/**\n * Expand a `tinycloud.encryption` manifest entry.\n *\n * - `path` MUST be a networkId URN (`urn:tinycloud:encryption:...`).\n * The manifest prefix is always skipped — network ids are top-level\n * owner-scoped resources, not space-scoped paths.\n * - `actions` must be `decrypt`, `network.create`, or `network.revoke`\n * (or their already-expanded `tinycloud.encryption/*` forms).\n *\n * The returned entry uses an internal `space = \"encryption\"` compatibility\n * label so old manifest grouping code does not collapse it into the app's\n * data space, and `skipPrefix` is forced to `true` so the prefix application\n * step is a no-op.\n */\nfunction expandEncryptionPermissionEntry(\n entry: PermissionEntry,\n): PermissionEntry[] {\n if (\n typeof entry.path !== \"string\" ||\n !entry.path.startsWith(\"urn:tinycloud:encryption:\")\n ) {\n throw new ManifestValidationError(\n `tinycloud.encryption entries require path to be a networkId URN ` +\n `(got ${JSON.stringify(entry.path)})`,\n );\n }\n const normalizedActions: string[] = [];\n for (const action of entry.actions) {\n if (action === \"decrypt\" || action === \"tinycloud.encryption/decrypt\") {\n normalizedActions.push(\"tinycloud.encryption/decrypt\");\n continue;\n }\n if (\n action === \"network.create\" ||\n action === \"tinycloud.encryption/network.create\"\n ) {\n normalizedActions.push(\"tinycloud.encryption/network.create\");\n continue;\n }\n if (\n action === \"network.revoke\" ||\n action === \"tinycloud.encryption/network.revoke\"\n ) {\n normalizedActions.push(\"tinycloud.encryption/network.revoke\");\n continue;\n }\n if (action.includes(\"/\")) {\n throw new ManifestValidationError(\n `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`,\n );\n }\n throw new ManifestValidationError(\n `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`,\n );\n }\n // Dedupe while preserving order\n const dedupedActions: string[] = [];\n const seen = new Set<string>();\n for (const a of normalizedActions) {\n if (!seen.has(a)) {\n dedupedActions.push(a);\n seen.add(a);\n }\n }\n // Encryption resources are network-scoped, not space-scoped. We\n // always emit the synthetic \"encryption\" space label so manifest\n // grouping can deal with it uniformly without collapsing the\n // networkId URN into an app data space.\n return [\n {\n service: ENCRYPTION_PERMISSION_SERVICE,\n space: ENCRYPTION_MANIFEST_SPACE,\n path: entry.path,\n actions: dedupedActions,\n skipPrefix: true,\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n },\n ];\n}\n\n/**\n * Expand a list of permission entries using {@link expandPermissionEntry}.\n */\nexport function expandPermissionEntries(\n entries: readonly PermissionEntry[],\n): PermissionEntry[] {\n return entries.flatMap(expandPermissionEntry);\n}\n\n/**\n * Apply the manifest prefix to a permission path per the spec rules.\n *\n * - `skipPrefix: true` → path is returned as-is\n * - `prefix === \"\"` → path is returned as-is\n * - path starts with \"/\" → `prefix + path` (e.g. \"com.listen.app\" + \"/\" → \"com.listen.app/\")\n * - otherwise → `prefix + \"/\" + path` (e.g. \"com.listen.app\" + \"data.sqlite\" → \"com.listen.app/data.sqlite\")\n */\nexport function applyPrefix(\n prefix: string,\n path: string,\n skipPrefix: boolean,\n): string {\n if (skipPrefix) {\n return path;\n }\n if (prefix === \"\") {\n return path;\n }\n if (path.startsWith(\"/\")) {\n return `${prefix}${path}`;\n }\n return `${prefix}/${path}`;\n}\n\n/**\n * Fetch and parse a manifest from a URL (browser) or file path (node).\n * The runtime decides the fetch strategy via `globalThis.fetch`; this is\n * platform-agnostic. Callers that want custom loading should JSON.parse a\n * Manifest themselves and skip this helper.\n *\n * @throws if the fetch fails, the JSON is invalid, or the manifest fails\n * validation.\n */\nexport async function loadManifest(url: string): Promise<Manifest> {\n const fetchFn: typeof fetch | undefined = (\n globalThis as { fetch?: typeof fetch }\n ).fetch;\n if (typeof fetchFn !== \"function\") {\n throw new ManifestValidationError(\n \"loadManifest requires a global fetch; pass the manifest object directly on runtimes without fetch\",\n );\n }\n const res = await fetchFn(url);\n if (!res.ok) {\n throw new ManifestValidationError(\n `failed to fetch manifest from ${url}: HTTP ${res.status}`,\n );\n }\n const json = (await res.json()) as unknown;\n return validateManifest(json);\n}\n\n/**\n * Validate a manifest-shaped object and return it strongly-typed.\n * Throws {@link ManifestValidationError} on any hard failure.\n */\nexport function validateManifest(input: unknown): Manifest {\n if (input === null || typeof input !== \"object\") {\n throw new ManifestValidationError(\"manifest must be an object\");\n }\n const m = input as Manifest;\n if (\n m.manifest_version !== undefined &&\n m.manifest_version !== DEFAULT_MANIFEST_VERSION\n ) {\n throw new ManifestValidationError(\n `manifest.manifest_version must be ${DEFAULT_MANIFEST_VERSION}`,\n );\n }\n if (typeof m.app_id !== \"string\" || m.app_id.length === 0) {\n throw new ManifestValidationError(\n \"manifest.app_id is required and must be a non-empty string\",\n );\n }\n if (typeof m.name !== \"string\" || m.name.length === 0) {\n throw new ManifestValidationError(\n \"manifest.name is required and must be a non-empty string\",\n );\n }\n if (\n m.did !== undefined &&\n (typeof m.did !== \"string\" || m.did.length === 0)\n ) {\n throw new ManifestValidationError(\n \"manifest.did must be a non-empty DID string\",\n );\n }\n if (\n m.space !== undefined &&\n (typeof m.space !== \"string\" || m.space.length === 0)\n ) {\n throw new ManifestValidationError(\n \"manifest.space must be a non-empty string\",\n );\n }\n if (m.expiry !== undefined) {\n // Will throw with a clear error if invalid.\n parseExpiry(m.expiry);\n }\n if (m.knowledge !== undefined) {\n resolveManifestKnowledgeRoot(m.knowledge);\n }\n if (m.permissions !== undefined) {\n if (!Array.isArray(m.permissions)) {\n throw new ManifestValidationError(\n \"manifest.permissions must be an array\",\n );\n }\n m.permissions.forEach((p, i) =>\n validatePermissionEntry(p, `permissions[${i}]`),\n );\n }\n if (m.secrets !== undefined) {\n validateManifestSecrets(m.secrets);\n }\n return m;\n}\n\n/**\n * Resolve a manifest knowledge pointer to its root markdown file.\n *\n * This is metadata only; app knowledge does not create capabilities.\n */\nexport function resolveManifestKnowledgeRoot(\n knowledge: Manifest[\"knowledge\"] | undefined,\n): string | undefined {\n if (knowledge === undefined) {\n return undefined;\n }\n if (knowledge === true) {\n return DEFAULT_KNOWLEDGE_ROOT;\n }\n if (typeof knowledge !== \"string\" || knowledge.length === 0) {\n throw new ManifestValidationError(\n \"manifest.knowledge must be true or a knowledge/*.md root path\",\n );\n }\n if (!/^knowledge\\/.+\\.md$/.test(knowledge)) {\n throw new ManifestValidationError(\n \"manifest.knowledge must be true or a knowledge/*.md root path\",\n );\n }\n return knowledge;\n}\n\nfunction validateManifestSecrets(secrets: unknown): void {\n if (secrets === null || typeof secrets !== \"object\" || Array.isArray(secrets)) {\n throw new ManifestValidationError(\"manifest.secrets must be an object\");\n }\n\n for (const [name, spec] of Object.entries(secrets)) {\n if (!SECRET_NAME_RE.test(name)) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} must match ${SECRET_NAME_RE.source}`,\n );\n }\n try {\n resolveSecretPath(\n secretNameFromSpec(name, spec as ManifestSecretActions),\n { scope: secretScopeFromSpec(spec as ManifestSecretActions) },\n );\n } catch (error) {\n throw new ManifestValidationError(\n `manifest.secrets.${name}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const actions = secretActionsFromSpec(name, spec as ManifestSecretActions);\n if (actions.length === 0) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} actions must be non-empty`,\n );\n }\n for (const action of actions) {\n if (typeof action !== \"string\" || action.length === 0) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} actions must be non-empty strings`,\n );\n }\n }\n if (\n spec !== null &&\n typeof spec === \"object\" &&\n !Array.isArray(spec) &&\n (spec as { expiry?: unknown }).expiry !== undefined\n ) {\n parseExpiry((spec as { expiry: string }).expiry);\n }\n }\n}\n\nfunction validatePermissionEntry(p: unknown, path: string): void {\n if (p === null || typeof p !== \"object\") {\n throw new ManifestValidationError(`${path} must be an object`);\n }\n const entry = p as PermissionEntry;\n if (typeof entry.service !== \"string\" || entry.service.length === 0) {\n throw new ManifestValidationError(`${path}.service is required`);\n }\n if (\n entry.space !== undefined &&\n (typeof entry.space !== \"string\" || entry.space.length === 0)\n ) {\n throw new ManifestValidationError(\n `${path}.space must be a non-empty string`,\n );\n }\n if (typeof entry.path !== \"string\") {\n throw new ManifestValidationError(\n `${path}.path is required (use \"\" or \"/\" for root)`,\n );\n }\n if (!Array.isArray(entry.actions) || entry.actions.length === 0) {\n throw new ManifestValidationError(\n `${path}.actions must be a non-empty array`,\n );\n }\n for (const action of entry.actions) {\n if (typeof action !== \"string\" || action.length === 0) {\n throw new ManifestValidationError(\n `${path}.actions must contain non-empty strings`,\n );\n }\n if (entry.service === VAULT_PERMISSION_SERVICE) {\n vaultActionExpansion(action);\n }\n }\n if (entry.caveats !== undefined &&\n (!Array.isArray(entry.caveats) || entry.caveats.some((caveat) =>\n caveat === null || typeof caveat !== \"object\" || Array.isArray(caveat)\n ))\n ) {\n throw new ManifestValidationError(`${path}.caveats must be an array of objects`);\n }\n if (entry.expiry !== undefined) {\n parseExpiry(entry.expiry);\n }\n}\n\n/**\n * Normalize a `defaults` value: lowercase + trim, then match against known\n * tiers. Unknown string values silently fall back to `true` (standard).\n * Boolean values pass through.\n */\nexport function normalizeDefaults(\n value: Manifest[\"defaults\"] | undefined,\n): ManifestDefaults {\n if (value === undefined) {\n return DEFAULT_DEFAULTS;\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value !== \"string\") {\n // Spec says unknown values silently fall back to `true`.\n return true;\n }\n const normalized = value.trim().toLowerCase();\n if (normalized === \"admin\" || normalized === \"all\") {\n return normalized;\n }\n // Anything else, including \"true\"/\"false\"/\"standard\"/garbage, falls back\n // to the standard tier per spec.\n return true;\n}\n\n/**\n * Return the default permission entries for the given tier. Entries are\n * deep-cloned so callers can mutate them without affecting the constants.\n */\nfunction defaultEntriesForTier(tier: ManifestDefaults): PermissionEntry[] {\n if (tier === false) {\n return [];\n }\n const source =\n tier === \"admin\"\n ? DEFAULT_ADMIN_ENTRIES\n : tier === \"all\"\n ? DEFAULT_ALL_ENTRIES\n : DEFAULT_STANDARD_ENTRIES;\n return source.map((e) => ({\n service: e.service,\n space: e.space,\n path: e.path,\n actions: [...e.actions],\n ...(e.skipPrefix !== undefined ? { skipPrefix: e.skipPrefix } : {}),\n }));\n}\n\n/**\n * Resolve a raw manifest into a {@link ResolvedCapabilities} object: expand\n * shortform actions, apply the prefix, merge defaults, and compute effective\n * expiries. Pure function — does no I/O.\n *\n * Resolution semantics (spec):\n * - `prefix` defaults to `app_id`; set to `\"\"` to disable prefix application entirely.\n * - `space` defaults to `applications`; per-permission `space` overrides it.\n * - `defaults` defaults to `true` (standard tier); unknown string values fall back to `true`.\n * - Per-entry expiry overrides per-delegation overrides manifest > `DEFAULT_EXPIRY`.\n * - Default entries use `skipPrefix: false` so they inherit the manifest prefix.\n */\nexport function resolveManifest(input: Manifest): ResolvedCapabilities {\n const manifest = validateManifest(input);\n\n const prefix =\n manifest.prefix !== undefined ? manifest.prefix : manifest.app_id;\n const space = manifest.space ?? DEFAULT_MANIFEST_SPACE;\n const expiryMs = parseExpiry(manifest.expiry ?? DEFAULT_EXPIRY);\n const includePublicSpace = manifest.includePublicSpace ?? true;\n const tier = normalizeDefaults(manifest.defaults);\n\n const defaultEntries = defaultEntriesForTier(tier);\n const explicitEntries = manifest.permissions ?? [];\n const secretEntries = secretEntriesForManifest(manifest.secrets);\n\n // Merge order: defaults first, then explicit entries, so explicit entries\n // for the same (service, space, path) tuple override defaults.\n const allEntries: PermissionEntry[] = [\n ...defaultEntries,\n ...explicitEntries,\n ...secretEntries,\n ];\n\n const resources: ResourceCapability[] = withCapabilitiesReadForSpaces(\n allEntries.flatMap((entry) => resolveEntry(entry, prefix, expiryMs, space)),\n );\n\n const additionalDelegates: ResolvedDelegate[] =\n manifest.did === undefined\n ? []\n : [\n {\n did: manifest.did,\n name: manifest.name,\n expiryMs,\n permissions: resources.map(cloneResourceCapability),\n },\n ];\n\n return {\n app_id: manifest.app_id,\n ...(manifest.did !== undefined ? { did: manifest.did } : {}),\n space,\n resources,\n expiryMs,\n includePublicSpace,\n additionalDelegates,\n };\n}\n\nfunction normalizeSecretActions(actions: readonly string[]): string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n const add = (action: string) => {\n if (!seen.has(action)) {\n out.push(action);\n seen.add(action);\n }\n };\n\n for (const action of actions) {\n if (action === \"read\") {\n add(\"get\");\n continue;\n }\n if (action === \"write\") {\n add(\"put\");\n continue;\n }\n if (action === \"delete\") {\n add(\"del\");\n continue;\n }\n if (\n action === \"get\" ||\n action === \"put\" ||\n action === \"del\" ||\n action === \"list\" ||\n action === \"metadata\"\n ) {\n add(action);\n continue;\n }\n if (\n action === \"tinycloud.kv/get\" ||\n action === \"tinycloud.kv/put\" ||\n action === \"tinycloud.kv/del\" ||\n action === \"tinycloud.kv/list\" ||\n action === \"tinycloud.kv/metadata\"\n ) {\n add(action);\n continue;\n }\n throw new ManifestValidationError(\n `unknown secret action ${JSON.stringify(action)}; expected read, write, delete, list, or metadata`,\n );\n }\n\n return out;\n}\n\nfunction secretNameFromSpec(\n fallbackName: string,\n spec: ManifestSecretActions,\n): string {\n if (spec !== null && typeof spec === \"object\" && !Array.isArray(spec)) {\n return spec.name ?? fallbackName;\n }\n return fallbackName;\n}\n\nfunction secretScopeFromSpec(\n spec: ManifestSecretActions,\n): string | undefined {\n if (spec !== null && typeof spec === \"object\" && !Array.isArray(spec)) {\n return spec.scope;\n }\n return undefined;\n}\n\nfunction secretActionsFromSpec(\n name: string,\n spec: ManifestSecretActions,\n): string[] {\n if (spec === true) {\n return [\"read\"];\n }\n if (typeof spec === \"string\") {\n return [spec];\n }\n if (Array.isArray(spec)) {\n return spec;\n }\n if (spec === null || typeof spec !== \"object\") {\n throw new ManifestValidationError(\n `manifest.secrets.${name} must be true, a string action, an actions array, or an object`,\n );\n }\n if (spec.actions === undefined) {\n return [\"read\"];\n }\n if (typeof spec.actions === \"string\") {\n return [spec.actions];\n }\n if (Array.isArray(spec.actions)) {\n return spec.actions;\n }\n throw new ManifestValidationError(\n `manifest.secrets.${name}.actions must be a string or array`,\n );\n}\n\nfunction secretEntriesForManifest(\n secrets: Manifest[\"secrets\"] | undefined,\n): PermissionEntry[] {\n if (secrets === undefined) {\n return [];\n }\n\n const entries: PermissionEntry[] = [];\n for (const [name, spec] of Object.entries(secrets)) {\n const actions = secretActionsFromSpec(name, spec);\n const secretPath = resolveSecretPath(\n secretNameFromSpec(name, spec),\n { scope: secretScopeFromSpec(spec) },\n );\n const extra: { expiry?: string; description?: string } =\n spec !== true && typeof spec === \"object\" && !Array.isArray(spec)\n ? spec\n : {};\n entries.push({\n service: VAULT_PERMISSION_SERVICE,\n space: SECRETS_SPACE,\n path: secretPath.vaultKey,\n actions: normalizeSecretActions(actions),\n skipPrefix: true,\n ...(extra.expiry !== undefined ? { expiry: extra.expiry } : {}),\n ...(extra.description !== undefined\n ? { description: extra.description }\n : {}),\n });\n }\n return entries;\n}\n\n/**\n * Expand a single permission entry into a {@link ResourceCapability}:\n * apply the prefix to the path and expand short actions into full URNs.\n */\nfunction resolveEntry(\n entry: PermissionEntry,\n prefix: string,\n _inheritedExpiryMs: number,\n inheritedSpace: string,\n): ResourceCapability[] {\n // Encryption permissions reference a networkId URN as their resource\n // — the manifest prefix is meaningless against a top-level\n // owner-scoped resource and would corrupt the URN. Always skip.\n const skipPrefixForEntry =\n entry.skipPrefix === true ||\n entry.service === ENCRYPTION_PERMISSION_SERVICE;\n const resolvedPath = applyPrefix(prefix, entry.path, skipPrefixForEntry);\n const entryExpiryMs =\n entry.expiry !== undefined ? parseExpiry(entry.expiry) : undefined;\n return expandPermissionEntry({\n ...entry,\n space: entry.space ?? inheritedSpace,\n path: resolvedPath,\n skipPrefix: true,\n }).map((expanded) => ({\n service: expanded.service,\n space: expanded.space ?? inheritedSpace,\n path: expanded.path,\n actions: expanded.actions,\n // Only populate `expiryMs` when the entry had its own expiry override.\n // When absent, callers use the parent (delegation or manifest) expiry\n // which is carried on ResolvedDelegate.expiryMs / ResolvedCapabilities.expiryMs.\n ...(entryExpiryMs !== undefined ? { expiryMs: entryExpiryMs } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n }));\n}\n\nfunction expandVaultPermissionEntry(entry: PermissionEntry): PermissionEntry[] {\n const byBase = new Map<VaultKVBase, string[]>();\n\n for (const action of entry.actions) {\n const expansion = vaultActionExpansion(action);\n for (const base of expansion.bases) {\n const actions = byBase.get(base) ?? [];\n if (!actions.includes(expansion.action)) {\n actions.push(expansion.action);\n }\n byBase.set(base, actions);\n }\n }\n\n return [...byBase.entries()].map(([base, actions]) => ({\n ...entry,\n service: \"tinycloud.kv\",\n path: vaultKVPath(base, entry.path),\n actions,\n skipPrefix: true,\n }));\n}\n\nfunction vaultActionExpansion(action: string): VaultActionExpansion {\n const normalized = normalizeVaultAction(action);\n if (normalized === \"read\" || normalized === \"get\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/get\" };\n }\n if (normalized === \"write\" || normalized === \"put\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/put\" };\n }\n if (normalized === \"delete\" || normalized === \"del\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/del\" };\n }\n if (normalized === \"list\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/list\" };\n }\n if (normalized === \"head\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/get\" };\n }\n if (normalized === \"metadata\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/metadata\" };\n }\n\n throw new ManifestValidationError(\n `unknown vault action ${JSON.stringify(action)}; expected read, write, delete, get, put, del, list, head, or metadata`,\n );\n}\n\nfunction normalizeVaultAction(action: string): string {\n if (action.startsWith(`${VAULT_PERMISSION_SERVICE}/`)) {\n return action.slice(`${VAULT_PERMISSION_SERVICE}/`.length);\n }\n if (action.startsWith(\"tinycloud.kv/\")) {\n return action.slice(\"tinycloud.kv/\".length);\n }\n if (action.includes(\"/\")) {\n throw new ManifestValidationError(\n `unknown vault action ${JSON.stringify(action)}; expected a tinycloud.vault or tinycloud.kv action`,\n );\n }\n return action;\n}\n\nfunction vaultKVPath(base: VaultKVBase, path: string): string {\n const normalized = path.startsWith(\"/\") ? path.slice(1) : path;\n return `${base}/${normalized}`;\n}\n\nfunction cloneResourceCapability(\n entry: ResourceCapability,\n): ResourceCapability {\n return {\n service: entry.service,\n space: entry.space,\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.expiryMs !== undefined ? { expiryMs: entry.expiryMs } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n };\n}\n\nfunction clonePermissionEntry(entry: PermissionEntry): PermissionEntry {\n return {\n service: entry.service,\n ...(entry.space !== undefined ? { space: entry.space } : {}),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats !== undefined\n ? { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }\n : {}),\n ...(entry.skipPrefix !== undefined ? { skipPrefix: entry.skipPrefix } : {}),\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n };\n}\n\nfunction dedupeResources(\n resources: readonly ResourceCapability[],\n): ResourceCapability[] {\n const byKey = new Map<string, ResourceCapability>();\n\n for (const resource of resources) {\n const key = `${resource.service}\\u0000${resource.space}\\u0000${resource.path}\\u0000${resource.expiryMs ?? \"\"}`;\n const existing = byKey.get(key);\n if (existing === undefined) {\n byKey.set(key, cloneResourceCapability(resource));\n continue;\n }\n\n const seen = new Set(existing.actions);\n for (const action of resource.actions) {\n if (!seen.has(action)) {\n existing.actions.push(action);\n seen.add(action);\n }\n }\n if (\n existing.description === undefined &&\n resource.description !== undefined\n ) {\n existing.description = resource.description;\n }\n }\n\n return [...byKey.values()];\n}\n\nfunction capabilitiesReadPermission(space: string): ResourceCapability {\n return {\n service: \"tinycloud.capabilities\",\n space,\n path: \"\",\n actions: [\"tinycloud.capabilities/read\"],\n };\n}\n\nfunction withCapabilitiesReadForSpaces(\n resources: readonly ResourceCapability[],\n): ResourceCapability[] {\n if (resources.length === 0) {\n return [];\n }\n\n const spaces = new Set(\n resources\n .filter((resource) => resource.service !== ENCRYPTION_PERMISSION_SERVICE)\n .map((resource) => resource.space),\n );\n return dedupeResources([\n ...resources,\n ...[...spaces].map(capabilitiesReadPermission),\n ]);\n}\n\n/**\n * Compose one or more manifests into the single capability request that should\n * be signed. Fetching manifests is intentionally out of band; callers pass the\n * already-loaded manifest objects.\n */\nexport function composeManifestRequest(\n inputs: readonly Manifest[],\n options: ComposeManifestOptions = {},\n): ComposedManifestRequest {\n if (!Array.isArray(inputs) || inputs.length === 0) {\n throw new ManifestValidationError(\n \"composeManifestRequest requires at least one manifest\",\n );\n }\n\n const includeAccountRegistryPermissions =\n options.includeAccountRegistryPermissions ?? true;\n const manifests = inputs.map(validateManifest);\n const resolved = manifests.map(resolveManifest);\n const resources = resolved.flatMap((entry) => entry.resources);\n const delegationTargets = resolved.flatMap((entry) =>\n entry.additionalDelegates.map((delegate) => ({\n ...delegate,\n permissions: dedupeResources(delegate.permissions),\n })),\n );\n\n if (includeAccountRegistryPermissions) {\n resources.push(\n ...ACCOUNT_MANIFEST_PERMISSIONS.map((resource) => ({\n ...resource,\n actions: [...resource.actions],\n })),\n );\n }\n const resourcesWithImplicitCapabilities =\n withCapabilitiesReadForSpaces(resources);\n\n const manifestsByAppId = new Map<string, Manifest[]>();\n for (const manifest of manifests) {\n const current = manifestsByAppId.get(manifest.app_id);\n if (current === undefined) {\n manifestsByAppId.set(manifest.app_id, [manifest]);\n } else {\n current.push(manifest);\n }\n }\n\n const registryRecords: ManifestRegistryRecord[] =\n includeAccountRegistryPermissions\n ? [...manifestsByAppId.entries()].map(([app_id, appManifests]) => ({\n key: `${ACCOUNT_REGISTRY_PATH}${app_id}`,\n app_id,\n manifests: appManifests.map((manifest) => ({\n ...manifest,\n permissions: manifest.permissions?.map(clonePermissionEntry),\n })),\n }))\n : [];\n\n return {\n manifests,\n resources: resourcesWithImplicitCapabilities,\n delegationTargets,\n registryRecords,\n expiryMs: Math.max(...resolved.map((entry) => entry.expiryMs)),\n includePublicSpace: resolved.some((entry) => entry.includePublicSpace),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Abilities map construction (bridge to WASM prepareSession / createDelegation)\n// ---------------------------------------------------------------------------\n\n/**\n * The shape `prepareSession` and the multi-resource `createDelegation` WASM\n * export both accept:\n *\n * ```\n * { [shortService]: { [path]: [fullUrnAction, ...] } }\n * ```\n *\n * - `shortService` is the recap-level service segment (`\"kv\"`, `\"sql\"`,\n * `\"duckdb\"`, `\"capabilities\"`, `\"hooks\"`) — not the manifest long form.\n * - `path` is the fully-resolved path (prefix already applied). An empty\n * string means \"no path segment\" on the resource URI.\n * - Action strings are full URNs like `\"tinycloud.kv/get\"`.\n *\n * This is a single source of truth for both the session's own recap (at\n * sign-in) and the delegations it can derive (post sign-in). We re-use it\n * for both so one manifest drives both sides.\n */\nexport type AbilitiesMap = Record<string, Record<string, string[]>>;\n\n/**\n * Per-space abilities map accepted by the newer WASM session config:\n *\n * ```\n * { [spaceIdOrName]: { [shortService]: { [path]: [fullUrnAction, ...] } } }\n * ```\n */\nexport type SpaceAbilitiesMap = Record<string, AbilitiesMap>;\n\n/**\n * Convert a list of {@link ResourceCapability} entries (manifest\n * long-form service, full-URN actions) into the {@link AbilitiesMap}\n * shape the WASM layer expects.\n *\n * When multiple entries target the same `(service, path)` pair, their\n * action lists are merged and deduped. Entries whose service has no\n * short-form mapping in {@link SERVICE_LONG_TO_SHORT} are rejected with\n * a {@link ManifestValidationError} — the SDK does not silently drop\n * unknown services because the recap encoding would lose them.\n *\n * Paths are kept verbatim: this function does NOT collapse\n * `\"com.listen.app/\"` and `\"com.listen.app\"` or reinterpret empty /\n * slash strings. Callers that care about path canonicalization should\n * normalize before calling.\n */\nexport function resourceCapabilitiesToAbilitiesMap(\n resources: readonly ResourceCapability[],\n): AbilitiesMap {\n const out: AbilitiesMap = {};\n for (const r of resources) {\n const shortService = SERVICE_LONG_TO_SHORT[r.service];\n if (shortService === undefined) {\n throw new ManifestValidationError(\n `unknown service '${r.service}' — no short-form mapping. Known services: ${Object.keys(SERVICE_LONG_TO_SHORT).join(\", \")}`,\n );\n }\n if (out[shortService] === undefined) {\n out[shortService] = {};\n }\n const pathsMap = out[shortService];\n const existing = pathsMap[r.path];\n if (existing === undefined) {\n // Copy so downstream mutation can't leak back into the input.\n pathsMap[r.path] = [...r.actions];\n } else {\n // Merge + dedupe while preserving first-seen order.\n const seen = new Set(existing);\n for (const action of r.actions) {\n if (!seen.has(action)) {\n existing.push(action);\n seen.add(action);\n }\n }\n }\n }\n return out;\n}\n\n/**\n * Group resolved capabilities by `space`, then convert each group into a WASM\n * abilities map. Short space names are left as-is here; platform layers that\n * know the wallet address and chain id turn them into full SpaceIds.\n */\nexport function resourceCapabilitiesToSpaceAbilitiesMap(\n resources: readonly ResourceCapability[],\n): SpaceAbilitiesMap {\n const grouped = new Map<string, ResourceCapability[]>();\n for (const resource of resources) {\n const entries = grouped.get(resource.space);\n if (entries === undefined) {\n grouped.set(resource.space, [resource]);\n } else {\n entries.push(resource);\n }\n }\n\n const out: SpaceAbilitiesMap = {};\n for (const [space, entries] of grouped.entries()) {\n out[space] = resourceCapabilitiesToAbilitiesMap(entries);\n }\n return out;\n}\n\n/**\n * Build the {@link AbilitiesMap} that a session should be signed with,\n * given a {@link ResolvedCapabilities} (i.e. the output of\n * {@link resolveManifest}).\n *\n * The resulting map is the **union** of:\n * 1. the app's own resources (`resolved.resources`), and\n * 2. every permission declared in every `additionalDelegates[*]` entry.\n *\n * The union is what makes the manifest's delegations ergonomic: at\n * sign-in, the session key acquires recap coverage for both the app's\n * runtime needs and every downstream delegation target. Post sign-in,\n * `delegateTo(backendDID, backendPermissions)` can then issue the\n * sub-delegation via the session key (no wallet prompt) because the\n * caps are already part of the granted set.\n *\n * Duplicate `(service, path, action)` triples across resources and\n * delegations are merged and deduped — the session SIWE doesn't need\n * them repeated.\n */\nexport function manifestAbilitiesUnion(\n resolved: ResolvedCapabilities,\n): AbilitiesMap {\n const all: ResourceCapability[] = [...resolved.resources];\n for (const delegate of resolved.additionalDelegates) {\n for (const perm of delegate.permissions) {\n all.push(perm);\n }\n }\n return resourceCapabilitiesToAbilitiesMap(all);\n}\n","/**\n * Capability subset checking and recap parsing.\n *\n * This module powers the capability-chain delegation flow. The key decision\n * a `delegateTo` call has to make is: \"are the requested capabilities a\n * subset of what the current session already grants?\"\n *\n * - If yes → issue the delegation via the session-key UCAN path (no wallet prompt).\n * - If no → raise {@link PermissionNotInManifestError} so the caller can\n * trigger an escalation flow via `requestPermissions`.\n *\n * Canonical spec: `.claude/specs/capability-chain.md`.\n *\n * @packageDocumentation\n */\n\nimport {\n DEFAULT_MANIFEST_SPACE,\n type PermissionEntry,\n SERVICE_SHORT_TO_LONG,\n expandActionShortNames,\n} from \"./manifest\";\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\n/**\n * Thrown when a `delegateTo` call requests capabilities that the current\n * session does not already grant. The caller can catch this and trigger\n * `requestPermissions(missing)` to show an escalation modal.\n */\nexport class PermissionNotInManifestError extends Error {\n public readonly missing: PermissionEntry[];\n public readonly granted: PermissionEntry[];\n\n constructor(missing: PermissionEntry[], granted: PermissionEntry[]) {\n super(\n `Requested capabilities exceed current session. Missing ${missing.length} entries.`\n );\n this.name = \"PermissionNotInManifestError\";\n this.missing = missing;\n this.granted = granted;\n }\n}\n\n/**\n * Thrown when the current session has expired (or will expire within the\n * safety margin). The caller should trigger a fresh sign-in.\n */\nexport class SessionExpiredError extends Error {\n public readonly expiredAt: Date;\n\n constructor(expiredAt: Date) {\n super(`Session expired at ${expiredAt.toISOString()}`);\n this.name = \"SessionExpiredError\";\n this.expiredAt = expiredAt;\n }\n}\n\n/**\n * Thrown when the installed WASM delegation boundary cannot encode every\n * constrained ReCap branch in a requested child delegation.\n */\nexport class CaveatedDelegationUnsupportedError extends Error {\n /** Stable machine-readable error code for fail-closed caveated delegation. */\n code = \"CAVEATED_DELEGATION_UNSUPPORTED\" as const;\n /** Requested entries whose constrained ReCap branches cannot be preserved. */\n entries: PermissionEntry[];\n\n constructor(entries: PermissionEntry[]) {\n super(\n \"Cannot create a caveated delegation because this WASM delegation boundary cannot preserve every ReCap caveat branch exactly.\"\n );\n this.name = \"CaveatedDelegationUnsupportedError\";\n this.entries = entries.map(cloneEntry);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Space normalization\n// ---------------------------------------------------------------------------\n\n/**\n * Normalize a space identifier to its short-name form.\n *\n * Recap resource URIs in a signed SIWE encode the space as a full URI of the\n * form `tinycloud:pkh:eip155:{chainId}:{address}:{name}` (e.g.\n * `tinycloud:pkh:eip155:1:0xd559...:default`). Manifest permissions and\n * backend-advertised permissions use the short `{name}` form (e.g.\n * `\"default\"`).\n *\n * Strict string comparison between these two forms would always fail, so we\n * normalize both sides to the short name before comparing. The trailing\n * segment after the last `:` in a `tinycloud:` URI is the space name.\n *\n * Short names (`\"default\"`, `\"work-space\"`) are returned unchanged.\n * Any non-`tinycloud:` string is returned unchanged. A malformed URI with a\n * trailing colon is returned unchanged (so the check degrades to a strict\n * mismatch rather than collapsing to an empty string).\n *\n * @internal\n */\nexport function normalizeSpace(space: string): string {\n if (!space.startsWith(\"tinycloud:\")) {\n return space;\n }\n const lastColon = space.lastIndexOf(\":\");\n if (lastColon === -1 || lastColon === space.length - 1) {\n return space;\n }\n return space.slice(lastColon + 1);\n}\n\n// ---------------------------------------------------------------------------\n// Subset check\n// ---------------------------------------------------------------------------\n\nexport interface SubsetCheckResult {\n /** True when every requested entry is covered by a granted entry. */\n subset: boolean;\n /** Entries the granted set does not cover (empty when `subset` is true). */\n missing: PermissionEntry[];\n}\n\n/**\n * Check whether `requested` is a strict subset of `granted`.\n *\n * Matching rules for each `requested[i]`:\n * - `service` matches exactly.\n * - `space` matches exactly.\n * - Path containment:\n * - If `granted.path` ends with `/`, it covers any `requested.path` that\n * starts with `granted.path`.\n * - Otherwise, the paths must match exactly.\n * - Action containment: every requested URN must be matched exactly or by a\n * service-scoped wildcard such as `tinycloud.kv/*`.\n *\n * Grant entries with the same service, space, path coverage, and caveats are\n * considered together. This matters because ReCap parsers may return one\n * entry per action even when the original manifest grouped those actions.\n * Any `requested` entry whose actions are not collectively covered is added\n * to `missing` and the overall result is non-subset.\n *\n * Both sides are expected to be in the canonical long-form shape (service\n * starts with `tinycloud.`, actions are full URNs). Use {@link parseRecapCapabilities}\n * or `expandActionShortNames` to normalize inputs first.\n */\nexport function isCapabilitySubset(\n requested: readonly PermissionEntry[],\n granted: readonly PermissionEntry[]\n): SubsetCheckResult {\n const missing: PermissionEntry[] = [];\n\n for (const req of requested) {\n const matchingScope = granted.filter((entry) =>\n canonicalizeEntryScopeMatches(req, entry)\n );\n const requestedActions = expandActionShortNames(\n req.service,\n req.actions\n );\n const grantedActions = matchingScope.flatMap((entry) =>\n expandActionShortNames(entry.service, entry.actions)\n );\n const covered = requestedActions.every((requestedAction) =>\n grantedActions.some((grantedAction) =>\n actionContains(grantedAction, requestedAction)\n )\n );\n if (!covered) {\n missing.push(cloneEntry(req));\n }\n }\n\n return { subset: missing.length === 0, missing };\n}\n\n/**\n * Returns true when `granted` fully covers `requested` — same service, same\n * space, path containment per spec, and action set containment.\n */\nfunction canonicalizeEntryScopeMatches(\n requested: PermissionEntry,\n granted: PermissionEntry\n): boolean {\n if (requested.service !== granted.service) {\n return false;\n }\n // Normalize both sides so callers passing short names (`\"default\"`) match\n // recap-parsed full URIs (`\"tinycloud:pkh:eip155:1:0xd559...:default\"`) and\n // vice versa. Idempotent for short names.\n if (\n normalizeSpace(requested.space ?? DEFAULT_MANIFEST_SPACE) !==\n normalizeSpace(granted.space ?? DEFAULT_MANIFEST_SPACE)\n ) {\n return false;\n }\n if (!pathContains(granted.path, requested.path)) {\n return false;\n }\n // There is no safe general partial ordering for arbitrary ReCap caveat\n // objects. A caveated authority therefore only covers the same caveat set;\n // treating it as uncaveated would authorize a broader child delegation.\n if (!recapCaveatsEqual(requested.caveats, granted.caveats)) {\n return false;\n }\n return true;\n}\n\n/**\n * Compare ReCap caveat branch sets without losing signed branch structure.\n *\n * ReCap represents an unconstrained ability as `[{}]`, while SDK callers can\n * represent that same authority as `undefined` or `[]`. Those three forms are\n * equivalent. Every other branch, including an unconstrained branch mixed\n * with a constrained one, remains part of the canonical comparison.\n */\nexport function recapCaveatsEqual(\n left: readonly Record<string, unknown>[] | undefined,\n right: readonly Record<string, unknown>[] | undefined,\n): boolean {\n return canonicalizeRecapCaveats(left) === canonicalizeRecapCaveats(right);\n}\n\n/**\n * Canonicalize a ReCap caveat branch set for exact equality checks.\n *\n * Object keys and branch order do not affect equality. A lone unconstrained\n * branch is normalized to the SDK's empty-caveat representation, but an\n * unconstrained branch in a mixed set is deliberately retained.\n */\nexport function canonicalizeRecapCaveats(\n caveats: readonly Record<string, unknown>[] | undefined,\n): string {\n const canonicalize = (value: unknown): string => {\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") {\n return JSON.stringify(value);\n }\n if (typeof value === \"number\") {\n if (Number.isFinite(value)) return JSON.stringify(value);\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n }\n if (Array.isArray(value)) return `[${value.map(canonicalize).join(\",\")}]`;\n if (typeof value === \"object\") {\n const object = value as Record<string, unknown>;\n const prototype = Object.getPrototypeOf(object);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n }\n return `{${Object.keys(object).sort().map((key) =>\n `${JSON.stringify(key)}:${canonicalize(object[key])}`,\n ).join(\",\")}}`;\n }\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n };\n const branches = (caveats ?? []).map(canonicalize).sort();\n if (branches.length === 0 || (branches.length === 1 && branches[0] === \"{}\")) {\n return \"[]\";\n }\n return `[${branches.join(\",\")}]`;\n}\n\n// Literal strings, not `KV.SYNC`/`KV.RETAIN`: those are derived from the\n// vendored registry at runtime, so an older bootstrap would turn them into\n// `undefined` and silently disable this guard.\nconst EXPLICIT_ONLY_ACTIONS: Readonly<Record<string, true>> = {\n \"tinycloud.kv/sync\": true,\n \"tinycloud.kv/retain\": true,\n};\n\n/**\n * Whether `action` is one no wildcard covers: `*` and `tinycloud.kv/*` do not\n * grant it, so a grant must name it (TC-732). `tinycloud.kv/sync` discloses a\n * prefix's change feed and `tinycloud.kv/retain` is an owner-approved\n * retention attestation; the node refuses both unless granted by name.\n */\nexport function isExplicitOnlyAction(action: string): boolean {\n return Object.prototype.hasOwnProperty.call(EXPLICIT_ONLY_ACTIONS, action);\n}\n\n/** Return whether a granted action pattern covers one requested action. */\nexport function actionContains(grantedAction: string, requestedAction: string): boolean {\n if (grantedAction === requestedAction) return true;\n if (isExplicitOnlyAction(requestedAction)) return false;\n if (grantedAction === \"*\") return true;\n if (!grantedAction.endsWith(\"/*\")) return false;\n const service = grantedAction.slice(0, -2);\n return requestedAction === service || requestedAction.startsWith(`${service}/`);\n}\n\n/**\n * Path containment per spec:\n * - `granted.path` ends with `/` → prefix match (requested starts with granted)\n * - otherwise → exact string match\n *\n * The empty string is treated as \"no path constraint\" and matches anything.\n * The single-character `\"/\"` also matches anything (it is a trailing-slash\n * prefix of zero-length).\n */\nfunction pathContains(grantedPath: string, requestedPath: string): boolean {\n if (grantedPath === \"\" || grantedPath === \"/\") {\n return true;\n }\n if (grantedPath.endsWith(\"/\")) {\n return requestedPath.startsWith(grantedPath);\n }\n return requestedPath === grantedPath;\n}\n\nfunction cloneEntry(entry: PermissionEntry): PermissionEntry {\n return {\n service: entry.service,\n ...(entry.space !== undefined ? { space: entry.space } : {}),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats !== undefined\n ? { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }\n : {}),\n ...(entry.skipPrefix !== undefined ? { skipPrefix: entry.skipPrefix } : {}),\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Recap parsing (WASM wrapper)\n// ---------------------------------------------------------------------------\n\n/**\n * The raw shape returned from the WASM `parseRecapFromSiwe` export. The\n * Rust layer encodes the service in the short form (e.g. `\"kv\"`) because\n * that is what the SIWE recap resource URI actually contains. We normalize\n * to the manifest long form (`\"tinycloud.kv\"`) in {@link parseRecapCapabilities}.\n *\n * @internal\n */\nexport interface WasmRecapEntry {\n service: string;\n space: string;\n path: string;\n actions: string[];\n /** Exact ReCap caveats shared by every action in this entry. */\n caveats?: Record<string, unknown>[];\n}\n\n/**\n * Signature of the WASM `parseRecapFromSiwe` export. Accepts the signed\n * SIWE message string and returns an array of raw recap entries. Throws if\n * the SIWE is malformed or the recap statement has been tampered.\n *\n * Exposed as an interface so the SDK can inject the web or node binding\n * without `capabilities.ts` needing to know which.\n */\nexport type ParseRecapFromSiwe = (siweString: string) => WasmRecapEntry[];\n\n/**\n * Parse a signed SIWE message into an array of {@link PermissionEntry}\n * objects in the canonical long-form manifest shape.\n *\n * This is a thin wrapper around the WASM `parseRecapFromSiwe` export that:\n * 1. Normalizes short-form services (`\"kv\"`) to long-form (`\"tinycloud.kv\"`).\n * 2. Returns entries in a deterministic order (sorted by space, then service,\n * then path) so downstream equality checks are stable.\n *\n * Returns an empty array when the SIWE has no recap resource (plain auth\n * SIWE); this matches the WASM function's behavior and the spec.\n *\n * @param parseWasm The WASM `parseRecapFromSiwe` binding.\n * @param siwe The signed SIWE message string (exactly what `session.siwe` stores).\n */\nexport function parseRecapCapabilities(\n parseWasm: ParseRecapFromSiwe,\n siwe: string\n): PermissionEntry[] {\n const raw = parseWasm(siwe);\n if (!Array.isArray(raw)) {\n throw new Error(\n \"parseRecapFromSiwe returned a non-array value; wasm binding may be out of sync\"\n );\n }\n const normalized: PermissionEntry[] = raw.map((entry) => {\n const longService =\n SERVICE_SHORT_TO_LONG[entry.service] ??\n // Unknown short names pass through. If the recap already contained a\n // long-form service (e.g. a future tinycloud-node version emits long\n // form directly), don't double-prefix.\n (entry.service.startsWith(\"tinycloud.\")\n ? entry.service\n : `tinycloud.${entry.service}`);\n return {\n service: longService,\n // The Rust layer emits the space as a full `tinycloud:pkh:...:name`\n // URI (the recap target URI). Normalize to the short name so the\n // returned entries match the shape manifests use.\n space: normalizeSpace(entry.space),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats === undefined\n ? {}\n : { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }),\n };\n });\n\n // Sort for determinism (callers do equality checks on arrays of entries\n // in tests; deterministic ordering keeps those stable).\n normalized.sort((a, b) => {\n const aSpace = a.space ?? DEFAULT_MANIFEST_SPACE;\n const bSpace = b.space ?? DEFAULT_MANIFEST_SPACE;\n if (aSpace !== bSpace) return aSpace < bSpace ? -1 : 1;\n if (a.service !== b.service) return a.service < b.service ? -1 : 1;\n if (a.path !== b.path) return a.path < b.path ? -1 : 1;\n return 0;\n });\n\n return normalized;\n}\n","/**\n * Blake3 fast hash is Blake2 with reduced security (round count). Can also be used as MAC & KDF.\n *\n * It is advertised as \"the fastest cryptographic hash\". However, it isn't true in JS.\n * Why is this so slow? While it should be 6x faster than blake2b, perf diff is only 20%:\n *\n * * There is only 30% reduction in number of rounds from blake2s\n * * Speed-up comes from tree structure, which is parallelized using SIMD & threading.\n * These features are not present in JS, so we only get overhead from trees.\n * * Parallelization only happens on 1024-byte chunks: there is no benefit for small inputs.\n * * It is still possible to make it faster using: a) loop unrolling b) web workers c) wasm\n * @module\n */\nimport { SHA256_IV } from './_md.ts';\nimport { fromBig } from './_u64.ts';\nimport { BLAKE2, compress } from './blake2.ts';\n// prettier-ignore\nimport {\n abytes, aexists, anumber, aoutput,\n clean, createXOFer, swap32IfBE, toBytes, u32, u8,\n type CHashXO, type HashXOF, type Input\n} from './utils.ts';\n\n// Flag bitset\nconst B3_Flags = {\n CHUNK_START: 0b1,\n CHUNK_END: 0b10,\n PARENT: 0b100,\n ROOT: 0b1000,\n KEYED_HASH: 0b10000,\n DERIVE_KEY_CONTEXT: 0b100000,\n DERIVE_KEY_MATERIAL: 0b1000000,\n} as const;\n\nconst B3_IV = SHA256_IV.slice();\n\nconst B3_SIGMA: Uint8Array = /* @__PURE__ */ (() => {\n const Id = Array.from({ length: 16 }, (_, i) => i);\n const permute = (arr: number[]) =>\n [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]);\n const res: number[] = [];\n for (let i = 0, v = Id; i < 7; i++, v = permute(v)) res.push(...v);\n return Uint8Array.from(res);\n})();\n\n/**\n * Ensure to use EITHER `key` OR `context`, not both.\n *\n * * `key`: 32-byte MAC key.\n * * `context`: string for KDF. Should be hardcoded, globally unique, and application - specific.\n * A good default format for the context string is \"[application] [commit timestamp] [purpose]\".\n */\nexport type Blake3Opts = { dkLen?: number; key?: Input; context?: Input };\n\n/** Blake3 hash. Can be used as MAC and KDF. */\nexport class BLAKE3 extends BLAKE2<BLAKE3> implements HashXOF<BLAKE3> {\n private chunkPos = 0; // Position of current block in chunk\n private chunksDone = 0; // How many chunks we already have\n private flags = 0 | 0;\n private IV: Uint32Array;\n private state: Uint32Array;\n private stack: Uint32Array[] = [];\n // Output\n private posOut = 0;\n private bufferOut32 = new Uint32Array(16);\n private bufferOut: Uint8Array;\n private chunkOut = 0; // index of output chunk\n private enableXOF = true;\n\n constructor(opts: Blake3Opts = {}, flags = 0) {\n super(64, opts.dkLen === undefined ? 32 : opts.dkLen);\n const { key, context } = opts;\n const hasContext = context !== undefined;\n if (key !== undefined) {\n if (hasContext) throw new Error('Only \"key\" or \"context\" can be specified at same time');\n const k = toBytes(key).slice();\n abytes(k, 32);\n this.IV = u32(k);\n swap32IfBE(this.IV);\n this.flags = flags | B3_Flags.KEYED_HASH;\n } else if (hasContext) {\n const ctx = toBytes(context);\n const contextKey = new BLAKE3({ dkLen: 32 }, B3_Flags.DERIVE_KEY_CONTEXT)\n .update(ctx)\n .digest();\n this.IV = u32(contextKey);\n swap32IfBE(this.IV);\n this.flags = flags | B3_Flags.DERIVE_KEY_MATERIAL;\n } else {\n this.IV = B3_IV.slice();\n this.flags = flags;\n }\n this.state = this.IV.slice();\n this.bufferOut = u8(this.bufferOut32);\n }\n // Unused\n protected get(): [] {\n return [];\n }\n protected set(): void {}\n private b2Compress(counter: number, flags: number, buf: Uint32Array, bufPos: number = 0) {\n const { state: s, pos } = this;\n const { h, l } = fromBig(BigInt(counter), true);\n // prettier-ignore\n const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } =\n compress(\n B3_SIGMA, bufPos, buf, 7,\n s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7],\n B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], h, l, pos, flags\n );\n s[0] = v0 ^ v8;\n s[1] = v1 ^ v9;\n s[2] = v2 ^ v10;\n s[3] = v3 ^ v11;\n s[4] = v4 ^ v12;\n s[5] = v5 ^ v13;\n s[6] = v6 ^ v14;\n s[7] = v7 ^ v15;\n }\n protected compress(buf: Uint32Array, bufPos: number = 0, isLast: boolean = false): void {\n // Compress last block\n let flags = this.flags;\n if (!this.chunkPos) flags |= B3_Flags.CHUNK_START;\n if (this.chunkPos === 15 || isLast) flags |= B3_Flags.CHUNK_END;\n if (!isLast) this.pos = this.blockLen;\n this.b2Compress(this.chunksDone, flags, buf, bufPos);\n this.chunkPos += 1;\n // If current block is last in chunk (16 blocks), then compress chunks\n if (this.chunkPos === 16 || isLast) {\n let chunk = this.state;\n this.state = this.IV.slice();\n // If not the last one, compress only when there are trailing zeros in chunk counter\n // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed.\n // 1 (001) - leaf not finished (just push current chunk to stack)\n // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back)\n // 3 (011) - last leaf not finished\n // 4 (100) - leafs finished at depth=1 and depth=2\n for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) {\n if (!(last = this.stack.pop())) break;\n this.buffer32.set(last, 0);\n this.buffer32.set(chunk, 8);\n this.pos = this.blockLen;\n this.b2Compress(0, this.flags | B3_Flags.PARENT, this.buffer32, 0);\n chunk = this.state;\n this.state = this.IV.slice();\n }\n this.chunksDone++;\n this.chunkPos = 0;\n this.stack.push(chunk);\n }\n this.pos = 0;\n }\n _cloneInto(to?: BLAKE3): BLAKE3 {\n to = super._cloneInto(to) as BLAKE3;\n const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this;\n to.state.set(state.slice());\n to.stack = stack.map((i) => Uint32Array.from(i));\n to.IV.set(IV);\n to.flags = flags;\n to.chunkPos = chunkPos;\n to.chunksDone = chunksDone;\n to.posOut = posOut;\n to.chunkOut = chunkOut;\n to.enableXOF = this.enableXOF;\n to.bufferOut32.set(this.bufferOut32);\n return to;\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.state, this.buffer32, this.IV, this.bufferOut32);\n clean(...this.stack);\n }\n // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8)\n private b2CompressOut() {\n const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this;\n const { h, l } = fromBig(BigInt(this.chunkOut++));\n swap32IfBE(buffer32);\n // prettier-ignore\n const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } =\n compress(\n B3_SIGMA, 0, buffer32, 7,\n s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7],\n B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], l, h, pos, flags\n );\n out32[0] = v0 ^ v8;\n out32[1] = v1 ^ v9;\n out32[2] = v2 ^ v10;\n out32[3] = v3 ^ v11;\n out32[4] = v4 ^ v12;\n out32[5] = v5 ^ v13;\n out32[6] = v6 ^ v14;\n out32[7] = v7 ^ v15;\n out32[8] = s[0] ^ v8;\n out32[9] = s[1] ^ v9;\n out32[10] = s[2] ^ v10;\n out32[11] = s[3] ^ v11;\n out32[12] = s[4] ^ v12;\n out32[13] = s[5] ^ v13;\n out32[14] = s[6] ^ v14;\n out32[15] = s[7] ^ v15;\n swap32IfBE(buffer32);\n swap32IfBE(out32);\n this.posOut = 0;\n }\n protected finish(): void {\n if (this.finished) return;\n this.finished = true;\n // Padding\n clean(this.buffer.subarray(this.pos));\n // Process last chunk\n let flags = this.flags | B3_Flags.ROOT;\n if (this.stack.length) {\n flags |= B3_Flags.PARENT;\n swap32IfBE(this.buffer32);\n this.compress(this.buffer32, 0, true);\n swap32IfBE(this.buffer32);\n this.chunksDone = 0;\n this.pos = this.blockLen;\n } else {\n flags |= (!this.chunkPos ? B3_Flags.CHUNK_START : 0) | B3_Flags.CHUNK_END;\n }\n this.flags = flags;\n this.b2CompressOut();\n }\n private writeInto(out: Uint8Array) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const { blockLen, bufferOut } = this;\n for (let pos = 0, len = out.length; pos < len; ) {\n if (this.posOut >= blockLen) this.b2CompressOut();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out: Uint8Array): Uint8Array {\n if (!this.enableXOF) throw new Error('XOF is not possible after digest call');\n return this.writeInto(out);\n }\n xof(bytes: number): Uint8Array {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out: Uint8Array): Uint8Array {\n aoutput(out, this);\n if (this.finished) throw new Error('digest() was already called');\n this.enableXOF = false;\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest(): Uint8Array {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n}\n\n/**\n * BLAKE3 hash function. Can be used as MAC and KDF.\n * @param msg - message that would be hashed\n * @param opts - `dkLen` for output length, `key` for MAC mode, `context` for KDF mode\n * @example\n * const data = new Uint8Array(32);\n * const hash = blake3(data);\n * const mac = blake3(data, { key: new Uint8Array(32) });\n * const kdf = blake3(data, { context: 'application name' });\n */\nexport const blake3: CHashXO = /* @__PURE__ */ createXOFer<BLAKE3, Blake3Opts>(\n (opts) => new BLAKE3(opts)\n);\n","/**\n * Internal helpers for blake hash.\n * @module\n */\nimport { rotr } from './utils.ts';\n\n/**\n * Internal blake variable.\n * For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1].\n */\n// prettier-ignore\nexport const BSIGMA: Uint8Array = /* @__PURE__ */ Uint8Array.from([\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,\n 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,\n 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,\n 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,\n 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,\n 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,\n 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,\n 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,\n 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,\n // Blake1, unused in others\n 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,\n 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,\n 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,\n 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,\n]);\n\n// prettier-ignore\nexport type Num4 = { a: number; b: number; c: number; d: number; };\n\n// Mixing function G splitted in two halfs\nexport function G1s(a: number, b: number, c: number, d: number, x: number): Num4 {\n a = (a + b + x) | 0;\n d = rotr(d ^ a, 16);\n c = (c + d) | 0;\n b = rotr(b ^ c, 12);\n return { a, b, c, d };\n}\n\nexport function G2s(a: number, b: number, c: number, d: number, x: number): Num4 {\n a = (a + b + x) | 0;\n d = rotr(d ^ a, 8);\n c = (c + d) | 0;\n b = rotr(b ^ c, 7);\n return { a, b, c, d };\n}\n","/**\n * blake2b (64-bit) & blake2s (8 to 32-bit) hash functions.\n * b could have been faster, but there is no fast u64 in js, so s is 1.5x faster.\n * @module\n */\nimport { BSIGMA, G1s, G2s } from './_blake.ts';\nimport { SHA256_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\n// prettier-ignore\nimport {\n abytes, aexists, anumber, aoutput,\n clean, createOptHasher, Hash, swap32IfBE, swap8IfBE, toBytes, u32,\n type CHashO, type Input\n} from './utils.ts';\n\n/** Blake hash options. dkLen is output length. key is used in MAC mode. salt is used in KDF mode. */\nexport type Blake2Opts = {\n dkLen?: number;\n key?: Input;\n salt?: Input;\n personalization?: Input;\n};\n\n// Same as SHA512_IV, but swapped endianness: LE instead of BE. iv[1] is iv[0], etc.\nconst B2B_IV = /* @__PURE__ */ Uint32Array.from([\n 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a,\n 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19,\n]);\n// Temporary buffer\nconst BBUF = /* @__PURE__ */ new Uint32Array(32);\n\n// Mixing function G splitted in two halfs\nfunction G1b(a: number, b: number, c: number, d: number, msg: Uint32Array, x: number) {\n // NOTE: V is LE here\n const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore\n let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore\n let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore\n let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore\n let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore\n // v[a] = (v[a] + v[b] + x) | 0;\n let ll = u64.add3L(Al, Bl, Xl);\n Ah = u64.add3H(ll, Ah, Bh, Xh);\n Al = ll | 0;\n // v[d] = rotr(v[d] ^ v[a], 32)\n ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });\n ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) });\n // v[c] = (v[c] + v[d]) | 0;\n ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));\n // v[b] = rotr(v[b] ^ v[c], 24)\n ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });\n ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) });\n (BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah);\n (BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh);\n (BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch);\n (BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh);\n}\n\nfunction G2b(a: number, b: number, c: number, d: number, msg: Uint32Array, x: number) {\n // NOTE: V is LE here\n const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore\n let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore\n let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore\n let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore\n let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore\n // v[a] = (v[a] + v[b] + x) | 0;\n let ll = u64.add3L(Al, Bl, Xl);\n Ah = u64.add3H(ll, Ah, Bh, Xh);\n Al = ll | 0;\n // v[d] = rotr(v[d] ^ v[a], 16)\n ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });\n ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) });\n // v[c] = (v[c] + v[d]) | 0;\n ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));\n // v[b] = rotr(v[b] ^ v[c], 63)\n ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });\n ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) });\n (BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah);\n (BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh);\n (BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch);\n (BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh);\n}\n\nfunction checkBlake2Opts(\n outputLen: number,\n opts: Blake2Opts | undefined = {},\n keyLen: number,\n saltLen: number,\n persLen: number\n) {\n anumber(keyLen);\n if (outputLen < 0 || outputLen > keyLen) throw new Error('outputLen bigger than keyLen');\n const { key, salt, personalization } = opts;\n if (key !== undefined && (key.length < 1 || key.length > keyLen))\n throw new Error('key length must be undefined or 1..' + keyLen);\n if (salt !== undefined && salt.length !== saltLen)\n throw new Error('salt must be undefined or ' + saltLen);\n if (personalization !== undefined && personalization.length !== persLen)\n throw new Error('personalization must be undefined or ' + persLen);\n}\n\n/** Class, from which others are subclassed. */\nexport abstract class BLAKE2<T extends BLAKE2<T>> extends Hash<T> {\n protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected buffer: Uint8Array;\n protected buffer32: Uint32Array;\n protected finished = false;\n protected destroyed = false;\n protected length: number = 0;\n protected pos: number = 0;\n readonly blockLen: number;\n readonly outputLen: number;\n\n constructor(blockLen: number, outputLen: number) {\n super();\n anumber(blockLen);\n anumber(outputLen);\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.buffer = new Uint8Array(blockLen);\n this.buffer32 = u32(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n // Main difference with other hashes: there is flag for last block,\n // so we cannot process current block before we know that there\n // is the next one. This significantly complicates logic and reduces ability\n // to do zero-copy processing\n const { blockLen, buffer, buffer32 } = this;\n const len = data.length;\n const offset = data.byteOffset;\n const buf = data.buffer;\n for (let pos = 0; pos < len; ) {\n // If buffer is full and we still have input (don't process last block, same as blake2s)\n if (this.pos === blockLen) {\n swap32IfBE(buffer32);\n this.compress(buffer32, 0, false);\n swap32IfBE(buffer32);\n this.pos = 0;\n }\n const take = Math.min(blockLen - this.pos, len - pos);\n const dataOffset = offset + pos;\n // full block && aligned to 4 bytes && not last in input\n if (take === blockLen && !(dataOffset % 4) && pos + take < len) {\n const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4));\n swap32IfBE(data32);\n for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {\n this.length += blockLen;\n this.compress(data32, pos32, false);\n }\n swap32IfBE(data32);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n this.length += take;\n pos += take;\n }\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n const { pos, buffer32 } = this;\n this.finished = true;\n // Padding\n clean(this.buffer.subarray(pos));\n swap32IfBE(buffer32);\n this.compress(buffer32, 0, true);\n swap32IfBE(buffer32);\n const out32 = u32(out);\n this.get().forEach((v, i) => (out32[i] = swap8IfBE(v)));\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n const { buffer, length, finished, destroyed, outputLen, pos } = this;\n to ||= new (this.constructor as any)({ dkLen: outputLen }) as T;\n to.set(...this.get());\n to.buffer.set(buffer);\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // @ts-ignore\n to.outputLen = outputLen;\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\nexport class BLAKE2b extends BLAKE2<BLAKE2b> {\n // Same as SHA-512, but LE\n private v0l = B2B_IV[0] | 0;\n private v0h = B2B_IV[1] | 0;\n private v1l = B2B_IV[2] | 0;\n private v1h = B2B_IV[3] | 0;\n private v2l = B2B_IV[4] | 0;\n private v2h = B2B_IV[5] | 0;\n private v3l = B2B_IV[6] | 0;\n private v3h = B2B_IV[7] | 0;\n private v4l = B2B_IV[8] | 0;\n private v4h = B2B_IV[9] | 0;\n private v5l = B2B_IV[10] | 0;\n private v5h = B2B_IV[11] | 0;\n private v6l = B2B_IV[12] | 0;\n private v6h = B2B_IV[13] | 0;\n private v7l = B2B_IV[14] | 0;\n private v7h = B2B_IV[15] | 0;\n\n constructor(opts: Blake2Opts = {}) {\n const olen = opts.dkLen === undefined ? 64 : opts.dkLen;\n super(128, olen);\n checkBlake2Opts(olen, opts, 64, 16, 16);\n let { key, personalization, salt } = opts;\n let keyLength = 0;\n if (key !== undefined) {\n key = toBytes(key);\n keyLength = key.length;\n }\n this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);\n if (salt !== undefined) {\n salt = toBytes(salt);\n const slt = u32(salt);\n this.v4l ^= swap8IfBE(slt[0]);\n this.v4h ^= swap8IfBE(slt[1]);\n this.v5l ^= swap8IfBE(slt[2]);\n this.v5h ^= swap8IfBE(slt[3]);\n }\n if (personalization !== undefined) {\n personalization = toBytes(personalization);\n const pers = u32(personalization);\n this.v6l ^= swap8IfBE(pers[0]);\n this.v6h ^= swap8IfBE(pers[1]);\n this.v7l ^= swap8IfBE(pers[2]);\n this.v7h ^= swap8IfBE(pers[3]);\n }\n if (key !== undefined) {\n // Pad to blockLen and update\n const tmp = new Uint8Array(this.blockLen);\n tmp.set(key);\n this.update(tmp);\n }\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;\n return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h];\n }\n // prettier-ignore\n protected set(\n v0l: number, v0h: number, v1l: number, v1h: number,\n v2l: number, v2h: number, v3l: number, v3h: number,\n v4l: number, v4h: number, v5l: number, v5h: number,\n v6l: number, v6h: number, v7l: number, v7h: number\n ): void {\n this.v0l = v0l | 0;\n this.v0h = v0h | 0;\n this.v1l = v1l | 0;\n this.v1h = v1h | 0;\n this.v2l = v2l | 0;\n this.v2h = v2h | 0;\n this.v3l = v3l | 0;\n this.v3h = v3h | 0;\n this.v4l = v4l | 0;\n this.v4h = v4h | 0;\n this.v5l = v5l | 0;\n this.v5h = v5h | 0;\n this.v6l = v6l | 0;\n this.v6h = v6h | 0;\n this.v7l = v7l | 0;\n this.v7h = v7h | 0;\n }\n protected compress(msg: Uint32Array, offset: number, isLast: boolean): void {\n this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state.\n BBUF.set(B2B_IV, 16); // Second half from IV.\n let { h, l } = u64.fromBig(BigInt(this.length));\n BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset.\n BBUF[25] = B2B_IV[9] ^ h; // High word.\n // Invert all bits for last block\n if (isLast) {\n BBUF[28] = ~BBUF[28];\n BBUF[29] = ~BBUF[29];\n }\n let j = 0;\n const s = BSIGMA;\n for (let i = 0; i < 12; i++) {\n G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]);\n G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]);\n G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]);\n G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]);\n G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]);\n G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]);\n G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]);\n G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]);\n\n G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]);\n G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]);\n G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]);\n G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]);\n G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]);\n G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]);\n G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]);\n G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]);\n }\n this.v0l ^= BBUF[0] ^ BBUF[16];\n this.v0h ^= BBUF[1] ^ BBUF[17];\n this.v1l ^= BBUF[2] ^ BBUF[18];\n this.v1h ^= BBUF[3] ^ BBUF[19];\n this.v2l ^= BBUF[4] ^ BBUF[20];\n this.v2h ^= BBUF[5] ^ BBUF[21];\n this.v3l ^= BBUF[6] ^ BBUF[22];\n this.v3h ^= BBUF[7] ^ BBUF[23];\n this.v4l ^= BBUF[8] ^ BBUF[24];\n this.v4h ^= BBUF[9] ^ BBUF[25];\n this.v5l ^= BBUF[10] ^ BBUF[26];\n this.v5h ^= BBUF[11] ^ BBUF[27];\n this.v6l ^= BBUF[12] ^ BBUF[28];\n this.v6h ^= BBUF[13] ^ BBUF[29];\n this.v7l ^= BBUF[14] ^ BBUF[30];\n this.v7h ^= BBUF[15] ^ BBUF[31];\n clean(BBUF);\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.buffer32);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/**\n * Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS.\n * @param msg - message that would be hashed\n * @param opts - dkLen output length, key for MAC mode, salt, personalization\n */\nexport const blake2b: CHashO = /* @__PURE__ */ createOptHasher<BLAKE2b, Blake2Opts>(\n (opts) => new BLAKE2b(opts)\n);\n\n// =================\n// Blake2S\n// =================\n\n// prettier-ignore\nexport type Num16 = {\n v0: number; v1: number; v2: number; v3: number;\n v4: number; v5: number; v6: number; v7: number;\n v8: number; v9: number; v10: number; v11: number;\n v12: number; v13: number; v14: number; v15: number;\n};\n\n// prettier-ignore\nexport function compress(s: Uint8Array, offset: number, msg: Uint32Array, rounds: number,\n v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number,\n v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number,\n): Num16 {\n let j = 0;\n for (let i = 0; i < rounds; i++) {\n ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]]));\n ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]]));\n ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]]));\n ({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]]));\n ({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]]));\n ({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]]));\n ({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]]));\n ({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]]));\n\n ({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]]));\n ({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]]));\n ({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]]));\n ({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]]));\n ({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]]));\n ({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]]));\n ({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]]));\n ({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]]));\n }\n return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 };\n}\n\nconst B2S_IV = SHA256_IV;\nexport class BLAKE2s extends BLAKE2<BLAKE2s> {\n // Internal state, same as SHA-256\n private v0 = B2S_IV[0] | 0;\n private v1 = B2S_IV[1] | 0;\n private v2 = B2S_IV[2] | 0;\n private v3 = B2S_IV[3] | 0;\n private v4 = B2S_IV[4] | 0;\n private v5 = B2S_IV[5] | 0;\n private v6 = B2S_IV[6] | 0;\n private v7 = B2S_IV[7] | 0;\n\n constructor(opts: Blake2Opts = {}) {\n const olen = opts.dkLen === undefined ? 32 : opts.dkLen;\n super(64, olen);\n checkBlake2Opts(olen, opts, 32, 8, 8);\n let { key, personalization, salt } = opts;\n let keyLength = 0;\n if (key !== undefined) {\n key = toBytes(key);\n keyLength = key.length;\n }\n this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);\n if (salt !== undefined) {\n salt = toBytes(salt);\n const slt = u32(salt as Uint8Array);\n this.v4 ^= swap8IfBE(slt[0]);\n this.v5 ^= swap8IfBE(slt[1]);\n }\n if (personalization !== undefined) {\n personalization = toBytes(personalization);\n const pers = u32(personalization as Uint8Array);\n this.v6 ^= swap8IfBE(pers[0]);\n this.v7 ^= swap8IfBE(pers[1]);\n }\n if (key !== undefined) {\n // Pad to blockLen and update\n abytes(key);\n const tmp = new Uint8Array(this.blockLen);\n tmp.set(key);\n this.update(tmp);\n }\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { v0, v1, v2, v3, v4, v5, v6, v7 } = this;\n return [v0, v1, v2, v3, v4, v5, v6, v7];\n }\n // prettier-ignore\n protected set(\n v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number\n ): void {\n this.v0 = v0 | 0;\n this.v1 = v1 | 0;\n this.v2 = v2 | 0;\n this.v3 = v3 | 0;\n this.v4 = v4 | 0;\n this.v5 = v5 | 0;\n this.v6 = v6 | 0;\n this.v7 = v7 | 0;\n }\n protected compress(msg: Uint32Array, offset: number, isLast: boolean): void {\n const { h, l } = u64.fromBig(BigInt(this.length));\n // prettier-ignore\n const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } =\n compress(\n BSIGMA, offset, msg, 10,\n this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7,\n B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7]\n );\n this.v0 ^= v0 ^ v8;\n this.v1 ^= v1 ^ v9;\n this.v2 ^= v2 ^ v10;\n this.v3 ^= v3 ^ v11;\n this.v4 ^= v4 ^ v12;\n this.v5 ^= v5 ^ v13;\n this.v6 ^= v6 ^ v14;\n this.v7 ^= v7 ^ v15;\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.buffer32);\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/**\n * Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS.\n * @param msg - message that would be hashed\n * @param opts - dkLen output length, key for MAC mode, salt, personalization\n */\nexport const blake2s: CHashO = /* @__PURE__ */ createOptHasher<BLAKE2s, Blake2Opts>(\n (opts) => new BLAKE2s(opts)\n);\n","/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, utf8ToBytes } from '@noble/hashes/utils.js';\nimport { pippenger, type AffinePoint } from './abstract/curve.ts';\nimport {\n PrimeEdwardsPoint,\n twistedEdwards,\n type CurveFn,\n type EdwardsOpts,\n type EdwardsPoint,\n} from './abstract/edwards.ts';\nimport {\n _DST_scalar,\n createHasher,\n expand_message_xmd,\n type H2CHasher,\n type H2CHasherBase,\n type H2CMethod,\n type htfBasicOpts,\n} from './abstract/hash-to-curve.ts';\nimport {\n Field,\n FpInvertBatch,\n FpSqrtEven,\n isNegativeLE,\n mod,\n pow2,\n type IField,\n} from './abstract/modular.ts';\nimport { montgomery, type MontgomeryECDH as XCurveFn } from './abstract/montgomery.ts';\nimport { bytesToNumberLE, ensureBytes, equalBytes, type Hex } from './utils.ts';\n\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n\n// P = 2n**255n-19n\nconst ed25519_CURVE_p = BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed'\n);\n\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE: EdwardsOpts = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_p;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// √(-1) aka √(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ed25519_CURVE_p;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\nconst Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();\nconst Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();\n\nconst ed25519Defaults = /* @__PURE__ */ (() => ({\n ...ed25519_CURVE,\n Fp,\n hash: sha512,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/√v\n uvRatio,\n}))();\n\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * import { ed25519 } from '@noble/curves/ed25519';\n * const { secretKey, publicKey } = ed25519.keygen();\n * const msg = new TextEncoder().encode('hello');\n * const sig = ed25519.sign(msg, priv);\n * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215\n * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5\n */\nexport const ed25519: CurveFn = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\n/** Context of ed25519. Uses context for domain separation. */\nexport const ed25519ctx: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n }))();\n\n/** Prehashed version of ed25519. Accepts already-hashed messages in sign() and verify(). */\nexport const ed25519ph: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards(\n Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n })\n ))();\n\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * import { x25519 } from '@noble/curves/ed25519';\n * const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';\n * const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';\n * x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases\n * x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);\n * x25519.getPublicKey(x25519.utils.randomSecretKey());\n */\nexport const x25519: XCurveFn = /* @__PURE__ */ (() => {\n const P = Fp.ORDER;\n return montgomery({\n P,\n type: 'x25519',\n powPminus2: (x: bigint): bigint => {\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n });\n})();\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J);// 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd!(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n\n/** Hashing to ed25519 points / field. RFC 9380 methods. */\nexport const ed25519_hasher: H2CHasher<bigint> = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.Point,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\n\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/√(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = EdwardsPoint;\n\n/**\n * Computes Elligator map for Ristretto255.\n * Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B) and on\n * the [website](https://ristretto.group/formulas/elligator.html).\n */\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n const { d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\nfunction ristretto255_map(bytes: Uint8Array): _RistrettoPoint {\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n}\n\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint<_RistrettoPoint> {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();\n // prettier-ignore\n static ZERO: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();\n // prettier-ignore\n static Fp: IField<bigint> =\n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn: IField<bigint> =\n /* @__PURE__ */ (() => Fn)();\n\n constructor(ep: ExtendedPoint) {\n super(ep);\n }\n\n static fromAffine(ap: AffinePoint<bigint>): _RistrettoPoint {\n return new _RistrettoPoint(ed25519.Point.fromAffine(ap));\n }\n\n protected assertSame(other: _RistrettoPoint): void {\n if (!(other instanceof _RistrettoPoint)) throw new Error('RistrettoPoint expected');\n }\n\n protected init(ep: EdwardsPoint): _RistrettoPoint {\n return new _RistrettoPoint(ep);\n }\n\n /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\n static hashToCurve(hex: Hex): _RistrettoPoint {\n return ristretto255_map(ensureBytes('ristrettoHash', hex, 64));\n }\n\n static fromBytes(bytes: Uint8Array): _RistrettoPoint {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const s = bytes255ToNumberLE(bytes);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519.Point(x, y, _1n, t));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: Hex): _RistrettoPoint {\n return _RistrettoPoint.fromBytes(ensureBytes('ristrettoHex', hex, 32));\n }\n\n static msm(points: _RistrettoPoint[], scalars: bigint[]): _RistrettoPoint {\n return pippenger(_RistrettoPoint, ed25519.Point.Fn, points, scalars);\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes(): Uint8Array {\n let { X, Y, Z, T } = this.ep;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1\n const u2 = mod(X * Y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * T); // 6\n let D: bigint; // 7\n if (isNegativeLE(T * zInv, P)) {\n let _x = mod(Y * SQRT_M1);\n let _y = mod(X * SQRT_M1);\n X = _x;\n Y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(X * zInv, P)) Y = mod(-Y); // 9\n let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return Fp.toBytes(s); // 11\n }\n\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other: _RistrettoPoint): boolean {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n const mod = (n: bigint) => Fp.create(n);\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n is0(): boolean {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\n\nexport const ristretto255: {\n Point: typeof _RistrettoPoint;\n} = { Point: _RistrettoPoint };\n\n/** Hashing to ristretto255 points / field. RFC 9380 methods. */\nexport const ristretto255_hasher: H2CHasherBase<bigint> = {\n hashToCurve(msg: Uint8Array, options?: htfBasicOpts): _RistrettoPoint {\n const DST = options?.DST || 'ristretto255_XMD:SHA-512_R255MAP_RO_';\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n return ristretto255_map(xmd);\n },\n hashToScalar(msg: Uint8Array, options: htfBasicOpts = { DST: _DST_scalar }) {\n const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n};\n\n// export const ristretto255_oprf: OPRF = createORPF({\n// name: 'ristretto255-SHA512',\n// Point: RistrettoPoint,\n// hash: sha512,\n// hashToGroup: ristretto255_hasher.hashToCurve,\n// hashToScalar: ristretto255_hasher.hashToScalar,\n// });\n\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * ⟨T⟩ = { O, T, 2T, 3T, 4T, 5T, 6T, 7T }\n */\nexport const ED25519_TORSION_SUBGROUP: string[] = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\n/** @deprecated use `ed25519.utils.toMontgomery` */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n return ed25519.utils.toMontgomery(ensureBytes('pub', edwardsPub));\n}\n/** @deprecated use `ed25519.utils.toMontgomery` */\nexport const edwardsToMontgomery: typeof edwardsToMontgomeryPub = edwardsToMontgomeryPub;\n\n/** @deprecated use `ed25519.utils.toMontgomerySecret` */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n return ed25519.utils.toMontgomerySecret(ensureBytes('pub', edwardsPriv));\n}\n\n/** @deprecated use `ristretto255.Point` */\nexport const RistrettoPoint: typeof _RistrettoPoint = _RistrettoPoint;\n/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */\nexport const hashToCurve: H2CMethod<bigint> = /* @__PURE__ */ (() => ed25519_hasher.hashToCurve)();\n/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */\nexport const encodeToCurve: H2CMethod<bigint> = /* @__PURE__ */ (() =>\n ed25519_hasher.encodeToCurve)();\ntype RistHasher = (msg: Uint8Array, options: htfBasicOpts) => _RistrettoPoint;\n/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\nexport const hashToRistretto255: RistHasher = /* @__PURE__ */ (() =>\n ristretto255_hasher.hashToCurve as RistHasher)();\n/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\nexport const hash_to_ristretto255: RistHasher = /* @__PURE__ */ (() =>\n ristretto255_hasher.hashToCurve as RistHasher)();\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n isBytes as isBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n abytes,\n anumber,\n bytesToHex,\n bytesToUtf8,\n concatBytes,\n hexToBytes,\n isBytes,\n randomBytes,\n utf8ToBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function abool(title: string, value: boolean): void {\n if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);\n}\n\n// tmp name until v2\nexport function _abool2(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\"`;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n// tmp name until v2\n/** Asserts something is Uint8Array. */\nexport function _abytes2(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes_(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n abytes_(bytes);\n return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes_(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'secret key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes_(hex);\n } catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n } else if (isBytes_(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(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/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as utf8ToBytes for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n });\n}\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\n// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\n// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n const u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\n const u8of = (byte: number) => Uint8Array.of(byte); // another shortcut\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n(0)) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes_(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\n\nexport function validateObject<T extends Record<string, any>>(\n object: T,\n validators: ValMap<T>,\n optValidators: ValMap<T> = {}\n): T {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function') throw new Error('invalid validator function');\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n 'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n\nexport function isHash(val: CHash): boolean {\n return typeof val === 'function' && Number.isSafeInteger(val.outputLen);\n}\nexport function _validateObject(\n object: Record<string, any>,\n fields: Record<string, string>,\n optFields: Record<string, string> = {}\n): void {\n if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));\n Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));\n}\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized<T extends object, R, O extends any[]>(\n fn: (arg: T, ...args: O) => R\n): (arg: T, ...args: O) => R {\n const map = new WeakMap<T, R>();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n _validateObject,\n anumber,\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n} from '../utils.ts';\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);\n// prettier-ignore\nconst _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\n}\n\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\nfunction assertIsSquare<T>(Fp: IField<T>, root: T, n: T): void {\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\n\nfunction sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n assertIsSquare(Fp, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return <T>(Fp: IField<T>, n: T) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3);// 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Field is not always over prime: for example, Fp2 has ORDER(q)=p^m. */\nexport interface IField<T> {\n ORDER: bigint;\n isLE: boolean;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n isValidNot0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n allowedLengths?: number[];\n // legendre?(num: T): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField<T>(field: IField<T>): IField<T> {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n _validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow<T>(Fp: IField<T>, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch<T>(Fp: IField<T>, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv<T>(Fp: IField<T>, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n */\nexport function FpLegendre<T>(Fp: IField<T>, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(Fp: IField<T>, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\nexport type NLength = { nByteLength: number; nBitLength: number };\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n sqrt: SqrtFn;\n isLE: boolean;\n BITS: number;\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes)\n}>;\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLenOrOpts?: number | FieldOpts, // TODO: use opts only in v2?\n isLE = false,\n opts: { sqrt?: SqrtFn } = {}\n): Readonly<FpField> {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n let _sqrt: SqrtFn | undefined = undefined;\n let modFromBytes: boolean = false;\n let allowedLengths: undefined | readonly number[] = undefined;\n if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {\n if (opts.sqrt || isLE) throw new Error('cannot specify opts in two arguments');\n const _opts = bitLenOrOpts;\n if (_opts.BITS) _nbitLength = _opts.BITS;\n if (_opts.sqrt) _sqrt = _opts.sqrt;\n if (typeof _opts.isLE === 'boolean') isLE = _opts.isLE;\n if (typeof _opts.modFromBytes === 'boolean') modFromBytes = _opts.modFromBytes;\n allowedLengths = _opts.allowedLengths;\n } else {\n if (typeof bitLenOrOpts === 'number') _nbitLength = bitLenOrOpts;\n if (opts.sqrt) _sqrt = opts.sqrt;\n }\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);\n if (BYTES > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP: ReturnType<typeof FpSqrt>; // cached sqrtP\n const f: Readonly<FpField> = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n allowedLengths: allowedLengths,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n // is valid and invertible\n isValidNot0: (num: bigint) => !f.is0(num) && f.isValid(num),\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt:\n _sqrt ||\n ((n) => {\n if (!sqrtP) sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes, skipValidation = true) => {\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!f.isValid(scalar)) throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n },\n // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(\n 'hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen\n );\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject } from '../utils.ts';\nimport { Field, FpInvertBatch, nLength, validateField, type IField } from './modular.ts';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { Z?: never };\n\n// This was initialy do this way to re-use montgomery ladder in field (add->mul,double->sqr), but\n// that didn't happen and there is probably not much reason to have separate Group like this?\nexport interface Group<T extends Group<T>> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n toAffine?(invertedZ?: any): AffinePoint<any>;\n}\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic curve Points. */\nexport interface CurvePoint<F, P extends CurvePoint<F, P>> extends Group<P> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n Z?: F;\n double(): P;\n negate(): P;\n add(other: P): P;\n subtract(other: P): P;\n equals(other: P): boolean;\n multiply(scalar: bigint): P;\n assertValidity(): void;\n clearCofactor(): P;\n is0(): boolean;\n isTorsionFree(): boolean;\n isSmallOrder(): boolean;\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * @param isLazy calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /** Converts point to 2D xy affine coordinates */\n toAffine(invertedZ?: F): AffinePoint<F>;\n toBytes(): Uint8Array;\n toHex(): string;\n}\n\n/** Base interface for all elliptic curve Point constructors. */\nexport interface CurvePointCons<P extends CurvePoint<any, P>> {\n [Symbol.hasInstance]: (item: unknown) => boolean;\n BASE: P;\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField<P_F<P>>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField<bigint>;\n /** Creates point from x, y. Does NOT validate if the point is valid. Use `.assertValidity()`. */\n fromAffine(p: AffinePoint<P_F<P>>): P;\n fromBytes(bytes: Uint8Array): P;\n fromHex(hex: Uint8Array | string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint<PC>': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint<PC>': it won't be accesible for arguments/return types\n// * `CurvePointCons<P extends CurvePoint<any, P>>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons<any>`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint<any, P>.\n// this means we need to do stuff like\n// `function test<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(`\n// if we want type safety around P, otherwise PC_P<PC> will be any\n\n/** Returns Fp type from Point (P_F<P> == P.F) */\nexport type P_F<P extends CurvePoint<any, P>> = P extends CurvePoint<infer F, P> ? F : never;\n/** Returns Fp type from PointCons (PC_F<PC> == PC.P.F) */\nexport type PC_F<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['Fp']['ZERO'];\n/** Returns Point type from PointCons (PC_P<PC> == PC.P) */\nexport type PC_P<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons<CurvePoint<any, any>>`, will return `any` after 1 operation\n// * `CurvePointCons<any>: WeierstrassPointCons<bigint> extends CurvePointCons<any> = false`\n// * `P extends CurvePoint, PC extends CurvePointCons<P>`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons<F, P>`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\nexport type PC_ANY = CurvePointCons<\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any, any>\n >>>>>>>>>\n>;\n\nexport interface CurveLengths {\n secretKey?: number;\n publicKey?: number;\n publicKeyUncompressed?: number;\n publicKeyHasPrefix?: boolean;\n signature?: number;\n seed?: number;\n}\nexport type GroupConstructor<T> = {\n BASE: T;\n ZERO: T;\n};\n/** @deprecated */\nexport type ExtendedGroupConstructor<T> = GroupConstructor<T> & {\n Fp: IField<any>;\n Fn: IField<bigint>;\n fromAffine(ap: AffinePoint<any>): T;\n};\nexport type Mapper<T> = (i: T[]) => T[];\n\nexport function negateCt<T extends { negate: () => T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\nexport function normalizeZ<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap<any, any[]>();\nconst pointWindowSizes = new WeakMap<any, number>();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF<PC extends PC_ANY> {\n private readonly BASE: PC_P<PC>;\n private readonly ZERO: PC_P<PC>;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P<PC>, n: bigint, p: PC_P<PC> = this.ZERO): PC_P<PC> {\n let d: PC_P<PC> = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P<PC>, W: number): PC_P<PC>[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P<PC>[] = [];\n let p: PC_P<PC> = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P<PC>[], n: bigint): { p: PC_P<PC>; f: PC_P<PC> } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n }\n\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P<PC>[],\n n: bigint,\n acc: PC_P<PC> = this.ZERO\n ): PC_P<PC> {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P<PC>, transform?: Mapper<PC_P<PC>>): PC_P<PC>[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P<PC>[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P<PC>,\n scalar: bigint,\n transform?: Mapper<PC_P<PC>>\n ): { p: PC_P<PC>; f: PC_P<PC> } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P<PC>, scalar: bigint, transform?: Mapper<PC_P<PC>>, prev?: PC_P<PC>): PC_P<PC> {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P: PC_P<PC>, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P<PC>): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka secret keys / bigints)\n */\nexport function pippenger<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n fieldN: IField<bigint>,\n points: P[],\n scalars: bigint[]\n): P {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as P;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n fieldN: IField<bigint>,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p: P) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): P => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\n// TODO: remove\n/**\n * Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n * Though generator can be different (Fp2 / Fp6 for BLS).\n */\nexport type BasicCurve<T> = {\n Fp: IField<T>; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\n// TODO: remove\n/** @deprecated */\nexport function validateBasic<FP, T>(\n curve: BasicCurve<FP> & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve<FP> &\n T & {\n p: bigint;\n }\n> {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n\nexport type ValidCurveParams<T> = {\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b?: T;\n d?: T;\n Gx: T;\n Gy: T;\n};\n\nfunction createField<T>(order: bigint, field?: IField<T>, isLE?: boolean): IField<T> {\n if (field) {\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n } else {\n return Field(order, { isLE }) as unknown as IField<T>;\n }\n}\nexport type FpFn<T> = { Fp: IField<T>; Fn: IField<bigint> };\n\n/** Validates CURVE opts and creates fields */\nexport function _createCurveFields<T>(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams<T>,\n curveOpts: Partial<FpFn<T>> = {},\n FpFnLE?: boolean\n): FpFn<T> & { CURVE: ValidCurveParams<T> } {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n","/**\n * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n _validateObject,\n _abool2 as abool,\n _abytes2 as abytes,\n aInRange,\n bytesToHex,\n bytesToNumberLE,\n concatBytes,\n copyBytes,\n ensureBytes,\n isBytes,\n memoized,\n notImplemented,\n randomBytes as randomBytesWeb,\n type FHash,\n type Hex,\n} from '../utils.ts';\nimport {\n _createCurveFields,\n normalizeZ,\n pippenger,\n wNAF,\n type AffinePoint,\n type BasicCurve,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport { Field, type IField, type NLength } from './modular.ts';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\nexport type UVRatio = (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n\n/** Instance of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPoint extends CurvePoint<bigint, EdwardsPoint> {\n /** extended X coordinate. Different from affine x. */\n readonly X: bigint;\n /** extended Y coordinate. Different from affine y. */\n readonly Y: bigint;\n /** extended Z coordinate */\n readonly Z: bigint;\n /** extended T coordinate */\n readonly T: bigint;\n\n /** @deprecated use `toBytes` */\n toRawBytes(): Uint8Array;\n /** @deprecated use `p.precompute(windowSize)` */\n _setWindowSize(windowSize: number): void;\n /** @deprecated use .X */\n readonly ex: bigint;\n /** @deprecated use .Y */\n readonly ey: bigint;\n /** @deprecated use .Z */\n readonly ez: bigint;\n /** @deprecated use .T */\n readonly et: bigint;\n}\n/** Static methods of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPointCons extends CurvePointCons<EdwardsPoint> {\n new (X: bigint, Y: bigint, Z: bigint, T: bigint): EdwardsPoint;\n CURVE(): EdwardsOpts;\n fromBytes(bytes: Uint8Array, zip215?: boolean): EdwardsPoint;\n fromHex(hex: Hex, zip215?: boolean): EdwardsPoint;\n /** @deprecated use `import { pippenger } from '@noble/curves/abstract/curve.js';` */\n msm(points: EdwardsPoint[], scalars: bigint[]): EdwardsPoint;\n}\n/** @deprecated use EdwardsPoint */\nexport type ExtPointType = EdwardsPoint;\n/** @deprecated use EdwardsPointCons */\nexport type ExtPointConstructor = EdwardsPointCons;\n\n/**\n * Twisted Edwards curve options.\n *\n * * a: formula param\n * * d: formula param\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor. h*n is group order; n is subgroup order\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type EdwardsOpts = Readonly<{\n p: bigint;\n n: bigint;\n h: bigint;\n a: bigint;\n d: bigint;\n Gx: bigint;\n Gy: bigint;\n}>;\n\n/**\n * Extra curve options for Twisted Edwards.\n *\n * * Fp: redefined Field over curve.p\n * * Fn: redefined Field over curve.n\n * * uvRatio: helper function for decompression, calculating √(u/v)\n */\nexport type EdwardsExtraOpts = Partial<{\n Fp: IField<bigint>;\n Fn: IField<bigint>;\n FpFnLE: boolean;\n uvRatio: (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) options.\n *\n * * hash: hash function used to hash secret keys and messages\n * * adjustScalarBytes: clears bits to get valid field element\n * * domain: Used for hashing\n * * mapToCurve: for hash-to-curve standard\n * * prehash: RFC 8032 pre-hashing of messages to sign() / verify()\n * * randomBytes: function generating random bytes, used for randomSecretKey\n */\nexport type EdDSAOpts = Partial<{\n adjustScalarBytes: (bytes: Uint8Array) => Uint8Array;\n domain: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;\n mapToCurve: (scalar: bigint[]) => AffinePoint<bigint>;\n prehash: FHash;\n randomBytes: (bytesLength?: number) => Uint8Array;\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) interface.\n *\n * Allows to create and verify signatures, create public and secret keys.\n */\nexport interface EdDSA {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Hex) => Uint8Array;\n sign: (message: Hex, secretKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n Point: EdwardsPointCons;\n utils: {\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n isValidSecretKey: (secretKey: Uint8Array) => boolean;\n isValidPublicKey: (publicKey: Uint8Array, zip215?: boolean) => boolean;\n\n /**\n * Converts ed public key to x public key.\n *\n * There is NO `fromMontgomery`:\n * - There are 2 valid ed25519 points for every x25519, with flipped coordinate\n * - Sometimes there are 0 valid ed25519 points, because x25519 *additionally*\n * accepts inputs on the quadratic twist, which can't be moved to ed25519\n *\n * @example\n * ```js\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomSecretKey());\n * const aPriv = x25519.utils.randomSecretKey();\n * x25519.getSharedSecret(aPriv, ed25519.utils.toMontgomery(someonesPub))\n * ```\n */\n toMontgomery: (publicKey: Uint8Array) => Uint8Array;\n /**\n * Converts ed secret key to x secret key.\n * @example\n * ```js\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomSecretKey());\n * const aPriv = ed25519.utils.randomSecretKey();\n * x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(aPriv), someonesPub)\n * ```\n */\n toMontgomerySecret: (privateKey: Uint8Array) => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: EdwardsPoint;\n pointBytes: Uint8Array;\n };\n\n /** @deprecated use `randomSecretKey` */\n randomPrivateKey: (seed?: Uint8Array) => Uint8Array;\n /** @deprecated use `point.precompute()` */\n precompute: (windowSize?: number, point?: EdwardsPoint) => EdwardsPoint;\n };\n lengths: CurveLengths;\n}\n\nfunction isEdValidXY(Fp: IField<bigint>, CURVE: EdwardsOpts, x: bigint, y: bigint): boolean {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\n\nexport function edwards(params: EdwardsOpts, extraOpts: EdwardsExtraOpts = {}): EdwardsPointCons {\n const validated = _createCurveFields('edwards', params, extraOpts, extraOpts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as EdwardsOpts;\n const { h: cofactor } = CURVE;\n _validateObject(extraOpts, {}, { uvRatio: 'function' });\n\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);\n const modP = (n: bigint) => Fp.create(n); // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n extraOpts.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n\n // Validate whether the passed curve params are valid.\n // equation ax² + y² = 1 + dx²y² should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title: string, n: bigint, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n\n function aextpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p: Point, iz?: bigint): AffinePoint<bigint> => {\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(Z) as bigint); // 8 was chosen arbitrarily\n const x = modP(X * iz);\n const y = modP(Y * iz);\n const zz = Fp.mul(Z, iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x, y };\n });\n const assertValidMemo = memoized((p: Point) => {\n const { a, d } = CURVE;\n if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { X, Y, Z, T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n return true;\n });\n\n // Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements EdwardsPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n // zero / infinity / identity point\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: bigint;\n readonly Y: bigint;\n readonly Z: bigint;\n readonly T: bigint;\n\n constructor(X: bigint, Y: bigint, Z: bigint, T: bigint) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n\n static CURVE(): EdwardsOpts {\n return CURVE;\n }\n\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes: Uint8Array, zip215 = false): Point {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\n\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid) throw new Error('bad point: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromHex(bytes: Uint8Array, zip215 = false): Point {\n return Point.fromBytes(ensureBytes('point', bytes), zip215);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n precompute(windowSize: number = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_2n); // random number\n return this;\n }\n\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n aextpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n aextpoint(other);\n const { a, d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n // 1 <= scalar < L\n if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n return normalizeZ(Point, [p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n multiplyUnsafe(scalar: bigint, acc = Point.ZERO): Point {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar)) throw new Error('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n) return Point.ZERO;\n if (this.is0() || scalar === _1n) return this;\n return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafe(this, CURVE.n).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return toAffineMemo(this, invertedZ);\n }\n\n clearCofactor(): Point {\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n toBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n\n // TODO: remove\n get ex(): bigint {\n return this.X;\n }\n get ey(): bigint {\n return this.Y;\n }\n get ez(): bigint {\n return this.Z;\n }\n get et(): bigint {\n return this.T;\n }\n static normalizeZ(points: Point[]): Point[] {\n return normalizeZ(Point, points);\n }\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n _setWindowSize(windowSize: number) {\n this.precompute(windowSize);\n }\n toRawBytes(): Uint8Array {\n return this.toBytes();\n }\n }\n const wnaf = new wNAF(Point, Fn.BITS);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points.\n */\nexport abstract class PrimeEdwardsPoint<T extends PrimeEdwardsPoint<T>>\n implements CurvePoint<bigint, T>\n{\n static BASE: PrimeEdwardsPoint<any>;\n static ZERO: PrimeEdwardsPoint<any>;\n static Fp: IField<bigint>;\n static Fn: IField<bigint>;\n\n protected readonly ep: EdwardsPoint;\n\n constructor(ep: EdwardsPoint) {\n this.ep = ep;\n }\n\n // Abstract methods that must be implemented by subclasses\n abstract toBytes(): Uint8Array;\n abstract equals(other: T): boolean;\n\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes: Uint8Array): any {\n notImplemented();\n }\n\n static fromHex(_hex: Hex): any {\n notImplemented();\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n // Common implementations\n clearCofactor(): T {\n // no-op for prime-order groups\n return this as any;\n }\n\n assertValidity(): void {\n this.ep.assertValidity();\n }\n\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return this.ep.toAffine(invertedZ);\n }\n\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n isTorsionFree(): boolean {\n return true;\n }\n\n isSmallOrder(): boolean {\n return false;\n }\n\n add(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n\n subtract(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): T {\n return this.init(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): T {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): T {\n return this.init(this.ep.double());\n }\n\n negate(): T {\n return this.init(this.ep.negate());\n }\n\n precompute(windowSize?: number, isLazy?: boolean): T {\n return this.init(this.ep.precompute(windowSize, isLazy));\n }\n\n // Helper methods\n abstract is0(): boolean;\n protected abstract assertSame(other: T): void;\n protected abstract init(ep: EdwardsPoint): T;\n\n /** @deprecated use `toBytes` */\n toRawBytes(): Uint8Array {\n return this.toBytes();\n }\n}\n\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n */\nexport function eddsa(Point: EdwardsPointCons, cHash: FHash, eddsaOpts: EdDSAOpts = {}): EdDSA {\n if (typeof cHash !== 'function') throw new Error('\"hash\" function param is required');\n _validateObject(\n eddsaOpts,\n {},\n {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n mapToCurve: 'function',\n }\n );\n\n const { prehash } = eddsaOpts;\n const { BASE, Fp, Fn } = Point;\n\n const randomBytes = eddsaOpts.randomBytes || randomBytesWeb;\n const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes: Uint8Array) => bytes);\n const domain =\n eddsaOpts.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key: Hex) {\n const len = lengths.secretKey;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5 */\n function getExtendedPublicKey(secretKey: Hex) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey: Hex): Uint8Array {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = Uint8Array.of(), ...msgs: Uint8Array[]) {\n const msg = concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, secretKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s)) throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n\n // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\n const verifyOpts: { context?: Hex; zip215?: boolean } = { zip215: true };\n\n /**\n * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n * An extended group equation is checked.\n */\n function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = lengths.signature;\n sig = ensureBytes('signature', sig, len);\n msg = ensureBytes('message', msg);\n publicKey = ensureBytes('publicKey', publicKey, lengths.publicKey);\n if (zip215 !== undefined) abool(zip215, 'zip215');\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false; // zip215 allows public keys of small order\n\n const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed = randomBytes(lengths.seed)): Uint8Array {\n return abytes(seed, lengths.seed, 'seed');\n }\n function keygen(seed?: Uint8Array) {\n const secretKey = utils.randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n }\n function isValidSecretKey(key: Uint8Array): boolean {\n return isBytes(key) && key.length === Fn.BYTES;\n }\n function isValidPublicKey(key: Uint8Array, zip215?: boolean): boolean {\n try {\n return !!Point.fromBytes(key, zip215);\n } catch (error) {\n return false;\n }\n }\n\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /**\n * Converts ed public key to x public key. Uses formula:\n * - ed25519:\n * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * - ed448:\n * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n */\n toMontgomery(publicKey: Uint8Array): Uint8Array {\n const { y } = Point.fromBytes(publicKey);\n const size = lengths.publicKey;\n const is25519 = size === 32;\n if (!is25519 && size !== 57) throw new Error('only defined for 25519 and 448');\n const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n return Fp.toBytes(u);\n },\n\n toMontgomerySecret(secretKey: Uint8Array): Uint8Array {\n const size = lengths.secretKey;\n abytes(secretKey, size);\n const hashed = cHash(secretKey.subarray(0, size));\n return adjustScalarBytes(hashed).subarray(0, size);\n },\n\n /** @deprecated */\n randomPrivateKey: randomSecretKey,\n /** @deprecated */\n precompute(windowSize = 8, point: EdwardsPoint = Point.BASE): EdwardsPoint {\n return point.precompute(windowSize, false);\n },\n };\n\n return Object.freeze({\n keygen,\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n });\n}\n\n// TODO: remove everything below\nexport type CurveType = BasicCurve<bigint> & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n /** @deprecated the property will be removed in next release */\n hash: FHash; // Hashing\n randomBytes?: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: UVRatio; // Ratio √(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\nexport type CurveTypeWithLength = Readonly<CurveType & Partial<NLength>>;\nexport type CurveFn = {\n /** @deprecated the property will be removed in next release */\n CURVE: CurveType;\n keygen: EdDSA['keygen'];\n getPublicKey: EdDSA['getPublicKey'];\n sign: EdDSA['sign'];\n verify: EdDSA['verify'];\n Point: EdwardsPointCons;\n /** @deprecated use `Point` */\n ExtendedPoint: EdwardsPointCons;\n utils: EdDSA['utils'];\n lengths: CurveLengths;\n};\nexport type EdComposed = {\n CURVE: EdwardsOpts;\n curveOpts: EdwardsExtraOpts;\n hash: FHash;\n eddsaOpts: EdDSAOpts;\n};\nfunction _eddsa_legacy_opts_to_new(c: CurveTypeWithLength): EdComposed {\n const CURVE: EdwardsOpts = {\n a: c.a,\n d: c.d,\n p: c.Fp.ORDER,\n n: c.n,\n h: c.h,\n Gx: c.Gx,\n Gy: c.Gy,\n };\n const Fp = c.Fp;\n const Fn = Field(CURVE.n, c.nBitLength, true);\n const curveOpts: EdwardsExtraOpts = { Fp, Fn, uvRatio: c.uvRatio };\n const eddsaOpts: EdDSAOpts = {\n randomBytes: c.randomBytes,\n adjustScalarBytes: c.adjustScalarBytes,\n domain: c.domain,\n prehash: c.prehash,\n mapToCurve: c.mapToCurve,\n };\n return { CURVE, curveOpts, hash: c.hash, eddsaOpts };\n}\nfunction _eddsa_new_output_to_legacy(c: CurveTypeWithLength, eddsa: EdDSA): CurveFn {\n const Point = eddsa.Point;\n const legacy = Object.assign({}, eddsa, {\n ExtendedPoint: Point,\n CURVE: c,\n nBitLength: Point.Fn.BITS,\n nByteLength: Point.Fn.BYTES,\n });\n return legacy;\n}\n// TODO: remove. Use eddsa\nexport function twistedEdwards(c: CurveTypeWithLength): CurveFn {\n const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);\n const Point = edwards(CURVE, curveOpts);\n const EDDSA = eddsa(Point, hash, eddsaOpts);\n return _eddsa_new_output_to_legacy(c, EDDSA);\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) { return true }\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') { return o }\n if (o instanceof ArrayBuffer) { return new Uint8Array(o) }\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable<number>} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder<Base extends string, Prefix extends string> implements MultibaseEncoder<Prefix>, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase<Prefix> {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder<Base extends string, Prefix extends string> implements MultibaseDecoder<Prefix>, UnibaseDecoder<Prefix>, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n const prefixCodePoint = prefix.codePointAt(0)\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefixCodePoint\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or<OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n}\n\ntype Decoders<Prefix extends string> = Record<Prefix, UnibaseDecoder<Prefix>>\n\nclass ComposedDecoder<Prefix extends string> implements MultibaseDecoder<Prefix>, CombobaseDecoder<Prefix> {\n readonly decoders: Decoders<Prefix>\n\n constructor (decoders: Decoders<Prefix>) {\n this.decoders = decoders\n }\n\n or <OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or <L extends string, R extends string> (left: UnibaseDecoder<L> | CombobaseDecoder<L>, right: UnibaseDecoder<R> | CombobaseDecoder<R>): ComposedDecoder<L | R> {\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder<L>).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder<R>).prefix]: right })\n } as Decoders<L | R>)\n}\n\nexport class Codec<Base extends string, Prefix extends string> implements MultibaseCodec<Prefix>, MultibaseEncoder<Prefix>, MultibaseDecoder<Prefix>, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder<Base, Prefix>\n readonly decoder: Decoder<Base, Prefix>\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from <Base extends string, Prefix extends string> ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec<Base, Prefix> {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX <Base extends string, Prefix extends string> ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec<Base, Prefix> {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabetIdx: Record<string, number>, bitsPerChar: number, name: string): Uint8Array {\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = alphabetIdx[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\nfunction createAlphabetIdx (alphabet: string): Record<string, number> {\n // Build the character lookup table:\n const alphabetIdx: Record<string, number> = {}\n for (let i = 0; i < alphabet.length; ++i) {\n alphabetIdx[alphabet[i]] = i\n }\n return alphabetIdx\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 <Base extends string, Prefix extends string> ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec<Base, Prefix> {\n const alphabetIdx = createAlphabetIdx(alphabet)\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabetIdx, bitsPerChar, name)\n }\n })\n}\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create <Code extends number> (code: Code, digest: Uint8Array): Digest<Code, number> {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest<Code extends number, Size extends number> implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n\n/**\n * Used to check that the passed multihash has the passed code\n */\nexport function hasCode <T extends number> (digest: MultihashDigest, code: T): digest is MultihashDigest<T> {\n return digest.code === code\n}\n","import { base32 } from './bases/base32.js'\nimport { base36 } from './bases/base36.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format <T extends API.Link<unknown, number, number, API.Version>, Prefix extends string> (link: T, base?: API.MultibaseEncoder<Prefix>): API.ToString<T, Prefix> {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder<Prefix>\n )\n }\n}\n\nexport function toJSON <Link extends API.UnknownLink> (link: Link): API.LinkJSON<Link> {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON <Link extends API.UnknownLink> (json: API.LinkJSON<Link>): CID<unknown, number, number, API.Version> {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap<API.UnknownLink, Map<string, string>>()\n\nfunction baseCache (cid: API.UnknownLink): Map<string, string> {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID<Data = unknown, Format extends number = number, Alg extends number = number, Version extends API.Version = API.Version> implements API.Link<Data, Format, Alg, Version> {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest<Alg>\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest<Alg>, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID<Data, API.DAG_PB, API.SHA_256, 0> {\n switch (this.version) {\n case 0: {\n return this as CID<Data, API.DAG_PB, API.SHA_256, 0>\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest<API.SHA_256>\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID<Data, Format, Alg, 1> {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID<Data, Format, Alg, 1>\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID<Data, Format, Alg, Version> {\n return CID.equals(this, other)\n }\n\n static equals <Data, Format extends number, Alg extends number, Version extends API.Version>(self: API.Link<Data, Format, Alg, Version>, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder<string>): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON<this> {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID <Data, Format extends number, Alg extends number, Version extends API.Version, U>(input: API.Link<Data, Format, Alg, Version> | U): CID<Data, Format, Alg, Version> | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest<Alg>,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest<Alg>\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create <Data, Format extends number, Alg extends number, Version extends API.Version>(version: Version, code: Format, digest: API.MultihashDigest<Alg>): CID<Data, Format, Alg, Version> {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 <T = unknown>(digest: API.MultihashDigest<typeof SHA_256_CODE>): CID<T, typeof DAG_PB_CODE, typeof SHA_256_CODE, 0> {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 <Data, Code extends number, Alg extends number>(code: Code, digest: API.MultihashDigest<Alg>): CID<Data, Code, Alg, 1> {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode <Data, Code extends number, Alg extends number, Version extends API.Version>(bytes: API.ByteView<API.Link<Data, Code, Alg, Version>>): CID<Data, Code, Alg, Version> {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst <T, C extends number, A extends number, V extends API.Version>(bytes: API.ByteView<API.Link<T, C, A, V>>): [CID<T, C, A, V>, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest<API.SHA_256>)\n : CID.createV1(specs.codec, digest)\n return [cid as CID<T, C, A, V>, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes <T, C extends number, A extends number, V extends API.Version>(initialBytes: API.ByteView<API.Link<T, C, A, V>>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version>(source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): CID<Data, Code, Alg, Version> {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version> (source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): [Prefix, API.ByteView<API.Link<Data, Code, Alg, Version>>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n case base36.prefix: {\n const decoder = base ?? base36\n return [base36.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 <Prefix extends string> (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<Prefix>): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import { sha256 } from \"@noble/hashes/sha256\";\nimport { blake3 } from \"@noble/hashes/blake3\";\nimport { ed25519 } from \"@noble/curves/ed25519\";\nimport { CID } from \"multiformats/cid\";\nimport { base58btc } from \"multiformats/bases/base58\";\nimport { create as createDigest } from \"multiformats/hashes/digest\";\nimport { z } from \"zod\";\nimport { jcsCanonicalize } from \"./jcs\";\nimport { httpResponseError } from \"../http-error\";\n\nexport const POLICY_V1_SCHEMA = \"xyz.tinycloud.policy/policy/v1\" as const;\nexport const POLICY_CAPABILITY_V1_SCHEMA =\n \"xyz.tinycloud.policy/capability/v1\" as const;\nexport const POLICY_ENFORCEMENT_DELEGATION_V2_SCHEMA =\n \"xyz.tinycloud.policy/enforcement-delegation/v2\" as const;\nexport const ATTESTED_ENFORCER_BINDING_V2_SCHEMA =\n \"xyz.tinycloud.policy/attested-enforcer/v2\" as const;\nexport const ROOT_STATUS_CHECKPOINT_V1_SCHEMA =\n \"xyz.tinycloud.policy/root-status/v1\" as const;\nexport const ROOT_REVOCATION_V1_SCHEMA =\n \"xyz.tinycloud.policy/root-revocation/v1\" as const;\nexport const POLICY_SESSION_UCAN_V1_PROFILE = \"policy-session-ucan/v1\" as const;\n\nexport const POLICY_V1_DOMAIN = \"xyz.tinycloud.policy/policy/v1\\0\";\nexport const POLICY_CAPABILITY_V1_DOMAIN =\n \"xyz.tinycloud.policy/PolicyCapability/v1\\0\";\nexport const CONTENT_SOURCE_V1_DOMAIN =\n \"xyz.tinycloud.policy/ContentSource/v1\\0\";\nexport const NATIVE_PROJECTION_V1_DOMAIN =\n \"xyz.tinycloud.policy/NativeProjection/v1\\0\";\nexport const ROOT_STATUS_V1_DOMAIN =\n \"xyz.tinycloud.policy/RootStatusCheckpoint/v1\\0\";\nexport const ROOT_STATUS_RENEWAL_V1_DOMAIN =\n \"xyz.tinycloud.policy/RootStatusRenewal/v1\\0\";\nexport const ROOT_REVOCATION_V1_DOMAIN =\n \"xyz.tinycloud.policy/RootRevocation/v1\\0\";\n\nexport const LAST_V2_CREATE_AT = \"2026-09-30T00:00:00Z\" as const;\nexport const MAX_LEGACY_ENVELOPE_EXPIRES_AT = \"2026-12-29T00:00:00Z\" as const;\nexport const LAST_V2_READ_AT = \"2027-01-05T00:00:00Z\" as const;\n\nexport type UnifiedResourceSelector = \"exact\" | \"prefix\";\n\nexport interface UnifiedKvCapability {\n readonly kind: \"kv\";\n readonly resource: string;\n readonly selector: UnifiedResourceSelector;\n readonly actions: readonly (\n | \"tinycloud.kv/get\"\n | \"tinycloud.kv/list\"\n | \"tinycloud.kv/metadata\"\n | \"tinycloud.kv/put\"\n )[];\n}\n\nexport interface UnifiedEncryptionCapability {\n readonly kind: \"encryption\";\n readonly resource: string;\n readonly action: \"tinycloud.encryption/decrypt\";\n}\n\nexport type UnifiedPolicyCapability =\n | UnifiedKvCapability\n | UnifiedEncryptionCapability;\n\nexport interface UnifiedNativeCapability {\n readonly service: \"tinycloud.kv\" | \"tinycloud.encryption\";\n readonly space: string;\n readonly path: string;\n readonly actions: readonly string[];\n readonly caveat?: Readonly<Record<string, string>>;\n}\n\nexport interface UnifiedContentSource {\n readonly shareId: string;\n readonly kvResource: string;\n readonly selector: UnifiedResourceSelector;\n readonly encryptionNetwork: string;\n readonly encryptedSymmetricKeyDigestHex: string;\n readonly keyVersion: number;\n readonly mode: \"mutable\" | \"immutable\";\n readonly initialCiphertextDigestHex?: string;\n}\n\nexport interface UnifiedPolicyV1 {\n readonly schema: typeof POLICY_V1_SCHEMA;\n readonly policyId: string;\n readonly ownerDid: string;\n readonly createdAt: string;\n readonly expiresAt?: string;\n readonly contentSource: UnifiedContentSource;\n readonly capabilityCeiling: readonly UnifiedPolicyCapability[];\n readonly signature: {\n readonly suite: string;\n readonly signerDid: string;\n readonly value: string;\n };\n}\n\nexport interface PolicyRootV3 {\n readonly cid: string;\n readonly authorization: string;\n}\n\nexport interface RegisterPolicyV3Input {\n readonly nodeOrigin: string;\n readonly policyCid: string;\n readonly policy: Readonly<Record<string, unknown>>;\n readonly policyRoot: PolicyRootV3;\n readonly enforcementRoot: PolicyRootV3;\n readonly contentSourceDigestHex: string;\n readonly nativeProjectionHashHex: string;\n readonly rootExpiresAt: string;\n readonly enforcerDid: string;\n readonly expectedNodeAudience: string;\n readonly fetch?: typeof fetch;\n readonly signal?: AbortSignal;\n}\n\nexport interface AttestedEnforcerBindingV2 {\n readonly schema: \"xyz.tinycloud.policy/attested-enforcer/v2\";\n readonly enforcerDid: string;\n readonly nodeAudience: string;\n readonly attestationBindingDigestHex: string;\n readonly issuedAt: string;\n readonly expiresAt: string;\n readonly signature: {\n readonly suite: \"Ed25519\";\n readonly signerDid: string;\n readonly value: string;\n };\n}\n\nexport interface RegisterPolicyV3Receipt {\n readonly policyCid: string;\n readonly policyRootCid: string;\n readonly enforcementRootCid: string;\n readonly attestedEnforcerBinding: AttestedEnforcerBindingV2;\n}\n\nexport type PolicySessionUcanFactV1 = Readonly<Record<string, unknown>> & {\n /** Present only on accountless PolicyCredentialPresentation/v4 admissions. */\n readonly credentialIdAuditDigestHex?: string;\n /** Present only on accountless PolicyCredentialPresentation/v4 admissions. */\n readonly presentationJtiAuditDigestHex?: string;\n};\n\nexport interface PolicySessionUcanV1 {\n readonly authorization: string;\n readonly cid: string;\n readonly iss: string;\n readonly aud: string;\n readonly prf: readonly [string, string];\n readonly att: Readonly<Record<string, Readonly<Record<string, readonly unknown[]>>>>;\n readonly nbf: number;\n readonly exp: number;\n readonly nnc: string;\n readonly fact: PolicySessionUcanFactV1;\n}\n\nexport interface PolicyChallengeV3 {\n readonly challengeId: string;\n readonly nonce: string;\n readonly policyCid: string;\n readonly recipientDid: string;\n readonly expiresAt?: string;\n readonly nodeAudience?: string;\n readonly [key: string]: unknown;\n}\n\nexport async function requestPolicyChallengeV3(input: {\n readonly nodeOrigin: string;\n /**\n * Policy control routes are part of the recipient's TinyCloud Node. This is\n * deliberately a path, not a second origin: applications must not send a\n * credential presentation to a separately discovered policy service.\n */\n readonly policyRuntimePath?: string;\n readonly policyCid: string;\n readonly recipientDid: string;\n readonly requestedCapabilities: readonly UnifiedPolicyCapability[];\n readonly fetch?: typeof fetch;\n readonly signal?: AbortSignal;\n}): Promise<PolicyChallengeV3> {\n const fetchFn = input.fetch ?? globalThis.fetch.bind(globalThis);\n const policyRuntimePath = policyRuntimeBasePath(input.policyRuntimePath);\n const response = await fetchFn(new URL(`${policyRuntimePath}/challenges`, input.nodeOrigin), {\n method: \"POST\",\n redirect: \"error\",\n signal: input.signal,\n headers: { accept: \"application/json\", \"content-type\": \"application/json\" },\n body: JSON.stringify({ policyCid: input.policyCid, recipientDid: input.recipientDid, requestedCapabilities: input.requestedCapabilities.map(normalizeUnifiedPolicyCapability) }),\n });\n if (!response.ok) throw await httpResponseError(response, \"policy challenge rejected\");\n const value = object(await response.json(), \"policy challenge\") as PolicyChallengeV3;\n if (typeof value.challengeId !== \"string\" || typeof value.nonce !== \"string\" || value.policyCid !== input.policyCid || value.recipientDid !== input.recipientDid)\n throw new Error(\"policy challenge binding is invalid\");\n return value;\n}\n\nfunction policyRuntimeBasePath(value: string | undefined): string {\n const path = value ?? \"/policy/v3\";\n if (!/^\\/policy(?:\\/[a-z0-9-]+)*$/.test(path)) {\n throw new Error(\"policy runtime path is invalid\");\n }\n return path;\n}\n\nexport async function mintPolicySessionV3(input: {\n readonly nodeOrigin: string;\n readonly policyCid: string;\n readonly policyRootCid: string;\n readonly enforcementRootCid: string;\n readonly recipientDid: string;\n readonly requestedCapabilities: readonly UnifiedPolicyCapability[];\n readonly expectedFacts?: Readonly<Record<string, string | number>>;\n readonly claim: Readonly<Record<string, unknown>>;\n readonly presentation: Readonly<Record<string, unknown>>;\n readonly challenge?: PolicyChallengeV3;\n readonly fetch?: typeof fetch;\n readonly signal?: AbortSignal;\n}): Promise<PolicySessionUcanV1> {\n const fetchFn = input.fetch ?? globalThis.fetch.bind(globalThis);\n const challenge = input.challenge ?? await requestPolicyChallengeV3(input);\n if (challenge.policyCid !== input.policyCid || challenge.recipientDid !== input.recipientDid)\n throw new Error(\"policy challenge binding is invalid\");\n const response = await fetchFn(new URL(\"/policy/v3/delegations\", input.nodeOrigin), {\n method: \"POST\",\n redirect: \"error\",\n signal: input.signal,\n headers: { accept: \"application/json\", \"content-type\": \"application/json\" },\n body: JSON.stringify({ policyCid: input.policyCid, challengeId: challenge.challengeId, nonce: challenge.nonce, claim: input.claim, presentation: input.presentation }),\n });\n if (!response.ok) throw await httpResponseError(response, \"policy delegation rejected\");\n const value = object(await response.json(), \"policy delegation\");\n if (value.admitted !== true || typeof value.sessionCid !== \"string\" || typeof value.authorization !== \"string\")\n throw new Error(\"policy delegation response is invalid\");\n const session = parsePolicySessionUcan(value.authorization, [input.policyRootCid, input.enforcementRootCid]);\n const expectedAttenuation = compactAttenuationForPolicyCapabilities(input.requestedCapabilities);\n if (session.cid !== value.sessionCid\n || session.aud !== input.recipientDid\n || session.fact.policyCid !== input.policyCid\n || session.fact.recipientDid !== input.recipientDid\n || session.fact.policyDelegationCid !== input.policyRootCid\n || session.fact.enforcementDelegationCid !== input.enforcementRootCid\n || jcsCanonicalize(session.att) !== jcsCanonicalize(expectedAttenuation)\n || Object.entries(input.expectedFacts ?? {}).some(([key, expected]) => session.fact[key] !== expected))\n throw new Error(\"policy delegation signed binding is invalid\");\n return session;\n}\n\nexport function compactAttenuationForPolicyCapabilities(\n input: readonly UnifiedPolicyCapability[],\n): Readonly<Record<string, Readonly<Record<string, readonly unknown[]>>>> {\n const attenuation: Record<string, Record<string, readonly unknown[]>> = {};\n for (const raw of input) {\n const capability = normalizeUnifiedPolicyCapability(raw);\n if (attenuation[capability.resource] !== undefined)\n throw new Error(\"policy capabilities contain a duplicate resource\");\n attenuation[capability.resource] = capability.kind === \"encryption\"\n ? { [capability.action]: [{}] }\n : Object.fromEntries(capability.actions.map((action) => [action, [{\n type: \"xyz.tinycloud.resource/selector\",\n kind: capability.selector,\n value: capability.resource,\n }]]));\n }\n return attenuation;\n}\n\nexport interface PolicyRootStatusV3 {\n readonly rootCid: string;\n readonly state: \"active\" | \"revoked\";\n readonly checkpoint: Readonly<Record<string, unknown>>;\n readonly revocation?: Readonly<Record<string, unknown>>;\n}\n\nexport function verifyPolicyRootStatusCheckpointV3(input: {\n readonly rootCid: string;\n readonly checkpoint: Readonly<Record<string, unknown>>;\n readonly expectedNodeAudience?: string;\n readonly now?: Date;\n}): boolean {\n const checkpoint = input.checkpoint;\n const allowed = new Set([\"schema\", \"targetCid\", \"targetRole\", \"ownerDid\", \"nodeAudience\", \"state\", \"sequence\", \"checkedAt\", \"freshUntil\", \"revokedAt\", \"revocationCid\", \"previousCheckpointDigestHex\", \"issuerDid\", \"signature\"]);\n if (Object.keys(checkpoint).some((key) => !allowed.has(key))\n || checkpoint.schema !== ROOT_STATUS_CHECKPOINT_V1_SCHEMA\n || checkpoint.targetCid !== input.rootCid\n || (checkpoint.targetRole !== \"policy-authority\" && checkpoint.targetRole !== \"policy-enforcement\")\n || (checkpoint.state !== \"active\" && checkpoint.state !== \"revoked\")\n || typeof checkpoint.ownerDid !== \"string\"\n || typeof checkpoint.nodeAudience !== \"string\"\n || checkpoint.issuerDid !== checkpoint.nodeAudience\n || (input.expectedNodeAudience !== undefined && checkpoint.nodeAudience !== input.expectedNodeAudience)\n || !Number.isInteger(checkpoint.sequence)\n || (checkpoint.sequence as number) < 1\n || typeof checkpoint.checkedAt !== \"string\"\n || typeof checkpoint.freshUntil !== \"string\") return false;\n const checkedAt = Date.parse(checkpoint.checkedAt as string);\n const freshUntil = Date.parse(checkpoint.freshUntil as string);\n const now = (input.now ?? new Date()).getTime();\n if (!Number.isFinite(checkedAt) || !Number.isFinite(freshUntil)\n || freshUntil < now || freshUntil <= checkedAt || freshUntil - checkedAt > 300_000) return false;\n if ((checkpoint.sequence === 1) !== (checkpoint.previousCheckpointDigestHex === undefined)) return false;\n if (checkpoint.sequence !== 1 && (typeof checkpoint.previousCheckpointDigestHex !== \"string\" || !/^[0-9a-f]{64}$/.test(checkpoint.previousCheckpointDigestHex))) return false;\n if (checkpoint.state === \"active\" && (checkpoint.revokedAt !== undefined || checkpoint.revocationCid !== undefined)) return false;\n if (checkpoint.state === \"revoked\" && (typeof checkpoint.revokedAt !== \"string\" || typeof checkpoint.revocationCid !== \"string\")) return false;\n const signature = checkpoint.signature;\n if (!isRecordValue(signature) || Object.keys(signature).length !== 3 || signature.suite !== \"Ed25519\" || signature.signerDid !== checkpoint.issuerDid || typeof signature.value !== \"string\") return false;\n try {\n const principal = (checkpoint.issuerDid as string).split(\"#\", 1)[0]!;\n const didMaterial = principal.startsWith(\"did:key:\") ? base58btc.decode(principal.slice(\"did:key:\".length)) : new Uint8Array();\n if (didMaterial.length !== 34 || didMaterial[0] !== 0xed || didMaterial[1] !== 0x01) return false;\n const unsigned = { ...checkpoint } as Record<string, unknown>;\n delete unsigned.signature;\n return ed25519.verify(\n decodeBase64Url(signature.value),\n sha256(new TextEncoder().encode(ROOT_STATUS_V1_DOMAIN + jcsCanonicalize(unsigned))),\n didMaterial.slice(2),\n );\n } catch {\n return false;\n }\n}\n\nexport async function getPolicyRootStatusV3(input: {\n readonly nodeOrigin: string;\n readonly rootCid: string;\n readonly expectedNodeAudience?: string;\n readonly expectedEnforcerDid?: string;\n readonly now?: Date;\n readonly fetch?: typeof fetch;\n}): Promise<PolicyRootStatusV3> {\n const fetchFn = input.fetch ?? globalThis.fetch.bind(globalThis);\n const response = await fetchFn(new URL(`/policy/v3/status/${encodeURIComponent(input.rootCid)}`, input.nodeOrigin), {\n method: \"GET\",\n redirect: \"error\",\n headers: { accept: \"application/json\" },\n });\n if (!response.ok) throw await httpResponseError(response, \"policy root status rejected\");\n const value = object(await response.json(), \"policy root status\");\n const checkpoint = object(value.checkpoint, \"policy root checkpoint\");\n if (value.rootCid !== input.rootCid\n || (value.state !== \"active\" && value.state !== \"revoked\")\n || value.state !== checkpoint.state\n || !verifyPolicyRootStatusCheckpointV3({ rootCid: input.rootCid, checkpoint, expectedNodeAudience: input.expectedNodeAudience, now: input.now }))\n throw new Error(\"policy root status binding is invalid\");\n const revocation = value.revocation === undefined ? undefined : object(value.revocation, \"policy root revocation\");\n if ((value.state === \"revoked\") !== (revocation !== undefined)\n || revocation !== undefined && !verifyPolicyRootRevocationV3({\n rootCid: input.rootCid,\n checkpoint,\n revocation,\n expectedEnforcerDid: input.expectedEnforcerDid,\n })) throw new Error(\"policy root status revocation evidence is invalid\");\n return { rootCid: input.rootCid, state: value.state, checkpoint, ...(revocation === undefined ? {} : { revocation }) };\n}\n\nexport function verifyPolicyRootRevocationV3(input: {\n readonly rootCid: string;\n readonly checkpoint: Readonly<Record<string, unknown>>;\n readonly revocation: Readonly<Record<string, unknown>>;\n readonly expectedEnforcerDid?: string;\n}): boolean {\n const value = input.revocation;\n const allowed = [\"schema\", \"targetCid\", \"targetRole\", \"ownerDid\", \"nodeAudience\", \"revokedAt\", \"reason\", \"issuerDid\", \"signature\"];\n if (Object.keys(value).length !== allowed.length || Object.keys(value).some((key) => !allowed.includes(key))\n || value.schema !== ROOT_REVOCATION_V1_SCHEMA\n || value.targetCid !== input.rootCid\n || value.targetRole !== input.checkpoint.targetRole\n || value.ownerDid !== input.checkpoint.ownerDid\n || value.nodeAudience !== input.checkpoint.nodeAudience\n || value.revokedAt !== input.checkpoint.revokedAt\n || typeof value.reason !== \"string\" || value.reason.length === 0\n || typeof value.issuerDid !== \"string\") return false;\n const authorized = value.issuerDid === value.ownerDid\n || value.targetRole === \"policy-enforcement\" && value.issuerDid === input.expectedEnforcerDid;\n if (!authorized) return false;\n const signature = value.signature;\n if (!isRecordValue(signature) || Object.keys(signature).length !== 3 || signature.suite !== \"Ed25519\" || signature.signerDid !== value.issuerDid || typeof signature.value !== \"string\") return false;\n try {\n const principal = (value.issuerDid as string).split(\"#\", 1)[0]!;\n const didMaterial = principal.startsWith(\"did:key:\") ? base58btc.decode(principal.slice(\"did:key:\".length)) : new Uint8Array();\n if (didMaterial.length !== 34 || didMaterial[0] !== 0xed || didMaterial[1] !== 0x01) return false;\n const unsigned = { ...value } as Record<string, unknown>;\n delete unsigned.signature;\n const digest = sha256(new TextEncoder().encode(ROOT_REVOCATION_V1_DOMAIN + jcsCanonicalize(unsigned)));\n return input.checkpoint.revocationCid === hex(digest)\n && ed25519.verify(decodeBase64Url(signature.value), digest, didMaterial.slice(2));\n } catch {\n return false;\n }\n}\n\nexport async function renewPolicyRootStatusV3(input: {\n readonly nodeOrigin: string;\n readonly rootCid: string;\n readonly ownerDid: string;\n readonly nodeAudience: string;\n readonly sign: (digest: Uint8Array) => Promise<Uint8Array>;\n readonly now?: Date;\n readonly nonce?: string;\n readonly fetch?: typeof fetch;\n}): Promise<Readonly<Record<string, unknown>>> {\n const fetchFn = input.fetch ?? globalThis.fetch.bind(globalThis);\n const current = await getPolicyRootStatusV3({ nodeOrigin: input.nodeOrigin, rootCid: input.rootCid, expectedNodeAudience: input.nodeAudience, now: input.now, fetch: fetchFn });\n if (current.state !== \"active\" || current.checkpoint.ownerDid !== input.ownerDid || current.checkpoint.nodeAudience !== input.nodeAudience || current.checkpoint.state !== \"active\" || !Number.isInteger(current.checkpoint.sequence))\n throw new Error(\"policy root status cannot be renewed\");\n const currentUnsigned = { ...current.checkpoint };\n delete currentUnsigned.signature;\n const previousCheckpointDigestHex = hex(sha256(new TextEncoder().encode(ROOT_STATUS_V1_DOMAIN + jcsCanonicalize(currentUnsigned))));\n const unsigned = {\n schema: \"xyz.tinycloud.policy/root-status-renewal/v1\",\n targetCid: input.rootCid,\n ownerDid: input.ownerDid,\n nodeAudience: input.nodeAudience,\n issuedAt: (input.now ?? new Date()).toISOString(),\n nonce: input.nonce ?? encodeBase64Url(crypto.getRandomValues(new Uint8Array(16))),\n sequence: (current.checkpoint.sequence as number) + 1,\n previousCheckpointDigestHex,\n };\n const signature = await input.sign(sha256(new TextEncoder().encode(ROOT_STATUS_RENEWAL_V1_DOMAIN + jcsCanonicalize(unsigned))));\n if (signature.length !== 64) throw new Error(\"policy root renewal signature must be Ed25519\");\n const response = await fetchFn(new URL(\"/policy/v3/status\", input.nodeOrigin), {\n method: \"POST\",\n redirect: \"error\",\n headers: { accept: \"application/json\", \"content-type\": \"application/json\" },\n body: JSON.stringify({ rootCid: input.rootCid, renewal: { ...unsigned, signature: { suite: \"Ed25519\", signerDid: input.ownerDid, value: encodeBase64Url(signature) } } }),\n });\n if (!response.ok) throw await httpResponseError(response, \"policy root renewal rejected\");\n return object(await response.json(), \"policy root renewal\");\n}\n\n/**\n * RFC 3339 in whole seconds. The Node refuses a revocation time it can't\n * reproduce exactly, and its formatter drops trailing zeros from the\n * fraction, so a millisecond `toISOString()` such as `.120Z` came back as\n * `.12Z` and was refused about one time in ten (TC-601).\n */\nfunction rfc3339Seconds(value: Date): string {\n return new Date(Math.floor(value.getTime() / 1000) * 1000).toISOString().replace(/\\.000Z$/, \"Z\");\n}\n\nexport async function revokePolicyRootV3(input: {\n readonly nodeOrigin: string;\n readonly rootCid: string;\n readonly targetRole: \"policy-authority\" | \"policy-enforcement\";\n readonly ownerDid: string;\n readonly issuerDid: string;\n readonly nodeAudience: string;\n readonly reason: string;\n readonly sign: (digest: Uint8Array) => Promise<Uint8Array>;\n readonly now?: Date;\n readonly fetch?: typeof fetch;\n}): Promise<Readonly<Record<string, unknown>>> {\n if (input.reason.length === 0) throw new Error(\"policy root revocation reason is required\");\n const unsigned = {\n schema: ROOT_REVOCATION_V1_SCHEMA,\n targetCid: input.rootCid,\n targetRole: input.targetRole,\n ownerDid: input.ownerDid,\n nodeAudience: input.nodeAudience,\n revokedAt: rfc3339Seconds(input.now ?? new Date()),\n reason: input.reason,\n issuerDid: input.issuerDid,\n };\n const signature = await input.sign(sha256(new TextEncoder().encode(ROOT_REVOCATION_V1_DOMAIN + jcsCanonicalize(unsigned))));\n if (signature.length !== 64) throw new Error(\"policy root revocation signature must be Ed25519\");\n const fetchFn = input.fetch ?? globalThis.fetch.bind(globalThis);\n const response = await fetchFn(new URL(\"/revoke\", input.nodeOrigin), {\n method: \"POST\",\n redirect: \"error\",\n headers: { accept: \"application/json\", \"content-type\": \"application/json\" },\n body: JSON.stringify({ revocation: { ...unsigned, signature: { suite: \"Ed25519\", signerDid: input.issuerDid, value: encodeBase64Url(signature) } } }),\n });\n if (!response.ok) throw await httpResponseError(response, \"policy root revocation rejected\");\n return object(await response.json(), \"policy root revocation\");\n}\n\nconst POLICY_SESSION_FACT_KEYS = [\n \"profile\",\n \"ownerDid\",\n \"policyId\",\n \"policyDigestHex\",\n \"policyCid\",\n \"policyDelegationCid\",\n \"enforcementDelegationCid\",\n \"contentSourceDigestHex\",\n \"capabilityCeilingHashHex\",\n \"nativeProjectionHashHex\",\n \"enforcerDid\",\n \"nodeAudience\",\n \"recipientDid\",\n \"challengeId\",\n \"claimDigestHex\",\n \"claimJti\",\n \"vpDigestHex\",\n \"credentialEvidenceDigestHex\",\n \"decisionContextDigestHex\",\n \"issuanceAuditDigestHex\",\n \"remainingRedelegationDepth\",\n] as const;\n\nconst POLICY_SESSION_V4_AUDIT_FACT_KEYS = [\n \"credentialIdAuditDigestHex\",\n \"presentationJtiAuditDigestHex\",\n] as const;\n\nconst LOWER_SHA256_HEX = /^[0-9a-f]{64}$/;\n\nconst KV_ACTIONS = new Set<string>([\n \"tinycloud.kv/get\",\n \"tinycloud.kv/list\",\n \"tinycloud.kv/metadata\",\n \"tinycloud.kv/put\",\n]);\n\nfunction object(value: unknown, label: string): Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`${label} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction exactKeys(\n value: Record<string, unknown>,\n allowed: readonly string[],\n label: string,\n): void {\n const keys = new Set(allowed);\n if (Object.keys(value).some((key) => !keys.has(key)))\n throw new Error(`${label} contains an unknown field`);\n}\n\nfunction nonEmptyString(value: unknown, label: string): string {\n if (typeof value !== \"string\" || value.length === 0)\n throw new Error(`${label} must be a non-empty string`);\n return value;\n}\n\nfunction parseKvResource(resource: string): { space: string; path: string } {\n const marker = resource.indexOf(\"/kv/\");\n const encodedSpace = marker < 1 ? \"\" : resource.slice(0, marker);\n const legacy = encodedSpace.startsWith(\"tinycloud://\");\n const space = legacy ? encodedSpace.slice(\"tinycloud://\".length) : encodedSpace;\n const path = marker < 1 ? \"\" : resource.slice(marker + 4);\n if (\n marker < 1 ||\n (legacy\n ? /[:/?#%]/.test(space)\n : !encodedSpace.startsWith(\"tinycloud:\") || /[/?#%]/.test(encodedSpace)) ||\n path.startsWith(\"/\") ||\n path.endsWith(\"/\") ||\n path.includes(\"//\") ||\n path\n .split(\"/\")\n .some((part) => part === \".\" || part === \"..\" || part.length === 0)\n ) {\n throw new Error(\"KV resource is not canonical\");\n }\n return { space, path };\n}\n\nfunction parseEncryptionResource(resource: string): void {\n if (!resource.startsWith(\"urn:tinycloud:encryption:\")) throw new Error(\"encryption capability is invalid\");\n const rest = resource.slice(\"urn:tinycloud:encryption:\".length);\n const separator = rest.lastIndexOf(\":\");\n const ownerDid = separator < 0 ? \"\" : rest.slice(0, separator);\n const network = separator < 0 ? \"\" : rest.slice(separator + 1);\n if (!ownerDid.startsWith(\"did:\") || network.length === 0 || network.includes(\":\") || network.includes(\"/\") || network.includes(\"%\") || network.includes(\"?\") || network.includes(\"#\")) {\n throw new Error(\"encryption capability is invalid\");\n }\n}\n\nexport function normalizeUnifiedPolicyCapability(\n input: unknown,\n): UnifiedPolicyCapability {\n const value = object(input, \"capability\");\n const kind = nonEmptyString(value.kind, \"capability.kind\");\n if (kind === \"kv\") {\n exactKeys(\n value,\n [\"kind\", \"resource\", \"selector\", \"actions\"],\n \"KV capability\",\n );\n const resource = nonEmptyString(value.resource, \"capability.resource\");\n parseKvResource(resource);\n if (value.selector !== \"exact\" && value.selector !== \"prefix\")\n throw new Error(\"capability.selector is invalid\");\n if (!Array.isArray(value.actions) || value.actions.length === 0)\n throw new Error(\"capability.actions is invalid\");\n const actions = value.actions.map((action) =>\n nonEmptyString(action, \"capability.actions[]\"),\n );\n if (\n new Set(actions).size !== actions.length ||\n actions.some((action) => !KV_ACTIONS.has(action))\n )\n throw new Error(\"capability.actions is invalid\");\n return {\n kind: \"kv\",\n resource,\n selector: value.selector,\n actions: [...actions].sort() as UnifiedKvCapability[\"actions\"],\n };\n }\n if (kind === \"encryption\") {\n exactKeys(value, [\"kind\", \"resource\", \"action\"], \"encryption capability\");\n const resource = nonEmptyString(value.resource, \"capability.resource\");\n if (value.action !== \"tinycloud.encryption/decrypt\")\n throw new Error(\"encryption capability is invalid\");\n parseEncryptionResource(resource);\n return {\n kind: \"encryption\",\n resource,\n action: \"tinycloud.encryption/decrypt\",\n };\n }\n throw new Error(\"capability.kind is invalid\");\n}\n\nexport function canonicalizeUnifiedPolicyCapability(\n input: unknown,\n): UnifiedPolicyCapability {\n return normalizeUnifiedPolicyCapability(input);\n}\n\nexport function unifiedPolicyCapabilityDigestHex(input: unknown): string {\n return hex(\n sha256(\n new TextEncoder().encode(\n POLICY_CAPABILITY_V1_DOMAIN +\n jcsCanonicalize(normalizeUnifiedPolicyCapability(input)),\n ),\n ),\n );\n}\n\nexport function unifiedPolicyCapabilityContains(\n authorityInput: unknown,\n requestedInput: unknown,\n): boolean {\n try {\n const authority = normalizeUnifiedPolicyCapability(authorityInput);\n const requested = normalizeUnifiedPolicyCapability(requestedInput);\n if (authority.kind !== requested.kind) return false;\n if (authority.kind === \"encryption\" && requested.kind === \"encryption\")\n return (\n authority.resource === requested.resource &&\n authority.action === requested.action\n );\n if (authority.kind !== \"kv\" || requested.kind !== \"kv\") return false;\n const { resource: authorized } = authority;\n const { resource: requestedResource } = requested;\n const pathContained =\n authority.selector === \"exact\"\n ? authorized === requestedResource\n : authorized === requestedResource ||\n requestedResource.startsWith(`${authorized}/`);\n if (\n !pathContained ||\n (authority.selector === \"exact\" && requested.selector === \"prefix\")\n )\n return false;\n return requested.actions.every((action) =>\n authority.actions.includes(action),\n );\n } catch {\n return false;\n }\n}\n\nexport function projectUnifiedPolicyCapability(\n input: unknown,\n): UnifiedNativeCapability {\n const capability = normalizeUnifiedPolicyCapability(input);\n if (capability.kind === \"encryption\") {\n return {\n service: \"tinycloud.encryption\",\n space: capability.resource,\n path: capability.resource,\n actions: [capability.action],\n };\n }\n const { space, path } = parseKvResource(capability.resource);\n return {\n service: \"tinycloud.kv\",\n space,\n path,\n actions: [...capability.actions],\n caveat: {\n type: \"xyz.tinycloud.resource/selector\",\n kind: capability.selector,\n value: capability.resource,\n },\n };\n}\n\nexport function projectUnifiedPolicyCapabilities(\n input: readonly unknown[],\n): UnifiedNativeCapability[] {\n return input\n .map(projectUnifiedPolicyCapability)\n .sort((left, right) => {\n const a = jcsCanonicalize(left);\n const b = jcsCanonicalize(right);\n return a < b ? -1 : a > b ? 1 : 0;\n });\n}\n\nexport function unifiedNativeProjectionHashHex(\n input: readonly unknown[],\n): string {\n return hex(\n sha256(\n new TextEncoder().encode(\n NATIVE_PROJECTION_V1_DOMAIN +\n jcsCanonicalize(projectUnifiedPolicyCapabilities(input)),\n ),\n ),\n );\n}\n\nexport function unifiedPolicyCapabilityFromNative(\n input: unknown,\n): UnifiedPolicyCapability {\n const value = object(input, \"native capability\");\n exactKeys(\n value,\n [\"service\", \"space\", \"path\", \"actions\", \"caveat\"],\n \"native capability\",\n );\n const service = nonEmptyString(value.service, \"native.service\");\n const actions = value.actions;\n if (!Array.isArray(actions)) throw new Error(\"native.actions is invalid\");\n if (\n service === \"tinycloud.encryption\" &&\n value.caveat === undefined &&\n value.space === value.path &&\n actions.length === 1 &&\n actions[0] === \"tinycloud.encryption/decrypt\"\n ) {\n return normalizeUnifiedPolicyCapability({\n kind: \"encryption\",\n resource: value.space,\n action: actions[0],\n });\n }\n if (\n service !== \"tinycloud.kv\" ||\n typeof value.space !== \"string\" ||\n typeof value.path !== \"string\"\n )\n throw new Error(\"native capability is not supported\");\n const caveat = object(value.caveat, \"native.caveat\");\n exactKeys(caveat, [\"type\", \"kind\", \"value\"], \"native selector caveat\");\n if (\n caveat.type !== \"xyz.tinycloud.resource/selector\" ||\n (caveat.kind !== \"exact\" && caveat.kind !== \"prefix\") ||\n caveat.value !== `${value.space.startsWith(\"tinycloud:\") ? value.space : `tinycloud://${value.space}`}/kv/${value.path}`\n )\n throw new Error(\"native selector caveat does not match capability\");\n return normalizeUnifiedPolicyCapability({\n kind: \"kv\",\n resource: caveat.value,\n selector: caveat.kind,\n actions,\n });\n}\n\nexport function contentSourceDigestHex(input: UnifiedContentSource): string {\n return hex(\n sha256(\n new TextEncoder().encode(\n CONTENT_SOURCE_V1_DOMAIN + jcsCanonicalize(input),\n ),\n ),\n );\n}\n\nfunction exactObject(\n value: unknown,\n keys: readonly string[],\n label: string,\n): Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`${label} is invalid`);\n }\n const record = value as Record<string, unknown>;\n if (\n Object.keys(record).length !== keys.length ||\n keys.some((key) => !Object.prototype.hasOwnProperty.call(record, key))\n ) {\n throw new Error(`${label} is invalid`);\n }\n return record;\n}\n\nfunction didKeyEd25519PublicKey(value: string): Uint8Array {\n const principal = value.split(\"#\", 1)[0]!;\n if (!principal.startsWith(\"did:key:\")) {\n throw new Error(\"policy enforcer binding signer is invalid\");\n }\n const material = base58btc.decode(principal.slice(\"did:key:\".length));\n if (material.length !== 34 || material[0] !== 0xed || material[1] !== 0x01) {\n throw new Error(\"policy enforcer binding signer is invalid\");\n }\n return material.slice(2);\n}\n\n/**\n * Register a signed policy and its sibling roots with the embedded Node\n * Policy/v3 runtime. This is intentionally application-neutral: callers\n * supply policy material, while Node owns both transport endpoints.\n */\nexport async function registerPolicyV3(\n input: RegisterPolicyV3Input,\n): Promise<RegisterPolicyV3Receipt> {\n const fetchFn = input.fetch ?? globalThis.fetch.bind(globalThis);\n const rootExpiresAt = new Date(input.rootExpiresAt);\n const canonicalRootExpiresAt = new Date(\n Math.floor(rootExpiresAt.getTime() / 1000) * 1000,\n )\n .toISOString()\n .replace(/\\.000Z$/, \"Z\");\n if (\n !Number.isFinite(rootExpiresAt.getTime()) ||\n canonicalRootExpiresAt !== input.rootExpiresAt ||\n rootExpiresAt.getTime() <= Date.now()\n ) {\n throw new Error(\"policy root expiry is invalid\");\n }\n const bindingResponse = await fetchFn(\n new URL(\"/policy/v3/enforcer-bindings\", input.nodeOrigin),\n {\n method: \"POST\",\n redirect: \"error\",\n signal: input.signal,\n headers: { accept: \"application/json\", \"content-type\": \"application/json\" },\n body: JSON.stringify({\n rootExpiresAt: input.rootExpiresAt,\n enforcerDid: input.enforcerDid,\n }),\n },\n );\n if (!bindingResponse.ok) {\n throw await httpResponseError(bindingResponse, \"policy enforcer binding rejected\");\n }\n const binding = exactObject(\n await bindingResponse.json(),\n [\n \"schema\",\n \"enforcerDid\",\n \"nodeAudience\",\n \"attestationBindingDigestHex\",\n \"issuedAt\",\n \"expiresAt\",\n \"signature\",\n ],\n \"policy enforcer binding\",\n );\n const signature = exactObject(\n binding.signature,\n [\"suite\", \"signerDid\", \"value\"],\n \"policy enforcer binding signature\",\n );\n const expectedBindingDigestHex = hex(\n sha256(\n new TextEncoder().encode(\n jcsCanonicalize({\n enforcerDid: input.enforcerDid,\n nodeAudience: input.expectedNodeAudience,\n }),\n ),\n ),\n );\n if (\n binding.schema !== ATTESTED_ENFORCER_BINDING_V2_SCHEMA ||\n binding.enforcerDid !== input.enforcerDid ||\n binding.nodeAudience !== input.expectedNodeAudience ||\n binding.attestationBindingDigestHex !== expectedBindingDigestHex ||\n binding.expiresAt !== input.rootExpiresAt ||\n typeof binding.issuedAt !== \"string\" ||\n Date.parse(binding.issuedAt) > Date.now() ||\n signature.suite !== \"Ed25519\" ||\n signature.signerDid !== input.expectedNodeAudience ||\n typeof signature.value !== \"string\"\n ) {\n throw new Error(\"policy enforcer binding is invalid\");\n }\n const { signature: _signature, ...unsignedBinding } = binding;\n const signedBinding = sha256(\n new TextEncoder().encode(\n `xyz.tinycloud.policy/AttestedEnforcerBinding/v2\\0${jcsCanonicalize(unsignedBinding)}`,\n ),\n );\n if (\n !ed25519.verify(\n decodeBase64Url(signature.value),\n signedBinding,\n didKeyEd25519PublicKey(input.expectedNodeAudience),\n { zip215: false },\n )\n ) {\n throw new Error(\"policy enforcer binding signature is invalid\");\n }\n\n const response = await fetchFn(\n new URL(\"/policy/v3/policies\", input.nodeOrigin),\n {\n method: \"POST\",\n redirect: \"error\",\n signal: input.signal,\n headers: { accept: \"application/json\", \"content-type\": \"application/json\" },\n body: JSON.stringify({\n policyCid: input.policyCid,\n policy: input.policy,\n policyRoot: input.policyRoot.authorization.replace(/^Bearer\\s+/i, \"\"),\n enforcementRoot: input.enforcementRoot.authorization.replace(/^Bearer\\s+/i, \"\"),\n contentSourceDigestHex: input.contentSourceDigestHex,\n nativeProjectionHashHex: input.nativeProjectionHashHex,\n attestedEnforcerBinding: binding,\n }),\n },\n );\n if (!response.ok) {\n throw await httpResponseError(response, \"policy registration rejected\");\n }\n const receipt = exactObject(\n await response.json(),\n [\"policyCid\", \"policyRootCid\", \"enforcementRootCid\"],\n \"policy registration response\",\n );\n if (\n receipt.policyCid !== input.policyCid ||\n receipt.policyRootCid !== input.policyRoot.cid ||\n receipt.enforcementRootCid !== input.enforcementRoot.cid\n ) {\n throw new Error(\"policy registration response binding is invalid\");\n }\n return {\n policyCid: input.policyCid,\n policyRootCid: input.policyRoot.cid,\n enforcementRootCid: input.enforcementRoot.cid,\n attestedEnforcerBinding: binding as unknown as AttestedEnforcerBindingV2,\n };\n}\n\nexport function policyDigestHex(\n policy: Omit<UnifiedPolicyV1, \"policyId\" | \"signature\">,\n): string {\n const canonicalPolicy = {\n ...policy,\n capabilityCeiling: policy.capabilityCeiling.map(\n normalizeUnifiedPolicyCapability,\n ),\n };\n return hex(\n sha256(\n new TextEncoder().encode(\n POLICY_V1_DOMAIN + jcsCanonicalize(canonicalPolicy),\n ),\n ),\n );\n}\n\nexport function policyIdForDigestHex(digestHex: string): string {\n const digest = Uint8Array.from(\n (digestHex.match(/.{2}/g) ?? []).map((byte) => Number.parseInt(byte, 16)),\n );\n if (digest.length !== 32) throw new Error(\"policy digest must be 32 bytes\");\n return `pol_${base32Lower(digest)}`;\n}\n\nexport function policyCidFromCanonicalBytes(bytes: Uint8Array): string {\n return CID.createV1(0x55, createDigest(0x12, sha256(bytes))).toString();\n}\n\nconst CompactHeaderSchema = z.object({\n alg: z.literal(\"EdDSA\"),\n jwk: z.object({ alg: z.literal(\"EdDSA\"), crv: z.literal(\"Ed25519\"), kty: z.literal(\"OKP\"), x: z.string().min(1) }).strict(),\n typ: z.literal(\"JWT\"),\n ucv: z.literal(\"0.10.0\"),\n}).strict();\nconst CompactPayloadSchema = z.object({\n att: z.record(z.record(z.array(z.unknown()).min(1))),\n aud: z.string().min(1),\n exp: z.number().int(),\n fct: z.array(z.record(z.unknown())).length(1),\n iss: z.string().min(1),\n nbf: z.number().int(),\n nnc: z.string().min(1),\n prf: z.array(z.string().min(1)),\n}).strict();\n\nexport interface CompactUcanAuthorizationV1 {\n readonly authorization: string;\n readonly cid: string;\n readonly header: z.infer<typeof CompactHeaderSchema>;\n readonly payload: z.infer<typeof CompactPayloadSchema>;\n}\n\nexport interface SignCompactUcanAuthorizationInput {\n readonly issuerDid: string;\n readonly audienceDid: string;\n readonly attenuation: Readonly<Record<string, Readonly<Record<string, readonly unknown[]>>>>;\n readonly facts: readonly [Readonly<Record<string, unknown>>];\n readonly proofs: readonly string[];\n readonly notBefore: number;\n readonly expiresAt: number;\n readonly nonce: string;\n readonly sign: (bytes: Uint8Array) => Promise<Uint8Array>;\n}\n\nexport interface SignCompactUcanRootAuthorizationInput {\n readonly issuerDid: string;\n readonly audienceDid: string;\n readonly attenuation: Readonly<Record<string, Readonly<Record<string, readonly unknown[]>>>>;\n readonly facts: readonly [Readonly<Record<string, unknown>>];\n readonly notBefore: number;\n readonly expiresAt: number;\n readonly nonce: string;\n readonly sign: (bytes: Uint8Array) => Promise<Uint8Array>;\n}\n\nasync function signCompactUcan(\n input: SignCompactUcanAuthorizationInput,\n): Promise<CompactUcanAuthorizationV1> {\n const principal = input.issuerDid.split(\"#\", 1)[0]!;\n const didMaterial = principal.startsWith(\"did:key:\")\n ? base58btc.decode(principal.slice(\"did:key:\".length))\n : new Uint8Array();\n if (didMaterial.length !== 34 || didMaterial[0] !== 0xed || didMaterial[1] !== 0x01)\n throw new Error(\"compact UCAN signer must be did:key Ed25519\");\n const header = { alg: \"EdDSA\", jwk: { alg: \"EdDSA\", crv: \"Ed25519\", kty: \"OKP\", x: encodeBase64Url(didMaterial.slice(2)) }, typ: \"JWT\", ucv: \"0.10.0\" };\n const payload = {\n att: input.attenuation,\n aud: input.audienceDid,\n exp: input.expiresAt,\n fct: input.facts,\n iss: input.issuerDid.includes(\"#\") ? input.issuerDid : `${principal}#${principal.slice(\"did:key:\".length)}`,\n nbf: input.notBefore,\n nnc: input.nonce,\n prf: input.proofs,\n };\n const protectedSegment = encodeBase64Url(new TextEncoder().encode(jcsCanonicalize(header)));\n const payloadSegment = encodeBase64Url(new TextEncoder().encode(jcsCanonicalize(payload)));\n const signature = await input.sign(new TextEncoder().encode(`${protectedSegment}.${payloadSegment}`));\n if (signature.length !== 64) throw new Error(\"compact Authorization signature must be Ed25519\");\n return parseCompactUcanAuthorization(`${protectedSegment}.${payloadSegment}.${encodeBase64Url(signature)}`);\n}\n\n/** Sign exact compact-UCAN bytes with a caller-owned, potentially non-extractable key. */\nexport async function signCompactUcanAuthorization(\n input: SignCompactUcanAuthorizationInput,\n): Promise<CompactUcanAuthorizationV1> {\n if (input.notBefore >= input.expiresAt || input.expiresAt - input.notBefore > 60)\n throw new Error(\"compact invocation lifetime must be between one and 60 seconds\");\n return signCompactUcan(input);\n}\n\n/**\n * Longest window a policy root may have. A policy session never outlives its\n * roots, so this also bounds every session and descendant.\n */\nconst MAX_POLICY_ROOT_SECONDS = 31 * 24 * 60 * 60;\n\n/** Sign a proofless policy root without weakening the 60-second invocation profile. */\nexport async function signCompactUcanRootAuthorization(\n input: SignCompactUcanRootAuthorizationInput,\n): Promise<CompactUcanAuthorizationV1> {\n if (input.notBefore >= input.expiresAt || input.expiresAt - input.notBefore > MAX_POLICY_ROOT_SECONDS)\n throw new Error(\"compact policy root lifetime must be between one second and 31 days\");\n return signCompactUcan({ ...input, proofs: [] });\n}\n\nexport interface CompactPolicyInvocationInput {\n readonly sessionAuthorization: string;\n readonly sessionCid: string;\n readonly recipientDid: string;\n readonly audienceDid: string;\n readonly resource: string;\n readonly action: string;\n readonly caveat?: Readonly<Record<string, unknown>>;\n readonly facts?: Readonly<Record<string, unknown>>;\n readonly privateKey: Uint8Array;\n readonly now?: number;\n readonly nonce?: string;\n}\n\n/** Sign a fresh one-parent ordinary invocation; S0 itself is never a bearer. */\nexport function createCompactPolicyInvocation(\n input: CompactPolicyInvocationInput,\n): CompactUcanAuthorizationV1 {\n const session = parsePolicySessionUcan(input.sessionAuthorization);\n if (session.cid !== input.sessionCid || session.aud !== input.recipientDid)\n throw new Error(\"policy session does not bind the recipient signer\");\n const principal = input.recipientDid.split(\"#\", 1)[0]!;\n const didMaterial = base58btc.decode(principal.slice(\"did:key:\".length));\n if (didMaterial.length !== 34 || didMaterial[0] !== 0xed || didMaterial[1] !== 0x01)\n throw new Error(\"policy invocation signer must be did:key Ed25519\");\n const publicKey = ed25519.getPublicKey(input.privateKey);\n if (!equalBytes(publicKey, didMaterial.slice(2)))\n throw new Error(\"policy invocation private key does not bind recipient DID\");\n const now = input.now ?? Math.floor(Date.now() / 1000);\n const exp = Math.min(now + 60, session.exp);\n if (exp <= now) throw new Error(\"policy session has expired\");\n const header = { alg: \"EdDSA\", jwk: { alg: \"EdDSA\", crv: \"Ed25519\", kty: \"OKP\", x: encodeBase64Url(publicKey) }, typ: \"JWT\", ucv: \"0.10.0\" };\n const payload = {\n att: { [input.resource]: { [input.action]: [input.caveat ?? {}] } },\n aud: input.audienceDid,\n exp,\n fct: [input.facts ?? { type: \"tinycloud.policy.invocation/v1\", policyCid: session.fact.policyCid, sessionCid: session.cid }],\n iss: input.recipientDid.includes(\"#\") ? input.recipientDid : `${principal}#${principal.slice(\"did:key:\".length)}`,\n nbf: now,\n nnc: input.nonce ?? encodeBase64Url(crypto.getRandomValues(new Uint8Array(16))),\n prf: [session.cid],\n };\n const protectedSegment = encodeBase64Url(new TextEncoder().encode(jcsCanonicalize(header)));\n const payloadSegment = encodeBase64Url(new TextEncoder().encode(jcsCanonicalize(payload)));\n const signingInput = new TextEncoder().encode(`${protectedSegment}.${payloadSegment}`);\n const signature = ed25519.sign(signingInput, input.privateKey);\n return parseCompactUcanAuthorization(`${protectedSegment}.${payloadSegment}.${encodeBase64Url(signature)}`);\n}\n\nexport interface CompactPolicyDescendantInput {\n readonly parentAuthorization: string;\n readonly parentCid: string;\n readonly issuerDid: string;\n readonly audienceDid: string;\n readonly attenuation: Readonly<Record<string, Readonly<Record<string, readonly unknown[]>>>>;\n /** Start of the window; defaults to one second after the parent's start. */\n readonly now?: number;\n /** Defaults to the longest window the parent allows: one second inside it. */\n readonly expiresAt?: number;\n readonly nonce?: string;\n}\n\n/** The checked claims of a descendant, before anyone signs them. */\nfunction compactPolicyDescendantClaims(input: CompactPolicyDescendantInput) {\n const parent = parseCompactUcanAuthorization(input.parentAuthorization, input.parentCid);\n if (parent.payload.aud !== input.issuerDid) throw new Error(\"policy descendant issuer is not the parent audience\");\n const parentFact = parent.payload.fct[0]!;\n const depth = parentFact.remainingRedelegationDepth;\n if (!Number.isInteger(depth) || (depth as number) <= 0) throw new Error(\"policy descendant depth is exhausted\");\n if (!compactAttenuationContains(parent.payload.att, input.attenuation))\n throw new Error(\"policy descendant exceeds the parent attenuation\");\n // Start just inside the parent's window, so a fresh link is usable at once.\n const now = Math.max(input.now ?? parent.payload.nbf + 1, parent.payload.nbf + 1);\n const exp = Math.min(input.expiresAt ?? parent.payload.exp - 1, parent.payload.exp - 1);\n if (exp <= now) throw new Error(\"policy parent has no strictly narrower validity window\");\n return {\n parentCid: parent.cid,\n fact: { ...parentFact, remainingRedelegationDepth: (depth as number) - 1 },\n notBefore: now,\n expiresAt: exp,\n nonce: input.nonce ?? encodeBase64Url(crypto.getRandomValues(new Uint8Array(16))),\n };\n}\n\nexport function createCompactPolicyDescendant(\n input: CompactPolicyDescendantInput & { readonly privateKey: Uint8Array },\n): CompactUcanAuthorizationV1 {\n const claims = compactPolicyDescendantClaims(input);\n const principal = input.issuerDid.split(\"#\", 1)[0]!;\n const didMaterial = base58btc.decode(principal.slice(\"did:key:\".length));\n const publicKey = ed25519.getPublicKey(input.privateKey);\n if (didMaterial.length !== 34 || !equalBytes(publicKey, didMaterial.slice(2))) throw new Error(\"policy descendant signer does not bind issuer DID\");\n const header = { alg: \"EdDSA\", jwk: { alg: \"EdDSA\", crv: \"Ed25519\", kty: \"OKP\", x: encodeBase64Url(publicKey) }, typ: \"JWT\", ucv: \"0.10.0\" };\n const payload = {\n att: input.attenuation,\n aud: input.audienceDid,\n exp: claims.expiresAt,\n fct: [claims.fact],\n iss: input.issuerDid.includes(\"#\") ? input.issuerDid : `${principal}#${principal.slice(\"did:key:\".length)}`,\n nbf: claims.notBefore,\n nnc: claims.nonce,\n prf: [claims.parentCid],\n };\n const protectedSegment = encodeBase64Url(new TextEncoder().encode(jcsCanonicalize(header)));\n const payloadSegment = encodeBase64Url(new TextEncoder().encode(jcsCanonicalize(payload)));\n const signature = ed25519.sign(new TextEncoder().encode(`${protectedSegment}.${payloadSegment}`), input.privateKey);\n return parseCompactUcanAuthorization(`${protectedSegment}.${payloadSegment}.${encodeBase64Url(signature)}`);\n}\n\n/**\n * The same descendant, signed by a caller-owned key that may be\n * non-extractable. The result is verified against the issuer DID.\n */\nexport async function signCompactPolicyDescendant(\n input: CompactPolicyDescendantInput & { readonly sign: (bytes: Uint8Array) => Promise<Uint8Array> },\n): Promise<CompactUcanAuthorizationV1> {\n const claims = compactPolicyDescendantClaims(input);\n return signCompactUcan({\n issuerDid: input.issuerDid,\n audienceDid: input.audienceDid,\n attenuation: input.attenuation,\n facts: [claims.fact],\n proofs: [claims.parentCid],\n notBefore: claims.notBefore,\n expiresAt: claims.expiresAt,\n nonce: claims.nonce,\n sign: input.sign,\n });\n}\n\n/** Byte-independent semantic containment shared by S0, descendants and mint requests. */\nexport function compactAttenuationContains(\n parent: Readonly<Record<string, Readonly<Record<string, readonly unknown[]>>>>,\n child: Readonly<Record<string, Readonly<Record<string, readonly unknown[]>>>>,\n): boolean {\n const selector = (value: readonly unknown[]): { readonly kind: \"exact\" | \"prefix\"; readonly value: string } | undefined => {\n if (value.length !== 1 || !isRecordValue(value[0])) return undefined;\n const caveat = value[0];\n if (Object.keys(caveat).length !== 3 || caveat.type !== \"xyz.tinycloud.resource/selector\" || (caveat.kind !== \"exact\" && caveat.kind !== \"prefix\") || typeof caveat.value !== \"string\") return undefined;\n return { kind: caveat.kind, value: caveat.value };\n };\n const equal = (left: unknown, right: unknown): boolean => jcsCanonicalize(left) === jcsCanonicalize(right);\n return Object.entries(child).every(([childResource, childActions]) =>\n Object.entries(childActions).every(([action, childCaveats]) =>\n Object.entries(parent).some(([parentResource, parentActions]) => {\n const parentCaveats = parentActions[action];\n if (parentCaveats === undefined) return false;\n if (parentResource === childResource && equal(parentCaveats, childCaveats)) return true;\n const parentSelector = selector(parentCaveats);\n const childSelector = selector(childCaveats);\n return parentSelector?.kind === \"prefix\"\n && childSelector !== undefined\n && parentSelector.value === parentResource\n && childSelector.value === childResource\n && (childResource === parentResource || childResource.startsWith(`${parentResource}/`));\n }),\n ),\n );\n}\n\nfunction isRecordValue(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function parseCompactUcanAuthorization(\n input: string,\n expectedCid?: string,\n): CompactUcanAuthorizationV1 {\n if (typeof input !== \"string\" || /\\s/.test(input))\n throw new Error(\"Authorization must be compact UCAN bytes\");\n const segments = input.split(\".\");\n if (segments.length !== 3 || segments.some((segment) => segment.length === 0))\n throw new Error(\"Authorization must have three compact segments\");\n const [headerSegment, payloadSegment, signatureSegment] = segments as [string, string, string];\n const headerBytes = decodeBase64Url(headerSegment);\n const payloadBytes = decodeBase64Url(payloadSegment);\n const signature = decodeBase64Url(signatureSegment);\n const headerValue: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(headerBytes));\n const payloadValue: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(payloadBytes));\n if (jcsCanonicalize(headerValue) !== new TextDecoder().decode(headerBytes)\n || jcsCanonicalize(payloadValue) !== new TextDecoder().decode(payloadBytes))\n throw new Error(\"compact UCAN segments are not canonical JCS\");\n const header = CompactHeaderSchema.parse(headerValue);\n const payload = CompactPayloadSchema.parse(payloadValue);\n if (payload.nbf >= payload.exp) throw new Error(\"compact UCAN validity is empty\");\n const principal = payload.iss.split(\"#\", 1)[0]!;\n const didMaterial = principal.startsWith(\"did:key:\")\n ? base58btc.decode(principal.slice(\"did:key:\".length))\n : new Uint8Array();\n if (didMaterial.length !== 34 || didMaterial[0] !== 0xed || didMaterial[1] !== 0x01)\n throw new Error(\"compact UCAN issuer must be did:key Ed25519\");\n const publicKey = didMaterial.slice(2);\n if (!equalBytes(publicKey, decodeBase64Url(header.jwk.x)))\n throw new Error(\"compact UCAN JWK does not bind issuer\");\n if (!ed25519.verify(signature, new TextEncoder().encode(`${headerSegment}.${payloadSegment}`), publicKey))\n throw new Error(\"compact UCAN signature is invalid\");\n const cid = CID.createV1(0x55, createDigest(0x1e, blake3(new TextEncoder().encode(input)))).toString();\n if (expectedCid !== undefined && cid !== expectedCid)\n throw new Error(\"compact UCAN CID does not match exact Authorization bytes\");\n return { authorization: input, cid, header, payload };\n}\n\nconst SignedCompactAttenuationSchema = z.record(z.record(z.array(z.unknown()).min(1)));\n/** Verify an issued UCAN's exact bytes while reading its signed attenuation. */\nexport function parseSignedCompactUcanAttenuation(input: string, expectedCid?: string): {\n cid: string;\n payload: { att: z.infer<typeof SignedCompactAttenuationSchema>; aud: string };\n} {\n if (typeof input !== \"string\" || /\\s/.test(input))\n throw new Error(\"Authorization must be compact UCAN bytes\");\n const segments = input.split(\".\");\n if (segments.length !== 3 || segments.some((segment) => segment.length === 0))\n throw new Error(\"Authorization must have three compact segments\");\n const [headerSegment, payloadSegment, signatureSegment] = segments as [string, string, string];\n const headerValue: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(decodeBase64Url(headerSegment)));\n const payloadValue: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(decodeBase64Url(payloadSegment)));\n if (!isRecordValue(headerValue) || !isRecordValue(headerValue.jwk) ||\n headerValue.alg !== \"EdDSA\" || headerValue.typ !== \"JWT\" || headerValue.ucv !== \"0.10.0\" ||\n headerValue.jwk.kty !== \"OKP\" || headerValue.jwk.crv !== \"Ed25519\" ||\n !isRecordValue(payloadValue) || typeof payloadValue.iss !== \"string\")\n throw new Error(\"Authorization has an invalid signed UCAN header or issuer\");\n const att = SignedCompactAttenuationSchema.parse(payloadValue.att);\n const principal = payloadValue.iss.split(\"#\", 1)[0]!;\n const didMaterial = principal.startsWith(\"did:key:\")\n ? base58btc.decode(principal.slice(\"did:key:\".length))\n : new Uint8Array();\n const publicKey = didMaterial.length === 34 && didMaterial[0] === 0xed && didMaterial[1] === 0x01\n ? didMaterial.slice(2)\n : new Uint8Array();\n const jwkKey = typeof headerValue.jwk.x === \"string\" ? decodeBase64Url(headerValue.jwk.x) : new Uint8Array();\n if (publicKey.length !== 32 || !equalBytes(publicKey, jwkKey))\n throw new Error(\"compact UCAN JWK does not bind issuer\");\n const signature = decodeBase64Url(signatureSegment);\n if (!ed25519.verify(signature, new TextEncoder().encode(`${headerSegment}.${payloadSegment}`), publicKey))\n throw new Error(\"compact UCAN signature is invalid\");\n if (typeof payloadValue.aud !== \"string\" || payloadValue.aud.length === 0)\n throw new Error(\"compact UCAN signed audience is missing\");\n const cid = CID.createV1(0x55, createDigest(0x1e, blake3(new TextEncoder().encode(input)))).toString();\n if (expectedCid !== undefined && cid !== expectedCid) throw new Error(\"compact UCAN CID does not match exact Authorization bytes\");\n return { cid, payload: { att, aud: payloadValue.aud } };\n}\n\nexport function parsePolicySessionUcan(\n authorization: string,\n expectedProofs?: readonly [string, string],\n): PolicySessionUcanV1 {\n const parsed = parseCompactUcanAuthorization(authorization);\n const fact = parsed.payload.fct[0]!;\n if (parsed.payload.prf.length !== 2 || parsed.payload.prf[0] === parsed.payload.prf[1])\n throw new Error(\"policy session UCAN requires two distinct ordered proofs\");\n if (expectedProofs !== undefined\n && (parsed.payload.prf[0] !== expectedProofs[0] || parsed.payload.prf[1] !== expectedProofs[1]))\n throw new Error(\"policy session UCAN ordered proofs do not match\");\n const factKeys = Object.keys(fact);\n const hasLegacyFactShape = factKeys.length === POLICY_SESSION_FACT_KEYS.length\n && factKeys.every((key) => POLICY_SESSION_FACT_KEYS.includes(key as never))\n && POLICY_SESSION_FACT_KEYS.every((key) => key in fact);\n const hasV4AuditFactShape = factKeys.length === POLICY_SESSION_FACT_KEYS.length + POLICY_SESSION_V4_AUDIT_FACT_KEYS.length\n && factKeys.every((key) => POLICY_SESSION_FACT_KEYS.includes(key as never) || POLICY_SESSION_V4_AUDIT_FACT_KEYS.includes(key as never))\n && POLICY_SESSION_FACT_KEYS.every((key) => key in fact)\n && POLICY_SESSION_V4_AUDIT_FACT_KEYS.every((key) => key in fact);\n if (!hasLegacyFactShape && !hasV4AuditFactShape)\n throw new Error(\"policy session UCAN fact is incomplete\");\n if (hasV4AuditFactShape\n && (!LOWER_SHA256_HEX.test(fact.credentialIdAuditDigestHex as string)\n || !LOWER_SHA256_HEX.test(fact.presentationJtiAuditDigestHex as string)))\n throw new Error(\"policy session UCAN v4 audit facts are invalid\");\n if (\n fact.profile !== POLICY_SESSION_UCAN_V1_PROFILE ||\n typeof fact.remainingRedelegationDepth !== \"number\" ||\n !Number.isInteger(fact.remainingRedelegationDepth) ||\n fact.remainingRedelegationDepth < 0 ||\n fact.remainingRedelegationDepth > 8 ||\n parsed.payload.exp - parsed.payload.nbf > MAX_POLICY_ROOT_SECONDS ||\n parsed.payload.iss.split(\"#\", 1)[0] !== fact.nodeAudience ||\n parsed.payload.aud !== fact.recipientDid\n )\n throw new Error(\"policy session UCAN fact is invalid\");\n return {\n authorization,\n cid: parsed.cid,\n iss: parsed.payload.iss,\n aud: parsed.payload.aud,\n prf: parsed.payload.prf as [string, string],\n att: parsed.payload.att,\n nbf: parsed.payload.nbf,\n exp: parsed.payload.exp,\n nnc: parsed.payload.nnc,\n fact,\n };\n}\n\nfunction decodeBase64Url(value: string): Uint8Array {\n if (!/^[A-Za-z0-9_-]+$/.test(value) || value.length % 4 === 1)\n throw new Error(\"value is not canonical base64url\");\n const normalized = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const binary = typeof atob === \"function\"\n ? atob(normalized.padEnd(Math.ceil(normalized.length / 4) * 4, \"=\"))\n : Buffer.from(normalized, \"base64\").toString(\"binary\");\n const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));\n const encoded = typeof btoa === \"function\"\n ? btoa(String.fromCharCode(...bytes)).replace(/=/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\")\n : Buffer.from(bytes).toString(\"base64url\");\n if (encoded !== value) throw new Error(\"value is not canonical base64url\");\n return bytes;\n}\n\nfunction encodeBase64Url(value: Uint8Array): string {\n return typeof btoa === \"function\"\n ? btoa(String.fromCharCode(...value)).replace(/=/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\")\n : Buffer.from(value).toString(\"base64url\");\n}\n\nfunction equalBytes(left: Uint8Array, right: Uint8Array): boolean {\n return left.length === right.length && left.every((byte, index) => byte === right[index]);\n}\n\nfunction hex(bytes: Uint8Array): string {\n return [...bytes].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction base32Lower(bytes: Uint8Array): string {\n const alphabet = \"abcdefghijklmnopqrstuvwxyz234567\";\n let output = \"\";\n let buffer = 0;\n let bits = 0;\n for (const byte of bytes) {\n buffer = (buffer << 8) | byte;\n bits += 8;\n while (bits >= 5) {\n output += alphabet[(buffer >>> (bits - 5)) & 31];\n bits -= 5;\n }\n }\n if (bits > 0) output += alphabet[(buffer << (5 - bits)) & 31];\n return output;\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport type { PermissionEntry } from \"@tinycloud/sdk-core\";\nimport { z } from \"zod\";\n\nimport {\n canonicalizeCapabilities,\n evaluateOperationAuthority,\n evaluateAuthority,\n} from \"./authority.js\";\nimport type { OperationSpaceResolver } from \"./authority.js\";\nimport type {\n OperationOperatorType,\n TinyCloudPosture,\n} from \"./contract.js\";\nimport { readAuthRequests, updateProfileStore } from \"./state.js\";\n\nexport { evaluateAuthority } from \"./authority.js\";\n\nconst THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1_000;\n\n/** The shared wire schema for SDK PermissionEntry values, including signed ReCap caveats. */\nexport const PermissionEntrySchema = z.object({\n service: z.string().min(1),\n space: z.string().min(1).optional(),\n path: z.string(),\n actions: z.array(z.string().min(1)).min(1),\n caveats: z.array(z.record(z.unknown())).optional(),\n skipPrefix: z.boolean().optional(),\n expiry: z.string().min(1).optional(),\n description: z.string().optional(),\n}).strict();\n\nconst CommandSchema = z.object({\n argv: z.array(z.string()).min(1),\n cwd: z.string().min(1),\n}).strict();\n\nconst LegacyPermissionRequestArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.request\"),\n version: z.literal(1),\n requestId: z.string(),\n sessionDid: z.string().min(1),\n requested: z.array(PermissionEntrySchema),\n requestedExpiry: z.union([z.string(), z.number().finite()]).optional(),\n}).strict();\n\nconst PortableDelegationSchema: z.ZodType<Record<string, unknown>> = z.lazy(() => z.object({\n cid: z.string().min(1),\n spaceId: z.string().min(1),\n path: z.string(),\n actions: z.array(z.string().min(1)).min(1),\n delegateDID: z.string().min(1),\n ownerAddress: z.string().min(1),\n chainId: z.number().int().positive(),\n expiry: z.union([z.string().datetime({ offset: true }), z.date()]),\n delegationHeader: z.object({ Authorization: z.string().min(1) }).strict(),\n host: z.string().min(1).optional(),\n disableSubDelegation: z.boolean().optional(),\n publicDelegation: PortableDelegationSchema.optional(),\n resources: z.array(PermissionEntrySchema).optional(),\n}).passthrough());\n\n/** Canonical wire-format v1 request retained for CLI and OpenKey compatibility. */\nexport const PermissionRequestArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.request\"),\n version: z.literal(1),\n requestId: z.string().min(1),\n createdAt: z.string().datetime({ offset: true }),\n profile: z.string().min(1),\n posture: z.enum([\"owner-openkey\", \"delegate-session\", \"local-owner-key\", \"unauthenticated\"]),\n operatorType: z.enum([\"human\", \"agent\"]),\n host: z.string().min(1),\n sessionDid: z.string().min(1),\n ownerDid: z.string().min(1).optional(),\n spaceId: z.string().min(1).optional(),\n requestedExpiry: z.union([z.string().min(1), z.number().finite()]).optional(),\n requested: z.array(PermissionEntrySchema),\n command: CommandSchema.optional(),\n}).strict();\n\n/** Canonical structured v1 delegation import accepted by the auth operation. */\nexport const DelegationImportArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.delegation\"),\n version: z.literal(1),\n requestId: z.string().min(1),\n delegationCid: z.string().min(1).optional(),\n delegation: PortableDelegationSchema,\n // This field is presentation metadata only. A later import operation obtains\n // effective permissions from validated, installed delegation authority.\n permissions: z.array(PermissionEntrySchema).optional(),\n expiry: z.string().datetime({ offset: true }).optional(),\n prompted: z.boolean().optional(),\n}).strict();\n\n/**\n * The stored request an imported delegation was checked against, persisted\n * with the delegation. Its fields are exactly the request artifact's, so\n * replay accepts every binding import can write.\n */\nexport const DelegationRequestBindingSchema = PermissionRequestArtifactSchema\n .pick({ requestId: true, requested: true })\n .strict();\nexport type DelegationRequestBinding = z.infer<typeof DelegationRequestBindingSchema>;\n\nexport type PermissionRequestArtifact = z.infer<typeof PermissionRequestArtifactSchema>;\nexport type DelegationImportArtifact = z.infer<typeof DelegationImportArtifactSchema>;\n/** The minimal public node-sdk request shape accepted by the legacy reader. */\nexport type LegacyPermissionRequestArtifact = z.infer<typeof LegacyPermissionRequestArtifactSchema>;\nexport type ArtifactClock = () => Date;\nexport type RequestIdSource = () => string;\n\n/** Invocation-owned values used to safely complete a legacy request record. */\nexport interface LegacyRequestContext {\n readonly profile: string;\n readonly host: string;\n readonly sessionDid: string;\n readonly posture: TinyCloudPosture;\n readonly operatorType: OperationOperatorType;\n readonly ownerDid?: string;\n readonly spaceId?: string;\n readonly now?: Date;\n}\n\nexport interface PermissionRequestIdentityInput {\n readonly profile: string;\n readonly sessionDid: string;\n readonly host: string;\n readonly missing: readonly PermissionEntry[];\n}\n\nexport interface BuildPermissionRequestArtifactInput extends PermissionRequestIdentityInput {\n readonly posture: TinyCloudPosture;\n readonly operatorType: OperationOperatorType;\n readonly ownerDid?: string;\n readonly spaceId?: string;\n readonly requestedExpiry?: string | number;\n readonly command?: { readonly argv: readonly string[]; readonly cwd: string };\n readonly now?: ArtifactClock;\n readonly createRequestId?: RequestIdSource;\n}\n\nexport interface CreateOrReusePermissionRequestInput extends BuildPermissionRequestArtifactInput {\n readonly granted: readonly PermissionEntry[];\n /** Owner-aware identity resolver used by registered operation callers. */\n readonly resolveSpace?: OperationSpaceResolver;\n readonly replace?: boolean;\n}\n\nexport type PermissionRequestResolution =\n | Readonly<{ status: \"satisfied\"; reused: false }>\n | Readonly<{ status: \"created\"; reused: boolean; request: PermissionRequestArtifact }>;\n\n/** Parses a request artifact without accepting a newer wire format as v1. */\nexport function validatePermissionRequestArtifact(value: unknown): PermissionRequestArtifact {\n return PermissionRequestArtifactSchema.parse(value);\n}\n\n/** Parses a structured active-session import artifact without accepting a newer wire format as v1. */\nexport function validateDelegationImportArtifact(value: unknown): DelegationImportArtifact {\n return DelegationImportArtifactSchema.parse(value);\n}\n\nexport function isPermissionRequestArtifact(value: unknown): value is PermissionRequestArtifact {\n return PermissionRequestArtifactSchema.safeParse(value).success;\n}\n\nexport function isDelegationImportArtifact(value: unknown): value is DelegationImportArtifact {\n return DelegationImportArtifactSchema.safeParse(value).success;\n}\n\nfunction normalizeLegacyPermissionRequest(\n value: LegacyPermissionRequestArtifact,\n context: LegacyRequestContext,\n): PermissionRequestArtifact {\n if (principal(value.sessionDid) !== principal(context.sessionDid)) {\n throw new TypeError(\"Stored authority request belongs to a different session.\");\n }\n const createdAt = context.now ?? new Date();\n if (Number.isNaN(createdAt.getTime())) {\n throw new TypeError(\"The legacy authority request has no usable creation time.\");\n }\n return {\n kind: \"tinycloud.auth.request\",\n version: 1,\n requestId: value.requestId,\n createdAt: createdAt.toISOString(),\n profile: context.profile,\n posture: context.posture,\n operatorType: context.operatorType,\n host: context.host,\n sessionDid: context.sessionDid,\n ...(context.ownerDid === undefined ? {} : { ownerDid: context.ownerDid }),\n ...(context.spaceId === undefined ? {} : { spaceId: context.spaceId }),\n ...(value.requestedExpiry === undefined ? {} : { requestedExpiry: value.requestedExpiry }),\n requested: canonicalizeCapabilities(value.requested),\n } as PermissionRequestArtifact;\n}\n\nfunction principal(value: string): string {\n return value.split(\"#\", 1)[0]!;\n}\n\n/**\n * Stable exact identity used only for request reuse. It binds a request to its\n * selected profile, active session DID, host, and canonical missing subset.\n */\nexport function createPermissionRequestIdentity(input: PermissionRequestIdentityInput): string {\n return JSON.stringify({\n profile: input.profile,\n sessionDid: input.sessionDid,\n host: input.host,\n missing: canonicalizeCapabilities(input.missing),\n });\n}\n\n/** Builds an on-disk-compatible v1 record. Omitted values stay omitted. */\nexport function buildPermissionRequestArtifact(\n input: BuildPermissionRequestArtifactInput,\n): PermissionRequestArtifact {\n const now = input.now ?? (() => new Date());\n const createdAt = now();\n if (Number.isNaN(createdAt.getTime())) throw new TypeError(\"The artifact clock returned an invalid date.\");\n const requested = canonicalizeCapabilities(input.missing);\n if (requested.length === 0) throw new TypeError(\"Permission requests require at least one missing capability.\");\n\n return validatePermissionRequestArtifact({\n kind: \"tinycloud.auth.request\",\n version: 1,\n requestId: input.createRequestId?.() ?? defaultRequestId(createdAt),\n createdAt: createdAt.toISOString(),\n profile: input.profile,\n posture: input.posture,\n operatorType: input.operatorType,\n host: input.host,\n sessionDid: input.sessionDid,\n ...(input.ownerDid !== undefined ? { ownerDid: input.ownerDid } : {}),\n ...(input.spaceId !== undefined ? { spaceId: input.spaceId } : {}),\n ...(input.requestedExpiry !== undefined ? { requestedExpiry: input.requestedExpiry } : {}),\n requested,\n ...(input.command !== undefined\n ? { command: { argv: [...input.command.argv], cwd: input.command.cwd } }\n : {}),\n });\n}\n\n/** Reads only valid canonical v1 records and refuses malformed stored artifacts. */\nexport async function listPermissionRequests(\n profile: string,\n context?: LegacyRequestContext,\n): Promise<PermissionRequestArtifact[]> {\n const records: PermissionRequestArtifact[] = [];\n for (const value of await readAuthRequests<unknown>(profile)) {\n const canonical = PermissionRequestArtifactSchema.safeParse(value);\n if (canonical.success) {\n if (context !== undefined && principal(canonical.data.sessionDid) !== principal(context.sessionDid)) {\n continue;\n }\n records.push(canonical.data);\n continue;\n }\n const legacy = LegacyPermissionRequestArtifactSchema.safeParse(value);\n if (!legacy.success) throw new TypeError(\"Stored authority request is malformed.\");\n if (context === undefined) {\n throw new TypeError(\"Legacy authority requests require the selected invocation context.\");\n }\n if (principal(legacy.data.sessionDid) !== principal(context.sessionDid)) continue;\n records.push(normalizeLegacyPermissionRequest(legacy.data, context));\n }\n return records;\n}\n\nexport async function findPermissionRequest(\n profile: string,\n requestId: string,\n identity: Pick<PermissionRequestIdentityInput, \"sessionDid\" | \"host\"> &\n Partial<Omit<LegacyRequestContext, \"profile\" | \"host\" | \"sessionDid\">>,\n): Promise<PermissionRequestArtifact | null> {\n const records = await listPermissionRequests(profile, {\n profile,\n host: identity.host,\n sessionDid: identity.sessionDid,\n posture: identity.posture ?? \"delegate-session\",\n operatorType: identity.operatorType ?? \"human\",\n ...(identity.ownerDid === undefined ? {} : { ownerDid: identity.ownerDid }),\n ...(identity.spaceId === undefined ? {} : { spaceId: identity.spaceId }),\n });\n return records.find((record) =>\n record.requestId === requestId &&\n record.sessionDid === identity.sessionDid &&\n record.host === identity.host,\n ) ?? null;\n}\n\n/**\n * Atomically returns the newest identical unresolved request, or writes a new\n * v1 record. Retention, stale-session pruning, covered-record pruning, and\n * partial-grant supersession all happen in the same existing profile lock.\n */\nexport async function createOrReusePermissionRequest(\n input: CreateOrReusePermissionRequestInput,\n): Promise<PermissionRequestResolution> {\n // Registered operations already computed this exact missing set during\n // canonical preflight. Do not recompute it with the legacy global matcher:\n // that matcher intentionally treats same-named short/full spaces as equal.\n const missing = input.resolveSpace === undefined\n ? evaluateAuthority(input.granted, input.missing).missing\n : canonicalizeCapabilities(input.missing);\n const now = input.now ?? (() => new Date());\n const observedNow = now();\n if (Number.isNaN(observedNow.getTime())) throw new TypeError(\"The artifact clock returned an invalid date.\");\n\n return updateProfileStore<unknown, PermissionRequestResolution>(\n input.profile,\n \"auth-requests\",\n (rawRecords) => {\n const records: PermissionRequestArtifact[] = [];\n for (const value of rawRecords) {\n const canonical = PermissionRequestArtifactSchema.safeParse(value);\n if (canonical.success) {\n if (principal(canonical.data.sessionDid) !== principal(input.sessionDid)) continue;\n records.push(canonical.data);\n continue;\n }\n const legacy = LegacyPermissionRequestArtifactSchema.safeParse(value);\n if (!legacy.success) throw new TypeError(\"Stored authority request is malformed.\");\n if (principal(legacy.data.sessionDid) !== principal(input.sessionDid)) continue;\n records.push(normalizeLegacyPermissionRequest(legacy.data, {\n profile: input.profile,\n host: input.host,\n sessionDid: input.sessionDid,\n posture: input.posture,\n operatorType: input.operatorType,\n ...(input.ownerDid === undefined ? {} : { ownerDid: input.ownerDid }),\n ...(input.spaceId === undefined ? {} : { spaceId: input.spaceId }),\n now: observedNow,\n }));\n }\n const retained = prunePermissionRequests(records, {\n profile: input.profile,\n sessionDid: input.sessionDid,\n granted: input.granted,\n resolveSpace: input.resolveSpace,\n now: observedNow,\n });\n\n if (missing.length === 0) {\n return { records: retained, result: { status: \"satisfied\", reused: false } };\n }\n\n const identity = createPermissionRequestIdentity({ ...input, missing });\n const withoutSuperseded = retained.filter((record) => !isSupersededBy(record, input, missing));\n const equivalent = newestEquivalentRequest(withoutSuperseded, identity);\n if (equivalent !== undefined && input.replace !== true) {\n return { records: withoutSuperseded, result: { status: \"created\", reused: true, request: equivalent } };\n }\n\n const next = withoutSuperseded.filter((record) =>\n input.replace !== true || permissionRequestArtifactIdentity(record) !== identity,\n );\n const request = buildPermissionRequestArtifact({ ...input, missing, now: () => observedNow });\n return {\n records: [...next, request],\n result: { status: \"created\", reused: false, request },\n };\n },\n );\n}\n\nexport interface PrunePermissionRequestsInput {\n readonly profile: string;\n readonly sessionDid: string;\n readonly granted: readonly PermissionEntry[];\n readonly resolveSpace?: OperationSpaceResolver;\n readonly now: Date;\n}\n\n/** Pure retention policy used by the locked persistence operation. */\nexport function prunePermissionRequests(\n records: readonly PermissionRequestArtifact[],\n input: PrunePermissionRequestsInput,\n): PermissionRequestArtifact[] {\n const cutoff = input.now.getTime() - THIRTY_DAYS_MS;\n return records.filter((record) => {\n const createdAt = Date.parse(record.createdAt);\n if (!Number.isFinite(createdAt) || createdAt < cutoff) return false;\n if (record.profile === input.profile && principal(record.sessionDid) !== principal(input.sessionDid)) return false;\n // Empty request arrays are historical CLI records. They carry no\n // authority, but remain readable and are retained byte-for-byte by the\n // shared format-1 writer for compatibility.\n if (record.requested.length === 0) return true;\n return !evaluateArtifactAuthority(\n input.granted,\n record.requested,\n input.resolveSpace,\n ).satisfied;\n });\n}\n\nfunction newestEquivalentRequest(\n records: readonly PermissionRequestArtifact[],\n identity: string,\n): PermissionRequestArtifact | undefined {\n let newest: PermissionRequestArtifact | undefined;\n for (const record of records) {\n if (permissionRequestArtifactIdentity(record) !== identity) continue;\n if (newest === undefined || record.createdAt >= newest.createdAt) newest = record;\n }\n return newest;\n}\n\nfunction isSupersededBy(\n record: PermissionRequestArtifact,\n input: CreateOrReusePermissionRequestInput,\n missing: readonly PermissionEntry[],\n): boolean {\n if (\n record.profile !== input.profile ||\n record.sessionDid !== input.sessionDid ||\n record.host !== input.host\n ) {\n return false;\n }\n const remaining = evaluateArtifactAuthority(\n input.granted,\n record.requested,\n input.resolveSpace,\n ).missing;\n return remaining.length > 0 &&\n permissionRequestArtifactIdentity(record) !==\n createPermissionRequestIdentity({ ...input, missing }) &&\n createPermissionRequestIdentity({ ...input, missing: remaining }) ===\n createPermissionRequestIdentity({ ...input, missing });\n}\n\nfunction permissionRequestArtifactIdentity(record: PermissionRequestArtifact): string {\n return createPermissionRequestIdentity({\n profile: record.profile,\n sessionDid: record.sessionDid,\n host: record.host,\n missing: record.requested,\n });\n}\n\nfunction evaluateArtifactAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n) {\n return resolveSpace === undefined\n ? evaluateAuthority(granted, required)\n : evaluateOperationAuthority(granted, required, resolveSpace);\n}\n\nfunction defaultRequestId(now: Date): string {\n return `req_${now.getTime().toString(36)}_${randomUUID().replace(/-/g, \"\")}`;\n}\n","import {\n canonicalizeRecapCaveats,\n isCapabilitySubset,\n type PermissionEntry,\n} from \"@tinycloud/sdk-core\";\n\n/**\n * A capability in the canonical form persisted in a v1 request artifact.\n *\n * The SDK remains the semantic authority for containment. This module only\n * establishes deterministic exact identity for persistence and display.\n */\nexport type CanonicalPermissionEntry = Readonly<PermissionEntry>;\n\nexport interface AuthorityEvaluation {\n readonly satisfied: boolean;\n readonly missing: readonly CanonicalPermissionEntry[];\n}\n\n/**\n * Operation-owned space resolution. The SDK's general capability evaluator\n * intentionally preserves its historical short/full-space compatibility; the\n * operation kernel supplies this narrower resolver when a space identifies a\n * remote owner's resource.\n */\nexport type OperationSpaceResolver = (space: string) => string;\n\nconst EXACT_PERMISSION_KEYS = new Set([\n \"service\",\n \"space\",\n \"path\",\n \"actions\",\n \"skipPrefix\",\n \"expiry\",\n \"description\",\n]);\n\n/**\n * Validate requirements that can be represented without semantic broadening in\n * a v1 artifact. Caveated authority is intentionally rejected: the v1 request\n * schema and grant path cannot preserve those signed branches end-to-end.\n */\nexport function validateExactCapabilities(value: unknown): PermissionEntry[] | undefined {\n if (!Array.isArray(value)) return undefined;\n\n const permissions: PermissionEntry[] = [];\n for (const candidate of value) {\n if (!isExactPermission(candidate)) return undefined;\n permissions.push(candidate);\n }\n return canonicalizeCapabilities(permissions);\n}\n\n/**\n * Evaluates required authority with the SDK's public subset primitive.\n *\n * In particular, this intentionally does not implement matching rules or\n * manufacture wildcards. A wildcard can cover a requirement only when it was\n * already present in the supplied granted authority and the SDK says so.\n */\nexport function evaluateAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n): AuthorityEvaluation {\n const canonicalGranted = canonicalizeCapabilities(granted);\n const canonicalRequired = canonicalizeCapabilities(required);\n const result = isCapabilitySubset(canonicalRequired, canonicalGranted);\n\n return {\n satisfied: result.subset,\n missing: canonicalizeCapabilities(result.missing),\n };\n}\n\n/**\n * Evaluate operation capabilities without allowing two owners' same-named\n * spaces to compare equal. Path and action containment still come from the\n * SDK primitive; only the operation space identity is made owner-exact.\n */\nexport function evaluateOperationAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): AuthorityEvaluation {\n const canonicalGranted = canonicalizeOperationCapabilities(granted, resolveSpace);\n const canonicalRequired = canonicalizeOperationCapabilities(required, resolveSpace);\n const missing: CanonicalPermissionEntry[] = [];\n\n for (const requested of canonicalRequired) {\n const covered = canonicalGranted.some((candidate) =>\n candidate.service === requested.service &&\n operationSpacesEqual(candidate.space, requested.space) &&\n isCapabilitySubset([requested], [candidate]).subset,\n );\n if (!covered) missing.push(requested);\n }\n\n return {\n satisfied: missing.length === 0,\n missing: canonicalizeCapabilities(missing),\n };\n}\n\n/**\n * Whether a delegation's signed capabilities stay inside the stored request\n * it answers. `tinycloud.auth.import` and runtime replay share this check, so\n * a delegation import accepts is never one replay discards.\n */\nexport function delegationWithinRequest(\n requested: readonly PermissionEntry[],\n effective: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): boolean {\n return requested.length > 0 &&\n evaluateOperationAuthority(requested, canonicalizeCapabilities(effective), resolveSpace).satisfied;\n}\n\n/**\n * Validate a runtime hint as an exact member of the registered plan. Runtime\n * nodes may report the one phase that failed, but they may not introduce a\n * broader, differently-owned, caveated, or otherwise new capability.\n */\nexport function isExactCapabilityMemberSubset(\n hinted: readonly PermissionEntry[],\n planned: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): boolean {\n const canonicalHinted = canonicalizeOperationCapabilities(hinted, resolveSpace);\n const canonicalPlanned = canonicalizeOperationCapabilities(planned, resolveSpace);\n return canonicalHinted.length > 0 && canonicalHinted.every((hint) => canonicalPlanned.some((plan) =>\n JSON.stringify(hint) === JSON.stringify(plan),\n ));\n}\n\n/** Canonical identity used by operation preflight, hints, and artifacts. */\nexport function canonicalizeOperationCapabilities(\n permissions: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): CanonicalPermissionEntry[] {\n return canonicalizeCapabilities(permissions.map((permission) => {\n const canonicalPath = canonicalizeOperationPath(permission);\n if (permission.space === undefined || resolveSpace === undefined) {\n return canonicalPath;\n }\n try {\n return { ...canonicalPath, space: resolveSpace(permission.space) };\n } catch {\n // An unresolvable identity remains a non-matching literal. It must never\n // be widened to a wildcard or to another authenticated owner.\n return canonicalPath;\n }\n }));\n}\n\nfunction canonicalizeOperationPath(permission: PermissionEntry): PermissionEntry {\n if (permission.service !== \"tinycloud.encryption\") return permission;\n const match = permission.path.match(\n /^(urn:tinycloud:encryption:did:pkh:eip155:\\d+:)(0x[0-9a-fA-F]{40})(:.*)$/,\n );\n if (!match) return permission;\n return { ...permission, path: `${match[1]}${match[2]!.toLowerCase()}${match[3]}` };\n}\n\nfunction operationSpacesEqual(\n granted: string | undefined,\n requested: string | undefined,\n): boolean {\n return granted === requested;\n}\n\n/** Returns a stable exact identity for one capability without containment. */\nexport function permissionIdentity(permission: PermissionEntry): string {\n return JSON.stringify(canonicalizeCapability(permission));\n}\n\n/**\n * Sorts actions and entries and removes only exactly-identical capabilities.\n * It does not coalesce paths, services, spaces, or actions into a broader\n * capability.\n */\nexport function canonicalizeCapabilities(\n permissions: readonly PermissionEntry[],\n): CanonicalPermissionEntry[] {\n const byIdentity = new Map<string, CanonicalPermissionEntry>();\n for (const permission of permissions) {\n const canonical = canonicalizeCapability(permission);\n byIdentity.set(permissionIdentityFromCanonical(canonical), canonical);\n }\n\n return [...byIdentity.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([, permission]) => permission);\n}\n\nfunction canonicalizeCapability(permission: PermissionEntry): CanonicalPermissionEntry {\n const actions = [...new Set(permission.actions)].sort((left, right) => left.localeCompare(right));\n return {\n service: permission.service,\n ...(permission.space !== undefined ? { space: permission.space } : {}),\n path: permission.path,\n actions,\n ...(permission.skipPrefix !== undefined ? { skipPrefix: permission.skipPrefix } : {}),\n ...(permission.expiry !== undefined ? { expiry: permission.expiry } : {}),\n ...(permission.description !== undefined ? { description: permission.description } : {}),\n ...(permission.caveats === undefined\n ? {}\n : { caveats: canonicalizeCaveats(permission.caveats) }),\n };\n}\n\nfunction permissionIdentityFromCanonical(permission: CanonicalPermissionEntry): string {\n return JSON.stringify({\n service: permission.service,\n ...(permission.space !== undefined ? { space: permission.space } : {}),\n path: permission.path,\n actions: permission.actions,\n ...(permission.skipPrefix !== undefined ? { skipPrefix: permission.skipPrefix } : {}),\n ...(permission.expiry !== undefined ? { expiry: permission.expiry } : {}),\n ...(permission.description !== undefined ? { description: permission.description } : {}),\n ...(permission.caveats === undefined ? {} : { caveats: permission.caveats }),\n });\n}\n\nfunction isExactPermission(value: unknown): value is PermissionEntry {\n if (\n !isExactRecord(value) ||\n Object.getOwnPropertyNames(value).some((key) => !EXACT_PERMISSION_KEYS.has(key)) ||\n Object.getOwnPropertySymbols(value).length > 0\n ) {\n return false;\n }\n if (\n !isExactText(value.service) ||\n !isExactPath(value.path, value.actions) ||\n (value.space !== undefined && !isExactText(value.space)) ||\n !Array.isArray(value.actions) ||\n value.actions.length === 0 ||\n !value.actions.every(isExactText) ||\n new Set(value.actions).size !== value.actions.length ||\n value.skipPrefix === true ||\n (value.skipPrefix !== undefined && value.skipPrefix !== false) ||\n (value.expiry !== undefined && !isExactText(value.expiry)) ||\n (value.description !== undefined && !isExactText(value.description))\n ) {\n return false;\n }\n return !(\"caveats\" in value);\n}\n\nfunction isExactRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isExactText(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0 && !value.includes(\"*\");\n}\n\nfunction isExactPath(value: unknown, actions: unknown): value is string {\n if (typeof value !== \"string\" || value === \"/\" || value.includes(\"*\")) return false;\n if (value === \"\" || value.endsWith(\"/\")) {\n return Array.isArray(actions) && actions.includes(\"tinycloud.kv/list\");\n }\n return true;\n}\n\nfunction canonicalizeCaveats(\n caveats: readonly Record<string, unknown>[],\n): Record<string, unknown>[] {\n return [...caveats]\n .map((caveat) => ({\n identity: canonicalizeRecapCaveats([caveat]),\n value: JSON.parse(JSON.stringify(caveat)) as Record<string, unknown>,\n }))\n .sort((left, right) => left.identity.localeCompare(right.identity))\n .map(({ value }) => value);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n chmod,\n link,\n mkdir,\n open,\n readFile,\n readdir,\n rename,\n rmdir,\n rm,\n stat,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, isAbsolute, join, relative, resolve } from \"node:path\";\n\nconst DEFAULT_PROFILE = \"default\";\nconst DEFAULT_LOCK_TIMEOUT_MS = 2_000;\nconst DEFAULT_LOCK_RETRY_MS = 25;\nconst DEFAULT_STALE_LOCK_MS = 30_000;\nconst TEST_LOCK_CONTENTION_SIGNAL_PATH = \"TC_TEST_PROFILE_LOCK_CONTENTION_SIGNAL_PATH\";\n// Profile state holds keys, sessions and delegations: owner-only access.\nconst PRIVATE_FILE_MODE = 0o600;\nconst PRIVATE_DIR_MODE = 0o700;\nconst TEST_LOCK_RECOVERY_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_RECOVERY_BARRIER_DIR\";\nconst TEST_LOCK_OWNERLESS_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_OWNERLESS_BARRIER_DIR\";\nconst TEST_LOCK_PUBLISH_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_PUBLISH_BARRIER_DIR\";\nconst TEST_LOCK_RELEASE_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_RELEASE_BARRIER_DIR\";\nconst TEST_LOCK_CLAIM_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_CLAIM_BARRIER_DIR\";\nconst TEST_LOCK_CLAIMED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_CLAIMED_BARRIER_DIR\";\nconst TEST_LOCK_VERIFIED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_VERIFIED_BARRIER_DIR\";\nconst TEST_LOCK_MOVED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_MOVED_BARRIER_DIR\";\nconst TEST_LOCK_TURN_PUBLISH_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_PUBLISH_BARRIER_DIR\";\nconst TEST_LOCK_TURN_SETTLE_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_SETTLE_BARRIER_DIR\";\nconst TEST_LOCK_TURN_COLLECT_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_COLLECT_BARRIER_DIR\";\n/** One acquisition of a profile lock; `active` is cleared before release. */\ninterface HeldProfileLock {\n readonly lockPath: string;\n /** The number of the turn this acquisition holds (see acquireTurn). */\n readonly turnSlot: number;\n /** A deletion of the profile ran while this acquisition waited for the lock. */\n readonly deletedWhileWaiting: boolean;\n active: boolean;\n}\n/**\n * Async context shared by every copy of this module in the process. Each\n * bundled operations entry point (`state`, `delegation-binding`, the root)\n * carries its own copy, so module-level context would make lock reentrancy and\n * the invocation state root stop at an entry-point boundary.\n * Each key is independently versioned for the shape and meaning of the\n * value it stores. Held-lock entries gained `turnSlot` and\n * `deletedWhileWaiting` in TC-633, so `.v2` must not read TC-602's `.v1`\n * entries. The invocation root remains a string path with unchanged\n * semantics and stays `.v1`. Relinquished turn tokens use a separate\n * versioned process-wide key: only an explicitly given-up turn of this PID\n * may be settled across separately bundled entry points.\n */\nfunction processWideContext<T>(key: string): AsyncLocalStorage<T> {\n const registry = globalThis as unknown as Record<symbol, AsyncLocalStorage<T> | undefined>;\n return registry[Symbol.for(key)] ??= new AsyncLocalStorage<T>();\n}\nconst invocationStateRoot = processWideContext<string>(\"tinycloud.operations.invocationStateRoot.v1\");\n/** Profile lock acquisitions held by the current async call chain (see withProfileLock). */\nconst heldProfileLocks = processWideContext<readonly HeldProfileLock[]>(\"tinycloud.operations.heldProfileLocks.v2\");\n\nexport type ProfileStoreName =\n | \"session\"\n | \"additional-delegations\"\n | \"auth-requests\";\n\nexport interface StoreMetadata {\n formatVersion: number;\n}\n\nexport interface ProfileStoreContents<T> {\n formatVersion: number;\n records: T[];\n}\n\nexport interface ProfileLockOptions {\n timeoutMs?: number;\n retryMs?: number;\n staleAfterMs?: number;\n /**\n * Lock only a profile that exists (its `profile.json` is present), and\n * never create its directory: a missing or deleted profile is refused with\n * ProfileDeletedError, before and after waiting for the lock. For writers\n * of state that lives inside an existing profile (replicas).\n */\n requireProfile?: boolean;\n}\n\nexport class ProfileLockTimeoutError extends Error {\n readonly code = \"PROFILE_LOCK_TIMEOUT\";\n\n /** `detail` names the cause when it is not simply another process holding the lock. */\n constructor(profile: string, timeoutMs: number, detail?: string) {\n super(`Timed out waiting for the profile lock for \"${profile}\" after ${timeoutMs}ms.${detail ? ` ${detail}` : \"\"}`);\n this.name = \"ProfileLockTimeoutError\";\n }\n}\n\n/**\n * A store write that waited for the profile lock while a deletion of that\n * profile held it, and found no profile settings once it got the lock. The\n * write is refused rather than recreating a profile with only a session or\n * store in it.\n */\nexport class ProfileDeletedError extends Error {\n readonly code = \"PROFILE_NOT_FOUND\";\n\n constructor(profile: string) {\n super(`Profile \"${profile}\" was deleted while this change waited for its lock, so the change was not written.`);\n this.name = \"ProfileDeletedError\";\n }\n}\n\n/**\n * The CLI's delegated-secret path treats TC_HOME as a home directory, rather\n * than a direct TinyCloud directory. Keep the shared store on that convention.\n */\nexport function tinycloudHomePath(): string {\n const home = invocationStateRoot.getStore() ??\n process.env.TC_HOME ??\n process.env.HOME ??\n process.env.USERPROFILE ??\n homedir();\n return join(home, \".tinycloud\");\n}\n\n/** Run one operation against an isolated TinyCloud home directory. */\nexport function withTinyCloudStateRoot<T>(\n stateRoot: string | undefined,\n action: () => Promise<T>,\n): Promise<T> {\n if (stateRoot === undefined) return action();\n if (!isAbsolute(stateRoot) || stateRoot.includes(\"\\0\")) {\n throw new TypeError(\"The TinyCloud state root must be an absolute path.\");\n }\n return invocationStateRoot.run(resolve(stateRoot), action);\n}\n\nexport function tinycloudConfigPath(): string {\n return join(tinycloudHomePath(), \"config.json\");\n}\n\nexport function profilesPath(): string {\n return join(tinycloudHomePath(), \"profiles\");\n}\n\nexport function profilePath(profile: string): string {\n return join(profilesPath(), validateProfileName(profile));\n}\n\nexport function profileConfigPath(profile: string): string {\n return join(profilePath(profile), \"profile.json\");\n}\n\nexport function sessionPath(profile: string): string {\n return profileStorePath(profile, \"session\");\n}\n\nexport function additionalDelegationsPath(profile: string): string {\n return profileStorePath(profile, \"additional-delegations\");\n}\n\nexport function authRequestsPath(profile: string): string {\n return profileStorePath(profile, \"auth-requests\");\n}\n\nexport function profileStorePath(profile: string, store: ProfileStoreName): string {\n return join(profilePath(profile), `${store}.json`);\n}\n\n/** The format record is deliberately separate from each legacy JSON payload. */\nexport function profileStoreMetadataPath(profile: string, store: ProfileStoreName): string {\n return `${profileStorePath(profile, store)}.metadata.json`;\n}\n\nexport function profileLockPath(profile: string): string {\n return join(profilePath(profile), \".lock\");\n}\n\nexport function profileLockMetadataPath(profile: string): string {\n return join(profileLockPath(profile), \"owner.json\");\n}\n\n/**\n * The turn lock of a profile (see acquireTurn). It lives outside the profile\n * directory, so neither a profile deletion nor an older release's cleanup\n * removes it.\n */\nexport function profileTurnLockPath(profile: string): string {\n return join(tinycloudHomePath(), \"profile-locks\", validateProfileName(profile));\n}\n\n/**\n * Reads JSON without hiding malformed or inaccessible files. A missing file is\n * the only condition represented as null.\n */\nexport async function readJson<T>(filePath: string): Promise<T | null> {\n try {\n return JSON.parse(await readFile(filePath, \"utf8\")) as T;\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return null;\n throw error;\n }\n}\n\n/**\n * Writes the same pretty-printed, trailing-newline JSON shape used by the CLI,\n * but publishes it with an atomic rename from the same directory.\n */\nexport async function writeJsonAtomic(filePath: string, value: unknown): Promise<void> {\n await replaceJson(filePath, value, false);\n}\n\n/**\n * writeJsonAtomic; `durable` also flushes the data to disk before the rename,\n * so a crash or power loss leaves the old record or the new one, never a\n * truncated one (for lock records, whose damage would stop every writer).\n */\nasync function replaceJson(filePath: string, value: unknown, durable: boolean): Promise<void> {\n const directory = dirname(filePath);\n const temporaryPath = join(\n directory,\n `.${basename(filePath)}.${process.pid}.${randomUUID()}.tmp`,\n );\n const contents = `${JSON.stringify(value, null, 2)}\\n`;\n\n await mkdir(directory, { recursive: true, mode: PRIVATE_DIR_MODE });\n try {\n if (durable) await writeFileDurably(temporaryPath, contents);\n else await writeFile(temporaryPath, contents, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE });\n await rename(temporaryPath, filePath);\n } catch (error) {\n await rm(temporaryPath, { force: true }).catch(() => undefined);\n throw error;\n }\n}\n\n/** Creates a file (exclusively) and, when it has contents, flushes them to disk. */\nasync function writeFileDurably(path: string, contents: string): Promise<void> {\n const handle = await open(path, \"wx\", PRIVATE_FILE_MODE);\n try {\n if (contents) {\n await handle.writeFile(contents, \"utf8\");\n await handle.datasync();\n }\n } finally {\n await handle.close();\n }\n}\n\nexport async function readProfile<T extends object = Record<string, unknown>>(\n profile: string,\n): Promise<T | null> {\n return readJson<T>(profileConfigPath(profile));\n}\n\nexport async function readSession<T extends object = Record<string, unknown>>(\n profile: string,\n): Promise<T | null> {\n await readStoreMetadata(profile, \"session\");\n return readJson<T>(sessionPath(profile));\n}\n\nexport async function readAdditionalDelegations<T = Record<string, unknown>>(\n profile: string,\n): Promise<T[]> {\n return (await readProfileStore<T>(profile, \"additional-delegations\")).records;\n}\n\nexport async function readAuthRequests<T = Record<string, unknown>>(\n profile: string,\n): Promise<T[]> {\n return (await readProfileStore<T>(profile, \"auth-requests\")).records;\n}\n\nexport async function readStoreMetadata(\n profile: string,\n store: ProfileStoreName,\n): Promise<StoreMetadata> {\n const metadata = await readJson<StoreMetadata>(profileStoreMetadataPath(profile, store));\n if (metadata === null) return { formatVersion: 1 };\n if (\n typeof metadata !== \"object\" ||\n metadata.formatVersion !== 1\n ) {\n throw new TypeError(`Unsupported store format for \"${store}\".`);\n }\n return metadata;\n}\n\nexport async function readProfileStore<T>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n): Promise<ProfileStoreContents<T>> {\n const [metadata, raw] = await Promise.all([\n readStoreMetadata(profile, store),\n readJson<unknown>(profileStorePath(profile, store)),\n ]);\n return {\n formatVersion: metadata.formatVersion,\n records: Array.isArray(raw) ? raw as T[] : [],\n };\n}\n\n/**\n * Runs a small critical section under the one lock shared by all profile\n * stores (see acquireProfileLock). Lock release verifies its ownership token\n * before removing the exact metadata instance it acquired.\n *\n * Reentrant within one async call chain: a critical section that already\n * holds a profile's lock (for example a login's compare-and-commit) can call\n * store writers that take the same lock without deadlocking. Ownership is\n * keyed by the resolved lock path (so switching state roots inside a lock\n * still takes the other root's lock) and lasts exactly as long as the\n * acquisition: it is revoked before release, so work deferred past the\n * critical section waits for the lock like any other caller.\n */\nexport async function withProfileLock<T>(\n profile: string,\n action: () => Promise<T>,\n options: ProfileLockOptions = {},\n): Promise<T> {\n const normalizedProfile = validateProfileName(profile);\n const lockPath = profileLockPath(normalizedProfile);\n const held = (heldProfileLocks.getStore() ?? []).filter((ownership) => ownership.active);\n if (held.some((ownership) => ownership.lockPath === lockPath)) return action();\n const acquired = await acquireProfileLock(normalizedProfile, options);\n const ownership: HeldProfileLock = {\n lockPath,\n turnSlot: acquired.turnSlot,\n deletedWhileWaiting: acquired.deletedWhileWaiting,\n active: true,\n };\n try {\n return await heldProfileLocks.run([...held, ownership], action);\n } finally {\n ownership.active = false;\n await acquired.release();\n // Taking the lock recreated the deleted profile's directory; remove it\n // again unless something was written into it (rmdir needs it empty).\n if (acquired.deletedWhileWaiting) await rmdir(profilePath(normalizedProfile)).catch(() => undefined);\n }\n}\n\n/**\n * Records, inside a profile deletion's critical section and after its files\n * are gone, that the profile was deleted, with the number of the deleting\n * turn. A store write whose wait overlapped that turn (it arrived before the\n * deletion released the lock, whether before or after this record) then\n * refuses (ProfileDeletedError) instead of recreating a profile with only a\n * session or store in it. The caller must hold the profile's lock.\n */\nexport async function recordProfileDeletion(profile: string): Promise<void> {\n const lockPath = profileLockPath(profile);\n const ownership = (heldProfileLocks.getStore() ?? []).find((candidate) => candidate.active && candidate.lockPath === lockPath);\n if (!ownership) throw new Error(`Recording the deletion of profile \"${profile}\" requires holding its lock.`);\n await replaceJson(join(profileTurnLockPath(profile), \"deleted.json\"), { slot: ownership.turnSlot }, true);\n}\n\n/**\n * Refuses a write that would recreate a profile deleted while this critical\n * section waited for the lock (ProfileDeletedError). Every writer of profile\n * state other than the profile settings themselves calls this inside its\n * critical section, before writing. The caller must hold the profile's lock.\n */\nexport async function refuseWriteToDeletedProfile(profile: string): Promise<void> {\n const lockPath = profileLockPath(profile);\n const ownership = (heldProfileLocks.getStore() ?? []).find((candidate) => candidate.active && candidate.lockPath === lockPath);\n if (!ownership?.deletedWhileWaiting) return;\n // Recreated meanwhile (or by this critical section): writing is fine.\n if (await exists(profileConfigPath(profile))) return;\n throw new ProfileDeletedError(profile);\n}\n\n/**\n * Appends a record or replaces the existing record with the supplied explicit\n * key. The extractor is supplied by the owning store so state.ts never needs\n * to know permission-request or delegation record shapes.\n */\nexport async function upsertProfileRecord<T>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n key: string,\n record: T,\n getKey: (candidate: T) => string | undefined,\n options: ProfileLockOptions = {},\n): Promise<T[]> {\n if (!key) throw new TypeError(\"A non-empty record key is required.\");\n\n return withProfileLock(profile, async () => {\n await refuseWriteToDeletedProfile(profile);\n const current = (await readProfileStore<T>(profile, store)).records;\n const next = current.filter((candidate) => getKey(candidate) !== key);\n next.push(record);\n await writeJsonAtomic(profileStorePath(profile, store), next);\n await writeFormatOneMetadata(profile, store);\n return next;\n }, options);\n}\n\n/**\n * Performs a typed read-modify-write of a legacy array store under the one\n * per-profile lock. The payload stays an array and the sibling metadata stays\n * format 1, so existing CLI readers keep their byte/layout contract.\n */\nexport async function updateProfileStore<T, Result>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n update: (\n records: readonly T[],\n ) => Promise<{ readonly records: readonly T[]; readonly result: Result }> | {\n readonly records: readonly T[];\n readonly result: Result;\n },\n options: ProfileLockOptions = {},\n): Promise<Result> {\n return withProfileLock(\n profile,\n () => updateProfileStoreWhileLocked(profile, store, update),\n options,\n );\n}\n\n/** The caller must already own this profile's lock. */\nasync function updateProfileStoreWhileLocked<T, Result>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n update: (\n records: readonly T[],\n ) => Promise<{ readonly records: readonly T[]; readonly result: Result }> | {\n readonly records: readonly T[];\n readonly result: Result;\n },\n): Promise<Result> {\n await refuseWriteToDeletedProfile(profile);\n const current = await readProfileStore<T>(profile, store);\n const next = await update(current.records);\n await writeJsonAtomic(profileStorePath(profile, store), next.records);\n await writeFormatOneMetadata(profile, store);\n return next.result;\n}\n\nexport async function writeSession<T extends object>(\n profile: string,\n session: T,\n options: ProfileLockOptions = {},\n): Promise<void> {\n await withProfileLock(profile, async () => {\n await refuseWriteToDeletedProfile(profile);\n await readStoreMetadata(profile, \"session\");\n await writeJsonAtomic(sessionPath(profile), session);\n await writeFormatOneMetadata(profile, \"session\");\n }, options);\n}\n\nexport async function removeSession(\n profile: string,\n options: ProfileLockOptions = {},\n): Promise<void> {\n await withProfileLock(profile, async () => {\n await readStoreMetadata(profile, \"session\");\n await rm(sessionPath(profile), { force: true });\n }, options);\n}\n\nasync function writeFormatOneMetadata(profile: string, store: ProfileStoreName): Promise<void> {\n await writeJsonAtomic(profileStoreMetadataPath(profile, store), { formatVersion: 1 });\n}\n\ninterface AcquiredProfileLock {\n readonly deletedWhileWaiting: boolean;\n readonly turnSlot: number;\n release(): Promise<void>;\n}\n\ninterface LockDeadline {\n readonly startedAt: number;\n readonly timeoutMs: number;\n readonly retryMs: number;\n}\n\n/**\n * Takes a profile's lock in two layers:\n *\n * 1. The turn lock (acquireTurn), used by this release and later ones. It\n * decides nothing from elapsed time, so a process paused anywhere, for\n * any length of time, cannot let a second holder in.\n * 2. Holding a turn, the `.lock` directory every older release uses\n * (publishProfileLock), so they keep excluding this release and it them.\n * Only one process of this release at a time acquires, recovers or\n * releases `.lock`.\n *\n * Also reports whether a profile deletion (recordProfileDeletion) ran while\n * this acquisition waited.\n */\nasync function acquireProfileLock(\n profile: string,\n options: ProfileLockOptions,\n): Promise<AcquiredProfileLock> {\n const deadline: LockDeadline = {\n startedAt: Date.now(),\n timeoutMs: options.timeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS,\n retryMs: options.retryMs ?? DEFAULT_LOCK_RETRY_MS,\n };\n const staleAfterMs = options.staleAfterMs ?? DEFAULT_STALE_LOCK_MS;\n const lockPath = profileLockPath(profile);\n const turnDirectory = profileTurnLockPath(profile);\n\n const directory = profilePath(profile);\n if (options.requireProfile && !(await exists(profileConfigPath(profile)))) throw new ProfileDeletedError(profile);\n if (!options.requireProfile) await mkdir(directory, { recursive: true, mode: PRIVATE_DIR_MODE });\n await mkdir(dirname(turnDirectory), { recursive: true, mode: PRIVATE_DIR_MODE });\n // Every store write takes this lock: tighten the tree older releases\n // created 0775 before writing sessions or delegations into it.\n for (const path of [tinycloudHomePath(), profilesPath(), directory]) {\n await chmod(path, PRIVATE_DIR_MODE).catch((error: unknown) => {\n // A profile deletion can remove the profile directory right after the\n // mkdir above; the lock attempt below recreates it 0700.\n if (path !== directory || !isErrno(error, \"ENOENT\")) throw error;\n });\n }\n\n const { turn, firstWaitedTurn } = await acquireTurn(profile, turnDirectory, deadline);\n try {\n // Holding the turn, no deletion runs: a profile present now stays until release.\n if (options.requireProfile && !(await exists(profileConfigPath(profile)))) {\n // A deletion that finished while this waited could not remove the\n // directory if a lock was held then; remove it if empty.\n await rmdir(directory).catch(() => undefined);\n throw new ProfileDeletedError(profile);\n }\n // An unreadable deletion record is ignored rather than failing every\n // acquisition; it is written durably, so only damage makes it so.\n const deletion = await readJson<{ slot?: unknown }>(join(turnDirectory, \"deleted.json\")).catch(() => null);\n const deletedWhileWaiting = typeof deletion?.slot === \"number\" && deletion.slot >= firstWaitedTurn;\n while (true) {\n const token = randomUUID();\n if (await publishProfileLock(profile, lockPath, token, options.requireProfile === true)) {\n return {\n deletedWhileWaiting,\n turnSlot: turn.slot,\n release: async () => {\n try {\n await releaseProfileLock(profile, lockPath, token);\n } finally {\n await releaseTurn(profile, turn);\n }\n },\n };\n }\n await signalTestLockContention(profile);\n if (await recoverStaleLock(profile, lockPath, staleAfterMs)) continue;\n await waitOrTimeOut(profile, deadline);\n }\n } catch (error) {\n await releaseTurn(profile, turn);\n throw error;\n }\n}\n\n/** Throws once the acquisition's time is up; `detail` explains a damaged turn lock. */\nfunction checkDeadline(profile: string, deadline: LockDeadline, detail?: string): void {\n if (Date.now() - deadline.startedAt >= deadline.timeoutMs) {\n throw new ProfileLockTimeoutError(profile, deadline.timeoutMs, detail);\n }\n}\n\n/** Sleeps one retry interval, or throws once the acquisition's time is up. */\nasync function waitOrTimeOut(profile: string, deadline: LockDeadline, detail?: string): Promise<void> {\n checkDeadline(profile, deadline, detail);\n await sleep(Math.min(deadline.retryMs, deadline.timeoutMs - (Date.now() - deadline.startedAt)));\n}\n\n/** One granted turn of the turn lock. */\ninterface Turn {\n readonly directory: string;\n readonly slot: number;\n readonly token: string;\n}\n\n/** A turn as recorded on disk. */\ninterface TurnState {\n readonly slot: number;\n readonly token: string;\n readonly pid: number;\n /** The token of the turn before it that its creator observed; null for turn 0. */\n readonly after: string | null;\n readonly held: boolean;\n readonly done: boolean;\n}\n\n/** Turn directory names: decimal turn numbers. */\nconst TURN = /^(?:0|[1-9][0-9]*)$/;\n\n/**\n * Tokens of turns this process published and then gave up (a marker write or\n * a read failed after publication): the positive evidence that lets this\n * process settle a turn of its own PID. A live process's turn that is not in\n * here is never settled by it, so a module instance that cannot see another\n * instance's set (another bundled copy of this package) waits rather than\n * settling a turn that copy still holds.\n *\n * One set per process, not per module instance: the package's entry points\n * (state, index, artifacts, cli-runtime; ESM and CJS) each bundle their own\n * copy of this module, and one process may load several. The key is\n * versioned so that a release changing what the set holds uses a new one.\n */\nconst relinquishedTurns: Set<string> =\n (globalThis as unknown as Record<symbol, Set<string> | undefined>)[Symbol.for(\"tinycloud.operations.relinquishedProfileTurns.v1\")] ??=\n new Set<string>();\n\n/** Marker writes are retried this many times, after these delays (ms), before giving up. */\nconst MARKER_RETRY_DELAYS_MS = [10, 50, 250];\n/** A given-up turn is settled in the background every second for up to five minutes. */\nconst SETTLE_RETRY_MS = 1_000;\nconst SETTLE_RETRIES = 300;\n\n/**\n * The turn lock: mutual exclusion among processes of this release that does\n * not depend on how long any of them is paused. It uses only `mkdir`,\n * `rename`, exclusive file creation, and a check that a holder's PID is gone\n * (as `.lock` recovery always has), so it needs no hard links.\n *\n * Turns are numbered directories in profileTurnLockPath(profile). Turn n has\n * `owner.json` ({ pid, createdAt, token, after }), where `after` is the token\n * of the turn n-1 its creator observed, and gains `<token>.held` when granted\n * and `<token>.done` when over. Markers name the turn's own token, so one\n * written late into a recreated directory of the same number means nothing.\n *\n * - A turn is published by renaming a fully written staging directory to\n * `n`, which fails while `n` exists (rename never replaces a non-empty\n * directory, and turn directories are never empty). The turn directory\n * itself is published the same way, with a granted, finished turn 0.\n * - A process takes turn n only after reading turn n-1 granted and done.\n * Once `n` is published it checks that turn n-1 is still the one it read\n * (same token, granted, done) and only then writes `held`; otherwise the\n * turn is void: it writes `done` alone and starts over.\n * - Turns are removed by renaming them aside: a void turn at any time, a\n * granted one only once no older turn is left and turn n+1 is granted and\n * done. The latest turn is never removed.\n *\n * Why at most one granted turn is ever not done: a removed number can be\n * published again, but turn n-1 is always removed before turn n, so a\n * process whose stale read led it to republish n finds n-1 gone or holding\n * another token, and its turn is void. A process that finds n-1 as it read\n * it published `n` for the first time, so it is the only process granted n,\n * and n-1 was done before. A turn is marked done only by its holder, or by\n * another process once the holder's PID is gone (or by its own process,\n * once it has explicitly given that turn up); a paused holder is alive.\n * A turn is voided only on definite evidence (the turn it follows is gone or\n * holds another token), never because a read failed. Nothing above is\n * decided from elapsed time.\n *\n * Returns the turn and the number of the first turn this acquisition waited\n * on: the latest turn when it first looked if that was not done yet, else\n * the next one.\n */\nasync function acquireTurn(\n profile: string,\n directory: string,\n deadline: LockDeadline,\n): Promise<{ turn: Turn; firstWaitedTurn: number }> {\n let firstWaitedTurn: number | undefined;\n // Why the turn lock looks damaged, as of the last look, for the timeout message.\n let problem: string | undefined;\n const damaged = (what: string) =>\n `The turn lock ${directory} ${what}, so no process can take it. ` +\n `If no tc or MCP process is using profile \"${profile}\", remove that directory.`;\n for (let first = true; ; first = false) {\n if (!first) checkDeadline(profile, deadline, problem);\n problem = undefined;\n const latest = await readLatestTurn(directory);\n if (latest === \"missing\") {\n await createTurnDirectory(directory);\n continue;\n }\n if (latest === \"empty\") {\n // Usually a listing that straddled a turn's publication and an older\n // turn's removal (readdir is not a snapshot); damaged if it persists.\n problem = damaged(\"has no turns\");\n await waitOrTimeOut(profile, deadline, problem);\n continue;\n }\n if (latest === null) continue;\n if (typeof latest === \"number\") {\n problem = damaged(`has an unreadable turn ${latest}`);\n await waitOrTimeOut(profile, deadline, problem);\n continue;\n }\n firstWaitedTurn ??= latest.done ? latest.slot + 1 : latest.slot;\n if (latest.held && latest.done) {\n const turn = await takeTurn(profile, directory, latest);\n if (turn !== null) return { turn, firstWaitedTurn };\n await waitOrTimeOut(profile, deadline);\n } else if (latest.done) {\n problem = damaged(`ends with turn ${latest.slot}, which was never granted`);\n await waitOrTimeOut(profile, deadline, problem);\n } else if (latest.pid === process.pid ? relinquishedTurns.has(latest.token) : !isProcessAlive(latest.pid)) {\n await waitForTestBarrier(TEST_LOCK_TURN_SETTLE_BARRIER_DIR, profile);\n await settleAbandonedTurn(directory, latest);\n relinquishedTurns.delete(latest.token);\n } else {\n await signalTestLockContention(profile);\n await waitOrTimeOut(profile, deadline);\n }\n }\n}\n\n/**\n * The highest-numbered turn: its state, its number if it is damaged, null if\n * it went away while being read.\n */\nasync function readLatestTurn(directory: string): Promise<TurnState | number | \"missing\" | \"empty\" | null> {\n let names: string[];\n try {\n names = await readdir(directory);\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return \"missing\";\n throw error;\n }\n const slots = names.filter((name) => TURN.test(name)).map(Number);\n if (slots.length === 0) return \"empty\";\n const slot = Math.max(...slots);\n const turn = await readTurn(directory, slot);\n return turn === \"damaged\" ? slot : turn;\n}\n\n/**\n * Turn `slot` as recorded now; null if it is gone; \"damaged\" if its owner\n * record is missing or unreadable (turns are renamed into place and aside\n * whole, with their owner record written durably). Any other read error is\n * thrown: it says nothing about the turn. `done` is read before `held`,\n * which every writer creates first, so a turn read as done is never misread\n * as void.\n */\nasync function readTurn(directory: string, slot: number): Promise<TurnState | \"damaged\" | null> {\n const path = join(directory, String(slot));\n let text: string;\n try {\n text = await readFile(join(path, \"owner.json\"), \"utf8\");\n } catch (error) {\n if (!isErrno(error, \"ENOENT\") && !isErrno(error, \"ENOTDIR\")) throw error;\n return await exists(path) ? \"damaged\" : null;\n }\n let owner: { pid?: unknown; token?: unknown; after?: unknown } | null;\n try {\n owner = JSON.parse(text) as typeof owner;\n } catch {\n return \"damaged\";\n }\n if (owner === null || typeof owner !== \"object\" || typeof owner.token !== \"string\" || typeof owner.pid !== \"number\") {\n return \"damaged\";\n }\n const done = await exists(join(path, `${owner.token}.done`));\n const held = await exists(join(path, `${owner.token}.held`));\n return {\n slot,\n token: owner.token,\n pid: owner.pid,\n after: typeof owner.after === \"string\" ? owner.after : null,\n held,\n done,\n };\n}\n\n/**\n * Whether turn `slot` is still the granted, finished turn with `token`. False\n * only on definite evidence: it is gone, or holds another token. Throws if it\n * cannot be read, or is damaged, so the caller leaves its own turn undecided.\n */\nasync function isFinishedTurn(directory: string, slot: number, token: string): Promise<boolean> {\n const turn = await readTurn(directory, slot);\n if (turn === \"damaged\") throw new Error(`Turn ${slot} of the turn lock ${directory} is unreadable.`);\n return turn !== null && turn.token === token && turn.held && turn.done;\n}\n\n/**\n * Publishes the turn after `latest` and claims it. Null if another process\n * published that number first, or the turn is void. If a step after\n * publication fails, the turn is handed to settleOwnTurn and the error thrown.\n */\nasync function takeTurn(profile: string, directory: string, latest: TurnState): Promise<Turn | null> {\n const token = randomUUID();\n const slot = latest.slot + 1;\n const path = join(directory, String(slot));\n const owner = { pid: process.pid, createdAt: new Date().toISOString(), token, after: latest.token };\n let published = false;\n try {\n published = await publishDirectory(\n join(directory, `.stage-${process.pid}-${token}`),\n path,\n { \"owner.json\": `${JSON.stringify(owner, null, 2)}\\n` },\n () => waitForTestBarrier(TEST_LOCK_TURN_PUBLISH_BARRIER_DIR, profile),\n );\n if (published && await isFinishedTurn(directory, latest.slot, latest.token) && await markTurn(path, token, \"held\")) {\n return { directory, slot, token };\n }\n if (published) await markTurn(path, token, \"done\");\n return null;\n } catch (error) {\n if (published) settleOwnTurn(directory, slot, token);\n throw error;\n }\n}\n\n/**\n * Finishes the turn of a process that is gone (or one this process gave up).\n * A turn its creator never got to grant is granted first if the turn before\n * it is still the one its creator read (the check the creator would have\n * made; that turn cannot have been removed, since that needs this turn\n * done), and left void only if it definitely is not.\n */\nasync function settleAbandonedTurn(directory: string, abandoned: TurnState): Promise<void> {\n const path = join(directory, String(abandoned.slot));\n if (!abandoned.held && abandoned.after !== null &&\n await isFinishedTurn(directory, abandoned.slot - 1, abandoned.after)) {\n await markTurn(path, abandoned.token, \"held\");\n }\n await markTurn(path, abandoned.token, \"done\");\n}\n\n/**\n * Settles a turn this process published but could not grant or finish (a\n * marker write or a read failed). Other processes wait on this live PID, so\n * it is retried in the background until it succeeds or the turn is settled\n * otherwise (by this process's next acquisition, or by another process once\n * this one has exited). The timer does not keep the process alive.\n */\nfunction settleOwnTurn(directory: string, slot: number, token: string, retries = SETTLE_RETRIES): void {\n relinquishedTurns.add(token);\n void (async () => {\n try {\n const turn = await readTurn(directory, slot);\n if (turn !== null && turn !== \"damaged\" && turn.token === token && !turn.done) await settleAbandonedTurn(directory, turn);\n relinquishedTurns.delete(token);\n } catch {\n // Still relinquished: this process's next acquisition settles it too.\n if (retries > 0) setTimeout(() => settleOwnTurn(directory, slot, token, retries - 1), SETTLE_RETRY_MS).unref();\n }\n })();\n}\n\n/**\n * Creates `<token>.<kind>` in a turn directory; false if the directory is\n * gone. Other failures (a full disk, a permission error) are retried a few\n * times, then thrown.\n */\nasync function markTurn(path: string, token: string, kind: \"held\" | \"done\"): Promise<boolean> {\n for (let attempt = 0; ; attempt++) {\n try {\n await writeFile(join(path, `${token}.${kind}`), \"\", { mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n return true;\n } catch (error) {\n if (isErrno(error, \"EEXIST\")) return true;\n if (isErrno(error, \"ENOENT\")) return false;\n if (attempt >= MARKER_RETRY_DELAYS_MS.length) throw error;\n await sleep(MARKER_RETRY_DELAYS_MS[attempt]!);\n }\n }\n}\n\n/** Creates the turn directory with a granted, finished turn 0, unless another process did. */\nasync function createTurnDirectory(directory: string): Promise<void> {\n const token = randomUUID();\n const owner = { pid: process.pid, createdAt: new Date().toISOString(), token, after: null };\n await publishDirectory(join(dirname(directory), `.stage-${basename(directory)}-${process.pid}-${token}`), directory, {\n \"0/owner.json\": `${JSON.stringify(owner, null, 2)}\\n`,\n [`0/${token}.held`]: \"\",\n [`0/${token}.done`]: \"\",\n });\n}\n\n/**\n * Writes `files` (durably, when not empty) into a new staging directory and\n * renames it to `target`. False if `target` already exists (or the turn\n * directory is gone); the caller starts over. Nothing else removes a live\n * process's staging directory (see collectTurns), so `target` never appears\n * incomplete.\n */\nasync function publishDirectory(\n stage: string,\n target: string,\n files: Readonly<Record<string, string>>,\n beforeRename?: () => Promise<void>,\n): Promise<boolean> {\n try {\n for (const [name, contents] of Object.entries(files)) {\n await mkdir(dirname(join(stage, name)), { recursive: true, mode: PRIVATE_DIR_MODE });\n await writeFileDurably(join(stage, name), contents);\n }\n await beforeRename?.();\n await rename(stage, target);\n return true;\n } catch (error) {\n // ENOTEMPTY/EEXIST: `target` exists, though it may be gone again by now.\n // Windows reports an existing target directory as EPERM.\n if ([\"ENOTEMPTY\", \"EEXIST\", \"ENOENT\"].some((code) => isErrno(error, code)) || await exists(target)) return false;\n throw error;\n } finally {\n await rm(stage, { recursive: true, force: true }).catch(() => undefined);\n }\n}\n\n/**\n * Finishes this process's turn. If `done` cannot be written even after\n * retries, the critical section is still over and its writes stand: the turn\n * is handed to settleOwnTurn rather than failing the caller.\n */\nasync function releaseTurn(profile: string, turn: Turn): Promise<void> {\n try {\n await markTurn(join(turn.directory, String(turn.slot)), turn.token, \"done\");\n } catch {\n settleOwnTurn(turn.directory, turn.slot, turn.token);\n return;\n }\n await collectTurns(profile, turn).catch(() => undefined);\n}\n\n/**\n * Leftovers in a turn directory whose writer is gone: trash (a removed turn\n * renamed aside, garbage from then on), and staging directories and\n * deletion-record temporaries named after their writer's PID.\n */\nfunction isAbandonedTurnEntry(name: string): boolean {\n if (name.startsWith(\".trash-\")) return true;\n const writer = /^\\.(?:stage|deleted\\.json)[-.]([0-9]+)[-.]/.exec(name)?.[1];\n return writer !== undefined && !isProcessAlive(Number(writer));\n}\n\n/** A turn directory's staging directory left beside it by a process that is gone. */\nfunction isAbandonedTurnDirectoryStage(name: string): boolean {\n const writer = /^\\.stage-.+-([0-9]+)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.exec(name)?.[1];\n return writer !== undefined && !isProcessAlive(Number(writer));\n}\n\n/**\n * Removes the turns before `turn`, which just finished: void turns, and\n * granted ones oldest first, each once no older turn is left and the next is\n * granted and done (see acquireTurn). A turn is renamed aside before it is\n * deleted, so its number is never an empty directory. A turn that is damaged\n * or cannot be read is left alone, and a read error stops the collection.\n * Leftovers of crashed processes go too, judged by PID, never by age:\n * removing a paused process's staging directory could publish an incomplete\n * turn.\n */\nasync function collectTurns(profile: string, turn: Turn): Promise<void> {\n for (const [directory, abandoned] of [\n [turn.directory, isAbandonedTurnEntry],\n [dirname(turn.directory), isAbandonedTurnDirectoryStage],\n ] as const) {\n for (const name of (await readdir(directory)).filter(abandoned)) {\n await rm(join(directory, name), { recursive: true, force: true }).catch(() => undefined);\n }\n }\n const older = (await readdir(turn.directory)).filter((name) => TURN.test(name)).map(Number)\n .filter((slot) => slot < turn.slot)\n .sort((left, right) => left - right);\n for (const slot of older) {\n const candidate = await readTurn(turn.directory, slot);\n if (candidate === null || candidate === \"damaged\" || !candidate.done) continue;\n if (candidate.held) {\n if (await exists(join(turn.directory, String(slot - 1)))) continue;\n const next = await readTurn(turn.directory, slot + 1);\n if (next === null || next === \"damaged\" || !next.held || !next.done) continue;\n }\n await waitForTestBarrier(TEST_LOCK_TURN_COLLECT_BARRIER_DIR, profile);\n const trash = join(turn.directory, `.trash-${randomUUID()}`);\n if (await rename(join(turn.directory, String(slot)), trash).then(() => true, () => false)) {\n await rm(trash, { recursive: true, force: true }).catch(() => undefined);\n }\n }\n}\n\n/**\n * One attempt to take `.lock`, made while holding a turn. Nothing here\n * replaces an existing path:\n *\n * 1. `mkdir(.lock)` (never recursive) is exclusive, and is the primitive\n * older releases use too, so they exclude each other.\n * 2. Ownership is published by `link`ing a fully written owner file (staged\n * beside `.lock`, on the same filesystem) to `.lock/owner.json`. `link`\n * fails with EEXIST if an owner exists, and with ENOENT if the directory\n * was removed meanwhile (an aged ownerless-lock reclaim by an older\n * release). Only a successful link holds the lock; on either failure\n * nothing is released, since nothing was acquired, and the caller retries.\n * On a filesystem without hard links (FAT/exFAT, some SMB mounts) the\n * owner file is created in place with an exclusive create instead, with\n * the same EEXIST/ENOENT outcomes. A reader may then briefly see it\n * incomplete; every release treats an owner file it cannot parse as a\n * held lock, and this release removes one only once it has aged (see\n * isAbandonedOwner).\n *\n * A profile deletion removes the profile directory once it has released its\n * lock, so `mkdir(.lock)` can see ENOENT; the directory is recreated (0700)\n * and the caller retries within its deadline, as for a first write to a new\n * profile.\n *\n * Only one owner.json can exist at the lock path, and it is removed only by\n * its holder's release or by recovery of an abandoned holder, so at most one\n * process holds the lock. Returns false when the lock is not acquired.\n */\nasync function publishProfileLock(profile: string, lockPath: string, token: string, requireProfile: boolean): Promise<boolean> {\n try {\n await mkdir(lockPath, { mode: PRIVATE_DIR_MODE });\n } catch (error) {\n if (isErrno(error, \"EEXIST\")) return false;\n if (!isErrno(error, \"ENOENT\")) throw error;\n // With requireProfile only an older release's deletion (which takes no turn) gets here.\n if (requireProfile) throw new ProfileDeletedError(profile);\n await mkdir(profilePath(profile), { recursive: true, mode: PRIVATE_DIR_MODE });\n return false;\n }\n await waitForTestBarrier(TEST_LOCK_PUBLISH_BARRIER_DIR, profile);\n const ownerPath = join(lockPath, \"owner.json\");\n const staged = join(dirname(lockPath), `.lock-owner-${token}.tmp`);\n const owner = `${JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString(), token }, null, 2)}\\n`;\n try {\n await writeFile(staged, owner, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n try {\n await link(staged, ownerPath);\n } catch (error) {\n if (!lacksHardLinks(error)) throw error;\n await writeFile(ownerPath, owner, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n }\n return true;\n } catch (error) {\n if (isErrno(error, \"EEXIST\") || isErrno(error, \"ENOENT\")) return false;\n // Do not leave an ownerless lock behind for others to wait out. rmdir\n // removes only an empty directory; anyone who created it after ours went\n // away sees ENOENT on link and retries.\n await rmdir(lockPath).catch(() => undefined);\n throw error;\n } finally {\n await rm(staged, { force: true }).catch(() => undefined);\n }\n}\n\n/**\n * Errors `link` reports on a filesystem without hard links: EPERM (Linux\n * FAT/exFAT), ENOTSUP/EOPNOTSUPP (macOS FAT/exFAT, SMB), ENOSYS, EISDIR\n * (libuv's code for Windows' ERROR_INVALID_FUNCTION on FAT32), and EMLINK\n * (too many links), for which the same fallback is just as correct.\n */\nconst NO_HARD_LINK_ERRORS = new Set([\"EPERM\", \"ENOTSUP\", \"EOPNOTSUPP\", \"ENOSYS\", \"EISDIR\", \"EMLINK\"]);\n\nfunction lacksHardLinks(error: unknown): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error &&\n NO_HARD_LINK_ERRORS.has(String((error as { code?: unknown }).code));\n}\n\n/**\n * Releases the lock if `.lock/owner.json` is still this acquisition's. No\n * one else can put an owner record there while it exists (owners are only\n * published into a directory their own `mkdir` created, and recovery\n * removes only an abandoned holder's record), so the record read is the one\n * unlinked.\n */\nasync function releaseProfileLock(profile: string, lockPath: string, token: string): Promise<void> {\n const ownerPath = join(lockPath, \"owner.json\");\n const owner = await readJson<{ token?: unknown }>(ownerPath).catch(() => null);\n if (owner?.token !== token) return;\n await rm(ownerPath, { force: true });\n // `.lock` is empty from here until the rmdir; a contender that removes it\n // and creates its own meanwhile is not harmed: rmdir fails on its owner\n // file, or the contender's link sees ENOENT and retries. If a recoverer's\n // claim file is still inside, rmdir fails and that recoverer removes the\n // directory when it drops its claim.\n await waitForTestBarrier(TEST_LOCK_RELEASE_BARRIER_DIR, profile);\n await rmdir(lockPath).catch(() => undefined);\n}\n\n/**\n * Gives process-level contention tests an event-driven witness that a second\n * writer has reached an already-held lock. This deliberately has no effect\n * outside an explicit test environment, and only creates a new signal file\n * beneath TC_HOME; it never changes lock acquisition or release semantics.\n */\nasync function signalTestLockContention(profile: string): Promise<void> {\n if (process.env.NODE_ENV !== \"test\") return;\n\n const configuredPath = process.env[TEST_LOCK_CONTENTION_SIGNAL_PATH];\n const configuredHome = process.env.TC_HOME;\n if (!configuredPath || !configuredHome) return;\n\n const home = resolve(configuredHome);\n const signalPath = resolve(configuredPath);\n const pathFromHome = relative(home, signalPath);\n if (\n pathFromHome === \"\" ||\n pathFromHome === \"..\" ||\n pathFromHome.startsWith(`..${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`) ||\n pathFromHome.startsWith(\"../\") ||\n pathFromHome.startsWith(\"..\\\\\")\n ) {\n return;\n }\n\n await writeFile(signalPath, `${profile}\\n`, { encoding: \"utf8\", flag: \"wx\" })\n .catch(() => undefined);\n}\n\n/**\n * Reclaims a `.lock` with no owner record, while holding a turn. A\n * `.recover-*` claim may contain a live legacy owner's record moved by a\n * no-hard-links recoverer just before it crashed. Restore that record first;\n * only orphaned claims holding dead or malformed records can be removed.\n * Otherwise the directory must be older than the stale threshold: one left\n * by a crash, or by an older release, whose `.stale-*` / `.release-*` claim\n * files are removed too. owner.json is never unlinked, and the directory\n * itself is only `rmdir`ed, which succeeds only while it is empty.\n *\n * Holding a turn, no other process of this release reclaims concurrently.\n * That closes the race in which two reclaimers' age checks let the later one\n * remove a directory a 1.0.0-beta.16-or-older release had just created,\n * which holds the lock from its `mkdir`. That race remains only if a\n * 1.0.0-beta.17 … 1.0.1-beta.4 release reclaims at the same moment, or the\n * older process stays paused between its `mkdir` and its owner write for\n * longer than the stale threshold; recoveryFenced bounds how stale this\n * process's age check can be.\n */\nasync function recoverOwnerlessLock(profile: string, lockPath: string, staleAfterMs: number): Promise<boolean> {\n let aged: boolean;\n try {\n const { mtimeMs } = await stat(lockPath);\n aged = Date.now() - mtimeMs >= staleAfterMs;\n } catch {\n return false;\n }\n const checkedAt = performance.now();\n await waitForTestBarrier(TEST_LOCK_OWNERLESS_BARRIER_DIR, profile);\n try {\n const entries = await readdir(lockPath);\n if (entries.includes(\"owner.json\")) return false;\n const onlyOrphanedClaims = entries.length > 0 && entries.every((entry) => RECOVERY_CLAIM.test(entry));\n if (!onlyOrphanedClaims && (!aged || recoveryFenced(checkedAt, staleAfterMs))) return false;\n for (const name of entries.filter((entry) => RECOVERY_CLAIM.test(entry))) {\n const claimPath = join(lockPath, name);\n if (await hasLiveRecoveryOwner(claimPath)) {\n // The claim keeps the directory in place. Only the original mkdir\n // owner could publish owner.json here; never overwrite that record.\n if (!await exists(join(lockPath, \"owner.json\"))) await rename(claimPath, join(lockPath, \"owner.json\"));\n return false;\n }\n await rm(claimPath, { force: true });\n }\n for (const name of entries.filter((entry) => ABANDONED_CLAIM.test(entry))) {\n await rm(join(lockPath, name), { force: true });\n }\n await rmdir(lockPath);\n } catch {\n return false;\n }\n await removeAgedOwnerFiles(lockPath, staleAfterMs);\n return true;\n}\n\n/** A no-hard-links claim may contain a live owner's record moved before a crash. */\nasync function hasLiveRecoveryOwner(claimPath: string): Promise<boolean> {\n let contents: string;\n try {\n contents = await readFile(claimPath, \"utf8\");\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return false;\n throw error; // An I/O failure is not evidence that the holder is gone.\n }\n let owner: unknown;\n try {\n owner = JSON.parse(contents);\n } catch {\n return false;\n }\n const pid = typeof owner === \"object\" && owner !== null && \"pid\" in owner ? owner.pid : null;\n return typeof pid === \"number\" && Number.isInteger(pid) && pid > 0 && isProcessAlive(pid);\n}\n\n/**\n * Whether an ownerless-reclaim decision made at `since` (a monotonic\n * timestamp) is too old to act on. The age check is only good for a while:\n * past half the stale threshold the reclaim starts over.\n */\nfunction recoveryFenced(since: number, staleAfterMs: number): boolean {\n return performance.now() - since >= staleAfterMs / 2;\n}\n\n/** Claim files of older releases' stale recovery and (up to 1.0.0-beta.16) release. */\nconst ABANDONED_CLAIM = /^\\.(?:release|stale)-[0-9a-f-]+\\.json$/;\n/**\n * Claim files of this release's stale recovery. Releases up to 1.0.1-beta.4\n * never remove them, which is what makes this recovery safe against them; a\n * recoverer that crashes leaves one that only a release with the turn lock\n * clears (see REFERENCE.md, \"Profile lock\").\n */\nconst RECOVERY_CLAIM = /^\\.recover-[0-9a-f-]+\\.json$/;\n/** Owner files staged by publishProfileLock beside `.lock`. */\nconst STAGED_OWNER = /^\\.lock-owner-[0-9a-f-]+\\.tmp$/;\n/**\n * Removes owner files a crashed acquirer staged beside `.lock`. A live\n * acquirer's staged file exists only for its write and link, so only files\n * older than the stale threshold are removed. Runs after a recovery, never\n * on the uncontended path.\n */\nasync function removeAgedOwnerFiles(lockPath: string, staleAfterMs: number): Promise<void> {\n const directory = dirname(lockPath);\n const names = await readdir(directory).catch(() => []);\n for (const name of names.filter((entry) => STAGED_OWNER.test(entry))) {\n const path = join(directory, name);\n const aged = await stat(path).then(({ mtimeMs }) => Date.now() - mtimeMs >= staleAfterMs, () => false);\n if (aged) await rm(path, { force: true }).catch(() => undefined);\n }\n}\n\n\n/**\n * Removes an abandoned owner record (see isAbandonedOwner) and its `.lock`,\n * while holding a turn, so no other process of this release recovers,\n * reclaims or acquires `.lock` meanwhile.\n *\n * The record is claimed first: hard-linked to `.recover-<uuid>.json`, and the\n * claim compared with the exact bytes read. A record that replaced the\n * observed one is left in place. While the claim is inside `.lock`, the\n * directory cannot be removed and recreated: older releases never remove a\n * `.recover-*` claim (they clean up only their own claim names), and other\n * processes of this release are kept out by the turn lock. So no other owner\n * record can appear in it, and the unlink of owner.json can only remove the\n * claimed, dead record. A live record is never unlinked or moved. `.lock`\n * itself is removed only after this process's claim is unlinked from it,\n * which proves it is still the dead holder's directory; if the claim cannot\n * be made, `.lock` is left alone (it may be a directory a 1.0.0-beta.16-or-\n * older writer just created, which it holds from that `mkdir`). No step\n * depends on how long this process takes.\n *\n * Without hard links (where 1.0.0-beta.17 … 1.0.1-beta.4 cannot run at all),\n * the record is renamed into the claim instead, and put back if it is not\n * the observed one: one a 1.0.0-beta.16-or-older process published after\n * recovering the same lock at the same moment. The claim keeps `.lock` held\n * meanwhile, so no second writer gets in, but if that holder releases\n * between the two renames, the put-back restores a released record, and\n * `.lock` stays held until that PID is gone and the record is 30 s old.\n */\nasync function recoverStaleLock(profile: string, lockPath: string, staleAfterMs: number): Promise<boolean> {\n const ownerPath = join(lockPath, \"owner.json\");\n const observed = await readFile(ownerPath, \"utf8\").catch(() => null);\n if (observed === null) return recoverOwnerlessLock(profile, lockPath, staleAfterMs);\n if (!await isAbandonedOwner(observed, ownerPath, staleAfterMs)) return false;\n\n await waitForTestBarrier(TEST_LOCK_RECOVERY_BARRIER_DIR, profile);\n const claimPath = join(lockPath, `.recover-${randomUUID()}.json`);\n let moved = false;\n try {\n await link(ownerPath, claimPath);\n } catch (error) {\n // Gone or replaced already (another release recovered it): leave `.lock`.\n if (!lacksHardLinks(error)) return false;\n try {\n await rename(ownerPath, claimPath);\n moved = true;\n } catch {\n return false;\n }\n }\n if (moved) await waitForTestBarrier(TEST_LOCK_MOVED_BARRIER_DIR, profile);\n const sameInstance = await readFile(claimPath, \"utf8\").then((claimed) => claimed === observed, () => false);\n await waitForTestBarrier(TEST_LOCK_VERIFIED_BARRIER_DIR, profile);\n if (!sameInstance) {\n if (moved) {\n // No other owner.json can have appeared meanwhile: only a process\n // whose mkdir created this `.lock` publishes one, and it already has.\n await rename(claimPath, ownerPath).catch(() => undefined);\n } else {\n await unlink(claimPath).catch(() => undefined);\n }\n return false;\n }\n if (!moved) await rm(ownerPath, { force: true });\n await waitForTestBarrier(TEST_LOCK_CLAIM_BARRIER_DIR, profile);\n await waitForTestBarrier(TEST_LOCK_CLAIMED_BARRIER_DIR, profile);\n // Drop any claim a crashed recoverer of this release left, then this one.\n for (const name of (await readdir(lockPath).catch(() => [])).filter((entry) => RECOVERY_CLAIM.test(entry))) {\n if (join(lockPath, name) !== claimPath) await rm(join(lockPath, name), { force: true });\n }\n // Empty now, and still the dead holder's directory if this claim was in\n // it: remove it rather than leave an ownerless lock to age out.\n if (await unlink(claimPath).then(() => true, () => false)) await rmdir(lockPath).catch(() => undefined);\n await removeAgedOwnerFiles(lockPath, staleAfterMs);\n return true;\n}\n\n/**\n * Whether an owner record (its exact bytes, read from `ownerPath`) is\n * abandoned: a holder's whose PID is gone, older than the stale threshold;\n * or, if it is not a complete record, a file older than that threshold.\n * Every release publishes complete records (by link or rename) except this\n * one's no-hard-link fallback, which writes in place while holding a turn;\n * so an incomplete record seen while holding a turn was left by a crash.\n */\nasync function isAbandonedOwner(observed: string, ownerPath: string, staleAfterMs: number): Promise<boolean> {\n let owner: unknown;\n try {\n owner = JSON.parse(observed);\n } catch {\n owner = null;\n }\n if (typeof owner === \"object\" && owner !== null && \"pid\" in owner) {\n return isStaleOwner(owner as { pid?: unknown; createdAt?: unknown }, staleAfterMs);\n }\n const modifiedAt = await stat(ownerPath).then(({ mtimeMs }) => mtimeMs, () => Number.NaN);\n return Date.now() - modifiedAt >= staleAfterMs;\n}\n\n/** Test-only rendezvous (NODE_ENV=test and the named barrier directory set). */\nasync function waitForTestBarrier(environmentName: string, profile: string): Promise<void> {\n if (process.env.NODE_ENV !== \"test\") return;\n const barrierDirectory = process.env[environmentName];\n if (!barrierDirectory) return;\n await mkdir(barrierDirectory, { recursive: true });\n const readyPath = join(barrierDirectory, `ready-${process.pid}-${profile}`);\n await writeFile(readyPath, \"ready\\n\", { encoding: \"utf8\", flag: \"wx\" }).catch(() => undefined);\n const releasePath = join(barrierDirectory, \"release\");\n while (true) {\n try {\n await readFile(releasePath, \"utf8\");\n return;\n } catch {\n await sleep(1);\n }\n }\n}\n\nfunction isStaleOwner(\n owner: { pid?: unknown; createdAt?: unknown } | null,\n staleAfterMs: number,\n): boolean {\n const now = Date.now();\n const createdAt = typeof owner?.createdAt === \"string\"\n ? Date.parse(owner.createdAt)\n : Number.NaN;\n\n // Reclaim only a fully published lock whose owner PID is confirmed dead.\n // A lock without an owner record is handled by recoverOwnerlessLock: a\n // process holds the lock only once its owner.json is linked in.\n if (!Number.isFinite(createdAt) || now - createdAt < staleAfterMs) return false;\n if (typeof owner?.pid !== \"number\" || !Number.isInteger(owner.pid) || owner.pid <= 0) {\n return false;\n }\n return !isProcessAlive(owner.pid);\n}\n\n/** Whether `path` exists. Only ENOENT/ENOTDIR mean it does not; other errors are thrown. */\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch (error) {\n if (isErrno(error, \"ENOENT\") || isErrno(error, \"ENOTDIR\")) return false;\n throw error;\n }\n}\n\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return !isErrno(error, \"ESRCH\");\n }\n}\n\nfunction validateProfileName(profile: string): string {\n if (\n !profile ||\n profile === \".\" ||\n profile === \"..\" ||\n profile.includes(\"/\") ||\n profile.includes(\"\\\\\") ||\n profile.includes(\"\\0\")\n ) {\n throw new TypeError(\"Profile names must be non-empty path segments.\");\n }\n return profile;\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error &&\n (error as { code?: unknown }).code === code;\n}\n\nfunction sleep(milliseconds: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\nexport { DEFAULT_PROFILE };\n","import type { z } from \"zod\";\n\nimport type { OperationError, OperationErrorCode } from \"./errors.js\";\n\n/** A stable, cross-surface operation identifier. */\nexport type OperationId = string;\n\n/** JSON Pointer syntax from RFC 6901, including the empty pointer for a root value. */\nexport type JsonPointer = \"\" | `/${string}`;\n\nexport type OperationEffect =\n | \"read\"\n | \"local_write\"\n | \"write\"\n | \"destructive\"\n | \"external\";\n\nexport type TinyCloudPosture =\n | \"owner-openkey\"\n | \"delegate-session\"\n | \"local-owner-key\"\n | \"unauthenticated\";\n\nexport type OperationOperatorType = \"human\" | \"agent\";\n\nexport type SurfaceDisposition =\n | Readonly<{ status: \"required\" }>\n | Readonly<{ status: \"excluded\"; reason: string }>;\n\n/**\n * Safe identity reported with every result. This deliberately excludes keys,\n * tokens, delegations, grants, and operation inputs or outputs.\n */\nexport interface OperationContextSummary {\n readonly profile: string;\n readonly host: string;\n readonly posture: TinyCloudPosture;\n readonly operatorType?: OperationOperatorType;\n readonly principalDid?: string;\n readonly sessionDid?: string;\n readonly ownerDid?: string;\n readonly space?: string;\n}\n\n/**\n * The profile foundation constructs this context for every invocation. The\n * invocation target never supplies an execution context or runtime object.\n */\nexport interface OperationContext {\n readonly summary: OperationContextSummary;\n /** Present for every normal invocation; optional for focused definition tests. */\n readonly runtime?: OperationRuntime;\n}\n\n/**\n * Per-invocation authority that is constructed inside operations. It is never\n * caller supplied and it is deliberately absent from result envelopes.\n */\nexport interface OperationRuntime {\n readonly node: unknown;\n readonly granted: readonly CapabilityRequirement[];\n /** Diagnostics gathered while building the runtime, attached to the result. */\n readonly warnings?: readonly OperationWarning[];\n}\n\n/**\n * Why a stored grant was not used. A fixed vocabulary: diagnostics never\n * carry exception text, node responses, URLs or other stored transport data.\n * `unbound`: the record has no valid request binding where one is required;\n * `outside_request`: its signed authority exceeds its binding.\n */\nexport const STORED_GRANT_SKIP_REASONS = [\n \"malformed\",\n \"unbound\",\n \"outside_request\",\n \"host_mismatch\",\n \"expired\",\n \"cid_mismatch\",\n \"authority_invalid\",\n \"proof_missing\",\n \"proof_invalid\",\n \"owner_mismatch\",\n \"audience_mismatch\",\n \"resources_mismatch\",\n \"unsupported\",\n \"activation_rejected\",\n \"invalid\",\n] as const;\n\nexport type StoredGrantSkipReason = typeof STORED_GRANT_SKIP_REASONS[number];\n\n/**\n * The string form of every delegation CID TinyCloud computes: CIDv1, raw\n * codec, BLAKE3-256 multihash, base32. A published `grantCid` also has to be\n * the CID recomputed from the stored authorization bytes.\n */\nexport const DELEGATION_CID_PATTERN = \"^bafkr4i[a-z2-7]{52}$\";\n\n/**\n * A non-fatal diagnostic attached to a result. `STORED_GRANT_SKIPPED`: a\n * stored grant failed validation and gave no authority; `grantCid` is present\n * only when the stored CID is the CID of the stored authorization bytes.\n */\nexport interface OperationWarning {\n readonly code: \"STORED_GRANT_SKIPPED\";\n readonly reason: StoredGrantSkipReason;\n readonly grantCid?: string;\n}\n\n/** Context given to planners and handlers after runtime authentication. */\nexport interface RuntimeOperationContext extends OperationContext {\n readonly runtime: OperationRuntime;\n}\n\nexport type AuthorityPlanningContext = RuntimeOperationContext;\n\n/**\n * Capability details are finalized by the authority/artifacts increment. The\n * kernel intentionally preserves them as canonical operation-owned data.\n */\nexport type CapabilityRequirement = Readonly<Record<string, unknown>>;\n\nexport interface PermissionRequestArtifact {\n readonly requestId: string;\n readonly [key: string]: unknown;\n}\n\nexport interface ApprovalAction {\n readonly kind: \"openkey\";\n readonly requestId: string;\n readonly url?: string;\n readonly fallback: string;\n}\n\nexport interface SetupAction {\n readonly kind: string;\n readonly [key: string]: unknown;\n}\n\nexport interface OperationRef {\n readonly operationId: OperationId;\n readonly operationVersion: number;\n}\n\nexport interface RetryDescriptor extends OperationRef {\n readonly inputDigest: string;\n readonly safeInput?: Readonly<Record<string, unknown>>;\n readonly requiresCallerInput: boolean;\n}\n\nexport interface OperationSensitivity {\n readonly input: readonly JsonPointer[];\n readonly output: readonly JsonPointer[];\n}\n\n/**\n * An inspection operation may read safe local profile state without creating a\n * node or authenticating. Every other operation requires an authenticated\n * runtime before planning or execution.\n */\nexport type OperationRuntimeRequirement = \"authenticated\" | \"inspection\";\n\nexport interface OperationExposure {\n readonly cli: SurfaceDisposition;\n readonly mcp: SurfaceDisposition;\n readonly skill: SurfaceDisposition;\n readonly docs: SurfaceDisposition;\n}\n\nexport interface OperationOkResult<O> {\n readonly status: \"ok\";\n readonly operation: OperationRef;\n readonly context: OperationContextSummary;\n readonly output: O;\n readonly warnings?: readonly OperationWarning[];\n}\n\nexport interface OperationAuthorityRequiredResult {\n readonly status: \"authority_required\";\n readonly operation: OperationRef;\n readonly context: OperationContextSummary;\n readonly missing: readonly CapabilityRequirement[];\n readonly request: PermissionRequestArtifact;\n readonly approval: ApprovalAction;\n readonly retry: RetryDescriptor;\n readonly warnings?: readonly OperationWarning[];\n}\n\nexport interface OperationSetupRequiredResult {\n readonly status: \"setup_required\";\n readonly operation: OperationRef;\n readonly context: OperationContextSummary;\n readonly setup: SetupAction;\n readonly retry: RetryDescriptor;\n readonly warnings?: readonly OperationWarning[];\n}\n\nexport interface OperationErrorResult {\n readonly status: \"error\";\n readonly operation: OperationRef;\n readonly context: OperationContextSummary;\n readonly error: OperationError;\n readonly warnings?: readonly OperationWarning[];\n}\n\nexport type OperationResult<O> =\n | OperationOkResult<O>\n | OperationAuthorityRequiredResult\n | OperationSetupRequiredResult\n | OperationErrorResult;\n\n/**\n * Handler outcomes intentionally omit invocation-owned operation, context, and\n * retry metadata. The kernel attaches those values after validation.\n */\nexport type OperationExecutionOutcome<O> =\n | Readonly<{ status: \"ok\"; output: O }>\n | Readonly<{\n status: \"authority_required\";\n missing: readonly CapabilityRequirement[];\n request: PermissionRequestArtifact;\n approval: ApprovalAction;\n requiresCallerInput?: boolean;\n }>\n | Readonly<{\n status: \"setup_required\";\n setup: SetupAction;\n requiresCallerInput?: boolean;\n }>\n | Readonly<{ status: \"error\"; error: OperationError }>;\n\n/**\n * Internal registry material. It is intentionally never re-exported by the\n * package root: projections can execute only by operation id and version.\n */\nexport interface OperationDefinition<I, O> {\n readonly id: OperationId;\n readonly version: 1;\n readonly title: string;\n readonly description: string;\n readonly input: z.ZodType<I>;\n readonly output: z.ZodType<O>;\n readonly effects: readonly OperationEffect[];\n readonly runtime: OperationRuntimeRequirement;\n readonly postures: readonly TinyCloudPosture[];\n readonly exposure: OperationExposure;\n readonly sensitivity: OperationSensitivity;\n /** A definition may give malformed transport artifacts a stable error code. */\n readonly invalidInputErrorCode?: OperationErrorCode;\n readonly authority: (\n context: AuthorityPlanningContext,\n input: I,\n ) => Promise<readonly CapabilityRequirement[]>;\n readonly execute: (\n context: OperationContext,\n input: I,\n ) => Promise<OperationExecutionOutcome<O>>;\n}\n\n/**\n * The only caller-controlled invocation settings. `privateKey` is a CLI-only,\n * nonpersistable override; it is deliberately excluded from result metadata,\n * retry descriptors, diagnostics, and all state written by this package.\n */\nexport interface InvocationTarget {\n readonly profile?: string;\n readonly host?: string;\n /**\n * Absolute home directory used for this invocation's TinyCloud profile\n * state. Hosted projections set this per authenticated principal so\n * concurrent tenants never share process-global TC_HOME state.\n */\n readonly stateRoot?: string;\n readonly allowOwnerProfile?: boolean;\n readonly privateKey?: string;\n}\n\n/**\n * Copy only the identity fields allowed in a public result. Keeping this\n * projection centralized prevents a profile/runtime implementation from\n * accidentally smuggling execution material into an envelope.\n */\nexport function safeOperationContextSummary(\n summary: OperationContextSummary,\n): OperationContextSummary {\n return {\n profile: summary.profile,\n host: summary.host,\n posture: summary.posture,\n ...(summary.operatorType === undefined\n ? {}\n : { operatorType: summary.operatorType }),\n ...(summary.principalDid === undefined\n ? {}\n : { principalDid: summary.principalDid }),\n ...(summary.sessionDid === undefined ? {} : { sessionDid: summary.sessionDid }),\n ...(summary.ownerDid === undefined ? {} : { ownerDid: summary.ownerDid }),\n ...(summary.space === undefined ? {} : { space: summary.space }),\n };\n}\n","// Namespace-shaped so modules that bundle this one stay compatible with\n// lightweight node-sdk test doubles.\nimport * as nodeSdk from \"@tinycloud/node-sdk\";\n\nimport { OperationInvocationError, operationError } from \"./errors.js\";\n\nconst DEFAULT_SECRETS_SPACE = \"secrets\";\nconst SECRET_MANAGER_BASE_URL = \"https://secrets.tinycloud.xyz\";\nconst SECRET_NAME_RE = /^[A-Z][A-Z0-9_]*$/;\nconst RESERVED_SECRET_SCOPES = new Set([\"default\", \"global\"]);\n\nexport interface SecretsGetInput {\n readonly name: string;\n readonly scope?: string;\n readonly space?: string;\n}\n\nexport interface SecretReference {\n readonly name: string;\n readonly scope?: string;\n readonly space: string;\n readonly vaultKey: string;\n readonly permissionPath: string;\n}\n\nexport function normalizeSecretsGetInput(\n input: SecretsGetInput,\n): SecretsGetInput {\n const reference = resolveSecretReference(input);\n return {\n name: reference.name,\n ...(reference.scope === undefined ? {} : { scope: reference.scope }),\n // Omission is meaningful: the CLI's default is the literal `secrets`\n // space, while an explicitly supplied short name is resolved later against\n // the authenticated identity.\n ...(input.space === undefined ? {} : { space: reference.space }),\n };\n}\n\n/** Resolves the one canonical backing key/path used by planning and setup. */\nexport function resolveSecretReference(\n input: SecretsGetInput,\n): SecretReference {\n const name = input.name.trim();\n if (!SECRET_NAME_RE.test(name)) {\n throw invalidSecretInput();\n }\n\n const scope = canonicalizeSecretScope(input.scope);\n const space = normalizeSecretsSpace(input.space);\n const vaultKey = scope === undefined\n ? `secrets/${name}`\n : `secrets/scoped/${scope}/${name}`;\n\n return {\n name,\n ...(scope === undefined ? {} : { scope }),\n space,\n vaultKey,\n permissionPath: `vault/${vaultKey}`,\n };\n}\n\n/**\n * Resolve the operation's space against the authenticated identity. The\n * public short-name contract remains `secrets`, while an authenticated\n * operation uses its owner-exact URI for the actual read boundary.\n */\nexport function resolveSecretReferenceForOperation(\n input: SecretsGetInput,\n node: unknown,\n ownerSpace?: string,\n): SecretReference {\n const reference = resolveSecretReference(input);\n if (input.space === undefined && ownerSpace === undefined) return reference;\n return {\n ...reference,\n space: resolveOperationSpace(reference.space, node, ownerSpace),\n };\n}\n\n/** Creates the one owner-aware resolver shared by operation matching paths. */\nexport function operationSpaceResolver(\n node: unknown,\n ownerSpace?: string,\n): (space: string) => string {\n return (space) => resolveOperationSpace(space, node, ownerSpace);\n}\n\nfunction resolveOperationSpace(space: string, node: unknown, ownerSpace?: string): string {\n if (space.startsWith(\"tinycloud:\")) return canonicalizeSpaceUri(space);\n\n const ownerSpaceId = ownerSpace === undefined ? undefined : ownedSpaceForName(ownerSpace, space);\n if (ownerSpaceId !== undefined) return canonicalizeSpaceUri(ownerSpaceId);\n\n const candidate = node as {\n resolveOwnedSpace?: (spaceName: string) => unknown;\n spaceId?: unknown;\n address?: unknown;\n did?: unknown;\n };\n try {\n const resolved = candidate.resolveOwnedSpace?.(space);\n if (typeof resolved === \"string\" && resolved.length > 0) {\n return canonicalizeSpaceUri(resolved);\n }\n } catch {\n // Continue to the identity-derived resolver below.\n }\n\n // A restored delegate session carries the owner's primary space even though\n // node.did is the delegate/session principal. This is the same owner\n // identity used by the CLI space resolver.\n if (typeof candidate.spaceId === \"string\") {\n const resolved = ownedSpaceForName(candidate.spaceId, space);\n if (resolved !== undefined) return canonicalizeSpaceUri(resolved);\n }\n\n const did = typeof candidate.did === \"string\" ? candidate.did : undefined;\n const pkh = did === undefined ? null : nodeSdk.parsePkhDid(did);\n if (pkh === null) {\n throw invalidSecretInput();\n }\n return nodeSdk.makePkhSpaceId(pkh.address, pkh.chainId, space);\n}\n\nfunction ownedSpaceForName(ownerSpace: string, name: string): string | undefined {\n const parsed = nodeSdk.parseSpaceUri(ownerSpace);\n if (parsed === null) return undefined;\n try {\n const pkh = nodeSdk.parsePkhDid(parsed.owner);\n return pkh === null ? undefined : nodeSdk.makePkhSpaceId(pkh.address, pkh.chainId, name);\n } catch {\n return undefined;\n }\n}\n\nfunction canonicalizeSpaceUri(space: string): string {\n const parts = space.split(\":\");\n const name = parts.at(-1);\n if (parts.length < 3 || name === undefined || name === \"\") {\n throw invalidSecretInput();\n }\n // EIP-155 address casing is interchangeable only in the repository's\n // anchored PKH space form. Other TinyCloud space/DID syntaxes are opaque\n // method-specific identifiers and must remain byte-for-byte unchanged.\n const pkh = space.match(\n /^tinycloud:pkh:eip155:(\\d+):(0x[0-9a-fA-F]{40}):([^:]+)$/,\n );\n if (pkh !== null) {\n return `tinycloud:pkh:eip155:${pkh[1]}:${nodeSdk.canonicalizeAddress(pkh[2]!).toLowerCase()}:${pkh[3]}`;\n }\n return space;\n}\n\n/**\n * Builds a setup action URL without ever accepting a secret value. It opens\n * Secret Manager's app with the secret's name (and scope) filled in.\n */\nexport function buildSecretSetupUrl(reference: SecretReference): string {\n const parameters = [\n [\"secret\", reference.name],\n ...(reference.scope === undefined ? [] : [[\"scope\", reference.scope] as const]),\n [\"space\", reference.space],\n ] as const;\n const query = parameters\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join(\"&\");\n return `${SECRET_MANAGER_BASE_URL}/app?${query}`;\n}\n\nfunction canonicalizeSecretScope(scope: string | undefined): string | undefined {\n if (scope === undefined || scope === \"\") return undefined;\n\n const trimmed = scope.trim();\n if (trimmed === \"\") throw invalidSecretInput();\n\n const canonical = trimmed\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n if (canonical === \"\" || RESERVED_SECRET_SCOPES.has(canonical)) {\n throw invalidSecretInput();\n }\n return canonical;\n}\n\nfunction normalizeSecretsSpace(space: string | undefined): string {\n if (space === undefined || space === \"\") return DEFAULT_SECRETS_SPACE;\n\n if (space.startsWith(\"tinycloud:\")) {\n const parts = space.split(\":\");\n if (parts.length < 3 || parts.at(-1) === undefined || parts.at(-1) === \"\") {\n throw invalidSecretInput();\n }\n return `tinycloud:${parts.slice(1, -1).join(\":\")}:${parts.at(-1)}`;\n }\n\n if (!/^[A-Za-z0-9_-]+$/.test(space)) throw invalidSecretInput();\n return space;\n}\n\nfunction invalidSecretInput(): OperationInvocationError {\n return new OperationInvocationError(\n operationError(\"INPUT_INVALID\", \"The secret reference is invalid.\"),\n );\n}\n","export const OPERATION_ERROR_CODES = [\n \"INPUT_INVALID\",\n \"OPERATION_NOT_FOUND\",\n \"OPERATION_VERSION_UNSUPPORTED\",\n \"PROFILE_NOT_FOUND\",\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"PROFILE_OWNER_OPT_IN_REQUIRED\",\n \"AUTH_REQUIRED\",\n \"PERMISSION_DENIED\",\n \"SESSION_NOT_FOUND\",\n \"PERMISSION_HINT_INVALID\",\n \"DELEGATION_ARTIFACT_INVALID\",\n \"DELEGATION_EXPIRED\",\n \"DELEGATION_AUDIENCE_MISMATCH\",\n \"DELEGATION_HOST_MISMATCH\",\n \"DELEGATION_REJECTED\",\n \"ENCRYPTION_NETWORK_UNRESOLVED\",\n \"NODE_UNREACHABLE\",\n \"NODE_ERROR\",\n \"STORAGE_QUOTA_EXCEEDED\",\n \"KV_NOT_FOUND\",\n \"KV_PRECONDITION_FAILED\",\n \"KV_CONFLICT\",\n \"KV_RESPONSE_TOO_LARGE\",\n \"SQL_QUERY_INVALID\",\n \"SQL_EXECUTION_FAILED\",\n \"SQL_RESULT_LIMIT_EXCEEDED\",\n \"SQL_VALUE_UNSAFE\",\n \"SECRET_READ_FAILED\",\n \"SECRET_DECRYPT_FAILED\",\n \"OUTPUT_INVALID\",\n \"INTERNAL_ERROR\",\n] as const;\n\nexport type OperationErrorCode = (typeof OPERATION_ERROR_CODES)[number];\n\nexport interface OperationError {\n readonly code: OperationErrorCode;\n readonly message: string;\n readonly retryable: boolean;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\nexport function operationError(\n code: OperationErrorCode,\n message: string,\n options: Readonly<{\n retryable?: boolean;\n details?: Readonly<Record<string, unknown>>;\n }> = {},\n): OperationError {\n return {\n code,\n message,\n retryable: options.retryable ?? false,\n ...(options.details === undefined ? {} : { details: options.details }),\n };\n}\n\nconst MANAGE_STORAGE = \"Do not retry: the owner must free up space or upgrade at https://account.tinycloud.xyz/billing.\";\n\n/**\n * A write the node refused because the owner's TinyCloud storage is full\n * (SDK `STORAGE_QUOTA_EXCEEDED`, HTTP 402) or too small for this write\n * (`STORAGE_LIMIT_REACHED`, HTTP 413). Nothing was written, so the outcome is\n * known, and it stays refused until the owner acts, so it is never retryable.\n * The SDK's account totals travel as details; per-space numbers never do.\n */\nexport function storageFullOperationError(error: unknown): OperationError | undefined {\n if (typeof error !== \"object\" || error === null) return undefined;\n const { code, meta } = error as { code?: unknown; meta?: unknown };\n if (code !== \"STORAGE_QUOTA_EXCEEDED\" && code !== \"STORAGE_LIMIT_REACHED\") return undefined;\n const account = typeof meta === \"object\" && meta !== null ? (meta as { account?: unknown }).account : undefined;\n return operationError(\n \"STORAGE_QUOTA_EXCEEDED\",\n code === \"STORAGE_LIMIT_REACHED\"\n ? `This write is larger than the TinyCloud storage left, so nothing was written. Reading still works. ${MANAGE_STORAGE}`\n : `TinyCloud storage is full, so nothing was written. Reading still works. ${MANAGE_STORAGE}`,\n { retryable: false, ...(account === undefined ? {} : { details: { account } }) },\n );\n}\n\n/**\n * Internal operations and profile resolution use this for expected failures.\n * Generic exceptions are never exposed at the projection boundary.\n */\nexport class OperationInvocationError extends Error {\n public readonly operationError: OperationError;\n\n constructor(operationError: OperationError) {\n super(operationError.message);\n this.name = \"OperationInvocationError\";\n this.operationError = operationError;\n }\n}\n\nexport function isOperationErrorCode(value: unknown): value is OperationErrorCode {\n return typeof value === \"string\" && OPERATION_ERROR_CODES.includes(value as OperationErrorCode);\n}\n\nexport function internalOperationError(): OperationError {\n return operationError(\n \"INTERNAL_ERROR\",\n \"The operation could not be completed.\",\n );\n}\n\nexport function sanitizeThrownOperationError(error: unknown): OperationError {\n if (error instanceof OperationInvocationError) {\n return sanitizeOperationError(error.operationError);\n }\n\n return internalOperationError();\n}\n\nexport function sanitizeOperationError(error: unknown): OperationError {\n if (\n typeof error !== \"object\" ||\n error === null ||\n !isOperationErrorCode((error as { code?: unknown }).code) ||\n typeof (error as { message?: unknown }).message !== \"string\" ||\n typeof (error as { retryable?: unknown }).retryable !== \"boolean\"\n ) {\n return internalOperationError();\n }\n\n const candidate = error as OperationError;\n return operationError(candidate.code, candidate.message, {\n retryable: candidate.retryable,\n ...(candidate.details === undefined ? {} : { details: candidate.details }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAIA,QAAI,IAAI;AACR,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AAgBZ,WAAO,UAAU,SAAU,KAAK,SAAS;AACvC,gBAAU,WAAW,CAAC;AACtB,UAAI,OAAO,OAAO;AAClB,UAAI,SAAS,YAAY,IAAI,SAAS,GAAG;AACvC,eAAO,MAAM,GAAG;AAAA,MAClB,WAAW,SAAS,YAAY,SAAS,GAAG,GAAG;AAC7C,eAAO,QAAQ,OAAO,QAAQ,GAAG,IAAI,SAAS,GAAG;AAAA,MACnD;AACA,YAAM,IAAI;AAAA,QACR,0DACE,KAAK,UAAU,GAAG;AAAA,MACtB;AAAA,IACF;AAUA,aAAS,MAAM,KAAK;AAClB,YAAM,OAAO,GAAG;AAChB,UAAI,IAAI,SAAS,KAAK;AACpB;AAAA,MACF;AACA,UAAI,QAAQ,mIAAmI;AAAA,QAC7I;AAAA,MACF;AACA,UAAI,CAAC,OAAO;AACV;AAAA,MACF;AACA,UAAI,IAAI,WAAW,MAAM,CAAC,CAAC;AAC3B,UAAI,QAAQ,MAAM,CAAC,KAAK,MAAM,YAAY;AAC1C,cAAQ,MAAM;AAAA,QACZ,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AACH,iBAAO,IAAI;AAAA,QACb,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AACH,iBAAO,IAAI;AAAA,QACb,KAAK;AAAA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pB,CAAC,MAAM,QAAQ,IAAI,OAAO,KAAK,CAAC,IAAI,QAAQ,MAAM,CAAC,WAAW,OAAO,WAAW,QAAQ,KACxF,OAAO,IAAI,gBAAgB,YAC3B,OAAO,IAAI,iBAAiB,YAC5B,OAAO,IAAI,YAAY,YACvB,OAAO,IAAI,iBAAiB,kBAAkB,UAC9C;AACA,WAAO;AAAA,EACT;AACA,SAAO,EAAE,GAAG,KAAK,OAAO;AAC1B;AAEA,SAAS,UAAU,OAAoC;AACrD,QAAM,MAAM,SAAS,KAAK,KAAK,SAAS,MAAM,UAAU,IAAI,MAAM,WAAW,MAAM;AACnF,SAAO,OAAO,QAAQ,WAAW,MAAM;AACzC;AAGA,SAAS,UAAU,OAAoD;AACrE,QAAM,aAAa,MAAM;AACzB,MAAI,CAAC,SAAS,UAAU,KAAK,CAAC,SAAS,WAAW,gBAAgB,EAAG,QAAO;AAC5E,SAAO,KAAK,UAAU,CAAC,WAAW,KAAK,WAAW,iBAAiB,aAAa,CAAC;AACnF;AAEA,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;","names":["ms","crypto","crypto","isLE","_32n","length","join","length","length","_0n","_1n","_0n","_1n","Fp","Fp","_1n","isLE","_0n","_1n","_0n","_1n","base","wbits","isLE","_0n","Fp","Fn","_0n","_1n","_2n","_8n","Fp","Fn","uvRatio","p","randomBytes","adjustScalarBytes","eddsa","_0n","_1n","_2n","_3n","_5n","_8n","_1n","mod","_0n","encode","length","i","j","decode","encode","decode","encode","decode","decode","decode","equals","link","base","baseCache","equals","base","decode","length","cache","cid","equalBytes","equalBytes","nodeSdk","randomUUID","z","_a","ownership","_a","resolve","z","operationError","join"]}
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/ms/index.js","../../../node_modules/@noble/hashes/src/_u64.ts","../../../node_modules/@noble/hashes/src/cryptoNode.ts","../../../node_modules/@noble/hashes/src/utils.ts","../../../node_modules/@noble/hashes/src/_md.ts","../../../node_modules/@noble/hashes/src/sha2.ts","../src/delegation-binding.ts","../../sdk-core/src/manifest.ts","../../sdk-core/src/capabilities.ts","../../../node_modules/@noble/hashes/src/blake3.ts","../../../node_modules/@noble/hashes/src/_blake.ts","../../../node_modules/@noble/hashes/src/blake2.ts","../../../node_modules/@noble/curves/src/ed25519.ts","../../../node_modules/@noble/curves/src/utils.ts","../../../node_modules/@noble/curves/src/abstract/modular.ts","../../../node_modules/@noble/curves/src/abstract/curve.ts","../../../node_modules/@noble/curves/src/abstract/edwards.ts","../../../node_modules/multiformats/src/bytes.ts","../../../node_modules/multiformats/src/vendor/base-x.js","../../../node_modules/multiformats/src/bases/base.ts","../../../node_modules/multiformats/src/bases/base32.ts","../../../node_modules/multiformats/src/bases/base36.ts","../../../node_modules/multiformats/src/bases/base58.ts","../../../node_modules/multiformats/src/vendor/varint.js","../../../node_modules/multiformats/src/varint.ts","../../../node_modules/multiformats/src/hashes/digest.ts","../../../node_modules/multiformats/src/cid.ts","../../sdk-core/src/policy/unified.ts","../src/artifacts.ts","../src/authority.ts","../src/state.ts","../src/contract.ts","../src/secrets.ts","../src/errors.ts"],"sourcesContent":["/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n","/**\n * Internal webcrypto alias.\n * We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.\n * Falls back to Node.js built-in crypto for Node.js <=v14.\n * See utils.ts for details.\n * @module\n */\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto: any =\n nc && typeof nc === 'object' && 'webcrypto' in nc\n ? (nc.webcrypto as any)\n : nc && typeof nc === 'object' && 'randomBytes' in nc\n ? nc\n : undefined;\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\nexport class SHA224 extends SHA256 {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD<SHA512> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA384 extends SHA512 {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\nexport class SHA512_224 extends SHA512 {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n","import { join } from \"node:path\";\nimport { parseSignedCompactUcanAttenuation } from \"@tinycloud/sdk-core\";\n\n// Keep the value import namespace-shaped so modules that import this one stay\n// compatible with lightweight node-sdk test doubles.\nimport * as nodeSdk from \"@tinycloud/node-sdk\";\nimport type {\n PermissionEntry,\n PortableDelegation,\n RuntimeDelegationActivator,\n ValidatedRuntimeDelegation,\n} from \"@tinycloud/node-sdk\";\n\nimport { DelegationRequestBindingSchema } from \"./artifacts.js\";\nimport { delegationWithinRequest, type OperationSpaceResolver } from \"./authority.js\";\nimport { DELEGATION_CID_PATTERN, STORED_GRANT_SKIP_REASONS, type OperationWarning, type StoredGrantSkipReason } from \"./contract.js\";\nimport {\n profilePath,\n readAdditionalDelegations,\n readJson,\n readSession,\n updateProfileStore,\n withProfileLock,\n writeJsonAtomic,\n} from \"./state.js\";\n\nexport { operationSpaceResolver } from \"./secrets.js\";\nexport { STORED_GRANT_SKIP_REASONS } from \"./contract.js\";\nexport type { OperationWarning, StoredGrantSkipReason } from \"./contract.js\";\n\n/**\n * Request bindings for delegations stored in `additional-delegations.json`.\n *\n * A compact-UCAN or signed-login (SIWE) record replays only when its\n * `authorityRequest` binding is valid and the capabilities its signed bytes\n * grant fit inside the binding's `requested`. Validated activation checks that\n * before anything is activated. Three writers produce bindings:\n *\n * - `tinycloud.auth.import`: the stored request the delegation was checked\n * against (`requestId` is that request's).\n * - `tc auth import` of an artifact with no request: exactly the delegation's\n * own signed capabilities (`unbound-import:<cid>`).\n * - The one-time migration of records stored before bindings existed: exactly\n * each record's own signed capabilities (`migrated:<cid>`).\n * - The CLI's own grants (`tc auth request --grant`, permission escalation),\n * once checked against the request they answer: exactly each grant's own\n * signed capabilities (`cli-grant:<cid>`). Their signed-login records carry\n * the `siweProof` replay verifies them from.\n *\n * Signed-login records the CLI stored without a `siweProof` cannot be\n * verified from signed bytes and are not installed by either runtime.\n *\n * The binding is local profile data. It stops records written by any other\n * path from granting authority. It does not stop someone who can write the\n * profile directory, who already holds the session key and the signed bytes.\n */\n\nexport type BindingSource = \"migration\" | \"unbound-import\" | \"cli-grant\";\n\nconst REQUEST_ID_PREFIX: Record<BindingSource, string> = {\n migration: \"migrated\",\n \"unbound-import\": \"unbound-import\",\n \"cli-grant\": \"cli-grant\",\n};\n\n/** The audit note written beside a binding the record's writer synthesized. */\nexport const BINDING_NOTES: Record<BindingSource, string> = {\n migration:\n \"Stored without a request binding before bindings were required. Bound at migration to exactly \" +\n \"its own signed capabilities, so replay refuses any delegation in this record that exceeds them.\",\n \"unbound-import\":\n \"Imported by `tc auth import` without a stored request. Bound to exactly its own signed \" +\n \"capabilities, so replay refuses any delegation in this record that exceeds them.\",\n \"cli-grant\":\n \"Granted to this CLI by `tc auth request --grant` or a permission escalation, and checked \" +\n \"against the request it answered. Bound to exactly its own signed capabilities, so replay \" +\n \"refuses any delegation in this record that exceeds them.\",\n};\n\n/** Short so a busy profile only defers migration to a later runtime. */\nconst MIGRATION_LOCK_TIMEOUT_MS = 250;\n\n/** The per-profile marker: present once that profile's unbound records were migrated. */\nexport function bindingMigrationPath(profile: string): string {\n return join(profilePath(profile), \"delegation-binding-migration.json\");\n}\n\n/**\n * Compact and signed-login records require a valid request binding and signed\n * proof. A legacy record with no proof is classified `other` only so replay\n * can report `proof_missing`; it never installs. Malformed headers are refused.\n *\n * A header must contain exactly one `Authorization` string key: other shapes\n * might reach the node as authorization bytes this rule never examined.\n */\nexport function storedDelegationKind(\n entry: unknown,\n): \"compact\" | \"signed-login\" | \"other\" | \"refused\" {\n // A stored element that is not an object is not a record at all.\n if (!isRecord(entry)) return \"refused\";\n const delegation = entry.delegation;\n if (!isRecord(delegation)) return \"refused\";\n const header = delegation.delegationHeader;\n if (\n !isRecord(header) ||\n Object.keys(header).length !== 1 ||\n !Object.prototype.hasOwnProperty.call(header, \"Authorization\") ||\n typeof header.Authorization !== \"string\"\n ) {\n return \"refused\";\n }\n if (\"siweProof\" in delegation) return \"signed-login\";\n if (header.Authorization.includes(\".\")) return \"compact\";\n return \"other\";\n}\n\n/** A record replays only within a valid stored request binding. */\nexport function replayLimit(entry: unknown): readonly PermissionEntry[] | undefined {\n const kind = storedDelegationKind(entry);\n if (!isRecord(entry) || (kind !== \"compact\" && kind !== \"signed-login\")) return undefined;\n const binding = DelegationRequestBindingSchema.safeParse(entry.authorityRequest);\n return binding.success ? binding.data.requested : undefined;\n}\n\n/** Match node-sdk's normalization before validating a compact signature. */\nexport function withoutBearer(authorization: string): string {\n return authorization.replace(/^Bearer /i, \"\");\n}\n\nexport type StoredDelegationSource = \"cli-grant\" | \"unbound-import\" | \"migration\" | \"request\" | \"legacy\" | \"unknown\";\n\n/** Constrained labels only; never publish untrusted request IDs or audit notes. */\nexport function storedDelegationSource(entry: unknown): StoredDelegationSource {\n if (!isRecord(entry) || storedDelegationKind(entry) === \"refused\") return \"unknown\";\n if (!(\"authorityRequest\" in entry)) return \"legacy\";\n const binding = DelegationRequestBindingSchema.safeParse(entry.authorityRequest);\n if (!binding.success) return \"unknown\";\n const cid = storedCid(entry);\n if (cid === undefined) return \"unknown\";\n if (binding.data.requestId === `cli-grant:${cid}`) return \"cli-grant\";\n if (binding.data.requestId === `unbound-import:${cid}`) return \"unbound-import\";\n if (binding.data.requestId === `migrated:${cid}`) return \"migration\";\n return \"request\";\n}\n\n/**\n * Binds a record to `requested`, with an audit note naming where the binding\n * came from. Throws when `requested` cannot form a valid binding.\n */\nfunction bindToRequest<T extends { readonly delegation: { readonly cid: string } }>(\n record: T,\n requested: readonly PermissionEntry[],\n source: BindingSource,\n recordedAt = new Date().toISOString(),\n): T & Record<\"authorityRequest\" | \"authorityRequestAudit\", unknown> {\n return {\n ...record,\n authorityRequest: DelegationRequestBindingSchema.parse({\n requestId: `${REQUEST_ID_PREFIX[source]}:${record.delegation.cid}`,\n requested: structuredClone(requested),\n }),\n authorityRequestAudit: { source, recordedAt, note: BINDING_NOTES[source] },\n };\n}\n\n/**\n * Binds the record of one of the CLI's own grants, already checked against\n * the request it answers, to exactly the capabilities its signed bytes grant.\n * They are read through the validated activation replay uses (nothing is\n * activated), so the binding is the authority replay will derive. Throws when\n * validated activation cannot read them for `node`'s session.\n */\nexport async function bindCliGrant<T extends { readonly delegation: PortableDelegation }>(\n node: RuntimeDelegationActivator,\n record: T,\n host: string,\n): Promise<T & Record<\"authorityRequest\" | \"authorityRequestAudit\", unknown>> {\n const signed = await signedCapabilities(node, record.delegation, host);\n if (signed === undefined) {\n throw new Error(\"The grant's signed authority could not be validated for this session.\");\n }\n return bindToRequest(record, signed, \"cli-grant\");\n}\n\n/**\n * Validates and activates an imported compact or signed-login delegation,\n * binding its record to exactly its verified signed capabilities.\n */\nexport async function activateUnboundImport(\n node: RuntimeDelegationActivator,\n delegation: PortableDelegation,\n host: string,\n): Promise<{ delegation: PortableDelegation; permissions: PermissionEntry[] } & Record<string, unknown>> {\n const activated = await nodeSdk.activateValidatedRuntimeDelegation(node, delegation, {\n host,\n authorize: () => {\n verifyCompactProof(delegation);\n return true;\n },\n });\n return bindToRequest(\n { delegation, permissions: [...activated.effectivePermissions] },\n activated.effectivePermissions,\n \"unbound-import\",\n );\n}\n\n/**\n * The stored records after adding records written without a stored request\n * (by `tc auth import` or a CLI grant). A stored record for the same CID that\n * carries an `authorityRequest` is kept as it is, so this route never drops,\n * replaces or weakens a binding; otherwise each record replaces every row for\n * its CID, at the first one's position, or is appended. Callers write the\n * result under the profile lock they already use for this store.\n */\nexport function mergeDelegationsWithoutRequest(\n stored: readonly unknown[],\n incoming: readonly ({ readonly delegation: { readonly cid: string } } & Record<string, unknown>)[],\n): unknown[] {\n let records = [...stored];\n for (const record of incoming) {\n const cid = record.delegation.cid;\n if (records.some((entry) => storedCid(entry) === cid && isRecord(entry) && \"authorityRequest\" in entry)) continue;\n const position = records.findIndex((entry) => storedCid(entry) === cid);\n const others = records.filter((entry) => storedCid(entry) !== cid);\n records = position === -1\n ? [...records, record]\n : [...others.slice(0, position), record, ...others.slice(position)];\n }\n return records;\n}\n\n/**\n * Runs migration before replay reads the profile's records. Returns whether\n * the marker exists; replay refuses unbound records either way.\n *\n * Migration runs under the profile lock, and only while the persisted session\n * is still the one `node` restored. Each unbound compact record is checked\n * without activation and bound to exactly its signed capabilities, or left\n * unbound when validation fails. `migrate` must be false unless the node\n * holds the profile's own restored session.\n *\n * Migration is best-effort and restartable. Bound records are written before\n * the marker; a busy lock or failure leaves migration for a later runtime.\n * Records already bound by an interrupted run keep their bindings.\n */\nexport async function prepareStoredDelegationReplay(\n profile: string,\n node: RuntimeDelegationActivator,\n options: { readonly host: string; readonly migrate: boolean },\n): Promise<boolean> {\n if (await bindingMigrationRecorded(profile)) return true;\n // A persisted session without a `verificationMethod`, or one this node did\n // not restore, never migrates here; skip the lock rather than take it for\n // nothing on every command.\n if (!options.migrate || !await holdsPersistedSession(profile, node)) return false;\n try {\n return await withProfileLock(profile, async () => {\n if (await bindingMigrationRecorded(profile)) return true;\n // Checked again under the lock: a session rotated since the restore\n // leaves migration to a runtime of the new session.\n if (!await holdsPersistedSession(profile, node)) return false;\n const recordedAt = new Date().toISOString();\n const bound = new Map<string, Record<string, unknown>>();\n const unbound: string[] = [];\n for (const entry of await readAdditionalDelegations<unknown>(profile)) {\n // Elements that are not objects are skipped: they install nothing.\n if (!isRecord(entry) || \"authorityRequest\" in entry || storedDelegationKind(entry) !== \"compact\" ||\n storedDelegationForAnotherKey(entry, node)) continue;\n const migrated = await migratedRecord(node, entry, options.host, recordedAt);\n if (migrated === undefined) unbound.push(String(storedCid(entry)));\n else bound.set(recordKey(entry)!, migrated);\n }\n if (bound.size > 0) {\n await updateProfileStore<unknown, void>(profile, \"additional-delegations\", (records) => ({\n records: records.map((entry) => {\n const key = !isRecord(entry) || \"authorityRequest\" in entry ? undefined : recordKey(entry);\n return (key === undefined ? undefined : bound.get(key)) ?? entry;\n }),\n result: undefined,\n }));\n }\n await writeJsonAtomic(bindingMigrationPath(profile), {\n formatVersion: 1,\n migratedAt: recordedAt,\n bound: [...bound.values()].map(storedCid),\n unbound,\n });\n return true;\n }, { timeoutMs: MIGRATION_LOCK_TIMEOUT_MS });\n } catch {\n return false;\n }\n}\n\n/** Whether the profile's persisted session is the one `node` restored. */\nasync function holdsPersistedSession(profile: string, node: RuntimeDelegationActivator): Promise<boolean> {\n try {\n const persisted = await readSession<Record<string, unknown>>(profile);\n return typeof persisted?.verificationMethod === \"string\" &&\n typeof node.sessionDid === \"string\" &&\n persisted.verificationMethod.split(\"#\", 1)[0] === node.sessionDid.split(\"#\", 1)[0];\n } catch {\n return false;\n }\n}\n\n/** One record's migration: bound to its own signed capabilities, or `undefined` if it cannot be. */\nasync function migratedRecord(\n node: RuntimeDelegationActivator,\n entry: Record<string, unknown>,\n host: string,\n recordedAt: string,\n): Promise<Record<string, unknown> | undefined> {\n const delegation = normalizeStoredDelegation(entry);\n if (delegation === undefined) return undefined;\n const signed = await signedCapabilities(node, delegation, host);\n if (signed === undefined) return undefined;\n try {\n // The stored delegation is kept exactly as it was; only the binding is added.\n return bindToRequest({ ...entry, delegation: { ...entry.delegation as object, cid: delegation.cid } }, signed, \"migration\", recordedAt);\n } catch {\n // Signed capabilities a request binding cannot hold (an empty action, say).\n return undefined;\n }\n}\n\n/**\n * What replay did with one stored record. `skipped` records grant nothing and\n * carry a fixed reason code that is safe to publish; `not-replayed` records\n * are routine (expired) and give nothing to act on.\n */\nexport type StoredDelegationReplay =\n | { readonly status: \"installed\"; readonly delegation: ValidatedRuntimeDelegation }\n | { readonly status: \"skipped\"; readonly reason: StoredGrantSkipReason }\n | { readonly status: \"not-replayed\" };\n\nconst NOT_REPLAYED: StoredDelegationReplay = { status: \"not-replayed\" };\n\nfunction skipped(reason: StoredGrantSkipReason): StoredDelegationReplay {\n return { status: \"skipped\", reason };\n}\n\n/**\n * The single stored-grant replay path for CLI and canonical runtimes.\n * Migration runs before the store read; CID deduplication affects authority\n * only, not the per-record fixed-code skip diagnostics.\n */\nexport async function replayProfileDelegations(\n profile: string,\n node: RuntimeDelegationActivator,\n options: { readonly host: string; readonly migrate: boolean; readonly resolveSpace: OperationSpaceResolver },\n): Promise<{ installed: ValidatedRuntimeDelegation[]; warnings: OperationWarning[] }> {\n await prepareStoredDelegationReplay(profile, node, { host: options.host, migrate: options.migrate });\n return replayStoredDelegationRecords(profile, node, options);\n}\n\n/**\n * Replays the profile's stored records as they are, under the replay rule,\n * without migrating: no lock, no store or marker write. Runtimes that must\n * never write profile state (the `\"restored\"` runtime) call only this.\n */\nexport async function replayStoredDelegationRecords(\n profile: string,\n node: RuntimeDelegationActivator,\n options: { readonly host: string; readonly resolveSpace: OperationSpaceResolver },\n): Promise<{ installed: ValidatedRuntimeDelegation[]; warnings: OperationWarning[] }> {\n const installed: ValidatedRuntimeDelegation[] = [];\n const warnings: OperationWarning[] = [];\n const seen = new Set<string>();\n // Cross-user imports are retained for wallet-mode use, not replayed into\n // this session. They are neither broken bindings nor actionable skips.\n for (const entry of await readAdditionalDelegations<unknown>(profile)) {\n if (storedDelegationForAnotherKey(entry, node)) continue;\n const replay = await replayStoredDelegation(node, entry, options);\n if (replay.status === \"installed\") {\n if (!seen.has(replay.delegation.cid)) {\n seen.add(replay.delegation.cid);\n installed.push(replay.delegation);\n }\n } else if (replay.status === \"skipped\") {\n const grantCid = verifiedStoredCid(node, entry);\n warnings.push({\n code: \"STORED_GRANT_SKIPPED\",\n reason: replay.reason,\n ...(grantCid === undefined ? {} : { grantCid }),\n });\n }\n }\n return { installed, warnings };\n}\n\n/** Return an audience only after the exact compact bytes, CID and signature verify. */\nexport function verifiedCompactAudience(node: RuntimeDelegationActivator, delegation: PortableDelegation): string | undefined {\n const authorization = delegation.delegationHeader.Authorization;\n const token = withoutBearer(authorization);\n // Neither the CID helper nor the signature verifier may strip a second prefix.\n if (/^Bearer(?:\\s|$)/i.test(token)) return undefined;\n try {\n if (node.computeDelegationCid(authorization) !== delegation.cid) return undefined;\n return parseSignedCompactUcanAttenuation(token, delegation.cid).payload.aud;\n } catch {\n return undefined;\n }\n}\n\n/** Only a verified signed audience and matching transport audience can identify a foreign grant. */\nexport function storedDelegationForAnotherKey(entry: unknown, node: RuntimeDelegationActivator): boolean {\n if (storedDelegationKind(entry) !== \"compact\" || typeof node.sessionDid !== \"string\") return false;\n const delegation = normalizeStoredDelegation(entry);\n if (delegation === undefined) return false;\n const audience = verifiedCompactAudience(node, delegation);\n if (audience === undefined) return false;\n try {\n return nodeSdk.principalDidEquals(delegation.delegateDID, audience) &&\n !nodeSdk.principalDidEquals(audience, node.sessionDid);\n } catch {\n return false;\n }\n}\n\n/**\n * Publish a stored CID only when it matches the stored authorization bytes.\n * Free-text and even correctly shaped CIDs of different bytes stay private.\n */\nexport function verifiedStoredCid(node: RuntimeDelegationActivator, entry: unknown): string | undefined {\n const delegation = isRecord(entry) && isRecord(entry.delegation) ? entry.delegation : undefined;\n const header = isRecord(delegation?.delegationHeader) ? delegation.delegationHeader : undefined;\n const cid = delegation?.cid;\n if (typeof cid !== \"string\" || typeof header?.Authorization !== \"string\" ||\n typeof node.computeDelegationCid !== \"function\") return undefined;\n try {\n return node.computeDelegationCid(header.Authorization) === cid &&\n DELEGATION_CID.test(cid) ? cid : undefined;\n } catch {\n return undefined;\n }\n}\n\nconst DELEGATION_CID = new RegExp(DELEGATION_CID_PATTERN);\n\n/**\n * Replays one stored record under its binding, never installing an unbound or\n * unproven grant. Stored bytes and node messages are never published.\n */\nexport async function replayStoredDelegation(\n node: RuntimeDelegationActivator,\n entry: unknown,\n options: { readonly host: string; readonly resolveSpace: OperationSpaceResolver },\n): Promise<StoredDelegationReplay> {\n const result = await assess(node, entry, options, { activate: true });\n return result.status === \"verified\" ? skipped(\"invalid\") : result;\n}\n\nexport type StoredDelegationInspection =\n | { readonly local: \"verified\"; readonly cid: string; readonly effectivePermissions: readonly PermissionEntry[]; readonly expiry: Date }\n | { readonly local: \"refused\"; readonly reason: StoredGrantSkipReason }\n | { readonly local: \"not_checked\"; readonly because: \"expired\" | \"no_session\" };\n\n/**\n * Checks only local signed bytes, expiry, audience, resources and binding.\n * The node still decides delegation-chain validity and revocation at install.\n */\nexport async function inspectStoredDelegation(\n entry: unknown,\n options: { readonly node?: RuntimeDelegationActivator; readonly host?: string; readonly resolveSpace?: OperationSpaceResolver } = {},\n): Promise<StoredDelegationInspection> {\n const delegation = normalizeStoredDelegation(entry);\n if (storedDelegationKind(entry) === \"refused\" || delegation === undefined) {\n return { local: \"refused\", reason: \"malformed\" };\n }\n if (delegation.expiry.getTime() <= Date.now()) return { local: \"not_checked\", because: \"expired\" };\n if (options.node === undefined) return { local: \"not_checked\", because: \"no_session\" };\n const result = await assess(options.node, entry, {\n host: options.host ?? delegation.host ?? \"\",\n resolveSpace: options.resolveSpace,\n }, { activate: false });\n if (result.status === \"verified\") {\n return { local: \"verified\", cid: result.cid, effectivePermissions: result.effectivePermissions, expiry: result.expiry };\n }\n if (result.status === \"not-replayed\") return { local: \"not_checked\", because: \"expired\" };\n return { local: \"refused\", reason: result.status === \"skipped\" ? result.reason : \"invalid\" };\n}\n\ntype Assessment = StoredDelegationReplay |\n { readonly status: \"verified\"; readonly cid: string; readonly effectivePermissions: readonly PermissionEntry[]; readonly expiry: Date };\n\nasync function assess(\n node: RuntimeDelegationActivator,\n entry: unknown,\n options: { readonly host: string; readonly resolveSpace?: OperationSpaceResolver },\n mode: { readonly activate: boolean },\n): Promise<Assessment> {\n const kind = storedDelegationKind(entry);\n const delegation = normalizeStoredDelegation(entry);\n if (kind === \"refused\" || delegation === undefined) return skipped(\"malformed\");\n if (delegation.expiry.getTime() <= Date.now()) return NOT_REPLAYED;\n if (kind === \"other\") return skipped(\"proof_missing\");\n const limit = replayLimit(entry);\n if (limit === undefined) return skipped(\"unbound\");\n // Bearer is a storage/HTTP presentation prefix, not part of the signed\n // compact bytes. The node's invocation signer must receive the raw token.\n const authorization = withoutBearer(delegation.delegationHeader.Authorization);\n if (/^Bearer(?:\\s|$)/i.test(authorization)) return skipped(\"cid_mismatch\");\n const toActivate = authorization === delegation.delegationHeader.Authorization\n ? delegation\n : { ...delegation, delegationHeader: { Authorization: authorization }, authHeader: authorization };\n let outsideRequest = false;\n let effectivePermissions: readonly PermissionEntry[] | undefined;\n try {\n const installed = await nodeSdk.activateValidatedRuntimeDelegation(node, toActivate, {\n host: options.host,\n authorize: (effective) => {\n verifyCompactProof(toActivate);\n outsideRequest = !delegationWithinRequest(limit, effective, options.resolveSpace);\n if (outsideRequest) return false;\n effectivePermissions = effective;\n return mode.activate;\n },\n });\n return { status: \"installed\", delegation: installed };\n } catch (error) {\n if (outsideRequest) return skipped(\"outside_request\");\n if (effectivePermissions !== undefined && !mode.activate) {\n return { status: \"verified\", cid: delegation.cid, effectivePermissions, expiry: delegation.expiry };\n }\n // The node compares audiences before invoking `authorize`. A corrupted\n // compact signature must not be mislabeled as an audience mismatch when\n // its transport DID also differs from this session.\n if (kind === \"compact\" && rejectionReason(error) === \"audience_mismatch\") {\n try {\n verifyCompactProof(toActivate);\n } catch {\n return skipped(\"proof_invalid\");\n }\n }\n return skipped(rejectionReason(error));\n }\n}\n\n/** Compact grants must pass the strict local verifier before any installation. */\nfunction verifyCompactProof(delegation: PortableDelegation): void {\n const authorization = delegation.delegationHeader.Authorization;\n if (!withoutBearer(authorization).includes(\".\")) return;\n try {\n parseSignedCompactUcanAttenuation(withoutBearer(authorization), delegation.cid);\n } catch {\n throw new nodeSdk.RuntimeDelegationRejectedError(\"proof_invalid\", \"The compact delegation proof is invalid.\");\n }\n}\n\n/** The published reason node-sdk attached to a refused delegation, else `invalid`. */\nfunction rejectionReason(error: unknown): StoredGrantSkipReason {\n const reason = isRecord(error) ? error.reason : undefined;\n return typeof reason === \"string\" && (STORED_GRANT_SKIP_REASONS as readonly string[]).includes(reason)\n ? reason as StoredGrantSkipReason\n : \"invalid\";\n}\n\n/** An unreadable marker counts as migrated: a damaged marker never reopens migration. */\nexport async function bindingMigrationRecorded(profile: string): Promise<boolean> {\n try {\n return await readJson<unknown>(bindingMigrationPath(profile)) !== null;\n } catch {\n return true;\n }\n}\n\n/**\n * The capabilities a stored delegation's signed bytes grant, read through\n * validated activation, which `authorize` stops before anything is activated.\n */\nasync function signedCapabilities(\n node: RuntimeDelegationActivator,\n delegation: PortableDelegation,\n host: string,\n): Promise<readonly PermissionEntry[] | undefined> {\n let signed: readonly PermissionEntry[] | undefined;\n try {\n await nodeSdk.activateValidatedRuntimeDelegation(node, delegation, {\n // The transport host is not signed authority; check it at replay instead.\n host: delegation.host ?? host,\n authorize: (effective) => {\n verifyCompactProof(delegation);\n signed = effective;\n return false;\n },\n });\n } catch {\n // Refused by `authorize` once the capabilities were read, or failed a check before it.\n }\n return signed;\n}\n\nfunction normalizeStoredDelegation(entry: unknown): PortableDelegation | undefined {\n if (!isRecord(entry)) return undefined;\n const raw = entry.delegation;\n if (!isRecord(raw) || !isRecord(raw.delegationHeader)) return undefined;\n const expiry = raw.expiry instanceof Date\n ? raw.expiry\n : typeof raw.expiry === \"string\" ? new Date(raw.expiry) : undefined;\n if (\n expiry === undefined || Number.isNaN(expiry.getTime()) ||\n typeof raw.cid !== \"string\" ||\n typeof raw.spaceId !== \"string\" ||\n typeof raw.path !== \"string\" ||\n !Array.isArray(raw.actions) || !raw.actions.every((action) => typeof action === \"string\") ||\n typeof raw.delegateDID !== \"string\" ||\n typeof raw.ownerAddress !== \"string\" ||\n typeof raw.chainId !== \"number\" ||\n typeof raw.delegationHeader.Authorization !== \"string\"\n ) {\n return undefined;\n }\n return { ...raw, expiry } as PortableDelegation;\n}\n\nfunction storedCid(entry: unknown): string | undefined {\n const cid = isRecord(entry) && isRecord(entry.delegation) ? entry.delegation.cid : undefined;\n return typeof cid === \"string\" ? cid : undefined;\n}\n\n/** A record's CID and exact authorization bytes. */\nfunction recordKey(entry: Record<string, unknown>): string | undefined {\n const delegation = entry.delegation;\n if (!isRecord(delegation) || !isRecord(delegation.delegationHeader)) return undefined;\n return JSON.stringify([delegation.cid, delegation.delegationHeader.Authorization]);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","/**\n * TinyCloud App Manifest\n *\n * A declarative description of an app's identity and the capabilities it\n * needs. The manifest drives the SIWE recap at sign-in time, enabling a\n * single wallet prompt that covers the app's own permissions plus any\n * pre-declared delegations.\n *\n * The SDK does NOT fetch external manifests. Apps compose their own manifest\n * (optionally including backend or agent addenda) before handing it to the\n * SDK.\n *\n * Canonical spec: `.claude/specs/manifest.md`.\n *\n * @packageDocumentation\n */\n\nimport ms from \"ms\";\nimport { ACCOUNT_MANIFEST_PERMISSIONS } from \"@tinycloud/bootstrap\";\nimport { resolveSecretPath, SECRET_NAME_RE } from \"@tinycloud/sdk-services\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * A single permission entry inside a manifest. This is the shape apps write\n * in their `manifest.json` and the shape we compare against when performing\n * the capability-subset derivability check in the delegation flow.\n *\n * `service` uses the long form (e.g. `\"tinycloud.kv\"`, `\"tinycloud.sql\"`).\n * `\"tinycloud.vault\"` is an SDK-only shorthand that expands to the KV\n * resources the vault service uses; it is never encoded as a recap service.\n */\nexport interface PermissionEntry {\n /** Service namespace, e.g. \"tinycloud.kv\", \"tinycloud.sql\", \"tinycloud.duckdb\", \"tinycloud.capabilities\". */\n service: string;\n /** Space name or full space URI. Defaults to \"applications\" inside manifests. */\n space?: string;\n /**\n * Service-specific path.\n * - tinycloud.kv: hierarchical prefix. \"/\" = all, \"foo/\" = prefix match, \"foo\" = exact key\n * - tinycloud.sql: database name/file (e.g. \"data.sqlite\") or \"/\" for all\n * - tinycloud.duckdb: database name/file\n * - tinycloud.capabilities: capability key URI or \"/\" for all\n */\n path: string;\n /**\n * Short action names (e.g. \"get\", \"put\", \"read\", \"schema\"). The SDK expands\n * these to full URNs (e.g. `tinycloud.kv/get`) during resolution.\n * Already-expanded URNs are passed through unchanged.\n */\n actions: string[];\n /** Exact ReCap caveat branches when this authority came from a signed ReCap. */\n caveats?: Record<string, unknown>[];\n /** When true, the manifest prefix is NOT prepended to `path`. Default false. */\n skipPrefix?: boolean;\n /** Per-entry expiry override, ms-format. */\n expiry?: string;\n /** User/agent-facing context for why this permission is requested. */\n description?: string;\n}\n\nexport type ManifestSecretActions =\n | true\n | string\n | string[]\n | {\n /** Actual vault secret name. Defaults to the manifest object key. */\n name?: string;\n /** Optional scoped secret namespace. Omit for global secrets. */\n scope?: string;\n actions?: string | string[];\n expiry?: string;\n description?: string;\n };\n\n/**\n * The valid values for `Manifest.defaults`.\n *\n * - `false` → no auto-included permissions\n * - `true` → standard tier (KV + SQL read/write + capabilities:read)\n * - `\"admin\"` → standard + SQL schema\n * - `\"all\"` → everything the SDK supports (including DuckDB)\n *\n * Unknown string values silently fall back to `true`. Values are normalized\n * (lowercase + trim) before matching.\n */\nexport type ManifestDefaults = boolean | \"admin\" | \"all\";\n\n/**\n * Agent-readable app knowledge bundle pointer.\n *\n * - `true` means the default root: `knowledge/index.md`\n * - string values must point at a markdown root under `knowledge/`\n */\nexport type ManifestKnowledge = true | string;\n\n/** Default root used when `manifest.knowledge === true`. */\nexport const DEFAULT_KNOWLEDGE_ROOT = \"knowledge/index.md\";\n\n/**\n * The raw manifest shape an app declares. See `.claude/specs/manifest.md`.\n */\nexport interface Manifest {\n /** Schema version. Optional, defaults to 1. */\n manifest_version?: 1;\n /** Application identifier / namespace prefix. Required. */\n app_id: string;\n /** Display name. Required. */\n name: string;\n /** Description of what the app or delegate does. Optional. */\n description?: string;\n /** DID of this manifest's delegate target. Optional. Required only for delegation materialization. */\n did?: string;\n /** URL to app icon. Optional. */\n icon?: string;\n /** App version string. Optional. */\n appVersion?: string;\n /** Default expiry for permissions. ms-format (\"30d\", \"2h\", \"1y\"). Default \"30d\". */\n expiry?: string;\n /** Space name or full space URI. Optional, defaults to \"applications\". */\n space?: string;\n /**\n * Path prefix auto-prepended to permission paths. Optional, defaults to\n * `app_id`. Set to `\"\"` to disable entirely. Individual permissions can opt\n * out with `skipPrefix: true`.\n */\n prefix?: string;\n /**\n * Default permission set to auto-include. Optional, defaults to `true`.\n * See {@link ManifestDefaults}.\n */\n defaults?: ManifestDefaults | string;\n /** Whether to include the public-space companion delegation. Default `true`. */\n includePublicSpace?: boolean;\n /** Agent-readable knowledge bundle root. `true` means `knowledge/index.md`. */\n knowledge?: ManifestKnowledge;\n /**\n * Additional permissions beyond the defaults. Use for cross-space access,\n * DuckDB (opt-in), or `skipPrefix: true` entries.\n */\n permissions?: PermissionEntry[];\n /**\n * Secret name shorthand. Entries resolve to encrypted vault KV resources in\n * the `secrets` space.\n */\n secrets?: Record<string, ManifestSecretActions>;\n}\n\n/**\n * A resolved permission entry with fully-expanded paths and action URNs.\n * This is the shape the delegation flow compares against parsed recap\n * capabilities, and the shape the session-key delegation path actually uses.\n */\nexport interface ResourceCapability {\n /** Long-form service, e.g. \"tinycloud.kv\". */\n service: string;\n /** Space name or URI. Short names are resolved to full SpaceIds at sign-in time. */\n space: string;\n /** Path with the manifest prefix applied (or skipped per `skipPrefix`). */\n path: string;\n /** Full-URN actions, e.g. [\"tinycloud.kv/get\", \"tinycloud.kv/put\"]. */\n actions: string[];\n /** Per-entry expiry override in milliseconds. */\n expiryMs?: number;\n /** User/agent-facing context copied from the source permission entry. */\n description?: string;\n}\n\n/**\n * A resolved delegation entry with fully-expanded permissions.\n */\nexport interface ResolvedDelegate {\n /** DID of the delegate. */\n did: string;\n /** Informational display name. Optional. */\n name?: string;\n /** Expiry in milliseconds (per-delegation > manifest default > 30 days). */\n expiryMs: number;\n /** Fully resolved permissions. */\n permissions: ResourceCapability[];\n}\n\n/**\n * The output of {@link resolveManifest}: a fully-expanded capability set\n * ready to drive the SIWE recap.\n */\nexport interface ResolvedCapabilities {\n /** Application identifier copied from manifest.app_id. */\n app_id: string;\n /** Delegate DID copied from manifest.did, when present. */\n did?: string;\n /** Effective default space for this manifest. */\n space: string;\n /** All session-key resources with paths fully resolved (prefix applied). */\n resources: ResourceCapability[];\n /** Default expiry for the session, in milliseconds. */\n expiryMs: number;\n /** Whether to include the public-space companion. */\n includePublicSpace: boolean;\n /** Delegate targets derived from manifests that declare `did`. */\n additionalDelegates: ResolvedDelegate[];\n}\n\nexport interface ManifestRegistryRecord {\n /** KV key inside the account space. */\n key: string;\n /** App id this record describes. */\n app_id: string;\n /** Latest manifest payloads composed for this app id. */\n manifests: Manifest[];\n}\n\nexport interface ComposeManifestOptions {\n /** Include implicit account-space registry permissions. Default true. */\n includeAccountRegistryPermissions?: boolean;\n}\n\nexport interface ComposedManifestRequest {\n /** Validated manifests that were composed. */\n manifests: Manifest[];\n /** Full permission union requested from the user in one SIWE. */\n resources: ResourceCapability[];\n /** Delegations that can be materialized after sign-in. */\n delegationTargets: ResolvedDelegate[];\n /** Account-space registry records to write after successful sign-in. */\n registryRecords: ManifestRegistryRecord[];\n /** Effective session expiry, using the longest composed manifest expiry. */\n expiryMs: number;\n /** Whether to include the public-space companion behavior. */\n includePublicSpace: boolean;\n}\n\n/**\n * Thrown when the manifest fails validation (missing id/name, bad expiry,\n * empty actions on a permission, etc).\n */\nexport class ManifestValidationError extends Error {\n constructor(message: string) {\n super(`Manifest validation failed: ${message}`);\n this.name = \"ManifestValidationError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Default expiry when neither the manifest, delegation, nor permission\n * specifies one. APP tier — see `expiry.ts`. Spec: 30 days.\n *\n * Kept as an ms-format string because the manifest schema stores expiry\n * as a string and the parser is shared between this default and\n * caller-provided values; converting `EXPIRY.APP_MS` back to a string\n * here would duplicate that same `30d` literal in another form.\n */\nexport const DEFAULT_EXPIRY = \"30d\";\n\n/**\n * Default `defaults` value when the manifest omits it. Spec: standard tier.\n */\nexport const DEFAULT_DEFAULTS: ManifestDefaults = true;\n\n/** Default manifest schema version. */\nexport const DEFAULT_MANIFEST_VERSION = 1;\n\n/** Default space for manifest-declared app data. */\nexport const DEFAULT_MANIFEST_SPACE = \"applications\";\n\n/** Account-space name used for installed-application registry records. */\nexport const ACCOUNT_REGISTRY_SPACE = \"account\";\n\n/** Account-space KV prefix used for installed-application registry records. */\nexport const ACCOUNT_REGISTRY_PATH = \"applications/\";\n\nexport const SECRETS_SPACE = \"secrets\";\n\n/** SDK-only permission service for encrypted vault resources. */\nexport const VAULT_PERMISSION_SERVICE = \"tinycloud.vault\";\n\ntype VaultKVBase = \"vault\";\n\ninterface VaultActionExpansion {\n bases: readonly VaultKVBase[];\n action: string;\n}\n\n/**\n * Known services and their short-form (recap URI) names. The TinyCloud\n * node encodes the recap resource URI with the short service name, while\n * action URNs and manifest entries use the long `tinycloud.<short>` form.\n * This table is the canonical bridge between the two.\n */\nexport const SERVICE_SHORT_TO_LONG: Readonly<Record<string, string>> =\n Object.freeze({\n kv: \"tinycloud.kv\",\n sql: \"tinycloud.sql\",\n duckdb: \"tinycloud.duckdb\",\n capabilities: \"tinycloud.capabilities\",\n hooks: \"tinycloud.hooks\",\n encryption: \"tinycloud.encryption\",\n delegation: \"tinycloud.delegation\",\n });\n\n/**\n * Manifest service identifier for TinyCloud encryption network grants.\n *\n * Encryption permissions live on a network id URN\n * (`urn:tinycloud:encryption:<ownerDid>:<network>`), not on a space.\n * The `path` field is the literal networkId; `actions` are\n * `[\"decrypt\"]` (expanded to `[\"tinycloud.encryption/decrypt\"]`).\n *\n * Apps should omit `space` for encryption permissions. The SDK may emit\n * an internal `\"encryption\"` compatibility label after expansion so the\n * older `PermissionEntry`/`ResourceCapability` shape can still carry the\n * raw network URN through subset checks.\n */\nexport const ENCRYPTION_PERMISSION_SERVICE = \"tinycloud.encryption\";\n\n/** Synthetic space label used by encryption manifest entries. */\nexport const ENCRYPTION_MANIFEST_SPACE = \"encryption\";\n\n/**\n * Inverse of {@link SERVICE_SHORT_TO_LONG}.\n */\nexport const SERVICE_LONG_TO_SHORT: Readonly<Record<string, string>> =\n Object.freeze(\n Object.fromEntries(\n Object.entries(SERVICE_SHORT_TO_LONG).map(([s, l]) => [l, s]),\n ),\n );\n\n/**\n * Default permission entries for the `true` / standard tier.\n *\n * `tinycloud.capabilities/read` is added separately for every requested\n * space, without the app path prefix. That keeps capability introspection\n * space-scoped instead of app-data scoped.\n */\nconst DEFAULT_STANDARD_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\"],\n },\n];\n\n/**\n * Default permission entries for the `\"admin\"` tier: standard + sql/schema.\n */\nconst DEFAULT_ADMIN_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\", \"schema\"],\n },\n];\n\n/**\n * Default permission entries for the `\"all\"` tier: admin + DuckDB.\n *\n * DuckDB is opt-in and only appears in this tier or in explicit manifest\n * `permissions` entries.\n */\nconst DEFAULT_ALL_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\", \"schema\"],\n },\n {\n service: \"tinycloud.duckdb\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\"],\n },\n];\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Parse an ms-format duration string (e.g. \"30d\", \"2h\", \"1y\") into\n * milliseconds.\n *\n * @throws {ManifestValidationError} on empty string, non-string input, or\n * any input `ms()` cannot parse.\n */\nexport function parseExpiry(duration: string): number {\n if (typeof duration !== \"string\" || duration.length === 0) {\n throw new ManifestValidationError(\n `expiry must be a non-empty duration string (got ${JSON.stringify(duration)})`,\n );\n }\n // `ms` returns `undefined` for unparseable input and can return a number\n // or a string depending on the call signature; cast explicitly.\n const parsed = (ms as unknown as (v: string) => number | undefined)(duration);\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new ManifestValidationError(\n `invalid expiry duration: ${JSON.stringify(duration)}`,\n );\n }\n return parsed;\n}\n\n/**\n * Expand a list of action short names (or already-expanded URNs) into full\n * ability URNs of the form `<service>/<action>`.\n *\n * Examples:\n * `expandActionShortNames(\"tinycloud.kv\", [\"get\", \"put\"])`\n * → `[\"tinycloud.kv/get\", \"tinycloud.kv/put\"]`\n * `expandActionShortNames(\"tinycloud.kv\", [\"tinycloud.kv/get\"])`\n * → `[\"tinycloud.kv/get\"]` (passed through unchanged)\n */\nexport function expandActionShortNames(\n service: string,\n actions: readonly string[],\n): string[] {\n return actions.map((a) => {\n if (a.includes(\"/\")) {\n // Already a full URN — pass through.\n return a;\n }\n return `${service}/${a}`;\n });\n}\n\n/**\n * Expand SDK virtual permission services into concrete recap-capable services.\n *\n * Today this handles `\"tinycloud.vault\"`, which is backed by inline\n * network-encrypted KV records:\n * - read/get: `vault/<path>` with `tinycloud.kv/get`\n * - write/put: `vault/<path>` with `tinycloud.kv/put`\n * - delete/del: `vault/<path>` with `tinycloud.kv/del`\n * - list: `vault/<path>` with `tinycloud.kv/list`\n * - head: `vault/<path>` with `tinycloud.kv/get`\n * - metadata: `vault/<path>` with `tinycloud.kv/metadata`\n */\nexport function expandPermissionEntry(entry: PermissionEntry): PermissionEntry[] {\n if (entry.service === ENCRYPTION_PERMISSION_SERVICE) {\n return expandEncryptionPermissionEntry(entry);\n }\n if (entry.service !== VAULT_PERMISSION_SERVICE) {\n return [\n {\n ...entry,\n actions: expandActionShortNames(entry.service, entry.actions),\n },\n ];\n }\n\n return expandVaultPermissionEntry(entry);\n}\n\n/**\n * Expand a `tinycloud.encryption` manifest entry.\n *\n * - `path` MUST be a networkId URN (`urn:tinycloud:encryption:...`).\n * The manifest prefix is always skipped — network ids are top-level\n * owner-scoped resources, not space-scoped paths.\n * - `actions` must be `decrypt`, `network.create`, or `network.revoke`\n * (or their already-expanded `tinycloud.encryption/*` forms).\n *\n * The returned entry uses an internal `space = \"encryption\"` compatibility\n * label so old manifest grouping code does not collapse it into the app's\n * data space, and `skipPrefix` is forced to `true` so the prefix application\n * step is a no-op.\n */\nfunction expandEncryptionPermissionEntry(\n entry: PermissionEntry,\n): PermissionEntry[] {\n if (\n typeof entry.path !== \"string\" ||\n !entry.path.startsWith(\"urn:tinycloud:encryption:\")\n ) {\n throw new ManifestValidationError(\n `tinycloud.encryption entries require path to be a networkId URN ` +\n `(got ${JSON.stringify(entry.path)})`,\n );\n }\n const normalizedActions: string[] = [];\n for (const action of entry.actions) {\n if (action === \"decrypt\" || action === \"tinycloud.encryption/decrypt\") {\n normalizedActions.push(\"tinycloud.encryption/decrypt\");\n continue;\n }\n if (\n action === \"network.create\" ||\n action === \"tinycloud.encryption/network.create\"\n ) {\n normalizedActions.push(\"tinycloud.encryption/network.create\");\n continue;\n }\n if (\n action === \"network.revoke\" ||\n action === \"tinycloud.encryption/network.revoke\"\n ) {\n normalizedActions.push(\"tinycloud.encryption/network.revoke\");\n continue;\n }\n if (action.includes(\"/\")) {\n throw new ManifestValidationError(\n `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`,\n );\n }\n throw new ManifestValidationError(\n `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`,\n );\n }\n // Dedupe while preserving order\n const dedupedActions: string[] = [];\n const seen = new Set<string>();\n for (const a of normalizedActions) {\n if (!seen.has(a)) {\n dedupedActions.push(a);\n seen.add(a);\n }\n }\n // Encryption resources are network-scoped, not space-scoped. We\n // always emit the synthetic \"encryption\" space label so manifest\n // grouping can deal with it uniformly without collapsing the\n // networkId URN into an app data space.\n return [\n {\n service: ENCRYPTION_PERMISSION_SERVICE,\n space: ENCRYPTION_MANIFEST_SPACE,\n path: entry.path,\n actions: dedupedActions,\n skipPrefix: true,\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n },\n ];\n}\n\n/**\n * Expand a list of permission entries using {@link expandPermissionEntry}.\n */\nexport function expandPermissionEntries(\n entries: readonly PermissionEntry[],\n): PermissionEntry[] {\n return entries.flatMap(expandPermissionEntry);\n}\n\n/**\n * Apply the manifest prefix to a permission path per the spec rules.\n *\n * - `skipPrefix: true` → path is returned as-is\n * - `prefix === \"\"` → path is returned as-is\n * - path starts with \"/\" → `prefix + path` (e.g. \"com.listen.app\" + \"/\" → \"com.listen.app/\")\n * - otherwise → `prefix + \"/\" + path` (e.g. \"com.listen.app\" + \"data.sqlite\" → \"com.listen.app/data.sqlite\")\n */\nexport function applyPrefix(\n prefix: string,\n path: string,\n skipPrefix: boolean,\n): string {\n if (skipPrefix) {\n return path;\n }\n if (prefix === \"\") {\n return path;\n }\n if (path.startsWith(\"/\")) {\n return `${prefix}${path}`;\n }\n return `${prefix}/${path}`;\n}\n\n/**\n * Fetch and parse a manifest from a URL (browser) or file path (node).\n * The runtime decides the fetch strategy via `globalThis.fetch`; this is\n * platform-agnostic. Callers that want custom loading should JSON.parse a\n * Manifest themselves and skip this helper.\n *\n * @throws if the fetch fails, the JSON is invalid, or the manifest fails\n * validation.\n */\nexport async function loadManifest(url: string): Promise<Manifest> {\n const fetchFn: typeof fetch | undefined = (\n globalThis as { fetch?: typeof fetch }\n ).fetch;\n if (typeof fetchFn !== \"function\") {\n throw new ManifestValidationError(\n \"loadManifest requires a global fetch; pass the manifest object directly on runtimes without fetch\",\n );\n }\n const res = await fetchFn(url);\n if (!res.ok) {\n throw new ManifestValidationError(\n `failed to fetch manifest from ${url}: HTTP ${res.status}`,\n );\n }\n const json = (await res.json()) as unknown;\n return validateManifest(json);\n}\n\n/**\n * Validate a manifest-shaped object and return it strongly-typed.\n * Throws {@link ManifestValidationError} on any hard failure.\n */\nexport function validateManifest(input: unknown): Manifest {\n if (input === null || typeof input !== \"object\") {\n throw new ManifestValidationError(\"manifest must be an object\");\n }\n const m = input as Manifest;\n if (\n m.manifest_version !== undefined &&\n m.manifest_version !== DEFAULT_MANIFEST_VERSION\n ) {\n throw new ManifestValidationError(\n `manifest.manifest_version must be ${DEFAULT_MANIFEST_VERSION}`,\n );\n }\n if (typeof m.app_id !== \"string\" || m.app_id.length === 0) {\n throw new ManifestValidationError(\n \"manifest.app_id is required and must be a non-empty string\",\n );\n }\n if (typeof m.name !== \"string\" || m.name.length === 0) {\n throw new ManifestValidationError(\n \"manifest.name is required and must be a non-empty string\",\n );\n }\n if (\n m.did !== undefined &&\n (typeof m.did !== \"string\" || m.did.length === 0)\n ) {\n throw new ManifestValidationError(\n \"manifest.did must be a non-empty DID string\",\n );\n }\n if (\n m.space !== undefined &&\n (typeof m.space !== \"string\" || m.space.length === 0)\n ) {\n throw new ManifestValidationError(\n \"manifest.space must be a non-empty string\",\n );\n }\n if (m.expiry !== undefined) {\n // Will throw with a clear error if invalid.\n parseExpiry(m.expiry);\n }\n if (m.knowledge !== undefined) {\n resolveManifestKnowledgeRoot(m.knowledge);\n }\n if (m.permissions !== undefined) {\n if (!Array.isArray(m.permissions)) {\n throw new ManifestValidationError(\n \"manifest.permissions must be an array\",\n );\n }\n m.permissions.forEach((p, i) =>\n validatePermissionEntry(p, `permissions[${i}]`),\n );\n }\n if (m.secrets !== undefined) {\n validateManifestSecrets(m.secrets);\n }\n return m;\n}\n\n/**\n * Resolve a manifest knowledge pointer to its root markdown file.\n *\n * This is metadata only; app knowledge does not create capabilities.\n */\nexport function resolveManifestKnowledgeRoot(\n knowledge: Manifest[\"knowledge\"] | undefined,\n): string | undefined {\n if (knowledge === undefined) {\n return undefined;\n }\n if (knowledge === true) {\n return DEFAULT_KNOWLEDGE_ROOT;\n }\n if (typeof knowledge !== \"string\" || knowledge.length === 0) {\n throw new ManifestValidationError(\n \"manifest.knowledge must be true or a knowledge/*.md root path\",\n );\n }\n if (!/^knowledge\\/.+\\.md$/.test(knowledge)) {\n throw new ManifestValidationError(\n \"manifest.knowledge must be true or a knowledge/*.md root path\",\n );\n }\n return knowledge;\n}\n\nfunction validateManifestSecrets(secrets: unknown): void {\n if (secrets === null || typeof secrets !== \"object\" || Array.isArray(secrets)) {\n throw new ManifestValidationError(\"manifest.secrets must be an object\");\n }\n\n for (const [name, spec] of Object.entries(secrets)) {\n if (!SECRET_NAME_RE.test(name)) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} must match ${SECRET_NAME_RE.source}`,\n );\n }\n try {\n resolveSecretPath(\n secretNameFromSpec(name, spec as ManifestSecretActions),\n { scope: secretScopeFromSpec(spec as ManifestSecretActions) },\n );\n } catch (error) {\n throw new ManifestValidationError(\n `manifest.secrets.${name}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const actions = secretActionsFromSpec(name, spec as ManifestSecretActions);\n if (actions.length === 0) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} actions must be non-empty`,\n );\n }\n for (const action of actions) {\n if (typeof action !== \"string\" || action.length === 0) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} actions must be non-empty strings`,\n );\n }\n }\n if (\n spec !== null &&\n typeof spec === \"object\" &&\n !Array.isArray(spec) &&\n (spec as { expiry?: unknown }).expiry !== undefined\n ) {\n parseExpiry((spec as { expiry: string }).expiry);\n }\n }\n}\n\nfunction validatePermissionEntry(p: unknown, path: string): void {\n if (p === null || typeof p !== \"object\") {\n throw new ManifestValidationError(`${path} must be an object`);\n }\n const entry = p as PermissionEntry;\n if (typeof entry.service !== \"string\" || entry.service.length === 0) {\n throw new ManifestValidationError(`${path}.service is required`);\n }\n if (\n entry.space !== undefined &&\n (typeof entry.space !== \"string\" || entry.space.length === 0)\n ) {\n throw new ManifestValidationError(\n `${path}.space must be a non-empty string`,\n );\n }\n if (typeof entry.path !== \"string\") {\n throw new ManifestValidationError(\n `${path}.path is required (use \"\" or \"/\" for root)`,\n );\n }\n if (!Array.isArray(entry.actions) || entry.actions.length === 0) {\n throw new ManifestValidationError(\n `${path}.actions must be a non-empty array`,\n );\n }\n for (const action of entry.actions) {\n if (typeof action !== \"string\" || action.length === 0) {\n throw new ManifestValidationError(\n `${path}.actions must contain non-empty strings`,\n );\n }\n if (entry.service === VAULT_PERMISSION_SERVICE) {\n vaultActionExpansion(action);\n }\n }\n if (entry.caveats !== undefined &&\n (!Array.isArray(entry.caveats) || entry.caveats.some((caveat) =>\n caveat === null || typeof caveat !== \"object\" || Array.isArray(caveat)\n ))\n ) {\n throw new ManifestValidationError(`${path}.caveats must be an array of objects`);\n }\n if (entry.expiry !== undefined) {\n parseExpiry(entry.expiry);\n }\n}\n\n/**\n * Normalize a `defaults` value: lowercase + trim, then match against known\n * tiers. Unknown string values silently fall back to `true` (standard).\n * Boolean values pass through.\n */\nexport function normalizeDefaults(\n value: Manifest[\"defaults\"] | undefined,\n): ManifestDefaults {\n if (value === undefined) {\n return DEFAULT_DEFAULTS;\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value !== \"string\") {\n // Spec says unknown values silently fall back to `true`.\n return true;\n }\n const normalized = value.trim().toLowerCase();\n if (normalized === \"admin\" || normalized === \"all\") {\n return normalized;\n }\n // Anything else, including \"true\"/\"false\"/\"standard\"/garbage, falls back\n // to the standard tier per spec.\n return true;\n}\n\n/**\n * Return the default permission entries for the given tier. Entries are\n * deep-cloned so callers can mutate them without affecting the constants.\n */\nfunction defaultEntriesForTier(tier: ManifestDefaults): PermissionEntry[] {\n if (tier === false) {\n return [];\n }\n const source =\n tier === \"admin\"\n ? DEFAULT_ADMIN_ENTRIES\n : tier === \"all\"\n ? DEFAULT_ALL_ENTRIES\n : DEFAULT_STANDARD_ENTRIES;\n return source.map((e) => ({\n service: e.service,\n space: e.space,\n path: e.path,\n actions: [...e.actions],\n ...(e.skipPrefix !== undefined ? { skipPrefix: e.skipPrefix } : {}),\n }));\n}\n\n/**\n * Resolve a raw manifest into a {@link ResolvedCapabilities} object: expand\n * shortform actions, apply the prefix, merge defaults, and compute effective\n * expiries. Pure function — does no I/O.\n *\n * Resolution semantics (spec):\n * - `prefix` defaults to `app_id`; set to `\"\"` to disable prefix application entirely.\n * - `space` defaults to `applications`; per-permission `space` overrides it.\n * - `defaults` defaults to `true` (standard tier); unknown string values fall back to `true`.\n * - Per-entry expiry overrides per-delegation overrides manifest > `DEFAULT_EXPIRY`.\n * - Default entries use `skipPrefix: false` so they inherit the manifest prefix.\n */\nexport function resolveManifest(input: Manifest): ResolvedCapabilities {\n const manifest = validateManifest(input);\n\n const prefix =\n manifest.prefix !== undefined ? manifest.prefix : manifest.app_id;\n const space = manifest.space ?? DEFAULT_MANIFEST_SPACE;\n const expiryMs = parseExpiry(manifest.expiry ?? DEFAULT_EXPIRY);\n const includePublicSpace = manifest.includePublicSpace ?? true;\n const tier = normalizeDefaults(manifest.defaults);\n\n const defaultEntries = defaultEntriesForTier(tier);\n const explicitEntries = manifest.permissions ?? [];\n const secretEntries = secretEntriesForManifest(manifest.secrets);\n\n // Merge order: defaults first, then explicit entries, so explicit entries\n // for the same (service, space, path) tuple override defaults.\n const allEntries: PermissionEntry[] = [\n ...defaultEntries,\n ...explicitEntries,\n ...secretEntries,\n ];\n\n const resources: ResourceCapability[] = withCapabilitiesReadForSpaces(\n allEntries.flatMap((entry) => resolveEntry(entry, prefix, expiryMs, space)),\n );\n\n const additionalDelegates: ResolvedDelegate[] =\n manifest.did === undefined\n ? []\n : [\n {\n did: manifest.did,\n name: manifest.name,\n expiryMs,\n permissions: resources.map(cloneResourceCapability),\n },\n ];\n\n return {\n app_id: manifest.app_id,\n ...(manifest.did !== undefined ? { did: manifest.did } : {}),\n space,\n resources,\n expiryMs,\n includePublicSpace,\n additionalDelegates,\n };\n}\n\nfunction normalizeSecretActions(actions: readonly string[]): string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n const add = (action: string) => {\n if (!seen.has(action)) {\n out.push(action);\n seen.add(action);\n }\n };\n\n for (const action of actions) {\n if (action === \"read\") {\n add(\"get\");\n continue;\n }\n if (action === \"write\") {\n add(\"put\");\n continue;\n }\n if (action === \"delete\") {\n add(\"del\");\n continue;\n }\n if (\n action === \"get\" ||\n action === \"put\" ||\n action === \"del\" ||\n action === \"list\" ||\n action === \"metadata\"\n ) {\n add(action);\n continue;\n }\n if (\n action === \"tinycloud.kv/get\" ||\n action === \"tinycloud.kv/put\" ||\n action === \"tinycloud.kv/del\" ||\n action === \"tinycloud.kv/list\" ||\n action === \"tinycloud.kv/metadata\"\n ) {\n add(action);\n continue;\n }\n throw new ManifestValidationError(\n `unknown secret action ${JSON.stringify(action)}; expected read, write, delete, list, or metadata`,\n );\n }\n\n return out;\n}\n\nfunction secretNameFromSpec(\n fallbackName: string,\n spec: ManifestSecretActions,\n): string {\n if (spec !== null && typeof spec === \"object\" && !Array.isArray(spec)) {\n return spec.name ?? fallbackName;\n }\n return fallbackName;\n}\n\nfunction secretScopeFromSpec(\n spec: ManifestSecretActions,\n): string | undefined {\n if (spec !== null && typeof spec === \"object\" && !Array.isArray(spec)) {\n return spec.scope;\n }\n return undefined;\n}\n\nfunction secretActionsFromSpec(\n name: string,\n spec: ManifestSecretActions,\n): string[] {\n if (spec === true) {\n return [\"read\"];\n }\n if (typeof spec === \"string\") {\n return [spec];\n }\n if (Array.isArray(spec)) {\n return spec;\n }\n if (spec === null || typeof spec !== \"object\") {\n throw new ManifestValidationError(\n `manifest.secrets.${name} must be true, a string action, an actions array, or an object`,\n );\n }\n if (spec.actions === undefined) {\n return [\"read\"];\n }\n if (typeof spec.actions === \"string\") {\n return [spec.actions];\n }\n if (Array.isArray(spec.actions)) {\n return spec.actions;\n }\n throw new ManifestValidationError(\n `manifest.secrets.${name}.actions must be a string or array`,\n );\n}\n\nfunction secretEntriesForManifest(\n secrets: Manifest[\"secrets\"] | undefined,\n): PermissionEntry[] {\n if (secrets === undefined) {\n return [];\n }\n\n const entries: PermissionEntry[] = [];\n for (const [name, spec] of Object.entries(secrets)) {\n const actions = secretActionsFromSpec(name, spec);\n const secretPath = resolveSecretPath(\n secretNameFromSpec(name, spec),\n { scope: secretScopeFromSpec(spec) },\n );\n const extra: { expiry?: string; description?: string } =\n spec !== true && typeof spec === \"object\" && !Array.isArray(spec)\n ? spec\n : {};\n entries.push({\n service: VAULT_PERMISSION_SERVICE,\n space: SECRETS_SPACE,\n path: secretPath.vaultKey,\n actions: normalizeSecretActions(actions),\n skipPrefix: true,\n ...(extra.expiry !== undefined ? { expiry: extra.expiry } : {}),\n ...(extra.description !== undefined\n ? { description: extra.description }\n : {}),\n });\n }\n return entries;\n}\n\n/**\n * Expand a single permission entry into a {@link ResourceCapability}:\n * apply the prefix to the path and expand short actions into full URNs.\n */\nfunction resolveEntry(\n entry: PermissionEntry,\n prefix: string,\n _inheritedExpiryMs: number,\n inheritedSpace: string,\n): ResourceCapability[] {\n // Encryption permissions reference a networkId URN as their resource\n // — the manifest prefix is meaningless against a top-level\n // owner-scoped resource and would corrupt the URN. Always skip.\n const skipPrefixForEntry =\n entry.skipPrefix === true ||\n entry.service === ENCRYPTION_PERMISSION_SERVICE;\n const resolvedPath = applyPrefix(prefix, entry.path, skipPrefixForEntry);\n const entryExpiryMs =\n entry.expiry !== undefined ? parseExpiry(entry.expiry) : undefined;\n return expandPermissionEntry({\n ...entry,\n space: entry.space ?? inheritedSpace,\n path: resolvedPath,\n skipPrefix: true,\n }).map((expanded) => ({\n service: expanded.service,\n space: expanded.space ?? inheritedSpace,\n path: expanded.path,\n actions: expanded.actions,\n // Only populate `expiryMs` when the entry had its own expiry override.\n // When absent, callers use the parent (delegation or manifest) expiry\n // which is carried on ResolvedDelegate.expiryMs / ResolvedCapabilities.expiryMs.\n ...(entryExpiryMs !== undefined ? { expiryMs: entryExpiryMs } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n }));\n}\n\nfunction expandVaultPermissionEntry(entry: PermissionEntry): PermissionEntry[] {\n const byBase = new Map<VaultKVBase, string[]>();\n\n for (const action of entry.actions) {\n const expansion = vaultActionExpansion(action);\n for (const base of expansion.bases) {\n const actions = byBase.get(base) ?? [];\n if (!actions.includes(expansion.action)) {\n actions.push(expansion.action);\n }\n byBase.set(base, actions);\n }\n }\n\n return [...byBase.entries()].map(([base, actions]) => ({\n ...entry,\n service: \"tinycloud.kv\",\n path: vaultKVPath(base, entry.path),\n actions,\n skipPrefix: true,\n }));\n}\n\nfunction vaultActionExpansion(action: string): VaultActionExpansion {\n const normalized = normalizeVaultAction(action);\n if (normalized === \"read\" || normalized === \"get\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/get\" };\n }\n if (normalized === \"write\" || normalized === \"put\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/put\" };\n }\n if (normalized === \"delete\" || normalized === \"del\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/del\" };\n }\n if (normalized === \"list\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/list\" };\n }\n if (normalized === \"head\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/get\" };\n }\n if (normalized === \"metadata\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/metadata\" };\n }\n\n throw new ManifestValidationError(\n `unknown vault action ${JSON.stringify(action)}; expected read, write, delete, get, put, del, list, head, or metadata`,\n );\n}\n\nfunction normalizeVaultAction(action: string): string {\n if (action.startsWith(`${VAULT_PERMISSION_SERVICE}/`)) {\n return action.slice(`${VAULT_PERMISSION_SERVICE}/`.length);\n }\n if (action.startsWith(\"tinycloud.kv/\")) {\n return action.slice(\"tinycloud.kv/\".length);\n }\n if (action.includes(\"/\")) {\n throw new ManifestValidationError(\n `unknown vault action ${JSON.stringify(action)}; expected a tinycloud.vault or tinycloud.kv action`,\n );\n }\n return action;\n}\n\nfunction vaultKVPath(base: VaultKVBase, path: string): string {\n const normalized = path.startsWith(\"/\") ? path.slice(1) : path;\n return `${base}/${normalized}`;\n}\n\nfunction cloneResourceCapability(\n entry: ResourceCapability,\n): ResourceCapability {\n return {\n service: entry.service,\n space: entry.space,\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.expiryMs !== undefined ? { expiryMs: entry.expiryMs } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n };\n}\n\nfunction clonePermissionEntry(entry: PermissionEntry): PermissionEntry {\n return {\n service: entry.service,\n ...(entry.space !== undefined ? { space: entry.space } : {}),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats !== undefined\n ? { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }\n : {}),\n ...(entry.skipPrefix !== undefined ? { skipPrefix: entry.skipPrefix } : {}),\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n };\n}\n\nfunction dedupeResources(\n resources: readonly ResourceCapability[],\n): ResourceCapability[] {\n const byKey = new Map<string, ResourceCapability>();\n\n for (const resource of resources) {\n const key = `${resource.service}\\u0000${resource.space}\\u0000${resource.path}\\u0000${resource.expiryMs ?? \"\"}`;\n const existing = byKey.get(key);\n if (existing === undefined) {\n byKey.set(key, cloneResourceCapability(resource));\n continue;\n }\n\n const seen = new Set(existing.actions);\n for (const action of resource.actions) {\n if (!seen.has(action)) {\n existing.actions.push(action);\n seen.add(action);\n }\n }\n if (\n existing.description === undefined &&\n resource.description !== undefined\n ) {\n existing.description = resource.description;\n }\n }\n\n return [...byKey.values()];\n}\n\nfunction capabilitiesReadPermission(space: string): ResourceCapability {\n return {\n service: \"tinycloud.capabilities\",\n space,\n path: \"\",\n actions: [\"tinycloud.capabilities/read\"],\n };\n}\n\nfunction withCapabilitiesReadForSpaces(\n resources: readonly ResourceCapability[],\n): ResourceCapability[] {\n if (resources.length === 0) {\n return [];\n }\n\n const spaces = new Set(\n resources\n .filter((resource) => resource.service !== ENCRYPTION_PERMISSION_SERVICE)\n .map((resource) => resource.space),\n );\n return dedupeResources([\n ...resources,\n ...[...spaces].map(capabilitiesReadPermission),\n ]);\n}\n\n/**\n * Compose one or more manifests into the single capability request that should\n * be signed. Fetching manifests is intentionally out of band; callers pass the\n * already-loaded manifest objects.\n */\nexport function composeManifestRequest(\n inputs: readonly Manifest[],\n options: ComposeManifestOptions = {},\n): ComposedManifestRequest {\n if (!Array.isArray(inputs) || inputs.length === 0) {\n throw new ManifestValidationError(\n \"composeManifestRequest requires at least one manifest\",\n );\n }\n\n const includeAccountRegistryPermissions =\n options.includeAccountRegistryPermissions ?? true;\n const manifests = inputs.map(validateManifest);\n const resolved = manifests.map(resolveManifest);\n const resources = resolved.flatMap((entry) => entry.resources);\n const delegationTargets = resolved.flatMap((entry) =>\n entry.additionalDelegates.map((delegate) => ({\n ...delegate,\n permissions: dedupeResources(delegate.permissions),\n })),\n );\n\n if (includeAccountRegistryPermissions) {\n resources.push(\n ...ACCOUNT_MANIFEST_PERMISSIONS.map((resource) => ({\n ...resource,\n actions: [...resource.actions],\n })),\n );\n }\n const resourcesWithImplicitCapabilities =\n withCapabilitiesReadForSpaces(resources);\n\n const manifestsByAppId = new Map<string, Manifest[]>();\n for (const manifest of manifests) {\n const current = manifestsByAppId.get(manifest.app_id);\n if (current === undefined) {\n manifestsByAppId.set(manifest.app_id, [manifest]);\n } else {\n current.push(manifest);\n }\n }\n\n const registryRecords: ManifestRegistryRecord[] =\n includeAccountRegistryPermissions\n ? [...manifestsByAppId.entries()].map(([app_id, appManifests]) => ({\n key: `${ACCOUNT_REGISTRY_PATH}${app_id}`,\n app_id,\n manifests: appManifests.map((manifest) => ({\n ...manifest,\n permissions: manifest.permissions?.map(clonePermissionEntry),\n })),\n }))\n : [];\n\n return {\n manifests,\n resources: resourcesWithImplicitCapabilities,\n delegationTargets,\n registryRecords,\n expiryMs: Math.max(...resolved.map((entry) => entry.expiryMs)),\n includePublicSpace: resolved.some((entry) => entry.includePublicSpace),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Abilities map construction (bridge to WASM prepareSession / createDelegation)\n// ---------------------------------------------------------------------------\n\n/**\n * The shape `prepareSession` and the multi-resource `createDelegation` WASM\n * export both accept:\n *\n * ```\n * { [shortService]: { [path]: [fullUrnAction, ...] } }\n * ```\n *\n * - `shortService` is the recap-level service segment (`\"kv\"`, `\"sql\"`,\n * `\"duckdb\"`, `\"capabilities\"`, `\"hooks\"`) — not the manifest long form.\n * - `path` is the fully-resolved path (prefix already applied). An empty\n * string means \"no path segment\" on the resource URI.\n * - Action strings are full URNs like `\"tinycloud.kv/get\"`.\n *\n * This is a single source of truth for both the session's own recap (at\n * sign-in) and the delegations it can derive (post sign-in). We re-use it\n * for both so one manifest drives both sides.\n */\nexport type AbilitiesMap = Record<string, Record<string, string[]>>;\n\n/**\n * Per-space abilities map accepted by the newer WASM session config:\n *\n * ```\n * { [spaceIdOrName]: { [shortService]: { [path]: [fullUrnAction, ...] } } }\n * ```\n */\nexport type SpaceAbilitiesMap = Record<string, AbilitiesMap>;\n\n/**\n * Convert a list of {@link ResourceCapability} entries (manifest\n * long-form service, full-URN actions) into the {@link AbilitiesMap}\n * shape the WASM layer expects.\n *\n * When multiple entries target the same `(service, path)` pair, their\n * action lists are merged and deduped. Entries whose service has no\n * short-form mapping in {@link SERVICE_LONG_TO_SHORT} are rejected with\n * a {@link ManifestValidationError} — the SDK does not silently drop\n * unknown services because the recap encoding would lose them.\n *\n * Paths are kept verbatim: this function does NOT collapse\n * `\"com.listen.app/\"` and `\"com.listen.app\"` or reinterpret empty /\n * slash strings. Callers that care about path canonicalization should\n * normalize before calling.\n */\nexport function resourceCapabilitiesToAbilitiesMap(\n resources: readonly ResourceCapability[],\n): AbilitiesMap {\n const out: AbilitiesMap = {};\n for (const r of resources) {\n const shortService = SERVICE_LONG_TO_SHORT[r.service];\n if (shortService === undefined) {\n throw new ManifestValidationError(\n `unknown service '${r.service}' — no short-form mapping. Known services: ${Object.keys(SERVICE_LONG_TO_SHORT).join(\", \")}`,\n );\n }\n if (out[shortService] === undefined) {\n out[shortService] = {};\n }\n const pathsMap = out[shortService];\n const existing = pathsMap[r.path];\n if (existing === undefined) {\n // Copy so downstream mutation can't leak back into the input.\n pathsMap[r.path] = [...r.actions];\n } else {\n // Merge + dedupe while preserving first-seen order.\n const seen = new Set(existing);\n for (const action of r.actions) {\n if (!seen.has(action)) {\n existing.push(action);\n seen.add(action);\n }\n }\n }\n }\n return out;\n}\n\n/**\n * Group resolved capabilities by `space`, then convert each group into a WASM\n * abilities map. Short space names are left as-is here; platform layers that\n * know the wallet address and chain id turn them into full SpaceIds.\n */\nexport function resourceCapabilitiesToSpaceAbilitiesMap(\n resources: readonly ResourceCapability[],\n): SpaceAbilitiesMap {\n const grouped = new Map<string, ResourceCapability[]>();\n for (const resource of resources) {\n const entries = grouped.get(resource.space);\n if (entries === undefined) {\n grouped.set(resource.space, [resource]);\n } else {\n entries.push(resource);\n }\n }\n\n const out: SpaceAbilitiesMap = {};\n for (const [space, entries] of grouped.entries()) {\n out[space] = resourceCapabilitiesToAbilitiesMap(entries);\n }\n return out;\n}\n\n/**\n * Build the {@link AbilitiesMap} that a session should be signed with,\n * given a {@link ResolvedCapabilities} (i.e. the output of\n * {@link resolveManifest}).\n *\n * The resulting map is the **union** of:\n * 1. the app's own resources (`resolved.resources`), and\n * 2. every permission declared in every `additionalDelegates[*]` entry.\n *\n * The union is what makes the manifest's delegations ergonomic: at\n * sign-in, the session key acquires recap coverage for both the app's\n * runtime needs and every downstream delegation target. Post sign-in,\n * `delegateTo(backendDID, backendPermissions)` can then issue the\n * sub-delegation via the session key (no wallet prompt) because the\n * caps are already part of the granted set.\n *\n * Duplicate `(service, path, action)` triples across resources and\n * delegations are merged and deduped — the session SIWE doesn't need\n * them repeated.\n */\nexport function manifestAbilitiesUnion(\n resolved: ResolvedCapabilities,\n): AbilitiesMap {\n const all: ResourceCapability[] = [...resolved.resources];\n for (const delegate of resolved.additionalDelegates) {\n for (const perm of delegate.permissions) {\n all.push(perm);\n }\n }\n return resourceCapabilitiesToAbilitiesMap(all);\n}\n","/**\n * Capability subset checking and recap parsing.\n *\n * This module powers the capability-chain delegation flow. The key decision\n * a `delegateTo` call has to make is: \"are the requested capabilities a\n * subset of what the current session already grants?\"\n *\n * - If yes → issue the delegation via the session-key UCAN path (no wallet prompt).\n * - If no → raise {@link PermissionNotInManifestError} so the caller can\n * trigger an escalation flow via `requestPermissions`.\n *\n * Canonical spec: `.claude/specs/capability-chain.md`.\n *\n * @packageDocumentation\n */\n\nimport {\n DEFAULT_MANIFEST_SPACE,\n type PermissionEntry,\n SERVICE_SHORT_TO_LONG,\n expandActionShortNames,\n} from \"./manifest\";\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\n/**\n * Thrown when a `delegateTo` call requests capabilities that the current\n * session does not already grant. The caller can catch this and trigger\n * `requestPermissions(missing)` to show an escalation modal.\n */\nexport class PermissionNotInManifestError extends Error {\n public readonly missing: PermissionEntry[];\n public readonly granted: PermissionEntry[];\n\n constructor(missing: PermissionEntry[], granted: PermissionEntry[]) {\n super(\n `Requested capabilities exceed current session. Missing ${missing.length} entries.`\n );\n this.name = \"PermissionNotInManifestError\";\n this.missing = missing;\n this.granted = granted;\n }\n}\n\n/**\n * Thrown when the current session has expired (or will expire within the\n * safety margin). The caller should trigger a fresh sign-in.\n */\nexport class SessionExpiredError extends Error {\n public readonly expiredAt: Date;\n\n constructor(expiredAt: Date) {\n super(`Session expired at ${expiredAt.toISOString()}`);\n this.name = \"SessionExpiredError\";\n this.expiredAt = expiredAt;\n }\n}\n\n/**\n * Thrown when the installed WASM delegation boundary cannot encode every\n * constrained ReCap branch in a requested child delegation.\n */\nexport class CaveatedDelegationUnsupportedError extends Error {\n /** Stable machine-readable error code for fail-closed caveated delegation. */\n code = \"CAVEATED_DELEGATION_UNSUPPORTED\" as const;\n /** Requested entries whose constrained ReCap branches cannot be preserved. */\n entries: PermissionEntry[];\n\n constructor(entries: PermissionEntry[]) {\n super(\n \"Cannot create a caveated delegation because this WASM delegation boundary cannot preserve every ReCap caveat branch exactly.\"\n );\n this.name = \"CaveatedDelegationUnsupportedError\";\n this.entries = entries.map(cloneEntry);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Space normalization\n// ---------------------------------------------------------------------------\n\n/**\n * Normalize a space identifier to its short-name form.\n *\n * Recap resource URIs in a signed SIWE encode the space as a full URI of the\n * form `tinycloud:pkh:eip155:{chainId}:{address}:{name}` (e.g.\n * `tinycloud:pkh:eip155:1:0xd559...:default`). Manifest permissions and\n * backend-advertised permissions use the short `{name}` form (e.g.\n * `\"default\"`).\n *\n * Strict string comparison between these two forms would always fail, so we\n * normalize both sides to the short name before comparing. The trailing\n * segment after the last `:` in a `tinycloud:` URI is the space name.\n *\n * Short names (`\"default\"`, `\"work-space\"`) are returned unchanged.\n * Any non-`tinycloud:` string is returned unchanged. A malformed URI with a\n * trailing colon is returned unchanged (so the check degrades to a strict\n * mismatch rather than collapsing to an empty string).\n *\n * @internal\n */\nexport function normalizeSpace(space: string): string {\n if (!space.startsWith(\"tinycloud:\")) {\n return space;\n }\n const lastColon = space.lastIndexOf(\":\");\n if (lastColon === -1 || lastColon === space.length - 1) {\n return space;\n }\n return space.slice(lastColon + 1);\n}\n\n// ---------------------------------------------------------------------------\n// Subset check\n// ---------------------------------------------------------------------------\n\nexport interface SubsetCheckResult {\n /** True when every requested entry is covered by a granted entry. */\n subset: boolean;\n /** Entries the granted set does not cover (empty when `subset` is true). */\n missing: PermissionEntry[];\n}\n\n/**\n * Check whether `requested` is a strict subset of `granted`.\n *\n * Matching rules for each `requested[i]`:\n * - `service` matches exactly.\n * - `space` matches exactly.\n * - Path containment:\n * - If `granted.path` ends with `/`, it covers any `requested.path` that\n * starts with `granted.path`.\n * - Otherwise, the paths must match exactly.\n * - Action containment: every requested URN must be matched exactly or by a\n * service-scoped wildcard such as `tinycloud.kv/*`.\n *\n * Grant entries with the same service, space, path coverage, and caveats are\n * considered together. This matters because ReCap parsers may return one\n * entry per action even when the original manifest grouped those actions.\n * Any `requested` entry whose actions are not collectively covered is added\n * to `missing` and the overall result is non-subset.\n *\n * Both sides are expected to be in the canonical long-form shape (service\n * starts with `tinycloud.`, actions are full URNs). Use {@link parseRecapCapabilities}\n * or `expandActionShortNames` to normalize inputs first.\n */\nexport function isCapabilitySubset(\n requested: readonly PermissionEntry[],\n granted: readonly PermissionEntry[]\n): SubsetCheckResult {\n const missing: PermissionEntry[] = [];\n\n for (const req of requested) {\n const matchingScope = granted.filter((entry) =>\n canonicalizeEntryScopeMatches(req, entry)\n );\n const requestedActions = expandActionShortNames(\n req.service,\n req.actions\n );\n const grantedActions = matchingScope.flatMap((entry) =>\n expandActionShortNames(entry.service, entry.actions)\n );\n const covered = requestedActions.every((requestedAction) =>\n grantedActions.some((grantedAction) =>\n actionContains(grantedAction, requestedAction)\n )\n );\n if (!covered) {\n missing.push(cloneEntry(req));\n }\n }\n\n return { subset: missing.length === 0, missing };\n}\n\n/**\n * Returns true when `granted` fully covers `requested` — same service, same\n * space, path containment per spec, and action set containment.\n */\nfunction canonicalizeEntryScopeMatches(\n requested: PermissionEntry,\n granted: PermissionEntry\n): boolean {\n if (requested.service !== granted.service) {\n return false;\n }\n // Normalize both sides so callers passing short names (`\"default\"`) match\n // recap-parsed full URIs (`\"tinycloud:pkh:eip155:1:0xd559...:default\"`) and\n // vice versa. Idempotent for short names.\n if (\n normalizeSpace(requested.space ?? DEFAULT_MANIFEST_SPACE) !==\n normalizeSpace(granted.space ?? DEFAULT_MANIFEST_SPACE)\n ) {\n return false;\n }\n if (!pathContains(granted.path, requested.path)) {\n return false;\n }\n // There is no safe general partial ordering for arbitrary ReCap caveat\n // objects. A caveated authority therefore only covers the same caveat set;\n // treating it as uncaveated would authorize a broader child delegation.\n if (!recapCaveatsEqual(requested.caveats, granted.caveats)) {\n return false;\n }\n return true;\n}\n\n/**\n * Compare ReCap caveat branch sets without losing signed branch structure.\n *\n * ReCap represents an unconstrained ability as `[{}]`, while SDK callers can\n * represent that same authority as `undefined` or `[]`. Those three forms are\n * equivalent. Every other branch, including an unconstrained branch mixed\n * with a constrained one, remains part of the canonical comparison.\n */\nexport function recapCaveatsEqual(\n left: readonly Record<string, unknown>[] | undefined,\n right: readonly Record<string, unknown>[] | undefined,\n): boolean {\n return canonicalizeRecapCaveats(left) === canonicalizeRecapCaveats(right);\n}\n\n/**\n * Canonicalize a ReCap caveat branch set for exact equality checks.\n *\n * Object keys and branch order do not affect equality. A lone unconstrained\n * branch is normalized to the SDK's empty-caveat representation, but an\n * unconstrained branch in a mixed set is deliberately retained.\n */\nexport function canonicalizeRecapCaveats(\n caveats: readonly Record<string, unknown>[] | undefined,\n): string {\n const canonicalize = (value: unknown): string => {\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") {\n return JSON.stringify(value);\n }\n if (typeof value === \"number\") {\n if (Number.isFinite(value)) return JSON.stringify(value);\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n }\n if (Array.isArray(value)) return `[${value.map(canonicalize).join(\",\")}]`;\n if (typeof value === \"object\") {\n const object = value as Record<string, unknown>;\n const prototype = Object.getPrototypeOf(object);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n }\n return `{${Object.keys(object).sort().map((key) =>\n `${JSON.stringify(key)}:${canonicalize(object[key])}`,\n ).join(\",\")}}`;\n }\n throw new Error(\"ReCap caveats must contain only JSON values.\");\n };\n const branches = (caveats ?? []).map(canonicalize).sort();\n if (branches.length === 0 || (branches.length === 1 && branches[0] === \"{}\")) {\n return \"[]\";\n }\n return `[${branches.join(\",\")}]`;\n}\n\n// Literal strings, not `KV.SYNC`/`KV.RETAIN`: those are derived from the\n// vendored registry at runtime, so an older bootstrap would turn them into\n// `undefined` and silently disable this guard.\nconst EXPLICIT_ONLY_ACTIONS: Readonly<Record<string, true>> = {\n \"tinycloud.kv/sync\": true,\n \"tinycloud.kv/retain\": true,\n};\n\n/**\n * Whether `action` is one no wildcard covers: `*` and `tinycloud.kv/*` do not\n * grant it, so a grant must name it (TC-732). `tinycloud.kv/sync` discloses a\n * prefix's change feed and `tinycloud.kv/retain` is an owner-approved\n * retention attestation; the node refuses both unless granted by name.\n */\nexport function isExplicitOnlyAction(action: string): boolean {\n return Object.prototype.hasOwnProperty.call(EXPLICIT_ONLY_ACTIONS, action);\n}\n\n/** Return whether a granted action pattern covers one requested action. */\nexport function actionContains(grantedAction: string, requestedAction: string): boolean {\n if (grantedAction === requestedAction) return true;\n if (isExplicitOnlyAction(requestedAction)) return false;\n if (grantedAction === \"*\") return true;\n if (!grantedAction.endsWith(\"/*\")) return false;\n const service = grantedAction.slice(0, -2);\n return requestedAction === service || requestedAction.startsWith(`${service}/`);\n}\n\n/**\n * Path containment per spec:\n * - `granted.path` ends with `/` → prefix match (requested starts with granted)\n * - otherwise → exact string match\n *\n * The empty string is treated as \"no path constraint\" and matches anything.\n * The single-character `\"/\"` also matches anything (it is a trailing-slash\n * prefix of zero-length).\n */\nfunction pathContains(grantedPath: string, requestedPath: string): boolean {\n if (grantedPath === \"\" || grantedPath === \"/\") {\n return true;\n }\n if (grantedPath.endsWith(\"/\")) {\n return requestedPath.startsWith(grantedPath);\n }\n return requestedPath === grantedPath;\n}\n\nfunction cloneEntry(entry: PermissionEntry): PermissionEntry {\n return {\n service: entry.service,\n ...(entry.space !== undefined ? { space: entry.space } : {}),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats !== undefined\n ? { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }\n : {}),\n ...(entry.skipPrefix !== undefined ? { skipPrefix: entry.skipPrefix } : {}),\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Recap parsing (WASM wrapper)\n// ---------------------------------------------------------------------------\n\n/**\n * The raw shape returned from the WASM `parseRecapFromSiwe` export. The\n * Rust layer encodes the service in the short form (e.g. `\"kv\"`) because\n * that is what the SIWE recap resource URI actually contains. We normalize\n * to the manifest long form (`\"tinycloud.kv\"`) in {@link parseRecapCapabilities}.\n *\n * @internal\n */\nexport interface WasmRecapEntry {\n service: string;\n space: string;\n path: string;\n actions: string[];\n /** Exact ReCap caveats shared by every action in this entry. */\n caveats?: Record<string, unknown>[];\n}\n\n/**\n * Signature of the WASM `parseRecapFromSiwe` export. Accepts the signed\n * SIWE message string and returns an array of raw recap entries. Throws if\n * the SIWE is malformed or the recap statement has been tampered.\n *\n * Exposed as an interface so the SDK can inject the web or node binding\n * without `capabilities.ts` needing to know which.\n */\nexport type ParseRecapFromSiwe = (siweString: string) => WasmRecapEntry[];\n\n/**\n * Parse a signed SIWE message into an array of {@link PermissionEntry}\n * objects in the canonical long-form manifest shape.\n *\n * This is a thin wrapper around the WASM `parseRecapFromSiwe` export that:\n * 1. Normalizes short-form services (`\"kv\"`) to long-form (`\"tinycloud.kv\"`).\n * 2. Returns entries in a deterministic order (sorted by space, then service,\n * then path) so downstream equality checks are stable.\n *\n * Returns an empty array when the SIWE has no recap resource (plain auth\n * SIWE); this matches the WASM function's behavior and the spec.\n *\n * @param parseWasm The WASM `parseRecapFromSiwe` binding.\n * @param siwe The signed SIWE message string (exactly what `session.siwe` stores).\n */\nexport function parseRecapCapabilities(\n parseWasm: ParseRecapFromSiwe,\n siwe: string\n): PermissionEntry[] {\n const raw = parseWasm(siwe);\n if (!Array.isArray(raw)) {\n throw new Error(\n \"parseRecapFromSiwe returned a non-array value; wasm binding may be out of sync\"\n );\n }\n const normalized: PermissionEntry[] = raw.map((entry) => {\n const longService =\n SERVICE_SHORT_TO_LONG[entry.service] ??\n // Unknown short names pass through. If the recap already contained a\n // long-form service (e.g. a future tinycloud-node version emits long\n // form directly), don't double-prefix.\n (entry.service.startsWith(\"tinycloud.\")\n ? entry.service\n : `tinycloud.${entry.service}`);\n return {\n service: longService,\n // The Rust layer emits the space as a full `tinycloud:pkh:...:name`\n // URI (the recap target URI). Normalize to the short name so the\n // returned entries match the shape manifests use.\n space: normalizeSpace(entry.space),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.caveats === undefined\n ? {}\n : { caveats: JSON.parse(JSON.stringify(entry.caveats)) as Record<string, unknown>[] }),\n };\n });\n\n // Sort for determinism (callers do equality checks on arrays of entries\n // in tests; deterministic ordering keeps those stable).\n normalized.sort((a, b) => {\n const aSpace = a.space ?? DEFAULT_MANIFEST_SPACE;\n const bSpace = b.space ?? DEFAULT_MANIFEST_SPACE;\n if (aSpace !== bSpace) return aSpace < bSpace ? -1 : 1;\n if (a.service !== b.service) return a.service < b.service ? -1 : 1;\n if (a.path !== b.path) return a.path < b.path ? -1 : 1;\n return 0;\n });\n\n return normalized;\n}\n","/**\n * Blake3 fast hash is Blake2 with reduced security (round count). Can also be used as MAC & KDF.\n *\n * It is advertised as \"the fastest cryptographic hash\". However, it isn't true in JS.\n * Why is this so slow? While it should be 6x faster than blake2b, perf diff is only 20%:\n *\n * * There is only 30% reduction in number of rounds from blake2s\n * * Speed-up comes from tree structure, which is parallelized using SIMD & threading.\n * These features are not present in JS, so we only get overhead from trees.\n * * Parallelization only happens on 1024-byte chunks: there is no benefit for small inputs.\n * * It is still possible to make it faster using: a) loop unrolling b) web workers c) wasm\n * @module\n */\nimport { SHA256_IV } from './_md.ts';\nimport { fromBig } from './_u64.ts';\nimport { BLAKE2, compress } from './blake2.ts';\n// prettier-ignore\nimport {\n abytes, aexists, anumber, aoutput,\n clean, createXOFer, swap32IfBE, toBytes, u32, u8,\n type CHashXO, type HashXOF, type Input\n} from './utils.ts';\n\n// Flag bitset\nconst B3_Flags = {\n CHUNK_START: 0b1,\n CHUNK_END: 0b10,\n PARENT: 0b100,\n ROOT: 0b1000,\n KEYED_HASH: 0b10000,\n DERIVE_KEY_CONTEXT: 0b100000,\n DERIVE_KEY_MATERIAL: 0b1000000,\n} as const;\n\nconst B3_IV = SHA256_IV.slice();\n\nconst B3_SIGMA: Uint8Array = /* @__PURE__ */ (() => {\n const Id = Array.from({ length: 16 }, (_, i) => i);\n const permute = (arr: number[]) =>\n [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]);\n const res: number[] = [];\n for (let i = 0, v = Id; i < 7; i++, v = permute(v)) res.push(...v);\n return Uint8Array.from(res);\n})();\n\n/**\n * Ensure to use EITHER `key` OR `context`, not both.\n *\n * * `key`: 32-byte MAC key.\n * * `context`: string for KDF. Should be hardcoded, globally unique, and application - specific.\n * A good default format for the context string is \"[application] [commit timestamp] [purpose]\".\n */\nexport type Blake3Opts = { dkLen?: number; key?: Input; context?: Input };\n\n/** Blake3 hash. Can be used as MAC and KDF. */\nexport class BLAKE3 extends BLAKE2<BLAKE3> implements HashXOF<BLAKE3> {\n private chunkPos = 0; // Position of current block in chunk\n private chunksDone = 0; // How many chunks we already have\n private flags = 0 | 0;\n private IV: Uint32Array;\n private state: Uint32Array;\n private stack: Uint32Array[] = [];\n // Output\n private posOut = 0;\n private bufferOut32 = new Uint32Array(16);\n private bufferOut: Uint8Array;\n private chunkOut = 0; // index of output chunk\n private enableXOF = true;\n\n constructor(opts: Blake3Opts = {}, flags = 0) {\n super(64, opts.dkLen === undefined ? 32 : opts.dkLen);\n const { key, context } = opts;\n const hasContext = context !== undefined;\n if (key !== undefined) {\n if (hasContext) throw new Error('Only \"key\" or \"context\" can be specified at same time');\n const k = toBytes(key).slice();\n abytes(k, 32);\n this.IV = u32(k);\n swap32IfBE(this.IV);\n this.flags = flags | B3_Flags.KEYED_HASH;\n } else if (hasContext) {\n const ctx = toBytes(context);\n const contextKey = new BLAKE3({ dkLen: 32 }, B3_Flags.DERIVE_KEY_CONTEXT)\n .update(ctx)\n .digest();\n this.IV = u32(contextKey);\n swap32IfBE(this.IV);\n this.flags = flags | B3_Flags.DERIVE_KEY_MATERIAL;\n } else {\n this.IV = B3_IV.slice();\n this.flags = flags;\n }\n this.state = this.IV.slice();\n this.bufferOut = u8(this.bufferOut32);\n }\n // Unused\n protected get(): [] {\n return [];\n }\n protected set(): void {}\n private b2Compress(counter: number, flags: number, buf: Uint32Array, bufPos: number = 0) {\n const { state: s, pos } = this;\n const { h, l } = fromBig(BigInt(counter), true);\n // prettier-ignore\n const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } =\n compress(\n B3_SIGMA, bufPos, buf, 7,\n s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7],\n B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], h, l, pos, flags\n );\n s[0] = v0 ^ v8;\n s[1] = v1 ^ v9;\n s[2] = v2 ^ v10;\n s[3] = v3 ^ v11;\n s[4] = v4 ^ v12;\n s[5] = v5 ^ v13;\n s[6] = v6 ^ v14;\n s[7] = v7 ^ v15;\n }\n protected compress(buf: Uint32Array, bufPos: number = 0, isLast: boolean = false): void {\n // Compress last block\n let flags = this.flags;\n if (!this.chunkPos) flags |= B3_Flags.CHUNK_START;\n if (this.chunkPos === 15 || isLast) flags |= B3_Flags.CHUNK_END;\n if (!isLast) this.pos = this.blockLen;\n this.b2Compress(this.chunksDone, flags, buf, bufPos);\n this.chunkPos += 1;\n // If current block is last in chunk (16 blocks), then compress chunks\n if (this.chunkPos === 16 || isLast) {\n let chunk = this.state;\n this.state = this.IV.slice();\n // If not the last one, compress only when there are trailing zeros in chunk counter\n // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed.\n // 1 (001) - leaf not finished (just push current chunk to stack)\n // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back)\n // 3 (011) - last leaf not finished\n // 4 (100) - leafs finished at depth=1 and depth=2\n for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) {\n if (!(last = this.stack.pop())) break;\n this.buffer32.set(last, 0);\n this.buffer32.set(chunk, 8);\n this.pos = this.blockLen;\n this.b2Compress(0, this.flags | B3_Flags.PARENT, this.buffer32, 0);\n chunk = this.state;\n this.state = this.IV.slice();\n }\n this.chunksDone++;\n this.chunkPos = 0;\n this.stack.push(chunk);\n }\n this.pos = 0;\n }\n _cloneInto(to?: BLAKE3): BLAKE3 {\n to = super._cloneInto(to) as BLAKE3;\n const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this;\n to.state.set(state.slice());\n to.stack = stack.map((i) => Uint32Array.from(i));\n to.IV.set(IV);\n to.flags = flags;\n to.chunkPos = chunkPos;\n to.chunksDone = chunksDone;\n to.posOut = posOut;\n to.chunkOut = chunkOut;\n to.enableXOF = this.enableXOF;\n to.bufferOut32.set(this.bufferOut32);\n return to;\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.state, this.buffer32, this.IV, this.bufferOut32);\n clean(...this.stack);\n }\n // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8)\n private b2CompressOut() {\n const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this;\n const { h, l } = fromBig(BigInt(this.chunkOut++));\n swap32IfBE(buffer32);\n // prettier-ignore\n const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } =\n compress(\n B3_SIGMA, 0, buffer32, 7,\n s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7],\n B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], l, h, pos, flags\n );\n out32[0] = v0 ^ v8;\n out32[1] = v1 ^ v9;\n out32[2] = v2 ^ v10;\n out32[3] = v3 ^ v11;\n out32[4] = v4 ^ v12;\n out32[5] = v5 ^ v13;\n out32[6] = v6 ^ v14;\n out32[7] = v7 ^ v15;\n out32[8] = s[0] ^ v8;\n out32[9] = s[1] ^ v9;\n out32[10] = s[2] ^ v10;\n out32[11] = s[3] ^ v11;\n out32[12] = s[4] ^ v12;\n out32[13] = s[5] ^ v13;\n out32[14] = s[6] ^ v14;\n out32[15] = s[7] ^ v15;\n swap32IfBE(buffer32);\n swap32IfBE(out32);\n this.posOut = 0;\n }\n protected finish(): void {\n if (this.finished) return;\n this.finished = true;\n // Padding\n clean(this.buffer.subarray(this.pos));\n // Process last chunk\n let flags = this.flags | B3_Flags.ROOT;\n if (this.stack.length) {\n flags |= B3_Flags.PARENT;\n swap32IfBE(this.buffer32);\n this.compress(this.buffer32, 0, true);\n swap32IfBE(this.buffer32);\n this.chunksDone = 0;\n this.pos = this.blockLen;\n } else {\n flags |= (!this.chunkPos ? B3_Flags.CHUNK_START : 0) | B3_Flags.CHUNK_END;\n }\n this.flags = flags;\n this.b2CompressOut();\n }\n private writeInto(out: Uint8Array) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const { blockLen, bufferOut } = this;\n for (let pos = 0, len = out.length; pos < len; ) {\n if (this.posOut >= blockLen) this.b2CompressOut();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out: Uint8Array): Uint8Array {\n if (!this.enableXOF) throw new Error('XOF is not possible after digest call');\n return this.writeInto(out);\n }\n xof(bytes: number): Uint8Array {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out: Uint8Array): Uint8Array {\n aoutput(out, this);\n if (this.finished) throw new Error('digest() was already called');\n this.enableXOF = false;\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest(): Uint8Array {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n}\n\n/**\n * BLAKE3 hash function. Can be used as MAC and KDF.\n * @param msg - message that would be hashed\n * @param opts - `dkLen` for output length, `key` for MAC mode, `context` for KDF mode\n * @example\n * const data = new Uint8Array(32);\n * const hash = blake3(data);\n * const mac = blake3(data, { key: new Uint8Array(32) });\n * const kdf = blake3(data, { context: 'application name' });\n */\nexport const blake3: CHashXO = /* @__PURE__ */ createXOFer<BLAKE3, Blake3Opts>(\n (opts) => new BLAKE3(opts)\n);\n","/**\n * Internal helpers for blake hash.\n * @module\n */\nimport { rotr } from './utils.ts';\n\n/**\n * Internal blake variable.\n * For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1].\n */\n// prettier-ignore\nexport const BSIGMA: Uint8Array = /* @__PURE__ */ Uint8Array.from([\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,\n 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,\n 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,\n 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,\n 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,\n 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,\n 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,\n 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,\n 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,\n // Blake1, unused in others\n 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,\n 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,\n 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,\n 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,\n]);\n\n// prettier-ignore\nexport type Num4 = { a: number; b: number; c: number; d: number; };\n\n// Mixing function G splitted in two halfs\nexport function G1s(a: number, b: number, c: number, d: number, x: number): Num4 {\n a = (a + b + x) | 0;\n d = rotr(d ^ a, 16);\n c = (c + d) | 0;\n b = rotr(b ^ c, 12);\n return { a, b, c, d };\n}\n\nexport function G2s(a: number, b: number, c: number, d: number, x: number): Num4 {\n a = (a + b + x) | 0;\n d = rotr(d ^ a, 8);\n c = (c + d) | 0;\n b = rotr(b ^ c, 7);\n return { a, b, c, d };\n}\n","/**\n * blake2b (64-bit) & blake2s (8 to 32-bit) hash functions.\n * b could have been faster, but there is no fast u64 in js, so s is 1.5x faster.\n * @module\n */\nimport { BSIGMA, G1s, G2s } from './_blake.ts';\nimport { SHA256_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\n// prettier-ignore\nimport {\n abytes, aexists, anumber, aoutput,\n clean, createOptHasher, Hash, swap32IfBE, swap8IfBE, toBytes, u32,\n type CHashO, type Input\n} from './utils.ts';\n\n/** Blake hash options. dkLen is output length. key is used in MAC mode. salt is used in KDF mode. */\nexport type Blake2Opts = {\n dkLen?: number;\n key?: Input;\n salt?: Input;\n personalization?: Input;\n};\n\n// Same as SHA512_IV, but swapped endianness: LE instead of BE. iv[1] is iv[0], etc.\nconst B2B_IV = /* @__PURE__ */ Uint32Array.from([\n 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a,\n 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19,\n]);\n// Temporary buffer\nconst BBUF = /* @__PURE__ */ new Uint32Array(32);\n\n// Mixing function G splitted in two halfs\nfunction G1b(a: number, b: number, c: number, d: number, msg: Uint32Array, x: number) {\n // NOTE: V is LE here\n const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore\n let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore\n let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore\n let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore\n let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore\n // v[a] = (v[a] + v[b] + x) | 0;\n let ll = u64.add3L(Al, Bl, Xl);\n Ah = u64.add3H(ll, Ah, Bh, Xh);\n Al = ll | 0;\n // v[d] = rotr(v[d] ^ v[a], 32)\n ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });\n ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) });\n // v[c] = (v[c] + v[d]) | 0;\n ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));\n // v[b] = rotr(v[b] ^ v[c], 24)\n ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });\n ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) });\n (BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah);\n (BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh);\n (BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch);\n (BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh);\n}\n\nfunction G2b(a: number, b: number, c: number, d: number, msg: Uint32Array, x: number) {\n // NOTE: V is LE here\n const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore\n let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore\n let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore\n let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore\n let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore\n // v[a] = (v[a] + v[b] + x) | 0;\n let ll = u64.add3L(Al, Bl, Xl);\n Ah = u64.add3H(ll, Ah, Bh, Xh);\n Al = ll | 0;\n // v[d] = rotr(v[d] ^ v[a], 16)\n ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });\n ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) });\n // v[c] = (v[c] + v[d]) | 0;\n ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));\n // v[b] = rotr(v[b] ^ v[c], 63)\n ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });\n ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) });\n (BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah);\n (BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh);\n (BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch);\n (BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh);\n}\n\nfunction checkBlake2Opts(\n outputLen: number,\n opts: Blake2Opts | undefined = {},\n keyLen: number,\n saltLen: number,\n persLen: number\n) {\n anumber(keyLen);\n if (outputLen < 0 || outputLen > keyLen) throw new Error('outputLen bigger than keyLen');\n const { key, salt, personalization } = opts;\n if (key !== undefined && (key.length < 1 || key.length > keyLen))\n throw new Error('key length must be undefined or 1..' + keyLen);\n if (salt !== undefined && salt.length !== saltLen)\n throw new Error('salt must be undefined or ' + saltLen);\n if (personalization !== undefined && personalization.length !== persLen)\n throw new Error('personalization must be undefined or ' + persLen);\n}\n\n/** Class, from which others are subclassed. */\nexport abstract class BLAKE2<T extends BLAKE2<T>> extends Hash<T> {\n protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected buffer: Uint8Array;\n protected buffer32: Uint32Array;\n protected finished = false;\n protected destroyed = false;\n protected length: number = 0;\n protected pos: number = 0;\n readonly blockLen: number;\n readonly outputLen: number;\n\n constructor(blockLen: number, outputLen: number) {\n super();\n anumber(blockLen);\n anumber(outputLen);\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.buffer = new Uint8Array(blockLen);\n this.buffer32 = u32(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n // Main difference with other hashes: there is flag for last block,\n // so we cannot process current block before we know that there\n // is the next one. This significantly complicates logic and reduces ability\n // to do zero-copy processing\n const { blockLen, buffer, buffer32 } = this;\n const len = data.length;\n const offset = data.byteOffset;\n const buf = data.buffer;\n for (let pos = 0; pos < len; ) {\n // If buffer is full and we still have input (don't process last block, same as blake2s)\n if (this.pos === blockLen) {\n swap32IfBE(buffer32);\n this.compress(buffer32, 0, false);\n swap32IfBE(buffer32);\n this.pos = 0;\n }\n const take = Math.min(blockLen - this.pos, len - pos);\n const dataOffset = offset + pos;\n // full block && aligned to 4 bytes && not last in input\n if (take === blockLen && !(dataOffset % 4) && pos + take < len) {\n const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4));\n swap32IfBE(data32);\n for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {\n this.length += blockLen;\n this.compress(data32, pos32, false);\n }\n swap32IfBE(data32);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n this.length += take;\n pos += take;\n }\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n const { pos, buffer32 } = this;\n this.finished = true;\n // Padding\n clean(this.buffer.subarray(pos));\n swap32IfBE(buffer32);\n this.compress(buffer32, 0, true);\n swap32IfBE(buffer32);\n const out32 = u32(out);\n this.get().forEach((v, i) => (out32[i] = swap8IfBE(v)));\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n const { buffer, length, finished, destroyed, outputLen, pos } = this;\n to ||= new (this.constructor as any)({ dkLen: outputLen }) as T;\n to.set(...this.get());\n to.buffer.set(buffer);\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // @ts-ignore\n to.outputLen = outputLen;\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\nexport class BLAKE2b extends BLAKE2<BLAKE2b> {\n // Same as SHA-512, but LE\n private v0l = B2B_IV[0] | 0;\n private v0h = B2B_IV[1] | 0;\n private v1l = B2B_IV[2] | 0;\n private v1h = B2B_IV[3] | 0;\n private v2l = B2B_IV[4] | 0;\n private v2h = B2B_IV[5] | 0;\n private v3l = B2B_IV[6] | 0;\n private v3h = B2B_IV[7] | 0;\n private v4l = B2B_IV[8] | 0;\n private v4h = B2B_IV[9] | 0;\n private v5l = B2B_IV[10] | 0;\n private v5h = B2B_IV[11] | 0;\n private v6l = B2B_IV[12] | 0;\n private v6h = B2B_IV[13] | 0;\n private v7l = B2B_IV[14] | 0;\n private v7h = B2B_IV[15] | 0;\n\n constructor(opts: Blake2Opts = {}) {\n const olen = opts.dkLen === undefined ? 64 : opts.dkLen;\n super(128, olen);\n checkBlake2Opts(olen, opts, 64, 16, 16);\n let { key, personalization, salt } = opts;\n let keyLength = 0;\n if (key !== undefined) {\n key = toBytes(key);\n keyLength = key.length;\n }\n this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);\n if (salt !== undefined) {\n salt = toBytes(salt);\n const slt = u32(salt);\n this.v4l ^= swap8IfBE(slt[0]);\n this.v4h ^= swap8IfBE(slt[1]);\n this.v5l ^= swap8IfBE(slt[2]);\n this.v5h ^= swap8IfBE(slt[3]);\n }\n if (personalization !== undefined) {\n personalization = toBytes(personalization);\n const pers = u32(personalization);\n this.v6l ^= swap8IfBE(pers[0]);\n this.v6h ^= swap8IfBE(pers[1]);\n this.v7l ^= swap8IfBE(pers[2]);\n this.v7h ^= swap8IfBE(pers[3]);\n }\n if (key !== undefined) {\n // Pad to blockLen and update\n const tmp = new Uint8Array(this.blockLen);\n tmp.set(key);\n this.update(tmp);\n }\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;\n return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h];\n }\n // prettier-ignore\n protected set(\n v0l: number, v0h: number, v1l: number, v1h: number,\n v2l: number, v2h: number, v3l: number, v3h: number,\n v4l: number, v4h: number, v5l: number, v5h: number,\n v6l: number, v6h: number, v7l: number, v7h: number\n ): void {\n this.v0l = v0l | 0;\n this.v0h = v0h | 0;\n this.v1l = v1l | 0;\n this.v1h = v1h | 0;\n this.v2l = v2l | 0;\n this.v2h = v2h | 0;\n this.v3l = v3l | 0;\n this.v3h = v3h | 0;\n this.v4l = v4l | 0;\n this.v4h = v4h | 0;\n this.v5l = v5l | 0;\n this.v5h = v5h | 0;\n this.v6l = v6l | 0;\n this.v6h = v6h | 0;\n this.v7l = v7l | 0;\n this.v7h = v7h | 0;\n }\n protected compress(msg: Uint32Array, offset: number, isLast: boolean): void {\n this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state.\n BBUF.set(B2B_IV, 16); // Second half from IV.\n let { h, l } = u64.fromBig(BigInt(this.length));\n BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset.\n BBUF[25] = B2B_IV[9] ^ h; // High word.\n // Invert all bits for last block\n if (isLast) {\n BBUF[28] = ~BBUF[28];\n BBUF[29] = ~BBUF[29];\n }\n let j = 0;\n const s = BSIGMA;\n for (let i = 0; i < 12; i++) {\n G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]);\n G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]);\n G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]);\n G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]);\n G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]);\n G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]);\n G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]);\n G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]);\n\n G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]);\n G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]);\n G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]);\n G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]);\n G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]);\n G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]);\n G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]);\n G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]);\n }\n this.v0l ^= BBUF[0] ^ BBUF[16];\n this.v0h ^= BBUF[1] ^ BBUF[17];\n this.v1l ^= BBUF[2] ^ BBUF[18];\n this.v1h ^= BBUF[3] ^ BBUF[19];\n this.v2l ^= BBUF[4] ^ BBUF[20];\n this.v2h ^= BBUF[5] ^ BBUF[21];\n this.v3l ^= BBUF[6] ^ BBUF[22];\n this.v3h ^= BBUF[7] ^ BBUF[23];\n this.v4l ^= BBUF[8] ^ BBUF[24];\n this.v4h ^= BBUF[9] ^ BBUF[25];\n this.v5l ^= BBUF[10] ^ BBUF[26];\n this.v5h ^= BBUF[11] ^ BBUF[27];\n this.v6l ^= BBUF[12] ^ BBUF[28];\n this.v6h ^= BBUF[13] ^ BBUF[29];\n this.v7l ^= BBUF[14] ^ BBUF[30];\n this.v7h ^= BBUF[15] ^ BBUF[31];\n clean(BBUF);\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.buffer32);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/**\n * Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS.\n * @param msg - message that would be hashed\n * @param opts - dkLen output length, key for MAC mode, salt, personalization\n */\nexport const blake2b: CHashO = /* @__PURE__ */ createOptHasher<BLAKE2b, Blake2Opts>(\n (opts) => new BLAKE2b(opts)\n);\n\n// =================\n// Blake2S\n// =================\n\n// prettier-ignore\nexport type Num16 = {\n v0: number; v1: number; v2: number; v3: number;\n v4: number; v5: number; v6: number; v7: number;\n v8: number; v9: number; v10: number; v11: number;\n v12: number; v13: number; v14: number; v15: number;\n};\n\n// prettier-ignore\nexport function compress(s: Uint8Array, offset: number, msg: Uint32Array, rounds: number,\n v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number,\n v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number,\n): Num16 {\n let j = 0;\n for (let i = 0; i < rounds; i++) {\n ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]]));\n ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]]));\n ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]]));\n ({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]]));\n ({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]]));\n ({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]]));\n ({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]]));\n ({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]]));\n\n ({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]]));\n ({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]]));\n ({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]]));\n ({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]]));\n ({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]]));\n ({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]]));\n ({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]]));\n ({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]]));\n }\n return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 };\n}\n\nconst B2S_IV = SHA256_IV;\nexport class BLAKE2s extends BLAKE2<BLAKE2s> {\n // Internal state, same as SHA-256\n private v0 = B2S_IV[0] | 0;\n private v1 = B2S_IV[1] | 0;\n private v2 = B2S_IV[2] | 0;\n private v3 = B2S_IV[3] | 0;\n private v4 = B2S_IV[4] | 0;\n private v5 = B2S_IV[5] | 0;\n private v6 = B2S_IV[6] | 0;\n private v7 = B2S_IV[7] | 0;\n\n constructor(opts: Blake2Opts = {}) {\n const olen = opts.dkLen === undefined ? 32 : opts.dkLen;\n super(64, olen);\n checkBlake2Opts(olen, opts, 32, 8, 8);\n let { key, personalization, salt } = opts;\n let keyLength = 0;\n if (key !== undefined) {\n key = toBytes(key);\n keyLength = key.length;\n }\n this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);\n if (salt !== undefined) {\n salt = toBytes(salt);\n const slt = u32(salt as Uint8Array);\n this.v4 ^= swap8IfBE(slt[0]);\n this.v5 ^= swap8IfBE(slt[1]);\n }\n if (personalization !== undefined) {\n personalization = toBytes(personalization);\n const pers = u32(personalization as Uint8Array);\n this.v6 ^= swap8IfBE(pers[0]);\n this.v7 ^= swap8IfBE(pers[1]);\n }\n if (key !== undefined) {\n // Pad to blockLen and update\n abytes(key);\n const tmp = new Uint8Array(this.blockLen);\n tmp.set(key);\n this.update(tmp);\n }\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { v0, v1, v2, v3, v4, v5, v6, v7 } = this;\n return [v0, v1, v2, v3, v4, v5, v6, v7];\n }\n // prettier-ignore\n protected set(\n v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number\n ): void {\n this.v0 = v0 | 0;\n this.v1 = v1 | 0;\n this.v2 = v2 | 0;\n this.v3 = v3 | 0;\n this.v4 = v4 | 0;\n this.v5 = v5 | 0;\n this.v6 = v6 | 0;\n this.v7 = v7 | 0;\n }\n protected compress(msg: Uint32Array, offset: number, isLast: boolean): void {\n const { h, l } = u64.fromBig(BigInt(this.length));\n // prettier-ignore\n const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } =\n compress(\n BSIGMA, offset, msg, 10,\n this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7,\n B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7]\n );\n this.v0 ^= v0 ^ v8;\n this.v1 ^= v1 ^ v9;\n this.v2 ^= v2 ^ v10;\n this.v3 ^= v3 ^ v11;\n this.v4 ^= v4 ^ v12;\n this.v5 ^= v5 ^ v13;\n this.v6 ^= v6 ^ v14;\n this.v7 ^= v7 ^ v15;\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.buffer32);\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/**\n * Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS.\n * @param msg - message that would be hashed\n * @param opts - dkLen output length, key for MAC mode, salt, personalization\n */\nexport const blake2s: CHashO = /* @__PURE__ */ createOptHasher<BLAKE2s, Blake2Opts>(\n (opts) => new BLAKE2s(opts)\n);\n","/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, utf8ToBytes } from '@noble/hashes/utils.js';\nimport { pippenger, type AffinePoint } from './abstract/curve.ts';\nimport {\n PrimeEdwardsPoint,\n twistedEdwards,\n type CurveFn,\n type EdwardsOpts,\n type EdwardsPoint,\n} from './abstract/edwards.ts';\nimport {\n _DST_scalar,\n createHasher,\n expand_message_xmd,\n type H2CHasher,\n type H2CHasherBase,\n type H2CMethod,\n type htfBasicOpts,\n} from './abstract/hash-to-curve.ts';\nimport {\n Field,\n FpInvertBatch,\n FpSqrtEven,\n isNegativeLE,\n mod,\n pow2,\n type IField,\n} from './abstract/modular.ts';\nimport { montgomery, type MontgomeryECDH as XCurveFn } from './abstract/montgomery.ts';\nimport { bytesToNumberLE, ensureBytes, equalBytes, type Hex } from './utils.ts';\n\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n\n// P = 2n**255n-19n\nconst ed25519_CURVE_p = BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed'\n);\n\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE: EdwardsOpts = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_p;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// √(-1) aka √(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ed25519_CURVE_p;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\nconst Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();\nconst Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();\n\nconst ed25519Defaults = /* @__PURE__ */ (() => ({\n ...ed25519_CURVE,\n Fp,\n hash: sha512,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/√v\n uvRatio,\n}))();\n\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * import { ed25519 } from '@noble/curves/ed25519';\n * const { secretKey, publicKey } = ed25519.keygen();\n * const msg = new TextEncoder().encode('hello');\n * const sig = ed25519.sign(msg, priv);\n * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215\n * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5\n */\nexport const ed25519: CurveFn = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\n/** Context of ed25519. Uses context for domain separation. */\nexport const ed25519ctx: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n }))();\n\n/** Prehashed version of ed25519. Accepts already-hashed messages in sign() and verify(). */\nexport const ed25519ph: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards(\n Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n })\n ))();\n\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * import { x25519 } from '@noble/curves/ed25519';\n * const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';\n * const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';\n * x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases\n * x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);\n * x25519.getPublicKey(x25519.utils.randomSecretKey());\n */\nexport const x25519: XCurveFn = /* @__PURE__ */ (() => {\n const P = Fp.ORDER;\n return montgomery({\n P,\n type: 'x25519',\n powPminus2: (x: bigint): bigint => {\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n });\n})();\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J);// 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd!(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n\n/** Hashing to ed25519 points / field. RFC 9380 methods. */\nexport const ed25519_hasher: H2CHasher<bigint> = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.Point,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\n\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/√(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = EdwardsPoint;\n\n/**\n * Computes Elligator map for Ristretto255.\n * Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B) and on\n * the [website](https://ristretto.group/formulas/elligator.html).\n */\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n const { d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\nfunction ristretto255_map(bytes: Uint8Array): _RistrettoPoint {\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n}\n\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint<_RistrettoPoint> {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();\n // prettier-ignore\n static ZERO: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();\n // prettier-ignore\n static Fp: IField<bigint> =\n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn: IField<bigint> =\n /* @__PURE__ */ (() => Fn)();\n\n constructor(ep: ExtendedPoint) {\n super(ep);\n }\n\n static fromAffine(ap: AffinePoint<bigint>): _RistrettoPoint {\n return new _RistrettoPoint(ed25519.Point.fromAffine(ap));\n }\n\n protected assertSame(other: _RistrettoPoint): void {\n if (!(other instanceof _RistrettoPoint)) throw new Error('RistrettoPoint expected');\n }\n\n protected init(ep: EdwardsPoint): _RistrettoPoint {\n return new _RistrettoPoint(ep);\n }\n\n /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\n static hashToCurve(hex: Hex): _RistrettoPoint {\n return ristretto255_map(ensureBytes('ristrettoHash', hex, 64));\n }\n\n static fromBytes(bytes: Uint8Array): _RistrettoPoint {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const s = bytes255ToNumberLE(bytes);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519.Point(x, y, _1n, t));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: Hex): _RistrettoPoint {\n return _RistrettoPoint.fromBytes(ensureBytes('ristrettoHex', hex, 32));\n }\n\n static msm(points: _RistrettoPoint[], scalars: bigint[]): _RistrettoPoint {\n return pippenger(_RistrettoPoint, ed25519.Point.Fn, points, scalars);\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes(): Uint8Array {\n let { X, Y, Z, T } = this.ep;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1\n const u2 = mod(X * Y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * T); // 6\n let D: bigint; // 7\n if (isNegativeLE(T * zInv, P)) {\n let _x = mod(Y * SQRT_M1);\n let _y = mod(X * SQRT_M1);\n X = _x;\n Y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(X * zInv, P)) Y = mod(-Y); // 9\n let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return Fp.toBytes(s); // 11\n }\n\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other: _RistrettoPoint): boolean {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n const mod = (n: bigint) => Fp.create(n);\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n is0(): boolean {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\n\nexport const ristretto255: {\n Point: typeof _RistrettoPoint;\n} = { Point: _RistrettoPoint };\n\n/** Hashing to ristretto255 points / field. RFC 9380 methods. */\nexport const ristretto255_hasher: H2CHasherBase<bigint> = {\n hashToCurve(msg: Uint8Array, options?: htfBasicOpts): _RistrettoPoint {\n const DST = options?.DST || 'ristretto255_XMD:SHA-512_R255MAP_RO_';\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n return ristretto255_map(xmd);\n },\n hashToScalar(msg: Uint8Array, options: htfBasicOpts = { DST: _DST_scalar }) {\n const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n};\n\n// export const ristretto255_oprf: OPRF = createORPF({\n// name: 'ristretto255-SHA512',\n// Point: RistrettoPoint,\n// hash: sha512,\n// hashToGroup: ristretto255_hasher.hashToCurve,\n// hashToScalar: ristretto255_hasher.hashToScalar,\n// });\n\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * ⟨T⟩ = { O, T, 2T, 3T, 4T, 5T, 6T, 7T }\n */\nexport const ED25519_TORSION_SUBGROUP: string[] = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\n/** @deprecated use `ed25519.utils.toMontgomery` */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n return ed25519.utils.toMontgomery(ensureBytes('pub', edwardsPub));\n}\n/** @deprecated use `ed25519.utils.toMontgomery` */\nexport const edwardsToMontgomery: typeof edwardsToMontgomeryPub = edwardsToMontgomeryPub;\n\n/** @deprecated use `ed25519.utils.toMontgomerySecret` */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n return ed25519.utils.toMontgomerySecret(ensureBytes('pub', edwardsPriv));\n}\n\n/** @deprecated use `ristretto255.Point` */\nexport const RistrettoPoint: typeof _RistrettoPoint = _RistrettoPoint;\n/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */\nexport const hashToCurve: H2CMethod<bigint> = /* @__PURE__ */ (() => ed25519_hasher.hashToCurve)();\n/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */\nexport const encodeToCurve: H2CMethod<bigint> = /* @__PURE__ */ (() =>\n ed25519_hasher.encodeToCurve)();\ntype RistHasher = (msg: Uint8Array, options: htfBasicOpts) => _RistrettoPoint;\n/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\nexport const hashToRistretto255: RistHasher = /* @__PURE__ */ (() =>\n ristretto255_hasher.hashToCurve as RistHasher)();\n/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\nexport const hash_to_ristretto255: RistHasher = /* @__PURE__ */ (() =>\n ristretto255_hasher.hashToCurve as RistHasher)();\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n isBytes as isBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n abytes,\n anumber,\n bytesToHex,\n bytesToUtf8,\n concatBytes,\n hexToBytes,\n isBytes,\n randomBytes,\n utf8ToBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function abool(title: string, value: boolean): void {\n if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);\n}\n\n// tmp name until v2\nexport function _abool2(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\"`;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n// tmp name until v2\n/** Asserts something is Uint8Array. */\nexport function _abytes2(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes_(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n abytes_(bytes);\n return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes_(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'secret key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes_(hex);\n } catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n } else if (isBytes_(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(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/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as utf8ToBytes for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n });\n}\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\n// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\n// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n const u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\n const u8of = (byte: number) => Uint8Array.of(byte); // another shortcut\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n(0)) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes_(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\n\nexport function validateObject<T extends Record<string, any>>(\n object: T,\n validators: ValMap<T>,\n optValidators: ValMap<T> = {}\n): T {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function') throw new Error('invalid validator function');\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n 'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n\nexport function isHash(val: CHash): boolean {\n return typeof val === 'function' && Number.isSafeInteger(val.outputLen);\n}\nexport function _validateObject(\n object: Record<string, any>,\n fields: Record<string, string>,\n optFields: Record<string, string> = {}\n): void {\n if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));\n Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));\n}\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized<T extends object, R, O extends any[]>(\n fn: (arg: T, ...args: O) => R\n): (arg: T, ...args: O) => R {\n const map = new WeakMap<T, R>();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n _validateObject,\n anumber,\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n} from '../utils.ts';\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);\n// prettier-ignore\nconst _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\n}\n\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\nfunction assertIsSquare<T>(Fp: IField<T>, root: T, n: T): void {\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\n\nfunction sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n assertIsSquare(Fp, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return <T>(Fp: IField<T>, n: T) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3);// 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Field is not always over prime: for example, Fp2 has ORDER(q)=p^m. */\nexport interface IField<T> {\n ORDER: bigint;\n isLE: boolean;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n isValidNot0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n allowedLengths?: number[];\n // legendre?(num: T): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField<T>(field: IField<T>): IField<T> {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n _validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow<T>(Fp: IField<T>, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch<T>(Fp: IField<T>, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv<T>(Fp: IField<T>, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n */\nexport function FpLegendre<T>(Fp: IField<T>, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(Fp: IField<T>, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\nexport type NLength = { nByteLength: number; nBitLength: number };\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n sqrt: SqrtFn;\n isLE: boolean;\n BITS: number;\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes)\n}>;\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLenOrOpts?: number | FieldOpts, // TODO: use opts only in v2?\n isLE = false,\n opts: { sqrt?: SqrtFn } = {}\n): Readonly<FpField> {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n let _sqrt: SqrtFn | undefined = undefined;\n let modFromBytes: boolean = false;\n let allowedLengths: undefined | readonly number[] = undefined;\n if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {\n if (opts.sqrt || isLE) throw new Error('cannot specify opts in two arguments');\n const _opts = bitLenOrOpts;\n if (_opts.BITS) _nbitLength = _opts.BITS;\n if (_opts.sqrt) _sqrt = _opts.sqrt;\n if (typeof _opts.isLE === 'boolean') isLE = _opts.isLE;\n if (typeof _opts.modFromBytes === 'boolean') modFromBytes = _opts.modFromBytes;\n allowedLengths = _opts.allowedLengths;\n } else {\n if (typeof bitLenOrOpts === 'number') _nbitLength = bitLenOrOpts;\n if (opts.sqrt) _sqrt = opts.sqrt;\n }\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);\n if (BYTES > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP: ReturnType<typeof FpSqrt>; // cached sqrtP\n const f: Readonly<FpField> = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n allowedLengths: allowedLengths,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n // is valid and invertible\n isValidNot0: (num: bigint) => !f.is0(num) && f.isValid(num),\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt:\n _sqrt ||\n ((n) => {\n if (!sqrtP) sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes, skipValidation = true) => {\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!f.isValid(scalar)) throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n },\n // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(\n 'hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen\n );\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject } from '../utils.ts';\nimport { Field, FpInvertBatch, nLength, validateField, type IField } from './modular.ts';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { Z?: never };\n\n// This was initialy do this way to re-use montgomery ladder in field (add->mul,double->sqr), but\n// that didn't happen and there is probably not much reason to have separate Group like this?\nexport interface Group<T extends Group<T>> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n toAffine?(invertedZ?: any): AffinePoint<any>;\n}\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic curve Points. */\nexport interface CurvePoint<F, P extends CurvePoint<F, P>> extends Group<P> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n Z?: F;\n double(): P;\n negate(): P;\n add(other: P): P;\n subtract(other: P): P;\n equals(other: P): boolean;\n multiply(scalar: bigint): P;\n assertValidity(): void;\n clearCofactor(): P;\n is0(): boolean;\n isTorsionFree(): boolean;\n isSmallOrder(): boolean;\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * @param isLazy calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /** Converts point to 2D xy affine coordinates */\n toAffine(invertedZ?: F): AffinePoint<F>;\n toBytes(): Uint8Array;\n toHex(): string;\n}\n\n/** Base interface for all elliptic curve Point constructors. */\nexport interface CurvePointCons<P extends CurvePoint<any, P>> {\n [Symbol.hasInstance]: (item: unknown) => boolean;\n BASE: P;\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField<P_F<P>>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField<bigint>;\n /** Creates point from x, y. Does NOT validate if the point is valid. Use `.assertValidity()`. */\n fromAffine(p: AffinePoint<P_F<P>>): P;\n fromBytes(bytes: Uint8Array): P;\n fromHex(hex: Uint8Array | string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint<PC>': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint<PC>': it won't be accesible for arguments/return types\n// * `CurvePointCons<P extends CurvePoint<any, P>>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons<any>`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint<any, P>.\n// this means we need to do stuff like\n// `function test<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(`\n// if we want type safety around P, otherwise PC_P<PC> will be any\n\n/** Returns Fp type from Point (P_F<P> == P.F) */\nexport type P_F<P extends CurvePoint<any, P>> = P extends CurvePoint<infer F, P> ? F : never;\n/** Returns Fp type from PointCons (PC_F<PC> == PC.P.F) */\nexport type PC_F<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['Fp']['ZERO'];\n/** Returns Point type from PointCons (PC_P<PC> == PC.P) */\nexport type PC_P<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons<CurvePoint<any, any>>`, will return `any` after 1 operation\n// * `CurvePointCons<any>: WeierstrassPointCons<bigint> extends CurvePointCons<any> = false`\n// * `P extends CurvePoint, PC extends CurvePointCons<P>`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons<F, P>`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\nexport type PC_ANY = CurvePointCons<\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any, any>\n >>>>>>>>>\n>;\n\nexport interface CurveLengths {\n secretKey?: number;\n publicKey?: number;\n publicKeyUncompressed?: number;\n publicKeyHasPrefix?: boolean;\n signature?: number;\n seed?: number;\n}\nexport type GroupConstructor<T> = {\n BASE: T;\n ZERO: T;\n};\n/** @deprecated */\nexport type ExtendedGroupConstructor<T> = GroupConstructor<T> & {\n Fp: IField<any>;\n Fn: IField<bigint>;\n fromAffine(ap: AffinePoint<any>): T;\n};\nexport type Mapper<T> = (i: T[]) => T[];\n\nexport function negateCt<T extends { negate: () => T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\nexport function normalizeZ<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap<any, any[]>();\nconst pointWindowSizes = new WeakMap<any, number>();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF<PC extends PC_ANY> {\n private readonly BASE: PC_P<PC>;\n private readonly ZERO: PC_P<PC>;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P<PC>, n: bigint, p: PC_P<PC> = this.ZERO): PC_P<PC> {\n let d: PC_P<PC> = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P<PC>, W: number): PC_P<PC>[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P<PC>[] = [];\n let p: PC_P<PC> = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P<PC>[], n: bigint): { p: PC_P<PC>; f: PC_P<PC> } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n }\n\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P<PC>[],\n n: bigint,\n acc: PC_P<PC> = this.ZERO\n ): PC_P<PC> {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P<PC>, transform?: Mapper<PC_P<PC>>): PC_P<PC>[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P<PC>[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P<PC>,\n scalar: bigint,\n transform?: Mapper<PC_P<PC>>\n ): { p: PC_P<PC>; f: PC_P<PC> } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P<PC>, scalar: bigint, transform?: Mapper<PC_P<PC>>, prev?: PC_P<PC>): PC_P<PC> {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P: PC_P<PC>, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P<PC>): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka secret keys / bigints)\n */\nexport function pippenger<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n fieldN: IField<bigint>,\n points: P[],\n scalars: bigint[]\n): P {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as P;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n fieldN: IField<bigint>,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p: P) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): P => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\n// TODO: remove\n/**\n * Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n * Though generator can be different (Fp2 / Fp6 for BLS).\n */\nexport type BasicCurve<T> = {\n Fp: IField<T>; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\n// TODO: remove\n/** @deprecated */\nexport function validateBasic<FP, T>(\n curve: BasicCurve<FP> & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve<FP> &\n T & {\n p: bigint;\n }\n> {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n\nexport type ValidCurveParams<T> = {\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b?: T;\n d?: T;\n Gx: T;\n Gy: T;\n};\n\nfunction createField<T>(order: bigint, field?: IField<T>, isLE?: boolean): IField<T> {\n if (field) {\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n } else {\n return Field(order, { isLE }) as unknown as IField<T>;\n }\n}\nexport type FpFn<T> = { Fp: IField<T>; Fn: IField<bigint> };\n\n/** Validates CURVE opts and creates fields */\nexport function _createCurveFields<T>(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams<T>,\n curveOpts: Partial<FpFn<T>> = {},\n FpFnLE?: boolean\n): FpFn<T> & { CURVE: ValidCurveParams<T> } {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n","/**\n * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n _validateObject,\n _abool2 as abool,\n _abytes2 as abytes,\n aInRange,\n bytesToHex,\n bytesToNumberLE,\n concatBytes,\n copyBytes,\n ensureBytes,\n isBytes,\n memoized,\n notImplemented,\n randomBytes as randomBytesWeb,\n type FHash,\n type Hex,\n} from '../utils.ts';\nimport {\n _createCurveFields,\n normalizeZ,\n pippenger,\n wNAF,\n type AffinePoint,\n type BasicCurve,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport { Field, type IField, type NLength } from './modular.ts';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\nexport type UVRatio = (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n\n/** Instance of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPoint extends CurvePoint<bigint, EdwardsPoint> {\n /** extended X coordinate. Different from affine x. */\n readonly X: bigint;\n /** extended Y coordinate. Different from affine y. */\n readonly Y: bigint;\n /** extended Z coordinate */\n readonly Z: bigint;\n /** extended T coordinate */\n readonly T: bigint;\n\n /** @deprecated use `toBytes` */\n toRawBytes(): Uint8Array;\n /** @deprecated use `p.precompute(windowSize)` */\n _setWindowSize(windowSize: number): void;\n /** @deprecated use .X */\n readonly ex: bigint;\n /** @deprecated use .Y */\n readonly ey: bigint;\n /** @deprecated use .Z */\n readonly ez: bigint;\n /** @deprecated use .T */\n readonly et: bigint;\n}\n/** Static methods of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPointCons extends CurvePointCons<EdwardsPoint> {\n new (X: bigint, Y: bigint, Z: bigint, T: bigint): EdwardsPoint;\n CURVE(): EdwardsOpts;\n fromBytes(bytes: Uint8Array, zip215?: boolean): EdwardsPoint;\n fromHex(hex: Hex, zip215?: boolean): EdwardsPoint;\n /** @deprecated use `import { pippenger } from '@noble/curves/abstract/curve.js';` */\n msm(points: EdwardsPoint[], scalars: bigint[]): EdwardsPoint;\n}\n/** @deprecated use EdwardsPoint */\nexport type ExtPointType = EdwardsPoint;\n/** @deprecated use EdwardsPointCons */\nexport type ExtPointConstructor = EdwardsPointCons;\n\n/**\n * Twisted Edwards curve options.\n *\n * * a: formula param\n * * d: formula param\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor. h*n is group order; n is subgroup order\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type EdwardsOpts = Readonly<{\n p: bigint;\n n: bigint;\n h: bigint;\n a: bigint;\n d: bigint;\n Gx: bigint;\n Gy: bigint;\n}>;\n\n/**\n * Extra curve options for Twisted Edwards.\n *\n * * Fp: redefined Field over curve.p\n * * Fn: redefined Field over curve.n\n * * uvRatio: helper function for decompression, calculating √(u/v)\n */\nexport type EdwardsExtraOpts = Partial<{\n Fp: IField<bigint>;\n Fn: IField<bigint>;\n FpFnLE: boolean;\n uvRatio: (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) options.\n *\n * * hash: hash function used to hash secret keys and messages\n * * adjustScalarBytes: clears bits to get valid field element\n * * domain: Used for hashing\n * * mapToCurve: for hash-to-curve standard\n * * prehash: RFC 8032 pre-hashing of messages to sign() / verify()\n * * randomBytes: function generating random bytes, used for randomSecretKey\n */\nexport type EdDSAOpts = Partial<{\n adjustScalarBytes: (bytes: Uint8Array) => Uint8Array;\n domain: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;\n mapToCurve: (scalar: bigint[]) => AffinePoint<bigint>;\n prehash: FHash;\n randomBytes: (bytesLength?: number) => Uint8Array;\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) interface.\n *\n * Allows to create and verify signatures, create public and secret keys.\n */\nexport interface EdDSA {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Hex) => Uint8Array;\n sign: (message: Hex, secretKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n Point: EdwardsPointCons;\n utils: {\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n isValidSecretKey: (secretKey: Uint8Array) => boolean;\n isValidPublicKey: (publicKey: Uint8Array, zip215?: boolean) => boolean;\n\n /**\n * Converts ed public key to x public key.\n *\n * There is NO `fromMontgomery`:\n * - There are 2 valid ed25519 points for every x25519, with flipped coordinate\n * - Sometimes there are 0 valid ed25519 points, because x25519 *additionally*\n * accepts inputs on the quadratic twist, which can't be moved to ed25519\n *\n * @example\n * ```js\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomSecretKey());\n * const aPriv = x25519.utils.randomSecretKey();\n * x25519.getSharedSecret(aPriv, ed25519.utils.toMontgomery(someonesPub))\n * ```\n */\n toMontgomery: (publicKey: Uint8Array) => Uint8Array;\n /**\n * Converts ed secret key to x secret key.\n * @example\n * ```js\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomSecretKey());\n * const aPriv = ed25519.utils.randomSecretKey();\n * x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(aPriv), someonesPub)\n * ```\n */\n toMontgomerySecret: (privateKey: Uint8Array) => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: EdwardsPoint;\n pointBytes: Uint8Array;\n };\n\n /** @deprecated use `randomSecretKey` */\n randomPrivateKey: (seed?: Uint8Array) => Uint8Array;\n /** @deprecated use `point.precompute()` */\n precompute: (windowSize?: number, point?: EdwardsPoint) => EdwardsPoint;\n };\n lengths: CurveLengths;\n}\n\nfunction isEdValidXY(Fp: IField<bigint>, CURVE: EdwardsOpts, x: bigint, y: bigint): boolean {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\n\nexport function edwards(params: EdwardsOpts, extraOpts: EdwardsExtraOpts = {}): EdwardsPointCons {\n const validated = _createCurveFields('edwards', params, extraOpts, extraOpts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as EdwardsOpts;\n const { h: cofactor } = CURVE;\n _validateObject(extraOpts, {}, { uvRatio: 'function' });\n\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);\n const modP = (n: bigint) => Fp.create(n); // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n extraOpts.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n\n // Validate whether the passed curve params are valid.\n // equation ax² + y² = 1 + dx²y² should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title: string, n: bigint, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n\n function aextpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p: Point, iz?: bigint): AffinePoint<bigint> => {\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(Z) as bigint); // 8 was chosen arbitrarily\n const x = modP(X * iz);\n const y = modP(Y * iz);\n const zz = Fp.mul(Z, iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x, y };\n });\n const assertValidMemo = memoized((p: Point) => {\n const { a, d } = CURVE;\n if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { X, Y, Z, T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n return true;\n });\n\n // Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements EdwardsPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n // zero / infinity / identity point\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: bigint;\n readonly Y: bigint;\n readonly Z: bigint;\n readonly T: bigint;\n\n constructor(X: bigint, Y: bigint, Z: bigint, T: bigint) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n\n static CURVE(): EdwardsOpts {\n return CURVE;\n }\n\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes: Uint8Array, zip215 = false): Point {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\n\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid) throw new Error('bad point: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromHex(bytes: Uint8Array, zip215 = false): Point {\n return Point.fromBytes(ensureBytes('point', bytes), zip215);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n precompute(windowSize: number = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_2n); // random number\n return this;\n }\n\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n aextpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n aextpoint(other);\n const { a, d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n // 1 <= scalar < L\n if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n return normalizeZ(Point, [p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n multiplyUnsafe(scalar: bigint, acc = Point.ZERO): Point {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar)) throw new Error('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n) return Point.ZERO;\n if (this.is0() || scalar === _1n) return this;\n return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafe(this, CURVE.n).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return toAffineMemo(this, invertedZ);\n }\n\n clearCofactor(): Point {\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n toBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n\n // TODO: remove\n get ex(): bigint {\n return this.X;\n }\n get ey(): bigint {\n return this.Y;\n }\n get ez(): bigint {\n return this.Z;\n }\n get et(): bigint {\n return this.T;\n }\n static normalizeZ(points: Point[]): Point[] {\n return normalizeZ(Point, points);\n }\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n _setWindowSize(windowSize: number) {\n this.precompute(windowSize);\n }\n toRawBytes(): Uint8Array {\n return this.toBytes();\n }\n }\n const wnaf = new wNAF(Point, Fn.BITS);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points.\n */\nexport abstract class PrimeEdwardsPoint<T extends PrimeEdwardsPoint<T>>\n implements CurvePoint<bigint, T>\n{\n static BASE: PrimeEdwardsPoint<any>;\n static ZERO: PrimeEdwardsPoint<any>;\n static Fp: IField<bigint>;\n static Fn: IField<bigint>;\n\n protected readonly ep: EdwardsPoint;\n\n constructor(ep: EdwardsPoint) {\n this.ep = ep;\n }\n\n // Abstract methods that must be implemented by subclasses\n abstract toBytes(): Uint8Array;\n abstract equals(other: T): boolean;\n\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes: Uint8Array): any {\n notImplemented();\n }\n\n static fromHex(_hex: Hex): any {\n notImplemented();\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n // Common implementations\n clearCofactor(): T {\n // no-op for prime-order groups\n return this as any;\n }\n\n assertValidity(): void {\n this.ep.assertValidity();\n }\n\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return this.ep.toAffine(invertedZ);\n }\n\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n isTorsionFree(): boolean {\n return true;\n }\n\n isSmallOrder(): boolean {\n return false;\n }\n\n add(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n\n subtract(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): T {\n return this.init(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): T {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): T {\n return this.init(this.ep.double());\n }\n\n negate(): T {\n return this.init(this.ep.negate());\n }\n\n precompute(windowSize?: number, isLazy?: boolean): T {\n return this.init(this.ep.precompute(windowSize, isLazy));\n }\n\n // Helper methods\n abstract is0(): boolean;\n protected abstract assertSame(other: T): void;\n protected abstract init(ep: EdwardsPoint): T;\n\n /** @deprecated use `toBytes` */\n toRawBytes(): Uint8Array {\n return this.toBytes();\n }\n}\n\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n */\nexport function eddsa(Point: EdwardsPointCons, cHash: FHash, eddsaOpts: EdDSAOpts = {}): EdDSA {\n if (typeof cHash !== 'function') throw new Error('\"hash\" function param is required');\n _validateObject(\n eddsaOpts,\n {},\n {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n mapToCurve: 'function',\n }\n );\n\n const { prehash } = eddsaOpts;\n const { BASE, Fp, Fn } = Point;\n\n const randomBytes = eddsaOpts.randomBytes || randomBytesWeb;\n const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes: Uint8Array) => bytes);\n const domain =\n eddsaOpts.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key: Hex) {\n const len = lengths.secretKey;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5 */\n function getExtendedPublicKey(secretKey: Hex) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey: Hex): Uint8Array {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = Uint8Array.of(), ...msgs: Uint8Array[]) {\n const msg = concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, secretKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s)) throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n\n // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\n const verifyOpts: { context?: Hex; zip215?: boolean } = { zip215: true };\n\n /**\n * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n * An extended group equation is checked.\n */\n function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = lengths.signature;\n sig = ensureBytes('signature', sig, len);\n msg = ensureBytes('message', msg);\n publicKey = ensureBytes('publicKey', publicKey, lengths.publicKey);\n if (zip215 !== undefined) abool(zip215, 'zip215');\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false; // zip215 allows public keys of small order\n\n const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed = randomBytes(lengths.seed)): Uint8Array {\n return abytes(seed, lengths.seed, 'seed');\n }\n function keygen(seed?: Uint8Array) {\n const secretKey = utils.randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n }\n function isValidSecretKey(key: Uint8Array): boolean {\n return isBytes(key) && key.length === Fn.BYTES;\n }\n function isValidPublicKey(key: Uint8Array, zip215?: boolean): boolean {\n try {\n return !!Point.fromBytes(key, zip215);\n } catch (error) {\n return false;\n }\n }\n\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /**\n * Converts ed public key to x public key. Uses formula:\n * - ed25519:\n * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * - ed448:\n * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n */\n toMontgomery(publicKey: Uint8Array): Uint8Array {\n const { y } = Point.fromBytes(publicKey);\n const size = lengths.publicKey;\n const is25519 = size === 32;\n if (!is25519 && size !== 57) throw new Error('only defined for 25519 and 448');\n const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n return Fp.toBytes(u);\n },\n\n toMontgomerySecret(secretKey: Uint8Array): Uint8Array {\n const size = lengths.secretKey;\n abytes(secretKey, size);\n const hashed = cHash(secretKey.subarray(0, size));\n return adjustScalarBytes(hashed).subarray(0, size);\n },\n\n /** @deprecated */\n randomPrivateKey: randomSecretKey,\n /** @deprecated */\n precompute(windowSize = 8, point: EdwardsPoint = Point.BASE): EdwardsPoint {\n return point.precompute(windowSize, false);\n },\n };\n\n return Object.freeze({\n keygen,\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n });\n}\n\n// TODO: remove everything below\nexport type CurveType = BasicCurve<bigint> & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n /** @deprecated the property will be removed in next release */\n hash: FHash; // Hashing\n randomBytes?: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: UVRatio; // Ratio √(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\nexport type CurveTypeWithLength = Readonly<CurveType & Partial<NLength>>;\nexport type CurveFn = {\n /** @deprecated the property will be removed in next release */\n CURVE: CurveType;\n keygen: EdDSA['keygen'];\n getPublicKey: EdDSA['getPublicKey'];\n sign: EdDSA['sign'];\n verify: EdDSA['verify'];\n Point: EdwardsPointCons;\n /** @deprecated use `Point` */\n ExtendedPoint: EdwardsPointCons;\n utils: EdDSA['utils'];\n lengths: CurveLengths;\n};\nexport type EdComposed = {\n CURVE: EdwardsOpts;\n curveOpts: EdwardsExtraOpts;\n hash: FHash;\n eddsaOpts: EdDSAOpts;\n};\nfunction _eddsa_legacy_opts_to_new(c: CurveTypeWithLength): EdComposed {\n const CURVE: EdwardsOpts = {\n a: c.a,\n d: c.d,\n p: c.Fp.ORDER,\n n: c.n,\n h: c.h,\n Gx: c.Gx,\n Gy: c.Gy,\n };\n const Fp = c.Fp;\n const Fn = Field(CURVE.n, c.nBitLength, true);\n const curveOpts: EdwardsExtraOpts = { Fp, Fn, uvRatio: c.uvRatio };\n const eddsaOpts: EdDSAOpts = {\n randomBytes: c.randomBytes,\n adjustScalarBytes: c.adjustScalarBytes,\n domain: c.domain,\n prehash: c.prehash,\n mapToCurve: c.mapToCurve,\n };\n return { CURVE, curveOpts, hash: c.hash, eddsaOpts };\n}\nfunction _eddsa_new_output_to_legacy(c: CurveTypeWithLength, eddsa: EdDSA): CurveFn {\n const Point = eddsa.Point;\n const legacy = Object.assign({}, eddsa, {\n ExtendedPoint: Point,\n CURVE: c,\n nBitLength: Point.Fn.BITS,\n nByteLength: Point.Fn.BYTES,\n });\n return legacy;\n}\n// TODO: remove. Use eddsa\nexport function twistedEdwards(c: CurveTypeWithLength): CurveFn {\n const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);\n const Point = edwards(CURVE, curveOpts);\n const EDDSA = eddsa(Point, hash, eddsaOpts);\n return _eddsa_new_output_to_legacy(c, EDDSA);\n}\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) { return true }\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') { return o }\n if (o instanceof ArrayBuffer) { return new Uint8Array(o) }\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable<number>} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder<Base extends string, Prefix extends string> implements MultibaseEncoder<Prefix>, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase<Prefix> {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder<Base extends string, Prefix extends string> implements MultibaseDecoder<Prefix>, UnibaseDecoder<Prefix>, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n const prefixCodePoint = prefix.codePointAt(0)\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefixCodePoint\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or<OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n}\n\ntype Decoders<Prefix extends string> = Record<Prefix, UnibaseDecoder<Prefix>>\n\nclass ComposedDecoder<Prefix extends string> implements MultibaseDecoder<Prefix>, CombobaseDecoder<Prefix> {\n readonly decoders: Decoders<Prefix>\n\n constructor (decoders: Decoders<Prefix>) {\n this.decoders = decoders\n }\n\n or <OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or <L extends string, R extends string> (left: UnibaseDecoder<L> | CombobaseDecoder<L>, right: UnibaseDecoder<R> | CombobaseDecoder<R>): ComposedDecoder<L | R> {\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder<L>).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder<R>).prefix]: right })\n } as Decoders<L | R>)\n}\n\nexport class Codec<Base extends string, Prefix extends string> implements MultibaseCodec<Prefix>, MultibaseEncoder<Prefix>, MultibaseDecoder<Prefix>, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder<Base, Prefix>\n readonly decoder: Decoder<Base, Prefix>\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from <Base extends string, Prefix extends string> ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec<Base, Prefix> {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX <Base extends string, Prefix extends string> ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec<Base, Prefix> {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabetIdx: Record<string, number>, bitsPerChar: number, name: string): Uint8Array {\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = alphabetIdx[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\nfunction createAlphabetIdx (alphabet: string): Record<string, number> {\n // Build the character lookup table:\n const alphabetIdx: Record<string, number> = {}\n for (let i = 0; i < alphabet.length; ++i) {\n alphabetIdx[alphabet[i]] = i\n }\n return alphabetIdx\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 <Base extends string, Prefix extends string> ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec<Base, Prefix> {\n const alphabetIdx = createAlphabetIdx(alphabet)\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabetIdx, bitsPerChar, name)\n }\n })\n}\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create <Code extends number> (code: Code, digest: Uint8Array): Digest<Code, number> {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest<Code extends number, Size extends number> implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n\n/**\n * Used to check that the passed multihash has the passed code\n */\nexport function hasCode <T extends number> (digest: MultihashDigest, code: T): digest is MultihashDigest<T> {\n return digest.code === code\n}\n","import { base32 } from './bases/base32.js'\nimport { base36 } from './bases/base36.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format <T extends API.Link<unknown, number, number, API.Version>, Prefix extends string> (link: T, base?: API.MultibaseEncoder<Prefix>): API.ToString<T, Prefix> {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder<Prefix>\n )\n }\n}\n\nexport function toJSON <Link extends API.UnknownLink> (link: Link): API.LinkJSON<Link> {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON <Link extends API.UnknownLink> (json: API.LinkJSON<Link>): CID<unknown, number, number, API.Version> {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap<API.UnknownLink, Map<string, string>>()\n\nfunction baseCache (cid: API.UnknownLink): Map<string, string> {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID<Data = unknown, Format extends number = number, Alg extends number = number, Version extends API.Version = API.Version> implements API.Link<Data, Format, Alg, Version> {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest<Alg>\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest<Alg>, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID<Data, API.DAG_PB, API.SHA_256, 0> {\n switch (this.version) {\n case 0: {\n return this as CID<Data, API.DAG_PB, API.SHA_256, 0>\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest<API.SHA_256>\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID<Data, Format, Alg, 1> {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID<Data, Format, Alg, 1>\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID<Data, Format, Alg, Version> {\n return CID.equals(this, other)\n }\n\n static equals <Data, Format extends number, Alg extends number, Version extends API.Version>(self: API.Link<Data, Format, Alg, Version>, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder<string>): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON<this> {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID <Data, Format extends number, Alg extends number, Version extends API.Version, U>(input: API.Link<Data, Format, Alg, Version> | U): CID<Data, Format, Alg, Version> | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest<Alg>,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest<Alg>\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create <Data, Format extends number, Alg extends number, Version extends API.Version>(version: Version, code: Format, digest: API.MultihashDigest<Alg>): CID<Data, Format, Alg, Version> {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 <T = unknown>(digest: API.MultihashDigest<typeof SHA_256_CODE>): CID<T, typeof DAG_PB_CODE, typeof SHA_256_CODE, 0> {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 <Data, Code extends number, Alg extends number>(code: Code, digest: API.MultihashDigest<Alg>): CID<Data, Code, Alg, 1> {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode <Data, Code extends number, Alg extends number, Version extends API.Version>(bytes: API.ByteView<API.Link<Data, Code, Alg, Version>>): CID<Data, Code, Alg, Version> {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst <T, C extends number, A extends number, V extends API.Version>(bytes: API.ByteView<API.Link<T, C, A, V>>): [CID<T, C, A, V>, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest<API.SHA_256>)\n : CID.createV1(specs.codec, digest)\n return [cid as CID<T, C, A, V>, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes <T, C extends number, A extends number, V extends API.Version>(initialBytes: API.ByteView<API.Link<T, C, A, V>>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version>(source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): CID<Data, Code, Alg, Version> {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version> (source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): [Prefix, API.ByteView<API.Link<Data, Code, Alg, Version>>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n case base36.prefix: {\n const decoder = base ?? base36\n return [base36.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 <Prefix extends string> (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<Prefix>): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n","import { sha256 } from \"@noble/hashes/sha256\";\nimport { blake3 } from \"@noble/hashes/blake3\";\nimport { ed25519 } from \"@noble/curves/ed25519\";\nimport { CID } from \"multiformats/cid\";\nimport { base58btc } from \"multiformats/bases/base58\";\nimport { create as createDigest } from \"multiformats/hashes/digest\";\nimport { z } from \"zod\";\nimport { jcsCanonicalize } from \"./jcs\";\nimport { httpResponseError } from \"../http-error\";\n\nexport const POLICY_V1_SCHEMA = \"xyz.tinycloud.policy/policy/v1\" as const;\nexport const POLICY_CAPABILITY_V1_SCHEMA =\n \"xyz.tinycloud.policy/capability/v1\" as const;\nexport const POLICY_ENFORCEMENT_DELEGATION_V2_SCHEMA =\n \"xyz.tinycloud.policy/enforcement-delegation/v2\" as const;\nexport const ATTESTED_ENFORCER_BINDING_V2_SCHEMA =\n \"xyz.tinycloud.policy/attested-enforcer/v2\" as const;\nexport const ROOT_STATUS_CHECKPOINT_V1_SCHEMA =\n \"xyz.tinycloud.policy/root-status/v1\" as const;\nexport const ROOT_REVOCATION_V1_SCHEMA =\n \"xyz.tinycloud.policy/root-revocation/v1\" as const;\nexport const POLICY_SESSION_UCAN_V1_PROFILE = \"policy-session-ucan/v1\" as const;\n\nexport const POLICY_V1_DOMAIN = \"xyz.tinycloud.policy/policy/v1\\0\";\nexport const POLICY_CAPABILITY_V1_DOMAIN =\n \"xyz.tinycloud.policy/PolicyCapability/v1\\0\";\nexport const CONTENT_SOURCE_V1_DOMAIN =\n \"xyz.tinycloud.policy/ContentSource/v1\\0\";\nexport const NATIVE_PROJECTION_V1_DOMAIN =\n \"xyz.tinycloud.policy/NativeProjection/v1\\0\";\nexport const ROOT_STATUS_V1_DOMAIN =\n \"xyz.tinycloud.policy/RootStatusCheckpoint/v1\\0\";\nexport const ROOT_STATUS_RENEWAL_V1_DOMAIN =\n \"xyz.tinycloud.policy/RootStatusRenewal/v1\\0\";\nexport const ROOT_REVOCATION_V1_DOMAIN =\n \"xyz.tinycloud.policy/RootRevocation/v1\\0\";\n\nexport const LAST_V2_CREATE_AT = \"2026-09-30T00:00:00Z\" as const;\nexport const MAX_LEGACY_ENVELOPE_EXPIRES_AT = \"2026-12-29T00:00:00Z\" as const;\nexport const LAST_V2_READ_AT = \"2027-01-05T00:00:00Z\" as const;\n\nexport type UnifiedResourceSelector = \"exact\" | \"prefix\";\n\nexport interface UnifiedKvCapability {\n readonly kind: \"kv\";\n readonly resource: string;\n readonly selector: UnifiedResourceSelector;\n readonly actions: readonly (\n | \"tinycloud.kv/get\"\n | \"tinycloud.kv/list\"\n | \"tinycloud.kv/metadata\"\n | \"tinycloud.kv/put\"\n )[];\n}\n\nexport interface UnifiedEncryptionCapability {\n readonly kind: \"encryption\";\n readonly resource: string;\n readonly action: \"tinycloud.encryption/decrypt\";\n}\n\nexport type UnifiedPolicyCapability =\n | UnifiedKvCapability\n | UnifiedEncryptionCapability;\n\nexport interface UnifiedNativeCapability {\n readonly service: \"tinycloud.kv\" | \"tinycloud.encryption\";\n readonly space: string;\n readonly path: string;\n readonly actions: readonly string[];\n readonly caveat?: Readonly<Record<string, string>>;\n}\n\nexport interface UnifiedContentSource {\n readonly shareId: string;\n readonly kvResource: string;\n readonly selector: UnifiedResourceSelector;\n readonly encryptionNetwork: string;\n readonly encryptedSymmetricKeyDigestHex: string;\n readonly keyVersion: number;\n readonly mode: \"mutable\" | \"immutable\";\n readonly initialCiphertextDigestHex?: string;\n}\n\nexport interface UnifiedPolicyV1 {\n readonly schema: typeof POLICY_V1_SCHEMA;\n readonly policyId: string;\n readonly ownerDid: string;\n readonly createdAt: string;\n readonly expiresAt?: string;\n readonly contentSource: UnifiedContentSource;\n readonly capabilityCeiling: readonly UnifiedPolicyCapability[];\n readonly signature: {\n readonly suite: string;\n readonly signerDid: string;\n readonly value: string;\n };\n}\n\nexport interface PolicyRootV3 {\n readonly cid: string;\n readonly authorization: string;\n}\n\nexport interface RegisterPolicyV3Input {\n readonly nodeOrigin: string;\n readonly policyCid: string;\n readonly policy: Readonly<Record<string, unknown>>;\n readonly policyRoot: PolicyRootV3;\n readonly enforcementRoot: PolicyRootV3;\n readonly contentSourceDigestHex: string;\n readonly nativeProjectionHashHex: string;\n readonly rootExpiresAt: string;\n readonly enforcerDid: string;\n readonly expectedNodeAudience: string;\n readonly fetch?: typeof fetch;\n readonly signal?: AbortSignal;\n}\n\nexport interface AttestedEnforcerBindingV2 {\n readonly schema: \"xyz.tinycloud.policy/attested-enforcer/v2\";\n readonly enforcerDid: string;\n readonly nodeAudience: string;\n readonly attestationBindingDigestHex: string;\n readonly issuedAt: string;\n readonly expiresAt: string;\n readonly signature: {\n readonly suite: \"Ed25519\";\n readonly signerDid: string;\n readonly value: string;\n };\n}\n\nexport interface RegisterPolicyV3Receipt {\n readonly policyCid: string;\n readonly policyRootCid: string;\n readonly enforcementRootCid: string;\n readonly attestedEnforcerBinding: AttestedEnforcerBindingV2;\n}\n\nexport type PolicySessionUcanFactV1 = Readonly<Record<string, unknown>> & {\n /** Present only on accountless PolicyCredentialPresentation/v4 admissions. */\n readonly credentialIdAuditDigestHex?: string;\n /** Present only on accountless PolicyCredentialPresentation/v4 admissions. */\n readonly presentationJtiAuditDigestHex?: string;\n};\n\nexport interface PolicySessionUcanV1 {\n readonly authorization: string;\n readonly cid: string;\n readonly iss: string;\n readonly aud: string;\n readonly prf: readonly [string, string];\n readonly att: Readonly<Record<string, Readonly<Record<string, readonly unknown[]>>>>;\n readonly nbf: number;\n readonly exp: number;\n readonly nnc: string;\n readonly fact: PolicySessionUcanFactV1;\n}\n\nexport interface PolicyChallengeV3 {\n readonly challengeId: string;\n readonly nonce: string;\n readonly policyCid: string;\n readonly recipientDid: string;\n readonly expiresAt?: string;\n readonly nodeAudience?: string;\n readonly [key: string]: unknown;\n}\n\nexport async function requestPolicyChallengeV3(input: {\n readonly nodeOrigin: string;\n /**\n * Policy control routes are part of the recipient's TinyCloud Node. This is\n * deliberately a path, not a second origin: applications must not send a\n * credential presentation to a separately discovered policy service.\n */\n readonly policyRuntimePath?: string;\n readonly policyCid: string;\n readonly recipientDid: string;\n readonly requestedCapabilities: readonly UnifiedPolicyCapability[];\n readonly fetch?: typeof fetch;\n readonly signal?: AbortSignal;\n}): Promise<PolicyChallengeV3> {\n const fetchFn = input.fetch ?? globalThis.fetch.bind(globalThis);\n const policyRuntimePath = policyRuntimeBasePath(input.policyRuntimePath);\n const response = await fetchFn(new URL(`${policyRuntimePath}/challenges`, input.nodeOrigin), {\n method: \"POST\",\n redirect: \"error\",\n signal: input.signal,\n headers: { accept: \"application/json\", \"content-type\": \"application/json\" },\n body: JSON.stringify({ policyCid: input.policyCid, recipientDid: input.recipientDid, requestedCapabilities: input.requestedCapabilities.map(normalizeUnifiedPolicyCapability) }),\n });\n if (!response.ok) throw await httpResponseError(response, \"policy challenge rejected\");\n const value = object(await response.json(), \"policy challenge\") as PolicyChallengeV3;\n if (typeof value.challengeId !== \"string\" || typeof value.nonce !== \"string\" || value.policyCid !== input.policyCid || value.recipientDid !== input.recipientDid)\n throw new Error(\"policy challenge binding is invalid\");\n return value;\n}\n\nfunction policyRuntimeBasePath(value: string | undefined): string {\n const path = value ?? \"/policy/v3\";\n if (!/^\\/policy(?:\\/[a-z0-9-]+)*$/.test(path)) {\n throw new Error(\"policy runtime path is invalid\");\n }\n return path;\n}\n\nexport async function mintPolicySessionV3(input: {\n readonly nodeOrigin: string;\n readonly policyCid: string;\n readonly policyRootCid: string;\n readonly enforcementRootCid: string;\n readonly recipientDid: string;\n readonly requestedCapabilities: readonly UnifiedPolicyCapability[];\n readonly expectedFacts?: Readonly<Record<string, string | number>>;\n readonly claim: Readonly<Record<string, unknown>>;\n readonly presentation: Readonly<Record<string, unknown>>;\n readonly challenge?: PolicyChallengeV3;\n readonly fetch?: typeof fetch;\n readonly signal?: AbortSignal;\n}): Promise<PolicySessionUcanV1> {\n const fetchFn = input.fetch ?? globalThis.fetch.bind(globalThis);\n const challenge = input.challenge ?? await requestPolicyChallengeV3(input);\n if (challenge.policyCid !== input.policyCid || challenge.recipientDid !== input.recipientDid)\n throw new Error(\"policy challenge binding is invalid\");\n const response = await fetchFn(new URL(\"/policy/v3/delegations\", input.nodeOrigin), {\n method: \"POST\",\n redirect: \"error\",\n signal: input.signal,\n headers: { accept: \"application/json\", \"content-type\": \"application/json\" },\n body: JSON.stringify({ policyCid: input.policyCid, challengeId: challenge.challengeId, nonce: challenge.nonce, claim: input.claim, presentation: input.presentation }),\n });\n if (!response.ok) throw await httpResponseError(response, \"policy delegation rejected\");\n const value = object(await response.json(), \"policy delegation\");\n if (value.admitted !== true || typeof value.sessionCid !== \"string\" || typeof value.authorization !== \"string\")\n throw new Error(\"policy delegation response is invalid\");\n const session = parsePolicySessionUcan(value.authorization, [input.policyRootCid, input.enforcementRootCid]);\n const expectedAttenuation = compactAttenuationForPolicyCapabilities(input.requestedCapabilities);\n if (session.cid !== value.sessionCid\n || session.aud !== input.recipientDid\n || session.fact.policyCid !== input.policyCid\n || session.fact.recipientDid !== input.recipientDid\n || session.fact.policyDelegationCid !== input.policyRootCid\n || session.fact.enforcementDelegationCid !== input.enforcementRootCid\n || jcsCanonicalize(session.att) !== jcsCanonicalize(expectedAttenuation)\n || Object.entries(input.expectedFacts ?? {}).some(([key, expected]) => session.fact[key] !== expected))\n throw new Error(\"policy delegation signed binding is invalid\");\n return session;\n}\n\nexport function compactAttenuationForPolicyCapabilities(\n input: readonly UnifiedPolicyCapability[],\n): Readonly<Record<string, Readonly<Record<string, readonly unknown[]>>>> {\n const attenuation: Record<string, Record<string, readonly unknown[]>> = {};\n for (const raw of input) {\n const capability = normalizeUnifiedPolicyCapability(raw);\n if (attenuation[capability.resource] !== undefined)\n throw new Error(\"policy capabilities contain a duplicate resource\");\n attenuation[capability.resource] = capability.kind === \"encryption\"\n ? { [capability.action]: [{}] }\n : Object.fromEntries(capability.actions.map((action) => [action, [{\n type: \"xyz.tinycloud.resource/selector\",\n kind: capability.selector,\n value: capability.resource,\n }]]));\n }\n return attenuation;\n}\n\nexport interface PolicyRootStatusV3 {\n readonly rootCid: string;\n readonly state: \"active\" | \"revoked\";\n readonly checkpoint: Readonly<Record<string, unknown>>;\n readonly revocation?: Readonly<Record<string, unknown>>;\n}\n\nexport function verifyPolicyRootStatusCheckpointV3(input: {\n readonly rootCid: string;\n readonly checkpoint: Readonly<Record<string, unknown>>;\n readonly expectedNodeAudience?: string;\n readonly now?: Date;\n}): boolean {\n const checkpoint = input.checkpoint;\n const allowed = new Set([\"schema\", \"targetCid\", \"targetRole\", \"ownerDid\", \"nodeAudience\", \"state\", \"sequence\", \"checkedAt\", \"freshUntil\", \"revokedAt\", \"revocationCid\", \"previousCheckpointDigestHex\", \"issuerDid\", \"signature\"]);\n if (Object.keys(checkpoint).some((key) => !allowed.has(key))\n || checkpoint.schema !== ROOT_STATUS_CHECKPOINT_V1_SCHEMA\n || checkpoint.targetCid !== input.rootCid\n || (checkpoint.targetRole !== \"policy-authority\" && checkpoint.targetRole !== \"policy-enforcement\")\n || (checkpoint.state !== \"active\" && checkpoint.state !== \"revoked\")\n || typeof checkpoint.ownerDid !== \"string\"\n || typeof checkpoint.nodeAudience !== \"string\"\n || checkpoint.issuerDid !== checkpoint.nodeAudience\n || (input.expectedNodeAudience !== undefined && checkpoint.nodeAudience !== input.expectedNodeAudience)\n || !Number.isInteger(checkpoint.sequence)\n || (checkpoint.sequence as number) < 1\n || typeof checkpoint.checkedAt !== \"string\"\n || typeof checkpoint.freshUntil !== \"string\") return false;\n const checkedAt = Date.parse(checkpoint.checkedAt as string);\n const freshUntil = Date.parse(checkpoint.freshUntil as string);\n const now = (input.now ?? new Date()).getTime();\n if (!Number.isFinite(checkedAt) || !Number.isFinite(freshUntil)\n || freshUntil < now || freshUntil <= checkedAt || freshUntil - checkedAt > 300_000) return false;\n if ((checkpoint.sequence === 1) !== (checkpoint.previousCheckpointDigestHex === undefined)) return false;\n if (checkpoint.sequence !== 1 && (typeof checkpoint.previousCheckpointDigestHex !== \"string\" || !/^[0-9a-f]{64}$/.test(checkpoint.previousCheckpointDigestHex))) return false;\n if (checkpoint.state === \"active\" && (checkpoint.revokedAt !== undefined || checkpoint.revocationCid !== undefined)) return false;\n if (checkpoint.state === \"revoked\" && (typeof checkpoint.revokedAt !== \"string\" || typeof checkpoint.revocationCid !== \"string\")) return false;\n const signature = checkpoint.signature;\n if (!isRecordValue(signature) || Object.keys(signature).length !== 3 || signature.suite !== \"Ed25519\" || signature.signerDid !== checkpoint.issuerDid || typeof signature.value !== \"string\") return false;\n try {\n const principal = (checkpoint.issuerDid as string).split(\"#\", 1)[0]!;\n const didMaterial = principal.startsWith(\"did:key:\") ? base58btc.decode(principal.slice(\"did:key:\".length)) : new Uint8Array();\n if (didMaterial.length !== 34 || didMaterial[0] !== 0xed || didMaterial[1] !== 0x01) return false;\n const unsigned = { ...checkpoint } as Record<string, unknown>;\n delete unsigned.signature;\n return ed25519.verify(\n decodeBase64Url(signature.value),\n sha256(new TextEncoder().encode(ROOT_STATUS_V1_DOMAIN + jcsCanonicalize(unsigned))),\n didMaterial.slice(2),\n );\n } catch {\n return false;\n }\n}\n\nexport async function getPolicyRootStatusV3(input: {\n readonly nodeOrigin: string;\n readonly rootCid: string;\n readonly expectedNodeAudience?: string;\n readonly expectedEnforcerDid?: string;\n readonly now?: Date;\n readonly fetch?: typeof fetch;\n}): Promise<PolicyRootStatusV3> {\n const fetchFn = input.fetch ?? globalThis.fetch.bind(globalThis);\n const response = await fetchFn(new URL(`/policy/v3/status/${encodeURIComponent(input.rootCid)}`, input.nodeOrigin), {\n method: \"GET\",\n redirect: \"error\",\n headers: { accept: \"application/json\" },\n });\n if (!response.ok) throw await httpResponseError(response, \"policy root status rejected\");\n const value = object(await response.json(), \"policy root status\");\n const checkpoint = object(value.checkpoint, \"policy root checkpoint\");\n if (value.rootCid !== input.rootCid\n || (value.state !== \"active\" && value.state !== \"revoked\")\n || value.state !== checkpoint.state\n || !verifyPolicyRootStatusCheckpointV3({ rootCid: input.rootCid, checkpoint, expectedNodeAudience: input.expectedNodeAudience, now: input.now }))\n throw new Error(\"policy root status binding is invalid\");\n const revocation = value.revocation === undefined ? undefined : object(value.revocation, \"policy root revocation\");\n if ((value.state === \"revoked\") !== (revocation !== undefined)\n || revocation !== undefined && !verifyPolicyRootRevocationV3({\n rootCid: input.rootCid,\n checkpoint,\n revocation,\n expectedEnforcerDid: input.expectedEnforcerDid,\n })) throw new Error(\"policy root status revocation evidence is invalid\");\n return { rootCid: input.rootCid, state: value.state, checkpoint, ...(revocation === undefined ? {} : { revocation }) };\n}\n\nexport function verifyPolicyRootRevocationV3(input: {\n readonly rootCid: string;\n readonly checkpoint: Readonly<Record<string, unknown>>;\n readonly revocation: Readonly<Record<string, unknown>>;\n readonly expectedEnforcerDid?: string;\n}): boolean {\n const value = input.revocation;\n const allowed = [\"schema\", \"targetCid\", \"targetRole\", \"ownerDid\", \"nodeAudience\", \"revokedAt\", \"reason\", \"issuerDid\", \"signature\"];\n if (Object.keys(value).length !== allowed.length || Object.keys(value).some((key) => !allowed.includes(key))\n || value.schema !== ROOT_REVOCATION_V1_SCHEMA\n || value.targetCid !== input.rootCid\n || value.targetRole !== input.checkpoint.targetRole\n || value.ownerDid !== input.checkpoint.ownerDid\n || value.nodeAudience !== input.checkpoint.nodeAudience\n || value.revokedAt !== input.checkpoint.revokedAt\n || typeof value.reason !== \"string\" || value.reason.length === 0\n || typeof value.issuerDid !== \"string\") return false;\n const authorized = value.issuerDid === value.ownerDid\n || value.targetRole === \"policy-enforcement\" && value.issuerDid === input.expectedEnforcerDid;\n if (!authorized) return false;\n const signature = value.signature;\n if (!isRecordValue(signature) || Object.keys(signature).length !== 3 || signature.suite !== \"Ed25519\" || signature.signerDid !== value.issuerDid || typeof signature.value !== \"string\") return false;\n try {\n const principal = (value.issuerDid as string).split(\"#\", 1)[0]!;\n const didMaterial = principal.startsWith(\"did:key:\") ? base58btc.decode(principal.slice(\"did:key:\".length)) : new Uint8Array();\n if (didMaterial.length !== 34 || didMaterial[0] !== 0xed || didMaterial[1] !== 0x01) return false;\n const unsigned = { ...value } as Record<string, unknown>;\n delete unsigned.signature;\n const digest = sha256(new TextEncoder().encode(ROOT_REVOCATION_V1_DOMAIN + jcsCanonicalize(unsigned)));\n return input.checkpoint.revocationCid === hex(digest)\n && ed25519.verify(decodeBase64Url(signature.value), digest, didMaterial.slice(2));\n } catch {\n return false;\n }\n}\n\nexport async function renewPolicyRootStatusV3(input: {\n readonly nodeOrigin: string;\n readonly rootCid: string;\n readonly ownerDid: string;\n readonly nodeAudience: string;\n readonly sign: (digest: Uint8Array) => Promise<Uint8Array>;\n readonly now?: Date;\n readonly nonce?: string;\n readonly fetch?: typeof fetch;\n}): Promise<Readonly<Record<string, unknown>>> {\n const fetchFn = input.fetch ?? globalThis.fetch.bind(globalThis);\n const current = await getPolicyRootStatusV3({ nodeOrigin: input.nodeOrigin, rootCid: input.rootCid, expectedNodeAudience: input.nodeAudience, now: input.now, fetch: fetchFn });\n if (current.state !== \"active\" || current.checkpoint.ownerDid !== input.ownerDid || current.checkpoint.nodeAudience !== input.nodeAudience || current.checkpoint.state !== \"active\" || !Number.isInteger(current.checkpoint.sequence))\n throw new Error(\"policy root status cannot be renewed\");\n const currentUnsigned = { ...current.checkpoint };\n delete currentUnsigned.signature;\n const previousCheckpointDigestHex = hex(sha256(new TextEncoder().encode(ROOT_STATUS_V1_DOMAIN + jcsCanonicalize(currentUnsigned))));\n const unsigned = {\n schema: \"xyz.tinycloud.policy/root-status-renewal/v1\",\n targetCid: input.rootCid,\n ownerDid: input.ownerDid,\n nodeAudience: input.nodeAudience,\n issuedAt: (input.now ?? new Date()).toISOString(),\n nonce: input.nonce ?? encodeBase64Url(crypto.getRandomValues(new Uint8Array(16))),\n sequence: (current.checkpoint.sequence as number) + 1,\n previousCheckpointDigestHex,\n };\n const signature = await input.sign(sha256(new TextEncoder().encode(ROOT_STATUS_RENEWAL_V1_DOMAIN + jcsCanonicalize(unsigned))));\n if (signature.length !== 64) throw new Error(\"policy root renewal signature must be Ed25519\");\n const response = await fetchFn(new URL(\"/policy/v3/status\", input.nodeOrigin), {\n method: \"POST\",\n redirect: \"error\",\n headers: { accept: \"application/json\", \"content-type\": \"application/json\" },\n body: JSON.stringify({ rootCid: input.rootCid, renewal: { ...unsigned, signature: { suite: \"Ed25519\", signerDid: input.ownerDid, value: encodeBase64Url(signature) } } }),\n });\n if (!response.ok) throw await httpResponseError(response, \"policy root renewal rejected\");\n return object(await response.json(), \"policy root renewal\");\n}\n\n/**\n * RFC 3339 in whole seconds. The Node refuses a revocation time it can't\n * reproduce exactly, and its formatter drops trailing zeros from the\n * fraction, so a millisecond `toISOString()` such as `.120Z` came back as\n * `.12Z` and was refused about one time in ten (TC-601).\n */\nfunction rfc3339Seconds(value: Date): string {\n return new Date(Math.floor(value.getTime() / 1000) * 1000).toISOString().replace(/\\.000Z$/, \"Z\");\n}\n\nexport async function revokePolicyRootV3(input: {\n readonly nodeOrigin: string;\n readonly rootCid: string;\n readonly targetRole: \"policy-authority\" | \"policy-enforcement\";\n readonly ownerDid: string;\n readonly issuerDid: string;\n readonly nodeAudience: string;\n readonly reason: string;\n readonly sign: (digest: Uint8Array) => Promise<Uint8Array>;\n readonly now?: Date;\n readonly fetch?: typeof fetch;\n}): Promise<Readonly<Record<string, unknown>>> {\n if (input.reason.length === 0) throw new Error(\"policy root revocation reason is required\");\n const unsigned = {\n schema: ROOT_REVOCATION_V1_SCHEMA,\n targetCid: input.rootCid,\n targetRole: input.targetRole,\n ownerDid: input.ownerDid,\n nodeAudience: input.nodeAudience,\n revokedAt: rfc3339Seconds(input.now ?? new Date()),\n reason: input.reason,\n issuerDid: input.issuerDid,\n };\n const signature = await input.sign(sha256(new TextEncoder().encode(ROOT_REVOCATION_V1_DOMAIN + jcsCanonicalize(unsigned))));\n if (signature.length !== 64) throw new Error(\"policy root revocation signature must be Ed25519\");\n const fetchFn = input.fetch ?? globalThis.fetch.bind(globalThis);\n const response = await fetchFn(new URL(\"/revoke\", input.nodeOrigin), {\n method: \"POST\",\n redirect: \"error\",\n headers: { accept: \"application/json\", \"content-type\": \"application/json\" },\n body: JSON.stringify({ revocation: { ...unsigned, signature: { suite: \"Ed25519\", signerDid: input.issuerDid, value: encodeBase64Url(signature) } } }),\n });\n if (!response.ok) throw await httpResponseError(response, \"policy root revocation rejected\");\n return object(await response.json(), \"policy root revocation\");\n}\n\nconst POLICY_SESSION_FACT_KEYS = [\n \"profile\",\n \"ownerDid\",\n \"policyId\",\n \"policyDigestHex\",\n \"policyCid\",\n \"policyDelegationCid\",\n \"enforcementDelegationCid\",\n \"contentSourceDigestHex\",\n \"capabilityCeilingHashHex\",\n \"nativeProjectionHashHex\",\n \"enforcerDid\",\n \"nodeAudience\",\n \"recipientDid\",\n \"challengeId\",\n \"claimDigestHex\",\n \"claimJti\",\n \"vpDigestHex\",\n \"credentialEvidenceDigestHex\",\n \"decisionContextDigestHex\",\n \"issuanceAuditDigestHex\",\n \"remainingRedelegationDepth\",\n] as const;\n\nconst POLICY_SESSION_V4_AUDIT_FACT_KEYS = [\n \"credentialIdAuditDigestHex\",\n \"presentationJtiAuditDigestHex\",\n] as const;\n\nconst LOWER_SHA256_HEX = /^[0-9a-f]{64}$/;\n\nconst KV_ACTIONS = new Set<string>([\n \"tinycloud.kv/get\",\n \"tinycloud.kv/list\",\n \"tinycloud.kv/metadata\",\n \"tinycloud.kv/put\",\n]);\n\nfunction object(value: unknown, label: string): Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`${label} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction exactKeys(\n value: Record<string, unknown>,\n allowed: readonly string[],\n label: string,\n): void {\n const keys = new Set(allowed);\n if (Object.keys(value).some((key) => !keys.has(key)))\n throw new Error(`${label} contains an unknown field`);\n}\n\nfunction nonEmptyString(value: unknown, label: string): string {\n if (typeof value !== \"string\" || value.length === 0)\n throw new Error(`${label} must be a non-empty string`);\n return value;\n}\n\nfunction parseKvResource(resource: string): { space: string; path: string } {\n const marker = resource.indexOf(\"/kv/\");\n const encodedSpace = marker < 1 ? \"\" : resource.slice(0, marker);\n const legacy = encodedSpace.startsWith(\"tinycloud://\");\n const space = legacy ? encodedSpace.slice(\"tinycloud://\".length) : encodedSpace;\n const path = marker < 1 ? \"\" : resource.slice(marker + 4);\n if (\n marker < 1 ||\n (legacy\n ? /[:/?#%]/.test(space)\n : !encodedSpace.startsWith(\"tinycloud:\") || /[/?#%]/.test(encodedSpace)) ||\n path.startsWith(\"/\") ||\n path.endsWith(\"/\") ||\n path.includes(\"//\") ||\n path\n .split(\"/\")\n .some((part) => part === \".\" || part === \"..\" || part.length === 0)\n ) {\n throw new Error(\"KV resource is not canonical\");\n }\n return { space, path };\n}\n\nfunction parseEncryptionResource(resource: string): void {\n if (!resource.startsWith(\"urn:tinycloud:encryption:\")) throw new Error(\"encryption capability is invalid\");\n const rest = resource.slice(\"urn:tinycloud:encryption:\".length);\n const separator = rest.lastIndexOf(\":\");\n const ownerDid = separator < 0 ? \"\" : rest.slice(0, separator);\n const network = separator < 0 ? \"\" : rest.slice(separator + 1);\n if (!ownerDid.startsWith(\"did:\") || network.length === 0 || network.includes(\":\") || network.includes(\"/\") || network.includes(\"%\") || network.includes(\"?\") || network.includes(\"#\")) {\n throw new Error(\"encryption capability is invalid\");\n }\n}\n\nexport function normalizeUnifiedPolicyCapability(\n input: unknown,\n): UnifiedPolicyCapability {\n const value = object(input, \"capability\");\n const kind = nonEmptyString(value.kind, \"capability.kind\");\n if (kind === \"kv\") {\n exactKeys(\n value,\n [\"kind\", \"resource\", \"selector\", \"actions\"],\n \"KV capability\",\n );\n const resource = nonEmptyString(value.resource, \"capability.resource\");\n parseKvResource(resource);\n if (value.selector !== \"exact\" && value.selector !== \"prefix\")\n throw new Error(\"capability.selector is invalid\");\n if (!Array.isArray(value.actions) || value.actions.length === 0)\n throw new Error(\"capability.actions is invalid\");\n const actions = value.actions.map((action) =>\n nonEmptyString(action, \"capability.actions[]\"),\n );\n if (\n new Set(actions).size !== actions.length ||\n actions.some((action) => !KV_ACTIONS.has(action))\n )\n throw new Error(\"capability.actions is invalid\");\n return {\n kind: \"kv\",\n resource,\n selector: value.selector,\n actions: [...actions].sort() as UnifiedKvCapability[\"actions\"],\n };\n }\n if (kind === \"encryption\") {\n exactKeys(value, [\"kind\", \"resource\", \"action\"], \"encryption capability\");\n const resource = nonEmptyString(value.resource, \"capability.resource\");\n if (value.action !== \"tinycloud.encryption/decrypt\")\n throw new Error(\"encryption capability is invalid\");\n parseEncryptionResource(resource);\n return {\n kind: \"encryption\",\n resource,\n action: \"tinycloud.encryption/decrypt\",\n };\n }\n throw new Error(\"capability.kind is invalid\");\n}\n\nexport function canonicalizeUnifiedPolicyCapability(\n input: unknown,\n): UnifiedPolicyCapability {\n return normalizeUnifiedPolicyCapability(input);\n}\n\nexport function unifiedPolicyCapabilityDigestHex(input: unknown): string {\n return hex(\n sha256(\n new TextEncoder().encode(\n POLICY_CAPABILITY_V1_DOMAIN +\n jcsCanonicalize(normalizeUnifiedPolicyCapability(input)),\n ),\n ),\n );\n}\n\nexport function unifiedPolicyCapabilityContains(\n authorityInput: unknown,\n requestedInput: unknown,\n): boolean {\n try {\n const authority = normalizeUnifiedPolicyCapability(authorityInput);\n const requested = normalizeUnifiedPolicyCapability(requestedInput);\n if (authority.kind !== requested.kind) return false;\n if (authority.kind === \"encryption\" && requested.kind === \"encryption\")\n return (\n authority.resource === requested.resource &&\n authority.action === requested.action\n );\n if (authority.kind !== \"kv\" || requested.kind !== \"kv\") return false;\n const { resource: authorized } = authority;\n const { resource: requestedResource } = requested;\n const pathContained =\n authority.selector === \"exact\"\n ? authorized === requestedResource\n : authorized === requestedResource ||\n requestedResource.startsWith(`${authorized}/`);\n if (\n !pathContained ||\n (authority.selector === \"exact\" && requested.selector === \"prefix\")\n )\n return false;\n return requested.actions.every((action) =>\n authority.actions.includes(action),\n );\n } catch {\n return false;\n }\n}\n\nexport function projectUnifiedPolicyCapability(\n input: unknown,\n): UnifiedNativeCapability {\n const capability = normalizeUnifiedPolicyCapability(input);\n if (capability.kind === \"encryption\") {\n return {\n service: \"tinycloud.encryption\",\n space: capability.resource,\n path: capability.resource,\n actions: [capability.action],\n };\n }\n const { space, path } = parseKvResource(capability.resource);\n return {\n service: \"tinycloud.kv\",\n space,\n path,\n actions: [...capability.actions],\n caveat: {\n type: \"xyz.tinycloud.resource/selector\",\n kind: capability.selector,\n value: capability.resource,\n },\n };\n}\n\nexport function projectUnifiedPolicyCapabilities(\n input: readonly unknown[],\n): UnifiedNativeCapability[] {\n return input\n .map(projectUnifiedPolicyCapability)\n .sort((left, right) => {\n const a = jcsCanonicalize(left);\n const b = jcsCanonicalize(right);\n return a < b ? -1 : a > b ? 1 : 0;\n });\n}\n\nexport function unifiedNativeProjectionHashHex(\n input: readonly unknown[],\n): string {\n return hex(\n sha256(\n new TextEncoder().encode(\n NATIVE_PROJECTION_V1_DOMAIN +\n jcsCanonicalize(projectUnifiedPolicyCapabilities(input)),\n ),\n ),\n );\n}\n\nexport function unifiedPolicyCapabilityFromNative(\n input: unknown,\n): UnifiedPolicyCapability {\n const value = object(input, \"native capability\");\n exactKeys(\n value,\n [\"service\", \"space\", \"path\", \"actions\", \"caveat\"],\n \"native capability\",\n );\n const service = nonEmptyString(value.service, \"native.service\");\n const actions = value.actions;\n if (!Array.isArray(actions)) throw new Error(\"native.actions is invalid\");\n if (\n service === \"tinycloud.encryption\" &&\n value.caveat === undefined &&\n value.space === value.path &&\n actions.length === 1 &&\n actions[0] === \"tinycloud.encryption/decrypt\"\n ) {\n return normalizeUnifiedPolicyCapability({\n kind: \"encryption\",\n resource: value.space,\n action: actions[0],\n });\n }\n if (\n service !== \"tinycloud.kv\" ||\n typeof value.space !== \"string\" ||\n typeof value.path !== \"string\"\n )\n throw new Error(\"native capability is not supported\");\n const caveat = object(value.caveat, \"native.caveat\");\n exactKeys(caveat, [\"type\", \"kind\", \"value\"], \"native selector caveat\");\n if (\n caveat.type !== \"xyz.tinycloud.resource/selector\" ||\n (caveat.kind !== \"exact\" && caveat.kind !== \"prefix\") ||\n caveat.value !== `${value.space.startsWith(\"tinycloud:\") ? value.space : `tinycloud://${value.space}`}/kv/${value.path}`\n )\n throw new Error(\"native selector caveat does not match capability\");\n return normalizeUnifiedPolicyCapability({\n kind: \"kv\",\n resource: caveat.value,\n selector: caveat.kind,\n actions,\n });\n}\n\nexport function contentSourceDigestHex(input: UnifiedContentSource): string {\n return hex(\n sha256(\n new TextEncoder().encode(\n CONTENT_SOURCE_V1_DOMAIN + jcsCanonicalize(input),\n ),\n ),\n );\n}\n\nfunction exactObject(\n value: unknown,\n keys: readonly string[],\n label: string,\n): Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`${label} is invalid`);\n }\n const record = value as Record<string, unknown>;\n if (\n Object.keys(record).length !== keys.length ||\n keys.some((key) => !Object.prototype.hasOwnProperty.call(record, key))\n ) {\n throw new Error(`${label} is invalid`);\n }\n return record;\n}\n\nfunction didKeyEd25519PublicKey(value: string): Uint8Array {\n const principal = value.split(\"#\", 1)[0]!;\n if (!principal.startsWith(\"did:key:\")) {\n throw new Error(\"policy enforcer binding signer is invalid\");\n }\n const material = base58btc.decode(principal.slice(\"did:key:\".length));\n if (material.length !== 34 || material[0] !== 0xed || material[1] !== 0x01) {\n throw new Error(\"policy enforcer binding signer is invalid\");\n }\n return material.slice(2);\n}\n\n/**\n * Register a signed policy and its sibling roots with the embedded Node\n * Policy/v3 runtime. This is intentionally application-neutral: callers\n * supply policy material, while Node owns both transport endpoints.\n */\nexport async function registerPolicyV3(\n input: RegisterPolicyV3Input,\n): Promise<RegisterPolicyV3Receipt> {\n const fetchFn = input.fetch ?? globalThis.fetch.bind(globalThis);\n const rootExpiresAt = new Date(input.rootExpiresAt);\n const canonicalRootExpiresAt = new Date(\n Math.floor(rootExpiresAt.getTime() / 1000) * 1000,\n )\n .toISOString()\n .replace(/\\.000Z$/, \"Z\");\n if (\n !Number.isFinite(rootExpiresAt.getTime()) ||\n canonicalRootExpiresAt !== input.rootExpiresAt ||\n rootExpiresAt.getTime() <= Date.now()\n ) {\n throw new Error(\"policy root expiry is invalid\");\n }\n const bindingResponse = await fetchFn(\n new URL(\"/policy/v3/enforcer-bindings\", input.nodeOrigin),\n {\n method: \"POST\",\n redirect: \"error\",\n signal: input.signal,\n headers: { accept: \"application/json\", \"content-type\": \"application/json\" },\n body: JSON.stringify({\n rootExpiresAt: input.rootExpiresAt,\n enforcerDid: input.enforcerDid,\n }),\n },\n );\n if (!bindingResponse.ok) {\n throw await httpResponseError(bindingResponse, \"policy enforcer binding rejected\");\n }\n const binding = exactObject(\n await bindingResponse.json(),\n [\n \"schema\",\n \"enforcerDid\",\n \"nodeAudience\",\n \"attestationBindingDigestHex\",\n \"issuedAt\",\n \"expiresAt\",\n \"signature\",\n ],\n \"policy enforcer binding\",\n );\n const signature = exactObject(\n binding.signature,\n [\"suite\", \"signerDid\", \"value\"],\n \"policy enforcer binding signature\",\n );\n const expectedBindingDigestHex = hex(\n sha256(\n new TextEncoder().encode(\n jcsCanonicalize({\n enforcerDid: input.enforcerDid,\n nodeAudience: input.expectedNodeAudience,\n }),\n ),\n ),\n );\n if (\n binding.schema !== ATTESTED_ENFORCER_BINDING_V2_SCHEMA ||\n binding.enforcerDid !== input.enforcerDid ||\n binding.nodeAudience !== input.expectedNodeAudience ||\n binding.attestationBindingDigestHex !== expectedBindingDigestHex ||\n binding.expiresAt !== input.rootExpiresAt ||\n typeof binding.issuedAt !== \"string\" ||\n Date.parse(binding.issuedAt) > Date.now() ||\n signature.suite !== \"Ed25519\" ||\n signature.signerDid !== input.expectedNodeAudience ||\n typeof signature.value !== \"string\"\n ) {\n throw new Error(\"policy enforcer binding is invalid\");\n }\n const { signature: _signature, ...unsignedBinding } = binding;\n const signedBinding = sha256(\n new TextEncoder().encode(\n `xyz.tinycloud.policy/AttestedEnforcerBinding/v2\\0${jcsCanonicalize(unsignedBinding)}`,\n ),\n );\n if (\n !ed25519.verify(\n decodeBase64Url(signature.value),\n signedBinding,\n didKeyEd25519PublicKey(input.expectedNodeAudience),\n { zip215: false },\n )\n ) {\n throw new Error(\"policy enforcer binding signature is invalid\");\n }\n\n const response = await fetchFn(\n new URL(\"/policy/v3/policies\", input.nodeOrigin),\n {\n method: \"POST\",\n redirect: \"error\",\n signal: input.signal,\n headers: { accept: \"application/json\", \"content-type\": \"application/json\" },\n body: JSON.stringify({\n policyCid: input.policyCid,\n policy: input.policy,\n policyRoot: input.policyRoot.authorization.replace(/^Bearer\\s+/i, \"\"),\n enforcementRoot: input.enforcementRoot.authorization.replace(/^Bearer\\s+/i, \"\"),\n contentSourceDigestHex: input.contentSourceDigestHex,\n nativeProjectionHashHex: input.nativeProjectionHashHex,\n attestedEnforcerBinding: binding,\n }),\n },\n );\n if (!response.ok) {\n throw await httpResponseError(response, \"policy registration rejected\");\n }\n const receipt = exactObject(\n await response.json(),\n [\"policyCid\", \"policyRootCid\", \"enforcementRootCid\"],\n \"policy registration response\",\n );\n if (\n receipt.policyCid !== input.policyCid ||\n receipt.policyRootCid !== input.policyRoot.cid ||\n receipt.enforcementRootCid !== input.enforcementRoot.cid\n ) {\n throw new Error(\"policy registration response binding is invalid\");\n }\n return {\n policyCid: input.policyCid,\n policyRootCid: input.policyRoot.cid,\n enforcementRootCid: input.enforcementRoot.cid,\n attestedEnforcerBinding: binding as unknown as AttestedEnforcerBindingV2,\n };\n}\n\nexport function policyDigestHex(\n policy: Omit<UnifiedPolicyV1, \"policyId\" | \"signature\">,\n): string {\n const canonicalPolicy = {\n ...policy,\n capabilityCeiling: policy.capabilityCeiling.map(\n normalizeUnifiedPolicyCapability,\n ),\n };\n return hex(\n sha256(\n new TextEncoder().encode(\n POLICY_V1_DOMAIN + jcsCanonicalize(canonicalPolicy),\n ),\n ),\n );\n}\n\nexport function policyIdForDigestHex(digestHex: string): string {\n const digest = Uint8Array.from(\n (digestHex.match(/.{2}/g) ?? []).map((byte) => Number.parseInt(byte, 16)),\n );\n if (digest.length !== 32) throw new Error(\"policy digest must be 32 bytes\");\n return `pol_${base32Lower(digest)}`;\n}\n\nexport function policyCidFromCanonicalBytes(bytes: Uint8Array): string {\n return CID.createV1(0x55, createDigest(0x12, sha256(bytes))).toString();\n}\n\nconst CompactHeaderSchema = z.object({\n alg: z.literal(\"EdDSA\"),\n jwk: z.object({ alg: z.literal(\"EdDSA\"), crv: z.literal(\"Ed25519\"), kty: z.literal(\"OKP\"), x: z.string().min(1) }).strict(),\n typ: z.literal(\"JWT\"),\n ucv: z.literal(\"0.10.0\"),\n}).strict();\nconst CompactPayloadSchema = z.object({\n att: z.record(z.record(z.array(z.unknown()).min(1))),\n aud: z.string().min(1),\n exp: z.number().int(),\n fct: z.array(z.record(z.unknown())).length(1),\n iss: z.string().min(1),\n nbf: z.number().int(),\n nnc: z.string().min(1),\n prf: z.array(z.string().min(1)),\n}).strict();\n\nexport interface CompactUcanAuthorizationV1 {\n readonly authorization: string;\n readonly cid: string;\n readonly header: z.infer<typeof CompactHeaderSchema>;\n readonly payload: z.infer<typeof CompactPayloadSchema>;\n}\n\nexport interface SignCompactUcanAuthorizationInput {\n readonly issuerDid: string;\n readonly audienceDid: string;\n readonly attenuation: Readonly<Record<string, Readonly<Record<string, readonly unknown[]>>>>;\n readonly facts: readonly [Readonly<Record<string, unknown>>];\n readonly proofs: readonly string[];\n readonly notBefore: number;\n readonly expiresAt: number;\n readonly nonce: string;\n readonly sign: (bytes: Uint8Array) => Promise<Uint8Array>;\n}\n\nexport interface SignCompactUcanRootAuthorizationInput {\n readonly issuerDid: string;\n readonly audienceDid: string;\n readonly attenuation: Readonly<Record<string, Readonly<Record<string, readonly unknown[]>>>>;\n readonly facts: readonly [Readonly<Record<string, unknown>>];\n readonly notBefore: number;\n readonly expiresAt: number;\n readonly nonce: string;\n readonly sign: (bytes: Uint8Array) => Promise<Uint8Array>;\n}\n\nasync function signCompactUcan(\n input: SignCompactUcanAuthorizationInput,\n): Promise<CompactUcanAuthorizationV1> {\n const principal = input.issuerDid.split(\"#\", 1)[0]!;\n const didMaterial = principal.startsWith(\"did:key:\")\n ? base58btc.decode(principal.slice(\"did:key:\".length))\n : new Uint8Array();\n if (didMaterial.length !== 34 || didMaterial[0] !== 0xed || didMaterial[1] !== 0x01)\n throw new Error(\"compact UCAN signer must be did:key Ed25519\");\n const header = { alg: \"EdDSA\", jwk: { alg: \"EdDSA\", crv: \"Ed25519\", kty: \"OKP\", x: encodeBase64Url(didMaterial.slice(2)) }, typ: \"JWT\", ucv: \"0.10.0\" };\n const payload = {\n att: input.attenuation,\n aud: input.audienceDid,\n exp: input.expiresAt,\n fct: input.facts,\n iss: input.issuerDid.includes(\"#\") ? input.issuerDid : `${principal}#${principal.slice(\"did:key:\".length)}`,\n nbf: input.notBefore,\n nnc: input.nonce,\n prf: input.proofs,\n };\n const protectedSegment = encodeBase64Url(new TextEncoder().encode(jcsCanonicalize(header)));\n const payloadSegment = encodeBase64Url(new TextEncoder().encode(jcsCanonicalize(payload)));\n const signature = await input.sign(new TextEncoder().encode(`${protectedSegment}.${payloadSegment}`));\n if (signature.length !== 64) throw new Error(\"compact Authorization signature must be Ed25519\");\n return parseCompactUcanAuthorization(`${protectedSegment}.${payloadSegment}.${encodeBase64Url(signature)}`);\n}\n\n/** Sign exact compact-UCAN bytes with a caller-owned, potentially non-extractable key. */\nexport async function signCompactUcanAuthorization(\n input: SignCompactUcanAuthorizationInput,\n): Promise<CompactUcanAuthorizationV1> {\n if (input.notBefore >= input.expiresAt || input.expiresAt - input.notBefore > 60)\n throw new Error(\"compact invocation lifetime must be between one and 60 seconds\");\n return signCompactUcan(input);\n}\n\n/**\n * Longest window a policy root may have. A policy session never outlives its\n * roots, so this also bounds every session and descendant.\n */\nconst MAX_POLICY_ROOT_SECONDS = 31 * 24 * 60 * 60;\n\n/** Sign a proofless policy root without weakening the 60-second invocation profile. */\nexport async function signCompactUcanRootAuthorization(\n input: SignCompactUcanRootAuthorizationInput,\n): Promise<CompactUcanAuthorizationV1> {\n if (input.notBefore >= input.expiresAt || input.expiresAt - input.notBefore > MAX_POLICY_ROOT_SECONDS)\n throw new Error(\"compact policy root lifetime must be between one second and 31 days\");\n return signCompactUcan({ ...input, proofs: [] });\n}\n\nexport interface CompactPolicyInvocationInput {\n readonly sessionAuthorization: string;\n readonly sessionCid: string;\n readonly recipientDid: string;\n readonly audienceDid: string;\n readonly resource: string;\n readonly action: string;\n readonly caveat?: Readonly<Record<string, unknown>>;\n readonly facts?: Readonly<Record<string, unknown>>;\n readonly privateKey: Uint8Array;\n readonly now?: number;\n readonly nonce?: string;\n}\n\n/** Sign a fresh one-parent ordinary invocation; S0 itself is never a bearer. */\nexport function createCompactPolicyInvocation(\n input: CompactPolicyInvocationInput,\n): CompactUcanAuthorizationV1 {\n const session = parsePolicySessionUcan(input.sessionAuthorization);\n if (session.cid !== input.sessionCid || session.aud !== input.recipientDid)\n throw new Error(\"policy session does not bind the recipient signer\");\n const principal = input.recipientDid.split(\"#\", 1)[0]!;\n const didMaterial = base58btc.decode(principal.slice(\"did:key:\".length));\n if (didMaterial.length !== 34 || didMaterial[0] !== 0xed || didMaterial[1] !== 0x01)\n throw new Error(\"policy invocation signer must be did:key Ed25519\");\n const publicKey = ed25519.getPublicKey(input.privateKey);\n if (!equalBytes(publicKey, didMaterial.slice(2)))\n throw new Error(\"policy invocation private key does not bind recipient DID\");\n const now = input.now ?? Math.floor(Date.now() / 1000);\n const exp = Math.min(now + 60, session.exp);\n if (exp <= now) throw new Error(\"policy session has expired\");\n const header = { alg: \"EdDSA\", jwk: { alg: \"EdDSA\", crv: \"Ed25519\", kty: \"OKP\", x: encodeBase64Url(publicKey) }, typ: \"JWT\", ucv: \"0.10.0\" };\n const payload = {\n att: { [input.resource]: { [input.action]: [input.caveat ?? {}] } },\n aud: input.audienceDid,\n exp,\n fct: [input.facts ?? { type: \"tinycloud.policy.invocation/v1\", policyCid: session.fact.policyCid, sessionCid: session.cid }],\n iss: input.recipientDid.includes(\"#\") ? input.recipientDid : `${principal}#${principal.slice(\"did:key:\".length)}`,\n nbf: now,\n nnc: input.nonce ?? encodeBase64Url(crypto.getRandomValues(new Uint8Array(16))),\n prf: [session.cid],\n };\n const protectedSegment = encodeBase64Url(new TextEncoder().encode(jcsCanonicalize(header)));\n const payloadSegment = encodeBase64Url(new TextEncoder().encode(jcsCanonicalize(payload)));\n const signingInput = new TextEncoder().encode(`${protectedSegment}.${payloadSegment}`);\n const signature = ed25519.sign(signingInput, input.privateKey);\n return parseCompactUcanAuthorization(`${protectedSegment}.${payloadSegment}.${encodeBase64Url(signature)}`);\n}\n\nexport interface CompactPolicyDescendantInput {\n readonly parentAuthorization: string;\n readonly parentCid: string;\n readonly issuerDid: string;\n readonly audienceDid: string;\n readonly attenuation: Readonly<Record<string, Readonly<Record<string, readonly unknown[]>>>>;\n /** Start of the window; defaults to one second after the parent's start. */\n readonly now?: number;\n /** Defaults to the longest window the parent allows: one second inside it. */\n readonly expiresAt?: number;\n readonly nonce?: string;\n}\n\n/** The checked claims of a descendant, before anyone signs them. */\nfunction compactPolicyDescendantClaims(input: CompactPolicyDescendantInput) {\n const parent = parseCompactUcanAuthorization(input.parentAuthorization, input.parentCid);\n if (parent.payload.aud !== input.issuerDid) throw new Error(\"policy descendant issuer is not the parent audience\");\n const parentFact = parent.payload.fct[0]!;\n const depth = parentFact.remainingRedelegationDepth;\n if (!Number.isInteger(depth) || (depth as number) <= 0) throw new Error(\"policy descendant depth is exhausted\");\n if (!compactAttenuationContains(parent.payload.att, input.attenuation))\n throw new Error(\"policy descendant exceeds the parent attenuation\");\n // Start just inside the parent's window, so a fresh link is usable at once.\n const now = Math.max(input.now ?? parent.payload.nbf + 1, parent.payload.nbf + 1);\n const exp = Math.min(input.expiresAt ?? parent.payload.exp - 1, parent.payload.exp - 1);\n if (exp <= now) throw new Error(\"policy parent has no strictly narrower validity window\");\n return {\n parentCid: parent.cid,\n fact: { ...parentFact, remainingRedelegationDepth: (depth as number) - 1 },\n notBefore: now,\n expiresAt: exp,\n nonce: input.nonce ?? encodeBase64Url(crypto.getRandomValues(new Uint8Array(16))),\n };\n}\n\nexport function createCompactPolicyDescendant(\n input: CompactPolicyDescendantInput & { readonly privateKey: Uint8Array },\n): CompactUcanAuthorizationV1 {\n const claims = compactPolicyDescendantClaims(input);\n const principal = input.issuerDid.split(\"#\", 1)[0]!;\n const didMaterial = base58btc.decode(principal.slice(\"did:key:\".length));\n const publicKey = ed25519.getPublicKey(input.privateKey);\n if (didMaterial.length !== 34 || !equalBytes(publicKey, didMaterial.slice(2))) throw new Error(\"policy descendant signer does not bind issuer DID\");\n const header = { alg: \"EdDSA\", jwk: { alg: \"EdDSA\", crv: \"Ed25519\", kty: \"OKP\", x: encodeBase64Url(publicKey) }, typ: \"JWT\", ucv: \"0.10.0\" };\n const payload = {\n att: input.attenuation,\n aud: input.audienceDid,\n exp: claims.expiresAt,\n fct: [claims.fact],\n iss: input.issuerDid.includes(\"#\") ? input.issuerDid : `${principal}#${principal.slice(\"did:key:\".length)}`,\n nbf: claims.notBefore,\n nnc: claims.nonce,\n prf: [claims.parentCid],\n };\n const protectedSegment = encodeBase64Url(new TextEncoder().encode(jcsCanonicalize(header)));\n const payloadSegment = encodeBase64Url(new TextEncoder().encode(jcsCanonicalize(payload)));\n const signature = ed25519.sign(new TextEncoder().encode(`${protectedSegment}.${payloadSegment}`), input.privateKey);\n return parseCompactUcanAuthorization(`${protectedSegment}.${payloadSegment}.${encodeBase64Url(signature)}`);\n}\n\n/**\n * The same descendant, signed by a caller-owned key that may be\n * non-extractable. The result is verified against the issuer DID.\n */\nexport async function signCompactPolicyDescendant(\n input: CompactPolicyDescendantInput & { readonly sign: (bytes: Uint8Array) => Promise<Uint8Array> },\n): Promise<CompactUcanAuthorizationV1> {\n const claims = compactPolicyDescendantClaims(input);\n return signCompactUcan({\n issuerDid: input.issuerDid,\n audienceDid: input.audienceDid,\n attenuation: input.attenuation,\n facts: [claims.fact],\n proofs: [claims.parentCid],\n notBefore: claims.notBefore,\n expiresAt: claims.expiresAt,\n nonce: claims.nonce,\n sign: input.sign,\n });\n}\n\n/** Byte-independent semantic containment shared by S0, descendants and mint requests. */\nexport function compactAttenuationContains(\n parent: Readonly<Record<string, Readonly<Record<string, readonly unknown[]>>>>,\n child: Readonly<Record<string, Readonly<Record<string, readonly unknown[]>>>>,\n): boolean {\n const selector = (value: readonly unknown[]): { readonly kind: \"exact\" | \"prefix\"; readonly value: string } | undefined => {\n if (value.length !== 1 || !isRecordValue(value[0])) return undefined;\n const caveat = value[0];\n if (Object.keys(caveat).length !== 3 || caveat.type !== \"xyz.tinycloud.resource/selector\" || (caveat.kind !== \"exact\" && caveat.kind !== \"prefix\") || typeof caveat.value !== \"string\") return undefined;\n return { kind: caveat.kind, value: caveat.value };\n };\n const equal = (left: unknown, right: unknown): boolean => jcsCanonicalize(left) === jcsCanonicalize(right);\n return Object.entries(child).every(([childResource, childActions]) =>\n Object.entries(childActions).every(([action, childCaveats]) =>\n Object.entries(parent).some(([parentResource, parentActions]) => {\n const parentCaveats = parentActions[action];\n if (parentCaveats === undefined) return false;\n if (parentResource === childResource && equal(parentCaveats, childCaveats)) return true;\n const parentSelector = selector(parentCaveats);\n const childSelector = selector(childCaveats);\n return parentSelector?.kind === \"prefix\"\n && childSelector !== undefined\n && parentSelector.value === parentResource\n && childSelector.value === childResource\n && (childResource === parentResource || childResource.startsWith(`${parentResource}/`));\n }),\n ),\n );\n}\n\nfunction isRecordValue(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function parseCompactUcanAuthorization(\n input: string,\n expectedCid?: string,\n): CompactUcanAuthorizationV1 {\n if (typeof input !== \"string\" || /\\s/.test(input))\n throw new Error(\"Authorization must be compact UCAN bytes\");\n const segments = input.split(\".\");\n if (segments.length !== 3 || segments.some((segment) => segment.length === 0))\n throw new Error(\"Authorization must have three compact segments\");\n const [headerSegment, payloadSegment, signatureSegment] = segments as [string, string, string];\n const headerBytes = decodeBase64Url(headerSegment);\n const payloadBytes = decodeBase64Url(payloadSegment);\n const signature = decodeBase64Url(signatureSegment);\n const headerValue: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(headerBytes));\n const payloadValue: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(payloadBytes));\n if (jcsCanonicalize(headerValue) !== new TextDecoder().decode(headerBytes)\n || jcsCanonicalize(payloadValue) !== new TextDecoder().decode(payloadBytes))\n throw new Error(\"compact UCAN segments are not canonical JCS\");\n const header = CompactHeaderSchema.parse(headerValue);\n const payload = CompactPayloadSchema.parse(payloadValue);\n if (payload.nbf >= payload.exp) throw new Error(\"compact UCAN validity is empty\");\n const principal = payload.iss.split(\"#\", 1)[0]!;\n const didMaterial = principal.startsWith(\"did:key:\")\n ? base58btc.decode(principal.slice(\"did:key:\".length))\n : new Uint8Array();\n if (didMaterial.length !== 34 || didMaterial[0] !== 0xed || didMaterial[1] !== 0x01)\n throw new Error(\"compact UCAN issuer must be did:key Ed25519\");\n const publicKey = didMaterial.slice(2);\n if (!equalBytes(publicKey, decodeBase64Url(header.jwk.x)))\n throw new Error(\"compact UCAN JWK does not bind issuer\");\n if (!ed25519.verify(signature, new TextEncoder().encode(`${headerSegment}.${payloadSegment}`), publicKey))\n throw new Error(\"compact UCAN signature is invalid\");\n const cid = CID.createV1(0x55, createDigest(0x1e, blake3(new TextEncoder().encode(input)))).toString();\n if (expectedCid !== undefined && cid !== expectedCid)\n throw new Error(\"compact UCAN CID does not match exact Authorization bytes\");\n return { authorization: input, cid, header, payload };\n}\n\nconst SignedCompactAttenuationSchema = z.record(z.record(z.array(z.unknown()).min(1)));\n/** Verify an issued UCAN's exact bytes while reading its signed attenuation. */\nexport function parseSignedCompactUcanAttenuation(input: string, expectedCid?: string): {\n cid: string;\n payload: { att: z.infer<typeof SignedCompactAttenuationSchema>; aud: string };\n} {\n if (typeof input !== \"string\" || /\\s/.test(input))\n throw new Error(\"Authorization must be compact UCAN bytes\");\n const segments = input.split(\".\");\n if (segments.length !== 3 || segments.some((segment) => segment.length === 0))\n throw new Error(\"Authorization must have three compact segments\");\n const [headerSegment, payloadSegment, signatureSegment] = segments as [string, string, string];\n const headerValue: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(decodeBase64Url(headerSegment)));\n const payloadValue: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(decodeBase64Url(payloadSegment)));\n if (!isRecordValue(headerValue) || !isRecordValue(headerValue.jwk) ||\n headerValue.alg !== \"EdDSA\" || headerValue.typ !== \"JWT\" || headerValue.ucv !== \"0.10.0\" ||\n headerValue.jwk.kty !== \"OKP\" || headerValue.jwk.crv !== \"Ed25519\" ||\n !isRecordValue(payloadValue) || typeof payloadValue.iss !== \"string\")\n throw new Error(\"Authorization has an invalid signed UCAN header or issuer\");\n const att = SignedCompactAttenuationSchema.parse(payloadValue.att);\n const principal = payloadValue.iss.split(\"#\", 1)[0]!;\n const didMaterial = principal.startsWith(\"did:key:\")\n ? base58btc.decode(principal.slice(\"did:key:\".length))\n : new Uint8Array();\n const publicKey = didMaterial.length === 34 && didMaterial[0] === 0xed && didMaterial[1] === 0x01\n ? didMaterial.slice(2)\n : new Uint8Array();\n const jwkKey = typeof headerValue.jwk.x === \"string\" ? decodeBase64Url(headerValue.jwk.x) : new Uint8Array();\n if (publicKey.length !== 32 || !equalBytes(publicKey, jwkKey))\n throw new Error(\"compact UCAN JWK does not bind issuer\");\n const signature = decodeBase64Url(signatureSegment);\n if (!ed25519.verify(signature, new TextEncoder().encode(`${headerSegment}.${payloadSegment}`), publicKey))\n throw new Error(\"compact UCAN signature is invalid\");\n if (typeof payloadValue.aud !== \"string\" || payloadValue.aud.length === 0)\n throw new Error(\"compact UCAN signed audience is missing\");\n const cid = CID.createV1(0x55, createDigest(0x1e, blake3(new TextEncoder().encode(input)))).toString();\n if (expectedCid !== undefined && cid !== expectedCid) throw new Error(\"compact UCAN CID does not match exact Authorization bytes\");\n return { cid, payload: { att, aud: payloadValue.aud } };\n}\n\nexport function parsePolicySessionUcan(\n authorization: string,\n expectedProofs?: readonly [string, string],\n): PolicySessionUcanV1 {\n const parsed = parseCompactUcanAuthorization(authorization);\n const fact = parsed.payload.fct[0]!;\n if (parsed.payload.prf.length !== 2 || parsed.payload.prf[0] === parsed.payload.prf[1])\n throw new Error(\"policy session UCAN requires two distinct ordered proofs\");\n if (expectedProofs !== undefined\n && (parsed.payload.prf[0] !== expectedProofs[0] || parsed.payload.prf[1] !== expectedProofs[1]))\n throw new Error(\"policy session UCAN ordered proofs do not match\");\n const factKeys = Object.keys(fact);\n const hasLegacyFactShape = factKeys.length === POLICY_SESSION_FACT_KEYS.length\n && factKeys.every((key) => POLICY_SESSION_FACT_KEYS.includes(key as never))\n && POLICY_SESSION_FACT_KEYS.every((key) => key in fact);\n const hasV4AuditFactShape = factKeys.length === POLICY_SESSION_FACT_KEYS.length + POLICY_SESSION_V4_AUDIT_FACT_KEYS.length\n && factKeys.every((key) => POLICY_SESSION_FACT_KEYS.includes(key as never) || POLICY_SESSION_V4_AUDIT_FACT_KEYS.includes(key as never))\n && POLICY_SESSION_FACT_KEYS.every((key) => key in fact)\n && POLICY_SESSION_V4_AUDIT_FACT_KEYS.every((key) => key in fact);\n if (!hasLegacyFactShape && !hasV4AuditFactShape)\n throw new Error(\"policy session UCAN fact is incomplete\");\n if (hasV4AuditFactShape\n && (!LOWER_SHA256_HEX.test(fact.credentialIdAuditDigestHex as string)\n || !LOWER_SHA256_HEX.test(fact.presentationJtiAuditDigestHex as string)))\n throw new Error(\"policy session UCAN v4 audit facts are invalid\");\n if (\n fact.profile !== POLICY_SESSION_UCAN_V1_PROFILE ||\n typeof fact.remainingRedelegationDepth !== \"number\" ||\n !Number.isInteger(fact.remainingRedelegationDepth) ||\n fact.remainingRedelegationDepth < 0 ||\n fact.remainingRedelegationDepth > 8 ||\n parsed.payload.exp - parsed.payload.nbf > MAX_POLICY_ROOT_SECONDS ||\n parsed.payload.iss.split(\"#\", 1)[0] !== fact.nodeAudience ||\n parsed.payload.aud !== fact.recipientDid\n )\n throw new Error(\"policy session UCAN fact is invalid\");\n return {\n authorization,\n cid: parsed.cid,\n iss: parsed.payload.iss,\n aud: parsed.payload.aud,\n prf: parsed.payload.prf as [string, string],\n att: parsed.payload.att,\n nbf: parsed.payload.nbf,\n exp: parsed.payload.exp,\n nnc: parsed.payload.nnc,\n fact,\n };\n}\n\nfunction decodeBase64Url(value: string): Uint8Array {\n if (!/^[A-Za-z0-9_-]+$/.test(value) || value.length % 4 === 1)\n throw new Error(\"value is not canonical base64url\");\n const normalized = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const binary = typeof atob === \"function\"\n ? atob(normalized.padEnd(Math.ceil(normalized.length / 4) * 4, \"=\"))\n : Buffer.from(normalized, \"base64\").toString(\"binary\");\n const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));\n const encoded = typeof btoa === \"function\"\n ? btoa(String.fromCharCode(...bytes)).replace(/=/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\")\n : Buffer.from(bytes).toString(\"base64url\");\n if (encoded !== value) throw new Error(\"value is not canonical base64url\");\n return bytes;\n}\n\nfunction encodeBase64Url(value: Uint8Array): string {\n return typeof btoa === \"function\"\n ? btoa(String.fromCharCode(...value)).replace(/=/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\")\n : Buffer.from(value).toString(\"base64url\");\n}\n\nfunction equalBytes(left: Uint8Array, right: Uint8Array): boolean {\n return left.length === right.length && left.every((byte, index) => byte === right[index]);\n}\n\nfunction hex(bytes: Uint8Array): string {\n return [...bytes].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction base32Lower(bytes: Uint8Array): string {\n const alphabet = \"abcdefghijklmnopqrstuvwxyz234567\";\n let output = \"\";\n let buffer = 0;\n let bits = 0;\n for (const byte of bytes) {\n buffer = (buffer << 8) | byte;\n bits += 8;\n while (bits >= 5) {\n output += alphabet[(buffer >>> (bits - 5)) & 31];\n bits -= 5;\n }\n }\n if (bits > 0) output += alphabet[(buffer << (5 - bits)) & 31];\n return output;\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport type { PermissionEntry } from \"@tinycloud/sdk-core\";\nimport { z } from \"zod\";\n\nimport {\n canonicalizeCapabilities,\n evaluateOperationAuthority,\n evaluateAuthority,\n} from \"./authority.js\";\nimport type { OperationSpaceResolver } from \"./authority.js\";\nimport type {\n OperationOperatorType,\n TinyCloudPosture,\n} from \"./contract.js\";\nimport { readAuthRequests, updateProfileStore } from \"./state.js\";\n\nexport { evaluateAuthority } from \"./authority.js\";\n\nconst THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1_000;\n\n/** The shared wire schema for SDK PermissionEntry values, including signed ReCap caveats. */\nexport const PermissionEntrySchema = z.object({\n service: z.string().min(1),\n space: z.string().min(1).optional(),\n path: z.string(),\n actions: z.array(z.string().min(1)).min(1),\n caveats: z.array(z.record(z.unknown())).optional(),\n skipPrefix: z.boolean().optional(),\n expiry: z.string().min(1).optional(),\n description: z.string().optional(),\n}).strict();\n\nconst CommandSchema = z.object({\n argv: z.array(z.string()).min(1),\n cwd: z.string().min(1),\n}).strict();\n\nconst LegacyPermissionRequestArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.request\"),\n version: z.literal(1),\n requestId: z.string(),\n sessionDid: z.string().min(1),\n requested: z.array(PermissionEntrySchema),\n requestedExpiry: z.union([z.string(), z.number().finite()]).optional(),\n}).strict();\n\nconst PortableDelegationSchema: z.ZodType<Record<string, unknown>> = z.lazy(() => z.object({\n cid: z.string().min(1),\n spaceId: z.string().min(1),\n path: z.string(),\n actions: z.array(z.string().min(1)).min(1),\n delegateDID: z.string().min(1),\n ownerAddress: z.string().min(1),\n chainId: z.number().int().positive(),\n expiry: z.union([z.string().datetime({ offset: true }), z.date()]),\n delegationHeader: z.object({ Authorization: z.string().min(1) }).strict(),\n host: z.string().min(1).optional(),\n disableSubDelegation: z.boolean().optional(),\n publicDelegation: PortableDelegationSchema.optional(),\n resources: z.array(PermissionEntrySchema).optional(),\n}).passthrough());\n\n/** Canonical wire-format v1 request retained for CLI and OpenKey compatibility. */\nexport const PermissionRequestArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.request\"),\n version: z.literal(1),\n requestId: z.string().min(1),\n createdAt: z.string().datetime({ offset: true }),\n profile: z.string().min(1),\n posture: z.enum([\"owner-openkey\", \"delegate-session\", \"local-owner-key\", \"unauthenticated\"]),\n operatorType: z.enum([\"human\", \"agent\"]),\n host: z.string().min(1),\n sessionDid: z.string().min(1),\n ownerDid: z.string().min(1).optional(),\n spaceId: z.string().min(1).optional(),\n requestedExpiry: z.union([z.string().min(1), z.number().finite()]).optional(),\n requested: z.array(PermissionEntrySchema),\n command: CommandSchema.optional(),\n}).strict();\n\n/** Canonical structured v1 delegation import accepted by the auth operation. */\nexport const DelegationImportArtifactSchema = z.object({\n kind: z.literal(\"tinycloud.auth.delegation\"),\n version: z.literal(1),\n requestId: z.string().min(1),\n delegationCid: z.string().min(1).optional(),\n delegation: PortableDelegationSchema,\n // This field is presentation metadata only. A later import operation obtains\n // effective permissions from validated, installed delegation authority.\n permissions: z.array(PermissionEntrySchema).optional(),\n expiry: z.string().datetime({ offset: true }).optional(),\n prompted: z.boolean().optional(),\n}).strict();\n\n/**\n * The stored request an imported delegation was checked against, persisted\n * with the delegation. Its fields are exactly the request artifact's, so\n * replay accepts every binding import can write.\n */\nexport const DelegationRequestBindingSchema = PermissionRequestArtifactSchema\n .pick({ requestId: true, requested: true })\n .strict();\nexport type DelegationRequestBinding = z.infer<typeof DelegationRequestBindingSchema>;\n\nexport type PermissionRequestArtifact = z.infer<typeof PermissionRequestArtifactSchema>;\nexport type DelegationImportArtifact = z.infer<typeof DelegationImportArtifactSchema>;\n/** The minimal public node-sdk request shape accepted by the legacy reader. */\nexport type LegacyPermissionRequestArtifact = z.infer<typeof LegacyPermissionRequestArtifactSchema>;\nexport type ArtifactClock = () => Date;\nexport type RequestIdSource = () => string;\n\n/** Invocation-owned values used to safely complete a legacy request record. */\nexport interface LegacyRequestContext {\n readonly profile: string;\n readonly host: string;\n readonly sessionDid: string;\n readonly posture: TinyCloudPosture;\n readonly operatorType: OperationOperatorType;\n readonly ownerDid?: string;\n readonly spaceId?: string;\n readonly now?: Date;\n}\n\nexport interface PermissionRequestIdentityInput {\n readonly profile: string;\n readonly sessionDid: string;\n readonly host: string;\n readonly missing: readonly PermissionEntry[];\n}\n\nexport interface BuildPermissionRequestArtifactInput extends PermissionRequestIdentityInput {\n readonly posture: TinyCloudPosture;\n readonly operatorType: OperationOperatorType;\n readonly ownerDid?: string;\n readonly spaceId?: string;\n readonly requestedExpiry?: string | number;\n readonly command?: { readonly argv: readonly string[]; readonly cwd: string };\n readonly now?: ArtifactClock;\n readonly createRequestId?: RequestIdSource;\n}\n\nexport interface CreateOrReusePermissionRequestInput extends BuildPermissionRequestArtifactInput {\n readonly granted: readonly PermissionEntry[];\n /** Owner-aware identity resolver used by registered operation callers. */\n readonly resolveSpace?: OperationSpaceResolver;\n readonly replace?: boolean;\n}\n\nexport type PermissionRequestResolution =\n | Readonly<{ status: \"satisfied\"; reused: false }>\n | Readonly<{ status: \"created\"; reused: boolean; request: PermissionRequestArtifact }>;\n\n/** Parses a request artifact without accepting a newer wire format as v1. */\nexport function validatePermissionRequestArtifact(value: unknown): PermissionRequestArtifact {\n return PermissionRequestArtifactSchema.parse(value);\n}\n\n/** Parses a structured active-session import artifact without accepting a newer wire format as v1. */\nexport function validateDelegationImportArtifact(value: unknown): DelegationImportArtifact {\n return DelegationImportArtifactSchema.parse(value);\n}\n\nexport function isPermissionRequestArtifact(value: unknown): value is PermissionRequestArtifact {\n return PermissionRequestArtifactSchema.safeParse(value).success;\n}\n\nexport function isDelegationImportArtifact(value: unknown): value is DelegationImportArtifact {\n return DelegationImportArtifactSchema.safeParse(value).success;\n}\n\nfunction normalizeLegacyPermissionRequest(\n value: LegacyPermissionRequestArtifact,\n context: LegacyRequestContext,\n): PermissionRequestArtifact {\n if (principal(value.sessionDid) !== principal(context.sessionDid)) {\n throw new TypeError(\"Stored authority request belongs to a different session.\");\n }\n const createdAt = context.now ?? new Date();\n if (Number.isNaN(createdAt.getTime())) {\n throw new TypeError(\"The legacy authority request has no usable creation time.\");\n }\n return {\n kind: \"tinycloud.auth.request\",\n version: 1,\n requestId: value.requestId,\n createdAt: createdAt.toISOString(),\n profile: context.profile,\n posture: context.posture,\n operatorType: context.operatorType,\n host: context.host,\n sessionDid: context.sessionDid,\n ...(context.ownerDid === undefined ? {} : { ownerDid: context.ownerDid }),\n ...(context.spaceId === undefined ? {} : { spaceId: context.spaceId }),\n ...(value.requestedExpiry === undefined ? {} : { requestedExpiry: value.requestedExpiry }),\n requested: canonicalizeCapabilities(value.requested),\n } as PermissionRequestArtifact;\n}\n\nfunction principal(value: string): string {\n return value.split(\"#\", 1)[0]!;\n}\n\n/**\n * Stable exact identity used only for request reuse. It binds a request to its\n * selected profile, active session DID, host, and canonical missing subset.\n */\nexport function createPermissionRequestIdentity(input: PermissionRequestIdentityInput): string {\n return JSON.stringify({\n profile: input.profile,\n sessionDid: input.sessionDid,\n host: input.host,\n missing: canonicalizeCapabilities(input.missing),\n });\n}\n\n/** Builds an on-disk-compatible v1 record. Omitted values stay omitted. */\nexport function buildPermissionRequestArtifact(\n input: BuildPermissionRequestArtifactInput,\n): PermissionRequestArtifact {\n const now = input.now ?? (() => new Date());\n const createdAt = now();\n if (Number.isNaN(createdAt.getTime())) throw new TypeError(\"The artifact clock returned an invalid date.\");\n const requested = canonicalizeCapabilities(input.missing);\n if (requested.length === 0) throw new TypeError(\"Permission requests require at least one missing capability.\");\n\n return validatePermissionRequestArtifact({\n kind: \"tinycloud.auth.request\",\n version: 1,\n requestId: input.createRequestId?.() ?? defaultRequestId(createdAt),\n createdAt: createdAt.toISOString(),\n profile: input.profile,\n posture: input.posture,\n operatorType: input.operatorType,\n host: input.host,\n sessionDid: input.sessionDid,\n ...(input.ownerDid !== undefined ? { ownerDid: input.ownerDid } : {}),\n ...(input.spaceId !== undefined ? { spaceId: input.spaceId } : {}),\n ...(input.requestedExpiry !== undefined ? { requestedExpiry: input.requestedExpiry } : {}),\n requested,\n ...(input.command !== undefined\n ? { command: { argv: [...input.command.argv], cwd: input.command.cwd } }\n : {}),\n });\n}\n\n/** Reads only valid canonical v1 records and refuses malformed stored artifacts. */\nexport async function listPermissionRequests(\n profile: string,\n context?: LegacyRequestContext,\n): Promise<PermissionRequestArtifact[]> {\n const records: PermissionRequestArtifact[] = [];\n for (const value of await readAuthRequests<unknown>(profile)) {\n const canonical = PermissionRequestArtifactSchema.safeParse(value);\n if (canonical.success) {\n if (context !== undefined && principal(canonical.data.sessionDid) !== principal(context.sessionDid)) {\n continue;\n }\n records.push(canonical.data);\n continue;\n }\n const legacy = LegacyPermissionRequestArtifactSchema.safeParse(value);\n if (!legacy.success) throw new TypeError(\"Stored authority request is malformed.\");\n if (context === undefined) {\n throw new TypeError(\"Legacy authority requests require the selected invocation context.\");\n }\n if (principal(legacy.data.sessionDid) !== principal(context.sessionDid)) continue;\n records.push(normalizeLegacyPermissionRequest(legacy.data, context));\n }\n return records;\n}\n\nexport async function findPermissionRequest(\n profile: string,\n requestId: string,\n identity: Pick<PermissionRequestIdentityInput, \"sessionDid\" | \"host\"> &\n Partial<Omit<LegacyRequestContext, \"profile\" | \"host\" | \"sessionDid\">>,\n): Promise<PermissionRequestArtifact | null> {\n const records = await listPermissionRequests(profile, {\n profile,\n host: identity.host,\n sessionDid: identity.sessionDid,\n posture: identity.posture ?? \"delegate-session\",\n operatorType: identity.operatorType ?? \"human\",\n ...(identity.ownerDid === undefined ? {} : { ownerDid: identity.ownerDid }),\n ...(identity.spaceId === undefined ? {} : { spaceId: identity.spaceId }),\n });\n return records.find((record) =>\n record.requestId === requestId &&\n record.sessionDid === identity.sessionDid &&\n record.host === identity.host,\n ) ?? null;\n}\n\n/**\n * Atomically returns the newest identical unresolved request, or writes a new\n * v1 record. Retention, stale-session pruning, covered-record pruning, and\n * partial-grant supersession all happen in the same existing profile lock.\n */\nexport async function createOrReusePermissionRequest(\n input: CreateOrReusePermissionRequestInput,\n): Promise<PermissionRequestResolution> {\n // Registered operations already computed this exact missing set during\n // canonical preflight. Do not recompute it with the legacy global matcher:\n // that matcher intentionally treats same-named short/full spaces as equal.\n const missing = input.resolveSpace === undefined\n ? evaluateAuthority(input.granted, input.missing).missing\n : canonicalizeCapabilities(input.missing);\n const now = input.now ?? (() => new Date());\n const observedNow = now();\n if (Number.isNaN(observedNow.getTime())) throw new TypeError(\"The artifact clock returned an invalid date.\");\n\n return updateProfileStore<unknown, PermissionRequestResolution>(\n input.profile,\n \"auth-requests\",\n (rawRecords) => {\n const records: PermissionRequestArtifact[] = [];\n for (const value of rawRecords) {\n const canonical = PermissionRequestArtifactSchema.safeParse(value);\n if (canonical.success) {\n if (principal(canonical.data.sessionDid) !== principal(input.sessionDid)) continue;\n records.push(canonical.data);\n continue;\n }\n const legacy = LegacyPermissionRequestArtifactSchema.safeParse(value);\n if (!legacy.success) throw new TypeError(\"Stored authority request is malformed.\");\n if (principal(legacy.data.sessionDid) !== principal(input.sessionDid)) continue;\n records.push(normalizeLegacyPermissionRequest(legacy.data, {\n profile: input.profile,\n host: input.host,\n sessionDid: input.sessionDid,\n posture: input.posture,\n operatorType: input.operatorType,\n ...(input.ownerDid === undefined ? {} : { ownerDid: input.ownerDid }),\n ...(input.spaceId === undefined ? {} : { spaceId: input.spaceId }),\n now: observedNow,\n }));\n }\n const retained = prunePermissionRequests(records, {\n profile: input.profile,\n sessionDid: input.sessionDid,\n granted: input.granted,\n resolveSpace: input.resolveSpace,\n now: observedNow,\n });\n\n if (missing.length === 0) {\n return { records: retained, result: { status: \"satisfied\", reused: false } };\n }\n\n const identity = createPermissionRequestIdentity({ ...input, missing });\n const withoutSuperseded = retained.filter((record) => !isSupersededBy(record, input, missing));\n const equivalent = newestEquivalentRequest(withoutSuperseded, identity);\n if (equivalent !== undefined && input.replace !== true) {\n return { records: withoutSuperseded, result: { status: \"created\", reused: true, request: equivalent } };\n }\n\n const next = withoutSuperseded.filter((record) =>\n input.replace !== true || permissionRequestArtifactIdentity(record) !== identity,\n );\n const request = buildPermissionRequestArtifact({ ...input, missing, now: () => observedNow });\n return {\n records: [...next, request],\n result: { status: \"created\", reused: false, request },\n };\n },\n );\n}\n\nexport interface PrunePermissionRequestsInput {\n readonly profile: string;\n readonly sessionDid: string;\n readonly granted: readonly PermissionEntry[];\n readonly resolveSpace?: OperationSpaceResolver;\n readonly now: Date;\n}\n\n/** Pure retention policy used by the locked persistence operation. */\nexport function prunePermissionRequests(\n records: readonly PermissionRequestArtifact[],\n input: PrunePermissionRequestsInput,\n): PermissionRequestArtifact[] {\n const cutoff = input.now.getTime() - THIRTY_DAYS_MS;\n return records.filter((record) => {\n const createdAt = Date.parse(record.createdAt);\n if (!Number.isFinite(createdAt) || createdAt < cutoff) return false;\n if (record.profile === input.profile && principal(record.sessionDid) !== principal(input.sessionDid)) return false;\n // Empty request arrays are historical CLI records. They carry no\n // authority, but remain readable and are retained byte-for-byte by the\n // shared format-1 writer for compatibility.\n if (record.requested.length === 0) return true;\n return !evaluateArtifactAuthority(\n input.granted,\n record.requested,\n input.resolveSpace,\n ).satisfied;\n });\n}\n\nfunction newestEquivalentRequest(\n records: readonly PermissionRequestArtifact[],\n identity: string,\n): PermissionRequestArtifact | undefined {\n let newest: PermissionRequestArtifact | undefined;\n for (const record of records) {\n if (permissionRequestArtifactIdentity(record) !== identity) continue;\n if (newest === undefined || record.createdAt >= newest.createdAt) newest = record;\n }\n return newest;\n}\n\nfunction isSupersededBy(\n record: PermissionRequestArtifact,\n input: CreateOrReusePermissionRequestInput,\n missing: readonly PermissionEntry[],\n): boolean {\n if (\n record.profile !== input.profile ||\n record.sessionDid !== input.sessionDid ||\n record.host !== input.host\n ) {\n return false;\n }\n const remaining = evaluateArtifactAuthority(\n input.granted,\n record.requested,\n input.resolveSpace,\n ).missing;\n return remaining.length > 0 &&\n permissionRequestArtifactIdentity(record) !==\n createPermissionRequestIdentity({ ...input, missing }) &&\n createPermissionRequestIdentity({ ...input, missing: remaining }) ===\n createPermissionRequestIdentity({ ...input, missing });\n}\n\nfunction permissionRequestArtifactIdentity(record: PermissionRequestArtifact): string {\n return createPermissionRequestIdentity({\n profile: record.profile,\n sessionDid: record.sessionDid,\n host: record.host,\n missing: record.requested,\n });\n}\n\nfunction evaluateArtifactAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n) {\n return resolveSpace === undefined\n ? evaluateAuthority(granted, required)\n : evaluateOperationAuthority(granted, required, resolveSpace);\n}\n\nfunction defaultRequestId(now: Date): string {\n return `req_${now.getTime().toString(36)}_${randomUUID().replace(/-/g, \"\")}`;\n}\n","import {\n canonicalizeRecapCaveats,\n isCapabilitySubset,\n type PermissionEntry,\n} from \"@tinycloud/sdk-core\";\n\n/**\n * A capability in the canonical form persisted in a v1 request artifact.\n *\n * The SDK remains the semantic authority for containment. This module only\n * establishes deterministic exact identity for persistence and display.\n */\nexport type CanonicalPermissionEntry = Readonly<PermissionEntry>;\n\nexport interface AuthorityEvaluation {\n readonly satisfied: boolean;\n readonly missing: readonly CanonicalPermissionEntry[];\n}\n\n/**\n * Operation-owned space resolution. The SDK's general capability evaluator\n * intentionally preserves its historical short/full-space compatibility; the\n * operation kernel supplies this narrower resolver when a space identifies a\n * remote owner's resource.\n */\nexport type OperationSpaceResolver = (space: string) => string;\n\nconst EXACT_PERMISSION_KEYS = new Set([\n \"service\",\n \"space\",\n \"path\",\n \"actions\",\n \"skipPrefix\",\n \"expiry\",\n \"description\",\n]);\n\n/**\n * Validate requirements that can be represented without semantic broadening in\n * a v1 artifact. Caveated authority is intentionally rejected: the v1 request\n * schema and grant path cannot preserve those signed branches end-to-end.\n */\nexport function validateExactCapabilities(value: unknown): PermissionEntry[] | undefined {\n if (!Array.isArray(value)) return undefined;\n\n const permissions: PermissionEntry[] = [];\n for (const candidate of value) {\n if (!isExactPermission(candidate)) return undefined;\n permissions.push(candidate);\n }\n return canonicalizeCapabilities(permissions);\n}\n\n/**\n * Evaluates required authority with the SDK's public subset primitive.\n *\n * In particular, this intentionally does not implement matching rules or\n * manufacture wildcards. A wildcard can cover a requirement only when it was\n * already present in the supplied granted authority and the SDK says so.\n */\nexport function evaluateAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n): AuthorityEvaluation {\n const canonicalGranted = canonicalizeCapabilities(granted);\n const canonicalRequired = canonicalizeCapabilities(required);\n const result = isCapabilitySubset(canonicalRequired, canonicalGranted);\n\n return {\n satisfied: result.subset,\n missing: canonicalizeCapabilities(result.missing),\n };\n}\n\n/**\n * Evaluate operation capabilities without allowing two owners' same-named\n * spaces to compare equal. Path and action containment still come from the\n * SDK primitive; only the operation space identity is made owner-exact.\n */\nexport function evaluateOperationAuthority(\n granted: readonly PermissionEntry[],\n required: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): AuthorityEvaluation {\n const canonicalGranted = canonicalizeOperationCapabilities(granted, resolveSpace);\n const canonicalRequired = canonicalizeOperationCapabilities(required, resolveSpace);\n const missing: CanonicalPermissionEntry[] = [];\n\n for (const requested of canonicalRequired) {\n const covered = canonicalGranted.some((candidate) =>\n candidate.service === requested.service &&\n operationSpacesEqual(candidate.space, requested.space) &&\n isCapabilitySubset([requested], [candidate]).subset,\n );\n if (!covered) missing.push(requested);\n }\n\n return {\n satisfied: missing.length === 0,\n missing: canonicalizeCapabilities(missing),\n };\n}\n\n/**\n * Whether a delegation's signed capabilities stay inside the stored request\n * it answers. `tinycloud.auth.import` and runtime replay share this check, so\n * a delegation import accepts is never one replay discards.\n */\nexport function delegationWithinRequest(\n requested: readonly PermissionEntry[],\n effective: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): boolean {\n return requested.length > 0 &&\n evaluateOperationAuthority(requested, canonicalizeCapabilities(effective), resolveSpace).satisfied;\n}\n\n/**\n * Validate a runtime hint as an exact member of the registered plan. Runtime\n * nodes may report the one phase that failed, but they may not introduce a\n * broader, differently-owned, caveated, or otherwise new capability.\n */\nexport function isExactCapabilityMemberSubset(\n hinted: readonly PermissionEntry[],\n planned: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): boolean {\n const canonicalHinted = canonicalizeOperationCapabilities(hinted, resolveSpace);\n const canonicalPlanned = canonicalizeOperationCapabilities(planned, resolveSpace);\n return canonicalHinted.length > 0 && canonicalHinted.every((hint) => canonicalPlanned.some((plan) =>\n JSON.stringify(hint) === JSON.stringify(plan),\n ));\n}\n\n/** Canonical identity used by operation preflight, hints, and artifacts. */\nexport function canonicalizeOperationCapabilities(\n permissions: readonly PermissionEntry[],\n resolveSpace?: OperationSpaceResolver,\n): CanonicalPermissionEntry[] {\n return canonicalizeCapabilities(permissions.map((permission) => {\n const canonicalPath = canonicalizeOperationPath(permission);\n if (permission.space === undefined || resolveSpace === undefined) {\n return canonicalPath;\n }\n try {\n return { ...canonicalPath, space: resolveSpace(permission.space) };\n } catch {\n // An unresolvable identity remains a non-matching literal. It must never\n // be widened to a wildcard or to another authenticated owner.\n return canonicalPath;\n }\n }));\n}\n\nfunction canonicalizeOperationPath(permission: PermissionEntry): PermissionEntry {\n if (permission.service !== \"tinycloud.encryption\") return permission;\n const match = permission.path.match(\n /^(urn:tinycloud:encryption:did:pkh:eip155:\\d+:)(0x[0-9a-fA-F]{40})(:.*)$/,\n );\n if (!match) return permission;\n return { ...permission, path: `${match[1]}${match[2]!.toLowerCase()}${match[3]}` };\n}\n\nfunction operationSpacesEqual(\n granted: string | undefined,\n requested: string | undefined,\n): boolean {\n return granted === requested;\n}\n\n/** Returns a stable exact identity for one capability without containment. */\nexport function permissionIdentity(permission: PermissionEntry): string {\n return JSON.stringify(canonicalizeCapability(permission));\n}\n\n/**\n * Sorts actions and entries and removes only exactly-identical capabilities.\n * It does not coalesce paths, services, spaces, or actions into a broader\n * capability.\n */\nexport function canonicalizeCapabilities(\n permissions: readonly PermissionEntry[],\n): CanonicalPermissionEntry[] {\n const byIdentity = new Map<string, CanonicalPermissionEntry>();\n for (const permission of permissions) {\n const canonical = canonicalizeCapability(permission);\n byIdentity.set(permissionIdentityFromCanonical(canonical), canonical);\n }\n\n return [...byIdentity.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([, permission]) => permission);\n}\n\nfunction canonicalizeCapability(permission: PermissionEntry): CanonicalPermissionEntry {\n const actions = [...new Set(permission.actions)].sort((left, right) => left.localeCompare(right));\n return {\n service: permission.service,\n ...(permission.space !== undefined ? { space: permission.space } : {}),\n path: permission.path,\n actions,\n ...(permission.skipPrefix !== undefined ? { skipPrefix: permission.skipPrefix } : {}),\n ...(permission.expiry !== undefined ? { expiry: permission.expiry } : {}),\n ...(permission.description !== undefined ? { description: permission.description } : {}),\n ...(permission.caveats === undefined\n ? {}\n : { caveats: canonicalizeCaveats(permission.caveats) }),\n };\n}\n\nfunction permissionIdentityFromCanonical(permission: CanonicalPermissionEntry): string {\n return JSON.stringify({\n service: permission.service,\n ...(permission.space !== undefined ? { space: permission.space } : {}),\n path: permission.path,\n actions: permission.actions,\n ...(permission.skipPrefix !== undefined ? { skipPrefix: permission.skipPrefix } : {}),\n ...(permission.expiry !== undefined ? { expiry: permission.expiry } : {}),\n ...(permission.description !== undefined ? { description: permission.description } : {}),\n ...(permission.caveats === undefined ? {} : { caveats: permission.caveats }),\n });\n}\n\nfunction isExactPermission(value: unknown): value is PermissionEntry {\n if (\n !isExactRecord(value) ||\n Object.getOwnPropertyNames(value).some((key) => !EXACT_PERMISSION_KEYS.has(key)) ||\n Object.getOwnPropertySymbols(value).length > 0\n ) {\n return false;\n }\n if (\n !isExactText(value.service) ||\n !isExactPath(value.path, value.actions) ||\n (value.space !== undefined && !isExactText(value.space)) ||\n !Array.isArray(value.actions) ||\n value.actions.length === 0 ||\n !value.actions.every(isExactText) ||\n new Set(value.actions).size !== value.actions.length ||\n value.skipPrefix === true ||\n (value.skipPrefix !== undefined && value.skipPrefix !== false) ||\n (value.expiry !== undefined && !isExactText(value.expiry)) ||\n (value.description !== undefined && !isExactText(value.description))\n ) {\n return false;\n }\n return !(\"caveats\" in value);\n}\n\nfunction isExactRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isExactText(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0 && !value.includes(\"*\");\n}\n\nfunction isExactPath(value: unknown, actions: unknown): value is string {\n if (typeof value !== \"string\" || value === \"/\" || value.includes(\"*\")) return false;\n if (value === \"\" || value.endsWith(\"/\")) {\n return Array.isArray(actions) && actions.includes(\"tinycloud.kv/list\");\n }\n return true;\n}\n\nfunction canonicalizeCaveats(\n caveats: readonly Record<string, unknown>[],\n): Record<string, unknown>[] {\n return [...caveats]\n .map((caveat) => ({\n identity: canonicalizeRecapCaveats([caveat]),\n value: JSON.parse(JSON.stringify(caveat)) as Record<string, unknown>,\n }))\n .sort((left, right) => left.identity.localeCompare(right.identity))\n .map(({ value }) => value);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n chmod,\n link,\n mkdir,\n open,\n readFile,\n readdir,\n rename,\n rmdir,\n rm,\n stat,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, isAbsolute, join, relative, resolve } from \"node:path\";\n\nconst DEFAULT_PROFILE = \"default\";\nconst DEFAULT_LOCK_TIMEOUT_MS = 2_000;\nconst DEFAULT_LOCK_RETRY_MS = 25;\nconst DEFAULT_STALE_LOCK_MS = 30_000;\nconst TEST_LOCK_CONTENTION_SIGNAL_PATH = \"TC_TEST_PROFILE_LOCK_CONTENTION_SIGNAL_PATH\";\n// Profile state holds keys, sessions and delegations: owner-only access.\nconst PRIVATE_FILE_MODE = 0o600;\nconst PRIVATE_DIR_MODE = 0o700;\nconst TEST_LOCK_RECOVERY_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_RECOVERY_BARRIER_DIR\";\nconst TEST_LOCK_OWNERLESS_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_OWNERLESS_BARRIER_DIR\";\nconst TEST_LOCK_PUBLISH_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_PUBLISH_BARRIER_DIR\";\nconst TEST_LOCK_RELEASE_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_RELEASE_BARRIER_DIR\";\nconst TEST_LOCK_CLAIM_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_CLAIM_BARRIER_DIR\";\nconst TEST_LOCK_CLAIMED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_CLAIMED_BARRIER_DIR\";\nconst TEST_LOCK_VERIFIED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_VERIFIED_BARRIER_DIR\";\nconst TEST_LOCK_MOVED_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_MOVED_BARRIER_DIR\";\nconst TEST_LOCK_TURN_PUBLISH_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_PUBLISH_BARRIER_DIR\";\nconst TEST_LOCK_TURN_SETTLE_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_SETTLE_BARRIER_DIR\";\nconst TEST_LOCK_TURN_COLLECT_BARRIER_DIR = \"TC_TEST_PROFILE_LOCK_TURN_COLLECT_BARRIER_DIR\";\n/** One acquisition of a profile lock; `active` is cleared before release. */\ninterface HeldProfileLock {\n readonly lockPath: string;\n /** The number of the turn this acquisition holds (see acquireTurn). */\n readonly turnSlot: number;\n /** A deletion of the profile ran while this acquisition waited for the lock. */\n readonly deletedWhileWaiting: boolean;\n active: boolean;\n}\n/**\n * Async context shared by every copy of this module in the process. Each\n * bundled operations entry point (`state`, `delegation-binding`, the root)\n * carries its own copy, so module-level context would make lock reentrancy and\n * the invocation state root stop at an entry-point boundary.\n * Each key is independently versioned for the shape and meaning of the\n * value it stores. Held-lock entries gained `turnSlot` and\n * `deletedWhileWaiting` in TC-633, so `.v2` must not read TC-602's `.v1`\n * entries. The invocation root remains a string path with unchanged\n * semantics and stays `.v1`. Relinquished turn tokens use a separate\n * versioned process-wide key: only an explicitly given-up turn of this PID\n * may be settled across separately bundled entry points.\n */\nfunction processWideContext<T>(key: string): AsyncLocalStorage<T> {\n const registry = globalThis as unknown as Record<symbol, AsyncLocalStorage<T> | undefined>;\n return registry[Symbol.for(key)] ??= new AsyncLocalStorage<T>();\n}\nconst invocationStateRoot = processWideContext<string>(\"tinycloud.operations.invocationStateRoot.v1\");\n/** Profile lock acquisitions held by the current async call chain (see withProfileLock). */\nconst heldProfileLocks = processWideContext<readonly HeldProfileLock[]>(\"tinycloud.operations.heldProfileLocks.v2\");\n\nexport type ProfileStoreName =\n | \"session\"\n | \"additional-delegations\"\n | \"auth-requests\";\n\nexport interface StoreMetadata {\n formatVersion: number;\n}\n\nexport interface ProfileStoreContents<T> {\n formatVersion: number;\n records: T[];\n}\n\nexport interface ProfileLockOptions {\n timeoutMs?: number;\n retryMs?: number;\n staleAfterMs?: number;\n /**\n * Lock only a profile that exists (its `profile.json` is present), and\n * never create its directory: a missing or deleted profile is refused with\n * ProfileDeletedError, before and after waiting for the lock. For writers\n * of state that lives inside an existing profile (replicas).\n */\n requireProfile?: boolean;\n}\n\nexport class ProfileLockTimeoutError extends Error {\n readonly code = \"PROFILE_LOCK_TIMEOUT\";\n\n /** `detail` names the cause when it is not simply another process holding the lock. */\n constructor(profile: string, timeoutMs: number, detail?: string) {\n super(`Timed out waiting for the profile lock for \"${profile}\" after ${timeoutMs}ms.${detail ? ` ${detail}` : \"\"}`);\n this.name = \"ProfileLockTimeoutError\";\n }\n}\n\n/**\n * A store write that waited for the profile lock while a deletion of that\n * profile held it, and found no profile settings once it got the lock. The\n * write is refused rather than recreating a profile with only a session or\n * store in it.\n */\nexport class ProfileDeletedError extends Error {\n readonly code = \"PROFILE_NOT_FOUND\";\n\n constructor(profile: string) {\n super(`Profile \"${profile}\" was deleted while this change waited for its lock, so the change was not written.`);\n this.name = \"ProfileDeletedError\";\n }\n}\n\n/**\n * The CLI's delegated-secret path treats TC_HOME as a home directory, rather\n * than a direct TinyCloud directory. Keep the shared store on that convention.\n */\nexport function tinycloudHomePath(): string {\n const home = invocationStateRoot.getStore() ??\n process.env.TC_HOME ??\n process.env.HOME ??\n process.env.USERPROFILE ??\n homedir();\n return join(home, \".tinycloud\");\n}\n\n/** Run one operation against an isolated TinyCloud home directory. */\nexport function withTinyCloudStateRoot<T>(\n stateRoot: string | undefined,\n action: () => Promise<T>,\n): Promise<T> {\n if (stateRoot === undefined) return action();\n if (!isAbsolute(stateRoot) || stateRoot.includes(\"\\0\")) {\n throw new TypeError(\"The TinyCloud state root must be an absolute path.\");\n }\n return invocationStateRoot.run(resolve(stateRoot), action);\n}\n\nexport function tinycloudConfigPath(): string {\n return join(tinycloudHomePath(), \"config.json\");\n}\n\nexport function profilesPath(): string {\n return join(tinycloudHomePath(), \"profiles\");\n}\n\nexport function profilePath(profile: string): string {\n return join(profilesPath(), validateProfileName(profile));\n}\n\nexport function profileConfigPath(profile: string): string {\n return join(profilePath(profile), \"profile.json\");\n}\n\nexport function sessionPath(profile: string): string {\n return profileStorePath(profile, \"session\");\n}\n\nexport function additionalDelegationsPath(profile: string): string {\n return profileStorePath(profile, \"additional-delegations\");\n}\n\nexport function authRequestsPath(profile: string): string {\n return profileStorePath(profile, \"auth-requests\");\n}\n\nexport function profileStorePath(profile: string, store: ProfileStoreName): string {\n return join(profilePath(profile), `${store}.json`);\n}\n\n/** The format record is deliberately separate from each legacy JSON payload. */\nexport function profileStoreMetadataPath(profile: string, store: ProfileStoreName): string {\n return `${profileStorePath(profile, store)}.metadata.json`;\n}\n\nexport function profileLockPath(profile: string): string {\n return join(profilePath(profile), \".lock\");\n}\n\nexport function profileLockMetadataPath(profile: string): string {\n return join(profileLockPath(profile), \"owner.json\");\n}\n\n/**\n * The turn lock of a profile (see acquireTurn). It lives outside the profile\n * directory, so neither a profile deletion nor an older release's cleanup\n * removes it.\n */\nexport function profileTurnLockPath(profile: string): string {\n return join(tinycloudHomePath(), \"profile-locks\", validateProfileName(profile));\n}\n\n/**\n * Reads JSON without hiding malformed or inaccessible files. A missing file is\n * the only condition represented as null.\n */\nexport async function readJson<T>(filePath: string): Promise<T | null> {\n try {\n return JSON.parse(await readFile(filePath, \"utf8\")) as T;\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return null;\n throw error;\n }\n}\n\n/**\n * Writes the same pretty-printed, trailing-newline JSON shape used by the CLI,\n * but publishes it with an atomic rename from the same directory.\n */\nexport async function writeJsonAtomic(filePath: string, value: unknown): Promise<void> {\n await replaceJson(filePath, value, false);\n}\n\n/**\n * writeJsonAtomic; `durable` also flushes the data to disk before the rename,\n * so a crash or power loss leaves the old record or the new one, never a\n * truncated one (for lock records, whose damage would stop every writer).\n */\nasync function replaceJson(filePath: string, value: unknown, durable: boolean): Promise<void> {\n const directory = dirname(filePath);\n const temporaryPath = join(\n directory,\n `.${basename(filePath)}.${process.pid}.${randomUUID()}.tmp`,\n );\n const contents = `${JSON.stringify(value, null, 2)}\\n`;\n\n await mkdir(directory, { recursive: true, mode: PRIVATE_DIR_MODE });\n try {\n if (durable) await writeFileDurably(temporaryPath, contents);\n else await writeFile(temporaryPath, contents, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE });\n await rename(temporaryPath, filePath);\n } catch (error) {\n await rm(temporaryPath, { force: true }).catch(() => undefined);\n throw error;\n }\n}\n\n/** Creates a file (exclusively) and, when it has contents, flushes them to disk. */\nasync function writeFileDurably(path: string, contents: string): Promise<void> {\n const handle = await open(path, \"wx\", PRIVATE_FILE_MODE);\n try {\n if (contents) {\n await handle.writeFile(contents, \"utf8\");\n await handle.datasync();\n }\n } finally {\n await handle.close();\n }\n}\n\nexport async function readProfile<T extends object = Record<string, unknown>>(\n profile: string,\n): Promise<T | null> {\n return readJson<T>(profileConfigPath(profile));\n}\n\nexport async function readSession<T extends object = Record<string, unknown>>(\n profile: string,\n): Promise<T | null> {\n await readStoreMetadata(profile, \"session\");\n return readJson<T>(sessionPath(profile));\n}\n\nexport async function readAdditionalDelegations<T = Record<string, unknown>>(\n profile: string,\n): Promise<T[]> {\n return (await readProfileStore<T>(profile, \"additional-delegations\")).records;\n}\n\nexport async function readAuthRequests<T = Record<string, unknown>>(\n profile: string,\n): Promise<T[]> {\n return (await readProfileStore<T>(profile, \"auth-requests\")).records;\n}\n\nexport async function readStoreMetadata(\n profile: string,\n store: ProfileStoreName,\n): Promise<StoreMetadata> {\n const metadata = await readJson<StoreMetadata>(profileStoreMetadataPath(profile, store));\n if (metadata === null) return { formatVersion: 1 };\n if (\n typeof metadata !== \"object\" ||\n metadata.formatVersion !== 1\n ) {\n throw new TypeError(`Unsupported store format for \"${store}\".`);\n }\n return metadata;\n}\n\nexport async function readProfileStore<T>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n): Promise<ProfileStoreContents<T>> {\n const [metadata, raw] = await Promise.all([\n readStoreMetadata(profile, store),\n readJson<unknown>(profileStorePath(profile, store)),\n ]);\n return {\n formatVersion: metadata.formatVersion,\n records: Array.isArray(raw) ? raw as T[] : [],\n };\n}\n\n/**\n * Runs a small critical section under the one lock shared by all profile\n * stores (see acquireProfileLock). Lock release verifies its ownership token\n * before removing the exact metadata instance it acquired.\n *\n * Reentrant within one async call chain: a critical section that already\n * holds a profile's lock (for example a login's compare-and-commit) can call\n * store writers that take the same lock without deadlocking. Ownership is\n * keyed by the resolved lock path (so switching state roots inside a lock\n * still takes the other root's lock) and lasts exactly as long as the\n * acquisition: it is revoked before release, so work deferred past the\n * critical section waits for the lock like any other caller.\n */\nexport async function withProfileLock<T>(\n profile: string,\n action: () => Promise<T>,\n options: ProfileLockOptions = {},\n): Promise<T> {\n const normalizedProfile = validateProfileName(profile);\n const lockPath = profileLockPath(normalizedProfile);\n const held = (heldProfileLocks.getStore() ?? []).filter((ownership) => ownership.active);\n if (held.some((ownership) => ownership.lockPath === lockPath)) return action();\n const acquired = await acquireProfileLock(normalizedProfile, options);\n const ownership: HeldProfileLock = {\n lockPath,\n turnSlot: acquired.turnSlot,\n deletedWhileWaiting: acquired.deletedWhileWaiting,\n active: true,\n };\n try {\n return await heldProfileLocks.run([...held, ownership], action);\n } finally {\n ownership.active = false;\n await acquired.release();\n // Taking the lock recreated the deleted profile's directory; remove it\n // again unless something was written into it (rmdir needs it empty).\n if (acquired.deletedWhileWaiting) await rmdir(profilePath(normalizedProfile)).catch(() => undefined);\n }\n}\n\n/**\n * Records, inside a profile deletion's critical section and after its files\n * are gone, that the profile was deleted, with the number of the deleting\n * turn. A store write whose wait overlapped that turn (it arrived before the\n * deletion released the lock, whether before or after this record) then\n * refuses (ProfileDeletedError) instead of recreating a profile with only a\n * session or store in it. The caller must hold the profile's lock.\n */\nexport async function recordProfileDeletion(profile: string): Promise<void> {\n const lockPath = profileLockPath(profile);\n const ownership = (heldProfileLocks.getStore() ?? []).find((candidate) => candidate.active && candidate.lockPath === lockPath);\n if (!ownership) throw new Error(`Recording the deletion of profile \"${profile}\" requires holding its lock.`);\n await replaceJson(join(profileTurnLockPath(profile), \"deleted.json\"), { slot: ownership.turnSlot }, true);\n}\n\n/**\n * Refuses a write that would recreate a profile deleted while this critical\n * section waited for the lock (ProfileDeletedError). Every writer of profile\n * state other than the profile settings themselves calls this inside its\n * critical section, before writing. The caller must hold the profile's lock.\n */\nexport async function refuseWriteToDeletedProfile(profile: string): Promise<void> {\n const lockPath = profileLockPath(profile);\n const ownership = (heldProfileLocks.getStore() ?? []).find((candidate) => candidate.active && candidate.lockPath === lockPath);\n if (!ownership?.deletedWhileWaiting) return;\n // Recreated meanwhile (or by this critical section): writing is fine.\n if (await exists(profileConfigPath(profile))) return;\n throw new ProfileDeletedError(profile);\n}\n\n/**\n * Appends a record or replaces the existing record with the supplied explicit\n * key. The extractor is supplied by the owning store so state.ts never needs\n * to know permission-request or delegation record shapes.\n */\nexport async function upsertProfileRecord<T>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n key: string,\n record: T,\n getKey: (candidate: T) => string | undefined,\n options: ProfileLockOptions = {},\n): Promise<T[]> {\n if (!key) throw new TypeError(\"A non-empty record key is required.\");\n\n return withProfileLock(profile, async () => {\n await refuseWriteToDeletedProfile(profile);\n const current = (await readProfileStore<T>(profile, store)).records;\n const next = current.filter((candidate) => getKey(candidate) !== key);\n next.push(record);\n await writeJsonAtomic(profileStorePath(profile, store), next);\n await writeFormatOneMetadata(profile, store);\n return next;\n }, options);\n}\n\n/**\n * Performs a typed read-modify-write of a legacy array store under the one\n * per-profile lock. The payload stays an array and the sibling metadata stays\n * format 1, so existing CLI readers keep their byte/layout contract.\n */\nexport async function updateProfileStore<T, Result>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n update: (\n records: readonly T[],\n ) => Promise<{ readonly records: readonly T[]; readonly result: Result }> | {\n readonly records: readonly T[];\n readonly result: Result;\n },\n options: ProfileLockOptions = {},\n): Promise<Result> {\n return withProfileLock(\n profile,\n () => updateProfileStoreWhileLocked(profile, store, update),\n options,\n );\n}\n\n/** The caller must already own this profile's lock. */\nasync function updateProfileStoreWhileLocked<T, Result>(\n profile: string,\n store: Exclude<ProfileStoreName, \"session\">,\n update: (\n records: readonly T[],\n ) => Promise<{ readonly records: readonly T[]; readonly result: Result }> | {\n readonly records: readonly T[];\n readonly result: Result;\n },\n): Promise<Result> {\n await refuseWriteToDeletedProfile(profile);\n const current = await readProfileStore<T>(profile, store);\n const next = await update(current.records);\n await writeJsonAtomic(profileStorePath(profile, store), next.records);\n await writeFormatOneMetadata(profile, store);\n return next.result;\n}\n\nexport async function writeSession<T extends object>(\n profile: string,\n session: T,\n options: ProfileLockOptions = {},\n): Promise<void> {\n await withProfileLock(profile, async () => {\n await refuseWriteToDeletedProfile(profile);\n await readStoreMetadata(profile, \"session\");\n await writeJsonAtomic(sessionPath(profile), session);\n await writeFormatOneMetadata(profile, \"session\");\n }, options);\n}\n\nexport async function removeSession(\n profile: string,\n options: ProfileLockOptions = {},\n): Promise<void> {\n await withProfileLock(profile, async () => {\n await readStoreMetadata(profile, \"session\");\n await rm(sessionPath(profile), { force: true });\n }, options);\n}\n\nasync function writeFormatOneMetadata(profile: string, store: ProfileStoreName): Promise<void> {\n await writeJsonAtomic(profileStoreMetadataPath(profile, store), { formatVersion: 1 });\n}\n\ninterface AcquiredProfileLock {\n readonly deletedWhileWaiting: boolean;\n readonly turnSlot: number;\n release(): Promise<void>;\n}\n\ninterface LockDeadline {\n readonly startedAt: number;\n readonly timeoutMs: number;\n readonly retryMs: number;\n}\n\n/**\n * Takes a profile's lock in two layers:\n *\n * 1. The turn lock (acquireTurn), used by this release and later ones. It\n * decides nothing from elapsed time, so a process paused anywhere, for\n * any length of time, cannot let a second holder in.\n * 2. Holding a turn, the `.lock` directory every older release uses\n * (publishProfileLock), so they keep excluding this release and it them.\n * Only one process of this release at a time acquires, recovers or\n * releases `.lock`.\n *\n * Also reports whether a profile deletion (recordProfileDeletion) ran while\n * this acquisition waited.\n */\nasync function acquireProfileLock(\n profile: string,\n options: ProfileLockOptions,\n): Promise<AcquiredProfileLock> {\n const deadline: LockDeadline = {\n startedAt: Date.now(),\n timeoutMs: options.timeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS,\n retryMs: options.retryMs ?? DEFAULT_LOCK_RETRY_MS,\n };\n const staleAfterMs = options.staleAfterMs ?? DEFAULT_STALE_LOCK_MS;\n const lockPath = profileLockPath(profile);\n const turnDirectory = profileTurnLockPath(profile);\n\n const directory = profilePath(profile);\n if (options.requireProfile && !(await exists(profileConfigPath(profile)))) throw new ProfileDeletedError(profile);\n if (!options.requireProfile) await mkdir(directory, { recursive: true, mode: PRIVATE_DIR_MODE });\n await mkdir(dirname(turnDirectory), { recursive: true, mode: PRIVATE_DIR_MODE });\n // Every store write takes this lock: tighten the tree older releases\n // created 0775 before writing sessions or delegations into it.\n for (const path of [tinycloudHomePath(), profilesPath(), directory]) {\n await chmod(path, PRIVATE_DIR_MODE).catch((error: unknown) => {\n // A profile deletion can remove the profile directory right after the\n // mkdir above; the lock attempt below recreates it 0700.\n if (path !== directory || !isErrno(error, \"ENOENT\")) throw error;\n });\n }\n\n const { turn, firstWaitedTurn } = await acquireTurn(profile, turnDirectory, deadline);\n try {\n // Holding the turn, no deletion runs: a profile present now stays until release.\n if (options.requireProfile && !(await exists(profileConfigPath(profile)))) {\n // A deletion that finished while this waited could not remove the\n // directory if a lock was held then; remove it if empty.\n await rmdir(directory).catch(() => undefined);\n throw new ProfileDeletedError(profile);\n }\n // An unreadable deletion record is ignored rather than failing every\n // acquisition; it is written durably, so only damage makes it so.\n const deletion = await readJson<{ slot?: unknown }>(join(turnDirectory, \"deleted.json\")).catch(() => null);\n const deletedWhileWaiting = typeof deletion?.slot === \"number\" && deletion.slot >= firstWaitedTurn;\n while (true) {\n const token = randomUUID();\n if (await publishProfileLock(profile, lockPath, token, options.requireProfile === true)) {\n return {\n deletedWhileWaiting,\n turnSlot: turn.slot,\n release: async () => {\n try {\n await releaseProfileLock(profile, lockPath, token);\n } finally {\n await releaseTurn(profile, turn);\n }\n },\n };\n }\n await signalTestLockContention(profile);\n if (await recoverStaleLock(profile, lockPath, staleAfterMs)) continue;\n await waitOrTimeOut(profile, deadline);\n }\n } catch (error) {\n await releaseTurn(profile, turn);\n throw error;\n }\n}\n\n/** Throws once the acquisition's time is up; `detail` explains a damaged turn lock. */\nfunction checkDeadline(profile: string, deadline: LockDeadline, detail?: string): void {\n if (Date.now() - deadline.startedAt >= deadline.timeoutMs) {\n throw new ProfileLockTimeoutError(profile, deadline.timeoutMs, detail);\n }\n}\n\n/** Sleeps one retry interval, or throws once the acquisition's time is up. */\nasync function waitOrTimeOut(profile: string, deadline: LockDeadline, detail?: string): Promise<void> {\n checkDeadline(profile, deadline, detail);\n await sleep(Math.min(deadline.retryMs, deadline.timeoutMs - (Date.now() - deadline.startedAt)));\n}\n\n/** One granted turn of the turn lock. */\ninterface Turn {\n readonly directory: string;\n readonly slot: number;\n readonly token: string;\n}\n\n/** A turn as recorded on disk. */\ninterface TurnState {\n readonly slot: number;\n readonly token: string;\n readonly pid: number;\n /** The token of the turn before it that its creator observed; null for turn 0. */\n readonly after: string | null;\n readonly held: boolean;\n readonly done: boolean;\n}\n\n/** Turn directory names: decimal turn numbers. */\nconst TURN = /^(?:0|[1-9][0-9]*)$/;\n\n/**\n * Tokens of turns this process published and then gave up (a marker write or\n * a read failed after publication): the positive evidence that lets this\n * process settle a turn of its own PID. A live process's turn that is not in\n * here is never settled by it, so a module instance that cannot see another\n * instance's set (another bundled copy of this package) waits rather than\n * settling a turn that copy still holds.\n *\n * One set per process, not per module instance: the package's entry points\n * (state, index, artifacts, cli-runtime; ESM and CJS) each bundle their own\n * copy of this module, and one process may load several. The key is\n * versioned so that a release changing what the set holds uses a new one.\n */\nconst relinquishedTurns: Set<string> =\n (globalThis as unknown as Record<symbol, Set<string> | undefined>)[Symbol.for(\"tinycloud.operations.relinquishedProfileTurns.v1\")] ??=\n new Set<string>();\n\n/** Marker writes are retried this many times, after these delays (ms), before giving up. */\nconst MARKER_RETRY_DELAYS_MS = [10, 50, 250];\n/** A given-up turn is settled in the background every second for up to five minutes. */\nconst SETTLE_RETRY_MS = 1_000;\nconst SETTLE_RETRIES = 300;\n\n/**\n * The turn lock: mutual exclusion among processes of this release that does\n * not depend on how long any of them is paused. It uses only `mkdir`,\n * `rename`, exclusive file creation, and a check that a holder's PID is gone\n * (as `.lock` recovery always has), so it needs no hard links.\n *\n * Turns are numbered directories in profileTurnLockPath(profile). Turn n has\n * `owner.json` ({ pid, createdAt, token, after }), where `after` is the token\n * of the turn n-1 its creator observed, and gains `<token>.held` when granted\n * and `<token>.done` when over. Markers name the turn's own token, so one\n * written late into a recreated directory of the same number means nothing.\n *\n * - A turn is published by renaming a fully written staging directory to\n * `n`, which fails while `n` exists (rename never replaces a non-empty\n * directory, and turn directories are never empty). The turn directory\n * itself is published the same way, with a granted, finished turn 0.\n * - A process takes turn n only after reading turn n-1 granted and done.\n * Once `n` is published it checks that turn n-1 is still the one it read\n * (same token, granted, done) and only then writes `held`; otherwise the\n * turn is void: it writes `done` alone and starts over.\n * - Turns are removed by renaming them aside: a void turn at any time, a\n * granted one only once no older turn is left and turn n+1 is granted and\n * done. The latest turn is never removed.\n *\n * Why at most one granted turn is ever not done: a removed number can be\n * published again, but turn n-1 is always removed before turn n, so a\n * process whose stale read led it to republish n finds n-1 gone or holding\n * another token, and its turn is void. A process that finds n-1 as it read\n * it published `n` for the first time, so it is the only process granted n,\n * and n-1 was done before. A turn is marked done only by its holder, or by\n * another process once the holder's PID is gone (or by its own process,\n * once it has explicitly given that turn up); a paused holder is alive.\n * A turn is voided only on definite evidence (the turn it follows is gone or\n * holds another token), never because a read failed. Nothing above is\n * decided from elapsed time.\n *\n * Returns the turn and the number of the first turn this acquisition waited\n * on: the latest turn when it first looked if that was not done yet, else\n * the next one.\n */\nasync function acquireTurn(\n profile: string,\n directory: string,\n deadline: LockDeadline,\n): Promise<{ turn: Turn; firstWaitedTurn: number }> {\n let firstWaitedTurn: number | undefined;\n // Why the turn lock looks damaged, as of the last look, for the timeout message.\n let problem: string | undefined;\n const damaged = (what: string) =>\n `The turn lock ${directory} ${what}, so no process can take it. ` +\n `If no tc or MCP process is using profile \"${profile}\", remove that directory.`;\n for (let first = true; ; first = false) {\n if (!first) checkDeadline(profile, deadline, problem);\n problem = undefined;\n const latest = await readLatestTurn(directory);\n if (latest === \"missing\") {\n await createTurnDirectory(directory);\n continue;\n }\n if (latest === \"empty\") {\n // Usually a listing that straddled a turn's publication and an older\n // turn's removal (readdir is not a snapshot); damaged if it persists.\n problem = damaged(\"has no turns\");\n await waitOrTimeOut(profile, deadline, problem);\n continue;\n }\n if (latest === null) continue;\n if (typeof latest === \"number\") {\n problem = damaged(`has an unreadable turn ${latest}`);\n await waitOrTimeOut(profile, deadline, problem);\n continue;\n }\n firstWaitedTurn ??= latest.done ? latest.slot + 1 : latest.slot;\n if (latest.held && latest.done) {\n const turn = await takeTurn(profile, directory, latest);\n if (turn !== null) return { turn, firstWaitedTurn };\n await waitOrTimeOut(profile, deadline);\n } else if (latest.done) {\n problem = damaged(`ends with turn ${latest.slot}, which was never granted`);\n await waitOrTimeOut(profile, deadline, problem);\n } else if (latest.pid === process.pid ? relinquishedTurns.has(latest.token) : !isProcessAlive(latest.pid)) {\n await waitForTestBarrier(TEST_LOCK_TURN_SETTLE_BARRIER_DIR, profile);\n await settleAbandonedTurn(directory, latest);\n relinquishedTurns.delete(latest.token);\n } else {\n await signalTestLockContention(profile);\n await waitOrTimeOut(profile, deadline);\n }\n }\n}\n\n/**\n * The highest-numbered turn: its state, its number if it is damaged, null if\n * it went away while being read.\n */\nasync function readLatestTurn(directory: string): Promise<TurnState | number | \"missing\" | \"empty\" | null> {\n let names: string[];\n try {\n names = await readdir(directory);\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return \"missing\";\n throw error;\n }\n const slots = names.filter((name) => TURN.test(name)).map(Number);\n if (slots.length === 0) return \"empty\";\n const slot = Math.max(...slots);\n const turn = await readTurn(directory, slot);\n return turn === \"damaged\" ? slot : turn;\n}\n\n/**\n * Turn `slot` as recorded now; null if it is gone; \"damaged\" if its owner\n * record is missing or unreadable (turns are renamed into place and aside\n * whole, with their owner record written durably). Any other read error is\n * thrown: it says nothing about the turn. `done` is read before `held`,\n * which every writer creates first, so a turn read as done is never misread\n * as void.\n */\nasync function readTurn(directory: string, slot: number): Promise<TurnState | \"damaged\" | null> {\n const path = join(directory, String(slot));\n let text: string;\n try {\n text = await readFile(join(path, \"owner.json\"), \"utf8\");\n } catch (error) {\n if (!isErrno(error, \"ENOENT\") && !isErrno(error, \"ENOTDIR\")) throw error;\n return await exists(path) ? \"damaged\" : null;\n }\n let owner: { pid?: unknown; token?: unknown; after?: unknown } | null;\n try {\n owner = JSON.parse(text) as typeof owner;\n } catch {\n return \"damaged\";\n }\n if (owner === null || typeof owner !== \"object\" || typeof owner.token !== \"string\" || typeof owner.pid !== \"number\") {\n return \"damaged\";\n }\n const done = await exists(join(path, `${owner.token}.done`));\n const held = await exists(join(path, `${owner.token}.held`));\n return {\n slot,\n token: owner.token,\n pid: owner.pid,\n after: typeof owner.after === \"string\" ? owner.after : null,\n held,\n done,\n };\n}\n\n/**\n * Whether turn `slot` is still the granted, finished turn with `token`. False\n * only on definite evidence: it is gone, or holds another token. Throws if it\n * cannot be read, or is damaged, so the caller leaves its own turn undecided.\n */\nasync function isFinishedTurn(directory: string, slot: number, token: string): Promise<boolean> {\n const turn = await readTurn(directory, slot);\n if (turn === \"damaged\") throw new Error(`Turn ${slot} of the turn lock ${directory} is unreadable.`);\n return turn !== null && turn.token === token && turn.held && turn.done;\n}\n\n/**\n * Publishes the turn after `latest` and claims it. Null if another process\n * published that number first, or the turn is void. If a step after\n * publication fails, the turn is handed to settleOwnTurn and the error thrown.\n */\nasync function takeTurn(profile: string, directory: string, latest: TurnState): Promise<Turn | null> {\n const token = randomUUID();\n const slot = latest.slot + 1;\n const path = join(directory, String(slot));\n const owner = { pid: process.pid, createdAt: new Date().toISOString(), token, after: latest.token };\n let published = false;\n try {\n published = await publishDirectory(\n join(directory, `.stage-${process.pid}-${token}`),\n path,\n { \"owner.json\": `${JSON.stringify(owner, null, 2)}\\n` },\n () => waitForTestBarrier(TEST_LOCK_TURN_PUBLISH_BARRIER_DIR, profile),\n );\n if (published && await isFinishedTurn(directory, latest.slot, latest.token) && await markTurn(path, token, \"held\")) {\n return { directory, slot, token };\n }\n if (published) await markTurn(path, token, \"done\");\n return null;\n } catch (error) {\n if (published) settleOwnTurn(directory, slot, token);\n throw error;\n }\n}\n\n/**\n * Finishes the turn of a process that is gone (or one this process gave up).\n * A turn its creator never got to grant is granted first if the turn before\n * it is still the one its creator read (the check the creator would have\n * made; that turn cannot have been removed, since that needs this turn\n * done), and left void only if it definitely is not.\n */\nasync function settleAbandonedTurn(directory: string, abandoned: TurnState): Promise<void> {\n const path = join(directory, String(abandoned.slot));\n if (!abandoned.held && abandoned.after !== null &&\n await isFinishedTurn(directory, abandoned.slot - 1, abandoned.after)) {\n await markTurn(path, abandoned.token, \"held\");\n }\n await markTurn(path, abandoned.token, \"done\");\n}\n\n/**\n * Settles a turn this process published but could not grant or finish (a\n * marker write or a read failed). Other processes wait on this live PID, so\n * it is retried in the background until it succeeds or the turn is settled\n * otherwise (by this process's next acquisition, or by another process once\n * this one has exited). The timer does not keep the process alive.\n */\nfunction settleOwnTurn(directory: string, slot: number, token: string, retries = SETTLE_RETRIES): void {\n relinquishedTurns.add(token);\n void (async () => {\n try {\n const turn = await readTurn(directory, slot);\n if (turn !== null && turn !== \"damaged\" && turn.token === token && !turn.done) await settleAbandonedTurn(directory, turn);\n relinquishedTurns.delete(token);\n } catch {\n // Still relinquished: this process's next acquisition settles it too.\n if (retries > 0) setTimeout(() => settleOwnTurn(directory, slot, token, retries - 1), SETTLE_RETRY_MS).unref();\n }\n })();\n}\n\n/**\n * Creates `<token>.<kind>` in a turn directory; false if the directory is\n * gone. Other failures (a full disk, a permission error) are retried a few\n * times, then thrown.\n */\nasync function markTurn(path: string, token: string, kind: \"held\" | \"done\"): Promise<boolean> {\n for (let attempt = 0; ; attempt++) {\n try {\n await writeFile(join(path, `${token}.${kind}`), \"\", { mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n return true;\n } catch (error) {\n if (isErrno(error, \"EEXIST\")) return true;\n if (isErrno(error, \"ENOENT\")) return false;\n if (attempt >= MARKER_RETRY_DELAYS_MS.length) throw error;\n await sleep(MARKER_RETRY_DELAYS_MS[attempt]!);\n }\n }\n}\n\n/** Creates the turn directory with a granted, finished turn 0, unless another process did. */\nasync function createTurnDirectory(directory: string): Promise<void> {\n const token = randomUUID();\n const owner = { pid: process.pid, createdAt: new Date().toISOString(), token, after: null };\n await publishDirectory(join(dirname(directory), `.stage-${basename(directory)}-${process.pid}-${token}`), directory, {\n \"0/owner.json\": `${JSON.stringify(owner, null, 2)}\\n`,\n [`0/${token}.held`]: \"\",\n [`0/${token}.done`]: \"\",\n });\n}\n\n/**\n * Writes `files` (durably, when not empty) into a new staging directory and\n * renames it to `target`. False if `target` already exists (or the turn\n * directory is gone); the caller starts over. Nothing else removes a live\n * process's staging directory (see collectTurns), so `target` never appears\n * incomplete.\n */\nasync function publishDirectory(\n stage: string,\n target: string,\n files: Readonly<Record<string, string>>,\n beforeRename?: () => Promise<void>,\n): Promise<boolean> {\n try {\n for (const [name, contents] of Object.entries(files)) {\n await mkdir(dirname(join(stage, name)), { recursive: true, mode: PRIVATE_DIR_MODE });\n await writeFileDurably(join(stage, name), contents);\n }\n await beforeRename?.();\n await rename(stage, target);\n return true;\n } catch (error) {\n // ENOTEMPTY/EEXIST: `target` exists, though it may be gone again by now.\n // Windows reports an existing target directory as EPERM.\n if ([\"ENOTEMPTY\", \"EEXIST\", \"ENOENT\"].some((code) => isErrno(error, code)) || await exists(target)) return false;\n throw error;\n } finally {\n await rm(stage, { recursive: true, force: true }).catch(() => undefined);\n }\n}\n\n/**\n * Finishes this process's turn. If `done` cannot be written even after\n * retries, the critical section is still over and its writes stand: the turn\n * is handed to settleOwnTurn rather than failing the caller.\n */\nasync function releaseTurn(profile: string, turn: Turn): Promise<void> {\n try {\n await markTurn(join(turn.directory, String(turn.slot)), turn.token, \"done\");\n } catch {\n settleOwnTurn(turn.directory, turn.slot, turn.token);\n return;\n }\n await collectTurns(profile, turn).catch(() => undefined);\n}\n\n/**\n * Leftovers in a turn directory whose writer is gone: trash (a removed turn\n * renamed aside, garbage from then on), and staging directories and\n * deletion-record temporaries named after their writer's PID.\n */\nfunction isAbandonedTurnEntry(name: string): boolean {\n if (name.startsWith(\".trash-\")) return true;\n const writer = /^\\.(?:stage|deleted\\.json)[-.]([0-9]+)[-.]/.exec(name)?.[1];\n return writer !== undefined && !isProcessAlive(Number(writer));\n}\n\n/** A turn directory's staging directory left beside it by a process that is gone. */\nfunction isAbandonedTurnDirectoryStage(name: string): boolean {\n const writer = /^\\.stage-.+-([0-9]+)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.exec(name)?.[1];\n return writer !== undefined && !isProcessAlive(Number(writer));\n}\n\n/**\n * Removes the turns before `turn`, which just finished: void turns, and\n * granted ones oldest first, each once no older turn is left and the next is\n * granted and done (see acquireTurn). A turn is renamed aside before it is\n * deleted, so its number is never an empty directory. A turn that is damaged\n * or cannot be read is left alone, and a read error stops the collection.\n * Leftovers of crashed processes go too, judged by PID, never by age:\n * removing a paused process's staging directory could publish an incomplete\n * turn.\n */\nasync function collectTurns(profile: string, turn: Turn): Promise<void> {\n for (const [directory, abandoned] of [\n [turn.directory, isAbandonedTurnEntry],\n [dirname(turn.directory), isAbandonedTurnDirectoryStage],\n ] as const) {\n for (const name of (await readdir(directory)).filter(abandoned)) {\n await rm(join(directory, name), { recursive: true, force: true }).catch(() => undefined);\n }\n }\n const older = (await readdir(turn.directory)).filter((name) => TURN.test(name)).map(Number)\n .filter((slot) => slot < turn.slot)\n .sort((left, right) => left - right);\n for (const slot of older) {\n const candidate = await readTurn(turn.directory, slot);\n if (candidate === null || candidate === \"damaged\" || !candidate.done) continue;\n if (candidate.held) {\n if (await exists(join(turn.directory, String(slot - 1)))) continue;\n const next = await readTurn(turn.directory, slot + 1);\n if (next === null || next === \"damaged\" || !next.held || !next.done) continue;\n }\n await waitForTestBarrier(TEST_LOCK_TURN_COLLECT_BARRIER_DIR, profile);\n const trash = join(turn.directory, `.trash-${randomUUID()}`);\n if (await rename(join(turn.directory, String(slot)), trash).then(() => true, () => false)) {\n await rm(trash, { recursive: true, force: true }).catch(() => undefined);\n }\n }\n}\n\n/**\n * One attempt to take `.lock`, made while holding a turn. Nothing here\n * replaces an existing path:\n *\n * 1. `mkdir(.lock)` (never recursive) is exclusive, and is the primitive\n * older releases use too, so they exclude each other.\n * 2. Ownership is published by `link`ing a fully written owner file (staged\n * beside `.lock`, on the same filesystem) to `.lock/owner.json`. `link`\n * fails with EEXIST if an owner exists, and with ENOENT if the directory\n * was removed meanwhile (an aged ownerless-lock reclaim by an older\n * release). Only a successful link holds the lock; on either failure\n * nothing is released, since nothing was acquired, and the caller retries.\n * On a filesystem without hard links (FAT/exFAT, some SMB mounts) the\n * owner file is created in place with an exclusive create instead, with\n * the same EEXIST/ENOENT outcomes. A reader may then briefly see it\n * incomplete; every release treats an owner file it cannot parse as a\n * held lock, and this release removes one only once it has aged (see\n * isAbandonedOwner).\n *\n * A profile deletion removes the profile directory once it has released its\n * lock, so `mkdir(.lock)` can see ENOENT; the directory is recreated (0700)\n * and the caller retries within its deadline, as for a first write to a new\n * profile.\n *\n * Only one owner.json can exist at the lock path, and it is removed only by\n * its holder's release or by recovery of an abandoned holder, so at most one\n * process holds the lock. Returns false when the lock is not acquired.\n */\nasync function publishProfileLock(profile: string, lockPath: string, token: string, requireProfile: boolean): Promise<boolean> {\n try {\n await mkdir(lockPath, { mode: PRIVATE_DIR_MODE });\n } catch (error) {\n if (isErrno(error, \"EEXIST\")) return false;\n if (!isErrno(error, \"ENOENT\")) throw error;\n // With requireProfile only an older release's deletion (which takes no turn) gets here.\n if (requireProfile) throw new ProfileDeletedError(profile);\n await mkdir(profilePath(profile), { recursive: true, mode: PRIVATE_DIR_MODE });\n return false;\n }\n await waitForTestBarrier(TEST_LOCK_PUBLISH_BARRIER_DIR, profile);\n const ownerPath = join(lockPath, \"owner.json\");\n const staged = join(dirname(lockPath), `.lock-owner-${token}.tmp`);\n const owner = `${JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString(), token }, null, 2)}\\n`;\n try {\n await writeFile(staged, owner, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n try {\n await link(staged, ownerPath);\n } catch (error) {\n if (!lacksHardLinks(error)) throw error;\n await writeFile(ownerPath, owner, { encoding: \"utf8\", mode: PRIVATE_FILE_MODE, flag: \"wx\" });\n }\n return true;\n } catch (error) {\n if (isErrno(error, \"EEXIST\") || isErrno(error, \"ENOENT\")) return false;\n // Do not leave an ownerless lock behind for others to wait out. rmdir\n // removes only an empty directory; anyone who created it after ours went\n // away sees ENOENT on link and retries.\n await rmdir(lockPath).catch(() => undefined);\n throw error;\n } finally {\n await rm(staged, { force: true }).catch(() => undefined);\n }\n}\n\n/**\n * Errors `link` reports on a filesystem without hard links: EPERM (Linux\n * FAT/exFAT), ENOTSUP/EOPNOTSUPP (macOS FAT/exFAT, SMB), ENOSYS, EISDIR\n * (libuv's code for Windows' ERROR_INVALID_FUNCTION on FAT32), and EMLINK\n * (too many links), for which the same fallback is just as correct.\n */\nconst NO_HARD_LINK_ERRORS = new Set([\"EPERM\", \"ENOTSUP\", \"EOPNOTSUPP\", \"ENOSYS\", \"EISDIR\", \"EMLINK\"]);\n\nfunction lacksHardLinks(error: unknown): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error &&\n NO_HARD_LINK_ERRORS.has(String((error as { code?: unknown }).code));\n}\n\n/**\n * Releases the lock if `.lock/owner.json` is still this acquisition's. No\n * one else can put an owner record there while it exists (owners are only\n * published into a directory their own `mkdir` created, and recovery\n * removes only an abandoned holder's record), so the record read is the one\n * unlinked.\n */\nasync function releaseProfileLock(profile: string, lockPath: string, token: string): Promise<void> {\n const ownerPath = join(lockPath, \"owner.json\");\n const owner = await readJson<{ token?: unknown }>(ownerPath).catch(() => null);\n if (owner?.token !== token) return;\n await rm(ownerPath, { force: true });\n // `.lock` is empty from here until the rmdir; a contender that removes it\n // and creates its own meanwhile is not harmed: rmdir fails on its owner\n // file, or the contender's link sees ENOENT and retries. If a recoverer's\n // claim file is still inside, rmdir fails and that recoverer removes the\n // directory when it drops its claim.\n await waitForTestBarrier(TEST_LOCK_RELEASE_BARRIER_DIR, profile);\n await rmdir(lockPath).catch(() => undefined);\n}\n\n/**\n * Gives process-level contention tests an event-driven witness that a second\n * writer has reached an already-held lock. This deliberately has no effect\n * outside an explicit test environment, and only creates a new signal file\n * beneath TC_HOME; it never changes lock acquisition or release semantics.\n */\nasync function signalTestLockContention(profile: string): Promise<void> {\n if (process.env.NODE_ENV !== \"test\") return;\n\n const configuredPath = process.env[TEST_LOCK_CONTENTION_SIGNAL_PATH];\n const configuredHome = process.env.TC_HOME;\n if (!configuredPath || !configuredHome) return;\n\n const home = resolve(configuredHome);\n const signalPath = resolve(configuredPath);\n const pathFromHome = relative(home, signalPath);\n if (\n pathFromHome === \"\" ||\n pathFromHome === \"..\" ||\n pathFromHome.startsWith(`..${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`) ||\n pathFromHome.startsWith(\"../\") ||\n pathFromHome.startsWith(\"..\\\\\")\n ) {\n return;\n }\n\n await writeFile(signalPath, `${profile}\\n`, { encoding: \"utf8\", flag: \"wx\" })\n .catch(() => undefined);\n}\n\n/**\n * Reclaims a `.lock` with no owner record, while holding a turn. A\n * `.recover-*` claim may contain a live legacy owner's record moved by a\n * no-hard-links recoverer just before it crashed. Restore that record first;\n * only orphaned claims holding dead or malformed records can be removed.\n * Otherwise the directory must be older than the stale threshold: one left\n * by a crash, or by an older release, whose `.stale-*` / `.release-*` claim\n * files are removed too. owner.json is never unlinked, and the directory\n * itself is only `rmdir`ed, which succeeds only while it is empty.\n *\n * Holding a turn, no other process of this release reclaims concurrently.\n * That closes the race in which two reclaimers' age checks let the later one\n * remove a directory a 1.0.0-beta.16-or-older release had just created,\n * which holds the lock from its `mkdir`. That race remains only if a\n * 1.0.0-beta.17 … 1.0.1-beta.4 release reclaims at the same moment, or the\n * older process stays paused between its `mkdir` and its owner write for\n * longer than the stale threshold; recoveryFenced bounds how stale this\n * process's age check can be.\n */\nasync function recoverOwnerlessLock(profile: string, lockPath: string, staleAfterMs: number): Promise<boolean> {\n let aged: boolean;\n try {\n const { mtimeMs } = await stat(lockPath);\n aged = Date.now() - mtimeMs >= staleAfterMs;\n } catch {\n return false;\n }\n const checkedAt = performance.now();\n await waitForTestBarrier(TEST_LOCK_OWNERLESS_BARRIER_DIR, profile);\n try {\n const entries = await readdir(lockPath);\n if (entries.includes(\"owner.json\")) return false;\n const onlyOrphanedClaims = entries.length > 0 && entries.every((entry) => RECOVERY_CLAIM.test(entry));\n if (!onlyOrphanedClaims && (!aged || recoveryFenced(checkedAt, staleAfterMs))) return false;\n for (const name of entries.filter((entry) => RECOVERY_CLAIM.test(entry))) {\n const claimPath = join(lockPath, name);\n if (await hasLiveRecoveryOwner(claimPath)) {\n // The claim keeps the directory in place. Only the original mkdir\n // owner could publish owner.json here; never overwrite that record.\n if (!await exists(join(lockPath, \"owner.json\"))) await rename(claimPath, join(lockPath, \"owner.json\"));\n return false;\n }\n await rm(claimPath, { force: true });\n }\n for (const name of entries.filter((entry) => ABANDONED_CLAIM.test(entry))) {\n await rm(join(lockPath, name), { force: true });\n }\n await rmdir(lockPath);\n } catch {\n return false;\n }\n await removeAgedOwnerFiles(lockPath, staleAfterMs);\n return true;\n}\n\n/** A no-hard-links claim may contain a live owner's record moved before a crash. */\nasync function hasLiveRecoveryOwner(claimPath: string): Promise<boolean> {\n let contents: string;\n try {\n contents = await readFile(claimPath, \"utf8\");\n } catch (error) {\n if (isErrno(error, \"ENOENT\")) return false;\n throw error; // An I/O failure is not evidence that the holder is gone.\n }\n let owner: unknown;\n try {\n owner = JSON.parse(contents);\n } catch {\n return false;\n }\n const pid = typeof owner === \"object\" && owner !== null && \"pid\" in owner ? owner.pid : null;\n return typeof pid === \"number\" && Number.isInteger(pid) && pid > 0 && isProcessAlive(pid);\n}\n\n/**\n * Whether an ownerless-reclaim decision made at `since` (a monotonic\n * timestamp) is too old to act on. The age check is only good for a while:\n * past half the stale threshold the reclaim starts over.\n */\nfunction recoveryFenced(since: number, staleAfterMs: number): boolean {\n return performance.now() - since >= staleAfterMs / 2;\n}\n\n/** Claim files of older releases' stale recovery and (up to 1.0.0-beta.16) release. */\nconst ABANDONED_CLAIM = /^\\.(?:release|stale)-[0-9a-f-]+\\.json$/;\n/**\n * Claim files of this release's stale recovery. Releases up to 1.0.1-beta.4\n * never remove them, which is what makes this recovery safe against them; a\n * recoverer that crashes leaves one that only a release with the turn lock\n * clears (see REFERENCE.md, \"Profile lock\").\n */\nconst RECOVERY_CLAIM = /^\\.recover-[0-9a-f-]+\\.json$/;\n/** Owner files staged by publishProfileLock beside `.lock`. */\nconst STAGED_OWNER = /^\\.lock-owner-[0-9a-f-]+\\.tmp$/;\n/**\n * Removes owner files a crashed acquirer staged beside `.lock`. A live\n * acquirer's staged file exists only for its write and link, so only files\n * older than the stale threshold are removed. Runs after a recovery, never\n * on the uncontended path.\n */\nasync function removeAgedOwnerFiles(lockPath: string, staleAfterMs: number): Promise<void> {\n const directory = dirname(lockPath);\n const names = await readdir(directory).catch(() => []);\n for (const name of names.filter((entry) => STAGED_OWNER.test(entry))) {\n const path = join(directory, name);\n const aged = await stat(path).then(({ mtimeMs }) => Date.now() - mtimeMs >= staleAfterMs, () => false);\n if (aged) await rm(path, { force: true }).catch(() => undefined);\n }\n}\n\n\n/**\n * Removes an abandoned owner record (see isAbandonedOwner) and its `.lock`,\n * while holding a turn, so no other process of this release recovers,\n * reclaims or acquires `.lock` meanwhile.\n *\n * The record is claimed first: hard-linked to `.recover-<uuid>.json`, and the\n * claim compared with the exact bytes read. A record that replaced the\n * observed one is left in place. While the claim is inside `.lock`, the\n * directory cannot be removed and recreated: older releases never remove a\n * `.recover-*` claim (they clean up only their own claim names), and other\n * processes of this release are kept out by the turn lock. So no other owner\n * record can appear in it, and the unlink of owner.json can only remove the\n * claimed, dead record. A live record is never unlinked or moved. `.lock`\n * itself is removed only after this process's claim is unlinked from it,\n * which proves it is still the dead holder's directory; if the claim cannot\n * be made, `.lock` is left alone (it may be a directory a 1.0.0-beta.16-or-\n * older writer just created, which it holds from that `mkdir`). No step\n * depends on how long this process takes.\n *\n * Without hard links (where 1.0.0-beta.17 … 1.0.1-beta.4 cannot run at all),\n * the record is renamed into the claim instead, and put back if it is not\n * the observed one: one a 1.0.0-beta.16-or-older process published after\n * recovering the same lock at the same moment. The claim keeps `.lock` held\n * meanwhile, so no second writer gets in, but if that holder releases\n * between the two renames, the put-back restores a released record, and\n * `.lock` stays held until that PID is gone and the record is 30 s old.\n */\nasync function recoverStaleLock(profile: string, lockPath: string, staleAfterMs: number): Promise<boolean> {\n const ownerPath = join(lockPath, \"owner.json\");\n const observed = await readFile(ownerPath, \"utf8\").catch(() => null);\n if (observed === null) return recoverOwnerlessLock(profile, lockPath, staleAfterMs);\n if (!await isAbandonedOwner(observed, ownerPath, staleAfterMs)) return false;\n\n await waitForTestBarrier(TEST_LOCK_RECOVERY_BARRIER_DIR, profile);\n const claimPath = join(lockPath, `.recover-${randomUUID()}.json`);\n let moved = false;\n try {\n await link(ownerPath, claimPath);\n } catch (error) {\n // Gone or replaced already (another release recovered it): leave `.lock`.\n if (!lacksHardLinks(error)) return false;\n try {\n await rename(ownerPath, claimPath);\n moved = true;\n } catch {\n return false;\n }\n }\n if (moved) await waitForTestBarrier(TEST_LOCK_MOVED_BARRIER_DIR, profile);\n const sameInstance = await readFile(claimPath, \"utf8\").then((claimed) => claimed === observed, () => false);\n await waitForTestBarrier(TEST_LOCK_VERIFIED_BARRIER_DIR, profile);\n if (!sameInstance) {\n if (moved) {\n // No other owner.json can have appeared meanwhile: only a process\n // whose mkdir created this `.lock` publishes one, and it already has.\n await rename(claimPath, ownerPath).catch(() => undefined);\n } else {\n await unlink(claimPath).catch(() => undefined);\n }\n return false;\n }\n if (!moved) await rm(ownerPath, { force: true });\n await waitForTestBarrier(TEST_LOCK_CLAIM_BARRIER_DIR, profile);\n await waitForTestBarrier(TEST_LOCK_CLAIMED_BARRIER_DIR, profile);\n // Drop any claim a crashed recoverer of this release left, then this one.\n for (const name of (await readdir(lockPath).catch(() => [])).filter((entry) => RECOVERY_CLAIM.test(entry))) {\n if (join(lockPath, name) !== claimPath) await rm(join(lockPath, name), { force: true });\n }\n // Empty now, and still the dead holder's directory if this claim was in\n // it: remove it rather than leave an ownerless lock to age out.\n if (await unlink(claimPath).then(() => true, () => false)) await rmdir(lockPath).catch(() => undefined);\n await removeAgedOwnerFiles(lockPath, staleAfterMs);\n return true;\n}\n\n/**\n * Whether an owner record (its exact bytes, read from `ownerPath`) is\n * abandoned: a holder's whose PID is gone, older than the stale threshold;\n * or, if it is not a complete record, a file older than that threshold.\n * Every release publishes complete records (by link or rename) except this\n * one's no-hard-link fallback, which writes in place while holding a turn;\n * so an incomplete record seen while holding a turn was left by a crash.\n */\nasync function isAbandonedOwner(observed: string, ownerPath: string, staleAfterMs: number): Promise<boolean> {\n let owner: unknown;\n try {\n owner = JSON.parse(observed);\n } catch {\n owner = null;\n }\n if (typeof owner === \"object\" && owner !== null && \"pid\" in owner) {\n return isStaleOwner(owner as { pid?: unknown; createdAt?: unknown }, staleAfterMs);\n }\n const modifiedAt = await stat(ownerPath).then(({ mtimeMs }) => mtimeMs, () => Number.NaN);\n return Date.now() - modifiedAt >= staleAfterMs;\n}\n\n/** Test-only rendezvous (NODE_ENV=test and the named barrier directory set). */\nasync function waitForTestBarrier(environmentName: string, profile: string): Promise<void> {\n if (process.env.NODE_ENV !== \"test\") return;\n const barrierDirectory = process.env[environmentName];\n if (!barrierDirectory) return;\n await mkdir(barrierDirectory, { recursive: true });\n const readyPath = join(barrierDirectory, `ready-${process.pid}-${profile}`);\n await writeFile(readyPath, \"ready\\n\", { encoding: \"utf8\", flag: \"wx\" }).catch(() => undefined);\n const releasePath = join(barrierDirectory, \"release\");\n while (true) {\n try {\n await readFile(releasePath, \"utf8\");\n return;\n } catch {\n await sleep(1);\n }\n }\n}\n\nfunction isStaleOwner(\n owner: { pid?: unknown; createdAt?: unknown } | null,\n staleAfterMs: number,\n): boolean {\n const now = Date.now();\n const createdAt = typeof owner?.createdAt === \"string\"\n ? Date.parse(owner.createdAt)\n : Number.NaN;\n\n // Reclaim only a fully published lock whose owner PID is confirmed dead.\n // A lock without an owner record is handled by recoverOwnerlessLock: a\n // process holds the lock only once its owner.json is linked in.\n if (!Number.isFinite(createdAt) || now - createdAt < staleAfterMs) return false;\n if (typeof owner?.pid !== \"number\" || !Number.isInteger(owner.pid) || owner.pid <= 0) {\n return false;\n }\n return !isProcessAlive(owner.pid);\n}\n\n/** Whether `path` exists. Only ENOENT/ENOTDIR mean it does not; other errors are thrown. */\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch (error) {\n if (isErrno(error, \"ENOENT\") || isErrno(error, \"ENOTDIR\")) return false;\n throw error;\n }\n}\n\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return !isErrno(error, \"ESRCH\");\n }\n}\n\nfunction validateProfileName(profile: string): string {\n if (\n !profile ||\n profile === \".\" ||\n profile === \"..\" ||\n profile.includes(\"/\") ||\n profile.includes(\"\\\\\") ||\n profile.includes(\"\\0\")\n ) {\n throw new TypeError(\"Profile names must be non-empty path segments.\");\n }\n return profile;\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error &&\n (error as { code?: unknown }).code === code;\n}\n\nfunction sleep(milliseconds: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\nexport { DEFAULT_PROFILE };\n","import type { z } from \"zod\";\n\nimport type { OperationError, OperationErrorCode } from \"./errors.js\";\n\n/** A stable, cross-surface operation identifier. */\nexport type OperationId = string;\n\n/** JSON Pointer syntax from RFC 6901, including the empty pointer for a root value. */\nexport type JsonPointer = \"\" | `/${string}`;\n\nexport type OperationEffect =\n | \"read\"\n | \"local_write\"\n | \"write\"\n | \"destructive\"\n | \"external\";\n\nexport type TinyCloudPosture =\n | \"owner-openkey\"\n | \"delegate-session\"\n | \"local-owner-key\"\n | \"unauthenticated\";\n\nexport type OperationOperatorType = \"human\" | \"agent\";\n\nexport type SurfaceDisposition =\n | Readonly<{ status: \"required\" }>\n | Readonly<{ status: \"excluded\"; reason: string }>;\n\n/**\n * Safe identity reported with every result. This deliberately excludes keys,\n * tokens, delegations, grants, and operation inputs or outputs.\n */\nexport interface OperationContextSummary {\n readonly profile: string;\n readonly host: string;\n readonly posture: TinyCloudPosture;\n readonly operatorType?: OperationOperatorType;\n readonly principalDid?: string;\n readonly sessionDid?: string;\n readonly ownerDid?: string;\n readonly space?: string;\n}\n\n/**\n * The profile foundation constructs this context for every invocation. The\n * invocation target never supplies an execution context or runtime object.\n */\nexport interface OperationContext {\n readonly summary: OperationContextSummary;\n /** Present for every normal invocation; optional for focused definition tests. */\n readonly runtime?: OperationRuntime;\n}\n\n/**\n * Per-invocation authority that is constructed inside operations. It is never\n * caller supplied and it is deliberately absent from result envelopes.\n */\nexport interface OperationRuntime {\n readonly node: unknown;\n readonly granted: readonly CapabilityRequirement[];\n /** Diagnostics gathered while building the runtime, attached to the result. */\n readonly warnings?: readonly OperationWarning[];\n /**\n * Internal, never projected. Whether the live identity is a local owner key\n * (an explicit key, or a profile `isLocalOwnerProfile` accepts). Set by every\n * runtime this package builds; optional only for focused definition tests.\n */\n readonly localOwner?: boolean;\n /** Internal, never projected: the reasons stored grants were skipped during replay. */\n readonly skippedGrantReasons?: readonly StoredGrantSkipReason[];\n}\n\n/**\n * Why a stored grant was not used. A fixed vocabulary: diagnostics never\n * carry exception text, node responses, URLs or other stored transport data.\n * `unbound`: the record has no valid request binding where one is required;\n * `outside_request`: its signed authority exceeds its binding;\n * `activation_unavailable`: the node could not be reached, timed out, was\n * rate limited or failed (transport, 408, 429, 5xx) while activating it;\n * `activation_unauthenticated`: the node answered 401 while activating it.\n */\nexport const STORED_GRANT_SKIP_REASONS = [\n \"malformed\",\n \"unbound\",\n \"outside_request\",\n \"host_mismatch\",\n \"expired\",\n \"cid_mismatch\",\n \"authority_invalid\",\n \"proof_missing\",\n \"proof_invalid\",\n \"owner_mismatch\",\n \"audience_mismatch\",\n \"resources_mismatch\",\n \"unsupported\",\n \"activation_rejected\",\n \"activation_unavailable\",\n \"activation_unauthenticated\",\n \"invalid\",\n] as const;\n\nexport type StoredGrantSkipReason = typeof STORED_GRANT_SKIP_REASONS[number];\n\n/**\n * The string form of every delegation CID TinyCloud computes: CIDv1, raw\n * codec, BLAKE3-256 multihash, base32. A published `grantCid` also has to be\n * the CID recomputed from the stored authorization bytes.\n */\nexport const DELEGATION_CID_PATTERN = \"^bafkr4i[a-z2-7]{52}$\";\n\n/**\n * A non-fatal diagnostic attached to a result. `STORED_GRANT_SKIPPED`: a\n * stored grant failed validation and gave no authority; `grantCid` is present\n * only when the stored CID is the CID of the stored authorization bytes.\n */\nexport interface OperationWarning {\n readonly code: \"STORED_GRANT_SKIPPED\";\n readonly reason: StoredGrantSkipReason;\n readonly grantCid?: string;\n}\n\n/** Context given to planners and handlers after runtime authentication. */\nexport interface RuntimeOperationContext extends OperationContext {\n readonly runtime: OperationRuntime;\n}\n\nexport type AuthorityPlanningContext = RuntimeOperationContext;\n\n/**\n * Capability details are finalized by the authority/artifacts increment. The\n * kernel intentionally preserves them as canonical operation-owned data.\n */\nexport type CapabilityRequirement = Readonly<Record<string, unknown>>;\n\nexport interface PermissionRequestArtifact {\n readonly requestId: string;\n readonly [key: string]: unknown;\n}\n\nexport interface ApprovalAction {\n readonly kind: \"openkey\";\n readonly requestId: string;\n readonly url?: string;\n readonly fallback: string;\n}\n\nexport interface SetupAction {\n readonly kind: string;\n readonly [key: string]: unknown;\n}\n\nexport interface OperationRef {\n readonly operationId: OperationId;\n readonly operationVersion: number;\n}\n\nexport interface RetryDescriptor extends OperationRef {\n readonly inputDigest: string;\n readonly safeInput?: Readonly<Record<string, unknown>>;\n readonly requiresCallerInput: boolean;\n}\n\nexport interface OperationSensitivity {\n readonly input: readonly JsonPointer[];\n readonly output: readonly JsonPointer[];\n}\n\n/**\n * An inspection operation may read safe local profile state without creating a\n * node or authenticating. An authenticated operation gets a runtime that may\n * sign in. A restored operation gets a runtime built only from the profile's\n * stored session: it never signs in, migrates, takes a profile lock or writes\n * profile state.\n */\nexport type OperationRuntimeRequirement = \"authenticated\" | \"inspection\" | \"restored\";\n\nexport interface OperationExposure {\n readonly cli: SurfaceDisposition;\n readonly mcp: SurfaceDisposition;\n readonly skill: SurfaceDisposition;\n readonly docs: SurfaceDisposition;\n}\n\nexport interface OperationOkResult<O> {\n readonly status: \"ok\";\n readonly operation: OperationRef;\n readonly context: OperationContextSummary;\n readonly output: O;\n readonly warnings?: readonly OperationWarning[];\n}\n\nexport interface OperationAuthorityRequiredResult {\n readonly status: \"authority_required\";\n readonly operation: OperationRef;\n readonly context: OperationContextSummary;\n readonly missing: readonly CapabilityRequirement[];\n readonly request: PermissionRequestArtifact;\n readonly approval: ApprovalAction;\n readonly retry: RetryDescriptor;\n readonly warnings?: readonly OperationWarning[];\n}\n\nexport interface OperationSetupRequiredResult {\n readonly status: \"setup_required\";\n readonly operation: OperationRef;\n readonly context: OperationContextSummary;\n readonly setup: SetupAction;\n readonly retry: RetryDescriptor;\n readonly warnings?: readonly OperationWarning[];\n}\n\nexport interface OperationErrorResult {\n readonly status: \"error\";\n readonly operation: OperationRef;\n readonly context: OperationContextSummary;\n readonly error: OperationError;\n readonly warnings?: readonly OperationWarning[];\n}\n\nexport type OperationResult<O> =\n | OperationOkResult<O>\n | OperationAuthorityRequiredResult\n | OperationSetupRequiredResult\n | OperationErrorResult;\n\n/**\n * Handler outcomes intentionally omit invocation-owned operation, context, and\n * retry metadata. The kernel attaches those values after validation.\n */\nexport type OperationExecutionOutcome<O> =\n | Readonly<{ status: \"ok\"; output: O }>\n | Readonly<{\n status: \"authority_required\";\n missing: readonly CapabilityRequirement[];\n request: PermissionRequestArtifact;\n approval: ApprovalAction;\n requiresCallerInput?: boolean;\n }>\n | Readonly<{\n status: \"setup_required\";\n setup: SetupAction;\n requiresCallerInput?: boolean;\n }>\n | Readonly<{ status: \"error\"; error: OperationError }>;\n\n/**\n * Internal registry material. It is intentionally never re-exported by the\n * package root: projections can execute only by operation id and version.\n */\nexport interface OperationDefinition<I, O> {\n readonly id: OperationId;\n readonly version: 1;\n readonly title: string;\n readonly description: string;\n readonly input: z.ZodType<I>;\n readonly output: z.ZodType<O>;\n readonly effects: readonly OperationEffect[];\n readonly runtime: OperationRuntimeRequirement;\n readonly postures: readonly TinyCloudPosture[];\n readonly exposure: OperationExposure;\n readonly sensitivity: OperationSensitivity;\n /** A definition may give malformed transport artifacts a stable error code. */\n readonly invalidInputErrorCode?: OperationErrorCode;\n /**\n * Response deadline. When set, `invokeOperation` returns a retryable\n * `NODE_UNREACHABLE` if the invocation has not finished within it; work\n * already started is abandoned, not cancelled.\n */\n readonly deadlineMs?: number;\n readonly authority: (\n context: AuthorityPlanningContext,\n input: I,\n ) => Promise<readonly CapabilityRequirement[]>;\n readonly execute: (\n context: OperationContext,\n input: I,\n ) => Promise<OperationExecutionOutcome<O>>;\n}\n\n/**\n * The only caller-controlled invocation settings. `privateKey` is a CLI-only,\n * nonpersistable override; it is deliberately excluded from result metadata,\n * retry descriptors, diagnostics, and all state written by this package.\n */\nexport interface InvocationTarget {\n readonly profile?: string;\n readonly host?: string;\n /**\n * Absolute home directory used for this invocation's TinyCloud profile\n * state. Hosted projections set this per authenticated principal so\n * concurrent tenants never share process-global TC_HOME state.\n */\n readonly stateRoot?: string;\n readonly allowOwnerProfile?: boolean;\n readonly privateKey?: string;\n}\n\n/**\n * Copy only the identity fields allowed in a public result. Keeping this\n * projection centralized prevents a profile/runtime implementation from\n * accidentally smuggling execution material into an envelope.\n */\nexport function safeOperationContextSummary(\n summary: OperationContextSummary,\n): OperationContextSummary {\n return {\n profile: summary.profile,\n host: summary.host,\n posture: summary.posture,\n ...(summary.operatorType === undefined\n ? {}\n : { operatorType: summary.operatorType }),\n ...(summary.principalDid === undefined\n ? {}\n : { principalDid: summary.principalDid }),\n ...(summary.sessionDid === undefined ? {} : { sessionDid: summary.sessionDid }),\n ...(summary.ownerDid === undefined ? {} : { ownerDid: summary.ownerDid }),\n ...(summary.space === undefined ? {} : { space: summary.space }),\n };\n}\n","// Namespace-shaped so modules that bundle this one stay compatible with\n// lightweight node-sdk test doubles.\nimport * as nodeSdk from \"@tinycloud/node-sdk\";\n\nimport { OperationInvocationError, operationError } from \"./errors.js\";\n\nconst DEFAULT_SECRETS_SPACE = \"secrets\";\nconst SECRET_NAME_RE = /^[A-Z][A-Z0-9_]*$/;\nconst RESERVED_SECRET_SCOPES = new Set([\"default\", \"global\"]);\n\nexport interface SecretsGetInput {\n readonly name: string;\n readonly scope?: string;\n readonly space?: string;\n}\n\nexport interface SecretReference {\n readonly name: string;\n readonly scope?: string;\n readonly space: string;\n readonly vaultKey: string;\n readonly permissionPath: string;\n}\n\nexport function normalizeSecretsGetInput(\n input: SecretsGetInput,\n): SecretsGetInput {\n const reference = resolveSecretReference(input);\n return {\n name: reference.name,\n ...(reference.scope === undefined ? {} : { scope: reference.scope }),\n // Omission is meaningful: the CLI's default is the literal `secrets`\n // space, while an explicitly supplied short name is resolved later against\n // the authenticated identity.\n ...(input.space === undefined ? {} : { space: reference.space }),\n };\n}\n\n/** Resolves the one canonical backing key/path used by planning and setup. */\nexport function resolveSecretReference(\n input: SecretsGetInput,\n): SecretReference {\n const name = input.name.trim();\n if (!SECRET_NAME_RE.test(name)) {\n throw invalidSecretInput();\n }\n\n const scope = canonicalizeSecretScope(input.scope);\n const space = normalizeSecretsSpace(input.space);\n const vaultKey = scope === undefined\n ? `secrets/${name}`\n : `secrets/scoped/${scope}/${name}`;\n\n return {\n name,\n ...(scope === undefined ? {} : { scope }),\n space,\n vaultKey,\n permissionPath: `vault/${vaultKey}`,\n };\n}\n\n/**\n * Resolve the operation's space against the authenticated identity. The\n * public short-name contract remains `secrets`, while an authenticated\n * operation uses its owner-exact URI for the actual read boundary.\n */\nexport function resolveSecretReferenceForOperation(\n input: SecretsGetInput,\n node: unknown,\n ownerSpace?: string,\n): SecretReference {\n const reference = resolveSecretReference(input);\n if (input.space === undefined && ownerSpace === undefined) return reference;\n return {\n ...reference,\n space: resolveOperationSpace(reference.space, node, ownerSpace),\n };\n}\n\n/** Creates the one owner-aware resolver shared by operation matching paths. */\nexport function operationSpaceResolver(\n node: unknown,\n ownerSpace?: string,\n): (space: string) => string {\n return (space) => resolveOperationSpace(space, node, ownerSpace);\n}\n\nfunction resolveOperationSpace(space: string, node: unknown, ownerSpace?: string): string {\n if (space.startsWith(\"tinycloud:\")) return canonicalizeSpaceUri(space);\n\n const ownerSpaceId = ownerSpace === undefined ? undefined : ownedSpaceForName(ownerSpace, space);\n if (ownerSpaceId !== undefined) return canonicalizeSpaceUri(ownerSpaceId);\n\n const candidate = node as {\n resolveOwnedSpace?: (spaceName: string) => unknown;\n spaceId?: unknown;\n address?: unknown;\n did?: unknown;\n };\n try {\n const resolved = candidate.resolveOwnedSpace?.(space);\n if (typeof resolved === \"string\" && resolved.length > 0) {\n return canonicalizeSpaceUri(resolved);\n }\n } catch {\n // Continue to the identity-derived resolver below.\n }\n\n // A restored delegate session carries the owner's primary space even though\n // node.did is the delegate/session principal. This is the same owner\n // identity used by the CLI space resolver.\n if (typeof candidate.spaceId === \"string\") {\n const resolved = ownedSpaceForName(candidate.spaceId, space);\n if (resolved !== undefined) return canonicalizeSpaceUri(resolved);\n }\n\n const did = typeof candidate.did === \"string\" ? candidate.did : undefined;\n const pkh = did === undefined ? null : nodeSdk.parsePkhDid(did);\n if (pkh === null) {\n throw invalidSecretInput();\n }\n return nodeSdk.makePkhSpaceId(pkh.address, pkh.chainId, space);\n}\n\nfunction ownedSpaceForName(ownerSpace: string, name: string): string | undefined {\n const parsed = nodeSdk.parseSpaceUri(ownerSpace);\n if (parsed === null) return undefined;\n try {\n const pkh = nodeSdk.parsePkhDid(parsed.owner);\n return pkh === null ? undefined : nodeSdk.makePkhSpaceId(pkh.address, pkh.chainId, name);\n } catch {\n return undefined;\n }\n}\n\nfunction canonicalizeSpaceUri(space: string): string {\n const parts = space.split(\":\");\n const name = parts.at(-1);\n if (parts.length < 3 || name === undefined || name === \"\") {\n throw invalidSecretInput();\n }\n // EIP-155 address casing is interchangeable only in the repository's\n // anchored PKH space form. Other TinyCloud space/DID syntaxes are opaque\n // method-specific identifiers and must remain byte-for-byte unchanged.\n const pkh = space.match(\n /^tinycloud:pkh:eip155:(\\d+):(0x[0-9a-fA-F]{40}):([^:]+)$/,\n );\n if (pkh !== null) {\n return `tinycloud:pkh:eip155:${pkh[1]}:${nodeSdk.canonicalizeAddress(pkh[2]!).toLowerCase()}:${pkh[3]}`;\n }\n return space;\n}\n\n/**\n * The operations scope canonicalizer: trims, lowercases and folds every other\n * character to `-`. Empty means unscoped; `default`/`global` are refused.\n */\nexport function canonicalizeSecretScope(scope: string | undefined): string | undefined {\n if (scope === undefined || scope === \"\") return undefined;\n\n const trimmed = scope.trim();\n if (trimmed === \"\") throw invalidSecretInput();\n\n const canonical = trimmed\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n if (canonical === \"\" || RESERVED_SECRET_SCOPES.has(canonical)) {\n throw invalidSecretInput();\n }\n return canonical;\n}\n\nfunction normalizeSecretsSpace(space: string | undefined): string {\n if (space === undefined || space === \"\") return DEFAULT_SECRETS_SPACE;\n\n if (space.startsWith(\"tinycloud:\")) {\n const parts = space.split(\":\");\n if (parts.length < 3 || parts.at(-1) === undefined || parts.at(-1) === \"\") {\n throw invalidSecretInput();\n }\n return `tinycloud:${parts.slice(1, -1).join(\":\")}:${parts.at(-1)}`;\n }\n\n if (!/^[A-Za-z0-9_-]+$/.test(space)) throw invalidSecretInput();\n return space;\n}\n\nfunction invalidSecretInput(): OperationInvocationError {\n return new OperationInvocationError(\n operationError(\"INPUT_INVALID\", \"The secret reference is invalid.\"),\n );\n}\n","export const OPERATION_ERROR_CODES = [\n \"INPUT_INVALID\",\n \"OPERATION_NOT_FOUND\",\n \"OPERATION_VERSION_UNSUPPORTED\",\n \"PROFILE_NOT_FOUND\",\n \"PROFILE_POSTURE_NOT_ALLOWED\",\n \"PROFILE_OWNER_OPT_IN_REQUIRED\",\n \"PROFILE_MIGRATION_REQUIRED\",\n \"AUTH_REQUIRED\",\n \"PERMISSION_DENIED\",\n \"SESSION_NOT_FOUND\",\n \"PERMISSION_HINT_INVALID\",\n \"DELEGATION_ARTIFACT_INVALID\",\n \"DELEGATION_EXPIRED\",\n \"DELEGATION_AUDIENCE_MISMATCH\",\n \"DELEGATION_HOST_MISMATCH\",\n \"DELEGATION_REJECTED\",\n \"ENCRYPTION_NETWORK_UNRESOLVED\",\n \"NODE_UNREACHABLE\",\n \"NODE_ERROR\",\n \"STORAGE_QUOTA_EXCEEDED\",\n \"KV_NOT_FOUND\",\n \"KV_PRECONDITION_FAILED\",\n \"KV_CONFLICT\",\n \"KV_RESPONSE_TOO_LARGE\",\n \"SQL_QUERY_INVALID\",\n \"SQL_EXECUTION_FAILED\",\n \"SQL_RESULT_LIMIT_EXCEEDED\",\n \"SQL_VALUE_UNSAFE\",\n \"SECRET_READ_FAILED\",\n \"SECRET_DECRYPT_FAILED\",\n \"OUTPUT_INVALID\",\n \"INTERNAL_ERROR\",\n] as const;\n\nexport type OperationErrorCode = (typeof OPERATION_ERROR_CODES)[number];\n\nexport interface OperationError {\n readonly code: OperationErrorCode;\n readonly message: string;\n readonly retryable: boolean;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\nexport function operationError(\n code: OperationErrorCode,\n message: string,\n options: Readonly<{\n retryable?: boolean;\n details?: Readonly<Record<string, unknown>>;\n }> = {},\n): OperationError {\n return {\n code,\n message,\n retryable: options.retryable ?? false,\n ...(options.details === undefined ? {} : { details: options.details }),\n };\n}\n\nconst MANAGE_STORAGE = \"Do not retry: the owner must free up space or upgrade at https://account.tinycloud.xyz/billing.\";\n\n/**\n * A write the node refused because the owner's TinyCloud storage is full\n * (SDK `STORAGE_QUOTA_EXCEEDED`, HTTP 402) or too small for this write\n * (`STORAGE_LIMIT_REACHED`, HTTP 413). Nothing was written, so the outcome is\n * known, and it stays refused until the owner acts, so it is never retryable.\n * The SDK's account totals travel as details; per-space numbers never do.\n */\nexport function storageFullOperationError(error: unknown): OperationError | undefined {\n if (typeof error !== \"object\" || error === null) return undefined;\n const { code, meta } = error as { code?: unknown; meta?: unknown };\n if (code !== \"STORAGE_QUOTA_EXCEEDED\" && code !== \"STORAGE_LIMIT_REACHED\") return undefined;\n const account = typeof meta === \"object\" && meta !== null ? (meta as { account?: unknown }).account : undefined;\n return operationError(\n \"STORAGE_QUOTA_EXCEEDED\",\n code === \"STORAGE_LIMIT_REACHED\"\n ? `This write is larger than the TinyCloud storage left, so nothing was written. Reading still works. ${MANAGE_STORAGE}`\n : `TinyCloud storage is full, so nothing was written. Reading still works. ${MANAGE_STORAGE}`,\n { retryable: false, ...(account === undefined ? {} : { details: { account } }) },\n );\n}\n\n/**\n * Internal operations and profile resolution use this for expected failures.\n * Generic exceptions are never exposed at the projection boundary.\n */\nexport class OperationInvocationError extends Error {\n public readonly operationError: OperationError;\n\n constructor(operationError: OperationError) {\n super(operationError.message);\n this.name = \"OperationInvocationError\";\n this.operationError = operationError;\n }\n}\n\nexport function isOperationErrorCode(value: unknown): value is OperationErrorCode {\n return typeof value === \"string\" && OPERATION_ERROR_CODES.includes(value as OperationErrorCode);\n}\n\nexport function internalOperationError(): OperationError {\n return operationError(\n \"INTERNAL_ERROR\",\n \"The operation could not be completed.\",\n );\n}\n\nexport function sanitizeThrownOperationError(error: unknown): OperationError {\n if (error instanceof OperationInvocationError) {\n return sanitizeOperationError(error.operationError);\n }\n\n return internalOperationError();\n}\n\nexport function sanitizeOperationError(error: unknown): OperationError {\n if (\n typeof error !== \"object\" ||\n error === null ||\n !isOperationErrorCode((error as { code?: unknown }).code) ||\n typeof (error as { message?: unknown }).message !== \"string\" ||\n typeof (error as { retryable?: unknown }).retryable !== \"boolean\"\n ) {\n return internalOperationError();\n }\n\n const candidate = error as OperationError;\n return operationError(candidate.code, candidate.message, {\n retryable: candidate.retryable,\n ...(candidate.details === undefined ? {} : { details: candidate.details }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAIA,QAAI,IAAI;AACR,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AAgBZ,WAAO,UAAU,SAAU,KAAK,SAAS;AACvC,gBAAU,WAAW,CAAC;AACtB,UAAI,OAAO,OAAO;AAClB,UAAI,SAAS,YAAY,IAAI,SAAS,GAAG;AACvC,eAAO,MAAM,GAAG;AAAA,MAClB,WAAW,SAAS,YAAY,SAAS,GAAG,GAAG;AAC7C,eAAO,QAAQ,OAAO,QAAQ,GAAG,IAAI,SAAS,GAAG;AAAA,MACnD;AACA,YAAM,IAAI;AAAA,QACR,0DACE,KAAK,UAAU,GAAG;AAAA,MACtB;AAAA,IACF;AAUA,aAAS,MAAM,KAAK;AAClB,YAAM,OAAO,GAAG;AAChB,UAAI,IAAI,SAAS,KAAK;AACpB;A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AAC5E;","names":["ms","crypto","crypto","isLE","_32n","length","join","length","length","_0n","_1n","_0n","_1n","Fp","Fp","_1n","isLE","_0n","_1n","_0n","_1n","base","wbits","isLE","_0n","Fp","Fn","_0n","_1n","_2n","_8n","Fp","Fn","uvRatio","p","randomBytes","adjustScalarBytes","eddsa","_0n","_1n","_2n","_3n","_5n","_8n","_1n","mod","_0n","encode","length","i","j","decode","encode","decode","encode","decode","decode","decode","equals","link","base","baseCache","equals","base","decode","length","cache","cid","equalBytes","equalBytes","nodeSdk","randomUUID","z","_a","ownership","_a","resolve","z","operationError","join"]}
|