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
@@ -35,8 +35,21 @@ export interface RsaJwkEntry extends JwkEntryBase {
35
35
  /** Base64url public exponent. */
36
36
  readonly e: string;
37
37
  }
38
+ /** An EC public key entry, with its curve and uncompressed affine coordinates. */
39
+ export interface EcJwkEntry extends JwkEntryBase {
40
+ /** Discriminant. */
41
+ readonly kind: "ec";
42
+ /** The curve identifier, retained even when unsupported. */
43
+ readonly crv: string;
44
+ /** Base64url fixed-width affine x coordinate. */
45
+ readonly x: string;
46
+ /** Base64url fixed-width affine y coordinate. */
47
+ readonly y: string;
48
+ }
49
+ /** Public key entries whose type this module can select. */
50
+ export type SupportedJwkEntry = RsaJwkEntry | EcJwkEntry;
38
51
  /**
39
- * An entry this module never selects: a `kty` other than `RSA`, or an entry with missing or
52
+ * An entry this module never selects: a `kty` other than `RSA` or `EC`, or an entry with missing or
40
53
  * wrongly typed members (RFC 7517 §5). Kept so callers can inspect the whole set.
41
54
  */
42
55
  export interface UnsupportedJwkEntry extends JwkEntryBase {
@@ -46,7 +59,7 @@ export interface UnsupportedJwkEntry extends JwkEntryBase {
46
59
  readonly kty?: string;
47
60
  }
48
61
  /** One key of a JWK Set. */
49
- export type JwkEntry = RsaJwkEntry | UnsupportedJwkEntry;
62
+ export type JwkEntry = SupportedJwkEntry | UnsupportedJwkEntry;
50
63
  /** A parsed JWK Set. */
51
64
  export interface Jwks {
52
65
  /** The keys, in document order. */
@@ -60,11 +73,21 @@ export type ParseJwksErrorCode = "jwks_malformed" | "limit_exceeded" | "invalid_
60
73
  * Parses a JWK Set document.
61
74
  *
62
75
  * The document must be duplicate-free JSON with a `keys` array within `limits`. Keys with a `kty`
63
- * other than `RSA`, and keys with missing or wrongly typed members, are kept as `unsupported`
76
+ * other than `RSA` or `EC`, and keys with missing or wrongly typed members, are kept as `unsupported`
64
77
  * entries and never selected (RFC 7517 §5). A set that is not a duplicate-free object with a
65
78
  * `keys` array of objects is `jwks_malformed`.
66
79
  */
67
80
  export declare function parseJwks(input: string | Uint8Array, limits?: Partial<JwksLimits>): JoseResult<Jwks, ParseJwksErrorCode>;
81
+ /**
82
+ * Validates already parsed, plain JSON data and owns a detached deep snapshot of it.
83
+ *
84
+ * Prefer {@linkcode parseJwks} for untrusted transport text: an object cannot reveal lost duplicate
85
+ * member names or invalid original UTF-8. No getters or `toJSON` are called. Cycles, non-JSON values,
86
+ * sparse arrays, accessors, symbols and custom prototypes are refused. `maxBytes` bounds the UTF-8
87
+ * size of the compact JSON data spelling, not the original transport bytes. Depth and node limits
88
+ * match the text parser. A changed source object requires a new validation and resolver instance.
89
+ */
90
+ export declare function validateJwks(value: unknown, limits?: Partial<JwksLimits>): JoseResult<Jwks, ParseJwksErrorCode>;
68
91
  /** What {@linkcode selectJwk} matches against. */
69
92
  export interface JwkSelector {
70
93
  /** The algorithm the token uses. */
@@ -75,19 +98,24 @@ export interface JwkSelector {
75
98
  /**
76
99
  * Selects the one key of a set that can verify `selector`.
77
100
  *
78
- * Keys are filtered by `kid` (when the token has one), key type, `use`, `key_ops`, `alg` and RSA
101
+ * Keys are filtered by `kid` (when the token has one), key type, `use`, `key_ops`, `alg` and RSA/EC
79
102
  * parameters. No match is `key_not_found`, or `key_unsuitable` when `kid` matched only keys that
80
103
  * fail the other checks. More than one match is `ambiguous_key`: a token without `kid` therefore
81
104
  * resolves only against a set with a single usable key.
82
105
  */
83
- export declare function selectJwk(jwks: Jwks, selector: JwkSelector): JoseResult<RsaJwkEntry, Exclude<KeyResolutionErrorCode, "jwks_unavailable" | "aborted">>;
84
- /** Imports a selected entry as a verify-only RS256 `CryptoKey`. */
85
- export declare function importJwkEntry(entry: RsaJwkEntry): Promise<JoseResult<CryptoKey, "key_unsuitable">>;
106
+ export declare function selectJwk(jwks: Jwks, selector: JwkSelector): JoseResult<SupportedJwkEntry, Exclude<KeyResolutionErrorCode, "jwks_unavailable" | "aborted">>;
107
+ /**
108
+ * Imports a selected entry as a verify-only key for `algorithm`. The default remains RS256;
109
+ * pass the selected algorithm explicitly for every other RSA hash or ECDSA curve.
110
+ */
111
+ export declare function importJwkEntry(entry: SupportedJwkEntry, algorithm?: JwsAlgorithm): Promise<JoseResult<CryptoKey, "key_unsuitable">>;
86
112
  /**
87
113
  * Creates a key resolver over a fixed JWK Set.
88
114
  *
89
115
  * The resolver selects with {@linkcode selectJwk} and imports each key once, so repeated
90
- * verifications reuse the same `CryptoKey`.
116
+ * verifications reuse the same `CryptoKey`. Keep one resolver per trusted source/snapshot and
117
+ * replace it when that snapshot changes so removed keys do not survive rotation.
118
+ *
119
+ * @see https://micro509.kjanat.dev/guide/jose-cache for application-owned raw JWKS caches.
91
120
  */
92
- export declare function createJwksKeyResolver(jwks: Jwks): JwsKeyResolver;
93
- //# sourceMappingURL=jwks.d.ts.map
121
+ export declare function createJwksKeyResolver(jwks: Jwks): JwsKeyResolver;
package/dist/jose/jwks.js CHANGED
@@ -1,9 +1,11 @@
1
- import { successResult as e } from "../result/result.js";
2
- import { importPublicJwk as t } from "../keys/keys.js";
3
- import { base64UrlDecode as n } from "../internal/jose/base64url.js";
1
+ import { isPrimeEcPoint as e } from "../internal/crypto/prime-ec.js";
2
+ import { base64UrlDecode as t } from "../internal/jose/base64url.js";
3
+ import { snapshotJsonData as n } from "../internal/jose/json-data.js";
4
4
  import { isJsonArray as r, isJsonObject as i, parseStrictJson as a } from "../internal/jose/strict-json.js";
5
5
  import { joseFailure as o } from "./errors.js";
6
- import { checkRs256VerificationKey as s, validRsaPublicExponent as c } from "./jws.js";
6
+ import { JWS_ALGORITHMS as s, checkJwsVerificationKey as c, jwsAlgorithmProfile as l, validRsaPublicExponent as u } from "./jws.js";
7
+ import { importPublicJwk as d } from "../keys/keys.js";
8
+ import { successResult as f } from "../result/result.js";
7
9
  // src/jose/jwks.ts
8
10
  /**
9
11
  * JSON Web Key Set (RFC 7517) parsing, key selection and a local key resolver. Nothing here
@@ -12,7 +14,7 @@ import { checkRs256VerificationKey as s, validRsaPublicExponent as c } from "./j
12
14
  * @module
13
15
  */
14
16
  /** The limits applied when a caller supplies none. */
15
- const l = {
17
+ const p = {
16
18
  maxBytes: 65536,
17
19
  maxKeys: 32
18
20
  };
@@ -35,38 +37,45 @@ function memberStrings(e, t) {
35
37
  }
36
38
  return i;
37
39
  }
38
- function parseEntry(t) {
39
- if (!i(t)) return malformed("JWK Set key is not an object");
40
- let n = memberString(t, "kty"), r = memberString(t, "kid"), a = memberString(t, "use"), o = memberString(t, "alg"), s = memberStrings(t, "key_ops");
41
- if (typeof n != "string" || r === null || a === null || o === null || s === null) return e({
40
+ function parseEntry(e) {
41
+ if (!i(e)) return malformed("JWK Set key is not an object");
42
+ let t = memberString(e, "kty"), n = memberString(e, "kid"), r = memberString(e, "use"), a = memberString(e, "alg"), o = memberStrings(e, "key_ops");
43
+ if (typeof t != "string" || n === null || r === null || a === null || o === null) return f({
42
44
  kind: "unsupported",
43
- ...typeof n == "string" ? { kty: n } : {},
44
- members: t
45
+ ...typeof t == "string" ? { kty: t } : {},
46
+ members: e
45
47
  });
46
- let c = {
47
- ...r === void 0 ? {} : { kid: r },
48
- ...a === void 0 ? {} : { use: a },
49
- ...o === void 0 ? {} : { alg: o },
50
- ...s === void 0 ? {} : { keyOps: s }
51
- }, l = t.n, u = t.e;
52
- return e(n !== "RSA" || typeof l != "string" || typeof u != "string" ? {
53
- kind: "unsupported",
54
- kty: n,
55
- ...c,
56
- members: t
57
- } : {
48
+ let s = {
49
+ ...n === void 0 ? {} : { kid: n },
50
+ ...r === void 0 ? {} : { use: r },
51
+ ...a === void 0 ? {} : { alg: a },
52
+ ...o === void 0 ? {} : { keyOps: o }
53
+ };
54
+ return t === "RSA" && typeof e.n == "string" && typeof e.e == "string" ? f({
58
55
  kind: "rsa",
59
- n: l,
60
- e: u,
61
- ...c,
62
- members: t
56
+ n: e.n,
57
+ e: e.e,
58
+ ...s,
59
+ members: e
60
+ }) : t === "EC" && typeof e.crv == "string" && typeof e.x == "string" && typeof e.y == "string" ? f({
61
+ kind: "ec",
62
+ crv: e.crv,
63
+ x: e.x,
64
+ y: e.y,
65
+ ...s,
66
+ members: e
67
+ }) : f({
68
+ kind: "unsupported",
69
+ kty: t,
70
+ ...s,
71
+ members: e
63
72
  });
64
73
  }
65
74
  /**
66
75
  * Parses a JWK Set document.
67
76
  *
68
77
  * The document must be duplicate-free JSON with a `keys` array within `limits`. Keys with a `kty`
69
- * other than `RSA`, and keys with missing or wrongly typed members, are kept as `unsupported`
78
+ * other than `RSA` or `EC`, and keys with missing or wrongly typed members, are kept as `unsupported`
70
79
  * entries and never selected (RFC 7517 §5). A set that is not a duplicate-free object with a
71
80
  * `keys` array of objects is `jwks_malformed`.
72
81
  */
@@ -74,105 +83,156 @@ function parseJwks(e, t) {
74
83
  let n = resolveJwksLimits(t);
75
84
  return n.ok ? parseWithLimits(e, n.value) : n;
76
85
  }
77
- const u = 16777216, d = 1024;
78
- function resolveJwksLimits(t) {
79
- if (t !== void 0 && (typeof t != "object" || !t)) return o("invalid_options", "limits must be an object");
80
- let n = t?.maxBytes === void 0 ? l.maxBytes : t.maxBytes, r = t?.maxKeys === void 0 ? l.maxKeys : t.maxKeys;
81
- return !Number.isSafeInteger(n) || n < 1 || n > u ? o("invalid_options", `limits.maxBytes must be from 1 to ${u}`) : !Number.isSafeInteger(r) || r < 1 || r > d ? o("invalid_options", `limits.maxKeys must be from 1 to ${d}`) : e({
82
- maxBytes: n,
83
- maxKeys: r
86
+ /**
87
+ * Validates already parsed, plain JSON data and owns a detached deep snapshot of it.
88
+ *
89
+ * Prefer {@linkcode parseJwks} for untrusted transport text: an object cannot reveal lost duplicate
90
+ * member names or invalid original UTF-8. No getters or `toJSON` are called. Cycles, non-JSON values,
91
+ * sparse arrays, accessors, symbols and custom prototypes are refused. `maxBytes` bounds the UTF-8
92
+ * size of the compact JSON data spelling, not the original transport bytes. Depth and node limits
93
+ * match the text parser. A changed source object requires a new validation and resolver instance.
94
+ */
95
+ function validateJwks(e, t) {
96
+ let r = resolveJwksLimits(t);
97
+ if (!r.ok) return r;
98
+ let i = n(e, {
99
+ maxBytes: r.value.maxBytes,
100
+ maxDepth: 8,
101
+ maxNodes: r.value.maxKeys * 64 + 64
102
+ });
103
+ return i.ok ? validateDocument(i.value, r.value) : i.code === "limit_exceeded" ? o("limit_exceeded", "JWK Set exceeds its JSON data bounds") : malformed("JWK Set is not plain JSON data");
104
+ }
105
+ const m = 16777216, h = 1024;
106
+ function resolveJwksLimits(e) {
107
+ if (e !== void 0 && (typeof e != "object" || !e)) return o("invalid_options", "limits must be an object");
108
+ let t = e?.maxBytes === void 0 ? p.maxBytes : e.maxBytes, n = e?.maxKeys === void 0 ? p.maxKeys : e.maxKeys;
109
+ return !Number.isSafeInteger(t) || t < 1 || t > m ? o("invalid_options", `limits.maxBytes must be from 1 to ${m}`) : !Number.isSafeInteger(n) || n < 1 || n > h ? o("invalid_options", `limits.maxKeys must be from 1 to ${h}`) : f({
110
+ maxBytes: t,
111
+ maxKeys: n
84
112
  });
85
113
  }
86
- function parseWithLimits(t, n) {
87
- if (typeof t == "string" && t.length > n.maxBytes) return o("limit_exceeded", `JWK Set exceeds ${n.maxBytes} bytes`);
88
- if (typeof t != "string" && !(t instanceof Uint8Array)) return malformed("JWK Set input is neither a string nor bytes");
89
- let s = typeof t == "string" ? new TextEncoder().encode(t) : t;
90
- if (s.byteLength > n.maxBytes) return o("limit_exceeded", `JWK Set exceeds ${n.maxBytes} bytes`);
91
- let c;
114
+ function parseWithLimits(e, t) {
115
+ if (typeof e == "string" && e.length > t.maxBytes) return o("limit_exceeded", `JWK Set exceeds ${t.maxBytes} bytes`);
116
+ if (typeof e != "string" && !(e instanceof Uint8Array)) return malformed("JWK Set input is neither a string nor bytes");
117
+ let n = typeof e == "string" ? new TextEncoder().encode(e) : e;
118
+ if (n.byteLength > t.maxBytes) return o("limit_exceeded", `JWK Set exceeds ${t.maxBytes} bytes`);
119
+ let r;
92
120
  try {
93
- c = new TextDecoder("utf-8", {
121
+ r = new TextDecoder("utf-8", {
94
122
  fatal: !0,
95
123
  ignoreBOM: !0
96
- }).decode(s);
124
+ }).decode(n);
97
125
  } catch {
98
126
  return malformed("JWK Set is not valid UTF-8");
99
127
  }
100
- let l = a(c, {
128
+ let i = a(r, {
101
129
  maxDepth: 8,
102
- maxNodes: n.maxKeys * 64 + 64
130
+ maxNodes: t.maxKeys * 64 + 64
103
131
  });
104
- if (!l.ok) return l.code === "limit_exceeded" ? o("limit_exceeded", `JWK Set: ${l.message}`) : malformed(`JWK Set: ${l.message}`);
105
- let u = l.value;
106
- if (!i(u)) return malformed("JWK Set is not an object");
107
- let d = u.keys;
108
- if (!r(d)) return malformed("JWK Set \"keys\" is not an array");
109
- if (d.length > n.maxKeys) return o("limit_exceeded", `JWK Set holds more than ${n.maxKeys} keys`);
110
- let f = [];
111
- for (let e of d) {
132
+ return i.ok ? validateDocument(i.value, t) : i.code === "limit_exceeded" ? o("limit_exceeded", `JWK Set: ${i.message}`) : malformed(`JWK Set: ${i.message}`);
133
+ }
134
+ function validateDocument(e, t) {
135
+ if (!i(e)) return malformed("JWK Set is not an object");
136
+ let n = e.keys;
137
+ if (!r(n)) return malformed("JWK Set \"keys\" is not an array");
138
+ if (n.length > t.maxKeys) return o("limit_exceeded", `JWK Set holds more than ${t.maxKeys} keys`);
139
+ let a = [];
140
+ for (let e of n) {
112
141
  let t = parseEntry(e);
113
142
  if (!t.ok) return t;
114
- f.push(t.value);
143
+ a.push(t.value);
115
144
  }
116
- return e({
117
- keys: f,
118
- members: u
145
+ return f({
146
+ keys: a,
147
+ members: e
119
148
  });
120
149
  }
121
150
  /** Why a key entry cannot verify a given algorithm, or `undefined` when it can. */
122
- function unsuitableReason(e, t) {
123
- if (e.kind !== "rsa") return "key type does not match the algorithm";
124
- if (e.use !== void 0 && e.use !== "sig") return "\"use\" is not \"sig\"";
125
- if (e.keyOps !== void 0 && !e.keyOps.includes("verify")) return "\"key_ops\" does not include \"verify\"";
126
- if (e.use === "sig" && e.keyOps?.some((e) => e !== "sign" && e !== "verify")) return "\"use\" and \"key_ops\" are inconsistent";
127
- if (e.alg !== void 0 && e.alg !== t) return "\"alg\" names another algorithm";
128
- let r = n(e.n), i = n(e.e);
129
- if (r === void 0 || i === void 0 || r.length === 0) return "RSA parameters are not canonical base64url";
130
- if (r[0] === 0 || i[0] === 0 || i.length === 0) return "RSA parameters have leading zero octets";
131
- if (r.length > 1024) return "RSA modulus is too large";
132
- if ((r.length - 1) * 8 + 32 - Math.clz32(r[0] ?? 0) < 2048) return "RSA modulus is too small";
133
- if (!c(i, r)) return "RSA public exponent is invalid";
151
+ function unsuitableReason(n, r) {
152
+ if (!s.includes(r)) return "unsupported algorithm";
153
+ let i = l(r);
154
+ if (n.kind !== i.kind) return "key type does not match the algorithm";
155
+ if (n.use !== void 0 && n.use !== "sig") return "\"use\" is not \"sig\"";
156
+ if (n.keyOps !== void 0 && !n.keyOps.includes("verify")) return "\"key_ops\" does not include \"verify\"";
157
+ if (n.use === "sig" && n.keyOps?.some((e) => e !== "sign" && e !== "verify")) return "\"use\" and \"key_ops\" are inconsistent";
158
+ if (n.alg !== void 0 && n.alg !== r) return "\"alg\" names another algorithm";
159
+ if (n.kind === "ec" && i.kind === "ec") {
160
+ if (n.crv !== i.curve) return "EC curve does not match the algorithm";
161
+ let r = t(n.x), a = t(n.y);
162
+ return r?.length !== i.coordinateBytes || a?.length !== i.coordinateBytes ? "EC coordinates must be canonical base64url of the required fixed width" : e(i.curve, r, a) ? void 0 : "EC point is not on the curve";
163
+ }
164
+ return n.kind === "rsa" ? unsuitableRsaParameters(n) : "key type does not match the algorithm";
165
+ }
166
+ function unsuitableRsaParameters(e) {
167
+ let n = t(e.n), r = t(e.e);
168
+ if (n === void 0 || r === void 0 || n.length === 0) return "RSA parameters are not canonical base64url";
169
+ if (n[0] === 0 || r[0] === 0 || r.length === 0) return "RSA parameters have leading zero octets";
170
+ if (n.length > 1024) return "RSA modulus is too large";
171
+ if ((n.length - 1) * 8 + 32 - Math.clz32(n[0] ?? 0) < 2048) return "RSA modulus is too small";
172
+ if (!u(r, n)) return "RSA public exponent is invalid";
134
173
  }
135
174
  /**
136
175
  * Selects the one key of a set that can verify `selector`.
137
176
  *
138
- * Keys are filtered by `kid` (when the token has one), key type, `use`, `key_ops`, `alg` and RSA
177
+ * Keys are filtered by `kid` (when the token has one), key type, `use`, `key_ops`, `alg` and RSA/EC
139
178
  * parameters. No match is `key_not_found`, or `key_unsuitable` when `kid` matched only keys that
140
179
  * fail the other checks. More than one match is `ambiguous_key`: a token without `kid` therefore
141
180
  * resolves only against a set with a single usable key.
142
181
  */
143
- function selectJwk(t, n) {
144
- let r = t.keys.filter((e) => n.kid === void 0 || e.kid === n.kid), i = n.kid === void 0 ? {} : { kid: n.kid };
145
- if (r.length === 0) return o("key_not_found", "No key matches the token", i);
146
- let a = [];
147
- for (let e of r) e.kind === "rsa" && unsuitableReason(e, n.algorithm) === void 0 && a.push(e);
148
- let [s, c] = a;
149
- return s === void 0 ? o("key_unsuitable", "No matching key can verify this algorithm", i) : c === void 0 ? e(s) : o("ambiguous_key", "More than one key matches the token", i);
182
+ function selectJwk(e, t) {
183
+ let n = e.keys.filter((e) => t.kid === void 0 || e.kid === t.kid), r = t.kid === void 0 ? {} : { kid: t.kid };
184
+ if (n.length === 0) return o("key_not_found", "No key matches the token", r);
185
+ let i = [];
186
+ for (let e of n) e.kind !== "unsupported" && unsuitableReason(e, t.algorithm) === void 0 && i.push(e);
187
+ let [a, s] = i;
188
+ return a === void 0 ? o("key_unsuitable", "No matching key can verify this algorithm", r) : s === void 0 ? f(a) : o("ambiguous_key", "More than one key matches the token", r);
150
189
  }
151
- /** Imports a selected entry as a verify-only RS256 `CryptoKey`. */
152
- async function importJwkEntry(n) {
153
- let r = unsuitableReason(n, "RS256");
154
- if (r !== void 0) return o("key_unsuitable", r, n.kid === void 0 ? void 0 : { kid: n.kid });
155
- let i = await t({
190
+ /**
191
+ * Imports a selected entry as a verify-only key for `algorithm`. The default remains RS256;
192
+ * pass the selected algorithm explicitly for every other RSA hash or ECDSA curve.
193
+ */
194
+ async function importJwkEntry(e, t = "RS256") {
195
+ let n = unsuitableReason(e, t);
196
+ if (n !== void 0) return o("key_unsuitable", n, e.kid === void 0 ? void 0 : { kid: e.kid });
197
+ let r = l(t), i = e.kind === "rsa" ? {
156
198
  kty: "RSA",
157
- n: n.n,
158
- e: n.e,
159
- alg: "RS256",
199
+ n: e.n,
200
+ e: e.e,
201
+ alg: t,
160
202
  key_ops: ["verify"],
161
203
  ext: !0
162
- }, {
204
+ } : {
205
+ kty: "EC",
206
+ crv: e.crv,
207
+ x: e.x,
208
+ y: e.y,
209
+ alg: t,
210
+ key_ops: ["verify"],
211
+ ext: !0
212
+ }, a = await d(i, r.kind === "rsa" ? {
163
213
  kind: "rsa",
164
214
  scheme: "pkcs1-v1_5",
165
- hash: "SHA-256"
215
+ hash: r.hash
216
+ } : {
217
+ kind: "ecdsa",
218
+ curve: r.curve
166
219
  });
167
- if (!i.ok) return o("key_unsuitable", "The RSA JWK cannot be imported", { ...n.kid === void 0 ? {} : { kid: n.kid } });
168
- let a = s(i.value);
169
- return a.ok ? e(i.value) : a;
220
+ if (!a.ok) return o("key_unsuitable", "The JWK cannot be imported", { ...e.kid === void 0 ? {} : { kid: e.kid } });
221
+ let s = c(a.value, t);
222
+ return s.ok ? f(a.value) : s;
223
+ }
224
+ /** Cache identity includes the admitted algorithm, which binds the RSA import hash. */
225
+ function jwkEntryCacheKey(e, t) {
226
+ return e.kind === "rsa" ? `${t}.rsa.${e.n}.${e.e}` : `${t}.ec.${e.crv}.${e.x}.${e.y}`;
170
227
  }
171
228
  /**
172
229
  * Creates a key resolver over a fixed JWK Set.
173
230
  *
174
231
  * The resolver selects with {@linkcode selectJwk} and imports each key once, so repeated
175
- * verifications reuse the same `CryptoKey`.
232
+ * verifications reuse the same `CryptoKey`. Keep one resolver per trusted source/snapshot and
233
+ * replace it when that snapshot changes so removed keys do not survive rotation.
234
+ *
235
+ * @see https://micro509.kjanat.dev/guide/jose-cache for application-owned raw JWKS caches.
176
236
  */
177
237
  function createJwksKeyResolver(e) {
178
238
  let t = /* @__PURE__ */ new Map();
@@ -182,12 +242,12 @@ function createJwksKeyResolver(e) {
182
242
  ...n.kid === void 0 ? {} : { kid: n.kid }
183
243
  });
184
244
  if (!r.ok) return r;
185
- let i = t.get(r.value);
186
- if (i !== void 0) return await i;
187
- let a = importJwkEntry(r.value);
188
- return t.set(r.value, a), await a;
245
+ let i = jwkEntryCacheKey(r.value, n.algorithm), a = t.get(i);
246
+ if (a !== void 0) return await a;
247
+ let o = importJwkEntry(r.value, n.algorithm);
248
+ return t.set(i, o), await o;
189
249
  };
190
250
  }
191
- export { l as DEFAULT_JWKS_LIMITS, createJwksKeyResolver, importJwkEntry, parseJwks, selectJwk };
251
+ export { p as DEFAULT_JWKS_LIMITS, createJwksKeyResolver, importJwkEntry, jwkEntryCacheKey, parseJwks, selectJwk, validateJwks };
192
252
 
193
253
  //# sourceMappingURL=jwks.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"jwks.js","names":["DEFAULT_JWKS_LIMITS","joseFailure","message","object","name","value","isJsonArray","items","item","isJsonObject","kty","kid","use","alg","ops","successResult","metadata","n","e","bounds","limits","input","MAX_JWKS_BYTES_LIMIT","MAX_JWKS_KEYS_LIMIT","overrides","maxBytes","maxKeys","bytes","text","parsed","parseStrictJson","document","keys","entries","key","entry","op","algorithm","modulus","base64UrlDecode","exponent","validRsaPublicExponent","named","jwks","selector","details","usable","only","second","reason","imported","importPublicJwk","suitable","checkRs256VerificationKey","selected","request","cached","pending"],"sources":["../../src/jose/jwks.ts"],"sourcesContent":["/**\n * JSON Web Key Set (RFC 7517) parsing, key selection and a local key resolver. Nothing here\n * performs network access.\n *\n * @module\n */\n\nimport { base64UrlDecode } 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 { JoseErrorResult, JoseResult, KeyResolutionErrorCode } from '#micro509/jose/errors';\nimport { joseFailure } from '#micro509/jose/errors';\nimport type { JwsAlgorithm, JwsKeyResolver } from '#micro509/jose/jws';\nimport {\n\tcheckRs256VerificationKey,\n\tMIN_RS256_MODULUS_BITS,\n\tvalidRsaPublicExponent,\n} from '#micro509/jose/jws';\nimport { importPublicJwk } from '#micro509/keys/keys';\nimport { successResult } from '#micro509/result/result';\n\n/** Bounds applied while parsing a JWK Set. */\nexport interface JwksLimits {\n\t/** Maximum JWK Set size in bytes. Default `65536`. */\n\treadonly maxBytes: number;\n\t/** Maximum number of keys in the set. Default `32`. */\n\treadonly maxKeys: number;\n}\n\n/** The limits applied when a caller supplies none. */\nexport const DEFAULT_JWKS_LIMITS: JwksLimits = { maxBytes: 65_536, maxKeys: 32 };\n\nconst MAX_RSA_MODULUS_BYTES = 1024;\nconst MAX_JWKS_JSON_DEPTH = 8;\n\n/** Members every JWK entry carries beside its key material. */\nexport interface JwkMetadata {\n\t/** Key identifier. */\n\treadonly kid?: string;\n\t/** Intended use: `sig` or `enc`, or another value kept verbatim. */\n\treadonly use?: string;\n\t/** Permitted operations, verbatim. */\n\treadonly keyOps?: readonly string[];\n\t/** The algorithm the key is restricted to. */\n\treadonly alg?: string;\n}\n\n/** Members shared by every parsed entry. */\nexport interface JwkEntryBase extends JwkMetadata {\n\t/** Every member the entry carried, as parsed, including key material this module does not read. */\n\treadonly members: JsonObject;\n}\n\n/** An RSA public key entry. */\nexport interface RsaJwkEntry extends JwkEntryBase {\n\t/** Discriminant. */\n\treadonly kind: 'rsa';\n\t/** Base64url modulus. */\n\treadonly n: string;\n\t/** Base64url public exponent. */\n\treadonly e: string;\n}\n\n/**\n * An entry this module never selects: a `kty` other than `RSA`, or an entry with missing or\n * wrongly typed members (RFC 7517 §5). Kept so callers can inspect the whole set.\n */\nexport interface UnsupportedJwkEntry extends JwkEntryBase {\n\t/** Discriminant. */\n\treadonly kind: 'unsupported';\n\t/** The `kty` the entry carried, when it was a string. */\n\treadonly kty?: string;\n}\n\n/** One key of a JWK Set. */\nexport type JwkEntry = RsaJwkEntry | UnsupportedJwkEntry;\n\n/** A parsed JWK Set. */\nexport interface Jwks {\n\t/** The keys, in document order. */\n\treadonly keys: readonly JwkEntry[];\n\t/** Every top-level member of the document, as parsed. */\n\treadonly members: JsonObject;\n}\n\n/** Codes {@linkcode parseJwks} returns. */\nexport type ParseJwksErrorCode = 'jwks_malformed' | 'limit_exceeded' | 'invalid_options';\n\nfunction malformed(message: string): JoseErrorResult<'jwks_malformed'> {\n\treturn joseFailure('jwks_malformed', message);\n}\n\nfunction memberString(object: JsonObject, name: string): string | undefined | null {\n\tif (!Object.hasOwn(object, name)) return undefined;\n\tconst value = object[name];\n\treturn typeof value === 'string' ? value : null;\n}\n\nfunction memberStrings(object: JsonObject, name: string): readonly string[] | undefined | null {\n\tif (!Object.hasOwn(object, name)) return undefined;\n\tconst value: JsonValue | undefined = object[name];\n\tif (!isJsonArray(value)) return null;\n\tconst items: string[] = [];\n\tfor (const item of value) {\n\t\tif (typeof item !== 'string' || items.includes(item)) return null;\n\t\titems.push(item);\n\t}\n\treturn items;\n}\n\nfunction parseEntry(value: JsonValue): JoseResult<JwkEntry, 'jwks_malformed'> {\n\tif (!isJsonObject(value)) {\n\t\treturn malformed('JWK Set key is not an object');\n\t}\n\tconst kty = memberString(value, 'kty');\n\tconst kid = memberString(value, 'kid');\n\tconst use = memberString(value, 'use');\n\tconst alg = memberString(value, 'alg');\n\tconst ops = memberStrings(value, 'key_ops');\n\tif (typeof kty !== 'string' || kid === null || use === null || alg === null || ops === null) {\n\t\treturn successResult({\n\t\t\tkind: 'unsupported',\n\t\t\t...(typeof kty === 'string' ? { kty } : {}),\n\t\t\tmembers: value,\n\t\t});\n\t}\n\tconst metadata: JwkMetadata = {\n\t\t...(kid === undefined ? {} : { kid }),\n\t\t...(use === undefined ? {} : { use }),\n\t\t...(alg === undefined ? {} : { alg }),\n\t\t...(ops === undefined ? {} : { keyOps: ops }),\n\t};\n\tconst n = value.n;\n\tconst e = value.e;\n\tif (kty !== 'RSA' || typeof n !== 'string' || typeof e !== 'string') {\n\t\treturn successResult({ kind: 'unsupported', kty, ...metadata, members: value });\n\t}\n\treturn successResult({ kind: 'rsa', n, e, ...metadata, members: value });\n}\n\n/**\n * Parses a JWK Set document.\n *\n * The document must be duplicate-free JSON with a `keys` array within `limits`. Keys with a `kty`\n * other than `RSA`, and keys with missing or wrongly typed members, are kept as `unsupported`\n * entries and never selected (RFC 7517 §5). A set that is not a duplicate-free object with a\n * `keys` array of objects is `jwks_malformed`.\n */\nexport function parseJwks(\n\tinput: string | Uint8Array,\n\tlimits?: Partial<JwksLimits>,\n): JoseResult<Jwks, ParseJwksErrorCode> {\n\tconst bounds = resolveJwksLimits(limits);\n\tif (!bounds.ok) return bounds;\n\treturn parseWithLimits(input, bounds.value);\n}\n\nconst MAX_JWKS_BYTES_LIMIT = 16_777_216;\nconst MAX_JWKS_KEYS_LIMIT = 1024;\n\nfunction resolveJwksLimits(\n\toverrides: Partial<JwksLimits> | undefined,\n): JoseResult<JwksLimits, '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 maxBytes =\n\t\toverrides?.maxBytes === undefined ? DEFAULT_JWKS_LIMITS.maxBytes : overrides.maxBytes;\n\tconst maxKeys =\n\t\toverrides?.maxKeys === undefined ? DEFAULT_JWKS_LIMITS.maxKeys : overrides.maxKeys;\n\tif (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_JWKS_BYTES_LIMIT) {\n\t\treturn joseFailure(\n\t\t\t'invalid_options',\n\t\t\t`limits.maxBytes must be from 1 to ${MAX_JWKS_BYTES_LIMIT}`,\n\t\t);\n\t}\n\tif (!Number.isSafeInteger(maxKeys) || maxKeys < 1 || maxKeys > MAX_JWKS_KEYS_LIMIT) {\n\t\treturn joseFailure(\n\t\t\t'invalid_options',\n\t\t\t`limits.maxKeys must be from 1 to ${MAX_JWKS_KEYS_LIMIT}`,\n\t\t);\n\t}\n\treturn successResult({ maxBytes, maxKeys });\n}\n\nfunction parseWithLimits(\n\tinput: string | Uint8Array,\n\tbounds: JwksLimits,\n): JoseResult<Jwks, 'jwks_malformed' | 'limit_exceeded'> {\n\tif (typeof input === 'string' && input.length > bounds.maxBytes) {\n\t\treturn joseFailure('limit_exceeded', `JWK Set exceeds ${bounds.maxBytes} bytes`);\n\t}\n\tif (typeof input !== 'string' && !(input instanceof Uint8Array)) {\n\t\treturn malformed('JWK Set input is neither a string nor bytes');\n\t}\n\tconst bytes = typeof input === 'string' ? new TextEncoder().encode(input) : input;\n\tif (bytes.byteLength > bounds.maxBytes) {\n\t\treturn joseFailure('limit_exceeded', `JWK Set exceeds ${bounds.maxBytes} bytes`);\n\t}\n\tlet text: string;\n\ttry {\n\t\ttext = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);\n\t} catch {\n\t\treturn malformed('JWK Set is not valid UTF-8');\n\t}\n\tconst parsed = parseStrictJson(text, {\n\t\tmaxDepth: MAX_JWKS_JSON_DEPTH,\n\t\tmaxNodes: bounds.maxKeys * 64 + 64,\n\t});\n\tif (!parsed.ok) {\n\t\treturn parsed.code === 'limit_exceeded'\n\t\t\t? joseFailure('limit_exceeded', `JWK Set: ${parsed.message}`)\n\t\t\t: malformed(`JWK Set: ${parsed.message}`);\n\t}\n\tconst document = parsed.value;\n\tif (!isJsonObject(document)) {\n\t\treturn malformed('JWK Set is not an object');\n\t}\n\tconst keys = document.keys;\n\tif (!isJsonArray(keys)) return malformed('JWK Set \"keys\" is not an array');\n\tif (keys.length > bounds.maxKeys) {\n\t\treturn joseFailure('limit_exceeded', `JWK Set holds more than ${bounds.maxKeys} keys`);\n\t}\n\tconst entries: JwkEntry[] = [];\n\tfor (const key of keys) {\n\t\tconst entry = parseEntry(key);\n\t\tif (!entry.ok) return entry;\n\t\tentries.push(entry.value);\n\t}\n\treturn successResult({ keys: entries, members: document });\n}\n\n/** Why a key entry cannot verify a given algorithm, or `undefined` when it can. */\nfunction unsuitableReason(entry: JwkEntry, algorithm: JwsAlgorithm): string | undefined {\n\tif (entry.kind !== 'rsa') return 'key type does not match the algorithm';\n\tif (entry.use !== undefined && entry.use !== 'sig') return '\"use\" is not \"sig\"';\n\tif (entry.keyOps !== undefined && !entry.keyOps.includes('verify')) {\n\t\treturn '\"key_ops\" does not include \"verify\"';\n\t}\n\tif (entry.use === 'sig' && entry.keyOps?.some((op) => op !== 'sign' && op !== 'verify')) {\n\t\treturn '\"use\" and \"key_ops\" are inconsistent';\n\t}\n\tif (entry.alg !== undefined && entry.alg !== algorithm) return '\"alg\" names another algorithm';\n\tconst modulus = base64UrlDecode(entry.n);\n\tconst exponent = base64UrlDecode(entry.e);\n\tif (modulus === undefined || exponent === undefined || modulus.length === 0) {\n\t\treturn 'RSA parameters are not canonical base64url';\n\t}\n\tif (modulus[0] === 0 || exponent[0] === 0 || exponent.length === 0) {\n\t\treturn 'RSA parameters have leading zero octets';\n\t}\n\tif (modulus.length > MAX_RSA_MODULUS_BYTES) return 'RSA modulus is too large';\n\tconst modulusBits = (modulus.length - 1) * 8 + 32 - Math.clz32(modulus[0] ?? 0);\n\tif (modulusBits < MIN_RS256_MODULUS_BITS) return 'RSA modulus is too small';\n\tif (!validRsaPublicExponent(exponent, modulus)) return 'RSA public exponent is invalid';\n\treturn undefined;\n}\n\n/** What {@linkcode selectJwk} matches against. */\nexport interface JwkSelector {\n\t/** The algorithm the token uses. */\n\treadonly algorithm: JwsAlgorithm;\n\t/** The token's `kid`, when it carries one. */\n\treadonly kid?: string;\n}\n\n/**\n * Selects the one key of a set that can verify `selector`.\n *\n * Keys are filtered by `kid` (when the token has one), key type, `use`, `key_ops`, `alg` and RSA\n * parameters. No match is `key_not_found`, or `key_unsuitable` when `kid` matched only keys that\n * fail the other checks. More than one match is `ambiguous_key`: a token without `kid` therefore\n * resolves only against a set with a single usable key.\n */\nexport function selectJwk(\n\tjwks: Jwks,\n\tselector: JwkSelector,\n): JoseResult<RsaJwkEntry, Exclude<KeyResolutionErrorCode, 'jwks_unavailable' | 'aborted'>> {\n\tconst named = jwks.keys.filter(\n\t\t(entry) => selector.kid === undefined || entry.kid === selector.kid,\n\t);\n\tconst details = selector.kid === undefined ? {} : { kid: selector.kid };\n\tif (named.length === 0) return joseFailure('key_not_found', 'No key matches the token', details);\n\tconst usable: RsaJwkEntry[] = [];\n\tfor (const entry of named) {\n\t\tif (entry.kind === 'rsa' && unsuitableReason(entry, selector.algorithm) === undefined) {\n\t\t\tusable.push(entry);\n\t\t}\n\t}\n\tconst [only, second] = usable;\n\tif (only === undefined) {\n\t\treturn joseFailure('key_unsuitable', 'No matching key can verify this algorithm', details);\n\t}\n\tif (second !== undefined) {\n\t\treturn joseFailure('ambiguous_key', 'More than one key matches the token', details);\n\t}\n\treturn successResult(only);\n}\n\n/** Imports a selected entry as a verify-only RS256 `CryptoKey`. */\nexport async function importJwkEntry(\n\tentry: RsaJwkEntry,\n): Promise<JoseResult<CryptoKey, 'key_unsuitable'>> {\n\tconst reason = unsuitableReason(entry, 'RS256');\n\tif (reason !== undefined) {\n\t\treturn joseFailure(\n\t\t\t'key_unsuitable',\n\t\t\treason,\n\t\t\tentry.kid === undefined ? undefined : { kid: entry.kid },\n\t\t);\n\t}\n\tconst imported = await importPublicJwk(\n\t\t{ kty: 'RSA', n: entry.n, e: entry.e, alg: 'RS256', key_ops: ['verify'], ext: true },\n\t\t{ kind: 'rsa', scheme: 'pkcs1-v1_5', hash: 'SHA-256' },\n\t);\n\tif (!imported.ok) {\n\t\treturn joseFailure('key_unsuitable', 'The RSA JWK cannot be imported', {\n\t\t\t...(entry.kid === undefined ? {} : { kid: entry.kid }),\n\t\t});\n\t}\n\tconst suitable = checkRs256VerificationKey(imported.value);\n\treturn suitable.ok ? successResult(imported.value) : suitable;\n}\n\n/**\n * Creates a key resolver over a fixed JWK Set.\n *\n * The resolver selects with {@linkcode selectJwk} and imports each key once, so repeated\n * verifications reuse the same `CryptoKey`.\n */\nexport function createJwksKeyResolver(jwks: Jwks): JwsKeyResolver {\n\tconst imported = new Map<RsaJwkEntry, Promise<JoseResult<CryptoKey, 'key_unsuitable'>>>();\n\treturn async (request) => {\n\t\tconst selected = selectJwk(jwks, {\n\t\t\talgorithm: request.algorithm,\n\t\t\t...(request.kid === undefined ? {} : { kid: request.kid }),\n\t\t});\n\t\tif (!selected.ok) return selected;\n\t\tconst cached = imported.get(selected.value);\n\t\tif (cached !== undefined) return await cached;\n\t\tconst pending = importJwkEntry(selected.value);\n\t\timported.set(selected.value, pending);\n\t\treturn await pending;\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAaA,IAAkC;CAAE,UAAU;CAAQ,SAAS;AAAG;AA0D/E,SAAS,UAAU,GAAoD;CACtE,OAAOC,EAAY,kBAAkBC,CAAO;AAC7C;AAEA,SAAS,aAAa,GAAoB,GAAyC;CAClF,IAAI,CAAC,OAAO,OAAOC,GAAQC,CAAI,GAAG;CAClC,IAAMC,IAAQF,EAAOC;CACrB,OAAO,OAAOC,KAAU,WAAWA,IAAQ;AAC5C;AAEA,SAAS,cAAc,GAAoB,GAAoD;CAC9F,IAAI,CAAC,OAAO,OAAOF,GAAQC,CAAI,GAAG;CAClC,IAAMC,IAA+BF,EAAOC;CAC5C,IAAI,CAACE,EAAYD,CAAK,GAAG,OAAO;CAChC,IAAME,IAAkB,CAAC;CACzB,KAAK,IAAMC,KAAQH,GAAO;EACzB,IAAI,OAAOG,KAAS,YAAYD,EAAM,SAASC,CAAI,GAAG,OAAO;EAC7D,EAAM,KAAKA,CAAI;CAChB;CACA,OAAOD;AACR;AAEA,SAAS,WAAW,GAA0D;CAC7E,IAAI,CAACE,EAAaJ,CAAK,GACtB,OAAO,UAAU,8BAA8B;CAEhD,IA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mE;CACxF,OAAO,OAAO,MAAY;EACzB,IAAMI,IAAW,UAAUX,GAAM;GAChC,WAAWY,EAAQ;GACnB,GAAIA,EAAQ,QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,KAAKA,EAAQ,IAAI;EACzD,CAAC;EACD,IAAI,CAACD,EAAS,IAAI,OAAOA;EACzB,IAAME,IAASN,EAAS,IAAII,EAAS,KAAK;EAC1C,IAAIE,MAAW,KAAA,GAAW,OAAO,MAAMA;EACvC,IAAMC,IAAU,eAAeH,EAAS,KAAK;EAE7C,OADAJ,EAAS,IAAII,EAAS,OAAOG,CAAO,GAC7B,MAAMA;CACd;AACD"}
1
+ {"version":3,"file":"jwks.js","names":["DEFAULT_JWKS_LIMITS","joseFailure","message","object","name","value","isJsonArray","items","item","isJsonObject","kty","kid","use","alg","ops","successResult","metadata","bounds","limits","input","snapshot","snapshotJsonData","MAX_JWKS_BYTES_LIMIT","MAX_JWKS_KEYS_LIMIT","overrides","maxBytes","maxKeys","bytes","text","parsed","parseStrictJson","document","keys","entries","key","entry","JWS_ALGORITHMS","algorithm","profile","jwsAlgorithmProfile","op","x","base64UrlDecode","y","isPrimeEcPoint","modulus","exponent","validRsaPublicExponent","named","jwks","selector","details","usable","only","second","reason","jwk","imported","importPublicJwk","suitable","checkJwsVerificationKey","selected","request","cacheKey","cached","pending"],"sources":["../../src/jose/jwks.ts"],"sourcesContent":["/**\n * JSON Web Key Set (RFC 7517) parsing, key selection and a local key resolver. Nothing here\n * performs network access.\n *\n * @module\n */\n\nimport { isPrimeEcPoint } from '#micro509/internal/crypto/prime-ec';\nimport { base64UrlDecode } from '#micro509/internal/jose/base64url';\nimport { snapshotJsonData } from '#micro509/internal/jose/json-data';\nimport type { JsonObject, JsonValue } from '#micro509/internal/jose/strict-json';\nimport { isJsonArray, isJsonObject, parseStrictJson } from '#micro509/internal/jose/strict-json';\nimport type { JoseErrorResult, JoseResult, KeyResolutionErrorCode } from '#micro509/jose/errors';\nimport { joseFailure } from '#micro509/jose/errors';\nimport type { JwsAlgorithm, JwsKeyResolver } from '#micro509/jose/jws';\nimport {\n\tcheckJwsVerificationKey,\n\tJWS_ALGORITHMS,\n\tjwsAlgorithmProfile,\n\tMIN_JWS_RSA_MODULUS_BITS,\n\tvalidRsaPublicExponent,\n} from '#micro509/jose/jws';\nimport { importPublicJwk } from '#micro509/keys/keys';\nimport { successResult } from '#micro509/result/result';\n\n/** Bounds applied while parsing a JWK Set. */\nexport interface JwksLimits {\n\t/** Maximum JWK Set size in bytes. Default `65536`. */\n\treadonly maxBytes: number;\n\t/** Maximum number of keys in the set. Default `32`. */\n\treadonly maxKeys: number;\n}\n\n/** The limits applied when a caller supplies none. */\nexport const DEFAULT_JWKS_LIMITS: JwksLimits = { maxBytes: 65_536, maxKeys: 32 };\n\nconst MAX_RSA_MODULUS_BYTES = 1024;\nconst MAX_JWKS_JSON_DEPTH = 8;\n\n/** Members every JWK entry carries beside its key material. */\nexport interface JwkMetadata {\n\t/** Key identifier. */\n\treadonly kid?: string;\n\t/** Intended use: `sig` or `enc`, or another value kept verbatim. */\n\treadonly use?: string;\n\t/** Permitted operations, verbatim. */\n\treadonly keyOps?: readonly string[];\n\t/** The algorithm the key is restricted to. */\n\treadonly alg?: string;\n}\n\n/** Members shared by every parsed entry. */\nexport interface JwkEntryBase extends JwkMetadata {\n\t/** Every member the entry carried, as parsed, including key material this module does not read. */\n\treadonly members: JsonObject;\n}\n\n/** An RSA public key entry. */\nexport interface RsaJwkEntry extends JwkEntryBase {\n\t/** Discriminant. */\n\treadonly kind: 'rsa';\n\t/** Base64url modulus. */\n\treadonly n: string;\n\t/** Base64url public exponent. */\n\treadonly e: string;\n}\n\n/** An EC public key entry, with its curve and uncompressed affine coordinates. */\nexport interface EcJwkEntry extends JwkEntryBase {\n\t/** Discriminant. */\n\treadonly kind: 'ec';\n\t/** The curve identifier, retained even when unsupported. */\n\treadonly crv: string;\n\t/** Base64url fixed-width affine x coordinate. */\n\treadonly x: string;\n\t/** Base64url fixed-width affine y coordinate. */\n\treadonly y: string;\n}\n\n/** Public key entries whose type this module can select. */\nexport type SupportedJwkEntry = RsaJwkEntry | EcJwkEntry;\n\n/**\n * An entry this module never selects: a `kty` other than `RSA` or `EC`, or an entry with missing or\n * wrongly typed members (RFC 7517 §5). Kept so callers can inspect the whole set.\n */\nexport interface UnsupportedJwkEntry extends JwkEntryBase {\n\t/** Discriminant. */\n\treadonly kind: 'unsupported';\n\t/** The `kty` the entry carried, when it was a string. */\n\treadonly kty?: string;\n}\n\n/** One key of a JWK Set. */\nexport type JwkEntry = SupportedJwkEntry | UnsupportedJwkEntry;\n\n/** A parsed JWK Set. */\nexport interface Jwks {\n\t/** The keys, in document order. */\n\treadonly keys: readonly JwkEntry[];\n\t/** Every top-level member of the document, as parsed. */\n\treadonly members: JsonObject;\n}\n\n/** Codes {@linkcode parseJwks} returns. */\nexport type ParseJwksErrorCode = 'jwks_malformed' | 'limit_exceeded' | 'invalid_options';\n\nfunction malformed(message: string): JoseErrorResult<'jwks_malformed'> {\n\treturn joseFailure('jwks_malformed', message);\n}\n\nfunction memberString(object: JsonObject, name: string): string | undefined | null {\n\tif (!Object.hasOwn(object, name)) return undefined;\n\tconst value = object[name];\n\treturn typeof value === 'string' ? value : null;\n}\n\nfunction memberStrings(object: JsonObject, name: string): readonly string[] | undefined | null {\n\tif (!Object.hasOwn(object, name)) return undefined;\n\tconst value: JsonValue | undefined = object[name];\n\tif (!isJsonArray(value)) return null;\n\tconst items: string[] = [];\n\tfor (const item of value) {\n\t\tif (typeof item !== 'string' || items.includes(item)) return null;\n\t\titems.push(item);\n\t}\n\treturn items;\n}\n\nfunction parseEntry(value: JsonValue): JoseResult<JwkEntry, 'jwks_malformed'> {\n\tif (!isJsonObject(value)) {\n\t\treturn malformed('JWK Set key is not an object');\n\t}\n\tconst kty = memberString(value, 'kty');\n\tconst kid = memberString(value, 'kid');\n\tconst use = memberString(value, 'use');\n\tconst alg = memberString(value, 'alg');\n\tconst ops = memberStrings(value, 'key_ops');\n\tif (typeof kty !== 'string' || kid === null || use === null || alg === null || ops === null) {\n\t\treturn successResult({\n\t\t\tkind: 'unsupported',\n\t\t\t...(typeof kty === 'string' ? { kty } : {}),\n\t\t\tmembers: value,\n\t\t});\n\t}\n\tconst metadata: JwkMetadata = {\n\t\t...(kid === undefined ? {} : { kid }),\n\t\t...(use === undefined ? {} : { use }),\n\t\t...(alg === undefined ? {} : { alg }),\n\t\t...(ops === undefined ? {} : { keyOps: ops }),\n\t};\n\tif (kty === 'RSA' && typeof value.n === 'string' && typeof value.e === 'string') {\n\t\treturn successResult({ kind: 'rsa', n: value.n, e: value.e, ...metadata, members: value });\n\t}\n\tif (\n\t\tkty === 'EC' &&\n\t\ttypeof value.crv === 'string' &&\n\t\ttypeof value.x === 'string' &&\n\t\ttypeof value.y === 'string'\n\t) {\n\t\treturn successResult({\n\t\t\tkind: 'ec',\n\t\t\tcrv: value.crv,\n\t\t\tx: value.x,\n\t\t\ty: value.y,\n\t\t\t...metadata,\n\t\t\tmembers: value,\n\t\t});\n\t}\n\treturn successResult({ kind: 'unsupported', kty, ...metadata, members: value });\n}\n\n/**\n * Parses a JWK Set document.\n *\n * The document must be duplicate-free JSON with a `keys` array within `limits`. Keys with a `kty`\n * other than `RSA` or `EC`, and keys with missing or wrongly typed members, are kept as `unsupported`\n * entries and never selected (RFC 7517 §5). A set that is not a duplicate-free object with a\n * `keys` array of objects is `jwks_malformed`.\n */\nexport function parseJwks(\n\tinput: string | Uint8Array,\n\tlimits?: Partial<JwksLimits>,\n): JoseResult<Jwks, ParseJwksErrorCode> {\n\tconst bounds = resolveJwksLimits(limits);\n\tif (!bounds.ok) return bounds;\n\treturn parseWithLimits(input, bounds.value);\n}\n\n/**\n * Validates already parsed, plain JSON data and owns a detached deep snapshot of it.\n *\n * Prefer {@linkcode parseJwks} for untrusted transport text: an object cannot reveal lost duplicate\n * member names or invalid original UTF-8. No getters or `toJSON` are called. Cycles, non-JSON values,\n * sparse arrays, accessors, symbols and custom prototypes are refused. `maxBytes` bounds the UTF-8\n * size of the compact JSON data spelling, not the original transport bytes. Depth and node limits\n * match the text parser. A changed source object requires a new validation and resolver instance.\n */\nexport function validateJwks(\n\tvalue: unknown,\n\tlimits?: Partial<JwksLimits>,\n): JoseResult<Jwks, ParseJwksErrorCode> {\n\tconst bounds = resolveJwksLimits(limits);\n\tif (!bounds.ok) return bounds;\n\tconst snapshot = snapshotJsonData(value, {\n\t\tmaxBytes: bounds.value.maxBytes,\n\t\tmaxDepth: MAX_JWKS_JSON_DEPTH,\n\t\tmaxNodes: bounds.value.maxKeys * 64 + 64,\n\t});\n\tif (!snapshot.ok)\n\t\treturn snapshot.code === 'limit_exceeded'\n\t\t\t? joseFailure('limit_exceeded', 'JWK Set exceeds its JSON data bounds')\n\t\t\t: malformed('JWK Set is not plain JSON data');\n\treturn validateDocument(snapshot.value, bounds.value);\n}\n\nconst MAX_JWKS_BYTES_LIMIT = 16_777_216;\nconst MAX_JWKS_KEYS_LIMIT = 1024;\n\nfunction resolveJwksLimits(\n\toverrides: Partial<JwksLimits> | undefined,\n): JoseResult<JwksLimits, '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 maxBytes =\n\t\toverrides?.maxBytes === undefined ? DEFAULT_JWKS_LIMITS.maxBytes : overrides.maxBytes;\n\tconst maxKeys =\n\t\toverrides?.maxKeys === undefined ? DEFAULT_JWKS_LIMITS.maxKeys : overrides.maxKeys;\n\tif (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_JWKS_BYTES_LIMIT) {\n\t\treturn joseFailure(\n\t\t\t'invalid_options',\n\t\t\t`limits.maxBytes must be from 1 to ${MAX_JWKS_BYTES_LIMIT}`,\n\t\t);\n\t}\n\tif (!Number.isSafeInteger(maxKeys) || maxKeys < 1 || maxKeys > MAX_JWKS_KEYS_LIMIT) {\n\t\treturn joseFailure(\n\t\t\t'invalid_options',\n\t\t\t`limits.maxKeys must be from 1 to ${MAX_JWKS_KEYS_LIMIT}`,\n\t\t);\n\t}\n\treturn successResult({ maxBytes, maxKeys });\n}\n\nfunction parseWithLimits(\n\tinput: string | Uint8Array,\n\tbounds: JwksLimits,\n): JoseResult<Jwks, 'jwks_malformed' | 'limit_exceeded'> {\n\tif (typeof input === 'string' && input.length > bounds.maxBytes) {\n\t\treturn joseFailure('limit_exceeded', `JWK Set exceeds ${bounds.maxBytes} bytes`);\n\t}\n\tif (typeof input !== 'string' && !(input instanceof Uint8Array)) {\n\t\treturn malformed('JWK Set input is neither a string nor bytes');\n\t}\n\tconst bytes = typeof input === 'string' ? new TextEncoder().encode(input) : input;\n\tif (bytes.byteLength > bounds.maxBytes) {\n\t\treturn joseFailure('limit_exceeded', `JWK Set exceeds ${bounds.maxBytes} bytes`);\n\t}\n\tlet text: string;\n\ttry {\n\t\ttext = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);\n\t} catch {\n\t\treturn malformed('JWK Set is not valid UTF-8');\n\t}\n\tconst parsed = parseStrictJson(text, {\n\t\tmaxDepth: MAX_JWKS_JSON_DEPTH,\n\t\tmaxNodes: bounds.maxKeys * 64 + 64,\n\t});\n\tif (!parsed.ok) {\n\t\treturn parsed.code === 'limit_exceeded'\n\t\t\t? joseFailure('limit_exceeded', `JWK Set: ${parsed.message}`)\n\t\t\t: malformed(`JWK Set: ${parsed.message}`);\n\t}\n\treturn validateDocument(parsed.value, bounds);\n}\n\nfunction validateDocument(\n\tdocument: JsonValue,\n\tbounds: JwksLimits,\n): JoseResult<Jwks, 'jwks_malformed' | 'limit_exceeded'> {\n\tif (!isJsonObject(document)) {\n\t\treturn malformed('JWK Set is not an object');\n\t}\n\tconst keys = document.keys;\n\tif (!isJsonArray(keys)) return malformed('JWK Set \"keys\" is not an array');\n\tif (keys.length > bounds.maxKeys) {\n\t\treturn joseFailure('limit_exceeded', `JWK Set holds more than ${bounds.maxKeys} keys`);\n\t}\n\tconst entries: JwkEntry[] = [];\n\tfor (const key of keys) {\n\t\tconst entry = parseEntry(key);\n\t\tif (!entry.ok) return entry;\n\t\tentries.push(entry.value);\n\t}\n\treturn successResult({ keys: entries, members: document });\n}\n\n/** Why a key entry cannot verify a given algorithm, or `undefined` when it can. */\nfunction unsuitableReason(entry: JwkEntry, algorithm: JwsAlgorithm): string | undefined {\n\tif (!JWS_ALGORITHMS.includes(algorithm)) return 'unsupported algorithm';\n\tconst profile = jwsAlgorithmProfile(algorithm);\n\tif (entry.kind !== profile.kind) return 'key type does not match the algorithm';\n\tif (entry.use !== undefined && entry.use !== 'sig') return '\"use\" is not \"sig\"';\n\tif (entry.keyOps !== undefined && !entry.keyOps.includes('verify')) {\n\t\treturn '\"key_ops\" does not include \"verify\"';\n\t}\n\tif (entry.use === 'sig' && entry.keyOps?.some((op) => op !== 'sign' && op !== 'verify')) {\n\t\treturn '\"use\" and \"key_ops\" are inconsistent';\n\t}\n\tif (entry.alg !== undefined && entry.alg !== algorithm) return '\"alg\" names another algorithm';\n\tif (entry.kind === 'ec' && profile.kind === 'ec') {\n\t\tif (entry.crv !== profile.curve) return 'EC curve does not match the algorithm';\n\t\tconst x = base64UrlDecode(entry.x);\n\t\tconst y = base64UrlDecode(entry.y);\n\t\tif (x?.length !== profile.coordinateBytes || y?.length !== profile.coordinateBytes) {\n\t\t\treturn 'EC coordinates must be canonical base64url of the required fixed width';\n\t\t}\n\t\treturn isPrimeEcPoint(profile.curve, x, y) ? undefined : 'EC point is not on the curve';\n\t}\n\treturn entry.kind === 'rsa'\n\t\t? unsuitableRsaParameters(entry)\n\t\t: 'key type does not match the algorithm';\n}\n\nfunction unsuitableRsaParameters(entry: RsaJwkEntry): string | undefined {\n\tconst modulus = base64UrlDecode(entry.n);\n\tconst exponent = base64UrlDecode(entry.e);\n\tif (modulus === undefined || exponent === undefined || modulus.length === 0) {\n\t\treturn 'RSA parameters are not canonical base64url';\n\t}\n\tif (modulus[0] === 0 || exponent[0] === 0 || exponent.length === 0) {\n\t\treturn 'RSA parameters have leading zero octets';\n\t}\n\tif (modulus.length > MAX_RSA_MODULUS_BYTES) return 'RSA modulus is too large';\n\tconst modulusBits = (modulus.length - 1) * 8 + 32 - Math.clz32(modulus[0] ?? 0);\n\tif (modulusBits < MIN_JWS_RSA_MODULUS_BITS) return 'RSA modulus is too small';\n\tif (!validRsaPublicExponent(exponent, modulus)) return 'RSA public exponent is invalid';\n\treturn undefined;\n}\n\n/** What {@linkcode selectJwk} matches against. */\nexport interface JwkSelector {\n\t/** The algorithm the token uses. */\n\treadonly algorithm: JwsAlgorithm;\n\t/** The token's `kid`, when it carries one. */\n\treadonly kid?: string;\n}\n\n/**\n * Selects the one key of a set that can verify `selector`.\n *\n * Keys are filtered by `kid` (when the token has one), key type, `use`, `key_ops`, `alg` and RSA/EC\n * parameters. No match is `key_not_found`, or `key_unsuitable` when `kid` matched only keys that\n * fail the other checks. More than one match is `ambiguous_key`: a token without `kid` therefore\n * resolves only against a set with a single usable key.\n */\nexport function selectJwk(\n\tjwks: Jwks,\n\tselector: JwkSelector,\n): JoseResult<SupportedJwkEntry, Exclude<KeyResolutionErrorCode, 'jwks_unavailable' | 'aborted'>> {\n\tconst named = jwks.keys.filter(\n\t\t(entry) => selector.kid === undefined || entry.kid === selector.kid,\n\t);\n\tconst details = selector.kid === undefined ? {} : { kid: selector.kid };\n\tif (named.length === 0) return joseFailure('key_not_found', 'No key matches the token', details);\n\tconst usable: SupportedJwkEntry[] = [];\n\tfor (const entry of named) {\n\t\tif (entry.kind !== 'unsupported' && unsuitableReason(entry, selector.algorithm) === undefined) {\n\t\t\tusable.push(entry);\n\t\t}\n\t}\n\tconst [only, second] = usable;\n\tif (only === undefined) {\n\t\treturn joseFailure('key_unsuitable', 'No matching key can verify this algorithm', details);\n\t}\n\tif (second !== undefined) {\n\t\treturn joseFailure('ambiguous_key', 'More than one key matches the token', details);\n\t}\n\treturn successResult(only);\n}\n\n/**\n * Imports a selected entry as a verify-only key for `algorithm`. The default remains RS256;\n * pass the selected algorithm explicitly for every other RSA hash or ECDSA curve.\n */\nexport async function importJwkEntry(\n\tentry: SupportedJwkEntry,\n\talgorithm: JwsAlgorithm = 'RS256',\n): Promise<JoseResult<CryptoKey, 'key_unsuitable'>> {\n\tconst reason = unsuitableReason(entry, algorithm);\n\tif (reason !== undefined) {\n\t\treturn joseFailure(\n\t\t\t'key_unsuitable',\n\t\t\treason,\n\t\t\tentry.kid === undefined ? undefined : { kid: entry.kid },\n\t\t);\n\t}\n\tconst profile = jwsAlgorithmProfile(algorithm);\n\tconst jwk: JsonWebKey =\n\t\tentry.kind === 'rsa'\n\t\t\t? { kty: 'RSA', n: entry.n, e: entry.e, alg: algorithm, key_ops: ['verify'], ext: true }\n\t\t\t: {\n\t\t\t\t\tkty: 'EC',\n\t\t\t\t\tcrv: entry.crv,\n\t\t\t\t\tx: entry.x,\n\t\t\t\t\ty: entry.y,\n\t\t\t\t\talg: algorithm,\n\t\t\t\t\tkey_ops: ['verify'],\n\t\t\t\t\text: true,\n\t\t\t\t};\n\tconst imported = await importPublicJwk(\n\t\tjwk,\n\t\tprofile.kind === 'rsa'\n\t\t\t? { kind: 'rsa', scheme: 'pkcs1-v1_5', hash: profile.hash }\n\t\t\t: { kind: 'ecdsa', curve: profile.curve },\n\t);\n\tif (!imported.ok) {\n\t\treturn joseFailure('key_unsuitable', 'The JWK cannot be imported', {\n\t\t\t...(entry.kid === undefined ? {} : { kid: entry.kid }),\n\t\t});\n\t}\n\tconst suitable = checkJwsVerificationKey(imported.value, algorithm);\n\treturn suitable.ok ? successResult(imported.value) : suitable;\n}\n\n/** Cache identity includes the admitted algorithm, which binds the RSA import hash. */\nexport function jwkEntryCacheKey(entry: SupportedJwkEntry, algorithm: JwsAlgorithm): string {\n\treturn entry.kind === 'rsa'\n\t\t? `${algorithm}.rsa.${entry.n}.${entry.e}`\n\t\t: `${algorithm}.ec.${entry.crv}.${entry.x}.${entry.y}`;\n}\n\n/**\n * Creates a key resolver over a fixed JWK Set.\n *\n * The resolver selects with {@linkcode selectJwk} and imports each key once, so repeated\n * verifications reuse the same `CryptoKey`. Keep one resolver per trusted source/snapshot and\n * replace it when that snapshot changes so removed keys do not survive rotation.\n *\n * @see https://micro509.kjanat.dev/guide/jose-cache for application-owned raw JWKS caches.\n */\nexport function createJwksKeyResolver(jwks: Jwks): JwsKeyResolver {\n\tconst imported = new Map<string, Promise<JoseResult<CryptoKey, 'key_unsuitable'>>>();\n\treturn async (request) => {\n\t\tconst selected = selectJwk(jwks, {\n\t\t\talgorithm: request.algorithm,\n\t\t\t...(request.kid === undefined ? {} : { kid: request.kid }),\n\t\t});\n\t\tif (!selected.ok) return selected;\n\t\tconst cacheKey = jwkEntryCacheKey(selected.value, request.algorithm);\n\t\tconst cached = imported.get(cacheKey);\n\t\tif (cached !== undefined) return await cached;\n\t\tconst pending = importJwkEntry(selected.value, request.algorithm);\n\t\timported.set(cacheKey, pending);\n\t\treturn await pending;\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkCA,MAAaA,IAAkC;CAAE,UAAU;CAAQ,SAAS;AAAG;AAyE/E,SAAS,UAAU,GAAoD;CACtE,OAAOC,EAAY,kBAAkBC,CAAO;AAC7C;AAEA,SAAS,aAAa,GAAoB,GAAyC;CAClF,IAAI,CAAC,OAAO,OAAOC,GAAQC,CAAI,GAAG;CAClC,IAAMC,IAAQF,EAAOC;CACrB,OAAO,OAAOC,KAAU,WAAWA,IAAQ;AAC5C;AAEA,SAAS,cAAc,GAAoB,GAAoD;CAC9F,IAAI,CAAC,OAAO,OAAOF,GAAQC,CAAI,GAAG;CAClC,IAAMC,IAA+BF,EAAOC;CAC5C,IAAI,CAACE,EAAYD,CAAK,GAAG,OAAO;CAChC,IAAME,IAAkB,CAAC;CACzB,KAAK,IAAMC,KAAQH,GAAO;EACzB,IAAI,OAAOG,KAAS,YAAYD,EAAM,SAASC,CAAI,GAAG,OAAO;EAC7D,EAAM,KAAKA,CA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B,EAAS,IACb,OAAOxD,EAAY,kBAAkB,8BAA8B,EAClE,GAAIkC,EAAM,QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,KAAKA,EAAM,IAAI,EACrD,CAAC;CAEF,IAAMwB,IAAWC,EAAwBH,EAAS,OAAOpB,CAAS;CAClE,OAAOsB,EAAS,KAAK5C,EAAc0C,EAAS,KAAK,IAAIE;AACtD;;AAGA,SAAgB,iBAAiB,GAA0B,GAAiC;CAC3F,OAAOxB,EAAM,SAAS,QACnB,GAAGE,EAAU,OAAOF,EAAM,EAAE,GAAGA,EAAM,MACrC,GAAGE,EAAU,MAAMF,EAAM,IAAI,GAAGA,EAAM,EAAE,GAAGA,EAAM;AACrD;;;;;;;;;;AAWA,SAAgB,sBAAsB,GAA4B;CACjE,IAAMsB,oBAAW,IAAI,IAA8D;CACnF,OAAO,OAAO,MAAY;EACzB,IAAMI,IAAW,UAAUZ,GAAM;GAChC,WAAWa,EAAQ;GACnB,GAAIA,EAAQ,QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,KAAKA,EAAQ,IAAI;EACzD,CAAC;EACD,IAAI,CAACD,EAAS,IAAI,OAAOA;EACzB,IAAME,IAAW,iBAAiBF,EAAS,OAAOC,EAAQ,SAAS,GAC7DE,IAASP,EAAS,IAAIM,CAAQ;EACpC,IAAIC,MAAW,KAAA,GAAW,OAAO,MAAMA;EACvC,IAAMC,IAAU,eAAeJ,EAAS,OAAOC,EAAQ,SAAS;EAEhE,OADAL,EAAS,IAAIM,GAAUE,CAAO,GACvB,MAAMA;CACd;AACD"}
@@ -1,11 +1,13 @@
1
1
  import { JsonObject } from "../internal/jose/strict-json.js";
2
2
  import { JoseResult, JwsParseErrorCode, KeyResolutionErrorCode, VerifyJwsErrorCode } from "./errors.js";
3
3
  /** Signature algorithms this module signs and verifies. */
4
- export type JwsAlgorithm = "RS256";
4
+ export type JwsAlgorithm = "RS256" | "RS384" | "RS512" | "ES256" | "ES384";
5
5
  /** Every {@linkcode JwsAlgorithm}. */
6
6
  export declare const JWS_ALGORITHMS: readonly JwsAlgorithm[];
7
7
  /** Smallest RSA modulus RS256 accepts (RFC 7518 §3.3). */
8
8
  export declare const MIN_RS256_MODULUS_BITS = 2048;
9
+ /** Smallest RSA modulus accepted by any implemented RSA JWS algorithm (RFC 7518 §3.3). */
10
+ export declare const MIN_JWS_RSA_MODULUS_BITS: number;
9
11
  /** Size and structure bounds enforced before any expensive parsing. */
10
12
  export interface JoseLimits {
11
13
  /** Maximum compact serialization length in characters. Default `32768`. */
@@ -113,7 +115,7 @@ export interface JwsHeaderInput {
113
115
  }
114
116
  /** Input for {@linkcode signCompactJws}. */
115
117
  export interface SignJwsInput {
116
- /** An RSASSA-PKCS1-v1_5 SHA-256 private key of at least 2048 bits. */
118
+ /** A signing key matching the algorithm's RSA hash or ECDSA curve. RSA needs at least 2048 bits. */
117
119
  readonly privateKey: CryptoKey;
118
120
  /** The signature algorithm. */
119
121
  readonly algorithm: JwsAlgorithm;
@@ -138,8 +140,9 @@ export declare function parseCompactJws(token: string, limits?: Partial<JoseLimi
138
140
  *
139
141
  * The caller's `algorithms` list decides what is accepted; the token's `alg` only selects among
140
142
  * them, and `none` is always refused as `unsigned_token`. The `tokenType` policy is applied before
141
- * any key is resolved. A fixed key or the resolver's key must be an RSASSA-PKCS1-v1_5 SHA-256
142
- * public key of at least 2048 bits for RS256. Header members such as `jku`, `jwk`, `x5u` and
143
+ * any key is resolved. The key must match the admitted algorithm's RSA hash (at least 2048 bits)
144
+ * or ECDSA curve. ECDSA signatures must be fixed-width raw R || S, with no DER retry.
145
+ * Header members such as `jku`, `jwk`, `x5u` and
143
146
  * `x5c` are never used to find a key. A resolver that throws or returns something other than a
144
147
  * result is reported as `key_resolution_failed` without its message.
145
148
  *
@@ -154,5 +157,4 @@ export declare function verifyCompactJws(token: string, options: VerifyJwsOption
154
157
  * (see `isResultError`) coded {@linkcode SignJoseErrorCode} when the algorithm, key or header
155
158
  * input is invalid. Intended for issuing tokens and for building synthetic tokens in tests.
156
159
  */
157
- export declare function signCompactJws(input: SignJwsInput): Promise<string>;
158
- //# sourceMappingURL=jws.d.ts.map
160
+ export declare function signCompactJws(input: SignJwsInput): Promise<string>;