micro509 0.17.1 → 0.19.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 (183) hide show
  1. package/CHANGELOG.md +165 -6
  2. package/dist/crypto/crypto.d.ts +12 -4
  3. package/dist/crypto/crypto.js +30 -17
  4. package/dist/crypto/crypto.js.map +1 -1
  5. package/dist/crypto.d.ts +8 -2
  6. package/dist/der/der.d.ts +14 -4
  7. package/dist/der/der.js +19 -19
  8. package/dist/der/der.js.map +1 -1
  9. package/dist/der.d.ts +26 -2
  10. package/dist/der.js +4 -4
  11. package/dist/index.d.ts +84 -16
  12. package/dist/index.js +19 -19
  13. package/dist/internal/asn1/asn1.d.ts +1 -2
  14. package/dist/internal/asn1/asn1.js +10 -2
  15. package/dist/internal/asn1/asn1.js.map +1 -1
  16. package/dist/internal/asn1/ber.js.map +1 -1
  17. package/dist/internal/asn1/decode-refusal.js.map +1 -1
  18. package/dist/internal/asn1/der.d.ts +1 -2
  19. package/dist/internal/asn1/der.js.map +1 -1
  20. package/dist/internal/asn1/oids.js +71 -353
  21. package/dist/internal/asn1/oids.js.map +1 -1
  22. package/dist/internal/asn1/oids.json.js +357 -0
  23. package/dist/internal/asn1/oids.json.js.map +1 -0
  24. package/dist/internal/crypto/algorithm-names.js +1 -1
  25. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  26. package/dist/internal/crypto/ecdsa.js.map +1 -1
  27. package/dist/internal/crypto/hash.js.map +1 -1
  28. package/dist/internal/crypto/pbes2.d.ts +1 -2
  29. package/dist/internal/crypto/pbes2.js +70 -70
  30. package/dist/internal/crypto/pbes2.js.map +1 -1
  31. package/dist/internal/crypto/prime-ec.js +37 -0
  32. package/dist/internal/crypto/prime-ec.js.map +1 -0
  33. package/dist/internal/crypto/rsa-pss.js +50 -50
  34. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  35. package/dist/internal/crypto/sig-verify.d.ts +41 -2
  36. package/dist/internal/crypto/sig-verify.js +125 -38
  37. package/dist/internal/crypto/sig-verify.js.map +1 -1
  38. package/dist/internal/crypto/signing.d.ts +1 -2
  39. package/dist/internal/crypto/signing.js +26 -26
  40. package/dist/internal/crypto/signing.js.map +1 -1
  41. package/dist/internal/jose/base64url.js.map +1 -1
  42. package/dist/internal/jose/json-data.js +108 -0
  43. package/dist/internal/jose/json-data.js.map +1 -0
  44. package/dist/internal/jose/strict-json.d.ts +1 -2
  45. package/dist/internal/jose/strict-json.js.map +1 -1
  46. package/dist/internal/shared/base64.js.map +1 -1
  47. package/dist/internal/shared/dn.d.ts +1 -2
  48. package/dist/internal/shared/dn.js +1 -1
  49. package/dist/internal/shared/dn.js.map +1 -1
  50. package/dist/internal/shared/idna.js.map +1 -1
  51. package/dist/internal/shared/ip.d.ts +1 -2
  52. package/dist/internal/shared/ip.js.map +1 -1
  53. package/dist/internal/shared/mailbox.js.map +1 -1
  54. package/dist/internal/shared/punycode.js.map +1 -1
  55. package/dist/internal/shared/uri-host.js.map +1 -1
  56. package/dist/internal/verify/name-constraints-engine.js +64 -64
  57. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  58. package/dist/internal/verify/policy-engine.js +1 -1
  59. package/dist/internal/verify/policy-engine.js.map +1 -1
  60. package/dist/internal/verify/spki-distrust.js.map +1 -1
  61. package/dist/internal/verify/verify-path.d.ts +1 -2
  62. package/dist/internal/verify/verify-path.js +234 -128
  63. package/dist/internal/verify/verify-path.js.map +1 -1
  64. package/dist/internal/x509/directory-name.js +10 -10
  65. package/dist/internal/x509/directory-name.js.map +1 -1
  66. package/dist/internal/x509/extension-bits.js.map +1 -1
  67. package/dist/internal/x509/extension-errors.d.ts +1 -2
  68. package/dist/internal/x509/extension-errors.js.map +1 -1
  69. package/dist/internal/x509/extension-registry.js +18 -18
  70. package/dist/internal/x509/extension-registry.js.map +1 -1
  71. package/dist/internal/x509/general-name-profile.js +9 -9
  72. package/dist/internal/x509/general-name-profile.js.map +1 -1
  73. package/dist/internal/x509/general-name.js +32 -32
  74. package/dist/internal/x509/general-name.js.map +1 -1
  75. package/dist/internal/x509/name-fields.js +1 -1
  76. package/dist/internal/x509/name-fields.js.map +1 -1
  77. package/dist/internal/x509/or-address.js.map +1 -1
  78. package/dist/jose/base64url.d.ts +4 -0
  79. package/dist/jose/base64url.js +14 -0
  80. package/dist/jose/base64url.js.map +1 -0
  81. package/dist/jose/errors.d.ts +9 -3
  82. package/dist/jose/errors.js.map +1 -1
  83. package/dist/jose/jwe.d.ts +64 -0
  84. package/dist/jose/jwe.js +188 -0
  85. package/dist/jose/jwe.js.map +1 -0
  86. package/dist/jose/jwks.d.ts +38 -10
  87. package/dist/jose/jwks.js +156 -96
  88. package/dist/jose/jwks.js.map +1 -1
  89. package/dist/jose/jws.d.ts +8 -6
  90. package/dist/jose/jws.js +216 -170
  91. package/dist/jose/jws.js.map +1 -1
  92. package/dist/jose/jwt.d.ts +8 -2
  93. package/dist/jose/jwt.js +98 -98
  94. package/dist/jose/jwt.js.map +1 -1
  95. package/dist/jose/remote-jwks.d.ts +1 -2
  96. package/dist/jose/remote-jwks.js +106 -108
  97. package/dist/jose/remote-jwks.js.map +1 -1
  98. package/dist/jose.d.ts +15 -4
  99. package/dist/jose.js +7 -5
  100. package/dist/kdf/argon2-arithmetic.js.map +1 -1
  101. package/dist/kdf/argon2-core.js.map +1 -1
  102. package/dist/kdf/argon2-memory.js.map +1 -1
  103. package/dist/kdf/argon2-portable.js.map +1 -1
  104. package/dist/kdf/argon2.d.ts +7 -2
  105. package/dist/kdf/argon2.js.map +1 -1
  106. package/dist/kdf.d.ts +6 -0
  107. package/dist/keys/keys.d.ts +31 -6
  108. package/dist/keys/keys.js +315 -233
  109. package/dist/keys/keys.js.map +1 -1
  110. package/dist/keys.d.ts +11 -2
  111. package/dist/keys.js +2 -2
  112. package/dist/pem/pem.d.ts +1 -2
  113. package/dist/pem/pem.js +40 -25
  114. package/dist/pem/pem.js.map +1 -1
  115. package/dist/pem.d.ts +6 -0
  116. package/dist/pkcs/pfx.d.ts +2 -3
  117. package/dist/pkcs/pfx.js +142 -142
  118. package/dist/pkcs/pfx.js.map +1 -1
  119. package/dist/pkcs/pkcs12-mac.d.ts +1 -2
  120. package/dist/pkcs/pkcs12-mac.js +122 -122
  121. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  122. package/dist/pkcs/pkcs7.d.ts +24 -3
  123. package/dist/pkcs/pkcs7.js +294 -256
  124. package/dist/pkcs/pkcs7.js.map +1 -1
  125. package/dist/pkcs.d.ts +10 -1
  126. package/dist/pkcs.js +4 -4
  127. package/dist/result/result.d.ts +1 -2
  128. package/dist/result/result.js.map +1 -1
  129. package/dist/result.d.ts +6 -0
  130. package/dist/revocation/chain.d.ts +69 -16
  131. package/dist/revocation/chain.js +431 -303
  132. package/dist/revocation/chain.js.map +1 -1
  133. package/dist/revocation/crl.d.ts +67 -14
  134. package/dist/revocation/crl.js +656 -366
  135. package/dist/revocation/crl.js.map +1 -1
  136. package/dist/revocation/ocsp.d.ts +78 -24
  137. package/dist/revocation/ocsp.js +622 -436
  138. package/dist/revocation/ocsp.js.map +1 -1
  139. package/dist/revocation/revocation.d.ts +68 -14
  140. package/dist/revocation/revocation.js +195 -74
  141. package/dist/revocation/revocation.js.map +1 -1
  142. package/dist/revocation.d.ts +14 -5
  143. package/dist/revocation.js +4 -4
  144. package/dist/ssh/ssh.d.ts +2 -3
  145. package/dist/ssh/ssh.js +165 -170
  146. package/dist/ssh/ssh.js.map +1 -1
  147. package/dist/ssh/wire.d.ts +1 -2
  148. package/dist/ssh/wire.js +10 -10
  149. package/dist/ssh/wire.js.map +1 -1
  150. package/dist/ssh.d.ts +8 -0
  151. package/dist/verify/identity.d.ts +3 -4
  152. package/dist/verify/identity.js +33 -33
  153. package/dist/verify/identity.js.map +1 -1
  154. package/dist/verify/name-constraints.d.ts +9 -2
  155. package/dist/verify/policy.d.ts +9 -2
  156. package/dist/verify/verify.d.ts +85 -34
  157. package/dist/verify/verify.js +276 -226
  158. package/dist/verify/verify.js.map +1 -1
  159. package/dist/verify.d.ts +12 -2
  160. package/dist/x509/certificate.d.ts +4 -5
  161. package/dist/x509/certificate.js +40 -40
  162. package/dist/x509/certificate.js.map +1 -1
  163. package/dist/x509/csr.d.ts +3 -4
  164. package/dist/x509/csr.js +15 -15
  165. package/dist/x509/csr.js.map +1 -1
  166. package/dist/x509/extensions.d.ts +1 -2
  167. package/dist/x509/extensions.js +165 -165
  168. package/dist/x509/extensions.js.map +1 -1
  169. package/dist/x509/fingerprint.d.ts +1 -2
  170. package/dist/x509/fingerprint.js.map +1 -1
  171. package/dist/x509/name-text.d.ts +1 -2
  172. package/dist/x509/name-text.js.map +1 -1
  173. package/dist/x509/name.d.ts +1 -2
  174. package/dist/x509/name.js +15 -15
  175. package/dist/x509/name.js.map +1 -1
  176. package/dist/x509/parse.d.ts +9 -6
  177. package/dist/x509/parse.js +394 -394
  178. package/dist/x509/parse.js.map +1 -1
  179. package/dist/x509.d.ts +17 -4
  180. package/dist/x509.js +8 -8
  181. package/package.json +32 -33
  182. package/dist/internal/asn1/oids2.js +0 -75
  183. package/dist/internal/asn1/oids2.js.map +0 -1
@@ -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;
@@ -1,61 +1,62 @@
1
- import { successResult as e, throwMicro509Error as t } from "../result/result.js";
2
- import { joseFailure as n } from "./errors.js";
3
- import { importJwkEntry as r, parseJwks as i, selectJwk as a } from "./jwks.js";
1
+ import { joseFailure as e } from "./errors.js";
2
+ import { importJwkEntry as t, jwkEntryCacheKey as n, parseJwks as r, selectJwk as i } from "./jwks.js";
3
+ import { JWS_ALGORITHMS as a } from "./jws.js";
4
+ import { successResult as o, throwMicro509Error as s } from "../result/result.js";
4
5
  // src/jose/remote-jwks.ts
5
- const o = Symbol("micro509.jose.aborted"), s = {
6
+ const c = Symbol("micro509.jose.aborted"), l = {
6
7
  timeoutMs: 5e3,
7
8
  maxResponseBytes: 65536,
8
9
  maxKeys: 32,
9
10
  defaultTtlMs: 6e5,
10
11
  maxTtlMs: 864e5,
11
12
  cooldownMs: 3e4
12
- }, c = /* @__PURE__ */ new Set([
13
+ }, u = /* @__PURE__ */ new Set([
13
14
  301,
14
15
  302,
15
16
  303,
16
17
  307,
17
18
  308
18
- ]), l = /* @__PURE__ */ new Set([
19
+ ]), d = /* @__PURE__ */ new Set([
19
20
  "localhost",
20
21
  "127.0.0.1",
21
22
  "[::1]"
22
23
  ]);
23
24
  function isPermittedUrl(e) {
24
- return e.protocol === "https:" || e.protocol === "http:" && l.has(e.hostname);
25
+ return e.protocol === "https:" || e.protocol === "http:" && d.has(e.hostname);
25
26
  }
26
- function positiveInteger(e, n, r) {
27
- let i = e ?? n;
28
- return !Number.isSafeInteger(i) || i <= 0 ? t("invalid_remote_jwks_config", `${r} must be a positive integer`) : i;
27
+ function positiveInteger(e, t, n) {
28
+ let r = e ?? t;
29
+ return !Number.isSafeInteger(r) || r <= 0 ? s("invalid_remote_jwks_config", `${n} must be a positive integer`) : r;
29
30
  }
30
31
  function resolveConfig(e) {
31
- let n;
32
+ let t;
32
33
  try {
33
- n = new URL(e.url);
34
+ t = new URL(e.url);
34
35
  } catch {
35
- return t("invalid_remote_jwks_config", "url is not an absolute URL");
36
+ return s("invalid_remote_jwks_config", "url is not an absolute URL");
36
37
  }
37
- if (!isPermittedUrl(n)) return t("invalid_remote_jwks_config", "url must use https, or http on a loopback host");
38
- if (n.username !== "" || n.password !== "") return t("invalid_remote_jwks_config", "url must not embed credentials");
39
- let r = e.redirects?.maxRedirects ?? 0;
40
- if (!Number.isSafeInteger(r) || r < 0 || r > 10) return t("invalid_remote_jwks_config", "maxRedirects must be an integer from 0 to 10");
41
- let i = positiveInteger(e.maxTtlMs, s.maxTtlMs, "maxTtlMs"), a = positiveInteger(e.cooldownMs, s.cooldownMs, "cooldownMs");
38
+ if (!isPermittedUrl(t)) return s("invalid_remote_jwks_config", "url must use https, or http on a loopback host");
39
+ if (t.username !== "" || t.password !== "") return s("invalid_remote_jwks_config", "url must not embed credentials");
40
+ let n = e.redirects?.maxRedirects ?? 0;
41
+ if (!Number.isSafeInteger(n) || n < 0 || n > 10) return s("invalid_remote_jwks_config", "maxRedirects must be an integer from 0 to 10");
42
+ let r = positiveInteger(e.maxTtlMs, l.maxTtlMs, "maxTtlMs"), i = positiveInteger(e.cooldownMs, l.cooldownMs, "cooldownMs");
42
43
  return {
43
- url: n,
44
+ url: t,
44
45
  transport: e.transport ?? ((e, t) => globalThis.fetch(e, t)),
45
46
  headers: { ...e.headers },
46
- timeoutMs: positiveInteger(e.timeoutMs, s.timeoutMs, "timeoutMs"),
47
- maxResponseBytes: positiveInteger(e.maxResponseBytes, s.maxResponseBytes, "maxResponseBytes"),
48
- maxKeys: positiveInteger(e.maxKeys, s.maxKeys, "maxKeys"),
49
- maxRedirects: r,
47
+ timeoutMs: positiveInteger(e.timeoutMs, l.timeoutMs, "timeoutMs"),
48
+ maxResponseBytes: positiveInteger(e.maxResponseBytes, l.maxResponseBytes, "maxResponseBytes"),
49
+ maxKeys: positiveInteger(e.maxKeys, l.maxKeys, "maxKeys"),
50
+ maxRedirects: n,
50
51
  allowRedirect: e.redirects?.allow ?? ((e, t) => e.origin === t.origin),
51
- defaultTtlMs: positiveInteger(e.defaultTtlMs, s.defaultTtlMs, "defaultTtlMs"),
52
- maxTtlMs: i,
53
- cooldownMs: a,
52
+ defaultTtlMs: positiveInteger(e.defaultTtlMs, l.defaultTtlMs, "defaultTtlMs"),
53
+ maxTtlMs: r,
54
+ cooldownMs: i,
54
55
  now: e.now ?? Date.now
55
56
  };
56
57
  }
57
- function unavailable(e, t) {
58
- return n("jwks_unavailable", e, t === void 0 ? void 0 : { status: t });
58
+ function unavailable(t, n) {
59
+ return e("jwks_unavailable", t, n === void 0 ? void 0 : { status: n });
59
60
  }
60
61
  function secondsHeader(e, t) {
61
62
  let n = e.get(t);
@@ -82,53 +83,53 @@ function freshnessMs(e, t, n, r) {
82
83
  }
83
84
  return Math.min(r.maxTtlMs, Math.max(0, d - l));
84
85
  }
85
- async function readBounded(t, r, i) {
86
- let a = n("jwks_malformed", `The JWKS response exceeds ${r} bytes`), o = t.headers.get("content-length");
87
- if (o !== null && /^\d+$/.test(o) && Number(o) > r) return await t.body?.cancel(), a;
88
- if (t.body === null) return e(/* @__PURE__ */ new Uint8Array());
86
+ async function readBounded(t, n, r) {
87
+ let i = e("jwks_malformed", `The JWKS response exceeds ${n} bytes`), a = t.headers.get("content-length");
88
+ if (a !== null && /^\d+$/.test(a) && Number(a) > n) return await t.body?.cancel(), i;
89
+ if (t.body === null) return o(/* @__PURE__ */ new Uint8Array());
89
90
  let s = t.body.getReader(), release = () => {
90
91
  s.cancel().catch(() => void 0);
91
92
  };
92
- i.addEventListener("abort", release, { once: !0 });
93
+ r.addEventListener("abort", release, { once: !0 });
93
94
  try {
94
- let t = [], n = 0;
95
+ let e = [], t = 0;
95
96
  for (;;) {
96
- let { done: e, value: o } = await s.read();
97
- if (i.aborted) return unavailable("The JWKS request was cancelled");
98
- if (e) break;
99
- if (n += o.byteLength, n > r) return release(), a;
100
- t.push(o);
97
+ let { done: a, value: o } = await s.read();
98
+ if (r.aborted) return unavailable("The JWKS request was cancelled");
99
+ if (a) break;
100
+ if (t += o.byteLength, t > n) return release(), i;
101
+ e.push(o);
101
102
  }
102
- let o = new Uint8Array(n), c = 0;
103
- for (let e of t) o.set(e, c), c += e.byteLength;
104
- return e(o);
103
+ let a = new Uint8Array(t), c = 0;
104
+ for (let t of e) a.set(t, c), c += t.byteLength;
105
+ return o(a);
105
106
  } finally {
106
- i.removeEventListener("abort", release);
107
+ r.removeEventListener("abort", release);
107
108
  }
108
109
  }
109
- function nextHop(t, n, r, i) {
110
- let a = r.headers.get("location");
111
- if (i >= t.maxRedirects || a === null) return unavailable("The JWKS endpoint redirected", r.status);
112
- let o;
110
+ function nextHop(e, t, n, r) {
111
+ let i = n.headers.get("location");
112
+ if (r >= e.maxRedirects || i === null) return unavailable("The JWKS endpoint redirected", n.status);
113
+ let a;
113
114
  try {
114
- o = new URL(a, n);
115
+ a = new URL(i, t);
115
116
  } catch {
116
- return unavailable("The JWKS redirect target is not a URL", r.status);
117
+ return unavailable("The JWKS redirect target is not a URL", n.status);
117
118
  }
118
- return !isPermittedUrl(o) || o.username !== "" || o.password !== "" || !t.allowRedirect(o, n) ? unavailable("The JWKS redirect target is not permitted", r.status) : e(o);
119
+ return !isPermittedUrl(a) || a.username !== "" || a.password !== "" || !e.allowRedirect(a, t) ? unavailable("The JWKS redirect target is not permitted", n.status) : o(a);
119
120
  }
120
- async function readJwks(t, r, a, o) {
121
- if (r.status !== 200) return await r.body?.cancel(), unavailable("The JWKS endpoint did not answer 200", r.status);
122
- let s = t.now(), c = await readBounded(r, t.maxResponseBytes, o);
121
+ async function readJwks(t, n, i, a) {
122
+ if (n.status !== 200) return await n.body?.cancel(), unavailable("The JWKS endpoint did not answer 200", n.status);
123
+ let s = t.now(), c = await readBounded(n, t.maxResponseBytes, a);
123
124
  if (!c.ok) return c;
124
- let l = i(c.value, {
125
+ let l = r(c.value, {
125
126
  maxBytes: t.maxResponseBytes,
126
127
  maxKeys: t.maxKeys
127
128
  });
128
- return l.ok ? e({
129
+ return l.ok ? o({
129
130
  jwks: l.value,
130
- expiresAt: s + freshnessMs(r.headers, a, s, t)
131
- }) : n("jwks_malformed", l.message);
131
+ expiresAt: s + freshnessMs(n.headers, i, s, t)
132
+ }) : e("jwks_malformed", l.message);
132
133
  }
133
134
  async function fetchJwks(e, t, n) {
134
135
  let r = e.url;
@@ -143,29 +144,26 @@ async function fetchJwks(e, t, n) {
143
144
  });
144
145
  if (t.aborted) return await a.body?.cancel(), unavailable("The JWKS request was cancelled");
145
146
  if (a.type === "opaqueredirect") return unavailable("The runtime hides redirects, so they cannot be validated");
146
- if (!c.has(a.status)) return await readJwks(e, a, n, t);
147
+ if (!u.has(a.status)) return await readJwks(e, a, n, t);
147
148
  await a.body?.cancel();
148
149
  let o = nextHop(e, r, a, i);
149
150
  if (!o.ok) return o;
150
151
  r = o.value;
151
152
  }
152
153
  }
153
- function entryKey(e) {
154
- return `${e.n}.${e.e}`;
155
- }
156
154
  function carryOver(e, t) {
157
- let n = /* @__PURE__ */ new Map();
158
- for (let r of e.jwks.keys) {
159
- let e = r.kind === "rsa" ? t?.imported.get(entryKey(r)) : void 0;
160
- r.kind === "rsa" && e !== void 0 && n.set(entryKey(r), e);
155
+ let r = /* @__PURE__ */ new Map();
156
+ for (let i of e.jwks.keys) if (i.kind !== "unsupported") for (let e of a) {
157
+ let a = n(i, e), o = t?.imported.get(a);
158
+ o !== void 0 && r.set(a, o);
161
159
  }
162
160
  return {
163
161
  jwks: e.jwks,
164
162
  expiresAt: e.expiresAt,
165
- imported: n
163
+ imported: r
166
164
  };
167
165
  }
168
- const u = Symbol("micro509.jose.timedOut");
166
+ const f = Symbol("micro509.jose.timedOut");
169
167
  /**
170
168
  * Creates a key resolver that reads a JWK Set from one trusted URL.
171
169
  *
@@ -196,19 +194,19 @@ const u = Symbol("micro509.jose.timedOut");
196
194
  * Redirect destinations, and the addresses a hostname resolves to, are limited by `redirects` and
197
195
  * the transport; this module cannot see DNS answers, and browsers hide redirect targets.
198
196
  */
199
- function createRemoteJwksKeyResolver(t) {
200
- let i = resolveConfig(t), s, c, l;
197
+ function createRemoteJwksKeyResolver(r) {
198
+ let a = resolveConfig(r), s, l, u;
201
199
  function startRefresh() {
202
- let e = new AbortController(), t = i.now(), n = l, r = s;
203
- l = t;
200
+ let e = new AbortController(), t = a.now(), n = u, r = s;
201
+ u = t;
204
202
  async function run() {
205
- let n, a = new Promise((e) => {
206
- n = setTimeout(() => e(u), i.timeoutMs);
207
- }), o = fetchJwks(i, e.signal, t);
203
+ let n, i = new Promise((e) => {
204
+ n = setTimeout(() => e(f), a.timeoutMs);
205
+ }), o = fetchJwks(a, e.signal, t);
208
206
  o.catch(() => void 0);
209
207
  try {
210
- let t = await Promise.race([o, a]);
211
- return t === u ? (e.abort(), {
208
+ let t = await Promise.race([o, i]);
209
+ return t === f ? (e.abort(), {
212
210
  kind: "failed",
213
211
  failure: unavailable("The JWKS request timed out")
214
212
  }) : t.ok ? {
@@ -227,11 +225,11 @@ function createRemoteJwksKeyResolver(t) {
227
225
  clearTimeout(n);
228
226
  }
229
227
  }
230
- let a = run().then((e) => c?.promise === a ? (e.kind === "fresh" && (s = e.snapshot), e) : { kind: "abandoned" }).finally(() => {
231
- c?.promise === a && (c = void 0);
228
+ let i = run().then((e) => l?.promise === i ? (e.kind === "fresh" && (s = e.snapshot), e) : { kind: "abandoned" }).finally(() => {
229
+ l?.promise === i && (l = void 0);
232
230
  });
233
231
  return {
234
- promise: a,
232
+ promise: i,
235
233
  controller: e,
236
234
  startedAt: t,
237
235
  previousAttemptAt: n,
@@ -239,14 +237,14 @@ function createRemoteJwksKeyResolver(t) {
239
237
  };
240
238
  }
241
239
  async function awaitRefresh(e) {
242
- if (e?.aborted === !0) return o;
243
- c ??= startRefresh();
244
- let t = c;
240
+ if (e?.aborted === !0) return c;
241
+ l ??= startRefresh();
242
+ let t = l;
245
243
  return t.waiters++, e === void 0 ? await t.promise : await new Promise((n) => {
246
244
  let r = !1, finish = () => {
247
245
  r = !0, e.removeEventListener("abort", onAbort);
248
246
  }, onAbort = () => {
249
- r || (finish(), t.waiters--, t.waiters === 0 && (c === t && (c = void 0), l === t.startedAt && (l = t.previousAttemptAt), t.controller.abort()), n(o));
247
+ r || (finish(), t.waiters--, t.waiters === 0 && (l === t && (l = void 0), u === t.startedAt && (u = t.previousAttemptAt), t.controller.abort()), n(c));
250
248
  };
251
249
  e.addEventListener("abort", onAbort, { once: !0 }), e.aborted && onAbort(), t.promise.then((e) => {
252
250
  r || (finish(), n(e));
@@ -254,43 +252,43 @@ function createRemoteJwksKeyResolver(t) {
254
252
  });
255
253
  }
256
254
  function refreshAllowed() {
257
- return c !== void 0 || l === void 0 || i.now() - l >= i.cooldownMs;
255
+ return l !== void 0 || u === void 0 || a.now() - u >= a.cooldownMs;
258
256
  }
259
257
  async function obtain(t) {
260
- if (!refreshAllowed()) return e(void 0);
261
- let r = await awaitRefresh(t);
262
- return r === o || r.kind === "abandoned" ? n("aborted", "Key resolution was cancelled") : r.kind === "failed" ? r.failure : e(r.snapshot);
258
+ if (!refreshAllowed()) return o(void 0);
259
+ let n = await awaitRefresh(t);
260
+ return n === c || n.kind === "abandoned" ? e("aborted", "Key resolution was cancelled") : n.kind === "failed" ? n.failure : o(n.snapshot);
263
261
  }
264
- async function importFrom(e, t) {
265
- let n = entryKey(t), i = e.imported.get(n);
266
- if (i !== void 0) return await i;
267
- let a = r(t);
268
- return e.imported.set(n, a), await a;
262
+ async function importFrom(e, r, i) {
263
+ let a = n(r, i), o = e.imported.get(a);
264
+ if (o !== void 0) return await o;
265
+ let s = t(r, i);
266
+ return e.imported.set(a, s), await s;
269
267
  }
270
- async function currentSnapshot(t) {
271
- if (s !== void 0 && i.now() < s.expiresAt) return e(s);
268
+ async function currentSnapshot(e) {
269
+ if (s !== void 0 && a.now() < s.expiresAt) return o(s);
272
270
  s = void 0;
273
- let n = await obtain(t);
274
- return n.ok ? n.value === void 0 ? unavailable("The JWKS endpoint is in cooldown") : e(n.value) : n;
271
+ let t = await obtain(e);
272
+ return t.ok ? t.value === void 0 ? unavailable("The JWKS endpoint is in cooldown") : o(t.value) : t;
275
273
  }
276
- async function select(e, t, r) {
277
- let i = e, o = a(i.jwks, t);
274
+ async function select(t, n, r) {
275
+ let a = t, o = i(a.jwks, n);
278
276
  if (!o.ok && o.code === "key_not_found") {
279
277
  let e = await obtain(r);
280
278
  if (!e.ok) return e;
281
- e.value !== void 0 && (i = e.value, o = a(i.jwks, t));
279
+ e.value !== void 0 && (a = e.value, o = i(a.jwks, n));
282
280
  }
283
281
  if (!o.ok) return o;
284
- let s = await importFrom(i, o.value);
285
- return r?.aborted === !0 ? n("aborted", "Key resolution was cancelled") : s;
282
+ let s = await importFrom(a, o.value, n.algorithm);
283
+ return r?.aborted === !0 ? e("aborted", "Key resolution was cancelled") : s;
286
284
  }
287
- return async (e) => {
288
- if (e.signal?.aborted === !0) return n("aborted", "Key resolution was cancelled");
289
- let t = await currentSnapshot(e.signal);
290
- return t.ok ? await select(t.value, {
291
- algorithm: e.algorithm,
292
- ...e.kid === void 0 ? {} : { kid: e.kid }
293
- }, e.signal) : t;
285
+ return async (t) => {
286
+ if (t.signal?.aborted === !0) return e("aborted", "Key resolution was cancelled");
287
+ let n = await currentSnapshot(t.signal);
288
+ return n.ok ? await select(n.value, {
289
+ algorithm: t.algorithm,
290
+ ...t.kid === void 0 ? {} : { kid: t.kid }
291
+ }, t.signal) : n;
294
292
  };
295
293
  }
296
294
  export { createRemoteJwksKeyResolver };
@@ -1 +1 @@
1
- {"version":3,"file":"remote-jwks.js","names":["ABORTED","DEFAULTS","REDIRECT_STATUSES","LOOPBACK_HOSTS","url","resolved","value","fallback","throwMicro509Error","name","config","maxRedirects","maxTtlMs","cooldownMs","target","init","destination","from","joseFailure","message","status","headers","directives","directive","date","apparentAge","receivedAt","reportedAge","transit","requestedAt","age","maxAge","lifetime","match","expires","tooLarge","maxBytes","declared","response","successResult","reader","chunks","total","signal","done","body","offset","chunk","location","redirects","jwks","parseJwks","hop","entry","imported","fetched","carried","previous","TIMED_OUT","settings","snapshot","refresh","lastAttemptAt","controller","previousAttemptAt","timer","deadline","resolve","work","tracked","outcome","joined","settled","key","cached","current","pending","importJwkEntry","loaded","source","selected","selectJwk","selector","reloaded","request"],"sources":["../../src/jose/remote-jwks.ts"],"sourcesContent":["/**\n * Opt-in remote JWK Set resolution. A resolver is bound to one trusted JWKS URL from caller\n * configuration and keeps its own cache, so two issuers never share keys. Importing this module\n * performs no request; only a verification that reaches the resolver can.\n *\n * @module\n */\n\nimport type { JoseErrorResult, JoseResult, KeyResolutionErrorCode } from '#micro509/jose/errors';\nimport { joseFailure } from '#micro509/jose/errors';\nimport type { JwkSelector, Jwks, RsaJwkEntry } from '#micro509/jose/jwks';\nimport { importJwkEntry, parseJwks, selectJwk } from '#micro509/jose/jwks';\nimport type { JwsKeyRequest, JwsKeyResolver } from '#micro509/jose/jws';\nimport { successResult, throwMicro509Error } from '#micro509/result/result';\n\n/** The request {@linkcode JwksTransport} must issue. */\nexport interface JwksRequestInit {\n\t/** Always `GET`. */\n\treadonly method: 'GET';\n\t/** Always `manual`: the resolver validates every redirect destination itself. */\n\treadonly redirect: 'manual';\n\t/** Always `omit`. */\n\treadonly credentials: 'omit';\n\t/** Always `no-store`: each resolver refresh must reach the issuer, bypassing the HTTP cache. */\n\treadonly cache: 'no-store';\n\t/** Configured request headers. Withheld from any origin other than the configured URL's. */\n\treadonly headers: Readonly<Record<string, string>>;\n\t/** Aborts on timeout, cancellation or when no verification still waits for the response. */\n\treadonly signal: AbortSignal;\n}\n\n/**\n * Performs one HTTP request. `fetch` satisfies this type. Supply another to route through a proxy,\n * apply egress or DNS controls, or serve fixtures; the transport sees only URLs the resolver\n * already validated.\n */\nexport type JwksTransport = (url: string, init: JwksRequestInit) => Promise<Response>;\n\n/** Redirect handling for a remote JWK Set. By default redirects are refused. */\nexport interface RemoteJwksRedirectPolicy {\n\t/** Maximum redirects followed per fetch. */\n\treadonly maxRedirects: number;\n\t/**\n\t * Approves a redirect destination. Default: same origin as the hop it came from. The scheme\n\t * rule applies first: `https`, or `http` for a loopback host.\n\t */\n\treadonly allow?: (destination: URL, from: URL) => boolean;\n}\n\n/** Configuration of {@linkcode createRemoteJwksKeyResolver}. */\nexport interface RemoteJwksConfig {\n\t/** The trusted JWKS URL. `https`, or `http` for a loopback host. Never taken from a token. */\n\treadonly url: string | URL;\n\t/** Request transport. Default: `globalThis.fetch`. */\n\treadonly transport?: JwksTransport;\n\t/** Request headers, sent only to the configured URL's origin. */\n\treadonly headers?: Readonly<Record<string, string>>;\n\t/** Whole-request deadline in milliseconds, response body included. Default `5000`. */\n\treadonly timeoutMs?: number;\n\t/** Maximum response body in bytes, enforced while streaming. Default `65536`. */\n\treadonly maxResponseBytes?: number;\n\t/** Maximum keys in the set. Default `32`. */\n\treadonly maxKeys?: number;\n\t/** Redirect handling. Default: refuse every redirect. */\n\treadonly redirects?: RemoteJwksRedirectPolicy;\n\t/** Freshness applied when the response states none, in milliseconds. Default `600000`. */\n\treadonly defaultTtlMs?: number;\n\t/** Longest freshness the resolver will keep a response for, in milliseconds. Default `86400000`. */\n\treadonly maxTtlMs?: number;\n\t/**\n\t * Minimum interval between the starts of two fetches, in milliseconds. It bounds how often\n\t * unknown `kid` values, expired responses and failures can cause a request, and does not\n\t * lengthen how long a response stays fresh. Default `30000`.\n\t */\n\treadonly cooldownMs?: number;\n\t/** The clock in milliseconds since the epoch. Default `Date.now`. */\n\treadonly now?: () => number;\n}\n\n/** Codes {@linkcode createRemoteJwksKeyResolver} throws for unusable configuration. */\nexport type RemoteJwksConfigErrorCode = 'invalid_remote_jwks_config';\n\ntype FetchFailureCode = 'jwks_unavailable' | 'jwks_malformed';\n\ninterface Snapshot {\n\treadonly jwks: Jwks;\n\treadonly expiresAt: number;\n\treadonly imported: Map<string, Promise<JoseResult<CryptoKey, 'key_unsuitable'>>>;\n}\n\ntype RefreshOutcome =\n\t| { readonly kind: 'fresh'; readonly snapshot: Snapshot }\n\t| { readonly kind: 'failed'; readonly failure: JoseErrorResult<FetchFailureCode> }\n\t| { readonly kind: 'abandoned' };\n\ninterface Refresh {\n\treadonly promise: Promise<RefreshOutcome>;\n\treadonly controller: AbortController;\n\treadonly startedAt: number;\n\treadonly previousAttemptAt: number | undefined;\n\twaiters: number;\n}\n\nconst ABORTED: unique symbol = Symbol('micro509.jose.aborted');\n\nconst DEFAULTS = {\n\ttimeoutMs: 5000,\n\tmaxResponseBytes: 65_536,\n\tmaxKeys: 32,\n\tdefaultTtlMs: 600_000,\n\tmaxTtlMs: 86_400_000,\n\tcooldownMs: 30_000,\n} as const;\n\nconst REDIRECT_STATUSES: ReadonlySet<number> = new Set([301, 302, 303, 307, 308]);\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nfunction isPermittedUrl(url: URL): boolean {\n\treturn (\n\t\turl.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))\n\t);\n}\n\nfunction positiveInteger(value: number | undefined, fallback: number, name: string): number {\n\tconst resolved = value ?? fallback;\n\tif (!Number.isSafeInteger(resolved) || resolved <= 0) {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', `${name} must be a positive integer`);\n\t}\n\treturn resolved;\n}\n\ninterface ResolvedConfig {\n\treadonly url: URL;\n\treadonly transport: JwksTransport;\n\treadonly headers: Readonly<Record<string, string>>;\n\treadonly timeoutMs: number;\n\treadonly maxResponseBytes: number;\n\treadonly maxKeys: number;\n\treadonly maxRedirects: number;\n\treadonly allowRedirect: (destination: URL, from: URL) => boolean;\n\treadonly defaultTtlMs: number;\n\treadonly maxTtlMs: number;\n\treadonly cooldownMs: number;\n\treadonly now: () => number;\n}\n\nfunction resolveConfig(config: RemoteJwksConfig): ResolvedConfig {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(config.url);\n\t} catch {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', 'url is not an absolute URL');\n\t}\n\tif (!isPermittedUrl(url)) {\n\t\treturn throwMicro509Error(\n\t\t\t'invalid_remote_jwks_config',\n\t\t\t'url must use https, or http on a loopback host',\n\t\t);\n\t}\n\tif (url.username !== '' || url.password !== '') {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', 'url must not embed credentials');\n\t}\n\tconst maxRedirects = config.redirects?.maxRedirects ?? 0;\n\tif (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0 || maxRedirects > 10) {\n\t\treturn throwMicro509Error(\n\t\t\t'invalid_remote_jwks_config',\n\t\t\t'maxRedirects must be an integer from 0 to 10',\n\t\t);\n\t}\n\tconst maxTtlMs = positiveInteger(config.maxTtlMs, DEFAULTS.maxTtlMs, 'maxTtlMs');\n\tconst cooldownMs = positiveInteger(config.cooldownMs, DEFAULTS.cooldownMs, 'cooldownMs');\n\treturn {\n\t\turl,\n\t\ttransport: config.transport ?? ((target, init) => globalThis.fetch(target, init)),\n\t\theaders: { ...config.headers },\n\t\ttimeoutMs: positiveInteger(config.timeoutMs, DEFAULTS.timeoutMs, 'timeoutMs'),\n\t\tmaxResponseBytes: positiveInteger(\n\t\t\tconfig.maxResponseBytes,\n\t\t\tDEFAULTS.maxResponseBytes,\n\t\t\t'maxResponseBytes',\n\t\t),\n\t\tmaxKeys: positiveInteger(config.maxKeys, DEFAULTS.maxKeys, 'maxKeys'),\n\t\tmaxRedirects,\n\t\tallowRedirect:\n\t\t\tconfig.redirects?.allow ?? ((destination, from) => destination.origin === from.origin),\n\t\tdefaultTtlMs: positiveInteger(config.defaultTtlMs, DEFAULTS.defaultTtlMs, 'defaultTtlMs'),\n\t\tmaxTtlMs,\n\t\tcooldownMs,\n\t\tnow: config.now ?? Date.now,\n\t};\n}\n\nfunction unavailable(message: string, status?: number): JoseErrorResult<'jwks_unavailable'> {\n\treturn joseFailure('jwks_unavailable', message, status === undefined ? undefined : { status });\n}\n\nconst NOT_A_NUMBER = Number.NaN;\n\nfunction secondsHeader(headers: Headers, name: string): number {\n\tconst value = headers.get(name);\n\treturn value !== null && /^\\d{1,10}$/.test(value) ? Number(value) * 1000 : NOT_A_NUMBER;\n}\n\n/**\n * Remaining freshness in milliseconds, never below zero and never above `maxTtlMs`.\n *\n * The lifetime is `Cache-Control: max-age`, else `Expires` less `Date`, else `defaultTtlMs`\n * (RFC 9111 §4.2.1); `no-store`, `no-cache` and unusable values give none. The response age is the\n * larger of the apparent age from `Date` and the `Age` header plus the transit delay\n * (RFC 9111 §4.2.3).\n */\nfunction freshnessMs(\n\theaders: Headers,\n\trequestedAt: number,\n\treceivedAt: number,\n\tconfig: ResolvedConfig,\n): number {\n\tconst directives = (headers.get('cache-control') ?? '')\n\t\t.split(',')\n\t\t.map((directive) => directive.trim().toLowerCase())\n\t\t.filter((directive) => directive.length > 0);\n\tif (directives.includes('no-store') || directives.includes('no-cache')) return 0;\n\tconst date = Date.parse(headers.get('date') ?? '');\n\tconst apparentAge = Number.isNaN(date) ? 0 : Math.max(0, receivedAt - date);\n\tconst reportedAge = secondsHeader(headers, 'age');\n\tconst transit = Math.max(0, receivedAt - requestedAt);\n\tconst age = Math.max(apparentAge, (Number.isNaN(reportedAge) ? 0 : reportedAge) + transit);\n\tconst maxAge = directives.find((directive) => directive.startsWith('max-age'));\n\tlet lifetime = config.defaultTtlMs;\n\tif (maxAge !== undefined) {\n\t\tconst match = /^max-age=(\"?)(\\d{1,10})\\1$/.exec(maxAge);\n\t\tlifetime = match?.[2] === undefined ? 0 : Number(match[2]) * 1000;\n\t} else if (headers.has('expires')) {\n\t\tconst expires = Date.parse(headers.get('expires') ?? '');\n\t\tlifetime = Number.isNaN(expires) ? 0 : expires - (Number.isNaN(date) ? receivedAt : date);\n\t}\n\treturn Math.min(config.maxTtlMs, Math.max(0, lifetime - age));\n}\n\ntype BodyResult = JoseResult<Uint8Array, 'jwks_unavailable' | 'jwks_malformed'>;\n\nasync function readBounded(\n\tresponse: Response,\n\tmaxBytes: number,\n\tsignal: AbortSignal,\n): Promise<BodyResult> {\n\tconst tooLarge = joseFailure('jwks_malformed', `The JWKS response exceeds ${maxBytes} bytes`);\n\tconst declared = response.headers.get('content-length');\n\tif (declared !== null && /^\\d+$/.test(declared) && Number(declared) > maxBytes) {\n\t\tawait response.body?.cancel();\n\t\treturn tooLarge;\n\t}\n\tif (response.body === null) return successResult(new Uint8Array(0));\n\tconst reader = response.body.getReader();\n\tconst release = (): void => {\n\t\treader.cancel().catch(() => undefined);\n\t};\n\tsignal.addEventListener('abort', release, { once: true });\n\ttry {\n\t\tconst chunks: Uint8Array[] = [];\n\t\tlet total = 0;\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (signal.aborted) return unavailable('The JWKS request was cancelled');\n\t\t\tif (done) break;\n\t\t\ttotal += value.byteLength;\n\t\t\tif (total > maxBytes) {\n\t\t\t\trelease();\n\t\t\t\treturn tooLarge;\n\t\t\t}\n\t\t\tchunks.push(value);\n\t\t}\n\t\tconst body = new Uint8Array(total);\n\t\tlet offset = 0;\n\t\tfor (const chunk of chunks) {\n\t\t\tbody.set(chunk, offset);\n\t\t\toffset += chunk.byteLength;\n\t\t}\n\t\treturn successResult(body);\n\t} finally {\n\t\tsignal.removeEventListener('abort', release);\n\t}\n}\n\ninterface Fetched {\n\treadonly jwks: Jwks;\n\treadonly expiresAt: number;\n}\n\nfunction nextHop(\n\tconfig: ResolvedConfig,\n\tfrom: URL,\n\tresponse: Response,\n\tredirects: number,\n): JoseResult<URL, 'jwks_unavailable'> {\n\tconst location = response.headers.get('location');\n\tif (redirects >= config.maxRedirects || location === null) {\n\t\treturn unavailable('The JWKS endpoint redirected', response.status);\n\t}\n\tlet destination: URL;\n\ttry {\n\t\tdestination = new URL(location, from);\n\t} catch {\n\t\treturn unavailable('The JWKS redirect target is not a URL', response.status);\n\t}\n\tif (\n\t\t!isPermittedUrl(destination) ||\n\t\tdestination.username !== '' ||\n\t\tdestination.password !== '' ||\n\t\t!config.allowRedirect(destination, from)\n\t) {\n\t\treturn unavailable('The JWKS redirect target is not permitted', response.status);\n\t}\n\treturn successResult(destination);\n}\n\nasync function readJwks(\n\tconfig: ResolvedConfig,\n\tresponse: Response,\n\trequestedAt: number,\n\tsignal: AbortSignal,\n): Promise<JoseResult<Fetched, FetchFailureCode>> {\n\tif (response.status !== 200) {\n\t\tawait response.body?.cancel();\n\t\treturn unavailable('The JWKS endpoint did not answer 200', response.status);\n\t}\n\tconst receivedAt = config.now();\n\tconst body = await readBounded(response, config.maxResponseBytes, signal);\n\tif (!body.ok) return body;\n\tconst jwks = parseJwks(body.value, {\n\t\tmaxBytes: config.maxResponseBytes,\n\t\tmaxKeys: config.maxKeys,\n\t});\n\tif (!jwks.ok) return joseFailure('jwks_malformed', jwks.message);\n\treturn successResult({\n\t\tjwks: jwks.value,\n\t\texpiresAt: receivedAt + freshnessMs(response.headers, requestedAt, receivedAt, config),\n\t});\n}\n\nasync function fetchJwks(\n\tconfig: ResolvedConfig,\n\tsignal: AbortSignal,\n\trequestedAt: number,\n): Promise<JoseResult<Fetched, FetchFailureCode>> {\n\tlet url = config.url;\n\tfor (let redirects = 0; ; redirects++) {\n\t\tconst response = await config.transport(url.href, {\n\t\t\tmethod: 'GET',\n\t\t\tredirect: 'manual',\n\t\t\tcredentials: 'omit',\n\t\t\tcache: 'no-store',\n\t\t\theaders: url.origin === config.url.origin ? config.headers : {},\n\t\t\tsignal,\n\t\t});\n\t\tif (signal.aborted) {\n\t\t\tawait response.body?.cancel();\n\t\t\treturn unavailable('The JWKS request was cancelled');\n\t\t}\n\t\tif (response.type === 'opaqueredirect') {\n\t\t\treturn unavailable('The runtime hides redirects, so they cannot be validated');\n\t\t}\n\t\tif (!REDIRECT_STATUSES.has(response.status)) {\n\t\t\treturn await readJwks(config, response, requestedAt, signal);\n\t\t}\n\t\tawait response.body?.cancel();\n\t\tconst hop = nextHop(config, url, response, redirects);\n\t\tif (!hop.ok) return hop;\n\t\turl = hop.value;\n\t}\n}\n\nfunction entryKey(entry: RsaJwkEntry): string {\n\treturn `${entry.n}.${entry.e}`;\n}\n\nfunction carryOver(fetched: Fetched, previous: Snapshot | undefined): Snapshot {\n\tconst imported = new Map<string, Promise<JoseResult<CryptoKey, 'key_unsuitable'>>>();\n\tfor (const entry of fetched.jwks.keys) {\n\t\tconst carried = entry.kind === 'rsa' ? previous?.imported.get(entryKey(entry)) : undefined;\n\t\tif (entry.kind === 'rsa' && carried !== undefined) imported.set(entryKey(entry), carried);\n\t}\n\treturn { jwks: fetched.jwks, expiresAt: fetched.expiresAt, imported };\n}\n\nconst TIMED_OUT: unique symbol = Symbol('micro509.jose.timedOut');\n\n/**\n * Creates a key resolver that reads a JWK Set from one trusted URL.\n *\n * Behaviour, per resolver:\n *\n * - The first verification fetches the set. Later ones reuse it while fresh. Freshness is the\n * remaining lifetime from `Cache-Control: max-age`, else `Expires`, else `defaultTtlMs`, less the\n * response age (the larger of the apparent age from `Date` and `Age` plus the transit delay),\n * capped at `maxTtlMs`. `no-store`, `no-cache` and a lifetime already spent leave none: the set\n * serves the verification that fetched it and nothing after. No heuristic freshness is applied.\n * - A set that is no longer fresh is never used, whether or not a refresh succeeds. There is no\n * stale-if-error. A refresh that fails while the cached set is still fresh keeps that set until\n * it expires.\n * - Refreshes are separate from freshness: after any attempt the next one waits `cooldownMs`.\n * Within that interval a token whose `kid` is absent gets `key_not_found`, and a token that\n * needs a set that is no longer fresh gets `jwks_unavailable`. Concurrent verifications share\n * a single request, and unknown `kid` values are never cached.\n * - A refresh replaces the whole set, so a rotated-out key stops verifying as soon as the new\n * set is read. Rotation must therefore introduce a new `kid`.\n * - The whole request, response body included, is bounded by `timeoutMs` and enforced even when\n * the transport ignores the abort signal. Redirects, bytes and keys are bounded by `redirects`,\n * `maxResponseBytes` and `maxKeys`. No retry happens inside a fetch. Cancelling the last waiting\n * verification aborts the request, and a response that finishes afterwards is discarded.\n * - Request headers go only to the configured origin. `jku`, `x5u` and `jwk` headers are never\n * used.\n *\n * Throws a `ResultError` coded {@linkcode RemoteJwksConfigErrorCode} for unusable configuration.\n * Redirect destinations, and the addresses a hostname resolves to, are limited by `redirects` and\n * the transport; this module cannot see DNS answers, and browsers hide redirect targets.\n */\nexport function createRemoteJwksKeyResolver(config: RemoteJwksConfig): JwsKeyResolver {\n\tconst settings = resolveConfig(config);\n\tlet snapshot: Snapshot | undefined;\n\tlet refresh: Refresh | undefined;\n\tlet lastAttemptAt: number | undefined;\n\n\tfunction startRefresh(): Refresh {\n\t\tconst controller = new AbortController();\n\t\tconst requestedAt = settings.now();\n\t\tconst previousAttemptAt = lastAttemptAt;\n\t\tconst previous = snapshot;\n\t\tlastAttemptAt = requestedAt;\n\n\t\tasync function run(): Promise<RefreshOutcome> {\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst deadline = new Promise<typeof TIMED_OUT>((resolve) => {\n\t\t\t\ttimer = setTimeout(() => resolve(TIMED_OUT), settings.timeoutMs);\n\t\t\t});\n\t\t\tconst work = fetchJwks(settings, controller.signal, requestedAt);\n\t\t\twork.catch(() => undefined);\n\t\t\ttry {\n\t\t\t\tconst fetched = await Promise.race([work, deadline]);\n\t\t\t\tif (fetched === TIMED_OUT) {\n\t\t\t\t\tcontroller.abort();\n\t\t\t\t\treturn { kind: 'failed', failure: unavailable('The JWKS request timed out') };\n\t\t\t\t}\n\t\t\t\tif (!fetched.ok) return { kind: 'failed', failure: fetched };\n\t\t\t\treturn { kind: 'fresh', snapshot: carryOver(fetched.value, previous) };\n\t\t\t} catch {\n\t\t\t\treturn controller.signal.aborted\n\t\t\t\t\t? { kind: 'abandoned' }\n\t\t\t\t\t: { kind: 'failed', failure: unavailable('The JWKS request failed') };\n\t\t\t} finally {\n\t\t\t\tclearTimeout(timer);\n\t\t\t}\n\t\t}\n\n\t\tconst tracked: Promise<RefreshOutcome> = run()\n\t\t\t.then((outcome): RefreshOutcome => {\n\t\t\t\tif (refresh?.promise !== tracked) return { kind: 'abandoned' };\n\t\t\t\tif (outcome.kind === 'fresh') snapshot = outcome.snapshot;\n\t\t\t\treturn outcome;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tif (refresh?.promise === tracked) refresh = undefined;\n\t\t\t});\n\t\treturn {\n\t\t\tpromise: tracked,\n\t\t\tcontroller,\n\t\t\tstartedAt: requestedAt,\n\t\t\tpreviousAttemptAt,\n\t\t\twaiters: 0,\n\t\t};\n\t}\n\n\tasync function awaitRefresh(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<RefreshOutcome | typeof ABORTED> {\n\t\tif (signal?.aborted === true) return ABORTED;\n\t\trefresh ??= startRefresh();\n\t\tconst joined = refresh;\n\t\tjoined.waiters++;\n\t\tif (signal === undefined) return await joined.promise;\n\t\treturn await new Promise<RefreshOutcome | typeof ABORTED>((resolve) => {\n\t\t\tlet settled = false;\n\t\t\tconst finish = (): void => {\n\t\t\t\tsettled = true;\n\t\t\t\tsignal.removeEventListener('abort', onAbort);\n\t\t\t};\n\t\t\tconst onAbort = (): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tfinish();\n\t\t\t\tjoined.waiters--;\n\t\t\t\tif (joined.waiters === 0) {\n\t\t\t\t\tif (refresh === joined) refresh = undefined;\n\t\t\t\t\tif (lastAttemptAt === joined.startedAt) lastAttemptAt = joined.previousAttemptAt;\n\t\t\t\t\tjoined.controller.abort();\n\t\t\t\t}\n\t\t\t\tresolve(ABORTED);\n\t\t\t};\n\t\t\tsignal.addEventListener('abort', onAbort, { once: true });\n\t\t\tif (signal.aborted) onAbort();\n\t\t\tvoid joined.promise.then((outcome) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tfinish();\n\t\t\t\tresolve(outcome);\n\t\t\t});\n\t\t});\n\t}\n\n\tfunction refreshAllowed(): boolean {\n\t\tif (refresh !== undefined || lastAttemptAt === undefined) return true;\n\t\treturn settings.now() - lastAttemptAt >= settings.cooldownMs;\n\t}\n\n\tasync function obtain(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<Snapshot | undefined, FetchFailureCode | 'aborted'>> {\n\t\tif (!refreshAllowed()) return successResult(undefined);\n\t\tconst outcome = await awaitRefresh(signal);\n\t\tif (outcome === ABORTED || outcome.kind === 'abandoned') {\n\t\t\treturn joseFailure('aborted', 'Key resolution was cancelled');\n\t\t}\n\t\tif (outcome.kind === 'failed') return outcome.failure;\n\t\treturn successResult(outcome.snapshot);\n\t}\n\n\tasync function importFrom(\n\t\tcurrent: Snapshot,\n\t\tentry: RsaJwkEntry,\n\t): Promise<JoseResult<CryptoKey, 'key_unsuitable'>> {\n\t\tconst key = entryKey(entry);\n\t\tconst cached = current.imported.get(key);\n\t\tif (cached !== undefined) return await cached;\n\t\tconst pending = importJwkEntry(entry);\n\t\tcurrent.imported.set(key, pending);\n\t\treturn await pending;\n\t}\n\n\tasync function currentSnapshot(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<Snapshot, FetchFailureCode | 'aborted'>> {\n\t\tif (snapshot !== undefined && settings.now() < snapshot.expiresAt) {\n\t\t\treturn successResult(snapshot);\n\t\t}\n\t\tsnapshot = undefined;\n\t\tconst loaded = await obtain(signal);\n\t\tif (!loaded.ok) return loaded;\n\t\treturn loaded.value === undefined\n\t\t\t? unavailable('The JWKS endpoint is in cooldown')\n\t\t\t: successResult(loaded.value);\n\t}\n\n\tasync function select(\n\t\tcurrent: Snapshot,\n\t\tselector: JwkSelector,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<CryptoKey, KeyResolutionErrorCode>> {\n\t\tlet source = current;\n\t\tlet selected = selectJwk(source.jwks, selector);\n\t\tif (!selected.ok && selected.code === 'key_not_found') {\n\t\t\tconst reloaded = await obtain(signal);\n\t\t\tif (!reloaded.ok) return reloaded;\n\t\t\tif (reloaded.value !== undefined) {\n\t\t\t\tsource = reloaded.value;\n\t\t\t\tselected = selectJwk(source.jwks, selector);\n\t\t\t}\n\t\t}\n\t\tif (!selected.ok) return selected;\n\t\tconst key = await importFrom(source, selected.value);\n\t\treturn signal?.aborted === true ? joseFailure('aborted', 'Key resolution was cancelled') : key;\n\t}\n\n\treturn async (request: JwsKeyRequest) => {\n\t\tif (request.signal?.aborted === true) {\n\t\t\treturn joseFailure('aborted', 'Key resolution was cancelled');\n\t\t}\n\t\tconst current = await currentSnapshot(request.signal);\n\t\tif (!current.ok) return current;\n\t\treturn await select(\n\t\t\tcurrent.value,\n\t\t\t{ algorithm: request.algorithm, ...(request.kid === undefined ? {} : { k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a,KAAA,KAAaD,EAAS,IAAI,IAAIC,EAAS,WACvD,OAAOrB,EAAcqB,CAAQ;EAE9B,IAAW,KAAA;EACX,IAAMkB,IAAS,MAAM,OAAOnC,CAAM;EAElC,OADKmC,EAAO,KACLA,EAAO,UAAU,KAAA,IACrB,YAAY,kCAAkC,IAC9CvC,EAAcuC,EAAO,KAAK,IAHNA;CAIxB;CAEA,eAAe,OACd,GACA,GACA,GACyD;EACzD,IAAIC,IAASJ,GACTK,IAAWC,EAAUF,EAAO,MAAMG,CAAQ;EAC9C,IAAI,CAACF,EAAS,MAAMA,EAAS,SAAS,iBAAiB;GACtD,IAAMG,IAAW,MAAM,OAAOxC,CAAM;GACpC,IAAI,CAACwC,EAAS,IAAI,OAAOA;GACzB,AAAIA,EAAS,UAAU,KAAA,MACtB,IAASA,EAAS,OAClB,IAAWF,EAAUF,EAAO,MAAMG,CAAQ;EAE5C;EACA,IAAI,CAACF,EAAS,IAAI,OAAOA;EACzB,IAAMP,IAAM,MAAM,WAAWM,GAAQC,EAAS,KAAK;EACnD,OAAOrC,GAAQ,YAAY,KAAOzB,EAAY,WAAW,8BAA8B,IAAIuD;CAC5F;CAEA,OAAO,OAAO,MAA2B;EACxC,IAAIW,EAAQ,QAAQ,YAAY,IAC/B,OAAOlE,EAAY,WAAW,8BAA8B;EAE7D,IAAMyD,IAAU,MAAM,gBAAgBS,EAAQ,MAAM;EAEpD,OADKT,EAAQ,KACN,MAAM,OACZA,EAAQ,OACR;GAAE,WAAWS,EAAQ;GAAW,GAAIA,EAAQ,QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,KAAKA,EAAQ,IAAI;EAAG,GAC3FA,EAAQ,MACT,IALwBT;CAMzB;AACD"}
1
+ {"version":3,"file":"remote-jwks.js","names":["joseFailure","importJwkEntry","jwkEntryCacheKey","parseJwks","selectJwk","JWS_ALGORITHMS","successResult","throwMicro509Error","ABORTED","DEFAULTS","REDIRECT_STATUSES","LOOPBACK_HOSTS","url","value","fallback","name","resolved","config","maxRedirects","maxTtlMs","cooldownMs","target","init","destination","from","message","status","headers","requestedAt","receivedAt","directives","directive","date","apparentAge","reportedAge","transit","age","maxAge","lifetime","match","expires","response","maxBytes","signal","tooLarge","declared","reader","chunks","total","done","body","offset","chunk","redirects","location","jwks","hop","fetched","previous","imported","entry","algorithm","key","carried","TIMED_OUT","settings","snapshot","refresh","lastAttemptAt","controller","previousAttemptAt","timer","deadline","resolve","work","tracked","outcome","joined","settled","current","cached","pending","loaded","selector","source","selected","reloaded","request"],"sources":["../../src/jose/remote-jwks.ts"],"sourcesContent":["/**\n * Opt-in remote JWK Set resolution. A resolver is bound to one trusted JWKS URL from caller\n * configuration and keeps its own cache, so two issuers never share keys. Importing this module\n * performs no request; only a verification that reaches the resolver can.\n *\n * @module\n */\n\nimport type { JoseErrorResult, JoseResult, KeyResolutionErrorCode } from '#micro509/jose/errors';\nimport { joseFailure } from '#micro509/jose/errors';\nimport type { JwkSelector, Jwks, SupportedJwkEntry } from '#micro509/jose/jwks';\nimport { importJwkEntry, jwkEntryCacheKey, parseJwks, selectJwk } from '#micro509/jose/jwks';\nimport type { JwsAlgorithm, JwsKeyRequest, JwsKeyResolver } from '#micro509/jose/jws';\nimport { JWS_ALGORITHMS } from '#micro509/jose/jws';\nimport { successResult, throwMicro509Error } from '#micro509/result/result';\n\n/** The request {@linkcode JwksTransport} must issue. */\nexport interface JwksRequestInit {\n\t/** Always `GET`. */\n\treadonly method: 'GET';\n\t/** Always `manual`: the resolver validates every redirect destination itself. */\n\treadonly redirect: 'manual';\n\t/** Always `omit`. */\n\treadonly credentials: 'omit';\n\t/** Always `no-store`: each resolver refresh must reach the issuer, bypassing the HTTP cache. */\n\treadonly cache: 'no-store';\n\t/** Configured request headers. Withheld from any origin other than the configured URL's. */\n\treadonly headers: Readonly<Record<string, string>>;\n\t/** Aborts on timeout, cancellation or when no verification still waits for the response. */\n\treadonly signal: AbortSignal;\n}\n\n/**\n * Performs one HTTP request. `fetch` satisfies this type. Supply another to route through a proxy,\n * apply egress or DNS controls, or serve fixtures; the transport sees only URLs the resolver\n * already validated.\n */\nexport type JwksTransport = (url: string, init: JwksRequestInit) => Promise<Response>;\n\n/** Redirect handling for a remote JWK Set. By default redirects are refused. */\nexport interface RemoteJwksRedirectPolicy {\n\t/** Maximum redirects followed per fetch. */\n\treadonly maxRedirects: number;\n\t/**\n\t * Approves a redirect destination. Default: same origin as the hop it came from. The scheme\n\t * rule applies first: `https`, or `http` for a loopback host.\n\t */\n\treadonly allow?: (destination: URL, from: URL) => boolean;\n}\n\n/** Configuration of {@linkcode createRemoteJwksKeyResolver}. */\nexport interface RemoteJwksConfig {\n\t/** The trusted JWKS URL. `https`, or `http` for a loopback host. Never taken from a token. */\n\treadonly url: string | URL;\n\t/** Request transport. Default: `globalThis.fetch`. */\n\treadonly transport?: JwksTransport;\n\t/** Request headers, sent only to the configured URL's origin. */\n\treadonly headers?: Readonly<Record<string, string>>;\n\t/** Whole-request deadline in milliseconds, response body included. Default `5000`. */\n\treadonly timeoutMs?: number;\n\t/** Maximum response body in bytes, enforced while streaming. Default `65536`. */\n\treadonly maxResponseBytes?: number;\n\t/** Maximum keys in the set. Default `32`. */\n\treadonly maxKeys?: number;\n\t/** Redirect handling. Default: refuse every redirect. */\n\treadonly redirects?: RemoteJwksRedirectPolicy;\n\t/** Freshness applied when the response states none, in milliseconds. Default `600000`. */\n\treadonly defaultTtlMs?: number;\n\t/** Longest freshness the resolver will keep a response for, in milliseconds. Default `86400000`. */\n\treadonly maxTtlMs?: number;\n\t/**\n\t * Minimum interval between the starts of two fetches, in milliseconds. It bounds how often\n\t * unknown `kid` values, expired responses and failures can cause a request, and does not\n\t * lengthen how long a response stays fresh. Default `30000`.\n\t */\n\treadonly cooldownMs?: number;\n\t/** The clock in milliseconds since the epoch. Default `Date.now`. */\n\treadonly now?: () => number;\n}\n\n/** Codes {@linkcode createRemoteJwksKeyResolver} throws for unusable configuration. */\nexport type RemoteJwksConfigErrorCode = 'invalid_remote_jwks_config';\n\ntype FetchFailureCode = 'jwks_unavailable' | 'jwks_malformed';\n\ninterface Snapshot {\n\treadonly jwks: Jwks;\n\treadonly expiresAt: number;\n\treadonly imported: Map<string, Promise<JoseResult<CryptoKey, 'key_unsuitable'>>>;\n}\n\ntype RefreshOutcome =\n\t| { readonly kind: 'fresh'; readonly snapshot: Snapshot }\n\t| { readonly kind: 'failed'; readonly failure: JoseErrorResult<FetchFailureCode> }\n\t| { readonly kind: 'abandoned' };\n\ninterface Refresh {\n\treadonly promise: Promise<RefreshOutcome>;\n\treadonly controller: AbortController;\n\treadonly startedAt: number;\n\treadonly previousAttemptAt: number | undefined;\n\twaiters: number;\n}\n\nconst ABORTED: unique symbol = Symbol('micro509.jose.aborted');\n\nconst DEFAULTS = {\n\ttimeoutMs: 5000,\n\tmaxResponseBytes: 65_536,\n\tmaxKeys: 32,\n\tdefaultTtlMs: 600_000,\n\tmaxTtlMs: 86_400_000,\n\tcooldownMs: 30_000,\n} as const;\n\nconst REDIRECT_STATUSES: ReadonlySet<number> = new Set([301, 302, 303, 307, 308]);\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nfunction isPermittedUrl(url: URL): boolean {\n\treturn (\n\t\turl.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))\n\t);\n}\n\nfunction positiveInteger(value: number | undefined, fallback: number, name: string): number {\n\tconst resolved = value ?? fallback;\n\tif (!Number.isSafeInteger(resolved) || resolved <= 0) {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', `${name} must be a positive integer`);\n\t}\n\treturn resolved;\n}\n\ninterface ResolvedConfig {\n\treadonly url: URL;\n\treadonly transport: JwksTransport;\n\treadonly headers: Readonly<Record<string, string>>;\n\treadonly timeoutMs: number;\n\treadonly maxResponseBytes: number;\n\treadonly maxKeys: number;\n\treadonly maxRedirects: number;\n\treadonly allowRedirect: (destination: URL, from: URL) => boolean;\n\treadonly defaultTtlMs: number;\n\treadonly maxTtlMs: number;\n\treadonly cooldownMs: number;\n\treadonly now: () => number;\n}\n\nfunction resolveConfig(config: RemoteJwksConfig): ResolvedConfig {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(config.url);\n\t} catch {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', 'url is not an absolute URL');\n\t}\n\tif (!isPermittedUrl(url)) {\n\t\treturn throwMicro509Error(\n\t\t\t'invalid_remote_jwks_config',\n\t\t\t'url must use https, or http on a loopback host',\n\t\t);\n\t}\n\tif (url.username !== '' || url.password !== '') {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', 'url must not embed credentials');\n\t}\n\tconst maxRedirects = config.redirects?.maxRedirects ?? 0;\n\tif (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0 || maxRedirects > 10) {\n\t\treturn throwMicro509Error(\n\t\t\t'invalid_remote_jwks_config',\n\t\t\t'maxRedirects must be an integer from 0 to 10',\n\t\t);\n\t}\n\tconst maxTtlMs = positiveInteger(config.maxTtlMs, DEFAULTS.maxTtlMs, 'maxTtlMs');\n\tconst cooldownMs = positiveInteger(config.cooldownMs, DEFAULTS.cooldownMs, 'cooldownMs');\n\treturn {\n\t\turl,\n\t\ttransport: config.transport ?? ((target, init) => globalThis.fetch(target, init)),\n\t\theaders: { ...config.headers },\n\t\ttimeoutMs: positiveInteger(config.timeoutMs, DEFAULTS.timeoutMs, 'timeoutMs'),\n\t\tmaxResponseBytes: positiveInteger(\n\t\t\tconfig.maxResponseBytes,\n\t\t\tDEFAULTS.maxResponseBytes,\n\t\t\t'maxResponseBytes',\n\t\t),\n\t\tmaxKeys: positiveInteger(config.maxKeys, DEFAULTS.maxKeys, 'maxKeys'),\n\t\tmaxRedirects,\n\t\tallowRedirect:\n\t\t\tconfig.redirects?.allow ?? ((destination, from) => destination.origin === from.origin),\n\t\tdefaultTtlMs: positiveInteger(config.defaultTtlMs, DEFAULTS.defaultTtlMs, 'defaultTtlMs'),\n\t\tmaxTtlMs,\n\t\tcooldownMs,\n\t\tnow: config.now ?? Date.now,\n\t};\n}\n\nfunction unavailable(message: string, status?: number): JoseErrorResult<'jwks_unavailable'> {\n\treturn joseFailure('jwks_unavailable', message, status === undefined ? undefined : { status });\n}\n\nconst NOT_A_NUMBER = Number.NaN;\n\nfunction secondsHeader(headers: Headers, name: string): number {\n\tconst value = headers.get(name);\n\treturn value !== null && /^\\d{1,10}$/.test(value) ? Number(value) * 1000 : NOT_A_NUMBER;\n}\n\n/**\n * Remaining freshness in milliseconds, never below zero and never above `maxTtlMs`.\n *\n * The lifetime is `Cache-Control: max-age`, else `Expires` less `Date`, else `defaultTtlMs`\n * (RFC 9111 §4.2.1); `no-store`, `no-cache` and unusable values give none. The response age is the\n * larger of the apparent age from `Date` and the `Age` header plus the transit delay\n * (RFC 9111 §4.2.3).\n */\nfunction freshnessMs(\n\theaders: Headers,\n\trequestedAt: number,\n\treceivedAt: number,\n\tconfig: ResolvedConfig,\n): number {\n\tconst directives = (headers.get('cache-control') ?? '')\n\t\t.split(',')\n\t\t.map((directive) => directive.trim().toLowerCase())\n\t\t.filter((directive) => directive.length > 0);\n\tif (directives.includes('no-store') || directives.includes('no-cache')) return 0;\n\tconst date = Date.parse(headers.get('date') ?? '');\n\tconst apparentAge = Number.isNaN(date) ? 0 : Math.max(0, receivedAt - date);\n\tconst reportedAge = secondsHeader(headers, 'age');\n\tconst transit = Math.max(0, receivedAt - requestedAt);\n\tconst age = Math.max(apparentAge, (Number.isNaN(reportedAge) ? 0 : reportedAge) + transit);\n\tconst maxAge = directives.find((directive) => directive.startsWith('max-age'));\n\tlet lifetime = config.defaultTtlMs;\n\tif (maxAge !== undefined) {\n\t\tconst match = /^max-age=(\"?)(\\d{1,10})\\1$/.exec(maxAge);\n\t\tlifetime = match?.[2] === undefined ? 0 : Number(match[2]) * 1000;\n\t} else if (headers.has('expires')) {\n\t\tconst expires = Date.parse(headers.get('expires') ?? '');\n\t\tlifetime = Number.isNaN(expires) ? 0 : expires - (Number.isNaN(date) ? receivedAt : date);\n\t}\n\treturn Math.min(config.maxTtlMs, Math.max(0, lifetime - age));\n}\n\ntype BodyResult = JoseResult<Uint8Array, 'jwks_unavailable' | 'jwks_malformed'>;\n\nasync function readBounded(\n\tresponse: Response,\n\tmaxBytes: number,\n\tsignal: AbortSignal,\n): Promise<BodyResult> {\n\tconst tooLarge = joseFailure('jwks_malformed', `The JWKS response exceeds ${maxBytes} bytes`);\n\tconst declared = response.headers.get('content-length');\n\tif (declared !== null && /^\\d+$/.test(declared) && Number(declared) > maxBytes) {\n\t\tawait response.body?.cancel();\n\t\treturn tooLarge;\n\t}\n\tif (response.body === null) return successResult(new Uint8Array(0));\n\tconst reader = response.body.getReader();\n\tconst release = (): void => {\n\t\treader.cancel().catch(() => undefined);\n\t};\n\tsignal.addEventListener('abort', release, { once: true });\n\ttry {\n\t\tconst chunks: Uint8Array[] = [];\n\t\tlet total = 0;\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (signal.aborted) return unavailable('The JWKS request was cancelled');\n\t\t\tif (done) break;\n\t\t\ttotal += value.byteLength;\n\t\t\tif (total > maxBytes) {\n\t\t\t\trelease();\n\t\t\t\treturn tooLarge;\n\t\t\t}\n\t\t\tchunks.push(value);\n\t\t}\n\t\tconst body = new Uint8Array(total);\n\t\tlet offset = 0;\n\t\tfor (const chunk of chunks) {\n\t\t\tbody.set(chunk, offset);\n\t\t\toffset += chunk.byteLength;\n\t\t}\n\t\treturn successResult(body);\n\t} finally {\n\t\tsignal.removeEventListener('abort', release);\n\t}\n}\n\ninterface Fetched {\n\treadonly jwks: Jwks;\n\treadonly expiresAt: number;\n}\n\nfunction nextHop(\n\tconfig: ResolvedConfig,\n\tfrom: URL,\n\tresponse: Response,\n\tredirects: number,\n): JoseResult<URL, 'jwks_unavailable'> {\n\tconst location = response.headers.get('location');\n\tif (redirects >= config.maxRedirects || location === null) {\n\t\treturn unavailable('The JWKS endpoint redirected', response.status);\n\t}\n\tlet destination: URL;\n\ttry {\n\t\tdestination = new URL(location, from);\n\t} catch {\n\t\treturn unavailable('The JWKS redirect target is not a URL', response.status);\n\t}\n\tif (\n\t\t!isPermittedUrl(destination) ||\n\t\tdestination.username !== '' ||\n\t\tdestination.password !== '' ||\n\t\t!config.allowRedirect(destination, from)\n\t) {\n\t\treturn unavailable('The JWKS redirect target is not permitted', response.status);\n\t}\n\treturn successResult(destination);\n}\n\nasync function readJwks(\n\tconfig: ResolvedConfig,\n\tresponse: Response,\n\trequestedAt: number,\n\tsignal: AbortSignal,\n): Promise<JoseResult<Fetched, FetchFailureCode>> {\n\tif (response.status !== 200) {\n\t\tawait response.body?.cancel();\n\t\treturn unavailable('The JWKS endpoint did not answer 200', response.status);\n\t}\n\tconst receivedAt = config.now();\n\tconst body = await readBounded(response, config.maxResponseBytes, signal);\n\tif (!body.ok) return body;\n\tconst jwks = parseJwks(body.value, {\n\t\tmaxBytes: config.maxResponseBytes,\n\t\tmaxKeys: config.maxKeys,\n\t});\n\tif (!jwks.ok) return joseFailure('jwks_malformed', jwks.message);\n\treturn successResult({\n\t\tjwks: jwks.value,\n\t\texpiresAt: receivedAt + freshnessMs(response.headers, requestedAt, receivedAt, config),\n\t});\n}\n\nasync function fetchJwks(\n\tconfig: ResolvedConfig,\n\tsignal: AbortSignal,\n\trequestedAt: number,\n): Promise<JoseResult<Fetched, FetchFailureCode>> {\n\tlet url = config.url;\n\tfor (let redirects = 0; ; redirects++) {\n\t\tconst response = await config.transport(url.href, {\n\t\t\tmethod: 'GET',\n\t\t\tredirect: 'manual',\n\t\t\tcredentials: 'omit',\n\t\t\tcache: 'no-store',\n\t\t\theaders: url.origin === config.url.origin ? config.headers : {},\n\t\t\tsignal,\n\t\t});\n\t\tif (signal.aborted) {\n\t\t\tawait response.body?.cancel();\n\t\t\treturn unavailable('The JWKS request was cancelled');\n\t\t}\n\t\tif (response.type === 'opaqueredirect') {\n\t\t\treturn unavailable('The runtime hides redirects, so they cannot be validated');\n\t\t}\n\t\tif (!REDIRECT_STATUSES.has(response.status)) {\n\t\t\treturn await readJwks(config, response, requestedAt, signal);\n\t\t}\n\t\tawait response.body?.cancel();\n\t\tconst hop = nextHop(config, url, response, redirects);\n\t\tif (!hop.ok) return hop;\n\t\turl = hop.value;\n\t}\n}\n\nfunction carryOver(fetched: Fetched, previous: Snapshot | undefined): Snapshot {\n\tconst imported = new Map<string, Promise<JoseResult<CryptoKey, 'key_unsuitable'>>>();\n\tfor (const entry of fetched.jwks.keys) {\n\t\tif (entry.kind === 'unsupported') continue;\n\t\tfor (const algorithm of JWS_ALGORITHMS) {\n\t\t\tconst key = jwkEntryCacheKey(entry, algorithm);\n\t\t\tconst carried = previous?.imported.get(key);\n\t\t\tif (carried !== undefined) imported.set(key, carried);\n\t\t}\n\t}\n\treturn { jwks: fetched.jwks, expiresAt: fetched.expiresAt, imported };\n}\n\nconst TIMED_OUT: unique symbol = Symbol('micro509.jose.timedOut');\n\n/**\n * Creates a key resolver that reads a JWK Set from one trusted URL.\n *\n * Behaviour, per resolver:\n *\n * - The first verification fetches the set. Later ones reuse it while fresh. Freshness is the\n * remaining lifetime from `Cache-Control: max-age`, else `Expires`, else `defaultTtlMs`, less the\n * response age (the larger of the apparent age from `Date` and `Age` plus the transit delay),\n * capped at `maxTtlMs`. `no-store`, `no-cache` and a lifetime already spent leave none: the set\n * serves the verification that fetched it and nothing after. No heuristic freshness is applied.\n * - A set that is no longer fresh is never used, whether or not a refresh succeeds. There is no\n * stale-if-error. A refresh that fails while the cached set is still fresh keeps that set until\n * it expires.\n * - Refreshes are separate from freshness: after any attempt the next one waits `cooldownMs`.\n * Within that interval a token whose `kid` is absent gets `key_not_found`, and a token that\n * needs a set that is no longer fresh gets `jwks_unavailable`. Concurrent verifications share\n * a single request, and unknown `kid` values are never cached.\n * - A refresh replaces the whole set, so a rotated-out key stops verifying as soon as the new\n * set is read. Rotation must therefore introduce a new `kid`.\n * - The whole request, response body included, is bounded by `timeoutMs` and enforced even when\n * the transport ignores the abort signal. Redirects, bytes and keys are bounded by `redirects`,\n * `maxResponseBytes` and `maxKeys`. No retry happens inside a fetch. Cancelling the last waiting\n * verification aborts the request, and a response that finishes afterwards is discarded.\n * - Request headers go only to the configured origin. `jku`, `x5u` and `jwk` headers are never\n * used.\n *\n * Throws a `ResultError` coded {@linkcode RemoteJwksConfigErrorCode} for unusable configuration.\n * Redirect destinations, and the addresses a hostname resolves to, are limited by `redirects` and\n * the transport; this module cannot see DNS answers, and browsers hide redirect targets.\n */\nexport function createRemoteJwksKeyResolver(config: RemoteJwksConfig): JwsKeyResolver {\n\tconst settings = resolveConfig(config);\n\tlet snapshot: Snapshot | undefined;\n\tlet refresh: Refresh | undefined;\n\tlet lastAttemptAt: number | undefined;\n\n\tfunction startRefresh(): Refresh {\n\t\tconst controller = new AbortController();\n\t\tconst requestedAt = settings.now();\n\t\tconst previousAttemptAt = lastAttemptAt;\n\t\tconst previous = snapshot;\n\t\tlastAttemptAt = requestedAt;\n\n\t\tasync function run(): Promise<RefreshOutcome> {\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst deadline = new Promise<typeof TIMED_OUT>((resolve) => {\n\t\t\t\ttimer = setTimeout(() => resolve(TIMED_OUT), settings.timeoutMs);\n\t\t\t});\n\t\t\tconst work = fetchJwks(settings, controller.signal, requestedAt);\n\t\t\twork.catch(() => undefined);\n\t\t\ttry {\n\t\t\t\tconst fetched = await Promise.race([work, deadline]);\n\t\t\t\tif (fetched === TIMED_OUT) {\n\t\t\t\t\tcontroller.abort();\n\t\t\t\t\treturn { kind: 'failed', failure: unavailable('The JWKS request timed out') };\n\t\t\t\t}\n\t\t\t\tif (!fetched.ok) return { kind: 'failed', failure: fetched };\n\t\t\t\treturn { kind: 'fresh', snapshot: carryOver(fetched.value, previous) };\n\t\t\t} catch {\n\t\t\t\treturn controller.signal.aborted\n\t\t\t\t\t? { kind: 'abandoned' }\n\t\t\t\t\t: { kind: 'failed', failure: unavailable('The JWKS request failed') };\n\t\t\t} finally {\n\t\t\t\tclearTimeout(timer);\n\t\t\t}\n\t\t}\n\n\t\tconst tracked: Promise<RefreshOutcome> = run()\n\t\t\t.then((outcome): RefreshOutcome => {\n\t\t\t\tif (refresh?.promise !== tracked) return { kind: 'abandoned' };\n\t\t\t\tif (outcome.kind === 'fresh') snapshot = outcome.snapshot;\n\t\t\t\treturn outcome;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tif (refresh?.promise === tracked) refresh = undefined;\n\t\t\t});\n\t\treturn {\n\t\t\tpromise: tracked,\n\t\t\tcontroller,\n\t\t\tstartedAt: requestedAt,\n\t\t\tpreviousAttemptAt,\n\t\t\twaiters: 0,\n\t\t};\n\t}\n\n\tasync function awaitRefresh(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<RefreshOutcome | typeof ABORTED> {\n\t\tif (signal?.aborted === true) return ABORTED;\n\t\trefresh ??= startRefresh();\n\t\tconst joined = refresh;\n\t\tjoined.waiters++;\n\t\tif (signal === undefined) return await joined.promise;\n\t\treturn await new Promise<RefreshOutcome | typeof ABORTED>((resolve) => {\n\t\t\tlet settled = false;\n\t\t\tconst finish = (): void => {\n\t\t\t\tsettled = true;\n\t\t\t\tsignal.removeEventListener('abort', onAbort);\n\t\t\t};\n\t\t\tconst onAbort = (): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tfinish();\n\t\t\t\tjoined.waiters--;\n\t\t\t\tif (joined.waiters === 0) {\n\t\t\t\t\tif (refresh === joined) refresh = undefined;\n\t\t\t\t\tif (lastAttemptAt === joined.startedAt) lastAttemptAt = joined.previousAttemptAt;\n\t\t\t\t\tjoined.controller.abort();\n\t\t\t\t}\n\t\t\t\tresolve(ABORTED);\n\t\t\t};\n\t\t\tsignal.addEventListener('abort', onAbort, { once: true });\n\t\t\tif (signal.aborted) onAbort();\n\t\t\tvoid joined.promise.then((outcome) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tfinish();\n\t\t\t\tresolve(outcome);\n\t\t\t});\n\t\t});\n\t}\n\n\tfunction refreshAllowed(): boolean {\n\t\tif (refresh !== undefined || lastAttemptAt === undefined) return true;\n\t\treturn settings.now() - lastAttemptAt >= settings.cooldownMs;\n\t}\n\n\tasync function obtain(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<Snapshot | undefined, FetchFailureCode | 'aborted'>> {\n\t\tif (!refreshAllowed()) return successResult(undefined);\n\t\tconst outcome = await awaitRefresh(signal);\n\t\tif (outcome === ABORTED || outcome.kind === 'abandoned') {\n\t\t\treturn joseFailure('aborted', 'Key resolution was cancelled');\n\t\t}\n\t\tif (outcome.kind === 'failed') return outcome.failure;\n\t\treturn successResult(outcome.snapshot);\n\t}\n\n\tasync function importFrom(\n\t\tcurrent: Snapshot,\n\t\tentry: SupportedJwkEntry,\n\t\talgorithm: JwsAlgorithm,\n\t): Promise<JoseResult<CryptoKey, 'key_unsuitable'>> {\n\t\tconst key = jwkEntryCacheKey(entry, algorithm);\n\t\tconst cached = current.imported.get(key);\n\t\tif (cached !== undefined) return await cached;\n\t\tconst pending = importJwkEntry(entry, algorithm);\n\t\tcurrent.imported.set(key, pending);\n\t\treturn await pending;\n\t}\n\n\tasync function currentSnapshot(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<Snapshot, FetchFailureCode | 'aborted'>> {\n\t\tif (snapshot !== undefined && settings.now() < snapshot.expiresAt) {\n\t\t\treturn successResult(snapshot);\n\t\t}\n\t\tsnapshot = undefined;\n\t\tconst loaded = await obtain(signal);\n\t\tif (!loaded.ok) return loaded;\n\t\treturn loaded.value === undefined\n\t\t\t? unavailable('The JWKS endpoint is in cooldown')\n\t\t\t: successResult(loaded.value);\n\t}\n\n\tasync function select(\n\t\tcurrent: Snapshot,\n\t\tselector: JwkSelector,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<CryptoKey, KeyResolutionErrorCode>> {\n\t\tlet source = current;\n\t\tlet selected = selectJwk(source.jwks, selector);\n\t\tif (!selected.ok && selected.code === 'key_not_found') {\n\t\t\tconst reloaded = await obtain(signal);\n\t\t\tif (!reloaded.ok) return reloaded;\n\t\t\tif (reloaded.value !== undefined) {\n\t\t\t\tsource = reloaded.value;\n\t\t\t\tselected = selectJwk(source.jwks, selector);\n\t\t\t}\n\t\t}\n\t\tif (!selected.ok) return selected;\n\t\tconst key = await importFrom(source, selected.value, selector.algorithm);\n\t\treturn signal?.aborted === true ? joseFailure('aborted', 'Key resolution was cancelled') : key;\n\t}\n\n\treturn async (request: JwsKeyRequest) => {\n\t\tif (request.signal?.aborted === true) {\n\t\t\treturn joseFailure('aborted', 'Key resolution was cancelled');\n\t\t}\n\t\tconst current = await currentSnapshot(request.signal);\n\t\tif (!current.ok) return current;\n\t\treturn await select(\n\t\t\tcurrent.value,\n\t\t\t{ algorithm: request.algorithm, ...(request.kid === undefined ? {} : { kid: request.kid }) },\n\t\t\trequest.signal,\n\t\t);\n\t};\n}\n"],"mappings":";;;;;AAwGA,MAAMQ,IAAyB,OAAO,uBAAuB,GAEvDC,IAAW;CAChB,WAAW;CACX,kBAAkB;CAClB,SAAS;CACT,cAAc;CACd,UAAU;CACV,YAAY;AACb,GAEMC,oBAAyC,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC,GAE1EC,oBAAsC,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;AAEvF,SAAS,eAAeC,GAAmB;CAC1C,OACCA,EAAI,aAAa,YAAaA,EAAI,aAAa,WAAWD,EAAe,IAAIC,EAAI,QAAQ;AAE3F;AAEA,SAAS,gBAAgBC,GAA2BC,GAAkBC,GAAsB;CAC3F,IAAMC,IAAWH,KAASC;CAI1B,OAHI,CAAC,OAAO,cAAcE,CAAQ,KAAKA,KAAY,IAC3CT,EAAmB,8BAA8B,GAAGQ,EAAK,4BAA4B,IAEtFC;AACR;AAiBA,SAAS,cAAcC,GAA0C;CAChE,IAAIL;CACJ,IAAI;EACHA,IAAM,IAAI,I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B,IAAM,MAAM,WAAWsB,GAAQC,EAAS,OAAOF,EAAS,SAAS;EACvE,OAAOxC,GAAQ,YAAY,KAAO3C,EAAY,WAAW,8BAA8B,IAAI8D;CAC5F;CAEA,OAAO,OAAOyB,MAA2B;EACxC,IAAIA,EAAQ,QAAQ,YAAY,IAC/B,OAAOvF,EAAY,WAAW,8BAA8B;EAE7D,IAAM+E,IAAU,MAAM,gBAAgBQ,EAAQ,MAAM;EAEpD,OADKR,EAAQ,KACN,MAAM,OACZA,EAAQ,OACR;GAAE,WAAWQ,EAAQ;GAAW,GAAIA,EAAQ,QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,KAAKA,EAAQ,IAAI;EAAG,GAC3FA,EAAQ,MACT,IALwBR;CAMzB;AACD"}
package/dist/jose.d.ts CHANGED
@@ -1,7 +1,18 @@
1
+ /**
2
+ * Optional JOSE surface: compact JWE plus signed compact JWS and JWT (RS256/384/512, ES256/384), JWK Sets, and opt-in remote JWKS
3
+ * resolution. Importing this entrypoint performs no network access.
4
+ *
5
+ * Start with {@linkcode verifyJwt} for tokens, {@linkcode createJwksKeyResolver} for a local
6
+ * JWK Set, and {@linkcode createRemoteJwksKeyResolver} to read keys from a trusted URL.
7
+ *
8
+ * @module micro509/jose
9
+ */
1
10
  import { JsonObject, JsonValue } from "./internal/jose/strict-json.js";
2
- import { JoseErrorCode, JoseErrorDetails, JoseErrorResult, JoseFailure, JoseResult, JwsParseErrorCode, JwsPolicyErrorCode, JwtClaimsErrorCode, KeyResolutionErrorCode, VerifyJwsErrorCode, VerifyJwtErrorCode } from "./jose/errors.js";
3
- import { DEFAULT_JOSE_LIMITS, JWS_ALGORITHMS, JoseLimits, JwsAlgorithm, JwsHeader, JwsHeaderInput, JwsKeyRequest, JwsKeyResolver, MIN_RS256_MODULUS_BITS, SignJoseErrorCode, SignJwsInput, TokenTypePolicy, Unchecked, UnverifiedJws, VerifiedJws, VerifyJwsOptions, parseCompactJws, signCompactJws, verifyCompactJws } from "./jose/jws.js";
4
- import { DEFAULT_JWKS_LIMITS, JwkEntry, JwkEntryBase, JwkMetadata, JwkSelector, Jwks, JwksLimits, ParseJwksErrorCode, RsaJwkEntry, UnsupportedJwkEntry, createJwksKeyResolver, importJwkEntry, parseJwks, selectJwk } from "./jose/jwks.js";
11
+ import { base64UrlDecode, base64UrlEncode } from "./jose/base64url.js";
12
+ import { JoseErrorCode, JoseErrorDetails, JoseErrorResult, JoseFailure, JoseResult, JweErrorCode, JwsParseErrorCode, JwsPolicyErrorCode, JwtClaimsErrorCode, KeyResolutionErrorCode, VerifyJwsErrorCode, VerifyJwtErrorCode } from "./jose/errors.js";
13
+ import { DecryptJweOptions, DecryptedJwe, EncryptJweInput, JweAlgorithm, JweEncryption, JweHeader, decryptCompactJwe, encryptCompactJwe } from "./jose/jwe.js";
14
+ import { DEFAULT_JWKS_LIMITS, EcJwkEntry, JwkEntry, JwkEntryBase, JwkMetadata, JwkSelector, Jwks, JwksLimits, ParseJwksErrorCode, RsaJwkEntry, SupportedJwkEntry, UnsupportedJwkEntry, createJwksKeyResolver, importJwkEntry, parseJwks, selectJwk, validateJwks } from "./jose/jwks.js";
15
+ import { DEFAULT_JOSE_LIMITS, JWS_ALGORITHMS, JoseLimits, JwsAlgorithm, JwsHeader, JwsHeaderInput, JwsKeyRequest, JwsKeyResolver, MIN_JWS_RSA_MODULUS_BITS, MIN_RS256_MODULUS_BITS, SignJoseErrorCode, SignJwsInput, TokenTypePolicy, Unchecked, UnverifiedJws, VerifiedJws, VerifyJwsOptions, parseCompactJws, signCompactJws, verifyCompactJws } from "./jose/jws.js";
5
16
  import { FutureIssuedAtPolicy, JwtClaimsPolicy, MAX_CLOCK_TOLERANCE_SECONDS, RegisteredClaims, SignJwtInput, UnverifiedJwt, VerifiedJwt, VerifyJwtOptions, decodeJwtUnverified, signJwt, verifyJwt } from "./jose/jwt.js";
6
17
  import { JwksRequestInit, JwksTransport, RemoteJwksConfig, RemoteJwksConfigErrorCode, RemoteJwksRedirectPolicy, createRemoteJwksKeyResolver } from "./jose/remote-jwks.js";
7
- export { DEFAULT_JOSE_LIMITS, DEFAULT_JWKS_LIMITS, type FutureIssuedAtPolicy, JWS_ALGORITHMS, type JoseErrorCode, type JoseErrorDetails, type JoseErrorResult, type JoseFailure, type JoseLimits, type JoseResult, type JsonObject, type JsonValue, type JwkEntry, type JwkEntryBase, type JwkMetadata, type JwkSelector, type Jwks, type JwksLimits, type JwksRequestInit, type JwksTransport, type JwsAlgorithm, type JwsHeader, type JwsHeaderInput, type JwsKeyRequest, type JwsKeyResolver, type JwsParseErrorCode, type JwsPolicyErrorCode, type JwtClaimsErrorCode, type JwtClaimsPolicy, type KeyResolutionErrorCode, MAX_CLOCK_TOLERANCE_SECONDS, MIN_RS256_MODULUS_BITS, type ParseJwksErrorCode, type RegisteredClaims, type RemoteJwksConfig, type RemoteJwksConfigErrorCode, type RemoteJwksRedirectPolicy, type RsaJwkEntry, type SignJoseErrorCode, type SignJwsInput, type SignJwtInput, type TokenTypePolicy, type Unchecked, type UnsupportedJwkEntry, type UnverifiedJws, type UnverifiedJwt, type VerifiedJws, type VerifiedJwt, type VerifyJwsErrorCode, type VerifyJwsOptions, type VerifyJwtErrorCode, type VerifyJwtOptions, createJwksKeyResolver, createRemoteJwksKeyResolver, decodeJwtUnverified, importJwkEntry, parseCompactJws, parseJwks, selectJwk, signCompactJws, signJwt, verifyCompactJws, verifyJwt };
18
+ export { DEFAULT_JOSE_LIMITS, DEFAULT_JWKS_LIMITS, type DecryptJweOptions, type DecryptedJwe, type EcJwkEntry, type EncryptJweInput, type FutureIssuedAtPolicy, JWS_ALGORITHMS, type JoseErrorCode, type JoseErrorDetails, type JoseErrorResult, type JoseFailure, type JoseLimits, type JoseResult, type JsonObject, type JsonValue, type JweAlgorithm, type JweEncryption, type JweErrorCode, type JweHeader, type JwkEntry, type JwkEntryBase, type JwkMetadata, type JwkSelector, type Jwks, type JwksLimits, type JwksRequestInit, type JwksTransport, type JwsAlgorithm, type JwsHeader, type JwsHeaderInput, type JwsKeyRequest, type JwsKeyResolver, type JwsParseErrorCode, type JwsPolicyErrorCode, type JwtClaimsErrorCode, type JwtClaimsPolicy, type KeyResolutionErrorCode, MAX_CLOCK_TOLERANCE_SECONDS, MIN_JWS_RSA_MODULUS_BITS, MIN_RS256_MODULUS_BITS, type ParseJwksErrorCode, type RegisteredClaims, type RemoteJwksConfig, type RemoteJwksConfigErrorCode, type RemoteJwksRedirectPolicy, type RsaJwkEntry, type SignJoseErrorCode, type SignJwsInput, type SignJwtInput, type SupportedJwkEntry, type TokenTypePolicy, type Unchecked, type UnsupportedJwkEntry, type UnverifiedJws, type UnverifiedJwt, type VerifiedJws, type VerifiedJwt, type VerifyJwsErrorCode, type VerifyJwsOptions, type VerifyJwtErrorCode, type VerifyJwtOptions, base64UrlDecode, base64UrlEncode, createJwksKeyResolver, createRemoteJwksKeyResolver, decodeJwtUnverified, decryptCompactJwe, encryptCompactJwe, importJwkEntry, parseCompactJws, parseJwks, selectJwk, signCompactJws, signJwt, validateJwks, verifyCompactJws, verifyJwt };
package/dist/jose.js CHANGED
@@ -1,5 +1,7 @@
1
- import { DEFAULT_JOSE_LIMITS as e, JWS_ALGORITHMS as t, MIN_RS256_MODULUS_BITS as n, parseCompactJws as r, signCompactJws as i, verifyCompactJws as a } from "./jose/jws.js";
2
- import { DEFAULT_JWKS_LIMITS as o, createJwksKeyResolver as s, importJwkEntry as c, parseJwks as l, selectJwk as u } from "./jose/jwks.js";
3
- import { MAX_CLOCK_TOLERANCE_SECONDS as d, decodeJwtUnverified as f, signJwt as p, verifyJwt as m } from "./jose/jwt.js";
4
- import { createRemoteJwksKeyResolver as h } from "./jose/remote-jwks.js";
5
- export { e as DEFAULT_JOSE_LIMITS, o as DEFAULT_JWKS_LIMITS, t as JWS_ALGORITHMS, d as MAX_CLOCK_TOLERANCE_SECONDS, n as MIN_RS256_MODULUS_BITS, s as createJwksKeyResolver, h as createRemoteJwksKeyResolver, f as decodeJwtUnverified, c as importJwkEntry, r as parseCompactJws, l as parseJwks, u as selectJwk, i as signCompactJws, p as signJwt, a as verifyCompactJws, m as verifyJwt };
1
+ import { base64UrlDecode as e, base64UrlEncode as t } from "./jose/base64url.js";
2
+ import { decryptCompactJwe as n, encryptCompactJwe as r } from "./jose/jwe.js";
3
+ import { DEFAULT_JWKS_LIMITS as i, createJwksKeyResolver as a, importJwkEntry as o, parseJwks as s, selectJwk as c, validateJwks as l } from "./jose/jwks.js";
4
+ import { DEFAULT_JOSE_LIMITS as u, JWS_ALGORITHMS as d, MIN_JWS_RSA_MODULUS_BITS as f, MIN_RS256_MODULUS_BITS as p, parseCompactJws as m, signCompactJws as h, verifyCompactJws as g } from "./jose/jws.js";
5
+ import { MAX_CLOCK_TOLERANCE_SECONDS as _, decodeJwtUnverified as v, signJwt as y, verifyJwt as b } from "./jose/jwt.js";
6
+ import { createRemoteJwksKeyResolver as x } from "./jose/remote-jwks.js";
7
+ export { u as DEFAULT_JOSE_LIMITS, i as DEFAULT_JWKS_LIMITS, d as JWS_ALGORITHMS, _ as MAX_CLOCK_TOLERANCE_SECONDS, f as MIN_JWS_RSA_MODULUS_BITS, p as MIN_RS256_MODULUS_BITS, e as base64UrlDecode, t as base64UrlEncode, a as createJwksKeyResolver, x as createRemoteJwksKeyResolver, v as decodeJwtUnverified, n as decryptCompactJwe, r as encryptCompactJwe, o as importJwkEntry, m as parseCompactJws, s as parseJwks, c as selectJwk, h as signCompactJws, y as signJwt, l as validateJwks, g as verifyCompactJws, b as verifyJwt };
@@ -1 +1 @@
1
- {"version":3,"file":"argon2-arithmetic.js","names":["a","b","low"],"sources":["../../src/kdf/argon2-arithmetic.ts"],"sourcesContent":["/**\n * Exact high word of an unsigned 32×32 product; `low` is Math.imul(a, b).\n *\n * Subtracting the exact low word leaves a multiple of 2^32 with at most 2048\n * units of floating-point error. Scaling by 2^32 reduces that error below\n * 2^-20, so adding 0.5 and truncating recovers the exact integer high word.\n * BlaMka already computes the low word and passes it here for reuse.\n */\nexport function multiplyHigh(a: number, b: number, low: number): number {\n\treturn ((a * b - (low >>> 0)) / 0x1_0000_0000 + 0.5) >>> 0;\n}\n"],"mappings":";;;;;;;;;AAQA,SAAgB,aAAa,GAAW,GAAW,GAAqB;CACvE,QAASA,IAAIC,KAAKC,MAAQ,MAAM,aAAgB,OAAS;AAC1D"}
1
+ {"version":3,"file":"argon2-arithmetic.js","names":["a","b","low"],"sources":["../../src/kdf/argon2-arithmetic.ts"],"sourcesContent":["/**\n * Exact high word of an unsigned 32×32 product; `low` is Math.imul(a, b).\n *\n * Subtracting the exact low word leaves a multiple of 2^32 with at most 2048\n * units of floating-point error. Scaling by 2^32 reduces that error below\n * 2^-20, so adding 0.5 and truncating recovers the exact integer high word.\n * BlaMka already computes the low word and passes it here for reuse.\n */\nexport function multiplyHigh(a: number, b: number, low: number): number {\n\treturn ((a * b - (low >>> 0)) / 0x1_0000_0000 + 0.5) >>> 0;\n}\n"],"mappings":";;;;;;;;;AAQA,SAAgB,aAAaA,GAAWC,GAAWC,GAAqB;CACvE,QAASF,IAAIC,KAAKC,MAAQ,MAAM,aAAgB,OAAS;AAC1D"}