micro509 0.18.0 → 0.19.1

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.
Files changed (113) hide show
  1. package/CHANGELOG.md +109 -1
  2. package/dist/crypto/crypto.d.ts +11 -2
  3. package/dist/crypto/crypto.js +30 -17
  4. package/dist/crypto/crypto.js.map +1 -1
  5. package/dist/crypto.d.ts +2 -2
  6. package/dist/der/der.js.map +1 -1
  7. package/dist/index.d.ts +7 -6
  8. package/dist/internal/asn1/asn1.js +10 -2
  9. package/dist/internal/asn1/asn1.js.map +1 -1
  10. package/dist/internal/asn1/ber.js.map +1 -1
  11. package/dist/internal/asn1/decode-refusal.js.map +1 -1
  12. package/dist/internal/asn1/der.js.map +1 -1
  13. package/dist/internal/asn1/oids.js.map +1 -1
  14. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  15. package/dist/internal/crypto/ecdsa.js.map +1 -1
  16. package/dist/internal/crypto/hash.js +64 -64
  17. package/dist/internal/crypto/hash.js.map +1 -1
  18. package/dist/internal/crypto/pbes2.js +3 -3
  19. package/dist/internal/crypto/pbes2.js.map +1 -1
  20. package/dist/internal/crypto/prime-ec.js.map +1 -1
  21. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  22. package/dist/internal/crypto/sig-verify.d.ts +40 -0
  23. package/dist/internal/crypto/sig-verify.js +152 -65
  24. package/dist/internal/crypto/sig-verify.js.map +1 -1
  25. package/dist/internal/crypto/signing.js.map +1 -1
  26. package/dist/internal/jose/base64url.js.map +1 -1
  27. package/dist/internal/jose/json-data.js.map +1 -1
  28. package/dist/internal/jose/strict-json.js.map +1 -1
  29. package/dist/internal/shared/base64.js.map +1 -1
  30. package/dist/internal/shared/dn.js +1 -1
  31. package/dist/internal/shared/dn.js.map +1 -1
  32. package/dist/internal/shared/idna-tables.js +3 -3
  33. package/dist/internal/shared/idna.js.map +1 -1
  34. package/dist/internal/shared/ip.js.map +1 -1
  35. package/dist/internal/shared/mailbox.js.map +1 -1
  36. package/dist/internal/shared/punycode.js +1 -1
  37. package/dist/internal/shared/punycode.js.map +1 -1
  38. package/dist/internal/shared/uri-host.js.map +1 -1
  39. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  40. package/dist/internal/verify/policy-engine.js.map +1 -1
  41. package/dist/internal/verify/spki-distrust.js.map +1 -1
  42. package/dist/internal/verify/verify-path.js +222 -116
  43. package/dist/internal/verify/verify-path.js.map +1 -1
  44. package/dist/internal/x509/directory-name.js.map +1 -1
  45. package/dist/internal/x509/extension-bits.js.map +1 -1
  46. package/dist/internal/x509/extension-errors.js.map +1 -1
  47. package/dist/internal/x509/extension-registry.js.map +1 -1
  48. package/dist/internal/x509/general-name-profile.js.map +1 -1
  49. package/dist/internal/x509/general-name.js.map +1 -1
  50. package/dist/internal/x509/name-fields.js.map +1 -1
  51. package/dist/internal/x509/or-address.js.map +1 -1
  52. package/dist/jose/base64url.js.map +1 -1
  53. package/dist/jose/errors.js.map +1 -1
  54. package/dist/jose/jwe.js.map +1 -1
  55. package/dist/jose/jwks.js.map +1 -1
  56. package/dist/jose/jws.js.map +1 -1
  57. package/dist/jose/jwt.js.map +1 -1
  58. package/dist/jose/remote-jwks.js.map +1 -1
  59. package/dist/kdf/argon2-arithmetic.js.map +1 -1
  60. package/dist/kdf/argon2-core.js.map +1 -1
  61. package/dist/kdf/argon2-memory.js.map +1 -1
  62. package/dist/kdf/argon2-portable.js +1 -1
  63. package/dist/kdf/argon2-portable.js.map +1 -1
  64. package/dist/kdf/argon2.js +2 -2
  65. package/dist/kdf/argon2.js.map +1 -1
  66. package/dist/keys/keys.d.ts +7 -2
  67. package/dist/keys/keys.js +10 -6
  68. package/dist/keys/keys.js.map +1 -1
  69. package/dist/pem/pem.d.ts +20 -7
  70. package/dist/pem/pem.js +24 -20
  71. package/dist/pem/pem.js.map +1 -1
  72. package/dist/pem.d.ts +2 -2
  73. package/dist/pkcs/pfx.js.map +1 -1
  74. package/dist/pkcs/pkcs12-mac.js +3 -3
  75. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  76. package/dist/pkcs/pkcs7.d.ts +10 -0
  77. package/dist/pkcs/pkcs7.js +106 -88
  78. package/dist/pkcs/pkcs7.js.map +1 -1
  79. package/dist/result/result.js.map +1 -1
  80. package/dist/revocation/chain.d.ts +67 -13
  81. package/dist/revocation/chain.js +429 -301
  82. package/dist/revocation/chain.js.map +1 -1
  83. package/dist/revocation/crl.d.ts +65 -11
  84. package/dist/revocation/crl.js +472 -182
  85. package/dist/revocation/crl.js.map +1 -1
  86. package/dist/revocation/ocsp.d.ts +79 -24
  87. package/dist/revocation/ocsp.js +417 -231
  88. package/dist/revocation/ocsp.js.map +1 -1
  89. package/dist/revocation/revocation.d.ts +68 -13
  90. package/dist/revocation/revocation.js +194 -73
  91. package/dist/revocation/revocation.js.map +1 -1
  92. package/dist/revocation.d.ts +4 -4
  93. package/dist/ssh/ssh.js.map +1 -1
  94. package/dist/ssh/wire.js.map +1 -1
  95. package/dist/verify/identity.d.ts +2 -2
  96. package/dist/verify/identity.js +2 -2
  97. package/dist/verify/identity.js.map +1 -1
  98. package/dist/verify/verify.d.ts +84 -32
  99. package/dist/verify/verify.js +221 -175
  100. package/dist/verify/verify.js.map +1 -1
  101. package/dist/verify.d.ts +3 -2
  102. package/dist/x509/certificate.js.map +1 -1
  103. package/dist/x509/csr.js.map +1 -1
  104. package/dist/x509/extensions.js +1 -1
  105. package/dist/x509/extensions.js.map +1 -1
  106. package/dist/x509/fingerprint.js.map +1 -1
  107. package/dist/x509/name-text.js +1 -1
  108. package/dist/x509/name-text.js.map +1 -1
  109. package/dist/x509/name.js.map +1 -1
  110. package/dist/x509/parse.d.ts +6 -2
  111. package/dist/x509/parse.js +121 -121
  112. package/dist/x509/parse.js.map +1 -1
  113. package/package.json +16 -16
@@ -1 +1 @@
1
- {"version":3,"file":"jws.js","names":["_exhaustive","JWS_ALGORITHMS","MIN_RS256_MODULUS_BITS","MIN_JWS_RSA_MODULUS_BITS","ALGORITHM_PROFILES","OIDS","algorithm","DEFAULT_JOSE_LIMITS","LIMIT_NAMES","overrides","joseFailure","resolved","name","value","ceiling","successResult","textEncoder","strictDecoder","decodedBytes","code","message","segment","maxBytes","bytes","base64UrlDecode","text","serialization","parsed","parseStrictJson","limits","isJsonObject","notObjectCode","members","crit","isJsonArray","names","entry","object","alg","typ","kid","cty","token","bounds","segments","headerSegment","payloadSegment","signatureSegment","headerBytes","header","payload","signature","essence","parameters","type","normalized","separator","parameter","policy","member","rule","admitted","supported","first","exponent","byte","last","length","modulus","i","left","right","key","profile","usage","keyAlgorithm","options","algorithms","candidate","typeRule","tokenType","signal","prepared","details","status","unverified","signatureBytes","failure","verification","verifySignatureWithKey","input","throwMicro509Error","suitable","signingInput","base64UrlEncode","signData","joseSignature","ecdsaSignatureDerToRaw"],"sources":["../../src/jose/jws.ts"],"sourcesContent":["/**\n * Compact JWS (RFC 7515) parsing, signing and verification with an explicit algorithm and token\n * type policy. Parsing yields an {@linkcode UnverifiedJws}; only {@linkcode verifyCompactJws}\n * yields a {@linkcode VerifiedJws}.\n *\n * @module\n */\n\nimport { ecdsaSignatureDerToRaw, signData, verifySignatureWithKey } from '#micro509/crypto/crypto';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { base64UrlDecode, base64UrlEncode } from '#micro509/internal/jose/base64url';\nimport type { JsonObject, JsonValue } from '#micro509/internal/jose/strict-json';\nimport { isJsonArray, isJsonObject, parseStrictJson } from '#micro509/internal/jose/strict-json';\nimport type {\n\tJoseErrorDetails,\n\tJoseErrorResult,\n\tJoseResult,\n\tJwsParseErrorCode,\n\tKeyResolutionErrorCode,\n\tVerifyJwsErrorCode,\n} from '#micro509/jose/errors';\nimport { joseFailure } from '#micro509/jose/errors';\nimport { successResult, throwMicro509Error } from '#micro509/result/result';\n\n/** Signature algorithms this module signs and verifies. */\nexport type JwsAlgorithm = 'RS256' | 'RS384' | 'RS512' | 'ES256' | 'ES384';\n\n/** Every {@linkcode JwsAlgorithm}. */\nexport const JWS_ALGORITHMS: readonly JwsAlgorithm[] = [\n\t'RS256',\n\t'RS384',\n\t'RS512',\n\t'ES256',\n\t'ES384',\n];\n\n/** Smallest RSA modulus RS256 accepts (RFC 7518 §3.3). */\nexport const MIN_RS256_MODULUS_BITS = 2048;\n\n/** Smallest RSA modulus accepted by any implemented RSA JWS algorithm (RFC 7518 §3.3). */\nexport const MIN_JWS_RSA_MODULUS_BITS: number = MIN_RS256_MODULUS_BITS;\n\ntype JwsAlgorithmProfile =\n\t| { readonly kind: 'rsa'; readonly hash: 'SHA-256' | 'SHA-384' | 'SHA-512'; readonly oid: string }\n\t| {\n\t\t\treadonly kind: 'ec';\n\t\t\treadonly hash: 'SHA-256' | 'SHA-384';\n\t\t\treadonly curve: 'P-256' | 'P-384';\n\t\t\treadonly coordinateBytes: number;\n\t\t\treadonly oid: string;\n\t };\n\nconst ALGORITHM_PROFILES: Readonly<Record<JwsAlgorithm, JwsAlgorithmProfile>> = {\n\tRS256: { kind: 'rsa', hash: 'SHA-256', oid: OIDS.sha256WithRSAEncryption },\n\tRS384: { kind: 'rsa', hash: 'SHA-384', oid: OIDS.sha384WithRSAEncryption },\n\tRS512: { kind: 'rsa', hash: 'SHA-512', oid: OIDS.sha512WithRSAEncryption },\n\tES256: {\n\t\tkind: 'ec',\n\t\thash: 'SHA-256',\n\t\tcurve: 'P-256',\n\t\tcoordinateBytes: 32,\n\t\toid: OIDS.ecdsaWithSHA256,\n\t},\n\tES384: {\n\t\tkind: 'ec',\n\t\thash: 'SHA-384',\n\t\tcurve: 'P-384',\n\t\tcoordinateBytes: 48,\n\t\toid: OIDS.ecdsaWithSHA384,\n\t},\n};\n\n/** The exact key and signature profile for an admitted JWS algorithm. */\nexport function jwsAlgorithmProfile(algorithm: JwsAlgorithm): JwsAlgorithmProfile {\n\treturn ALGORITHM_PROFILES[algorithm];\n}\n\n/** Size and structure bounds enforced before any expensive parsing. */\nexport interface JoseLimits {\n\t/** Maximum compact serialization length in characters. Default `32768`. */\n\treadonly maxTokenLength: number;\n\t/** Maximum decoded protected header size in bytes. Default `4096`. */\n\treadonly maxHeaderBytes: number;\n\t/** Maximum decoded payload size in bytes. Default `16384`. */\n\treadonly maxPayloadBytes: number;\n\t/** Maximum decoded signature size in bytes. Default `1024`. */\n\treadonly maxSignatureBytes: number;\n\t/** Maximum JSON nesting in the header and payload. Default `16`. */\n\treadonly maxJsonDepth: number;\n\t/** Maximum JSON values in the header or payload. Default `2048`. */\n\treadonly maxJsonNodes: number;\n}\n\n/** The limits applied when a caller supplies none. */\nexport const DEFAULT_JOSE_LIMITS: JoseLimits = {\n\tmaxTokenLength: 32_768,\n\tmaxHeaderBytes: 4096,\n\tmaxPayloadBytes: 16_384,\n\tmaxSignatureBytes: 1024,\n\tmaxJsonDepth: 16,\n\tmaxJsonNodes: 2048,\n};\n\nconst LIMIT_NAMES = [\n\t'maxTokenLength',\n\t'maxHeaderBytes',\n\t'maxPayloadBytes',\n\t'maxSignatureBytes',\n\t'maxJsonDepth',\n\t'maxJsonNodes',\n] as const;\n\n/** Deepest JSON nesting any limit may allow; keeps the recursive parser inside the stack. */\nexport const MAX_JSON_DEPTH_LIMIT = 64;\n\n/**\n * Resolves caller-supplied limit overrides against {@linkcode DEFAULT_JOSE_LIMITS}. An omitted or\n * `undefined` field takes its default; any other value must be a positive safe integer, and\n * `maxJsonDepth` may not exceed {@linkcode MAX_JSON_DEPTH_LIMIT}.\n */\nexport function resolveJoseLimits(\n\toverrides: Partial<JoseLimits> | undefined,\n): JoseResult<JoseLimits, 'invalid_options'> {\n\tif (overrides !== undefined && (typeof overrides !== 'object' || overrides === null)) {\n\t\treturn joseFailure('invalid_options', 'limits must be an object');\n\t}\n\tconst resolved: { -readonly [Name in keyof JoseLimits]: JoseLimits[Name] } = {\n\t\t...DEFAULT_JOSE_LIMITS,\n\t};\n\tfor (const name of LIMIT_NAMES) {\n\t\tconst value = overrides?.[name];\n\t\tif (value === undefined) continue;\n\t\tconst ceiling = name === 'maxJsonDepth' ? MAX_JSON_DEPTH_LIMIT : Number.MAX_SAFE_INTEGER;\n\t\tif (!Number.isSafeInteger(value) || value < 1 || value > ceiling) {\n\t\t\treturn joseFailure('invalid_options', `limits.${name} must be a positive safe integer`);\n\t\t}\n\t\tresolved[name] = value;\n\t}\n\treturn successResult(resolved);\n}\n\n/** A protected header. Every member the token carried stays reachable through `members`. */\nexport interface JwsHeader<TAlgorithm extends string = string> {\n\t/** The `alg` member. */\n\treadonly alg: TAlgorithm;\n\t/** The `typ` member, when present. */\n\treadonly typ?: string;\n\t/** The `kid` member, when present. */\n\treadonly kid?: string;\n\t/** The `cty` member, when present. */\n\treadonly cty?: string;\n\t/** Every header member as the token carried it. */\n\treadonly members: JsonObject;\n}\n\n/**\n * A parsed token whose signature has not been checked. Nothing in it is trustworthy until\n * {@linkcode verifyCompactJws} succeeds.\n */\nexport interface UnverifiedJws {\n\t/** Always `false`. */\n\treadonly verified: false;\n\t/** The header, unauthenticated. */\n\treadonly header: JwsHeader;\n\t/** The payload bytes, unauthenticated. */\n\treadonly payload: Uint8Array;\n\t/** ASCII bytes of `BASE64URL(header) || '.' || BASE64URL(payload)`. */\n\treadonly signingInput: Uint8Array;\n\t/** The decoded signature bytes. */\n\treadonly signature: Uint8Array;\n}\n\n/** A token whose signature verified under the caller's algorithm and key policy. */\nexport interface VerifiedJws {\n\t/** Always `true`. */\n\treadonly verified: true;\n\t/** The authenticated protected header. */\n\treadonly header: JwsHeader<JwsAlgorithm>;\n\t/** The authenticated payload bytes. */\n\treadonly payload: Uint8Array;\n}\n\n/** What a key resolver is asked for. The header is unauthenticated. */\nexport interface JwsKeyRequest {\n\t/** The unauthenticated header of the token being verified. */\n\treadonly header: JwsHeader<JwsAlgorithm>;\n\t/** The algorithm the policy admitted for this token. */\n\treadonly algorithm: JwsAlgorithm;\n\t/** The `kid` header, when present. */\n\treadonly kid?: string;\n\t/** Cancellation from {@linkcode VerifyJwsOptions.signal}. */\n\treadonly signal?: AbortSignal;\n}\n\n/** Supplies the verification key for a token. */\nexport type JwsKeyResolver = (\n\trequest: JwsKeyRequest,\n) => Promise<JoseResult<CryptoKey, KeyResolutionErrorCode>>;\n\n/** Marks a policy dimension as deliberately not checked. */\nexport interface Unchecked {\n\t/** Always `true`. */\n\treadonly unchecked: true;\n}\n\n/**\n * Expectation for the `typ` header (RFC 7515 §4.1.9, RFC 8725 §3.11).\n *\n * A string requires that media type, compared case-insensitively with an omitted `application/`\n * prefix restored. `{ absent: true }` requires the header to be missing. `{ unchecked: true }`\n * accepts any value.\n */\nexport type TokenTypePolicy = string | { readonly absent: true } | Unchecked;\n\n/** Options for {@linkcode verifyCompactJws}. */\nexport interface VerifyJwsOptions {\n\t/** Algorithms admitted for this token use. Never derived from the token. */\n\treadonly algorithms: readonly [JwsAlgorithm, ...JwsAlgorithm[]];\n\t/** A fixed verification key, or a resolver chosen by the caller. */\n\treadonly key: CryptoKey | JwsKeyResolver;\n\t/** The token type this verification accepts. */\n\treadonly tokenType: TokenTypePolicy;\n\t/** Overrides for {@linkcode DEFAULT_JOSE_LIMITS}. */\n\treadonly limits?: Partial<JoseLimits>;\n\t/** Cancels key resolution. */\n\treadonly signal?: AbortSignal;\n}\n\n/** Header members {@linkcode signCompactJws} sets beside `alg`. */\nexport interface JwsHeaderInput {\n\t/** Token type. */\n\treadonly typ?: string;\n\t/** Key identifier. */\n\treadonly kid?: string;\n\t/** Content type. */\n\treadonly cty?: string;\n}\n\n/** Input for {@linkcode signCompactJws}. */\nexport interface SignJwsInput {\n\t/** A signing key matching the algorithm's RSA hash or ECDSA curve. RSA needs at least 2048 bits. */\n\treadonly privateKey: CryptoKey;\n\t/** The signature algorithm. */\n\treadonly algorithm: JwsAlgorithm;\n\t/** The payload bytes. */\n\treadonly payload: Uint8Array;\n\t/** Header members beside `alg`. */\n\treadonly header?: JwsHeaderInput;\n}\n\n/** Codes {@linkcode signCompactJws} and {@linkcode signJwt} throw. */\nexport type SignJoseErrorCode =\n\t| 'unsupported_algorithm'\n\t| 'incompatible_key'\n\t| 'invalid_header'\n\t| 'invalid_claims';\n\nconst textEncoder = new TextEncoder();\nconst strictDecoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });\n\nfunction maxEncodedLength(decodedBytes: number): number {\n\treturn Math.ceil((decodedBytes * 4) / 3);\n}\n\nfunction parseFailure<TCode extends JwsParseErrorCode>(\n\tcode: TCode,\n\tmessage: string,\n): JoseErrorResult<TCode> {\n\treturn joseFailure(code, message);\n}\n\nfunction decodeSegment(\n\tsegment: string,\n\tmaxBytes: number,\n\tname: string,\n): JoseResult<Uint8Array, JwsParseErrorCode> {\n\tif (segment.length > maxEncodedLength(maxBytes)) {\n\t\treturn parseFailure('limit_exceeded', `JWS ${name} exceeds ${maxBytes} bytes`);\n\t}\n\tconst bytes = base64UrlDecode(segment);\n\tif (bytes === undefined) {\n\t\treturn parseFailure('invalid_encoding', `JWS ${name} is not canonical base64url`);\n\t}\n\treturn successResult(bytes);\n}\n\n/** Decodes UTF-8 strictly and parses it as a JSON object with no duplicate members. */\nexport function decodeJsonObject<TCode extends 'invalid_header' | 'invalid_payload'>(\n\tbytes: Uint8Array,\n\tlimits: JoseLimits,\n\tname: string,\n\tnotObjectCode: TCode,\n\tserialization: 'JWS' | 'JWE' = 'JWS',\n): JoseResult<\n\tJsonObject,\n\tTCode | 'invalid_utf8' | 'invalid_json' | 'duplicate_member' | 'limit_exceeded'\n> {\n\tlet text: string;\n\ttry {\n\t\ttext = strictDecoder.decode(bytes);\n\t} catch {\n\t\treturn parseFailure('invalid_utf8', `${serialization} ${name} is not valid UTF-8`);\n\t}\n\tconst parsed = parseStrictJson(text, {\n\t\tmaxDepth: limits.maxJsonDepth,\n\t\tmaxNodes: limits.maxJsonNodes,\n\t});\n\tif (!parsed.ok) {\n\t\treturn parseFailure(parsed.code, `${serialization} ${name}: ${parsed.message}`);\n\t}\n\tconst value = parsed.value;\n\tif (!isJsonObject(value)) {\n\t\treturn parseFailure(notObjectCode, `${serialization} ${name} is not a JSON object`);\n\t}\n\treturn successResult(value);\n}\n\nfunction optionalString(\n\tmembers: JsonObject,\n\tname: string,\n): JoseResult<string | undefined, JwsParseErrorCode> {\n\tif (!Object.hasOwn(members, name)) return successResult(undefined);\n\tconst value = members[name];\n\tif (typeof value !== 'string') {\n\t\treturn parseFailure('invalid_header', `JWS header \"${name}\" is not a string`);\n\t}\n\treturn successResult(value);\n}\n\nfunction criticalNames(members: JsonObject): JoseResult<readonly string[], JwsParseErrorCode> {\n\tif (!Object.hasOwn(members, 'crit')) return successResult([]);\n\tconst crit: JsonValue | undefined = members.crit;\n\tif (!isJsonArray(crit) || crit.length === 0) {\n\t\treturn parseFailure('invalid_header', 'JWS header \"crit\" is not a non-empty array');\n\t}\n\tconst names: string[] = [];\n\tfor (const entry of crit) {\n\t\tif (typeof entry !== 'string' || names.includes(entry)) {\n\t\t\treturn parseFailure(\n\t\t\t\t'invalid_header',\n\t\t\t\t'JWS header \"crit\" holds a non-string or repeated name',\n\t\t\t);\n\t\t}\n\t\tnames.push(entry);\n\t}\n\treturn successResult(names);\n}\n\nfunction parseHeader(\n\tbytes: Uint8Array,\n\tlimits: JoseLimits,\n): JoseResult<JwsHeader, JwsParseErrorCode> {\n\tconst object = decodeJsonObject(bytes, limits, 'header', 'invalid_header');\n\tif (!object.ok) return object;\n\tconst members = object.value;\n\tconst alg = members.alg;\n\tif (typeof alg !== 'string' || alg.length === 0) {\n\t\treturn parseFailure('invalid_header', 'JWS header \"alg\" is missing or not a string');\n\t}\n\tconst typ = optionalString(members, 'typ');\n\tif (!typ.ok) return typ;\n\tconst kid = optionalString(members, 'kid');\n\tif (!kid.ok) return kid;\n\tconst cty = optionalString(members, 'cty');\n\tif (!cty.ok) return cty;\n\tconst crit = criticalNames(members);\n\tif (!crit.ok) return crit;\n\tif (members.b64 === false || crit.value.includes('b64')) {\n\t\treturn parseFailure(\n\t\t\t'unsupported_unencoded_payload',\n\t\t\t'Unencoded and detached payloads (RFC 7797) are not supported',\n\t\t);\n\t}\n\tif (Object.hasOwn(members, 'b64') && typeof members.b64 !== 'boolean') {\n\t\treturn parseFailure('invalid_header', 'JWS header \"b64\" is not a boolean');\n\t}\n\tif (crit.value.length > 0) {\n\t\treturn joseFailure('unsupported_critical_header', 'JWS header lists critical extensions', {\n\t\t\talg,\n\t\t\tcrit: crit.value,\n\t\t});\n\t}\n\treturn successResult({\n\t\talg,\n\t\t...(typ.value === undefined ? {} : { typ: typ.value }),\n\t\t...(kid.value === undefined ? {} : { kid: kid.value }),\n\t\t...(cty.value === undefined ? {} : { cty: cty.value }),\n\t\tmembers,\n\t});\n}\n\n/**\n * Parses a compact JWS without checking its signature.\n *\n * Refuses tokens that are oversized, do not have exactly three segments, carry non-canonical\n * base64url, invalid UTF-8, a header that is not a duplicate-free JSON object with a string `alg`,\n * a `crit` list, or an unencoded payload (`b64: false`). The result is {@linkcode UnverifiedJws};\n * pass the token to {@linkcode verifyCompactJws} before trusting any of it.\n */\nexport function parseCompactJws(\n\ttoken: string,\n\tlimits?: Partial<JoseLimits>,\n): JoseResult<UnverifiedJws, JwsParseErrorCode | 'invalid_options'> {\n\tconst resolved = resolveJoseLimits(limits);\n\tif (!resolved.ok) return resolved;\n\treturn parseWithLimits(token, resolved.value);\n}\n\nfunction parseWithLimits(\n\ttoken: string,\n\tbounds: JoseLimits,\n): JoseResult<UnverifiedJws, JwsParseErrorCode> {\n\tif (typeof token !== 'string') {\n\t\treturn parseFailure('malformed_token', 'JWS token is not a string');\n\t}\n\tif (token.length > bounds.maxTokenLength) {\n\t\treturn parseFailure('token_too_large', `JWS token exceeds ${bounds.maxTokenLength} characters`);\n\t}\n\tconst segments = token.split('.');\n\tconst [headerSegment, payloadSegment, signatureSegment] = segments;\n\tif (\n\t\tsegments.length !== 3 ||\n\t\theaderSegment === undefined ||\n\t\tpayloadSegment === undefined ||\n\t\tsignatureSegment === undefined ||\n\t\theaderSegment.length === 0\n\t) {\n\t\treturn parseFailure('malformed_token', 'JWS compact serialization needs three segments');\n\t}\n\tconst headerBytes = decodeSegment(headerSegment, bounds.maxHeaderBytes, 'header');\n\tif (!headerBytes.ok) return headerBytes;\n\tconst header = parseHeader(headerBytes.value, bounds);\n\tif (!header.ok) return header;\n\tconst payload = decodeSegment(payloadSegment, bounds.maxPayloadBytes, 'payload');\n\tif (!payload.ok) return payload;\n\tconst signature = decodeSegment(signatureSegment, bounds.maxSignatureBytes, 'signature');\n\tif (!signature.ok) return signature;\n\treturn successResult({\n\t\tverified: false,\n\t\theader: header.value,\n\t\tpayload: payload.value,\n\t\tsigningInput: textEncoder.encode(`${headerSegment}.${payloadSegment}`),\n\t\tsignature: signature.value,\n\t});\n}\n\n/**\n * Comparison key for a media type per RFC 7515 §4.1.9: type, subtype and parameter names fold to\n * lower case, an omitted `application/` is restored, and parameter values stay exact.\n */\nexport function mediaTypeKey(value: string): string {\n\tconst [essence = '', ...parameters] = value.split(';');\n\tconst type = essence.trim().toLowerCase();\n\tconst normalized = parameters.map((parameter) => {\n\t\tconst separator = parameter.indexOf('=');\n\t\treturn separator < 0\n\t\t\t? parameter.trim().toLowerCase()\n\t\t\t: `${parameter.slice(0, separator).trim().toLowerCase()}=${parameter.slice(separator + 1).trim()}`;\n\t});\n\treturn [type.includes('/') ? type : `application/${type}`, ...normalized].join(';');\n}\n\n/** A token type policy reduced to the one form verification compares against. */\nexport type TypeRule =\n\t| { readonly kind: 'media'; readonly key: string }\n\t| { readonly kind: 'absent' }\n\t| { readonly kind: 'unchecked' };\n\n/** Whether `value` is exactly `{ unchecked: true }`. */\nexport function isUncheckedPolicy(value: unknown): boolean {\n\treturn soleTrueMember(value) === 'unchecked';\n}\n\nfunction soleTrueMember(value: unknown): string | undefined {\n\tif (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n\tconst names = Object.keys(value);\n\tconst [name] = names;\n\tif (names.length !== 1 || name === undefined) return undefined;\n\treturn Reflect.get(value, name) === true ? name : undefined;\n}\n\nfunction normalizeTokenType(policy: unknown): TypeRule | undefined {\n\tif (typeof policy === 'string') return { kind: 'media', key: mediaTypeKey(policy) };\n\tconst member = soleTrueMember(policy);\n\tif (member === 'absent') return { kind: 'absent' };\n\tif (member === 'unchecked') return { kind: 'unchecked' };\n\treturn undefined;\n}\n\nfunction matchesTokenType(header: JwsHeader, rule: TypeRule): boolean {\n\tswitch (rule.kind) {\n\t\tcase 'media':\n\t\t\treturn header.typ !== undefined && mediaTypeKey(header.typ) === rule.key;\n\t\tcase 'unchecked':\n\t\t\treturn true;\n\t\tcase 'absent':\n\t\t\treturn header.typ === undefined;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = rule;\n\t\t\treturn _exhaustive;\n\t\t}\n\t}\n}\n\nfunction isAlgorithmAdmitted(\n\talgorithm: string,\n\tadmitted: readonly string[],\n): algorithm is JwsAlgorithm {\n\treturn (\n\t\tadmitted.includes(algorithm) && JWS_ALGORITHMS.some((supported) => supported === algorithm)\n\t);\n}\n\n/** Checks the observable RSA exponent constraints in RFC 8017 section 3.1. */\nexport function validRsaPublicExponent(exponent: Uint8Array, modulus?: Uint8Array): boolean {\n\tconst first = exponent.findIndex((byte) => byte !== 0);\n\tconst last = exponent[exponent.length - 1] ?? 0;\n\tif (first < 0 || (last & 1) === 0) return false;\n\tconst length = exponent.length - first;\n\tif (length === 1 && last < 3) return false;\n\tif (modulus === undefined) return true;\n\tif (length !== modulus.length) return length < modulus.length;\n\tfor (let i = 0; i < length; i++) {\n\t\tconst left = exponent[first + i] ?? 0;\n\t\tconst right = modulus[i] ?? 0;\n\t\tif (left !== right) return left < right;\n\t}\n\treturn false;\n}\n\n/** Checks the key profile and returns the exact JOSE signature length (RFC 7518 §§3.3–3.4). */\nexport function checkJwsVerificationKey(\n\tkey: CryptoKey,\n\talgorithm: JwsAlgorithm,\n): JoseResult<number, 'key_unsuitable'> {\n\treturn checkJwsKey(key, algorithm, 'public');\n}\n\nfunction checkJwsKey(\n\tkey: CryptoKey,\n\talgorithm: JwsAlgorithm,\n\ttype: 'public' | 'private',\n): JoseResult<number, 'key_unsuitable'> {\n\ttry {\n\t\treturn inspectJwsKey(key, algorithm, type);\n\t} catch {\n\t\treturn joseFailure('key_unsuitable', 'The key cannot be inspected');\n\t}\n}\n\nfunction inspectJwsKey(\n\tkey: CryptoKey,\n\talgorithm: JwsAlgorithm,\n\ttype: 'public' | 'private',\n): JoseResult<number, 'key_unsuitable'> {\n\tconst profile = jwsAlgorithmProfile(algorithm);\n\tconst usage = type === 'public' ? 'verify' : 'sign';\n\tif (key.type !== type || !key.usages.includes(usage)) {\n\t\treturn joseFailure('key_unsuitable', `${algorithm} needs a ${type} key with ${usage} usage`);\n\t}\n\tconst keyAlgorithm = key.algorithm;\n\tif (profile.kind === 'ec') {\n\t\tif (\n\t\t\tkeyAlgorithm.name !== 'ECDSA' ||\n\t\t\t!('namedCurve' in keyAlgorithm) ||\n\t\t\tkeyAlgorithm.namedCurve !== profile.curve\n\t\t) {\n\t\t\treturn joseFailure('key_unsuitable', `${algorithm} needs an ECDSA ${profile.curve} key`);\n\t\t}\n\t\treturn successResult(profile.coordinateBytes * 2);\n\t}\n\tif (\n\t\tkeyAlgorithm.name !== 'RSASSA-PKCS1-v1_5' ||\n\t\t!('hash' in keyAlgorithm) ||\n\t\ttypeof keyAlgorithm.hash !== 'object' ||\n\t\tkeyAlgorithm.hash === null ||\n\t\t!('name' in keyAlgorithm.hash) ||\n\t\tkeyAlgorithm.hash.name !== profile.hash\n\t) {\n\t\treturn joseFailure(\n\t\t\t'key_unsuitable',\n\t\t\t`${algorithm} needs an RSASSA-PKCS1-v1_5 ${profile.hash} key`,\n\t\t);\n\t}\n\tif (\n\t\t!('modulusLength' in keyAlgorithm) ||\n\t\ttypeof keyAlgorithm.modulusLength !== 'number' ||\n\t\tkeyAlgorithm.modulusLength < MIN_JWS_RSA_MODULUS_BITS\n\t) {\n\t\treturn joseFailure(\n\t\t\t'key_unsuitable',\n\t\t\t`${algorithm} needs an RSA modulus of at least ${MIN_JWS_RSA_MODULUS_BITS} bits`,\n\t\t);\n\t}\n\tif (\n\t\t!('publicExponent' in keyAlgorithm) ||\n\t\t!(keyAlgorithm.publicExponent instanceof Uint8Array) ||\n\t\t!validRsaPublicExponent(keyAlgorithm.publicExponent)\n\t) {\n\t\treturn joseFailure(\n\t\t\t'key_unsuitable',\n\t\t\t`${algorithm} needs a valid odd RSA public exponent of at least 3`,\n\t\t);\n\t}\n\treturn successResult(Math.ceil(keyAlgorithm.modulusLength / 8));\n}\n\n/** Verification options validated once and copied, so later changes by the caller cannot alter a run. */\nexport interface PreparedVerify {\n\t/** The admitted algorithms. */\n\treadonly algorithms: readonly JwsAlgorithm[];\n\t/** The fixed key or the resolver. */\n\treadonly key: CryptoKey | JwsKeyResolver;\n\t/** The token type rule. */\n\treadonly typeRule: TypeRule;\n\t/** The resolved limits. */\n\treadonly limits: JoseLimits;\n\t/** Cancellation for key resolution. */\n\treadonly signal: AbortSignal | undefined;\n}\n\nfunction isCryptoKey(value: unknown): value is CryptoKey {\n\treturn value instanceof CryptoKey;\n}\n\n/** Validates and copies verification options. Everything the run reads is captured here. */\nexport function prepareVerify(\n\toptions: VerifyJwsOptions,\n): JoseResult<PreparedVerify, 'invalid_options'> {\n\tif (typeof options !== 'object' || options === null) {\n\t\treturn joseFailure('invalid_options', 'Verification options are required');\n\t}\n\tconst { algorithms, key, tokenType, limits, signal } = options;\n\tif (!Array.isArray(algorithms) || algorithms.length === 0) {\n\t\treturn joseFailure('invalid_options', 'An explicit, non-empty algorithm list is required');\n\t}\n\tconst admitted: JwsAlgorithm[] = [];\n\tfor (const algorithm of algorithms) {\n\t\tconst supported = JWS_ALGORITHMS.find((candidate) => candidate === algorithm);\n\t\tif (supported === undefined) {\n\t\t\treturn joseFailure('invalid_options', 'The algorithm list names an unsupported algorithm');\n\t\t}\n\t\tadmitted.push(supported);\n\t}\n\tif (typeof key !== 'function' && !isCryptoKey(key)) {\n\t\treturn joseFailure('invalid_options', 'A key or key resolver is required');\n\t}\n\tconst typeRule = normalizeTokenType(tokenType);\n\tif (typeRule === undefined) {\n\t\treturn joseFailure('invalid_options', 'A token type policy is required');\n\t}\n\tif (signal !== undefined && !(signal instanceof AbortSignal)) {\n\t\treturn joseFailure('invalid_options', 'signal must be an AbortSignal');\n\t}\n\tconst bounds = resolveJoseLimits(limits);\n\tif (!bounds.ok) return bounds;\n\treturn successResult({ algorithms: admitted, key, typeRule, limits: bounds.value, signal });\n}\n\nasync function resolveKey(\n\tprepared: PreparedVerify,\n\theader: JwsHeader<JwsAlgorithm>,\n): Promise<JoseResult<CryptoKey, KeyResolutionErrorCode>> {\n\tconst { key, signal } = prepared;\n\tif (typeof key !== 'function') return successResult(key);\n\tlet resolved: unknown;\n\ttry {\n\t\tresolved = await key({\n\t\t\theader,\n\t\t\talgorithm: header.alg,\n\t\t\t...(header.kid === undefined ? {} : { kid: header.kid }),\n\t\t\t...(signal === undefined ? {} : { signal }),\n\t\t});\n\t} catch {\n\t\treturn signal?.aborted === true\n\t\t\t? joseFailure('aborted', 'Key resolution was cancelled')\n\t\t\t: joseFailure('key_resolution_failed', 'The key resolver failed');\n\t}\n\tif (typeof resolved !== 'object' || resolved === null) {\n\t\treturn joseFailure('key_resolution_failed', 'The key resolver returned no result');\n\t}\n\tif (Reflect.get(resolved, 'ok') === true) {\n\t\tconst value: unknown = Reflect.get(resolved, 'value');\n\t\treturn isCryptoKey(value)\n\t\t\t? successResult(value)\n\t\t\t: joseFailure('key_resolution_failed', 'The key resolver returned no key');\n\t}\n\tconst code: unknown = Reflect.get(resolved, 'code');\n\tswitch (code) {\n\t\tcase 'key_not_found':\n\t\tcase 'ambiguous_key':\n\t\tcase 'key_unsuitable':\n\t\tcase 'key_resolution_failed':\n\t\tcase 'jwks_unavailable':\n\t\tcase 'jwks_malformed':\n\t\tcase 'aborted':\n\t\t\treturn joseFailure(code, `Key resolution failed: ${code}`, resolverDetails(resolved));\n\t\tdefault:\n\t\t\treturn joseFailure('key_resolution_failed', 'The key resolver returned an unknown failure');\n\t}\n}\n\nfunction resolverDetails(resolved: object): JoseErrorDetails | undefined {\n\tconst details: unknown = Reflect.get(resolved, 'details');\n\tif (typeof details !== 'object' || details === null) return undefined;\n\tconst kid: unknown = Reflect.get(details, 'kid');\n\tconst status: unknown = Reflect.get(details, 'status');\n\treturn {\n\t\t...(typeof kid === 'string' ? { kid } : {}),\n\t\t...(typeof status === 'number' && Number.isSafeInteger(status) ? { status } : {}),\n\t};\n}\n\n/**\n * Verifies a compact JWS.\n *\n * The caller's `algorithms` list decides what is accepted; the token's `alg` only selects among\n * them, and `none` is always refused as `unsigned_token`. The `tokenType` policy is applied before\n * any key is resolved. The key must match the admitted algorithm's RSA hash (at least 2048 bits)\n * or ECDSA curve. ECDSA signatures must be fixed-width raw R || S, with no DER retry.\n * Header members such as `jku`, `jwk`, `x5u` and\n * `x5c` are never used to find a key. A resolver that throws or returns something other than a\n * result is reported as `key_resolution_failed` without its message.\n *\n * Returns a {@linkcode VerifiedJws} on success. Failures carry a stable code and never echo the\n * token.\n */\nexport async function verifyCompactJws(\n\ttoken: string,\n\toptions: VerifyJwsOptions,\n): Promise<JoseResult<VerifiedJws, VerifyJwsErrorCode>> {\n\tconst prepared = prepareVerify(options);\n\tif (!prepared.ok) return prepared;\n\treturn await verifyPrepared(token, prepared.value);\n}\n\n/** Verifies `token` under options already checked by {@linkcode prepareVerify}. */\nexport async function verifyPrepared(\n\ttoken: string,\n\tprepared: PreparedVerify,\n): Promise<JoseResult<VerifiedJws, VerifyJwsErrorCode>> {\n\tconst parsed = parseWithLimits(token, prepared.limits);\n\tif (!parsed.ok) return parsed;\n\tconst unverified = parsed.value;\n\tconst alg = unverified.header.alg;\n\tif (alg === 'none') {\n\t\treturn joseFailure('unsigned_token', 'Unsigned tokens are never accepted', { alg });\n\t}\n\tif (!isAlgorithmAdmitted(alg, prepared.algorithms)) {\n\t\treturn joseFailure('algorithm_not_allowed', 'The token algorithm is not in the allowed list', {\n\t\t\talg,\n\t\t});\n\t}\n\tif (!matchesTokenType(unverified.header, prepared.typeRule)) {\n\t\treturn joseFailure('token_type_mismatch', 'The token \"typ\" does not match the expected type', {\n\t\t\talg,\n\t\t});\n\t}\n\tconst header: JwsHeader<JwsAlgorithm> = { ...unverified.header, alg };\n\tconst key = await resolveKey(prepared, header);\n\tif (!key.ok) return key;\n\tconst signatureBytes = checkJwsVerificationKey(key.value, alg);\n\tif (!signatureBytes.ok) return signatureBytes;\n\tif (unverified.signature.length !== signatureBytes.value) {\n\t\treturn joseFailure(\n\t\t\t'invalid_signature',\n\t\t\t'The signature length does not match the algorithm and key',\n\t\t\t{\n\t\t\t\talg,\n\t\t\t},\n\t\t);\n\t}\n\tconst failure = joseFailure('invalid_signature', 'The signature does not verify', {\n\t\talg,\n\t\t...(header.kid === undefined ? {} : { kid: header.kid }),\n\t});\n\tconst verification = await verifySignatureWithKey({\n\t\tpublicKey: key.value,\n\t\tsignatureAlgorithm: { oid: jwsAlgorithmProfile(alg).oid },\n\t\tsignatureEncoding: 'raw',\n\t\tsignature: unverified.signature,\n\t\tdata: unverified.signingInput,\n\t});\n\tif (!verification.ok || !verification.valid) return failure;\n\treturn successResult({ verified: true, header, payload: unverified.payload });\n}\n\nfunction assertSigningKey(input: SignJwsInput): void {\n\tif (!JWS_ALGORITHMS.includes(input.algorithm)) {\n\t\tthrowMicro509Error('unsupported_algorithm', 'Unsupported JWS algorithm');\n\t}\n\tconst suitable = checkJwsKey(input.privateKey, input.algorithm, 'private');\n\tif (!suitable.ok) {\n\t\tthrowMicro509Error('incompatible_key', suitable.message);\n\t}\n}\n\n/**\n * Signs a compact JWS with an existing private `CryptoKey`.\n *\n * The header is `alg` followed by the optional `typ`, `kid` and `cty`. Throws a `ResultError`\n * (see `isResultError`) coded {@linkcode SignJoseErrorCode} when the algorithm, key or header\n * input is invalid. Intended for issuing tokens and for building synthetic tokens in tests.\n */\nexport async function signCompactJws(input: SignJwsInput): Promise<string> {\n\tassertSigningKey(input);\n\tconst profile = jwsAlgorithmProfile(input.algorithm);\n\tconst header: Record<string, string> = { alg: input.algorithm };\n\tfor (const name of ['typ', 'kid', 'cty'] as const) {\n\t\tconst value = input.header?.[name];\n\t\tif (value === undefined) continue;\n\t\tif (typeof value !== 'string') {\n\t\t\tthrowMicro509Error('invalid_header', `Header \"${name}\" must be a string`);\n\t\t}\n\t\theader[name] = value;\n\t}\n\tconst signingInput = `${base64UrlEncode(textEncoder.encode(JSON.stringify(header)))}.${base64UrlEncode(input.payload)}`;\n\tconst { signature } = await signData(input.privateKey, textEncoder.encode(signingInput));\n\tconst joseSignature =\n\t\tprofile.kind === 'ec' ? ecdsaSignatureDerToRaw(signature, profile.curve) : signature;\n\treturn `${signingInput}.${base64UrlEncode(joseSignature)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,MAAaC,IAA0C;CACtD;CACA;CACA;CACA;CACA;AACD,GAGaC,IAAyB,MAGzBC,IAAmCD,GAY1CE,IAA0E;CAC/E,OAAO;EAAE,MAAM;EAAO,MAAM;EAAW,KAAKC,EAAK;CAAwB;CACzE,OAAO;EAAE,MAAM;EAAO,MAAM;EAAW,KAAKA,EAAK;CAAwB;CACzE,OAAO;EAAE,MAAM;EAAO,MAAM;EAAW,KAAKA,EAAK;CAAwB;CACzE,OAAO;EACN,MAAM;EACN,MAAM;EACN,OAAO;EACP,iBAAiB;EACjB,KAAKA,EAAK;CACX;CACA,OAAO;EACN,MAAM;EACN,MAAM;EACN,OAAO;EACP,iBAAiB;EACjB,KAAKA,EAAK;CACX;AACD;;AAGA,SAAgB,oBAAoB,GAA8C;CACjF,OAAOD,EAAmBE;AAC3B;;AAmBA,MAAaC,IAAkC;CAC9C,gBAAgB;CAChB,gBAAgB;CAChB,iBAAiB;CACjB,mBAAmB;CACnB,cAAc;CACd,cAAc;AACf,GAEMC,IAAc;CACnB;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;AAUA,SAAgB,kBACf,GAC4C;CAC5C,IAAIC,MAAc,KAAA,MAAc,OAAOA,KAAc,aAA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CACpD,AAAKpF,EAAe,SAASyF,EAAM,SAAS,KAC3CC,EAAmB,yBAAyB,2BAA2B;CAExE,IAAMC,IAAW,YAAYF,EAAM,YAAYA,EAAM,WAAW,SAAS;CACzE,AAAKE,EAAS,MACbD,EAAmB,oBAAoBC,EAAS,OAAO;AAEzD;;;;;;;;AASA,eAAsB,eAAe,GAAsC;CAC1E,iBAAiBF,CAAK;CACtB,IAAMjB,IAAU,oBAAoBiB,EAAM,SAAS,GAC7CzC,IAAiC,EAAE,KAAKyC,EAAM,UAAU;CAC9D,KAAK,IAAM9E,KAAQ;EAAC;EAAO;EAAO;CAAK,GAAY;EAClD,IAAMC,IAAQ6E,EAAM,SAAS9E;EAC7B,AAAIC,MAAU,KAAA,MACV,OAAOA,KAAU,YACpB8E,EAAmB,kBAAkB,WAAW/E,EAAK,mBAAmB,GAEzE,EAAOA,KAAQC;CAChB;CACA,IAAMgF,IAAe,GAAGC,EAAgB9E,EAAY,OAAO,KAAK,UAAUiC,CAAM,CAAC,CAAC,EAAE,GAAG6C,EAAgBJ,EAAM,OAAO,KAC9G,EAAE,iBAAc,MAAMK,EAASL,EAAM,YAAY1E,EAAY,OAAO6E,CAAY,CAAC,GACjFG,IACLvB,EAAQ,SAAS,OAAOwB,EAAuB9C,GAAWsB,EAAQ,KAAK,IAAItB;CAC5E,OAAO,GAAG0C,EAAa,GAAGC,EAAgBE,CAAa;AACxD"}
1
+ {"version":3,"file":"jws.js","names":["_exhaustive","ecdsaSignatureDerToRaw","signData","verifySignatureWithKey","OIDS","base64UrlDecode","base64UrlEncode","isJsonArray","isJsonObject","parseStrictJson","joseFailure","successResult","throwMicro509Error","JWS_ALGORITHMS","MIN_RS256_MODULUS_BITS","MIN_JWS_RSA_MODULUS_BITS","ALGORITHM_PROFILES","algorithm","DEFAULT_JOSE_LIMITS","LIMIT_NAMES","overrides","resolved","name","value","ceiling","textEncoder","strictDecoder","decodedBytes","code","message","segment","maxBytes","bytes","limits","notObjectCode","serialization","text","parsed","members","crit","names","entry","object","alg","typ","kid","cty","token","bounds","segments","headerSegment","payloadSegment","signatureSegment","headerBytes","header","payload","signature","essence","parameters","type","normalized","parameter","separator","policy","member","rule","admitted","supported","exponent","modulus","first","byte","last","length","i","left","right","key","profile","usage","keyAlgorithm","options","algorithms","tokenType","signal","candidate","typeRule","prepared","details","status","unverified","signatureBytes","failure","verification","input","suitable","signingInput","joseSignature"],"sources":["../../src/jose/jws.ts"],"sourcesContent":["/**\n * Compact JWS (RFC 7515) parsing, signing and verification with an explicit algorithm and token\n * type policy. Parsing yields an {@linkcode UnverifiedJws}; only {@linkcode verifyCompactJws}\n * yields a {@linkcode VerifiedJws}.\n *\n * @module\n */\n\nimport { ecdsaSignatureDerToRaw, signData, verifySignatureWithKey } from '#micro509/crypto/crypto';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { base64UrlDecode, base64UrlEncode } from '#micro509/internal/jose/base64url';\nimport type { JsonObject, JsonValue } from '#micro509/internal/jose/strict-json';\nimport { isJsonArray, isJsonObject, parseStrictJson } from '#micro509/internal/jose/strict-json';\nimport type {\n\tJoseErrorDetails,\n\tJoseErrorResult,\n\tJoseResult,\n\tJwsParseErrorCode,\n\tKeyResolutionErrorCode,\n\tVerifyJwsErrorCode,\n} from '#micro509/jose/errors';\nimport { joseFailure } from '#micro509/jose/errors';\nimport { successResult, throwMicro509Error } from '#micro509/result/result';\n\n/** Signature algorithms this module signs and verifies. */\nexport type JwsAlgorithm = 'RS256' | 'RS384' | 'RS512' | 'ES256' | 'ES384';\n\n/** Every {@linkcode JwsAlgorithm}. */\nexport const JWS_ALGORITHMS: readonly JwsAlgorithm[] = [\n\t'RS256',\n\t'RS384',\n\t'RS512',\n\t'ES256',\n\t'ES384',\n];\n\n/** Smallest RSA modulus RS256 accepts (RFC 7518 §3.3). */\nexport const MIN_RS256_MODULUS_BITS = 2048;\n\n/** Smallest RSA modulus accepted by any implemented RSA JWS algorithm (RFC 7518 §3.3). */\nexport const MIN_JWS_RSA_MODULUS_BITS: number = MIN_RS256_MODULUS_BITS;\n\ntype JwsAlgorithmProfile =\n\t| { readonly kind: 'rsa'; readonly hash: 'SHA-256' | 'SHA-384' | 'SHA-512'; readonly oid: string }\n\t| {\n\t\t\treadonly kind: 'ec';\n\t\t\treadonly hash: 'SHA-256' | 'SHA-384';\n\t\t\treadonly curve: 'P-256' | 'P-384';\n\t\t\treadonly coordinateBytes: number;\n\t\t\treadonly oid: string;\n\t };\n\nconst ALGORITHM_PROFILES: Readonly<Record<JwsAlgorithm, JwsAlgorithmProfile>> = {\n\tRS256: { kind: 'rsa', hash: 'SHA-256', oid: OIDS.sha256WithRSAEncryption },\n\tRS384: { kind: 'rsa', hash: 'SHA-384', oid: OIDS.sha384WithRSAEncryption },\n\tRS512: { kind: 'rsa', hash: 'SHA-512', oid: OIDS.sha512WithRSAEncryption },\n\tES256: {\n\t\tkind: 'ec',\n\t\thash: 'SHA-256',\n\t\tcurve: 'P-256',\n\t\tcoordinateBytes: 32,\n\t\toid: OIDS.ecdsaWithSHA256,\n\t},\n\tES384: {\n\t\tkind: 'ec',\n\t\thash: 'SHA-384',\n\t\tcurve: 'P-384',\n\t\tcoordinateBytes: 48,\n\t\toid: OIDS.ecdsaWithSHA384,\n\t},\n};\n\n/** The exact key and signature profile for an admitted JWS algorithm. */\nexport function jwsAlgorithmProfile(algorithm: JwsAlgorithm): JwsAlgorithmProfile {\n\treturn ALGORITHM_PROFILES[algorithm];\n}\n\n/** Size and structure bounds enforced before any expensive parsing. */\nexport interface JoseLimits {\n\t/** Maximum compact serialization length in characters. Default `32768`. */\n\treadonly maxTokenLength: number;\n\t/** Maximum decoded protected header size in bytes. Default `4096`. */\n\treadonly maxHeaderBytes: number;\n\t/** Maximum decoded payload size in bytes. Default `16384`. */\n\treadonly maxPayloadBytes: number;\n\t/** Maximum decoded signature size in bytes. Default `1024`. */\n\treadonly maxSignatureBytes: number;\n\t/** Maximum JSON nesting in the header and payload. Default `16`. */\n\treadonly maxJsonDepth: number;\n\t/** Maximum JSON values in the header or payload. Default `2048`. */\n\treadonly maxJsonNodes: number;\n}\n\n/** The limits applied when a caller supplies none. */\nexport const DEFAULT_JOSE_LIMITS: JoseLimits = {\n\tmaxTokenLength: 32_768,\n\tmaxHeaderBytes: 4096,\n\tmaxPayloadBytes: 16_384,\n\tmaxSignatureBytes: 1024,\n\tmaxJsonDepth: 16,\n\tmaxJsonNodes: 2048,\n};\n\nconst LIMIT_NAMES = [\n\t'maxTokenLength',\n\t'maxHeaderBytes',\n\t'maxPayloadBytes',\n\t'maxSignatureBytes',\n\t'maxJsonDepth',\n\t'maxJsonNodes',\n] as const;\n\n/** Deepest JSON nesting any limit may allow; keeps the recursive parser inside the stack. */\nexport const MAX_JSON_DEPTH_LIMIT = 64;\n\n/**\n * Resolves caller-supplied limit overrides against {@linkcode DEFAULT_JOSE_LIMITS}. An omitted or\n * `undefined` field takes its default; any other value must be a positive safe integer, and\n * `maxJsonDepth` may not exceed {@linkcode MAX_JSON_DEPTH_LIMIT}.\n */\nexport function resolveJoseLimits(\n\toverrides: Partial<JoseLimits> | undefined,\n): JoseResult<JoseLimits, 'invalid_options'> {\n\tif (overrides !== undefined && (typeof overrides !== 'object' || overrides === null)) {\n\t\treturn joseFailure('invalid_options', 'limits must be an object');\n\t}\n\tconst resolved: { -readonly [Name in keyof JoseLimits]: JoseLimits[Name] } = {\n\t\t...DEFAULT_JOSE_LIMITS,\n\t};\n\tfor (const name of LIMIT_NAMES) {\n\t\tconst value = overrides?.[name];\n\t\tif (value === undefined) continue;\n\t\tconst ceiling = name === 'maxJsonDepth' ? MAX_JSON_DEPTH_LIMIT : Number.MAX_SAFE_INTEGER;\n\t\tif (!Number.isSafeInteger(value) || value < 1 || value > ceiling) {\n\t\t\treturn joseFailure('invalid_options', `limits.${name} must be a positive safe integer`);\n\t\t}\n\t\tresolved[name] = value;\n\t}\n\treturn successResult(resolved);\n}\n\n/** A protected header. Every member the token carried stays reachable through `members`. */\nexport interface JwsHeader<TAlgorithm extends string = string> {\n\t/** The `alg` member. */\n\treadonly alg: TAlgorithm;\n\t/** The `typ` member, when present. */\n\treadonly typ?: string;\n\t/** The `kid` member, when present. */\n\treadonly kid?: string;\n\t/** The `cty` member, when present. */\n\treadonly cty?: string;\n\t/** Every header member as the token carried it. */\n\treadonly members: JsonObject;\n}\n\n/**\n * A parsed token whose signature has not been checked. Nothing in it is trustworthy until\n * {@linkcode verifyCompactJws} succeeds.\n */\nexport interface UnverifiedJws {\n\t/** Always `false`. */\n\treadonly verified: false;\n\t/** The header, unauthenticated. */\n\treadonly header: JwsHeader;\n\t/** The payload bytes, unauthenticated. */\n\treadonly payload: Uint8Array;\n\t/** ASCII bytes of `BASE64URL(header) || '.' || BASE64URL(payload)`. */\n\treadonly signingInput: Uint8Array;\n\t/** The decoded signature bytes. */\n\treadonly signature: Uint8Array;\n}\n\n/** A token whose signature verified under the caller's algorithm and key policy. */\nexport interface VerifiedJws {\n\t/** Always `true`. */\n\treadonly verified: true;\n\t/** The authenticated protected header. */\n\treadonly header: JwsHeader<JwsAlgorithm>;\n\t/** The authenticated payload bytes. */\n\treadonly payload: Uint8Array;\n}\n\n/** What a key resolver is asked for. The header is unauthenticated. */\nexport interface JwsKeyRequest {\n\t/** The unauthenticated header of the token being verified. */\n\treadonly header: JwsHeader<JwsAlgorithm>;\n\t/** The algorithm the policy admitted for this token. */\n\treadonly algorithm: JwsAlgorithm;\n\t/** The `kid` header, when present. */\n\treadonly kid?: string;\n\t/** Cancellation from {@linkcode VerifyJwsOptions.signal}. */\n\treadonly signal?: AbortSignal;\n}\n\n/** Supplies the verification key for a token. */\nexport type JwsKeyResolver = (\n\trequest: JwsKeyRequest,\n) => Promise<JoseResult<CryptoKey, KeyResolutionErrorCode>>;\n\n/** Marks a policy dimension as deliberately not checked. */\nexport interface Unchecked {\n\t/** Always `true`. */\n\treadonly unchecked: true;\n}\n\n/**\n * Expectation for the `typ` header (RFC 7515 §4.1.9, RFC 8725 §3.11).\n *\n * A string requires that media type, compared case-insensitively with an omitted `application/`\n * prefix restored. `{ absent: true }` requires the header to be missing. `{ unchecked: true }`\n * accepts any value.\n */\nexport type TokenTypePolicy = string | { readonly absent: true } | Unchecked;\n\n/** Options for {@linkcode verifyCompactJws}. */\nexport interface VerifyJwsOptions {\n\t/** Algorithms admitted for this token use. Never derived from the token. */\n\treadonly algorithms: readonly [JwsAlgorithm, ...JwsAlgorithm[]];\n\t/** A fixed verification key, or a resolver chosen by the caller. */\n\treadonly key: CryptoKey | JwsKeyResolver;\n\t/** The token type this verification accepts. */\n\treadonly tokenType: TokenTypePolicy;\n\t/** Overrides for {@linkcode DEFAULT_JOSE_LIMITS}. */\n\treadonly limits?: Partial<JoseLimits>;\n\t/** Cancels key resolution. */\n\treadonly signal?: AbortSignal;\n}\n\n/** Header members {@linkcode signCompactJws} sets beside `alg`. */\nexport interface JwsHeaderInput {\n\t/** Token type. */\n\treadonly typ?: string;\n\t/** Key identifier. */\n\treadonly kid?: string;\n\t/** Content type. */\n\treadonly cty?: string;\n}\n\n/** Input for {@linkcode signCompactJws}. */\nexport interface SignJwsInput {\n\t/** A signing key matching the algorithm's RSA hash or ECDSA curve. RSA needs at least 2048 bits. */\n\treadonly privateKey: CryptoKey;\n\t/** The signature algorithm. */\n\treadonly algorithm: JwsAlgorithm;\n\t/** The payload bytes. */\n\treadonly payload: Uint8Array;\n\t/** Header members beside `alg`. */\n\treadonly header?: JwsHeaderInput;\n}\n\n/** Codes {@linkcode signCompactJws} and {@linkcode signJwt} throw. */\nexport type SignJoseErrorCode =\n\t| 'unsupported_algorithm'\n\t| 'incompatible_key'\n\t| 'invalid_header'\n\t| 'invalid_claims';\n\nconst textEncoder = new TextEncoder();\nconst strictDecoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });\n\nfunction maxEncodedLength(decodedBytes: number): number {\n\treturn Math.ceil((decodedBytes * 4) / 3);\n}\n\nfunction parseFailure<TCode extends JwsParseErrorCode>(\n\tcode: TCode,\n\tmessage: string,\n): JoseErrorResult<TCode> {\n\treturn joseFailure(code, message);\n}\n\nfunction decodeSegment(\n\tsegment: string,\n\tmaxBytes: number,\n\tname: string,\n): JoseResult<Uint8Array, JwsParseErrorCode> {\n\tif (segment.length > maxEncodedLength(maxBytes)) {\n\t\treturn parseFailure('limit_exceeded', `JWS ${name} exceeds ${maxBytes} bytes`);\n\t}\n\tconst bytes = base64UrlDecode(segment);\n\tif (bytes === undefined) {\n\t\treturn parseFailure('invalid_encoding', `JWS ${name} is not canonical base64url`);\n\t}\n\treturn successResult(bytes);\n}\n\n/** Decodes UTF-8 strictly and parses it as a JSON object with no duplicate members. */\nexport function decodeJsonObject<TCode extends 'invalid_header' | 'invalid_payload'>(\n\tbytes: Uint8Array,\n\tlimits: JoseLimits,\n\tname: string,\n\tnotObjectCode: TCode,\n\tserialization: 'JWS' | 'JWE' = 'JWS',\n): JoseResult<\n\tJsonObject,\n\tTCode | 'invalid_utf8' | 'invalid_json' | 'duplicate_member' | 'limit_exceeded'\n> {\n\tlet text: string;\n\ttry {\n\t\ttext = strictDecoder.decode(bytes);\n\t} catch {\n\t\treturn parseFailure('invalid_utf8', `${serialization} ${name} is not valid UTF-8`);\n\t}\n\tconst parsed = parseStrictJson(text, {\n\t\tmaxDepth: limits.maxJsonDepth,\n\t\tmaxNodes: limits.maxJsonNodes,\n\t});\n\tif (!parsed.ok) {\n\t\treturn parseFailure(parsed.code, `${serialization} ${name}: ${parsed.message}`);\n\t}\n\tconst value = parsed.value;\n\tif (!isJsonObject(value)) {\n\t\treturn parseFailure(notObjectCode, `${serialization} ${name} is not a JSON object`);\n\t}\n\treturn successResult(value);\n}\n\nfunction optionalString(\n\tmembers: JsonObject,\n\tname: string,\n): JoseResult<string | undefined, JwsParseErrorCode> {\n\tif (!Object.hasOwn(members, name)) return successResult(undefined);\n\tconst value = members[name];\n\tif (typeof value !== 'string') {\n\t\treturn parseFailure('invalid_header', `JWS header \"${name}\" is not a string`);\n\t}\n\treturn successResult(value);\n}\n\nfunction criticalNames(members: JsonObject): JoseResult<readonly string[], JwsParseErrorCode> {\n\tif (!Object.hasOwn(members, 'crit')) return successResult([]);\n\tconst crit: JsonValue | undefined = members.crit;\n\tif (!isJsonArray(crit) || crit.length === 0) {\n\t\treturn parseFailure('invalid_header', 'JWS header \"crit\" is not a non-empty array');\n\t}\n\tconst names: string[] = [];\n\tfor (const entry of crit) {\n\t\tif (typeof entry !== 'string' || names.includes(entry)) {\n\t\t\treturn parseFailure(\n\t\t\t\t'invalid_header',\n\t\t\t\t'JWS header \"crit\" holds a non-string or repeated name',\n\t\t\t);\n\t\t}\n\t\tnames.push(entry);\n\t}\n\treturn successResult(names);\n}\n\nfunction parseHeader(\n\tbytes: Uint8Array,\n\tlimits: JoseLimits,\n): JoseResult<JwsHeader, JwsParseErrorCode> {\n\tconst object = decodeJsonObject(bytes, limits, 'header', 'invalid_header');\n\tif (!object.ok) return object;\n\tconst members = object.value;\n\tconst alg = members.alg;\n\tif (typeof alg !== 'string' || alg.length === 0) {\n\t\treturn parseFailure('invalid_header', 'JWS header \"alg\" is missing or not a string');\n\t}\n\tconst typ = optionalString(members, 'typ');\n\tif (!typ.ok) return typ;\n\tconst kid = optionalString(members, 'kid');\n\tif (!kid.ok) return kid;\n\tconst cty = optionalString(members, 'cty');\n\tif (!cty.ok) return cty;\n\tconst crit = criticalNames(members);\n\tif (!crit.ok) return crit;\n\tif (members.b64 === false || crit.value.includes('b64')) {\n\t\treturn parseFailure(\n\t\t\t'unsupported_unencoded_payload',\n\t\t\t'Unencoded and detached payloads (RFC 7797) are not supported',\n\t\t);\n\t}\n\tif (Object.hasOwn(members, 'b64') && typeof members.b64 !== 'boolean') {\n\t\treturn parseFailure('invalid_header', 'JWS header \"b64\" is not a boolean');\n\t}\n\tif (crit.value.length > 0) {\n\t\treturn joseFailure('unsupported_critical_header', 'JWS header lists critical extensions', {\n\t\t\talg,\n\t\t\tcrit: crit.value,\n\t\t});\n\t}\n\treturn successResult({\n\t\talg,\n\t\t...(typ.value === undefined ? {} : { typ: typ.value }),\n\t\t...(kid.value === undefined ? {} : { kid: kid.value }),\n\t\t...(cty.value === undefined ? {} : { cty: cty.value }),\n\t\tmembers,\n\t});\n}\n\n/**\n * Parses a compact JWS without checking its signature.\n *\n * Refuses tokens that are oversized, do not have exactly three segments, carry non-canonical\n * base64url, invalid UTF-8, a header that is not a duplicate-free JSON object with a string `alg`,\n * a `crit` list, or an unencoded payload (`b64: false`). The result is {@linkcode UnverifiedJws};\n * pass the token to {@linkcode verifyCompactJws} before trusting any of it.\n */\nexport function parseCompactJws(\n\ttoken: string,\n\tlimits?: Partial<JoseLimits>,\n): JoseResult<UnverifiedJws, JwsParseErrorCode | 'invalid_options'> {\n\tconst resolved = resolveJoseLimits(limits);\n\tif (!resolved.ok) return resolved;\n\treturn parseWithLimits(token, resolved.value);\n}\n\nfunction parseWithLimits(\n\ttoken: string,\n\tbounds: JoseLimits,\n): JoseResult<UnverifiedJws, JwsParseErrorCode> {\n\tif (typeof token !== 'string') {\n\t\treturn parseFailure('malformed_token', 'JWS token is not a string');\n\t}\n\tif (token.length > bounds.maxTokenLength) {\n\t\treturn parseFailure('token_too_large', `JWS token exceeds ${bounds.maxTokenLength} characters`);\n\t}\n\tconst segments = token.split('.');\n\tconst [headerSegment, payloadSegment, signatureSegment] = segments;\n\tif (\n\t\tsegments.length !== 3 ||\n\t\theaderSegment === undefined ||\n\t\tpayloadSegment === undefined ||\n\t\tsignatureSegment === undefined ||\n\t\theaderSegment.length === 0\n\t) {\n\t\treturn parseFailure('malformed_token', 'JWS compact serialization needs three segments');\n\t}\n\tconst headerBytes = decodeSegment(headerSegment, bounds.maxHeaderBytes, 'header');\n\tif (!headerBytes.ok) return headerBytes;\n\tconst header = parseHeader(headerBytes.value, bounds);\n\tif (!header.ok) return header;\n\tconst payload = decodeSegment(payloadSegment, bounds.maxPayloadBytes, 'payload');\n\tif (!payload.ok) return payload;\n\tconst signature = decodeSegment(signatureSegment, bounds.maxSignatureBytes, 'signature');\n\tif (!signature.ok) return signature;\n\treturn successResult({\n\t\tverified: false,\n\t\theader: header.value,\n\t\tpayload: payload.value,\n\t\tsigningInput: textEncoder.encode(`${headerSegment}.${payloadSegment}`),\n\t\tsignature: signature.value,\n\t});\n}\n\n/**\n * Comparison key for a media type per RFC 7515 §4.1.9: type, subtype and parameter names fold to\n * lower case, an omitted `application/` is restored, and parameter values stay exact.\n */\nexport function mediaTypeKey(value: string): string {\n\tconst [essence = '', ...parameters] = value.split(';');\n\tconst type = essence.trim().toLowerCase();\n\tconst normalized = parameters.map((parameter) => {\n\t\tconst separator = parameter.indexOf('=');\n\t\treturn separator < 0\n\t\t\t? parameter.trim().toLowerCase()\n\t\t\t: `${parameter.slice(0, separator).trim().toLowerCase()}=${parameter.slice(separator + 1).trim()}`;\n\t});\n\treturn [type.includes('/') ? type : `application/${type}`, ...normalized].join(';');\n}\n\n/** A token type policy reduced to the one form verification compares against. */\nexport type TypeRule =\n\t| { readonly kind: 'media'; readonly key: string }\n\t| { readonly kind: 'absent' }\n\t| { readonly kind: 'unchecked' };\n\n/** Whether `value` is exactly `{ unchecked: true }`. */\nexport function isUncheckedPolicy(value: unknown): boolean {\n\treturn soleTrueMember(value) === 'unchecked';\n}\n\nfunction soleTrueMember(value: unknown): string | undefined {\n\tif (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n\tconst names = Object.keys(value);\n\tconst [name] = names;\n\tif (names.length !== 1 || name === undefined) return undefined;\n\treturn Reflect.get(value, name) === true ? name : undefined;\n}\n\nfunction normalizeTokenType(policy: unknown): TypeRule | undefined {\n\tif (typeof policy === 'string') return { kind: 'media', key: mediaTypeKey(policy) };\n\tconst member = soleTrueMember(policy);\n\tif (member === 'absent') return { kind: 'absent' };\n\tif (member === 'unchecked') return { kind: 'unchecked' };\n\treturn undefined;\n}\n\nfunction matchesTokenType(header: JwsHeader, rule: TypeRule): boolean {\n\tswitch (rule.kind) {\n\t\tcase 'media':\n\t\t\treturn header.typ !== undefined && mediaTypeKey(header.typ) === rule.key;\n\t\tcase 'unchecked':\n\t\t\treturn true;\n\t\tcase 'absent':\n\t\t\treturn header.typ === undefined;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = rule;\n\t\t\treturn _exhaustive;\n\t\t}\n\t}\n}\n\nfunction isAlgorithmAdmitted(\n\talgorithm: string,\n\tadmitted: readonly string[],\n): algorithm is JwsAlgorithm {\n\treturn (\n\t\tadmitted.includes(algorithm) && JWS_ALGORITHMS.some((supported) => supported === algorithm)\n\t);\n}\n\n/** Checks the observable RSA exponent constraints in RFC 8017 section 3.1. */\nexport function validRsaPublicExponent(exponent: Uint8Array, modulus?: Uint8Array): boolean {\n\tconst first = exponent.findIndex((byte) => byte !== 0);\n\tconst last = exponent[exponent.length - 1] ?? 0;\n\tif (first < 0 || (last & 1) === 0) return false;\n\tconst length = exponent.length - first;\n\tif (length === 1 && last < 3) return false;\n\tif (modulus === undefined) return true;\n\tif (length !== modulus.length) return length < modulus.length;\n\tfor (let i = 0; i < length; i++) {\n\t\tconst left = exponent[first + i] ?? 0;\n\t\tconst right = modulus[i] ?? 0;\n\t\tif (left !== right) return left < right;\n\t}\n\treturn false;\n}\n\n/** Checks the key profile and returns the exact JOSE signature length (RFC 7518 §§3.3–3.4). */\nexport function checkJwsVerificationKey(\n\tkey: CryptoKey,\n\talgorithm: JwsAlgorithm,\n): JoseResult<number, 'key_unsuitable'> {\n\treturn checkJwsKey(key, algorithm, 'public');\n}\n\nfunction checkJwsKey(\n\tkey: CryptoKey,\n\talgorithm: JwsAlgorithm,\n\ttype: 'public' | 'private',\n): JoseResult<number, 'key_unsuitable'> {\n\ttry {\n\t\treturn inspectJwsKey(key, algorithm, type);\n\t} catch {\n\t\treturn joseFailure('key_unsuitable', 'The key cannot be inspected');\n\t}\n}\n\nfunction inspectJwsKey(\n\tkey: CryptoKey,\n\talgorithm: JwsAlgorithm,\n\ttype: 'public' | 'private',\n): JoseResult<number, 'key_unsuitable'> {\n\tconst profile = jwsAlgorithmProfile(algorithm);\n\tconst usage = type === 'public' ? 'verify' : 'sign';\n\tif (key.type !== type || !key.usages.includes(usage)) {\n\t\treturn joseFailure('key_unsuitable', `${algorithm} needs a ${type} key with ${usage} usage`);\n\t}\n\tconst keyAlgorithm = key.algorithm;\n\tif (profile.kind === 'ec') {\n\t\tif (\n\t\t\tkeyAlgorithm.name !== 'ECDSA' ||\n\t\t\t!('namedCurve' in keyAlgorithm) ||\n\t\t\tkeyAlgorithm.namedCurve !== profile.curve\n\t\t) {\n\t\t\treturn joseFailure('key_unsuitable', `${algorithm} needs an ECDSA ${profile.curve} key`);\n\t\t}\n\t\treturn successResult(profile.coordinateBytes * 2);\n\t}\n\tif (\n\t\tkeyAlgorithm.name !== 'RSASSA-PKCS1-v1_5' ||\n\t\t!('hash' in keyAlgorithm) ||\n\t\ttypeof keyAlgorithm.hash !== 'object' ||\n\t\tkeyAlgorithm.hash === null ||\n\t\t!('name' in keyAlgorithm.hash) ||\n\t\tkeyAlgorithm.hash.name !== profile.hash\n\t) {\n\t\treturn joseFailure(\n\t\t\t'key_unsuitable',\n\t\t\t`${algorithm} needs an RSASSA-PKCS1-v1_5 ${profile.hash} key`,\n\t\t);\n\t}\n\tif (\n\t\t!('modulusLength' in keyAlgorithm) ||\n\t\ttypeof keyAlgorithm.modulusLength !== 'number' ||\n\t\tkeyAlgorithm.modulusLength < MIN_JWS_RSA_MODULUS_BITS\n\t) {\n\t\treturn joseFailure(\n\t\t\t'key_unsuitable',\n\t\t\t`${algorithm} needs an RSA modulus of at least ${MIN_JWS_RSA_MODULUS_BITS} bits`,\n\t\t);\n\t}\n\tif (\n\t\t!('publicExponent' in keyAlgorithm) ||\n\t\t!(keyAlgorithm.publicExponent instanceof Uint8Array) ||\n\t\t!validRsaPublicExponent(keyAlgorithm.publicExponent)\n\t) {\n\t\treturn joseFailure(\n\t\t\t'key_unsuitable',\n\t\t\t`${algorithm} needs a valid odd RSA public exponent of at least 3`,\n\t\t);\n\t}\n\treturn successResult(Math.ceil(keyAlgorithm.modulusLength / 8));\n}\n\n/** Verification options validated once and copied, so later changes by the caller cannot alter a run. */\nexport interface PreparedVerify {\n\t/** The admitted algorithms. */\n\treadonly algorithms: readonly JwsAlgorithm[];\n\t/** The fixed key or the resolver. */\n\treadonly key: CryptoKey | JwsKeyResolver;\n\t/** The token type rule. */\n\treadonly typeRule: TypeRule;\n\t/** The resolved limits. */\n\treadonly limits: JoseLimits;\n\t/** Cancellation for key resolution. */\n\treadonly signal: AbortSignal | undefined;\n}\n\nfunction isCryptoKey(value: unknown): value is CryptoKey {\n\treturn value instanceof CryptoKey;\n}\n\n/** Validates and copies verification options. Everything the run reads is captured here. */\nexport function prepareVerify(\n\toptions: VerifyJwsOptions,\n): JoseResult<PreparedVerify, 'invalid_options'> {\n\tif (typeof options !== 'object' || options === null) {\n\t\treturn joseFailure('invalid_options', 'Verification options are required');\n\t}\n\tconst { algorithms, key, tokenType, limits, signal } = options;\n\tif (!Array.isArray(algorithms) || algorithms.length === 0) {\n\t\treturn joseFailure('invalid_options', 'An explicit, non-empty algorithm list is required');\n\t}\n\tconst admitted: JwsAlgorithm[] = [];\n\tfor (const algorithm of algorithms) {\n\t\tconst supported = JWS_ALGORITHMS.find((candidate) => candidate === algorithm);\n\t\tif (supported === undefined) {\n\t\t\treturn joseFailure('invalid_options', 'The algorithm list names an unsupported algorithm');\n\t\t}\n\t\tadmitted.push(supported);\n\t}\n\tif (typeof key !== 'function' && !isCryptoKey(key)) {\n\t\treturn joseFailure('invalid_options', 'A key or key resolver is required');\n\t}\n\tconst typeRule = normalizeTokenType(tokenType);\n\tif (typeRule === undefined) {\n\t\treturn joseFailure('invalid_options', 'A token type policy is required');\n\t}\n\tif (signal !== undefined && !(signal instanceof AbortSignal)) {\n\t\treturn joseFailure('invalid_options', 'signal must be an AbortSignal');\n\t}\n\tconst bounds = resolveJoseLimits(limits);\n\tif (!bounds.ok) return bounds;\n\treturn successResult({ algorithms: admitted, key, typeRule, limits: bounds.value, signal });\n}\n\nasync function resolveKey(\n\tprepared: PreparedVerify,\n\theader: JwsHeader<JwsAlgorithm>,\n): Promise<JoseResult<CryptoKey, KeyResolutionErrorCode>> {\n\tconst { key, signal } = prepared;\n\tif (typeof key !== 'function') return successResult(key);\n\tlet resolved: unknown;\n\ttry {\n\t\tresolved = await key({\n\t\t\theader,\n\t\t\talgorithm: header.alg,\n\t\t\t...(header.kid === undefined ? {} : { kid: header.kid }),\n\t\t\t...(signal === undefined ? {} : { signal }),\n\t\t});\n\t} catch {\n\t\treturn signal?.aborted === true\n\t\t\t? joseFailure('aborted', 'Key resolution was cancelled')\n\t\t\t: joseFailure('key_resolution_failed', 'The key resolver failed');\n\t}\n\tif (typeof resolved !== 'object' || resolved === null) {\n\t\treturn joseFailure('key_resolution_failed', 'The key resolver returned no result');\n\t}\n\tif (Reflect.get(resolved, 'ok') === true) {\n\t\tconst value: unknown = Reflect.get(resolved, 'value');\n\t\treturn isCryptoKey(value)\n\t\t\t? successResult(value)\n\t\t\t: joseFailure('key_resolution_failed', 'The key resolver returned no key');\n\t}\n\tconst code: unknown = Reflect.get(resolved, 'code');\n\tswitch (code) {\n\t\tcase 'key_not_found':\n\t\tcase 'ambiguous_key':\n\t\tcase 'key_unsuitable':\n\t\tcase 'key_resolution_failed':\n\t\tcase 'jwks_unavailable':\n\t\tcase 'jwks_malformed':\n\t\tcase 'aborted':\n\t\t\treturn joseFailure(code, `Key resolution failed: ${code}`, resolverDetails(resolved));\n\t\tdefault:\n\t\t\treturn joseFailure('key_resolution_failed', 'The key resolver returned an unknown failure');\n\t}\n}\n\nfunction resolverDetails(resolved: object): JoseErrorDetails | undefined {\n\tconst details: unknown = Reflect.get(resolved, 'details');\n\tif (typeof details !== 'object' || details === null) return undefined;\n\tconst kid: unknown = Reflect.get(details, 'kid');\n\tconst status: unknown = Reflect.get(details, 'status');\n\treturn {\n\t\t...(typeof kid === 'string' ? { kid } : {}),\n\t\t...(typeof status === 'number' && Number.isSafeInteger(status) ? { status } : {}),\n\t};\n}\n\n/**\n * Verifies a compact JWS.\n *\n * The caller's `algorithms` list decides what is accepted; the token's `alg` only selects among\n * them, and `none` is always refused as `unsigned_token`. The `tokenType` policy is applied before\n * any key is resolved. The key must match the admitted algorithm's RSA hash (at least 2048 bits)\n * or ECDSA curve. ECDSA signatures must be fixed-width raw R || S, with no DER retry.\n * Header members such as `jku`, `jwk`, `x5u` and\n * `x5c` are never used to find a key. A resolver that throws or returns something other than a\n * result is reported as `key_resolution_failed` without its message.\n *\n * Returns a {@linkcode VerifiedJws} on success. Failures carry a stable code and never echo the\n * token.\n */\nexport async function verifyCompactJws(\n\ttoken: string,\n\toptions: VerifyJwsOptions,\n): Promise<JoseResult<VerifiedJws, VerifyJwsErrorCode>> {\n\tconst prepared = prepareVerify(options);\n\tif (!prepared.ok) return prepared;\n\treturn await verifyPrepared(token, prepared.value);\n}\n\n/** Verifies `token` under options already checked by {@linkcode prepareVerify}. */\nexport async function verifyPrepared(\n\ttoken: string,\n\tprepared: PreparedVerify,\n): Promise<JoseResult<VerifiedJws, VerifyJwsErrorCode>> {\n\tconst parsed = parseWithLimits(token, prepared.limits);\n\tif (!parsed.ok) return parsed;\n\tconst unverified = parsed.value;\n\tconst alg = unverified.header.alg;\n\tif (alg === 'none') {\n\t\treturn joseFailure('unsigned_token', 'Unsigned tokens are never accepted', { alg });\n\t}\n\tif (!isAlgorithmAdmitted(alg, prepared.algorithms)) {\n\t\treturn joseFailure('algorithm_not_allowed', 'The token algorithm is not in the allowed list', {\n\t\t\talg,\n\t\t});\n\t}\n\tif (!matchesTokenType(unverified.header, prepared.typeRule)) {\n\t\treturn joseFailure('token_type_mismatch', 'The token \"typ\" does not match the expected type', {\n\t\t\talg,\n\t\t});\n\t}\n\tconst header: JwsHeader<JwsAlgorithm> = { ...unverified.header, alg };\n\tconst key = await resolveKey(prepared, header);\n\tif (!key.ok) return key;\n\tconst signatureBytes = checkJwsVerificationKey(key.value, alg);\n\tif (!signatureBytes.ok) return signatureBytes;\n\tif (unverified.signature.length !== signatureBytes.value) {\n\t\treturn joseFailure(\n\t\t\t'invalid_signature',\n\t\t\t'The signature length does not match the algorithm and key',\n\t\t\t{\n\t\t\t\talg,\n\t\t\t},\n\t\t);\n\t}\n\tconst failure = joseFailure('invalid_signature', 'The signature does not verify', {\n\t\talg,\n\t\t...(header.kid === undefined ? {} : { kid: header.kid }),\n\t});\n\tconst verification = await verifySignatureWithKey({\n\t\tpublicKey: key.value,\n\t\tsignatureAlgorithm: { oid: jwsAlgorithmProfile(alg).oid },\n\t\tsignatureEncoding: 'raw',\n\t\tsignature: unverified.signature,\n\t\tdata: unverified.signingInput,\n\t});\n\tif (!verification.ok || !verification.valid) return failure;\n\treturn successResult({ verified: true, header, payload: unverified.payload });\n}\n\nfunction assertSigningKey(input: SignJwsInput): void {\n\tif (!JWS_ALGORITHMS.includes(input.algorithm)) {\n\t\tthrowMicro509Error('unsupported_algorithm', 'Unsupported JWS algorithm');\n\t}\n\tconst suitable = checkJwsKey(input.privateKey, input.algorithm, 'private');\n\tif (!suitable.ok) {\n\t\tthrowMicro509Error('incompatible_key', suitable.message);\n\t}\n}\n\n/**\n * Signs a compact JWS with an existing private `CryptoKey`.\n *\n * The header is `alg` followed by the optional `typ`, `kid` and `cty`. Throws a `ResultError`\n * (see `isResultError`) coded {@linkcode SignJoseErrorCode} when the algorithm, key or header\n * input is invalid. Intended for issuing tokens and for building synthetic tokens in tests.\n */\nexport async function signCompactJws(input: SignJwsInput): Promise<string> {\n\tassertSigningKey(input);\n\tconst profile = jwsAlgorithmProfile(input.algorithm);\n\tconst header: Record<string, string> = { alg: input.algorithm };\n\tfor (const name of ['typ', 'kid', 'cty'] as const) {\n\t\tconst value = input.header?.[name];\n\t\tif (value === undefined) continue;\n\t\tif (typeof value !== 'string') {\n\t\t\tthrowMicro509Error('invalid_header', `Header \"${name}\" must be a string`);\n\t\t}\n\t\theader[name] = value;\n\t}\n\tconst signingInput = `${base64UrlEncode(textEncoder.encode(JSON.stringify(header)))}.${base64UrlEncode(input.payload)}`;\n\tconst { signature } = await signData(input.privateKey, textEncoder.encode(signingInput));\n\tconst joseSignature =\n\t\tprofile.kind === 'ec' ? ecdsaSignatureDerToRaw(signature, profile.curve) : signature;\n\treturn `${signingInput}.${base64UrlEncode(joseSignature)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,MAAaa,IAA0C;CACtD;CACA;CACA;CACA;CACA;AACD,GAGaC,IAAyB,MAGzBC,IAAmCD,GAY1CE,IAA0E;CAC/E,OAAO;EAAE,MAAM;EAAO,MAAM;EAAW,KAAKZ,EAAK;CAAwB;CACzE,OAAO;EAAE,MAAM;EAAO,MAAM;EAAW,KAAKA,EAAK;CAAwB;CACzE,OAAO;EAAE,MAAM;EAAO,MAAM;EAAW,KAAKA,EAAK;CAAwB;CACzE,OAAO;EACN,MAAM;EACN,MAAM;EACN,OAAO;EACP,iBAAiB;EACjB,KAAKA,EAAK;CACX;CACA,OAAO;EACN,MAAM;EACN,MAAM;EACN,OAAO;EACP,iBAAiB;EACjB,KAAKA,EAAK;CACX;AACD;;AAGA,SAAgB,oBAAoBa,GAA8C;CACjF,OAAOD,EAAmBC;AAC3B;;AAmBA,MAAaC,IAAkC;CAC9C,gBAAgB;CAChB,gBAAgB;CAChB,iBAAiB;CACjB,mBAAmB;CACnB,cAAc;CACd,cAAc;AACf,GAEMC,IAAc;CACnB;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;AAUA,SAAgB,kBACfC,GAC4C;CAC5C,IAAIA,MAAc,KAAA,MAAc,OAAOA,KAAc,aAAYA,IAChE,OAAOV,EAAY,mBAAmB,0BAA0B;CAEjE,IAAMW,IAAuE,EAC5E,GAAGH,EACJ;CACA,KAAK,IAAMI,KAAQH,GAAa;EAC/B,IAAMI,IAAQH,IAAYE;EAC1B,IAAIC,MAAU,KAAA,GAAW;EACzB,IAAMC,IAAUF,MAAS,iBAAA;EACzB,IAAI,CAAC,OAAO,cAAcC,CAAK,KAAKA,I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,EAAM,WAAW,SAAS;CACpEC,EAAS,MACbnF,EAAmB,oBAAoBmF,EAAS,OAAO;AAEzD;;;;;;;;AASA,eAAsB,eAAeD,GAAsC;CAC1E,iBAAiBA,CAAK;CACtB,IAAMhB,IAAU,oBAAoBgB,EAAM,SAAS,GAC7CxC,IAAiC,EAAE,KAAKwC,EAAM,UAAU;CAC9D,KAAK,IAAMxE,KAAQ;EAAC;EAAO;EAAO;CAAK,GAAY;EAClD,IAAMC,IAAQuE,EAAM,SAASxE;EACzBC,MAAU,KAAA,MACV,OAAOA,KAAU,YACpBX,EAAmB,kBAAkB,WAAWU,EAAK,mBAAmB,GAEzEgC,EAAOhC,KAAQC;CAChB;CACA,IAAMyE,IAAe,GAAG1F,EAAgBmB,EAAY,OAAO,KAAK,UAAU6B,CAAM,CAAC,CAAC,EAAE,GAAGhD,EAAgBwF,EAAM,OAAO,KAC9G,EAAEtC,iBAAc,MAAMtD,EAAS4F,EAAM,YAAYrE,EAAY,OAAOuE,CAAY,CAAC,GACjFC,IACLnB,EAAQ,SAAS,OAAO7E,EAAuBuD,GAAWsB,EAAQ,KAAK,IAAItB;CAC5E,OAAO,GAAGwC,EAAa,GAAG1F,EAAgB2F,CAAa;AACxD"}
@@ -1 +1 @@
1
- {"version":3,"file":"jwt.js","names":["MAX_CLOCK_TOLERANCE_SECONDS","header","mediaTypeKey","joseFailure","decodeJsonObject","payload","limits","bounds","resolveJoseLimits","parsed","parseCompactJws","token","claims","successResult","code","message","name","value","isJsonArray","audiences","entry","iss","sub","jti","aud","exp","nbf","iat","expectation","isUncheckedPolicy","policy","tolerance","maxAge","required","issuers","registered","nowSeconds","reading","identity","now","times","options","claimsPolicy","prepared","prepareVerify","jws","verifyPrepared","input","throwMicro509Error","_claims","rest","signCompactJws"],"sources":["../../src/jose/jwt.ts"],"sourcesContent":["/**\n * JWT (RFC 7519) validation on top of compact JWS. Signature verification and the claims policy\n * are separate steps with separate types: {@linkcode decodeJwtUnverified} yields an\n * {@linkcode UnverifiedJwt}, and only {@linkcode verifyJwt} yields a {@linkcode VerifiedJwt}.\n *\n * @module\n */\n\nimport type { JsonObject } from '#micro509/internal/jose/strict-json';\nimport { isJsonArray } from '#micro509/internal/jose/strict-json';\nimport type {\n\tJoseErrorResult,\n\tJoseResult,\n\tJwsParseErrorCode,\n\tVerifyJwtErrorCode,\n} from '#micro509/jose/errors';\nimport { joseFailure } from '#micro509/jose/errors';\nimport type {\n\tJoseLimits,\n\tJwsAlgorithm,\n\tJwsHeader,\n\tSignJwsInput,\n\tUnchecked,\n\tVerifyJwsOptions,\n} from '#micro509/jose/jws';\nimport {\n\tdecodeJsonObject,\n\tisUncheckedPolicy,\n\tmediaTypeKey,\n\tparseCompactJws,\n\tprepareVerify,\n\tresolveJoseLimits,\n\tsignCompactJws,\n\tverifyPrepared,\n} from '#micro509/jose/jws';\nimport { successResult, throwMicro509Error } from '#micro509/result/result';\n\n/** Largest clock tolerance {@linkcode JwtClaimsPolicy.clockToleranceSeconds} accepts. */\nexport const MAX_CLOCK_TOLERANCE_SECONDS = 600;\n\n/** The RFC 7519 §4.1 registered claims, each checked against its defined type. */\nexport interface RegisteredClaims {\n\t/** Issuer. */\n\treadonly iss?: string;\n\t/** Subject. */\n\treadonly sub?: string;\n\t/** Audience, as the token carried it: a string or an array of strings. */\n\treadonly aud?: string | readonly string[];\n\t/** Expiration time in seconds since the epoch. */\n\treadonly exp?: number;\n\t/** Not-before time in seconds since the epoch. */\n\treadonly nbf?: number;\n\t/** Issued-at time in seconds since the epoch. */\n\treadonly iat?: number;\n\t/** Token identifier. */\n\treadonly jti?: string;\n}\n\n/** A decoded JWT whose signature has not been checked. */\nexport interface UnverifiedJwt {\n\t/** Always `false`. */\n\treadonly verified: false;\n\t/** The header, unauthenticated. */\n\treadonly header: JwsHeader;\n\t/** The claims, unauthenticated and not policy-checked. */\n\treadonly claims: JsonObject;\n}\n\n/** A JWT whose signature and claims both passed the caller's policy. */\nexport interface VerifiedJwt {\n\t/** Always `true`. */\n\treadonly verified: true;\n\t/** The authenticated protected header. */\n\treadonly header: JwsHeader<JwsAlgorithm>;\n\t/** Every authenticated claim, exactly as the token carried it. */\n\treadonly claims: JsonObject;\n\t/** The registered claims, validated against their types. */\n\treadonly registered: RegisteredClaims;\n}\n\n/** Whether an `iat` later than the clock is accepted. */\nexport type FutureIssuedAtPolicy = 'reject' | 'allow';\n\n/** Claims policy for {@linkcode verifyJwt}. Application authorization stays with the caller. */\nexport interface JwtClaimsPolicy {\n\t/** Accepted `iss` values (any one may match), or `{ unchecked: true }`. */\n\treadonly issuer: string | readonly string[] | Unchecked;\n\t/** Accepted `aud` values (any one may match), or `{ unchecked: true }`. */\n\treadonly audience: string | readonly string[] | Unchecked;\n\t/** Claims that must be present. Default `['exp']`. */\n\treadonly requiredClaims?: readonly string[];\n\t/** The clock. Default is the system time. */\n\treadonly now?: () => Date;\n\t/** Leeway in seconds for `exp`, `nbf` and `iat`, from 0 to 600. Default `0`. */\n\treadonly clockToleranceSeconds?: number;\n\t/** Oldest acceptable token age in seconds, measured from `iat`. Requires `iat`. */\n\treadonly maxAgeSeconds?: number;\n\t/** Whether `iat` after the clock is accepted. Default `'reject'`. */\n\treadonly futureIssuedAt?: FutureIssuedAtPolicy;\n}\n\n/** Options for {@linkcode verifyJwt}. */\nexport interface VerifyJwtOptions extends VerifyJwsOptions {\n\t/** Claims policy. */\n\treadonly claims: JwtClaimsPolicy;\n}\n\n/** Input for {@linkcode signJwt}. */\nexport interface SignJwtInput extends Omit<SignJwsInput, 'payload'> {\n\t/** The claims to sign. Must be JSON-serializable. */\n\treadonly claims: JsonObject;\n}\n\nfunction decodeClaims(\n\theader: JwsHeader,\n\tpayload: Uint8Array,\n\tlimits: JoseLimits,\n): JoseResult<JsonObject, JwsParseErrorCode> {\n\tif (header.cty !== undefined && mediaTypeKey(header.cty) === 'application/jwt') {\n\t\treturn joseFailure('unsupported_nested_jwt', 'Nested JWTs (cty \"JWT\") are not supported');\n\t}\n\treturn decodeJsonObject(payload, limits, 'payload', 'invalid_payload');\n}\n\n/** Decodes a JWT without checking its signature. Every field of the result is unauthenticated. */\nexport function decodeJwtUnverified(\n\ttoken: string,\n\tlimits?: Partial<JoseLimits>,\n): JoseResult<UnverifiedJwt, JwsParseErrorCode | 'invalid_options'> {\n\tconst bounds = resolveJoseLimits(limits);\n\tif (!bounds.ok) return bounds;\n\tconst parsed = parseCompactJws(token, bounds.value);\n\tif (!parsed.ok) return parsed;\n\tconst claims = decodeClaims(parsed.value.header, parsed.value.payload, bounds.value);\n\tif (!claims.ok) return claims;\n\treturn successResult({ verified: false, header: parsed.value.header, claims: claims.value });\n}\n\nfunction claimFailure<TCode extends VerifyJwtErrorCode>(\n\tcode: TCode,\n\tmessage: string,\n\tclaim: string,\n): JoseErrorResult<TCode> {\n\treturn joseFailure(code, message, { claim });\n}\n\nfunction numericDate(\n\tclaims: JsonObject,\n\tname: 'exp' | 'nbf' | 'iat',\n): JoseResult<number | undefined, 'invalid_claim'> {\n\tif (!Object.hasOwn(claims, name)) return successResult(undefined);\n\tconst value = claims[name];\n\tif (typeof value !== 'number' || !Number.isFinite(value)) {\n\t\treturn claimFailure('invalid_claim', `Claim \"${name}\" is not a NumericDate`, name);\n\t}\n\treturn successResult(value);\n}\n\nfunction stringClaim(\n\tclaims: JsonObject,\n\tname: 'iss' | 'sub' | 'jti',\n): JoseResult<string | undefined, 'invalid_claim'> {\n\tif (!Object.hasOwn(claims, name)) return successResult(undefined);\n\tconst value = claims[name];\n\tif (typeof value !== 'string') {\n\t\treturn claimFailure('invalid_claim', `Claim \"${name}\" is not a string`, name);\n\t}\n\treturn successResult(value);\n}\n\nfunction audienceClaim(\n\tclaims: JsonObject,\n): JoseResult<string | readonly string[] | undefined, 'invalid_claim'> {\n\tif (!Object.hasOwn(claims, 'aud')) return successResult(undefined);\n\tconst value = claims.aud;\n\tif (typeof value === 'string') return successResult(value);\n\tif (!isJsonArray(value)) {\n\t\treturn claimFailure('invalid_claim', 'Claim \"aud\" is neither a string nor an array', 'aud');\n\t}\n\tconst audiences: string[] = [];\n\tfor (const entry of value) {\n\t\tif (typeof entry !== 'string') {\n\t\t\treturn claimFailure('invalid_claim', 'Claim \"aud\" holds a non-string', 'aud');\n\t\t}\n\t\taudiences.push(entry);\n\t}\n\treturn successResult(audiences);\n}\n\nfunction registeredClaims(claims: JsonObject): JoseResult<RegisteredClaims, 'invalid_claim'> {\n\tconst iss = stringClaim(claims, 'iss');\n\tif (!iss.ok) return iss;\n\tconst sub = stringClaim(claims, 'sub');\n\tif (!sub.ok) return sub;\n\tconst jti = stringClaim(claims, 'jti');\n\tif (!jti.ok) return jti;\n\tconst aud = audienceClaim(claims);\n\tif (!aud.ok) return aud;\n\tconst exp = numericDate(claims, 'exp');\n\tif (!exp.ok) return exp;\n\tconst nbf = numericDate(claims, 'nbf');\n\tif (!nbf.ok) return nbf;\n\tconst iat = numericDate(claims, 'iat');\n\tif (!iat.ok) return iat;\n\treturn successResult({\n\t\t...(iss.value === undefined ? {} : { iss: iss.value }),\n\t\t...(sub.value === undefined ? {} : { sub: sub.value }),\n\t\t...(aud.value === undefined ? {} : { aud: aud.value }),\n\t\t...(exp.value === undefined ? {} : { exp: exp.value }),\n\t\t...(nbf.value === undefined ? {} : { nbf: nbf.value }),\n\t\t...(iat.value === undefined ? {} : { iat: iat.value }),\n\t\t...(jti.value === undefined ? {} : { jti: jti.value }),\n\t});\n}\n\n/** Claims policy validated once and copied, so later changes by the caller cannot alter a run. */\ninterface PreparedClaims {\n\treadonly issuers: readonly string[] | undefined;\n\treadonly audiences: readonly string[] | undefined;\n\treadonly required: readonly string[];\n\treadonly now: () => Date;\n\treadonly toleranceSeconds: number;\n\treadonly maxAgeSeconds: number | undefined;\n\treadonly allowFutureIssuedAt: boolean;\n}\n\nfunction expectedValues(\n\texpectation: unknown,\n): JoseResult<readonly string[] | undefined, 'invalid_options'> {\n\tif (typeof expectation === 'string') return successResult([expectation]);\n\tif (isUncheckedPolicy(expectation)) return successResult(undefined);\n\tif (\n\t\tArray.isArray(expectation) &&\n\t\texpectation.length > 0 &&\n\t\texpectation.every((value) => typeof value === 'string')\n\t) {\n\t\treturn successResult([...expectation]);\n\t}\n\treturn joseFailure(\n\t\t'invalid_options',\n\t\t'issuer and audience need expected values or { unchecked: true }',\n\t);\n}\n\nfunction prepareClaims(policy: JwtClaimsPolicy): JoseResult<PreparedClaims, 'invalid_options'> {\n\tif (typeof policy !== 'object' || policy === null) {\n\t\treturn joseFailure('invalid_options', 'A claims policy is required');\n\t}\n\tconst tolerance = policy.clockToleranceSeconds ?? 0;\n\tif (\n\t\ttypeof tolerance !== 'number' ||\n\t\t!Number.isFinite(tolerance) ||\n\t\ttolerance < 0 ||\n\t\ttolerance > MAX_CLOCK_TOLERANCE_SECONDS\n\t) {\n\t\treturn joseFailure(\n\t\t\t'invalid_options',\n\t\t\t`clockToleranceSeconds must be between 0 and ${MAX_CLOCK_TOLERANCE_SECONDS}`,\n\t\t);\n\t}\n\tconst maxAge = policy.maxAgeSeconds;\n\tif (\n\t\tmaxAge !== undefined &&\n\t\t(typeof maxAge !== 'number' || !Number.isFinite(maxAge) || maxAge < 0)\n\t) {\n\t\treturn joseFailure('invalid_options', 'maxAgeSeconds must be a non-negative number');\n\t}\n\tconst required = policy.requiredClaims ?? ['exp'];\n\tif (!Array.isArray(required) || !required.every((name) => typeof name === 'string')) {\n\t\treturn joseFailure('invalid_options', 'requiredClaims must be an array of strings');\n\t}\n\tif (\n\t\tpolicy.futureIssuedAt !== undefined &&\n\t\tpolicy.futureIssuedAt !== 'reject' &&\n\t\tpolicy.futureIssuedAt !== 'allow'\n\t) {\n\t\treturn joseFailure('invalid_options', \"futureIssuedAt must be 'reject' or 'allow'\");\n\t}\n\tif (policy.now !== undefined && typeof policy.now !== 'function') {\n\t\treturn joseFailure('invalid_options', 'now must be a function');\n\t}\n\tconst issuers = expectedValues(policy.issuer);\n\tif (!issuers.ok) return issuers;\n\tconst audiences = expectedValues(policy.audience);\n\tif (!audiences.ok) return audiences;\n\treturn successResult({\n\t\tissuers: issuers.value,\n\t\taudiences: audiences.value,\n\t\trequired: [...required],\n\t\tnow: policy.now ?? (() => new Date()),\n\t\ttoleranceSeconds: tolerance,\n\t\tmaxAgeSeconds: maxAge,\n\t\tallowFutureIssuedAt: policy.futureIssuedAt === 'allow',\n\t});\n}\n\nfunction checkIdentity(\n\tregistered: RegisteredClaims,\n\tpolicy: PreparedClaims,\n): JoseErrorResult<VerifyJwtErrorCode> | undefined {\n\tconst { issuers, audiences } = policy;\n\tif (\n\t\tissuers !== undefined &&\n\t\t(registered.iss === undefined || !issuers.includes(registered.iss))\n\t) {\n\t\treturn claimFailure('issuer_mismatch', 'The token issuer is not accepted', 'iss');\n\t}\n\tif (audiences !== undefined) {\n\t\tconst carried = typeof registered.aud === 'string' ? [registered.aud] : (registered.aud ?? []);\n\t\tif (!carried.some((entry) => audiences.includes(entry))) {\n\t\t\treturn claimFailure('audience_mismatch', 'The token audience is not accepted', 'aud');\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction checkTimes(\n\tregistered: RegisteredClaims,\n\tpolicy: PreparedClaims,\n\tnowSeconds: number,\n): JoseErrorResult<VerifyJwtErrorCode> | undefined {\n\tconst tolerance = policy.toleranceSeconds;\n\tconst { exp, nbf, iat } = registered;\n\tif (exp !== undefined && nowSeconds >= exp + tolerance) {\n\t\treturn claimFailure('expired', 'The token has expired', 'exp');\n\t}\n\tif (nbf !== undefined && nowSeconds < nbf - tolerance) {\n\t\treturn claimFailure('not_yet_valid', 'The token is not valid yet', 'nbf');\n\t}\n\tif (iat !== undefined && !policy.allowFutureIssuedAt && iat - tolerance > nowSeconds) {\n\t\treturn claimFailure('issued_in_future', 'The token was issued in the future', 'iat');\n\t}\n\tif (policy.maxAgeSeconds !== undefined) {\n\t\tif (iat === undefined) {\n\t\t\treturn claimFailure('missing_claim', 'Claim \"iat\" is required by maxAgeSeconds', 'iat');\n\t\t}\n\t\tif (nowSeconds - iat > policy.maxAgeSeconds + tolerance) {\n\t\t\treturn claimFailure('token_too_old', 'The token is older than the maximum age', 'iat');\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction clockSeconds(policy: PreparedClaims): JoseResult<number, 'invalid_options'> {\n\tlet reading: unknown;\n\ttry {\n\t\treading = policy.now();\n\t} catch {\n\t\treturn joseFailure('invalid_options', 'The claims clock threw');\n\t}\n\tif (!(reading instanceof Date) || !Number.isFinite(reading.getTime())) {\n\t\treturn joseFailure('invalid_options', 'The claims clock did not return a valid Date');\n\t}\n\treturn successResult(reading.getTime() / 1000);\n}\n\nfunction validateClaims(\n\tclaims: JsonObject,\n\tpolicy: PreparedClaims,\n): JoseResult<RegisteredClaims, VerifyJwtErrorCode> {\n\tfor (const name of policy.required) {\n\t\tif (!Object.hasOwn(claims, name)) {\n\t\t\treturn claimFailure('missing_claim', `Claim \"${name}\" is required`, name);\n\t\t}\n\t}\n\tconst registered = registeredClaims(claims);\n\tif (!registered.ok) return registered;\n\tconst identity = checkIdentity(registered.value, policy);\n\tif (identity !== undefined) return identity;\n\tconst now = clockSeconds(policy);\n\tif (!now.ok) return now;\n\tconst times = checkTimes(registered.value, policy, now.value);\n\tif (times !== undefined) return times;\n\treturn registered;\n}\n\n/**\n * Verifies a JWT: the signature and `tokenType` policy as {@linkcode verifyCompactJws} applies\n * them, then the payload as a duplicate-free JSON object, then `claims`.\n *\n * `iss` and `aud` must be stated explicitly. Time claims follow RFC 7519 §4.1.4 and §4.1.5: the\n * token is expired when the clock is at or after `exp` and not yet valid when it is before\n * `nbf`, each moved by `clockToleranceSeconds`. Time claims must be JSON numbers; strings are never\n * coerced. `exp` is required unless `requiredClaims` says otherwise.\n */\nexport async function verifyJwt(\n\ttoken: string,\n\toptions: VerifyJwtOptions,\n): Promise<JoseResult<VerifiedJwt, VerifyJwtErrorCode>> {\n\tif (typeof options !== 'object' || options === null) {\n\t\treturn joseFailure('invalid_options', 'Verification options are required');\n\t}\n\tconst claimsPolicy = prepareClaims(options.claims);\n\tif (!claimsPolicy.ok) return claimsPolicy;\n\tconst prepared = prepareVerify(options);\n\tif (!prepared.ok) return prepared;\n\tconst jws = await verifyPrepared(token, prepared.value);\n\tif (!jws.ok) return jws;\n\tconst claims = decodeClaims(jws.value.header, jws.value.payload, prepared.value.limits);\n\tif (!claims.ok) return claims;\n\tconst registered = validateClaims(claims.value, claimsPolicy.value);\n\tif (!registered.ok) return registered;\n\treturn successResult({\n\t\tverified: true,\n\t\theader: jws.value.header,\n\t\tclaims: claims.value,\n\t\tregistered: registered.value,\n\t});\n}\n\n/**\n * Signs a JWT. The header carries `typ: \"JWT\"` unless `header.typ` says otherwise.\n *\n * Throws a `ResultError` coded `SignJoseErrorCode` for an unusable key, algorithm or header, and\n * `invalid_claims` when `claims` cannot be serialized.\n */\nexport async function signJwt(input: SignJwtInput): Promise<string> {\n\tlet payload: string | undefined;\n\ttry {\n\t\tpayload = JSON.stringify(input.claims);\n\t} catch {\n\t\tpayload = undefined;\n\t}\n\tif (typeof payload !== 'string') {\n\t\treturn throwMicro509Error('invalid_claims', 'JWT claims are not JSON-serializable');\n\t}\n\tconst { claims: _claims, ...rest } = input;\n\treturn await signCompactJws({\n\t\t...rest,\n\t\tpayload: new TextEncoder().encode(payload),\n\t\theader: { typ: 'JWT', ...input.header },\n\t});\n}\n"],"mappings":";;;;;;AAsCA,MAAaA,IAA8B;AA2E3C,SAAS,aACR,GACA,GACA,GAC4C;CAI5C,OAHIC,EAAO,QAAQ,KAAA,KAAaC,EAAaD,EAAO,GAAG,MAAM,oBACrDE,EAAY,0BAA0B,6CAA2C,IAElFC,EAAiBC,GAASC,GAAQ,WAAW,iBAAiB;AACtE;;AAGA,SAAgB,oBACf,GACA,GACmE;CACnE,IAAMC,IAASC,EAAkBF,CAAM;CACvC,IAAI,CAACC,EAAO,IAAI,OAAOA;CACvB,IAAME,IAASC,EAAgBC,GAAOJ,EAAO,KAAK;CAClD,IAAI,CAACE,EAAO,IAAI,OAAOA;CACvB,IAAMG,IAAS,a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AW;CACxB,CAAC,IAN0BA;AAO5B;;;;;;;AAQA,eAAsB,QAAQ,GAAsC;CACnE,IAAI9B;CACJ,IAAI;EACH,IAAU,KAAK,UAAU0C,EAAM,MAAM;CACtC,QAAQ;EACP,IAAU,KAAA;CACX;CACA,IAAI,OAAO1C,KAAY,UACtB,OAAO2C,EAAmB,kBAAkB,sCAAsC;CAEnF,IAAM,EAAE,QAAQC,GAAS,GAAGC,MAASH;CACrC,OAAO,MAAMI,EAAe;EAC3B,GAAGD;EACH,SAAS,IAAI,YAAY,CAAC,CAAC,OAAO7C,CAAO;EACzC,QAAQ;GAAE,KAAK;GAAO,GAAG0C,EAAM;EAAO;CACvC,CAAC;AACF"}
1
+ {"version":3,"file":"jwt.js","names":["isJsonArray","joseFailure","decodeJsonObject","isUncheckedPolicy","mediaTypeKey","parseCompactJws","prepareVerify","resolveJoseLimits","signCompactJws","verifyPrepared","successResult","throwMicro509Error","MAX_CLOCK_TOLERANCE_SECONDS","header","payload","limits","token","bounds","parsed","claims","code","message","claim","name","value","audiences","entry","iss","sub","jti","aud","exp","nbf","iat","expectation","policy","tolerance","maxAge","required","issuers","registered","nowSeconds","reading","identity","now","times","options","claimsPolicy","prepared","jws","input","_claims","rest"],"sources":["../../src/jose/jwt.ts"],"sourcesContent":["/**\n * JWT (RFC 7519) validation on top of compact JWS. Signature verification and the claims policy\n * are separate steps with separate types: {@linkcode decodeJwtUnverified} yields an\n * {@linkcode UnverifiedJwt}, and only {@linkcode verifyJwt} yields a {@linkcode VerifiedJwt}.\n *\n * @module\n */\n\nimport type { JsonObject } from '#micro509/internal/jose/strict-json';\nimport { isJsonArray } from '#micro509/internal/jose/strict-json';\nimport type {\n\tJoseErrorResult,\n\tJoseResult,\n\tJwsParseErrorCode,\n\tVerifyJwtErrorCode,\n} from '#micro509/jose/errors';\nimport { joseFailure } from '#micro509/jose/errors';\nimport type {\n\tJoseLimits,\n\tJwsAlgorithm,\n\tJwsHeader,\n\tSignJwsInput,\n\tUnchecked,\n\tVerifyJwsOptions,\n} from '#micro509/jose/jws';\nimport {\n\tdecodeJsonObject,\n\tisUncheckedPolicy,\n\tmediaTypeKey,\n\tparseCompactJws,\n\tprepareVerify,\n\tresolveJoseLimits,\n\tsignCompactJws,\n\tverifyPrepared,\n} from '#micro509/jose/jws';\nimport { successResult, throwMicro509Error } from '#micro509/result/result';\n\n/** Largest clock tolerance {@linkcode JwtClaimsPolicy.clockToleranceSeconds} accepts. */\nexport const MAX_CLOCK_TOLERANCE_SECONDS = 600;\n\n/** The RFC 7519 §4.1 registered claims, each checked against its defined type. */\nexport interface RegisteredClaims {\n\t/** Issuer. */\n\treadonly iss?: string;\n\t/** Subject. */\n\treadonly sub?: string;\n\t/** Audience, as the token carried it: a string or an array of strings. */\n\treadonly aud?: string | readonly string[];\n\t/** Expiration time in seconds since the epoch. */\n\treadonly exp?: number;\n\t/** Not-before time in seconds since the epoch. */\n\treadonly nbf?: number;\n\t/** Issued-at time in seconds since the epoch. */\n\treadonly iat?: number;\n\t/** Token identifier. */\n\treadonly jti?: string;\n}\n\n/** A decoded JWT whose signature has not been checked. */\nexport interface UnverifiedJwt {\n\t/** Always `false`. */\n\treadonly verified: false;\n\t/** The header, unauthenticated. */\n\treadonly header: JwsHeader;\n\t/** The claims, unauthenticated and not policy-checked. */\n\treadonly claims: JsonObject;\n}\n\n/** A JWT whose signature and claims both passed the caller's policy. */\nexport interface VerifiedJwt {\n\t/** Always `true`. */\n\treadonly verified: true;\n\t/** The authenticated protected header. */\n\treadonly header: JwsHeader<JwsAlgorithm>;\n\t/** Every authenticated claim, exactly as the token carried it. */\n\treadonly claims: JsonObject;\n\t/** The registered claims, validated against their types. */\n\treadonly registered: RegisteredClaims;\n}\n\n/** Whether an `iat` later than the clock is accepted. */\nexport type FutureIssuedAtPolicy = 'reject' | 'allow';\n\n/** Claims policy for {@linkcode verifyJwt}. Application authorization stays with the caller. */\nexport interface JwtClaimsPolicy {\n\t/** Accepted `iss` values (any one may match), or `{ unchecked: true }`. */\n\treadonly issuer: string | readonly string[] | Unchecked;\n\t/** Accepted `aud` values (any one may match), or `{ unchecked: true }`. */\n\treadonly audience: string | readonly string[] | Unchecked;\n\t/** Claims that must be present. Default `['exp']`. */\n\treadonly requiredClaims?: readonly string[];\n\t/** The clock. Default is the system time. */\n\treadonly now?: () => Date;\n\t/** Leeway in seconds for `exp`, `nbf` and `iat`, from 0 to 600. Default `0`. */\n\treadonly clockToleranceSeconds?: number;\n\t/** Oldest acceptable token age in seconds, measured from `iat`. Requires `iat`. */\n\treadonly maxAgeSeconds?: number;\n\t/** Whether `iat` after the clock is accepted. Default `'reject'`. */\n\treadonly futureIssuedAt?: FutureIssuedAtPolicy;\n}\n\n/** Options for {@linkcode verifyJwt}. */\nexport interface VerifyJwtOptions extends VerifyJwsOptions {\n\t/** Claims policy. */\n\treadonly claims: JwtClaimsPolicy;\n}\n\n/** Input for {@linkcode signJwt}. */\nexport interface SignJwtInput extends Omit<SignJwsInput, 'payload'> {\n\t/** The claims to sign. Must be JSON-serializable. */\n\treadonly claims: JsonObject;\n}\n\nfunction decodeClaims(\n\theader: JwsHeader,\n\tpayload: Uint8Array,\n\tlimits: JoseLimits,\n): JoseResult<JsonObject, JwsParseErrorCode> {\n\tif (header.cty !== undefined && mediaTypeKey(header.cty) === 'application/jwt') {\n\t\treturn joseFailure('unsupported_nested_jwt', 'Nested JWTs (cty \"JWT\") are not supported');\n\t}\n\treturn decodeJsonObject(payload, limits, 'payload', 'invalid_payload');\n}\n\n/** Decodes a JWT without checking its signature. Every field of the result is unauthenticated. */\nexport function decodeJwtUnverified(\n\ttoken: string,\n\tlimits?: Partial<JoseLimits>,\n): JoseResult<UnverifiedJwt, JwsParseErrorCode | 'invalid_options'> {\n\tconst bounds = resolveJoseLimits(limits);\n\tif (!bounds.ok) return bounds;\n\tconst parsed = parseCompactJws(token, bounds.value);\n\tif (!parsed.ok) return parsed;\n\tconst claims = decodeClaims(parsed.value.header, parsed.value.payload, bounds.value);\n\tif (!claims.ok) return claims;\n\treturn successResult({ verified: false, header: parsed.value.header, claims: claims.value });\n}\n\nfunction claimFailure<TCode extends VerifyJwtErrorCode>(\n\tcode: TCode,\n\tmessage: string,\n\tclaim: string,\n): JoseErrorResult<TCode> {\n\treturn joseFailure(code, message, { claim });\n}\n\nfunction numericDate(\n\tclaims: JsonObject,\n\tname: 'exp' | 'nbf' | 'iat',\n): JoseResult<number | undefined, 'invalid_claim'> {\n\tif (!Object.hasOwn(claims, name)) return successResult(undefined);\n\tconst value = claims[name];\n\tif (typeof value !== 'number' || !Number.isFinite(value)) {\n\t\treturn claimFailure('invalid_claim', `Claim \"${name}\" is not a NumericDate`, name);\n\t}\n\treturn successResult(value);\n}\n\nfunction stringClaim(\n\tclaims: JsonObject,\n\tname: 'iss' | 'sub' | 'jti',\n): JoseResult<string | undefined, 'invalid_claim'> {\n\tif (!Object.hasOwn(claims, name)) return successResult(undefined);\n\tconst value = claims[name];\n\tif (typeof value !== 'string') {\n\t\treturn claimFailure('invalid_claim', `Claim \"${name}\" is not a string`, name);\n\t}\n\treturn successResult(value);\n}\n\nfunction audienceClaim(\n\tclaims: JsonObject,\n): JoseResult<string | readonly string[] | undefined, 'invalid_claim'> {\n\tif (!Object.hasOwn(claims, 'aud')) return successResult(undefined);\n\tconst value = claims.aud;\n\tif (typeof value === 'string') return successResult(value);\n\tif (!isJsonArray(value)) {\n\t\treturn claimFailure('invalid_claim', 'Claim \"aud\" is neither a string nor an array', 'aud');\n\t}\n\tconst audiences: string[] = [];\n\tfor (const entry of value) {\n\t\tif (typeof entry !== 'string') {\n\t\t\treturn claimFailure('invalid_claim', 'Claim \"aud\" holds a non-string', 'aud');\n\t\t}\n\t\taudiences.push(entry);\n\t}\n\treturn successResult(audiences);\n}\n\nfunction registeredClaims(claims: JsonObject): JoseResult<RegisteredClaims, 'invalid_claim'> {\n\tconst iss = stringClaim(claims, 'iss');\n\tif (!iss.ok) return iss;\n\tconst sub = stringClaim(claims, 'sub');\n\tif (!sub.ok) return sub;\n\tconst jti = stringClaim(claims, 'jti');\n\tif (!jti.ok) return jti;\n\tconst aud = audienceClaim(claims);\n\tif (!aud.ok) return aud;\n\tconst exp = numericDate(claims, 'exp');\n\tif (!exp.ok) return exp;\n\tconst nbf = numericDate(claims, 'nbf');\n\tif (!nbf.ok) return nbf;\n\tconst iat = numericDate(claims, 'iat');\n\tif (!iat.ok) return iat;\n\treturn successResult({\n\t\t...(iss.value === undefined ? {} : { iss: iss.value }),\n\t\t...(sub.value === undefined ? {} : { sub: sub.value }),\n\t\t...(aud.value === undefined ? {} : { aud: aud.value }),\n\t\t...(exp.value === undefined ? {} : { exp: exp.value }),\n\t\t...(nbf.value === undefined ? {} : { nbf: nbf.value }),\n\t\t...(iat.value === undefined ? {} : { iat: iat.value }),\n\t\t...(jti.value === undefined ? {} : { jti: jti.value }),\n\t});\n}\n\n/** Claims policy validated once and copied, so later changes by the caller cannot alter a run. */\ninterface PreparedClaims {\n\treadonly issuers: readonly string[] | undefined;\n\treadonly audiences: readonly string[] | undefined;\n\treadonly required: readonly string[];\n\treadonly now: () => Date;\n\treadonly toleranceSeconds: number;\n\treadonly maxAgeSeconds: number | undefined;\n\treadonly allowFutureIssuedAt: boolean;\n}\n\nfunction expectedValues(\n\texpectation: unknown,\n): JoseResult<readonly string[] | undefined, 'invalid_options'> {\n\tif (typeof expectation === 'string') return successResult([expectation]);\n\tif (isUncheckedPolicy(expectation)) return successResult(undefined);\n\tif (\n\t\tArray.isArray(expectation) &&\n\t\texpectation.length > 0 &&\n\t\texpectation.every((value) => typeof value === 'string')\n\t) {\n\t\treturn successResult([...expectation]);\n\t}\n\treturn joseFailure(\n\t\t'invalid_options',\n\t\t'issuer and audience need expected values or { unchecked: true }',\n\t);\n}\n\nfunction prepareClaims(policy: JwtClaimsPolicy): JoseResult<PreparedClaims, 'invalid_options'> {\n\tif (typeof policy !== 'object' || policy === null) {\n\t\treturn joseFailure('invalid_options', 'A claims policy is required');\n\t}\n\tconst tolerance = policy.clockToleranceSeconds ?? 0;\n\tif (\n\t\ttypeof tolerance !== 'number' ||\n\t\t!Number.isFinite(tolerance) ||\n\t\ttolerance < 0 ||\n\t\ttolerance > MAX_CLOCK_TOLERANCE_SECONDS\n\t) {\n\t\treturn joseFailure(\n\t\t\t'invalid_options',\n\t\t\t`clockToleranceSeconds must be between 0 and ${MAX_CLOCK_TOLERANCE_SECONDS}`,\n\t\t);\n\t}\n\tconst maxAge = policy.maxAgeSeconds;\n\tif (\n\t\tmaxAge !== undefined &&\n\t\t(typeof maxAge !== 'number' || !Number.isFinite(maxAge) || maxAge < 0)\n\t) {\n\t\treturn joseFailure('invalid_options', 'maxAgeSeconds must be a non-negative number');\n\t}\n\tconst required = policy.requiredClaims ?? ['exp'];\n\tif (!Array.isArray(required) || !required.every((name) => typeof name === 'string')) {\n\t\treturn joseFailure('invalid_options', 'requiredClaims must be an array of strings');\n\t}\n\tif (\n\t\tpolicy.futureIssuedAt !== undefined &&\n\t\tpolicy.futureIssuedAt !== 'reject' &&\n\t\tpolicy.futureIssuedAt !== 'allow'\n\t) {\n\t\treturn joseFailure('invalid_options', \"futureIssuedAt must be 'reject' or 'allow'\");\n\t}\n\tif (policy.now !== undefined && typeof policy.now !== 'function') {\n\t\treturn joseFailure('invalid_options', 'now must be a function');\n\t}\n\tconst issuers = expectedValues(policy.issuer);\n\tif (!issuers.ok) return issuers;\n\tconst audiences = expectedValues(policy.audience);\n\tif (!audiences.ok) return audiences;\n\treturn successResult({\n\t\tissuers: issuers.value,\n\t\taudiences: audiences.value,\n\t\trequired: [...required],\n\t\tnow: policy.now ?? (() => new Date()),\n\t\ttoleranceSeconds: tolerance,\n\t\tmaxAgeSeconds: maxAge,\n\t\tallowFutureIssuedAt: policy.futureIssuedAt === 'allow',\n\t});\n}\n\nfunction checkIdentity(\n\tregistered: RegisteredClaims,\n\tpolicy: PreparedClaims,\n): JoseErrorResult<VerifyJwtErrorCode> | undefined {\n\tconst { issuers, audiences } = policy;\n\tif (\n\t\tissuers !== undefined &&\n\t\t(registered.iss === undefined || !issuers.includes(registered.iss))\n\t) {\n\t\treturn claimFailure('issuer_mismatch', 'The token issuer is not accepted', 'iss');\n\t}\n\tif (audiences !== undefined) {\n\t\tconst carried = typeof registered.aud === 'string' ? [registered.aud] : (registered.aud ?? []);\n\t\tif (!carried.some((entry) => audiences.includes(entry))) {\n\t\t\treturn claimFailure('audience_mismatch', 'The token audience is not accepted', 'aud');\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction checkTimes(\n\tregistered: RegisteredClaims,\n\tpolicy: PreparedClaims,\n\tnowSeconds: number,\n): JoseErrorResult<VerifyJwtErrorCode> | undefined {\n\tconst tolerance = policy.toleranceSeconds;\n\tconst { exp, nbf, iat } = registered;\n\tif (exp !== undefined && nowSeconds >= exp + tolerance) {\n\t\treturn claimFailure('expired', 'The token has expired', 'exp');\n\t}\n\tif (nbf !== undefined && nowSeconds < nbf - tolerance) {\n\t\treturn claimFailure('not_yet_valid', 'The token is not valid yet', 'nbf');\n\t}\n\tif (iat !== undefined && !policy.allowFutureIssuedAt && iat - tolerance > nowSeconds) {\n\t\treturn claimFailure('issued_in_future', 'The token was issued in the future', 'iat');\n\t}\n\tif (policy.maxAgeSeconds !== undefined) {\n\t\tif (iat === undefined) {\n\t\t\treturn claimFailure('missing_claim', 'Claim \"iat\" is required by maxAgeSeconds', 'iat');\n\t\t}\n\t\tif (nowSeconds - iat > policy.maxAgeSeconds + tolerance) {\n\t\t\treturn claimFailure('token_too_old', 'The token is older than the maximum age', 'iat');\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction clockSeconds(policy: PreparedClaims): JoseResult<number, 'invalid_options'> {\n\tlet reading: unknown;\n\ttry {\n\t\treading = policy.now();\n\t} catch {\n\t\treturn joseFailure('invalid_options', 'The claims clock threw');\n\t}\n\tif (!(reading instanceof Date) || !Number.isFinite(reading.getTime())) {\n\t\treturn joseFailure('invalid_options', 'The claims clock did not return a valid Date');\n\t}\n\treturn successResult(reading.getTime() / 1000);\n}\n\nfunction validateClaims(\n\tclaims: JsonObject,\n\tpolicy: PreparedClaims,\n): JoseResult<RegisteredClaims, VerifyJwtErrorCode> {\n\tfor (const name of policy.required) {\n\t\tif (!Object.hasOwn(claims, name)) {\n\t\t\treturn claimFailure('missing_claim', `Claim \"${name}\" is required`, name);\n\t\t}\n\t}\n\tconst registered = registeredClaims(claims);\n\tif (!registered.ok) return registered;\n\tconst identity = checkIdentity(registered.value, policy);\n\tif (identity !== undefined) return identity;\n\tconst now = clockSeconds(policy);\n\tif (!now.ok) return now;\n\tconst times = checkTimes(registered.value, policy, now.value);\n\tif (times !== undefined) return times;\n\treturn registered;\n}\n\n/**\n * Verifies a JWT: the signature and `tokenType` policy as {@linkcode verifyCompactJws} applies\n * them, then the payload as a duplicate-free JSON object, then `claims`.\n *\n * `iss` and `aud` must be stated explicitly. Time claims follow RFC 7519 §4.1.4 and §4.1.5: the\n * token is expired when the clock is at or after `exp` and not yet valid when it is before\n * `nbf`, each moved by `clockToleranceSeconds`. Time claims must be JSON numbers; strings are never\n * coerced. `exp` is required unless `requiredClaims` says otherwise.\n */\nexport async function verifyJwt(\n\ttoken: string,\n\toptions: VerifyJwtOptions,\n): Promise<JoseResult<VerifiedJwt, VerifyJwtErrorCode>> {\n\tif (typeof options !== 'object' || options === null) {\n\t\treturn joseFailure('invalid_options', 'Verification options are required');\n\t}\n\tconst claimsPolicy = prepareClaims(options.claims);\n\tif (!claimsPolicy.ok) return claimsPolicy;\n\tconst prepared = prepareVerify(options);\n\tif (!prepared.ok) return prepared;\n\tconst jws = await verifyPrepared(token, prepared.value);\n\tif (!jws.ok) return jws;\n\tconst claims = decodeClaims(jws.value.header, jws.value.payload, prepared.value.limits);\n\tif (!claims.ok) return claims;\n\tconst registered = validateClaims(claims.value, claimsPolicy.value);\n\tif (!registered.ok) return registered;\n\treturn successResult({\n\t\tverified: true,\n\t\theader: jws.value.header,\n\t\tclaims: claims.value,\n\t\tregistered: registered.value,\n\t});\n}\n\n/**\n * Signs a JWT. The header carries `typ: \"JWT\"` unless `header.typ` says otherwise.\n *\n * Throws a `ResultError` coded `SignJoseErrorCode` for an unusable key, algorithm or header, and\n * `invalid_claims` when `claims` cannot be serialized.\n */\nexport async function signJwt(input: SignJwtInput): Promise<string> {\n\tlet payload: string | undefined;\n\ttry {\n\t\tpayload = JSON.stringify(input.claims);\n\t} catch {\n\t\tpayload = undefined;\n\t}\n\tif (typeof payload !== 'string') {\n\t\treturn throwMicro509Error('invalid_claims', 'JWT claims are not JSON-serializable');\n\t}\n\tconst { claims: _claims, ...rest } = input;\n\treturn await signCompactJws({\n\t\t...rest,\n\t\tpayload: new TextEncoder().encode(payload),\n\t\theader: { typ: 'JWT', ...input.header },\n\t});\n}\n"],"mappings":";;;;;;AAsCA,MAAaY,IAA8B;AA2E3C,SAAS,aACRC,GACAC,GACAC,GAC4C;CAI5C,OAHIF,EAAO,QAAQ,KAAA,KAAaT,EAAaS,EAAO,GAAG,MAAM,oBACrDZ,EAAY,0BAA0B,6CAA2C,IAElFC,EAAiBY,GAASC,GAAQ,WAAW,iBAAiB;AACtE;;AAGA,SAAgB,oBACfC,GACAD,GACmE;CACnE,IAAME,IAASV,EAAkBQ,CAAM;CACvC,IAAI,CAACE,EAAO,IAAI,OAAOA;CACvB,IAAMC,IAASb,EAAgBW,GAAOC,EAAO,KAAK;CAClD,IAAI,CAACC,EAAO,IAAI,OAAOA;CACvB,IAAMC,IAAS,aAAaD,EAAO,MAAM,QAAQA,EAAO,MAAM,SAASD,EAAO,KAAK;CAEnF,OADKE,EAAO,KACLT,EAAc;EAAE,UAAU;EAAO,QAAQQ,EAAO,MAAM;EAAQ,QAAQC,EAAO;CAAM,CAAC,IADpEA;AAExB;AAEA,SAAS,aACRC,GACAC,GACAC,GACyB;CACzB,OAAOrB,EAAYmB,GAAMC,GAAS,EAAEC,SAAM,CAAC;AAC5C;AAEA,SAAS,YACRH,GACAI,GACkD;CAClD,IAAI,CAAC,OAAO,OAAOJ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AAGC,MAASF;CACrC,OAAO,MAAM1C,EAAe;EAC3B,GAAG4C;EACH,SAAS,IAAI,YAAY,CAAC,CAAC,OAAOtC,CAAO;EACzC,QAAQ;GAAE,KAAK;GAAO,GAAGoC,EAAM;EAAO;CACvC,CAAC;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"remote-jwks.js","names":["ABORTED","DEFAULTS","REDIRECT_STATUSES","LOOPBACK_HOSTS","url","resolved","value","fallback","throwMicro509Error","name","config","maxRedirects","maxTtlMs","cooldownMs","target","init","destination","from","joseFailure","message","status","headers","directives","directive","date","apparentAge","receivedAt","reportedAge","transit","requestedAt","age","maxAge","lifetime","match","expires","tooLarge","maxBytes","declared","response","successResult","reader","chunks","total","signal","done","body","offset","chunk","location","redirects","jwks","parseJwks","hop","imported","entry","fetched","algorithm","JWS_ALGORITHMS","key","jwkEntryCacheKey","carried","previous","TIMED_OUT","settings","snapshot","refresh","lastAttemptAt","controller","previousAttemptAt","timer","deadline","resolve","work","tracked","outcome","joined","settled","cached","current","pending","importJwkEntry","loaded","source","selected","selectJwk","selector","reloaded","request"],"sources":["../../src/jose/remote-jwks.ts"],"sourcesContent":["/**\n * Opt-in remote JWK Set resolution. A resolver is bound to one trusted JWKS URL from caller\n * configuration and keeps its own cache, so two issuers never share keys. Importing this module\n * performs no request; only a verification that reaches the resolver can.\n *\n * @module\n */\n\nimport type { JoseErrorResult, JoseResult, KeyResolutionErrorCode } from '#micro509/jose/errors';\nimport { joseFailure } from '#micro509/jose/errors';\nimport type { JwkSelector, Jwks, SupportedJwkEntry } from '#micro509/jose/jwks';\nimport { importJwkEntry, jwkEntryCacheKey, parseJwks, selectJwk } from '#micro509/jose/jwks';\nimport type { JwsAlgorithm, JwsKeyRequest, JwsKeyResolver } from '#micro509/jose/jws';\nimport { JWS_ALGORITHMS } from '#micro509/jose/jws';\nimport { successResult, throwMicro509Error } from '#micro509/result/result';\n\n/** The request {@linkcode JwksTransport} must issue. */\nexport interface JwksRequestInit {\n\t/** Always `GET`. */\n\treadonly method: 'GET';\n\t/** Always `manual`: the resolver validates every redirect destination itself. */\n\treadonly redirect: 'manual';\n\t/** Always `omit`. */\n\treadonly credentials: 'omit';\n\t/** Always `no-store`: each resolver refresh must reach the issuer, bypassing the HTTP cache. */\n\treadonly cache: 'no-store';\n\t/** Configured request headers. Withheld from any origin other than the configured URL's. */\n\treadonly headers: Readonly<Record<string, string>>;\n\t/** Aborts on timeout, cancellation or when no verification still waits for the response. */\n\treadonly signal: AbortSignal;\n}\n\n/**\n * Performs one HTTP request. `fetch` satisfies this type. Supply another to route through a proxy,\n * apply egress or DNS controls, or serve fixtures; the transport sees only URLs the resolver\n * already validated.\n */\nexport type JwksTransport = (url: string, init: JwksRequestInit) => Promise<Response>;\n\n/** Redirect handling for a remote JWK Set. By default redirects are refused. */\nexport interface RemoteJwksRedirectPolicy {\n\t/** Maximum redirects followed per fetch. */\n\treadonly maxRedirects: number;\n\t/**\n\t * Approves a redirect destination. Default: same origin as the hop it came from. The scheme\n\t * rule applies first: `https`, or `http` for a loopback host.\n\t */\n\treadonly allow?: (destination: URL, from: URL) => boolean;\n}\n\n/** Configuration of {@linkcode createRemoteJwksKeyResolver}. */\nexport interface RemoteJwksConfig {\n\t/** The trusted JWKS URL. `https`, or `http` for a loopback host. Never taken from a token. */\n\treadonly url: string | URL;\n\t/** Request transport. Default: `globalThis.fetch`. */\n\treadonly transport?: JwksTransport;\n\t/** Request headers, sent only to the configured URL's origin. */\n\treadonly headers?: Readonly<Record<string, string>>;\n\t/** Whole-request deadline in milliseconds, response body included. Default `5000`. */\n\treadonly timeoutMs?: number;\n\t/** Maximum response body in bytes, enforced while streaming. Default `65536`. */\n\treadonly maxResponseBytes?: number;\n\t/** Maximum keys in the set. Default `32`. */\n\treadonly maxKeys?: number;\n\t/** Redirect handling. Default: refuse every redirect. */\n\treadonly redirects?: RemoteJwksRedirectPolicy;\n\t/** Freshness applied when the response states none, in milliseconds. Default `600000`. */\n\treadonly defaultTtlMs?: number;\n\t/** Longest freshness the resolver will keep a response for, in milliseconds. Default `86400000`. */\n\treadonly maxTtlMs?: number;\n\t/**\n\t * Minimum interval between the starts of two fetches, in milliseconds. It bounds how often\n\t * unknown `kid` values, expired responses and failures can cause a request, and does not\n\t * lengthen how long a response stays fresh. Default `30000`.\n\t */\n\treadonly cooldownMs?: number;\n\t/** The clock in milliseconds since the epoch. Default `Date.now`. */\n\treadonly now?: () => number;\n}\n\n/** Codes {@linkcode createRemoteJwksKeyResolver} throws for unusable configuration. */\nexport type RemoteJwksConfigErrorCode = 'invalid_remote_jwks_config';\n\ntype FetchFailureCode = 'jwks_unavailable' | 'jwks_malformed';\n\ninterface Snapshot {\n\treadonly jwks: Jwks;\n\treadonly expiresAt: number;\n\treadonly imported: Map<string, Promise<JoseResult<CryptoKey, 'key_unsuitable'>>>;\n}\n\ntype RefreshOutcome =\n\t| { readonly kind: 'fresh'; readonly snapshot: Snapshot }\n\t| { readonly kind: 'failed'; readonly failure: JoseErrorResult<FetchFailureCode> }\n\t| { readonly kind: 'abandoned' };\n\ninterface Refresh {\n\treadonly promise: Promise<RefreshOutcome>;\n\treadonly controller: AbortController;\n\treadonly startedAt: number;\n\treadonly previousAttemptAt: number | undefined;\n\twaiters: number;\n}\n\nconst ABORTED: unique symbol = Symbol('micro509.jose.aborted');\n\nconst DEFAULTS = {\n\ttimeoutMs: 5000,\n\tmaxResponseBytes: 65_536,\n\tmaxKeys: 32,\n\tdefaultTtlMs: 600_000,\n\tmaxTtlMs: 86_400_000,\n\tcooldownMs: 30_000,\n} as const;\n\nconst REDIRECT_STATUSES: ReadonlySet<number> = new Set([301, 302, 303, 307, 308]);\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nfunction isPermittedUrl(url: URL): boolean {\n\treturn (\n\t\turl.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))\n\t);\n}\n\nfunction positiveInteger(value: number | undefined, fallback: number, name: string): number {\n\tconst resolved = value ?? fallback;\n\tif (!Number.isSafeInteger(resolved) || resolved <= 0) {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', `${name} must be a positive integer`);\n\t}\n\treturn resolved;\n}\n\ninterface ResolvedConfig {\n\treadonly url: URL;\n\treadonly transport: JwksTransport;\n\treadonly headers: Readonly<Record<string, string>>;\n\treadonly timeoutMs: number;\n\treadonly maxResponseBytes: number;\n\treadonly maxKeys: number;\n\treadonly maxRedirects: number;\n\treadonly allowRedirect: (destination: URL, from: URL) => boolean;\n\treadonly defaultTtlMs: number;\n\treadonly maxTtlMs: number;\n\treadonly cooldownMs: number;\n\treadonly now: () => number;\n}\n\nfunction resolveConfig(config: RemoteJwksConfig): ResolvedConfig {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(config.url);\n\t} catch {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', 'url is not an absolute URL');\n\t}\n\tif (!isPermittedUrl(url)) {\n\t\treturn throwMicro509Error(\n\t\t\t'invalid_remote_jwks_config',\n\t\t\t'url must use https, or http on a loopback host',\n\t\t);\n\t}\n\tif (url.username !== '' || url.password !== '') {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', 'url must not embed credentials');\n\t}\n\tconst maxRedirects = config.redirects?.maxRedirects ?? 0;\n\tif (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0 || maxRedirects > 10) {\n\t\treturn throwMicro509Error(\n\t\t\t'invalid_remote_jwks_config',\n\t\t\t'maxRedirects must be an integer from 0 to 10',\n\t\t);\n\t}\n\tconst maxTtlMs = positiveInteger(config.maxTtlMs, DEFAULTS.maxTtlMs, 'maxTtlMs');\n\tconst cooldownMs = positiveInteger(config.cooldownMs, DEFAULTS.cooldownMs, 'cooldownMs');\n\treturn {\n\t\turl,\n\t\ttransport: config.transport ?? ((target, init) => globalThis.fetch(target, init)),\n\t\theaders: { ...config.headers },\n\t\ttimeoutMs: positiveInteger(config.timeoutMs, DEFAULTS.timeoutMs, 'timeoutMs'),\n\t\tmaxResponseBytes: positiveInteger(\n\t\t\tconfig.maxResponseBytes,\n\t\t\tDEFAULTS.maxResponseBytes,\n\t\t\t'maxResponseBytes',\n\t\t),\n\t\tmaxKeys: positiveInteger(config.maxKeys, DEFAULTS.maxKeys, 'maxKeys'),\n\t\tmaxRedirects,\n\t\tallowRedirect:\n\t\t\tconfig.redirects?.allow ?? ((destination, from) => destination.origin === from.origin),\n\t\tdefaultTtlMs: positiveInteger(config.defaultTtlMs, DEFAULTS.defaultTtlMs, 'defaultTtlMs'),\n\t\tmaxTtlMs,\n\t\tcooldownMs,\n\t\tnow: config.now ?? Date.now,\n\t};\n}\n\nfunction unavailable(message: string, status?: number): JoseErrorResult<'jwks_unavailable'> {\n\treturn joseFailure('jwks_unavailable', message, status === undefined ? undefined : { status });\n}\n\nconst NOT_A_NUMBER = Number.NaN;\n\nfunction secondsHeader(headers: Headers, name: string): number {\n\tconst value = headers.get(name);\n\treturn value !== null && /^\\d{1,10}$/.test(value) ? Number(value) * 1000 : NOT_A_NUMBER;\n}\n\n/**\n * Remaining freshness in milliseconds, never below zero and never above `maxTtlMs`.\n *\n * The lifetime is `Cache-Control: max-age`, else `Expires` less `Date`, else `defaultTtlMs`\n * (RFC 9111 §4.2.1); `no-store`, `no-cache` and unusable values give none. The response age is the\n * larger of the apparent age from `Date` and the `Age` header plus the transit delay\n * (RFC 9111 §4.2.3).\n */\nfunction freshnessMs(\n\theaders: Headers,\n\trequestedAt: number,\n\treceivedAt: number,\n\tconfig: ResolvedConfig,\n): number {\n\tconst directives = (headers.get('cache-control') ?? '')\n\t\t.split(',')\n\t\t.map((directive) => directive.trim().toLowerCase())\n\t\t.filter((directive) => directive.length > 0);\n\tif (directives.includes('no-store') || directives.includes('no-cache')) return 0;\n\tconst date = Date.parse(headers.get('date') ?? '');\n\tconst apparentAge = Number.isNaN(date) ? 0 : Math.max(0, receivedAt - date);\n\tconst reportedAge = secondsHeader(headers, 'age');\n\tconst transit = Math.max(0, receivedAt - requestedAt);\n\tconst age = Math.max(apparentAge, (Number.isNaN(reportedAge) ? 0 : reportedAge) + transit);\n\tconst maxAge = directives.find((directive) => directive.startsWith('max-age'));\n\tlet lifetime = config.defaultTtlMs;\n\tif (maxAge !== undefined) {\n\t\tconst match = /^max-age=(\"?)(\\d{1,10})\\1$/.exec(maxAge);\n\t\tlifetime = match?.[2] === undefined ? 0 : Number(match[2]) * 1000;\n\t} else if (headers.has('expires')) {\n\t\tconst expires = Date.parse(headers.get('expires') ?? '');\n\t\tlifetime = Number.isNaN(expires) ? 0 : expires - (Number.isNaN(date) ? receivedAt : date);\n\t}\n\treturn Math.min(config.maxTtlMs, Math.max(0, lifetime - age));\n}\n\ntype BodyResult = JoseResult<Uint8Array, 'jwks_unavailable' | 'jwks_malformed'>;\n\nasync function readBounded(\n\tresponse: Response,\n\tmaxBytes: number,\n\tsignal: AbortSignal,\n): Promise<BodyResult> {\n\tconst tooLarge = joseFailure('jwks_malformed', `The JWKS response exceeds ${maxBytes} bytes`);\n\tconst declared = response.headers.get('content-length');\n\tif (declared !== null && /^\\d+$/.test(declared) && Number(declared) > maxBytes) {\n\t\tawait response.body?.cancel();\n\t\treturn tooLarge;\n\t}\n\tif (response.body === null) return successResult(new Uint8Array(0));\n\tconst reader = response.body.getReader();\n\tconst release = (): void => {\n\t\treader.cancel().catch(() => undefined);\n\t};\n\tsignal.addEventListener('abort', release, { once: true });\n\ttry {\n\t\tconst chunks: Uint8Array[] = [];\n\t\tlet total = 0;\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (signal.aborted) return unavailable('The JWKS request was cancelled');\n\t\t\tif (done) break;\n\t\t\ttotal += value.byteLength;\n\t\t\tif (total > maxBytes) {\n\t\t\t\trelease();\n\t\t\t\treturn tooLarge;\n\t\t\t}\n\t\t\tchunks.push(value);\n\t\t}\n\t\tconst body = new Uint8Array(total);\n\t\tlet offset = 0;\n\t\tfor (const chunk of chunks) {\n\t\t\tbody.set(chunk, offset);\n\t\t\toffset += chunk.byteLength;\n\t\t}\n\t\treturn successResult(body);\n\t} finally {\n\t\tsignal.removeEventListener('abort', release);\n\t}\n}\n\ninterface Fetched {\n\treadonly jwks: Jwks;\n\treadonly expiresAt: number;\n}\n\nfunction nextHop(\n\tconfig: ResolvedConfig,\n\tfrom: URL,\n\tresponse: Response,\n\tredirects: number,\n): JoseResult<URL, 'jwks_unavailable'> {\n\tconst location = response.headers.get('location');\n\tif (redirects >= config.maxRedirects || location === null) {\n\t\treturn unavailable('The JWKS endpoint redirected', response.status);\n\t}\n\tlet destination: URL;\n\ttry {\n\t\tdestination = new URL(location, from);\n\t} catch {\n\t\treturn unavailable('The JWKS redirect target is not a URL', response.status);\n\t}\n\tif (\n\t\t!isPermittedUrl(destination) ||\n\t\tdestination.username !== '' ||\n\t\tdestination.password !== '' ||\n\t\t!config.allowRedirect(destination, from)\n\t) {\n\t\treturn unavailable('The JWKS redirect target is not permitted', response.status);\n\t}\n\treturn successResult(destination);\n}\n\nasync function readJwks(\n\tconfig: ResolvedConfig,\n\tresponse: Response,\n\trequestedAt: number,\n\tsignal: AbortSignal,\n): Promise<JoseResult<Fetched, FetchFailureCode>> {\n\tif (response.status !== 200) {\n\t\tawait response.body?.cancel();\n\t\treturn unavailable('The JWKS endpoint did not answer 200', response.status);\n\t}\n\tconst receivedAt = config.now();\n\tconst body = await readBounded(response, config.maxResponseBytes, signal);\n\tif (!body.ok) return body;\n\tconst jwks = parseJwks(body.value, {\n\t\tmaxBytes: config.maxResponseBytes,\n\t\tmaxKeys: config.maxKeys,\n\t});\n\tif (!jwks.ok) return joseFailure('jwks_malformed', jwks.message);\n\treturn successResult({\n\t\tjwks: jwks.value,\n\t\texpiresAt: receivedAt + freshnessMs(response.headers, requestedAt, receivedAt, config),\n\t});\n}\n\nasync function fetchJwks(\n\tconfig: ResolvedConfig,\n\tsignal: AbortSignal,\n\trequestedAt: number,\n): Promise<JoseResult<Fetched, FetchFailureCode>> {\n\tlet url = config.url;\n\tfor (let redirects = 0; ; redirects++) {\n\t\tconst response = await config.transport(url.href, {\n\t\t\tmethod: 'GET',\n\t\t\tredirect: 'manual',\n\t\t\tcredentials: 'omit',\n\t\t\tcache: 'no-store',\n\t\t\theaders: url.origin === config.url.origin ? config.headers : {},\n\t\t\tsignal,\n\t\t});\n\t\tif (signal.aborted) {\n\t\t\tawait response.body?.cancel();\n\t\t\treturn unavailable('The JWKS request was cancelled');\n\t\t}\n\t\tif (response.type === 'opaqueredirect') {\n\t\t\treturn unavailable('The runtime hides redirects, so they cannot be validated');\n\t\t}\n\t\tif (!REDIRECT_STATUSES.has(response.status)) {\n\t\t\treturn await readJwks(config, response, requestedAt, signal);\n\t\t}\n\t\tawait response.body?.cancel();\n\t\tconst hop = nextHop(config, url, response, redirects);\n\t\tif (!hop.ok) return hop;\n\t\turl = hop.value;\n\t}\n}\n\nfunction carryOver(fetched: Fetched, previous: Snapshot | undefined): Snapshot {\n\tconst imported = new Map<string, Promise<JoseResult<CryptoKey, 'key_unsuitable'>>>();\n\tfor (const entry of fetched.jwks.keys) {\n\t\tif (entry.kind === 'unsupported') continue;\n\t\tfor (const algorithm of JWS_ALGORITHMS) {\n\t\t\tconst key = jwkEntryCacheKey(entry, algorithm);\n\t\t\tconst carried = previous?.imported.get(key);\n\t\t\tif (carried !== undefined) imported.set(key, carried);\n\t\t}\n\t}\n\treturn { jwks: fetched.jwks, expiresAt: fetched.expiresAt, imported };\n}\n\nconst TIMED_OUT: unique symbol = Symbol('micro509.jose.timedOut');\n\n/**\n * Creates a key resolver that reads a JWK Set from one trusted URL.\n *\n * Behaviour, per resolver:\n *\n * - The first verification fetches the set. Later ones reuse it while fresh. Freshness is the\n * remaining lifetime from `Cache-Control: max-age`, else `Expires`, else `defaultTtlMs`, less the\n * response age (the larger of the apparent age from `Date` and `Age` plus the transit delay),\n * capped at `maxTtlMs`. `no-store`, `no-cache` and a lifetime already spent leave none: the set\n * serves the verification that fetched it and nothing after. No heuristic freshness is applied.\n * - A set that is no longer fresh is never used, whether or not a refresh succeeds. There is no\n * stale-if-error. A refresh that fails while the cached set is still fresh keeps that set until\n * it expires.\n * - Refreshes are separate from freshness: after any attempt the next one waits `cooldownMs`.\n * Within that interval a token whose `kid` is absent gets `key_not_found`, and a token that\n * needs a set that is no longer fresh gets `jwks_unavailable`. Concurrent verifications share\n * a single request, and unknown `kid` values are never cached.\n * - A refresh replaces the whole set, so a rotated-out key stops verifying as soon as the new\n * set is read. Rotation must therefore introduce a new `kid`.\n * - The whole request, response body included, is bounded by `timeoutMs` and enforced even when\n * the transport ignores the abort signal. Redirects, bytes and keys are bounded by `redirects`,\n * `maxResponseBytes` and `maxKeys`. No retry happens inside a fetch. Cancelling the last waiting\n * verification aborts the request, and a response that finishes afterwards is discarded.\n * - Request headers go only to the configured origin. `jku`, `x5u` and `jwk` headers are never\n * used.\n *\n * Throws a `ResultError` coded {@linkcode RemoteJwksConfigErrorCode} for unusable configuration.\n * Redirect destinations, and the addresses a hostname resolves to, are limited by `redirects` and\n * the transport; this module cannot see DNS answers, and browsers hide redirect targets.\n */\nexport function createRemoteJwksKeyResolver(config: RemoteJwksConfig): JwsKeyResolver {\n\tconst settings = resolveConfig(config);\n\tlet snapshot: Snapshot | undefined;\n\tlet refresh: Refresh | undefined;\n\tlet lastAttemptAt: number | undefined;\n\n\tfunction startRefresh(): Refresh {\n\t\tconst controller = new AbortController();\n\t\tconst requestedAt = settings.now();\n\t\tconst previousAttemptAt = lastAttemptAt;\n\t\tconst previous = snapshot;\n\t\tlastAttemptAt = requestedAt;\n\n\t\tasync function run(): Promise<RefreshOutcome> {\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst deadline = new Promise<typeof TIMED_OUT>((resolve) => {\n\t\t\t\ttimer = setTimeout(() => resolve(TIMED_OUT), settings.timeoutMs);\n\t\t\t});\n\t\t\tconst work = fetchJwks(settings, controller.signal, requestedAt);\n\t\t\twork.catch(() => undefined);\n\t\t\ttry {\n\t\t\t\tconst fetched = await Promise.race([work, deadline]);\n\t\t\t\tif (fetched === TIMED_OUT) {\n\t\t\t\t\tcontroller.abort();\n\t\t\t\t\treturn { kind: 'failed', failure: unavailable('The JWKS request timed out') };\n\t\t\t\t}\n\t\t\t\tif (!fetched.ok) return { kind: 'failed', failure: fetched };\n\t\t\t\treturn { kind: 'fresh', snapshot: carryOver(fetched.value, previous) };\n\t\t\t} catch {\n\t\t\t\treturn controller.signal.aborted\n\t\t\t\t\t? { kind: 'abandoned' }\n\t\t\t\t\t: { kind: 'failed', failure: unavailable('The JWKS request failed') };\n\t\t\t} finally {\n\t\t\t\tclearTimeout(timer);\n\t\t\t}\n\t\t}\n\n\t\tconst tracked: Promise<RefreshOutcome> = run()\n\t\t\t.then((outcome): RefreshOutcome => {\n\t\t\t\tif (refresh?.promise !== tracked) return { kind: 'abandoned' };\n\t\t\t\tif (outcome.kind === 'fresh') snapshot = outcome.snapshot;\n\t\t\t\treturn outcome;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tif (refresh?.promise === tracked) refresh = undefined;\n\t\t\t});\n\t\treturn {\n\t\t\tpromise: tracked,\n\t\t\tcontroller,\n\t\t\tstartedAt: requestedAt,\n\t\t\tpreviousAttemptAt,\n\t\t\twaiters: 0,\n\t\t};\n\t}\n\n\tasync function awaitRefresh(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<RefreshOutcome | typeof ABORTED> {\n\t\tif (signal?.aborted === true) return ABORTED;\n\t\trefresh ??= startRefresh();\n\t\tconst joined = refresh;\n\t\tjoined.waiters++;\n\t\tif (signal === undefined) return await joined.promise;\n\t\treturn await new Promise<RefreshOutcome | typeof ABORTED>((resolve) => {\n\t\t\tlet settled = false;\n\t\t\tconst finish = (): void => {\n\t\t\t\tsettled = true;\n\t\t\t\tsignal.removeEventListener('abort', onAbort);\n\t\t\t};\n\t\t\tconst onAbort = (): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tfinish();\n\t\t\t\tjoined.waiters--;\n\t\t\t\tif (joined.waiters === 0) {\n\t\t\t\t\tif (refresh === joined) refresh = undefined;\n\t\t\t\t\tif (lastAttemptAt === joined.startedAt) lastAttemptAt = joined.previousAttemptAt;\n\t\t\t\t\tjoined.controller.abort();\n\t\t\t\t}\n\t\t\t\tresolve(ABORTED);\n\t\t\t};\n\t\t\tsignal.addEventListener('abort', onAbort, { once: true });\n\t\t\tif (signal.aborted) onAbort();\n\t\t\tvoid joined.promise.then((outcome) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tfinish();\n\t\t\t\tresolve(outcome);\n\t\t\t});\n\t\t});\n\t}\n\n\tfunction refreshAllowed(): boolean {\n\t\tif (refresh !== undefined || lastAttemptAt === undefined) return true;\n\t\treturn settings.now() - lastAttemptAt >= settings.cooldownMs;\n\t}\n\n\tasync function obtain(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<Snapshot | undefined, FetchFailureCode | 'aborted'>> {\n\t\tif (!refreshAllowed()) return successResult(undefined);\n\t\tconst outcome = await awaitRefresh(signal);\n\t\tif (outcome === ABORTED || outcome.kind === 'abandoned') {\n\t\t\treturn joseFailure('aborted', 'Key resolution was cancelled');\n\t\t}\n\t\tif (outcome.kind === 'failed') return outcome.failure;\n\t\treturn successResult(outcome.snapshot);\n\t}\n\n\tasync function importFrom(\n\t\tcurrent: Snapshot,\n\t\tentry: SupportedJwkEntry,\n\t\talgorithm: JwsAlgorithm,\n\t): Promise<JoseResult<CryptoKey, 'key_unsuitable'>> {\n\t\tconst key = jwkEntryCacheKey(entry, algorithm);\n\t\tconst cached = current.imported.get(key);\n\t\tif (cached !== undefined) return await cached;\n\t\tconst pending = importJwkEntry(entry, algorithm);\n\t\tcurrent.imported.set(key, pending);\n\t\treturn await pending;\n\t}\n\n\tasync function currentSnapshot(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<Snapshot, FetchFailureCode | 'aborted'>> {\n\t\tif (snapshot !== undefined && settings.now() < snapshot.expiresAt) {\n\t\t\treturn successResult(snapshot);\n\t\t}\n\t\tsnapshot = undefined;\n\t\tconst loaded = await obtain(signal);\n\t\tif (!loaded.ok) return loaded;\n\t\treturn loaded.value === undefined\n\t\t\t? unavailable('The JWKS endpoint is in cooldown')\n\t\t\t: successResult(loaded.value);\n\t}\n\n\tasync function select(\n\t\tcurrent: Snapshot,\n\t\tselector: JwkSelector,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<CryptoKey, KeyResolutionErrorCode>> {\n\t\tlet source = current;\n\t\tlet selected = selectJwk(source.jwks, selector);\n\t\tif (!selected.ok && selected.code === 'key_not_found') {\n\t\t\tconst reloaded = await obtain(signal);\n\t\t\tif (!reloaded.ok) return reloaded;\n\t\t\tif (reloaded.value !== undefined) {\n\t\t\t\tsource = reloaded.value;\n\t\t\t\tselected = selectJwk(source.jwks, selector);\n\t\t\t}\n\t\t}\n\t\tif (!selected.ok) return selected;\n\t\tconst key = await importFrom(source, selected.value, selector.algorithm);\n\t\treturn signal?.aborted === true ? joseFailure('aborted', 'Key resolution was cancelled') : key;\n\t}\n\n\treturn async (request: JwsKeyRequest) => {\n\t\tif (request.signal?.aborted === true) {\n\t\t\treturn joseFailure('aborted', 'Key resolution was cancelled');\n\t\t}\n\t\tconst current = await currentSnapshot(request.signal);\n\t\tif (!current.ok) return current;\n\t\treturn await select(\n\t\t\tcurrent.value,\n\t\t\t{ algorithm: request.algorithm, ...(request.kid === undefined ? {} : { kid: request.kid }) },\n\t\t\trequest.signal,\n\t\t);\n\t};\n}\n"],"mappings":";;;;;AAwGA,MAAMA,IAAyB,OAAO,uBAAuB,GAEvDC,IAAW;CAChB,WAAW;CACX,kBAAkB;CAClB,SAAS;CACT,cAAc;CACd,UAAU;CACV,YAAY;AACb,GAEMC,oBAAyC,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC,GAE1EC,oBAAsC,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;AAEvF,SAAS,eA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AAS,SAAS,iBAAiB;GACtD,IAAMG,IAAW,MAAM,OAAO3C,CAAM;GACpC,IAAI,CAAC2C,EAAS,IAAI,OAAOA;GACzB,AAAIA,EAAS,UAAU,KAAA,MACtB,IAASA,EAAS,OAClB,IAAWF,EAAUF,EAAO,MAAMG,CAAQ;EAE5C;EACA,IAAI,CAACF,EAAS,IAAI,OAAOA;EACzB,IAAMzB,IAAM,MAAM,WAAWwB,GAAQC,EAAS,OAAOE,EAAS,SAAS;EACvE,OAAO1C,GAAQ,YAAY,KAAOzB,EAAY,WAAW,8BAA8B,IAAIwC;CAC5F;CAEA,OAAO,OAAO,MAA2B;EACxC,IAAI6B,EAAQ,QAAQ,YAAY,IAC/B,OAAOrE,EAAY,WAAW,8BAA8B;EAE7D,IAAM4D,IAAU,MAAM,gBAAgBS,EAAQ,MAAM;EAEpD,OADKT,EAAQ,KACN,MAAM,OACZA,EAAQ,OACR;GAAE,WAAWS,EAAQ;GAAW,GAAIA,EAAQ,QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,KAAKA,EAAQ,IAAI;EAAG,GAC3FA,EAAQ,MACT,IALwBT;CAMzB;AACD"}
1
+ {"version":3,"file":"remote-jwks.js","names":["joseFailure","importJwkEntry","jwkEntryCacheKey","parseJwks","selectJwk","JWS_ALGORITHMS","successResult","throwMicro509Error","ABORTED","DEFAULTS","REDIRECT_STATUSES","LOOPBACK_HOSTS","url","value","fallback","name","resolved","config","maxRedirects","maxTtlMs","cooldownMs","target","init","destination","from","message","status","headers","requestedAt","receivedAt","directives","directive","date","apparentAge","reportedAge","transit","age","maxAge","lifetime","match","expires","response","maxBytes","signal","tooLarge","declared","reader","chunks","total","done","body","offset","chunk","redirects","location","jwks","hop","fetched","previous","imported","entry","algorithm","key","carried","TIMED_OUT","settings","snapshot","refresh","lastAttemptAt","controller","previousAttemptAt","timer","deadline","resolve","work","tracked","outcome","joined","settled","current","cached","pending","loaded","selector","source","selected","reloaded","request"],"sources":["../../src/jose/remote-jwks.ts"],"sourcesContent":["/**\n * Opt-in remote JWK Set resolution. A resolver is bound to one trusted JWKS URL from caller\n * configuration and keeps its own cache, so two issuers never share keys. Importing this module\n * performs no request; only a verification that reaches the resolver can.\n *\n * @module\n */\n\nimport type { JoseErrorResult, JoseResult, KeyResolutionErrorCode } from '#micro509/jose/errors';\nimport { joseFailure } from '#micro509/jose/errors';\nimport type { JwkSelector, Jwks, SupportedJwkEntry } from '#micro509/jose/jwks';\nimport { importJwkEntry, jwkEntryCacheKey, parseJwks, selectJwk } from '#micro509/jose/jwks';\nimport type { JwsAlgorithm, JwsKeyRequest, JwsKeyResolver } from '#micro509/jose/jws';\nimport { JWS_ALGORITHMS } from '#micro509/jose/jws';\nimport { successResult, throwMicro509Error } from '#micro509/result/result';\n\n/** The request {@linkcode JwksTransport} must issue. */\nexport interface JwksRequestInit {\n\t/** Always `GET`. */\n\treadonly method: 'GET';\n\t/** Always `manual`: the resolver validates every redirect destination itself. */\n\treadonly redirect: 'manual';\n\t/** Always `omit`. */\n\treadonly credentials: 'omit';\n\t/** Always `no-store`: each resolver refresh must reach the issuer, bypassing the HTTP cache. */\n\treadonly cache: 'no-store';\n\t/** Configured request headers. Withheld from any origin other than the configured URL's. */\n\treadonly headers: Readonly<Record<string, string>>;\n\t/** Aborts on timeout, cancellation or when no verification still waits for the response. */\n\treadonly signal: AbortSignal;\n}\n\n/**\n * Performs one HTTP request. `fetch` satisfies this type. Supply another to route through a proxy,\n * apply egress or DNS controls, or serve fixtures; the transport sees only URLs the resolver\n * already validated.\n */\nexport type JwksTransport = (url: string, init: JwksRequestInit) => Promise<Response>;\n\n/** Redirect handling for a remote JWK Set. By default redirects are refused. */\nexport interface RemoteJwksRedirectPolicy {\n\t/** Maximum redirects followed per fetch. */\n\treadonly maxRedirects: number;\n\t/**\n\t * Approves a redirect destination. Default: same origin as the hop it came from. The scheme\n\t * rule applies first: `https`, or `http` for a loopback host.\n\t */\n\treadonly allow?: (destination: URL, from: URL) => boolean;\n}\n\n/** Configuration of {@linkcode createRemoteJwksKeyResolver}. */\nexport interface RemoteJwksConfig {\n\t/** The trusted JWKS URL. `https`, or `http` for a loopback host. Never taken from a token. */\n\treadonly url: string | URL;\n\t/** Request transport. Default: `globalThis.fetch`. */\n\treadonly transport?: JwksTransport;\n\t/** Request headers, sent only to the configured URL's origin. */\n\treadonly headers?: Readonly<Record<string, string>>;\n\t/** Whole-request deadline in milliseconds, response body included. Default `5000`. */\n\treadonly timeoutMs?: number;\n\t/** Maximum response body in bytes, enforced while streaming. Default `65536`. */\n\treadonly maxResponseBytes?: number;\n\t/** Maximum keys in the set. Default `32`. */\n\treadonly maxKeys?: number;\n\t/** Redirect handling. Default: refuse every redirect. */\n\treadonly redirects?: RemoteJwksRedirectPolicy;\n\t/** Freshness applied when the response states none, in milliseconds. Default `600000`. */\n\treadonly defaultTtlMs?: number;\n\t/** Longest freshness the resolver will keep a response for, in milliseconds. Default `86400000`. */\n\treadonly maxTtlMs?: number;\n\t/**\n\t * Minimum interval between the starts of two fetches, in milliseconds. It bounds how often\n\t * unknown `kid` values, expired responses and failures can cause a request, and does not\n\t * lengthen how long a response stays fresh. Default `30000`.\n\t */\n\treadonly cooldownMs?: number;\n\t/** The clock in milliseconds since the epoch. Default `Date.now`. */\n\treadonly now?: () => number;\n}\n\n/** Codes {@linkcode createRemoteJwksKeyResolver} throws for unusable configuration. */\nexport type RemoteJwksConfigErrorCode = 'invalid_remote_jwks_config';\n\ntype FetchFailureCode = 'jwks_unavailable' | 'jwks_malformed';\n\ninterface Snapshot {\n\treadonly jwks: Jwks;\n\treadonly expiresAt: number;\n\treadonly imported: Map<string, Promise<JoseResult<CryptoKey, 'key_unsuitable'>>>;\n}\n\ntype RefreshOutcome =\n\t| { readonly kind: 'fresh'; readonly snapshot: Snapshot }\n\t| { readonly kind: 'failed'; readonly failure: JoseErrorResult<FetchFailureCode> }\n\t| { readonly kind: 'abandoned' };\n\ninterface Refresh {\n\treadonly promise: Promise<RefreshOutcome>;\n\treadonly controller: AbortController;\n\treadonly startedAt: number;\n\treadonly previousAttemptAt: number | undefined;\n\twaiters: number;\n}\n\nconst ABORTED: unique symbol = Symbol('micro509.jose.aborted');\n\nconst DEFAULTS = {\n\ttimeoutMs: 5000,\n\tmaxResponseBytes: 65_536,\n\tmaxKeys: 32,\n\tdefaultTtlMs: 600_000,\n\tmaxTtlMs: 86_400_000,\n\tcooldownMs: 30_000,\n} as const;\n\nconst REDIRECT_STATUSES: ReadonlySet<number> = new Set([301, 302, 303, 307, 308]);\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nfunction isPermittedUrl(url: URL): boolean {\n\treturn (\n\t\turl.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))\n\t);\n}\n\nfunction positiveInteger(value: number | undefined, fallback: number, name: string): number {\n\tconst resolved = value ?? fallback;\n\tif (!Number.isSafeInteger(resolved) || resolved <= 0) {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', `${name} must be a positive integer`);\n\t}\n\treturn resolved;\n}\n\ninterface ResolvedConfig {\n\treadonly url: URL;\n\treadonly transport: JwksTransport;\n\treadonly headers: Readonly<Record<string, string>>;\n\treadonly timeoutMs: number;\n\treadonly maxResponseBytes: number;\n\treadonly maxKeys: number;\n\treadonly maxRedirects: number;\n\treadonly allowRedirect: (destination: URL, from: URL) => boolean;\n\treadonly defaultTtlMs: number;\n\treadonly maxTtlMs: number;\n\treadonly cooldownMs: number;\n\treadonly now: () => number;\n}\n\nfunction resolveConfig(config: RemoteJwksConfig): ResolvedConfig {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(config.url);\n\t} catch {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', 'url is not an absolute URL');\n\t}\n\tif (!isPermittedUrl(url)) {\n\t\treturn throwMicro509Error(\n\t\t\t'invalid_remote_jwks_config',\n\t\t\t'url must use https, or http on a loopback host',\n\t\t);\n\t}\n\tif (url.username !== '' || url.password !== '') {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', 'url must not embed credentials');\n\t}\n\tconst maxRedirects = config.redirects?.maxRedirects ?? 0;\n\tif (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0 || maxRedirects > 10) {\n\t\treturn throwMicro509Error(\n\t\t\t'invalid_remote_jwks_config',\n\t\t\t'maxRedirects must be an integer from 0 to 10',\n\t\t);\n\t}\n\tconst maxTtlMs = positiveInteger(config.maxTtlMs, DEFAULTS.maxTtlMs, 'maxTtlMs');\n\tconst cooldownMs = positiveInteger(config.cooldownMs, DEFAULTS.cooldownMs, 'cooldownMs');\n\treturn {\n\t\turl,\n\t\ttransport: config.transport ?? ((target, init) => globalThis.fetch(target, init)),\n\t\theaders: { ...config.headers },\n\t\ttimeoutMs: positiveInteger(config.timeoutMs, DEFAULTS.timeoutMs, 'timeoutMs'),\n\t\tmaxResponseBytes: positiveInteger(\n\t\t\tconfig.maxResponseBytes,\n\t\t\tDEFAULTS.maxResponseBytes,\n\t\t\t'maxResponseBytes',\n\t\t),\n\t\tmaxKeys: positiveInteger(config.maxKeys, DEFAULTS.maxKeys, 'maxKeys'),\n\t\tmaxRedirects,\n\t\tallowRedirect:\n\t\t\tconfig.redirects?.allow ?? ((destination, from) => destination.origin === from.origin),\n\t\tdefaultTtlMs: positiveInteger(config.defaultTtlMs, DEFAULTS.defaultTtlMs, 'defaultTtlMs'),\n\t\tmaxTtlMs,\n\t\tcooldownMs,\n\t\tnow: config.now ?? Date.now,\n\t};\n}\n\nfunction unavailable(message: string, status?: number): JoseErrorResult<'jwks_unavailable'> {\n\treturn joseFailure('jwks_unavailable', message, status === undefined ? undefined : { status });\n}\n\nconst NOT_A_NUMBER = Number.NaN;\n\nfunction secondsHeader(headers: Headers, name: string): number {\n\tconst value = headers.get(name);\n\treturn value !== null && /^\\d{1,10}$/.test(value) ? Number(value) * 1000 : NOT_A_NUMBER;\n}\n\n/**\n * Remaining freshness in milliseconds, never below zero and never above `maxTtlMs`.\n *\n * The lifetime is `Cache-Control: max-age`, else `Expires` less `Date`, else `defaultTtlMs`\n * (RFC 9111 §4.2.1); `no-store`, `no-cache` and unusable values give none. The response age is the\n * larger of the apparent age from `Date` and the `Age` header plus the transit delay\n * (RFC 9111 §4.2.3).\n */\nfunction freshnessMs(\n\theaders: Headers,\n\trequestedAt: number,\n\treceivedAt: number,\n\tconfig: ResolvedConfig,\n): number {\n\tconst directives = (headers.get('cache-control') ?? '')\n\t\t.split(',')\n\t\t.map((directive) => directive.trim().toLowerCase())\n\t\t.filter((directive) => directive.length > 0);\n\tif (directives.includes('no-store') || directives.includes('no-cache')) return 0;\n\tconst date = Date.parse(headers.get('date') ?? '');\n\tconst apparentAge = Number.isNaN(date) ? 0 : Math.max(0, receivedAt - date);\n\tconst reportedAge = secondsHeader(headers, 'age');\n\tconst transit = Math.max(0, receivedAt - requestedAt);\n\tconst age = Math.max(apparentAge, (Number.isNaN(reportedAge) ? 0 : reportedAge) + transit);\n\tconst maxAge = directives.find((directive) => directive.startsWith('max-age'));\n\tlet lifetime = config.defaultTtlMs;\n\tif (maxAge !== undefined) {\n\t\tconst match = /^max-age=(\"?)(\\d{1,10})\\1$/.exec(maxAge);\n\t\tlifetime = match?.[2] === undefined ? 0 : Number(match[2]) * 1000;\n\t} else if (headers.has('expires')) {\n\t\tconst expires = Date.parse(headers.get('expires') ?? '');\n\t\tlifetime = Number.isNaN(expires) ? 0 : expires - (Number.isNaN(date) ? receivedAt : date);\n\t}\n\treturn Math.min(config.maxTtlMs, Math.max(0, lifetime - age));\n}\n\ntype BodyResult = JoseResult<Uint8Array, 'jwks_unavailable' | 'jwks_malformed'>;\n\nasync function readBounded(\n\tresponse: Response,\n\tmaxBytes: number,\n\tsignal: AbortSignal,\n): Promise<BodyResult> {\n\tconst tooLarge = joseFailure('jwks_malformed', `The JWKS response exceeds ${maxBytes} bytes`);\n\tconst declared = response.headers.get('content-length');\n\tif (declared !== null && /^\\d+$/.test(declared) && Number(declared) > maxBytes) {\n\t\tawait response.body?.cancel();\n\t\treturn tooLarge;\n\t}\n\tif (response.body === null) return successResult(new Uint8Array(0));\n\tconst reader = response.body.getReader();\n\tconst release = (): void => {\n\t\treader.cancel().catch(() => undefined);\n\t};\n\tsignal.addEventListener('abort', release, { once: true });\n\ttry {\n\t\tconst chunks: Uint8Array[] = [];\n\t\tlet total = 0;\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (signal.aborted) return unavailable('The JWKS request was cancelled');\n\t\t\tif (done) break;\n\t\t\ttotal += value.byteLength;\n\t\t\tif (total > maxBytes) {\n\t\t\t\trelease();\n\t\t\t\treturn tooLarge;\n\t\t\t}\n\t\t\tchunks.push(value);\n\t\t}\n\t\tconst body = new Uint8Array(total);\n\t\tlet offset = 0;\n\t\tfor (const chunk of chunks) {\n\t\t\tbody.set(chunk, offset);\n\t\t\toffset += chunk.byteLength;\n\t\t}\n\t\treturn successResult(body);\n\t} finally {\n\t\tsignal.removeEventListener('abort', release);\n\t}\n}\n\ninterface Fetched {\n\treadonly jwks: Jwks;\n\treadonly expiresAt: number;\n}\n\nfunction nextHop(\n\tconfig: ResolvedConfig,\n\tfrom: URL,\n\tresponse: Response,\n\tredirects: number,\n): JoseResult<URL, 'jwks_unavailable'> {\n\tconst location = response.headers.get('location');\n\tif (redirects >= config.maxRedirects || location === null) {\n\t\treturn unavailable('The JWKS endpoint redirected', response.status);\n\t}\n\tlet destination: URL;\n\ttry {\n\t\tdestination = new URL(location, from);\n\t} catch {\n\t\treturn unavailable('The JWKS redirect target is not a URL', response.status);\n\t}\n\tif (\n\t\t!isPermittedUrl(destination) ||\n\t\tdestination.username !== '' ||\n\t\tdestination.password !== '' ||\n\t\t!config.allowRedirect(destination, from)\n\t) {\n\t\treturn unavailable('The JWKS redirect target is not permitted', response.status);\n\t}\n\treturn successResult(destination);\n}\n\nasync function readJwks(\n\tconfig: ResolvedConfig,\n\tresponse: Response,\n\trequestedAt: number,\n\tsignal: AbortSignal,\n): Promise<JoseResult<Fetched, FetchFailureCode>> {\n\tif (response.status !== 200) {\n\t\tawait response.body?.cancel();\n\t\treturn unavailable('The JWKS endpoint did not answer 200', response.status);\n\t}\n\tconst receivedAt = config.now();\n\tconst body = await readBounded(response, config.maxResponseBytes, signal);\n\tif (!body.ok) return body;\n\tconst jwks = parseJwks(body.value, {\n\t\tmaxBytes: config.maxResponseBytes,\n\t\tmaxKeys: config.maxKeys,\n\t});\n\tif (!jwks.ok) return joseFailure('jwks_malformed', jwks.message);\n\treturn successResult({\n\t\tjwks: jwks.value,\n\t\texpiresAt: receivedAt + freshnessMs(response.headers, requestedAt, receivedAt, config),\n\t});\n}\n\nasync function fetchJwks(\n\tconfig: ResolvedConfig,\n\tsignal: AbortSignal,\n\trequestedAt: number,\n): Promise<JoseResult<Fetched, FetchFailureCode>> {\n\tlet url = config.url;\n\tfor (let redirects = 0; ; redirects++) {\n\t\tconst response = await config.transport(url.href, {\n\t\t\tmethod: 'GET',\n\t\t\tredirect: 'manual',\n\t\t\tcredentials: 'omit',\n\t\t\tcache: 'no-store',\n\t\t\theaders: url.origin === config.url.origin ? config.headers : {},\n\t\t\tsignal,\n\t\t});\n\t\tif (signal.aborted) {\n\t\t\tawait response.body?.cancel();\n\t\t\treturn unavailable('The JWKS request was cancelled');\n\t\t}\n\t\tif (response.type === 'opaqueredirect') {\n\t\t\treturn unavailable('The runtime hides redirects, so they cannot be validated');\n\t\t}\n\t\tif (!REDIRECT_STATUSES.has(response.status)) {\n\t\t\treturn await readJwks(config, response, requestedAt, signal);\n\t\t}\n\t\tawait response.body?.cancel();\n\t\tconst hop = nextHop(config, url, response, redirects);\n\t\tif (!hop.ok) return hop;\n\t\turl = hop.value;\n\t}\n}\n\nfunction carryOver(fetched: Fetched, previous: Snapshot | undefined): Snapshot {\n\tconst imported = new Map<string, Promise<JoseResult<CryptoKey, 'key_unsuitable'>>>();\n\tfor (const entry of fetched.jwks.keys) {\n\t\tif (entry.kind === 'unsupported') continue;\n\t\tfor (const algorithm of JWS_ALGORITHMS) {\n\t\t\tconst key = jwkEntryCacheKey(entry, algorithm);\n\t\t\tconst carried = previous?.imported.get(key);\n\t\t\tif (carried !== undefined) imported.set(key, carried);\n\t\t}\n\t}\n\treturn { jwks: fetched.jwks, expiresAt: fetched.expiresAt, imported };\n}\n\nconst TIMED_OUT: unique symbol = Symbol('micro509.jose.timedOut');\n\n/**\n * Creates a key resolver that reads a JWK Set from one trusted URL.\n *\n * Behaviour, per resolver:\n *\n * - The first verification fetches the set. Later ones reuse it while fresh. Freshness is the\n * remaining lifetime from `Cache-Control: max-age`, else `Expires`, else `defaultTtlMs`, less the\n * response age (the larger of the apparent age from `Date` and `Age` plus the transit delay),\n * capped at `maxTtlMs`. `no-store`, `no-cache` and a lifetime already spent leave none: the set\n * serves the verification that fetched it and nothing after. No heuristic freshness is applied.\n * - A set that is no longer fresh is never used, whether or not a refresh succeeds. There is no\n * stale-if-error. A refresh that fails while the cached set is still fresh keeps that set until\n * it expires.\n * - Refreshes are separate from freshness: after any attempt the next one waits `cooldownMs`.\n * Within that interval a token whose `kid` is absent gets `key_not_found`, and a token that\n * needs a set that is no longer fresh gets `jwks_unavailable`. Concurrent verifications share\n * a single request, and unknown `kid` values are never cached.\n * - A refresh replaces the whole set, so a rotated-out key stops verifying as soon as the new\n * set is read. Rotation must therefore introduce a new `kid`.\n * - The whole request, response body included, is bounded by `timeoutMs` and enforced even when\n * the transport ignores the abort signal. Redirects, bytes and keys are bounded by `redirects`,\n * `maxResponseBytes` and `maxKeys`. No retry happens inside a fetch. Cancelling the last waiting\n * verification aborts the request, and a response that finishes afterwards is discarded.\n * - Request headers go only to the configured origin. `jku`, `x5u` and `jwk` headers are never\n * used.\n *\n * Throws a `ResultError` coded {@linkcode RemoteJwksConfigErrorCode} for unusable configuration.\n * Redirect destinations, and the addresses a hostname resolves to, are limited by `redirects` and\n * the transport; this module cannot see DNS answers, and browsers hide redirect targets.\n */\nexport function createRemoteJwksKeyResolver(config: RemoteJwksConfig): JwsKeyResolver {\n\tconst settings = resolveConfig(config);\n\tlet snapshot: Snapshot | undefined;\n\tlet refresh: Refresh | undefined;\n\tlet lastAttemptAt: number | undefined;\n\n\tfunction startRefresh(): Refresh {\n\t\tconst controller = new AbortController();\n\t\tconst requestedAt = settings.now();\n\t\tconst previousAttemptAt = lastAttemptAt;\n\t\tconst previous = snapshot;\n\t\tlastAttemptAt = requestedAt;\n\n\t\tasync function run(): Promise<RefreshOutcome> {\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst deadline = new Promise<typeof TIMED_OUT>((resolve) => {\n\t\t\t\ttimer = setTimeout(() => resolve(TIMED_OUT), settings.timeoutMs);\n\t\t\t});\n\t\t\tconst work = fetchJwks(settings, controller.signal, requestedAt);\n\t\t\twork.catch(() => undefined);\n\t\t\ttry {\n\t\t\t\tconst fetched = await Promise.race([work, deadline]);\n\t\t\t\tif (fetched === TIMED_OUT) {\n\t\t\t\t\tcontroller.abort();\n\t\t\t\t\treturn { kind: 'failed', failure: unavailable('The JWKS request timed out') };\n\t\t\t\t}\n\t\t\t\tif (!fetched.ok) return { kind: 'failed', failure: fetched };\n\t\t\t\treturn { kind: 'fresh', snapshot: carryOver(fetched.value, previous) };\n\t\t\t} catch {\n\t\t\t\treturn controller.signal.aborted\n\t\t\t\t\t? { kind: 'abandoned' }\n\t\t\t\t\t: { kind: 'failed', failure: unavailable('The JWKS request failed') };\n\t\t\t} finally {\n\t\t\t\tclearTimeout(timer);\n\t\t\t}\n\t\t}\n\n\t\tconst tracked: Promise<RefreshOutcome> = run()\n\t\t\t.then((outcome): RefreshOutcome => {\n\t\t\t\tif (refresh?.promise !== tracked) return { kind: 'abandoned' };\n\t\t\t\tif (outcome.kind === 'fresh') snapshot = outcome.snapshot;\n\t\t\t\treturn outcome;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tif (refresh?.promise === tracked) refresh = undefined;\n\t\t\t});\n\t\treturn {\n\t\t\tpromise: tracked,\n\t\t\tcontroller,\n\t\t\tstartedAt: requestedAt,\n\t\t\tpreviousAttemptAt,\n\t\t\twaiters: 0,\n\t\t};\n\t}\n\n\tasync function awaitRefresh(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<RefreshOutcome | typeof ABORTED> {\n\t\tif (signal?.aborted === true) return ABORTED;\n\t\trefresh ??= startRefresh();\n\t\tconst joined = refresh;\n\t\tjoined.waiters++;\n\t\tif (signal === undefined) return await joined.promise;\n\t\treturn await new Promise<RefreshOutcome | typeof ABORTED>((resolve) => {\n\t\t\tlet settled = false;\n\t\t\tconst finish = (): void => {\n\t\t\t\tsettled = true;\n\t\t\t\tsignal.removeEventListener('abort', onAbort);\n\t\t\t};\n\t\t\tconst onAbort = (): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tfinish();\n\t\t\t\tjoined.waiters--;\n\t\t\t\tif (joined.waiters === 0) {\n\t\t\t\t\tif (refresh === joined) refresh = undefined;\n\t\t\t\t\tif (lastAttemptAt === joined.startedAt) lastAttemptAt = joined.previousAttemptAt;\n\t\t\t\t\tjoined.controller.abort();\n\t\t\t\t}\n\t\t\t\tresolve(ABORTED);\n\t\t\t};\n\t\t\tsignal.addEventListener('abort', onAbort, { once: true });\n\t\t\tif (signal.aborted) onAbort();\n\t\t\tvoid joined.promise.then((outcome) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tfinish();\n\t\t\t\tresolve(outcome);\n\t\t\t});\n\t\t});\n\t}\n\n\tfunction refreshAllowed(): boolean {\n\t\tif (refresh !== undefined || lastAttemptAt === undefined) return true;\n\t\treturn settings.now() - lastAttemptAt >= settings.cooldownMs;\n\t}\n\n\tasync function obtain(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<Snapshot | undefined, FetchFailureCode | 'aborted'>> {\n\t\tif (!refreshAllowed()) return successResult(undefined);\n\t\tconst outcome = await awaitRefresh(signal);\n\t\tif (outcome === ABORTED || outcome.kind === 'abandoned') {\n\t\t\treturn joseFailure('aborted', 'Key resolution was cancelled');\n\t\t}\n\t\tif (outcome.kind === 'failed') return outcome.failure;\n\t\treturn successResult(outcome.snapshot);\n\t}\n\n\tasync function importFrom(\n\t\tcurrent: Snapshot,\n\t\tentry: SupportedJwkEntry,\n\t\talgorithm: JwsAlgorithm,\n\t): Promise<JoseResult<CryptoKey, 'key_unsuitable'>> {\n\t\tconst key = jwkEntryCacheKey(entry, algorithm);\n\t\tconst cached = current.imported.get(key);\n\t\tif (cached !== undefined) return await cached;\n\t\tconst pending = importJwkEntry(entry, algorithm);\n\t\tcurrent.imported.set(key, pending);\n\t\treturn await pending;\n\t}\n\n\tasync function currentSnapshot(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<Snapshot, FetchFailureCode | 'aborted'>> {\n\t\tif (snapshot !== undefined && settings.now() < snapshot.expiresAt) {\n\t\t\treturn successResult(snapshot);\n\t\t}\n\t\tsnapshot = undefined;\n\t\tconst loaded = await obtain(signal);\n\t\tif (!loaded.ok) return loaded;\n\t\treturn loaded.value === undefined\n\t\t\t? unavailable('The JWKS endpoint is in cooldown')\n\t\t\t: successResult(loaded.value);\n\t}\n\n\tasync function select(\n\t\tcurrent: Snapshot,\n\t\tselector: JwkSelector,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<CryptoKey, KeyResolutionErrorCode>> {\n\t\tlet source = current;\n\t\tlet selected = selectJwk(source.jwks, selector);\n\t\tif (!selected.ok && selected.code === 'key_not_found') {\n\t\t\tconst reloaded = await obtain(signal);\n\t\t\tif (!reloaded.ok) return reloaded;\n\t\t\tif (reloaded.value !== undefined) {\n\t\t\t\tsource = reloaded.value;\n\t\t\t\tselected = selectJwk(source.jwks, selector);\n\t\t\t}\n\t\t}\n\t\tif (!selected.ok) return selected;\n\t\tconst key = await importFrom(source, selected.value, selector.algorithm);\n\t\treturn signal?.aborted === true ? joseFailure('aborted', 'Key resolution was cancelled') : key;\n\t}\n\n\treturn async (request: JwsKeyRequest) => {\n\t\tif (request.signal?.aborted === true) {\n\t\t\treturn joseFailure('aborted', 'Key resolution was cancelled');\n\t\t}\n\t\tconst current = await currentSnapshot(request.signal);\n\t\tif (!current.ok) return current;\n\t\treturn await select(\n\t\t\tcurrent.value,\n\t\t\t{ algorithm: request.algorithm, ...(request.kid === undefined ? {} : { kid: request.kid }) },\n\t\t\trequest.signal,\n\t\t);\n\t};\n}\n"],"mappings":";;;;;AAwGA,MAAMQ,IAAyB,OAAO,uBAAuB,GAEvDC,IAAW;CAChB,WAAW;CACX,kBAAkB;CAClB,SAAS;CACT,cAAc;CACd,UAAU;CACV,YAAY;AACb,GAEMC,oBAAyC,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC,GAE1EC,oBAAsC,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;AAEvF,SAAS,eAAeC,GAAmB;CAC1C,OACCA,EAAI,aAAa,YAAaA,EAAI,aAAa,WAAWD,EAAe,IAAIC,EAAI,QAAQ;AAE3F;AAEA,SAAS,gBAAgBC,GAA2BC,GAAkBC,GAAsB;CAC3F,IAAMC,IAAWH,KAASC;CAI1B,OAHI,CAAC,OAAO,cAAcE,CAAQ,KAAKA,KAAY,IAC3CT,EAAmB,8BAA8B,GAAGQ,EAAK,4BAA4B,IAEtFC;AACR;AAiBA,SAAS,cAAcC,GAA0C;CAChE,IAAIL;CACJ,IAAI;EACHA,IAAM,IAAI,IAAIK,EAAO,GAAG;CACzB,QAAQ;EACP,OAAOV,EAAmB,8BAA8B,4BAA4B;CACrF;CACA,IAAI,CAAC,eAAeK,CAAG,GACtB,OAAOL,EACN,8BACA,gDACD;CAED,IAAIK,EAAI,aAAa,MAAMA,EAAI,aAAa,IAC3C,OAAOL,EAAmB,8BAA8B,gCAAgC;CAEzF,IAAMW,IAAeD,EAAO,WAAW,gBAAgB;CACvD,IAAI,CAAC,OAAO,cAAcC,CAAY,KAAKA,IAAe,KAAKA,IAAe,IAC7E,OAAOX,EACN,8BACA,8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GAAW,GAAIA,EAAQ,QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,KAAKA,EAAQ,IAAI;EAAG,GAC3FA,EAAQ,MACT,IALwBR;CAMzB;AACD"}
@@ -1 +1 @@
1
- {"version":3,"file":"argon2-arithmetic.js","names":["a","b","low"],"sources":["../../src/kdf/argon2-arithmetic.ts"],"sourcesContent":["/**\n * Exact high word of an unsigned 32×32 product; `low` is Math.imul(a, b).\n *\n * Subtracting the exact low word leaves a multiple of 2^32 with at most 2048\n * units of floating-point error. Scaling by 2^32 reduces that error below\n * 2^-20, so adding 0.5 and truncating recovers the exact integer high word.\n * BlaMka already computes the low word and passes it here for reuse.\n */\nexport function multiplyHigh(a: number, b: number, low: number): number {\n\treturn ((a * b - (low >>> 0)) / 0x1_0000_0000 + 0.5) >>> 0;\n}\n"],"mappings":";;;;;;;;;AAQA,SAAgB,aAAa,GAAW,GAAW,GAAqB;CACvE,QAASA,IAAIC,KAAKC,MAAQ,MAAM,aAAgB,OAAS;AAC1D"}
1
+ {"version":3,"file":"argon2-arithmetic.js","names":["a","b","low"],"sources":["../../src/kdf/argon2-arithmetic.ts"],"sourcesContent":["/**\n * Exact high word of an unsigned 32×32 product; `low` is Math.imul(a, b).\n *\n * Subtracting the exact low word leaves a multiple of 2^32 with at most 2048\n * units of floating-point error. Scaling by 2^32 reduces that error below\n * 2^-20, so adding 0.5 and truncating recovers the exact integer high word.\n * BlaMka already computes the low word and passes it here for reuse.\n */\nexport function multiplyHigh(a: number, b: number, low: number): number {\n\treturn ((a * b - (low >>> 0)) / 0x1_0000_0000 + 0.5) >>> 0;\n}\n"],"mappings":";;;;;;;;;AAQA,SAAgB,aAAaA,GAAWC,GAAWC,GAAqB;CACvE,QAASF,IAAIC,KAAKC,MAAQ,MAAM,aAAgB,OAAS;AAC1D"}