@palbase/backend 39.1.2 → 39.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/_dnt.shims.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/consts.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/kems/dhkemPrimitives/ec.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/utils/noble.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/hash.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/hmac.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/u64.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/sha3.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/utils.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/_arx.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/_poly1305.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/chacha.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/exporterContext.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/mutex.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/recipientContext.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/senderContext.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/cipherSuiteNative.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/kems/dhkemPrimitives/x25519.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/kems/dhkemPrimitives/x448.js","../../../core/src/config.ts","../../../core/src/errors.ts","../../../core/src/platform.ts","../../../core/src/pow.ts","../../../core/src/sealed.ts","../../../core/src/sealed-json.ts","../../../core/src/sealed-keys.ts","../../../core/src/url.ts","../../../core/src/http.ts","../../../core/src/token.ts","../../src/test/api.ts","../../src/test/container.ts","../../src/__tests__/helpers/mock-db.ts","../../src/test/fake-db.ts","../../src/test/with-services.ts"],"sourcesContent":["const dntGlobals = {};\nexport const dntGlobalThis = createMergeProxy(globalThis, dntGlobals);\nfunction createMergeProxy(baseObj, extObj) {\n return new Proxy(baseObj, {\n get(_target, prop, _receiver) {\n if (prop in extObj) {\n return extObj[prop];\n }\n else {\n return baseObj[prop];\n }\n },\n set(_target, prop, value) {\n if (prop in extObj) {\n delete extObj[prop];\n }\n baseObj[prop] = value;\n return true;\n },\n deleteProperty(_target, prop) {\n let success = false;\n if (prop in extObj) {\n delete extObj[prop];\n success = true;\n }\n if (prop in baseObj) {\n delete baseObj[prop];\n success = true;\n }\n return success;\n },\n ownKeys(_target) {\n const baseKeys = Reflect.ownKeys(baseObj);\n const extKeys = Reflect.ownKeys(extObj);\n const extKeysSet = new Set(extKeys);\n return [...baseKeys.filter((k) => !extKeysSet.has(k)), ...extKeys];\n },\n defineProperty(_target, prop, desc) {\n if (prop in extObj) {\n delete extObj[prop];\n }\n Reflect.defineProperty(baseObj, prop, desc);\n return true;\n },\n getOwnPropertyDescriptor(_target, prop) {\n if (prop in extObj) {\n return Reflect.getOwnPropertyDescriptor(extObj, prop);\n }\n else {\n return Reflect.getOwnPropertyDescriptor(baseObj, prop);\n }\n },\n has(_target, prop) {\n return prop in extObj || prop in baseObj;\n },\n });\n}\n","// The input length limit (psk, psk_id, info, exporter_context, ikm).\nexport const INPUT_LENGTH_LIMIT = 8192;\nexport const INFO_LENGTH_LIMIT = 268435456;\n// The minimum length of a PSK.\nexport const MINIMUM_PSK_LENGTH = 32;\n// b\"\"\nexport const EMPTY = /* @__PURE__ */ new Uint8Array(0);\n// Common BigInt constants\nexport const N_0 = 0n;\nexport const N_1 = 1n;\nexport const N_2 = 2n;\nexport const N_7 = 7n;\nexport const N_32 = 32n;\nexport const N_256 = 256n;\nexport const N_0x71 = 0x71n;\nexport const BYTE_TO_BIGINT_256 = /* @__PURE__ */ (() => {\n const out = new Array(256);\n let i = 0;\n let value = 0n;\n while (i < 256) {\n out[i] = value;\n i++;\n value += 1n;\n }\n return out;\n})();\n","import { NativeAlgorithm } from \"../../algorithm.js\";\nimport { BYTE_TO_BIGINT_256, EMPTY } from \"../../consts.js\";\nimport { toArrayBuffer } from \"../../kdfs/hkdf.js\";\nimport { DeriveKeyPairError, DeserializeError, NotSupportedError, SerializeError, } from \"../../errors.js\";\nimport { KemId } from \"../../identifiers.js\";\nimport { KEM_USAGES, LABEL_DKP_PRK } from \"../../interfaces/dhkemPrimitives.js\";\nimport { Bignum } from \"../../utils/bignum.js\";\nimport { base64UrlToBytes, i2Osp } from \"../../utils/misc.js\";\n// b\"candidate\"\n// deno-fmt-ignore\nconst LABEL_CANDIDATE = /* @__PURE__ */ new Uint8Array([\n 99, 97, 110, 100, 105, 100, 97, 116, 101,\n]);\n// the order of the curve being used.\n// deno-fmt-ignore\nconst ORDER_P_256 = /* @__PURE__ */ new Uint8Array([\n 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84,\n 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51,\n]);\n// deno-fmt-ignore\nconst ORDER_P_384 = /* @__PURE__ */ new Uint8Array([\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xc7, 0x63, 0x4d, 0x81, 0xf4, 0x37, 0x2d, 0xdf,\n 0x58, 0x1a, 0x0d, 0xb2, 0x48, 0xb0, 0xa7, 0x7a,\n 0xec, 0xec, 0x19, 0x6a, 0xcc, 0xc5, 0x29, 0x73,\n]);\n// deno-fmt-ignore\nconst ORDER_P_521 = /* @__PURE__ */ new Uint8Array([\n 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xfa, 0x51, 0x86, 0x87, 0x83, 0xbf, 0x2f,\n 0x96, 0x6b, 0x7f, 0xcc, 0x01, 0x48, 0xf7, 0x09,\n 0xa5, 0xd0, 0x3b, 0xb5, 0xc9, 0xb8, 0x89, 0x9c,\n 0x47, 0xae, 0xbb, 0x6f, 0xb7, 0x1e, 0x91, 0x38,\n 0x64, 0x09,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_256 = /* @__PURE__ */ new Uint8Array([\n 48, 65, 2, 1, 0, 48, 19, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 8, 42, 134,\n 72, 206, 61, 3, 1, 7, 4, 39, 48, 37,\n 2, 1, 1, 4, 32,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_384 = /* @__PURE__ */ new Uint8Array([\n 48, 78, 2, 1, 0, 48, 16, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 5, 43, 129,\n 4, 0, 34, 4, 55, 48, 53, 2, 1, 1,\n 4, 48,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_521 = /* @__PURE__ */ new Uint8Array([\n 48, 96, 2, 1, 0, 48, 16, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 5, 43, 129,\n 4, 0, 35, 4, 73, 48, 71, 2, 1, 1,\n 4, 66,\n]);\nconst EC_P_256_PARAMS = {\n p: 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn,\n b: 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn,\n gx: 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296n,\n gy: 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5n,\n coordinateSize: 32,\n};\nconst EC_P_384_PARAMS = {\n p: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffffn,\n b: 0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aefn,\n gx: 0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7n,\n gy: 0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5fn,\n coordinateSize: 48,\n};\nconst EC_P_521_PARAMS = {\n p: (1n << 521n) - 1n,\n b: 0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00n,\n gx: 0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66n,\n gy: 0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650n,\n coordinateSize: 66,\n};\nfunction mod(a, p) {\n const r = a % p;\n return r >= 0n ? r : r + p;\n}\nfunction modPow(base, exponent, p) {\n let result = 1n;\n let b = mod(base, p);\n let e = exponent;\n while (e > 0n) {\n if ((e & 1n) === 1n) {\n result = mod(result * b, p);\n }\n b = mod(b * b, p);\n e >>= 1n;\n }\n return result;\n}\nfunction modSqrt(rhs, p) {\n // P-256/P-384/P-521 primes satisfy p % 4 == 3.\n const y = modPow(rhs, (p + 1n) >> 2n, p);\n if (mod(y * y, p) !== mod(rhs, p)) {\n throw new Error(\"Invalid ECDH point\");\n }\n return y;\n}\nfunction bytesToBigInt(bytes) {\n let v = 0n;\n for (const b of bytes) {\n v = (v << 8n) | BYTE_TO_BIGINT_256[b];\n }\n return v;\n}\nfunction bigIntToBytes(v, len) {\n const out = new Uint8Array(len);\n let n = v;\n for (let i = len - 1; i >= 0; i--) {\n out[i] = Number(n & 0xffn);\n n >>= 8n;\n }\n if (n !== 0n) {\n throw new Error(\"Invalid coordinate length\");\n }\n return out;\n}\nfunction buildRawUncompressedPublicKey(x, y, coordinateSize) {\n const out = new Uint8Array(1 + coordinateSize * 2);\n out[0] = 0x04;\n out.set(bigIntToBytes(x, coordinateSize), 1);\n out.set(bigIntToBytes(y, coordinateSize), 1 + coordinateSize);\n return out;\n}\nexport class Ec extends NativeAlgorithm {\n constructor(kem, hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // EC specific arguments for deriving key pair.\n Object.defineProperty(this, \"_order\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_bitmask\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_curveParams\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._hkdf = hkdf;\n switch (kem) {\n case KemId.DhkemP256HkdfSha256:\n this._alg = { name: \"ECDH\", namedCurve: \"P-256\" };\n this._nPk = 65;\n this._nSk = 32;\n this._nDh = 32;\n this._order = ORDER_P_256;\n this._bitmask = 0xFF;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_256;\n this._curveParams = EC_P_256_PARAMS;\n break;\n case KemId.DhkemP384HkdfSha384:\n this._alg = { name: \"ECDH\", namedCurve: \"P-384\" };\n this._nPk = 97;\n this._nSk = 48;\n this._nDh = 48;\n this._order = ORDER_P_384;\n this._bitmask = 0xFF;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_384;\n this._curveParams = EC_P_384_PARAMS;\n break;\n default:\n // case KemId.DhkemP521HkdfSha512:\n this._alg = { name: \"ECDH\", namedCurve: \"P-521\" };\n this._nPk = 133;\n this._nSk = 66;\n this._nDh = 66;\n this._order = ORDER_P_521;\n this._bitmask = 0x01;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_521;\n this._curveParams = EC_P_521_PARAMS;\n break;\n }\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(this._alg, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const rawIkm = toArrayBuffer(ikm);\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n const bn = new Bignum(this._nSk);\n for (let counter = 0; bn.isZero() || !bn.lessThan(this._order); counter++) {\n if (counter > 255) {\n throw new Error(\"Faild to derive a key pair\");\n }\n const bytes = new Uint8Array(await this._hkdf.labeledExpand(dkpPrk, LABEL_CANDIDATE, i2Osp(counter, 1), this._nSk));\n bytes[0] = bytes[0] & this._bitmask;\n bn.set(bytes);\n }\n const sk = await this._deserializePkcs8Key(bn.val());\n bn.reset();\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch {\n try {\n // Firefox fails to export JWK from some imported ECDH private keys.\n return await this._derivePublicKeyWithoutJwkExport(key);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n }\n async dh(sk, pk) {\n try {\n await this._setup();\n const bits = await this._api.deriveBits({\n name: \"ECDH\",\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.crv === \"undefined\" || key.crv !== this._alg.namedCurve) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n async _derivePublicKeyWithoutJwkExport(key) {\n const basePointRaw = buildRawUncompressedPublicKey(this._curveParams.gx, this._curveParams.gy, this._curveParams.coordinateSize);\n const basePoint = await this._api.importKey(\"raw\", basePointRaw.buffer, this._alg, true, []);\n const xBytes = new Uint8Array(await this._api.deriveBits({\n name: \"ECDH\",\n public: basePoint,\n }, key, this._nDh * 8));\n const p = this._curveParams.p;\n const x = bytesToBigInt(xBytes);\n const rhs = mod(modPow(x, 3n, p) - 3n * x + this._curveParams.b, p);\n let y = modSqrt(rhs, p);\n // Canonicalize sign so the encoded point is deterministic.\n if ((y & 1n) === 1n) {\n y = p - y;\n }\n const pubRaw = buildRawUncompressedPublicKey(x, y, this._curveParams.coordinateSize);\n return await this._api.importKey(\"raw\", pubRaw.buffer, this._alg, true, []);\n }\n}\n","// deno-lint-ignore-file no-explicit-any\n/**\n * This file is based on noble-curves (https://github.com/paulmillr/noble-curves).\n *\n * noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-curves/blob/b9d49d2b41d550571a0c5be443ecb62109fa3373/src/utils.ts\n */\n/**\n * Hex, bytes and number utilities.\n * @module\n */\nimport { loadCrypto } from \"./misc.js\";\nimport { N_0 } from \"../consts.js\";\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) && a.constructor.name === \"Uint8Array\");\n}\n/** Asserts something is positive integer. */\nexport function anumber(n, title = \"\") {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >0, got ${n}`);\n }\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(value, length, title = \"\") {\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// ahash function is now imported from ../hash/hash.ts\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error(\"Hash instance has been destroyed\");\n if (checkFinished && instance.finished) {\n throw new Error(\"Hash#digest() has already been called\");\n }\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out, undefined, \"digestInto() output\");\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n// Used in weierstrass, der\nfunction abignumer(n) {\n if (typeof n === \"bigint\") {\n if (!isPosBig(n))\n throw new Error(\"positive bigint expected, got \" + n);\n }\n else\n anumber(n);\n return n;\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Pre-computed buffer for endianness detection */\nconst _endianTestBuffer = /* @__PURE__ */ new Uint32Array([0x11223344]);\nconst _endianTestBytes = /* @__PURE__ */ new Uint8Array(_endianTestBuffer.buffer);\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ _endianTestBytes[0] === 0x44;\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport function swap8IfBE(n) {\n return isLE ? n : byteSwap(n);\n}\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport function swap32IfBE(u) {\n return isLE ? u : byteSwap32(u);\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore: to use toHex\ntypeof Uint8Array.from([]).toHex === \"function\" &&\n // @ts-ignore: to use fromHex\n typeof Uint8Array.fromHex === \"function\")();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, \"0\"));\nconst HEX_TO_BIGINT = /* @__PURE__ */ [\n 0n,\n 1n,\n 2n,\n 3n,\n 4n,\n 5n,\n 6n,\n 7n,\n 8n,\n 9n,\n 10n,\n 11n,\n 12n,\n 13n,\n 14n,\n 15n,\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) {\n abytes(bytes);\n // @ts-ignore: to use toHex\n if (hasHexBuiltin)\n 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// 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 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\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) {\n if (typeof hex !== \"string\") {\n throw new Error(\"hex string expected, got \" + typeof hex);\n }\n // @ts-ignore: to use fromHex\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) {\n throw new Error(\"hex string expected, got unpadded hex of length \" + hl);\n }\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 ' +\n 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 * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== \"string\")\n throw new Error(\"string expected\");\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\nexport function numberToHexUnpadded(num) {\n const hex = abignumer(num).toString(16);\n return hex.length & 1 ? \"0\" + hex : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== \"string\") {\n throw new Error(\"hex string expected, got \" + typeof hex);\n }\n let out = N_0;\n for (let i = 0; i < hex.length; i++) {\n const n = asciiToBase16(hex.charCodeAt(i));\n if (n === undefined) {\n throw new Error('hex string expected, got non-hex character \"' + hex[i] +\n '\" at index ' + i);\n }\n out = (out << 4n) | HEX_TO_BIGINT[n];\n }\n return out; // Big Endian\n}\nexport function numberToBigint(num) {\n anumber(num, \"numberToBigint\");\n let n = num;\n let out = N_0;\n let bit = 1n;\n while (n > 0) {\n if (n % 2 === 1)\n out += bit;\n n = Math.floor(n / 2);\n bit <<= 1n;\n }\n return out;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n anumber(len);\n n = abignumer(n);\n const res = hexToBytes(n.toString(16).padStart(len * 2, \"0\"));\n if (res.length !== len)\n throw new Error(\"number too large\");\n return res;\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\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) {\n return Uint8Array.from(bytes);\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\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/**\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) {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n// Is positive bigint\nfunction isPosBig(n) {\n return typeof n === \"bigint\" && N_0 <= n;\n}\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\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, n, min, max) {\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}\nexport function validateObject(object, fields = {}, optFields = {}) {\n if (!object || typeof object !== \"object\") {\n throw new Error(\"expected valid options object\");\n }\n function checkField(fieldName, expectedType, isOpt) {\n const val = object[fieldName];\n if (isOpt && val === undefined)\n 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 }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n// createHasher function is now exported above with ahash\n// /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\n// export function randomBytes(bytesLength = 32): Uint8Array {\n// const cr = typeof globalThis != null && (globalThis as any).crypto;\n// if (!cr || typeof cr.getRandomValues !== \"function\") {\n// throw new Error(\"crypto.getRandomValues must be defined\");\n// }\n// return cr.getRandomValues(new Uint8Array(bytesLength));\n// }\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport async function randomBytesAsync(bytesLength = 32) {\n const api = await loadCrypto();\n const rnd = new Uint8Array(bytesLength);\n api.getRandomValues(rnd);\n return rnd;\n}\n// 06 09 60 86 48 01 65 03 04 02\nexport function oidNist(suffix) {\n return {\n oid: Uint8Array.from([\n 0x06,\n 0x09,\n 0x60,\n 0x86,\n 0x48,\n 0x01,\n 0x65,\n 0x03,\n 0x04,\n 0x02,\n suffix,\n ]),\n };\n}\n","/**\n * This file is based on noble-curves (https://github.com/paulmillr/noble-curves).\n *\n * noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-curves/blob/b9d49d2b41d550571a0c5be443ecb62109fa3373/src/utils.ts\n */\n/**\n * Hash utilities and type definitions extracted from noble.ts\n * @module\n */\nimport { anumber } from \"../utils/noble.js\";\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== \"function\" || typeof h.create !== \"function\") {\n throw new Error(\"Hash must wrapped by utils.createHasher\");\n }\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\nexport function createHasher(hashCons, info = {}) {\n const hashFn = (msg, opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n const hashC = Object.assign(hashFn, {\n outputLen: tmp.outputLen,\n blockLen: tmp.blockLen,\n create: (opts) => hashCons(opts),\n ...info,\n });\n return Object.freeze(hashC);\n}\n","// deno-lint-ignore-file no-explicit-any\n/**\n * This file is based on noble-hashes (https://github.com/paulmillr/noble-hashes).\n *\n * noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-hashes/blob/2e0c00e1aa134082ba1380bf3afb8b1641f60fed/src/hmac.ts\n */\n/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, clean } from \"../utils/noble.js\";\nimport { ahash } from \"./hash.js\";\nexport class _HMAC {\n constructor(hash, key) {\n Object.defineProperty(this, \"oHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"iHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"blockLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"outputLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"finished\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"destroyed\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n ahash(hash);\n abytes(key, undefined, \"key\");\n this.iHash = hash.create();\n if (typeof this.iHash.update !== \"function\") {\n throw new Error(\"Expected instance of class which extends utils.Hash\");\n }\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n abytes(out, this.outputLen, \"output\");\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new _HMAC(hash, key);\n","/**\n * This file is based on noble-hashes (https://github.com/paulmillr/noble-hashes).\n *\n * noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-hashes/blob/4e358a46d682adfb005ae6314ec999f2513086b9/src/_u64.ts\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 = 0xffffffffn;\nconst _32n = 32n;\nfunction fromBig(n, le = false) {\n if (le) {\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n }\n return {\n h: Number((n >> _32n) & U32_MASK64) | 0,\n l: Number(n & U32_MASK64) | 0,\n };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n const Ah = new Uint32Array(len);\n const 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}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\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(Ah, Al, Bh, Bl) {\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, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig, };\n// prettier-ignore\nconst u64 = {\n fromBig,\n split,\n toBig,\n shrSH,\n shrSL,\n rotrSH,\n rotrSL,\n rotrBH,\n rotrBL,\n rotr32H,\n rotr32L,\n rotlSH,\n rotlSL,\n rotlBH,\n rotlBL,\n add,\n add3L,\n add3H,\n add4L,\n add4H,\n add5H,\n add5L,\n};\nexport default u64;\n","/**\n * This file is based on noble-hashes (https://github.com/paulmillr/noble-hashes).\n *\n * noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-hashes/blob/4e358a46d682adfb005ae6314ec999f2513086b9/src/sha3.ts\n */\n/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from \"./u64.js\";\nimport { abytes, aexists, anumber, aoutput, clean, oidNist, swap32IfBE, u32, } from \"../utils/noble.js\";\nimport { createHasher, } from \"./hash.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = 0n;\nconst _1n = 1n;\nconst _2n = 2n;\nconst _7n = 7n;\nconst _256n = 256n;\nconst _0x71n = 0x71n;\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = []; // no pure annotation: var is always used\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s, rounds = 24, B) {\n if (!B)\n B = new Uint32Array(10);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++) {\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n }\n // for (let x = 0; x < 10; x += 2) {\n // const idx1 = (x + 8) % 10;\n // const idx0 = (x + 2) % 10;\n // const B0 = B[idx0];\n // const B1 = B[idx0 + 1];\n // const Th = rotlH(B0, B1, 1) ^ B[idx1];\n // const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n // for (let y = 0; y < 50; y += 10) {\n // s[x + y] ^= Th;\n // s[x + y + 1] ^= Tl;\n // }\n // }\n { // x=0: idx0=2, idx1=8\n const Th = rotlH(B[2], B[3], 1) ^ B[8];\n const Tl = rotlL(B[2], B[3], 1) ^ B[9];\n s[0] ^= Th;\n s[1] ^= Tl;\n s[10] ^= Th;\n s[11] ^= Tl;\n s[20] ^= Th;\n s[21] ^= Tl;\n s[30] ^= Th;\n s[31] ^= Tl;\n s[40] ^= Th;\n s[41] ^= Tl;\n }\n { // x=2: idx0=4, idx1=0\n const Th = rotlH(B[4], B[5], 1) ^ B[0];\n const Tl = rotlL(B[4], B[5], 1) ^ B[1];\n s[2] ^= Th;\n s[3] ^= Tl;\n s[12] ^= Th;\n s[13] ^= Tl;\n s[22] ^= Th;\n s[23] ^= Tl;\n s[32] ^= Th;\n s[33] ^= Tl;\n s[42] ^= Th;\n s[43] ^= Tl;\n }\n { // x=4: idx0=6, idx1=2\n const Th = rotlH(B[6], B[7], 1) ^ B[2];\n const Tl = rotlL(B[6], B[7], 1) ^ B[3];\n s[4] ^= Th;\n s[5] ^= Tl;\n s[14] ^= Th;\n s[15] ^= Tl;\n s[24] ^= Th;\n s[25] ^= Tl;\n s[34] ^= Th;\n s[35] ^= Tl;\n s[44] ^= Th;\n s[45] ^= Tl;\n }\n { // x=6: idx0=8, idx1=4\n const Th = rotlH(B[8], B[9], 1) ^ B[4];\n const Tl = rotlL(B[8], B[9], 1) ^ B[5];\n s[6] ^= Th;\n s[7] ^= Tl;\n s[16] ^= Th;\n s[17] ^= Tl;\n s[26] ^= Th;\n s[27] ^= Tl;\n s[36] ^= Th;\n s[37] ^= Tl;\n s[46] ^= Th;\n s[47] ^= Tl;\n }\n { // x=8: idx0=0, idx1=6\n const Th = rotlH(B[0], B[1], 1) ^ B[6];\n const Tl = rotlL(B[0], B[1], 1) ^ B[7];\n s[8] ^= Th;\n s[9] ^= Tl;\n s[18] ^= Th;\n s[19] ^= Tl;\n s[28] ^= Th;\n s[29] ^= Tl;\n s[38] ^= Th;\n s[39] ^= Tl;\n s[48] ^= Th;\n s[49] ^= Tl;\n }\n // Rho (ρ) and Pi (π) — fully unrolled\n let curH = s[2];\n let curL = s[3];\n // for (let t = 0; t < 24; t++) {\n // const shift = SHA3_ROTL[t];\n // const Th = rotlH(curH, curL, shift);\n // const Tl = rotlL(curH, curL, shift);\n // const PI = SHA3_PI[t];\n // curH = s[PI];\n // curL = s[PI + 1];\n // s[PI] = Th;\n // s[PI + 1] = Tl;\n // }\n let Th, Tl;\n // t=0: shift=1(S), PI=20\n Th = rotlSH(curH, curL, 1);\n Tl = rotlSL(curH, curL, 1);\n curH = s[20];\n curL = s[21];\n s[20] = Th;\n s[21] = Tl;\n // t=1: shift=3(S), PI=14\n Th = rotlSH(curH, curL, 3);\n Tl = rotlSL(curH, curL, 3);\n curH = s[14];\n curL = s[15];\n s[14] = Th;\n s[15] = Tl;\n // t=2: shift=6(S), PI=22\n Th = rotlSH(curH, curL, 6);\n Tl = rotlSL(curH, curL, 6);\n curH = s[22];\n curL = s[23];\n s[22] = Th;\n s[23] = Tl;\n // t=3: shift=10(S), PI=34\n Th = rotlSH(curH, curL, 10);\n Tl = rotlSL(curH, curL, 10);\n curH = s[34];\n curL = s[35];\n s[34] = Th;\n s[35] = Tl;\n // t=4: shift=15(S), PI=36\n Th = rotlSH(curH, curL, 15);\n Tl = rotlSL(curH, curL, 15);\n curH = s[36];\n curL = s[37];\n s[36] = Th;\n s[37] = Tl;\n // t=5: shift=21(S), PI=6\n Th = rotlSH(curH, curL, 21);\n Tl = rotlSL(curH, curL, 21);\n curH = s[6];\n curL = s[7];\n s[6] = Th;\n s[7] = Tl;\n // t=6: shift=28(S), PI=10\n Th = rotlSH(curH, curL, 28);\n Tl = rotlSL(curH, curL, 28);\n curH = s[10];\n curL = s[11];\n s[10] = Th;\n s[11] = Tl;\n // t=7: shift=36(B), PI=32\n Th = rotlBH(curH, curL, 36);\n Tl = rotlBL(curH, curL, 36);\n curH = s[32];\n curL = s[33];\n s[32] = Th;\n s[33] = Tl;\n // t=8: shift=45(B), PI=16\n Th = rotlBH(curH, curL, 45);\n Tl = rotlBL(curH, curL, 45);\n curH = s[16];\n curL = s[17];\n s[16] = Th;\n s[17] = Tl;\n // t=9: shift=55(B), PI=42\n Th = rotlBH(curH, curL, 55);\n Tl = rotlBL(curH, curL, 55);\n curH = s[42];\n curL = s[43];\n s[42] = Th;\n s[43] = Tl;\n // t=10: shift=2(S), PI=48\n Th = rotlSH(curH, curL, 2);\n Tl = rotlSL(curH, curL, 2);\n curH = s[48];\n curL = s[49];\n s[48] = Th;\n s[49] = Tl;\n // t=11: shift=14(S), PI=8\n Th = rotlSH(curH, curL, 14);\n Tl = rotlSL(curH, curL, 14);\n curH = s[8];\n curL = s[9];\n s[8] = Th;\n s[9] = Tl;\n // t=12: shift=27(S), PI=30\n Th = rotlSH(curH, curL, 27);\n Tl = rotlSL(curH, curL, 27);\n curH = s[30];\n curL = s[31];\n s[30] = Th;\n s[31] = Tl;\n // t=13: shift=41(B), PI=46\n Th = rotlBH(curH, curL, 41);\n Tl = rotlBL(curH, curL, 41);\n curH = s[46];\n curL = s[47];\n s[46] = Th;\n s[47] = Tl;\n // t=14: shift=56(B), PI=38\n Th = rotlBH(curH, curL, 56);\n Tl = rotlBL(curH, curL, 56);\n curH = s[38];\n curL = s[39];\n s[38] = Th;\n s[39] = Tl;\n // t=15: shift=8(S), PI=26\n Th = rotlSH(curH, curL, 8);\n Tl = rotlSL(curH, curL, 8);\n curH = s[26];\n curL = s[27];\n s[26] = Th;\n s[27] = Tl;\n // t=16: shift=25(S), PI=24\n Th = rotlSH(curH, curL, 25);\n Tl = rotlSL(curH, curL, 25);\n curH = s[24];\n curL = s[25];\n s[24] = Th;\n s[25] = Tl;\n // t=17: shift=43(B), PI=4\n Th = rotlBH(curH, curL, 43);\n Tl = rotlBL(curH, curL, 43);\n curH = s[4];\n curL = s[5];\n s[4] = Th;\n s[5] = Tl;\n // t=18: shift=62(B), PI=40\n Th = rotlBH(curH, curL, 62);\n Tl = rotlBL(curH, curL, 62);\n curH = s[40];\n curL = s[41];\n s[40] = Th;\n s[41] = Tl;\n // t=19: shift=18(S), PI=28\n Th = rotlSH(curH, curL, 18);\n Tl = rotlSL(curH, curL, 18);\n curH = s[28];\n curL = s[29];\n s[28] = Th;\n s[29] = Tl;\n // t=20: shift=39(B), PI=44\n Th = rotlBH(curH, curL, 39);\n Tl = rotlBL(curH, curL, 39);\n curH = s[44];\n curL = s[45];\n s[44] = Th;\n s[45] = Tl;\n // t=21: shift=61(B), PI=18\n Th = rotlBH(curH, curL, 61);\n Tl = rotlBL(curH, curL, 61);\n curH = s[18];\n curL = s[19];\n s[18] = Th;\n s[19] = Tl;\n // t=22: shift=20(S), PI=12\n Th = rotlSH(curH, curL, 20);\n Tl = rotlSL(curH, curL, 20);\n curH = s[12];\n curL = s[13];\n s[12] = Th;\n s[13] = Tl;\n // t=23: shift=44(B), PI=2\n Th = rotlBH(curH, curL, 44);\n Tl = rotlBL(curH, curL, 44);\n s[2] = Th;\n s[3] = Tl;\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n B[0] = s[y];\n B[1] = s[y + 1];\n B[2] = s[y + 2];\n B[3] = s[y + 3];\n B[4] = s[y + 4];\n B[5] = s[y + 5];\n B[6] = s[y + 6];\n B[7] = s[y + 7];\n B[8] = s[y + 8];\n B[9] = s[y + 9];\n s[y + 0] ^= ~B[2] & B[4];\n s[y + 1] ^= ~B[3] & B[5];\n s[y + 2] ^= ~B[4] & B[6];\n s[y + 3] ^= ~B[5] & B[7];\n s[y + 4] ^= ~B[6] & B[8];\n s[y + 5] ^= ~B[7] & B[9];\n s[y + 6] ^= ~B[8] & B[0];\n s[y + 7] ^= ~B[9] & B[1];\n s[y + 8] ^= ~B[0] & B[2];\n s[y + 9] ^= ~B[1] & B[3];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n}\n/** Keccak sponge function. */\nexport class Keccak {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n Object.defineProperty(this, \"state\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"pos\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"posOut\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"finished\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"state32\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"destroyed\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"_B\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint32Array(10)\n });\n Object.defineProperty(this, \"blockLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"suffix\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"outputLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"enableXOF\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"rounds\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen, \"outputLen\");\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200)) {\n throw new Error(\"only keccak-f1600 function is supported\");\n }\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n /** Resets instance to initial (empty) state for reuse. */\n reset() {\n this.state.fill(0);\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds, this._B);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n abytes(data);\n return this.updateUnsafe(data);\n }\n /** Like update(), but skips validation. Caller must ensure valid state and input. */\n updateUnsafe(data) {\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n return this.writeIntoUnsafe(out);\n }\n /** Like writeInto(), but skips validation. Caller must ensure valid state and output. */\n writeIntoUnsafe(out) {\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\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) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF) {\n throw new Error(\"XOF is not possible for this instance\");\n }\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error(\"digest() was already called\");\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);\n// /** SHA3-224 hash function. */\n// export const sha3_224: CHash = /* @__PURE__ */ genKeccak(\n// 0x06,\n// 144,\n// 28,\n// /* @__PURE__ */ oidNist(0x07),\n// );\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256 = /* @__PURE__ */ genKeccak(0x06, 136, 32, \n/* @__PURE__ */ oidNist(0x08));\n/** SHA3-384 hash function. */\nexport const sha3_384 = /* @__PURE__ */ genKeccak(0x06, 104, 48, \n/* @__PURE__ */ oidNist(0x09));\n/** SHA3-512 hash function. */\nexport const sha3_512 = /* @__PURE__ */ genKeccak(0x06, 72, 64, \n/* @__PURE__ */ oidNist(0x0a));\n/** keccak-224 hash function. */\nexport const keccak_224 = /* @__PURE__ */ genKeccak(0x01, 144, 28);\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256 = /* @__PURE__ */ genKeccak(0x01, 136, 32);\n/** keccak-384 hash function. */\nexport const keccak_384 = /* @__PURE__ */ genKeccak(0x01, 104, 48);\n/** keccak-512 hash function. */\nexport const keccak_512 = /* @__PURE__ */ genKeccak(0x01, 72, 64);\nconst genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true), info);\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));\n// /** SHAKE128 XOF with 256-bit output (NIST version). */\n// export const shake128_32: CHashXOF<Keccak, ShakeOpts> =\n// /* @__PURE__ */\n// genShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b));\n// /** SHAKE256 XOF with 512-bit output (NIST version). */\n// export const shake256_64: CHashXOF<Keccak, ShakeOpts> =\n// /* @__PURE__ */\n// genShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c));\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/utils.ts\n */\n/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\nimport { abytes, aexists, anumber, aoutput, clean, copyBytes, createView, isLE, numberToBigint, u32, } from \"@hpke/common\";\nexport { abytes, aexists, anumber, aoutput, clean, copyBytes, createView, isLE, u32, };\n/** Asserts something is boolean. */\nexport function abool(b) {\n if (typeof b !== \"boolean\")\n throw new Error(`boolean expected, not ${b}`);\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * @__NO_SIDE_EFFECTS__\n */\n// deno-lint-ignore no-explicit-any\nexport const wrapCipher = (params, constructor) => {\n // deno-lint-ignore no-explicit-any\n function wrappedCipher(key, ...args) {\n // Validate key\n abytes(key, undefined, \"key\");\n // Big-Endian hardware is rare. Just in case someone still decides to run ciphers:\n if (!isLE) {\n throw new Error(\"Non little-endian hardware is not yet supported\");\n }\n // Validate nonce if nonceLength is present\n if (params.nonceLength !== undefined) {\n const nonce = args[0];\n abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, \"nonce\");\n }\n // Validate AAD if tagLength present\n const tagl = params.tagLength;\n if (tagl && args[1] !== undefined)\n abytes(args[1], undefined, \"AAD\");\n const cipher = constructor(key, ...args);\n const checkOutput = (fnLength, output) => {\n if (output !== undefined) {\n if (fnLength !== 2)\n throw new Error(\"cipher output not supported\");\n abytes(output, undefined, \"output\");\n }\n };\n // Create wrapped cipher with validation and single-use encryption\n let called = false;\n const wrCipher = {\n encrypt(data, output) {\n if (called) {\n throw new Error(\"cannot encrypt() twice with same key + nonce\");\n }\n called = true;\n abytes(data);\n checkOutput(cipher.encrypt.length, output);\n return cipher.encrypt(data, output);\n },\n decrypt(data, output) {\n abytes(data);\n if (tagl && data.length < tagl) {\n throw new Error('\"ciphertext\" expected length bigger than tagLength=' + tagl);\n }\n checkOutput(cipher.decrypt.length, output);\n return cipher.decrypt(data, output);\n },\n };\n return wrCipher;\n }\n Object.assign(wrappedCipher, params);\n return wrappedCipher;\n};\nexport function checkOpts(defaults, opts) {\n if (opts == null || typeof opts !== \"object\") {\n throw new Error(\"options must be defined\");\n }\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** Compares 2 uint8array-s in kinda constant time. */\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n */\nexport function getOutput(expectedLength, out, onlyAligned = true) {\n if (out === undefined)\n return new Uint8Array(expectedLength);\n if (out.length !== expectedLength) {\n throw new Error('\"output\" expected Uint8Array of length ' + expectedLength + \", got: \" +\n out.length);\n }\n if (onlyAligned && !isAligned32(out)) {\n throw new Error(\"invalid output, must be aligned\");\n }\n return out;\n}\nexport function u64Lengths(dataLength, aadLength, isLE) {\n abool(isLE);\n const num = new Uint8Array(16);\n const view = createView(num);\n view.setBigUint64(0, numberToBigint(aadLength), isLE);\n view.setBigUint64(8, numberToBigint(dataLength), isLE);\n return num;\n}\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\n// Re-exported from @hpke/common.\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/_arx.ts\n */\n/**\n * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\n\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | cnt(1) | nonce(3)\n chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).\n\n[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/\n[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2\n\n * @module\n */\nimport { abool, abytes, anumber, checkOpts, clean, copyBytes, u32, } from \"./utils.js\";\n// Can't use similar utils.utf8ToBytes, because it uses `TextEncoder` - not available in all envs\nconst _utf8ToBytes = (str) => Uint8Array.from(str.split(\"\").map((c) => c.charCodeAt(0)));\nconst sigma16 = _utf8ToBytes(\"expand 16-byte k\");\nconst sigma32 = _utf8ToBytes(\"expand 32-byte k\");\nconst sigma16_32 = u32(sigma16);\nconst sigma32_32 = u32(sigma32);\n/** Rotate left. */\nexport function rotl(a, b) {\n return (a << b) | (a >>> (32 - b));\n}\n// Is byte array aligned to 4 byte offset (u32)?\nfunction isAligned32(b) {\n return b.byteOffset % 4 === 0;\n}\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\nconst BLOCK_LEN32 = 16;\n// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]\n// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]\nconst MAX_COUNTER = 2 ** 32 - 1;\nconst U32_EMPTY = Uint32Array.of();\nfunction runCipher(core, sigma, key, nonce, data, output, counter, rounds) {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n if (counter >= MAX_COUNTER)\n throw new Error(\"arx: counter overflow\");\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0)\n throw new Error(\"arx: invalid block position\");\n for (let j = 0, posj; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\n/** Creates ARX-like (ChaCha, Salsa) cipher stream from core function. */\nexport function createCipher(core, opts) {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({\n allowShortKeys: false,\n counterLength: 8,\n counterRight: false,\n rounds: 20,\n }, opts);\n if (typeof core !== \"function\")\n throw new Error(\"core must be a function\");\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (key, nonce, data, output, counter = 0) => {\n abytes(key, undefined, \"key\");\n abytes(nonce, undefined, \"nonce\");\n abytes(data, undefined, \"data\");\n const len = data.length;\n if (output === undefined)\n output = new Uint8Array(len);\n abytes(output, undefined, \"output\");\n anumber(counter);\n if (counter < 0 || counter >= MAX_COUNTER) {\n throw new Error(\"arx: counter overflow\");\n }\n if (output.length < len) {\n throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);\n }\n const toClean = [];\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n const l = key.length;\n let k;\n let sigma;\n if (l === 32) {\n toClean.push(k = copyBytes(key));\n sigma = sigma32_32;\n }\n else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n }\n else {\n abytes(key, 32, \"arx key\");\n throw new Error(\"invalid key size\");\n // throw new Error(`\"arx key\" expected Uint8Array of length 32, got length=${l}`);\n }\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Align nonce to 4 bytes\n if (!isAligned32(nonce))\n toClean.push(nonce = copyBytes(nonce));\n const k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24) {\n throw new Error(`arx: extended nonce must be 24 bytes`);\n }\n extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);\n nonce = nonce.subarray(16);\n }\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length) {\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n }\n // Pad counter when nonce is 64 bit\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = u32(nonce);\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n clean(...toClean);\n return output;\n };\n}\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/_poly1305.ts\n */\n/**\n * Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf),\n * [wiki](https://en.wikipedia.org/wiki/Poly1305))\n * is a fast and parallel secret-key message-authentication code suitable for\n * a wide variety of applications. It was standardized in\n * [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439) and is now used in TLS 1.3.\n *\n * Polynomial MACs are not perfect for every situation:\n * they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.\n * See [invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/).\n * To combat invisible salamanders, `hash(key)` can be included in ciphertext,\n * however, this would violate ciphertext indistinguishability:\n * an attacker would know which key was used - so `HKDF(key, i)`\n * could be used instead.\n *\n * Check out [original website](https://cr.yp.to/mac.html).\n * Based on Public Domain [poly1305-donna](https://github.com/floodyberry/poly1305-donna).\n * @module\n */\nimport { abytes, aexists, aoutput, clean, copyBytes, } from \"./utils.js\";\nfunction u8to16(a, i) {\n return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\n}\n// function bytesToNumberLE(bytes: Uint8Array): bigint {\n// return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n// }\n// /** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */\n// function poly1305_small(msg: Uint8Array, key: Uint8Array): Uint8Array {\n// abytes(msg);\n// abytes(key, 32, \"key\");\n// const POW_2_130_5 = 2n ** 130n - 5n; // 2^130-5\n// const POW_2_128_1 = 2n ** 128n - 1n; // 2^128-1\n// const CLAMP_R = 0x0ffffffc0ffffffc0ffffffc0fffffffn;\n// const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;\n// const s = bytesToNumberLE(key.subarray(16));\n// // Process by 16 byte chunks\n// let acc = 0n;\n// for (let i = 0; i < msg.length; i += 16) {\n// const m = msg.subarray(i, i + 16);\n// const n = bytesToNumberLE(m) | (1n << (8n * mLen)); // mLen: bigint\n// acc = ((acc + n) * r) % POW_2_130_5;\n// }\n// const res = (acc + s) & POW_2_128_1;\n// return numberToBytesBE(res, 16).reverse(); // LE\n// }\n// Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability.\n// function poly1305_computeTag_small(\n// authKey: Uint8Array,\n// lengths: Uint8Array,\n// ciphertext: Uint8Array,\n// AAD?: Uint8Array,\n// ): Uint8Array {\n// const res = [];\n// const updatePadded2 = (msg: Uint8Array) => {\n// res.push(msg);\n// const leftover = msg.length % 16;\n// if (leftover) res.push(new Uint8Array(16).slice(leftover));\n// };\n// if (AAD) updatePadded2(AAD);\n// updatePadded2(ciphertext);\n// res.push(lengths);\n// return poly1305_small(concatBytes(...res), authKey);\n// }\n/** Poly1305 class. Prefer poly1305() function instead. */\nexport class Poly1305 {\n // Can be speed-up using BigUint64Array, at the cost of complexity\n constructor(key) {\n Object.defineProperty(this, \"blockLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n Object.defineProperty(this, \"outputLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n Object.defineProperty(this, \"buffer\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint8Array(16)\n });\n Object.defineProperty(this, \"r\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint16Array(10)\n }); // Allocating 1 array with .subarray() here is slower than 3\n Object.defineProperty(this, \"h\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint16Array(10)\n });\n Object.defineProperty(this, \"pad\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint16Array(8)\n });\n Object.defineProperty(this, \"pos\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"finished\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n key = copyBytes(abytes(key, 32, \"key\"));\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++)\n this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n process(data, offset, isLast = false) {\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n const h0 = h[0] + (t0 & 0x1fff);\n const h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n const h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n const h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n const h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n const h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n const h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n const h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n const h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n const h9 = h[9] + ((t7 >>> 5) | hibit);\n let c = 0;\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) +\n h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) +\n h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) +\n h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) +\n h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) +\n h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) +\n h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) +\n h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) +\n h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++)\n g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++)\n h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n clean(g);\n }\n update(data) {\n aexists(this);\n abytes(data);\n data = copyBytes(data);\n const { 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\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(data, 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(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy() {\n clean(this.h, this.r, this.buffer, this.pad);\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n buffer[pos++] = 1;\n for (; pos < 16; pos++)\n buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n return out;\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n}\nexport function wrapConstructorWithKey(hashCons) {\n const hashC = (msg, key) => hashCons(key).update(msg).digest();\n const tmp = hashCons(new Uint8Array(32)); // tmp array, used just once below\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key) => hashCons(key);\n return hashC;\n}\n/** Poly1305 MAC from RFC 8439. */\nexport const poly1305 = \n/** @__PURE__ */ (() => wrapConstructorWithKey((key) => new Poly1305(key)))();\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/chacha.ts\n */\n/**\n * ChaCha stream cipher, released\n * in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.\n * It was standardized in [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439) and\n * is now used in TLS 1.3.\n *\n * [XChaCha20](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha)\n * extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with\n * randomly-generated nonces.\n *\n * Check out [PDF](http://cr.yp.to/chacha/chacha-20080128.pdf) and\n * [wiki](https://en.wikipedia.org/wiki/Salsa20) and\n * [website](https://cr.yp.to/chacha.html).\n *\n * @module\n */\nimport { createCipher, rotl } from \"./_arx.js\";\nimport { poly1305 } from \"./_poly1305.js\";\nimport { abytes, clean, equalBytes, getOutput, u64Lengths, wrapCipher, } from \"./utils.js\";\n/**\n * ChaCha core function. It is implemented twice:\n * 1. Simple loop (chachaCore_small, hchacha_small)\n * 2. Unrolled loop (chachaCore, hchacha) - 4x faster, but larger & harder to read\n * The specific implementation is selected in `createCipher` below.\n */\nfunction chachaCore(s, k, n, out, cnt, rounds = 20) {\n const y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter\tNonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 7);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 7);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 7);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 8);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 7);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 7);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 7);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 7);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 16);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 7);\n }\n // Write output\n let oi = 0;\n out[oi++] = (y00 + x00) | 0;\n out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0;\n out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0;\n out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0;\n out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0;\n out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0;\n out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0;\n out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0;\n out[oi++] = (y15 + x15) | 0;\n}\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// Pad to digest size with zeros\nconst updatePadded = (h, msg) => {\n h.update(msg);\n const leftover = msg.length % 16;\n if (leftover)\n h.update(ZEROS16.subarray(leftover));\n};\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(fn, key, nonce, ciphertext, AAD) {\n if (AAD !== undefined)\n abytes(AAD, undefined, \"AAD\");\n const authKey = fn(key, nonce, ZEROS32);\n const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);\n // Methods below can be replaced with\n // return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)\n const h = poly1305.create(authKey);\n if (AAD)\n updatePadded(h, AAD);\n updatePadded(h, ciphertext);\n h.update(lengths);\n const res = h.digest();\n clean(authKey, lengths);\n return res;\n}\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them, but it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {\n const tagLength = 16;\n return {\n encrypt(plaintext, output) {\n const plength = plaintext.length;\n output = getOutput(plength + tagLength, output, false);\n output.set(plaintext);\n const oPlain = output.subarray(0, -tagLength);\n // Actual encryption\n xorStream(key, nonce, oPlain, oPlain, 1);\n const tag = computeTag(xorStream, key, nonce, oPlain, AAD);\n output.set(tag, plength); // append tag\n clean(tag);\n return output;\n },\n decrypt(ciphertext, output) {\n output = getOutput(ciphertext.length - tagLength, output, false);\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n if (!equalBytes(passedTag, tag))\n throw new Error(\"invalid tag\");\n output.set(ciphertext.subarray(0, -tagLength));\n // Actual decryption\n xorStream(key, nonce, output, output, 1); // start stream with i=1\n clean(tag);\n return output;\n },\n };\n};\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n *\n * Unsafe to use random nonces under the same key, due to collision chance.\n * Prefer XChaCha instead.\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20));\n","import { ExportError, INPUT_LENGTH_LIMIT, InvalidParamError, toArrayBuffer, } from \"@hpke/common\";\nimport { emitNotSupported } from \"./utils/emitNotSupported.js\";\n// b\"sec\"\nconst LABEL_SEC = new Uint8Array([115, 101, 99]);\nexport class ExporterContextImpl {\n constructor(api, kdf, exporterSecret) {\n Object.defineProperty(this, \"_api\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"exporterSecret\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._api = api;\n this._kdf = kdf;\n this.exporterSecret = exporterSecret;\n }\n async seal(_data, _aad) {\n return await emitNotSupported();\n }\n async open(_data, _aad) {\n return await emitNotSupported();\n }\n async export(exporterContext, len) {\n const rawExporterContext = toArrayBuffer(exporterContext);\n if (rawExporterContext.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long exporter context\");\n }\n try {\n return await this._kdf.labeledExpand(this.exporterSecret, LABEL_SEC, new Uint8Array(rawExporterContext), len);\n }\n catch (e) {\n throw new ExportError(e);\n }\n }\n}\nexport class RecipientExporterContextImpl extends ExporterContextImpl {\n}\nexport class SenderExporterContextImpl extends ExporterContextImpl {\n constructor(api, kdf, exporterSecret, enc) {\n super(api, kdf, exporterSecret);\n Object.defineProperty(this, \"enc\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.enc = enc;\n return;\n }\n}\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _Mutex_locked;\nexport class Mutex {\n constructor() {\n _Mutex_locked.set(this, Promise.resolve());\n }\n async lock() {\n let releaseLock;\n const nextLock = new Promise((resolve) => {\n releaseLock = resolve;\n });\n const previousLock = __classPrivateFieldGet(this, _Mutex_locked, \"f\");\n __classPrivateFieldSet(this, _Mutex_locked, nextLock, \"f\");\n await previousLock;\n return releaseLock;\n }\n}\n_Mutex_locked = new WeakMap();\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _RecipientContextImpl_mutex;\nimport { EMPTY, OpenError, toArrayBuffer } from \"@hpke/common\";\nimport { EncryptionContextImpl } from \"./encryptionContext.js\";\nimport { Mutex } from \"./mutex.js\";\nexport class RecipientContextImpl extends EncryptionContextImpl {\n constructor() {\n super(...arguments);\n _RecipientContextImpl_mutex.set(this, void 0);\n }\n async open(data, aad = EMPTY.buffer) {\n __classPrivateFieldSet(this, _RecipientContextImpl_mutex, __classPrivateFieldGet(this, _RecipientContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n const release = await __classPrivateFieldGet(this, _RecipientContextImpl_mutex, \"f\").lock();\n let pt;\n try {\n pt = await this._ctx.key.open(this.computeNonce(this._ctx), toArrayBuffer(data), toArrayBuffer(aad));\n }\n catch (e) {\n throw new OpenError(e);\n }\n finally {\n release();\n }\n this.incrementSeq(this._ctx);\n return pt;\n }\n}\n_RecipientContextImpl_mutex = new WeakMap();\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _SenderContextImpl_mutex;\nimport { EMPTY, SealError, toArrayBuffer } from \"@hpke/common\";\nimport { EncryptionContextImpl } from \"./encryptionContext.js\";\nimport { Mutex } from \"./mutex.js\";\nexport class SenderContextImpl extends EncryptionContextImpl {\n constructor(api, kdf, params, enc) {\n super(api, kdf, params);\n Object.defineProperty(this, \"enc\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n _SenderContextImpl_mutex.set(this, void 0);\n this.enc = enc;\n }\n async seal(data, aad = EMPTY.buffer) {\n __classPrivateFieldSet(this, _SenderContextImpl_mutex, __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n const release = await __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\").lock();\n let ct;\n try {\n ct = await this._ctx.key.seal(this.computeNonce(this._ctx), toArrayBuffer(data), toArrayBuffer(aad));\n }\n catch (e) {\n throw new SealError(e);\n }\n finally {\n release();\n }\n this.incrementSeq(this._ctx);\n return ct;\n }\n}\n_SenderContextImpl_mutex = new WeakMap();\n","import { AeadId, EMPTY, i2Osp, INFO_LENGTH_LIMIT, INPUT_LENGTH_LIMIT, InvalidParamError, MINIMUM_PSK_LENGTH, Mode, NativeAlgorithm, toUint8Array, } from \"@hpke/common\";\nimport { RecipientExporterContextImpl, SenderExporterContextImpl, } from \"./exporterContext.js\";\nimport { RecipientContextImpl } from \"./recipientContext.js\";\nimport { SenderContextImpl } from \"./senderContext.js\";\n// b\"base_nonce\"\n// deno-fmt-ignore\nconst LABEL_BASE_NONCE = new Uint8Array([\n 98, 97, 115, 101, 95, 110, 111, 110, 99, 101,\n]);\n// b\"exp\"\nconst LABEL_EXP = new Uint8Array([101, 120, 112]);\n// b\"info_hash\"\n// deno-fmt-ignore\nconst LABEL_INFO_HASH = new Uint8Array([\n 105, 110, 102, 111, 95, 104, 97, 115, 104,\n]);\n// b\"key\"\nconst LABEL_KEY = new Uint8Array([107, 101, 121]);\n// b\"psk_id_hash\"\n// deno-fmt-ignore\nconst LABEL_PSK_ID_HASH = new Uint8Array([\n 112, 115, 107, 95, 105, 100, 95, 104, 97, 115, 104,\n]);\n// b\"secret\"\nconst LABEL_SECRET = new Uint8Array([115, 101, 99, 114, 101, 116]);\n// b\"HPKE\"\n// deno-fmt-ignore\nconst SUITE_ID_HEADER_HPKE = new Uint8Array([\n 72, 80, 75, 69, 0, 0, 0, 0, 0, 0,\n]);\n/**\n * The Hybrid Public Key Encryption (HPKE) ciphersuite,\n * which is implemented using only\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n *\n * This is the super class of {@link CipherSuite} and the same as\n * {@link https://jsr.io/@hpke/core/doc/~/CipherSuite | @hpke/core#CipherSuite} as follows:\n * which supports only the ciphersuites that can be implemented on the native\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n * Therefore, the following cryptographic algorithms are not supported for now:\n * - DHKEM(X25519, HKDF-SHA256)\n * - DHKEM(X448, HKDF-SHA512)\n * - ChaCha20Poly1305\n *\n * In addtion, the HKDF functions contained in this class can only derive\n * keys of the same length as the `hashSize`.\n *\n * If you want to use the unsupported cryptographic algorithms\n * above or derive keys longer than the `hashSize`,\n * please use {@link CipherSuite}.\n *\n * This class provides following functions:\n *\n * - Creates encryption contexts both for senders and recipients.\n * - {@link createSenderContext}\n * - {@link createRecipientContext}\n * - Provides single-shot encryption API.\n * - {@link seal}\n * - {@link open}\n *\n * The calling of the constructor of this class is the starting\n * point for HPKE operations for both senders and recipients.\n *\n * @example Use only ciphersuites supported by Web Cryptography API.\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * CipherSuite,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n *\n * @example Use a ciphersuite which is currently not supported by Web Cryptography API.\n *\n * ```ts\n * import { Aes128Gcm, HkdfSha256, CipherSuite } from \"@hpke/core\";\n * // Use an extension module.\n * import { DhkemX25519HkdfSha256 } from \"@hpke/dhkem-x25519\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemX25519HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class CipherSuiteNative extends NativeAlgorithm {\n /**\n * @param params A set of parameters for building a cipher suite.\n *\n * If the error occurred, throws {@link InvalidParamError}.\n *\n * @throws {@link InvalidParamError}\n */\n constructor(params) {\n super();\n Object.defineProperty(this, \"_kem\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_aead\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_suiteId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // KEM\n if (typeof params.kem === \"number\") {\n throw new InvalidParamError(\"KemId cannot be used\");\n }\n this._kem = params.kem;\n // KDF\n if (typeof params.kdf === \"number\") {\n throw new InvalidParamError(\"KdfId cannot be used\");\n }\n this._kdf = params.kdf;\n // AEAD\n if (typeof params.aead === \"number\") {\n throw new InvalidParamError(\"AeadId cannot be used\");\n }\n this._aead = params.aead;\n this._suiteId = new Uint8Array(SUITE_ID_HEADER_HPKE);\n this._suiteId.set(i2Osp(this._kem.id, 2), 4);\n this._suiteId.set(i2Osp(this._kdf.id, 2), 6);\n this._suiteId.set(i2Osp(this._aead.id, 2), 8);\n this._kdf.init(this._suiteId);\n }\n /**\n * Gets the KEM context of the ciphersuite.\n */\n get kem() {\n return this._kem;\n }\n /**\n * Gets the KDF context of the ciphersuite.\n */\n get kdf() {\n return this._kdf;\n }\n /**\n * Gets the AEAD context of the ciphersuite.\n */\n get aead() {\n return this._aead;\n }\n /**\n * Creates an encryption context for a sender.\n *\n * If the error occurred, throws {@link DecapError} | {@link ValidationError}.\n *\n * @param params A set of parameters for the sender encryption context.\n * @returns A sender encryption context.\n * @throws {@link EncapError}, {@link ValidationError}\n */\n async createSenderContext(params) {\n this._validateInputLength(params);\n await this._setup();\n const dh = await this._kem.encap(params);\n let mode;\n if (params.psk !== undefined) {\n mode = params.senderKey !== undefined ? Mode.AuthPsk : Mode.Psk;\n }\n else {\n mode = params.senderKey !== undefined ? Mode.Auth : Mode.Base;\n }\n return await this._keyScheduleS(mode, dh.sharedSecret, dh.enc, params);\n }\n /**\n * Creates an encryption context for a recipient.\n *\n * If the error occurred, throws {@link DecapError}\n * | {@link DeserializeError} | {@link ValidationError}.\n *\n * @param params A set of parameters for the recipient encryption context.\n * @returns A recipient encryption context.\n * @throws {@link DecapError}, {@link DeserializeError}, {@link ValidationError}\n */\n async createRecipientContext(params) {\n this._validateInputLength(params);\n await this._setup();\n const sharedSecret = await this._kem.decap(params);\n let mode;\n if (params.psk !== undefined) {\n mode = params.senderPublicKey !== undefined ? Mode.AuthPsk : Mode.Psk;\n }\n else {\n mode = params.senderPublicKey !== undefined ? Mode.Auth : Mode.Base;\n }\n return await this._keyScheduleR(mode, sharedSecret, params);\n }\n /**\n * Encrypts a message to a recipient.\n *\n * If the error occurred, throws `EncapError` | `MessageLimitReachedError` | `SealError` | `ValidationError`.\n *\n * @param params A set of parameters for building a sender encryption context.\n * @param pt A plain text as bytes to be encrypted.\n * @param aad Additional authenticated data as bytes fed by an application.\n * @returns A cipher text and an encapsulated key as bytes.\n * @throws {@link EncapError}, {@link MessageLimitReachedError}, {@link SealError}, {@link ValidationError}\n */\n async seal(params, pt, aad = EMPTY.buffer) {\n const ctx = await this.createSenderContext(params);\n return {\n ct: await ctx.seal(pt, aad),\n enc: ctx.enc,\n };\n }\n /**\n * Decrypts a message from a sender.\n *\n * If the error occurred, throws `DecapError` | `DeserializeError` | `OpenError` | `ValidationError`.\n *\n * @param params A set of parameters for building a recipient encryption context.\n * @param ct An encrypted text as bytes to be decrypted.\n * @param aad Additional authenticated data as bytes fed by an application.\n * @returns A decrypted plain text as bytes.\n * @throws {@link DecapError}, {@link DeserializeError}, {@link OpenError}, {@link ValidationError}\n */\n async open(params, ct, aad = EMPTY.buffer) {\n const ctx = await this.createRecipientContext(params);\n return await ctx.open(ct, aad);\n }\n // private verifyPskInputs(mode: Mode, params: KeyScheduleParams) {\n // const gotPsk = (params.psk !== undefined);\n // const gotPskId = (params.psk !== undefined && params.psk.id.byteLength > 0);\n // if (gotPsk !== gotPskId) {\n // throw new Error('Inconsistent PSK inputs');\n // }\n // if (gotPsk && (mode === Mode.Base || mode === Mode.Auth)) {\n // throw new Error('PSK input provided when not needed');\n // }\n // if (!gotPsk && (mode === Mode.Psk || mode === Mode.AuthPsk)) {\n // throw new Error('Missing required PSK input');\n // }\n // return;\n // }\n async _keySchedule(mode, sharedSecret, params) {\n // Currently, there is no point in executing this function\n // because this hpke library does not allow users to explicitly specify the mode.\n //\n // this.verifyPskInputs(mode, params);\n const pskId = params.psk === undefined\n ? EMPTY\n : toUint8Array(params.psk.id);\n const pskIdHash = await this._kdf.labeledExtract(EMPTY, LABEL_PSK_ID_HASH, pskId);\n const info = params.info === undefined ? EMPTY : toUint8Array(params.info);\n const infoHash = await this._kdf.labeledExtract(EMPTY, LABEL_INFO_HASH, info);\n const keyScheduleContext = new Uint8Array(1 + pskIdHash.byteLength + infoHash.byteLength);\n keyScheduleContext.set(new Uint8Array([mode]), 0);\n keyScheduleContext.set(new Uint8Array(pskIdHash), 1);\n keyScheduleContext.set(new Uint8Array(infoHash), 1 + pskIdHash.byteLength);\n const psk = params.psk === undefined ? EMPTY : toUint8Array(params.psk.key);\n const ikm = this._kdf.buildLabeledIkm(LABEL_SECRET, psk);\n const exporterSecretInfo = this._kdf.buildLabeledInfo(LABEL_EXP, keyScheduleContext, this._kdf.hashSize);\n const exporterSecret = await this._kdf.extractAndExpand(sharedSecret, ikm, exporterSecretInfo, this._kdf.hashSize);\n if (this._aead.id === AeadId.ExportOnly) {\n return { aead: this._aead, exporterSecret: exporterSecret };\n }\n const keyInfo = this._kdf.buildLabeledInfo(LABEL_KEY, keyScheduleContext, this._aead.keySize);\n const key = await this._kdf.extractAndExpand(sharedSecret, ikm, keyInfo, this._aead.keySize);\n const baseNonceInfo = this._kdf.buildLabeledInfo(LABEL_BASE_NONCE, keyScheduleContext, this._aead.nonceSize);\n const baseNonce = await this._kdf.extractAndExpand(sharedSecret, ikm, baseNonceInfo, this._aead.nonceSize);\n return {\n aead: this._aead,\n exporterSecret: exporterSecret,\n key: key,\n baseNonce: new Uint8Array(baseNonce),\n seq: 0,\n };\n }\n async _keyScheduleS(mode, sharedSecret, enc, params) {\n const res = await this._keySchedule(mode, sharedSecret, params);\n if (res.key === undefined) {\n return new SenderExporterContextImpl(this._api, this._kdf, res.exporterSecret, enc);\n }\n return new SenderContextImpl(this._api, this._kdf, res, enc);\n }\n async _keyScheduleR(mode, sharedSecret, params) {\n const res = await this._keySchedule(mode, sharedSecret, params);\n if (res.key === undefined) {\n return new RecipientExporterContextImpl(this._api, this._kdf, res.exporterSecret);\n }\n return new RecipientContextImpl(this._api, this._kdf, res);\n }\n _validateInputLength(params) {\n if (params.info !== undefined &&\n params.info.byteLength > INFO_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long info\");\n }\n if (params.psk !== undefined) {\n if (params.psk.key.byteLength < MINIMUM_PSK_LENGTH) {\n throw new InvalidParamError(`PSK must have at least ${MINIMUM_PSK_LENGTH} bytes`);\n }\n if (params.psk.key.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long psk.key\");\n }\n if (params.psk.id.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long psk.id\");\n }\n }\n return;\n }\n}\n","import { base64UrlToBytes, DeriveKeyPairError, DeserializeError, EMPTY, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, NativeAlgorithm, NotSupportedError, SerializeError, toArrayBuffer, } from \"@hpke/common\";\nconst ALG_NAME = \"X25519\";\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_X25519 = new Uint8Array([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,\n 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20,\n]);\nconst BASE_POINT_X25519 = /* @__PURE__ */ (() => {\n const p = new Uint8Array(32);\n p[0] = 9;\n return p;\n})();\nexport class X25519 extends NativeAlgorithm {\n constructor(hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._alg = { name: ALG_NAME };\n this._hkdf = hkdf;\n this._nPk = 32;\n this._nSk = 32;\n this._nDh = 32;\n this._pkcs8AlgId = PKCS8_ALG_ID_X25519;\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(ALG_NAME, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const rawIkm = toArrayBuffer(ikm);\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n const rawSk = await this._hkdf.labeledExpand(dkpPrk, LABEL_SK, EMPTY, this._nSk);\n const rawSkBytes = new Uint8Array(rawSk);\n const sk = await this._deserializePkcs8Key(rawSkBytes);\n rawSkBytes.fill(0);\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch {\n try {\n // Firefox fails to export JWK from some imported X25519 private keys.\n const bp = await this._api.importKey(\"raw\", BASE_POINT_X25519.buffer, this._alg, true, []);\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: bp,\n }, key, this._nPk * 8);\n return await this._api.importKey(\"raw\", bits, this._alg, true, []);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n }\n async dh(sk, pk) {\n await this._setup();\n try {\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.kty === \"undefined\" || key.kty !== \"OKP\") {\n throw new Error(`Invalid kty: ${key.crv}`);\n }\n if (typeof key.crv === \"undefined\" || key.crv !== ALG_NAME) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n}\n","import { base64UrlToBytes, DeriveKeyPairError, DeserializeError, EMPTY, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, NativeAlgorithm, NotSupportedError, SerializeError, toArrayBuffer, } from \"@hpke/common\";\nconst ALG_NAME = \"X448\";\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_X448 = new Uint8Array([\n 0x30, 0x46, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,\n 0x03, 0x2b, 0x65, 0x6f, 0x04, 0x3a, 0x04, 0x38,\n]);\nconst BASE_POINT_X448 = /* @__PURE__ */ (() => {\n const p = new Uint8Array(56);\n p[0] = 5;\n return p;\n})();\nexport class X448 extends NativeAlgorithm {\n constructor(hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._alg = { name: ALG_NAME };\n this._hkdf = hkdf;\n this._nPk = 56;\n this._nSk = 56;\n this._nDh = 56;\n this._pkcs8AlgId = PKCS8_ALG_ID_X448;\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(ALG_NAME, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const rawIkm = toArrayBuffer(ikm);\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n const rawSk = await this._hkdf.labeledExpand(dkpPrk, LABEL_SK, EMPTY, this._nSk);\n const rawSkBytes = new Uint8Array(rawSk);\n const sk = await this._deserializePkcs8Key(rawSkBytes);\n rawSkBytes.fill(0);\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch {\n try {\n // Some runtimes cannot export JWK from imported X448 private keys.\n const bp = await this._api.importKey(\"raw\", BASE_POINT_X448.buffer, this._alg, true, []);\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: bp,\n }, key, this._nPk * 8);\n return await this._api.importKey(\"raw\", bits, this._alg, true, []);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n }\n async dh(sk, pk) {\n await this._setup();\n try {\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.kty === \"undefined\" || key.kty !== \"OKP\") {\n throw new Error(`Invalid kty: ${key.crv}`);\n }\n if (typeof key.crv === \"undefined\" || key.crv !== ALG_NAME) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n}\n","import type { HttpClient } from './http.js';\nimport type { ProjectConfig } from './types.js';\n\nconst CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes\n\nexport class ConfigFetcher {\n protected readonly httpClient: HttpClient;\n private cachedConfig: ProjectConfig | null = null;\n private cacheTimestamp = 0;\n\n constructor(httpClient: HttpClient) {\n this.httpClient = httpClient;\n }\n\n async getConfig(): Promise<ProjectConfig | null> {\n const now = Date.now();\n\n if (this.cachedConfig && now - this.cacheTimestamp < CACHE_TTL_MS) {\n return this.cachedConfig;\n }\n\n try {\n const response = await this.httpClient.request<ProjectConfig>('GET', '/v1/config');\n\n if (response.error || !response.data) {\n return null;\n }\n\n this.cachedConfig = response.data;\n this.cacheTimestamp = now;\n\n return this.cachedConfig;\n } catch {\n return null;\n }\n }\n}\n","export class PalbaseError extends Error {\n readonly code: string;\n readonly status: number;\n readonly details?: unknown;\n\n constructor(code: string, message: string, status: number, details?: unknown) {\n super(message);\n this.name = 'PalbaseError';\n this.code = code;\n this.status = status;\n this.details = details;\n }\n}\n","export type Platform = 'browser' | 'node' | 'react-native' | 'deno' | 'bun';\n\ndeclare const Deno: unknown;\n\nexport function detectPlatform(): Platform {\n if (typeof Deno !== 'undefined') {\n return 'deno';\n }\n\n const runtime = globalThis as typeof globalThis & { process?: { versions?: Record<string, string> } };\n if (runtime.process?.versions) {\n if ('bun' in runtime.process.versions) {\n return 'bun';\n }\n if ('node' in runtime.process.versions) {\n return 'node';\n }\n }\n\n if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {\n return 'react-native';\n }\n\n return 'browser';\n}\n\n/**\n * The platform word this SDK puts on the wire (`X-Platform`), which the server\n * reads to target flags and to label telemetry.\n *\n * It is NOT `detectPlatform()`'s value verbatim: that reports the JS host\n * (\"browser\"), while the wire wants the platform. iOS sends \"ios\", not the name\n * of its runtime, and a condition author writes `client.platform == 'web'` —\n * the word every other flag vendor uses too. Server hosts keep their own names,\n * where the distinction is the useful part.\n */\nexport function wirePlatform(): string {\n const host = detectPlatform();\n return host === 'browser' ? 'web' : host;\n}\n","// Proof-of-work: the bot gate in front of /auth/signup and /auth/login.\n//\n// The server answers an unsolved request with 403 and a challenge in the body:\n//\n// { \"error\": \"pow_required\", \"challenge\": { \"id\", \"prefix\", \"difficulty\" } }\n//\n// A client finds any nonce whose SHA-256(prefix + nonce) begins with\n// `difficulty` zero bits, then repeats the request carrying the id and nonce as\n// headers. The work is the point: a person signing up pays it once and does not\n// notice, a script signing up ten thousand times pays it ten thousand times.\n//\n// # Why this lives in core, and not one layer up\n//\n// Until 2026-08-14 nothing shipped could solve it: the gate was written with the\n// server and its own integration harness, and every real client sent requests\n// without the headers and got 403. It was then solved in @palbase/web's own\n// request path — which covers `pb.call` and the module facades and NOT\n// `pb.auth.*`, because those go through @palbase/auth's client and from there\n// into core's HttpClient. So the fix landed everywhere except the two endpoints\n// the gate actually guards, and `npm i @palbase/web` still could not sign a\n// person in. Measured 2026-08-18 against a real stack, on the published 7.3.0.\n//\n// The lesson is where a retry belongs: at the layer that ISSUES the request.\n// Core owns fetch for every client in this repo, so core owns the challenge.\n//\n// WebCrypto rather than a hashing dependency: `crypto.subtle` is present in\n// browsers and in Node 18+, which is the same floor the rest of the SDK sets.\n// Measured at the server's default difficulty of 16: ~330ms, ~65k digests.\n\n/** The challenge a `pow_required` response carries. */\nexport interface PowChallenge {\n id: string;\n prefix: string;\n difficulty: number;\n}\n\n/** Header names the retry must carry. Mirrors the server's constants. */\nexport const POW_CHALLENGE_ID_HEADER = 'X-PoW-Challenge-ID';\nexport const POW_NONCE_HEADER = 'X-PoW-Nonce';\n\n/**\n * Reads a challenge out of an error envelope, or returns null when the envelope\n * is not a `pow_required` one.\n *\n * The whole wire envelope is stored on the error, so the challenge arrives\n * without the HTTP layer having to know about proof-of-work at all.\n */\nexport function asPowChallenge(details: unknown): PowChallenge | null {\n if (typeof details !== 'object' || details === null) return null;\n const env = details as Record<string, unknown>;\n if (env.error !== 'pow_required') return null;\n const c = env.challenge;\n if (typeof c !== 'object' || c === null) return null;\n const { id, prefix, difficulty } = c as Record<string, unknown>;\n if (typeof id !== 'string' || typeof prefix !== 'string') return null;\n if (typeof difficulty !== 'number' || !Number.isInteger(difficulty) || difficulty < 0) return null;\n return { id, prefix, difficulty };\n}\n\nconst encoder = new TextEncoder();\n\n/**\n * One SHA-256, by the fastest route this runtime offers.\n *\n * Awaiting `crypto.subtle.digest` once per nonce is what made this expensive,\n * and the cost is the await rather than the hashing. Measured on one machine,\n * 200k digests of a 40-byte input:\n *\n *\tawaited crypto.subtle.digest 105,597 digests/s\n *\tsync node:crypto createHash 1,324,503 digests/s — 12.5x\n *\n * That is the difference between difficulty 24 taking 159 seconds and taking\n * 13. Node, Bun and Deno all have the sync one; a browser has only WebCrypto,\n * and there it stays async.\n *\n * The specifier is assembled at runtime so a browser bundler does not try to\n * resolve `node:crypto` and fail the build over a branch that never runs there.\n */\ntype Hasher = (input: string) => Uint8Array | Promise<Uint8Array>;\n\nlet hasher: Hasher | null = null;\n\nasync function digester(): Promise<Hasher> {\n if (hasher) return hasher;\n // Read off globalThis with an inline shape rather than by naming `process`,\n // which needs @types/node — a dependency this package does not have and should\n // not grow for one branch. It typechecked locally only because those types\n // were hoisted into node_modules by a sibling package; the publish workflow's\n // clean checkout is what said so, which is exactly what it is for.\n const runtime = globalThis as {\n process?: { versions?: { node?: string; bun?: string } };\n };\n const nodeish =\n runtime.process?.versions?.node !== undefined ||\n runtime.process?.versions?.bun !== undefined;\n if (nodeish) {\n try {\n const mod = (await import(/* @vite-ignore */ `${'node:'}crypto`)) as {\n createHash?: (alg: string) => { update(s: string): { digest(): Uint8Array } };\n };\n if (typeof mod.createHash === 'function') {\n const createHash = mod.createHash;\n hasher = (input: string) => new Uint8Array(createHash('sha256').update(input).digest());\n return hasher;\n }\n } catch {\n // No node:crypto here. WebCrypto below is not a fallback in the apologetic\n // sense — it is the only hash a browser has, and it is correct.\n }\n }\n hasher = async (input: string) =>\n new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode(input)));\n return hasher;\n}\n\n/** Monotonic where it exists, wall-clock where it does not. */\nconst now = (): number =>\n typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now();\n\n/** Counts leading zero bits, stopping at the first byte that has a one. */\nfunction leadingZeroBits(hash: Uint8Array): number {\n let bits = 0;\n for (const byte of hash) {\n if (byte === 0) {\n bits += 8;\n continue;\n }\n // clz32 counts across 32 bits; a byte occupies the low 8, so the first 24\n // are always zero and get subtracted back off.\n return bits + Math.clz32(byte) - 24;\n }\n return bits;\n}\n\n/**\n * The hardest challenge this client will attempt.\n *\n * Not a taste: it is the server's own ceiling. palauth maps a risk score to a\n * difficulty and its worst case is 24 (`DifficultyForRisk`, bot/pow.go:156-166).\n * Anything above that cannot have come from a stack behaving as designed, and\n * the cost of humouring it falls entirely on this side — each step up DOUBLES\n * the work, so difficulty 30 is sixty-four times a legitimate worst case and, on\n * the web, sixty-four times a frozen main thread. Refused immediately, by name.\n */\nexport const MAX_POW_DIFFICULTY = 24;\n\n/**\n * Finds a nonce satisfying the challenge and returns the headers a retry needs.\n *\n * THE BUDGET SCALES WITH THE CHALLENGE, and the first version of this did not.\n * It bounded the search at a flat `1 << 24` — which is not a generous bound for\n * difficulty 24, it is the EXPECTED number of attempts. Finding a nonce is a\n * geometric process: the chance of needing more than 2^d attempts is 1/e, so a\n * flat 2^24 would have failed roughly 37% of legitimate hardest-risk challenges,\n * and failed them for precisely the users the gate exists to slow down — who\n * would have been unable to sign in at all rather than made to wait.\n *\n * Eight times expected puts that at e^-8, about three in ten thousand, while\n * leaving the common case (the server's default 16, and 12 for an unremarkable\n * caller) exactly as cheap as it was.\n *\n * `powBudget` is exported and separate so the RELATIONSHIP can be asserted\n * directly. A test that only watches a cheap challenge succeed cannot tell this\n * budget from the flat one it replaced — measured: reinstating `1 << 24` left\n * such a test green.\n */\nexport function powBudget(difficulty: number): number {\n return 8 * 2 ** difficulty;\n}\n\n/**\n * The longest a solve may be ALLOWED to take, and the difference from a\n * deadline is the whole point.\n *\n * The first version of this was a flat 120s deadline, and it was measured to be\n * worse than the flat iteration budget it was meant to backstop: at ~105k\n * digests/s, difficulty 24 EXPECTS 159 seconds, so a 120s clock killed the\n * majority of legitimate hardest-risk solves — reintroducing, larger, exactly\n * the class of defect that replacing `1 << 24` had removed. Guessing a number\n * for an unknown machine cannot work: the same difficulty is 13 seconds on a\n * runtime with a sync hasher and 159 on one without.\n *\n * So the machine is MEASURED, and the decision moves to the front. A short\n * calibration gives the rate this process actually hashes at; if the whole\n * iteration budget cannot fit in this window at that rate, the solve is refused\n * IMMEDIATELY, naming the numbers. A caller then learns in milliseconds that\n * this difficulty is unpayable here, instead of after two minutes of work\n * thrown away.\n *\n * What remains after that is a guarantee rather than a gamble: a solve that\n * starts can always finish inside its budget, so the only failure left is the\n * budget's own e^-8.\n */\nexport const POW_TIME_BUDGET_MS = 120_000;\n\n/**\n * The window the rate is measured over, and the warm-up it deliberately skips.\n *\n * All of these are REAL attempts — the search starts at nonce 0 and never\n * restarts — so calibration costs nothing but the reading. The first 1024 are\n * excluded from the timing because they include this loop's own JIT warm-up:\n * measured, timing from zero reported 747k digests/s on a machine whose steady\n * rate is 1.32M, and the decision below would have refused a difficulty this\n * machine can pay in half the allowance.\n */\nconst CALIBRATION_WARMUP = 1024;\nconst CALIBRATION_END = 9216;\n\nexport async function solvePowChallenge(\n challenge: PowChallenge,\n maxIterations = powBudget(challenge.difficulty),\n // The caller's AbortSignal, honoured INSIDE the loop rather than only around\n // the fetch it precedes — for the callers that have one. `pb.auth.signIn` does\n // NOT: it reaches the network through @palbase/auth's client, which takes\n // credentials and nothing else. So it is the extra a caller can opt into, and\n // POW_TIME_BUDGET_MS below is what actually bounds the work.\n signal?: AbortSignal,\n): Promise<Record<string, string>> {\n if (challenge.difficulty > MAX_POW_DIFFICULTY) {\n throw new Error(\n `proof-of-work: refusing difficulty ${challenge.difficulty}; this client attempts at most ${MAX_POW_DIFFICULTY}, which is the highest a Palbase stack issues`,\n );\n }\n\n const digest = await digester();\n let warmedAt = 0;\n let calibrated = false;\n // Armed by the calibration below, never before it: until the rate is known\n // there is no honest number to put here.\n let deadline = Number.POSITIVE_INFINITY;\n\n for (let nonce = 0; nonce < maxIterations; nonce++) {\n // Checked in batches: reading them is cheap but not free, and a\n // 1024-digest granularity bounds the delay at a few milliseconds.\n if ((nonce & 1023) === 0) {\n if (signal?.aborted) {\n throw new DOMException('proof-of-work solve aborted', 'AbortError');\n }\n if (now() > deadline) {\n throw new Error(\n `proof-of-work: gave up on difficulty ${challenge.difficulty} after ${POW_TIME_BUDGET_MS / 1000}s ` +\n `and ${nonce.toLocaleString()} attempts — the tail this run drew is longer than the allowance`,\n );\n }\n }\n\n // THE DECISION, TAKEN ONCE AND TAKEN EARLY.\n //\n // After CALIBRATION_DIGESTS real attempts the rate of THIS process is\n // known, so the question \"can this machine pay this difficulty\" has an\n // answer instead of an assumption. If the whole budget cannot fit in the\n // time budget, refuse here — milliseconds in, with the numbers — rather\n // than spend two minutes and throw them away. If it fits, everything after\n // this point is guaranteed to finish inside the window, so the only\n // remaining failure is the budget's own e^-8.\n if (nonce === CALIBRATION_WARMUP) {\n warmedAt = now();\n }\n if (!calibrated && nonce === CALIBRATION_END) {\n calibrated = true;\n const elapsed = Math.max(now() - warmedAt, 0.001);\n const rate = (CALIBRATION_END - CALIBRATION_WARMUP) / (elapsed / 1000);\n // EXPECTED, not worst case, and the difference is the whole judgement.\n //\n // Finding a nonce is geometric: 2^difficulty attempts on average, with a\n // long tail the 8x budget covers. Refusing because the TAIL will not fit\n // would turn away work whose expected cost is seventeen seconds — measured\n // exactly that on this machine at difficulty 24. Refusing on the EXPECTED\n // cost turns away only what is genuinely unpayable here, and what it lets\n // through is then cut by the clock with probability e^-(budget/expected):\n // at 120s against a 17s expectation that is one run in a thousand, and at\n // difficulty 20 on a browser it is one in a hundred and fifty thousand.\n const expectedMs = (2 ** challenge.difficulty / rate) * 1000;\n if (expectedMs > POW_TIME_BUDGET_MS) {\n throw new Error(\n `proof-of-work: difficulty ${challenge.difficulty} needs about ${Math.round(expectedMs / 1000)}s here ` +\n `(${Math.round(rate).toLocaleString()} digests/s) and this client allows ${POW_TIME_BUDGET_MS / 1000}s; ` +\n `refusing before spending the time rather than after`,\n );\n }\n deadline = now() + (POW_TIME_BUDGET_MS - (now() - warmedAt));\n }\n\n const hash = await digest(challenge.prefix + nonce);\n if (leadingZeroBits(hash) >= challenge.difficulty) {\n return {\n [POW_CHALLENGE_ID_HEADER]: challenge.id,\n [POW_NONCE_HEADER]: String(nonce),\n };\n }\n }\n throw new Error(\n `proof-of-work: no nonce found for difficulty ${challenge.difficulty} within ${maxIterations} attempts`,\n );\n}\n","import { Chacha20Poly1305 } from '@hpke/chacha20poly1305';\nimport { CipherSuite, HkdfSha256 } from '@hpke/core';\nimport { DhkemX25519HkdfSha256 } from '@hpke/dhkem-x25519';\nimport { PalbaseError } from './errors.js';\nimport { fromBase64, toBase64 } from './sealed-json.js';\nimport type { SealingKey } from './sealed-keys.js';\n\nexport const SEALED_CONTENT_TYPE = 'application/palbase-sealed+json';\nexport const SEALED_HEADER = 'X-Palbase-Sealed';\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder('utf-8', { fatal: true });\nconst responseLabel = 'palbase-sealed/response/v1';\n\nexport function sealingRequired(path: string): boolean {\n // Mirrors v2/internal/server/sealed.go. Tenant/runtime routes cannot unseal.\n return new URL(path, 'https://unused.invalid').pathname.startsWith('/auth/');\n}\n\nexport function requestAAD(\n host: string,\n method: string,\n path: string,\n ict: string,\n ts: number,\n idem: string,\n): Uint8Array<ArrayBuffer> {\n const fields = [host, method, path, ict, idem].map((field) => encoder.encode(field));\n const bytes = new Uint8Array(fields.reduce((size, field) => size + 4 + field.length, 8));\n const view = new DataView(bytes.buffer);\n let offset = 0;\n for (const [index, field] of fields.entries()) {\n if (index === 4) {\n view.setBigUint64(offset, BigInt(ts));\n offset += 8;\n }\n view.setUint32(offset, field.length);\n offset += 4;\n bytes.set(field, offset);\n offset += field.length;\n }\n return bytes;\n}\n\nexport function sealingSuite(): CipherSuite {\n return new CipherSuite({\n kem: new DhkemX25519HkdfSha256(),\n kdf: new HkdfSha256(),\n aead: new Chacha20Poly1305(),\n });\n}\n\nexport async function sealRequest(\n key: SealingKey,\n url: string,\n init: RequestInit,\n): Promise<Uint8Array<ArrayBuffer>> {\n const suite = sealingSuite();\n const sender = await suite.createSenderContext({\n recipientPublicKey: await suite.kem.importKey('raw', key.publicKey.buffer),\n });\n const headers = new Headers(init.headers);\n const ict = headers.get('content-type') ?? 'application/json';\n const ts = Math.floor(Date.now() / 1000);\n const target = new URL(url);\n const method = init.method ?? 'GET';\n // Go binds r.URL.Path (decoded, without the query), not RequestURI.\n const aad = requestAAD(\n target.host,\n method,\n decodeURIComponent(target.pathname),\n ict,\n ts,\n headers.get('idempotency-key') ?? '',\n );\n const ct = await sender.seal(encoder.encode(typeof init.body === 'string' ? init.body : ''), aad);\n const envelope = JSON.stringify({\n v: 2,\n kid: key.kid,\n enc: toBase64(new Uint8Array(sender.enc)),\n ct: toBase64(new Uint8Array(ct)),\n ict,\n ts,\n });\n if (method === 'GET' || method === 'HEAD' || init.body === undefined) {\n headers.set(\n SEALED_HEADER,\n toBase64(encoder.encode(envelope)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''),\n );\n delete init.body;\n } else {\n headers.delete(SEALED_HEADER);\n headers.set('Content-Type', SEALED_CONTENT_TYPE);\n init.body = envelope;\n }\n headers.delete('Content-Length');\n init.headers = Object.fromEntries(headers.entries());\n // Do not redirect a credential-bearing envelope to a different endpoint.\n init.redirect = 'error';\n return new Uint8Array(await sender.export(encoder.encode(responseLabel), 32));\n}\n\nexport async function openSealedResponse(\n response: Response,\n exporter: Uint8Array | undefined,\n method: string,\n): Promise<Response> {\n if (\n response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !==\n SEALED_CONTENT_TYPE\n ) {\n // Edge/middleware errors are plaintext. A successful auth result cannot be.\n if (exporter && response.ok && method !== 'HEAD') {\n throw new PalbaseError(\n 'sealed_response_invalid',\n 'The server returned an unencrypted response.',\n response.status,\n );\n }\n return response;\n }\n // HTTP HEAD has no response body, including when the handler sealed it.\n if (method === 'HEAD') return response;\n try {\n if (!exporter) throw new Error('No sealing context');\n const envelope = (await response.json()) as {\n v: number;\n n: string;\n ct: string;\n ict: string;\n st: number;\n };\n if (\n envelope.v !== 2 ||\n !Number.isInteger(envelope.st) ||\n envelope.st < 200 ||\n envelope.st > 599 ||\n typeof envelope.ict !== 'string'\n ) {\n throw new Error('Invalid response envelope');\n }\n const plaintext = await new Chacha20Poly1305()\n .createEncryptionContext(exporter)\n .open(\n fromBase64(envelope.n),\n fromBase64(envelope.ct),\n encoder.encode(`${responseLabel}\\n${envelope.ict}\\n${envelope.st}`),\n );\n const headers = new Headers(response.headers);\n headers.set('Content-Type', envelope.ict);\n headers.delete('Content-Length');\n headers.delete('Content-Encoding');\n // The outer status is always 200; auth failures and PoW live inside the seal.\n return new Response([204, 205, 304].includes(envelope.st) ? null : decoder.decode(plaintext), {\n status: envelope.st,\n headers,\n });\n } catch {\n throw new PalbaseError(\n 'sealed_response_invalid',\n 'The encrypted server response could not be verified.',\n response.status,\n );\n }\n}\n","// Signatures cover the original JSON bytes, not JSON.stringify(JSON.parse(raw)).\n// Go's encoder preserves struct field order and escapes characters differently.\nexport function rawObjectFields(raw: string): Map<string, string> {\n const parsed: unknown = JSON.parse(raw);\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('Expected a JSON object');\n }\n const fields = new Map<string, string>();\n let i = 0;\n const space = () => {\n while (/\\s/.test(raw[i] ?? '') && i < raw.length) i++;\n };\n const stringEnd = (start: number) => {\n let end = start + 1;\n while (end < raw.length) {\n if (raw[end] === '\\\\') end += 2;\n else if (raw[end++] === '\"') return end;\n }\n throw new Error('Unterminated JSON string');\n };\n space();\n i++; // opening object, already validated by JSON.parse\n while (true) {\n space();\n if (raw[i] === '}') return fields;\n const nameEnd = stringEnd(i);\n const name = JSON.parse(raw.slice(i, nameEnd)) as string;\n i = nameEnd;\n space();\n i++; // colon\n space();\n const start = i;\n if (raw[i] === '\"') i = stringEnd(i);\n else if (raw[i] === '{' || raw[i] === '[') {\n let depth = 0;\n do {\n const c = raw[i];\n if (c === '\"') {\n i = stringEnd(i);\n continue;\n }\n if (c === '{' || c === '[') depth++;\n if (c === '}' || c === ']') depth--;\n i++;\n } while (depth > 0 && i < raw.length);\n } else {\n while (i < raw.length && !/[\\s,}]/.test(raw[i] ?? '')) i++;\n }\n // A first-match slice and JSON.parse's last-match value must never disagree.\n if (fields.has(name)) throw new Error('Duplicate JSON field');\n fields.set(name, raw.slice(start, i));\n space();\n if (raw[i] === ',') i++;\n }\n}\n\nexport function fromBase64(value: string): Uint8Array<ArrayBuffer> {\n return Uint8Array.from(atob(value), (c) => c.charCodeAt(0));\n}\n\nexport function toBase64(bytes: Uint8Array): string {\n // Avoid a spread: envelopes can exceed the engine's argument-count limit.\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n","import { ed25519 } from '@noble/curves/ed25519.js';\nimport { PalbaseError } from './errors.js';\nimport { fromBase64, rawObjectFields } from './sealed-json.js';\nimport { endpointUrl } from './url.js';\nimport type { HttpClientOptions } from './types.js';\n\nexport const SEALED_KEYSET_PATH = '/palbase-sealed-keys.json';\nexport const SEALED_SUITE = 'DHKEM-X25519-HKDF-SHA256/HKDF-SHA256/ChaCha20Poly1305';\n// Fleet PUBLIC key, identical to the iOS SDK pin. Never learned from a response.\nconst FLEET_ROOT = 'mRDTIWzhW0JCk0e2Jvkn679VeZBB38zOOfPTMO6vBpU=';\nconst REFRESH_MS = 5 * 60_000;\nconst FAILURE_COOLDOWN_MS = 60_000;\nconst encoder = new TextEncoder();\n\nexport interface SealingKey {\n kid: string;\n publicKey: Uint8Array<ArrayBuffer>;\n expires: number;\n version: number;\n}\n\nexport function expectedSealedStack(baseUrl: string, apiKey: string): string {\n // Fleet tenant hosts name the stack even when a legacy key says pb_project_.\n // Apex/custom/self-host URLs instead need the key's ref (or an explicit pin).\n const host = new URL(baseUrl).hostname;\n return (\n /^([a-z0-9]{4,24})\\.(?:(?:dev|staging)\\.)?palbase\\.studio$/.exec(host)?.[1] ??\n /^pb_([^_]+)_/.exec(apiKey)?.[1] ??\n ''\n );\n}\n\nfunction record(raw: string | undefined): Record<string, unknown> {\n if (!raw) throw new Error('Missing signed object');\n rawObjectFields(raw); // also refuses duplicate fields\n return JSON.parse(raw) as Record<string, unknown>;\n}\n\nfunction string(value: unknown): string {\n if (typeof value !== 'string' || !value) throw new Error('Missing string');\n return value;\n}\n\nfunction integer(value: unknown): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new Error('Invalid integer');\n }\n return value;\n}\n\nfunction verifySignature(raw: string, signed: Record<string, unknown>, publicKey: Uint8Array) {\n if (\n signed.alg !== 'ed25519' ||\n publicKey.length !== 32 ||\n !ed25519.verify(fromBase64(string(signed.sig)), encoder.encode(raw), publicKey, {\n zip215: false,\n })\n )\n throw new Error('Invalid sealed key signature');\n}\n\n/** Verify fleet → expected stack → keyset, retaining the exact signed bytes. */\nexport function verifySealingKey(\n raw: string,\n expectedRef: string,\n root: string,\n lastVersion: number,\n now: number,\n): SealingKey {\n const fields = rawObjectFields(raw);\n const signed = record(raw);\n const statementRaw = fields.get('binding');\n const statement = record(statementRaw);\n const bindingRaw = rawObjectFields(statementRaw ?? '').get('binding');\n if (!bindingRaw || statement.rootKid !== 'sealed-root-v1') {\n throw new Error('Unknown sealed trust root');\n }\n verifySignature(bindingRaw, statement, fromBase64(root));\n const binding = record(bindingRaw);\n if (\n binding.v !== 1 ||\n !expectedRef ||\n string(binding.stackRef).trim().toLowerCase() !== expectedRef.toLowerCase()\n ) {\n throw new Error('Sealed binding belongs to another stack');\n }\n const bindingExpiry = integer(binding.expires);\n if (bindingExpiry * 1000 <= now) throw new Error('Expired sealed binding');\n const keysetRaw = fields.get('keyset');\n if (!keysetRaw) throw new Error('Missing sealed keyset');\n verifySignature(keysetRaw, signed, fromBase64(string(binding.signingKey)));\n const keyset = record(keysetRaw);\n const version = integer(keyset.version);\n const expires = Math.min(integer(keyset.expires), bindingExpiry);\n if (version < lastVersion) throw new Error('Sealed keyset version went backwards');\n if (expires * 1000 <= now) throw new Error('Expired sealed keyset');\n if (keyset.v !== 1 || !Array.isArray(keyset.keys)) throw new Error('Invalid sealed keyset');\n for (const item of keyset.keys) {\n if (item === null || typeof item !== 'object') continue;\n const entry = item as Record<string, unknown>;\n if (entry.alg !== SEALED_SUITE) continue;\n const publicKey = fromBase64(string(entry.pub));\n if (publicKey.length !== 32) throw new Error('Invalid sealing public key');\n return { kid: string(entry.kid), publicKey, expires, version };\n }\n throw new Error('No supported sealing key');\n}\n\nexport class SealedKeyStore {\n private cached?: SealingKey;\n private pending?: Promise<SealingKey>;\n private fetchedAt = 0;\n private retryAfter = 0;\n private lastVersion = 0;\n private lastError?: PalbaseError;\n private rotationRefreshAt = 0;\n\n constructor(\n private readonly baseUrl: string,\n private readonly apiKey: string,\n private readonly options?: Exclude<HttpClientOptions['sealed'], false>,\n ) {}\n\n async current(signal?: AbortSignal, rotate = false): Promise<SealingKey> {\n signal?.throwIfAborted();\n const now = Date.now();\n const valid = this.cached && this.cached.expires * 1000 > now ? this.cached : undefined;\n if (this.pending) return this.waitFor(this.pending, signal);\n // A forged unknown-kid response cannot turn every request into a key fetch.\n if (rotate && now - this.rotationRefreshAt >= FAILURE_COOLDOWN_MS) {\n this.fetchedAt = 0;\n this.retryAfter = 0;\n this.rotationRefreshAt = now;\n }\n if (valid && now - this.fetchedAt < REFRESH_MS) return valid;\n if (now < this.retryAfter) {\n if (valid) return valid;\n throw this.lastError;\n }\n const pending = this.fetchKey()\n .then((key) => {\n this.cached = key;\n this.lastVersion = key.version;\n this.fetchedAt = Date.now();\n this.retryAfter = 0;\n return key;\n })\n .catch((error: unknown) => {\n this.retryAfter = Date.now() + FAILURE_COOLDOWN_MS;\n this.lastError =\n error instanceof PalbaseError\n ? error\n : new PalbaseError(\n 'sealed_key_unavailable',\n 'The server encryption key could not be verified. Please try again later.',\n 0,\n );\n // A transient refresh failure may reuse a verified, unexpired key only.\n if (this.cached && this.cached.expires * 1000 > Date.now()) return this.cached;\n throw this.lastError;\n })\n .finally(() => {\n this.pending = undefined;\n });\n this.pending = pending;\n return this.waitFor(pending, signal);\n }\n\n private async fetchKey(): Promise<SealingKey> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 15_000);\n try {\n const response = await fetch(endpointUrl(this.baseUrl, SEALED_KEYSET_PATH), {\n headers: this.apiKey ? { apikey: this.apiKey } : {},\n signal: controller.signal,\n cache: 'no-store',\n redirect: 'error',\n });\n if (!response.ok) throw new Error('Sealed keyset unavailable');\n const raw = await response.text();\n if (raw.length > 64 * 1024) throw new Error('Sealed keyset too large');\n const expectedRef = this.options?.stackRef ?? expectedSealedStack(this.baseUrl, this.apiKey);\n return verifySealingKey(\n raw,\n expectedRef,\n this.options?.root ?? FLEET_ROOT,\n this.lastVersion,\n Date.now(),\n );\n } finally {\n clearTimeout(timer);\n }\n }\n\n // One caller's cancellation must not abort a shared key fetch for other calls.\n private waitFor(pending: Promise<SealingKey>, signal?: AbortSignal): Promise<SealingKey> {\n if (!signal) return pending;\n return new Promise((resolve, reject) => {\n const aborted = () => reject(signal.reason);\n signal.addEventListener('abort', aborted, { once: true });\n pending.then(resolve, reject).finally(() => signal.removeEventListener('abort', aborted));\n if (signal.aborted) aborted();\n });\n }\n}\n","/**\n * Join the configured base URL with an SDK path.\n *\n * A BASE URL MAY CARRY A PATH, NOT JUST AN ORIGIN — a self-host published\n * under `https://api.example.com/palbase`, or an app that routes the browser\n * through its own server (`<origin>/pb`, rewritten upstream) because the\n * Environment's edge does not answer its origin with CORS headers.\n *\n * `new URL('/palbase-sealed-keys.json', base)` reads as the careful way to do\n * this and is the one form that DROPS that path: the leading slash makes the\n * path absolute against the base's ORIGIN. The sealed key store used it while\n * every ordinary request concatenated, so one request in the client asked a\n * different server than all the others — measured live 2026-09-11, the keyset\n * fetch landed on the app's own 404 page and every sealed call failed with\n * `sealed_key_unavailable`. The other two SDK surfaces never had the split:\n * iOS appends (`SealedKeyStore.swift`), Android concatenates onto a\n * slash-trimmed base (`SealedKeyStore.kt`) — this is their shape.\n */\nexport function endpointUrl(base: string, path: string): string {\n return `${base.replace(/\\/+$/, '')}${path}`;\n}\n","import { PalbaseError } from './errors.js';\nimport { wirePlatform } from './platform.js';\nimport { asPowChallenge, solvePowChallenge } from './pow.js';\nimport { openSealedResponse, sealingRequired, sealRequest } from './sealed.js';\nimport { SealedKeyStore } from './sealed-keys.js';\nimport type { TokenManager } from './token.js';\nimport { endpointUrl } from './url.js';\nimport type { HttpClientOptions, PalbaseResponse, RequestOptions } from './types.js';\n\n/**\n * Default production host. Dev / staging / local callers override via\n * `options.url`. Apex-style routing is the only supported production path;\n * Kong resolves Environment identity from the API key.\n */\nconst PALBASE_DEFAULT_HOST = 'api.palbase.studio';\n\n/**\n * Parse the Environment ref from a Palbase API key.\n *\n * Canonical shape: `pb_{environment_ref}_c{random}`, where the Environment ref\n * is 4-24 lowercase ASCII alphanumeric characters and random is AT LEAST 20\n * base62 chars.\n *\n * The length is a floor, not an equality. The stack's own minter writes 20\n * (v2/cmd/palsvc/initenv.go) and the cloud control plane writes 32\n * (cloud/platform/server/services/keys.ts), and the door that admits the\n * request refuses to rule on the difference: *\"a shorter or longer secret is\n * not a security property this door can rule on\"*\n * (v2/internal/platform/identitymw.go: parseAPIKey). A client that is stricter\n * than the server does not add safety — it just refuses working keys, which is\n * exactly what this one did to every cloud project until 2026-08-25.\n *\n * Returns the Environment ref on match; `null` otherwise.\n */\nconst API_KEY_RE = /^pb_([a-z0-9]{4,24})_c[A-Za-z0-9]{20,}$/;\n\nfunction parseEnvironmentRef(apiKey: string): string | null {\n return API_KEY_RE.exec(apiKey)?.[1] ?? null;\n}\nconst MAX_RETRIES = 3;\nconst INITIAL_BACKOFF_MS = 200;\n/**\n * Upper bound on a single 429 retry sleep. A server may return a long\n * Retry-After (a locked account can send minutes/hours); honoring it verbatim\n * would HANG the request for that whole window. Cap each retry at 10s — after\n * MAX_RETRIES the 429 envelope surfaces to the caller (fail fast, don't sleep\n * minutes). The clamp never skips a retry; it only bounds how long each waits.\n */\nconst MAX_RETRY_DELAY_MS = 10_000;\n\n/**\n * Carry a 429's retry hint into the error envelope when only the header has it.\n *\n * A REFUSAL FROM THE EDGE CARRIES NOTHING BUT THE HEADER. Envoy and the\n * gateway limiter answer before any Palbase service is reached, so their 429\n * has no `retry_after` and no `data.retryAfter` — and every reader above this\n * layer (`@palbase/web`'s BackendError, the iOS SDK) looks in the BODY. The\n * seconds were on the wire and unreachable to all of them.\n *\n * Lifted under `retry_after`, the platform's own name for it (palauth's\n * rate-limit envelope), never overwriting a hint the service itself sent — a\n * service knows its window, the edge only knows its own.\n */\nfunction withRetryHint(\n body: Record<string, unknown> | undefined,\n response: Response,\n): Record<string, unknown> | undefined {\n if (response.status !== 429) return body;\n const data = body?.data;\n const alreadyStated =\n typeof body?.retry_after === 'number' ||\n (typeof data === 'object' && data !== null && 'retryAfter' in data);\n if (alreadyStated) return body;\n const seconds = Number.parseInt(response.headers.get('Retry-After') ?? '', 10);\n if (Number.isNaN(seconds) || seconds <= 0) return body;\n return { ...body, retry_after: seconds };\n}\n\n/**\n * Request interceptor. Runs before every HTTP request.\n * Can modify headers, body, or reject the request.\n */\nexport type RequestInterceptor = (request: {\n headers: Record<string, string>;\n method: string;\n path: string;\n}) => void | Promise<void>;\n\nexport class HttpClient {\n protected readonly apiKey: string;\n protected readonly options?: HttpClientOptions;\n\n tokenManager: TokenManager | null = null;\n\n /**\n * Admin JWT used for platform admin endpoints (/admin/*).\n * When set, takes precedence over tokenManager access token in the\n * Authorization header.\n */\n adminToken: string | null = null;\n\n private readonly interceptors: RequestInterceptor[] = [];\n private readonly forbiddenListeners = new Set<(body: Record<string, unknown>) => void>();\n private sealedKeys?: SealedKeyStore;\n\n constructor(apiKey: string, options?: HttpClientOptions) {\n this.apiKey = apiKey;\n this.options = options;\n }\n\n /** Set (or clear) the admin JWT used on admin endpoints. */\n setAdminToken(token: string | null): void {\n this.adminToken = token;\n }\n\n /**\n * Called with the RAW body of every 403 this client receives (FR-010). Core\n * does not know the envelope's fields — the layer that does (palbe) reads\n * `required` out of it. Nothing is retried or swallowed: the error still\n * returns to the caller.\n */\n onForbidden(handler: (body: Record<string, unknown>) => void): () => void {\n this.forbiddenListeners.add(handler);\n return () => {\n this.forbiddenListeners.delete(handler);\n };\n }\n\n /**\n * Create a scoped HttpClient that adds the given extra headers to every\n * request. The returned client shares the admin token and token manager\n * with the parent at runtime — later changes on the parent propagate to\n * the scope and vice versa.\n *\n * Typical use: adding an Environment-routing header for an admin call.\n */\n withHeaders(extra: Record<string, string>): HttpClient {\n const mergedHeaders = { ...(this.options?.headers ?? {}), ...extra };\n\n const scoped: HttpClient = new HttpClient(this.apiKey, {\n ...this.options,\n headers: mergedHeaders,\n });\n scoped.tokenManager = this.tokenManager;\n // Delegate adminToken reads + writes to the parent so the scope always\n // sees the latest token, and setAdminToken on the scope affects the parent.\n // The scope shares the parent's 403 listeners: a refusal is a refusal\n // whichever header set the request carried.\n Object.defineProperty(scoped, 'forbiddenListeners', {\n get: () => this.forbiddenListeners,\n });\n Object.defineProperty(scoped, 'adminToken', {\n get: () => this.adminToken,\n set: (v: string | null) => {\n this.adminToken = v;\n },\n configurable: true,\n });\n Object.defineProperty(scoped, 'sealedKeys', {\n get: () => this.sealedKeys,\n set: (v: SealedKeyStore | undefined) => {\n this.sealedKeys = v;\n },\n });\n return scoped;\n }\n\n /** Add a request interceptor. Runs before every request. */\n addInterceptor(interceptor: RequestInterceptor): void {\n this.interceptors.push(interceptor);\n }\n\n async request<T>(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<PalbaseResponse<T>> {\n // If token is expired and refresh is available, refresh before making the request\n if (\n !options?.skipSessionRefresh &&\n this.tokenManager?.isExpired() &&\n this.tokenManager.getRefreshToken() &&\n this.tokenManager.refreshFunction\n ) {\n try {\n await this.tokenManager.refreshSession();\n } catch (e) {\n const status = e instanceof PalbaseError ? e.status : 0;\n if (status === 400 || status === 401 || status === 403) {\n // Terminal: the refresh token is dead (revoked/expired/forbidden).\n // Clear the session (listeners persist the sign-out) and proceed\n // unauthenticated — the endpoint will 401 into the normal error\n // envelope instead of bricking every subsequent call including\n // the recovery sign-in.\n this.tokenManager.clearSession();\n } else {\n throw e; // network/5xx: transient, stay loud\n }\n }\n }\n\n return this.executeWithRetry<T>(method.toUpperCase(), path, options, 0);\n }\n\n /**\n * A response read as it arrives, for `text/event-stream` routes.\n *\n * Deliberately NOT `executeWithRetry`: a retry replays the request, and a\n * stream the caller has already begun reading cannot be replayed — the frames\n * it handed over would arrive a second time. A stream that fails to open fails\n * to the caller, once, with its status.\n *\n * The buffered path's headers, base URL and interceptors are reused verbatim,\n * so a streaming call is authenticated exactly like every other call; only the\n * body handling differs. `Accept` says what the caller wants, and the status\n * is returned beside the body because the CALLER decides what a non-2xx means\n * (an error envelope arrives as an ordinary buffered body).\n */\n async requestStream(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<{ status: number; body: ReadableStream<Uint8Array> | null; contentType: string }> {\n method = method.toUpperCase();\n if (\n !options?.skipSessionRefresh &&\n this.tokenManager?.isExpired() &&\n this.tokenManager.getRefreshToken() &&\n this.tokenManager.refreshFunction\n ) {\n try {\n await this.tokenManager.refreshSession();\n } catch (e) {\n const status = e instanceof PalbaseError ? e.status : 0;\n if (status === 400 || status === 401 || status === 403) {\n this.tokenManager.clearSession();\n } else {\n throw e;\n }\n }\n }\n\n const url = endpointUrl(this.getBaseUrl(), path);\n const headers = { ...this.buildHeaders(options), Accept: 'text/event-stream' };\n for (const interceptor of this.interceptors) {\n await interceptor({ headers, method, path });\n }\n\n const fetchOptions: RequestInit = { method, headers, signal: options?.signal };\n if (options?.body !== undefined) fetchOptions.body = JSON.stringify(options.body);\n const exporter = await this.prepareSealed(url, path, fetchOptions);\n\n const response = await openSealedResponse(await fetch(url, fetchOptions), exporter, method);\n return {\n status: response.status,\n body: response.body,\n contentType: response.headers.get('content-type') ?? '',\n };\n }\n\n private async prepareSealed(\n url: string,\n path: string,\n init: RequestInit,\n ): Promise<Uint8Array<ArrayBuffer> | undefined> {\n if (this.options?.sealed === false || !sealingRequired(path)) return undefined;\n this.sealedKeys ??= new SealedKeyStore(this.getBaseUrl(), this.apiKey, this.options?.sealed);\n const key = await this.sealedKeys.current(init.signal ?? undefined);\n init.signal?.throwIfAborted();\n try {\n return await sealRequest(key, url, init);\n } catch (error) {\n init.signal?.throwIfAborted();\n if (error instanceof PalbaseError) throw error;\n throw new PalbaseError('sealed_request_failed', 'The request could not be encrypted.', 0);\n }\n }\n\n private getBaseUrl(): string {\n // Explicit URL always wins (local dev, staging, test rigs).\n if (this.options?.url) {\n return this.options.url;\n }\n\n // Validate the key shape up front so apex-routed callers still\n // fail loud on a malformed key instead of hitting the gateway\n // with bad credentials.\n if (this.apiKey && parseEnvironmentRef(this.apiKey) === null) {\n throw new PalbaseError(\n 'invalid_api_key',\n 'Invalid API key format. Expected pb_{environment_ref}_c{at least 20 base62 chars}. For dev/staging pass `url: \"https://api.dev.palbase.studio\"` via options.',\n 0,\n );\n }\n\n return `https://${PALBASE_DEFAULT_HOST}`;\n }\n\n private buildHeaders(options?: RequestOptions): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n // Client identity, the web counterpart of the iOS SDK's\n // ClientInfo.augment(). The server reads these to resolve flag targeting\n // conditions and to label telemetry, so an app declares nothing and calls\n // nothing — whatever the SDK can know, it sends.\n 'X-Platform': wirePlatform(),\n };\n // The host app's own version is not knowable on the web (no bundle to read\n // it from), so it is opt-in; when given it fills the same header iOS fills\n // from CFBundleShortVersionString.\n const appVersion = this.options?.appVersion?.trim();\n if (appVersion) {\n headers['X-Palbase-Client-Version'] = appVersion;\n }\n\n // Palbase Environment keys live in the `apikey` header — never in\n // `Authorization` — because Kong's key-auth resolves them on that\n // header and the gateway's pre-function plugin stamps the downstream\n // identity.\n const effectiveKey = this.apiKey;\n if (effectiveKey) {\n headers['apikey'] = effectiveKey;\n }\n\n // User session token, if any. Kong's pre-function plugin strips\n // Authorization on /v1/* routes anyway (PostgREST has no JWT\n // secret and would crash on a Bearer it can't decode), but\n // sending it preserves the contract for /auth/* endpoints that\n // do consume the bearer (e.g. session refresh).\n const token = this.tokenManager?.getAccessToken();\n if (token) {\n headers['Authorization'] = `Bearer ${token}`;\n }\n\n // adminToken (platform admin JWT) takes precedence — used by the\n // @palbase/admin internal flows that hit /admin/* routes; those\n // routes verify the bearer themselves and aren't subject to the\n // /v1/* Authorization-strip rule.\n if (this.adminToken) {\n headers['Authorization'] = `Bearer ${this.adminToken}`;\n }\n\n // Merge global custom headers\n if (this.options?.headers) {\n Object.assign(headers, this.options.headers);\n }\n\n // Merge per-request headers\n if (options?.headers) {\n Object.assign(headers, options.headers);\n }\n\n return headers;\n }\n\n private async executeWithRetry<T>(\n method: string,\n path: string,\n options: RequestOptions | undefined,\n attempt: number,\n // Headers a PREVIOUS attempt earned and this one has to carry. Today that\n // is only the solved proof-of-work pair; it is a parameter rather than a\n // field because it belongs to one request's second try, and a field would\n // leak it onto every later call made through this client.\n earned?: Record<string, string>,\n rotated = false,\n ): Promise<PalbaseResponse<T>> {\n const url = endpointUrl(this.getBaseUrl(), path);\n const headers = { ...this.buildHeaders(options), ...earned };\n\n // Run interceptors\n for (const interceptor of this.interceptors) {\n await interceptor({ headers, method, path });\n }\n\n const fetchOptions: RequestInit = {\n method,\n headers,\n signal: options?.signal,\n };\n\n if (options?.body !== undefined) {\n fetchOptions.body = JSON.stringify(options.body);\n }\n // A fresh HPKE encapsulation on EVERY attempt: reusing an envelope trips\n // the server replay guard, even when the first response was lost.\n const exporter = await this.prepareSealed(url, path, fetchOptions);\n\n let response: Response;\n try {\n response = await fetch(url, fetchOptions);\n } catch (error) {\n options?.signal?.throwIfAborted();\n // Network error — retry with backoff\n if (options?.retry !== false && attempt < MAX_RETRIES - 1) {\n const backoff = INITIAL_BACKOFF_MS * 2 ** attempt;\n await this.delay(backoff);\n // WITHOUT `earned`, and that is the whole point of this line.\n //\n // A network error means the response was lost, not that the request\n // was. If it reached the server, the challenge is already SPENT —\n // palauth's VerifyChallenge reads and deletes in one step\n // (bot/pow.go:96-104), deliberately, because a proof presented twice is\n // not proof. Replaying the nonce would then answer `pow_invalid`, and\n // the one-solve guard below would refuse to try again: a request one\n // fresh solve away from succeeding, failed. Dropping it costs nothing\n // in the other case — if the server never saw the request, a fresh\n // challenge works exactly as well as the old one.\n return this.executeWithRetry<T>(method, path, options, attempt + 1, undefined, rotated);\n }\n\n // All retries exhausted — throw PalbaseError\n throw new PalbaseError(\n 'network_error',\n error instanceof Error ? error.message : 'Network request failed',\n 0,\n );\n }\n response = await openSealedResponse(response, exporter, method);\n\n // Handle 429 Too Many Requests — retry with Retry-After or backoff;\n // if retries exhausted, fall through to normal error response handling below\n if (response.status === 429) {\n if (options?.retry !== false && attempt < MAX_RETRIES - 1) {\n const retryAfter = response.headers.get('Retry-After');\n const parsed = retryAfter ? Number.parseInt(retryAfter, 10) : Number.NaN;\n // Clamp the server-requested wait: a long Retry-After (locked account)\n // must not hang the request — cap each sleep, exhaust MAX_RETRIES, then\n // fall through to surface the 429 envelope below.\n const delayMs = Number.isNaN(parsed)\n ? INITIAL_BACKOFF_MS * 2 ** attempt\n : Math.min(parsed * 1000, MAX_RETRY_DELAY_MS);\n await this.delay(delayMs);\n // WITH `earned`, unlike the network path above: a 429 is a refusal the\n // server issued INSTEAD of doing the work, so the challenge was never\n // consumed. The edge's rate limiter answers before palsvc, and on the\n // auth routes palauth's own limiter runs BEFORE the proof-of-work\n // middleware (auth/internal/server/server.go: rl.LoginByIP, then powMW).\n return this.executeWithRetry<T>(method, path, options, attempt + 1, earned, rotated);\n }\n }\n\n // Parse response body\n let data: T | null = null;\n let errorBody:\n | { error?: string; error_description?: string; status?: number; required?: string }\n | undefined;\n\n // HEAD responses have no body by spec — skip parsing.\n const contentType = response.headers.get('Content-Type');\n if (\n method !== 'HEAD' &&\n ![204, 205, 304].includes(response.status) &&\n contentType?.includes('json')\n ) {\n const body = (await response.json()) as Record<string, unknown>;\n if (response.ok) {\n data = body as T;\n } else {\n errorBody = body as typeof errorBody;\n }\n }\n\n if (\n exporter &&\n !rotated &&\n response.status === 400 &&\n errorBody?.error === 'sealed_unknown_kid'\n ) {\n await this.sealedKeys?.current(options?.signal, true);\n return this.executeWithRetry<T>(method, path, options, attempt, earned, true);\n }\n\n // Proof-of-work: /auth/signup and /auth/token sit behind a bot gate that\n // answers an unsolved request with 403 and the challenge in the body. Solve\n // it and repeat the request carrying the two headers; the caller never\n // learns the gate is there.\n //\n // HERE, in core, because this is the layer that issues the request for every\n // client in the repo — @palbase/auth's sign-in, @palbase/web's facades, the\n // server SDK. The same retry lived one layer up in @palbase/web until\n // 2026-08-18 and covered everything EXCEPT `pb.auth.*`, which reaches the\n // network through this method; so the gate stayed unsatisfiable on exactly\n // the two endpoints it guards.\n //\n // ONE retry, and only when the body really carries a challenge: `earned`\n // being set already means this IS the second try. A 403 that says\n // pow_required without a challenge is a server the client cannot satisfy,\n // and looping on it would turn a broken gate into a hang.\n if (response.status === 403 && !earned) {\n const challenge = asPowChallenge(errorBody);\n if (challenge) {\n return this.executeWithRetry<T>(\n method,\n path,\n options,\n attempt,\n await solvePowChallenge(challenge, undefined, options?.signal),\n rotated,\n );\n }\n }\n\n if (!response.ok) {\n if (response.status === 403 && errorBody !== undefined) {\n const body: Record<string, unknown> = errorBody;\n for (const listener of this.forbiddenListeners) {\n try {\n listener(body);\n } catch {\n // A consumer's handler must not turn a well-formed refusal into a\n // thrown error, nor stop the listeners after it (same rule as\n // internal.ts' configured listeners).\n }\n }\n }\n return {\n data: null,\n error: new PalbaseError(\n errorBody?.error ?? 'unknown_error',\n errorBody?.error_description ?? response.statusText,\n response.status,\n withRetryHint(errorBody, response),\n ),\n status: response.status,\n };\n }\n\n // Parse PostgREST Content-Range for count queries (e.g. \"0-9/42\" or \"*/42\").\n const contentRange = response.headers.get('Content-Range');\n let count: number | undefined;\n if (contentRange) {\n const slash = contentRange.lastIndexOf('/');\n if (slash >= 0) {\n const totalPart = contentRange.slice(slash + 1);\n if (totalPart !== '*') {\n const parsed = Number.parseInt(totalPart, 10);\n if (!Number.isNaN(parsed)) {\n count = parsed;\n }\n }\n }\n }\n\n return {\n data,\n error: null,\n status: response.status,\n ...(count !== undefined ? { count } : {}),\n };\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","import type { AuthStateCallback, Session, Unsubscribe } from './types.js';\n\nexport class TokenManager {\n private session: Session | null = null;\n private listeners: Set<AuthStateCallback> = new Set();\n private refreshPromise: Promise<void> | null = null;\n private refreshing = false;\n\n refreshFunction: ((refreshToken: string) => Promise<Session>) | null = null;\n\n setSession(session: Session): void {\n this.session = session;\n this.notify('SESSION_SET', session);\n }\n\n getAccessToken(): string | null {\n return this.session?.accessToken ?? null;\n }\n\n getRefreshToken(): string | null {\n return this.session?.refreshToken ?? null;\n }\n\n clearSession(): void {\n this.session = null;\n this.notify('SESSION_CLEARED', null);\n }\n\n isExpired(): boolean {\n if (!this.session) return true;\n return Date.now() >= this.session.expiresAt;\n }\n\n async refreshSession(): Promise<void> {\n if (!this.session?.refreshToken || !this.refreshFunction) {\n return;\n }\n\n // Collapse concurrent refresh calls into a single request\n if (this.refreshPromise) {\n return this.refreshPromise;\n }\n\n // Re-entrancy guard: the wired refreshFunction issues its own HTTP request\n // (POST /auth/token/refresh) through HttpClient, whose pre-flight calls\n // refreshSession() again SYNCHRONOUSLY — before `refreshPromise` below is\n // assigned (the whole chain runs before the first real await). Without\n // this flag that recursion is unbounded (stack overflow). Returning early\n // lets the refresh request itself proceed unauthenticated — it carries\n // the refresh token in its body, not the Bearer header.\n if (this.refreshing) {\n return;\n }\n\n this.refreshing = true;\n this.refreshPromise = this.executeRefresh(this.session.refreshToken);\n\n try {\n await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n this.refreshing = false;\n }\n }\n\n onAuthStateChange(callback: AuthStateCallback): Unsubscribe {\n this.listeners.add(callback);\n return () => {\n this.listeners.delete(callback);\n };\n }\n\n private async executeRefresh(refreshToken: string): Promise<void> {\n if (!this.refreshFunction) return;\n const startedSession = this.session;\n try {\n const newSession = await this.refreshFunction(refreshToken);\n // Sign-out, a new sign-in, or another session adoption takes precedence\n // over a refresh that started against an older session.\n if (this.session === startedSession) this.setSession(newSession);\n } catch (error) {\n // The caller would clear its session on a terminal refresh error. An\n // error from an older session must not clear a newer one.\n if (this.session === startedSession) throw error;\n }\n }\n\n private notify(event: 'SESSION_SET' | 'SESSION_CLEARED', session: Session | null): void {\n for (const listener of this.listeners) {\n listener(event, session);\n }\n }\n}\n","/** The client a tenant's tests use to call their own backend.\n *\n * These tests run against a REAL deployment — the release the deploy just built,\n * serving from the same Environment as production, with the same database, the\n * same secrets and the same gateway in front of it. So this client is a plain\n * HTTP client, not a simulation: every call crosses the gateway, the API key\n * check, the auth rail, the zod validation at the boundary, and row-level\n * security, exactly as a shipped app's call does.\n *\n * There is deliberately no schema knowledge here. The tenant already wrote their\n * types — `import type { TodoSchema } from \"../models/todos/shared.js\"` — so a\n * test types its own call (`api.get<TodoSchema[]>(\"/todos\")`) and can validate it\n * with the same zod schema the endpoint declares. A second generated client would\n * be a second thing to keep in step.\n */\n\nimport { asPowChallenge, solvePowChallenge } from \"@palbase/core\";\n\n/** How to reach the release under test. Supplied by the deploy, never guessed. */\nexport interface TestApiConfig {\n baseUrl: string;\n apiKey: string;\n /** This deploy's secret. Without it the request is served the LIVE release.\n *\n * OPTIONAL against a stack running on this machine: a local stack serves one\n * version — the directory `palbase start` mounted — so there is no candidate\n * to select. Required everywhere else. */\n candidateToken?: string;\n /** The run's minted logins, keyed by the name declared in config/test-users.ts. */\n identities?: Record<string, TestIdentity>;\n /** The fetch to use. Injected by tests of this client; production passes none. */\n fetch?: typeof fetch;\n}\n\n/** One login the deploy minted for this run.\n *\n * `accessToken` is the session issued when the identity was created, and is what\n * `signInAs` uses. The credentials come along for a test that wants to exercise\n * the login rail itself — but a suite that switches users repeatedly must not be\n * signing in each time: those calls come from one address and trip the login rate\n * limiter, failing tests for a reason that has nothing to do with the code\n * under test.\n */\nexport interface TestIdentity {\n id?: string;\n email: string;\n password: string;\n accessToken?: string;\n}\n\n/** One call the suite made, in the order it was made. */\nexport interface RecordedRequest {\n method: string;\n path: string;\n status: number;\n ms: number;\n}\n\n/** A non-2xx answer, carrying the platform's error envelope.\n *\n * The envelope is the contract every Palbase endpoint answers with, so a test\n * asserts on `status`/`error`/`data` rather than parsing a message. The message\n * exists for the human reading a failed deploy.\n */\nexport class TestApiError extends Error {\n readonly status: number;\n readonly error: string;\n /** Payload of an error your code threw — `new BadRequest({ fields })` arrives here. */\n readonly data: unknown;\n /** The whole envelope, exactly as the server sent it. */\n readonly body: ErrorEnvelope;\n\n constructor(method: string, path: string, status: number, body: unknown) {\n const envelope = (body ?? {}) as ErrorEnvelope;\n const code = envelope.error ?? String(status);\n super(`${method} ${path} → ${status} ${code}${envelope.error_description ? `: ${envelope.error_description}` : \"\"}`);\n this.name = \"TestApiError\";\n this.status = status;\n this.error = code;\n this.data = envelope.data;\n this.body = envelope;\n }\n}\n\n/** A Palbase error response.\n *\n * `data` carries the payload of an error your code threw. Validation refused at\n * the boundary — before your handler runs — answers with `details` instead, one\n * entry per field. The index signature is deliberate: whatever the server sends\n * is readable from a test, so no assertion is ever blocked on this type being\n * exhaustive.\n */\nexport interface ErrorEnvelope {\n error?: string;\n error_description?: string;\n status?: number;\n request_id?: string;\n data?: unknown;\n details?: Array<{ field: string; message: string }>;\n [key: string]: unknown;\n}\n\nexport interface CallOptions {\n headers?: Record<string, string>;\n}\n\nexport interface TestApi {\n get<T = unknown>(path: string, opts?: CallOptions): Promise<T>;\n post<T = unknown>(path: string, body?: unknown, opts?: CallOptions): Promise<T>;\n patch<T = unknown>(path: string, body?: unknown, opts?: CallOptions): Promise<T>;\n put<T = unknown>(path: string, body?: unknown, opts?: CallOptions): Promise<T>;\n delete<T = unknown>(path: string, opts?: CallOptions): Promise<T>;\n /** HTTP QUERY (RFC 10008): a safe, idempotent read whose filter travels in the body. */\n query<T = unknown>(path: string, body?: unknown, opts?: CallOptions): Promise<T>;\n /** Sign in with credentials you supply. */\n signIn(credentials: { email: string; password: string }): Promise<{ id: string; email?: string }>;\n /**\n * Sign in as one of the identities this run was given, by the name you\n * declared it under in `config/test-users.ts`.\n *\n * Each is minted by the platform for the length of ONE deploy, seeded with the\n * data that declaration describes, and retired after — which is why this works\n * on every Environment including production, where a committed fixture password\n * is refused on purpose.\n */\n signInAs(name: string): Promise<{ id: string; email?: string }>;\n signOut(): Promise<void>;\n /** Drop the bearer without calling the server — the anonymous caller. */\n asAnonymous(): void;\n /** Every call made, in order. Printed for the failing test in a red deploy. */\n readonly requests: readonly RecordedRequest[];\n}\n\nfunction required(value: string, envName: string): string {\n if (!value) {\n throw new Error(\n `${envName} is not set — the test client has nowhere to send requests. ` +\n `This is set by the deploy that runs your tests; if you are running them by hand, set it yourself.`,\n );\n }\n return value;\n}\n\n/** A stack running on this machine. There is exactly ONE version there — the\n * directory `palbase start` mounted — so there is no candidate to select, and\n * demanding a token for one made local runs invent a value to satisfy a header\n * nothing reads. */\nfunction isLocalTarget(baseUrl: string): boolean {\n try {\n const { hostname } = new URL(baseUrl);\n return hostname === \"127.0.0.1\" || hostname === \"localhost\" || hostname === \"[::1]\" || hostname === \"::1\";\n } catch {\n return false;\n }\n}\n\n/** Seconds until a JWT's `exp`, or null when the token carries no readable one.\n * Read WITHOUT verifying: this is a diagnosis, never a decision — the server\n * remains the only authority on whether a token is good. */\nfunction secondsUntilExpiry(token: string): number | null {\n const body = token.split(\".\")[1];\n if (!body) return null;\n try {\n const claims = JSON.parse(Buffer.from(body, \"base64url\").toString(\"utf8\")) as { exp?: unknown };\n return typeof claims.exp === \"number\" ? claims.exp - Math.floor(Date.now() / 1000) : null;\n } catch {\n return null;\n }\n}\n\nexport function createTestApi(config: TestApiConfig): TestApi {\n const baseUrl = required(config.baseUrl, \"PALBASE_TEST_BASE_URL\").replace(/\\/$/, \"\");\n const apiKey = required(config.apiKey, \"PALBASE_TEST_API_KEY\");\n const local = isLocalTarget(baseUrl);\n // Local stacks serve one version, so there is nothing to select. Everywhere\n // else the token stays REQUIRED: without it the gateway serves the LIVE\n // release and the suite would grade code that is not under test.\n const candidateToken = local ? (config.candidateToken ?? \"\") : required(config.candidateToken ?? \"\", \"PALBASE_TEST_CANDIDATE\");\n const doFetch = config.fetch ?? fetch;\n\n const requests: RecordedRequest[] = [];\n let bearer: string | null = null;\n\n async function call<T>(method: string, path: string, body: unknown, opts: CallOptions = {}): Promise<T> {\n const headers: Record<string, string> = {\n apikey: apiKey,\n // Selects the release under test. Omit it and the gateway serves the LIVE\n // one, which would make the whole suite grade the wrong code. Absent only\n // against a local stack, which has a single version.\n ...(candidateToken ? { \"x-palbase-candidate\": candidateToken } : {}),\n ...opts.headers,\n };\n if (bearer) headers.authorization = `Bearer ${bearer}`;\n if (body !== undefined) headers[\"content-type\"] = \"application/json\";\n\n const startedAt = Date.now();\n const res = await doFetch(`${baseUrl}${path}`, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n const text = await res.text();\n const parsed: unknown = text ? safeParse(text) : undefined;\n\n requests.push({ method, path, status: res.status, ms: Date.now() - startedAt });\n\n if (!res.ok) {\n // A 401 on a token that has simply RUN OUT is the most likely 401 a suite\n // sees, and the least legible: the mint issues ~30 minutes, so a file of\n // credentials written yesterday answers `401 unauthorized` with nothing to\n // act on. Measured on a customer run: the next step taken was to blame the\n // credentials rather than their age.\n if (res.status === 401 && bearer) {\n const left = secondsUntilExpiry(bearer);\n if (left !== null && left <= 0) {\n throw new TestApiError(method, path, res.status, {\n error: \"access_token_expired\",\n error_description:\n `this run's access token EXPIRED ${Math.abs(left)}s ago — a test identity is minted for the ` +\n `length of ONE deploy, so a saved token does not survive to the next run. Re-mint it ` +\n \"(`palbase test-user create --json`, or let `palbase test` do it) and run again.\",\n });\n }\n }\n throw new TestApiError(method, path, res.status, parsed);\n }\n return parsed as T;\n }\n\n return {\n requests,\n get: (path, opts) => call(\"GET\", path, undefined, opts),\n post: (path, body, opts) => call(\"POST\", path, body, opts),\n patch: (path, body, opts) => call(\"PATCH\", path, body, opts),\n put: (path, body, opts) => call(\"PUT\", path, body, opts),\n delete: (path, opts) => call(\"DELETE\", path, undefined, opts),\n query: (path, body, opts) => call(\"QUERY\", path, body, opts),\n\n async signInAs(name) {\n const identity = (config.identities ?? {})[name];\n if (!identity) {\n const declared = Object.keys(config.identities ?? {});\n throw new Error(\n `no test identity named ${JSON.stringify(name)} — the deploy mints one per user declared in ` +\n `config/test-users.ts` +\n (declared.length\n ? `; this run has: ${declared.join(\", \")}`\n : // Not \"you declared none\": from here the two causes are\n // indistinguishable, and blaming the customer's config for a\n // platform failure sends them to look in the wrong file. The\n // deploy log names which one it was.\n \", and this run has none — either your config declares no users \" +\n \"or the deploy could not mint them; the deploy log says which\"),\n );\n }\n // The session the mint already issued — no network call, so switching\n // users is free and the login rail never sees this run.\n if (identity.accessToken) {\n bearer = identity.accessToken;\n return { id: identity.id ?? \"\", email: identity.email };\n }\n return this.signIn(identity);\n },\n\n async signIn(credentials) {\n // PROOF-OF-WORK IS PART OF LOGGING IN, so a client that cannot solve one\n // cannot log in at all. The web SDK has solved it since bot protection\n // shipped; this harness went straight to `fetch` and therefore answered\n // `403 pow_required` on every password login — which made the whole\n // credentials path DEAD on a stack with the gate on, exactly when a\n // suite falls back to it because its minted token ran out.\n //\n // One retry, and only when the refusal really carries a challenge: a 403\n // saying pow_required without one is a server this client cannot satisfy,\n // and looping would turn a broken gate into a hang. Same rule as\n // @palbase/core's own retry.\n const attempt = async (extra?: Record<string, string>) =>\n call<{ access_token: string; user?: { id: string; email?: string } }>(\n \"POST\",\n \"/auth/login\",\n credentials,\n extra ? { headers: extra } : {},\n );\n\n let result: { access_token: string; user?: { id: string; email?: string } };\n try {\n result = await attempt();\n } catch (e) {\n const refusal = e as { status?: number; body?: unknown };\n const challenge = refusal.status === 403 ? asPowChallenge(refusal.body) : null;\n if (!challenge) throw e;\n result = await attempt(await solvePowChallenge(challenge));\n }\n bearer = result.access_token;\n return result.user ?? { id: \"\" };\n },\n async signOut() {\n await call(\"POST\", \"/auth/logout\", undefined);\n bearer = null;\n },\n asAnonymous() {\n bearer = null;\n },\n };\n}\n\n/** The run's identities, as the deploy passed them. Absent is not an error: a\n * project that declares none still runs every test that needs no login. */\nfunction parseIdentities(raw: string | undefined): Record<string, TestIdentity> {\n if (!raw) return {};\n try {\n return JSON.parse(raw) as Record<string, TestIdentity>;\n } catch {\n return {};\n }\n}\n\nfunction safeParse(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/** The client the deploy configured, from the environment it set.\n *\n * Constructed lazily so importing this module outside a test run — a typecheck,\n * an editor — does not fail on absent configuration.\n */\nlet configured: TestApi | null = null;\n\nexport const api: TestApi = new Proxy({} as TestApi, {\n get(_target, prop) {\n configured ??= createTestApi({\n baseUrl: process.env.PALBASE_TEST_BASE_URL ?? \"\",\n apiKey: process.env.PALBASE_TEST_API_KEY ?? \"\",\n candidateToken: process.env.PALBASE_TEST_CANDIDATE ?? \"\",\n identities: parseIdentities(process.env.PALBASE_TEST_IDENTITIES),\n });\n return Reflect.get(configured, prop, configured);\n },\n});\n","import \"reflect-metadata\";\n\nimport type { Token } from \"../container.js\";\n\nexport interface IsolatedContainer {\n /** Substitutes a token. Chainable; the last write for a token wins. */\n with<T>(t: Token<T>, v: T): IsolatedContainer;\n get<T>(t: Token<T>): T;\n}\n\n/**\n * How a test replaces a dependency.\n *\n * Rebuilds the graph with the overrides in place and never touches the process\n * singleton cache, so the next test in the same process does not meet a doubled\n * instance left behind by this one. Substitution is DEEP: `Report` asks for\n * `Money` and gets whatever the graph was rebuilt with, however many hops down.\n *\n * Substitution is by `with` alone — there is no separate platform map, because\n * platform services are ambient rather than injected (FR-005).\n *\n * Module boundaries are NOT enforced here, deliberately. They are a build-time\n * rule about the shipped application; making a unit test fail on them would\n * force every test to restate a module layout it is not testing. What a test\n * gets is a graph, not a second opinion about the architecture.\n */\nexport function isolated(): IsolatedContainer {\n const over = new Map<Token, unknown>();\n const local = new Map<Token, unknown>();\n\n const make = (c: Token): unknown => {\n if (over.has(c)) return over.get(c);\n const hit = local.get(c);\n if (hit !== undefined) return hit;\n const meta = (Reflect.getMetadata(\"design:paramtypes\", c) as unknown[] | undefined) ?? [];\n const inst = new (c as unknown as new (...a: unknown[]) => unknown)(\n ...meta.map((d) => make(d as Token)),\n );\n local.set(c, inst);\n return inst;\n };\n\n const api: IsolatedContainer = {\n with<T>(t: Token<T>, v: T): IsolatedContainer {\n over.set(t as Token, v);\n return api;\n },\n get<T>(t: Token<T>): T {\n return make(t as Token) as T;\n },\n };\n return api;\n}\n","import type { DBClient, DBOps } from \"../../endpoint.js\";\nimport { validateInsertManyOptions, type InsertManyOptions } from \"../../db/bulk.js\";\n// The SAME refusals the engine applies. Without these the fake accepted every\n// call the driver path had just started rejecting, and the scaffold points\n// authors at this fake to test their services — so the test went green and\n// production threw. Measured against the published 24.1.0.\nimport { assertUsableFilter, assertUsableWriteValues, assertNoExpressionHandles, isColRef, isSqlFragment, isNowExpr, isColumnExpr } from \"../../db/input-guards.js\";\n\n/**\n * `sqlFragment` sahte veritabanında ÇALIŞTIRILAMAZ — ve sessizce yok sayılamaz.\n *\n * Fake'in bir SQL değerlendiricisi yok. Fragment'i görmezden gelmek, filtreyi\n * hiç uygulamamak demektir: test TÜM satırları görür, üretim ise süzülmüş\n * satırları. Yazarın testi o gün yeşil, üretim yanlış olur — bu dosyanın var\n * olma sebebi tam olarak o sınıf hata. O yüzden adıyla reddediliyor, ve hata\n * çalışan bir alternatif söylüyor (P6).\n */\nfunction refuseFragment(caller: string, table: string, where: unknown): void {\n if (isSqlFragment(where)) {\n throw new Error(\n `${caller}(${table}): fakeDatabase bir sqlFragment'i değerlendiremez — sahte depo SQL çalıştırmaz. ` +\n `Filtreyi tipli filtre diliyle kurun (gt/gte/lt/lte/neq/in/contains/isNull, OR/AND/NOT), ` +\n `ya da bu testi gerçek bir Postgres'e karşı yazın.`,\n );\n }\n // İÇ İÇE de reddedilir. Yalnız ÜST DÜZEYE bakmak, { OR: [ sqlFragment tag, … ] }\n // filtresini fake'te SESSİZCE boş sonuca çeviriyordu; motor onu derliyor\n // (W2-B/C5, ölçüldü). Reddin de bileşim dallarını dolaşması gerekiyor.\n if (where === null || typeof where !== \"object\") return;\n for (const [k, v] of Object.entries(where as Record<string, unknown>)) {\n if (k === \"OR\" || k === \"AND\") {\n for (const branch of (Array.isArray(v) ? v : [])) refuseFragment(caller, table, branch);\n } else if (k === \"NOT\") {\n refuseFragment(caller, table, v);\n }\n }\n}\n\n/**\n * Sayaç aritmetiği — motorun döndürdüğü ALANDA.\n *\n * Postgres `numeric` kolonu STRING döndürür ve toplamayı tam yapar. Fake\n * `Number()` ile hesaplıyordu; ölçülen sonuçlar: `\"0.10\" + \"0.20\"` →\n * `0.30000000000000004`, `\"12345678901234567890\" + 1` →\n * `12345678901234567000`, ve satırın tipi string'den number'a KAYIYORDU.\n * D-007'nin (string miktar) var olma sebebi tam olarak bu kayıptı; fake onu\n * geri getiriyordu (inceleme I-4/I-3).\n *\n * `null` + n = `null`: Postgres'te de öyle, satır değişmez.\n */\nfunction addDecimal(cell: unknown, by: number | string, sign: 1 | -1): unknown {\n if (cell === null || cell === undefined) return null;\n if (typeof cell === \"number\" && typeof by === \"number\") return cell + sign * by;\n const a = String(cell);\n const b = String(by);\n const parse = (x: string): { unit: bigint; scale: number } | null => {\n const m = /^([+-]?)(\\d*)(?:\\.(\\d*))?$/.exec(x.trim());\n if (m === null || (m[2] === \"\" && (m[3] ?? \"\") === \"\")) return null;\n const frac = m[3] ?? \"\";\n const unit = BigInt(`${m[1] === \"-\" ? \"-\" : \"\"}${m[2] === \"\" ? \"0\" : m[2]}${frac}`);\n return { unit, scale: frac.length };\n };\n const pa = parse(a);\n const pb = parse(b);\n if (pa === null || pb === null) {\n // Motor bu durumda Postgres'e sorar ve `operator does not exist:\n // text + integer` alır. Sessizce NaN yazmak yerine ADIYLA reddediyoruz.\n throw new Error(\n `fakeDatabase: increment()/decrement() sayısal olmayan bir değere uygulandı (\"${a}\") — ` +\n `Postgres bunu \"operator does not exist\" ile reddeder.`,\n );\n }\n const scale = Math.max(pa.scale, pb.scale);\n const lift = (v: { unit: bigint; scale: number }): bigint =>\n v.unit * 10n ** BigInt(scale - v.scale);\n const total = lift(pa) + BigInt(sign) * lift(pb);\n if (scale === 0) return typeof cell === \"number\" ? Number(total) : total.toString();\n const neg = total < 0n;\n const digits = (neg ? -total : total).toString().padStart(scale + 1, \"0\");\n const out = `${neg ? \"-\" : \"\"}${digits.slice(0, -scale)}.${digits.slice(-scale)}`;\n return typeof cell === \"number\" ? Number(out) : out;\n}\nimport { columnExprOf } from \"../../db/tx-plan.js\";\nimport type {\n TxPlanBody,\n TxPlanOpResult,\n TxPlanRejection,\n TxPlanResponse,\n TxWireGuard,\n TxWireOp,\n TxWireValue,\n} from \"../../db/tx-plan.js\";\n\n/** Tracked records for assertions. */\ninterface TrackedRecords {\n inserted: Map<string, Record<string, unknown>[]>;\n updated: Map<string, Record<string, unknown>[]>;\n deleted: Map<string, string[]>;\n}\n\n/** Mock DB client with tracking and seed data support. */\n/**\n * TEK EŞLEŞTİRİCİ — `findMany`, `updateMany`, `deleteMany` ve `count` bunu\n * kullanır.\n *\n * Motorda tek bir `compileWhereBare` var; fake'te DÖRT ayrı eşleştirici vardı\n * ve üçü yalnız katı eşitliğe bakıyordu. Ölçülen sonuç (inceleme C3/C6/I2):\n * `updateMany({ id, balance: { gte: \"5.00\" } }, …)` fake'te HİÇBİR satır\n * eşleştirmiyordu, yani FR-014'ün doc'unun ÖĞRETTİĞİ \"yetersiz bakiye\" deseni\n * fake'e karşı HER ZAMAN başarısız dala düşüyor — yazar başarı yolunu hiç test\n * edemiyor, üretimde para gerçekten çekiliyor.\n */\nfunction rowMatchesFilter(\n caller: string,\n table: string,\n row: Record<string, unknown>,\n f: Record<string, unknown>,\n): boolean {\n return Object.entries(f).every(([k, c]) => {\n if (k === \"OR\") return (c as Record<string, unknown>[]).some((b) => rowMatchesFilter(caller, table, row, b));\n if (k === \"AND\") return (c as Record<string, unknown>[]).every((b) => rowMatchesFilter(caller, table, row, b));\n if (k === \"NOT\") return !rowMatchesFilter(caller, table, row, c as Record<string, unknown>);\n // `has` ilişki GRAFİĞİ ister ve sahte deponun grafiği YOK — tablolar bir\n // Map'te, aralarındaki yabancı anahtarlar hiçbir yerde. Sessizce yok saymak\n // filtreyi hiç uygulamamak olurdu: test TÜM satırları görür, üretim\n // süzülmüş satırları. Bu dosyanın var olma sebebi tam olarak o sınıf.\n if (k === \"has\") {\n throw new Error(\n `${caller}(${table}): fakeDatabase bir \\`has\\` filtresini çözemez — ilişki grafiği ` +\n `bildirimden türetiliyor ve sahte deponun bildirimi yok. Bu testi gerçek bir Postgres'e ` +\n `karşı yazın, ya da ilişkiyi filtrede AÇIKÇA kurun (önce ilişki tablosunu okuyup ` +\n `{ id: { in: [...] } } ile süzün).`,\n );\n }\n return matchesCell(caller, table, row, k, c);\n });\n}\n\n/**\n * SQL'in üç değerli mantığı: NULL taşıyan karşılaştırma UNKNOWN'dır, yani satır\n * EŞLEŞMEZ. Fake `===` kullanıyordu ve iki NULL kolonu EŞİT sayıyordu — motorun\n * her yerde uyguladığı FR-006 doktrininin tersi (inceleme I3, ölçüldü).\n */\nfunction cmp(a: unknown, b: unknown, op: string): boolean {\n if (a === null || a === undefined || b === null || b === undefined) return false;\n const l = a instanceof Date ? a.getTime() : a;\n const r = b instanceof Date ? b.getTime() : b;\n switch (op) {\n case \"eq\": return l === r;\n case \"neq\": return l !== r;\n case \"gt\": return (l as number) > (r as number);\n case \"gte\": return (l as number) >= (r as number);\n case \"lt\": return (l as number) < (r as number);\n case \"lte\": return (l as number) <= (r as number);\n default: return false;\n }\n}\n\nfunction matchesCell(\n caller: string,\n table: string,\n row: Record<string, unknown>,\n key: string,\n cond: unknown,\n): boolean {\n // Kolon-kolon karşılaştırma (FR-011) — motorla PARİTE. Fake `col()`'u\n // tanımasaydı `{ $col: \"x\" }` nesnesini DEĞER sanıp eşitlik kurar, hiçbir\n // satır dönmez ve yazarın testi sessizce boş sonuca geçerdi.\n if (isColRef(cond)) return cmp(row[key], row[cond.$col], \"eq\");\n // `now()` — motorla PARİTE. Tutamak bir Proxy, yani `Object.entries` BOŞ\n // döner ve `.every()` boş listede TRUE'dur: ayırt edilmezse koşul HER SATIRLA\n // eşleşirdi. Yani \"süresi geçmemişler\" filtresi testte süresi geçenleri de\n // döndürür, test yeşil kalır ve üretimde davranış AYRIŞIRDI.\n if (isNowExpr(cond)) return cmp(row[key], new Date().toISOString(), \"eq\");\n if (cond !== null && typeof cond === \"object\" && !Array.isArray(cond)) {\n return Object.entries(cond as Record<string, unknown>).every(([op, v]) => {\n const cell = row[key];\n if (isNowExpr(v)) {\n if (![\"neq\", \"gt\", \"gte\", \"lt\", \"lte\"].includes(op)) {\n throw new Error(`${caller}(${table}): where.${key}.${op} now() ile kullanılamaz`);\n }\n return cmp(cell, new Date().toISOString(), op);\n }\n if (isColumnExpr(v)) {\n throw new Error(\n `${caller}(${table}): where.${key}.${op} bir YAZMA ifadesi aldı (increment/decrement) — ` +\n `karşılaştırma değeri değil. Sunucu saati için now() kullanın.`,\n );\n }\n if (isColRef(v)) {\n if (![\"neq\", \"gt\", \"gte\", \"lt\", \"lte\"].includes(op)) {\n throw new Error(`${caller}(${table}): where.${key}.${op} col() ile kullanılamaz`);\n }\n return cmp(cell, row[v.$col], op);\n }\n switch (op) {\n case \"in\":\n if (!Array.isArray(v)) throw new Error(`${caller}(${table}): where.${key}.in bir dizi olmalı`);\n if (v.some(isColRef)) {\n throw new Error(\n `${caller}(${table}): where.${key}.in col() ile kullanılamaz — kolon karşılaştırması için gt/gte/lt/lte/neq kullanın`,\n );\n }\n return v.includes(cell);\n case \"neq\": case \"gt\": case \"gte\": case \"lt\": case \"lte\":\n return cmp(cell, v, op);\n // K1 metin operatörleri (FR-005) ve null testi (FR-006). Bunlar BURADA\n // da olmak zorunda: guard onları KABUL ettiği anda fake sessizce yanlış\n // cevap verir ve yazarın testi, üretimde farklı davranan koda karşı\n // yeşil verirdi (input-guards.ts'in uyardığı tam sınıf).\n case \"isNull\":\n if (typeof v !== \"boolean\") throw new Error(`${caller}(${table}): where.${key}.isNull bir boolean olmalı`);\n return v ? cell == null : cell != null;\n case \"contains\": case \"icontains\": case \"startsWith\": case \"endsWith\": {\n if (typeof v !== \"string\") throw new Error(`${caller}(${table}): where.${key}.${op} bir string olmalı`);\n if (typeof cell !== \"string\") return false;\n if (op === \"contains\") return cell.includes(v);\n if (op === \"icontains\") return cell.toLowerCase().includes(v.toLowerCase());\n if (op === \"startsWith\") return cell.startsWith(v);\n return cell.endsWith(v);\n }\n default:\n throw new Error(`${caller}(${table}): where.${key} bilinmeyen operatör \"${op}\"`);\n }\n });\n }\n return row[key] === cond;\n}\n\nexport interface MockDBClient extends DBClient {\n /** Get records inserted into a table. */\n inserted(table: string): Record<string, unknown>[];\n /** Get records updated in a table. */\n updated(table: string): Record<string, unknown>[];\n /** Get IDs deleted from a table. */\n deleted(table: string): string[];\n /** Pre-seed data into a table for findById/findMany. */\n seed(table: string, data: Record<string, unknown>[]): void;\n}\n\n/** Create a mock DB client with in-memory tracking. */\nexport function createMockDB(): MockDBClient {\n const store = new Map<string, Record<string, unknown>[]>();\n const tracked: TrackedRecords = {\n inserted: new Map(),\n updated: new Map(),\n deleted: new Map(),\n };\n\n function rowsOf(table: string): Record<string, unknown>[] {\n let rows = store.get(table);\n if (!rows) {\n rows = [];\n store.set(table, rows);\n }\n return rows;\n }\n\n function track(\n map: Map<string, Record<string, unknown>[]>,\n table: string,\n row: Record<string, unknown>,\n ): void {\n const list = map.get(table);\n if (list) list.push(row);\n else map.set(table, [row]);\n }\n\n/**\n * EKLEME yolunda değerleri motorun yaptığı gibi çöz — `now()` sunucu saati,\n * sayaç ifadesi adıyla ret.\n *\n * Fake bunu bilmeseydi `assertNoExpressionHandles` `now()`'ı reddeder, test\n * kırmızı olur ve yazar ÇALIŞAN bir çağrıyı bozuk sanırdı. Sürüm 28'de motor\n * beş ekleme kurucusunun hepsinde `now()` derliyor.\n */\nfunction resolveInsertValues(\n caller: string,\n table: string,\n data: Record<string, unknown>,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(data)) {\n const expr = columnExprOf(v);\n if (expr !== null && expr.fn === \"now\") {\n out[k] = new Date().toISOString();\n continue;\n }\n if (expr !== null) {\n throw new Error(\n `${caller}(${table}): \"${k}\" ${expr.fn === \"inc\" ? \"increment()\" : \"decrement()\"} aldı — ` +\n `satır HENÜZ YOK, yani \"kolonun şu anki değeri\" diye bir şey yok.`,\n );\n }\n out[k] = v;\n }\n return out;\n}\n\n // Build the op surface first (the six string-keyed ops). `txPlan` below\n // interprets a whole plan against the SAME in-memory store and tracking maps,\n // so a transaction's writes are visible to later assertions exactly as a\n // direct write would be.\n const ops: DBOps = {\n diagnostics: () => null,\n // The bulk ops and count run against the SAME in-memory store the direct\n // ops write to, so a test that writes three rows and counts them gets 3 —\n // a mock that answered 0 would make the surface look broken in exactly the\n // tests meant to prove it works.\n async updateMany(\n table: string,\n where: Record<string, unknown>,\n set: Record<string, unknown>,\n opts?: { returning?: boolean },\n ) {\n if (Object.keys(where).length === 0) throw new Error(`updateMany(${table}): boş filtre`);\n assertUsableFilter(\"updateMany\", table, where);\n refuseFragment(\"updateMany\", table, where);\n assertUsableWriteValues(\"updateMany\", table, Object.keys(set), set);\n const hit = (store.get(table) ?? []).filter((r) =>\n rowMatchesFilter(\"updateMany\", table, r, where),\n );\n // increment()/decrement() (FR-012) — motorla PARİTE. Fake ifadeyi DEĞER\n // sanıp yazsaydı, sayaç kolonu bir proxy nesnesine dönerdi ve yazarın\n // testi \"artış oldu\" diye değil, sessizce bozuk veriyle geçerdi.\n for (const row of hit) {\n for (const [k, v] of Object.entries(set)) {\n const expr = columnExprOf(v);\n if (expr !== null && expr.fn === \"now\") {\n // Motor `SET col = now()` derliyor; fake'in karşılığı bir zaman damgası.\n row[k] = new Date();\n continue;\n }\n if (expr !== null) {\n row[k] = addDecimal(row[k], expr.by as number | string, expr.fn === \"inc\" ? 1 : -1);\n continue;\n }\n row[k] = v;\n }\n }\n // HER YAZMA `updated()`'a DÜŞER. `update` ve tx-plan'ın update op'u zaten\n // kaydediyordu; `updateMany` kaydetmiyordu, yani defter YARI KÖRDÜ:\n // servisini `updateMany` ile yazan bir tüketici\n // `expect(fake.updated(\"accounts\")).toEqual([])` yazar ve yazma GERÇEKTEN\n // olduğu hâlde yeşil alırdı — FR-008'in aynadaki hâli.\n for (const row of hit) track(tracked.updated, table, row);\n\n // `returning: false` SAYI döndürür, dizi değil — motor gibi\n // (engine/db.ts) ve tipli yüzeyin daralttığı gibi (db/typed-db.ts).\n // Sahte daima dizi döndürdüğü sürece\n // const n = await db.updateMany(t, w, s, { returning: false });\n // if (n === 0) throw new Conflict(...)\n // guard'ı testte HİÇ çalışmaz ([] === 0 değil), üretimde çalışır: test\n // yeşil, canlıda 409. `update`→null ile aynı sınıf yalan.\n return opts?.returning === false ? hit.length : hit;\n },\n async deleteMany(table: string, where: Record<string, unknown>) {\n if (Object.keys(where).length === 0) throw new Error(`deleteMany(${table}): boş filtre`);\n assertUsableFilter(\"deleteMany\", table, where);\n refuseFragment(\"deleteMany\", table, where);\n const list = store.get(table) ?? [];\n const keep = list.filter((r) => !rowMatchesFilter(\"deleteMany\", table, r, where));\n store.set(table, keep);\n return list.length - keep.length;\n },\n async count(table: string, where: Record<string, unknown> = {}) {\n assertUsableFilter(\"count\", table, where);\n // `refuseFragment` burada ATLANMIŞTI: fragment'li count fake'te sessizce\n // 0 döndürüyordu, motor gerçek sayıyı (W2-B/C4).\n refuseFragment(\"count\", table, where);\n return (store.get(table) ?? []).filter((r) =>\n rowMatchesFilter(\"count\", table, r, where),\n ).length;\n },\n async search(_table: string, _params?: Record<string, unknown>) {\n return [];\n },\n async facets(_table: string, _params?: Record<string, unknown>) {\n return {};\n },\n async similar() {\n return [];\n },\n async recommend() {\n return [];\n },\n async supersede(_table: string, _id: string, row: Record<string, unknown>) {\n return { id: crypto.randomUUID(), ...row };\n },\n async query(_sql: string, _params?: unknown[]) {\n return [];\n },\n\n async insert(table: string, raw: Record<string, unknown>) {\n const data = resolveInsertValues(\"insert\", table, raw);\n assertUsableWriteValues(\"insert\", table, Object.keys(data), data);\n // Motorla PARİTE: ifade tutamağı bu yolda değer değildir. Fake onu\n // satıra YAZIYORDU; satır artık JSON'a bile çevrilemiyordu.\n assertNoExpressionHandles(\"insert\", table, Object.keys(data), data);\n const record = { id: crypto.randomUUID(), ...data };\n rowsOf(table).push(record);\n track(tracked.inserted, table, record);\n return record;\n },\n\n /**\n * `insertMany` — motorla PARİTE, ANAHTAR KÜMESİ kuralı dahil.\n *\n * Fake bu kuralı bilmeseydi farklı şekilli satırları kabul eder, test yeşil\n * kalır, üretimde motor adıyla reddederdi — yani fake, sürüm atlamayı\n * kolaylaştırmak yerine gizlerdi.\n */\n /**\n * `aggregate` — motorla PARİTE, PARA KESİNLİĞİ dahil.\n *\n * Fake toplamayı JS `number` ile yapsaydı test yeşil kalır ve üretimde\n * `numeric` kesinliği kaybolurdu — yani fake tam da korunması gereken şeyi\n * gizlerdi. `addDecimal` BigInt ölçekli toplama yapıyor, motorun\n * `sum(numeric)::text`'inin karşılığı.\n */\n async aggregate(table: string, q: Parameters<DBOps[\"aggregate\"]>[1]) {\n const rows = (store.get(table) ?? []).filter((r) =>\n q.where === undefined || rowMatchesFilter(\"aggregate\", table, r, q.where),\n );\n const groups = q.groupBy ?? [];\n const shape = (bucket: Record<string, unknown>[]): Record<string, unknown> => {\n const out: Record<string, unknown> = {};\n for (const c of q.sum ?? []) {\n const vals = bucket.map((r) => r[c]).filter((v) => v !== null && v !== undefined);\n ((out[\"sum\"] ??= {}) as Record<string, unknown>)[c] =\n vals.length === 0 ? null : String(vals.reduce<string | number>((a, v) => addDecimal(a, v as string | number, 1) as string, \"0\"));\n }\n for (const c of q.avg ?? []) {\n const vals = bucket.map((r) => r[c]).filter((v) => v !== null && v !== undefined);\n ((out[\"avg\"] ??= {}) as Record<string, unknown>)[c] =\n vals.length === 0\n ? null\n : String(Number(vals.reduce<string | number>((a, v) => addDecimal(a, v as string | number, 1) as string, \"0\")) / vals.length);\n }\n for (const [fn, pick] of [[\"min\", -1], [\"max\", 1]] as const) {\n for (const c of q[fn] ?? []) {\n const vals = bucket.map((r) => r[c]).filter((v) => v !== null && v !== undefined);\n ((out[fn] ??= {}) as Record<string, unknown>)[c] =\n vals.length === 0\n ? null\n : vals.reduce((a, v) => (cmp(v, a, pick === 1 ? \"gt\" : \"lt\") ? v : a));\n }\n }\n if (q.count === true) out[\"count\"] = bucket.length;\n return out;\n };\n if (groups.length === 0) return shape(rows);\n const byKey = new Map<string, Record<string, unknown>[]>();\n for (const r of rows) {\n const k = JSON.stringify(groups.map((c) => r[c]));\n byKey.set(k, [...(byKey.get(k) ?? []), r]);\n }\n return [...byKey.values()].map((bucket) => {\n const out = shape(bucket);\n for (const c of groups) out[c] = bucket[0]![c];\n return out;\n });\n },\n\n insertMany: (async function(table: string, rows: readonly Record<string, unknown>[], opts?: InsertManyOptions) {\n validateInsertManyOptions(opts);\n if (opts?.onConflict?.length) throw new Error(\"fakeDatabase insertMany cannot enforce PostgreSQL unique constraints; use an integration test for onConflict\");\n if (rows.length === 0) return opts?.returning === false ? 0 : [];\n const cols = Object.keys(rows[0]!);\n for (let i = 1; i < rows.length; i++) {\n const missing = cols.filter((c) => !(c in rows[i]!));\n const extra = Object.keys(rows[i]!).filter((k) => !cols.includes(k));\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `insertMany(${table}): ${i}. satırın kolonları ilk satırla aynı değil` +\n (missing.length > 0 ? ` (eksik: ${missing.join(\", \")})` : \"\") +\n (extra.length > 0 ? ` (fazla: ${extra.join(\", \")})` : \"\") +\n `. Eksikler için null yazın, ya da farklı şekilli satırları ayrı çağrılarda ekleyin.`,\n );\n }\n }\n const out: Record<string, unknown>[] = [];\n for (const rawRow of rows) {\n const data = resolveInsertValues(\"insertMany\", table, rawRow);\n assertUsableWriteValues(\"insertMany\", table, cols, data);\n assertNoExpressionHandles(\"insertMany\", table, cols, data);\n const record = { id: crypto.randomUUID(), ...data };\n rowsOf(table).push(record);\n track(tracked.inserted, table, record);\n out.push(record);\n }\n return opts?.returning === false ? out.length : out;\n }) as DBOps[\"insertMany\"],\n\n /**\n * `claim` — motorla PARİTE (FR-033).\n *\n * Fake bunu sunmasaydı `claim` ile yazılmış bir servis, iskelenin yazarlara\n * önerdiği test yolunda `undefined is not a function` verirdi; sunup da\n * FARKLI davransaydı (ör. hep `inserted: true`) idempotency testi üretimde\n * çalışmayan koda karşı yeşil olurdu.\n *\n * Anahtar ZATEN VARSA var olan satır dönüyor ve hiçbir şey yazılmıyor —\n * motorun 23505 dalının aynısı.\n */\n /**\n * `lockRows` — sahte depoda kilit YOKTUR, ama çağrı da patlamamalı.\n *\n * Motorla parite burada \"aynı SQL\" değil, \"aynı SÖZLEŞME\": boş liste\n * no-op, tekrar edenler tekilleşir, ve PK'sı olmayan tablo adıyla\n * reddedilir. Kilidin kendisi tek işlemli bir sahte depoda anlamsız —\n * ama sözleşmeyi bozan bir çağrı burada da hata almalı.\n */\n async lockRows(table: string, ids: readonly string[]) {\n if (ids.length === 0) return;\n const rows = store.get(table) ?? [];\n const unique = [...new Set(ids)].sort();\n const missing = unique.filter((id) => !rows.some((r) => r[\"id\"] === id));\n if (missing.length > 0 && rows.length > 0) {\n // Sessiz geçmek, testin \"kilitledim\" sanmasına yol açardı.\n throw new Error(\n `lockRows(${table}): şu id'ler yok: ${missing.join(\", \")} — kilitlenecek satır bulunamadı.`,\n );\n }\n },\n\n /**\n * `lockRowsWhere` — `lockRows` ile AYNI gerekçe, aynı parite seviyesi.\n *\n * Kilit tek işlemli bir sahte depoda anlamsız, ama motorun REDDETTİĞİ bir\n * çağrı burada da reddedilmeli: boş filtre (bütün tabloyu kilitlemek) ve\n * tanınmayan bir kilit modu. Fake bunları geçirseydi, yazarın testi\n * üretimde patlayan bir çağrıya karşı yeşil olurdu.\n */\n async lockRowsWhere(\n table: string,\n where: Record<string, unknown>,\n opts?: { mode?: \"update\" | \"share\" | \"noKeyUpdate\" },\n ) {\n const mode = opts?.mode ?? \"update\";\n if (mode !== \"update\" && mode !== \"share\" && mode !== \"noKeyUpdate\") {\n throw new Error(\n `lockRowsWhere(${table}): bilinmeyen mode \"${String(mode)}\" — \"update\", \"share\" ya da \"noKeyUpdate\".`,\n );\n }\n if (Object.keys(where).length === 0) throw new Error(`lockRowsWhere(${table}): boş filtre`);\n assertUsableFilter(\"lockRowsWhere\", table, where);\n refuseFragment(\"lockRowsWhere\", table, where);\n // Eşleşen satırlar OKUNUYOR: filtre fake'in kendi eşleştiricisinden\n // geçmezse (ör. tanınmayan operatör) çağıran bunu burada öğrenir.\n (store.get(table) ?? []).filter((r) => rowMatchesFilter(\"lockRowsWhere\", table, r, where));\n },\n\n /** Sahte depoda kilit yok; sözleşme (çağrı patlamaz) korunuyor. */\n async advisoryXactLock(_key: string) {\n return undefined;\n },\n\n async claim(\n table: string,\n unique: Record<string, unknown>,\n extra: Record<string, unknown> = {},\n ) {\n const keyCols = Object.keys(unique);\n if (keyCols.length === 0) {\n throw new Error(\n `claim(${table}): benzersiz alan verilmedi. claim, bir anahtarı sahiplenmektir; ` +\n `anahtar yoksa sahiplenecek bir şey de yok — insert(${table}, …) kullanın.`,\n );\n }\n assertUsableWriteValues(\"claim\", table, keyCols, unique);\n const existing = (store.get(table) ?? []).find((r) =>\n keyCols.every((c) => r[c] === unique[c]),\n );\n if (existing) return { inserted: false, row: existing };\n const data = resolveInsertValues(\"claim\", table, { ...unique, ...extra });\n assertUsableWriteValues(\"claim\", table, Object.keys(data), data);\n assertNoExpressionHandles(\"claim\", table, Object.keys(data), data);\n const record = { id: crypto.randomUUID(), ...data };\n rowsOf(table).push(record);\n track(tracked.inserted, table, record);\n return { inserted: true, row: record };\n },\n\n // Same semantics the engine's SQL has: match on the conflict columns, update\n // everything else, and return the resulting row either way.\n async put(\n table: string,\n rawData: Record<string, unknown>,\n opts: { onConflict: readonly string[] },\n ) {\n if (opts.onConflict.length === 0) {\n throw new Error(`put into ${table}: onConflict en az bir kolon adı ister`);\n }\n const data = resolveInsertValues(\"put\", table, rawData);\n assertUsableWriteValues(\"upsert\", table, Object.keys(data), data);\n // Motorla PARİTE: ifade tutamağı bu yolda değer değildir. Fake onu\n // satıra YAZIYORDU; satır artık JSON'a bile çevrilemiyordu.\n assertNoExpressionHandles(\"upsert\", table, Object.keys(data), data);\n const rows = rowsOf(table);\n const existing = rows.find((r) => opts.onConflict.every((c) => r[c] === data[c]));\n if (existing) {\n for (const [k, v] of Object.entries(data)) {\n if (!opts.onConflict.includes(k)) existing[k] = v;\n }\n return existing;\n }\n const record = { id: crypto.randomUUID(), ...data };\n rows.push(record);\n track(tracked.inserted, table, record);\n return record;\n },\n\n async update(table: string, id: string, data: Record<string, unknown>) {\n assertUsableWriteValues(\"update\", table, Object.keys(data), data);\n const rows = store.get(table) ?? [];\n const idx = rows.findIndex((r) => r[\"id\"] === id);\n // 28'de motor `update(id)` ile `updateMany`'nin SET kurucusunu PAYLAŞIYOR,\n // yani `now()` ve sayaç ifadeleri burada da geçerli. Fake eskisi gibi\n // reddetseydi, ÇALIŞAN bir çağrı testte kırmızı olurdu — fake'in var olma\n // amacının tam tersi.\n const current = idx >= 0 ? rows[idx]! : {};\n const applied: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(data)) {\n const expr = columnExprOf(v);\n if (expr !== null && expr.fn === \"now\") {\n applied[k] = new Date();\n continue;\n }\n if (expr !== null) {\n applied[k] = addDecimal(current[k], expr.by, expr.fn === \"inc\" ? 1 : -1);\n continue;\n }\n applied[k] = v;\n }\n assertNoExpressionHandles(\"update\", table, Object.keys(applied), applied);\n // 0 SATIR → NULL, motorun KENDİSİ gibi (engine/db.ts:\n // `rows[0] ? asTableRow(table, rows[0]) : null`).\n //\n // Eskiden eşleşme yokken `{ id, ...applied }` UYDURULUYOR ve o uydurma\n // satır `updated()`'a da yazılıyordu. İki sonucu vardı: eşleşmeyen bir\n // update'i test eden kod SESSİZCE geçiyor ama üretimde `null` alıp\n // patlıyordu; ve \"0 satır → null\" sözleşmesi bu harness'la hiç\n // doğrulanamıyordu — bir tüketici projesi iddiayı yazamayıp yorum olarak\n // bırakmak zorunda kaldı (FR-007, FR-008).\n if (idx < 0) return null;\n const updated = { ...rows[idx], ...applied };\n rows[idx] = updated;\n track(tracked.updated, table, updated);\n return updated;\n },\n\n async delete(table: string, id: string) {\n const rows = store.get(table) ?? [];\n const idx = rows.findIndex((r) => r[\"id\"] === id);\n // EŞLEŞME YOKSA DEFTERE YAZILMAZ — `update` ile aynı kural (FR-008).\n // Eskiden eşleşmeyen bir `delete` de `deleted()`'a düşüyordu: silme\n // GERÇEKLEŞMEDİĞİ hâlde `expect(fake.deleted(\"x\")).toEqual([\"yok\"])`\n // yeşil oluyordu, yani defter olmayan bir yazmayı rapor ediyordu.\n if (idx < 0) return;\n rows.splice(idx, 1);\n const list = tracked.deleted.get(table);\n if (list) list.push(id);\n else tracked.deleted.set(table, [id]);\n },\n\n async findUnique() {\n throw new Error(\"MockDB.findUnique cannot verify declared PostgreSQL unique constraints; use a PostgreSQL integration test\");\n },\n async findById(table: string, id: string) {\n const rows = store.get(table) ?? [];\n return rows.find((r) => r[\"id\"] === id) ?? null;\n },\n\n // The SAME filter language the engine compiles to SQL: a plain value is\n // equality, an object is an operator set. A fake that understood less would\n // pass a service test that the live database then fails — which is the one\n // thing a stand-in must never do.\n async page() {\n throw new Error(\"fakeDatabase cannot reproduce PostgreSQL cursor ordering, collations or RLS; use a PostgreSQL integration test or inject an explicit page response\");\n },\n async findMany(\n table: string,\n query?: Record<string, unknown>,\n opts?: {\n orderBy?:\n | { column: string; direction?: \"asc\" | \"desc\"; nulls?: \"first\" | \"last\" }\n | { column: string; direction?: \"asc\" | \"desc\"; nulls?: \"first\" | \"last\" }[];\n select?: string[];\n with?: Record<string, unknown>;\n limit?: number;\n offset?: number;\n },\n ) {\n assertUsableFilter(\"findMany\", table, query);\n refuseFragment(\"findMany\", table, query);\n const { limit, offset } = opts ?? {};\n if (limit !== undefined && (!Number.isInteger(limit) || limit < 0)) {\n throw new Error(`findMany: limit bir negatif olmayan tam sayı olmalı (geldi: ${String(limit)})`);\n }\n if (offset !== undefined) {\n if (!Number.isInteger(offset) || offset < 0) {\n throw new Error(`findMany: offset bir negatif olmayan tam sayı olmalı (geldi: ${String(offset)})`);\n }\n if (limit === undefined) {\n throw new Error(\n \"findMany: offset yalnız limit ile birlikte verilir — limitsiz offset bir sayfa değil, sınırsız bir kuyruğun kaydırılmışıdır\",\n );\n }\n }\n // `with` — fake'in ilişki grafiği YOK, ve olsaydı ikinci bir yorumcu\n // olurdu (motorunki `buildRelations`'tan geliyor). Sessizce YOK SAYMAK\n // en kötüsü olurdu: yazar `rows[0].orders` yazar, `undefined` gelir ve\n // test motorun döndürdüğünden BAŞKA bir şeyi doğrular.\n if (opts?.with !== undefined && Object.keys(opts.with).length > 0) {\n throw new Error(\n `findMany(${table}): fakeDatabase \\`with\\` desteklemiyor — ilişki grafiği ` +\n `yabancı anahtarlardan TÜRETİLİYOR ve fake şemayı okumuyor. İlişkili ` +\n `satırları ölçen bir test gerçek motoru kullanmalı; fake ile ölçmek ` +\n `istiyorsanız ilgili satırları \\`seed\\` ile ayrı koyup ayrı sorgulayın.`,\n );\n }\n const rows = store.get(table) ?? [];\n let out = query\n ? rows.filter((row) => rowMatchesFilter(\"findMany\", table, row, query))\n : [...rows];\n // Çoklu sıralama ve NULL yeri — motorla PARİTE (FR-008). Tek obje de\n // kabul edilir; liste hâline getirilip aynı yoldan geçer.\n const orderSpecs = opts?.orderBy === undefined\n ? []\n : Array.isArray(opts.orderBy) ? opts.orderBy : [opts.orderBy];\n if (orderSpecs.length > 0) {\n out = [...out].sort((a, b) => {\n for (const o of orderSpecs) {\n const dir = o.direction === \"desc\" ? -1 : 1;\n const x = a[o.column];\n const y = b[o.column];\n const xNull = x === null || x === undefined;\n const yNull = y === null || y === undefined;\n if (xNull || yNull) {\n if (xNull && yNull) continue;\n // Verilmezse Postgres varsayılanı: ASC'de NULLS LAST, DESC'te FIRST.\n const nullsFirst = o.nulls === undefined ? dir === -1 : o.nulls === \"first\";\n return (xNull ? 1 : -1) * (nullsFirst ? -1 : 1);\n }\n if (x === y) continue;\n return ((x as never) < (y as never) ? -1 : 1) * dir;\n }\n return 0;\n });\n }\n const start = offset ?? 0;\n const page = limit === undefined ? out : out.slice(start, start + limit);\n // Projeksiyon (FR-009) — motorla PARİTE. Fake tam satır döndürürse, `select`\n // ile yazılmış bir kod sahte veritabanında seçilmemiş kolonu okur ve GEÇER;\n // gerçek motorda o kolon SQL'e hiç girmediği için `undefined` olur.\n const cols = opts?.select;\n if (cols === undefined || cols.length === 0) return page;\n return page.map((row) => Object.fromEntries(cols.map((c) => [c, row[c]])));\n },\n };\n\n /**\n * Interpret a whole plan, atomically.\n *\n * The rollback is the point. A test that asserts \"the second write failed, so\n * the first one is not there\" must be able to FAIL — a mock that applied ops\n * and left them applied would pass that test while the real broker rolled the\n * transaction back, or the other way round. So the store and the tracking maps\n * are snapshotted, and any failure restores both before rejecting.\n *\n * The rejection carries the same envelope fields the runtime copies off the\n * broker's response (`error_code`, `slot`), because the SDK maps `slot` back\n * to the caller's own Error — a mock that rejected with a bare Error would\n * make every guard in every tenant test look like a generic failure.\n */\n async function txPlan(plan: TxPlanBody): Promise<TxPlanResponse> {\n const snapshot = new Map<string, Record<string, unknown>[]>();\n for (const [table, rows] of store) snapshot.set(table, [...rows]);\n const trackedSnapshot: TrackedRecords = {\n inserted: cloneTracked(tracked.inserted),\n updated: cloneTracked(tracked.updated),\n deleted: new Map([...tracked.deleted].map(([k, v]) => [k, [...v]])),\n };\n\n const results: TxPlanOpResult[] = [];\n try {\n for (const op of plan.ops) {\n const result = applyOp(op, results);\n results.push(result);\n const failure = guardFailure(op.guard, result.rows.length);\n if (failure) throw failure;\n }\n } catch (err) {\n store.clear();\n for (const [table, rows] of snapshot) store.set(table, rows);\n tracked.inserted = trackedSnapshot.inserted;\n tracked.updated = trackedSnapshot.updated;\n tracked.deleted = trackedSnapshot.deleted;\n throw err;\n }\n return { results };\n }\n\n function applyOp(op: TxWireOp, results: TxPlanOpResult[]): TxPlanOpResult {\n switch (op.op) {\n case \"upsert\": {\n const values = resolveMap(op.values ?? {}, results, null);\n const conflict = op.onConflict ?? [];\n const rows = rowsOf(op.table);\n const hit = rows.find((r) => conflict.every((c) => r[c] === values[c]));\n if (hit) {\n for (const [key, value] of Object.entries(values)) {\n if (!conflict.includes(key)) hit[key] = value;\n }\n return { rows: [hit], rows_affected: 1 };\n }\n const created = { id: crypto.randomUUID(), ...values };\n rows.push(created);\n track(tracked.inserted, op.table, created);\n return { rows: [created], rows_affected: 1 };\n }\n case \"insert\": {\n const record = { id: crypto.randomUUID(), ...resolveMap(op.values ?? {}, results, null) };\n rowsOf(op.table).push(record);\n track(tracked.inserted, op.table, record);\n return { rows: [record], rows_affected: 1 };\n }\n case \"insertMany\": {\n const written = (op.rows ?? []).map((row) => {\n const record = { id: crypto.randomUUID(), ...resolveMap(row, results, null) };\n rowsOf(op.table).push(record);\n track(tracked.inserted, op.table, record);\n return record;\n });\n return { rows: written, rows_affected: written.length };\n }\n case \"update\": {\n const rows = rowsOf(op.table);\n const where = resolveMap(op.where ?? {}, results, null);\n const written: Record<string, unknown>[] = [];\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n if (!row || !matches(row, where)) continue;\n const next = { ...row, ...resolveMap(op.set ?? {}, results, row) };\n rows[i] = next;\n track(tracked.updated, op.table, next);\n written.push(next);\n }\n return { rows: written, rows_affected: written.length };\n }\n case \"delete\": {\n const rows = rowsOf(op.table);\n const where = resolveMap(op.where ?? {}, results, null);\n const removed = rows.filter((row) => matches(row, where));\n for (const row of removed) {\n rows.splice(rows.indexOf(row), 1);\n const id = row[\"id\"];\n const list = tracked.deleted.get(op.table);\n const key = typeof id === \"string\" ? id : String(id);\n if (list) list.push(key);\n else tracked.deleted.set(op.table, [key]);\n }\n return { rows: removed, rows_affected: removed.length };\n }\n case \"select\": {\n const where = resolveMap(op.where ?? {}, results, null);\n let found = rowsOf(op.table).filter((row) => matches(row, where));\n if (op.limit !== undefined) found = found.slice(0, op.limit);\n return { rows: found, rows_affected: found.length };\n }\n }\n }\n\n const client: MockDBClient = {\n ...ops,\n async command(plan, options) {\n if (options?.mode === \"compiled\") throw new Error(\"fakeDatabase does not run the PostgreSQL command executor; verify compiled mode against PostgreSQL\");\n return client.txPlan(plan);\n },\n\n async atomic() {\n throw new Error(\"fakeDatabase cannot verify physical transaction isolation, COMMIT or retry; test $atomic against PostgreSQL or inject a transaction test double explicitly\");\n },\n\n // No real savepoint in memory: the fake runs the callback against the SAME\n // store. An assertion about rollback here would be asserting the fake.\n attempt: <T,>(fn: (tx: DBOps) => Promise<T>): Promise<T> => fn(ops),\n\n txPlan,\n\n // In tests there is no real DB role; `asService()` returns the same\n // in-memory client so RLS-bypass code paths still hit the same store and\n // tracking maps. The omitted `asService` matches the contract (no\n // double-bypass), so callers can't recurse.\n asService(): Omit<DBClient, \"asService\"> {\n return client;\n },\n\n inserted(table: string) {\n return tracked.inserted.get(table) ?? [];\n },\n\n updated(table: string) {\n return tracked.updated.get(table) ?? [];\n },\n\n deleted(table: string) {\n return tracked.deleted.get(table) ?? [];\n },\n\n seed(table: string, data: Record<string, unknown>[]) {\n store.set(table, [...data]);\n },\n };\n\n return client;\n}\n\nfunction cloneTracked(\n map: Map<string, Record<string, unknown>[]>,\n): Map<string, Record<string, unknown>[]> {\n return new Map([...map].map(([k, v]) => [k, [...v]]));\n}\n\n/** Resolve one plan value: a `$ref` into an earlier result, a `$expr`, or a\n * literal. `current` is the row being updated, which is what `inc`/`dec` read. */\nfunction resolveValue(\n value: TxWireValue,\n results: TxPlanOpResult[],\n current: Record<string, unknown> | null,\n column: string,\n): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n const tagged = value as { $ref?: { op: number; field: string }; $expr?: Record<string, unknown> };\n\n if (tagged.$ref) {\n const row = results[tagged.$ref.op]?.rows[0];\n if (!row) {\n throw txRejection(409, \"tx_ref_unresolved\", {\n message: `operation ${tagged.$ref.op} produced no row to reference`,\n });\n }\n return row[tagged.$ref.field];\n }\n\n if (tagged.$expr) {\n const fn = tagged.$expr[\"fn\"];\n if (fn === \"now\") return new Date().toISOString();\n const by = Number(tagged.$expr[\"by\"]);\n const base = Number(current?.[column] ?? 0);\n return fn === \"dec\" ? base - by : base + by;\n }\n\n return value;\n}\n\nfunction resolveMap(\n map: Record<string, TxWireValue>,\n results: TxPlanOpResult[],\n current: Record<string, unknown> | null,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(map)) {\n out[key] = resolveValue(value, results, current, key);\n }\n return out;\n}\n\n/** Equality filter, with `null` meaning IS NULL — the broker's rule, so a\n * `{ accepted_at: null }` guard behaves the same in a test as in production. */\nfunction matches(row: Record<string, unknown>, where: Record<string, unknown>): boolean {\n return Object.entries(where).every(([key, value]) =>\n value === null ? row[key] === null || row[key] === undefined : row[key] === value,\n );\n}\n\nfunction guardFailure(guard: TxWireGuard | undefined, count: number): unknown {\n if (!guard) return null;\n const ok =\n guard.kind === \"one\"\n ? count === 1\n : guard.kind === \"none\"\n ? count === 0\n : guard.kind === \"atLeast\"\n ? count >= guard.n\n : count <= guard.n;\n if (ok) return null;\n return txRejection(409, \"tx_guard_failed\", {\n slot: guard.slot,\n message: `expected ${guard.kind} ${guard.n} row(s), got ${count}`,\n });\n}\n\n/** Build a rejection shaped like the one the runtime throws for a broker error:\n * an Error carrying the envelope's `status`/`error_code`/`slot`. */\nfunction txRejection(\n status: number,\n code: string,\n extra: { slot?: number; message: string },\n): Error & TxPlanRejection {\n const err = new Error(extra.message) as Error & TxPlanRejection;\n err.status = status;\n err.error_code = code;\n if (extra.slot !== undefined) err.slot = extra.slot;\n return err;\n}\n","/**\n * `fakeDatabase()` — the in-memory `Database` a SERVICE-LAYER test runs against.\n *\n * WHY IT IS PUBLIC. The scaffold's own AGENTS.md tells authors to \"test the\n * service layer… the test passes a stand-in\", and the SDK shipped no stand-in to\n * pass. So every project wrote its own: a measured customer run carried two — a\n * hand-written `MembershipDb` interface for one service, and a bare `{ query }`\n * object in the tests of another. Both are guesses at this SDK's own surface,\n * and both stop compiling the moment the surface grows.\n *\n * The engine already had exactly this object; it just lived under `__tests__/`\n * where only this package could reach it.\n *\n * WHAT IT IS NOT. It does not interpret SQL. `query()` records what it was asked\n * and answers no rows, because a fake that parsed SQL would be a second, worse\n * Postgres — and a test that passed against it would prove nothing about the\n * real one. Assert on `queries` when the SQL is the thing under test, and put\n * anything that depends on what SQL RETURNS in a live test (`palbase test`).\n */\nimport { createMockDB } from \"../__tests__/helpers/mock-db.js\";\nimport type { DBClient } from \"../endpoint.js\";\nimport { makeTypedSurface } from \"../runtime.js\";\nimport type { EnvServiceDatabase } from \"../db/typed-db.js\";\n\n/** One `Database.$query(...)` call, as the service made it. */\nexport interface RecordedQuery {\n sql: string;\n params: unknown[];\n}\n\n/** What a service-layer test is handed. */\nexport interface FakeDatabase {\n /** Pass this where the service expects `Database`.\n *\n * Built with the SAME constructor the production `Database` uses\n * (`makeTypedSurface`), so the fake's surface cannot drift from the real one\n * — including the `$`-prefixed raw ops and the typed `public` schema surface. */\n db: EnvServiceDatabase;\n /**\n * The RAW `DBClient` behind {@link FakeDatabase.db} (FR-028).\n *\n * `RuntimeServices.Database` is the raw client — the ambient `Database`\n * singleton is what WRAPS it with `makeTypedSurface`. So a test that installs\n * the fake as the ambient runtime passes THIS:\n *\n * withServices({ Database: fake.raw }, () => …)\n *\n * Passing `db` there would wrap an already-wrapped surface and every `$op`\n * would miss (measured). Two fields because there are two call sites: `db`\n * goes straight to a service, `raw` goes into the runtime.\n */\n raw: DBClient;\n /** Every `query()` call, in order. */\n queries: readonly RecordedQuery[];\n /** Put rows in a table before the code under test runs. */\n seed(table: string, rows: Record<string, unknown>[]): void;\n /** Rows inserted into a table, for asserting a write happened. */\n inserted(table: string): Record<string, unknown>[];\n /** Rows updated in a table. */\n updated(table: string): Record<string, unknown>[];\n /** Ids deleted from a table. */\n deleted(table: string): string[];\n}\n\nexport function fakeDatabase(): FakeDatabase {\n const mock = createMockDB();\n const queries: RecordedQuery[] = [];\n\n // The recorder wraps `query` and leaves every other op alone, so the fake's\n // behaviour is the engine's mock plus one observation.\n const db: DBClient = Object.assign(Object.create(Object.getPrototypeOf(mock) as object) as DBClient, mock, {\n query: async (sql: string, params: unknown[] = []) => {\n queries.push({ sql, params });\n return mock.query(sql, params);\n },\n });\n\n return {\n db: makeTypedSurface(db),\n raw: db,\n queries,\n seed: (table, rows) => mock.seed(table, rows),\n inserted: (table) => mock.inserted(table),\n updated: (table) => mock.updated(table),\n deleted: (table) => mock.deleted(table),\n };\n}\n","/**\n * `withServices()` — run code with only the platform services a test supplies.\n *\n * WHY IT IS PUBLIC. `isolated()` substitutes CONSTRUCTOR dependencies, and its\n * own documentation says why it cannot help here: \"platform services are\n * ambient rather than injected\". So the repository layer — the one place that\n * really does `import { Database } from \"@palbase/backend\"` — had no supported\n * way to be unit-tested, while `__runWithRuntime` demands EVERY service. A\n * measured consumer project wrote this helper by hand, exploding proxies\n * included, and 30.0.0 then added a tenth required service (`Auth`) which broke\n * that hand-written copy. Shipping it here is what stops that from recurring.\n *\n * WHAT IS ABSENT IS LOUD. An unsupplied service is neither `undefined` nor a\n * silent no-op: touching it throws and NAMES itself, so a test that quietly\n * grew a dependency on `Cache` fails saying \"Cache\", not \"cannot read\n * properties of undefined\".\n *\n * SCOPE IS THE REQUEST ALS, never the process-global slot. Two tests in one\n * file must not be able to see each other's services, and a helper that wrote\n * the global slot would leak the first test's fake into the second.\n *\n * EKSİKSİZLİK DERLEYİCİYE SORULUR, BİR LİSTEYE DEĞİL. İlk yazımı servis\n * adlarını bir diziye koyup `satisfies readonly (keyof RuntimeServices)[]` ile\n * pinliyordu — ama `satisfies` yalnız \"her ELEMAN bir anahtar mı\" diye bakar,\n * \"her ANAHTAR listede mi\" diye BAKMAZ. Ölçüldü: `RuntimeServices`'a on birinci\n * bir servis eklenip liste dokunulmadan bırakıldığında `tsc --strict` TEMİZ\n * derliyor, ve eksik servise erişen tüketici `TypeError: Reflect.get called on\n * non-object` alıyor — ne servisin adı, ne çaresi. Yani bu dosyanın var olma\n * sebebi olan kusurun ta kendisi, bu dosya tarafından üretiliyordu.\n *\n * Şimdi `filled` düz bir `RuntimeServices` nesne literali: bir alan eksik\n * kalırsa TypeScript `TS2741: Property '<ad>' is missing` diyor ve derleme\n * durur. `as unknown as` yok.\n */\nimport { __runWithRuntime, __requestALS, type RuntimeServices } from \"../runtime.js\";\n\n/**\n * A stand-in that refuses every read by NAME.\n *\n * The Proxy target is irrelevant (all access goes through `get`); the single\n * narrowing names the surface the caller expects — the same one-point cast\n * `makeServiceProxy` already uses for exactly this shape.\n */\nfunction absent<K extends keyof RuntimeServices>(name: K): RuntimeServices[K] {\n return new Proxy({} as RuntimeServices[K], {\n get(_target, prop) {\n throw new Error(\n `${String(name)}.${String(prop)} was read, but this test did not provide ${String(name)}. ` +\n `Pass it: withServices({ ${String(name)}: … }, () => …)`,\n );\n },\n });\n}\n\n/** The supplied service, or one that names itself when touched. */\nfunction pick<K extends keyof RuntimeServices>(\n services: Partial<RuntimeServices>,\n key: K,\n): RuntimeServices[K] {\n return services[key] ?? absent(key);\n}\n\nexport function withServices<T>(services: Partial<RuntimeServices>, fn: () => T): T {\n // Nesne LİTERALİ, üretilmiş bir kayıt değil: eksik bir alan burada derleme\n // hatasıdır (ölçüldü: TS2741), bir çalışma zamanı sürprizi değil.\n const filled: RuntimeServices = {\n Database: pick(services, \"Database\"),\n Auth: pick(services, \"Auth\"),\n Secrets: pick(services, \"Secrets\"),\n Documents: pick(services, \"Documents\"),\n Storage: pick(services, \"Storage\"),\n Cache: pick(services, \"Cache\"),\n Log: pick(services, \"Log\"),\n Notifications: pick(services, \"Notifications\"),\n Flags: pick(services, \"Flags\"),\n Realtime: pick(services, \"Realtime\"),\n };\n // `userId`'yi MOTORUN yazdığı gibi yaz. Motor `runWithRuntime`'ın hemen\n // ardından kutuya `userId ?? null` koyuyor ve `RequestStore`'un sözleşmesi\n // \"anonim istekte null\" diyor. Yalnız `{ runtime }` yazmak `undefined`\n // bırakırdı; `undefined` ile `null`'ı ayıran her dal testte bir yol,\n // üretimde başka bir yol koşardı — testin yeşilliği üretim hakkında yalan\n // söylerdi.\n return __requestALS.run({ runtime: filled, userId: null }, fn);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,IAAMA,aAAa,CAAC;AACb,IAAMC,gBAAgBC,iBAAiBC,YAAYH,UAAAA;AAC1D,SAASE,iBAAiBE,SAASC,QAAM;AACrC,SAAO,IAAIC,MAAMF,SAAS;IACtBG,IAAIC,SAASC,MAAMC,WAAS;AACxB,UAAID,QAAQJ,QAAQ;AAChB,eAAOA,OAAOI,IAAAA;MAClB,OACK;AACD,eAAOL,QAAQK,IAAAA;MACnB;IACJ;IACAE,IAAIH,SAASC,MAAMG,OAAK;AACpB,UAAIH,QAAQJ,QAAQ;AAChB,eAAOA,OAAOI,IAAAA;MAClB;AACAL,cAAQK,IAAAA,IAAQG;AAChB,aAAO;IACX;IACAC,eAAeL,SAASC,MAAI;AACxB,UAAIK,UAAU;AACd,UAAIL,QAAQJ,QAAQ;AAChB,eAAOA,OAAOI,IAAAA;AACdK,kBAAU;MACd;AACA,UAAIL,QAAQL,SAAS;AACjB,eAAOA,QAAQK,IAAAA;AACfK,kBAAU;MACd;AACA,aAAOA;IACX;IACAC,QAAQP,SAAO;AACX,YAAMQ,WAAWC,QAAQF,QAAQX,OAAAA;AACjC,YAAMc,UAAUD,QAAQF,QAAQV,MAAAA;AAChC,YAAMc,aAAa,IAAIC,IAAIF,OAAAA;AAC3B,aAAO;WAAIF,SAASK,OAAO,CAACC,MAAM,CAACH,WAAWI,IAAID,CAAAA,CAAAA;WAAQJ;;IAC9D;IACAM,eAAehB,SAASC,MAAMgB,MAAI;AAC9B,UAAIhB,QAAQJ,QAAQ;AAChB,eAAOA,OAAOI,IAAAA;MAClB;AACAQ,cAAQO,eAAepB,SAASK,MAA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BgBhB;;;ACrBhB,SAASqB,OAAwCC,MAAO;AACtD,SAAO,IAAIC,MAAM,CAAC,GAAyB;IACzCC,IAAIC,SAASC,MAAI;AACf,YAAM,IAAIC,MACR,GAAGC,OAAON,IAAAA,CAAAA,IAASM,OAAOF,IAAAA,CAAAA,4CAAiDE,OAAON,IAAAA,CAAAA,6BACrDM,OAAON,IAAAA,CAAAA,2BAAsB;IAE9D;EACF,CAAA;AACF;AATSD;AAYT,SAASQ,KACPC,UACAC,KAAM;AAEN,SAAOD,SAASC,GAAAA,KAAQV,OAAOU,GAAAA;AACjC;AALSF;AAOF,SAASG,aAAgBF,UAAoCG,IAAW;AAG7E,QAAMC,SAA0B;IAC9BC,UAAUN,KAAKC,UAAU,UAAA;IACzBM,MAAMP,KAAKC,UAAU,MAAA;IACrBO,SAASR,KAAKC,UAAU,SAAA;IACxBQ,WAAWT,KAAKC,UAAU,WAAA;IAC1BS,SAASV,KAAKC,UAAU,SAAA;IACxBU,OAAOX,KAAKC,UAAU,OAAA;IACtBW,KAAKZ,KAAKC,UAAU,KAAA;IACpBY,eAAeb,KAAKC,UAAU,eAAA;IAC9Ba,OAAOd,KAAKC,UAAU,OAAA;IACtBc,UAAUf,KAAKC,UAAU,UAAA;EAC3B;AAOA,SAAOe,aAAaC,IAAI;IAAEC,SAASb;IAAQc,QAAQ;EAAK,GAAGf,EAAAA;AAC7D;AAtBgBD;","names":["dntGlobals","dntGlobalThis","createMergeProxy","globalThis","baseObj","extObj","Proxy","get","_target","prop","_receiver","set","value","deleteProperty","success","ownKeys","baseKeys","Reflect","extKeys","extKeysSet","Set","filter","k","has","defineProperty","desc","getOwnPropertyDescriptor","N_0","EC_P_521_PARAMS","p","b","gx","gy","coordinateSize","isBytes","a","Uint8Array","ArrayBuffer","isView","name","anumber","n","title","Number","isSafeInteger","prefix","Error","abytes","value","length","bytes","len","needsLen","undefined","ofLen","got","aexists","instance","checkFinished","destroyed","finished","aoutput","out","min","outputLen","u32","arr","Uint32Array","buffer","byteOffset","Math","floor","byteLength","clean","arrays","i","length","fill","_endianTestBuffer","_endianTestBytes","Uint8Array","isLE","createView","arr","DataView","buffer","byteOffset","byteLength","numberToBigint","num","anumber","n","out","N_0","bit","Math","floor","copyBytes","bytes","Uint8Array","from","ahash","h","create","Error","anumber","outputLen","blockLen","_HMAC","hash","key","Object","defineProperty","enumerable","configurable","writable","value","ahash","abytes","undefined","iHash","create","update","Error","blockLen","outputLen","pad","Uint8Array","set","length","digest","i","oHash","clean","buf","aexists","digestInto","out","finished","destroy","_cloneInto","to","getPrototypeOf","destroyed","clone","hmac","message","U32_MASK64","_32n","fromBig","n","le","h","Number","l","split","lst","len","length","Ah","Uint32Array","Al","i","_0n","_1n","_2n","_7n","_256n","_0x71n","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","round","R","x","y","push","t","j","BigInt","IOTAS","split","SHA3_IOTA_H","SHA3_IOTA_L","abool","b","Error","wrapCipher","params","constructor","wrappedCipher","key","args","abytes","undefined","isLE","Error","nonceLength","nonce","varSizeNonce","tagl","tagLength","cipher","checkOutput","fnLength","output","called","wrCipher","encrypt","data","length","decrypt","Object","assign","checkOpts","defaults","opts","merged","equalBytes","a","b","diff","i","getOutput","expectedLength","out","onlyAligned","Uint8Array","isAligned32","u64Lengths","dataLength","aadLength","abool","num","view","createView","setBigUint64","numberToBigint","bytes","byteOffset","_utf8ToBytes","str","Uint8Array","from","split","map","c","charCodeAt","sigma16","sigma32","sigma16_32","u32","sigma32_32","rotl","a","b","isAligned32","byteOffset","BLOCK_LEN","BLOCK_LEN32","MAX_COUNTER","U32_EMPTY","Uint32Array","of","runCipher","core","sigma","key","nonce","data","output","counter","rounds","len","length","block","b32","isAligned","d32","o32","pos","Error","take","Math","min","pos32","j","posj","createCipher","opts","allowShortKeys","extendNonceFn","counterLength","counterRight","checkOpts","anumber","abool","abytes","undefined","toClean","l","k","push","copyBytes","set","k32","subarray","nonceNcLen","nc","n32","clean","u8to16","a","i","Poly1305","key","Object","defineProperty","enumerable","configurable","writable","value","Uint8Array","Uint16Array","copyBytes","abytes","t0","t1","t2","t3","t4","t5","t6","t7","r","pad","process","data","offset","isLast","hibit","h","r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","h0","h1","h2","h3","h4","h5","h6","h7","h8","h9","c","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","finalize","g","mask","f","clean","update","aexists","buffer","blockLen","len","length","pos","take","Math","min","set","subarray","destroy","digestInto","out","aoutput","finished","opos","digest","outputLen","res","slice","wrapConstructorWithKey","hashCons","hashC","msg","tmp","create","poly1305","chachaCore","s","k","n","out","cnt","rounds","y00","y01","y02","y03","y04","y05","y06","y07","y08","y09","y10","y11","y12","y13","y14","y15","x00","x01","x02","x03","x04","x05","x06","x07","x08","x09","x10","x11","x12","x13","x14","x15","r","rotl","oi","chacha20","createCipher","counterRight","counterLength","allowShortKeys","ZEROS16","Uint8Array","updatePadded","h","msg","update","leftover","length","subarray","ZEROS32","computeTag","fn","key","nonce","ciphertext","AAD","undefined","abytes","authKey","lengths","u64Lengths","poly1305","create","res","digest","clean","_poly1305_aead","xorStream","tagLength","encrypt","plaintext","output","plength","getOutput","set","oPlain","tag","decrypt","data","passedTag","equalBytes","Error","chacha20poly1305","wrapCipher","blockSize","nonceLength","LABEL_SEC","Uint8Array","_Mutex_locked","_Mutex_locked","WeakMap","_RecipientContextImpl_mutex","_RecipientContextImpl_mutex","WeakMap","_SenderContextImpl_mutex","_SenderContextImpl_mutex","WeakMap","LABEL_BASE_NONCE","Uint8Array","LABEL_EXP","LABEL_INFO_HASH","LABEL_KEY","LABEL_PSK_ID_HASH","LABEL_SECRET","SUITE_ID_HEADER_HPKE","PKCS8_ALG_ID_X25519","Uint8Array","PKCS8_ALG_ID_X448","Uint8Array","mod","encoder","encoder","TestApiError","Error","status","error","data","body","method","path","envelope","code","String","error_description","name","required","value","envName","isLocalTarget","baseUrl","hostname","URL","secondsUntilExpiry","token","split","claims","JSON","parse","Buffer","from","toString","exp","Math","floor","Date","now","createTestApi","config","replace","apiKey","local","candidateToken","doFetch","fetch","requests","bearer","call","opts","headers","apikey","authorization","undefined","startedAt","res","stringify","text","parsed","safeParse","push","ms","ok","left","abs","get","post","patch","put","delete","query","signInAs","identity","identities","declared","Object","keys","length","join","accessToken","id","email","signIn","credentials","attempt","extra","result","e","refusal","challenge","asPowChallenge","solvePowChallenge","access_token","user","signOut","asAnonymous","parseIdentities","raw","configured","api","Proxy","_target","prop","process","env","PALBASE_TEST_BASE_URL","PALBASE_TEST_API_KEY","PALBASE_TEST_CANDIDATE","PALBASE_TEST_IDENTITIES","Reflect","isolated","over","Map","local","make","c","has","get","hit","undefined","meta","Reflect","getMetadata","inst","map","d","set","api","with","t","v","refuseFragment","caller","table","where","isSqlFragment","Error","k","v","Object","entries","branch","Array","isArray","addDecimal","cell","by","sign","undefined","a","String","b","parse","x","m","exec","trim","frac","unit","BigInt","scale","length","pa","pb","Math","max","lift","total","Number","toString","neg","digits","padStart","out","slice","rowMatchesFilter","row","f","every","c","some","matchesCell","cmp","op","l","Date","getTime","r","key","cond","isColRef","$col","isNowExpr","toISOString","includes","isColumnExpr","toLowerCase","startsWith","endsWith","createMockDB","store","Map","tracked","inserted","updated","deleted","rowsOf","rows","get","set","track","map","list","push","resolveInsertValues","data","expr","columnExprOf","fn","ops","diagnostics","updateMany","opts","keys","assertUsableFilter","assertUsableWriteValues","hit","filter","returning","deleteMany","keep","count","search","_table","_params","facets","similar","recommend","supersede","_id","id","crypto","randomUUID","query","_sql","insert","raw","assertNoExpressionHandles","record","aggregate","q","groups","groupBy","shape","bucket","sum","vals","reduce","avg","pick","byKey","JSON","stringify","values","insertMany","validateInsertManyOptions","onConflict","cols","i","missing","extra","join","rawRow","lockRows","ids","unique","Set","sort","lockRowsWhere","mode","advisoryXactLock","_key","claim","keyCols","existing","find","put","rawData","update","idx","findIndex","current","applied","delete","splice","findUnique","findById","page","findMany","limit","offset","isInteger","with","orderSpecs","orderBy","o","dir","direction","column","y","xNull","yNull","nullsFirst","nulls","start","select","fromEntries","txPlan","plan","snapshot","trackedSnapshot","cloneTracked","results","result","applyOp","failure","guardFailure","guard","err","clear","resolveMap","conflict","value","rows_affected","created","written","matches","next","removed","indexOf","found","client","command","options","atomic","attempt","asService","seed","resolveValue","tagged","$ref","txRejection","message","field","$expr","base","ok","kind","n","slot","status","code","error_code","fakeDatabase","mock","createMockDB","queries","db","Object","assign","create","getPrototypeOf","query","sql","params","push","makeTypedSurface","raw","seed","table","rows","inserted","updated","deleted","absent","name","Proxy","get","_target","prop","Error","String","pick","services","key","withServices","fn","filled","Database","Auth","Secrets","Documents","Storage","Cache","Log","Notifications","Flags","Realtime","__requestALS","run","runtime","userId"]}
1
+ {"version":3,"sources":["../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/_dnt.shims.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/consts.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/kems/dhkemPrimitives/ec.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/utils/noble.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/hash.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/hmac.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/u64.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/sha3.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/utils.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/_arx.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/_poly1305.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/chacha.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/exporterContext.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/mutex.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/recipientContext.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/senderContext.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/cipherSuiteNative.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/kems/dhkemPrimitives/x25519.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/kems/dhkemPrimitives/x448.js","../../../core/src/config.ts","../../../core/src/errors.ts","../../../core/src/platform.ts","../../../core/src/pow.ts","../../../core/src/sealed.ts","../../../core/src/sealed-json.ts","../../../core/src/sealed-keys.ts","../../../core/src/url.ts","../../../core/src/http.ts","../../../core/src/token.ts","../../src/test/api.ts","../../src/test/container.ts","../../src/__tests__/helpers/mock-db.ts","../../src/test/fake-db.ts","../../src/test/with-services.ts"],"sourcesContent":["const dntGlobals = {};\nexport const dntGlobalThis = createMergeProxy(globalThis, dntGlobals);\nfunction createMergeProxy(baseObj, extObj) {\n return new Proxy(baseObj, {\n get(_target, prop, _receiver) {\n if (prop in extObj) {\n return extObj[prop];\n }\n else {\n return baseObj[prop];\n }\n },\n set(_target, prop, value) {\n if (prop in extObj) {\n delete extObj[prop];\n }\n baseObj[prop] = value;\n return true;\n },\n deleteProperty(_target, prop) {\n let success = false;\n if (prop in extObj) {\n delete extObj[prop];\n success = true;\n }\n if (prop in baseObj) {\n delete baseObj[prop];\n success = true;\n }\n return success;\n },\n ownKeys(_target) {\n const baseKeys = Reflect.ownKeys(baseObj);\n const extKeys = Reflect.ownKeys(extObj);\n const extKeysSet = new Set(extKeys);\n return [...baseKeys.filter((k) => !extKeysSet.has(k)), ...extKeys];\n },\n defineProperty(_target, prop, desc) {\n if (prop in extObj) {\n delete extObj[prop];\n }\n Reflect.defineProperty(baseObj, prop, desc);\n return true;\n },\n getOwnPropertyDescriptor(_target, prop) {\n if (prop in extObj) {\n return Reflect.getOwnPropertyDescriptor(extObj, prop);\n }\n else {\n return Reflect.getOwnPropertyDescriptor(baseObj, prop);\n }\n },\n has(_target, prop) {\n return prop in extObj || prop in baseObj;\n },\n });\n}\n","// The input length limit (psk, psk_id, info, exporter_context, ikm).\nexport const INPUT_LENGTH_LIMIT = 8192;\nexport const INFO_LENGTH_LIMIT = 268435456;\n// The minimum length of a PSK.\nexport const MINIMUM_PSK_LENGTH = 32;\n// b\"\"\nexport const EMPTY = /* @__PURE__ */ new Uint8Array(0);\n// Common BigInt constants\nexport const N_0 = 0n;\nexport const N_1 = 1n;\nexport const N_2 = 2n;\nexport const N_7 = 7n;\nexport const N_32 = 32n;\nexport const N_256 = 256n;\nexport const N_0x71 = 0x71n;\nexport const BYTE_TO_BIGINT_256 = /* @__PURE__ */ (() => {\n const out = new Array(256);\n let i = 0;\n let value = 0n;\n while (i < 256) {\n out[i] = value;\n i++;\n value += 1n;\n }\n return out;\n})();\n","import { NativeAlgorithm } from \"../../algorithm.js\";\nimport { BYTE_TO_BIGINT_256, EMPTY } from \"../../consts.js\";\nimport { toArrayBuffer } from \"../../kdfs/hkdf.js\";\nimport { DeriveKeyPairError, DeserializeError, NotSupportedError, SerializeError, } from \"../../errors.js\";\nimport { KemId } from \"../../identifiers.js\";\nimport { KEM_USAGES, LABEL_DKP_PRK } from \"../../interfaces/dhkemPrimitives.js\";\nimport { Bignum } from \"../../utils/bignum.js\";\nimport { base64UrlToBytes, i2Osp } from \"../../utils/misc.js\";\n// b\"candidate\"\n// deno-fmt-ignore\nconst LABEL_CANDIDATE = /* @__PURE__ */ new Uint8Array([\n 99, 97, 110, 100, 105, 100, 97, 116, 101,\n]);\n// the order of the curve being used.\n// deno-fmt-ignore\nconst ORDER_P_256 = /* @__PURE__ */ new Uint8Array([\n 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84,\n 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51,\n]);\n// deno-fmt-ignore\nconst ORDER_P_384 = /* @__PURE__ */ new Uint8Array([\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xc7, 0x63, 0x4d, 0x81, 0xf4, 0x37, 0x2d, 0xdf,\n 0x58, 0x1a, 0x0d, 0xb2, 0x48, 0xb0, 0xa7, 0x7a,\n 0xec, 0xec, 0x19, 0x6a, 0xcc, 0xc5, 0x29, 0x73,\n]);\n// deno-fmt-ignore\nconst ORDER_P_521 = /* @__PURE__ */ new Uint8Array([\n 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xfa, 0x51, 0x86, 0x87, 0x83, 0xbf, 0x2f,\n 0x96, 0x6b, 0x7f, 0xcc, 0x01, 0x48, 0xf7, 0x09,\n 0xa5, 0xd0, 0x3b, 0xb5, 0xc9, 0xb8, 0x89, 0x9c,\n 0x47, 0xae, 0xbb, 0x6f, 0xb7, 0x1e, 0x91, 0x38,\n 0x64, 0x09,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_256 = /* @__PURE__ */ new Uint8Array([\n 48, 65, 2, 1, 0, 48, 19, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 8, 42, 134,\n 72, 206, 61, 3, 1, 7, 4, 39, 48, 37,\n 2, 1, 1, 4, 32,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_384 = /* @__PURE__ */ new Uint8Array([\n 48, 78, 2, 1, 0, 48, 16, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 5, 43, 129,\n 4, 0, 34, 4, 55, 48, 53, 2, 1, 1,\n 4, 48,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_521 = /* @__PURE__ */ new Uint8Array([\n 48, 96, 2, 1, 0, 48, 16, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 5, 43, 129,\n 4, 0, 35, 4, 73, 48, 71, 2, 1, 1,\n 4, 66,\n]);\nconst EC_P_256_PARAMS = {\n p: 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn,\n b: 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn,\n gx: 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296n,\n gy: 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5n,\n coordinateSize: 32,\n};\nconst EC_P_384_PARAMS = {\n p: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffffn,\n b: 0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aefn,\n gx: 0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7n,\n gy: 0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5fn,\n coordinateSize: 48,\n};\nconst EC_P_521_PARAMS = {\n p: (1n << 521n) - 1n,\n b: 0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00n,\n gx: 0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66n,\n gy: 0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650n,\n coordinateSize: 66,\n};\nfunction mod(a, p) {\n const r = a % p;\n return r >= 0n ? r : r + p;\n}\nfunction modPow(base, exponent, p) {\n let result = 1n;\n let b = mod(base, p);\n let e = exponent;\n while (e > 0n) {\n if ((e & 1n) === 1n) {\n result = mod(result * b, p);\n }\n b = mod(b * b, p);\n e >>= 1n;\n }\n return result;\n}\nfunction modSqrt(rhs, p) {\n // P-256/P-384/P-521 primes satisfy p % 4 == 3.\n const y = modPow(rhs, (p + 1n) >> 2n, p);\n if (mod(y * y, p) !== mod(rhs, p)) {\n throw new Error(\"Invalid ECDH point\");\n }\n return y;\n}\nfunction bytesToBigInt(bytes) {\n let v = 0n;\n for (const b of bytes) {\n v = (v << 8n) | BYTE_TO_BIGINT_256[b];\n }\n return v;\n}\nfunction bigIntToBytes(v, len) {\n const out = new Uint8Array(len);\n let n = v;\n for (let i = len - 1; i >= 0; i--) {\n out[i] = Number(n & 0xffn);\n n >>= 8n;\n }\n if (n !== 0n) {\n throw new Error(\"Invalid coordinate length\");\n }\n return out;\n}\nfunction buildRawUncompressedPublicKey(x, y, coordinateSize) {\n const out = new Uint8Array(1 + coordinateSize * 2);\n out[0] = 0x04;\n out.set(bigIntToBytes(x, coordinateSize), 1);\n out.set(bigIntToBytes(y, coordinateSize), 1 + coordinateSize);\n return out;\n}\nexport class Ec extends NativeAlgorithm {\n constructor(kem, hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // EC specific arguments for deriving key pair.\n Object.defineProperty(this, \"_order\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_bitmask\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_curveParams\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._hkdf = hkdf;\n switch (kem) {\n case KemId.DhkemP256HkdfSha256:\n this._alg = { name: \"ECDH\", namedCurve: \"P-256\" };\n this._nPk = 65;\n this._nSk = 32;\n this._nDh = 32;\n this._order = ORDER_P_256;\n this._bitmask = 0xFF;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_256;\n this._curveParams = EC_P_256_PARAMS;\n break;\n case KemId.DhkemP384HkdfSha384:\n this._alg = { name: \"ECDH\", namedCurve: \"P-384\" };\n this._nPk = 97;\n this._nSk = 48;\n this._nDh = 48;\n this._order = ORDER_P_384;\n this._bitmask = 0xFF;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_384;\n this._curveParams = EC_P_384_PARAMS;\n break;\n default:\n // case KemId.DhkemP521HkdfSha512:\n this._alg = { name: \"ECDH\", namedCurve: \"P-521\" };\n this._nPk = 133;\n this._nSk = 66;\n this._nDh = 66;\n this._order = ORDER_P_521;\n this._bitmask = 0x01;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_521;\n this._curveParams = EC_P_521_PARAMS;\n break;\n }\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(this._alg, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const rawIkm = toArrayBuffer(ikm);\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n const bn = new Bignum(this._nSk);\n for (let counter = 0; bn.isZero() || !bn.lessThan(this._order); counter++) {\n if (counter > 255) {\n throw new Error(\"Faild to derive a key pair\");\n }\n const bytes = new Uint8Array(await this._hkdf.labeledExpand(dkpPrk, LABEL_CANDIDATE, i2Osp(counter, 1), this._nSk));\n bytes[0] = bytes[0] & this._bitmask;\n bn.set(bytes);\n }\n const sk = await this._deserializePkcs8Key(bn.val());\n bn.reset();\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch {\n try {\n // Firefox fails to export JWK from some imported ECDH private keys.\n return await this._derivePublicKeyWithoutJwkExport(key);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n }\n async dh(sk, pk) {\n try {\n await this._setup();\n const bits = await this._api.deriveBits({\n name: \"ECDH\",\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.crv === \"undefined\" || key.crv !== this._alg.namedCurve) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n async _derivePublicKeyWithoutJwkExport(key) {\n const basePointRaw = buildRawUncompressedPublicKey(this._curveParams.gx, this._curveParams.gy, this._curveParams.coordinateSize);\n const basePoint = await this._api.importKey(\"raw\", basePointRaw.buffer, this._alg, true, []);\n const xBytes = new Uint8Array(await this._api.deriveBits({\n name: \"ECDH\",\n public: basePoint,\n }, key, this._nDh * 8));\n const p = this._curveParams.p;\n const x = bytesToBigInt(xBytes);\n const rhs = mod(modPow(x, 3n, p) - 3n * x + this._curveParams.b, p);\n let y = modSqrt(rhs, p);\n // Canonicalize sign so the encoded point is deterministic.\n if ((y & 1n) === 1n) {\n y = p - y;\n }\n const pubRaw = buildRawUncompressedPublicKey(x, y, this._curveParams.coordinateSize);\n return await this._api.importKey(\"raw\", pubRaw.buffer, this._alg, true, []);\n }\n}\n","// deno-lint-ignore-file no-explicit-any\n/**\n * This file is based on noble-curves (https://github.com/paulmillr/noble-curves).\n *\n * noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-curves/blob/b9d49d2b41d550571a0c5be443ecb62109fa3373/src/utils.ts\n */\n/**\n * Hex, bytes and number utilities.\n * @module\n */\nimport { loadCrypto } from \"./misc.js\";\nimport { N_0 } from \"../consts.js\";\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) && a.constructor.name === \"Uint8Array\");\n}\n/** Asserts something is positive integer. */\nexport function anumber(n, title = \"\") {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >0, got ${n}`);\n }\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(value, length, title = \"\") {\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// ahash function is now imported from ../hash/hash.ts\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error(\"Hash instance has been destroyed\");\n if (checkFinished && instance.finished) {\n throw new Error(\"Hash#digest() has already been called\");\n }\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out, undefined, \"digestInto() output\");\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n// Used in weierstrass, der\nfunction abignumer(n) {\n if (typeof n === \"bigint\") {\n if (!isPosBig(n))\n throw new Error(\"positive bigint expected, got \" + n);\n }\n else\n anumber(n);\n return n;\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Pre-computed buffer for endianness detection */\nconst _endianTestBuffer = /* @__PURE__ */ new Uint32Array([0x11223344]);\nconst _endianTestBytes = /* @__PURE__ */ new Uint8Array(_endianTestBuffer.buffer);\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ _endianTestBytes[0] === 0x44;\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport function swap8IfBE(n) {\n return isLE ? n : byteSwap(n);\n}\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport function swap32IfBE(u) {\n return isLE ? u : byteSwap32(u);\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore: to use toHex\ntypeof Uint8Array.from([]).toHex === \"function\" &&\n // @ts-ignore: to use fromHex\n typeof Uint8Array.fromHex === \"function\")();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, \"0\"));\nconst HEX_TO_BIGINT = /* @__PURE__ */ [\n 0n,\n 1n,\n 2n,\n 3n,\n 4n,\n 5n,\n 6n,\n 7n,\n 8n,\n 9n,\n 10n,\n 11n,\n 12n,\n 13n,\n 14n,\n 15n,\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) {\n abytes(bytes);\n // @ts-ignore: to use toHex\n if (hasHexBuiltin)\n 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// 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 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\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) {\n if (typeof hex !== \"string\") {\n throw new Error(\"hex string expected, got \" + typeof hex);\n }\n // @ts-ignore: to use fromHex\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) {\n throw new Error(\"hex string expected, got unpadded hex of length \" + hl);\n }\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 ' +\n 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 * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== \"string\")\n throw new Error(\"string expected\");\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\nexport function numberToHexUnpadded(num) {\n const hex = abignumer(num).toString(16);\n return hex.length & 1 ? \"0\" + hex : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== \"string\") {\n throw new Error(\"hex string expected, got \" + typeof hex);\n }\n let out = N_0;\n for (let i = 0; i < hex.length; i++) {\n const n = asciiToBase16(hex.charCodeAt(i));\n if (n === undefined) {\n throw new Error('hex string expected, got non-hex character \"' + hex[i] +\n '\" at index ' + i);\n }\n out = (out << 4n) | HEX_TO_BIGINT[n];\n }\n return out; // Big Endian\n}\nexport function numberToBigint(num) {\n anumber(num, \"numberToBigint\");\n let n = num;\n let out = N_0;\n let bit = 1n;\n while (n > 0) {\n if (n % 2 === 1)\n out += bit;\n n = Math.floor(n / 2);\n bit <<= 1n;\n }\n return out;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n anumber(len);\n n = abignumer(n);\n const res = hexToBytes(n.toString(16).padStart(len * 2, \"0\"));\n if (res.length !== len)\n throw new Error(\"number too large\");\n return res;\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\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) {\n return Uint8Array.from(bytes);\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\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/**\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) {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n// Is positive bigint\nfunction isPosBig(n) {\n return typeof n === \"bigint\" && N_0 <= n;\n}\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\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, n, min, max) {\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}\nexport function validateObject(object, fields = {}, optFields = {}) {\n if (!object || typeof object !== \"object\") {\n throw new Error(\"expected valid options object\");\n }\n function checkField(fieldName, expectedType, isOpt) {\n const val = object[fieldName];\n if (isOpt && val === undefined)\n 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 }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n// createHasher function is now exported above with ahash\n// /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\n// export function randomBytes(bytesLength = 32): Uint8Array {\n// const cr = typeof globalThis != null && (globalThis as any).crypto;\n// if (!cr || typeof cr.getRandomValues !== \"function\") {\n// throw new Error(\"crypto.getRandomValues must be defined\");\n// }\n// return cr.getRandomValues(new Uint8Array(bytesLength));\n// }\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport async function randomBytesAsync(bytesLength = 32) {\n const api = await loadCrypto();\n const rnd = new Uint8Array(bytesLength);\n api.getRandomValues(rnd);\n return rnd;\n}\n// 06 09 60 86 48 01 65 03 04 02\nexport function oidNist(suffix) {\n return {\n oid: Uint8Array.from([\n 0x06,\n 0x09,\n 0x60,\n 0x86,\n 0x48,\n 0x01,\n 0x65,\n 0x03,\n 0x04,\n 0x02,\n suffix,\n ]),\n };\n}\n","/**\n * This file is based on noble-curves (https://github.com/paulmillr/noble-curves).\n *\n * noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-curves/blob/b9d49d2b41d550571a0c5be443ecb62109fa3373/src/utils.ts\n */\n/**\n * Hash utilities and type definitions extracted from noble.ts\n * @module\n */\nimport { anumber } from \"../utils/noble.js\";\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== \"function\" || typeof h.create !== \"function\") {\n throw new Error(\"Hash must wrapped by utils.createHasher\");\n }\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\nexport function createHasher(hashCons, info = {}) {\n const hashFn = (msg, opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n const hashC = Object.assign(hashFn, {\n outputLen: tmp.outputLen,\n blockLen: tmp.blockLen,\n create: (opts) => hashCons(opts),\n ...info,\n });\n return Object.freeze(hashC);\n}\n","// deno-lint-ignore-file no-explicit-any\n/**\n * This file is based on noble-hashes (https://github.com/paulmillr/noble-hashes).\n *\n * noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-hashes/blob/2e0c00e1aa134082ba1380bf3afb8b1641f60fed/src/hmac.ts\n */\n/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, clean } from \"../utils/noble.js\";\nimport { ahash } from \"./hash.js\";\nexport class _HMAC {\n constructor(hash, key) {\n Object.defineProperty(this, \"oHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"iHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"blockLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"outputLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"finished\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"destroyed\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n ahash(hash);\n abytes(key, undefined, \"key\");\n this.iHash = hash.create();\n if (typeof this.iHash.update !== \"function\") {\n throw new Error(\"Expected instance of class which extends utils.Hash\");\n }\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n abytes(out, this.outputLen, \"output\");\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new _HMAC(hash, key);\n","/**\n * This file is based on noble-hashes (https://github.com/paulmillr/noble-hashes).\n *\n * noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-hashes/blob/4e358a46d682adfb005ae6314ec999f2513086b9/src/_u64.ts\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 = 0xffffffffn;\nconst _32n = 32n;\nfunction fromBig(n, le = false) {\n if (le) {\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n }\n return {\n h: Number((n >> _32n) & U32_MASK64) | 0,\n l: Number(n & U32_MASK64) | 0,\n };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n const Ah = new Uint32Array(len);\n const 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}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\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(Ah, Al, Bh, Bl) {\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, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig, };\n// prettier-ignore\nconst u64 = {\n fromBig,\n split,\n toBig,\n shrSH,\n shrSL,\n rotrSH,\n rotrSL,\n rotrBH,\n rotrBL,\n rotr32H,\n rotr32L,\n rotlSH,\n rotlSL,\n rotlBH,\n rotlBL,\n add,\n add3L,\n add3H,\n add4L,\n add4H,\n add5H,\n add5L,\n};\nexport default u64;\n","/**\n * This file is based on noble-hashes (https://github.com/paulmillr/noble-hashes).\n *\n * noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-hashes/blob/4e358a46d682adfb005ae6314ec999f2513086b9/src/sha3.ts\n */\n/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from \"./u64.js\";\nimport { abytes, aexists, anumber, aoutput, clean, oidNist, swap32IfBE, u32, } from \"../utils/noble.js\";\nimport { createHasher, } from \"./hash.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = 0n;\nconst _1n = 1n;\nconst _2n = 2n;\nconst _7n = 7n;\nconst _256n = 256n;\nconst _0x71n = 0x71n;\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = []; // no pure annotation: var is always used\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s, rounds = 24, B) {\n if (!B)\n B = new Uint32Array(10);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++) {\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n }\n // for (let x = 0; x < 10; x += 2) {\n // const idx1 = (x + 8) % 10;\n // const idx0 = (x + 2) % 10;\n // const B0 = B[idx0];\n // const B1 = B[idx0 + 1];\n // const Th = rotlH(B0, B1, 1) ^ B[idx1];\n // const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n // for (let y = 0; y < 50; y += 10) {\n // s[x + y] ^= Th;\n // s[x + y + 1] ^= Tl;\n // }\n // }\n { // x=0: idx0=2, idx1=8\n const Th = rotlH(B[2], B[3], 1) ^ B[8];\n const Tl = rotlL(B[2], B[3], 1) ^ B[9];\n s[0] ^= Th;\n s[1] ^= Tl;\n s[10] ^= Th;\n s[11] ^= Tl;\n s[20] ^= Th;\n s[21] ^= Tl;\n s[30] ^= Th;\n s[31] ^= Tl;\n s[40] ^= Th;\n s[41] ^= Tl;\n }\n { // x=2: idx0=4, idx1=0\n const Th = rotlH(B[4], B[5], 1) ^ B[0];\n const Tl = rotlL(B[4], B[5], 1) ^ B[1];\n s[2] ^= Th;\n s[3] ^= Tl;\n s[12] ^= Th;\n s[13] ^= Tl;\n s[22] ^= Th;\n s[23] ^= Tl;\n s[32] ^= Th;\n s[33] ^= Tl;\n s[42] ^= Th;\n s[43] ^= Tl;\n }\n { // x=4: idx0=6, idx1=2\n const Th = rotlH(B[6], B[7], 1) ^ B[2];\n const Tl = rotlL(B[6], B[7], 1) ^ B[3];\n s[4] ^= Th;\n s[5] ^= Tl;\n s[14] ^= Th;\n s[15] ^= Tl;\n s[24] ^= Th;\n s[25] ^= Tl;\n s[34] ^= Th;\n s[35] ^= Tl;\n s[44] ^= Th;\n s[45] ^= Tl;\n }\n { // x=6: idx0=8, idx1=4\n const Th = rotlH(B[8], B[9], 1) ^ B[4];\n const Tl = rotlL(B[8], B[9], 1) ^ B[5];\n s[6] ^= Th;\n s[7] ^= Tl;\n s[16] ^= Th;\n s[17] ^= Tl;\n s[26] ^= Th;\n s[27] ^= Tl;\n s[36] ^= Th;\n s[37] ^= Tl;\n s[46] ^= Th;\n s[47] ^= Tl;\n }\n { // x=8: idx0=0, idx1=6\n const Th = rotlH(B[0], B[1], 1) ^ B[6];\n const Tl = rotlL(B[0], B[1], 1) ^ B[7];\n s[8] ^= Th;\n s[9] ^= Tl;\n s[18] ^= Th;\n s[19] ^= Tl;\n s[28] ^= Th;\n s[29] ^= Tl;\n s[38] ^= Th;\n s[39] ^= Tl;\n s[48] ^= Th;\n s[49] ^= Tl;\n }\n // Rho (ρ) and Pi (π) — fully unrolled\n let curH = s[2];\n let curL = s[3];\n // for (let t = 0; t < 24; t++) {\n // const shift = SHA3_ROTL[t];\n // const Th = rotlH(curH, curL, shift);\n // const Tl = rotlL(curH, curL, shift);\n // const PI = SHA3_PI[t];\n // curH = s[PI];\n // curL = s[PI + 1];\n // s[PI] = Th;\n // s[PI + 1] = Tl;\n // }\n let Th, Tl;\n // t=0: shift=1(S), PI=20\n Th = rotlSH(curH, curL, 1);\n Tl = rotlSL(curH, curL, 1);\n curH = s[20];\n curL = s[21];\n s[20] = Th;\n s[21] = Tl;\n // t=1: shift=3(S), PI=14\n Th = rotlSH(curH, curL, 3);\n Tl = rotlSL(curH, curL, 3);\n curH = s[14];\n curL = s[15];\n s[14] = Th;\n s[15] = Tl;\n // t=2: shift=6(S), PI=22\n Th = rotlSH(curH, curL, 6);\n Tl = rotlSL(curH, curL, 6);\n curH = s[22];\n curL = s[23];\n s[22] = Th;\n s[23] = Tl;\n // t=3: shift=10(S), PI=34\n Th = rotlSH(curH, curL, 10);\n Tl = rotlSL(curH, curL, 10);\n curH = s[34];\n curL = s[35];\n s[34] = Th;\n s[35] = Tl;\n // t=4: shift=15(S), PI=36\n Th = rotlSH(curH, curL, 15);\n Tl = rotlSL(curH, curL, 15);\n curH = s[36];\n curL = s[37];\n s[36] = Th;\n s[37] = Tl;\n // t=5: shift=21(S), PI=6\n Th = rotlSH(curH, curL, 21);\n Tl = rotlSL(curH, curL, 21);\n curH = s[6];\n curL = s[7];\n s[6] = Th;\n s[7] = Tl;\n // t=6: shift=28(S), PI=10\n Th = rotlSH(curH, curL, 28);\n Tl = rotlSL(curH, curL, 28);\n curH = s[10];\n curL = s[11];\n s[10] = Th;\n s[11] = Tl;\n // t=7: shift=36(B), PI=32\n Th = rotlBH(curH, curL, 36);\n Tl = rotlBL(curH, curL, 36);\n curH = s[32];\n curL = s[33];\n s[32] = Th;\n s[33] = Tl;\n // t=8: shift=45(B), PI=16\n Th = rotlBH(curH, curL, 45);\n Tl = rotlBL(curH, curL, 45);\n curH = s[16];\n curL = s[17];\n s[16] = Th;\n s[17] = Tl;\n // t=9: shift=55(B), PI=42\n Th = rotlBH(curH, curL, 55);\n Tl = rotlBL(curH, curL, 55);\n curH = s[42];\n curL = s[43];\n s[42] = Th;\n s[43] = Tl;\n // t=10: shift=2(S), PI=48\n Th = rotlSH(curH, curL, 2);\n Tl = rotlSL(curH, curL, 2);\n curH = s[48];\n curL = s[49];\n s[48] = Th;\n s[49] = Tl;\n // t=11: shift=14(S), PI=8\n Th = rotlSH(curH, curL, 14);\n Tl = rotlSL(curH, curL, 14);\n curH = s[8];\n curL = s[9];\n s[8] = Th;\n s[9] = Tl;\n // t=12: shift=27(S), PI=30\n Th = rotlSH(curH, curL, 27);\n Tl = rotlSL(curH, curL, 27);\n curH = s[30];\n curL = s[31];\n s[30] = Th;\n s[31] = Tl;\n // t=13: shift=41(B), PI=46\n Th = rotlBH(curH, curL, 41);\n Tl = rotlBL(curH, curL, 41);\n curH = s[46];\n curL = s[47];\n s[46] = Th;\n s[47] = Tl;\n // t=14: shift=56(B), PI=38\n Th = rotlBH(curH, curL, 56);\n Tl = rotlBL(curH, curL, 56);\n curH = s[38];\n curL = s[39];\n s[38] = Th;\n s[39] = Tl;\n // t=15: shift=8(S), PI=26\n Th = rotlSH(curH, curL, 8);\n Tl = rotlSL(curH, curL, 8);\n curH = s[26];\n curL = s[27];\n s[26] = Th;\n s[27] = Tl;\n // t=16: shift=25(S), PI=24\n Th = rotlSH(curH, curL, 25);\n Tl = rotlSL(curH, curL, 25);\n curH = s[24];\n curL = s[25];\n s[24] = Th;\n s[25] = Tl;\n // t=17: shift=43(B), PI=4\n Th = rotlBH(curH, curL, 43);\n Tl = rotlBL(curH, curL, 43);\n curH = s[4];\n curL = s[5];\n s[4] = Th;\n s[5] = Tl;\n // t=18: shift=62(B), PI=40\n Th = rotlBH(curH, curL, 62);\n Tl = rotlBL(curH, curL, 62);\n curH = s[40];\n curL = s[41];\n s[40] = Th;\n s[41] = Tl;\n // t=19: shift=18(S), PI=28\n Th = rotlSH(curH, curL, 18);\n Tl = rotlSL(curH, curL, 18);\n curH = s[28];\n curL = s[29];\n s[28] = Th;\n s[29] = Tl;\n // t=20: shift=39(B), PI=44\n Th = rotlBH(curH, curL, 39);\n Tl = rotlBL(curH, curL, 39);\n curH = s[44];\n curL = s[45];\n s[44] = Th;\n s[45] = Tl;\n // t=21: shift=61(B), PI=18\n Th = rotlBH(curH, curL, 61);\n Tl = rotlBL(curH, curL, 61);\n curH = s[18];\n curL = s[19];\n s[18] = Th;\n s[19] = Tl;\n // t=22: shift=20(S), PI=12\n Th = rotlSH(curH, curL, 20);\n Tl = rotlSL(curH, curL, 20);\n curH = s[12];\n curL = s[13];\n s[12] = Th;\n s[13] = Tl;\n // t=23: shift=44(B), PI=2\n Th = rotlBH(curH, curL, 44);\n Tl = rotlBL(curH, curL, 44);\n s[2] = Th;\n s[3] = Tl;\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n B[0] = s[y];\n B[1] = s[y + 1];\n B[2] = s[y + 2];\n B[3] = s[y + 3];\n B[4] = s[y + 4];\n B[5] = s[y + 5];\n B[6] = s[y + 6];\n B[7] = s[y + 7];\n B[8] = s[y + 8];\n B[9] = s[y + 9];\n s[y + 0] ^= ~B[2] & B[4];\n s[y + 1] ^= ~B[3] & B[5];\n s[y + 2] ^= ~B[4] & B[6];\n s[y + 3] ^= ~B[5] & B[7];\n s[y + 4] ^= ~B[6] & B[8];\n s[y + 5] ^= ~B[7] & B[9];\n s[y + 6] ^= ~B[8] & B[0];\n s[y + 7] ^= ~B[9] & B[1];\n s[y + 8] ^= ~B[0] & B[2];\n s[y + 9] ^= ~B[1] & B[3];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n}\n/** Keccak sponge function. */\nexport class Keccak {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n Object.defineProperty(this, \"state\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"pos\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"posOut\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"finished\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"state32\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"destroyed\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"_B\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint32Array(10)\n });\n Object.defineProperty(this, \"blockLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"suffix\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"outputLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"enableXOF\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"rounds\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen, \"outputLen\");\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200)) {\n throw new Error(\"only keccak-f1600 function is supported\");\n }\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n /** Resets instance to initial (empty) state for reuse. */\n reset() {\n this.state.fill(0);\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds, this._B);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n abytes(data);\n return this.updateUnsafe(data);\n }\n /** Like update(), but skips validation. Caller must ensure valid state and input. */\n updateUnsafe(data) {\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n return this.writeIntoUnsafe(out);\n }\n /** Like writeInto(), but skips validation. Caller must ensure valid state and output. */\n writeIntoUnsafe(out) {\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\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) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF) {\n throw new Error(\"XOF is not possible for this instance\");\n }\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error(\"digest() was already called\");\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);\n// /** SHA3-224 hash function. */\n// export const sha3_224: CHash = /* @__PURE__ */ genKeccak(\n// 0x06,\n// 144,\n// 28,\n// /* @__PURE__ */ oidNist(0x07),\n// );\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256 = /* @__PURE__ */ genKeccak(0x06, 136, 32, \n/* @__PURE__ */ oidNist(0x08));\n/** SHA3-384 hash function. */\nexport const sha3_384 = /* @__PURE__ */ genKeccak(0x06, 104, 48, \n/* @__PURE__ */ oidNist(0x09));\n/** SHA3-512 hash function. */\nexport const sha3_512 = /* @__PURE__ */ genKeccak(0x06, 72, 64, \n/* @__PURE__ */ oidNist(0x0a));\n/** keccak-224 hash function. */\nexport const keccak_224 = /* @__PURE__ */ genKeccak(0x01, 144, 28);\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256 = /* @__PURE__ */ genKeccak(0x01, 136, 32);\n/** keccak-384 hash function. */\nexport const keccak_384 = /* @__PURE__ */ genKeccak(0x01, 104, 48);\n/** keccak-512 hash function. */\nexport const keccak_512 = /* @__PURE__ */ genKeccak(0x01, 72, 64);\nconst genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true), info);\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));\n// /** SHAKE128 XOF with 256-bit output (NIST version). */\n// export const shake128_32: CHashXOF<Keccak, ShakeOpts> =\n// /* @__PURE__ */\n// genShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b));\n// /** SHAKE256 XOF with 512-bit output (NIST version). */\n// export const shake256_64: CHashXOF<Keccak, ShakeOpts> =\n// /* @__PURE__ */\n// genShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c));\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/utils.ts\n */\n/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\nimport { abytes, aexists, anumber, aoutput, clean, copyBytes, createView, isLE, numberToBigint, u32, } from \"@hpke/common\";\nexport { abytes, aexists, anumber, aoutput, clean, copyBytes, createView, isLE, u32, };\n/** Asserts something is boolean. */\nexport function abool(b) {\n if (typeof b !== \"boolean\")\n throw new Error(`boolean expected, not ${b}`);\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * @__NO_SIDE_EFFECTS__\n */\n// deno-lint-ignore no-explicit-any\nexport const wrapCipher = (params, constructor) => {\n // deno-lint-ignore no-explicit-any\n function wrappedCipher(key, ...args) {\n // Validate key\n abytes(key, undefined, \"key\");\n // Big-Endian hardware is rare. Just in case someone still decides to run ciphers:\n if (!isLE) {\n throw new Error(\"Non little-endian hardware is not yet supported\");\n }\n // Validate nonce if nonceLength is present\n if (params.nonceLength !== undefined) {\n const nonce = args[0];\n abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, \"nonce\");\n }\n // Validate AAD if tagLength present\n const tagl = params.tagLength;\n if (tagl && args[1] !== undefined)\n abytes(args[1], undefined, \"AAD\");\n const cipher = constructor(key, ...args);\n const checkOutput = (fnLength, output) => {\n if (output !== undefined) {\n if (fnLength !== 2)\n throw new Error(\"cipher output not supported\");\n abytes(output, undefined, \"output\");\n }\n };\n // Create wrapped cipher with validation and single-use encryption\n let called = false;\n const wrCipher = {\n encrypt(data, output) {\n if (called) {\n throw new Error(\"cannot encrypt() twice with same key + nonce\");\n }\n called = true;\n abytes(data);\n checkOutput(cipher.encrypt.length, output);\n return cipher.encrypt(data, output);\n },\n decrypt(data, output) {\n abytes(data);\n if (tagl && data.length < tagl) {\n throw new Error('\"ciphertext\" expected length bigger than tagLength=' + tagl);\n }\n checkOutput(cipher.decrypt.length, output);\n return cipher.decrypt(data, output);\n },\n };\n return wrCipher;\n }\n Object.assign(wrappedCipher, params);\n return wrappedCipher;\n};\nexport function checkOpts(defaults, opts) {\n if (opts == null || typeof opts !== \"object\") {\n throw new Error(\"options must be defined\");\n }\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** Compares 2 uint8array-s in kinda constant time. */\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n */\nexport function getOutput(expectedLength, out, onlyAligned = true) {\n if (out === undefined)\n return new Uint8Array(expectedLength);\n if (out.length !== expectedLength) {\n throw new Error('\"output\" expected Uint8Array of length ' + expectedLength + \", got: \" +\n out.length);\n }\n if (onlyAligned && !isAligned32(out)) {\n throw new Error(\"invalid output, must be aligned\");\n }\n return out;\n}\nexport function u64Lengths(dataLength, aadLength, isLE) {\n abool(isLE);\n const num = new Uint8Array(16);\n const view = createView(num);\n view.setBigUint64(0, numberToBigint(aadLength), isLE);\n view.setBigUint64(8, numberToBigint(dataLength), isLE);\n return num;\n}\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\n// Re-exported from @hpke/common.\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/_arx.ts\n */\n/**\n * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\n\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | cnt(1) | nonce(3)\n chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).\n\n[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/\n[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2\n\n * @module\n */\nimport { abool, abytes, anumber, checkOpts, clean, copyBytes, u32, } from \"./utils.js\";\n// Can't use similar utils.utf8ToBytes, because it uses `TextEncoder` - not available in all envs\nconst _utf8ToBytes = (str) => Uint8Array.from(str.split(\"\").map((c) => c.charCodeAt(0)));\nconst sigma16 = _utf8ToBytes(\"expand 16-byte k\");\nconst sigma32 = _utf8ToBytes(\"expand 32-byte k\");\nconst sigma16_32 = u32(sigma16);\nconst sigma32_32 = u32(sigma32);\n/** Rotate left. */\nexport function rotl(a, b) {\n return (a << b) | (a >>> (32 - b));\n}\n// Is byte array aligned to 4 byte offset (u32)?\nfunction isAligned32(b) {\n return b.byteOffset % 4 === 0;\n}\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\nconst BLOCK_LEN32 = 16;\n// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]\n// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]\nconst MAX_COUNTER = 2 ** 32 - 1;\nconst U32_EMPTY = Uint32Array.of();\nfunction runCipher(core, sigma, key, nonce, data, output, counter, rounds) {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n if (counter >= MAX_COUNTER)\n throw new Error(\"arx: counter overflow\");\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0)\n throw new Error(\"arx: invalid block position\");\n for (let j = 0, posj; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\n/** Creates ARX-like (ChaCha, Salsa) cipher stream from core function. */\nexport function createCipher(core, opts) {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({\n allowShortKeys: false,\n counterLength: 8,\n counterRight: false,\n rounds: 20,\n }, opts);\n if (typeof core !== \"function\")\n throw new Error(\"core must be a function\");\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (key, nonce, data, output, counter = 0) => {\n abytes(key, undefined, \"key\");\n abytes(nonce, undefined, \"nonce\");\n abytes(data, undefined, \"data\");\n const len = data.length;\n if (output === undefined)\n output = new Uint8Array(len);\n abytes(output, undefined, \"output\");\n anumber(counter);\n if (counter < 0 || counter >= MAX_COUNTER) {\n throw new Error(\"arx: counter overflow\");\n }\n if (output.length < len) {\n throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);\n }\n const toClean = [];\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n const l = key.length;\n let k;\n let sigma;\n if (l === 32) {\n toClean.push(k = copyBytes(key));\n sigma = sigma32_32;\n }\n else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n }\n else {\n abytes(key, 32, \"arx key\");\n throw new Error(\"invalid key size\");\n // throw new Error(`\"arx key\" expected Uint8Array of length 32, got length=${l}`);\n }\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Align nonce to 4 bytes\n if (!isAligned32(nonce))\n toClean.push(nonce = copyBytes(nonce));\n const k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24) {\n throw new Error(`arx: extended nonce must be 24 bytes`);\n }\n extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);\n nonce = nonce.subarray(16);\n }\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length) {\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n }\n // Pad counter when nonce is 64 bit\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = u32(nonce);\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n clean(...toClean);\n return output;\n };\n}\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/_poly1305.ts\n */\n/**\n * Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf),\n * [wiki](https://en.wikipedia.org/wiki/Poly1305))\n * is a fast and parallel secret-key message-authentication code suitable for\n * a wide variety of applications. It was standardized in\n * [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439) and is now used in TLS 1.3.\n *\n * Polynomial MACs are not perfect for every situation:\n * they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.\n * See [invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/).\n * To combat invisible salamanders, `hash(key)` can be included in ciphertext,\n * however, this would violate ciphertext indistinguishability:\n * an attacker would know which key was used - so `HKDF(key, i)`\n * could be used instead.\n *\n * Check out [original website](https://cr.yp.to/mac.html).\n * Based on Public Domain [poly1305-donna](https://github.com/floodyberry/poly1305-donna).\n * @module\n */\nimport { abytes, aexists, aoutput, clean, copyBytes, } from \"./utils.js\";\nfunction u8to16(a, i) {\n return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\n}\n// function bytesToNumberLE(bytes: Uint8Array): bigint {\n// return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n// }\n// /** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */\n// function poly1305_small(msg: Uint8Array, key: Uint8Array): Uint8Array {\n// abytes(msg);\n// abytes(key, 32, \"key\");\n// const POW_2_130_5 = 2n ** 130n - 5n; // 2^130-5\n// const POW_2_128_1 = 2n ** 128n - 1n; // 2^128-1\n// const CLAMP_R = 0x0ffffffc0ffffffc0ffffffc0fffffffn;\n// const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;\n// const s = bytesToNumberLE(key.subarray(16));\n// // Process by 16 byte chunks\n// let acc = 0n;\n// for (let i = 0; i < msg.length; i += 16) {\n// const m = msg.subarray(i, i + 16);\n// const n = bytesToNumberLE(m) | (1n << (8n * mLen)); // mLen: bigint\n// acc = ((acc + n) * r) % POW_2_130_5;\n// }\n// const res = (acc + s) & POW_2_128_1;\n// return numberToBytesBE(res, 16).reverse(); // LE\n// }\n// Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability.\n// function poly1305_computeTag_small(\n// authKey: Uint8Array,\n// lengths: Uint8Array,\n// ciphertext: Uint8Array,\n// AAD?: Uint8Array,\n// ): Uint8Array {\n// const res = [];\n// const updatePadded2 = (msg: Uint8Array) => {\n// res.push(msg);\n// const leftover = msg.length % 16;\n// if (leftover) res.push(new Uint8Array(16).slice(leftover));\n// };\n// if (AAD) updatePadded2(AAD);\n// updatePadded2(ciphertext);\n// res.push(lengths);\n// return poly1305_small(concatBytes(...res), authKey);\n// }\n/** Poly1305 class. Prefer poly1305() function instead. */\nexport class Poly1305 {\n // Can be speed-up using BigUint64Array, at the cost of complexity\n constructor(key) {\n Object.defineProperty(this, \"blockLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n Object.defineProperty(this, \"outputLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n Object.defineProperty(this, \"buffer\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint8Array(16)\n });\n Object.defineProperty(this, \"r\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint16Array(10)\n }); // Allocating 1 array with .subarray() here is slower than 3\n Object.defineProperty(this, \"h\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint16Array(10)\n });\n Object.defineProperty(this, \"pad\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint16Array(8)\n });\n Object.defineProperty(this, \"pos\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"finished\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n key = copyBytes(abytes(key, 32, \"key\"));\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++)\n this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n process(data, offset, isLast = false) {\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n const h0 = h[0] + (t0 & 0x1fff);\n const h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n const h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n const h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n const h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n const h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n const h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n const h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n const h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n const h9 = h[9] + ((t7 >>> 5) | hibit);\n let c = 0;\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) +\n h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) +\n h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) +\n h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) +\n h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) +\n h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) +\n h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) +\n h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) +\n h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++)\n g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++)\n h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n clean(g);\n }\n update(data) {\n aexists(this);\n abytes(data);\n data = copyBytes(data);\n const { 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\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(data, 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(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy() {\n clean(this.h, this.r, this.buffer, this.pad);\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n buffer[pos++] = 1;\n for (; pos < 16; pos++)\n buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n return out;\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n}\nexport function wrapConstructorWithKey(hashCons) {\n const hashC = (msg, key) => hashCons(key).update(msg).digest();\n const tmp = hashCons(new Uint8Array(32)); // tmp array, used just once below\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key) => hashCons(key);\n return hashC;\n}\n/** Poly1305 MAC from RFC 8439. */\nexport const poly1305 = \n/** @__PURE__ */ (() => wrapConstructorWithKey((key) => new Poly1305(key)))();\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/chacha.ts\n */\n/**\n * ChaCha stream cipher, released\n * in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.\n * It was standardized in [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439) and\n * is now used in TLS 1.3.\n *\n * [XChaCha20](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha)\n * extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with\n * randomly-generated nonces.\n *\n * Check out [PDF](http://cr.yp.to/chacha/chacha-20080128.pdf) and\n * [wiki](https://en.wikipedia.org/wiki/Salsa20) and\n * [website](https://cr.yp.to/chacha.html).\n *\n * @module\n */\nimport { createCipher, rotl } from \"./_arx.js\";\nimport { poly1305 } from \"./_poly1305.js\";\nimport { abytes, clean, equalBytes, getOutput, u64Lengths, wrapCipher, } from \"./utils.js\";\n/**\n * ChaCha core function. It is implemented twice:\n * 1. Simple loop (chachaCore_small, hchacha_small)\n * 2. Unrolled loop (chachaCore, hchacha) - 4x faster, but larger & harder to read\n * The specific implementation is selected in `createCipher` below.\n */\nfunction chachaCore(s, k, n, out, cnt, rounds = 20) {\n const y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter\tNonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 7);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 7);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 7);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 8);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 7);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 7);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 7);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 7);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 16);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 7);\n }\n // Write output\n let oi = 0;\n out[oi++] = (y00 + x00) | 0;\n out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0;\n out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0;\n out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0;\n out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0;\n out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0;\n out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0;\n out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0;\n out[oi++] = (y15 + x15) | 0;\n}\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// Pad to digest size with zeros\nconst updatePadded = (h, msg) => {\n h.update(msg);\n const leftover = msg.length % 16;\n if (leftover)\n h.update(ZEROS16.subarray(leftover));\n};\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(fn, key, nonce, ciphertext, AAD) {\n if (AAD !== undefined)\n abytes(AAD, undefined, \"AAD\");\n const authKey = fn(key, nonce, ZEROS32);\n const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);\n // Methods below can be replaced with\n // return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)\n const h = poly1305.create(authKey);\n if (AAD)\n updatePadded(h, AAD);\n updatePadded(h, ciphertext);\n h.update(lengths);\n const res = h.digest();\n clean(authKey, lengths);\n return res;\n}\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them, but it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {\n const tagLength = 16;\n return {\n encrypt(plaintext, output) {\n const plength = plaintext.length;\n output = getOutput(plength + tagLength, output, false);\n output.set(plaintext);\n const oPlain = output.subarray(0, -tagLength);\n // Actual encryption\n xorStream(key, nonce, oPlain, oPlain, 1);\n const tag = computeTag(xorStream, key, nonce, oPlain, AAD);\n output.set(tag, plength); // append tag\n clean(tag);\n return output;\n },\n decrypt(ciphertext, output) {\n output = getOutput(ciphertext.length - tagLength, output, false);\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n if (!equalBytes(passedTag, tag))\n throw new Error(\"invalid tag\");\n output.set(ciphertext.subarray(0, -tagLength));\n // Actual decryption\n xorStream(key, nonce, output, output, 1); // start stream with i=1\n clean(tag);\n return output;\n },\n };\n};\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n *\n * Unsafe to use random nonces under the same key, due to collision chance.\n * Prefer XChaCha instead.\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20));\n","import { ExportError, INPUT_LENGTH_LIMIT, InvalidParamError, toArrayBuffer, } from \"@hpke/common\";\nimport { emitNotSupported } from \"./utils/emitNotSupported.js\";\n// b\"sec\"\nconst LABEL_SEC = new Uint8Array([115, 101, 99]);\nexport class ExporterContextImpl {\n constructor(api, kdf, exporterSecret) {\n Object.defineProperty(this, \"_api\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"exporterSecret\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._api = api;\n this._kdf = kdf;\n this.exporterSecret = exporterSecret;\n }\n async seal(_data, _aad) {\n return await emitNotSupported();\n }\n async open(_data, _aad) {\n return await emitNotSupported();\n }\n async export(exporterContext, len) {\n const rawExporterContext = toArrayBuffer(exporterContext);\n if (rawExporterContext.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long exporter context\");\n }\n try {\n return await this._kdf.labeledExpand(this.exporterSecret, LABEL_SEC, new Uint8Array(rawExporterContext), len);\n }\n catch (e) {\n throw new ExportError(e);\n }\n }\n}\nexport class RecipientExporterContextImpl extends ExporterContextImpl {\n}\nexport class SenderExporterContextImpl extends ExporterContextImpl {\n constructor(api, kdf, exporterSecret, enc) {\n super(api, kdf, exporterSecret);\n Object.defineProperty(this, \"enc\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.enc = enc;\n return;\n }\n}\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _Mutex_locked;\nexport class Mutex {\n constructor() {\n _Mutex_locked.set(this, Promise.resolve());\n }\n async lock() {\n let releaseLock;\n const nextLock = new Promise((resolve) => {\n releaseLock = resolve;\n });\n const previousLock = __classPrivateFieldGet(this, _Mutex_locked, \"f\");\n __classPrivateFieldSet(this, _Mutex_locked, nextLock, \"f\");\n await previousLock;\n return releaseLock;\n }\n}\n_Mutex_locked = new WeakMap();\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _RecipientContextImpl_mutex;\nimport { EMPTY, OpenError, toArrayBuffer } from \"@hpke/common\";\nimport { EncryptionContextImpl } from \"./encryptionContext.js\";\nimport { Mutex } from \"./mutex.js\";\nexport class RecipientContextImpl extends EncryptionContextImpl {\n constructor() {\n super(...arguments);\n _RecipientContextImpl_mutex.set(this, void 0);\n }\n async open(data, aad = EMPTY.buffer) {\n __classPrivateFieldSet(this, _RecipientContextImpl_mutex, __classPrivateFieldGet(this, _RecipientContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n const release = await __classPrivateFieldGet(this, _RecipientContextImpl_mutex, \"f\").lock();\n let pt;\n try {\n pt = await this._ctx.key.open(this.computeNonce(this._ctx), toArrayBuffer(data), toArrayBuffer(aad));\n }\n catch (e) {\n throw new OpenError(e);\n }\n finally {\n release();\n }\n this.incrementSeq(this._ctx);\n return pt;\n }\n}\n_RecipientContextImpl_mutex = new WeakMap();\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _SenderContextImpl_mutex;\nimport { EMPTY, SealError, toArrayBuffer } from \"@hpke/common\";\nimport { EncryptionContextImpl } from \"./encryptionContext.js\";\nimport { Mutex } from \"./mutex.js\";\nexport class SenderContextImpl extends EncryptionContextImpl {\n constructor(api, kdf, params, enc) {\n super(api, kdf, params);\n Object.defineProperty(this, \"enc\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n _SenderContextImpl_mutex.set(this, void 0);\n this.enc = enc;\n }\n async seal(data, aad = EMPTY.buffer) {\n __classPrivateFieldSet(this, _SenderContextImpl_mutex, __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n const release = await __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\").lock();\n let ct;\n try {\n ct = await this._ctx.key.seal(this.computeNonce(this._ctx), toArrayBuffer(data), toArrayBuffer(aad));\n }\n catch (e) {\n throw new SealError(e);\n }\n finally {\n release();\n }\n this.incrementSeq(this._ctx);\n return ct;\n }\n}\n_SenderContextImpl_mutex = new WeakMap();\n","import { AeadId, EMPTY, i2Osp, INFO_LENGTH_LIMIT, INPUT_LENGTH_LIMIT, InvalidParamError, MINIMUM_PSK_LENGTH, Mode, NativeAlgorithm, toUint8Array, } from \"@hpke/common\";\nimport { RecipientExporterContextImpl, SenderExporterContextImpl, } from \"./exporterContext.js\";\nimport { RecipientContextImpl } from \"./recipientContext.js\";\nimport { SenderContextImpl } from \"./senderContext.js\";\n// b\"base_nonce\"\n// deno-fmt-ignore\nconst LABEL_BASE_NONCE = new Uint8Array([\n 98, 97, 115, 101, 95, 110, 111, 110, 99, 101,\n]);\n// b\"exp\"\nconst LABEL_EXP = new Uint8Array([101, 120, 112]);\n// b\"info_hash\"\n// deno-fmt-ignore\nconst LABEL_INFO_HASH = new Uint8Array([\n 105, 110, 102, 111, 95, 104, 97, 115, 104,\n]);\n// b\"key\"\nconst LABEL_KEY = new Uint8Array([107, 101, 121]);\n// b\"psk_id_hash\"\n// deno-fmt-ignore\nconst LABEL_PSK_ID_HASH = new Uint8Array([\n 112, 115, 107, 95, 105, 100, 95, 104, 97, 115, 104,\n]);\n// b\"secret\"\nconst LABEL_SECRET = new Uint8Array([115, 101, 99, 114, 101, 116]);\n// b\"HPKE\"\n// deno-fmt-ignore\nconst SUITE_ID_HEADER_HPKE = new Uint8Array([\n 72, 80, 75, 69, 0, 0, 0, 0, 0, 0,\n]);\n/**\n * The Hybrid Public Key Encryption (HPKE) ciphersuite,\n * which is implemented using only\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n *\n * This is the super class of {@link CipherSuite} and the same as\n * {@link https://jsr.io/@hpke/core/doc/~/CipherSuite | @hpke/core#CipherSuite} as follows:\n * which supports only the ciphersuites that can be implemented on the native\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n * Therefore, the following cryptographic algorithms are not supported for now:\n * - DHKEM(X25519, HKDF-SHA256)\n * - DHKEM(X448, HKDF-SHA512)\n * - ChaCha20Poly1305\n *\n * In addtion, the HKDF functions contained in this class can only derive\n * keys of the same length as the `hashSize`.\n *\n * If you want to use the unsupported cryptographic algorithms\n * above or derive keys longer than the `hashSize`,\n * please use {@link CipherSuite}.\n *\n * This class provides following functions:\n *\n * - Creates encryption contexts both for senders and recipients.\n * - {@link createSenderContext}\n * - {@link createRecipientContext}\n * - Provides single-shot encryption API.\n * - {@link seal}\n * - {@link open}\n *\n * The calling of the constructor of this class is the starting\n * point for HPKE operations for both senders and recipients.\n *\n * @example Use only ciphersuites supported by Web Cryptography API.\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * CipherSuite,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n *\n * @example Use a ciphersuite which is currently not supported by Web Cryptography API.\n *\n * ```ts\n * import { Aes128Gcm, HkdfSha256, CipherSuite } from \"@hpke/core\";\n * // Use an extension module.\n * import { DhkemX25519HkdfSha256 } from \"@hpke/dhkem-x25519\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemX25519HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class CipherSuiteNative extends NativeAlgorithm {\n /**\n * @param params A set of parameters for building a cipher suite.\n *\n * If the error occurred, throws {@link InvalidParamError}.\n *\n * @throws {@link InvalidParamError}\n */\n constructor(params) {\n super();\n Object.defineProperty(this, \"_kem\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_aead\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_suiteId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // KEM\n if (typeof params.kem === \"number\") {\n throw new InvalidParamError(\"KemId cannot be used\");\n }\n this._kem = params.kem;\n // KDF\n if (typeof params.kdf === \"number\") {\n throw new InvalidParamError(\"KdfId cannot be used\");\n }\n this._kdf = params.kdf;\n // AEAD\n if (typeof params.aead === \"number\") {\n throw new InvalidParamError(\"AeadId cannot be used\");\n }\n this._aead = params.aead;\n this._suiteId = new Uint8Array(SUITE_ID_HEADER_HPKE);\n this._suiteId.set(i2Osp(this._kem.id, 2), 4);\n this._suiteId.set(i2Osp(this._kdf.id, 2), 6);\n this._suiteId.set(i2Osp(this._aead.id, 2), 8);\n this._kdf.init(this._suiteId);\n }\n /**\n * Gets the KEM context of the ciphersuite.\n */\n get kem() {\n return this._kem;\n }\n /**\n * Gets the KDF context of the ciphersuite.\n */\n get kdf() {\n return this._kdf;\n }\n /**\n * Gets the AEAD context of the ciphersuite.\n */\n get aead() {\n return this._aead;\n }\n /**\n * Creates an encryption context for a sender.\n *\n * If the error occurred, throws {@link DecapError} | {@link ValidationError}.\n *\n * @param params A set of parameters for the sender encryption context.\n * @returns A sender encryption context.\n * @throws {@link EncapError}, {@link ValidationError}\n */\n async createSenderContext(params) {\n this._validateInputLength(params);\n await this._setup();\n const dh = await this._kem.encap(params);\n let mode;\n if (params.psk !== undefined) {\n mode = params.senderKey !== undefined ? Mode.AuthPsk : Mode.Psk;\n }\n else {\n mode = params.senderKey !== undefined ? Mode.Auth : Mode.Base;\n }\n return await this._keyScheduleS(mode, dh.sharedSecret, dh.enc, params);\n }\n /**\n * Creates an encryption context for a recipient.\n *\n * If the error occurred, throws {@link DecapError}\n * | {@link DeserializeError} | {@link ValidationError}.\n *\n * @param params A set of parameters for the recipient encryption context.\n * @returns A recipient encryption context.\n * @throws {@link DecapError}, {@link DeserializeError}, {@link ValidationError}\n */\n async createRecipientContext(params) {\n this._validateInputLength(params);\n await this._setup();\n const sharedSecret = await this._kem.decap(params);\n let mode;\n if (params.psk !== undefined) {\n mode = params.senderPublicKey !== undefined ? Mode.AuthPsk : Mode.Psk;\n }\n else {\n mode = params.senderPublicKey !== undefined ? Mode.Auth : Mode.Base;\n }\n return await this._keyScheduleR(mode, sharedSecret, params);\n }\n /**\n * Encrypts a message to a recipient.\n *\n * If the error occurred, throws `EncapError` | `MessageLimitReachedError` | `SealError` | `ValidationError`.\n *\n * @param params A set of parameters for building a sender encryption context.\n * @param pt A plain text as bytes to be encrypted.\n * @param aad Additional authenticated data as bytes fed by an application.\n * @returns A cipher text and an encapsulated key as bytes.\n * @throws {@link EncapError}, {@link MessageLimitReachedError}, {@link SealError}, {@link ValidationError}\n */\n async seal(params, pt, aad = EMPTY.buffer) {\n const ctx = await this.createSenderContext(params);\n return {\n ct: await ctx.seal(pt, aad),\n enc: ctx.enc,\n };\n }\n /**\n * Decrypts a message from a sender.\n *\n * If the error occurred, throws `DecapError` | `DeserializeError` | `OpenError` | `ValidationError`.\n *\n * @param params A set of parameters for building a recipient encryption context.\n * @param ct An encrypted text as bytes to be decrypted.\n * @param aad Additional authenticated data as bytes fed by an application.\n * @returns A decrypted plain text as bytes.\n * @throws {@link DecapError}, {@link DeserializeError}, {@link OpenError}, {@link ValidationError}\n */\n async open(params, ct, aad = EMPTY.buffer) {\n const ctx = await this.createRecipientContext(params);\n return await ctx.open(ct, aad);\n }\n // private verifyPskInputs(mode: Mode, params: KeyScheduleParams) {\n // const gotPsk = (params.psk !== undefined);\n // const gotPskId = (params.psk !== undefined && params.psk.id.byteLength > 0);\n // if (gotPsk !== gotPskId) {\n // throw new Error('Inconsistent PSK inputs');\n // }\n // if (gotPsk && (mode === Mode.Base || mode === Mode.Auth)) {\n // throw new Error('PSK input provided when not needed');\n // }\n // if (!gotPsk && (mode === Mode.Psk || mode === Mode.AuthPsk)) {\n // throw new Error('Missing required PSK input');\n // }\n // return;\n // }\n async _keySchedule(mode, sharedSecret, params) {\n // Currently, there is no point in executing this function\n // because this hpke library does not allow users to explicitly specify the mode.\n //\n // this.verifyPskInputs(mode, params);\n const pskId = params.psk === undefined\n ? EMPTY\n : toUint8Array(params.psk.id);\n const pskIdHash = await this._kdf.labeledExtract(EMPTY, LABEL_PSK_ID_HASH, pskId);\n const info = params.info === undefined ? EMPTY : toUint8Array(params.info);\n const infoHash = await this._kdf.labeledExtract(EMPTY, LABEL_INFO_HASH, info);\n const keyScheduleContext = new Uint8Array(1 + pskIdHash.byteLength + infoHash.byteLength);\n keyScheduleContext.set(new Uint8Array([mode]), 0);\n keyScheduleContext.set(new Uint8Array(pskIdHash), 1);\n keyScheduleContext.set(new Uint8Array(infoHash), 1 + pskIdHash.byteLength);\n const psk = params.psk === undefined ? EMPTY : toUint8Array(params.psk.key);\n const ikm = this._kdf.buildLabeledIkm(LABEL_SECRET, psk);\n const exporterSecretInfo = this._kdf.buildLabeledInfo(LABEL_EXP, keyScheduleContext, this._kdf.hashSize);\n const exporterSecret = await this._kdf.extractAndExpand(sharedSecret, ikm, exporterSecretInfo, this._kdf.hashSize);\n if (this._aead.id === AeadId.ExportOnly) {\n return { aead: this._aead, exporterSecret: exporterSecret };\n }\n const keyInfo = this._kdf.buildLabeledInfo(LABEL_KEY, keyScheduleContext, this._aead.keySize);\n const key = await this._kdf.extractAndExpand(sharedSecret, ikm, keyInfo, this._aead.keySize);\n const baseNonceInfo = this._kdf.buildLabeledInfo(LABEL_BASE_NONCE, keyScheduleContext, this._aead.nonceSize);\n const baseNonce = await this._kdf.extractAndExpand(sharedSecret, ikm, baseNonceInfo, this._aead.nonceSize);\n return {\n aead: this._aead,\n exporterSecret: exporterSecret,\n key: key,\n baseNonce: new Uint8Array(baseNonce),\n seq: 0,\n };\n }\n async _keyScheduleS(mode, sharedSecret, enc, params) {\n const res = await this._keySchedule(mode, sharedSecret, params);\n if (res.key === undefined) {\n return new SenderExporterContextImpl(this._api, this._kdf, res.exporterSecret, enc);\n }\n return new SenderContextImpl(this._api, this._kdf, res, enc);\n }\n async _keyScheduleR(mode, sharedSecret, params) {\n const res = await this._keySchedule(mode, sharedSecret, params);\n if (res.key === undefined) {\n return new RecipientExporterContextImpl(this._api, this._kdf, res.exporterSecret);\n }\n return new RecipientContextImpl(this._api, this._kdf, res);\n }\n _validateInputLength(params) {\n if (params.info !== undefined &&\n params.info.byteLength > INFO_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long info\");\n }\n if (params.psk !== undefined) {\n if (params.psk.key.byteLength < MINIMUM_PSK_LENGTH) {\n throw new InvalidParamError(`PSK must have at least ${MINIMUM_PSK_LENGTH} bytes`);\n }\n if (params.psk.key.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long psk.key\");\n }\n if (params.psk.id.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long psk.id\");\n }\n }\n return;\n }\n}\n","import { base64UrlToBytes, DeriveKeyPairError, DeserializeError, EMPTY, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, NativeAlgorithm, NotSupportedError, SerializeError, toArrayBuffer, } from \"@hpke/common\";\nconst ALG_NAME = \"X25519\";\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_X25519 = new Uint8Array([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,\n 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20,\n]);\nconst BASE_POINT_X25519 = /* @__PURE__ */ (() => {\n const p = new Uint8Array(32);\n p[0] = 9;\n return p;\n})();\nexport class X25519 extends NativeAlgorithm {\n constructor(hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._alg = { name: ALG_NAME };\n this._hkdf = hkdf;\n this._nPk = 32;\n this._nSk = 32;\n this._nDh = 32;\n this._pkcs8AlgId = PKCS8_ALG_ID_X25519;\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(ALG_NAME, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const rawIkm = toArrayBuffer(ikm);\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n const rawSk = await this._hkdf.labeledExpand(dkpPrk, LABEL_SK, EMPTY, this._nSk);\n const rawSkBytes = new Uint8Array(rawSk);\n const sk = await this._deserializePkcs8Key(rawSkBytes);\n rawSkBytes.fill(0);\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch {\n try {\n // Firefox fails to export JWK from some imported X25519 private keys.\n const bp = await this._api.importKey(\"raw\", BASE_POINT_X25519.buffer, this._alg, true, []);\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: bp,\n }, key, this._nPk * 8);\n return await this._api.importKey(\"raw\", bits, this._alg, true, []);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n }\n async dh(sk, pk) {\n await this._setup();\n try {\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.kty === \"undefined\" || key.kty !== \"OKP\") {\n throw new Error(`Invalid kty: ${key.crv}`);\n }\n if (typeof key.crv === \"undefined\" || key.crv !== ALG_NAME) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n}\n","import { base64UrlToBytes, DeriveKeyPairError, DeserializeError, EMPTY, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, NativeAlgorithm, NotSupportedError, SerializeError, toArrayBuffer, } from \"@hpke/common\";\nconst ALG_NAME = \"X448\";\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_X448 = new Uint8Array([\n 0x30, 0x46, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,\n 0x03, 0x2b, 0x65, 0x6f, 0x04, 0x3a, 0x04, 0x38,\n]);\nconst BASE_POINT_X448 = /* @__PURE__ */ (() => {\n const p = new Uint8Array(56);\n p[0] = 5;\n return p;\n})();\nexport class X448 extends NativeAlgorithm {\n constructor(hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._alg = { name: ALG_NAME };\n this._hkdf = hkdf;\n this._nPk = 56;\n this._nSk = 56;\n this._nDh = 56;\n this._pkcs8AlgId = PKCS8_ALG_ID_X448;\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(ALG_NAME, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const rawIkm = toArrayBuffer(ikm);\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n const rawSk = await this._hkdf.labeledExpand(dkpPrk, LABEL_SK, EMPTY, this._nSk);\n const rawSkBytes = new Uint8Array(rawSk);\n const sk = await this._deserializePkcs8Key(rawSkBytes);\n rawSkBytes.fill(0);\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch {\n try {\n // Some runtimes cannot export JWK from imported X448 private keys.\n const bp = await this._api.importKey(\"raw\", BASE_POINT_X448.buffer, this._alg, true, []);\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: bp,\n }, key, this._nPk * 8);\n return await this._api.importKey(\"raw\", bits, this._alg, true, []);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n }\n async dh(sk, pk) {\n await this._setup();\n try {\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.kty === \"undefined\" || key.kty !== \"OKP\") {\n throw new Error(`Invalid kty: ${key.crv}`);\n }\n if (typeof key.crv === \"undefined\" || key.crv !== ALG_NAME) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n}\n","import type { HttpClient } from './http.js';\nimport type { ProjectConfig } from './types.js';\n\nconst CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes\n\nexport class ConfigFetcher {\n protected readonly httpClient: HttpClient;\n private cachedConfig: ProjectConfig | null = null;\n private cacheTimestamp = 0;\n\n constructor(httpClient: HttpClient) {\n this.httpClient = httpClient;\n }\n\n async getConfig(): Promise<ProjectConfig | null> {\n const now = Date.now();\n\n if (this.cachedConfig && now - this.cacheTimestamp < CACHE_TTL_MS) {\n return this.cachedConfig;\n }\n\n try {\n const response = await this.httpClient.request<ProjectConfig>('GET', '/v1/config');\n\n if (response.error || !response.data) {\n return null;\n }\n\n this.cachedConfig = response.data;\n this.cacheTimestamp = now;\n\n return this.cachedConfig;\n } catch {\n return null;\n }\n }\n}\n","export class PalbaseError extends Error {\n readonly code: string;\n readonly status: number;\n readonly details?: unknown;\n\n constructor(code: string, message: string, status: number, details?: unknown) {\n super(message);\n this.name = 'PalbaseError';\n this.code = code;\n this.status = status;\n this.details = details;\n }\n}\n","export type Platform = 'browser' | 'node' | 'react-native' | 'deno' | 'bun';\n\ndeclare const Deno: unknown;\n\nexport function detectPlatform(): Platform {\n if (typeof Deno !== 'undefined') {\n return 'deno';\n }\n\n const runtime = globalThis as typeof globalThis & { process?: { versions?: Record<string, string> } };\n if (runtime.process?.versions) {\n if ('bun' in runtime.process.versions) {\n return 'bun';\n }\n if ('node' in runtime.process.versions) {\n return 'node';\n }\n }\n\n if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {\n return 'react-native';\n }\n\n return 'browser';\n}\n\n/**\n * The platform word this SDK puts on the wire (`X-Platform`), which the server\n * reads to target flags and to label telemetry.\n *\n * It is NOT `detectPlatform()`'s value verbatim: that reports the JS host\n * (\"browser\"), while the wire wants the platform. iOS sends \"ios\", not the name\n * of its runtime, and a condition author writes `client.platform == 'web'` —\n * the word every other flag vendor uses too. Server hosts keep their own names,\n * where the distinction is the useful part.\n */\nexport function wirePlatform(): string {\n const host = detectPlatform();\n return host === 'browser' ? 'web' : host;\n}\n","// Proof-of-work: the bot gate in front of /auth/signup and /auth/login.\n//\n// The server answers an unsolved request with 403 and a challenge in the body:\n//\n// { \"error\": \"pow_required\", \"challenge\": { \"id\", \"prefix\", \"difficulty\" } }\n//\n// A client finds any nonce whose SHA-256(prefix + nonce) begins with\n// `difficulty` zero bits, then repeats the request carrying the id and nonce as\n// headers. The work is the point: a person signing up pays it once and does not\n// notice, a script signing up ten thousand times pays it ten thousand times.\n//\n// # Why this lives in core, and not one layer up\n//\n// Until 2026-08-14 nothing shipped could solve it: the gate was written with the\n// server and its own integration harness, and every real client sent requests\n// without the headers and got 403. It was then solved in @palbase/web's own\n// request path — which covers `pb.call` and the module facades and NOT\n// `pb.auth.*`, because those go through @palbase/auth's client and from there\n// into core's HttpClient. So the fix landed everywhere except the two endpoints\n// the gate actually guards, and `npm i @palbase/web` still could not sign a\n// person in. Measured 2026-08-18 against a real stack, on the published 7.3.0.\n//\n// The lesson is where a retry belongs: at the layer that ISSUES the request.\n// Core owns fetch for every client in this repo, so core owns the challenge.\n//\n// WebCrypto rather than a hashing dependency: `crypto.subtle` is present in\n// browsers and in Node 18+, which is the same floor the rest of the SDK sets.\n// Measured at the server's default difficulty of 16: ~330ms, ~65k digests.\n\n/** The challenge a `pow_required` response carries. */\nexport interface PowChallenge {\n id: string;\n prefix: string;\n difficulty: number;\n}\n\n/** Header names the retry must carry. Mirrors the server's constants. */\nexport const POW_CHALLENGE_ID_HEADER = 'X-PoW-Challenge-ID';\nexport const POW_NONCE_HEADER = 'X-PoW-Nonce';\n\n/**\n * Reads a challenge out of an error envelope, or returns null when the envelope\n * is not a `pow_required` one.\n *\n * The whole wire envelope is stored on the error, so the challenge arrives\n * without the HTTP layer having to know about proof-of-work at all.\n */\nexport function asPowChallenge(details: unknown): PowChallenge | null {\n if (typeof details !== 'object' || details === null) return null;\n const env = details as Record<string, unknown>;\n if (env.error !== 'pow_required') return null;\n const c = env.challenge;\n if (typeof c !== 'object' || c === null) return null;\n const { id, prefix, difficulty } = c as Record<string, unknown>;\n if (typeof id !== 'string' || typeof prefix !== 'string') return null;\n if (typeof difficulty !== 'number' || !Number.isInteger(difficulty) || difficulty < 0) return null;\n return { id, prefix, difficulty };\n}\n\nconst encoder = new TextEncoder();\n\n/**\n * One SHA-256, by the fastest route this runtime offers.\n *\n * Awaiting `crypto.subtle.digest` once per nonce is what made this expensive,\n * and the cost is the await rather than the hashing. Measured on one machine,\n * 200k digests of a 40-byte input:\n *\n *\tawaited crypto.subtle.digest 105,597 digests/s\n *\tsync node:crypto createHash 1,324,503 digests/s — 12.5x\n *\n * That is the difference between difficulty 24 taking 159 seconds and taking\n * 13. Node, Bun and Deno all have the sync one; a browser has only WebCrypto,\n * and there it stays async.\n *\n * The specifier is assembled at runtime so a browser bundler does not try to\n * resolve `node:crypto` and fail the build over a branch that never runs there.\n */\ntype Hasher = (input: string) => Uint8Array | Promise<Uint8Array>;\n\nlet hasher: Hasher | null = null;\n\nasync function digester(): Promise<Hasher> {\n if (hasher) return hasher;\n // Read off globalThis with an inline shape rather than by naming `process`,\n // which needs @types/node — a dependency this package does not have and should\n // not grow for one branch. It typechecked locally only because those types\n // were hoisted into node_modules by a sibling package; the publish workflow's\n // clean checkout is what said so, which is exactly what it is for.\n const runtime = globalThis as {\n process?: { versions?: { node?: string; bun?: string } };\n };\n const nodeish =\n runtime.process?.versions?.node !== undefined ||\n runtime.process?.versions?.bun !== undefined;\n if (nodeish) {\n try {\n const mod = (await import(/* @vite-ignore */ `${'node:'}crypto`)) as {\n createHash?: (alg: string) => { update(s: string): { digest(): Uint8Array } };\n };\n if (typeof mod.createHash === 'function') {\n const createHash = mod.createHash;\n hasher = (input: string) => new Uint8Array(createHash('sha256').update(input).digest());\n return hasher;\n }\n } catch {\n // No node:crypto here. WebCrypto below is not a fallback in the apologetic\n // sense — it is the only hash a browser has, and it is correct.\n }\n }\n hasher = async (input: string) =>\n new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode(input)));\n return hasher;\n}\n\n/** Monotonic where it exists, wall-clock where it does not. */\nconst now = (): number =>\n typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now();\n\n/** Counts leading zero bits, stopping at the first byte that has a one. */\nfunction leadingZeroBits(hash: Uint8Array): number {\n let bits = 0;\n for (const byte of hash) {\n if (byte === 0) {\n bits += 8;\n continue;\n }\n // clz32 counts across 32 bits; a byte occupies the low 8, so the first 24\n // are always zero and get subtracted back off.\n return bits + Math.clz32(byte) - 24;\n }\n return bits;\n}\n\n/**\n * The hardest challenge this client will attempt.\n *\n * Not a taste: it is the server's own ceiling. palauth maps a risk score to a\n * difficulty and its worst case is 24 (`DifficultyForRisk`, bot/pow.go:156-166).\n * Anything above that cannot have come from a stack behaving as designed, and\n * the cost of humouring it falls entirely on this side — each step up DOUBLES\n * the work, so difficulty 30 is sixty-four times a legitimate worst case and, on\n * the web, sixty-four times a frozen main thread. Refused immediately, by name.\n */\nexport const MAX_POW_DIFFICULTY = 24;\n\n/**\n * Finds a nonce satisfying the challenge and returns the headers a retry needs.\n *\n * THE BUDGET SCALES WITH THE CHALLENGE, and the first version of this did not.\n * It bounded the search at a flat `1 << 24` — which is not a generous bound for\n * difficulty 24, it is the EXPECTED number of attempts. Finding a nonce is a\n * geometric process: the chance of needing more than 2^d attempts is 1/e, so a\n * flat 2^24 would have failed roughly 37% of legitimate hardest-risk challenges,\n * and failed them for precisely the users the gate exists to slow down — who\n * would have been unable to sign in at all rather than made to wait.\n *\n * Eight times expected puts that at e^-8, about three in ten thousand, while\n * leaving the common case (the server's default 16, and 12 for an unremarkable\n * caller) exactly as cheap as it was.\n *\n * `powBudget` is exported and separate so the RELATIONSHIP can be asserted\n * directly. A test that only watches a cheap challenge succeed cannot tell this\n * budget from the flat one it replaced — measured: reinstating `1 << 24` left\n * such a test green.\n */\nexport function powBudget(difficulty: number): number {\n return 8 * 2 ** difficulty;\n}\n\n/**\n * The longest a solve may be ALLOWED to take, and the difference from a\n * deadline is the whole point.\n *\n * The first version of this was a flat 120s deadline, and it was measured to be\n * worse than the flat iteration budget it was meant to backstop: at ~105k\n * digests/s, difficulty 24 EXPECTS 159 seconds, so a 120s clock killed the\n * majority of legitimate hardest-risk solves — reintroducing, larger, exactly\n * the class of defect that replacing `1 << 24` had removed. Guessing a number\n * for an unknown machine cannot work: the same difficulty is 13 seconds on a\n * runtime with a sync hasher and 159 on one without.\n *\n * So the machine is MEASURED, and the decision moves to the front. A short\n * calibration gives the rate this process actually hashes at; if the whole\n * iteration budget cannot fit in this window at that rate, the solve is refused\n * IMMEDIATELY, naming the numbers. A caller then learns in milliseconds that\n * this difficulty is unpayable here, instead of after two minutes of work\n * thrown away.\n *\n * What remains after that is a guarantee rather than a gamble: a solve that\n * starts can always finish inside its budget, so the only failure left is the\n * budget's own e^-8.\n */\nexport const POW_TIME_BUDGET_MS = 120_000;\n\n/**\n * The window the rate is measured over, and the warm-up it deliberately skips.\n *\n * All of these are REAL attempts — the search starts at nonce 0 and never\n * restarts — so calibration costs nothing but the reading. The first 1024 are\n * excluded from the timing because they include this loop's own JIT warm-up:\n * measured, timing from zero reported 747k digests/s on a machine whose steady\n * rate is 1.32M, and the decision below would have refused a difficulty this\n * machine can pay in half the allowance.\n */\nconst CALIBRATION_WARMUP = 1024;\nconst CALIBRATION_END = 9216;\n\nexport async function solvePowChallenge(\n challenge: PowChallenge,\n maxIterations = powBudget(challenge.difficulty),\n // The caller's AbortSignal, honoured INSIDE the loop rather than only around\n // the fetch it precedes — for the callers that have one. `pb.auth.signIn` does\n // NOT: it reaches the network through @palbase/auth's client, which takes\n // credentials and nothing else. So it is the extra a caller can opt into, and\n // POW_TIME_BUDGET_MS below is what actually bounds the work.\n signal?: AbortSignal,\n): Promise<Record<string, string>> {\n if (challenge.difficulty > MAX_POW_DIFFICULTY) {\n throw new Error(\n `proof-of-work: refusing difficulty ${challenge.difficulty}; this client attempts at most ${MAX_POW_DIFFICULTY}, which is the highest a Palbase stack issues`,\n );\n }\n\n const digest = await digester();\n let warmedAt = 0;\n let calibrated = false;\n // Armed by the calibration below, never before it: until the rate is known\n // there is no honest number to put here.\n let deadline = Number.POSITIVE_INFINITY;\n\n for (let nonce = 0; nonce < maxIterations; nonce++) {\n // Checked in batches: reading them is cheap but not free, and a\n // 1024-digest granularity bounds the delay at a few milliseconds.\n if ((nonce & 1023) === 0) {\n if (signal?.aborted) {\n throw new DOMException('proof-of-work solve aborted', 'AbortError');\n }\n if (now() > deadline) {\n throw new Error(\n `proof-of-work: gave up on difficulty ${challenge.difficulty} after ${POW_TIME_BUDGET_MS / 1000}s ` +\n `and ${nonce.toLocaleString()} attempts — the tail this run drew is longer than the allowance`,\n );\n }\n }\n\n // THE DECISION, TAKEN ONCE AND TAKEN EARLY.\n //\n // After CALIBRATION_DIGESTS real attempts the rate of THIS process is\n // known, so the question \"can this machine pay this difficulty\" has an\n // answer instead of an assumption. If the whole budget cannot fit in the\n // time budget, refuse here — milliseconds in, with the numbers — rather\n // than spend two minutes and throw them away. If it fits, everything after\n // this point is guaranteed to finish inside the window, so the only\n // remaining failure is the budget's own e^-8.\n if (nonce === CALIBRATION_WARMUP) {\n warmedAt = now();\n }\n if (!calibrated && nonce === CALIBRATION_END) {\n calibrated = true;\n const elapsed = Math.max(now() - warmedAt, 0.001);\n const rate = (CALIBRATION_END - CALIBRATION_WARMUP) / (elapsed / 1000);\n // EXPECTED, not worst case, and the difference is the whole judgement.\n //\n // Finding a nonce is geometric: 2^difficulty attempts on average, with a\n // long tail the 8x budget covers. Refusing because the TAIL will not fit\n // would turn away work whose expected cost is seventeen seconds — measured\n // exactly that on this machine at difficulty 24. Refusing on the EXPECTED\n // cost turns away only what is genuinely unpayable here, and what it lets\n // through is then cut by the clock with probability e^-(budget/expected):\n // at 120s against a 17s expectation that is one run in a thousand, and at\n // difficulty 20 on a browser it is one in a hundred and fifty thousand.\n const expectedMs = (2 ** challenge.difficulty / rate) * 1000;\n if (expectedMs > POW_TIME_BUDGET_MS) {\n throw new Error(\n `proof-of-work: difficulty ${challenge.difficulty} needs about ${Math.round(expectedMs / 1000)}s here ` +\n `(${Math.round(rate).toLocaleString()} digests/s) and this client allows ${POW_TIME_BUDGET_MS / 1000}s; ` +\n `refusing before spending the time rather than after`,\n );\n }\n deadline = now() + (POW_TIME_BUDGET_MS - (now() - warmedAt));\n }\n\n const hash = await digest(challenge.prefix + nonce);\n if (leadingZeroBits(hash) >= challenge.difficulty) {\n return {\n [POW_CHALLENGE_ID_HEADER]: challenge.id,\n [POW_NONCE_HEADER]: String(nonce),\n };\n }\n }\n throw new Error(\n `proof-of-work: no nonce found for difficulty ${challenge.difficulty} within ${maxIterations} attempts`,\n );\n}\n","import { Chacha20Poly1305 } from '@hpke/chacha20poly1305';\nimport { CipherSuite, HkdfSha256 } from '@hpke/core';\nimport { DhkemX25519HkdfSha256 } from '@hpke/dhkem-x25519';\nimport { PalbaseError } from './errors.js';\nimport { fromBase64, toBase64 } from './sealed-json.js';\nimport type { SealingKey } from './sealed-keys.js';\n\nexport const SEALED_CONTENT_TYPE = 'application/palbase-sealed+json';\nexport const SEALED_HEADER = 'X-Palbase-Sealed';\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder('utf-8', { fatal: true });\nconst responseLabel = 'palbase-sealed/response/v1';\n\nexport function sealingRequired(path: string): boolean {\n // Mirrors v2/internal/server/sealed.go. Tenant/runtime routes cannot unseal.\n return new URL(path, 'https://unused.invalid').pathname.startsWith('/auth/');\n}\n\nexport function requestAAD(\n host: string,\n method: string,\n path: string,\n ict: string,\n ts: number,\n idem: string,\n): Uint8Array<ArrayBuffer> {\n const fields = [host, method, path, ict, idem].map((field) => encoder.encode(field));\n const bytes = new Uint8Array(fields.reduce((size, field) => size + 4 + field.length, 8));\n const view = new DataView(bytes.buffer);\n let offset = 0;\n for (const [index, field] of fields.entries()) {\n if (index === 4) {\n view.setBigUint64(offset, BigInt(ts));\n offset += 8;\n }\n view.setUint32(offset, field.length);\n offset += 4;\n bytes.set(field, offset);\n offset += field.length;\n }\n return bytes;\n}\n\nexport function sealingSuite(): CipherSuite {\n return new CipherSuite({\n kem: new DhkemX25519HkdfSha256(),\n kdf: new HkdfSha256(),\n aead: new Chacha20Poly1305(),\n });\n}\n\nexport async function sealRequest(\n key: SealingKey,\n url: string,\n init: RequestInit,\n): Promise<Uint8Array<ArrayBuffer>> {\n const suite = sealingSuite();\n const sender = await suite.createSenderContext({\n recipientPublicKey: await suite.kem.importKey('raw', key.publicKey.buffer),\n });\n const headers = new Headers(init.headers);\n const ict = headers.get('content-type') ?? 'application/json';\n const ts = Math.floor(Date.now() / 1000);\n const target = new URL(url);\n const method = init.method ?? 'GET';\n // Go binds r.URL.Path (decoded, without the query), not RequestURI.\n const aad = requestAAD(\n target.host,\n method,\n decodeURIComponent(target.pathname),\n ict,\n ts,\n headers.get('idempotency-key') ?? '',\n );\n const ct = await sender.seal(encoder.encode(typeof init.body === 'string' ? init.body : ''), aad);\n const envelope = JSON.stringify({\n v: 2,\n kid: key.kid,\n enc: toBase64(new Uint8Array(sender.enc)),\n ct: toBase64(new Uint8Array(ct)),\n ict,\n ts,\n });\n if (method === 'GET' || method === 'HEAD' || init.body === undefined) {\n headers.set(\n SEALED_HEADER,\n toBase64(encoder.encode(envelope)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''),\n );\n delete init.body;\n } else {\n headers.delete(SEALED_HEADER);\n headers.set('Content-Type', SEALED_CONTENT_TYPE);\n init.body = envelope;\n }\n headers.delete('Content-Length');\n init.headers = Object.fromEntries(headers.entries());\n // Do not redirect a credential-bearing envelope to a different endpoint.\n init.redirect = 'error';\n return new Uint8Array(await sender.export(encoder.encode(responseLabel), 32));\n}\n\nexport async function openSealedResponse(\n response: Response,\n exporter: Uint8Array | undefined,\n method: string,\n): Promise<Response> {\n if (\n response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !==\n SEALED_CONTENT_TYPE\n ) {\n // Edge/middleware errors are plaintext. A successful auth result cannot be.\n if (exporter && response.ok && method !== 'HEAD') {\n throw new PalbaseError(\n 'sealed_response_invalid',\n 'The server returned an unencrypted response.',\n response.status,\n );\n }\n return response;\n }\n // HTTP HEAD has no response body, including when the handler sealed it.\n if (method === 'HEAD') return response;\n try {\n if (!exporter) throw new Error('No sealing context');\n const envelope = (await response.json()) as {\n v: number;\n n: string;\n ct: string;\n ict: string;\n st: number;\n };\n if (\n envelope.v !== 2 ||\n !Number.isInteger(envelope.st) ||\n envelope.st < 200 ||\n envelope.st > 599 ||\n typeof envelope.ict !== 'string'\n ) {\n throw new Error('Invalid response envelope');\n }\n const plaintext = await new Chacha20Poly1305()\n .createEncryptionContext(exporter)\n .open(\n fromBase64(envelope.n),\n fromBase64(envelope.ct),\n encoder.encode(`${responseLabel}\\n${envelope.ict}\\n${envelope.st}`),\n );\n const headers = new Headers(response.headers);\n headers.set('Content-Type', envelope.ict);\n headers.delete('Content-Length');\n headers.delete('Content-Encoding');\n // The outer status is always 200; auth failures and PoW live inside the seal.\n return new Response([204, 205, 304].includes(envelope.st) ? null : decoder.decode(plaintext), {\n status: envelope.st,\n headers,\n });\n } catch {\n throw new PalbaseError(\n 'sealed_response_invalid',\n 'The encrypted server response could not be verified.',\n response.status,\n );\n }\n}\n","// Signatures cover the original JSON bytes, not JSON.stringify(JSON.parse(raw)).\n// Go's encoder preserves struct field order and escapes characters differently.\nexport function rawObjectFields(raw: string): Map<string, string> {\n const parsed: unknown = JSON.parse(raw);\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('Expected a JSON object');\n }\n const fields = new Map<string, string>();\n let i = 0;\n const space = () => {\n while (/\\s/.test(raw[i] ?? '') && i < raw.length) i++;\n };\n const stringEnd = (start: number) => {\n let end = start + 1;\n while (end < raw.length) {\n if (raw[end] === '\\\\') end += 2;\n else if (raw[end++] === '\"') return end;\n }\n throw new Error('Unterminated JSON string');\n };\n space();\n i++; // opening object, already validated by JSON.parse\n while (true) {\n space();\n if (raw[i] === '}') return fields;\n const nameEnd = stringEnd(i);\n const name = JSON.parse(raw.slice(i, nameEnd)) as string;\n i = nameEnd;\n space();\n i++; // colon\n space();\n const start = i;\n if (raw[i] === '\"') i = stringEnd(i);\n else if (raw[i] === '{' || raw[i] === '[') {\n let depth = 0;\n do {\n const c = raw[i];\n if (c === '\"') {\n i = stringEnd(i);\n continue;\n }\n if (c === '{' || c === '[') depth++;\n if (c === '}' || c === ']') depth--;\n i++;\n } while (depth > 0 && i < raw.length);\n } else {\n while (i < raw.length && !/[\\s,}]/.test(raw[i] ?? '')) i++;\n }\n // A first-match slice and JSON.parse's last-match value must never disagree.\n if (fields.has(name)) throw new Error('Duplicate JSON field');\n fields.set(name, raw.slice(start, i));\n space();\n if (raw[i] === ',') i++;\n }\n}\n\nexport function fromBase64(value: string): Uint8Array<ArrayBuffer> {\n return Uint8Array.from(atob(value), (c) => c.charCodeAt(0));\n}\n\nexport function toBase64(bytes: Uint8Array): string {\n // Avoid a spread: envelopes can exceed the engine's argument-count limit.\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n","import { ed25519 } from '@noble/curves/ed25519.js';\nimport { PalbaseError } from './errors.js';\nimport { fromBase64, rawObjectFields } from './sealed-json.js';\nimport { endpointUrl } from './url.js';\nimport type { HttpClientOptions } from './types.js';\n\nexport const SEALED_KEYSET_PATH = '/palbase-sealed-keys.json';\nexport const SEALED_SUITE = 'DHKEM-X25519-HKDF-SHA256/HKDF-SHA256/ChaCha20Poly1305';\n// Fleet PUBLIC key, identical to the iOS SDK pin. Never learned from a response.\nconst FLEET_ROOT = 'mRDTIWzhW0JCk0e2Jvkn679VeZBB38zOOfPTMO6vBpU=';\nconst REFRESH_MS = 5 * 60_000;\nconst FAILURE_COOLDOWN_MS = 60_000;\nconst encoder = new TextEncoder();\n\nexport interface SealingKey {\n kid: string;\n publicKey: Uint8Array<ArrayBuffer>;\n expires: number;\n version: number;\n}\n\nexport function expectedSealedStack(baseUrl: string, apiKey: string): string {\n // Fleet tenant hosts name the stack even when a legacy key says pb_project_.\n // Apex/custom/self-host URLs instead need the key's ref (or an explicit pin).\n const host = new URL(baseUrl).hostname;\n return (\n /^([a-z0-9]{4,24})\\.(?:(?:dev|staging)\\.)?palbase\\.studio$/.exec(host)?.[1] ??\n /^pb_([^_]+)_/.exec(apiKey)?.[1] ??\n ''\n );\n}\n\nfunction record(raw: string | undefined): Record<string, unknown> {\n if (!raw) throw new Error('Missing signed object');\n rawObjectFields(raw); // also refuses duplicate fields\n return JSON.parse(raw) as Record<string, unknown>;\n}\n\nfunction string(value: unknown): string {\n if (typeof value !== 'string' || !value) throw new Error('Missing string');\n return value;\n}\n\nfunction integer(value: unknown): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new Error('Invalid integer');\n }\n return value;\n}\n\nfunction verifySignature(raw: string, signed: Record<string, unknown>, publicKey: Uint8Array) {\n if (\n signed.alg !== 'ed25519' ||\n publicKey.length !== 32 ||\n !ed25519.verify(fromBase64(string(signed.sig)), encoder.encode(raw), publicKey, {\n zip215: false,\n })\n )\n throw new Error('Invalid sealed key signature');\n}\n\n/** Verify fleet → expected stack → keyset, retaining the exact signed bytes. */\nexport function verifySealingKey(\n raw: string,\n expectedRef: string,\n root: string,\n lastVersion: number,\n now: number,\n): SealingKey {\n const fields = rawObjectFields(raw);\n const signed = record(raw);\n const statementRaw = fields.get('binding');\n const statement = record(statementRaw);\n const bindingRaw = rawObjectFields(statementRaw ?? '').get('binding');\n if (!bindingRaw || statement.rootKid !== 'sealed-root-v1') {\n throw new Error('Unknown sealed trust root');\n }\n verifySignature(bindingRaw, statement, fromBase64(root));\n const binding = record(bindingRaw);\n if (\n binding.v !== 1 ||\n !expectedRef ||\n string(binding.stackRef).trim().toLowerCase() !== expectedRef.toLowerCase()\n ) {\n throw new Error('Sealed binding belongs to another stack');\n }\n const bindingExpiry = integer(binding.expires);\n if (bindingExpiry * 1000 <= now) throw new Error('Expired sealed binding');\n const keysetRaw = fields.get('keyset');\n if (!keysetRaw) throw new Error('Missing sealed keyset');\n verifySignature(keysetRaw, signed, fromBase64(string(binding.signingKey)));\n const keyset = record(keysetRaw);\n const version = integer(keyset.version);\n const expires = Math.min(integer(keyset.expires), bindingExpiry);\n if (version < lastVersion) throw new Error('Sealed keyset version went backwards');\n if (expires * 1000 <= now) throw new Error('Expired sealed keyset');\n if (keyset.v !== 1 || !Array.isArray(keyset.keys)) throw new Error('Invalid sealed keyset');\n for (const item of keyset.keys) {\n if (item === null || typeof item !== 'object') continue;\n const entry = item as Record<string, unknown>;\n if (entry.alg !== SEALED_SUITE) continue;\n const publicKey = fromBase64(string(entry.pub));\n if (publicKey.length !== 32) throw new Error('Invalid sealing public key');\n return { kid: string(entry.kid), publicKey, expires, version };\n }\n throw new Error('No supported sealing key');\n}\n\nexport class SealedKeyStore {\n private cached?: SealingKey;\n private pending?: Promise<SealingKey>;\n private fetchedAt = 0;\n private retryAfter = 0;\n private lastVersion = 0;\n private lastError?: PalbaseError;\n private rotationRefreshAt = 0;\n\n constructor(\n private readonly baseUrl: string,\n private readonly apiKey: string,\n private readonly options?: Exclude<HttpClientOptions['sealed'], false>,\n ) {}\n\n async current(signal?: AbortSignal, rotate = false): Promise<SealingKey> {\n signal?.throwIfAborted();\n const now = Date.now();\n const valid = this.cached && this.cached.expires * 1000 > now ? this.cached : undefined;\n if (this.pending) return this.waitFor(this.pending, signal);\n // A forged unknown-kid response cannot turn every request into a key fetch.\n if (rotate && now - this.rotationRefreshAt >= FAILURE_COOLDOWN_MS) {\n this.fetchedAt = 0;\n this.retryAfter = 0;\n this.rotationRefreshAt = now;\n }\n if (valid && now - this.fetchedAt < REFRESH_MS) return valid;\n if (now < this.retryAfter) {\n if (valid) return valid;\n throw this.lastError;\n }\n const pending = this.fetchKey()\n .then((key) => {\n this.cached = key;\n this.lastVersion = key.version;\n this.fetchedAt = Date.now();\n this.retryAfter = 0;\n return key;\n })\n .catch((error: unknown) => {\n this.retryAfter = Date.now() + FAILURE_COOLDOWN_MS;\n this.lastError =\n error instanceof PalbaseError\n ? error\n : new PalbaseError(\n 'sealed_key_unavailable',\n 'The server encryption key could not be verified. Please try again later.',\n 0,\n );\n // A transient refresh failure may reuse a verified, unexpired key only.\n if (this.cached && this.cached.expires * 1000 > Date.now()) return this.cached;\n throw this.lastError;\n })\n .finally(() => {\n this.pending = undefined;\n });\n this.pending = pending;\n return this.waitFor(pending, signal);\n }\n\n private async fetchKey(): Promise<SealingKey> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 15_000);\n try {\n const response = await fetch(endpointUrl(this.baseUrl, SEALED_KEYSET_PATH), {\n headers: this.apiKey ? { apikey: this.apiKey } : {},\n signal: controller.signal,\n cache: 'no-store',\n redirect: 'error',\n });\n if (!response.ok) throw new Error('Sealed keyset unavailable');\n const raw = await response.text();\n if (raw.length > 64 * 1024) throw new Error('Sealed keyset too large');\n const expectedRef = this.options?.stackRef ?? expectedSealedStack(this.baseUrl, this.apiKey);\n return verifySealingKey(\n raw,\n expectedRef,\n this.options?.root ?? FLEET_ROOT,\n this.lastVersion,\n Date.now(),\n );\n } finally {\n clearTimeout(timer);\n }\n }\n\n // One caller's cancellation must not abort a shared key fetch for other calls.\n private waitFor(pending: Promise<SealingKey>, signal?: AbortSignal): Promise<SealingKey> {\n if (!signal) return pending;\n return new Promise((resolve, reject) => {\n const aborted = () => reject(signal.reason);\n signal.addEventListener('abort', aborted, { once: true });\n pending.then(resolve, reject).finally(() => signal.removeEventListener('abort', aborted));\n if (signal.aborted) aborted();\n });\n }\n}\n","/**\n * Join the configured base URL with an SDK path.\n *\n * A BASE URL MAY CARRY A PATH, NOT JUST AN ORIGIN — a self-host published\n * under `https://api.example.com/palbase`, or an app that routes the browser\n * through its own server (`<origin>/pb`, rewritten upstream) because the\n * Environment's edge does not answer its origin with CORS headers.\n *\n * `new URL('/palbase-sealed-keys.json', base)` reads as the careful way to do\n * this and is the one form that DROPS that path: the leading slash makes the\n * path absolute against the base's ORIGIN. The sealed key store used it while\n * every ordinary request concatenated, so one request in the client asked a\n * different server than all the others — measured live 2026-09-11, the keyset\n * fetch landed on the app's own 404 page and every sealed call failed with\n * `sealed_key_unavailable`. The other two SDK surfaces never had the split:\n * iOS appends (`SealedKeyStore.swift`), Android concatenates onto a\n * slash-trimmed base (`SealedKeyStore.kt`) — this is their shape.\n */\nexport function endpointUrl(base: string, path: string): string {\n return `${base.replace(/\\/+$/, '')}${path}`;\n}\n","import { PalbaseError } from './errors.js';\nimport { wirePlatform } from './platform.js';\nimport { asPowChallenge, solvePowChallenge } from './pow.js';\nimport { openSealedResponse, sealingRequired, sealRequest } from './sealed.js';\nimport { SealedKeyStore } from './sealed-keys.js';\nimport type { TokenManager } from './token.js';\nimport { endpointUrl } from './url.js';\nimport type { HttpClientOptions, PalbaseResponse, RequestOptions } from './types.js';\n\n/**\n * Default production host. Dev / staging / local callers override via\n * `options.url`. Apex-style routing is the only supported production path;\n * Kong resolves Environment identity from the API key.\n */\nconst PALBASE_DEFAULT_HOST = 'api.palbase.studio';\n\n/**\n * Parse the Environment ref from a Palbase API key.\n *\n * Canonical shape: `pb_{environment_ref}_c{random}`, where the Environment ref\n * is 4-24 lowercase ASCII alphanumeric characters and random is AT LEAST 20\n * base62 chars.\n *\n * The length is a floor, not an equality. The stack's own minter writes 20\n * (v2/cmd/palsvc/initenv.go) and the cloud control plane writes 32\n * (cloud/platform/server/services/keys.ts), and the door that admits the\n * request refuses to rule on the difference: *\"a shorter or longer secret is\n * not a security property this door can rule on\"*\n * (v2/internal/platform/identitymw.go: parseAPIKey). A client that is stricter\n * than the server does not add safety — it just refuses working keys, which is\n * exactly what this one did to every cloud project until 2026-08-25.\n *\n * Returns the Environment ref on match; `null` otherwise.\n */\nconst API_KEY_RE = /^pb_([a-z0-9]{4,24})_c[A-Za-z0-9]{20,}$/;\n\nfunction parseEnvironmentRef(apiKey: string): string | null {\n return API_KEY_RE.exec(apiKey)?.[1] ?? null;\n}\nconst MAX_RETRIES = 3;\nconst INITIAL_BACKOFF_MS = 200;\n/**\n * Upper bound on a single 429 retry sleep. A server may return a long\n * Retry-After (a locked account can send minutes/hours); honoring it verbatim\n * would HANG the request for that whole window. Cap each retry at 10s — after\n * MAX_RETRIES the 429 envelope surfaces to the caller (fail fast, don't sleep\n * minutes). The clamp never skips a retry; it only bounds how long each waits.\n */\nconst MAX_RETRY_DELAY_MS = 10_000;\n\n/**\n * Carry a 429's retry hint into the error envelope when only the header has it.\n *\n * A REFUSAL FROM THE EDGE CARRIES NOTHING BUT THE HEADER. Envoy and the\n * gateway limiter answer before any Palbase service is reached, so their 429\n * has no `retry_after` and no `data.retryAfter` — and every reader above this\n * layer (`@palbase/web`'s BackendError, the iOS SDK) looks in the BODY. The\n * seconds were on the wire and unreachable to all of them.\n *\n * Lifted under `retry_after`, the platform's own name for it (palauth's\n * rate-limit envelope), never overwriting a hint the service itself sent — a\n * service knows its window, the edge only knows its own.\n */\nfunction withRetryHint(\n body: Record<string, unknown> | undefined,\n response: Response,\n): Record<string, unknown> | undefined {\n if (response.status !== 429) return body;\n const data = body?.data;\n const alreadyStated =\n typeof body?.retry_after === 'number' ||\n (typeof data === 'object' && data !== null && 'retryAfter' in data);\n if (alreadyStated) return body;\n const seconds = Number.parseInt(response.headers.get('Retry-After') ?? '', 10);\n if (Number.isNaN(seconds) || seconds <= 0) return body;\n return { ...body, retry_after: seconds };\n}\n\n/**\n * Request interceptor. Runs before every HTTP request.\n * Can modify headers, body, or reject the request.\n */\nexport type RequestInterceptor = (request: {\n headers: Record<string, string>;\n method: string;\n path: string;\n}) => void | Promise<void>;\n\nexport class HttpClient {\n protected readonly apiKey: string;\n protected readonly options?: HttpClientOptions;\n\n tokenManager: TokenManager | null = null;\n\n /**\n * Admin JWT used for platform admin endpoints (/admin/*).\n * When set, takes precedence over tokenManager access token in the\n * Authorization header.\n */\n adminToken: string | null = null;\n\n private readonly interceptors: RequestInterceptor[] = [];\n private readonly forbiddenListeners = new Set<(body: Record<string, unknown>) => void>();\n private sealedKeys?: SealedKeyStore;\n\n constructor(apiKey: string, options?: HttpClientOptions) {\n this.apiKey = apiKey;\n this.options = options;\n }\n\n /** Set (or clear) the admin JWT used on admin endpoints. */\n setAdminToken(token: string | null): void {\n this.adminToken = token;\n }\n\n /**\n * Called with the RAW body of every 403 this client receives (FR-010). Core\n * does not know the envelope's fields — the layer that does (palbe) reads\n * `required` out of it. Nothing is retried or swallowed: the error still\n * returns to the caller.\n */\n onForbidden(handler: (body: Record<string, unknown>) => void): () => void {\n this.forbiddenListeners.add(handler);\n return () => {\n this.forbiddenListeners.delete(handler);\n };\n }\n\n /**\n * Create a scoped HttpClient that adds the given extra headers to every\n * request. The returned client shares the admin token and token manager\n * with the parent at runtime — later changes on the parent propagate to\n * the scope and vice versa.\n *\n * Typical use: adding an Environment-routing header for an admin call.\n */\n withHeaders(extra: Record<string, string>): HttpClient {\n const mergedHeaders = { ...(this.options?.headers ?? {}), ...extra };\n\n const scoped: HttpClient = new HttpClient(this.apiKey, {\n ...this.options,\n headers: mergedHeaders,\n });\n scoped.tokenManager = this.tokenManager;\n // Delegate adminToken reads + writes to the parent so the scope always\n // sees the latest token, and setAdminToken on the scope affects the parent.\n // The scope shares the parent's 403 listeners: a refusal is a refusal\n // whichever header set the request carried.\n Object.defineProperty(scoped, 'forbiddenListeners', {\n get: () => this.forbiddenListeners,\n });\n Object.defineProperty(scoped, 'adminToken', {\n get: () => this.adminToken,\n set: (v: string | null) => {\n this.adminToken = v;\n },\n configurable: true,\n });\n Object.defineProperty(scoped, 'sealedKeys', {\n get: () => this.sealedKeys,\n set: (v: SealedKeyStore | undefined) => {\n this.sealedKeys = v;\n },\n });\n return scoped;\n }\n\n /** Add a request interceptor. Runs before every request. */\n addInterceptor(interceptor: RequestInterceptor): void {\n this.interceptors.push(interceptor);\n }\n\n async request<T>(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<PalbaseResponse<T>> {\n // If token is expired and refresh is available, refresh before making the request\n if (\n !options?.skipSessionRefresh &&\n this.tokenManager?.isExpired() &&\n this.tokenManager.getRefreshToken() &&\n this.tokenManager.refreshFunction\n ) {\n try {\n await this.tokenManager.refreshSession();\n } catch (e) {\n const status = e instanceof PalbaseError ? e.status : 0;\n if (status === 400 || status === 401 || status === 403) {\n // Terminal: the refresh token is dead (revoked/expired/forbidden).\n // Clear the session (listeners persist the sign-out) and proceed\n // unauthenticated — the endpoint will 401 into the normal error\n // envelope instead of bricking every subsequent call including\n // the recovery sign-in.\n this.tokenManager.clearSession();\n } else {\n throw e; // network/5xx: transient, stay loud\n }\n }\n }\n\n return this.executeWithRetry<T>(method.toUpperCase(), path, options, 0);\n }\n\n /**\n * A response read as it arrives, for `text/event-stream` routes.\n *\n * Deliberately NOT `executeWithRetry`: a retry replays the request, and a\n * stream the caller has already begun reading cannot be replayed — the frames\n * it handed over would arrive a second time. A stream that fails to open fails\n * to the caller, once, with its status.\n *\n * The buffered path's headers, base URL and interceptors are reused verbatim,\n * so a streaming call is authenticated exactly like every other call; only the\n * body handling differs. `Accept` says what the caller wants, and the status\n * is returned beside the body because the CALLER decides what a non-2xx means\n * (an error envelope arrives as an ordinary buffered body).\n */\n async requestStream(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<{ status: number; body: ReadableStream<Uint8Array> | null; contentType: string }> {\n method = method.toUpperCase();\n if (\n !options?.skipSessionRefresh &&\n this.tokenManager?.isExpired() &&\n this.tokenManager.getRefreshToken() &&\n this.tokenManager.refreshFunction\n ) {\n try {\n await this.tokenManager.refreshSession();\n } catch (e) {\n const status = e instanceof PalbaseError ? e.status : 0;\n if (status === 400 || status === 401 || status === 403) {\n this.tokenManager.clearSession();\n } else {\n throw e;\n }\n }\n }\n\n const url = endpointUrl(this.getBaseUrl(), path);\n const headers = { ...this.buildHeaders(options), Accept: 'text/event-stream' };\n for (const interceptor of this.interceptors) {\n await interceptor({ headers, method, path });\n }\n\n const fetchOptions: RequestInit = { method, headers, signal: options?.signal };\n if (options?.body !== undefined) fetchOptions.body = JSON.stringify(options.body);\n const exporter = await this.prepareSealed(url, path, fetchOptions);\n\n const response = await openSealedResponse(await fetch(url, fetchOptions), exporter, method);\n return {\n status: response.status,\n body: response.body,\n contentType: response.headers.get('content-type') ?? '',\n };\n }\n\n private async prepareSealed(\n url: string,\n path: string,\n init: RequestInit,\n ): Promise<Uint8Array<ArrayBuffer> | undefined> {\n if (this.options?.sealed === false || !sealingRequired(path)) return undefined;\n this.sealedKeys ??= new SealedKeyStore(this.getBaseUrl(), this.apiKey, this.options?.sealed);\n const key = await this.sealedKeys.current(init.signal ?? undefined);\n init.signal?.throwIfAborted();\n try {\n return await sealRequest(key, url, init);\n } catch (error) {\n init.signal?.throwIfAborted();\n if (error instanceof PalbaseError) throw error;\n throw new PalbaseError('sealed_request_failed', 'The request could not be encrypted.', 0);\n }\n }\n\n private getBaseUrl(): string {\n // Explicit URL always wins (local dev, staging, test rigs).\n if (this.options?.url) {\n return this.options.url;\n }\n\n // Validate the key shape up front so apex-routed callers still\n // fail loud on a malformed key instead of hitting the gateway\n // with bad credentials.\n if (this.apiKey && parseEnvironmentRef(this.apiKey) === null) {\n throw new PalbaseError(\n 'invalid_api_key',\n 'Invalid API key format. Expected pb_{environment_ref}_c{at least 20 base62 chars}. For dev/staging pass `url: \"https://api.dev.palbase.studio\"` via options.',\n 0,\n );\n }\n\n return `https://${PALBASE_DEFAULT_HOST}`;\n }\n\n private buildHeaders(options?: RequestOptions): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n // Client identity, the web counterpart of the iOS SDK's\n // ClientInfo.augment(). The server reads these to resolve flag targeting\n // conditions and to label telemetry, so an app declares nothing and calls\n // nothing — whatever the SDK can know, it sends.\n 'X-Platform': wirePlatform(),\n };\n // The host app's own version is not knowable on the web (no bundle to read\n // it from), so it is opt-in; when given it fills the same header iOS fills\n // from CFBundleShortVersionString.\n const appVersion = this.options?.appVersion?.trim();\n if (appVersion) {\n headers['X-Palbase-Client-Version'] = appVersion;\n }\n\n // Palbase Environment keys live in the `apikey` header — never in\n // `Authorization` — because Kong's key-auth resolves them on that\n // header and the gateway's pre-function plugin stamps the downstream\n // identity.\n const effectiveKey = this.apiKey;\n if (effectiveKey) {\n headers['apikey'] = effectiveKey;\n }\n\n // User session token, if any. Kong's pre-function plugin strips\n // Authorization on /v1/* routes anyway (PostgREST has no JWT\n // secret and would crash on a Bearer it can't decode), but\n // sending it preserves the contract for /auth/* endpoints that\n // do consume the bearer (e.g. session refresh).\n const token = this.tokenManager?.getAccessToken();\n if (token) {\n headers['Authorization'] = `Bearer ${token}`;\n }\n\n // adminToken (platform admin JWT) takes precedence — used by the\n // @palbase/admin internal flows that hit /admin/* routes; those\n // routes verify the bearer themselves and aren't subject to the\n // /v1/* Authorization-strip rule.\n if (this.adminToken) {\n headers['Authorization'] = `Bearer ${this.adminToken}`;\n }\n\n // Merge global custom headers\n if (this.options?.headers) {\n Object.assign(headers, this.options.headers);\n }\n\n // Merge per-request headers\n if (options?.headers) {\n Object.assign(headers, options.headers);\n }\n\n return headers;\n }\n\n private async executeWithRetry<T>(\n method: string,\n path: string,\n options: RequestOptions | undefined,\n attempt: number,\n // Headers a PREVIOUS attempt earned and this one has to carry. Today that\n // is only the solved proof-of-work pair; it is a parameter rather than a\n // field because it belongs to one request's second try, and a field would\n // leak it onto every later call made through this client.\n earned?: Record<string, string>,\n rotated = false,\n ): Promise<PalbaseResponse<T>> {\n const url = endpointUrl(this.getBaseUrl(), path);\n const headers = { ...this.buildHeaders(options), ...earned };\n\n // Run interceptors\n for (const interceptor of this.interceptors) {\n await interceptor({ headers, method, path });\n }\n\n const fetchOptions: RequestInit = {\n method,\n headers,\n signal: options?.signal,\n };\n\n if (options?.body !== undefined) {\n fetchOptions.body = JSON.stringify(options.body);\n }\n // A fresh HPKE encapsulation on EVERY attempt: reusing an envelope trips\n // the server replay guard, even when the first response was lost.\n const exporter = await this.prepareSealed(url, path, fetchOptions);\n\n let response: Response;\n try {\n response = await fetch(url, fetchOptions);\n } catch (error) {\n options?.signal?.throwIfAborted();\n // Network error — retry with backoff\n if (options?.retry !== false && attempt < MAX_RETRIES - 1) {\n const backoff = INITIAL_BACKOFF_MS * 2 ** attempt;\n await this.delay(backoff);\n // WITHOUT `earned`, and that is the whole point of this line.\n //\n // A network error means the response was lost, not that the request\n // was. If it reached the server, the challenge is already SPENT —\n // palauth's VerifyChallenge reads and deletes in one step\n // (bot/pow.go:96-104), deliberately, because a proof presented twice is\n // not proof. Replaying the nonce would then answer `pow_invalid`, and\n // the one-solve guard below would refuse to try again: a request one\n // fresh solve away from succeeding, failed. Dropping it costs nothing\n // in the other case — if the server never saw the request, a fresh\n // challenge works exactly as well as the old one.\n return this.executeWithRetry<T>(method, path, options, attempt + 1, undefined, rotated);\n }\n\n // All retries exhausted — throw PalbaseError\n throw new PalbaseError(\n 'network_error',\n error instanceof Error ? error.message : 'Network request failed',\n 0,\n );\n }\n response = await openSealedResponse(response, exporter, method);\n\n // Handle 429 Too Many Requests — retry with Retry-After or backoff;\n // if retries exhausted, fall through to normal error response handling below\n if (response.status === 429) {\n if (options?.retry !== false && attempt < MAX_RETRIES - 1) {\n const retryAfter = response.headers.get('Retry-After');\n const parsed = retryAfter ? Number.parseInt(retryAfter, 10) : Number.NaN;\n // Clamp the server-requested wait: a long Retry-After (locked account)\n // must not hang the request — cap each sleep, exhaust MAX_RETRIES, then\n // fall through to surface the 429 envelope below.\n const delayMs = Number.isNaN(parsed)\n ? INITIAL_BACKOFF_MS * 2 ** attempt\n : Math.min(parsed * 1000, MAX_RETRY_DELAY_MS);\n await this.delay(delayMs);\n // WITH `earned`, unlike the network path above: a 429 is a refusal the\n // server issued INSTEAD of doing the work, so the challenge was never\n // consumed. The edge's rate limiter answers before palsvc, and on the\n // auth routes palauth's own limiter runs BEFORE the proof-of-work\n // middleware (auth/internal/server/server.go: rl.LoginByIP, then powMW).\n return this.executeWithRetry<T>(method, path, options, attempt + 1, earned, rotated);\n }\n }\n\n // Parse response body\n let data: T | null = null;\n let errorBody:\n | { error?: string; error_description?: string; status?: number; required?: string }\n | undefined;\n\n // HEAD responses have no body by spec — skip parsing.\n const contentType = response.headers.get('Content-Type');\n if (\n method !== 'HEAD' &&\n ![204, 205, 304].includes(response.status) &&\n contentType?.includes('json')\n ) {\n const body = (await response.json()) as Record<string, unknown>;\n if (response.ok) {\n data = body as T;\n } else {\n errorBody = body as typeof errorBody;\n }\n }\n\n if (\n exporter &&\n !rotated &&\n response.status === 400 &&\n errorBody?.error === 'sealed_unknown_kid'\n ) {\n await this.sealedKeys?.current(options?.signal, true);\n return this.executeWithRetry<T>(method, path, options, attempt, earned, true);\n }\n\n // Proof-of-work: /auth/signup and /auth/token sit behind a bot gate that\n // answers an unsolved request with 403 and the challenge in the body. Solve\n // it and repeat the request carrying the two headers; the caller never\n // learns the gate is there.\n //\n // HERE, in core, because this is the layer that issues the request for every\n // client in the repo — @palbase/auth's sign-in, @palbase/web's facades, the\n // server SDK. The same retry lived one layer up in @palbase/web until\n // 2026-08-18 and covered everything EXCEPT `pb.auth.*`, which reaches the\n // network through this method; so the gate stayed unsatisfiable on exactly\n // the two endpoints it guards.\n //\n // ONE retry, and only when the body really carries a challenge: `earned`\n // being set already means this IS the second try. A 403 that says\n // pow_required without a challenge is a server the client cannot satisfy,\n // and looping on it would turn a broken gate into a hang.\n if (response.status === 403 && !earned) {\n const challenge = asPowChallenge(errorBody);\n if (challenge) {\n return this.executeWithRetry<T>(\n method,\n path,\n options,\n attempt,\n await solvePowChallenge(challenge, undefined, options?.signal),\n rotated,\n );\n }\n }\n\n if (!response.ok) {\n if (response.status === 403 && errorBody !== undefined) {\n const body: Record<string, unknown> = errorBody;\n for (const listener of this.forbiddenListeners) {\n try {\n listener(body);\n } catch {\n // A consumer's handler must not turn a well-formed refusal into a\n // thrown error, nor stop the listeners after it (same rule as\n // internal.ts' configured listeners).\n }\n }\n }\n return {\n data: null,\n error: new PalbaseError(\n errorBody?.error ?? 'unknown_error',\n errorBody?.error_description ?? response.statusText,\n response.status,\n withRetryHint(errorBody, response),\n ),\n status: response.status,\n };\n }\n\n // Parse PostgREST Content-Range for count queries (e.g. \"0-9/42\" or \"*/42\").\n const contentRange = response.headers.get('Content-Range');\n let count: number | undefined;\n if (contentRange) {\n const slash = contentRange.lastIndexOf('/');\n if (slash >= 0) {\n const totalPart = contentRange.slice(slash + 1);\n if (totalPart !== '*') {\n const parsed = Number.parseInt(totalPart, 10);\n if (!Number.isNaN(parsed)) {\n count = parsed;\n }\n }\n }\n }\n\n // Header names are case-insensitive and `Headers.get` already honours that;\n // the wire spells this one lowercase.\n const etag = response.headers.get('etag');\n\n return {\n data,\n error: null,\n status: response.status,\n ...(count !== undefined ? { count } : {}),\n ...(etag ? { etag } : {}),\n };\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","import type { AuthStateCallback, Session, Unsubscribe } from './types.js';\n\nexport class TokenManager {\n private session: Session | null = null;\n private listeners: Set<AuthStateCallback> = new Set();\n private refreshPromise: Promise<void> | null = null;\n private refreshing = false;\n\n refreshFunction: ((refreshToken: string) => Promise<Session>) | null = null;\n\n setSession(session: Session): void {\n this.session = session;\n this.notify('SESSION_SET', session);\n }\n\n getAccessToken(): string | null {\n return this.session?.accessToken ?? null;\n }\n\n getRefreshToken(): string | null {\n return this.session?.refreshToken ?? null;\n }\n\n clearSession(): void {\n this.session = null;\n this.notify('SESSION_CLEARED', null);\n }\n\n isExpired(): boolean {\n if (!this.session) return true;\n return Date.now() >= this.session.expiresAt;\n }\n\n async refreshSession(): Promise<void> {\n if (!this.session?.refreshToken || !this.refreshFunction) {\n return;\n }\n\n // Collapse concurrent refresh calls into a single request\n if (this.refreshPromise) {\n return this.refreshPromise;\n }\n\n // Re-entrancy guard: the wired refreshFunction issues its own HTTP request\n // (POST /auth/token/refresh) through HttpClient, whose pre-flight calls\n // refreshSession() again SYNCHRONOUSLY — before `refreshPromise` below is\n // assigned (the whole chain runs before the first real await). Without\n // this flag that recursion is unbounded (stack overflow). Returning early\n // lets the refresh request itself proceed unauthenticated — it carries\n // the refresh token in its body, not the Bearer header.\n if (this.refreshing) {\n return;\n }\n\n this.refreshing = true;\n this.refreshPromise = this.executeRefresh(this.session.refreshToken);\n\n try {\n await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n this.refreshing = false;\n }\n }\n\n onAuthStateChange(callback: AuthStateCallback): Unsubscribe {\n this.listeners.add(callback);\n return () => {\n this.listeners.delete(callback);\n };\n }\n\n private async executeRefresh(refreshToken: string): Promise<void> {\n if (!this.refreshFunction) return;\n const startedSession = this.session;\n try {\n const newSession = await this.refreshFunction(refreshToken);\n // Sign-out, a new sign-in, or another session adoption takes precedence\n // over a refresh that started against an older session.\n if (this.session === startedSession) this.setSession(newSession);\n } catch (error) {\n // The caller would clear its session on a terminal refresh error. An\n // error from an older session must not clear a newer one.\n if (this.session === startedSession) throw error;\n }\n }\n\n private notify(event: 'SESSION_SET' | 'SESSION_CLEARED', session: Session | null): void {\n for (const listener of this.listeners) {\n listener(event, session);\n }\n }\n}\n","/** The client a tenant's tests use to call their own backend.\n *\n * These tests run against a REAL deployment — the release the deploy just built,\n * serving from the same Environment as production, with the same database, the\n * same secrets and the same gateway in front of it. So this client is a plain\n * HTTP client, not a simulation: every call crosses the gateway, the API key\n * check, the auth rail, the zod validation at the boundary, and row-level\n * security, exactly as a shipped app's call does.\n *\n * There is deliberately no schema knowledge here. The tenant already wrote their\n * types — `import type { TodoSchema } from \"../models/todos/shared.js\"` — so a\n * test types its own call (`api.get<TodoSchema[]>(\"/todos\")`) and can validate it\n * with the same zod schema the endpoint declares. A second generated client would\n * be a second thing to keep in step.\n */\n\nimport { asPowChallenge, solvePowChallenge } from \"@palbase/core\";\n\n/** How to reach the release under test. Supplied by the deploy, never guessed. */\nexport interface TestApiConfig {\n baseUrl: string;\n apiKey: string;\n /** This deploy's secret. Without it the request is served the LIVE release.\n *\n * OPTIONAL against a stack running on this machine: a local stack serves one\n * version — the directory `palbase start` mounted — so there is no candidate\n * to select. Required everywhere else. */\n candidateToken?: string;\n /** The run's minted logins, keyed by the name declared in config/test-users.ts. */\n identities?: Record<string, TestIdentity>;\n /** The fetch to use. Injected by tests of this client; production passes none. */\n fetch?: typeof fetch;\n}\n\n/** One login the deploy minted for this run.\n *\n * `accessToken` is the session issued when the identity was created, and is what\n * `signInAs` uses. The credentials come along for a test that wants to exercise\n * the login rail itself — but a suite that switches users repeatedly must not be\n * signing in each time: those calls come from one address and trip the login rate\n * limiter, failing tests for a reason that has nothing to do with the code\n * under test.\n */\nexport interface TestIdentity {\n id?: string;\n email: string;\n password: string;\n accessToken?: string;\n}\n\n/** One call the suite made, in the order it was made. */\nexport interface RecordedRequest {\n method: string;\n path: string;\n status: number;\n ms: number;\n}\n\n/** A non-2xx answer, carrying the platform's error envelope.\n *\n * The envelope is the contract every Palbase endpoint answers with, so a test\n * asserts on `status`/`error`/`data` rather than parsing a message. The message\n * exists for the human reading a failed deploy.\n */\nexport class TestApiError extends Error {\n readonly status: number;\n readonly error: string;\n /** Payload of an error your code threw — `new BadRequest({ fields })` arrives here. */\n readonly data: unknown;\n /** The whole envelope, exactly as the server sent it. */\n readonly body: ErrorEnvelope;\n\n constructor(method: string, path: string, status: number, body: unknown) {\n const envelope = (body ?? {}) as ErrorEnvelope;\n const code = envelope.error ?? String(status);\n super(`${method} ${path} → ${status} ${code}${envelope.error_description ? `: ${envelope.error_description}` : \"\"}`);\n this.name = \"TestApiError\";\n this.status = status;\n this.error = code;\n this.data = envelope.data;\n this.body = envelope;\n }\n}\n\n/** A Palbase error response.\n *\n * `data` carries the payload of an error your code threw. Validation refused at\n * the boundary — before your handler runs — answers with `details` instead, one\n * entry per field. The index signature is deliberate: whatever the server sends\n * is readable from a test, so no assertion is ever blocked on this type being\n * exhaustive.\n */\nexport interface ErrorEnvelope {\n error?: string;\n error_description?: string;\n status?: number;\n request_id?: string;\n data?: unknown;\n details?: Array<{ field: string; message: string }>;\n [key: string]: unknown;\n}\n\nexport interface CallOptions {\n headers?: Record<string, string>;\n}\n\nexport interface TestApi {\n get<T = unknown>(path: string, opts?: CallOptions): Promise<T>;\n post<T = unknown>(path: string, body?: unknown, opts?: CallOptions): Promise<T>;\n patch<T = unknown>(path: string, body?: unknown, opts?: CallOptions): Promise<T>;\n put<T = unknown>(path: string, body?: unknown, opts?: CallOptions): Promise<T>;\n delete<T = unknown>(path: string, opts?: CallOptions): Promise<T>;\n /** HTTP QUERY (RFC 10008): a safe, idempotent read whose filter travels in the body. */\n query<T = unknown>(path: string, body?: unknown, opts?: CallOptions): Promise<T>;\n /** Sign in with credentials you supply. */\n signIn(credentials: { email: string; password: string }): Promise<{ id: string; email?: string }>;\n /**\n * Sign in as one of the identities this run was given, by the name you\n * declared it under in `config/test-users.ts`.\n *\n * Each is minted by the platform for the length of ONE deploy, seeded with the\n * data that declaration describes, and retired after — which is why this works\n * on every Environment including production, where a committed fixture password\n * is refused on purpose.\n */\n signInAs(name: string): Promise<{ id: string; email?: string }>;\n signOut(): Promise<void>;\n /** Drop the bearer without calling the server — the anonymous caller. */\n asAnonymous(): void;\n /** Every call made, in order. Printed for the failing test in a red deploy. */\n readonly requests: readonly RecordedRequest[];\n}\n\nfunction required(value: string, envName: string): string {\n if (!value) {\n throw new Error(\n `${envName} is not set — the test client has nowhere to send requests. ` +\n `This is set by the deploy that runs your tests; if you are running them by hand, set it yourself.`,\n );\n }\n return value;\n}\n\n/** A stack running on this machine. There is exactly ONE version there — the\n * directory `palbase start` mounted — so there is no candidate to select, and\n * demanding a token for one made local runs invent a value to satisfy a header\n * nothing reads. */\nfunction isLocalTarget(baseUrl: string): boolean {\n try {\n const { hostname } = new URL(baseUrl);\n return hostname === \"127.0.0.1\" || hostname === \"localhost\" || hostname === \"[::1]\" || hostname === \"::1\";\n } catch {\n return false;\n }\n}\n\n/** Seconds until a JWT's `exp`, or null when the token carries no readable one.\n * Read WITHOUT verifying: this is a diagnosis, never a decision — the server\n * remains the only authority on whether a token is good. */\nfunction secondsUntilExpiry(token: string): number | null {\n const body = token.split(\".\")[1];\n if (!body) return null;\n try {\n const claims = JSON.parse(Buffer.from(body, \"base64url\").toString(\"utf8\")) as { exp?: unknown };\n return typeof claims.exp === \"number\" ? claims.exp - Math.floor(Date.now() / 1000) : null;\n } catch {\n return null;\n }\n}\n\nexport function createTestApi(config: TestApiConfig): TestApi {\n const baseUrl = required(config.baseUrl, \"PALBASE_TEST_BASE_URL\").replace(/\\/$/, \"\");\n const apiKey = required(config.apiKey, \"PALBASE_TEST_API_KEY\");\n const local = isLocalTarget(baseUrl);\n // Local stacks serve one version, so there is nothing to select. Everywhere\n // else the token stays REQUIRED: without it the gateway serves the LIVE\n // release and the suite would grade code that is not under test.\n const candidateToken = local ? (config.candidateToken ?? \"\") : required(config.candidateToken ?? \"\", \"PALBASE_TEST_CANDIDATE\");\n const doFetch = config.fetch ?? fetch;\n\n const requests: RecordedRequest[] = [];\n let bearer: string | null = null;\n\n async function call<T>(method: string, path: string, body: unknown, opts: CallOptions = {}): Promise<T> {\n const headers: Record<string, string> = {\n apikey: apiKey,\n // Selects the release under test. Omit it and the gateway serves the LIVE\n // one, which would make the whole suite grade the wrong code. Absent only\n // against a local stack, which has a single version.\n ...(candidateToken ? { \"x-palbase-candidate\": candidateToken } : {}),\n ...opts.headers,\n };\n if (bearer) headers.authorization = `Bearer ${bearer}`;\n if (body !== undefined) headers[\"content-type\"] = \"application/json\";\n\n const startedAt = Date.now();\n const res = await doFetch(`${baseUrl}${path}`, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n const text = await res.text();\n const parsed: unknown = text ? safeParse(text) : undefined;\n\n requests.push({ method, path, status: res.status, ms: Date.now() - startedAt });\n\n if (!res.ok) {\n // A 401 on a token that has simply RUN OUT is the most likely 401 a suite\n // sees, and the least legible: the mint issues ~30 minutes, so a file of\n // credentials written yesterday answers `401 unauthorized` with nothing to\n // act on. Measured on a customer run: the next step taken was to blame the\n // credentials rather than their age.\n if (res.status === 401 && bearer) {\n const left = secondsUntilExpiry(bearer);\n if (left !== null && left <= 0) {\n throw new TestApiError(method, path, res.status, {\n error: \"access_token_expired\",\n error_description:\n `this run's access token EXPIRED ${Math.abs(left)}s ago — a test identity is minted for the ` +\n `length of ONE deploy, so a saved token does not survive to the next run. Re-mint it ` +\n \"(`palbase test-user create --json`, or let `palbase test` do it) and run again.\",\n });\n }\n }\n throw new TestApiError(method, path, res.status, parsed);\n }\n return parsed as T;\n }\n\n return {\n requests,\n get: (path, opts) => call(\"GET\", path, undefined, opts),\n post: (path, body, opts) => call(\"POST\", path, body, opts),\n patch: (path, body, opts) => call(\"PATCH\", path, body, opts),\n put: (path, body, opts) => call(\"PUT\", path, body, opts),\n delete: (path, opts) => call(\"DELETE\", path, undefined, opts),\n query: (path, body, opts) => call(\"QUERY\", path, body, opts),\n\n async signInAs(name) {\n const identity = (config.identities ?? {})[name];\n if (!identity) {\n const declared = Object.keys(config.identities ?? {});\n throw new Error(\n `no test identity named ${JSON.stringify(name)} — the deploy mints one per user declared in ` +\n `config/test-users.ts` +\n (declared.length\n ? `; this run has: ${declared.join(\", \")}`\n : // Not \"you declared none\": from here the two causes are\n // indistinguishable, and blaming the customer's config for a\n // platform failure sends them to look in the wrong file. The\n // deploy log names which one it was.\n \", and this run has none — either your config declares no users \" +\n \"or the deploy could not mint them; the deploy log says which\"),\n );\n }\n // The session the mint already issued — no network call, so switching\n // users is free and the login rail never sees this run.\n if (identity.accessToken) {\n bearer = identity.accessToken;\n return { id: identity.id ?? \"\", email: identity.email };\n }\n return this.signIn(identity);\n },\n\n async signIn(credentials) {\n // PROOF-OF-WORK IS PART OF LOGGING IN, so a client that cannot solve one\n // cannot log in at all. The web SDK has solved it since bot protection\n // shipped; this harness went straight to `fetch` and therefore answered\n // `403 pow_required` on every password login — which made the whole\n // credentials path DEAD on a stack with the gate on, exactly when a\n // suite falls back to it because its minted token ran out.\n //\n // One retry, and only when the refusal really carries a challenge: a 403\n // saying pow_required without one is a server this client cannot satisfy,\n // and looping would turn a broken gate into a hang. Same rule as\n // @palbase/core's own retry.\n const attempt = async (extra?: Record<string, string>) =>\n call<{ access_token: string; user?: { id: string; email?: string } }>(\n \"POST\",\n \"/auth/login\",\n credentials,\n extra ? { headers: extra } : {},\n );\n\n let result: { access_token: string; user?: { id: string; email?: string } };\n try {\n result = await attempt();\n } catch (e) {\n const refusal = e as { status?: number; body?: unknown };\n const challenge = refusal.status === 403 ? asPowChallenge(refusal.body) : null;\n if (!challenge) throw e;\n result = await attempt(await solvePowChallenge(challenge));\n }\n bearer = result.access_token;\n return result.user ?? { id: \"\" };\n },\n async signOut() {\n await call(\"POST\", \"/auth/logout\", undefined);\n bearer = null;\n },\n asAnonymous() {\n bearer = null;\n },\n };\n}\n\n/** The run's identities, as the deploy passed them. Absent is not an error: a\n * project that declares none still runs every test that needs no login. */\nfunction parseIdentities(raw: string | undefined): Record<string, TestIdentity> {\n if (!raw) return {};\n try {\n return JSON.parse(raw) as Record<string, TestIdentity>;\n } catch {\n return {};\n }\n}\n\nfunction safeParse(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/** The client the deploy configured, from the environment it set.\n *\n * Constructed lazily so importing this module outside a test run — a typecheck,\n * an editor — does not fail on absent configuration.\n */\nlet configured: TestApi | null = null;\n\nexport const api: TestApi = new Proxy({} as TestApi, {\n get(_target, prop) {\n configured ??= createTestApi({\n baseUrl: process.env.PALBASE_TEST_BASE_URL ?? \"\",\n apiKey: process.env.PALBASE_TEST_API_KEY ?? \"\",\n candidateToken: process.env.PALBASE_TEST_CANDIDATE ?? \"\",\n identities: parseIdentities(process.env.PALBASE_TEST_IDENTITIES),\n });\n return Reflect.get(configured, prop, configured);\n },\n});\n","import \"reflect-metadata\";\n\nimport type { Token } from \"../container.js\";\n\nexport interface IsolatedContainer {\n /** Substitutes a token. Chainable; the last write for a token wins. */\n with<T>(t: Token<T>, v: T): IsolatedContainer;\n get<T>(t: Token<T>): T;\n}\n\n/**\n * How a test replaces a dependency.\n *\n * Rebuilds the graph with the overrides in place and never touches the process\n * singleton cache, so the next test in the same process does not meet a doubled\n * instance left behind by this one. Substitution is DEEP: `Report` asks for\n * `Money` and gets whatever the graph was rebuilt with, however many hops down.\n *\n * Substitution is by `with` alone — there is no separate platform map, because\n * platform services are ambient rather than injected (FR-005).\n *\n * Module boundaries are NOT enforced here, deliberately. They are a build-time\n * rule about the shipped application; making a unit test fail on them would\n * force every test to restate a module layout it is not testing. What a test\n * gets is a graph, not a second opinion about the architecture.\n */\nexport function isolated(): IsolatedContainer {\n const over = new Map<Token, unknown>();\n const local = new Map<Token, unknown>();\n\n const make = (c: Token): unknown => {\n if (over.has(c)) return over.get(c);\n const hit = local.get(c);\n if (hit !== undefined) return hit;\n const meta = (Reflect.getMetadata(\"design:paramtypes\", c) as unknown[] | undefined) ?? [];\n const inst = new (c as unknown as new (...a: unknown[]) => unknown)(\n ...meta.map((d) => make(d as Token)),\n );\n local.set(c, inst);\n return inst;\n };\n\n const api: IsolatedContainer = {\n with<T>(t: Token<T>, v: T): IsolatedContainer {\n over.set(t as Token, v);\n return api;\n },\n get<T>(t: Token<T>): T {\n return make(t as Token) as T;\n },\n };\n return api;\n}\n","import type { DBClient, DBOps } from \"../../endpoint.js\";\nimport { validateInsertManyOptions, type InsertManyOptions } from \"../../db/bulk.js\";\n// The SAME refusals the engine applies. Without these the fake accepted every\n// call the driver path had just started rejecting, and the scaffold points\n// authors at this fake to test their services — so the test went green and\n// production threw. Measured against the published 24.1.0.\nimport { assertUsableFilter, assertUsableWriteValues, assertNoExpressionHandles, isColRef, isSqlFragment, isNowExpr, isColumnExpr } from \"../../db/input-guards.js\";\n\n/**\n * `sqlFragment` sahte veritabanında ÇALIŞTIRILAMAZ — ve sessizce yok sayılamaz.\n *\n * Fake'in bir SQL değerlendiricisi yok. Fragment'i görmezden gelmek, filtreyi\n * hiç uygulamamak demektir: test TÜM satırları görür, üretim ise süzülmüş\n * satırları. Yazarın testi o gün yeşil, üretim yanlış olur — bu dosyanın var\n * olma sebebi tam olarak o sınıf hata. O yüzden adıyla reddediliyor, ve hata\n * çalışan bir alternatif söylüyor (P6).\n */\nfunction refuseFragment(caller: string, table: string, where: unknown): void {\n if (isSqlFragment(where)) {\n throw new Error(\n `${caller}(${table}): fakeDatabase bir sqlFragment'i değerlendiremez — sahte depo SQL çalıştırmaz. ` +\n `Filtreyi tipli filtre diliyle kurun (gt/gte/lt/lte/neq/in/contains/isNull, OR/AND/NOT), ` +\n `ya da bu testi gerçek bir Postgres'e karşı yazın.`,\n );\n }\n // İÇ İÇE de reddedilir. Yalnız ÜST DÜZEYE bakmak, { OR: [ sqlFragment tag, … ] }\n // filtresini fake'te SESSİZCE boş sonuca çeviriyordu; motor onu derliyor\n // (W2-B/C5, ölçüldü). Reddin de bileşim dallarını dolaşması gerekiyor.\n if (where === null || typeof where !== \"object\") return;\n for (const [k, v] of Object.entries(where as Record<string, unknown>)) {\n if (k === \"OR\" || k === \"AND\") {\n for (const branch of (Array.isArray(v) ? v : [])) refuseFragment(caller, table, branch);\n } else if (k === \"NOT\") {\n refuseFragment(caller, table, v);\n }\n }\n}\n\n/**\n * Sayaç aritmetiği — motorun döndürdüğü ALANDA.\n *\n * Postgres `numeric` kolonu STRING döndürür ve toplamayı tam yapar. Fake\n * `Number()` ile hesaplıyordu; ölçülen sonuçlar: `\"0.10\" + \"0.20\"` →\n * `0.30000000000000004`, `\"12345678901234567890\" + 1` →\n * `12345678901234567000`, ve satırın tipi string'den number'a KAYIYORDU.\n * D-007'nin (string miktar) var olma sebebi tam olarak bu kayıptı; fake onu\n * geri getiriyordu (inceleme I-4/I-3).\n *\n * `null` + n = `null`: Postgres'te de öyle, satır değişmez.\n */\nfunction addDecimal(cell: unknown, by: number | string, sign: 1 | -1): unknown {\n if (cell === null || cell === undefined) return null;\n if (typeof cell === \"number\" && typeof by === \"number\") return cell + sign * by;\n const a = String(cell);\n const b = String(by);\n const parse = (x: string): { unit: bigint; scale: number } | null => {\n const m = /^([+-]?)(\\d*)(?:\\.(\\d*))?$/.exec(x.trim());\n if (m === null || (m[2] === \"\" && (m[3] ?? \"\") === \"\")) return null;\n const frac = m[3] ?? \"\";\n const unit = BigInt(`${m[1] === \"-\" ? \"-\" : \"\"}${m[2] === \"\" ? \"0\" : m[2]}${frac}`);\n return { unit, scale: frac.length };\n };\n const pa = parse(a);\n const pb = parse(b);\n if (pa === null || pb === null) {\n // Motor bu durumda Postgres'e sorar ve `operator does not exist:\n // text + integer` alır. Sessizce NaN yazmak yerine ADIYLA reddediyoruz.\n throw new Error(\n `fakeDatabase: increment()/decrement() sayısal olmayan bir değere uygulandı (\"${a}\") — ` +\n `Postgres bunu \"operator does not exist\" ile reddeder.`,\n );\n }\n const scale = Math.max(pa.scale, pb.scale);\n const lift = (v: { unit: bigint; scale: number }): bigint =>\n v.unit * 10n ** BigInt(scale - v.scale);\n const total = lift(pa) + BigInt(sign) * lift(pb);\n if (scale === 0) return typeof cell === \"number\" ? Number(total) : total.toString();\n const neg = total < 0n;\n const digits = (neg ? -total : total).toString().padStart(scale + 1, \"0\");\n const out = `${neg ? \"-\" : \"\"}${digits.slice(0, -scale)}.${digits.slice(-scale)}`;\n return typeof cell === \"number\" ? Number(out) : out;\n}\nimport { columnExprOf } from \"../../db/tx-plan.js\";\nimport type {\n TxPlanBody,\n TxPlanOpResult,\n TxPlanRejection,\n TxPlanResponse,\n TxWireGuard,\n TxWireOp,\n TxWireValue,\n} from \"../../db/tx-plan.js\";\n\n/** Tracked records for assertions. */\ninterface TrackedRecords {\n inserted: Map<string, Record<string, unknown>[]>;\n updated: Map<string, Record<string, unknown>[]>;\n deleted: Map<string, string[]>;\n}\n\n/** Mock DB client with tracking and seed data support. */\n/**\n * TEK EŞLEŞTİRİCİ — `findMany`, `updateMany`, `deleteMany` ve `count` bunu\n * kullanır.\n *\n * Motorda tek bir `compileWhereBare` var; fake'te DÖRT ayrı eşleştirici vardı\n * ve üçü yalnız katı eşitliğe bakıyordu. Ölçülen sonuç (inceleme C3/C6/I2):\n * `updateMany({ id, balance: { gte: \"5.00\" } }, …)` fake'te HİÇBİR satır\n * eşleştirmiyordu, yani FR-014'ün doc'unun ÖĞRETTİĞİ \"yetersiz bakiye\" deseni\n * fake'e karşı HER ZAMAN başarısız dala düşüyor — yazar başarı yolunu hiç test\n * edemiyor, üretimde para gerçekten çekiliyor.\n */\nfunction rowMatchesFilter(\n caller: string,\n table: string,\n row: Record<string, unknown>,\n f: Record<string, unknown>,\n): boolean {\n return Object.entries(f).every(([k, c]) => {\n if (k === \"OR\") return (c as Record<string, unknown>[]).some((b) => rowMatchesFilter(caller, table, row, b));\n if (k === \"AND\") return (c as Record<string, unknown>[]).every((b) => rowMatchesFilter(caller, table, row, b));\n if (k === \"NOT\") return !rowMatchesFilter(caller, table, row, c as Record<string, unknown>);\n // `has` ilişki GRAFİĞİ ister ve sahte deponun grafiği YOK — tablolar bir\n // Map'te, aralarındaki yabancı anahtarlar hiçbir yerde. Sessizce yok saymak\n // filtreyi hiç uygulamamak olurdu: test TÜM satırları görür, üretim\n // süzülmüş satırları. Bu dosyanın var olma sebebi tam olarak o sınıf.\n if (k === \"has\") {\n throw new Error(\n `${caller}(${table}): fakeDatabase bir \\`has\\` filtresini çözemez — ilişki grafiği ` +\n `bildirimden türetiliyor ve sahte deponun bildirimi yok. Bu testi gerçek bir Postgres'e ` +\n `karşı yazın, ya da ilişkiyi filtrede AÇIKÇA kurun (önce ilişki tablosunu okuyup ` +\n `{ id: { in: [...] } } ile süzün).`,\n );\n }\n return matchesCell(caller, table, row, k, c);\n });\n}\n\n/**\n * SQL'in üç değerli mantığı: NULL taşıyan karşılaştırma UNKNOWN'dır, yani satır\n * EŞLEŞMEZ. Fake `===` kullanıyordu ve iki NULL kolonu EŞİT sayıyordu — motorun\n * her yerde uyguladığı FR-006 doktrininin tersi (inceleme I3, ölçüldü).\n */\nfunction cmp(a: unknown, b: unknown, op: string): boolean {\n if (a === null || a === undefined || b === null || b === undefined) return false;\n const l = a instanceof Date ? a.getTime() : a;\n const r = b instanceof Date ? b.getTime() : b;\n switch (op) {\n case \"eq\": return l === r;\n case \"neq\": return l !== r;\n case \"gt\": return (l as number) > (r as number);\n case \"gte\": return (l as number) >= (r as number);\n case \"lt\": return (l as number) < (r as number);\n case \"lte\": return (l as number) <= (r as number);\n default: return false;\n }\n}\n\nfunction matchesCell(\n caller: string,\n table: string,\n row: Record<string, unknown>,\n key: string,\n cond: unknown,\n): boolean {\n // Kolon-kolon karşılaştırma (FR-011) — motorla PARİTE. Fake `col()`'u\n // tanımasaydı `{ $col: \"x\" }` nesnesini DEĞER sanıp eşitlik kurar, hiçbir\n // satır dönmez ve yazarın testi sessizce boş sonuca geçerdi.\n if (isColRef(cond)) return cmp(row[key], row[cond.$col], \"eq\");\n // `now()` — motorla PARİTE. Tutamak bir Proxy, yani `Object.entries` BOŞ\n // döner ve `.every()` boş listede TRUE'dur: ayırt edilmezse koşul HER SATIRLA\n // eşleşirdi. Yani \"süresi geçmemişler\" filtresi testte süresi geçenleri de\n // döndürür, test yeşil kalır ve üretimde davranış AYRIŞIRDI.\n if (isNowExpr(cond)) return cmp(row[key], new Date().toISOString(), \"eq\");\n if (cond !== null && typeof cond === \"object\" && !Array.isArray(cond)) {\n return Object.entries(cond as Record<string, unknown>).every(([op, v]) => {\n const cell = row[key];\n if (isNowExpr(v)) {\n if (![\"neq\", \"gt\", \"gte\", \"lt\", \"lte\"].includes(op)) {\n throw new Error(`${caller}(${table}): where.${key}.${op} now() ile kullanılamaz`);\n }\n return cmp(cell, new Date().toISOString(), op);\n }\n if (isColumnExpr(v)) {\n throw new Error(\n `${caller}(${table}): where.${key}.${op} bir YAZMA ifadesi aldı (increment/decrement) — ` +\n `karşılaştırma değeri değil. Sunucu saati için now() kullanın.`,\n );\n }\n if (isColRef(v)) {\n if (![\"neq\", \"gt\", \"gte\", \"lt\", \"lte\"].includes(op)) {\n throw new Error(`${caller}(${table}): where.${key}.${op} col() ile kullanılamaz`);\n }\n return cmp(cell, row[v.$col], op);\n }\n switch (op) {\n case \"in\":\n if (!Array.isArray(v)) throw new Error(`${caller}(${table}): where.${key}.in bir dizi olmalı`);\n if (v.some(isColRef)) {\n throw new Error(\n `${caller}(${table}): where.${key}.in col() ile kullanılamaz — kolon karşılaştırması için gt/gte/lt/lte/neq kullanın`,\n );\n }\n return v.includes(cell);\n case \"neq\": case \"gt\": case \"gte\": case \"lt\": case \"lte\":\n return cmp(cell, v, op);\n // K1 metin operatörleri (FR-005) ve null testi (FR-006). Bunlar BURADA\n // da olmak zorunda: guard onları KABUL ettiği anda fake sessizce yanlış\n // cevap verir ve yazarın testi, üretimde farklı davranan koda karşı\n // yeşil verirdi (input-guards.ts'in uyardığı tam sınıf).\n case \"isNull\":\n if (typeof v !== \"boolean\") throw new Error(`${caller}(${table}): where.${key}.isNull bir boolean olmalı`);\n return v ? cell == null : cell != null;\n case \"contains\": case \"icontains\": case \"startsWith\": case \"endsWith\": {\n if (typeof v !== \"string\") throw new Error(`${caller}(${table}): where.${key}.${op} bir string olmalı`);\n if (typeof cell !== \"string\") return false;\n if (op === \"contains\") return cell.includes(v);\n if (op === \"icontains\") return cell.toLowerCase().includes(v.toLowerCase());\n if (op === \"startsWith\") return cell.startsWith(v);\n return cell.endsWith(v);\n }\n default:\n throw new Error(`${caller}(${table}): where.${key} bilinmeyen operatör \"${op}\"`);\n }\n });\n }\n return row[key] === cond;\n}\n\nexport interface MockDBClient extends DBClient {\n /** Get records inserted into a table. */\n inserted(table: string): Record<string, unknown>[];\n /** Get records updated in a table. */\n updated(table: string): Record<string, unknown>[];\n /** Get IDs deleted from a table. */\n deleted(table: string): string[];\n /** Pre-seed data into a table for findById/findMany. */\n seed(table: string, data: Record<string, unknown>[]): void;\n}\n\n/** Create a mock DB client with in-memory tracking. */\nexport function createMockDB(): MockDBClient {\n const store = new Map<string, Record<string, unknown>[]>();\n const tracked: TrackedRecords = {\n inserted: new Map(),\n updated: new Map(),\n deleted: new Map(),\n };\n\n function rowsOf(table: string): Record<string, unknown>[] {\n let rows = store.get(table);\n if (!rows) {\n rows = [];\n store.set(table, rows);\n }\n return rows;\n }\n\n function track(\n map: Map<string, Record<string, unknown>[]>,\n table: string,\n row: Record<string, unknown>,\n ): void {\n const list = map.get(table);\n if (list) list.push(row);\n else map.set(table, [row]);\n }\n\n/**\n * EKLEME yolunda değerleri motorun yaptığı gibi çöz — `now()` sunucu saati,\n * sayaç ifadesi adıyla ret.\n *\n * Fake bunu bilmeseydi `assertNoExpressionHandles` `now()`'ı reddeder, test\n * kırmızı olur ve yazar ÇALIŞAN bir çağrıyı bozuk sanırdı. Sürüm 28'de motor\n * beş ekleme kurucusunun hepsinde `now()` derliyor.\n */\nfunction resolveInsertValues(\n caller: string,\n table: string,\n data: Record<string, unknown>,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(data)) {\n const expr = columnExprOf(v);\n if (expr !== null && expr.fn === \"now\") {\n out[k] = new Date().toISOString();\n continue;\n }\n if (expr !== null) {\n throw new Error(\n `${caller}(${table}): \"${k}\" ${expr.fn === \"inc\" ? \"increment()\" : \"decrement()\"} aldı — ` +\n `satır HENÜZ YOK, yani \"kolonun şu anki değeri\" diye bir şey yok.`,\n );\n }\n out[k] = v;\n }\n return out;\n}\n\n // Build the op surface first (the six string-keyed ops). `txPlan` below\n // interprets a whole plan against the SAME in-memory store and tracking maps,\n // so a transaction's writes are visible to later assertions exactly as a\n // direct write would be.\n const ops: DBOps = {\n diagnostics: () => null,\n // The bulk ops and count run against the SAME in-memory store the direct\n // ops write to, so a test that writes three rows and counts them gets 3 —\n // a mock that answered 0 would make the surface look broken in exactly the\n // tests meant to prove it works.\n async updateMany(\n table: string,\n where: Record<string, unknown>,\n set: Record<string, unknown>,\n opts?: { returning?: boolean },\n ) {\n if (Object.keys(where).length === 0) throw new Error(`updateMany(${table}): boş filtre`);\n assertUsableFilter(\"updateMany\", table, where);\n refuseFragment(\"updateMany\", table, where);\n assertUsableWriteValues(\"updateMany\", table, Object.keys(set), set);\n const hit = (store.get(table) ?? []).filter((r) =>\n rowMatchesFilter(\"updateMany\", table, r, where),\n );\n // increment()/decrement() (FR-012) — motorla PARİTE. Fake ifadeyi DEĞER\n // sanıp yazsaydı, sayaç kolonu bir proxy nesnesine dönerdi ve yazarın\n // testi \"artış oldu\" diye değil, sessizce bozuk veriyle geçerdi.\n for (const row of hit) {\n for (const [k, v] of Object.entries(set)) {\n const expr = columnExprOf(v);\n if (expr !== null && expr.fn === \"now\") {\n // Motor `SET col = now()` derliyor; fake'in karşılığı bir zaman damgası.\n row[k] = new Date();\n continue;\n }\n if (expr !== null) {\n row[k] = addDecimal(row[k], expr.by as number | string, expr.fn === \"inc\" ? 1 : -1);\n continue;\n }\n row[k] = v;\n }\n }\n // HER YAZMA `updated()`'a DÜŞER. `update` ve tx-plan'ın update op'u zaten\n // kaydediyordu; `updateMany` kaydetmiyordu, yani defter YARI KÖRDÜ:\n // servisini `updateMany` ile yazan bir tüketici\n // `expect(fake.updated(\"accounts\")).toEqual([])` yazar ve yazma GERÇEKTEN\n // olduğu hâlde yeşil alırdı — FR-008'in aynadaki hâli.\n for (const row of hit) track(tracked.updated, table, row);\n\n // `returning: false` SAYI döndürür, dizi değil — motor gibi\n // (engine/db.ts) ve tipli yüzeyin daralttığı gibi (db/typed-db.ts).\n // Sahte daima dizi döndürdüğü sürece\n // const n = await db.updateMany(t, w, s, { returning: false });\n // if (n === 0) throw new Conflict(...)\n // guard'ı testte HİÇ çalışmaz ([] === 0 değil), üretimde çalışır: test\n // yeşil, canlıda 409. `update`→null ile aynı sınıf yalan.\n return opts?.returning === false ? hit.length : hit;\n },\n async deleteMany(table: string, where: Record<string, unknown>) {\n if (Object.keys(where).length === 0) throw new Error(`deleteMany(${table}): boş filtre`);\n assertUsableFilter(\"deleteMany\", table, where);\n refuseFragment(\"deleteMany\", table, where);\n const list = store.get(table) ?? [];\n const keep = list.filter((r) => !rowMatchesFilter(\"deleteMany\", table, r, where));\n store.set(table, keep);\n return list.length - keep.length;\n },\n async count(table: string, where: Record<string, unknown> = {}) {\n assertUsableFilter(\"count\", table, where);\n // `refuseFragment` burada ATLANMIŞTI: fragment'li count fake'te sessizce\n // 0 döndürüyordu, motor gerçek sayıyı (W2-B/C4).\n refuseFragment(\"count\", table, where);\n return (store.get(table) ?? []).filter((r) =>\n rowMatchesFilter(\"count\", table, r, where),\n ).length;\n },\n async search(_table: string, _params?: Record<string, unknown>) {\n return [];\n },\n async facets(_table: string, _params?: Record<string, unknown>) {\n return {};\n },\n async similar() {\n return [];\n },\n async recommend() {\n return [];\n },\n async supersede(_table: string, _id: string, row: Record<string, unknown>) {\n return { id: crypto.randomUUID(), ...row };\n },\n async query(_sql: string, _params?: unknown[]) {\n return [];\n },\n\n async insert(table: string, raw: Record<string, unknown>) {\n const data = resolveInsertValues(\"insert\", table, raw);\n assertUsableWriteValues(\"insert\", table, Object.keys(data), data);\n // Motorla PARİTE: ifade tutamağı bu yolda değer değildir. Fake onu\n // satıra YAZIYORDU; satır artık JSON'a bile çevrilemiyordu.\n assertNoExpressionHandles(\"insert\", table, Object.keys(data), data);\n const record = { id: crypto.randomUUID(), ...data };\n rowsOf(table).push(record);\n track(tracked.inserted, table, record);\n return record;\n },\n\n /**\n * `insertMany` — motorla PARİTE, ANAHTAR KÜMESİ kuralı dahil.\n *\n * Fake bu kuralı bilmeseydi farklı şekilli satırları kabul eder, test yeşil\n * kalır, üretimde motor adıyla reddederdi — yani fake, sürüm atlamayı\n * kolaylaştırmak yerine gizlerdi.\n */\n /**\n * `aggregate` — motorla PARİTE, PARA KESİNLİĞİ dahil.\n *\n * Fake toplamayı JS `number` ile yapsaydı test yeşil kalır ve üretimde\n * `numeric` kesinliği kaybolurdu — yani fake tam da korunması gereken şeyi\n * gizlerdi. `addDecimal` BigInt ölçekli toplama yapıyor, motorun\n * `sum(numeric)::text`'inin karşılığı.\n */\n async aggregate(table: string, q: Parameters<DBOps[\"aggregate\"]>[1]) {\n const rows = (store.get(table) ?? []).filter((r) =>\n q.where === undefined || rowMatchesFilter(\"aggregate\", table, r, q.where),\n );\n const groups = q.groupBy ?? [];\n const shape = (bucket: Record<string, unknown>[]): Record<string, unknown> => {\n const out: Record<string, unknown> = {};\n for (const c of q.sum ?? []) {\n const vals = bucket.map((r) => r[c]).filter((v) => v !== null && v !== undefined);\n ((out[\"sum\"] ??= {}) as Record<string, unknown>)[c] =\n vals.length === 0 ? null : String(vals.reduce<string | number>((a, v) => addDecimal(a, v as string | number, 1) as string, \"0\"));\n }\n for (const c of q.avg ?? []) {\n const vals = bucket.map((r) => r[c]).filter((v) => v !== null && v !== undefined);\n ((out[\"avg\"] ??= {}) as Record<string, unknown>)[c] =\n vals.length === 0\n ? null\n : String(Number(vals.reduce<string | number>((a, v) => addDecimal(a, v as string | number, 1) as string, \"0\")) / vals.length);\n }\n for (const [fn, pick] of [[\"min\", -1], [\"max\", 1]] as const) {\n for (const c of q[fn] ?? []) {\n const vals = bucket.map((r) => r[c]).filter((v) => v !== null && v !== undefined);\n ((out[fn] ??= {}) as Record<string, unknown>)[c] =\n vals.length === 0\n ? null\n : vals.reduce((a, v) => (cmp(v, a, pick === 1 ? \"gt\" : \"lt\") ? v : a));\n }\n }\n if (q.count === true) out[\"count\"] = bucket.length;\n return out;\n };\n if (groups.length === 0) return shape(rows);\n const byKey = new Map<string, Record<string, unknown>[]>();\n for (const r of rows) {\n const k = JSON.stringify(groups.map((c) => r[c]));\n byKey.set(k, [...(byKey.get(k) ?? []), r]);\n }\n return [...byKey.values()].map((bucket) => {\n const out = shape(bucket);\n for (const c of groups) out[c] = bucket[0]![c];\n return out;\n });\n },\n\n insertMany: (async function(table: string, rows: readonly Record<string, unknown>[], opts?: InsertManyOptions) {\n validateInsertManyOptions(opts);\n if (opts?.onConflict?.length) throw new Error(\"fakeDatabase insertMany cannot enforce PostgreSQL unique constraints; use an integration test for onConflict\");\n if (rows.length === 0) return opts?.returning === false ? 0 : [];\n const cols = Object.keys(rows[0]!);\n for (let i = 1; i < rows.length; i++) {\n const missing = cols.filter((c) => !(c in rows[i]!));\n const extra = Object.keys(rows[i]!).filter((k) => !cols.includes(k));\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `insertMany(${table}): ${i}. satırın kolonları ilk satırla aynı değil` +\n (missing.length > 0 ? ` (eksik: ${missing.join(\", \")})` : \"\") +\n (extra.length > 0 ? ` (fazla: ${extra.join(\", \")})` : \"\") +\n `. Eksikler için null yazın, ya da farklı şekilli satırları ayrı çağrılarda ekleyin.`,\n );\n }\n }\n const out: Record<string, unknown>[] = [];\n for (const rawRow of rows) {\n const data = resolveInsertValues(\"insertMany\", table, rawRow);\n assertUsableWriteValues(\"insertMany\", table, cols, data);\n assertNoExpressionHandles(\"insertMany\", table, cols, data);\n const record = { id: crypto.randomUUID(), ...data };\n rowsOf(table).push(record);\n track(tracked.inserted, table, record);\n out.push(record);\n }\n return opts?.returning === false ? out.length : out;\n }) as DBOps[\"insertMany\"],\n\n /**\n * `claim` — motorla PARİTE (FR-033).\n *\n * Fake bunu sunmasaydı `claim` ile yazılmış bir servis, iskelenin yazarlara\n * önerdiği test yolunda `undefined is not a function` verirdi; sunup da\n * FARKLI davransaydı (ör. hep `inserted: true`) idempotency testi üretimde\n * çalışmayan koda karşı yeşil olurdu.\n *\n * Anahtar ZATEN VARSA var olan satır dönüyor ve hiçbir şey yazılmıyor —\n * motorun 23505 dalının aynısı.\n */\n /**\n * `lockRows` — sahte depoda kilit YOKTUR, ama çağrı da patlamamalı.\n *\n * Motorla parite burada \"aynı SQL\" değil, \"aynı SÖZLEŞME\": boş liste\n * no-op, tekrar edenler tekilleşir, ve PK'sı olmayan tablo adıyla\n * reddedilir. Kilidin kendisi tek işlemli bir sahte depoda anlamsız —\n * ama sözleşmeyi bozan bir çağrı burada da hata almalı.\n */\n async lockRows(table: string, ids: readonly string[]) {\n if (ids.length === 0) return;\n const rows = store.get(table) ?? [];\n const unique = [...new Set(ids)].sort();\n const missing = unique.filter((id) => !rows.some((r) => r[\"id\"] === id));\n if (missing.length > 0 && rows.length > 0) {\n // Sessiz geçmek, testin \"kilitledim\" sanmasına yol açardı.\n throw new Error(\n `lockRows(${table}): şu id'ler yok: ${missing.join(\", \")} — kilitlenecek satır bulunamadı.`,\n );\n }\n },\n\n /**\n * `lockRowsWhere` — `lockRows` ile AYNI gerekçe, aynı parite seviyesi.\n *\n * Kilit tek işlemli bir sahte depoda anlamsız, ama motorun REDDETTİĞİ bir\n * çağrı burada da reddedilmeli: boş filtre (bütün tabloyu kilitlemek) ve\n * tanınmayan bir kilit modu. Fake bunları geçirseydi, yazarın testi\n * üretimde patlayan bir çağrıya karşı yeşil olurdu.\n */\n async lockRowsWhere(\n table: string,\n where: Record<string, unknown>,\n opts?: { mode?: \"update\" | \"share\" | \"noKeyUpdate\" },\n ) {\n const mode = opts?.mode ?? \"update\";\n if (mode !== \"update\" && mode !== \"share\" && mode !== \"noKeyUpdate\") {\n throw new Error(\n `lockRowsWhere(${table}): bilinmeyen mode \"${String(mode)}\" — \"update\", \"share\" ya da \"noKeyUpdate\".`,\n );\n }\n if (Object.keys(where).length === 0) throw new Error(`lockRowsWhere(${table}): boş filtre`);\n assertUsableFilter(\"lockRowsWhere\", table, where);\n refuseFragment(\"lockRowsWhere\", table, where);\n // Eşleşen satırlar OKUNUYOR: filtre fake'in kendi eşleştiricisinden\n // geçmezse (ör. tanınmayan operatör) çağıran bunu burada öğrenir.\n (store.get(table) ?? []).filter((r) => rowMatchesFilter(\"lockRowsWhere\", table, r, where));\n },\n\n /** Sahte depoda kilit yok; sözleşme (çağrı patlamaz) korunuyor. */\n async advisoryXactLock(_key: string) {\n return undefined;\n },\n\n async claim(\n table: string,\n unique: Record<string, unknown>,\n extra: Record<string, unknown> = {},\n ) {\n const keyCols = Object.keys(unique);\n if (keyCols.length === 0) {\n throw new Error(\n `claim(${table}): benzersiz alan verilmedi. claim, bir anahtarı sahiplenmektir; ` +\n `anahtar yoksa sahiplenecek bir şey de yok — insert(${table}, …) kullanın.`,\n );\n }\n assertUsableWriteValues(\"claim\", table, keyCols, unique);\n const existing = (store.get(table) ?? []).find((r) =>\n keyCols.every((c) => r[c] === unique[c]),\n );\n if (existing) return { inserted: false, row: existing };\n const data = resolveInsertValues(\"claim\", table, { ...unique, ...extra });\n assertUsableWriteValues(\"claim\", table, Object.keys(data), data);\n assertNoExpressionHandles(\"claim\", table, Object.keys(data), data);\n const record = { id: crypto.randomUUID(), ...data };\n rowsOf(table).push(record);\n track(tracked.inserted, table, record);\n return { inserted: true, row: record };\n },\n\n // Same semantics the engine's SQL has: match on the conflict columns, update\n // everything else, and return the resulting row either way.\n async put(\n table: string,\n rawData: Record<string, unknown>,\n opts: { onConflict: readonly string[] },\n ) {\n if (opts.onConflict.length === 0) {\n throw new Error(`put into ${table}: onConflict en az bir kolon adı ister`);\n }\n const data = resolveInsertValues(\"put\", table, rawData);\n assertUsableWriteValues(\"upsert\", table, Object.keys(data), data);\n // Motorla PARİTE: ifade tutamağı bu yolda değer değildir. Fake onu\n // satıra YAZIYORDU; satır artık JSON'a bile çevrilemiyordu.\n assertNoExpressionHandles(\"upsert\", table, Object.keys(data), data);\n const rows = rowsOf(table);\n const existing = rows.find((r) => opts.onConflict.every((c) => r[c] === data[c]));\n if (existing) {\n for (const [k, v] of Object.entries(data)) {\n if (!opts.onConflict.includes(k)) existing[k] = v;\n }\n return existing;\n }\n const record = { id: crypto.randomUUID(), ...data };\n rows.push(record);\n track(tracked.inserted, table, record);\n return record;\n },\n\n async update(table: string, id: string, data: Record<string, unknown>) {\n assertUsableWriteValues(\"update\", table, Object.keys(data), data);\n const rows = store.get(table) ?? [];\n const idx = rows.findIndex((r) => r[\"id\"] === id);\n // 28'de motor `update(id)` ile `updateMany`'nin SET kurucusunu PAYLAŞIYOR,\n // yani `now()` ve sayaç ifadeleri burada da geçerli. Fake eskisi gibi\n // reddetseydi, ÇALIŞAN bir çağrı testte kırmızı olurdu — fake'in var olma\n // amacının tam tersi.\n const current = idx >= 0 ? rows[idx]! : {};\n const applied: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(data)) {\n const expr = columnExprOf(v);\n if (expr !== null && expr.fn === \"now\") {\n applied[k] = new Date();\n continue;\n }\n if (expr !== null) {\n applied[k] = addDecimal(current[k], expr.by, expr.fn === \"inc\" ? 1 : -1);\n continue;\n }\n applied[k] = v;\n }\n assertNoExpressionHandles(\"update\", table, Object.keys(applied), applied);\n // 0 SATIR → NULL, motorun KENDİSİ gibi (engine/db.ts:\n // `rows[0] ? asTableRow(table, rows[0]) : null`).\n //\n // Eskiden eşleşme yokken `{ id, ...applied }` UYDURULUYOR ve o uydurma\n // satır `updated()`'a da yazılıyordu. İki sonucu vardı: eşleşmeyen bir\n // update'i test eden kod SESSİZCE geçiyor ama üretimde `null` alıp\n // patlıyordu; ve \"0 satır → null\" sözleşmesi bu harness'la hiç\n // doğrulanamıyordu — bir tüketici projesi iddiayı yazamayıp yorum olarak\n // bırakmak zorunda kaldı (FR-007, FR-008).\n if (idx < 0) return null;\n const updated = { ...rows[idx], ...applied };\n rows[idx] = updated;\n track(tracked.updated, table, updated);\n return updated;\n },\n\n async delete(table: string, id: string) {\n const rows = store.get(table) ?? [];\n const idx = rows.findIndex((r) => r[\"id\"] === id);\n // EŞLEŞME YOKSA DEFTERE YAZILMAZ — `update` ile aynı kural (FR-008).\n // Eskiden eşleşmeyen bir `delete` de `deleted()`'a düşüyordu: silme\n // GERÇEKLEŞMEDİĞİ hâlde `expect(fake.deleted(\"x\")).toEqual([\"yok\"])`\n // yeşil oluyordu, yani defter olmayan bir yazmayı rapor ediyordu.\n if (idx < 0) return;\n rows.splice(idx, 1);\n const list = tracked.deleted.get(table);\n if (list) list.push(id);\n else tracked.deleted.set(table, [id]);\n },\n\n async findUnique() {\n throw new Error(\"MockDB.findUnique cannot verify declared PostgreSQL unique constraints; use a PostgreSQL integration test\");\n },\n async findById(table: string, id: string) {\n const rows = store.get(table) ?? [];\n return rows.find((r) => r[\"id\"] === id) ?? null;\n },\n\n // The SAME filter language the engine compiles to SQL: a plain value is\n // equality, an object is an operator set. A fake that understood less would\n // pass a service test that the live database then fails — which is the one\n // thing a stand-in must never do.\n async page() {\n throw new Error(\"fakeDatabase cannot reproduce PostgreSQL cursor ordering, collations or RLS; use a PostgreSQL integration test or inject an explicit page response\");\n },\n async findMany(\n table: string,\n query?: Record<string, unknown>,\n opts?: {\n orderBy?:\n | { column: string; direction?: \"asc\" | \"desc\"; nulls?: \"first\" | \"last\" }\n | { column: string; direction?: \"asc\" | \"desc\"; nulls?: \"first\" | \"last\" }[];\n select?: string[];\n with?: Record<string, unknown>;\n limit?: number;\n offset?: number;\n },\n ) {\n assertUsableFilter(\"findMany\", table, query);\n refuseFragment(\"findMany\", table, query);\n const { limit, offset } = opts ?? {};\n if (limit !== undefined && (!Number.isInteger(limit) || limit < 0)) {\n throw new Error(`findMany: limit bir negatif olmayan tam sayı olmalı (geldi: ${String(limit)})`);\n }\n if (offset !== undefined) {\n if (!Number.isInteger(offset) || offset < 0) {\n throw new Error(`findMany: offset bir negatif olmayan tam sayı olmalı (geldi: ${String(offset)})`);\n }\n if (limit === undefined) {\n throw new Error(\n \"findMany: offset yalnız limit ile birlikte verilir — limitsiz offset bir sayfa değil, sınırsız bir kuyruğun kaydırılmışıdır\",\n );\n }\n }\n // `with` — fake'in ilişki grafiği YOK, ve olsaydı ikinci bir yorumcu\n // olurdu (motorunki `buildRelations`'tan geliyor). Sessizce YOK SAYMAK\n // en kötüsü olurdu: yazar `rows[0].orders` yazar, `undefined` gelir ve\n // test motorun döndürdüğünden BAŞKA bir şeyi doğrular.\n if (opts?.with !== undefined && Object.keys(opts.with).length > 0) {\n throw new Error(\n `findMany(${table}): fakeDatabase \\`with\\` desteklemiyor — ilişki grafiği ` +\n `yabancı anahtarlardan TÜRETİLİYOR ve fake şemayı okumuyor. İlişkili ` +\n `satırları ölçen bir test gerçek motoru kullanmalı; fake ile ölçmek ` +\n `istiyorsanız ilgili satırları \\`seed\\` ile ayrı koyup ayrı sorgulayın.`,\n );\n }\n const rows = store.get(table) ?? [];\n let out = query\n ? rows.filter((row) => rowMatchesFilter(\"findMany\", table, row, query))\n : [...rows];\n // Çoklu sıralama ve NULL yeri — motorla PARİTE (FR-008). Tek obje de\n // kabul edilir; liste hâline getirilip aynı yoldan geçer.\n const orderSpecs = opts?.orderBy === undefined\n ? []\n : Array.isArray(opts.orderBy) ? opts.orderBy : [opts.orderBy];\n if (orderSpecs.length > 0) {\n out = [...out].sort((a, b) => {\n for (const o of orderSpecs) {\n const dir = o.direction === \"desc\" ? -1 : 1;\n const x = a[o.column];\n const y = b[o.column];\n const xNull = x === null || x === undefined;\n const yNull = y === null || y === undefined;\n if (xNull || yNull) {\n if (xNull && yNull) continue;\n // Verilmezse Postgres varsayılanı: ASC'de NULLS LAST, DESC'te FIRST.\n const nullsFirst = o.nulls === undefined ? dir === -1 : o.nulls === \"first\";\n return (xNull ? 1 : -1) * (nullsFirst ? -1 : 1);\n }\n if (x === y) continue;\n return ((x as never) < (y as never) ? -1 : 1) * dir;\n }\n return 0;\n });\n }\n const start = offset ?? 0;\n const page = limit === undefined ? out : out.slice(start, start + limit);\n // Projeksiyon (FR-009) — motorla PARİTE. Fake tam satır döndürürse, `select`\n // ile yazılmış bir kod sahte veritabanında seçilmemiş kolonu okur ve GEÇER;\n // gerçek motorda o kolon SQL'e hiç girmediği için `undefined` olur.\n const cols = opts?.select;\n if (cols === undefined || cols.length === 0) return page;\n return page.map((row) => Object.fromEntries(cols.map((c) => [c, row[c]])));\n },\n };\n\n /**\n * Interpret a whole plan, atomically.\n *\n * The rollback is the point. A test that asserts \"the second write failed, so\n * the first one is not there\" must be able to FAIL — a mock that applied ops\n * and left them applied would pass that test while the real broker rolled the\n * transaction back, or the other way round. So the store and the tracking maps\n * are snapshotted, and any failure restores both before rejecting.\n *\n * The rejection carries the same envelope fields the runtime copies off the\n * broker's response (`error_code`, `slot`), because the SDK maps `slot` back\n * to the caller's own Error — a mock that rejected with a bare Error would\n * make every guard in every tenant test look like a generic failure.\n */\n async function txPlan(plan: TxPlanBody): Promise<TxPlanResponse> {\n const snapshot = new Map<string, Record<string, unknown>[]>();\n for (const [table, rows] of store) snapshot.set(table, [...rows]);\n const trackedSnapshot: TrackedRecords = {\n inserted: cloneTracked(tracked.inserted),\n updated: cloneTracked(tracked.updated),\n deleted: new Map([...tracked.deleted].map(([k, v]) => [k, [...v]])),\n };\n\n const results: TxPlanOpResult[] = [];\n try {\n for (const op of plan.ops) {\n const result = applyOp(op, results);\n results.push(result);\n const failure = guardFailure(op.guard, result.rows.length);\n if (failure) throw failure;\n }\n } catch (err) {\n store.clear();\n for (const [table, rows] of snapshot) store.set(table, rows);\n tracked.inserted = trackedSnapshot.inserted;\n tracked.updated = trackedSnapshot.updated;\n tracked.deleted = trackedSnapshot.deleted;\n throw err;\n }\n return { results };\n }\n\n function applyOp(op: TxWireOp, results: TxPlanOpResult[]): TxPlanOpResult {\n switch (op.op) {\n case \"upsert\": {\n const values = resolveMap(op.values ?? {}, results, null);\n const conflict = op.onConflict ?? [];\n const rows = rowsOf(op.table);\n const hit = rows.find((r) => conflict.every((c) => r[c] === values[c]));\n if (hit) {\n for (const [key, value] of Object.entries(values)) {\n if (!conflict.includes(key)) hit[key] = value;\n }\n return { rows: [hit], rows_affected: 1 };\n }\n const created = { id: crypto.randomUUID(), ...values };\n rows.push(created);\n track(tracked.inserted, op.table, created);\n return { rows: [created], rows_affected: 1 };\n }\n case \"insert\": {\n const record = { id: crypto.randomUUID(), ...resolveMap(op.values ?? {}, results, null) };\n rowsOf(op.table).push(record);\n track(tracked.inserted, op.table, record);\n return { rows: [record], rows_affected: 1 };\n }\n case \"insertMany\": {\n const written = (op.rows ?? []).map((row) => {\n const record = { id: crypto.randomUUID(), ...resolveMap(row, results, null) };\n rowsOf(op.table).push(record);\n track(tracked.inserted, op.table, record);\n return record;\n });\n return { rows: written, rows_affected: written.length };\n }\n case \"update\": {\n const rows = rowsOf(op.table);\n const where = resolveMap(op.where ?? {}, results, null);\n const written: Record<string, unknown>[] = [];\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n if (!row || !matches(row, where)) continue;\n const next = { ...row, ...resolveMap(op.set ?? {}, results, row) };\n rows[i] = next;\n track(tracked.updated, op.table, next);\n written.push(next);\n }\n return { rows: written, rows_affected: written.length };\n }\n case \"delete\": {\n const rows = rowsOf(op.table);\n const where = resolveMap(op.where ?? {}, results, null);\n const removed = rows.filter((row) => matches(row, where));\n for (const row of removed) {\n rows.splice(rows.indexOf(row), 1);\n const id = row[\"id\"];\n const list = tracked.deleted.get(op.table);\n const key = typeof id === \"string\" ? id : String(id);\n if (list) list.push(key);\n else tracked.deleted.set(op.table, [key]);\n }\n return { rows: removed, rows_affected: removed.length };\n }\n case \"select\": {\n const where = resolveMap(op.where ?? {}, results, null);\n let found = rowsOf(op.table).filter((row) => matches(row, where));\n if (op.limit !== undefined) found = found.slice(0, op.limit);\n return { rows: found, rows_affected: found.length };\n }\n }\n }\n\n const client: MockDBClient = {\n ...ops,\n async command(plan, options) {\n if (options?.mode === \"compiled\") throw new Error(\"fakeDatabase does not run the PostgreSQL command executor; verify compiled mode against PostgreSQL\");\n return client.txPlan(plan);\n },\n\n async atomic() {\n throw new Error(\"fakeDatabase cannot verify physical transaction isolation, COMMIT or retry; test $atomic against PostgreSQL or inject a transaction test double explicitly\");\n },\n\n // No real savepoint in memory: the fake runs the callback against the SAME\n // store. An assertion about rollback here would be asserting the fake.\n attempt: <T,>(fn: (tx: DBOps) => Promise<T>): Promise<T> => fn(ops),\n\n txPlan,\n\n // In tests there is no real DB role; `asService()` returns the same\n // in-memory client so RLS-bypass code paths still hit the same store and\n // tracking maps. The omitted `asService` matches the contract (no\n // double-bypass), so callers can't recurse.\n asService(): Omit<DBClient, \"asService\"> {\n return client;\n },\n\n inserted(table: string) {\n return tracked.inserted.get(table) ?? [];\n },\n\n updated(table: string) {\n return tracked.updated.get(table) ?? [];\n },\n\n deleted(table: string) {\n return tracked.deleted.get(table) ?? [];\n },\n\n seed(table: string, data: Record<string, unknown>[]) {\n store.set(table, [...data]);\n },\n };\n\n return client;\n}\n\nfunction cloneTracked(\n map: Map<string, Record<string, unknown>[]>,\n): Map<string, Record<string, unknown>[]> {\n return new Map([...map].map(([k, v]) => [k, [...v]]));\n}\n\n/** Resolve one plan value: a `$ref` into an earlier result, a `$expr`, or a\n * literal. `current` is the row being updated, which is what `inc`/`dec` read. */\nfunction resolveValue(\n value: TxWireValue,\n results: TxPlanOpResult[],\n current: Record<string, unknown> | null,\n column: string,\n): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n const tagged = value as { $ref?: { op: number; field: string }; $expr?: Record<string, unknown> };\n\n if (tagged.$ref) {\n const row = results[tagged.$ref.op]?.rows[0];\n if (!row) {\n throw txRejection(409, \"tx_ref_unresolved\", {\n message: `operation ${tagged.$ref.op} produced no row to reference`,\n });\n }\n return row[tagged.$ref.field];\n }\n\n if (tagged.$expr) {\n const fn = tagged.$expr[\"fn\"];\n if (fn === \"now\") return new Date().toISOString();\n const by = Number(tagged.$expr[\"by\"]);\n const base = Number(current?.[column] ?? 0);\n return fn === \"dec\" ? base - by : base + by;\n }\n\n return value;\n}\n\nfunction resolveMap(\n map: Record<string, TxWireValue>,\n results: TxPlanOpResult[],\n current: Record<string, unknown> | null,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(map)) {\n out[key] = resolveValue(value, results, current, key);\n }\n return out;\n}\n\n/** Equality filter, with `null` meaning IS NULL — the broker's rule, so a\n * `{ accepted_at: null }` guard behaves the same in a test as in production. */\nfunction matches(row: Record<string, unknown>, where: Record<string, unknown>): boolean {\n return Object.entries(where).every(([key, value]) =>\n value === null ? row[key] === null || row[key] === undefined : row[key] === value,\n );\n}\n\nfunction guardFailure(guard: TxWireGuard | undefined, count: number): unknown {\n if (!guard) return null;\n const ok =\n guard.kind === \"one\"\n ? count === 1\n : guard.kind === \"none\"\n ? count === 0\n : guard.kind === \"atLeast\"\n ? count >= guard.n\n : count <= guard.n;\n if (ok) return null;\n return txRejection(409, \"tx_guard_failed\", {\n slot: guard.slot,\n message: `expected ${guard.kind} ${guard.n} row(s), got ${count}`,\n });\n}\n\n/** Build a rejection shaped like the one the runtime throws for a broker error:\n * an Error carrying the envelope's `status`/`error_code`/`slot`. */\nfunction txRejection(\n status: number,\n code: string,\n extra: { slot?: number; message: string },\n): Error & TxPlanRejection {\n const err = new Error(extra.message) as Error & TxPlanRejection;\n err.status = status;\n err.error_code = code;\n if (extra.slot !== undefined) err.slot = extra.slot;\n return err;\n}\n","/**\n * `fakeDatabase()` — the in-memory `Database` a SERVICE-LAYER test runs against.\n *\n * WHY IT IS PUBLIC. The scaffold's own AGENTS.md tells authors to \"test the\n * service layer… the test passes a stand-in\", and the SDK shipped no stand-in to\n * pass. So every project wrote its own: a measured customer run carried two — a\n * hand-written `MembershipDb` interface for one service, and a bare `{ query }`\n * object in the tests of another. Both are guesses at this SDK's own surface,\n * and both stop compiling the moment the surface grows.\n *\n * The engine already had exactly this object; it just lived under `__tests__/`\n * where only this package could reach it.\n *\n * WHAT IT IS NOT. It does not interpret SQL. `query()` records what it was asked\n * and answers no rows, because a fake that parsed SQL would be a second, worse\n * Postgres — and a test that passed against it would prove nothing about the\n * real one. Assert on `queries` when the SQL is the thing under test, and put\n * anything that depends on what SQL RETURNS in a live test (`palbase test`).\n */\nimport { createMockDB } from \"../__tests__/helpers/mock-db.js\";\nimport type { DBClient } from \"../endpoint.js\";\nimport { makeTypedSurface } from \"../runtime.js\";\nimport type { EnvServiceDatabase } from \"../db/typed-db.js\";\n\n/** One `Database.$query(...)` call, as the service made it. */\nexport interface RecordedQuery {\n sql: string;\n params: unknown[];\n}\n\n/** What a service-layer test is handed. */\nexport interface FakeDatabase {\n /** Pass this where the service expects `Database`.\n *\n * Built with the SAME constructor the production `Database` uses\n * (`makeTypedSurface`), so the fake's surface cannot drift from the real one\n * — including the `$`-prefixed raw ops and the typed `public` schema surface. */\n db: EnvServiceDatabase;\n /**\n * The RAW `DBClient` behind {@link FakeDatabase.db} (FR-028).\n *\n * `RuntimeServices.Database` is the raw client — the ambient `Database`\n * singleton is what WRAPS it with `makeTypedSurface`. So a test that installs\n * the fake as the ambient runtime passes THIS:\n *\n * withServices({ Database: fake.raw }, () => …)\n *\n * Passing `db` there would wrap an already-wrapped surface and every `$op`\n * would miss (measured). Two fields because there are two call sites: `db`\n * goes straight to a service, `raw` goes into the runtime.\n */\n raw: DBClient;\n /** Every `query()` call, in order. */\n queries: readonly RecordedQuery[];\n /** Put rows in a table before the code under test runs. */\n seed(table: string, rows: Record<string, unknown>[]): void;\n /** Rows inserted into a table, for asserting a write happened. */\n inserted(table: string): Record<string, unknown>[];\n /** Rows updated in a table. */\n updated(table: string): Record<string, unknown>[];\n /** Ids deleted from a table. */\n deleted(table: string): string[];\n}\n\nexport function fakeDatabase(): FakeDatabase {\n const mock = createMockDB();\n const queries: RecordedQuery[] = [];\n\n // The recorder wraps `query` and leaves every other op alone, so the fake's\n // behaviour is the engine's mock plus one observation.\n const db: DBClient = Object.assign(Object.create(Object.getPrototypeOf(mock) as object) as DBClient, mock, {\n query: async (sql: string, params: unknown[] = []) => {\n queries.push({ sql, params });\n return mock.query(sql, params);\n },\n });\n\n return {\n db: makeTypedSurface(db),\n raw: db,\n queries,\n seed: (table, rows) => mock.seed(table, rows),\n inserted: (table) => mock.inserted(table),\n updated: (table) => mock.updated(table),\n deleted: (table) => mock.deleted(table),\n };\n}\n","/**\n * `withServices()` — run code with only the platform services a test supplies.\n *\n * WHY IT IS PUBLIC. `isolated()` substitutes CONSTRUCTOR dependencies, and its\n * own documentation says why it cannot help here: \"platform services are\n * ambient rather than injected\". So the repository layer — the one place that\n * really does `import { Database } from \"@palbase/backend\"` — had no supported\n * way to be unit-tested, while `__runWithRuntime` demands EVERY service. A\n * measured consumer project wrote this helper by hand, exploding proxies\n * included, and 30.0.0 then added a tenth required service (`Auth`) which broke\n * that hand-written copy. Shipping it here is what stops that from recurring.\n *\n * WHAT IS ABSENT IS LOUD. An unsupplied service is neither `undefined` nor a\n * silent no-op: touching it throws and NAMES itself, so a test that quietly\n * grew a dependency on `Cache` fails saying \"Cache\", not \"cannot read\n * properties of undefined\".\n *\n * SCOPE IS THE REQUEST ALS, never the process-global slot. Two tests in one\n * file must not be able to see each other's services, and a helper that wrote\n * the global slot would leak the first test's fake into the second.\n *\n * EKSİKSİZLİK DERLEYİCİYE SORULUR, BİR LİSTEYE DEĞİL. İlk yazımı servis\n * adlarını bir diziye koyup `satisfies readonly (keyof RuntimeServices)[]` ile\n * pinliyordu — ama `satisfies` yalnız \"her ELEMAN bir anahtar mı\" diye bakar,\n * \"her ANAHTAR listede mi\" diye BAKMAZ. Ölçüldü: `RuntimeServices`'a on birinci\n * bir servis eklenip liste dokunulmadan bırakıldığında `tsc --strict` TEMİZ\n * derliyor, ve eksik servise erişen tüketici `TypeError: Reflect.get called on\n * non-object` alıyor — ne servisin adı, ne çaresi. Yani bu dosyanın var olma\n * sebebi olan kusurun ta kendisi, bu dosya tarafından üretiliyordu.\n *\n * Şimdi `filled` düz bir `RuntimeServices` nesne literali: bir alan eksik\n * kalırsa TypeScript `TS2741: Property '<ad>' is missing` diyor ve derleme\n * durur. `as unknown as` yok.\n */\nimport { __runWithRuntime, __requestALS, type RuntimeServices } from \"../runtime.js\";\n\n/**\n * A stand-in that refuses every read by NAME.\n *\n * The Proxy target is irrelevant (all access goes through `get`); the single\n * narrowing names the surface the caller expects — the same one-point cast\n * `makeServiceProxy` already uses for exactly this shape.\n */\nfunction absent<K extends keyof RuntimeServices>(name: K): RuntimeServices[K] {\n return new Proxy({} as RuntimeServices[K], {\n get(_target, prop) {\n throw new Error(\n `${String(name)}.${String(prop)} was read, but this test did not provide ${String(name)}. ` +\n `Pass it: withServices({ ${String(name)}: … }, () => …)`,\n );\n },\n });\n}\n\n/** The supplied service, or one that names itself when touched. */\nfunction pick<K extends keyof RuntimeServices>(\n services: Partial<RuntimeServices>,\n key: K,\n): RuntimeServices[K] {\n return services[key] ?? absent(key);\n}\n\nexport function withServices<T>(services: Partial<RuntimeServices>, fn: () => T): T {\n // Nesne LİTERALİ, üretilmiş bir kayıt değil: eksik bir alan burada derleme\n // hatasıdır (ölçüldü: TS2741), bir çalışma zamanı sürprizi değil.\n const filled: RuntimeServices = {\n Database: pick(services, \"Database\"),\n Auth: pick(services, \"Auth\"),\n Secrets: pick(services, \"Secrets\"),\n Documents: pick(services, \"Documents\"),\n Storage: pick(services, \"Storage\"),\n Cache: pick(services, \"Cache\"),\n Log: pick(services, \"Log\"),\n Notifications: pick(services, \"Notifications\"),\n Flags: pick(services, \"Flags\"),\n Realtime: pick(services, \"Realtime\"),\n };\n // `userId`'yi MOTORUN yazdığı gibi yaz. Motor `runWithRuntime`'ın hemen\n // ardından kutuya `userId ?? null` koyuyor ve `RequestStore`'un sözleşmesi\n // \"anonim istekte null\" diyor. Yalnız `{ runtime }` yazmak `undefined`\n // bırakırdı; `undefined` ile `null`'ı ayıran her dal testte bir yol,\n // üretimde başka bir yol koşardı — testin yeşilliği üretim hakkında yalan\n // söylerdi.\n return __requestALS.run({ runtime: filled, userId: null }, fn);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,IAAMA,aAAa,CAAC;AACb,IAAMC,gBAAgBC,iBAAiBC,YAAYH,UAAAA;AAC1D,SAASE,iBAAiBE,SAASC,QAAM;AACrC,SAAO,IAAIC,MAAMF,SAAS;IACtBG,IAAIC,SAASC,MAAMC,WAAS;AACxB,UAAID,QAAQJ,QAAQ;AAChB,eAAOA,OAAOI,IAAAA;MAClB,OACK;AACD,eAAOL,QAAQK,IAAAA;MACnB;IACJ;IACAE,IAAIH,SAASC,MAAMG,OAAK;AACpB,UAAIH,QAAQJ,QAAQ;AAChB,eAAOA,OAAOI,IAAAA;MAClB;AACAL,cAAQK,IAAAA,IAAQG;AAChB,aAAO;IACX;IACAC,eAAeL,SAASC,MAAI;AACxB,UAAIK,UAAU;AACd,UAAIL,QAAQJ,QAAQ;AAChB,eAAOA,OAAOI,IAAAA;AACdK,kBAAU;MACd;AACA,UAAIL,QAAQL,SAAS;AACjB,eAAOA,QAAQK,IAAAA;A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;EAAK,GAAGf,EAAAA;AAC7D;AAtBgBD;","names":["dntGlobals","dntGlobalThis","createMergeProxy","globalThis","baseObj","extObj","Proxy","get","_target","prop","_receiver","set","value","deleteProperty","success","ownKeys","baseKeys","Reflect","extKeys","extKeysSet","Set","filter","k","has","defineProperty","desc","getOwnPropertyDescriptor","N_0","EC_P_521_PARAMS","p","b","gx","gy","coordinateSize","isBytes","a","Uint8Array","ArrayBuffer","isView","name","anumber","n","title","Number","isSafeInteger","prefix","Error","abytes","value","length","bytes","len","needsLen","undefined","ofLen","got","aexists","instance","checkFinished","destroyed","finished","aoutput","out","min","outputLen","u32","arr","Uint32Array","buffer","byteOffset","Math","floor","byteLength","clean","arrays","i","length","fill","_endianTestBuffer","_endianTestBytes","Uint8Array","isLE","createView","arr","DataView","buffer","byteOffset","byteLength","numberToBigint","num","anumber","n","out","N_0","bit","Math","floor","copyBytes","bytes","Uint8Array","from","ahash","h","create","Error","anumber","outputLen","blockLen","_HMAC","hash","key","Object","defineProperty","enumerable","configurable","writable","value","ahash","abytes","undefined","iHash","create","update","Error","blockLen","outputLen","pad","Uint8Array","set","length","digest","i","oHash","clean","buf","aexists","digestInto","out","finished","destroy","_cloneInto","to","getPrototypeOf","destroyed","clone","hmac","message","U32_MASK64","_32n","fromBig","n","le","h","Number","l","split","lst","len","length","Ah","Uint32Array","Al","i","_0n","_1n","_2n","_7n","_256n","_0x71n","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","round","R","x","y","push","t","j","BigInt","IOTAS","split","SHA3_IOTA_H","SHA3_IOTA_L","abool","b","Error","wrapCipher","params","constructor","wrappedCipher","key","args","abytes","undefined","isLE","Error","nonceLength","nonce","varSizeNonce","tagl","tagLength","cipher","checkOutput","fnLength","output","called","wrCipher","encrypt","data","length","decrypt","Object","assign","checkOpts","defaults","opts","merged","equalBytes","a","b","diff","i","getOutput","expectedLength","out","onlyAligned","Uint8Array","isAligned32","u64Lengths","dataLength","aadLength","abool","num","view","createView","setBigUint64","numberToBigint","bytes","byteOffset","_utf8ToBytes","str","Uint8Array","from","split","map","c","charCodeAt","sigma16","sigma32","sigma16_32","u32","sigma32_32","rotl","a","b","isAligned32","byteOffset","BLOCK_LEN","BLOCK_LEN32","MAX_COUNTER","U32_EMPTY","Uint32Array","of","runCipher","core","sigma","key","nonce","data","output","counter","rounds","len","length","block","b32","isAligned","d32","o32","pos","Error","take","Math","min","pos32","j","posj","createCipher","opts","allowShortKeys","extendNonceFn","counterLength","counterRight","checkOpts","anumber","abool","abytes","undefined","toClean","l","k","push","copyBytes","set","k32","subarray","nonceNcLen","nc","n32","clean","u8to16","a","i","Poly1305","key","Object","defineProperty","enumerable","configurable","writable","value","Uint8Array","Uint16Array","copyBytes","abytes","t0","t1","t2","t3","t4","t5","t6","t7","r","pad","process","data","offset","isLast","hibit","h","r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","h0","h1","h2","h3","h4","h5","h6","h7","h8","h9","c","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","finalize","g","mask","f","clean","update","aexists","buffer","blockLen","len","length","pos","take","Math","min","set","subarray","destroy","digestInto","out","aoutput","finished","opos","digest","outputLen","res","slice","wrapConstructorWithKey","hashCons","hashC","msg","tmp","create","poly1305","chachaCore","s","k","n","out","cnt","rounds","y00","y01","y02","y03","y04","y05","y06","y07","y08","y09","y10","y11","y12","y13","y14","y15","x00","x01","x02","x03","x04","x05","x06","x07","x08","x09","x10","x11","x12","x13","x14","x15","r","rotl","oi","chacha20","createCipher","counterRight","counterLength","allowShortKeys","ZEROS16","Uint8Array","updatePadded","h","msg","update","leftover","length","subarray","ZEROS32","computeTag","fn","key","nonce","ciphertext","AAD","undefined","abytes","authKey","lengths","u64Lengths","poly1305","create","res","digest","clean","_poly1305_aead","xorStream","tagLength","encrypt","plaintext","output","plength","getOutput","set","oPlain","tag","decrypt","data","passedTag","equalBytes","Error","chacha20poly1305","wrapCipher","blockSize","nonceLength","LABEL_SEC","Uint8Array","_Mutex_locked","_Mutex_locked","WeakMap","_RecipientContextImpl_mutex","_RecipientContextImpl_mutex","WeakMap","_SenderContextImpl_mutex","_SenderContextImpl_mutex","WeakMap","LABEL_BASE_NONCE","Uint8Array","LABEL_EXP","LABEL_INFO_HASH","LABEL_KEY","LABEL_PSK_ID_HASH","LABEL_SECRET","SUITE_ID_HEADER_HPKE","PKCS8_ALG_ID_X25519","Uint8Array","PKCS8_ALG_ID_X448","Uint8Array","mod","encoder","encoder","TestApiError","Error","status","error","data","body","method","path","envelope","code","String","error_description","name","required","value","envName","isLocalTarget","baseUrl","hostname","URL","secondsUntilExpiry","token","split","claims","JSON","parse","Buffer","from","toString","exp","Math","floor","Date","now","createTestApi","config","replace","apiKey","local","candidateToken","doFetch","fetch","requests","bearer","call","opts","headers","apikey","authorization","undefined","startedAt","res","stringify","text","parsed","safeParse","push","ms","ok","left","abs","get","post","patch","put","delete","query","signInAs","identity","identities","declared","Object","keys","length","join","accessToken","id","email","signIn","credentials","attempt","extra","result","e","refusal","challenge","asPowChallenge","solvePowChallenge","access_token","user","signOut","asAnonymous","parseIdentities","raw","configured","api","Proxy","_target","prop","process","env","PALBASE_TEST_BASE_URL","PALBASE_TEST_API_KEY","PALBASE_TEST_CANDIDATE","PALBASE_TEST_IDENTITIES","Reflect","isolated","over","Map","local","make","c","has","get","hit","undefined","meta","Reflect","getMetadata","inst","map","d","set","api","with","t","v","refuseFragment","caller","table","where","isSqlFragment","Error","k","v","Object","entries","branch","Array","isArray","addDecimal","cell","by","sign","undefined","a","String","b","parse","x","m","exec","trim","frac","unit","BigInt","scale","length","pa","pb","Math","max","lift","total","Number","toString","neg","digits","padStart","out","slice","rowMatchesFilter","row","f","every","c","some","matchesCell","cmp","op","l","Date","getTime","r","key","cond","isColRef","$col","isNowExpr","toISOString","includes","isColumnExpr","toLowerCase","startsWith","endsWith","createMockDB","store","Map","tracked","inserted","updated","deleted","rowsOf","rows","get","set","track","map","list","push","resolveInsertValues","data","expr","columnExprOf","fn","ops","diagnostics","updateMany","opts","keys","assertUsableFilter","assertUsableWriteValues","hit","filter","returning","deleteMany","keep","count","search","_table","_params","facets","similar","recommend","supersede","_id","id","crypto","randomUUID","query","_sql","insert","raw","assertNoExpressionHandles","record","aggregate","q","groups","groupBy","shape","bucket","sum","vals","reduce","avg","pick","byKey","JSON","stringify","values","insertMany","validateInsertManyOptions","onConflict","cols","i","missing","extra","join","rawRow","lockRows","ids","unique","Set","sort","lockRowsWhere","mode","advisoryXactLock","_key","claim","keyCols","existing","find","put","rawData","update","idx","findIndex","current","applied","delete","splice","findUnique","findById","page","findMany","limit","offset","isInteger","with","orderSpecs","orderBy","o","dir","direction","column","y","xNull","yNull","nullsFirst","nulls","start","select","fromEntries","txPlan","plan","snapshot","trackedSnapshot","cloneTracked","results","result","applyOp","failure","guardFailure","guard","err","clear","resolveMap","conflict","value","rows_affected","created","written","matches","next","removed","indexOf","found","client","command","options","atomic","attempt","asService","seed","resolveValue","tagged","$ref","txRejection","message","field","$expr","base","ok","kind","n","slot","status","code","error_code","fakeDatabase","mock","createMockDB","queries","db","Object","assign","create","getPrototypeOf","query","sql","params","push","makeTypedSurface","raw","seed","table","rows","inserted","updated","deleted","absent","name","Proxy","get","_target","prop","Error","String","pick","services","key","withServices","fn","filled","Database","Auth","Secrets","Documents","Storage","Cache","Log","Notifications","Flags","Realtime","__requestALS","run","runtime","userId"]}