micro509 0.17.1 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/CHANGELOG.md +78 -6
  2. package/dist/crypto/crypto.d.ts +2 -3
  3. package/dist/crypto.d.ts +6 -0
  4. package/dist/der/der.d.ts +14 -4
  5. package/dist/der/der.js +19 -19
  6. package/dist/der.d.ts +26 -2
  7. package/dist/der.js +4 -4
  8. package/dist/index.d.ts +82 -15
  9. package/dist/index.js +19 -19
  10. package/dist/internal/asn1/asn1.d.ts +1 -2
  11. package/dist/internal/asn1/der.d.ts +1 -2
  12. package/dist/internal/asn1/oids.js +71 -353
  13. package/dist/internal/asn1/oids.js.map +1 -1
  14. package/dist/internal/asn1/oids.json.js +357 -0
  15. package/dist/internal/asn1/oids.json.js.map +1 -0
  16. package/dist/internal/crypto/algorithm-names.js +1 -1
  17. package/dist/internal/crypto/pbes2.d.ts +1 -2
  18. package/dist/internal/crypto/pbes2.js +70 -70
  19. package/dist/internal/crypto/prime-ec.js +37 -0
  20. package/dist/internal/crypto/prime-ec.js.map +1 -0
  21. package/dist/internal/crypto/rsa-pss.js +50 -50
  22. package/dist/internal/crypto/sig-verify.d.ts +1 -2
  23. package/dist/internal/crypto/sig-verify.js +60 -60
  24. package/dist/internal/crypto/signing.d.ts +1 -2
  25. package/dist/internal/crypto/signing.js +26 -26
  26. package/dist/internal/jose/json-data.js +108 -0
  27. package/dist/internal/jose/json-data.js.map +1 -0
  28. package/dist/internal/jose/strict-json.d.ts +1 -2
  29. package/dist/internal/shared/dn.d.ts +1 -2
  30. package/dist/internal/shared/dn.js +1 -1
  31. package/dist/internal/shared/ip.d.ts +1 -2
  32. package/dist/internal/verify/name-constraints-engine.js +64 -64
  33. package/dist/internal/verify/policy-engine.js +1 -1
  34. package/dist/internal/verify/verify-path.d.ts +1 -2
  35. package/dist/internal/verify/verify-path.js +19 -19
  36. package/dist/internal/x509/directory-name.js +10 -10
  37. package/dist/internal/x509/extension-errors.d.ts +1 -2
  38. package/dist/internal/x509/extension-registry.js +18 -18
  39. package/dist/internal/x509/general-name-profile.js +9 -9
  40. package/dist/internal/x509/general-name.js +32 -32
  41. package/dist/internal/x509/name-fields.js +1 -1
  42. package/dist/jose/base64url.d.ts +4 -0
  43. package/dist/jose/base64url.js +14 -0
  44. package/dist/jose/base64url.js.map +1 -0
  45. package/dist/jose/errors.d.ts +9 -3
  46. package/dist/jose/errors.js.map +1 -1
  47. package/dist/jose/jwe.d.ts +64 -0
  48. package/dist/jose/jwe.js +188 -0
  49. package/dist/jose/jwe.js.map +1 -0
  50. package/dist/jose/jwks.d.ts +38 -10
  51. package/dist/jose/jwks.js +156 -96
  52. package/dist/jose/jwks.js.map +1 -1
  53. package/dist/jose/jws.d.ts +8 -6
  54. package/dist/jose/jws.js +216 -170
  55. package/dist/jose/jws.js.map +1 -1
  56. package/dist/jose/jwt.d.ts +8 -2
  57. package/dist/jose/jwt.js +98 -98
  58. package/dist/jose/remote-jwks.d.ts +1 -2
  59. package/dist/jose/remote-jwks.js +106 -108
  60. package/dist/jose/remote-jwks.js.map +1 -1
  61. package/dist/jose.d.ts +15 -4
  62. package/dist/jose.js +7 -5
  63. package/dist/kdf/argon2.d.ts +7 -2
  64. package/dist/kdf.d.ts +6 -0
  65. package/dist/keys/keys.d.ts +31 -6
  66. package/dist/keys/keys.js +315 -233
  67. package/dist/keys/keys.js.map +1 -1
  68. package/dist/keys.d.ts +11 -2
  69. package/dist/keys.js +2 -2
  70. package/dist/pem/pem.d.ts +1 -2
  71. package/dist/pem/pem.js +40 -25
  72. package/dist/pem/pem.js.map +1 -1
  73. package/dist/pem.d.ts +6 -0
  74. package/dist/pkcs/pfx.d.ts +2 -3
  75. package/dist/pkcs/pfx.js +142 -142
  76. package/dist/pkcs/pkcs12-mac.d.ts +1 -2
  77. package/dist/pkcs/pkcs12-mac.js +122 -122
  78. package/dist/pkcs/pkcs7.d.ts +14 -3
  79. package/dist/pkcs/pkcs7.js +268 -248
  80. package/dist/pkcs/pkcs7.js.map +1 -1
  81. package/dist/pkcs.d.ts +10 -1
  82. package/dist/pkcs.js +4 -4
  83. package/dist/result/result.d.ts +1 -2
  84. package/dist/result.d.ts +6 -0
  85. package/dist/revocation/chain.d.ts +2 -3
  86. package/dist/revocation/chain.js +52 -52
  87. package/dist/revocation/crl.d.ts +2 -3
  88. package/dist/revocation/crl.js +319 -319
  89. package/dist/revocation/crl.js.map +1 -1
  90. package/dist/revocation/ocsp.d.ts +2 -3
  91. package/dist/revocation/ocsp.js +395 -395
  92. package/dist/revocation/revocation.d.ts +2 -3
  93. package/dist/revocation/revocation.js +22 -22
  94. package/dist/revocation.d.ts +12 -3
  95. package/dist/revocation.js +4 -4
  96. package/dist/ssh/ssh.d.ts +2 -3
  97. package/dist/ssh/ssh.js +165 -170
  98. package/dist/ssh/ssh.js.map +1 -1
  99. package/dist/ssh/wire.d.ts +1 -2
  100. package/dist/ssh/wire.js +10 -10
  101. package/dist/ssh.d.ts +8 -0
  102. package/dist/verify/identity.d.ts +1 -2
  103. package/dist/verify/identity.js +31 -31
  104. package/dist/verify/name-constraints.d.ts +9 -2
  105. package/dist/verify/policy.d.ts +9 -2
  106. package/dist/verify/verify.d.ts +3 -4
  107. package/dist/verify/verify.js +121 -121
  108. package/dist/verify.d.ts +9 -0
  109. package/dist/x509/certificate.d.ts +4 -5
  110. package/dist/x509/certificate.js +40 -40
  111. package/dist/x509/csr.d.ts +3 -4
  112. package/dist/x509/csr.js +15 -15
  113. package/dist/x509/extensions.d.ts +1 -2
  114. package/dist/x509/extensions.js +165 -165
  115. package/dist/x509/extensions.js.map +1 -1
  116. package/dist/x509/fingerprint.d.ts +1 -2
  117. package/dist/x509/name-text.d.ts +1 -2
  118. package/dist/x509/name.d.ts +1 -2
  119. package/dist/x509/name.js +15 -15
  120. package/dist/x509/parse.d.ts +3 -4
  121. package/dist/x509/parse.js +423 -423
  122. package/dist/x509.d.ts +17 -4
  123. package/dist/x509.js +8 -8
  124. package/package.json +22 -23
  125. package/dist/internal/asn1/oids2.js +0 -75
  126. package/dist/internal/asn1/oids2.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"jws.js","names":["_exhaustive","JWS_ALGORITHMS","MIN_RS256_MODULUS_BITS","DEFAULT_JOSE_LIMITS","LIMIT_NAMES","overrides","joseFailure","resolved","name","value","ceiling","successResult","textEncoder","strictDecoder","decodedBytes","code","message","segment","maxBytes","bytes","base64UrlDecode","text","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","algorithm","supported","first","exponent","byte","last","length","modulus","i","left","right","key","options","algorithms","candidate","typeRule","tokenType","signal","prepared","details","status","unverified","signatureBytes","failure","verification","verifySignatureWithKey","OIDS","input","throwMicro509Error","signingInput","base64UrlEncode","signData"],"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 { 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';\n\n/** Every {@linkcode JwsAlgorithm}. */\nexport const JWS_ALGORITHMS: readonly JwsAlgorithm[] = ['RS256'];\n\n/** Smallest RSA modulus RS256 accepts (RFC 7518 §3.3). */\nexport const MIN_RS256_MODULUS_BITS = 2048;\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/** An RSASSA-PKCS1-v1_5 SHA-256 private key of 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(\n\tcode: JwsParseErrorCode,\n\tmessage: string,\n): JoseErrorResult<JwsParseErrorCode> {\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(\n\tbytes: Uint8Array,\n\tlimits: JoseLimits,\n\tname: string,\n\tnotObjectCode: 'invalid_header' | 'invalid_payload',\n): JoseResult<JsonObject, JwsParseErrorCode> {\n\tlet text: string;\n\ttry {\n\t\ttext = strictDecoder.decode(bytes);\n\t} catch {\n\t\treturn parseFailure('invalid_utf8', `JWS ${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, `JWS ${name}: ${parsed.message}`);\n\t}\n\tconst value = parsed.value;\n\tif (!isJsonObject(value)) {\n\t\treturn parseFailure(notObjectCode, `JWS ${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/**\n * Checks a key may verify RS256 (RFC 7518 §3.3, RFC 8725 §3.1) and returns the signature length\n * in bytes it requires (RFC 8017 §8.2.2).\n */\nexport function checkRs256VerificationKey(key: CryptoKey): JoseResult<number, 'key_unsuitable'> {\n\ttry {\n\t\treturn inspectRs256VerificationKey(key);\n\t} catch {\n\t\treturn joseFailure('key_unsuitable', 'The key cannot be inspected');\n\t}\n}\n\nfunction inspectRs256VerificationKey(key: CryptoKey): JoseResult<number, 'key_unsuitable'> {\n\tconst algorithm = key.algorithm;\n\tif (key.type !== 'public' || !key.usages.includes('verify')) {\n\t\treturn joseFailure('key_unsuitable', 'RS256 needs a public key with verify usage');\n\t}\n\tif (\n\t\talgorithm.name !== 'RSASSA-PKCS1-v1_5' ||\n\t\t!('hash' in algorithm) ||\n\t\ttypeof algorithm.hash !== 'object' ||\n\t\talgorithm.hash === null ||\n\t\t!('name' in algorithm.hash) ||\n\t\talgorithm.hash.name !== 'SHA-256'\n\t) {\n\t\treturn joseFailure('key_unsuitable', 'RS256 needs an RSASSA-PKCS1-v1_5 SHA-256 key');\n\t}\n\tif (\n\t\t!('modulusLength' in algorithm) ||\n\t\ttypeof algorithm.modulusLength !== 'number' ||\n\t\talgorithm.modulusLength < MIN_RS256_MODULUS_BITS\n\t) {\n\t\treturn joseFailure(\n\t\t\t'key_unsuitable',\n\t\t\t`RS256 needs an RSA modulus of at least ${MIN_RS256_MODULUS_BITS} bits`,\n\t\t);\n\t}\n\tif (\n\t\t!('publicExponent' in algorithm) ||\n\t\t!(algorithm.publicExponent instanceof Uint8Array) ||\n\t\t!validRsaPublicExponent(algorithm.publicExponent)\n\t) {\n\t\treturn joseFailure(\n\t\t\t'key_unsuitable',\n\t\t\t'RS256 needs a valid odd RSA public exponent of at least 3',\n\t\t);\n\t}\n\treturn successResult(Math.ceil(algorithm.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. A fixed key or the resolver's key must be an RSASSA-PKCS1-v1_5 SHA-256\n * public key of at least 2048 bits for RS256. 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 = checkRs256VerificationKey(key.value);\n\tif (!signatureBytes.ok) return signatureBytes;\n\tif (unverified.signature.length !== signatureBytes.value) {\n\t\treturn joseFailure('invalid_signature', 'The signature length differs from the modulus', {\n\t\t\talg,\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: OIDS.sha256WithRSAEncryption },\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\tconst algorithm = input.privateKey.algorithm;\n\tif (!JWS_ALGORITHMS.includes(input.algorithm)) {\n\t\tthrowMicro509Error('unsupported_algorithm', 'Unsupported JWS algorithm');\n\t}\n\tif (\n\t\tinput.privateKey.type !== 'private' ||\n\t\t!input.privateKey.usages.includes('sign') ||\n\t\talgorithm.name !== 'RSASSA-PKCS1-v1_5' ||\n\t\t!('hash' in algorithm) ||\n\t\ttypeof algorithm.hash !== 'object' ||\n\t\talgorithm.hash === null ||\n\t\t!('name' in algorithm.hash) ||\n\t\talgorithm.hash.name !== 'SHA-256' ||\n\t\t!('modulusLength' in algorithm) ||\n\t\ttypeof algorithm.modulusLength !== 'number' ||\n\t\talgorithm.modulusLength < MIN_RS256_MODULUS_BITS\n\t) {\n\t\tthrowMicro509Error(\n\t\t\t'incompatible_key',\n\t\t\t`RS256 signing needs an RSASSA-PKCS1-v1_5 SHA-256 private key of at least ${MIN_RS256_MODULUS_BITS} bits`,\n\t\t);\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 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\treturn `${signingInput}.${base64UrlEncode(signature)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,MAAaC,IAA0C,CAAC,OAAO,GAGlDC,IAAyB,MAmBzBC,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,aAAYA,IAChE,OAAOC,EAAY,mBAAmB,0BAA0B;CAEjE,IAAMC,IAAuE,EAC5E,GAAGJ,EACJ;CACA,KAAK,IAAMK,KAAQJ,GAAa;EAC/B,IAAMK,IAAQJ,IAAYG;EAC1B,IAAIC,MAAU,KAAA,GAAW;EACzB,IAAMC,IAAUF,MAAS,iBAAA;EACzB,IAAI,CAAC,OAAO,cAAcC,CAAK,KAAKA,IAAQ,KAAKA,IAAQC,GACxD,OAAOJ,EAAY,mBAAmB,UAAUE,EAAK,iCAAiC;EAEvF,EAASA,KAAQC;CAClB;CACA,OAAOE,EAAcJ,CAAQ;AAC9B;AAsHA,MAAMK,IAAc,IAAI,YAAY,GAC9BC,IAAgB,IAAI,YAAY,SAAS;CAAE,OAAO;CAAM,WAAW;AAAK,CAAC;AAE/E,SAAS,iBAAiB,GAA8B;CACvD,OAAO,KAAK,KAAMC,IAAe,IAAK,CAAC;AACxC;AAEA,SAAS,aACR,GACA,GACqC;CACrC,OAAOR,EAAYS,GAAMC,CAAO;AACjC;AAEA,SAAS,cACR,GACA,GACA,GAC4C;CAC5C,IAAIC,EAAQ,SAAS,iBAAiBC,CAA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F,EAAe,SAASmF,EAAM,SAAS,KAC3CC,EAAmB,yBAAyB,2BAA2B,IAGvED,EAAM,WAAW,SAAS,aAC1B,CAACA,EAAM,WAAW,OAAO,SAAS,MAAM,KACxC3B,EAAU,SAAS,uBACnB,EAAE,UAAUA,MACZ,OAAOA,EAAU,QAAS,YAC1BA,EAAU,SAAS,QACnB,EAAE,UAAUA,EAAU,SACtBA,EAAU,KAAK,SAAS,aACxB,EAAE,mBAAmBA,MACrB,OAAOA,EAAU,iBAAkB,YACnCA,EAAU,gBAAA,SAEV4B,EACC,oBACA,4EAA4EnF,EAAuB,MACpG;AAEF;;;;;;;;AASA,eAAsB,eAAe,GAAsC;CAC1E,iBAAiBkF,CAAK;CACtB,IAAMxC,IAAiC,EAAE,KAAKwC,EAAM,UAAU;CAC9D,KAAK,IAAM5E,KAAQ;EAAC;EAAO;EAAO;CAAK,GAAY;EAClD,IAAMC,IAAQ2E,EAAM,SAAS5E;EAC7B,AAAIC,MAAU,KAAA,MACV,OAAOA,KAAU,YACpB4E,EAAmB,kBAAkB,WAAW7E,EAAK,mBAAmB,GAEzE,EAAOA,KAAQC;CAChB;CACA,IAAM6E,IAAe,GAAGC,EAAgB3E,EAAY,OAAO,KAAK,UAAUgC,CAAM,CAAC,CAAC,EAAE,GAAG2C,EAAgBH,EAAM,OAAO,KAC9G,EAAE,iBAAc,MAAMI,EAASJ,EAAM,YAAYxE,EAAY,OAAO0E,CAAY,CAAC;CACvF,OAAO,GAAGA,EAAa,GAAGC,EAAgBzC,CAAS;AACpD"}
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,aAAYA,IAChE,OAAOC,EAAY,mBAAmB,0BAA0B;CAEjE,IAAMC,IAAuE,EAC5E,GAAGJ,EACJ;CACA,KAAK,IAAMK,KAAQJ,GAAa;EAC/B,IAAMK,IAAQJ,IAAYG;EAC1B,IAAIC,MAAU,KAAA,GAAW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,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,3 +1,10 @@
1
+ /**
2
+ * JWT (RFC 7519) validation on top of compact JWS. Signature verification and the claims policy
3
+ * are separate steps with separate types: {@linkcode decodeJwtUnverified} yields an
4
+ * {@linkcode UnverifiedJwt}, and only {@linkcode verifyJwt} yields a {@linkcode VerifiedJwt}.
5
+ *
6
+ * @module
7
+ */
1
8
  import { JsonObject } from "../internal/jose/strict-json.js";
2
9
  import { JoseResult, JwsParseErrorCode, VerifyJwtErrorCode } from "./errors.js";
3
10
  import { JoseLimits, JwsAlgorithm, JwsHeader, SignJwsInput, Unchecked, VerifyJwsOptions } from "./jws.js";
@@ -87,5 +94,4 @@ export declare function verifyJwt(token: string, options: VerifyJwtOptions): Pro
87
94
  * Throws a `ResultError` coded `SignJoseErrorCode` for an unusable key, algorithm or header, and
88
95
  * `invalid_claims` when `claims` cannot be serialized.
89
96
  */
90
- export declare function signJwt(input: SignJwtInput): Promise<string>;
91
- //# sourceMappingURL=jwt.d.ts.map
97
+ export declare function signJwt(input: SignJwtInput): Promise<string>;
package/dist/jose/jwt.js CHANGED
@@ -1,100 +1,100 @@
1
- import { successResult as e, throwMicro509Error as t } from "../result/result.js";
2
- import { isJsonArray as n } from "../internal/jose/strict-json.js";
3
- import { joseFailure as r } from "./errors.js";
4
- import { decodeJsonObject as i, isUncheckedPolicy as a, mediaTypeKey as o, parseCompactJws as s, prepareVerify as c, resolveJoseLimits as l, signCompactJws as u, verifyPrepared as d } from "./jws.js";
1
+ import { isJsonArray as e } from "../internal/jose/strict-json.js";
2
+ import { joseFailure as t } from "./errors.js";
3
+ import { decodeJsonObject as n, isUncheckedPolicy as r, mediaTypeKey as i, parseCompactJws as a, prepareVerify as o, resolveJoseLimits as s, signCompactJws as c, verifyPrepared as l } from "./jws.js";
4
+ import { successResult as u, throwMicro509Error as d } from "../result/result.js";
5
5
  // src/jose/jwt.ts
6
6
  /** Largest clock tolerance {@linkcode JwtClaimsPolicy.clockToleranceSeconds} accepts. */
7
7
  const f = 600;
8
- function decodeClaims(e, t, n) {
9
- return e.cty !== void 0 && o(e.cty) === "application/jwt" ? r("unsupported_nested_jwt", "Nested JWTs (cty \"JWT\") are not supported") : i(t, n, "payload", "invalid_payload");
8
+ function decodeClaims(e, r, a) {
9
+ return e.cty !== void 0 && i(e.cty) === "application/jwt" ? t("unsupported_nested_jwt", "Nested JWTs (cty \"JWT\") are not supported") : n(r, a, "payload", "invalid_payload");
10
10
  }
11
11
  /** Decodes a JWT without checking its signature. Every field of the result is unauthenticated. */
12
- function decodeJwtUnverified(t, n) {
13
- let r = l(n);
12
+ function decodeJwtUnverified(e, t) {
13
+ let n = s(t);
14
+ if (!n.ok) return n;
15
+ let r = a(e, n.value);
14
16
  if (!r.ok) return r;
15
- let i = s(t, r.value);
16
- if (!i.ok) return i;
17
- let a = decodeClaims(i.value.header, i.value.payload, r.value);
18
- return a.ok ? e({
17
+ let i = decodeClaims(r.value.header, r.value.payload, n.value);
18
+ return i.ok ? u({
19
19
  verified: !1,
20
- header: i.value.header,
21
- claims: a.value
22
- }) : a;
20
+ header: r.value.header,
21
+ claims: i.value
22
+ }) : i;
23
23
  }
24
- function claimFailure(e, t, n) {
25
- return r(e, t, { claim: n });
24
+ function claimFailure(e, n, r) {
25
+ return t(e, n, { claim: r });
26
26
  }
27
- function numericDate(t, n) {
28
- if (!Object.hasOwn(t, n)) return e(void 0);
29
- let r = t[n];
30
- return typeof r != "number" || !Number.isFinite(r) ? claimFailure("invalid_claim", `Claim "${n}" is not a NumericDate`, n) : e(r);
27
+ function numericDate(e, t) {
28
+ if (!Object.hasOwn(e, t)) return u(void 0);
29
+ let n = e[t];
30
+ return typeof n != "number" || !Number.isFinite(n) ? claimFailure("invalid_claim", `Claim "${t}" is not a NumericDate`, t) : u(n);
31
31
  }
32
- function stringClaim(t, n) {
33
- if (!Object.hasOwn(t, n)) return e(void 0);
34
- let r = t[n];
35
- return typeof r == "string" ? e(r) : claimFailure("invalid_claim", `Claim "${n}" is not a string`, n);
32
+ function stringClaim(e, t) {
33
+ if (!Object.hasOwn(e, t)) return u(void 0);
34
+ let n = e[t];
35
+ return typeof n == "string" ? u(n) : claimFailure("invalid_claim", `Claim "${t}" is not a string`, t);
36
36
  }
37
37
  function audienceClaim(t) {
38
- if (!Object.hasOwn(t, "aud")) return e(void 0);
39
- let r = t.aud;
40
- if (typeof r == "string") return e(r);
41
- if (!n(r)) return claimFailure("invalid_claim", "Claim \"aud\" is neither a string nor an array", "aud");
42
- let i = [];
43
- for (let e of r) {
38
+ if (!Object.hasOwn(t, "aud")) return u(void 0);
39
+ let n = t.aud;
40
+ if (typeof n == "string") return u(n);
41
+ if (!e(n)) return claimFailure("invalid_claim", "Claim \"aud\" is neither a string nor an array", "aud");
42
+ let r = [];
43
+ for (let e of n) {
44
44
  if (typeof e != "string") return claimFailure("invalid_claim", "Claim \"aud\" holds a non-string", "aud");
45
- i.push(e);
45
+ r.push(e);
46
46
  }
47
- return e(i);
47
+ return u(r);
48
48
  }
49
- function registeredClaims(t) {
50
- let n = stringClaim(t, "iss");
49
+ function registeredClaims(e) {
50
+ let t = stringClaim(e, "iss");
51
+ if (!t.ok) return t;
52
+ let n = stringClaim(e, "sub");
51
53
  if (!n.ok) return n;
52
- let r = stringClaim(t, "sub");
54
+ let r = stringClaim(e, "jti");
53
55
  if (!r.ok) return r;
54
- let i = stringClaim(t, "jti");
56
+ let i = audienceClaim(e);
55
57
  if (!i.ok) return i;
56
- let a = audienceClaim(t);
58
+ let a = numericDate(e, "exp");
57
59
  if (!a.ok) return a;
58
- let o = numericDate(t, "exp");
60
+ let o = numericDate(e, "nbf");
59
61
  if (!o.ok) return o;
60
- let s = numericDate(t, "nbf");
61
- if (!s.ok) return s;
62
- let c = numericDate(t, "iat");
63
- return c.ok ? e({
64
- ...n.value === void 0 ? {} : { iss: n.value },
65
- ...r.value === void 0 ? {} : { sub: r.value },
66
- ...a.value === void 0 ? {} : { aud: a.value },
67
- ...o.value === void 0 ? {} : { exp: o.value },
68
- ...s.value === void 0 ? {} : { nbf: s.value },
69
- ...c.value === void 0 ? {} : { iat: c.value },
70
- ...i.value === void 0 ? {} : { jti: i.value }
71
- }) : c;
62
+ let s = numericDate(e, "iat");
63
+ return s.ok ? u({
64
+ ...t.value === void 0 ? {} : { iss: t.value },
65
+ ...n.value === void 0 ? {} : { sub: n.value },
66
+ ...i.value === void 0 ? {} : { aud: i.value },
67
+ ...a.value === void 0 ? {} : { exp: a.value },
68
+ ...o.value === void 0 ? {} : { nbf: o.value },
69
+ ...s.value === void 0 ? {} : { iat: s.value },
70
+ ...r.value === void 0 ? {} : { jti: r.value }
71
+ }) : s;
72
72
  }
73
- function expectedValues(t) {
74
- return typeof t == "string" ? e([t]) : a(t) ? e(void 0) : Array.isArray(t) && t.length > 0 && t.every((e) => typeof e == "string") ? e([...t]) : r("invalid_options", "issuer and audience need expected values or { unchecked: true }");
73
+ function expectedValues(e) {
74
+ return typeof e == "string" ? u([e]) : r(e) ? u(void 0) : Array.isArray(e) && e.length > 0 && e.every((e) => typeof e == "string") ? u([...e]) : t("invalid_options", "issuer and audience need expected values or { unchecked: true }");
75
75
  }
76
- function prepareClaims(t) {
77
- if (typeof t != "object" || !t) return r("invalid_options", "A claims policy is required");
78
- let n = t.clockToleranceSeconds ?? 0;
79
- if (typeof n != "number" || !Number.isFinite(n) || n < 0 || n > 600) return r("invalid_options", "clockToleranceSeconds must be between 0 and 600");
80
- let i = t.maxAgeSeconds;
81
- if (i !== void 0 && (typeof i != "number" || !Number.isFinite(i) || i < 0)) return r("invalid_options", "maxAgeSeconds must be a non-negative number");
82
- let a = t.requiredClaims ?? ["exp"];
83
- if (!Array.isArray(a) || !a.every((e) => typeof e == "string")) return r("invalid_options", "requiredClaims must be an array of strings");
84
- if (t.futureIssuedAt !== void 0 && t.futureIssuedAt !== "reject" && t.futureIssuedAt !== "allow") return r("invalid_options", "futureIssuedAt must be 'reject' or 'allow'");
85
- if (t.now !== void 0 && typeof t.now != "function") return r("invalid_options", "now must be a function");
86
- let o = expectedValues(t.issuer);
87
- if (!o.ok) return o;
88
- let s = expectedValues(t.audience);
89
- return s.ok ? e({
90
- issuers: o.value,
91
- audiences: s.value,
92
- required: [...a],
93
- now: t.now ?? (() => /* @__PURE__ */ new Date()),
76
+ function prepareClaims(e) {
77
+ if (typeof e != "object" || !e) return t("invalid_options", "A claims policy is required");
78
+ let n = e.clockToleranceSeconds ?? 0;
79
+ if (typeof n != "number" || !Number.isFinite(n) || n < 0 || n > 600) return t("invalid_options", "clockToleranceSeconds must be between 0 and 600");
80
+ let r = e.maxAgeSeconds;
81
+ if (r !== void 0 && (typeof r != "number" || !Number.isFinite(r) || r < 0)) return t("invalid_options", "maxAgeSeconds must be a non-negative number");
82
+ let i = e.requiredClaims ?? ["exp"];
83
+ if (!Array.isArray(i) || !i.every((e) => typeof e == "string")) return t("invalid_options", "requiredClaims must be an array of strings");
84
+ if (e.futureIssuedAt !== void 0 && e.futureIssuedAt !== "reject" && e.futureIssuedAt !== "allow") return t("invalid_options", "futureIssuedAt must be 'reject' or 'allow'");
85
+ if (e.now !== void 0 && typeof e.now != "function") return t("invalid_options", "now must be a function");
86
+ let a = expectedValues(e.issuer);
87
+ if (!a.ok) return a;
88
+ let o = expectedValues(e.audience);
89
+ return o.ok ? u({
90
+ issuers: a.value,
91
+ audiences: o.value,
92
+ required: [...i],
93
+ now: e.now ?? (() => /* @__PURE__ */ new Date()),
94
94
  toleranceSeconds: n,
95
- maxAgeSeconds: i,
96
- allowFutureIssuedAt: t.futureIssuedAt === "allow"
97
- }) : s;
95
+ maxAgeSeconds: r,
96
+ allowFutureIssuedAt: e.futureIssuedAt === "allow"
97
+ }) : o;
98
98
  }
99
99
  function checkIdentity(e, t) {
100
100
  let { issuers: n, audiences: r } = t;
@@ -111,14 +111,14 @@ function checkTimes(e, t, n) {
111
111
  if (n - o > t.maxAgeSeconds + r) return claimFailure("token_too_old", "The token is older than the maximum age", "iat");
112
112
  }
113
113
  }
114
- function clockSeconds(t) {
114
+ function clockSeconds(e) {
115
115
  let n;
116
116
  try {
117
- n = t.now();
117
+ n = e.now();
118
118
  } catch {
119
- return r("invalid_options", "The claims clock threw");
119
+ return t("invalid_options", "The claims clock threw");
120
120
  }
121
- return !(n instanceof Date) || !Number.isFinite(n.getTime()) ? r("invalid_options", "The claims clock did not return a valid Date") : e(n.getTime() / 1e3);
121
+ return !(n instanceof Date) || !Number.isFinite(n.getTime()) ? t("invalid_options", "The claims clock did not return a valid Date") : u(n.getTime() / 1e3);
122
122
  }
123
123
  function validateClaims(e, t) {
124
124
  for (let n of t.required) if (!Object.hasOwn(e, n)) return claimFailure("missing_claim", `Claim "${n}" is required`, n);
@@ -140,23 +140,23 @@ function validateClaims(e, t) {
140
140
  * `nbf`, each moved by `clockToleranceSeconds`. Time claims must be JSON numbers; strings are never
141
141
  * coerced. `exp` is required unless `requiredClaims` says otherwise.
142
142
  */
143
- async function verifyJwt(t, n) {
144
- if (typeof n != "object" || !n) return r("invalid_options", "Verification options are required");
145
- let i = prepareClaims(n.claims);
143
+ async function verifyJwt(e, n) {
144
+ if (typeof n != "object" || !n) return t("invalid_options", "Verification options are required");
145
+ let r = prepareClaims(n.claims);
146
+ if (!r.ok) return r;
147
+ let i = o(n);
146
148
  if (!i.ok) return i;
147
- let a = c(n);
149
+ let a = await l(e, i.value);
148
150
  if (!a.ok) return a;
149
- let o = await d(t, a.value);
150
- if (!o.ok) return o;
151
- let s = decodeClaims(o.value.header, o.value.payload, a.value.limits);
151
+ let s = decodeClaims(a.value.header, a.value.payload, i.value.limits);
152
152
  if (!s.ok) return s;
153
- let l = validateClaims(s.value, i.value);
154
- return l.ok ? e({
153
+ let c = validateClaims(s.value, r.value);
154
+ return c.ok ? u({
155
155
  verified: !0,
156
- header: o.value.header,
156
+ header: a.value.header,
157
157
  claims: s.value,
158
- registered: l.value
159
- }) : l;
158
+ registered: c.value
159
+ }) : c;
160
160
  }
161
161
  /**
162
162
  * Signs a JWT. The header carries `typ: "JWT"` unless `header.typ` says otherwise.
@@ -165,17 +165,17 @@ async function verifyJwt(t, n) {
165
165
  * `invalid_claims` when `claims` cannot be serialized.
166
166
  */
167
167
  async function signJwt(e) {
168
- let n;
168
+ let t;
169
169
  try {
170
- n = JSON.stringify(e.claims);
170
+ t = JSON.stringify(e.claims);
171
171
  } catch {
172
- n = void 0;
172
+ t = void 0;
173
173
  }
174
- if (typeof n != "string") return t("invalid_claims", "JWT claims are not JSON-serializable");
175
- let { claims: r, ...i } = e;
176
- return await u({
177
- ...i,
178
- payload: new TextEncoder().encode(n),
174
+ if (typeof t != "string") return d("invalid_claims", "JWT claims are not JSON-serializable");
175
+ let { claims: n, ...r } = e;
176
+ return await c({
177
+ ...r,
178
+ payload: new TextEncoder().encode(t),
179
179
  header: {
180
180
  typ: "JWT",
181
181
  ...e.header
@@ -91,5 +91,4 @@ export type RemoteJwksConfigErrorCode = "invalid_remote_jwks_config";
91
91
  * Redirect destinations, and the addresses a hostname resolves to, are limited by `redirects` and
92
92
  * the transport; this module cannot see DNS answers, and browsers hide redirect targets.
93
93
  */
94
- export declare function createRemoteJwksKeyResolver(config: RemoteJwksConfig): JwsKeyResolver;
95
- //# sourceMappingURL=remote-jwks.d.ts.map
94
+ export declare function createRemoteJwksKeyResolver(config: RemoteJwksConfig): JwsKeyResolver;