@orangecheck/me-client 0.48.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../node_modules/jose/dist/webapi/lib/buffer_utils.js","../node_modules/jose/dist/webapi/util/errors.js","../node_modules/jose/dist/webapi/util/base64url.js","../node_modules/jose/dist/webapi/lib/validate.js","../node_modules/jose/dist/webapi/lib/key.js","../node_modules/jose/dist/webapi/lib/key_descriptor.js","../node_modules/jose/dist/webapi/lib/jwe_algorithms.js","../node_modules/jose/dist/webapi/lib/jws_algorithms.js","../node_modules/jose/dist/webapi/lib/key_algorithm.js","../node_modules/jose/dist/webapi/key/import.js","../src/identity.ts","../src/connect.ts","../src/connect-consent.ts","../src/tokens.ts","../src/merged.ts","../src/server.ts"],"names":["sig","DEFAULT_ISSUER","DEFAULT_TIMEOUT_MS","MAX_TIMEOUT_MS","fail","post","verifyOcTokenCore","checkOcTokenCore","familyRevocationCheck","integratorRevocationCheck","readOcSessionToken","SAFE_METHODS","bondMeets","readBondClaim","refused"],"mappings":";;;;;;;;;AAAgB,IAAI,WAAA;AAApB,IAAmC,OAAA,GAAU,IAAI,WAAA,EAAY;AAAmB,IAAI,WAAA,CAAY,SAAS,EAAE,KAAA,EAAO,MAAI;AA8CtH,SAAS,YAAA,CAAa,OAAA,EAAS,GAAA,GAAM,KAAA,EAAI;AACvC,EAAA,IAAI,UAAA,CAAW,UAAA;AACb,IAAA,OAAO,UAAA,CAAW,WAAW,OAAA,EAAS,EAAE,UAAU,GAAA,GAAM,WAAA,GAAc,UAAU,CAAA;AAClF,EAAA,IAAI,GAAA,EAAK;AACP,IAAA,IAAI,QAAQ,QAAA,CAAS,GAAG,CAAA,IAAK,OAAA,CAAQ,SAAS,GAAG,CAAA;AAC/C,MAAA,MAAM,IAAI,UAAU,mBAAmB,CAAA;AACzC,IAAA,OAAA,GAAU,QAAQ,OAAA,CAAQ,IAAA,EA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AAG,OAAA;AAAA,MACH,MAAA,EAAQ,CAAA,CAAE,GAAA,CAAI,GAAA,CAAI;AAAA,KACrB,CAAA;AACD,IAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,MAAA,KAAW,WAAA,GAAc,QAAQ,OAAA,GAAU,IAAA;AACnE,IAAA,CAAA,CAAE,GAAA,CAAI,aAAa,OAAO,CAAA;AAC1B,IAAA,MAAMA,QAAAA,GACF,OAAA,CAAQ,MAAA,KAAW,aAAA,GACb,WAAA,CAAY,OAAO,CAAA,GACnB,MAAM,OAAA,CAAQ,OAAA,EAAS,OAAA,EAAS,UAAA,CAAW,OAAO,CAAC,CAAA;AAC7D,IAAA,IAAIA,UAAS,OAAO,CAAA,CAAE,KAAKA,QAAAA,CAAQ,IAAA,EAAMA,SAAQ,MAAM,CAAA;AACvD,IAAA,MAAM,IAAA,EAAK;AAAA,EACf,CAAA;AACJ","file":"server.js","sourcesContent":["const encoder = new TextEncoder(), decoder = new TextDecoder(), strictDecoder = new TextDecoder(\"utf-8\", { fatal: !0 }), UINT32_RANGE = 2 ** 32;\nfunction concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0), buf = new Uint8Array(size);\n let i = 0;\n for (const buffer of buffers)\n buf.set(buffer, i), i += buffer.length;\n return buf;\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= UINT32_RANGE)\n throw new RangeError(`value must be >= 0 and <= ${UINT32_RANGE - 1}. Received ${value}`);\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset);\n}\nfunction uint64be(value) {\n const high = Math.floor(value / UINT32_RANGE), low = value % UINT32_RANGE, buf = new Uint8Array(8);\n return writeUInt32BE(buf, high, 0), writeUInt32BE(buf, low, 4), buf;\n}\nfunction uint32be(value) {\n const buf = new Uint8Array(4);\n return writeUInt32BE(buf, value), buf;\n}\nconst NON_ASCII = /[^\\x00-\\x7f]/;\nfunction encode(string) {\n if (typeof string == \"string\" && string.length >= 128) {\n if (NON_ASCII.test(string))\n throw new TypeError(\"non-ASCII string encountered in encode()\");\n return encoder.encode(string);\n }\n const bytes = new Uint8Array(string.length);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code > 127)\n throw new TypeError(\"non-ASCII string encountered in encode()\");\n bytes[i] = code;\n }\n return bytes;\n}\nfunction encodeBase64(input, url = !1) {\n if (Uint8Array.prototype.toBase64)\n return input.toBase64({ alphabet: url ? \"base64url\" : \"base64\", omitPadding: url });\n const CHUNK_SIZE = 32768, arr = [];\n for (let i = 0; i < input.length; i += CHUNK_SIZE)\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n const encoded = btoa(arr.join(\"\"));\n return url ? encoded.replace(/=/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\") : encoded;\n}\nfunction decodeBase64(encoded, url = !1) {\n if (Uint8Array.fromBase64)\n return Uint8Array.fromBase64(encoded, { alphabet: url ? \"base64url\" : \"base64\" });\n if (url) {\n if (encoded.includes(\"+\") || encoded.includes(\"/\"))\n throw new TypeError(\"Invalid base64url\");\n encoded = encoded.replace(/-/g, \"+\").replace(/_/g, \"/\");\n }\n const binary = atob(encoded), bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\nasync function digest(algorithm, data) {\n const subtleDigest = `SHA-${algorithm.slice(-3)}`;\n return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));\n}\nexport {\n concat,\n decodeBase64,\n decoder,\n digest,\n encode,\n encodeBase64,\n encoder,\n strictDecoder,\n uint32be,\n uint64be\n};\n","class JOSEError extends Error {\n static code = \"ERR_JOSE_GENERIC\";\n code = \"ERR_JOSE_GENERIC\";\n constructor(message, options) {\n super(message, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);\n }\n}\nclass JWTClaimValidationFailed extends JOSEError {\n static code = \"ERR_JWT_CLAIM_VALIDATION_FAILED\";\n code = \"ERR_JWT_CLAIM_VALIDATION_FAILED\";\n claim;\n reason;\n payload;\n constructor(message, payload, claim = \"unspecified\", reason = \"unspecified\") {\n super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;\n }\n}\nclass JWTExpired extends JOSEError {\n static code = \"ERR_JWT_EXPIRED\";\n code = \"ERR_JWT_EXPIRED\";\n claim;\n reason;\n payload;\n constructor(message, payload, claim = \"unspecified\", reason = \"unspecified\") {\n super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;\n }\n}\nclass JOSEAlgNotAllowed extends JOSEError {\n static code = \"ERR_JOSE_ALG_NOT_ALLOWED\";\n code = \"ERR_JOSE_ALG_NOT_ALLOWED\";\n}\nclass JOSENotSupported extends JOSEError {\n static code = \"ERR_JOSE_NOT_SUPPORTED\";\n code = \"ERR_JOSE_NOT_SUPPORTED\";\n}\nclass JWEDecryptionFailed extends JOSEError {\n static code = \"ERR_JWE_DECRYPTION_FAILED\";\n code = \"ERR_JWE_DECRYPTION_FAILED\";\n constructor(message = \"decryption operation failed\", options) {\n super(message, options);\n }\n}\nclass JWEInvalid extends JOSEError {\n static code = \"ERR_JWE_INVALID\";\n code = \"ERR_JWE_INVALID\";\n}\nclass JWSInvalid extends JOSEError {\n static code = \"ERR_JWS_INVALID\";\n code = \"ERR_JWS_INVALID\";\n}\nclass JWTInvalid extends JOSEError {\n static code = \"ERR_JWT_INVALID\";\n code = \"ERR_JWT_INVALID\";\n}\nclass JWKInvalid extends JOSEError {\n static code = \"ERR_JWK_INVALID\";\n code = \"ERR_JWK_INVALID\";\n}\nclass JWKSInvalid extends JOSEError {\n static code = \"ERR_JWKS_INVALID\";\n code = \"ERR_JWKS_INVALID\";\n}\nclass JWKSNoMatchingKey extends JOSEError {\n static code = \"ERR_JWKS_NO_MATCHING_KEY\";\n code = \"ERR_JWKS_NO_MATCHING_KEY\";\n constructor(message = \"no applicable key found in the JSON Web Key Set\", options) {\n super(message, options);\n }\n}\nclass JWKSMultipleMatchingKeys extends JOSEError {\n [Symbol.asyncIterator] = async function* () {\n };\n static code = \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\";\n code = \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\";\n constructor(message = \"multiple matching keys found in the JSON Web Key Set\", options) {\n super(message, options);\n }\n}\nclass JWKSTimeout extends JOSEError {\n static code = \"ERR_JWKS_TIMEOUT\";\n code = \"ERR_JWKS_TIMEOUT\";\n constructor(message = \"request timed out\", options) {\n super(message, options);\n }\n}\nclass JWSSignatureVerificationFailed extends JOSEError {\n static code = \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\";\n code = \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\";\n constructor(message = \"signature verification failed\", options) {\n super(message, options);\n }\n}\nexport {\n JOSEAlgNotAllowed,\n JOSEError,\n JOSENotSupported,\n JWEDecryptionFailed,\n JWEInvalid,\n JWKInvalid,\n JWKSInvalid,\n JWKSMultipleMatchingKeys,\n JWKSNoMatchingKey,\n JWKSTimeout,\n JWSInvalid,\n JWSSignatureVerificationFailed,\n JWTClaimValidationFailed,\n JWTExpired,\n JWTInvalid\n};\n","import { encoder, decoder, encodeBase64, decodeBase64 } from \"../lib/buffer_utils.js\";\nconst invalid = \"The input to be decoded is not correctly encoded.\";\nfunction decode(input) {\n try {\n return decodeBase64(typeof input == \"string\" ? input : decoder.decode(input), !0);\n } catch (cause) {\n throw new TypeError(invalid, { cause });\n }\n}\nfunction encode(input) {\n return encodeBase64(typeof input == \"string\" ? encoder.encode(input) : input, !0);\n}\nexport {\n decode,\n encode\n};\n","import { JOSENotSupported, JWSInvalid } from \"../util/errors.js\";\nimport { decode } from \"../util/base64url.js\";\nimport { encode, strictDecoder } from \"./buffer_utils.js\";\nfunction assertUint8Array(input, label) {\n if (!(input instanceof Uint8Array))\n throw new TypeError(`${label} must be an instance of Uint8Array`);\n}\nfunction isObject(input) {\n if (typeof input != \"object\" || input === null || Object.prototype.toString.call(input) !== \"[object Object]\")\n return !1;\n const prototype = Object.getPrototypeOf(input);\n return prototype === null || Object.getPrototypeOf(prototype) === null;\n}\nfunction isJwkSet(input) {\n return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject);\n}\nfunction isDisjoint(...headers) {\n const parameters = /* @__PURE__ */ new Set();\n for (const header of headers)\n if (header)\n for (const parameter of Object.keys(header)) {\n if (parameters.has(parameter))\n return !1;\n parameters.add(parameter);\n }\n return !0;\n}\nfunction assertNotSet(value, name) {\n if (value !== void 0)\n throw new TypeError(`${name} can only be called once`);\n}\nfunction decodeBase64url(value, label, ErrorClass) {\n try {\n return decode(value);\n } catch (cause) {\n throw new ErrorClass(`Failed to base64url decode the ${label}`, { cause });\n }\n}\nfunction encodeAsciiMember(value, label, ErrorClass) {\n try {\n return encode(value);\n } catch (cause) {\n throw new ErrorClass(`The ${label} is not a valid base64url string`, { cause });\n }\n}\nfunction parseJoseHeader(encodedProtectedHeader, ErrorClass, message) {\n let parsed;\n try {\n parsed = JSON.parse(strictDecoder.decode(decode(encodedProtectedHeader)));\n } catch (cause) {\n throw new ErrorClass(message, { cause });\n }\n if (!isObject(parsed))\n throw new ErrorClass(message);\n return parsed;\n}\nconst JWS_RECOGNIZED = { __proto__: null, b64: !0 }, JWE_RECOGNIZED = { __proto__: null };\nfunction validateAlgorithms(option, algorithms) {\n if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != \"string\")))\n throw new TypeError(`\"${option}\" option must be an array of strings`);\n return algorithms === void 0 ? void 0 : new Set(algorithms);\n}\nfunction validateCritDuplicates(Err, protectedHeader) {\n const { crit } = protectedHeader ?? {};\n if (Array.isArray(crit) && new Set(crit).size !== crit.length)\n throw new Err('\"crit\" (Critical) Header Parameter MUST NOT contain duplicate values');\n}\nfunction validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0)\n throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n if (!protectedHeader || protectedHeader.crit === void 0)\n return [];\n if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != \"string\" || input.length === 0))\n throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };\n for (const parameter of protectedHeader.crit) {\n if (!(parameter in recognized))\n throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0)\n throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0))\n throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n }\n return protectedHeader.crit;\n}\nfunction validateB64(protectedHeader, extensions) {\n if (extensions.includes(\"b64\")) {\n const b64 = protectedHeader.b64;\n if (typeof b64 != \"boolean\")\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n return b64;\n }\n return !0;\n}\nfunction serializeJoseHeader(Err, header) {\n let serialized, parsed;\n try {\n serialized = JSON.stringify(header), parsed = JSON.parse(serialized);\n } catch (cause) {\n throw new Err(\"JOSE Header is not valid JSON\", { cause });\n }\n if (!isObject(parsed))\n throw new Err(\"JOSE Header is not a JSON object\");\n return [parsed, serialized];\n}\nexport {\n JWE_RECOGNIZED,\n JWS_RECOGNIZED,\n assertNotSet,\n assertUint8Array,\n decodeBase64url,\n encodeAsciiMember,\n isDisjoint,\n isJwkSet,\n isObject,\n parseJoseHeader,\n serializeJoseHeader,\n validateAlgorithms,\n validateB64,\n validateCrit,\n validateCritDuplicates\n};\n","import { isObject } from \"./validate.js\";\nimport { decode } from \"../util/base64url.js\";\nimport { JOSENotSupported } from \"../util/errors.js\";\nconst tag = (key) => key[Symbol.toStringTag], jwkMatchesOp = (entry, key, usage) => {\n const { alg } = entry;\n if (key.use !== void 0) {\n const expected = usage === \"sign\" || usage === \"verify\" ? \"sig\" : \"enc\";\n if (key.use !== expected)\n throw new TypeError(`Invalid key for this operation, its \"use\" must be \"${expected}\" when present`);\n }\n if (key.alg !== void 0 && key.alg !== alg)\n throw new TypeError(`Invalid key for this operation, its \"alg\" must be \"${alg}\" when present`);\n if (Array.isArray(key.key_ops)) {\n const expectedKeyOp = usage === \"encrypt\" || usage === \"decrypt\" ? entry.ops?.[usage === \"encrypt\" ? 0 : 1] : usage;\n if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp))\n throw new TypeError(`Invalid key for this operation, its \"key_ops\" must include \"${expectedKeyOp}\" when present`);\n }\n};\nasync function prepareKey(entry, key, usage) {\n const { alg, secret } = entry, requiresPrivateKey = usage === \"decrypt\" || usage === \"sign\";\n if (secret && key instanceof Uint8Array)\n return key;\n let normalized, keyObject;\n if (isObject(key)) {\n if (normalized = normalizeJwk(key), typeof normalized.kty != \"string\")\n throw invalidKeyType(alg, key, secret);\n if (!(secret ? normalized.kty === \"oct\" && typeof normalized.k == \"string\" : normalized.kty !== \"oct\" && (requiresPrivateKey ? normalized.kty === \"AKP\" && typeof normalized.priv == \"string\" || typeof normalized.d == \"string\" : normalized.d === void 0 && normalized.priv === void 0)))\n throw new TypeError(secret ? 'JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present' : `JSON Web Key for this operation must be a ${requiresPrivateKey ? \"private\" : \"public\"} JWK`);\n if (jwkMatchesOp(entry, normalized, usage), normalized.kty === \"oct\")\n return decode(normalized.k);\n if (!Object.isFrozen(key)) {\n const { key_ops } = key;\n Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);\n }\n } else {\n if (!isKeyLike(key))\n throw invalidKeyType(alg, key, secret);\n const expectedType = secret ? \"secret\" : requiresPrivateKey ? \"private\" : \"public\";\n if (key.type !== expectedType && (secret || [\"secret\", \"public\", \"private\"].includes(key.type)))\n throw new TypeError(`${tag(key)} instances must be of type \"${expectedType}\" for the ${alg} algorithm`);\n if (isCryptoKey(key))\n return key;\n if (keyObject = key, keyObject.type === \"secret\")\n return keyObject.export();\n }\n cache ||= /* @__PURE__ */ new WeakMap();\n const cacheKey = key;\n let cached = cache.get(cacheKey);\n if (cached?.[alg])\n return cached[alg];\n if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == \"function\") {\n const isPublic = keyObject.type === \"public\", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({ crv, asymmetricKeyType: keyObject.asymmetricKeyType }) ?? entry.subtle;\n return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);\n }\n return normalized ??= keyObject.export({ format: \"jwk\" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized);\n}\nlet cache;\nconst nist = {\n __proto__: null,\n prime256v1: \"P-256\",\n secp384r1: \"P-384\",\n secp521r1: \"P-521\"\n};\nfunction assertCryptoKey(key) {\n if (!isCryptoKey(key))\n throw new Error(\"CryptoKey instance expected\");\n}\nconst isCryptoKey = (key) => {\n if (key?.[Symbol.toStringTag] === \"CryptoKey\")\n return !0;\n try {\n return key instanceof CryptoKey;\n } catch {\n return !1;\n }\n}, isKeyObject = (key) => key?.[Symbol.toStringTag] === \"KeyObject\", isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);\nfunction message(msg, actual, ...types) {\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(\", \")}, or ${last}.`;\n } else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;\n return actual == null ? msg += ` Received ${actual}` : typeof actual == \"function\" && actual.name ? msg += ` Received function ${actual.name}` : typeof actual == \"object\" && actual != null && actual.constructor?.name && (msg += ` Received an instance of ${actual.constructor.name}`), msg;\n}\nconst invalidKeyInput = (actual, ...types) => message(\"Key must be \", actual, ...types);\nfunction invalidKeyType(alg, actual, secret) {\n const types = [\"CryptoKey\", \"KeyObject\", \"JSON Web Key\"];\n return secret && types.push(\"Uint8Array\"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));\n}\nconst unusable = (name, prop = \"algorithm.name\") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\nfunction checkUsage(key, usage) {\n if (usage && !key.usages.includes(usage))\n throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);\n}\nfunction checkModulusLength(alg, key) {\n const { modulusLength } = key.algorithm;\n if (typeof modulusLength != \"number\" || modulusLength < 2048)\n throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n}\nfunction checkCryptoKey(key, expected, usage) {\n const algorithm = key.algorithm;\n if (algorithm.name !== expected.name)\n throw unusable(expected.name);\n if (expected.hash && algorithm.hash?.name !== expected.hash)\n throw unusable(expected.hash, \"algorithm.hash\");\n if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve)\n throw unusable(expected.namedCurve, \"algorithm.namedCurve\");\n if (expected.length !== void 0 && algorithm.length !== expected.length)\n throw unusable(expected.length, \"algorithm.length\");\n checkUsage(key, usage);\n}\nfunction snapshotJwk(jwk) {\n return { __proto__: null, ...jwk };\n}\nfunction normalizeJwk(jwk) {\n const normalized = snapshotJwk(jwk);\n if (normalized.ext !== void 0 && typeof normalized.ext != \"boolean\")\n throw new TypeError('\"ext\" (Extractable) Parameter must be a boolean');\n if (normalized.key_ops !== void 0) {\n const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;\n if (!keyOps || keyOps.some((operation) => typeof operation != \"string\") || new Set(keyOps).size !== keyOps.length)\n throw new TypeError('\"key_ops\" (Key Operations) Parameter must be an array of unique strings');\n normalized.key_ops = keyOps;\n }\n return normalized;\n}\nfunction validateExtractableOption(extractable) {\n if (extractable !== void 0 && typeof extractable != \"boolean\")\n throw new TypeError('\"extractable\" option must be a boolean');\n return extractable;\n}\nasync function jwkToKey(entry, jwk, extractable) {\n if (!entry.kty.includes(jwk.kty))\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = { ...jwk, ext: extractable ?? jwk.ext };\n return keyData.kty !== \"AKP\" && delete keyData.alg, delete keyData.use, crypto.subtle.importKey(\"jwk\", keyData, algorithm, keyData.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);\n}\nasync function rawKey(key, expected, usage, extractable = !1) {\n return key instanceof Uint8Array && (key = await crypto.subtle.importKey(\"raw\", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;\n}\nexport {\n assertCryptoKey,\n checkCryptoKey,\n checkModulusLength,\n checkUsage,\n invalidKeyInput,\n isCryptoKey,\n isKeyLike,\n isKeyObject,\n jwkToKey,\n normalizeJwk,\n prepareKey,\n rawKey,\n snapshotJwk,\n validateExtractableOption\n};\n","function table(entries) {\n const out = { __proto__: null };\n for (const alg in entries)\n out[alg] = { ...entries[alg], alg };\n return out;\n}\nexport {\n table\n};\n","import { JOSENotSupported } from \"../util/errors.js\";\nimport { table } from \"./key_descriptor.js\";\nconst wrap = [\n [\"encrypt\", \"wrapKey\"],\n [\"decrypt\", \"unwrapKey\"]\n], derive = [[], [\"deriveBits\"]], none = [[], []];\nfunction rsaes(bits) {\n return {\n kty: [\"RSA\"],\n mode: \"key-encryption\",\n subtle: { name: \"RSA-OAEP\", hash: `SHA-${bits}` },\n usages: wrap,\n ops: [\"wrapKey\", \"unwrapKey\"]\n };\n}\nfunction ecdh(mode) {\n return {\n kty: [\"EC\", \"OKP\"],\n mode,\n subtle: { name: \"ECDH\" },\n resolve: ({ kty, crv, asymmetricKeyType }) => {\n if (crv === \"X25519\" || asymmetricKeyType === \"x25519\")\n return { name: \"X25519\" };\n if (kty === \"OKP\")\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n return { name: \"ECDH\", namedCurve: crv };\n },\n usages: derive,\n ops: [void 0, \"deriveBits\"]\n };\n}\nfunction aeskw(bits, gcm = !1) {\n return {\n kty: [\"oct\"],\n mode: \"key-wrapping\",\n secret: !0,\n subtle: { name: gcm ? \"AES-GCM\" : \"AES-KW\", length: bits },\n usages: none,\n ops: gcm ? [\"encrypt\", \"decrypt\"] : [\"wrapKey\", \"unwrapKey\"]\n };\n}\nfunction pbes2() {\n return {\n kty: [\"oct\"],\n mode: \"key-wrapping\",\n secret: !0,\n subtle: { name: \"PBKDF2\" },\n usages: none,\n ops: [\"deriveBits\", \"deriveBits\"]\n };\n}\nconst JWE = table({\n dir: {\n kty: [\"oct\"],\n mode: \"direct-encryption\",\n secret: !0,\n subtle: { name: \"AES-GCM\" },\n usages: none,\n ops: [\"encrypt\", \"decrypt\"]\n },\n \"RSA-OAEP\": rsaes(1),\n \"RSA-OAEP-256\": rsaes(256),\n \"RSA-OAEP-384\": rsaes(384),\n \"RSA-OAEP-512\": rsaes(512),\n \"ECDH-ES\": ecdh(\"direct-key-agreement\"),\n \"ECDH-ES+A128KW\": ecdh(\"key-agreement-with-key-wrapping\"),\n \"ECDH-ES+A192KW\": ecdh(\"key-agreement-with-key-wrapping\"),\n \"ECDH-ES+A256KW\": ecdh(\"key-agreement-with-key-wrapping\"),\n A128KW: aeskw(128),\n A192KW: aeskw(192),\n A256KW: aeskw(256),\n A128GCMKW: aeskw(128, !0),\n A192GCMKW: aeskw(192, !0),\n A256GCMKW: aeskw(256, !0),\n \"PBES2-HS256+A128KW\": pbes2(),\n \"PBES2-HS384+A192KW\": pbes2(),\n \"PBES2-HS512+A256KW\": pbes2()\n}), contentOps = [\"encrypt\", \"decrypt\"];\nfunction contentEncryption(bits, cbc = !1) {\n return {\n kty: [\"oct\"],\n secret: !0,\n subtle: { name: cbc ? \"AES-CBC\" : \"AES-GCM\", length: bits },\n usages: none,\n ops: contentOps,\n cekBits: bits,\n ivBits: cbc ? 128 : 96,\n cbc\n };\n}\nconst ENC = table({\n A128GCM: contentEncryption(128),\n A192GCM: contentEncryption(192),\n A256GCM: contentEncryption(256),\n \"A128CBC-HS256\": contentEncryption(256, !0),\n \"A192CBC-HS384\": contentEncryption(384, !0),\n \"A256CBC-HS512\": contentEncryption(512, !0)\n});\nfunction unsupported(parameter, name) {\n throw new JOSENotSupported(`Invalid or unsupported \"${parameter}\" (JWE ${name}) header value`);\n}\nfunction jweAlgorithm(alg) {\n return (typeof alg == \"string\" ? JWE[alg] : void 0) ?? unsupported(\"alg\", \"Algorithm\");\n}\nfunction isJWECEKTransport(algorithm) {\n return algorithm.mode === \"key-wrapping\" || algorithm.mode === \"key-encryption\" || algorithm.mode === \"key-agreement-with-key-wrapping\";\n}\nfunction jweEncryption(enc) {\n return (typeof enc == \"string\" ? ENC[enc] : void 0) ?? unsupported(\"enc\", \"Encryption Algorithm\");\n}\nexport {\n JWE,\n isJWECEKTransport,\n jweAlgorithm,\n jweEncryption\n};\n","import { JOSENotSupported } from \"../util/errors.js\";\nimport { table } from \"./key_descriptor.js\";\nconst sig = [[\"verify\"], [\"sign\"]];\nfunction hmac(bits) {\n const subtle = { name: \"HMAC\", hash: `SHA-${bits}` };\n return { kty: [\"oct\"], secret: !0, subtle, signing: subtle, usages: sig };\n}\nfunction rsa(bits, saltLength) {\n const subtle = { name: saltLength ? \"RSA-PSS\" : \"RSASSA-PKCS1-v1_5\", hash: `SHA-${bits}` };\n return {\n kty: [\"RSA\"],\n subtle,\n signing: saltLength ? { ...subtle, saltLength } : subtle,\n usages: sig,\n minRsaBits: 2048\n };\n}\nfunction ecdsa(crv, bits) {\n return {\n kty: [\"EC\"],\n crv,\n subtle: { name: \"ECDSA\", namedCurve: crv },\n signing: { name: \"ECDSA\", hash: `SHA-${bits}` },\n usages: sig\n };\n}\nfunction eddsa() {\n const subtle = { name: \"Ed25519\" };\n return {\n kty: [\"OKP\"],\n crv: \"Ed25519\",\n subtle,\n signing: subtle,\n usages: sig\n };\n}\nfunction mldsa(parameterSet) {\n const subtle = { name: `ML-DSA-${parameterSet}` };\n return {\n kty: [\"AKP\"],\n subtle,\n signing: subtle,\n usages: sig\n };\n}\nconst JWS = table({\n HS256: hmac(256),\n HS384: hmac(384),\n HS512: hmac(512),\n RS256: rsa(256),\n RS384: rsa(384),\n RS512: rsa(512),\n PS256: rsa(256, 32),\n PS384: rsa(384, 48),\n PS512: rsa(512, 64),\n ES256: ecdsa(\"P-256\", 256),\n ES384: ecdsa(\"P-384\", 384),\n ES512: ecdsa(\"P-521\", 512),\n EdDSA: eddsa(),\n Ed25519: eddsa(),\n \"ML-DSA-44\": mldsa(44),\n \"ML-DSA-65\": mldsa(65),\n \"ML-DSA-87\": mldsa(87)\n});\nfunction jwsAlgorithm(alg) {\n const entry = typeof alg == \"string\" ? JWS[alg] : void 0;\n if (!entry)\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n return entry;\n}\nexport {\n JWS,\n jwsAlgorithm\n};\n","import { JOSENotSupported } from \"../util/errors.js\";\nimport { JWS } from \"./jws_algorithms.js\";\nimport { JWE } from \"./jwe_algorithms.js\";\nconst algArgument = '\"alg\" (Algorithm)';\nfunction unsupportedAlg(source = 'JWK \"alg\" (Algorithm) Parameter') {\n throw new JOSENotSupported(`Invalid or unsupported ${source} value`);\n}\nfunction keyAlgorithm(alg, source) {\n return (typeof alg == \"string\" ? JWS[alg] ?? JWE[alg] : void 0) ?? unsupportedAlg(source);\n}\nexport {\n algArgument,\n keyAlgorithm,\n unsupportedAlg\n};\n","import { decode as decodeBase64URL } from \"../util/base64url.js\";\nimport { fromSPKI, fromPKCS8, fromX509 } from \"../lib/asn1.js\";\nimport { jwkToKey, validateExtractableOption, normalizeJwk } from \"../lib/key.js\";\nimport { keyAlgorithm } from \"../lib/key_algorithm.js\";\nimport { JOSENotSupported } from \"../util/errors.js\";\nimport { isObject } from \"../lib/validate.js\";\nasync function importSPKI(spki, alg, options) {\n if (typeof spki != \"string\" || spki.indexOf(\"-----BEGIN PUBLIC KEY-----\") !== 0)\n throw new TypeError('\"spki\" must be SPKI formatted string');\n return fromSPKI(spki, alg, options);\n}\nasync function importX509(x509, alg, options) {\n if (typeof x509 != \"string\" || x509.indexOf(\"-----BEGIN CERTIFICATE-----\") !== 0)\n throw new TypeError('\"x509\" must be X.509 formatted string');\n return fromX509(x509, alg, options);\n}\nasync function importPKCS8(pkcs8, alg, options) {\n if (typeof pkcs8 != \"string\" || pkcs8.indexOf(\"-----BEGIN PRIVATE KEY-----\") !== 0)\n throw new TypeError('\"pkcs8\" must be PKCS#8 formatted string');\n return fromPKCS8(pkcs8, alg, options);\n}\nasync function importJWK(jwk, alg, options) {\n if (!isObject(jwk))\n throw new TypeError(\"JWK must be an object\");\n const normalized = normalizeJwk(jwk), extractable = validateExtractableOption(options?.extractable), { alg: jwkAlg } = normalized;\n if (alg ??= jwkAlg, normalized.kty !== \"oct\" && !alg)\n throw new TypeError('\"alg\" argument is required when \"jwk.alg\" is not present');\n switch (normalized.kty) {\n case \"oct\":\n if (typeof normalized.k != \"string\")\n throw new TypeError('missing \"k\" (Key Value) Parameter value');\n return decodeBase64URL(normalized.k);\n case \"AKP\": {\n if (typeof jwkAlg != \"string\" || !jwkAlg)\n throw new TypeError('missing \"alg\" (Algorithm) Parameter value');\n if (alg !== jwkAlg)\n throw new TypeError(\"JWK alg and alg option value mismatch\");\n return jwkToKey(keyAlgorithm(alg), normalized, extractable);\n }\n case \"RSA\":\n case \"EC\":\n case \"OKP\":\n return jwkToKey(keyAlgorithm(alg), normalized, extractable);\n default:\n throw new JOSENotSupported('Unsupported \"kty\" (Key Type) Parameter value');\n }\n}\nexport {\n importJWK,\n importPKCS8,\n importSPKI,\n importX509\n};\n","/**\n * `oc.identity.verifyActivityAttestation` — one-call ed25519 verifier\n * for a /api/me/activity-attestation bundle.\n *\n * Cashes the \"trivially to verify\" strategic claim: an integrator\n * receiving a signed attestation JSON from a user calls one function,\n * gets a typed result with per-check detail, never reaches into\n * @noble/curves or jose themselves.\n *\n * import { oc } from '@orangecheck/me-client';\n *\n * const result = await oc.identity.verifyActivityAttestation(bundle);\n * if (!result.ok) return res.status(401).send(result.reason);\n * // result.attestation is typed · safe to gate on lifetime_sats etc.\n *\n * The JWKS issuer is me.ochk.io (the envelope key), DISTINCT from\n * the auth host's ochk.io JWKS that signs webhooks. Same Ed25519\n * curve, same kid lookup pattern, fetched + cached separately.\n */\n\nimport { importJWK, type CryptoKey, type KeyObject } from 'jose';\n\nconst DEFAULT_ISSUER = 'https://me.ochk.io';\nconst DEFAULT_TTL_MS = 60 * 60 * 1000;\n/** How old a key list may be and still stand in for one that can't be fetched. */\nconst DEFAULT_MAX_STALE_MS = 6 * 60 * 60 * 1000;\n/** An unknown kid refetches the key list at most this often per issuer. */\nconst FORCED_REFRESH_MIN_INTERVAL_MS = 60_000;\nconst ENVELOPE_JWKS_PATH = '/.well-known/oc-envelope-jwks.json';\n\nexport interface ActivityAttestation {\n id: string;\n v: 1;\n kind: 'oc-me-activity';\n did_oc: string;\n event_count: number;\n human_event_count: number;\n lifetime_sats: number;\n distinct_integrator_count: number;\n oldest_event_at: string | null;\n active_days: number;\n computed_at: string;\n expires_at: string;\n}\n\nexport interface ActivityAttestationBundle {\n /** A readable copy. Never trusted: the result is read from the signed\n * bytes, and a copy that differs from them fails the check. */\n attestation?: ActivityAttestation;\n sig: string;\n kid: string;\n canonical_b64: string;\n}\n\nexport interface ActivityVerifyCheck {\n ok: boolean;\n label: string;\n detail?: string;\n}\n\nexport interface ActivityVerifyResult {\n ok: boolean;\n reason?: string;\n attestation?: ActivityAttestation;\n checks: ActivityVerifyCheck[];\n}\n\ninterface OcEnvelopePublicJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n kid: string;\n alg?: 'EdDSA';\n use?: 'sig';\n}\n\nexport interface VerifyActivityOptions {\n /** Override the me.ochk.io issuer (defaults to https://me.ochk.io).\n * Useful for staging / self-hosted dev. */\n issuer?: string;\n /** Pass a JWK directly to skip the network fetch · convenient when\n * embedding the public key in your service for air-gapped or\n * edge-runtime deployments. */\n jwk?: OcEnvelopePublicJwk;\n /** JWKS cache TTL in ms. Defaults to 1h. Stale-on-error falls back\n * to the previous cached value, for at most `jwksMaxStaleMs`. */\n jwksCacheTtlMs?: number;\n /** How old a cached JWKS may be and still stand in during an outage.\n * Defaults to 6h; past it, verification fails closed. */\n jwksMaxStaleMs?: number;\n /** Optional · override \"now\" for deterministic tests. */\n now?: Date;\n}\n\ntype AuthKey = CryptoKey | KeyObject;\n\ninterface JwksCacheEntry {\n keys: Record<string, AuthKey>;\n fetchedAt: number;\n}\n\nconst jwksCache = new Map<string, JwksCacheEntry>();\nconst inflight = new Map<string, Promise<JwksCacheEntry>>();\nconst lastForcedRefresh = new Map<string, number>();\n\nasync function fetchEnvelopeJwks(\n issuer: string,\n ttlMs: number,\n maxStaleMs = DEFAULT_MAX_STALE_MS\n): Promise<JwksCacheEntry> {\n const cached = jwksCache.get(issuer);\n if (cached && Date.now() - cached.fetchedAt < ttlMs) return cached;\n const existing = inflight.get(issuer);\n if (existing) return existing;\n const p = (async (): Promise<JwksCacheEntry> => {\n try {\n const url = `${issuer.replace(/\\/$/, '')}${ENVELOPE_JWKS_PATH}`;\n const res = await fetch(url, { headers: { Accept: 'application/json' } });\n if (!res.ok) throw new Error(`envelope JWKS fetch ${url} returned ${res.status}`);\n const json = (await res.json()) as { keys: OcEnvelopePublicJwk[] };\n if (!json || !Array.isArray(json.keys)) {\n throw new Error(`envelope JWKS at ${url} did not return {keys:[…]}`);\n }\n const keys: Record<string, AuthKey> = {};\n for (const k of json.keys) {\n if (typeof k.kid !== 'string') continue;\n try {\n keys[k.kid] = (await importJWK(k, 'EdDSA')) as AuthKey;\n } catch {\n /* skip keys that won't import */\n }\n }\n const entry: JwksCacheEntry = { keys, fetchedAt: Date.now() };\n jwksCache.set(issuer, entry);\n return entry;\n } catch (err) {\n // A key the issuer removed must stop verifying even while its list can't be fetched.\n const stale = jwksCache.get(issuer);\n if (stale && Date.now() - stale.fetchedAt < maxStaleMs) return stale;\n throw err;\n }\n })().finally(() => {\n inflight.delete(issuer);\n });\n inflight.set(issuer, p);\n return p;\n}\n\nfunction hexToBytes(hex: string): Uint8Array | null {\n if (typeof hex !== 'string') return null;\n const s = hex.trim();\n if (s.length === 0 || s.length % 2 !== 0) return null;\n const out = new Uint8Array(s.length / 2);\n for (let i = 0; i < out.length; i++) {\n const b = parseInt(s.slice(i * 2, i * 2 + 2), 16);\n if (Number.isNaN(b)) return null;\n out[i] = b;\n }\n return out;\n}\n\nfunction base64ToBytes(b64: string): Uint8Array | null {\n try {\n const bin =\n typeof atob === 'function'\n ? atob(b64)\n : Buffer.from(b64, 'base64').toString('binary');\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n } catch {\n return null;\n }\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n let out = '';\n for (const b of bytes) out += b.toString(16).padStart(2, '0');\n return out;\n}\n\nasync function sha256(bytes: Uint8Array): Promise<Uint8Array> {\n const subtle =\n typeof globalThis.crypto !== 'undefined' && globalThis.crypto.subtle\n ? globalThis.crypto.subtle\n : null;\n if (!subtle) {\n throw new Error('crypto.subtle unavailable · need Node 20+ / modern browser / Edge runtime');\n }\n const buf = await subtle.digest('SHA-256', bytes as unknown as ArrayBuffer);\n return new Uint8Array(buf);\n}\n\nfunction toArrayBuffer(view: Uint8Array): ArrayBuffer {\n const buf = new ArrayBuffer(view.byteLength);\n new Uint8Array(buf).set(view);\n return buf;\n}\n\nasync function verifyEd25519(\n key: AuthKey,\n sig: Uint8Array,\n msg: Uint8Array\n): Promise<boolean> {\n const subtle =\n typeof globalThis.crypto !== 'undefined' && globalThis.crypto.subtle\n ? globalThis.crypto.subtle\n : null;\n if (!subtle) return false;\n try {\n return await subtle.verify(\n 'Ed25519',\n key as CryptoKey,\n toArrayBuffer(sig),\n toArrayBuffer(msg)\n );\n } catch {\n return false;\n }\n}\n\n/** The signed fields, in the order me.ochk.io encodes them. */\nconst SIGNED_FIELDS = [\n 'v',\n 'kind',\n 'did_oc',\n 'event_count',\n 'human_event_count',\n 'lifetime_sats',\n 'distinct_integrator_count',\n 'oldest_event_at',\n 'active_days',\n 'computed_at',\n 'expires_at',\n] as const;\nconst COUNTS = [\n 'event_count',\n 'human_event_count',\n 'lifetime_sats',\n 'distinct_integrator_count',\n 'active_days',\n] as const;\n\n/** The attestation the signature covers, read from the signed bytes, or\n * null when they are not one in canonical form. */\nfunction readSignedAttestation(canonical: Uint8Array, id: string): ActivityAttestation | null {\n const text = new TextDecoder().decode(canonical);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;\n const o = parsed as Record<string, unknown>;\n if (o.v !== 1 || o.kind !== 'oc-me-activity' || typeof o.did_oc !== 'string') return null;\n const countsOk = COUNTS.every((k) => {\n const n = o[k];\n return typeof n === 'number' && Number.isSafeInteger(n) && n >= 0;\n });\n if (!countsOk) return null;\n if (o.oldest_event_at !== null && typeof o.oldest_event_at !== 'string') return null;\n if (typeof o.computed_at !== 'string' || typeof o.expires_at !== 'string') return null;\n const ordered = Object.fromEntries(SIGNED_FIELDS.map((k) => [k, o[k]]));\n // Only the canonical encoding counts: no extra keys, no reordering, no whitespace.\n if (JSON.stringify(ordered) !== text) return null;\n return { id, ...(ordered as Omit<ActivityAttestation, 'id'>) };\n}\n\n/** True when every field of the readable copy equals the signed value. */\nfunction sameAttestation(copy: ActivityAttestation, signed: ActivityAttestation): boolean {\n const c = copy as unknown as Record<string, unknown>;\n const v = signed as unknown as Record<string, unknown>;\n return (['id', ...SIGNED_FIELDS] as const).every((k) => c[k] === v[k]);\n}\n\n/**\n * Verify a signed activity attestation bundle. Returns a typed\n * ActivityVerifyResult with per-check detail · never throws (network\n * + parse failures surface as ok=false rows in the checks array, so\n * the caller can log them without try/catch).\n *\n * Checks, in order: bundle shape, the signed bytes decode and are an\n * attestation in canonical form, the readable copy (when given) equals\n * them, JWK with matching kid present, ed25519 signature, freshness.\n * `attestation` in the result is read from the signed bytes, and is set\n * only when every check passes.\n */\nexport async function verifyActivityAttestation(\n bundle: ActivityAttestationBundle,\n options: VerifyActivityOptions = {}\n): Promise<ActivityVerifyResult> {\n const checks: ActivityVerifyCheck[] = [];\n\n // 1. Bundle shape\n const shapeOk =\n !!bundle &&\n typeof bundle === 'object' &&\n typeof bundle.sig === 'string' &&\n typeof bundle.kid === 'string' &&\n typeof bundle.canonical_b64 === 'string' &&\n (bundle.attestation === undefined ||\n (!!bundle.attestation && typeof bundle.attestation === 'object'));\n checks.push({\n ok: shapeOk,\n label: 'bundle shape · sig / kid / canonical_b64',\n });\n if (!shapeOk) {\n return { ok: false, reason: 'bundle shape invalid', checks };\n }\n\n // 2. canonical_b64 decodes\n const canonical = base64ToBytes(bundle.canonical_b64);\n checks.push({\n ok: canonical !== null,\n label: 'canonical_b64 decodes',\n detail: canonical ? `${canonical.length} bytes` : 'invalid base64',\n });\n if (!canonical) return { ok: false, reason: 'canonical_b64 invalid base64', checks };\n\n // 3. The signed bytes are an attestation, and the readable copy says the same\n const computedId = bytesToHex(await sha256(canonical));\n const signed = readSignedAttestation(canonical, computedId);\n checks.push({\n ok: signed !== null,\n label: 'canonical_bytes are an oc-me-activity attestation in canonical form',\n });\n if (!signed) return { ok: false, reason: 'canonical bytes are not an activity attestation', checks };\n\n const copy = bundle.attestation;\n const copyOk = copy === undefined || sameAttestation(copy, signed);\n checks.push({\n ok: copyOk,\n label: 'attestation === the signed bytes, id = sha256(canonical_bytes)',\n detail: copyOk ? computedId : 'the readable copy differs from what was signed',\n });\n if (!copyOk) return { ok: false, reason: 'attestation does not match the signed bytes', checks };\n\n // 4. JWK lookup + ed25519 verify\n let key: AuthKey | null = null;\n if (options.jwk) {\n if (options.jwk.kid !== bundle.kid) {\n checks.push({\n ok: false,\n label: 'JWK with matching kid present',\n detail: `provided jwk.kid=${options.jwk.kid} but bundle.kid=${bundle.kid}`,\n });\n return { ok: false, reason: 'kid mismatch with provided jwk', checks };\n }\n try {\n key = (await importJWK(options.jwk, 'EdDSA')) as AuthKey;\n checks.push({ ok: true, label: 'JWK with matching kid present', detail: `kid ${bundle.kid} (provided)` });\n } catch (err) {\n checks.push({\n ok: false,\n label: 'JWK with matching kid present',\n detail: `provided jwk failed import: ${(err as Error).message}`,\n });\n return { ok: false, reason: 'provided jwk failed import', checks };\n }\n } else {\n const issuer = options.issuer ?? DEFAULT_ISSUER;\n const ttl = options.jwksCacheTtlMs ?? DEFAULT_TTL_MS;\n const maxStale = options.jwksMaxStaleMs ?? DEFAULT_MAX_STALE_MS;\n try {\n let entry = await fetchEnvelopeJwks(issuer, ttl, maxStale);\n key = entry.keys[bundle.kid] ?? null;\n if (!key && Date.now() - (lastForcedRefresh.get(issuer) ?? 0) >= FORCED_REFRESH_MIN_INTERVAL_MS) {\n // Cache miss · likely a rotation. Refetch, at most once a minute.\n lastForcedRefresh.set(issuer, Date.now());\n entry = await fetchEnvelopeJwks(issuer, 0, maxStale);\n key = entry.keys[bundle.kid] ?? null;\n }\n checks.push({\n ok: !!key,\n label: 'JWK with matching kid present',\n detail: key ? `kid ${bundle.kid}` : `no JWK with kid ${bundle.kid} at ${issuer}${ENVELOPE_JWKS_PATH}`,\n });\n if (!key) {\n return { ok: false, reason: `kid ${bundle.kid} not in envelope JWKS`, checks };\n }\n } catch (err) {\n checks.push({\n ok: false,\n label: 'JWK with matching kid present',\n detail: `envelope JWKS unavailable: ${(err as Error).message}`,\n });\n return {\n ok: false,\n reason: `envelope JWKS unavailable: ${(err as Error).message}`,\n checks,\n };\n }\n }\n\n const sigBytes = hexToBytes(bundle.sig);\n if (!sigBytes) {\n checks.push({\n ok: false,\n label: 'ed25519.verify(sig, canonical_bytes, jwk.public)',\n detail: 'malformed sig (expected hex)',\n });\n return { ok: false, reason: 'malformed sig', checks };\n }\n const sigOk = await verifyEd25519(key, sigBytes, canonical);\n checks.push({\n ok: sigOk,\n label: 'ed25519.verify(sig, canonical_bytes, jwk.public)',\n detail: sigOk ? 'signature valid' : 'signature does not match',\n });\n if (!sigOk) return { ok: false, reason: 'signature does not match', checks };\n\n // 5. Freshness, from the signed expiry\n const now = options.now ?? new Date();\n const expiresMs = Date.parse(signed.expires_at);\n const freshOk = Number.isFinite(expiresMs) && expiresMs > now.getTime();\n checks.push({\n ok: freshOk,\n label: 'now < attestation.expires_at',\n detail: freshOk\n ? `expires ${new Date(expiresMs).toISOString()}`\n : 'attestation has expired',\n });\n if (!freshOk) return { ok: false, reason: 'attestation has expired', checks };\n\n return { ok: true, attestation: signed, checks };\n}\n\n/** Force-refresh the envelope-JWKS cache · useful after a key rotation\n * if you don't want to wait for the TTL to expire. */\nexport async function refreshEnvelopeJwks(issuer = DEFAULT_ISSUER): Promise<void> {\n jwksCache.delete(issuer);\n await fetchEnvelopeJwks(issuer, DEFAULT_TTL_MS);\n}\n\nexport const identity = {\n verifyActivityAttestation,\n refreshEnvelopeJwks,\n};\n","/**\n * OC Connect from a site's own backend: the site keeps its own login and makes\n * an orangecheck account for its user with one call (ochk.io/docs/connect).\n *\n * connectProvision({ apiKey, userId, consent? }) → { ok, did_oc, is_new }\n * connectClaimLink({ apiKey, userId }) → { ok, url, expires_at }\n * connectDelete({ apiKey, userId }) → { ok, result }\n *\n * A refusal or an outage is a result (`{ ok: false, reason, status }`), never a\n * throw, so a failed call can't block the site's own login. Only a mistake in\n * the call itself throws, before anything is sent: an option it does not read,\n * a missing key or user id, or `consent: false`.\n *\n * They refuse to run where there is a `document`, as a hint for the most common\n * mistake. That is not a guard: a browser Web Worker has no `document`. What\n * keeps the key safe is importing these only from `/server` code that never\n * reaches a client bundle.\n */\n\n/** The only place a call goes: the key never travels anywhere else. */\nconst ORIGIN = 'https://ochk.io';\nconst DEFAULT_TIMEOUT_MS = 5000;\nconst MAX_TIMEOUT_MS = 30_000;\nconst DID_OC = /^did:oc:[0-9a-f]{32}$/;\n\nexport interface ConnectOptions {\n /** Your Connect API key (ochk.app → your project → Sign-in → Your own login). Server only. */\n apiKey: string;\n /** Your own stable id for this user, 1 to 256 characters. */\n userId: string;\n /** Answer `unavailable` after this long. Default 5000, at most 30000. */\n timeoutMs?: number;\n}\n\nexport interface ConnectProvisionOptions extends ConnectOptions {\n /**\n * `true` only when the person ticked your \"Also create my orangecheck\n * account\" box just now. Recorded once. Leave it out when you show no box.\n * An unticked box means no call at all, so `false` is refused.\n */\n consent?: true;\n /** The user's email. ochk.io keeps it only as a keyed hash. */\n email?: string;\n /** `true` when you verified `email` yourself (a code or a link they answered). */\n emailVerified?: boolean;\n}\n\n/**\n * Why ochk.io did not answer with an account. `unavailable` covers an outage, a\n * timeout and any answer this SDK can't read: try again later.\n */\nexport type ConnectProvisionRefusal =\n | 'account_deleted'\n | 'daily_limit'\n | 'rate_limited'\n | 'invalid_api_key'\n | 'app_suspended'\n | 'bad_request'\n | 'unavailable';\nexport type ConnectDeleteRefusal =\n | 'unknown_user'\n | 'holds_earnings'\n | 'not_deletable'\n | 'rate_limited'\n | 'invalid_api_key'\n | 'bad_request'\n | 'unavailable';\nexport type ConnectClaimLinkRefusal =\n | 'unknown_user'\n | 'already_claimed'\n | 'rate_limited'\n | 'invalid_api_key'\n | 'app_suspended'\n | 'bad_request'\n | 'unavailable';\n\n/** A refusal: `status` is ochk.io's HTTP status, 0 when nothing came back. */\nexport interface ConnectRefused<R extends string> {\n ok: false;\n reason: R;\n status: number;\n}\n\nexport type ConnectProvisionResult =\n | { ok: true; did_oc: string; is_new: boolean }\n | ConnectRefused<ConnectProvisionRefusal>;\nexport type ConnectDeleteResult =\n | { ok: true; result: 'deleted' | 'detached' | 'already_deleted' }\n | ConnectRefused<ConnectDeleteRefusal>;\nexport type ConnectClaimLinkResult =\n | { ok: true; url: string; expires_at: string }\n | ConnectRefused<ConnectClaimLinkRefusal>;\n\nconst BASE_KEYS = ['apiKey', 'userId', 'timeoutMs'];\nconst PROVISION_KEYS = new Set([...BASE_KEYS, 'consent', 'email', 'emailVerified']);\nconst USER_KEYS = new Set(BASE_KEYS);\nconst PROVISION_REASONS = new Set<string>([\n 'account_deleted',\n 'daily_limit',\n 'rate_limited',\n 'invalid_api_key',\n 'app_suspended',\n 'bad_request',\n]);\nconst DELETE_REASONS = new Set<string>([\n 'unknown_user',\n 'holds_earnings',\n 'not_deletable',\n 'rate_limited',\n 'invalid_api_key',\n 'bad_request',\n]);\nconst CLAIM_LINK_REASONS = new Set<string>([\n 'unknown_user',\n 'already_claimed',\n 'rate_limited',\n 'invalid_api_key',\n 'app_suspended',\n 'bad_request',\n]);\nconst DELETE_RESULTS = new Set(['deleted', 'detached', 'already_deleted']);\n\nfunction fail(message: string): never {\n throw new TypeError(`@orangecheck/me-client: ${message}`);\n}\n\n/**\n * Check the call itself; throws on a mistake in it. Returns the options copied\n * once onto a bare object, and every later read is from that copy, so an\n * inherited `consent` (a polluted Object.prototype, or options made with\n * Object.create) is never read and a getter is read once.\n */\nfunction checkCall<O extends ConnectOptions>(name: string, options: O, known: ReadonlySet<string>): O {\n if (typeof document !== 'undefined') {\n fail(`${name} runs on your server only: in a browser your API key would be exposed`);\n }\n if (options === null || typeof options !== 'object') fail(`${name}: options must be an object`);\n const unknown = Object.keys(options).filter((k) => !known.has(k));\n if (unknown.length > 0) {\n const only = [...known].join(', ');\n fail(`${name}: unknown option ${unknown.join(', ')}. It reads only ${only}.`);\n }\n const o = Object.assign(Object.create(null) as O, options);\n if (typeof o.apiKey !== 'string' || o.apiKey.trim() === '') {\n fail(`${name}: apiKey is required (your Connect API key)`);\n }\n // ochk.io counts a user id in UTF-16 code units, as JavaScript's length does.\n const id = o.userId;\n if (typeof id !== 'string' || id.length < 1 || id.length > 256) {\n fail(`${name}: userId must be your user's id, 1 to 256 characters`);\n }\n const t = o.timeoutMs;\n if (t !== undefined && !(typeof t === 'number' && t > 0 && t <= MAX_TIMEOUT_MS)) {\n fail(`${name}: timeoutMs must be above 0 and at most ${MAX_TIMEOUT_MS}`);\n }\n return o;\n}\n\ntype Answer = { status: number; body: Record<string, unknown> | null };\n\nasync function post(\n path: string,\n apiKey: string,\n body: Record<string, unknown>,\n timeoutMs: number\n): Promise<Answer> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await fetch(`${ORIGIN}${path}`, {\n method: 'POST',\n // These endpoints never redirect, so a redirect is an error: the key and\n // the body go to ochk.io and nowhere else.\n redirect: 'error',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n let parsed: unknown = null;\n try {\n parsed = await res.json();\n } catch {\n parsed = null;\n }\n const ok = parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed);\n return { status: res.status, body: ok ? (parsed as Record<string, unknown>) : null };\n } catch {\n return { status: 0, body: null };\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction refused<R extends string>(\n answer: Answer,\n known: ReadonlySet<string>\n): ConnectRefused<R> {\n const raw = answer.body?.reason;\n const said = raw === 'missing_api_key' ? 'invalid_api_key' : raw;\n const reason = typeof said === 'string' && known.has(said) ? said : 'unavailable';\n return { ok: false, reason: reason as R, status: answer.status };\n}\n\n/**\n * Make (or find) the orangecheck account for one of your users. Idempotent:\n * the same user always gets the same `did_oc`. Call it once per user and keep\n * the `did_oc` on your user record.\n */\nexport function connectProvision(\n options: ConnectProvisionOptions\n): Promise<ConnectProvisionResult> {\n const o = checkCall('connectProvision', options, PROVISION_KEYS);\n if (o.consent !== undefined && o.consent !== true) {\n fail(\n 'connectProvision: consent must be true or left out. An unticked box means no ' +\n 'call at all; a call without consent makes an account nobody asked for'\n );\n }\n const { email, emailVerified } = o;\n if (email !== undefined && (typeof email !== 'string' || email === '')) {\n fail('connectProvision: email must be a non-empty string');\n }\n if (emailVerified !== undefined && typeof emailVerified !== 'boolean') {\n fail('connectProvision: emailVerified must be a boolean');\n }\n if (emailVerified !== undefined && email === undefined) {\n fail('connectProvision: emailVerified describes email, so pass email too');\n }\n const body: Record<string, unknown> = { user_id: o.userId };\n if (o.consent === true) body.consent = true;\n if (email !== undefined) body.email = email;\n if (emailVerified !== undefined) body.email_verified = emailVerified;\n return call('/api/connect/provision', o, body).then(\n (answer): ConnectProvisionResult => {\n const b = answer.body;\n if (answer.status !== 200) return refused(answer, PROVISION_REASONS);\n const good =\n b?.ok === true &&\n typeof b.did_oc === 'string' &&\n DID_OC.test(b.did_oc) &&\n typeof b.is_new === 'boolean';\n return good\n ? { ok: true, did_oc: b.did_oc as string, is_new: b.is_new as boolean }\n : { ok: false, reason: 'unavailable', status: 200 };\n }\n );\n}\n\n/**\n * A link for your signed-in user to claim their account at ochk.app. Good once,\n * for fifteen minutes. A link anywhere but https://ochk.app is refused\n * (`unavailable`), so you never send your user somewhere else.\n */\nexport function connectClaimLink(options: ConnectOptions): Promise<ConnectClaimLinkResult> {\n const o = checkCall('connectClaimLink', options, USER_KEYS);\n return call('/api/connect/claim-link', o, { user_id: o.userId }).then(\n (answer): ConnectClaimLinkResult => {\n const b = answer.body;\n if (answer.status !== 200) return refused(answer, CLAIM_LINK_REASONS);\n const good =\n b?.ok === true &&\n isClaimUrl(b.url) &&\n typeof b.expires_at === 'string' &&\n b.expires_at !== '';\n return good\n ? { ok: true, url: b.url as string, expires_at: b.expires_at as string }\n : { ok: false, reason: 'unavailable', status: 200 };\n }\n );\n}\n\n/** Your user deleted their account with you: delete the one Connect made for them. */\nexport function connectDelete(options: ConnectOptions): Promise<ConnectDeleteResult> {\n const o = checkCall('connectDelete', options, USER_KEYS);\n return call('/api/connect/delete', o, { user_id: o.userId }).then(\n (answer): ConnectDeleteResult => {\n const b = answer.body;\n if (answer.status !== 200) return refused(answer, DELETE_REASONS);\n return b?.ok === true && typeof b.result === 'string' && DELETE_RESULTS.has(b.result)\n ? { ok: true, result: b.result as 'deleted' | 'detached' | 'already_deleted' }\n : { ok: false, reason: 'unavailable', status: 200 };\n }\n );\n}\n\nfunction call(path: string, o: ConnectOptions, body: Record<string, unknown>): Promise<Answer> {\n return post(path, o.apiKey, body, o.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n}\n\n/** An https link on ochk.app, the only place a claim happens: no user name, password or port. */\nfunction isClaimUrl(v: unknown): v is string {\n if (typeof v !== 'string') return false;\n try {\n const url = new URL(v);\n return (\n url.protocol === 'https:' &&\n url.hostname === 'ochk.app' &&\n url.port === '' &&\n url.username === '' &&\n url.password === ''\n );\n } catch {\n return false;\n }\n}\n","/**\n * @orangecheck/me-client/connect-consent\n *\n * The words for an optional \"also make me an orangecheck account\" box on a\n * site that keeps its own login (OC Connect). Plain strings with no imports, so\n * any UI can render its own checkbox: React, Vue, a server template, plain HTML.\n *\n * import {\n * CONNECT_CONSENT_LABEL,\n * CONNECT_CONSENT_BLURB,\n * } from '@orangecheck/me-client/connect-consent';\n *\n * Show the box unticked, never pre-ticked and never bundled with your Terms.\n * Ticked: call connectProvision with `consent: true`. Unticked: make no call.\n */\n\n/** The checkbox label. */\nexport const CONNECT_CONSENT_LABEL = 'Also create my orangecheck account';\n\n/** The line under the label. */\nexport const CONNECT_CONSENT_BLURB =\n 'It stays with orangecheck until you claim it at ochk.app. Then you can use it on ' +\n 'other sites, or delete it.';\n","/**\n * Two things a site's own backend does with the token from the sign-in popup,\n * once it has verified it (ochk.io/docs/me/sdk):\n *\n * spendOnce(jti, exp, store) → true the first time, false for a repeat\n * revokeToken(token) → { ok, revoked } | { ok: false, reason, status }\n *\n * spendOnce keeps a token from starting a second session; revokeToken ends it\n * at the auth host once the site's own session has taken over. Only a mistake\n * in the call itself throws, before anything is read or sent.\n */\n\nconst DEFAULT_ISSUER = 'https://ochk.io';\nconst DEFAULT_TIMEOUT_MS = 5000;\nconst MAX_TIMEOUT_MS = 30_000;\n/** What ochk.io's /api/auth/revoke takes in one call. */\nconst MAX_TOKENS = 8;\nconst MAX_TOKEN_LENGTH = 4096;\n\nfunction fail(message: string): never {\n throw new TypeError(`@orangecheck/me-client: ${message}`);\n}\n\nconst nowSeconds = () => Math.floor(Date.now() / 1000);\n\n/**\n * Where you record the jti of each token you accepted, until it expires. Yours\n * to provide, shared by every server that accepts sign-ins: a unique row in your\n * database, or Redis `SET jti 1 NX EXAT exp`. `add` must be atomic: true when\n * it recorded the jti, false when the jti was there already.\n */\nexport interface JtiStore {\n add(jti: string, exp: number): boolean | Promise<boolean>;\n}\n\n/**\n * A {@link JtiStore} in this process's memory: for tests and a single process.\n * Two servers, or a restart, each have their own, so a token could start a\n * session on each: in production, use a store they share.\n */\nexport class MemoryJtiStore implements JtiStore {\n private readonly spent = new Map<string, number>();\n\n add(jti: string, exp: number): boolean {\n const now = nowSeconds();\n for (const [k, until] of this.spent) if (until <= now) this.spent.delete(k);\n if (this.spent.has(jti)) return false;\n this.spent.set(jti, exp);\n return true;\n }\n}\n\n/**\n * Spend a verified token's `jti` so it starts one session: true the first time,\n * false for a repeat or a token that has expired (`exp`, in seconds, at or\n * before now). Call it after verifying the token and before starting your own\n * session; on false, refuse the sign-in. A store that fails throws, so the\n * sign-in fails closed.\n */\nexport function spendOnce(jti: string, exp: number, store: JtiStore): Promise<boolean> {\n if (typeof jti !== 'string' || jti === '') fail('spendOnce: jti must be one non-empty string');\n if (typeof exp !== 'number' || !Number.isFinite(exp)) {\n fail(\"spendOnce: exp must be the token's expiry, in seconds\");\n }\n if (store === null || typeof store !== 'object' || typeof store.add !== 'function') {\n fail('spendOnce: store must have add(jti, exp)');\n }\n if (exp <= nowSeconds()) return Promise.resolve(false);\n return Promise.resolve()\n .then(() => store.add(jti, exp))\n .then((spent) => {\n if (typeof spent !== 'boolean') fail('spendOnce: store.add must answer true or false');\n return spent;\n });\n}\n\nexport interface RevokeTokenOptions {\n /** The auth host that issued the token. Default https://ochk.io. */\n issuer?: string;\n /** Answer `unavailable` after this long. Default 5000, at most 30000. */\n timeoutMs?: number;\n}\n\n/**\n * Why ochk.io did not end the tokens. `unavailable` covers an outage, a timeout\n * and any answer this SDK can't read: the token still ends when it expires.\n */\nexport type RevokeTokenRefusal = 'rate_limited' | 'bad_request' | 'unavailable';\n\n/**\n * `revoked` counts the tokens ochk.io ended: 0 when it could not read one as\n * its own (expired already, or signed elsewhere). A refusal's `status` is\n * ochk.io's HTTP status, 0 when nothing came back.\n */\nexport type RevokeTokenResult =\n | { ok: true; revoked: number }\n | { ok: false; reason: RevokeTokenRefusal; status: number };\n\nconst REVOKE_OPTIONS: ReadonlySet<string> = new Set<keyof RevokeTokenOptions>(['issuer', 'timeoutMs']);\n\n/**\n * The issuer as one origin, `scheme://host[:port]`: https, or http on this\n * machine only. A path, a query, a fragment or a user name would send the\n * tokens somewhere else on the host (or carry credentials), so each is refused.\n */\nfunction issuerOrigin(issuer: unknown): string {\n if (typeof issuer !== 'string') fail('revokeToken: issuer must be a URL');\n const refuse = (): never =>\n fail(`revokeToken: issuer must be one https origin (http only on this machine), such as https://ochk.io, got ${issuer}`);\n if (/[?#@\\\\]/.test(issuer)) refuse();\n let url: URL;\n try {\n url = new URL(issuer);\n } catch {\n return refuse();\n }\n const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) refuse();\n if (url.pathname !== '/' || url.search !== '' || url.hash !== '' || url.username !== '' || url.password !== '') {\n refuse();\n }\n return url.origin;\n}\n\n/**\n * End a sign-in token at the auth host (`POST /api/auth/revoke`), on every\n * site that reads the list of ended sessions. Holding a token is the authority\n * to end it; nothing else is sent. Call it once your own session has taken\n * over. Takes one token or up to eight. An outage is a result, never a throw,\n * so it can't break a sign-in.\n */\nexport function revokeToken(\n token: string | readonly string[],\n options: RevokeTokenOptions = {}\n): Promise<RevokeTokenResult> {\n if (options === null || typeof options !== 'object') fail('revokeToken: options must be an object');\n const unknown = Object.keys(options).filter((k) => !REVOKE_OPTIONS.has(k));\n if (unknown.length > 0) {\n fail(`revokeToken: unknown option ${unknown.join(', ')}. It reads only ${[...REVOKE_OPTIONS].join(', ')}.`);\n }\n const tokens = typeof token === 'string' ? [token] : Array.isArray(token) ? [...token] : null;\n if (\n !tokens ||\n tokens.length < 1 ||\n tokens.length > MAX_TOKENS ||\n !tokens.every((t) => typeof t === 'string' && t.length > 0 && t.length <= MAX_TOKEN_LENGTH)\n ) {\n fail(`revokeToken: pass one token, or 1 to ${MAX_TOKENS}, each a non-empty string of at most ${MAX_TOKEN_LENGTH} characters`);\n }\n const origin = issuerOrigin(options.issuer ?? DEFAULT_ISSUER);\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (typeof timeoutMs !== 'number' || !(timeoutMs > 0 && timeoutMs <= MAX_TIMEOUT_MS)) {\n fail(`revokeToken: timeoutMs must be above 0 and at most ${MAX_TIMEOUT_MS}`);\n }\n return post(`${origin}/api/auth/revoke`, tokens, timeoutMs);\n}\n\nasync function post(url: string, tokens: string[], timeoutMs: number): Promise<RevokeTokenResult> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await fetch(url, {\n method: 'POST',\n // The endpoint never redirects, so a redirect is an error: the tokens go\n // to the auth host and nowhere else.\n redirect: 'error',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ tokens }),\n signal: controller.signal,\n });\n let body: unknown = null;\n try {\n body = await res.json();\n } catch {\n body = null;\n }\n const b = body !== null && typeof body === 'object' ? (body as { ok?: unknown; revoked?: unknown }) : null;\n if (res.status === 200) {\n return b?.ok === true && Number.isSafeInteger(b.revoked) && (b.revoked as number) >= 0\n ? { ok: true, revoked: b.revoked as number }\n : { ok: false, reason: 'unavailable', status: 200 };\n }\n if (res.status === 429) return { ok: false, reason: 'rate_limited', status: 429 };\n if (res.status === 400) return { ok: false, reason: 'bad_request', status: 400 };\n return { ok: false, reason: 'unavailable', status: res.status };\n } catch {\n return { ok: false, reason: 'unavailable', status: 0 };\n } finally {\n clearTimeout(timer);\n }\n}\n","/**\n * After someone merges two orangecheck accounts, the one they no longer use\n * stops signing in. A token from the sign-in popup then carries `merged_rh`:\n * your site's revocation handle for each account merged in. Match it against\n * the handles you stored (every `rh` you have seen, kept with your user) to\n * keep that person's history under the account they use now.\n */\n\n/** At most this many handles ride one token; a longer claim is not read. */\nconst MERGED_HANDLES_MAX = 16;\n\n/** What a token's merged handles name in your own table. */\nexport type MergedUserMatch =\n | { kind: 'none' }\n | { kind: 'one'; user: string }\n | { kind: 'conflict'; users: string[] };\n\n/**\n * The merged handles on a session `verifyOcToken` or `checkOcSession` already\n * accepted. A claim that is not a list of at most 16 non-empty strings reads\n * as none.\n */\nexport function mergedHandles(session: { merged_rh?: unknown }): string[] {\n const v = session.merged_rh;\n if (!Array.isArray(v) || v.length > MERGED_HANDLES_MAX) return [];\n if (!v.every((h) => typeof h === 'string' && h.length > 0)) return [];\n return [...new Set(v as string[])];\n}\n\n/**\n * Which of your users this person was before a merge. Call it with a verified\n * session whose `did_oc` you have no row for. `lookup` answers the user that\n * stored a handle, or null.\n *\n * - `none`: create a user, as for anyone new.\n * - `one`: attach this `did_oc` and `rh` to that user.\n * - `conflict`: the handles name two of your users. Pick neither; log it.\n */\nexport async function matchMergedUser(\n session: { merged_rh?: unknown },\n lookup: (rh: string) => string | null | undefined | Promise<string | null | undefined>\n): Promise<MergedUserMatch> {\n const users = new Set<string>();\n for (const rh of mergedHandles(session)) {\n const user = await lookup(rh);\n if (typeof user === 'string' && user.length > 0) users.add(user);\n }\n if (users.size === 0) return { kind: 'none' };\n if (users.size === 1) return { kind: 'one', user: [...users][0]! };\n return { kind: 'conflict', users: [...users].sort() };\n}\n","/**\n * Server-side helpers: verify a sign-in token (`checkOcToken`,\n * `verifyOcToken`), check a request's session (`checkOcSession`, `withOcAuth`,\n * `ocAuthExpress`, `ocAuthHono`), end a token (`revokeToken`), spend one once\n * (`spendOnce`), and the Connect calls. The rest of the client is in\n * [`@orangecheck/me-client`](/sdk/me-client/README), and the popup in\n * [`@orangecheck/me-client/popup`](/sdk/me-client/popup/README).\n *\n * @packageDocumentation\n */\n\n/**\n * @orangecheck/me-client/server\n *\n * Server-side verification helpers for OC integrators.\n *\n * import {\n * withOcAuth,\n * getOcSession,\n * verifyOcToken,\n * verifyActivityAttestation,\n * } from '@orangecheck/me-client/server';\n *\n * Zero env vars, zero JWK handling. Internally lazy-fetches the auth\n * host's JWKS at https://ochk.io/.well-known/jwks.json and the\n * envelope JWKS at https://me.ochk.io/.well-known/oc-envelope-jwks.json,\n * caches both in-process. Integrators write code; we handle the crypto.\n *\n * Three layers of session verification, smallest to thickest:\n *\n * verifyOcToken(token) → SessionPayload | null\n * getOcSession(headers) → SessionPayload | null (cookie OR Bearer)\n * withOcAuth(handler) → Next.js Pages adapter that injects\n * req.ocSession on the request object\n * ocAuthExpress(opts?) → Express / Connect middleware\n * ocAuthHono(opts?) → Hono middleware\n *\n * OC Connect, for a site that keeps its own login (ochk.io/docs/connect):\n *\n * connectProvision({ apiKey, userId, consent? }) → { ok, did_oc, is_new }\n * connectClaimLink({ apiKey, userId }) → { ok, url, expires_at }\n * connectDelete({ apiKey, userId }) → { ok, result }\n *\n * Plus the activity-attestation verifier · for sybil-resistance gating:\n *\n * verifyActivityAttestation(bundle, opts?) → ActivityVerifyResult\n *\n * Same envelope-JWKS verification posture as the public /verify-activity\n * page; same five checks (shape / id / kid / sig / freshness). Use to\n * gate sensitive flows on cross-integrator lifetime_sats + duration +\n * distinct_count + active_days · all values are content-addressed and\n * signed.\n *\n * All thin wrappers around the same crypto primitives. Bring your own\n * framework.\n */\n\nimport {\n bondMeets,\n checkOcToken as checkOcTokenCore,\n familyRevocationCheck,\n integratorRevocationCheck,\n readBondClaim,\n readOcSessionToken,\n SAFE_METHODS,\n verifyOcToken as verifyOcTokenCore,\n type BondClaim,\n type RevocationCheck,\n type SessionPayload,\n type VerifyOcOptions,\n type SessionRequestHeaders,\n} from '@orangecheck/auth-core';\n\nexport { bondMeets, readBondClaim };\nexport type { BondClaim, SessionPayload, VerifyOcOptions };\n\n/** Why a token that verified is still not a session here. */\nexport type OcSessionRefusal = 'no_session_handle';\n\nexport interface VerifyOcTokenOptions extends VerifyOcOptions {\n /**\n * Refuse a token bound to your site (one with `aud`) that carries no `rh`,\n * its handle on your project's list of ended sessions. Without it \"sign out\n * everywhere\" can't reach the session, so it is refused by default.\n * Every token ochk.app's sign-in popup issues carries one; `false` accepts\n * one minted some other way, and then sign out everywhere does not end it.\n * A family session (no `aud`, on *.ochk.io) is not held to this: the\n * family's own feed ends it. `audience: '*'` admits family sessions too,\n * so keep it for routes that receive tokens forwarded from *.ochk.io.\n * Default: true.\n */\n requireHandle?: boolean;\n}\n\n/** A bound token with no handle, unless the site opted out. */\n// Each session this module verified, so checkSignInRule takes nothing else: a\n// claims-shaped object anyone built could carry any did and any backing.\nconst VERIFIED = new WeakSet<SessionPayload>();\nfunction vouch(session: SessionPayload): SessionPayload {\n VERIFIED.add(session);\n return session;\n}\n\n/** A family session: no aud, or an empty list, as verification with no audience accepts. */\nfunction isFamily(session: SessionPayload): boolean {\n const aud: unknown = session.aud;\n return aud === undefined || (Array.isArray(aud) && aud.length === 0);\n}\n\nfunction lacksHandle(session: SessionPayload, requireHandle: boolean | undefined): boolean {\n if (requireHandle === false || isFamily(session)) return false;\n const rh: unknown = session.rh;\n return typeof rh !== 'string' || rh.length === 0;\n}\n\nfunction checkRequireHandle(requireHandle: unknown): void {\n if (requireHandle !== undefined && typeof requireHandle !== 'boolean') {\n throw new TypeError('@orangecheck/me-client: requireHandle must be true or false');\n }\n}\n\nlet warnedHandle = false;\n\n/** Say once why a signed-in person is turned away for want of a handle. */\nfunction warnNoHandle(session: SessionPayload): void {\n if (warnedHandle) return;\n warnedHandle = true;\n console.warn(\n `[@orangecheck/me-client] a sign-in token bound to ${JSON.stringify((session as { aud?: unknown }).aud)} ` +\n 'carries no revocation handle (rh), so sign out everywhere could not end it, and it was refused ' +\n '(no_session_handle). Tokens from the ochk.app sign-in popup carry one. Pass requireHandle: false ' +\n 'only to accept tokens minted some other way.'\n );\n}\n\n/**\n * Verify a sign-in token: the signature, the issuer, expiry and, with\n * `audience`, that it was issued to your site. A token bound to your site with\n * no revocation handle is refused (see {@link VerifyOcTokenOptions.requireHandle}).\n * Null for any token that fails. It does not read the list of ended sessions:\n * `getOcSession` and the adapters do.\n */\nexport async function verifyOcToken(\n token: string,\n options: VerifyOcTokenOptions = {}\n): Promise<SessionPayload | null> {\n if (options === null || typeof options !== 'object') {\n throw new TypeError('@orangecheck/me-client: options must be an object');\n }\n const { requireHandle, ...core } = options;\n checkRequireHandle(requireHandle);\n const session = await verifyOcTokenCore(token, core);\n if (!session) return null;\n if (lacksHandle(session, requireHandle)) {\n warnNoHandle(session);\n return null;\n }\n return vouch(session);\n}\n\n/**\n * A sign-in token's check, telling one that fails from a key set that can't be\n * read. `unavailable` is an outage: answer it 503 so the client tries again,\n * never as a failed sign-in.\n */\nexport type OcTokenCheck =\n | { status: 'valid'; session: SessionPayload }\n | { status: 'invalid'; reason?: OcSessionRefusal }\n | { status: 'unavailable'; reason: 'key_set_unavailable' };\n\n/**\n * {@link verifyOcToken}, telling a token that fails from a key set that can't\n * be read (see {@link OcTokenCheck}). For the route that receives the token\n * from the sign-in popup. Throws on an option it does not read, or an issuer it\n * may not fetch from.\n */\nexport async function checkOcToken(token: string, options: VerifyOcTokenOptions = {}): Promise<OcTokenCheck> {\n if (options === null || typeof options !== 'object') {\n throw new TypeError('@orangecheck/me-client: options must be an object');\n }\n const { requireHandle, ...core } = options;\n checkRequireHandle(requireHandle);\n const checked = await checkOcTokenCore(token, core);\n if (checked.status === 'unavailable') return { status: 'unavailable', reason: 'key_set_unavailable' };\n if (checked.status === 'invalid') return { status: 'invalid' };\n if (lacksHandle(checked.session, requireHandle)) {\n warnNoHandle(checked.session);\n return { status: 'invalid', reason: 'no_session_handle' };\n }\n return { status: 'valid', session: vouch(checked.session) };\n}\n\n// Activity-attestation verifier · re-export from the identity module so\n// server-side integrators get the gating helper alongside session\n// verification without a second import path.\nexport {\n identity,\n verifyActivityAttestation,\n refreshEnvelopeJwks,\n} from './identity';\n// OC Connect: a site that keeps its own login makes an orangecheck account\n// for its user from its own backend.\nexport { connectProvision, connectClaimLink, connectDelete } from './connect';\nexport type {\n ConnectOptions,\n ConnectProvisionOptions,\n ConnectProvisionResult,\n ConnectProvisionRefusal,\n ConnectClaimLinkResult,\n ConnectClaimLinkRefusal,\n ConnectDeleteResult,\n ConnectDeleteRefusal,\n ConnectRefused,\n} from './connect';\nexport { CONNECT_CONSENT_LABEL, CONNECT_CONSENT_BLURB } from './connect-consent';\n// After a sign-in: start one session per token, then end the token at ochk.io.\nexport { spendOnce, MemoryJtiStore, revokeToken } from './tokens';\n// After an account merge: find the user this person was at your site.\nexport { matchMergedUser, mergedHandles } from './merged';\nexport type { MergedUserMatch } from './merged';\nexport type { JtiStore, RevokeTokenOptions, RevokeTokenResult, RevokeTokenRefusal } from './tokens';\nexport type {\n ActivityAttestation,\n ActivityAttestationBundle,\n ActivityVerifyCheck,\n ActivityVerifyResult,\n VerifyActivityOptions,\n} from './identity';\n\nexport interface OcSessionOptions extends VerifyOcTokenOptions {\n /**\n * The request's method. While me.ochk.io's list of ended sessions can't be\n * read, reads go on and writes are refused; with no method, a request\n * counts as a write. The adapters pass it for you.\n */\n method?: string;\n /** Your project key. Default `OC_PROJECT_KEY`. */\n projectKey?: string;\n /**\n * Where me.ochk.io is: the project's sign-in rule and its list of ended\n * sessions are read there. Default https://me.ochk.io (`OC_ME_ORIGIN` for\n * the list).\n */\n meOrigin?: string;\n /**\n * The check for sessions the person ended everywhere (sign out\n * everywhere, a passkey removed, the account deleted). Default, for a\n * token bound to your site: auth-core's `integratorRevocationCheck`, from\n * `OC_PROJECT_KEY` and `OC_SIGNING_SECRET`; none when they are unset. For a\n * family session (no `aud`, the ochk.io cookie a *.ochk.io site reads):\n * auth-core's `familyRevocationCheck`, from `OC_REVOCATION_FEED_TOKEN`, and\n * with that unset the call throws rather than read the session by its\n * signature alone (0.44.0). `false` turns the check off for both.\n */\n revocation?: RevocationCheck | false;\n}\n\n/** One check per me.ochk.io and project key, shared by every request in this process. */\nconst sessionChecks = new Map<string, RevocationCheck | null>();\nlet warnedUnchecked = false;\n\nfunction revocationFor(options: OcSessionOptions, session: SessionPayload): RevocationCheck | null {\n if (options.revocation === false) return null;\n if (options.revocation) return options.revocation;\n // A family session is ended on ochk.io's own feed, never on a project's list.\n if (isFamily(session)) {\n const token = typeof process !== 'undefined' ? process.env?.OC_REVOCATION_FEED_TOKEN?.trim() : undefined;\n if (!token) {\n throw new Error(\n '@orangecheck/me-client: a family session (no aud) is checked against ochk.io\\'s ' +\n 'revocation feed, and OC_REVOCATION_FEED_TOKEN is not set. Set it, or pass ' +\n '`revocation: false` to read family sessions by signature alone.'\n );\n }\n return familyRevocationCheck();\n }\n const key = `${options.meOrigin ?? ''} ${options.projectKey ?? ''}`;\n if (!sessionChecks.has(key)) {\n sessionChecks.set(\n key,\n integratorRevocationCheck({\n ...(options.projectKey ? { projectKey: options.projectKey } : {}),\n ...(options.meOrigin ? { meOrigin: options.meOrigin } : {}),\n })\n );\n }\n const check = sessionChecks.get(key)!;\n const production = typeof process !== 'undefined' && process.env?.NODE_ENV === 'production';\n if (!check && !warnedUnchecked && production) {\n warnedUnchecked = true;\n console.warn(\n '[@orangecheck/me-client] sessions are checked by signature only, so one the person ended ' +\n 'everywhere stays valid here until it expires. Set OC_PROJECT_KEY and OC_SIGNING_SECRET ' +\n 'to refuse it.'\n );\n }\n return check;\n}\n\n/** Tests only: forget the per-project checks and the one-time warnings. */\nexport function _resetSessionChecksForTests(): void {\n sessionChecks.clear();\n warnedUnchecked = false;\n warnedHandle = false;\n}\n\n/**\n * Verify the OC session for a request. Accepts either:\n *\n * - A Web Headers object (Hono / edge / Fetch API): `c.req.raw.headers`\n * - A plain `{ cookie, authorization }` object (Express / Next.js Pages /\n * Fastify / etc.): `{ cookie: req.headers.cookie, authorization: req.headers.authorization }`\n *\n * Reads the `oc_session` cookie first; falls back to\n * `Authorization: Bearer <token>` so cross-domain integrators (no\n * .ochk.io cookie reach) verify the same way.\n *\n * A session the person ended everywhere is refused once `OC_PROJECT_KEY` and\n * `OC_SIGNING_SECRET` are set (see {@link OcSessionOptions.revocation}).\n *\n * Returns `null` for unauthenticated requests. Throws only on an option it\n * does not read.\n */\nexport async function getOcSession(\n headers: SessionRequestHeaders | Headers,\n options: OcSessionOptions = {}\n): Promise<SessionPayload | null> {\n const checked = await checkOcSession(headers, options);\n return checked.status === 'signed_in' ? checked.session : null;\n}\n\n/** Why a session can't be told right now: the key set, or the list of ended sessions. */\nexport type OcSessionUnavailable = 'key_set_unavailable' | 'revocations_unavailable';\n\n/**\n * A request's session: signed in, signed out, or not checkable right now.\n * `reason` says why a token that verified is still signed out, or what can't\n * be read.\n */\nexport type OcSessionCheck =\n | { status: 'signed_in'; session: SessionPayload }\n | { status: 'signed_out'; reason?: OcSessionRefusal }\n | { status: 'unavailable'; reason?: OcSessionUnavailable };\n\n/**\n * `getOcSession`, telling \"signed out\" from \"can't tell right now\".\n * `unavailable` with `reason: 'key_set_unavailable'` when the request carries a\n * token and ochk.io's key set can't be read (with auth-core 2.16.0 or later),\n * and `'revocations_unavailable'` when the token verifies but me.ochk.io's list\n * of ended sessions can't vouch for this request (a write while the list can't\n * be read). A token the person ended is `signed_out`, and so is one bound to\n * your site with no revocation handle (`reason: 'no_session_handle'`, unless\n * `requireHandle: false`). The adapters answer `unavailable` with 503 and that\n * reason, so a client retries instead of signing the person out.\n */\nexport async function checkOcSession(\n headers: SessionRequestHeaders | Headers,\n options: OcSessionOptions = {}\n): Promise<OcSessionCheck> {\n checkOptions(options);\n const { issuer, jwksCacheTtlMs, jwksMaxStaleMs, audience } = options;\n const token = readOcSessionToken(headers);\n if (!token) return { status: 'signed_out' };\n const verified = await checkOcTokenCore(token, { issuer, jwksCacheTtlMs, jwksMaxStaleMs, audience });\n // An outage is never \"signed out\": the client retries.\n if (verified.status === 'unavailable') return { status: 'unavailable', reason: 'key_set_unavailable' };\n if (verified.status === 'invalid') {\n if (options.audience === undefined) warnIfAudienceMissing(headers);\n return { status: 'signed_out' };\n }\n const session = verified.session;\n if (lacksHandle(session, options.requireHandle)) {\n warnNoHandle(session);\n return { status: 'signed_out', reason: 'no_session_handle' };\n }\n const check = revocationFor(options, session);\n if (check) {\n // One read of the list, so the answer can't change between two.\n const state = await check.status(session);\n if (state === 'revoked') return { status: 'signed_out' };\n if (state === 'unverified' && !SAFE_METHODS.has((options.method ?? '').toUpperCase())) {\n return { status: 'unavailable', reason: 'revocations_unavailable' };\n }\n }\n return { status: 'signed_in', session: vouch(session) };\n}\n\nconst unavailable = (checked: { reason?: OcSessionUnavailable }) => ({\n status: 503,\n body: { ok: false, reason: checked.reason ?? 'revocations_unavailable' },\n});\n\nconst refusedFor = (checked: OcSessionCheck): OcSessionRefusal | undefined =>\n checked.status === 'signed_out' ? checked.reason : undefined;\n\nlet warnedAudience = false;\n\n/**\n * The popup issues a token bound to your site's origin. Verified with no\n * `audience`, it is refused — correctly, since a verifier with no audience\n * accepts only family sessions — and every popup sign-in would 401 with no\n * clue why. Say so, once, the first time it happens.\n */\nfunction warnIfAudienceMissing(headers: SessionRequestHeaders | Headers): void {\n if (warnedAudience) return;\n const web = typeof Headers !== 'undefined' && headers instanceof Headers;\n const auth = web ? headers.get('authorization') : (headers as SessionRequestHeaders).authorization;\n const cookie = web ? headers.get('cookie') : (headers as SessionRequestHeaders).cookie;\n // The token arrives as a Bearer, or in the oc_session cookie your own route set.\n const bearer = typeof auth === 'string' ? /^Bearer\\s+(\\S+)$/i.exec(auth.trim())?.[1] : undefined;\n const fromCookie =\n typeof cookie === 'string' ? /(?:^|;\\s*)oc_session=([^;]+)/.exec(cookie)?.[1] : undefined;\n const m = /^([^.]+)\\.([^.]+)\\./.exec(bearer ?? fromCookie ?? '');\n if (!m) return;\n try {\n const payload = JSON.parse(base64UrlToString(m[2]!)) as { aud?: unknown };\n if (payload.aud === undefined) return;\n warnedAudience = true;\n console.warn(\n `[@orangecheck/me-client] a sign-in token bound to ${JSON.stringify(payload.aud)} was refused ` +\n 'because no `audience` is configured. Pass your site origin, e.g. ' +\n \"withOcAuth(handler, { audience: 'https://your-site.example' }).\"\n );\n } catch {\n // Not a JWT we can read · nothing useful to say.\n }\n}\n\nfunction base64UrlToString(s: string): string {\n const b64 = s.replace(/-/g, '+').replace(/_/g, '/');\n if (typeof atob === 'function') return atob(b64 + '='.repeat((4 - (b64.length % 4)) % 4));\n return Buffer.from(s, 'base64url').toString('utf8');\n}\n\n// ─── Next.js Pages Router adapter ────────────────────────────────────────\n\ninterface NextApiRequestLike {\n method?: string;\n headers: { cookie?: string; authorization?: string; [k: string]: unknown };\n ocSession?: SessionPayload | null;\n}\ninterface NextApiResponseLike {\n status(code: number): NextApiResponseLike;\n json(body: unknown): unknown;\n setHeader(name: string, value: string | number | readonly string[]): unknown;\n}\n/** A request with the verified session attached: `WithOcSession<NextApiRequest>`. */\nexport type WithOcSession<Req> = Req & { ocSession?: SessionPayload | null };\n\nexport interface WithOcAuthOptions extends OcSessionOptions {\n /** When true, unauthenticated requests get a 401 + `{ok:false}` response\n * before the wrapped handler runs. Default: false — handler runs and\n * receives `req.ocSession === null`, useful when the route serves both\n * signed-in and anonymous users. */\n required?: boolean;\n /**\n * Refuse a signed-in account (403, `reason: 'bond_required'`) unless a\n * bond backs it: one unspent coin of at least `minSats`, unspent at least\n * `minDays` days, checked within `maxAgeSecs`. The app never learns the\n * coin; `req.ocSession.oc_bond.nullifier` is the same for the same coin at\n * your site, so ban that to ban the coin. Implies `required`.\n */\n requireBond?: { minSats?: number; minDays?: number; maxAgeSecs?: number };\n /**\n * Your project key. The requirement you set in the project's settings\n * (\"who can sign in\") is read from me.ochk.io within a minute of a change\n * and holds every signed-in account like `requireBond`, so you change it\n * there, not in code. A request with no session is not held to it and never\n * waits on reading it: pass `required` to answer it 401. An explicit\n * `requireBond` wins over it. Default `OC_PROJECT_KEY` for the ended-session\n * check only.\n */\n projectKey?: string;\n}\n\ntype BondNeed = NonNullable<WithOcAuthOptions['requireBond']>;\n\n/** The options the session check and the adapters read. */\nconst KNOWN_OPTIONS: ReadonlySet<string> = new Set<keyof WithOcAuthOptions>([\n 'issuer',\n 'jwksCacheTtlMs',\n 'jwksMaxStaleMs',\n 'audience',\n 'method',\n 'projectKey',\n 'meOrigin',\n 'revocation',\n 'requireHandle',\n 'required',\n 'requireBond',\n]);\nconst BOND_OPTIONS: ReadonlySet<string> = new Set<keyof BondNeed>(['minSats', 'minDays', 'maxAgeSecs']);\n\n/**\n * Throw on a key me-client does not read. Ignored, a misspelt `projectKey`\n * would skip the project's sign-in rule, a misspelt `audience` would accept\n * family sessions, and a misspelt `requireBond.minSats` would read as 0.\n */\nfunction checkOptions(options: WithOcAuthOptions): void {\n if (options === null || typeof options !== 'object') {\n throw new TypeError('@orangecheck/me-client: options must be an object');\n }\n const unknown = Object.keys(options).filter((k) => !KNOWN_OPTIONS.has(k));\n if (unknown.length > 0) {\n throw new TypeError(\n `@orangecheck/me-client: unknown option ${unknown.join(', ')}. ` +\n `It reads only ${[...KNOWN_OPTIONS].join(', ')}.`\n );\n }\n checkRequireHandle(options.requireHandle);\n const bond = options.requireBond;\n if (bond === undefined) return;\n if (bond === null || typeof bond !== 'object') {\n throw new TypeError('@orangecheck/me-client: requireBond must be an object');\n }\n const extra = Object.keys(bond).filter((k) => !BOND_OPTIONS.has(k));\n if (extra.length > 0) {\n throw new TypeError(\n `@orangecheck/me-client: requireBond: unknown option ${extra.join(', ')}. ` +\n `It reads only ${[...BOND_OPTIONS].join(', ')}.`\n );\n }\n}\n/** Where someone turned away for want of backing can back their account. */\nexport const BACK_ACCOUNT_URL = 'https://ochk.app/me/account#backing';\n/** A moment on both clocks: performance.now() and the wall clock. */\ntype Stamp = { mono: number; wall: number };\nconst stamp = (): Stamp => ({ mono: performance.now(), wall: Date.now() });\n/**\n * Time since a stamp: the longer of the two readings, so neither a wall clock\n * set back nor a pause performance.now() slept through (a suspended host) can\n * stretch a minute, a ten-second wait or the ten-minute standing.\n */\nconst since = (s: Stamp) => Math.max(performance.now() - s.mono, Date.now() - s.wall);\n/** Keys me.ochk.io answered 404 for, and when; re-checked after a minute. */\nconst unknownKeys = new Map<string, Stamp>();\nconst UNKNOWN_PROJECT = Symbol('unknown_project');\nconst POLICY_TTL_MS = 60_000;\n/** After a failed read, how long before me.ochk.io is asked again. */\nconst POLICY_RETRY_MS = 10_000;\n/** How long the last rule read stands while it can't be read again. */\nconst POLICY_MAX_STALE_MS = 600_000;\ntype ProjectRule = BondNeed | null | undefined | typeof UNKNOWN_PROJECT;\nconst policies = new Map<string, { at: Stamp | null; need: BondNeed | null; failedAt?: Stamp }>();\n/** The read in flight for each project: requests that arrive together share it. */\nconst policyReads = new Map<string, Promise<ProjectRule>>();\n\nconst isFloor = (n: unknown): n is number => Number.isSafeInteger(n) && (n as number) >= 0;\n\n/** The rule in me.ochk.io's answer, or undefined when the answer does not say one. */\nfunction readRequirement(body: unknown): BondNeed | null | undefined {\n const b = body as { ok?: unknown; require_bond?: unknown } | null;\n if (!b || typeof b !== 'object' || b.ok !== true || !('require_bond' in b)) return undefined;\n if (b.require_bond === null) return null;\n const r = b.require_bond as { min_sats?: unknown; min_days?: unknown } | undefined;\n if (!r || typeof r !== 'object' || !isFloor(r.min_sats) || !isFloor(r.min_days)) return undefined;\n return { minSats: r.min_sats, minDays: r.min_days };\n}\n\n/** The last rule read, while it is younger than ten minutes; undefined after. */\nfunction standing(slot: string): BondNeed | null | undefined {\n const hit = policies.get(slot);\n return hit?.at && since(hit.at) < POLICY_MAX_STALE_MS ? hit.need : undefined;\n}\n\n/**\n * The project's requirement, from its uncached sign-in endpoint, held a\n * minute here. (The price config is edge-cached for ten minutes: reading the\n * requirement there let a just-tightened app keep admitting unbacked accounts.)\n * When it can't be read, or the answer does not say it, the last one read\n * stands for ten minutes, and the next try waits ten seconds so an outage\n * doesn't hold every request; with none read in that time it is `undefined`,\n * and the request is refused rather than let through unchecked.\n */\nasync function projectRequirement(options: WithOcAuthOptions): Promise<ProjectRule> {\n const base = (options.meOrigin ?? 'https://me.ochk.io').replace(/\\/$/, '');\n const key = options.projectKey!;\n const slot = `${base} ${key}`;\n const unknownAt = unknownKeys.get(slot);\n if (unknownAt && since(unknownAt) < POLICY_TTL_MS) return UNKNOWN_PROJECT;\n const hit = policies.get(slot);\n if (hit?.at && since(hit.at) < POLICY_TTL_MS) return hit.need;\n if (hit?.failedAt && since(hit.failedAt) < POLICY_RETRY_MS) return standing(slot);\n let read = policyReads.get(slot);\n if (!read) {\n read = readProjectRule(base, key, slot).finally(() => policyReads.delete(slot));\n policyReads.set(slot, read);\n }\n return read;\n}\n\nasync function readProjectRule(base: string, key: string, slot: string): Promise<ProjectRule> {\n try {\n const r = await fetch(`${base}/api/integrator/${encodeURIComponent(key)}/sign-in`, {\n signal: AbortSignal.timeout(4000),\n });\n // A key that names no project is a setup mistake, not an outage: say so once.\n if (r.status === 404) {\n if (!unknownKeys.has(slot)) {\n console.error(\n `[@orangecheck/me-client] projectKey \"${key}\" is not a project. Copy yours from https://ochk.app/me/projects.`\n );\n }\n unknownKeys.set(slot, stamp());\n return UNKNOWN_PROJECT;\n }\n unknownKeys.delete(slot);\n if (!r.ok) throw new Error(`HTTP ${r.status}`);\n const need = readRequirement(await r.json());\n if (need === undefined) throw new Error('unexpected body');\n policies.set(slot, { at: stamp(), need });\n return need;\n } catch {\n // The wait counts from the failure, not from when the read began.\n const hit = policies.get(slot);\n policies.set(slot, { at: hit?.at ?? null, need: hit?.need ?? null, failedAt: stamp() });\n return standing(slot);\n }\n}\n\n/** The requirement in force: explicit, else the project's, else none. */\nasync function bondNeed(\n options: WithOcAuthOptions\n): Promise<BondNeed | null | undefined | typeof UNKNOWN_PROJECT> {\n if (options.requireBond) return options.requireBond;\n if (options.projectKey) return projectRequirement(options);\n return null;\n}\n\n/**\n * Why a session can't pass, as a status and body, or null when it can. `why`\n * names what turned a token away, so a 401 says it rather than \"unauthenticated\".\n */\nasync function refusal(\n session: SessionPayload | null,\n options: WithOcAuthOptions,\n why?: OcSessionRefusal\n): Promise<{ status: number; body: Record<string, unknown> } | null> {\n const unauthenticated = { status: 401, body: { ok: false, reason: why ?? 'unauthenticated' } };\n if (!session && options.required) return unauthenticated;\n // The project's rule is about who signs in: a request with no session is not\n // held to it, so it never waits on reading it.\n if (!session && !options.requireBond) return null;\n const need = await bondNeed(options);\n if (need === UNKNOWN_PROJECT) {\n return { status: 500, body: { ok: false, reason: 'unknown_project_key' } };\n }\n if (need === undefined) {\n return { status: 503, body: { ok: false, reason: 'bond_policy_unavailable' } };\n }\n if (!session) return need ? unauthenticated : null;\n if (need && !bondMeets(session, need)) {\n const have = readBondClaim(session);\n return {\n status: 403,\n body: {\n ok: false,\n reason: 'bond_required',\n need: {\n min_sats: need.minSats ?? 0,\n min_days: need.minDays ?? 0,\n ...(need.maxAgeSecs !== undefined ? { max_age_secs: need.maxAgeSecs } : {}),\n },\n have: have ? { sats_floor: have.sats_floor, days_floor: have.days_floor } : null,\n back_url: BACK_ACCOUNT_URL,\n },\n };\n }\n return null;\n}\n\n/** The options {@link checkSignInRule} reads. */\nexport interface SignInRuleOptions {\n /** Your project key: its \"who can sign in\" rule is read from me.ochk.io, as `withOcAuth` reads it. */\n projectKey?: string;\n /** Default `https://me.ochk.io`. */\n meOrigin?: string;\n /** An explicit floor, which wins over the project's rule. */\n requireBond?: WithOcAuthOptions['requireBond'];\n}\n\n/**\n * Whether a session meets the sign-in rule: `{ ok: true }`, or the status and\n * body the adapters answer with (403 `bond_required`, 503\n * `bond_policy_unavailable`, 500 `unknown_project_key`).\n */\nexport type SignInRuleCheck = { ok: true } | { ok: false; status: number; body: Record<string, unknown> };\n\nconst SIGN_IN_RULE_OPTIONS: ReadonlySet<string> = new Set<keyof SignInRuleOptions>([\n 'projectKey',\n 'meOrigin',\n 'requireBond',\n]);\n\n/**\n * Apply your project's \"who can sign in\" rule to a session you have already\n * verified, for a site whose own session replaces the token: `checkOcToken`\n * and `verifyOcToken` check the token, not the rule. It reads the rule with the\n * same one-minute cache and ten-minute stand-in as `withOcAuth`, and refuses\n * rather than lets in when no rule could be read.\n *\n * `session` is the object `verifyOcToken`, `checkOcToken`, `getOcSession` or\n * an adapter (`req.ocSession`) returned, as is. Anything else throws, a copy or\n * claims read back from your own store included: apply the rule in the route\n * that starts your session, where you hold the verified one. It also throws\n * on a missing rule or an option it does not read.\n *\n * const session = await verifyOcToken(token, { audience: 'https://your-site.example' });\n * if (!session) return res.status(401).json({ ok: false });\n * const checked = await checkSignInRule(session, { projectKey: process.env.OC_PROJECT_KEY! });\n * if (!checked.ok) return res.status(checked.status).json(checked.body);\n */\nexport async function checkSignInRule(\n session: SessionPayload,\n options: SignInRuleOptions\n): Promise<SignInRuleCheck> {\n if (options === null || typeof options !== 'object') {\n throw new TypeError('@orangecheck/me-client: options must be an object');\n }\n const unknown = Object.keys(options).filter((k) => !SIGN_IN_RULE_OPTIONS.has(k));\n if (unknown.length > 0) {\n throw new TypeError(\n `@orangecheck/me-client: unknown option ${unknown.join(', ')}. ` +\n `It reads only ${[...SIGN_IN_RULE_OPTIONS].join(', ')}.`\n );\n }\n checkOptions(options);\n if (!options.projectKey && !options.requireBond) {\n throw new TypeError('@orangecheck/me-client: checkSignInRule needs projectKey or requireBond');\n }\n if (session === null || typeof session !== 'object' || !VERIFIED.has(session)) {\n throw new TypeError(\n '@orangecheck/me-client: checkSignInRule takes the session verifyOcToken, checkOcToken or ' +\n 'getOcSession returned, as is, not claims read some other way'\n );\n }\n const refused = await refusal(session, options);\n return refused ? { ok: false, status: refused.status, body: refused.body } : { ok: true };\n}\n\n/**\n * Wrap a Next.js Pages-Router API route handler. Adds `req.ocSession` —\n * the verified SessionPayload, or null when unauthenticated.\n *\n * // pages/api/me/profile.ts\n * import { withOcAuth } from '@orangecheck/me-client/server';\n *\n * export default withOcAuth(async (req, res) => {\n * if (!req.ocSession) return res.status(401).json({ ok: false });\n * res.status(200).json({ account: { address: req.ocSession.did_oc } });\n * }, { required: true, audience: 'https://your-site.example' });\n *\n * `audience` is your own origin. The sign-in popup issues each site a token\n * bound to it; a site on *.ochk.io that reads the family cookie omits it.\n *\n * `Cache-Control: no-store, private` and `Vary: Cookie, Authorization`\n * are set on every authenticated response — without them a cached 401\n * leaks anonymous to authenticated callers.\n */\nexport function withOcAuth<\n Req extends NextApiRequestLike = NextApiRequestLike,\n Res extends NextApiResponseLike = NextApiResponseLike,\n>(\n handler: (req: WithOcSession<Req>, res: Res) => unknown,\n options: WithOcAuthOptions = {}\n): (req: Req, res: Res) => Promise<unknown> {\n checkOptions(options);\n return async (req: Req, res: Res) => {\n res.setHeader('Cache-Control', 'no-store, private');\n res.setHeader('Vary', 'Cookie, Authorization');\n const checked = await checkOcSession(\n {\n cookie: typeof req.headers.cookie === 'string' ? req.headers.cookie : null,\n authorization:\n typeof req.headers.authorization === 'string'\n ? req.headers.authorization\n : null,\n },\n { ...options, method: req.method }\n );\n const session = checked.status === 'signed_in' ? checked.session : null;\n const withSession = req as WithOcSession<Req>;\n withSession.ocSession = session;\n const refused =\n checked.status === 'unavailable'\n ? unavailable(checked)\n : await refusal(session, options, refusedFor(checked));\n if (refused) return res.status(refused.status).json(refused.body);\n return handler(withSession, res);\n };\n}\n\n// ─── Express / Connect middleware ────────────────────────────────────────\n\n// `req.ocSession` on Express's own Request type, so `ocAuthExpress()` routes\n// type-check without a cast. Inert when @types/express is absent.\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n ocSession?: SessionPayload | null;\n }\n }\n}\n\n/** Hono env for `ocAuthHono()`: `new Hono<OcHonoEnv>()` types `c.get('ocSession')`. */\nexport type OcHonoEnv = { Variables: { ocSession: SessionPayload | null } };\n\ninterface ExpressRequestLike {\n method?: string;\n headers: { cookie?: string; authorization?: string; [k: string]: unknown };\n ocSession?: SessionPayload | null;\n}\ninterface ExpressResponseLike {\n status(code: number): ExpressResponseLike;\n json(body: unknown): unknown;\n setHeader(name: string, value: string | number | readonly string[]): unknown;\n}\ntype ExpressNextLike = (err?: unknown) => void;\n\n/**\n * Express / Connect middleware. Attaches `req.ocSession` (verified\n * SessionPayload | null) and calls next(). Use it as a global middleware\n * or per-route.\n *\n * import express from 'express';\n * import { ocAuthExpress } from '@orangecheck/me-client/server';\n *\n * const app = express();\n * app.use(ocAuthExpress());\n *\n * app.get('/api/profile', (req, res) => {\n * if (!req.ocSession) return res.status(401).json({ error: 'sign in' });\n * res.json({ address: req.ocSession.did_oc });\n * });\n *\n * Pass `{ required: true }` to short-circuit unauthenticated requests\n * with a 401 before they reach your handler.\n */\nexport function ocAuthExpress(options: WithOcAuthOptions = {}) {\n checkOptions(options);\n return async (req: ExpressRequestLike, res: ExpressResponseLike, next: ExpressNextLike) => {\n try {\n res.setHeader('Cache-Control', 'no-store, private');\n res.setHeader('Vary', 'Cookie, Authorization');\n const checked = await checkOcSession(\n {\n cookie: typeof req.headers.cookie === 'string' ? req.headers.cookie : null,\n authorization:\n typeof req.headers.authorization === 'string'\n ? req.headers.authorization\n : null,\n },\n { ...options, method: req.method }\n );\n const session = checked.status === 'signed_in' ? checked.session : null;\n req.ocSession = session;\n const refused =\n checked.status === 'unavailable'\n ? unavailable(checked)\n : await refusal(session, options, refusedFor(checked));\n if (refused) {\n res.status(refused.status).json(refused.body);\n return;\n }\n next();\n } catch (err) {\n next(err);\n }\n };\n}\n\n// ─── Hono middleware ─────────────────────────────────────────────────────\n\ninterface HonoContextLike {\n req: { raw: { headers: Headers; method?: string } };\n set(key: string, value: unknown): void;\n json(body: unknown, status?: number): unknown;\n header(name: string, value: string): void;\n}\ntype HonoNextLike = () => Promise<void>;\n\n/**\n * Hono middleware. Attaches the verified session at `c.get('ocSession')`.\n *\n * import { Hono } from 'hono';\n * import { ocAuthHono, type OcHonoEnv } from '@orangecheck/me-client/server';\n *\n * const app = new Hono<OcHonoEnv>();\n * app.use('*', ocAuthHono());\n *\n * app.get('/api/profile', (c) => {\n * const session = c.get('ocSession');\n * if (!session) return c.json({ error: 'sign in' }, 401);\n * return c.json({ address: session.did_oc });\n * });\n */\nexport function ocAuthHono(options: WithOcAuthOptions = {}) {\n checkOptions(options);\n return async (c: HonoContextLike, next: HonoNextLike) => {\n c.header('Cache-Control', 'no-store, private');\n c.header('Vary', 'Cookie, Authorization');\n const checked = await checkOcSession(c.req.raw.headers, {\n ...options,\n method: c.req.raw.method,\n });\n const session = checked.status === 'signed_in' ? checked.session : null;\n c.set('ocSession', session);\n const refused =\n checked.status === 'unavailable'\n ? unavailable(checked)\n : await refusal(session, options, refusedFor(checked));\n if (refused) return c.json(refused.body, refused.status);\n await next();\n };\n}\n"]}
1
+ {"version":3,"sources":["../node_modules/jose/dist/webapi/lib/buffer_utils.js","../node_modules/jose/dist/webapi/util/errors.js","../node_modules/jose/dist/webapi/util/base64url.js","../node_modules/jose/dist/webapi/lib/validate.js","../node_modules/jose/dist/webapi/lib/key.js","../node_modules/jose/dist/webapi/lib/key_descriptor.js","../node_modules/jose/dist/webapi/lib/jwe_algorithms.js","../node_modules/jose/dist/webapi/lib/jws_algorithms.js","../node_modules/jose/dist/webapi/lib/key_algorithm.js","../node_modules/jose/dist/webapi/key/import.js","../src/identity.ts","../src/connect.ts","../src/connect-consent.ts","../src/tokens.ts","../src/native.ts","../src/merged.ts","../src/server.ts"],"names":["sig","DEFAULT_ISSUER","DEFAULT_TIMEOUT_MS","MAX_TIMEOUT_MS","fail","post","unavailable","verifyOcTokenCore","checkOcTokenCore","familyRevocationCheck","integratorRevocationCheck","readOcSessionToken","SAFE_METHODS","bondMeets","readBondClaim","refused"],"mappings":";;;;;;;;;AAAgB,IAAI,WAAA;AAApB,IAAmC,OAAA,GAAU,IAAI,WAAA,EAAY;AAAmB,IAAI,WAAA,CAAY,SAAS,EAAE,KAAA,EAAO,MAAI;AA8CtH,SAAS,YAAA,CAAa,OAAA,EAAS,GAAA,GAAM,KAAA,EAAI;AACvC,EAAA,IAAI,UAAA,CAAW,UAAA;AACb,I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AA,IAAIA,UAAS,OAAO,CAAA,CAAE,KAAKA,QAAAA,CAAQ,IAAA,EAAMA,SAAQ,MAAM,CAAA;AACvD,IAAA,MAAM,IAAA,EAAK;AAAA,EACf,CAAA;AACJ","file":"server.js","sourcesContent":["const encoder = new TextEncoder(), decoder = new TextDecoder(), strictDecoder = new TextDecoder(\"utf-8\", { fatal: !0 }), UINT32_RANGE = 2 ** 32;\nfunction concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0), buf = new Uint8Array(size);\n let i = 0;\n for (const buffer of buffers)\n buf.set(buffer, i), i += buffer.length;\n return buf;\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= UINT32_RANGE)\n throw new RangeError(`value must be >= 0 and <= ${UINT32_RANGE - 1}. Received ${value}`);\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset);\n}\nfunction uint64be(value) {\n const high = Math.floor(value / UINT32_RANGE), low = value % UINT32_RANGE, buf = new Uint8Array(8);\n return writeUInt32BE(buf, high, 0), writeUInt32BE(buf, low, 4), buf;\n}\nfunction uint32be(value) {\n const buf = new Uint8Array(4);\n return writeUInt32BE(buf, value), buf;\n}\nconst NON_ASCII = /[^\\x00-\\x7f]/;\nfunction encode(string) {\n if (typeof string == \"string\" && string.length >= 128) {\n if (NON_ASCII.test(string))\n throw new TypeError(\"non-ASCII string encountered in encode()\");\n return encoder.encode(string);\n }\n const bytes = new Uint8Array(string.length);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code > 127)\n throw new TypeError(\"non-ASCII string encountered in encode()\");\n bytes[i] = code;\n }\n return bytes;\n}\nfunction encodeBase64(input, url = !1) {\n if (Uint8Array.prototype.toBase64)\n return input.toBase64({ alphabet: url ? \"base64url\" : \"base64\", omitPadding: url });\n const CHUNK_SIZE = 32768, arr = [];\n for (let i = 0; i < input.length; i += CHUNK_SIZE)\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n const encoded = btoa(arr.join(\"\"));\n return url ? encoded.replace(/=/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\") : encoded;\n}\nfunction decodeBase64(encoded, url = !1) {\n if (Uint8Array.fromBase64)\n return Uint8Array.fromBase64(encoded, { alphabet: url ? \"base64url\" : \"base64\" });\n if (url) {\n if (encoded.includes(\"+\") || encoded.includes(\"/\"))\n throw new TypeError(\"Invalid base64url\");\n encoded = encoded.replace(/-/g, \"+\").replace(/_/g, \"/\");\n }\n const binary = atob(encoded), bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\nasync function digest(algorithm, data) {\n const subtleDigest = `SHA-${algorithm.slice(-3)}`;\n return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));\n}\nexport {\n concat,\n decodeBase64,\n decoder,\n digest,\n encode,\n encodeBase64,\n encoder,\n strictDecoder,\n uint32be,\n uint64be\n};\n","class JOSEError extends Error {\n static code = \"ERR_JOSE_GENERIC\";\n code = \"ERR_JOSE_GENERIC\";\n constructor(message, options) {\n super(message, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);\n }\n}\nclass JWTClaimValidationFailed extends JOSEError {\n static code = \"ERR_JWT_CLAIM_VALIDATION_FAILED\";\n code = \"ERR_JWT_CLAIM_VALIDATION_FAILED\";\n claim;\n reason;\n payload;\n constructor(message, payload, claim = \"unspecified\", reason = \"unspecified\") {\n super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;\n }\n}\nclass JWTExpired extends JOSEError {\n static code = \"ERR_JWT_EXPIRED\";\n code = \"ERR_JWT_EXPIRED\";\n claim;\n reason;\n payload;\n constructor(message, payload, claim = \"unspecified\", reason = \"unspecified\") {\n super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;\n }\n}\nclass JOSEAlgNotAllowed extends JOSEError {\n static code = \"ERR_JOSE_ALG_NOT_ALLOWED\";\n code = \"ERR_JOSE_ALG_NOT_ALLOWED\";\n}\nclass JOSENotSupported extends JOSEError {\n static code = \"ERR_JOSE_NOT_SUPPORTED\";\n code = \"ERR_JOSE_NOT_SUPPORTED\";\n}\nclass JWEDecryptionFailed extends JOSEError {\n static code = \"ERR_JWE_DECRYPTION_FAILED\";\n code = \"ERR_JWE_DECRYPTION_FAILED\";\n constructor(message = \"decryption operation failed\", options) {\n super(message, options);\n }\n}\nclass JWEInvalid extends JOSEError {\n static code = \"ERR_JWE_INVALID\";\n code = \"ERR_JWE_INVALID\";\n}\nclass JWSInvalid extends JOSEError {\n static code = \"ERR_JWS_INVALID\";\n code = \"ERR_JWS_INVALID\";\n}\nclass JWTInvalid extends JOSEError {\n static code = \"ERR_JWT_INVALID\";\n code = \"ERR_JWT_INVALID\";\n}\nclass JWKInvalid extends JOSEError {\n static code = \"ERR_JWK_INVALID\";\n code = \"ERR_JWK_INVALID\";\n}\nclass JWKSInvalid extends JOSEError {\n static code = \"ERR_JWKS_INVALID\";\n code = \"ERR_JWKS_INVALID\";\n}\nclass JWKSNoMatchingKey extends JOSEError {\n static code = \"ERR_JWKS_NO_MATCHING_KEY\";\n code = \"ERR_JWKS_NO_MATCHING_KEY\";\n constructor(message = \"no applicable key found in the JSON Web Key Set\", options) {\n super(message, options);\n }\n}\nclass JWKSMultipleMatchingKeys extends JOSEError {\n [Symbol.asyncIterator] = async function* () {\n };\n static code = \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\";\n code = \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\";\n constructor(message = \"multiple matching keys found in the JSON Web Key Set\", options) {\n super(message, options);\n }\n}\nclass JWKSTimeout extends JOSEError {\n static code = \"ERR_JWKS_TIMEOUT\";\n code = \"ERR_JWKS_TIMEOUT\";\n constructor(message = \"request timed out\", options) {\n super(message, options);\n }\n}\nclass JWSSignatureVerificationFailed extends JOSEError {\n static code = \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\";\n code = \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\";\n constructor(message = \"signature verification failed\", options) {\n super(message, options);\n }\n}\nexport {\n JOSEAlgNotAllowed,\n JOSEError,\n JOSENotSupported,\n JWEDecryptionFailed,\n JWEInvalid,\n JWKInvalid,\n JWKSInvalid,\n JWKSMultipleMatchingKeys,\n JWKSNoMatchingKey,\n JWKSTimeout,\n JWSInvalid,\n JWSSignatureVerificationFailed,\n JWTClaimValidationFailed,\n JWTExpired,\n JWTInvalid\n};\n","import { encoder, decoder, encodeBase64, decodeBase64 } from \"../lib/buffer_utils.js\";\nconst invalid = \"The input to be decoded is not correctly encoded.\";\nfunction decode(input) {\n try {\n return decodeBase64(typeof input == \"string\" ? input : decoder.decode(input), !0);\n } catch (cause) {\n throw new TypeError(invalid, { cause });\n }\n}\nfunction encode(input) {\n return encodeBase64(typeof input == \"string\" ? encoder.encode(input) : input, !0);\n}\nexport {\n decode,\n encode\n};\n","import { JOSENotSupported, JWSInvalid } from \"../util/errors.js\";\nimport { decode } from \"../util/base64url.js\";\nimport { encode, strictDecoder } from \"./buffer_utils.js\";\nfunction assertUint8Array(input, label) {\n if (!(input instanceof Uint8Array))\n throw new TypeError(`${label} must be an instance of Uint8Array`);\n}\nfunction isObject(input) {\n if (typeof input != \"object\" || input === null || Object.prototype.toString.call(input) !== \"[object Object]\")\n return !1;\n const prototype = Object.getPrototypeOf(input);\n return prototype === null || Object.getPrototypeOf(prototype) === null;\n}\nfunction isJwkSet(input) {\n return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject);\n}\nfunction isDisjoint(...headers) {\n const parameters = /* @__PURE__ */ new Set();\n for (const header of headers)\n if (header)\n for (const parameter of Object.keys(header)) {\n if (parameters.has(parameter))\n return !1;\n parameters.add(parameter);\n }\n return !0;\n}\nfunction assertNotSet(value, name) {\n if (value !== void 0)\n throw new TypeError(`${name} can only be called once`);\n}\nfunction decodeBase64url(value, label, ErrorClass) {\n try {\n return decode(value);\n } catch (cause) {\n throw new ErrorClass(`Failed to base64url decode the ${label}`, { cause });\n }\n}\nfunction encodeAsciiMember(value, label, ErrorClass) {\n try {\n return encode(value);\n } catch (cause) {\n throw new ErrorClass(`The ${label} is not a valid base64url string`, { cause });\n }\n}\nfunction parseJoseHeader(encodedProtectedHeader, ErrorClass, message) {\n let parsed;\n try {\n parsed = JSON.parse(strictDecoder.decode(decode(encodedProtectedHeader)));\n } catch (cause) {\n throw new ErrorClass(message, { cause });\n }\n if (!isObject(parsed))\n throw new ErrorClass(message);\n return parsed;\n}\nconst JWS_RECOGNIZED = { __proto__: null, b64: !0 }, JWE_RECOGNIZED = { __proto__: null };\nfunction validateAlgorithms(option, algorithms) {\n if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != \"string\")))\n throw new TypeError(`\"${option}\" option must be an array of strings`);\n return algorithms === void 0 ? void 0 : new Set(algorithms);\n}\nfunction validateCritDuplicates(Err, protectedHeader) {\n const { crit } = protectedHeader ?? {};\n if (Array.isArray(crit) && new Set(crit).size !== crit.length)\n throw new Err('\"crit\" (Critical) Header Parameter MUST NOT contain duplicate values');\n}\nfunction validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0)\n throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n if (!protectedHeader || protectedHeader.crit === void 0)\n return [];\n if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != \"string\" || input.length === 0))\n throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };\n for (const parameter of protectedHeader.crit) {\n if (!(parameter in recognized))\n throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0)\n throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0))\n throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n }\n return protectedHeader.crit;\n}\nfunction validateB64(protectedHeader, extensions) {\n if (extensions.includes(\"b64\")) {\n const b64 = protectedHeader.b64;\n if (typeof b64 != \"boolean\")\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n return b64;\n }\n return !0;\n}\nfunction serializeJoseHeader(Err, header) {\n let serialized, parsed;\n try {\n serialized = JSON.stringify(header), parsed = JSON.parse(serialized);\n } catch (cause) {\n throw new Err(\"JOSE Header is not valid JSON\", { cause });\n }\n if (!isObject(parsed))\n throw new Err(\"JOSE Header is not a JSON object\");\n return [parsed, serialized];\n}\nexport {\n JWE_RECOGNIZED,\n JWS_RECOGNIZED,\n assertNotSet,\n assertUint8Array,\n decodeBase64url,\n encodeAsciiMember,\n isDisjoint,\n isJwkSet,\n isObject,\n parseJoseHeader,\n serializeJoseHeader,\n validateAlgorithms,\n validateB64,\n validateCrit,\n validateCritDuplicates\n};\n","import { isObject } from \"./validate.js\";\nimport { decode } from \"../util/base64url.js\";\nimport { JOSENotSupported } from \"../util/errors.js\";\nconst tag = (key) => key[Symbol.toStringTag], jwkMatchesOp = (entry, key, usage) => {\n const { alg } = entry;\n if (key.use !== void 0) {\n const expected = usage === \"sign\" || usage === \"verify\" ? \"sig\" : \"enc\";\n if (key.use !== expected)\n throw new TypeError(`Invalid key for this operation, its \"use\" must be \"${expected}\" when present`);\n }\n if (key.alg !== void 0 && key.alg !== alg)\n throw new TypeError(`Invalid key for this operation, its \"alg\" must be \"${alg}\" when present`);\n if (Array.isArray(key.key_ops)) {\n const expectedKeyOp = usage === \"encrypt\" || usage === \"decrypt\" ? entry.ops?.[usage === \"encrypt\" ? 0 : 1] : usage;\n if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp))\n throw new TypeError(`Invalid key for this operation, its \"key_ops\" must include \"${expectedKeyOp}\" when present`);\n }\n};\nasync function prepareKey(entry, key, usage) {\n const { alg, secret } = entry, requiresPrivateKey = usage === \"decrypt\" || usage === \"sign\";\n if (secret && key instanceof Uint8Array)\n return key;\n let normalized, keyObject;\n if (isObject(key)) {\n if (normalized = normalizeJwk(key), typeof normalized.kty != \"string\")\n throw invalidKeyType(alg, key, secret);\n if (!(secret ? normalized.kty === \"oct\" && typeof normalized.k == \"string\" : normalized.kty !== \"oct\" && (requiresPrivateKey ? normalized.kty === \"AKP\" && typeof normalized.priv == \"string\" || typeof normalized.d == \"string\" : normalized.d === void 0 && normalized.priv === void 0)))\n throw new TypeError(secret ? 'JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present' : `JSON Web Key for this operation must be a ${requiresPrivateKey ? \"private\" : \"public\"} JWK`);\n if (jwkMatchesOp(entry, normalized, usage), normalized.kty === \"oct\")\n return decode(normalized.k);\n if (!Object.isFrozen(key)) {\n const { key_ops } = key;\n Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);\n }\n } else {\n if (!isKeyLike(key))\n throw invalidKeyType(alg, key, secret);\n const expectedType = secret ? \"secret\" : requiresPrivateKey ? \"private\" : \"public\";\n if (key.type !== expectedType && (secret || [\"secret\", \"public\", \"private\"].includes(key.type)))\n throw new TypeError(`${tag(key)} instances must be of type \"${expectedType}\" for the ${alg} algorithm`);\n if (isCryptoKey(key))\n return key;\n if (keyObject = key, keyObject.type === \"secret\")\n return keyObject.export();\n }\n cache ||= /* @__PURE__ */ new WeakMap();\n const cacheKey = key;\n let cached = cache.get(cacheKey);\n if (cached?.[alg])\n return cached[alg];\n if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == \"function\") {\n const isPublic = keyObject.type === \"public\", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({ crv, asymmetricKeyType: keyObject.asymmetricKeyType }) ?? entry.subtle;\n return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);\n }\n return normalized ??= keyObject.export({ format: \"jwk\" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized);\n}\nlet cache;\nconst nist = {\n __proto__: null,\n prime256v1: \"P-256\",\n secp384r1: \"P-384\",\n secp521r1: \"P-521\"\n};\nfunction assertCryptoKey(key) {\n if (!isCryptoKey(key))\n throw new Error(\"CryptoKey instance expected\");\n}\nconst isCryptoKey = (key) => {\n if (key?.[Symbol.toStringTag] === \"CryptoKey\")\n return !0;\n try {\n return key instanceof CryptoKey;\n } catch {\n return !1;\n }\n}, isKeyObject = (key) => key?.[Symbol.toStringTag] === \"KeyObject\", isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);\nfunction message(msg, actual, ...types) {\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(\", \")}, or ${last}.`;\n } else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;\n return actual == null ? msg += ` Received ${actual}` : typeof actual == \"function\" && actual.name ? msg += ` Received function ${actual.name}` : typeof actual == \"object\" && actual != null && actual.constructor?.name && (msg += ` Received an instance of ${actual.constructor.name}`), msg;\n}\nconst invalidKeyInput = (actual, ...types) => message(\"Key must be \", actual, ...types);\nfunction invalidKeyType(alg, actual, secret) {\n const types = [\"CryptoKey\", \"KeyObject\", \"JSON Web Key\"];\n return secret && types.push(\"Uint8Array\"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));\n}\nconst unusable = (name, prop = \"algorithm.name\") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\nfunction checkUsage(key, usage) {\n if (usage && !key.usages.includes(usage))\n throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);\n}\nfunction checkModulusLength(alg, key) {\n const { modulusLength } = key.algorithm;\n if (typeof modulusLength != \"number\" || modulusLength < 2048)\n throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n}\nfunction checkCryptoKey(key, expected, usage) {\n const algorithm = key.algorithm;\n if (algorithm.name !== expected.name)\n throw unusable(expected.name);\n if (expected.hash && algorithm.hash?.name !== expected.hash)\n throw unusable(expected.hash, \"algorithm.hash\");\n if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve)\n throw unusable(expected.namedCurve, \"algorithm.namedCurve\");\n if (expected.length !== void 0 && algorithm.length !== expected.length)\n throw unusable(expected.length, \"algorithm.length\");\n checkUsage(key, usage);\n}\nfunction snapshotJwk(jwk) {\n return { __proto__: null, ...jwk };\n}\nfunction normalizeJwk(jwk) {\n const normalized = snapshotJwk(jwk);\n if (normalized.ext !== void 0 && typeof normalized.ext != \"boolean\")\n throw new TypeError('\"ext\" (Extractable) Parameter must be a boolean');\n if (normalized.key_ops !== void 0) {\n const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;\n if (!keyOps || keyOps.some((operation) => typeof operation != \"string\") || new Set(keyOps).size !== keyOps.length)\n throw new TypeError('\"key_ops\" (Key Operations) Parameter must be an array of unique strings');\n normalized.key_ops = keyOps;\n }\n return normalized;\n}\nfunction validateExtractableOption(extractable) {\n if (extractable !== void 0 && typeof extractable != \"boolean\")\n throw new TypeError('\"extractable\" option must be a boolean');\n return extractable;\n}\nasync function jwkToKey(entry, jwk, extractable) {\n if (!entry.kty.includes(jwk.kty))\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = { ...jwk, ext: extractable ?? jwk.ext };\n return keyData.kty !== \"AKP\" && delete keyData.alg, delete keyData.use, crypto.subtle.importKey(\"jwk\", keyData, algorithm, keyData.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);\n}\nasync function rawKey(key, expected, usage, extractable = !1) {\n return key instanceof Uint8Array && (key = await crypto.subtle.importKey(\"raw\", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;\n}\nexport {\n assertCryptoKey,\n checkCryptoKey,\n checkModulusLength,\n checkUsage,\n invalidKeyInput,\n isCryptoKey,\n isKeyLike,\n isKeyObject,\n jwkToKey,\n normalizeJwk,\n prepareKey,\n rawKey,\n snapshotJwk,\n validateExtractableOption\n};\n","function table(entries) {\n const out = { __proto__: null };\n for (const alg in entries)\n out[alg] = { ...entries[alg], alg };\n return out;\n}\nexport {\n table\n};\n","import { JOSENotSupported } from \"../util/errors.js\";\nimport { table } from \"./key_descriptor.js\";\nconst wrap = [\n [\"encrypt\", \"wrapKey\"],\n [\"decrypt\", \"unwrapKey\"]\n], derive = [[], [\"deriveBits\"]], none = [[], []];\nfunction rsaes(bits) {\n return {\n kty: [\"RSA\"],\n mode: \"key-encryption\",\n subtle: { name: \"RSA-OAEP\", hash: `SHA-${bits}` },\n usages: wrap,\n ops: [\"wrapKey\", \"unwrapKey\"]\n };\n}\nfunction ecdh(mode) {\n return {\n kty: [\"EC\", \"OKP\"],\n mode,\n subtle: { name: \"ECDH\" },\n resolve: ({ kty, crv, asymmetricKeyType }) => {\n if (crv === \"X25519\" || asymmetricKeyType === \"x25519\")\n return { name: \"X25519\" };\n if (kty === \"OKP\")\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n return { name: \"ECDH\", namedCurve: crv };\n },\n usages: derive,\n ops: [void 0, \"deriveBits\"]\n };\n}\nfunction aeskw(bits, gcm = !1) {\n return {\n kty: [\"oct\"],\n mode: \"key-wrapping\",\n secret: !0,\n subtle: { name: gcm ? \"AES-GCM\" : \"AES-KW\", length: bits },\n usages: none,\n ops: gcm ? [\"encrypt\", \"decrypt\"] : [\"wrapKey\", \"unwrapKey\"]\n };\n}\nfunction pbes2() {\n return {\n kty: [\"oct\"],\n mode: \"key-wrapping\",\n secret: !0,\n subtle: { name: \"PBKDF2\" },\n usages: none,\n ops: [\"deriveBits\", \"deriveBits\"]\n };\n}\nconst JWE = table({\n dir: {\n kty: [\"oct\"],\n mode: \"direct-encryption\",\n secret: !0,\n subtle: { name: \"AES-GCM\" },\n usages: none,\n ops: [\"encrypt\", \"decrypt\"]\n },\n \"RSA-OAEP\": rsaes(1),\n \"RSA-OAEP-256\": rsaes(256),\n \"RSA-OAEP-384\": rsaes(384),\n \"RSA-OAEP-512\": rsaes(512),\n \"ECDH-ES\": ecdh(\"direct-key-agreement\"),\n \"ECDH-ES+A128KW\": ecdh(\"key-agreement-with-key-wrapping\"),\n \"ECDH-ES+A192KW\": ecdh(\"key-agreement-with-key-wrapping\"),\n \"ECDH-ES+A256KW\": ecdh(\"key-agreement-with-key-wrapping\"),\n A128KW: aeskw(128),\n A192KW: aeskw(192),\n A256KW: aeskw(256),\n A128GCMKW: aeskw(128, !0),\n A192GCMKW: aeskw(192, !0),\n A256GCMKW: aeskw(256, !0),\n \"PBES2-HS256+A128KW\": pbes2(),\n \"PBES2-HS384+A192KW\": pbes2(),\n \"PBES2-HS512+A256KW\": pbes2()\n}), contentOps = [\"encrypt\", \"decrypt\"];\nfunction contentEncryption(bits, cbc = !1) {\n return {\n kty: [\"oct\"],\n secret: !0,\n subtle: { name: cbc ? \"AES-CBC\" : \"AES-GCM\", length: bits },\n usages: none,\n ops: contentOps,\n cekBits: bits,\n ivBits: cbc ? 128 : 96,\n cbc\n };\n}\nconst ENC = table({\n A128GCM: contentEncryption(128),\n A192GCM: contentEncryption(192),\n A256GCM: contentEncryption(256),\n \"A128CBC-HS256\": contentEncryption(256, !0),\n \"A192CBC-HS384\": contentEncryption(384, !0),\n \"A256CBC-HS512\": contentEncryption(512, !0)\n});\nfunction unsupported(parameter, name) {\n throw new JOSENotSupported(`Invalid or unsupported \"${parameter}\" (JWE ${name}) header value`);\n}\nfunction jweAlgorithm(alg) {\n return (typeof alg == \"string\" ? JWE[alg] : void 0) ?? unsupported(\"alg\", \"Algorithm\");\n}\nfunction isJWECEKTransport(algorithm) {\n return algorithm.mode === \"key-wrapping\" || algorithm.mode === \"key-encryption\" || algorithm.mode === \"key-agreement-with-key-wrapping\";\n}\nfunction jweEncryption(enc) {\n return (typeof enc == \"string\" ? ENC[enc] : void 0) ?? unsupported(\"enc\", \"Encryption Algorithm\");\n}\nexport {\n JWE,\n isJWECEKTransport,\n jweAlgorithm,\n jweEncryption\n};\n","import { JOSENotSupported } from \"../util/errors.js\";\nimport { table } from \"./key_descriptor.js\";\nconst sig = [[\"verify\"], [\"sign\"]];\nfunction hmac(bits) {\n const subtle = { name: \"HMAC\", hash: `SHA-${bits}` };\n return { kty: [\"oct\"], secret: !0, subtle, signing: subtle, usages: sig };\n}\nfunction rsa(bits, saltLength) {\n const subtle = { name: saltLength ? \"RSA-PSS\" : \"RSASSA-PKCS1-v1_5\", hash: `SHA-${bits}` };\n return {\n kty: [\"RSA\"],\n subtle,\n signing: saltLength ? { ...subtle, saltLength } : subtle,\n usages: sig,\n minRsaBits: 2048\n };\n}\nfunction ecdsa(crv, bits) {\n return {\n kty: [\"EC\"],\n crv,\n subtle: { name: \"ECDSA\", namedCurve: crv },\n signing: { name: \"ECDSA\", hash: `SHA-${bits}` },\n usages: sig\n };\n}\nfunction eddsa() {\n const subtle = { name: \"Ed25519\" };\n return {\n kty: [\"OKP\"],\n crv: \"Ed25519\",\n subtle,\n signing: subtle,\n usages: sig\n };\n}\nfunction mldsa(parameterSet) {\n const subtle = { name: `ML-DSA-${parameterSet}` };\n return {\n kty: [\"AKP\"],\n subtle,\n signing: subtle,\n usages: sig\n };\n}\nconst JWS = table({\n HS256: hmac(256),\n HS384: hmac(384),\n HS512: hmac(512),\n RS256: rsa(256),\n RS384: rsa(384),\n RS512: rsa(512),\n PS256: rsa(256, 32),\n PS384: rsa(384, 48),\n PS512: rsa(512, 64),\n ES256: ecdsa(\"P-256\", 256),\n ES384: ecdsa(\"P-384\", 384),\n ES512: ecdsa(\"P-521\", 512),\n EdDSA: eddsa(),\n Ed25519: eddsa(),\n \"ML-DSA-44\": mldsa(44),\n \"ML-DSA-65\": mldsa(65),\n \"ML-DSA-87\": mldsa(87)\n});\nfunction jwsAlgorithm(alg) {\n const entry = typeof alg == \"string\" ? JWS[alg] : void 0;\n if (!entry)\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n return entry;\n}\nexport {\n JWS,\n jwsAlgorithm\n};\n","import { JOSENotSupported } from \"../util/errors.js\";\nimport { JWS } from \"./jws_algorithms.js\";\nimport { JWE } from \"./jwe_algorithms.js\";\nconst algArgument = '\"alg\" (Algorithm)';\nfunction unsupportedAlg(source = 'JWK \"alg\" (Algorithm) Parameter') {\n throw new JOSENotSupported(`Invalid or unsupported ${source} value`);\n}\nfunction keyAlgorithm(alg, source) {\n return (typeof alg == \"string\" ? JWS[alg] ?? JWE[alg] : void 0) ?? unsupportedAlg(source);\n}\nexport {\n algArgument,\n keyAlgorithm,\n unsupportedAlg\n};\n","import { decode as decodeBase64URL } from \"../util/base64url.js\";\nimport { fromSPKI, fromPKCS8, fromX509 } from \"../lib/asn1.js\";\nimport { jwkToKey, validateExtractableOption, normalizeJwk } from \"../lib/key.js\";\nimport { keyAlgorithm } from \"../lib/key_algorithm.js\";\nimport { JOSENotSupported } from \"../util/errors.js\";\nimport { isObject } from \"../lib/validate.js\";\nasync function importSPKI(spki, alg, options) {\n if (typeof spki != \"string\" || spki.indexOf(\"-----BEGIN PUBLIC KEY-----\") !== 0)\n throw new TypeError('\"spki\" must be SPKI formatted string');\n return fromSPKI(spki, alg, options);\n}\nasync function importX509(x509, alg, options) {\n if (typeof x509 != \"string\" || x509.indexOf(\"-----BEGIN CERTIFICATE-----\") !== 0)\n throw new TypeError('\"x509\" must be X.509 formatted string');\n return fromX509(x509, alg, options);\n}\nasync function importPKCS8(pkcs8, alg, options) {\n if (typeof pkcs8 != \"string\" || pkcs8.indexOf(\"-----BEGIN PRIVATE KEY-----\") !== 0)\n throw new TypeError('\"pkcs8\" must be PKCS#8 formatted string');\n return fromPKCS8(pkcs8, alg, options);\n}\nasync function importJWK(jwk, alg, options) {\n if (!isObject(jwk))\n throw new TypeError(\"JWK must be an object\");\n const normalized = normalizeJwk(jwk), extractable = validateExtractableOption(options?.extractable), { alg: jwkAlg } = normalized;\n if (alg ??= jwkAlg, normalized.kty !== \"oct\" && !alg)\n throw new TypeError('\"alg\" argument is required when \"jwk.alg\" is not present');\n switch (normalized.kty) {\n case \"oct\":\n if (typeof normalized.k != \"string\")\n throw new TypeError('missing \"k\" (Key Value) Parameter value');\n return decodeBase64URL(normalized.k);\n case \"AKP\": {\n if (typeof jwkAlg != \"string\" || !jwkAlg)\n throw new TypeError('missing \"alg\" (Algorithm) Parameter value');\n if (alg !== jwkAlg)\n throw new TypeError(\"JWK alg and alg option value mismatch\");\n return jwkToKey(keyAlgorithm(alg), normalized, extractable);\n }\n case \"RSA\":\n case \"EC\":\n case \"OKP\":\n return jwkToKey(keyAlgorithm(alg), normalized, extractable);\n default:\n throw new JOSENotSupported('Unsupported \"kty\" (Key Type) Parameter value');\n }\n}\nexport {\n importJWK,\n importPKCS8,\n importSPKI,\n importX509\n};\n","/**\n * `oc.identity.verifyActivityAttestation` — one-call ed25519 verifier\n * for a /api/me/activity-attestation bundle.\n *\n * Cashes the \"trivially to verify\" strategic claim: an integrator\n * receiving a signed attestation JSON from a user calls one function,\n * gets a typed result with per-check detail, never reaches into\n * @noble/curves or jose themselves.\n *\n * import { oc } from '@orangecheck/me-client';\n *\n * const result = await oc.identity.verifyActivityAttestation(bundle);\n * if (!result.ok) return res.status(401).send(result.reason);\n * // result.attestation is typed · safe to gate on lifetime_sats etc.\n *\n * The JWKS issuer is me.ochk.io (the envelope key), DISTINCT from\n * the auth host's ochk.io JWKS that signs webhooks. Same Ed25519\n * curve, same kid lookup pattern, fetched + cached separately.\n */\n\nimport { importJWK, type CryptoKey, type KeyObject } from 'jose';\n\nconst DEFAULT_ISSUER = 'https://me.ochk.io';\nconst DEFAULT_TTL_MS = 60 * 60 * 1000;\n/** How old a key list may be and still stand in for one that can't be fetched. */\nconst DEFAULT_MAX_STALE_MS = 6 * 60 * 60 * 1000;\n/** An unknown kid refetches the key list at most this often per issuer. */\nconst FORCED_REFRESH_MIN_INTERVAL_MS = 60_000;\nconst ENVELOPE_JWKS_PATH = '/.well-known/oc-envelope-jwks.json';\n\nexport interface ActivityAttestation {\n id: string;\n v: 1;\n kind: 'oc-me-activity';\n did_oc: string;\n event_count: number;\n human_event_count: number;\n lifetime_sats: number;\n distinct_integrator_count: number;\n oldest_event_at: string | null;\n active_days: number;\n computed_at: string;\n expires_at: string;\n}\n\nexport interface ActivityAttestationBundle {\n /** A readable copy. Never trusted: the result is read from the signed\n * bytes, and a copy that differs from them fails the check. */\n attestation?: ActivityAttestation;\n sig: string;\n kid: string;\n canonical_b64: string;\n}\n\nexport interface ActivityVerifyCheck {\n ok: boolean;\n label: string;\n detail?: string;\n}\n\nexport interface ActivityVerifyResult {\n ok: boolean;\n reason?: string;\n attestation?: ActivityAttestation;\n checks: ActivityVerifyCheck[];\n}\n\ninterface OcEnvelopePublicJwk {\n kty: 'OKP';\n crv: 'Ed25519';\n x: string;\n kid: string;\n alg?: 'EdDSA';\n use?: 'sig';\n}\n\nexport interface VerifyActivityOptions {\n /** Override the me.ochk.io issuer (defaults to https://me.ochk.io).\n * Useful for staging / self-hosted dev. */\n issuer?: string;\n /** Pass a JWK directly to skip the network fetch · convenient when\n * embedding the public key in your service for air-gapped or\n * edge-runtime deployments. */\n jwk?: OcEnvelopePublicJwk;\n /** JWKS cache TTL in ms. Defaults to 1h. Stale-on-error falls back\n * to the previous cached value, for at most `jwksMaxStaleMs`. */\n jwksCacheTtlMs?: number;\n /** How old a cached JWKS may be and still stand in during an outage.\n * Defaults to 6h; past it, verification fails closed. */\n jwksMaxStaleMs?: number;\n /** Optional · override \"now\" for deterministic tests. */\n now?: Date;\n}\n\ntype AuthKey = CryptoKey | KeyObject;\n\ninterface JwksCacheEntry {\n keys: Record<string, AuthKey>;\n fetchedAt: number;\n}\n\nconst jwksCache = new Map<string, JwksCacheEntry>();\nconst inflight = new Map<string, Promise<JwksCacheEntry>>();\nconst lastForcedRefresh = new Map<string, number>();\n\nasync function fetchEnvelopeJwks(\n issuer: string,\n ttlMs: number,\n maxStaleMs = DEFAULT_MAX_STALE_MS\n): Promise<JwksCacheEntry> {\n const cached = jwksCache.get(issuer);\n if (cached && Date.now() - cached.fetchedAt < ttlMs) return cached;\n const existing = inflight.get(issuer);\n if (existing) return existing;\n const p = (async (): Promise<JwksCacheEntry> => {\n try {\n const url = `${issuer.replace(/\\/$/, '')}${ENVELOPE_JWKS_PATH}`;\n const res = await fetch(url, { headers: { Accept: 'application/json' } });\n if (!res.ok) throw new Error(`envelope JWKS fetch ${url} returned ${res.status}`);\n const json = (await res.json()) as { keys: OcEnvelopePublicJwk[] };\n if (!json || !Array.isArray(json.keys)) {\n throw new Error(`envelope JWKS at ${url} did not return {keys:[…]}`);\n }\n const keys: Record<string, AuthKey> = {};\n for (const k of json.keys) {\n if (typeof k.kid !== 'string') continue;\n try {\n keys[k.kid] = (await importJWK(k, 'EdDSA')) as AuthKey;\n } catch {\n /* skip keys that won't import */\n }\n }\n const entry: JwksCacheEntry = { keys, fetchedAt: Date.now() };\n jwksCache.set(issuer, entry);\n return entry;\n } catch (err) {\n // A key the issuer removed must stop verifying even while its list can't be fetched.\n const stale = jwksCache.get(issuer);\n if (stale && Date.now() - stale.fetchedAt < maxStaleMs) return stale;\n throw err;\n }\n })().finally(() => {\n inflight.delete(issuer);\n });\n inflight.set(issuer, p);\n return p;\n}\n\nfunction hexToBytes(hex: string): Uint8Array | null {\n if (typeof hex !== 'string') return null;\n const s = hex.trim();\n if (s.length === 0 || s.length % 2 !== 0) return null;\n const out = new Uint8Array(s.length / 2);\n for (let i = 0; i < out.length; i++) {\n const b = parseInt(s.slice(i * 2, i * 2 + 2), 16);\n if (Number.isNaN(b)) return null;\n out[i] = b;\n }\n return out;\n}\n\nfunction base64ToBytes(b64: string): Uint8Array | null {\n try {\n const bin =\n typeof atob === 'function'\n ? atob(b64)\n : Buffer.from(b64, 'base64').toString('binary');\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n } catch {\n return null;\n }\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n let out = '';\n for (const b of bytes) out += b.toString(16).padStart(2, '0');\n return out;\n}\n\nasync function sha256(bytes: Uint8Array): Promise<Uint8Array> {\n const subtle =\n typeof globalThis.crypto !== 'undefined' && globalThis.crypto.subtle\n ? globalThis.crypto.subtle\n : null;\n if (!subtle) {\n throw new Error('crypto.subtle unavailable · need Node 20+ / modern browser / Edge runtime');\n }\n const buf = await subtle.digest('SHA-256', bytes as unknown as ArrayBuffer);\n return new Uint8Array(buf);\n}\n\nfunction toArrayBuffer(view: Uint8Array): ArrayBuffer {\n const buf = new ArrayBuffer(view.byteLength);\n new Uint8Array(buf).set(view);\n return buf;\n}\n\nasync function verifyEd25519(\n key: AuthKey,\n sig: Uint8Array,\n msg: Uint8Array\n): Promise<boolean> {\n const subtle =\n typeof globalThis.crypto !== 'undefined' && globalThis.crypto.subtle\n ? globalThis.crypto.subtle\n : null;\n if (!subtle) return false;\n try {\n return await subtle.verify(\n 'Ed25519',\n key as CryptoKey,\n toArrayBuffer(sig),\n toArrayBuffer(msg)\n );\n } catch {\n return false;\n }\n}\n\n/** The signed fields, in the order me.ochk.io encodes them. */\nconst SIGNED_FIELDS = [\n 'v',\n 'kind',\n 'did_oc',\n 'event_count',\n 'human_event_count',\n 'lifetime_sats',\n 'distinct_integrator_count',\n 'oldest_event_at',\n 'active_days',\n 'computed_at',\n 'expires_at',\n] as const;\nconst COUNTS = [\n 'event_count',\n 'human_event_count',\n 'lifetime_sats',\n 'distinct_integrator_count',\n 'active_days',\n] as const;\n\n/** The attestation the signature covers, read from the signed bytes, or\n * null when they are not one in canonical form. */\nfunction readSignedAttestation(canonical: Uint8Array, id: string): ActivityAttestation | null {\n const text = new TextDecoder().decode(canonical);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;\n const o = parsed as Record<string, unknown>;\n if (o.v !== 1 || o.kind !== 'oc-me-activity' || typeof o.did_oc !== 'string') return null;\n const countsOk = COUNTS.every((k) => {\n const n = o[k];\n return typeof n === 'number' && Number.isSafeInteger(n) && n >= 0;\n });\n if (!countsOk) return null;\n if (o.oldest_event_at !== null && typeof o.oldest_event_at !== 'string') return null;\n if (typeof o.computed_at !== 'string' || typeof o.expires_at !== 'string') return null;\n const ordered = Object.fromEntries(SIGNED_FIELDS.map((k) => [k, o[k]]));\n // Only the canonical encoding counts: no extra keys, no reordering, no whitespace.\n if (JSON.stringify(ordered) !== text) return null;\n return { id, ...(ordered as Omit<ActivityAttestation, 'id'>) };\n}\n\n/** True when every field of the readable copy equals the signed value. */\nfunction sameAttestation(copy: ActivityAttestation, signed: ActivityAttestation): boolean {\n const c = copy as unknown as Record<string, unknown>;\n const v = signed as unknown as Record<string, unknown>;\n return (['id', ...SIGNED_FIELDS] as const).every((k) => c[k] === v[k]);\n}\n\n/**\n * Verify a signed activity attestation bundle. Returns a typed\n * ActivityVerifyResult with per-check detail · never throws (network\n * + parse failures surface as ok=false rows in the checks array, so\n * the caller can log them without try/catch).\n *\n * Checks, in order: bundle shape, the signed bytes decode and are an\n * attestation in canonical form, the readable copy (when given) equals\n * them, JWK with matching kid present, ed25519 signature, freshness.\n * `attestation` in the result is read from the signed bytes, and is set\n * only when every check passes.\n */\nexport async function verifyActivityAttestation(\n bundle: ActivityAttestationBundle,\n options: VerifyActivityOptions = {}\n): Promise<ActivityVerifyResult> {\n const checks: ActivityVerifyCheck[] = [];\n\n // 1. Bundle shape\n const shapeOk =\n !!bundle &&\n typeof bundle === 'object' &&\n typeof bundle.sig === 'string' &&\n typeof bundle.kid === 'string' &&\n typeof bundle.canonical_b64 === 'string' &&\n (bundle.attestation === undefined ||\n (!!bundle.attestation && typeof bundle.attestation === 'object'));\n checks.push({\n ok: shapeOk,\n label: 'bundle shape · sig / kid / canonical_b64',\n });\n if (!shapeOk) {\n return { ok: false, reason: 'bundle shape invalid', checks };\n }\n\n // 2. canonical_b64 decodes\n const canonical = base64ToBytes(bundle.canonical_b64);\n checks.push({\n ok: canonical !== null,\n label: 'canonical_b64 decodes',\n detail: canonical ? `${canonical.length} bytes` : 'invalid base64',\n });\n if (!canonical) return { ok: false, reason: 'canonical_b64 invalid base64', checks };\n\n // 3. The signed bytes are an attestation, and the readable copy says the same\n const computedId = bytesToHex(await sha256(canonical));\n const signed = readSignedAttestation(canonical, computedId);\n checks.push({\n ok: signed !== null,\n label: 'canonical_bytes are an oc-me-activity attestation in canonical form',\n });\n if (!signed) return { ok: false, reason: 'canonical bytes are not an activity attestation', checks };\n\n const copy = bundle.attestation;\n const copyOk = copy === undefined || sameAttestation(copy, signed);\n checks.push({\n ok: copyOk,\n label: 'attestation === the signed bytes, id = sha256(canonical_bytes)',\n detail: copyOk ? computedId : 'the readable copy differs from what was signed',\n });\n if (!copyOk) return { ok: false, reason: 'attestation does not match the signed bytes', checks };\n\n // 4. JWK lookup + ed25519 verify\n let key: AuthKey | null = null;\n if (options.jwk) {\n if (options.jwk.kid !== bundle.kid) {\n checks.push({\n ok: false,\n label: 'JWK with matching kid present',\n detail: `provided jwk.kid=${options.jwk.kid} but bundle.kid=${bundle.kid}`,\n });\n return { ok: false, reason: 'kid mismatch with provided jwk', checks };\n }\n try {\n key = (await importJWK(options.jwk, 'EdDSA')) as AuthKey;\n checks.push({ ok: true, label: 'JWK with matching kid present', detail: `kid ${bundle.kid} (provided)` });\n } catch (err) {\n checks.push({\n ok: false,\n label: 'JWK with matching kid present',\n detail: `provided jwk failed import: ${(err as Error).message}`,\n });\n return { ok: false, reason: 'provided jwk failed import', checks };\n }\n } else {\n const issuer = options.issuer ?? DEFAULT_ISSUER;\n const ttl = options.jwksCacheTtlMs ?? DEFAULT_TTL_MS;\n const maxStale = options.jwksMaxStaleMs ?? DEFAULT_MAX_STALE_MS;\n try {\n let entry = await fetchEnvelopeJwks(issuer, ttl, maxStale);\n key = entry.keys[bundle.kid] ?? null;\n if (!key && Date.now() - (lastForcedRefresh.get(issuer) ?? 0) >= FORCED_REFRESH_MIN_INTERVAL_MS) {\n // Cache miss · likely a rotation. Refetch, at most once a minute.\n lastForcedRefresh.set(issuer, Date.now());\n entry = await fetchEnvelopeJwks(issuer, 0, maxStale);\n key = entry.keys[bundle.kid] ?? null;\n }\n checks.push({\n ok: !!key,\n label: 'JWK with matching kid present',\n detail: key ? `kid ${bundle.kid}` : `no JWK with kid ${bundle.kid} at ${issuer}${ENVELOPE_JWKS_PATH}`,\n });\n if (!key) {\n return { ok: false, reason: `kid ${bundle.kid} not in envelope JWKS`, checks };\n }\n } catch (err) {\n checks.push({\n ok: false,\n label: 'JWK with matching kid present',\n detail: `envelope JWKS unavailable: ${(err as Error).message}`,\n });\n return {\n ok: false,\n reason: `envelope JWKS unavailable: ${(err as Error).message}`,\n checks,\n };\n }\n }\n\n const sigBytes = hexToBytes(bundle.sig);\n if (!sigBytes) {\n checks.push({\n ok: false,\n label: 'ed25519.verify(sig, canonical_bytes, jwk.public)',\n detail: 'malformed sig (expected hex)',\n });\n return { ok: false, reason: 'malformed sig', checks };\n }\n const sigOk = await verifyEd25519(key, sigBytes, canonical);\n checks.push({\n ok: sigOk,\n label: 'ed25519.verify(sig, canonical_bytes, jwk.public)',\n detail: sigOk ? 'signature valid' : 'signature does not match',\n });\n if (!sigOk) return { ok: false, reason: 'signature does not match', checks };\n\n // 5. Freshness, from the signed expiry\n const now = options.now ?? new Date();\n const expiresMs = Date.parse(signed.expires_at);\n const freshOk = Number.isFinite(expiresMs) && expiresMs > now.getTime();\n checks.push({\n ok: freshOk,\n label: 'now < attestation.expires_at',\n detail: freshOk\n ? `expires ${new Date(expiresMs).toISOString()}`\n : 'attestation has expired',\n });\n if (!freshOk) return { ok: false, reason: 'attestation has expired', checks };\n\n return { ok: true, attestation: signed, checks };\n}\n\n/** Force-refresh the envelope-JWKS cache · useful after a key rotation\n * if you don't want to wait for the TTL to expire. */\nexport async function refreshEnvelopeJwks(issuer = DEFAULT_ISSUER): Promise<void> {\n jwksCache.delete(issuer);\n await fetchEnvelopeJwks(issuer, DEFAULT_TTL_MS);\n}\n\nexport const identity = {\n verifyActivityAttestation,\n refreshEnvelopeJwks,\n};\n","/**\n * OC Connect from a site's own backend: the site keeps its own login and makes\n * an orangecheck account for its user with one call (ochk.io/docs/connect).\n *\n * connectProvision({ apiKey, userId, consent? }) → { ok, did_oc, is_new }\n * connectClaimLink({ apiKey, userId }) → { ok, url, expires_at }\n * connectDelete({ apiKey, userId }) → { ok, result }\n *\n * A refusal or an outage is a result (`{ ok: false, reason, status }`), never a\n * throw, so a failed call can't block the site's own login. Only a mistake in\n * the call itself throws, before anything is sent: an option it does not read,\n * a missing key or user id, or `consent: false`.\n *\n * They refuse to run where there is a `document`, as a hint for the most common\n * mistake. That is not a guard: a browser Web Worker has no `document`. What\n * keeps the key safe is importing these only from `/server` code that never\n * reaches a client bundle.\n */\n\n/** The only place a call goes: the key never travels anywhere else. */\nconst ORIGIN = 'https://ochk.io';\nconst DEFAULT_TIMEOUT_MS = 5000;\nconst MAX_TIMEOUT_MS = 30_000;\nconst DID_OC = /^did:oc:[0-9a-f]{32}$/;\n\nexport interface ConnectOptions {\n /** Your Connect API key (ochk.app → your project → Sign-in → Your own login). Server only. */\n apiKey: string;\n /** Your own stable id for this user, 1 to 256 characters. */\n userId: string;\n /** Answer `unavailable` after this long. Default 5000, at most 30000. */\n timeoutMs?: number;\n}\n\nexport interface ConnectProvisionOptions extends ConnectOptions {\n /**\n * `true` only when the person ticked your \"Also create my orangecheck\n * account\" box just now. Recorded once. Leave it out when you show no box.\n * An unticked box means no call at all, so `false` is refused.\n */\n consent?: true;\n /** The user's email. ochk.io keeps it only as a keyed hash. */\n email?: string;\n /** `true` when you verified `email` yourself (a code or a link they answered). */\n emailVerified?: boolean;\n}\n\n/**\n * Why ochk.io did not answer with an account. `unavailable` covers an outage, a\n * timeout and any answer this SDK can't read: try again later.\n */\nexport type ConnectProvisionRefusal =\n | 'account_deleted'\n | 'daily_limit'\n | 'rate_limited'\n | 'invalid_api_key'\n | 'app_suspended'\n | 'bad_request'\n | 'unavailable';\nexport type ConnectDeleteRefusal =\n | 'unknown_user'\n | 'holds_earnings'\n | 'not_deletable'\n | 'rate_limited'\n | 'invalid_api_key'\n | 'bad_request'\n | 'unavailable';\nexport type ConnectClaimLinkRefusal =\n | 'unknown_user'\n | 'already_claimed'\n | 'rate_limited'\n | 'invalid_api_key'\n | 'app_suspended'\n | 'bad_request'\n | 'unavailable';\n\n/** A refusal: `status` is ochk.io's HTTP status, 0 when nothing came back. */\nexport interface ConnectRefused<R extends string> {\n ok: false;\n reason: R;\n status: number;\n}\n\nexport type ConnectProvisionResult =\n | { ok: true; did_oc: string; is_new: boolean }\n | ConnectRefused<ConnectProvisionRefusal>;\nexport type ConnectDeleteResult =\n | { ok: true; result: 'deleted' | 'detached' | 'already_deleted' }\n | ConnectRefused<ConnectDeleteRefusal>;\nexport type ConnectClaimLinkResult =\n | { ok: true; url: string; expires_at: string }\n | ConnectRefused<ConnectClaimLinkRefusal>;\n\nconst BASE_KEYS = ['apiKey', 'userId', 'timeoutMs'];\nconst PROVISION_KEYS = new Set([...BASE_KEYS, 'consent', 'email', 'emailVerified']);\nconst USER_KEYS = new Set(BASE_KEYS);\nconst PROVISION_REASONS = new Set<string>([\n 'account_deleted',\n 'daily_limit',\n 'rate_limited',\n 'invalid_api_key',\n 'app_suspended',\n 'bad_request',\n]);\nconst DELETE_REASONS = new Set<string>([\n 'unknown_user',\n 'holds_earnings',\n 'not_deletable',\n 'rate_limited',\n 'invalid_api_key',\n 'bad_request',\n]);\nconst CLAIM_LINK_REASONS = new Set<string>([\n 'unknown_user',\n 'already_claimed',\n 'rate_limited',\n 'invalid_api_key',\n 'app_suspended',\n 'bad_request',\n]);\nconst DELETE_RESULTS = new Set(['deleted', 'detached', 'already_deleted']);\n\nfunction fail(message: string): never {\n throw new TypeError(`@orangecheck/me-client: ${message}`);\n}\n\n/**\n * Check the call itself; throws on a mistake in it. Returns the options copied\n * once onto a bare object, and every later read is from that copy, so an\n * inherited `consent` (a polluted Object.prototype, or options made with\n * Object.create) is never read and a getter is read once.\n */\nfunction checkCall<O extends ConnectOptions>(name: string, options: O, known: ReadonlySet<string>): O {\n if (typeof document !== 'undefined') {\n fail(`${name} runs on your server only: in a browser your API key would be exposed`);\n }\n if (options === null || typeof options !== 'object') fail(`${name}: options must be an object`);\n const unknown = Object.keys(options).filter((k) => !known.has(k));\n if (unknown.length > 0) {\n const only = [...known].join(', ');\n fail(`${name}: unknown option ${unknown.join(', ')}. It reads only ${only}.`);\n }\n const o = Object.assign(Object.create(null) as O, options);\n if (typeof o.apiKey !== 'string' || o.apiKey.trim() === '') {\n fail(`${name}: apiKey is required (your Connect API key)`);\n }\n // ochk.io counts a user id in UTF-16 code units, as JavaScript's length does.\n const id = o.userId;\n if (typeof id !== 'string' || id.length < 1 || id.length > 256) {\n fail(`${name}: userId must be your user's id, 1 to 256 characters`);\n }\n const t = o.timeoutMs;\n if (t !== undefined && !(typeof t === 'number' && t > 0 && t <= MAX_TIMEOUT_MS)) {\n fail(`${name}: timeoutMs must be above 0 and at most ${MAX_TIMEOUT_MS}`);\n }\n return o;\n}\n\ntype Answer = { status: number; body: Record<string, unknown> | null };\n\nasync function post(\n path: string,\n apiKey: string,\n body: Record<string, unknown>,\n timeoutMs: number\n): Promise<Answer> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await fetch(`${ORIGIN}${path}`, {\n method: 'POST',\n // These endpoints never redirect, so a redirect is an error: the key and\n // the body go to ochk.io and nowhere else.\n redirect: 'error',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n let parsed: unknown = null;\n try {\n parsed = await res.json();\n } catch {\n parsed = null;\n }\n const ok = parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed);\n return { status: res.status, body: ok ? (parsed as Record<string, unknown>) : null };\n } catch {\n return { status: 0, body: null };\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction refused<R extends string>(\n answer: Answer,\n known: ReadonlySet<string>\n): ConnectRefused<R> {\n const raw = answer.body?.reason;\n const said = raw === 'missing_api_key' ? 'invalid_api_key' : raw;\n const reason = typeof said === 'string' && known.has(said) ? said : 'unavailable';\n return { ok: false, reason: reason as R, status: answer.status };\n}\n\n/**\n * Make (or find) the orangecheck account for one of your users. Idempotent:\n * the same user always gets the same `did_oc`. Call it once per user and keep\n * the `did_oc` on your user record.\n */\nexport function connectProvision(\n options: ConnectProvisionOptions\n): Promise<ConnectProvisionResult> {\n const o = checkCall('connectProvision', options, PROVISION_KEYS);\n if (o.consent !== undefined && o.consent !== true) {\n fail(\n 'connectProvision: consent must be true or left out. An unticked box means no ' +\n 'call at all; a call without consent makes an account nobody asked for'\n );\n }\n const { email, emailVerified } = o;\n if (email !== undefined && (typeof email !== 'string' || email === '')) {\n fail('connectProvision: email must be a non-empty string');\n }\n if (emailVerified !== undefined && typeof emailVerified !== 'boolean') {\n fail('connectProvision: emailVerified must be a boolean');\n }\n if (emailVerified !== undefined && email === undefined) {\n fail('connectProvision: emailVerified describes email, so pass email too');\n }\n const body: Record<string, unknown> = { user_id: o.userId };\n if (o.consent === true) body.consent = true;\n if (email !== undefined) body.email = email;\n if (emailVerified !== undefined) body.email_verified = emailVerified;\n return call('/api/connect/provision', o, body).then(\n (answer): ConnectProvisionResult => {\n const b = answer.body;\n if (answer.status !== 200) return refused(answer, PROVISION_REASONS);\n const good =\n b?.ok === true &&\n typeof b.did_oc === 'string' &&\n DID_OC.test(b.did_oc) &&\n typeof b.is_new === 'boolean';\n return good\n ? { ok: true, did_oc: b.did_oc as string, is_new: b.is_new as boolean }\n : { ok: false, reason: 'unavailable', status: 200 };\n }\n );\n}\n\n/**\n * A link for your signed-in user to claim their account at ochk.app. Good once,\n * for fifteen minutes. A link anywhere but https://ochk.app is refused\n * (`unavailable`), so you never send your user somewhere else.\n */\nexport function connectClaimLink(options: ConnectOptions): Promise<ConnectClaimLinkResult> {\n const o = checkCall('connectClaimLink', options, USER_KEYS);\n return call('/api/connect/claim-link', o, { user_id: o.userId }).then(\n (answer): ConnectClaimLinkResult => {\n const b = answer.body;\n if (answer.status !== 200) return refused(answer, CLAIM_LINK_REASONS);\n const good =\n b?.ok === true &&\n isClaimUrl(b.url) &&\n typeof b.expires_at === 'string' &&\n b.expires_at !== '';\n return good\n ? { ok: true, url: b.url as string, expires_at: b.expires_at as string }\n : { ok: false, reason: 'unavailable', status: 200 };\n }\n );\n}\n\n/** Your user deleted their account with you: delete the one Connect made for them. */\nexport function connectDelete(options: ConnectOptions): Promise<ConnectDeleteResult> {\n const o = checkCall('connectDelete', options, USER_KEYS);\n return call('/api/connect/delete', o, { user_id: o.userId }).then(\n (answer): ConnectDeleteResult => {\n const b = answer.body;\n if (answer.status !== 200) return refused(answer, DELETE_REASONS);\n return b?.ok === true && typeof b.result === 'string' && DELETE_RESULTS.has(b.result)\n ? { ok: true, result: b.result as 'deleted' | 'detached' | 'already_deleted' }\n : { ok: false, reason: 'unavailable', status: 200 };\n }\n );\n}\n\nfunction call(path: string, o: ConnectOptions, body: Record<string, unknown>): Promise<Answer> {\n return post(path, o.apiKey, body, o.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n}\n\n/** An https link on ochk.app, the only place a claim happens: no user name, password or port. */\nfunction isClaimUrl(v: unknown): v is string {\n if (typeof v !== 'string') return false;\n try {\n const url = new URL(v);\n return (\n url.protocol === 'https:' &&\n url.hostname === 'ochk.app' &&\n url.port === '' &&\n url.username === '' &&\n url.password === ''\n );\n } catch {\n return false;\n }\n}\n","/**\n * @orangecheck/me-client/connect-consent\n *\n * The words for an optional \"also make me an orangecheck account\" box on a\n * site that keeps its own login (OC Connect). Plain strings with no imports, so\n * any UI can render its own checkbox: React, Vue, a server template, plain HTML.\n *\n * import {\n * CONNECT_CONSENT_LABEL,\n * CONNECT_CONSENT_BLURB,\n * } from '@orangecheck/me-client/connect-consent';\n *\n * Show the box unticked, never pre-ticked and never bundled with your Terms.\n * Ticked: call connectProvision with `consent: true`. Unticked: make no call.\n */\n\n/** The checkbox label. */\nexport const CONNECT_CONSENT_LABEL = 'Also create my orangecheck account';\n\n/** The line under the label. */\nexport const CONNECT_CONSENT_BLURB =\n 'It stays with orangecheck until you claim it at ochk.app. Then you can use it on ' +\n 'other sites, or delete it.';\n","/**\n * Two things a site's own backend does with the token from the sign-in popup,\n * once it has verified it (ochk.io/docs/me/sdk):\n *\n * spendOnce(jti, exp, store) → true the first time, false for a repeat\n * revokeToken(token) → { ok, revoked } | { ok: false, reason, status }\n *\n * spendOnce keeps a token from starting a second session; revokeToken ends it\n * at the auth host once the site's own session has taken over. Only a mistake\n * in the call itself throws, before anything is read or sent.\n */\n\nconst DEFAULT_ISSUER = 'https://ochk.io';\nconst DEFAULT_TIMEOUT_MS = 5000;\nconst MAX_TIMEOUT_MS = 30_000;\n/** What ochk.io's /api/auth/revoke takes in one call. */\nconst MAX_TOKENS = 8;\nconst MAX_TOKEN_LENGTH = 4096;\n\nfunction fail(message: string): never {\n throw new TypeError(`@orangecheck/me-client: ${message}`);\n}\n\nconst nowSeconds = () => Math.floor(Date.now() / 1000);\n\n/**\n * Where you record the jti of each token you accepted, until it expires. Yours\n * to provide, shared by every server that accepts sign-ins: a unique row in your\n * database, or Redis `SET jti 1 NX EXAT exp`. `add` must be atomic: true when\n * it recorded the jti, false when the jti was there already.\n */\nexport interface JtiStore {\n add(jti: string, exp: number): boolean | Promise<boolean>;\n}\n\n/**\n * A {@link JtiStore} in this process's memory: for tests and a single process.\n * Two servers, or a restart, each have their own, so a token could start a\n * session on each: in production, use a store they share.\n */\nexport class MemoryJtiStore implements JtiStore {\n private readonly spent = new Map<string, number>();\n\n add(jti: string, exp: number): boolean {\n const now = nowSeconds();\n for (const [k, until] of this.spent) if (until <= now) this.spent.delete(k);\n if (this.spent.has(jti)) return false;\n this.spent.set(jti, exp);\n return true;\n }\n}\n\n/**\n * Spend a verified token's `jti` so it starts one session: true the first time,\n * false for a repeat or a token that has expired (`exp`, in seconds, at or\n * before now). Call it after verifying the token and before starting your own\n * session; on false, refuse the sign-in. A store that fails throws, so the\n * sign-in fails closed.\n */\nexport function spendOnce(jti: string, exp: number, store: JtiStore): Promise<boolean> {\n if (typeof jti !== 'string' || jti === '') fail('spendOnce: jti must be one non-empty string');\n if (typeof exp !== 'number' || !Number.isFinite(exp)) {\n fail(\"spendOnce: exp must be the token's expiry, in seconds\");\n }\n if (store === null || typeof store !== 'object' || typeof store.add !== 'function') {\n fail('spendOnce: store must have add(jti, exp)');\n }\n if (exp <= nowSeconds()) return Promise.resolve(false);\n return Promise.resolve()\n .then(() => store.add(jti, exp))\n .then((spent) => {\n if (typeof spent !== 'boolean') fail('spendOnce: store.add must answer true or false');\n return spent;\n });\n}\n\nexport interface RevokeTokenOptions {\n /** The auth host that issued the token. Default https://ochk.io. */\n issuer?: string;\n /** Answer `unavailable` after this long. Default 5000, at most 30000. */\n timeoutMs?: number;\n}\n\n/**\n * Why ochk.io did not end the tokens. `unavailable` covers an outage, a timeout\n * and any answer this SDK can't read: the token still ends when it expires.\n */\nexport type RevokeTokenRefusal = 'rate_limited' | 'bad_request' | 'unavailable';\n\n/**\n * `revoked` counts the tokens ochk.io ended: 0 when it could not read one as\n * its own (expired already, or signed elsewhere). A refusal's `status` is\n * ochk.io's HTTP status, 0 when nothing came back.\n */\nexport type RevokeTokenResult =\n | { ok: true; revoked: number }\n | { ok: false; reason: RevokeTokenRefusal; status: number };\n\nconst REVOKE_OPTIONS: ReadonlySet<string> = new Set<keyof RevokeTokenOptions>(['issuer', 'timeoutMs']);\n\n/**\n * The issuer as one origin, `scheme://host[:port]`: https, or http on this\n * machine only. A path, a query, a fragment or a user name would send the\n * tokens somewhere else on the host (or carry credentials), so each is refused.\n */\nexport function issuerOrigin(issuer: unknown, where = 'revokeToken'): string {\n if (typeof issuer !== 'string') fail(`${where}: issuer must be a URL`);\n const refuse = (): never =>\n fail(`${where}: issuer must be one https origin (http only on this machine), such as https://ochk.io, got ${issuer}`);\n if (/[?#@\\\\]/.test(issuer)) refuse();\n let url: URL;\n try {\n url = new URL(issuer);\n } catch {\n return refuse();\n }\n const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) refuse();\n if (url.pathname !== '/' || url.search !== '' || url.hash !== '' || url.username !== '' || url.password !== '') {\n refuse();\n }\n return url.origin;\n}\n\n/**\n * End a sign-in token at the auth host (`POST /api/auth/revoke`), on every\n * site that reads the list of ended sessions. Holding a token is the authority\n * to end it; nothing else is sent. Call it once your own session has taken\n * over. Takes one token or up to eight. An outage is a result, never a throw,\n * so it can't break a sign-in.\n */\nexport function revokeToken(\n token: string | readonly string[],\n options: RevokeTokenOptions = {}\n): Promise<RevokeTokenResult> {\n if (options === null || typeof options !== 'object') fail('revokeToken: options must be an object');\n const unknown = Object.keys(options).filter((k) => !REVOKE_OPTIONS.has(k));\n if (unknown.length > 0) {\n fail(`revokeToken: unknown option ${unknown.join(', ')}. It reads only ${[...REVOKE_OPTIONS].join(', ')}.`);\n }\n const tokens = typeof token === 'string' ? [token] : Array.isArray(token) ? [...token] : null;\n if (\n !tokens ||\n tokens.length < 1 ||\n tokens.length > MAX_TOKENS ||\n !tokens.every((t) => typeof t === 'string' && t.length > 0 && t.length <= MAX_TOKEN_LENGTH)\n ) {\n fail(`revokeToken: pass one token, or 1 to ${MAX_TOKENS}, each a non-empty string of at most ${MAX_TOKEN_LENGTH} characters`);\n }\n const origin = issuerOrigin(options.issuer ?? DEFAULT_ISSUER);\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (typeof timeoutMs !== 'number' || !(timeoutMs > 0 && timeoutMs <= MAX_TIMEOUT_MS)) {\n fail(`revokeToken: timeoutMs must be above 0 and at most ${MAX_TIMEOUT_MS}`);\n }\n return post(`${origin}/api/auth/revoke`, tokens, timeoutMs);\n}\n\nasync function post(url: string, tokens: string[], timeoutMs: number): Promise<RevokeTokenResult> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await fetch(url, {\n method: 'POST',\n // The endpoint never redirects, so a redirect is an error: the tokens go\n // to the auth host and nowhere else.\n redirect: 'error',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ tokens }),\n signal: controller.signal,\n });\n let body: unknown = null;\n try {\n body = await res.json();\n } catch {\n body = null;\n }\n const b = body !== null && typeof body === 'object' ? (body as { ok?: unknown; revoked?: unknown }) : null;\n if (res.status === 200) {\n return b?.ok === true && Number.isSafeInteger(b.revoked) && (b.revoked as number) >= 0\n ? { ok: true, revoked: b.revoked as number }\n : { ok: false, reason: 'unavailable', status: 200 };\n }\n if (res.status === 429) return { ok: false, reason: 'rate_limited', status: 429 };\n if (res.status === 400) return { ok: false, reason: 'bad_request', status: 400 };\n return { ok: false, reason: 'unavailable', status: res.status };\n } catch {\n return { ok: false, reason: 'unavailable', status: 0 };\n } finally {\n clearTimeout(timer);\n }\n}\n","/**\n * Native sign-in, the server's half (ochk.io/docs/integration/native-sign-in): an app on a\n * person's own device, a desktop build or a game, signs them in through the\n * system browser. It listens on 127.0.0.1, opens ochk.io's\n * /native/authorize with a PKCE challenge, and its listener receives a\n * one-time `code`. It hands the code and its verifier to your server, which\n * trades them here for the same token the sign-in popup gives, checked as\n * `withOcAuth` checks one:\n *\n * exchangeNativeCode({ code, codeVerifier, redirectUri, audience }, { projectKey })\n * → { status: 'valid', token, session } | { status: 'invalid', reason }\n * | { status: 'unavailable', reason }\n *\n * `valid` means the token verifies for your audience, carries its handle,\n * was not ended everywhere, and the account meets your project's \"who can\n * sign in\" rule. No secret is involved in the app: the verifier proves the\n * app that started the sign-in is the one finishing it. Only a mistake in\n * the call throws.\n */\n\nimport type { RevocationCheck, SessionPayload } from '@orangecheck/auth-core';\n\nimport { checkOcSession, checkOcToken, checkSignInRule, type WithOcAuthOptions } from './server';\nimport { issuerOrigin } from './tokens';\n\nconst DEFAULT_ISSUER = 'https://ochk.io';\nconst DEFAULT_TIMEOUT_MS = 5000;\nconst MAX_TIMEOUT_MS = 30_000;\nconst MAX_FIELD_LENGTH = 512;\n\nexport interface ExchangeNativeCodeInput {\n /** The `code` your app's loopback listener received. */\n code: string;\n /** The PKCE verifier the app made its `code_challenge` from. */\n codeVerifier: string;\n /** The redirect the app sent, exactly: `http://127.0.0.1:<port>/<path>`. */\n redirectUri: string;\n /**\n * Your site's origin, which the token must be bound to: the project's\n * verified domain (`https://your-site.example`), or a test project's\n * development origin. Never taken from ochk.io's answer.\n */\n audience: string;\n}\n\nexport interface ExchangeNativeCodeOptions {\n /**\n * Your project key, from your own config: default `OC_PROJECT_KEY`. Never\n * one the app sends, since the key decides whose \"who can sign in\" rule\n * and list of ended sessions apply.\n */\n projectKey?: string;\n /** The auth host. Default https://ochk.io. */\n issuer?: string;\n /** Where the rule and the list of ended sessions are read. Default https://me.ochk.io. */\n meOrigin?: string;\n /**\n * The check for sessions the person ended everywhere, as `checkOcSession`\n * takes it. Default: auth-core's `integratorRevocationCheck` with your\n * project key and `OC_SIGNING_SECRET`; none while the secret is unset.\n * The trade counts as a write: a list that can't be read answers\n * `unavailable`.\n */\n revocation?: RevocationCheck | false;\n /** An explicit floor, which wins over the project's rule, as `withOcAuth` takes it. */\n requireBond?: WithOcAuthOptions['requireBond'];\n /** Answer `unavailable` after this long. Default 5000, at most 30000. */\n timeoutMs?: number;\n}\n\n/**\n * Why there is no session.\n * - `invalid_grant`: the code is unknown, spent or expired, was sent with\n * another verifier, redirect or project, or the project no longer allows\n * native sign-in. Start the sign-in again.\n * - `not_offered`: this auth host does not offer native sign-in.\n * - `bad_request`: a field ochk.io could not read.\n * - `invalid_token`, `no_session_handle`: the token did not verify for your\n * `audience`.\n * - `session_ended`: the person ended their sessions everywhere.\n * - `bond_required`: the account does not meet your project's rule; `need`,\n * `have` and `back_url` say what it asks and where to back the account, as\n * the adapters' 403 does.\n * - `unknown_project_key`: your project key names no project at `meOrigin`.\n */\nexport type ExchangeNativeCodeRefusal =\n | 'invalid_grant'\n | 'not_offered'\n | 'bad_request'\n | 'invalid_token'\n | 'no_session_handle'\n | 'session_ended'\n | 'unknown_project_key';\n\n/** What an outage left unknown. Answer it 503, so the app tries again. */\nexport type ExchangeNativeCodeUnavailable =\n | 'auth_host_unavailable'\n | 'rate_limited'\n | 'key_set_unavailable'\n | 'revocations_unavailable'\n | 'bond_policy_unavailable';\n\nexport type ExchangeNativeCodeResult =\n | { status: 'valid'; token: string; session: SessionPayload }\n | { status: 'invalid'; reason: ExchangeNativeCodeRefusal }\n | {\n status: 'invalid';\n reason: 'bond_required';\n need: { min_sats: number; min_days: number; max_age_secs?: number };\n have: { sats_floor: number; days_floor: number } | null;\n back_url: string;\n }\n | { status: 'unavailable'; reason: ExchangeNativeCodeUnavailable };\n\nconst OPTIONS: ReadonlySet<string> = new Set<keyof ExchangeNativeCodeOptions>([\n 'projectKey',\n 'issuer',\n 'meOrigin',\n 'revocation',\n 'requireBond',\n 'timeoutMs',\n]);\nconst FIELDS = ['code', 'codeVerifier', 'redirectUri', 'audience'] as const;\n\nfunction fail(message: string): never {\n throw new TypeError(`@orangecheck/me-client: exchangeNativeCode: ${message}`);\n}\n\n/**\n * Trade a native sign-in's code for its token (`POST <issuer>/api/auth/native/token`),\n * then check it as `withOcAuth` does a request's: verified for your\n * `audience` with its handle, not ended everywhere (the trade counts as a\n * write), and meeting your project's rule. Each code works once, whatever\n * the answer. Start your own session only on `valid`, after\n * `spendOnce(session.jti, session.exp, store)`. An outage is a result, never\n * a throw.\n */\nexport async function exchangeNativeCode(\n input: ExchangeNativeCodeInput,\n options: ExchangeNativeCodeOptions = {}\n): Promise<ExchangeNativeCodeResult> {\n if (input === null || typeof input !== 'object') fail('input must be an object');\n if ('projectKey' in input) {\n fail('projectKey is your own key: pass it in options, or set OC_PROJECT_KEY, never from the request');\n }\n const extra = Object.keys(input).filter((k) => !(FIELDS as readonly string[]).includes(k));\n if (extra.length > 0) fail(`unknown input ${extra.join(', ')}. It reads only ${FIELDS.join(', ')}.`);\n for (const f of FIELDS) {\n const v: unknown = input[f];\n if (typeof v !== 'string' || v.length === 0 || v.length > MAX_FIELD_LENGTH) {\n fail(`${f} must be a non-empty string of at most ${MAX_FIELD_LENGTH} characters`);\n }\n }\n if (input.audience === '*') fail(\"audience must be your site's origin, not '*'\");\n if (options === null || typeof options !== 'object') fail('options must be an object');\n const unknown = Object.keys(options).filter((k) => !OPTIONS.has(k));\n if (unknown.length > 0) fail(`unknown option ${unknown.join(', ')}. It reads only ${[...OPTIONS].join(', ')}.`);\n const projectKey =\n options.projectKey ?? (typeof process !== 'undefined' ? process.env?.OC_PROJECT_KEY?.trim() : undefined);\n if (typeof projectKey !== 'string' || projectKey.length === 0 || projectKey.length > MAX_FIELD_LENGTH) {\n fail('needs your project key: options.projectKey, or OC_PROJECT_KEY');\n }\n const issuer = issuerOrigin(options.issuer ?? DEFAULT_ISSUER, 'exchangeNativeCode');\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (typeof timeoutMs !== 'number' || !(timeoutMs > 0 && timeoutMs <= MAX_TIMEOUT_MS)) {\n fail(`timeoutMs must be above 0 and at most ${MAX_TIMEOUT_MS}`);\n }\n\n const answer = await post(`${issuer}/api/auth/native/token`, input, projectKey, timeoutMs);\n if (answer.status !== 'token') return answer;\n const token = answer.token;\n\n // The token itself: signature, issuer, expiry, audience and handle.\n const verified = await checkOcToken(token, { audience: input.audience, issuer });\n if (verified.status === 'unavailable') return { status: 'unavailable', reason: 'key_set_unavailable' };\n if (verified.status === 'invalid') return { status: 'invalid', reason: verified.reason ?? 'invalid_token' };\n\n // The list of ended sessions, as a write, exactly as the adapters read it.\n const where = options.meOrigin ? { meOrigin: options.meOrigin } : {};\n const checked = await checkOcSession(\n { authorization: `Bearer ${token}` },\n {\n audience: input.audience,\n issuer,\n projectKey,\n method: 'POST',\n ...where,\n ...(options.revocation !== undefined ? { revocation: options.revocation } : {}),\n }\n );\n if (checked.status === 'unavailable') {\n return { status: 'unavailable', reason: checked.reason ?? 'revocations_unavailable' };\n }\n if (checked.status === 'signed_out') return { status: 'invalid', reason: checked.reason ?? 'session_ended' };\n\n // The project's \"who can sign in\" rule, read and answered as checkSignInRule does.\n const rule = await checkSignInRule(checked.session, {\n projectKey,\n ...where,\n ...(options.requireBond ? { requireBond: options.requireBond } : {}),\n });\n if (!rule.ok) {\n const b = rule.body as {\n reason?: string;\n need?: { min_sats: number; min_days: number; max_age_secs?: number };\n have?: { sats_floor: number; days_floor: number } | null;\n back_url?: string;\n };\n if (b.reason === 'bond_required' && b.need && b.back_url) {\n return { status: 'invalid', reason: 'bond_required', need: b.need, have: b.have ?? null, back_url: b.back_url };\n }\n if (b.reason === 'unknown_project_key') return { status: 'invalid', reason: 'unknown_project_key' };\n return { status: 'unavailable', reason: 'bond_policy_unavailable' };\n }\n return { status: 'valid', token, session: checked.session };\n}\n\ntype TokenAnswer = { ok?: unknown; token?: unknown; reason?: unknown };\n\nasync function post(\n url: string,\n input: ExchangeNativeCodeInput,\n projectKey: string,\n timeoutMs: number\n): Promise<\n | { status: 'token'; token: string }\n | { status: 'invalid'; reason: ExchangeNativeCodeRefusal }\n | { status: 'unavailable'; reason: ExchangeNativeCodeUnavailable }\n> {\n const unavailable = { status: 'unavailable', reason: 'auth_host_unavailable' } as const;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await fetch(url, {\n method: 'POST',\n // The endpoint never redirects: the code goes to the auth host and nowhere else.\n redirect: 'error',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n grant_type: 'authorization_code',\n code: input.code,\n code_verifier: input.codeVerifier,\n redirect_uri: input.redirectUri,\n project: projectKey,\n }),\n signal: controller.signal,\n });\n let body: TokenAnswer | null = null;\n try {\n const json: unknown = await res.json();\n if (json !== null && typeof json === 'object') body = json as TokenAnswer;\n } catch {\n body = null;\n }\n if (res.status === 200) {\n return body?.ok === true && typeof body.token === 'string' && body.token.length > 0\n ? { status: 'token', token: body.token }\n : unavailable;\n }\n if (res.status === 400) {\n return { status: 'invalid', reason: body?.reason === 'invalid_grant' ? 'invalid_grant' : 'bad_request' };\n }\n if (res.status === 404) return { status: 'invalid', reason: 'not_offered' };\n if (res.status === 429) return { status: 'unavailable', reason: 'rate_limited' };\n return unavailable;\n } catch {\n return unavailable;\n } finally {\n clearTimeout(timer);\n }\n}\n","/**\n * After someone merges two orangecheck accounts, the one they no longer use\n * stops signing in. A token from the sign-in popup then carries `merged_rh`:\n * your site's revocation handle for each account merged in. Match it against\n * the handles you stored (every `rh` you have seen, kept with your user) to\n * keep that person's history under the account they use now.\n */\n\n/** At most this many handles ride one token; a longer claim is not read. */\nconst MERGED_HANDLES_MAX = 16;\n\n/** What a token's merged handles name in your own table. */\nexport type MergedUserMatch =\n | { kind: 'none' }\n | { kind: 'one'; user: string }\n | { kind: 'conflict'; users: string[] };\n\n/**\n * The merged handles on a session `verifyOcToken` or `checkOcSession` already\n * accepted. A claim that is not a list of at most 16 non-empty strings reads\n * as none.\n */\nexport function mergedHandles(session: { merged_rh?: unknown }): string[] {\n const v = session.merged_rh;\n if (!Array.isArray(v) || v.length > MERGED_HANDLES_MAX) return [];\n if (!v.every((h) => typeof h === 'string' && h.length > 0)) return [];\n return [...new Set(v as string[])];\n}\n\n/**\n * Which of your users this person was before a merge. Call it with a verified\n * session whose `did_oc` you have no row for. `lookup` answers the user that\n * stored a handle, or null.\n *\n * - `none`: create a user, as for anyone new.\n * - `one`: attach this `did_oc` and `rh` to that user.\n * - `conflict`: the handles name two of your users. Pick neither; log it.\n */\nexport async function matchMergedUser(\n session: { merged_rh?: unknown },\n lookup: (rh: string) => string | null | undefined | Promise<string | null | undefined>\n): Promise<MergedUserMatch> {\n const users = new Set<string>();\n for (const rh of mergedHandles(session)) {\n const user = await lookup(rh);\n if (typeof user === 'string' && user.length > 0) users.add(user);\n }\n if (users.size === 0) return { kind: 'none' };\n if (users.size === 1) return { kind: 'one', user: [...users][0]! };\n return { kind: 'conflict', users: [...users].sort() };\n}\n","/**\n * Server-side helpers: verify a sign-in token (`checkOcToken`,\n * `verifyOcToken`), check a request's session (`checkOcSession`, `withOcAuth`,\n * `ocAuthExpress`, `ocAuthHono`), end a token (`revokeToken`), spend one once\n * (`spendOnce`), trade a native app's sign-in code (`exchangeNativeCode`), and\n * the Connect calls. The rest of the client is in\n * [`@orangecheck/me-client`](/sdk/me-client/README), and the popup in\n * [`@orangecheck/me-client/popup`](/sdk/me-client/popup/README).\n *\n * @packageDocumentation\n */\n\n/**\n * @orangecheck/me-client/server\n *\n * Server-side verification helpers for OC integrators.\n *\n * import {\n * withOcAuth,\n * getOcSession,\n * verifyOcToken,\n * verifyActivityAttestation,\n * } from '@orangecheck/me-client/server';\n *\n * Zero env vars, zero JWK handling. Internally lazy-fetches the auth\n * host's JWKS at https://ochk.io/.well-known/jwks.json and the\n * envelope JWKS at https://me.ochk.io/.well-known/oc-envelope-jwks.json,\n * caches both in-process. Integrators write code; we handle the crypto.\n *\n * Three layers of session verification, smallest to thickest:\n *\n * verifyOcToken(token) → SessionPayload | null\n * getOcSession(headers) → SessionPayload | null (cookie OR Bearer)\n * withOcAuth(handler) → Next.js Pages adapter that injects\n * req.ocSession on the request object\n * ocAuthExpress(opts?) → Express / Connect middleware\n * ocAuthHono(opts?) → Hono middleware\n *\n * OC Connect, for a site that keeps its own login (ochk.io/docs/connect):\n *\n * connectProvision({ apiKey, userId, consent? }) → { ok, did_oc, is_new }\n * connectClaimLink({ apiKey, userId }) → { ok, url, expires_at }\n * connectDelete({ apiKey, userId }) → { ok, result }\n *\n * Native sign-in, for an app on a person's device (ochk.io/docs/integration/native-sign-in):\n *\n * exchangeNativeCode({ code, codeVerifier, redirectUri, audience }, { projectKey })\n * → { status: 'valid', token, session } | { status: 'invalid' | 'unavailable', reason }\n * (valid: verified for your audience, not ended everywhere, meets your project's rule)\n *\n * Plus the activity-attestation verifier · for sybil-resistance gating:\n *\n * verifyActivityAttestation(bundle, opts?) → ActivityVerifyResult\n *\n * Same envelope-JWKS verification posture as the public /verify-activity\n * page; same five checks (shape / id / kid / sig / freshness). Use to\n * gate sensitive flows on cross-integrator lifetime_sats + duration +\n * distinct_count + active_days · all values are content-addressed and\n * signed.\n *\n * All thin wrappers around the same crypto primitives. Bring your own\n * framework.\n */\n\nimport {\n bondMeets,\n checkOcToken as checkOcTokenCore,\n familyRevocationCheck,\n integratorRevocationCheck,\n readBondClaim,\n readOcSessionToken,\n SAFE_METHODS,\n verifyOcToken as verifyOcTokenCore,\n type BondClaim,\n type RevocationCheck,\n type SessionPayload,\n type VerifyOcOptions,\n type SessionRequestHeaders,\n} from '@orangecheck/auth-core';\n\nexport { bondMeets, readBondClaim };\nexport type { BondClaim, SessionPayload, VerifyOcOptions };\n\n/** Why a token that verified is still not a session here. */\nexport type OcSessionRefusal = 'no_session_handle';\n\nexport interface VerifyOcTokenOptions extends VerifyOcOptions {\n /**\n * Refuse a token bound to your site (one with `aud`) that carries no `rh`,\n * its handle on your project's list of ended sessions. Without it \"sign out\n * everywhere\" can't reach the session, so it is refused by default.\n * Every token ochk.app's sign-in popup issues carries one; `false` accepts\n * one minted some other way, and then sign out everywhere does not end it.\n * A family session (no `aud`, on *.ochk.io) is not held to this: the\n * family's own feed ends it. `audience: '*'` admits family sessions too,\n * so keep it for routes that receive tokens forwarded from *.ochk.io.\n * Default: true.\n */\n requireHandle?: boolean;\n}\n\n/** A bound token with no handle, unless the site opted out. */\n// Each session this module verified, so checkSignInRule takes nothing else: a\n// claims-shaped object anyone built could carry any did and any backing.\nconst VERIFIED = new WeakSet<SessionPayload>();\nfunction vouch(session: SessionPayload): SessionPayload {\n VERIFIED.add(session);\n return session;\n}\n\n/** A family session: no aud, or an empty list, as verification with no audience accepts. */\nfunction isFamily(session: SessionPayload): boolean {\n const aud: unknown = session.aud;\n return aud === undefined || (Array.isArray(aud) && aud.length === 0);\n}\n\nfunction lacksHandle(session: SessionPayload, requireHandle: boolean | undefined): boolean {\n if (requireHandle === false || isFamily(session)) return false;\n const rh: unknown = session.rh;\n return typeof rh !== 'string' || rh.length === 0;\n}\n\nfunction checkRequireHandle(requireHandle: unknown): void {\n if (requireHandle !== undefined && typeof requireHandle !== 'boolean') {\n throw new TypeError('@orangecheck/me-client: requireHandle must be true or false');\n }\n}\n\nlet warnedHandle = false;\n\n/** Say once why a signed-in person is turned away for want of a handle. */\nfunction warnNoHandle(session: SessionPayload): void {\n if (warnedHandle) return;\n warnedHandle = true;\n console.warn(\n `[@orangecheck/me-client] a sign-in token bound to ${JSON.stringify((session as { aud?: unknown }).aud)} ` +\n 'carries no revocation handle (rh), so sign out everywhere could not end it, and it was refused ' +\n '(no_session_handle). Tokens from the ochk.app sign-in popup carry one. Pass requireHandle: false ' +\n 'only to accept tokens minted some other way.'\n );\n}\n\n/**\n * Verify a sign-in token: the signature, the issuer, expiry and, with\n * `audience`, that it was issued to your site. A token bound to your site with\n * no revocation handle is refused (see {@link VerifyOcTokenOptions.requireHandle}).\n * Null for any token that fails. It does not read the list of ended sessions:\n * `getOcSession` and the adapters do.\n */\nexport async function verifyOcToken(\n token: string,\n options: VerifyOcTokenOptions = {}\n): Promise<SessionPayload | null> {\n if (options === null || typeof options !== 'object') {\n throw new TypeError('@orangecheck/me-client: options must be an object');\n }\n const { requireHandle, ...core } = options;\n checkRequireHandle(requireHandle);\n const session = await verifyOcTokenCore(token, core);\n if (!session) return null;\n if (lacksHandle(session, requireHandle)) {\n warnNoHandle(session);\n return null;\n }\n return vouch(session);\n}\n\n/**\n * A sign-in token's check, telling one that fails from a key set that can't be\n * read. `unavailable` is an outage: answer it 503 so the client tries again,\n * never as a failed sign-in.\n */\nexport type OcTokenCheck =\n | { status: 'valid'; session: SessionPayload }\n | { status: 'invalid'; reason?: OcSessionRefusal }\n | { status: 'unavailable'; reason: 'key_set_unavailable' };\n\n/**\n * {@link verifyOcToken}, telling a token that fails from a key set that can't\n * be read (see {@link OcTokenCheck}). For the route that receives the token\n * from the sign-in popup. Throws on an option it does not read, or an issuer it\n * may not fetch from.\n */\nexport async function checkOcToken(token: string, options: VerifyOcTokenOptions = {}): Promise<OcTokenCheck> {\n if (options === null || typeof options !== 'object') {\n throw new TypeError('@orangecheck/me-client: options must be an object');\n }\n const { requireHandle, ...core } = options;\n checkRequireHandle(requireHandle);\n const checked = await checkOcTokenCore(token, core);\n if (checked.status === 'unavailable') return { status: 'unavailable', reason: 'key_set_unavailable' };\n if (checked.status === 'invalid') return { status: 'invalid' };\n if (lacksHandle(checked.session, requireHandle)) {\n warnNoHandle(checked.session);\n return { status: 'invalid', reason: 'no_session_handle' };\n }\n return { status: 'valid', session: vouch(checked.session) };\n}\n\n// Activity-attestation verifier · re-export from the identity module so\n// server-side integrators get the gating helper alongside session\n// verification without a second import path.\nexport {\n identity,\n verifyActivityAttestation,\n refreshEnvelopeJwks,\n} from './identity';\n// OC Connect: a site that keeps its own login makes an orangecheck account\n// for its user from its own backend.\nexport { connectProvision, connectClaimLink, connectDelete } from './connect';\nexport type {\n ConnectOptions,\n ConnectProvisionOptions,\n ConnectProvisionResult,\n ConnectProvisionRefusal,\n ConnectClaimLinkResult,\n ConnectClaimLinkRefusal,\n ConnectDeleteResult,\n ConnectDeleteRefusal,\n ConnectRefused,\n} from './connect';\nexport { CONNECT_CONSENT_LABEL, CONNECT_CONSENT_BLURB } from './connect-consent';\n// After a sign-in: start one session per token, then end the token at ochk.io.\nexport { spendOnce, MemoryJtiStore, revokeToken } from './tokens';\nexport { exchangeNativeCode } from './native';\nexport type {\n ExchangeNativeCodeInput,\n ExchangeNativeCodeOptions,\n ExchangeNativeCodeRefusal,\n ExchangeNativeCodeResult,\n ExchangeNativeCodeUnavailable,\n} from './native';\n// After an account merge: find the user this person was at your site.\nexport { matchMergedUser, mergedHandles } from './merged';\nexport type { MergedUserMatch } from './merged';\nexport type { JtiStore, RevokeTokenOptions, RevokeTokenResult, RevokeTokenRefusal } from './tokens';\nexport type {\n ActivityAttestation,\n ActivityAttestationBundle,\n ActivityVerifyCheck,\n ActivityVerifyResult,\n VerifyActivityOptions,\n} from './identity';\n\nexport interface OcSessionOptions extends VerifyOcTokenOptions {\n /**\n * The request's method. While me.ochk.io's list of ended sessions can't be\n * read, reads go on and writes are refused; with no method, a request\n * counts as a write. The adapters pass it for you.\n */\n method?: string;\n /** Your project key. Default `OC_PROJECT_KEY`. */\n projectKey?: string;\n /**\n * Where me.ochk.io is: the project's sign-in rule and its list of ended\n * sessions are read there. Default https://me.ochk.io (`OC_ME_ORIGIN` for\n * the list).\n */\n meOrigin?: string;\n /**\n * The check for sessions the person ended everywhere (sign out\n * everywhere, a passkey removed, the account deleted). Default, for a\n * token bound to your site: auth-core's `integratorRevocationCheck`, from\n * `OC_PROJECT_KEY` and `OC_SIGNING_SECRET`; none when they are unset. For a\n * family session (no `aud`, the ochk.io cookie a *.ochk.io site reads):\n * auth-core's `familyRevocationCheck`, from `OC_REVOCATION_FEED_TOKEN`, and\n * with that unset the call throws rather than read the session by its\n * signature alone (0.44.0). `false` turns the check off for both.\n */\n revocation?: RevocationCheck | false;\n}\n\n/** One check per me.ochk.io and project key, shared by every request in this process. */\nconst sessionChecks = new Map<string, RevocationCheck | null>();\nlet warnedUnchecked = false;\n\nfunction revocationFor(options: OcSessionOptions, session: SessionPayload): RevocationCheck | null {\n if (options.revocation === false) return null;\n if (options.revocation) return options.revocation;\n // A family session is ended on ochk.io's own feed, never on a project's list.\n if (isFamily(session)) {\n const token = typeof process !== 'undefined' ? process.env?.OC_REVOCATION_FEED_TOKEN?.trim() : undefined;\n if (!token) {\n throw new Error(\n '@orangecheck/me-client: a family session (no aud) is checked against ochk.io\\'s ' +\n 'revocation feed, and OC_REVOCATION_FEED_TOKEN is not set. Set it, or pass ' +\n '`revocation: false` to read family sessions by signature alone.'\n );\n }\n return familyRevocationCheck();\n }\n const key = `${options.meOrigin ?? ''} ${options.projectKey ?? ''}`;\n if (!sessionChecks.has(key)) {\n sessionChecks.set(\n key,\n integratorRevocationCheck({\n ...(options.projectKey ? { projectKey: options.projectKey } : {}),\n ...(options.meOrigin ? { meOrigin: options.meOrigin } : {}),\n })\n );\n }\n const check = sessionChecks.get(key)!;\n const production = typeof process !== 'undefined' && process.env?.NODE_ENV === 'production';\n if (!check && !warnedUnchecked && production) {\n warnedUnchecked = true;\n console.warn(\n '[@orangecheck/me-client] sessions are checked by signature only, so one the person ended ' +\n 'everywhere stays valid here until it expires. Set OC_PROJECT_KEY and OC_SIGNING_SECRET ' +\n 'to refuse it.'\n );\n }\n return check;\n}\n\n/** Tests only: forget the per-project checks and the one-time warnings. */\nexport function _resetSessionChecksForTests(): void {\n sessionChecks.clear();\n warnedUnchecked = false;\n warnedHandle = false;\n}\n\n/**\n * Verify the OC session for a request. Accepts either:\n *\n * - A Web Headers object (Hono / edge / Fetch API): `c.req.raw.headers`\n * - A plain `{ cookie, authorization }` object (Express / Next.js Pages /\n * Fastify / etc.): `{ cookie: req.headers.cookie, authorization: req.headers.authorization }`\n *\n * Reads the `oc_session` cookie first; falls back to\n * `Authorization: Bearer <token>` so cross-domain integrators (no\n * .ochk.io cookie reach) verify the same way.\n *\n * A session the person ended everywhere is refused once `OC_PROJECT_KEY` and\n * `OC_SIGNING_SECRET` are set (see {@link OcSessionOptions.revocation}).\n *\n * Returns `null` for unauthenticated requests. Throws only on an option it\n * does not read.\n */\nexport async function getOcSession(\n headers: SessionRequestHeaders | Headers,\n options: OcSessionOptions = {}\n): Promise<SessionPayload | null> {\n const checked = await checkOcSession(headers, options);\n return checked.status === 'signed_in' ? checked.session : null;\n}\n\n/** Why a session can't be told right now: the key set, or the list of ended sessions. */\nexport type OcSessionUnavailable = 'key_set_unavailable' | 'revocations_unavailable';\n\n/**\n * A request's session: signed in, signed out, or not checkable right now.\n * `reason` says why a token that verified is still signed out, or what can't\n * be read.\n */\nexport type OcSessionCheck =\n | { status: 'signed_in'; session: SessionPayload }\n | { status: 'signed_out'; reason?: OcSessionRefusal }\n | { status: 'unavailable'; reason?: OcSessionUnavailable };\n\n/**\n * `getOcSession`, telling \"signed out\" from \"can't tell right now\".\n * `unavailable` with `reason: 'key_set_unavailable'` when the request carries a\n * token and ochk.io's key set can't be read (with auth-core 2.16.0 or later),\n * and `'revocations_unavailable'` when the token verifies but me.ochk.io's list\n * of ended sessions can't vouch for this request (a write while the list can't\n * be read). A token the person ended is `signed_out`, and so is one bound to\n * your site with no revocation handle (`reason: 'no_session_handle'`, unless\n * `requireHandle: false`). The adapters answer `unavailable` with 503 and that\n * reason, so a client retries instead of signing the person out.\n */\nexport async function checkOcSession(\n headers: SessionRequestHeaders | Headers,\n options: OcSessionOptions = {}\n): Promise<OcSessionCheck> {\n checkOptions(options);\n const { issuer, jwksCacheTtlMs, jwksMaxStaleMs, audience } = options;\n const token = readOcSessionToken(headers);\n if (!token) return { status: 'signed_out' };\n const verified = await checkOcTokenCore(token, { issuer, jwksCacheTtlMs, jwksMaxStaleMs, audience });\n // An outage is never \"signed out\": the client retries.\n if (verified.status === 'unavailable') return { status: 'unavailable', reason: 'key_set_unavailable' };\n if (verified.status === 'invalid') {\n if (options.audience === undefined) warnIfAudienceMissing(headers);\n return { status: 'signed_out' };\n }\n const session = verified.session;\n if (lacksHandle(session, options.requireHandle)) {\n warnNoHandle(session);\n return { status: 'signed_out', reason: 'no_session_handle' };\n }\n const check = revocationFor(options, session);\n if (check) {\n // One read of the list, so the answer can't change between two.\n const state = await check.status(session);\n if (state === 'revoked') return { status: 'signed_out' };\n if (state === 'unverified' && !SAFE_METHODS.has((options.method ?? '').toUpperCase())) {\n return { status: 'unavailable', reason: 'revocations_unavailable' };\n }\n }\n return { status: 'signed_in', session: vouch(session) };\n}\n\nconst unavailable = (checked: { reason?: OcSessionUnavailable }) => ({\n status: 503,\n body: { ok: false, reason: checked.reason ?? 'revocations_unavailable' },\n});\n\nconst refusedFor = (checked: OcSessionCheck): OcSessionRefusal | undefined =>\n checked.status === 'signed_out' ? checked.reason : undefined;\n\nlet warnedAudience = false;\n\n/**\n * The popup issues a token bound to your site's origin. Verified with no\n * `audience`, it is refused — correctly, since a verifier with no audience\n * accepts only family sessions — and every popup sign-in would 401 with no\n * clue why. Say so, once, the first time it happens.\n */\nfunction warnIfAudienceMissing(headers: SessionRequestHeaders | Headers): void {\n if (warnedAudience) return;\n const web = typeof Headers !== 'undefined' && headers instanceof Headers;\n const auth = web ? headers.get('authorization') : (headers as SessionRequestHeaders).authorization;\n const cookie = web ? headers.get('cookie') : (headers as SessionRequestHeaders).cookie;\n // The token arrives as a Bearer, or in the oc_session cookie your own route set.\n const bearer = typeof auth === 'string' ? /^Bearer\\s+(\\S+)$/i.exec(auth.trim())?.[1] : undefined;\n const fromCookie =\n typeof cookie === 'string' ? /(?:^|;\\s*)oc_session=([^;]+)/.exec(cookie)?.[1] : undefined;\n const m = /^([^.]+)\\.([^.]+)\\./.exec(bearer ?? fromCookie ?? '');\n if (!m) return;\n try {\n const payload = JSON.parse(base64UrlToString(m[2]!)) as { aud?: unknown };\n if (payload.aud === undefined) return;\n warnedAudience = true;\n console.warn(\n `[@orangecheck/me-client] a sign-in token bound to ${JSON.stringify(payload.aud)} was refused ` +\n 'because no `audience` is configured. Pass your site origin, e.g. ' +\n \"withOcAuth(handler, { audience: 'https://your-site.example' }).\"\n );\n } catch {\n // Not a JWT we can read · nothing useful to say.\n }\n}\n\nfunction base64UrlToString(s: string): string {\n const b64 = s.replace(/-/g, '+').replace(/_/g, '/');\n if (typeof atob === 'function') return atob(b64 + '='.repeat((4 - (b64.length % 4)) % 4));\n return Buffer.from(s, 'base64url').toString('utf8');\n}\n\n// ─── Next.js Pages Router adapter ────────────────────────────────────────\n\ninterface NextApiRequestLike {\n method?: string;\n headers: { cookie?: string; authorization?: string; [k: string]: unknown };\n ocSession?: SessionPayload | null;\n}\ninterface NextApiResponseLike {\n status(code: number): NextApiResponseLike;\n json(body: unknown): unknown;\n setHeader(name: string, value: string | number | readonly string[]): unknown;\n}\n/** A request with the verified session attached: `WithOcSession<NextApiRequest>`. */\nexport type WithOcSession<Req> = Req & { ocSession?: SessionPayload | null };\n\nexport interface WithOcAuthOptions extends OcSessionOptions {\n /** When true, unauthenticated requests get a 401 + `{ok:false}` response\n * before the wrapped handler runs. Default: false — handler runs and\n * receives `req.ocSession === null`, useful when the route serves both\n * signed-in and anonymous users. */\n required?: boolean;\n /**\n * Refuse a signed-in account (403, `reason: 'bond_required'`) unless a\n * bond backs it: one unspent coin of at least `minSats`, unspent at least\n * `minDays` days, checked within `maxAgeSecs`. The app never learns the\n * coin; `req.ocSession.oc_bond.nullifier` is the same for the same coin at\n * your site, so ban that to ban the coin. Implies `required`.\n */\n requireBond?: { minSats?: number; minDays?: number; maxAgeSecs?: number };\n /**\n * Your project key. The requirement you set in the project's settings\n * (\"who can sign in\") is read from me.ochk.io within a minute of a change\n * and holds every signed-in account like `requireBond`, so you change it\n * there, not in code. A request with no session is not held to it and never\n * waits on reading it: pass `required` to answer it 401. An explicit\n * `requireBond` wins over it. Default `OC_PROJECT_KEY` for the ended-session\n * check only.\n */\n projectKey?: string;\n}\n\ntype BondNeed = NonNullable<WithOcAuthOptions['requireBond']>;\n\n/** The options the session check and the adapters read. */\nconst KNOWN_OPTIONS: ReadonlySet<string> = new Set<keyof WithOcAuthOptions>([\n 'issuer',\n 'jwksCacheTtlMs',\n 'jwksMaxStaleMs',\n 'audience',\n 'method',\n 'projectKey',\n 'meOrigin',\n 'revocation',\n 'requireHandle',\n 'required',\n 'requireBond',\n]);\nconst BOND_OPTIONS: ReadonlySet<string> = new Set<keyof BondNeed>(['minSats', 'minDays', 'maxAgeSecs']);\n\n/**\n * Throw on a key me-client does not read. Ignored, a misspelt `projectKey`\n * would skip the project's sign-in rule, a misspelt `audience` would accept\n * family sessions, and a misspelt `requireBond.minSats` would read as 0.\n */\nfunction checkOptions(options: WithOcAuthOptions): void {\n if (options === null || typeof options !== 'object') {\n throw new TypeError('@orangecheck/me-client: options must be an object');\n }\n const unknown = Object.keys(options).filter((k) => !KNOWN_OPTIONS.has(k));\n if (unknown.length > 0) {\n throw new TypeError(\n `@orangecheck/me-client: unknown option ${unknown.join(', ')}. ` +\n `It reads only ${[...KNOWN_OPTIONS].join(', ')}.`\n );\n }\n checkRequireHandle(options.requireHandle);\n const bond = options.requireBond;\n if (bond === undefined) return;\n if (bond === null || typeof bond !== 'object') {\n throw new TypeError('@orangecheck/me-client: requireBond must be an object');\n }\n const extra = Object.keys(bond).filter((k) => !BOND_OPTIONS.has(k));\n if (extra.length > 0) {\n throw new TypeError(\n `@orangecheck/me-client: requireBond: unknown option ${extra.join(', ')}. ` +\n `It reads only ${[...BOND_OPTIONS].join(', ')}.`\n );\n }\n}\n/** Where someone turned away for want of backing can back their account. */\nexport const BACK_ACCOUNT_URL = 'https://ochk.app/me/account#backing';\n/** A moment on both clocks: performance.now() and the wall clock. */\ntype Stamp = { mono: number; wall: number };\nconst stamp = (): Stamp => ({ mono: performance.now(), wall: Date.now() });\n/**\n * Time since a stamp: the longer of the two readings, so neither a wall clock\n * set back nor a pause performance.now() slept through (a suspended host) can\n * stretch a minute, a ten-second wait or the ten-minute standing.\n */\nconst since = (s: Stamp) => Math.max(performance.now() - s.mono, Date.now() - s.wall);\n/** Keys me.ochk.io answered 404 for, and when; re-checked after a minute. */\nconst unknownKeys = new Map<string, Stamp>();\nconst UNKNOWN_PROJECT = Symbol('unknown_project');\nconst POLICY_TTL_MS = 60_000;\n/** After a failed read, how long before me.ochk.io is asked again. */\nconst POLICY_RETRY_MS = 10_000;\n/** How long the last rule read stands while it can't be read again. */\nconst POLICY_MAX_STALE_MS = 600_000;\ntype ProjectRule = BondNeed | null | undefined | typeof UNKNOWN_PROJECT;\nconst policies = new Map<string, { at: Stamp | null; need: BondNeed | null; failedAt?: Stamp }>();\n/** The read in flight for each project: requests that arrive together share it. */\nconst policyReads = new Map<string, Promise<ProjectRule>>();\n\nconst isFloor = (n: unknown): n is number => Number.isSafeInteger(n) && (n as number) >= 0;\n\n/** The rule in me.ochk.io's answer, or undefined when the answer does not say one. */\nfunction readRequirement(body: unknown): BondNeed | null | undefined {\n const b = body as { ok?: unknown; require_bond?: unknown } | null;\n if (!b || typeof b !== 'object' || b.ok !== true || !('require_bond' in b)) return undefined;\n if (b.require_bond === null) return null;\n const r = b.require_bond as { min_sats?: unknown; min_days?: unknown } | undefined;\n if (!r || typeof r !== 'object' || !isFloor(r.min_sats) || !isFloor(r.min_days)) return undefined;\n return { minSats: r.min_sats, minDays: r.min_days };\n}\n\n/** The last rule read, while it is younger than ten minutes; undefined after. */\nfunction standing(slot: string): BondNeed | null | undefined {\n const hit = policies.get(slot);\n return hit?.at && since(hit.at) < POLICY_MAX_STALE_MS ? hit.need : undefined;\n}\n\n/**\n * The project's requirement, from its uncached sign-in endpoint, held a\n * minute here. (The price config is edge-cached for ten minutes: reading the\n * requirement there let a just-tightened app keep admitting unbacked accounts.)\n * When it can't be read, or the answer does not say it, the last one read\n * stands for ten minutes, and the next try waits ten seconds so an outage\n * doesn't hold every request; with none read in that time it is `undefined`,\n * and the request is refused rather than let through unchecked.\n */\nasync function projectRequirement(options: WithOcAuthOptions): Promise<ProjectRule> {\n const base = (options.meOrigin ?? 'https://me.ochk.io').replace(/\\/$/, '');\n const key = options.projectKey!;\n const slot = `${base} ${key}`;\n const unknownAt = unknownKeys.get(slot);\n if (unknownAt && since(unknownAt) < POLICY_TTL_MS) return UNKNOWN_PROJECT;\n const hit = policies.get(slot);\n if (hit?.at && since(hit.at) < POLICY_TTL_MS) return hit.need;\n if (hit?.failedAt && since(hit.failedAt) < POLICY_RETRY_MS) return standing(slot);\n let read = policyReads.get(slot);\n if (!read) {\n read = readProjectRule(base, key, slot).finally(() => policyReads.delete(slot));\n policyReads.set(slot, read);\n }\n return read;\n}\n\nasync function readProjectRule(base: string, key: string, slot: string): Promise<ProjectRule> {\n try {\n const r = await fetch(`${base}/api/integrator/${encodeURIComponent(key)}/sign-in`, {\n signal: AbortSignal.timeout(4000),\n });\n // A key that names no project is a setup mistake, not an outage: say so once.\n if (r.status === 404) {\n if (!unknownKeys.has(slot)) {\n console.error(\n `[@orangecheck/me-client] projectKey \"${key}\" is not a project. Copy yours from https://ochk.app/me/projects.`\n );\n }\n unknownKeys.set(slot, stamp());\n return UNKNOWN_PROJECT;\n }\n unknownKeys.delete(slot);\n if (!r.ok) throw new Error(`HTTP ${r.status}`);\n const need = readRequirement(await r.json());\n if (need === undefined) throw new Error('unexpected body');\n policies.set(slot, { at: stamp(), need });\n return need;\n } catch {\n // The wait counts from the failure, not from when the read began.\n const hit = policies.get(slot);\n policies.set(slot, { at: hit?.at ?? null, need: hit?.need ?? null, failedAt: stamp() });\n return standing(slot);\n }\n}\n\n/** The requirement in force: explicit, else the project's, else none. */\nasync function bondNeed(\n options: WithOcAuthOptions\n): Promise<BondNeed | null | undefined | typeof UNKNOWN_PROJECT> {\n if (options.requireBond) return options.requireBond;\n if (options.projectKey) return projectRequirement(options);\n return null;\n}\n\n/**\n * Why a session can't pass, as a status and body, or null when it can. `why`\n * names what turned a token away, so a 401 says it rather than \"unauthenticated\".\n */\nasync function refusal(\n session: SessionPayload | null,\n options: WithOcAuthOptions,\n why?: OcSessionRefusal\n): Promise<{ status: number; body: Record<string, unknown> } | null> {\n const unauthenticated = { status: 401, body: { ok: false, reason: why ?? 'unauthenticated' } };\n if (!session && options.required) return unauthenticated;\n // The project's rule is about who signs in: a request with no session is not\n // held to it, so it never waits on reading it.\n if (!session && !options.requireBond) return null;\n const need = await bondNeed(options);\n if (need === UNKNOWN_PROJECT) {\n return { status: 500, body: { ok: false, reason: 'unknown_project_key' } };\n }\n if (need === undefined) {\n return { status: 503, body: { ok: false, reason: 'bond_policy_unavailable' } };\n }\n if (!session) return need ? unauthenticated : null;\n if (need && !bondMeets(session, need)) {\n const have = readBondClaim(session);\n return {\n status: 403,\n body: {\n ok: false,\n reason: 'bond_required',\n need: {\n min_sats: need.minSats ?? 0,\n min_days: need.minDays ?? 0,\n ...(need.maxAgeSecs !== undefined ? { max_age_secs: need.maxAgeSecs } : {}),\n },\n have: have ? { sats_floor: have.sats_floor, days_floor: have.days_floor } : null,\n back_url: BACK_ACCOUNT_URL,\n },\n };\n }\n return null;\n}\n\n/** The options {@link checkSignInRule} reads. */\nexport interface SignInRuleOptions {\n /** Your project key: its \"who can sign in\" rule is read from me.ochk.io, as `withOcAuth` reads it. */\n projectKey?: string;\n /** Default `https://me.ochk.io`. */\n meOrigin?: string;\n /** An explicit floor, which wins over the project's rule. */\n requireBond?: WithOcAuthOptions['requireBond'];\n}\n\n/**\n * Whether a session meets the sign-in rule: `{ ok: true }`, or the status and\n * body the adapters answer with (403 `bond_required`, 503\n * `bond_policy_unavailable`, 500 `unknown_project_key`).\n */\nexport type SignInRuleCheck = { ok: true } | { ok: false; status: number; body: Record<string, unknown> };\n\nconst SIGN_IN_RULE_OPTIONS: ReadonlySet<string> = new Set<keyof SignInRuleOptions>([\n 'projectKey',\n 'meOrigin',\n 'requireBond',\n]);\n\n/**\n * Apply your project's \"who can sign in\" rule to a session you have already\n * verified, for a site whose own session replaces the token: `checkOcToken`\n * and `verifyOcToken` check the token, not the rule. It reads the rule with the\n * same one-minute cache and ten-minute stand-in as `withOcAuth`, and refuses\n * rather than lets in when no rule could be read.\n *\n * `session` is the object `verifyOcToken`, `checkOcToken`, `getOcSession` or\n * an adapter (`req.ocSession`) returned, as is. Anything else throws, a copy or\n * claims read back from your own store included: apply the rule in the route\n * that starts your session, where you hold the verified one. It also throws\n * on a missing rule or an option it does not read.\n *\n * const session = await verifyOcToken(token, { audience: 'https://your-site.example' });\n * if (!session) return res.status(401).json({ ok: false });\n * const checked = await checkSignInRule(session, { projectKey: process.env.OC_PROJECT_KEY! });\n * if (!checked.ok) return res.status(checked.status).json(checked.body);\n */\nexport async function checkSignInRule(\n session: SessionPayload,\n options: SignInRuleOptions\n): Promise<SignInRuleCheck> {\n if (options === null || typeof options !== 'object') {\n throw new TypeError('@orangecheck/me-client: options must be an object');\n }\n const unknown = Object.keys(options).filter((k) => !SIGN_IN_RULE_OPTIONS.has(k));\n if (unknown.length > 0) {\n throw new TypeError(\n `@orangecheck/me-client: unknown option ${unknown.join(', ')}. ` +\n `It reads only ${[...SIGN_IN_RULE_OPTIONS].join(', ')}.`\n );\n }\n checkOptions(options);\n if (!options.projectKey && !options.requireBond) {\n throw new TypeError('@orangecheck/me-client: checkSignInRule needs projectKey or requireBond');\n }\n if (session === null || typeof session !== 'object' || !VERIFIED.has(session)) {\n throw new TypeError(\n '@orangecheck/me-client: checkSignInRule takes the session verifyOcToken, checkOcToken or ' +\n 'getOcSession returned, as is, not claims read some other way'\n );\n }\n const refused = await refusal(session, options);\n return refused ? { ok: false, status: refused.status, body: refused.body } : { ok: true };\n}\n\n/**\n * Wrap a Next.js Pages-Router API route handler. Adds `req.ocSession` —\n * the verified SessionPayload, or null when unauthenticated.\n *\n * // pages/api/me/profile.ts\n * import { withOcAuth } from '@orangecheck/me-client/server';\n *\n * export default withOcAuth(async (req, res) => {\n * if (!req.ocSession) return res.status(401).json({ ok: false });\n * res.status(200).json({ account: { address: req.ocSession.did_oc } });\n * }, { required: true, audience: 'https://your-site.example' });\n *\n * `audience` is your own origin. The sign-in popup issues each site a token\n * bound to it; a site on *.ochk.io that reads the family cookie omits it.\n *\n * `Cache-Control: no-store, private` and `Vary: Cookie, Authorization`\n * are set on every authenticated response — without them a cached 401\n * leaks anonymous to authenticated callers.\n */\nexport function withOcAuth<\n Req extends NextApiRequestLike = NextApiRequestLike,\n Res extends NextApiResponseLike = NextApiResponseLike,\n>(\n handler: (req: WithOcSession<Req>, res: Res) => unknown,\n options: WithOcAuthOptions = {}\n): (req: Req, res: Res) => Promise<unknown> {\n checkOptions(options);\n return async (req: Req, res: Res) => {\n res.setHeader('Cache-Control', 'no-store, private');\n res.setHeader('Vary', 'Cookie, Authorization');\n const checked = await checkOcSession(\n {\n cookie: typeof req.headers.cookie === 'string' ? req.headers.cookie : null,\n authorization:\n typeof req.headers.authorization === 'string'\n ? req.headers.authorization\n : null,\n },\n { ...options, method: req.method }\n );\n const session = checked.status === 'signed_in' ? checked.session : null;\n const withSession = req as WithOcSession<Req>;\n withSession.ocSession = session;\n const refused =\n checked.status === 'unavailable'\n ? unavailable(checked)\n : await refusal(session, options, refusedFor(checked));\n if (refused) return res.status(refused.status).json(refused.body);\n return handler(withSession, res);\n };\n}\n\n// ─── Express / Connect middleware ────────────────────────────────────────\n\n// `req.ocSession` on Express's own Request type, so `ocAuthExpress()` routes\n// type-check without a cast. Inert when @types/express is absent.\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n ocSession?: SessionPayload | null;\n }\n }\n}\n\n/** Hono env for `ocAuthHono()`: `new Hono<OcHonoEnv>()` types `c.get('ocSession')`. */\nexport type OcHonoEnv = { Variables: { ocSession: SessionPayload | null } };\n\ninterface ExpressRequestLike {\n method?: string;\n headers: { cookie?: string; authorization?: string; [k: string]: unknown };\n ocSession?: SessionPayload | null;\n}\ninterface ExpressResponseLike {\n status(code: number): ExpressResponseLike;\n json(body: unknown): unknown;\n setHeader(name: string, value: string | number | readonly string[]): unknown;\n}\ntype ExpressNextLike = (err?: unknown) => void;\n\n/**\n * Express / Connect middleware. Attaches `req.ocSession` (verified\n * SessionPayload | null) and calls next(). Use it as a global middleware\n * or per-route.\n *\n * import express from 'express';\n * import { ocAuthExpress } from '@orangecheck/me-client/server';\n *\n * const app = express();\n * app.use(ocAuthExpress());\n *\n * app.get('/api/profile', (req, res) => {\n * if (!req.ocSession) return res.status(401).json({ error: 'sign in' });\n * res.json({ address: req.ocSession.did_oc });\n * });\n *\n * Pass `{ required: true }` to short-circuit unauthenticated requests\n * with a 401 before they reach your handler.\n */\nexport function ocAuthExpress(options: WithOcAuthOptions = {}) {\n checkOptions(options);\n return async (req: ExpressRequestLike, res: ExpressResponseLike, next: ExpressNextLike) => {\n try {\n res.setHeader('Cache-Control', 'no-store, private');\n res.setHeader('Vary', 'Cookie, Authorization');\n const checked = await checkOcSession(\n {\n cookie: typeof req.headers.cookie === 'string' ? req.headers.cookie : null,\n authorization:\n typeof req.headers.authorization === 'string'\n ? req.headers.authorization\n : null,\n },\n { ...options, method: req.method }\n );\n const session = checked.status === 'signed_in' ? checked.session : null;\n req.ocSession = session;\n const refused =\n checked.status === 'unavailable'\n ? unavailable(checked)\n : await refusal(session, options, refusedFor(checked));\n if (refused) {\n res.status(refused.status).json(refused.body);\n return;\n }\n next();\n } catch (err) {\n next(err);\n }\n };\n}\n\n// ─── Hono middleware ─────────────────────────────────────────────────────\n\ninterface HonoContextLike {\n req: { raw: { headers: Headers; method?: string } };\n set(key: string, value: unknown): void;\n json(body: unknown, status?: number): unknown;\n header(name: string, value: string): void;\n}\ntype HonoNextLike = () => Promise<void>;\n\n/**\n * Hono middleware. Attaches the verified session at `c.get('ocSession')`.\n *\n * import { Hono } from 'hono';\n * import { ocAuthHono, type OcHonoEnv } from '@orangecheck/me-client/server';\n *\n * const app = new Hono<OcHonoEnv>();\n * app.use('*', ocAuthHono());\n *\n * app.get('/api/profile', (c) => {\n * const session = c.get('ocSession');\n * if (!session) return c.json({ error: 'sign in' }, 401);\n * return c.json({ address: session.did_oc });\n * });\n */\nexport function ocAuthHono(options: WithOcAuthOptions = {}) {\n checkOptions(options);\n return async (c: HonoContextLike, next: HonoNextLike) => {\n c.header('Cache-Control', 'no-store, private');\n c.header('Vary', 'Cookie, Authorization');\n const checked = await checkOcSession(c.req.raw.headers, {\n ...options,\n method: c.req.raw.method,\n });\n const session = checked.status === 'signed_in' ? checked.session : null;\n c.set('ocSession', session);\n const refused =\n checked.status === 'unavailable'\n ? unavailable(checked)\n : await refusal(session, options, refusedFor(checked));\n if (refused) return c.json(refused.body, refused.status);\n await next();\n };\n}\n"]}