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.
- package/CHANGELOG.md +78 -6
- package/dist/crypto/crypto.d.ts +2 -3
- package/dist/crypto.d.ts +6 -0
- package/dist/der/der.d.ts +14 -4
- package/dist/der/der.js +19 -19
- package/dist/der.d.ts +26 -2
- package/dist/der.js +4 -4
- package/dist/index.d.ts +82 -15
- package/dist/index.js +19 -19
- package/dist/internal/asn1/asn1.d.ts +1 -2
- package/dist/internal/asn1/der.d.ts +1 -2
- package/dist/internal/asn1/oids.js +71 -353
- package/dist/internal/asn1/oids.js.map +1 -1
- package/dist/internal/asn1/oids.json.js +357 -0
- package/dist/internal/asn1/oids.json.js.map +1 -0
- package/dist/internal/crypto/algorithm-names.js +1 -1
- package/dist/internal/crypto/pbes2.d.ts +1 -2
- package/dist/internal/crypto/pbes2.js +70 -70
- package/dist/internal/crypto/prime-ec.js +37 -0
- package/dist/internal/crypto/prime-ec.js.map +1 -0
- package/dist/internal/crypto/rsa-pss.js +50 -50
- package/dist/internal/crypto/sig-verify.d.ts +1 -2
- package/dist/internal/crypto/sig-verify.js +60 -60
- package/dist/internal/crypto/signing.d.ts +1 -2
- package/dist/internal/crypto/signing.js +26 -26
- package/dist/internal/jose/json-data.js +108 -0
- package/dist/internal/jose/json-data.js.map +1 -0
- package/dist/internal/jose/strict-json.d.ts +1 -2
- package/dist/internal/shared/dn.d.ts +1 -2
- package/dist/internal/shared/dn.js +1 -1
- package/dist/internal/shared/ip.d.ts +1 -2
- package/dist/internal/verify/name-constraints-engine.js +64 -64
- package/dist/internal/verify/policy-engine.js +1 -1
- package/dist/internal/verify/verify-path.d.ts +1 -2
- package/dist/internal/verify/verify-path.js +19 -19
- package/dist/internal/x509/directory-name.js +10 -10
- package/dist/internal/x509/extension-errors.d.ts +1 -2
- package/dist/internal/x509/extension-registry.js +18 -18
- package/dist/internal/x509/general-name-profile.js +9 -9
- package/dist/internal/x509/general-name.js +32 -32
- package/dist/internal/x509/name-fields.js +1 -1
- package/dist/jose/base64url.d.ts +4 -0
- package/dist/jose/base64url.js +14 -0
- package/dist/jose/base64url.js.map +1 -0
- package/dist/jose/errors.d.ts +9 -3
- package/dist/jose/errors.js.map +1 -1
- package/dist/jose/jwe.d.ts +64 -0
- package/dist/jose/jwe.js +188 -0
- package/dist/jose/jwe.js.map +1 -0
- package/dist/jose/jwks.d.ts +38 -10
- package/dist/jose/jwks.js +156 -96
- package/dist/jose/jwks.js.map +1 -1
- package/dist/jose/jws.d.ts +8 -6
- package/dist/jose/jws.js +216 -170
- package/dist/jose/jws.js.map +1 -1
- package/dist/jose/jwt.d.ts +8 -2
- package/dist/jose/jwt.js +98 -98
- package/dist/jose/remote-jwks.d.ts +1 -2
- package/dist/jose/remote-jwks.js +106 -108
- package/dist/jose/remote-jwks.js.map +1 -1
- package/dist/jose.d.ts +15 -4
- package/dist/jose.js +7 -5
- package/dist/kdf/argon2.d.ts +7 -2
- package/dist/kdf.d.ts +6 -0
- package/dist/keys/keys.d.ts +31 -6
- package/dist/keys/keys.js +315 -233
- package/dist/keys/keys.js.map +1 -1
- package/dist/keys.d.ts +11 -2
- package/dist/keys.js +2 -2
- package/dist/pem/pem.d.ts +1 -2
- package/dist/pem/pem.js +40 -25
- package/dist/pem/pem.js.map +1 -1
- package/dist/pem.d.ts +6 -0
- package/dist/pkcs/pfx.d.ts +2 -3
- package/dist/pkcs/pfx.js +142 -142
- package/dist/pkcs/pkcs12-mac.d.ts +1 -2
- package/dist/pkcs/pkcs12-mac.js +122 -122
- package/dist/pkcs/pkcs7.d.ts +14 -3
- package/dist/pkcs/pkcs7.js +268 -248
- package/dist/pkcs/pkcs7.js.map +1 -1
- package/dist/pkcs.d.ts +10 -1
- package/dist/pkcs.js +4 -4
- package/dist/result/result.d.ts +1 -2
- package/dist/result.d.ts +6 -0
- package/dist/revocation/chain.d.ts +2 -3
- package/dist/revocation/chain.js +52 -52
- package/dist/revocation/crl.d.ts +2 -3
- package/dist/revocation/crl.js +319 -319
- package/dist/revocation/crl.js.map +1 -1
- package/dist/revocation/ocsp.d.ts +2 -3
- package/dist/revocation/ocsp.js +395 -395
- package/dist/revocation/revocation.d.ts +2 -3
- package/dist/revocation/revocation.js +22 -22
- package/dist/revocation.d.ts +12 -3
- package/dist/revocation.js +4 -4
- package/dist/ssh/ssh.d.ts +2 -3
- package/dist/ssh/ssh.js +165 -170
- package/dist/ssh/ssh.js.map +1 -1
- package/dist/ssh/wire.d.ts +1 -2
- package/dist/ssh/wire.js +10 -10
- package/dist/ssh.d.ts +8 -0
- package/dist/verify/identity.d.ts +1 -2
- package/dist/verify/identity.js +31 -31
- package/dist/verify/name-constraints.d.ts +9 -2
- package/dist/verify/policy.d.ts +9 -2
- package/dist/verify/verify.d.ts +3 -4
- package/dist/verify/verify.js +121 -121
- package/dist/verify.d.ts +9 -0
- package/dist/x509/certificate.d.ts +4 -5
- package/dist/x509/certificate.js +40 -40
- package/dist/x509/csr.d.ts +3 -4
- package/dist/x509/csr.js +15 -15
- package/dist/x509/extensions.d.ts +1 -2
- package/dist/x509/extensions.js +165 -165
- package/dist/x509/extensions.js.map +1 -1
- package/dist/x509/fingerprint.d.ts +1 -2
- package/dist/x509/name-text.d.ts +1 -2
- package/dist/x509/name.d.ts +1 -2
- package/dist/x509/name.js +15 -15
- package/dist/x509/parse.d.ts +3 -4
- package/dist/x509/parse.js +423 -423
- package/dist/x509.d.ts +17 -4
- package/dist/x509.js +8 -8
- package/package.json +22 -23
- package/dist/internal/asn1/oids2.js +0 -75
- package/dist/internal/asn1/oids2.js.map +0 -1
package/dist/jose/remote-jwks.js
CHANGED
|
@@ -1,61 +1,62 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
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
|
|
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
|
-
},
|
|
13
|
+
}, u = /* @__PURE__ */ new Set([
|
|
13
14
|
301,
|
|
14
15
|
302,
|
|
15
16
|
303,
|
|
16
17
|
307,
|
|
17
18
|
308
|
|
18
|
-
]),
|
|
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:" &&
|
|
25
|
+
return e.protocol === "https:" || e.protocol === "http:" && d.has(e.hostname);
|
|
25
26
|
}
|
|
26
|
-
function positiveInteger(e,
|
|
27
|
-
let
|
|
28
|
-
return !Number.isSafeInteger(
|
|
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
|
|
32
|
+
let t;
|
|
32
33
|
try {
|
|
33
|
-
|
|
34
|
+
t = new URL(e.url);
|
|
34
35
|
} catch {
|
|
35
|
-
return
|
|
36
|
+
return s("invalid_remote_jwks_config", "url is not an absolute URL");
|
|
36
37
|
}
|
|
37
|
-
if (!isPermittedUrl(
|
|
38
|
-
if (
|
|
39
|
-
let
|
|
40
|
-
if (!Number.isSafeInteger(
|
|
41
|
-
let
|
|
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:
|
|
44
|
+
url: t,
|
|
44
45
|
transport: e.transport ?? ((e, t) => globalThis.fetch(e, t)),
|
|
45
46
|
headers: { ...e.headers },
|
|
46
|
-
timeoutMs: positiveInteger(e.timeoutMs,
|
|
47
|
-
maxResponseBytes: positiveInteger(e.maxResponseBytes,
|
|
48
|
-
maxKeys: positiveInteger(e.maxKeys,
|
|
49
|
-
maxRedirects:
|
|
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,
|
|
52
|
-
maxTtlMs:
|
|
53
|
-
cooldownMs:
|
|
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(
|
|
58
|
-
return
|
|
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,
|
|
86
|
-
let
|
|
87
|
-
if (
|
|
88
|
-
if (t.body === null) return
|
|
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
|
-
|
|
93
|
+
r.addEventListener("abort", release, { once: !0 });
|
|
93
94
|
try {
|
|
94
|
-
let
|
|
95
|
+
let e = [], t = 0;
|
|
95
96
|
for (;;) {
|
|
96
|
-
let { done:
|
|
97
|
-
if (
|
|
98
|
-
if (
|
|
99
|
-
if (
|
|
100
|
-
|
|
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
|
|
103
|
-
for (let
|
|
104
|
-
return
|
|
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
|
-
|
|
107
|
+
r.removeEventListener("abort", release);
|
|
107
108
|
}
|
|
108
109
|
}
|
|
109
|
-
function nextHop(t, n, r
|
|
110
|
-
let
|
|
111
|
-
if (
|
|
112
|
-
let
|
|
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
|
-
|
|
115
|
+
a = new URL(i, t);
|
|
115
116
|
} catch {
|
|
116
|
-
return unavailable("The JWKS redirect target is not a URL",
|
|
117
|
+
return unavailable("The JWKS redirect target is not a URL", n.status);
|
|
117
118
|
}
|
|
118
|
-
return !isPermittedUrl(
|
|
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,
|
|
121
|
-
if (
|
|
122
|
-
let s = t.now(), c = await readBounded(
|
|
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 =
|
|
125
|
+
let l = r(c.value, {
|
|
125
126
|
maxBytes: t.maxResponseBytes,
|
|
126
127
|
maxKeys: t.maxKeys
|
|
127
128
|
});
|
|
128
|
-
return l.ok ?
|
|
129
|
+
return l.ok ? o({
|
|
129
130
|
jwks: l.value,
|
|
130
|
-
expiresAt: s + freshnessMs(
|
|
131
|
-
}) :
|
|
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 (!
|
|
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
|
|
158
|
-
for (let
|
|
159
|
-
let
|
|
160
|
-
|
|
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:
|
|
163
|
+
imported: r
|
|
166
164
|
};
|
|
167
165
|
}
|
|
168
|
-
const
|
|
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(
|
|
200
|
-
let
|
|
197
|
+
function createRemoteJwksKeyResolver(r) {
|
|
198
|
+
let a = resolveConfig(r), s, l, u;
|
|
201
199
|
function startRefresh() {
|
|
202
|
-
let e = new AbortController(), t =
|
|
203
|
-
|
|
200
|
+
let e = new AbortController(), t = a.now(), n = u, r = s;
|
|
201
|
+
u = t;
|
|
204
202
|
async function run() {
|
|
205
|
-
let n,
|
|
206
|
-
n = setTimeout(() => e(
|
|
207
|
-
}), o = fetchJwks(
|
|
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,
|
|
211
|
-
return t ===
|
|
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
|
|
231
|
-
|
|
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:
|
|
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
|
|
243
|
-
|
|
244
|
-
let t =
|
|
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 && (
|
|
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
|
|
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
|
|
261
|
-
let
|
|
262
|
-
return
|
|
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,
|
|
265
|
-
let
|
|
266
|
-
if (
|
|
267
|
-
let
|
|
268
|
-
return e.imported.set(
|
|
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(
|
|
271
|
-
if (s !== void 0 &&
|
|
268
|
+
async function currentSnapshot(e) {
|
|
269
|
+
if (s !== void 0 && a.now() < s.expiresAt) return o(s);
|
|
272
270
|
s = void 0;
|
|
273
|
-
let
|
|
274
|
-
return
|
|
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(
|
|
277
|
-
let
|
|
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 && (
|
|
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(
|
|
285
|
-
return r?.aborted === !0 ?
|
|
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 (
|
|
288
|
-
if (
|
|
289
|
-
let
|
|
290
|
-
return
|
|
291
|
-
algorithm:
|
|
292
|
-
...
|
|
293
|
-
},
|
|
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 ? {} : { kid: request.kid }) },\n\t\t\trequest.signal,\n\t\t);\n\t};\n}\n"],"mappings":";;;;AAuGA,MAAMA,IAAyB,OAAO,uBAAuB,GAEvDC,IAAW;CAChB,WAAW;CACX,kBAAkB;CAClB,SAAS;CACT,cAAc;CACd,UAAU;CACV,YAAY;AACb,GAEMC,oBAAyC,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC,GAE1EC,oBAAsC,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;AAEvF,SAAS,eAAe,GAAmB;CAC1C,OACCC,EAAI,aAAa,YAAaA,EAAI,aAAa,WAAWD,EAAe,IAAIC,EAAI,QAAQ;AAE3F;AAEA,SAAS,gBAAgB,GAA2B,GAAkB,GAAsB;CAC3F,IAAMC,IAAWC,KAASC;CAI1B,OAHI,CAAC,OAAO,cAAcF,CAAQ,KAAKA,KAAY,IAC3CG,EAAmB,8BAA8B,GAAGC,EAAK,4BAA4B,IAEtFJ;AACR;AAiBA,SAAS,cAAc,GAA0C;CAChE,IAAID;CACJ,IAAI;EACH,IAAM,IAAI,IAAIM,EAAO,GAAG;CACzB,QAAQ;EACP,OAAOF,EAAmB,8BAA8B,4BAA4B;CACrF;CACA,IAAI,CAAC,eAAeJ,CAAG,GACtB,OAAOI,EACN,8BACA,gDACD;CAED,IAAIJ,EAAI,aAAa,MAAMA,EAAI,aAAa,IAC3C,OAAOI,EAAmB,8BAA8B,gCAAgC;CAEzF,IAAMG,IAAeD,EAAO,WAAW,gBAAgB;CACvD,IAAI,CAAC,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QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,KAAKA,EAAQ,IAAI;EAAG,GAC3FA,EAAQ,MACT,IALwBT;CAMzB;AACD"}
|
|
1
|
+
{"version":3,"file":"remote-jwks.js","names":["ABORTED","DEFAULTS","REDIRECT_STATUSES","LOOPBACK_HOSTS","url","resolved","value","fallback","throwMicro509Error","name","config","maxRedirects","maxTtlMs","cooldownMs","target","init","destination","from","joseFailure","message","status","headers","directives","directive","date","apparentAge","receivedAt","reportedAge","transit","requestedAt","age","maxAge","lifetime","match","expires","tooLarge","maxBytes","declared","response","successResult","reader","chunks","total","signal","done","body","offset","chunk","location","redirects","jwks","parseJwks","hop","imported","entry","fetched","algorithm","JWS_ALGORITHMS","key","jwkEntryCacheKey","carried","previous","TIMED_OUT","settings","snapshot","refresh","lastAttemptAt","controller","previousAttemptAt","timer","deadline","resolve","work","tracked","outcome","joined","settled","cached","current","pending","importJwkEntry","loaded","source","selected","selectJwk","selector","reloaded","request"],"sources":["../../src/jose/remote-jwks.ts"],"sourcesContent":["/**\n * Opt-in remote JWK Set resolution. A resolver is bound to one trusted JWKS URL from caller\n * configuration and keeps its own cache, so two issuers never share keys. Importing this module\n * performs no request; only a verification that reaches the resolver can.\n *\n * @module\n */\n\nimport type { JoseErrorResult, JoseResult, KeyResolutionErrorCode } from '#micro509/jose/errors';\nimport { joseFailure } from '#micro509/jose/errors';\nimport type { JwkSelector, Jwks, SupportedJwkEntry } from '#micro509/jose/jwks';\nimport { importJwkEntry, jwkEntryCacheKey, parseJwks, selectJwk } from '#micro509/jose/jwks';\nimport type { JwsAlgorithm, JwsKeyRequest, JwsKeyResolver } from '#micro509/jose/jws';\nimport { JWS_ALGORITHMS } from '#micro509/jose/jws';\nimport { successResult, throwMicro509Error } from '#micro509/result/result';\n\n/** The request {@linkcode JwksTransport} must issue. */\nexport interface JwksRequestInit {\n\t/** Always `GET`. */\n\treadonly method: 'GET';\n\t/** Always `manual`: the resolver validates every redirect destination itself. */\n\treadonly redirect: 'manual';\n\t/** Always `omit`. */\n\treadonly credentials: 'omit';\n\t/** Always `no-store`: each resolver refresh must reach the issuer, bypassing the HTTP cache. */\n\treadonly cache: 'no-store';\n\t/** Configured request headers. Withheld from any origin other than the configured URL's. */\n\treadonly headers: Readonly<Record<string, string>>;\n\t/** Aborts on timeout, cancellation or when no verification still waits for the response. */\n\treadonly signal: AbortSignal;\n}\n\n/**\n * Performs one HTTP request. `fetch` satisfies this type. Supply another to route through a proxy,\n * apply egress or DNS controls, or serve fixtures; the transport sees only URLs the resolver\n * already validated.\n */\nexport type JwksTransport = (url: string, init: JwksRequestInit) => Promise<Response>;\n\n/** Redirect handling for a remote JWK Set. By default redirects are refused. */\nexport interface RemoteJwksRedirectPolicy {\n\t/** Maximum redirects followed per fetch. */\n\treadonly maxRedirects: number;\n\t/**\n\t * Approves a redirect destination. Default: same origin as the hop it came from. The scheme\n\t * rule applies first: `https`, or `http` for a loopback host.\n\t */\n\treadonly allow?: (destination: URL, from: URL) => boolean;\n}\n\n/** Configuration of {@linkcode createRemoteJwksKeyResolver}. */\nexport interface RemoteJwksConfig {\n\t/** The trusted JWKS URL. `https`, or `http` for a loopback host. Never taken from a token. */\n\treadonly url: string | URL;\n\t/** Request transport. Default: `globalThis.fetch`. */\n\treadonly transport?: JwksTransport;\n\t/** Request headers, sent only to the configured URL's origin. */\n\treadonly headers?: Readonly<Record<string, string>>;\n\t/** Whole-request deadline in milliseconds, response body included. Default `5000`. */\n\treadonly timeoutMs?: number;\n\t/** Maximum response body in bytes, enforced while streaming. Default `65536`. */\n\treadonly maxResponseBytes?: number;\n\t/** Maximum keys in the set. Default `32`. */\n\treadonly maxKeys?: number;\n\t/** Redirect handling. Default: refuse every redirect. */\n\treadonly redirects?: RemoteJwksRedirectPolicy;\n\t/** Freshness applied when the response states none, in milliseconds. Default `600000`. */\n\treadonly defaultTtlMs?: number;\n\t/** Longest freshness the resolver will keep a response for, in milliseconds. Default `86400000`. */\n\treadonly maxTtlMs?: number;\n\t/**\n\t * Minimum interval between the starts of two fetches, in milliseconds. It bounds how often\n\t * unknown `kid` values, expired responses and failures can cause a request, and does not\n\t * lengthen how long a response stays fresh. Default `30000`.\n\t */\n\treadonly cooldownMs?: number;\n\t/** The clock in milliseconds since the epoch. Default `Date.now`. */\n\treadonly now?: () => number;\n}\n\n/** Codes {@linkcode createRemoteJwksKeyResolver} throws for unusable configuration. */\nexport type RemoteJwksConfigErrorCode = 'invalid_remote_jwks_config';\n\ntype FetchFailureCode = 'jwks_unavailable' | 'jwks_malformed';\n\ninterface Snapshot {\n\treadonly jwks: Jwks;\n\treadonly expiresAt: number;\n\treadonly imported: Map<string, Promise<JoseResult<CryptoKey, 'key_unsuitable'>>>;\n}\n\ntype RefreshOutcome =\n\t| { readonly kind: 'fresh'; readonly snapshot: Snapshot }\n\t| { readonly kind: 'failed'; readonly failure: JoseErrorResult<FetchFailureCode> }\n\t| { readonly kind: 'abandoned' };\n\ninterface Refresh {\n\treadonly promise: Promise<RefreshOutcome>;\n\treadonly controller: AbortController;\n\treadonly startedAt: number;\n\treadonly previousAttemptAt: number | undefined;\n\twaiters: number;\n}\n\nconst ABORTED: unique symbol = Symbol('micro509.jose.aborted');\n\nconst DEFAULTS = {\n\ttimeoutMs: 5000,\n\tmaxResponseBytes: 65_536,\n\tmaxKeys: 32,\n\tdefaultTtlMs: 600_000,\n\tmaxTtlMs: 86_400_000,\n\tcooldownMs: 30_000,\n} as const;\n\nconst REDIRECT_STATUSES: ReadonlySet<number> = new Set([301, 302, 303, 307, 308]);\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nfunction isPermittedUrl(url: URL): boolean {\n\treturn (\n\t\turl.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))\n\t);\n}\n\nfunction positiveInteger(value: number | undefined, fallback: number, name: string): number {\n\tconst resolved = value ?? fallback;\n\tif (!Number.isSafeInteger(resolved) || resolved <= 0) {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', `${name} must be a positive integer`);\n\t}\n\treturn resolved;\n}\n\ninterface ResolvedConfig {\n\treadonly url: URL;\n\treadonly transport: JwksTransport;\n\treadonly headers: Readonly<Record<string, string>>;\n\treadonly timeoutMs: number;\n\treadonly maxResponseBytes: number;\n\treadonly maxKeys: number;\n\treadonly maxRedirects: number;\n\treadonly allowRedirect: (destination: URL, from: URL) => boolean;\n\treadonly defaultTtlMs: number;\n\treadonly maxTtlMs: number;\n\treadonly cooldownMs: number;\n\treadonly now: () => number;\n}\n\nfunction resolveConfig(config: RemoteJwksConfig): ResolvedConfig {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(config.url);\n\t} catch {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', 'url is not an absolute URL');\n\t}\n\tif (!isPermittedUrl(url)) {\n\t\treturn throwMicro509Error(\n\t\t\t'invalid_remote_jwks_config',\n\t\t\t'url must use https, or http on a loopback host',\n\t\t);\n\t}\n\tif (url.username !== '' || url.password !== '') {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', 'url must not embed credentials');\n\t}\n\tconst maxRedirects = config.redirects?.maxRedirects ?? 0;\n\tif (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0 || maxRedirects > 10) {\n\t\treturn throwMicro509Error(\n\t\t\t'invalid_remote_jwks_config',\n\t\t\t'maxRedirects must be an integer from 0 to 10',\n\t\t);\n\t}\n\tconst maxTtlMs = positiveInteger(config.maxTtlMs, DEFAULTS.maxTtlMs, 'maxTtlMs');\n\tconst cooldownMs = positiveInteger(config.cooldownMs, DEFAULTS.cooldownMs, 'cooldownMs');\n\treturn {\n\t\turl,\n\t\ttransport: config.transport ?? ((target, init) => globalThis.fetch(target, init)),\n\t\theaders: { ...config.headers },\n\t\ttimeoutMs: positiveInteger(config.timeoutMs, DEFAULTS.timeoutMs, 'timeoutMs'),\n\t\tmaxResponseBytes: positiveInteger(\n\t\t\tconfig.maxResponseBytes,\n\t\t\tDEFAULTS.maxResponseBytes,\n\t\t\t'maxResponseBytes',\n\t\t),\n\t\tmaxKeys: positiveInteger(config.maxKeys, DEFAULTS.maxKeys, 'maxKeys'),\n\t\tmaxRedirects,\n\t\tallowRedirect:\n\t\t\tconfig.redirects?.allow ?? ((destination, from) => destination.origin === from.origin),\n\t\tdefaultTtlMs: positiveInteger(config.defaultTtlMs, DEFAULTS.defaultTtlMs, 'defaultTtlMs'),\n\t\tmaxTtlMs,\n\t\tcooldownMs,\n\t\tnow: config.now ?? Date.now,\n\t};\n}\n\nfunction unavailable(message: string, status?: number): JoseErrorResult<'jwks_unavailable'> {\n\treturn joseFailure('jwks_unavailable', message, status === undefined ? undefined : { status });\n}\n\nconst NOT_A_NUMBER = Number.NaN;\n\nfunction secondsHeader(headers: Headers, name: string): number {\n\tconst value = headers.get(name);\n\treturn value !== null && /^\\d{1,10}$/.test(value) ? Number(value) * 1000 : NOT_A_NUMBER;\n}\n\n/**\n * Remaining freshness in milliseconds, never below zero and never above `maxTtlMs`.\n *\n * The lifetime is `Cache-Control: max-age`, else `Expires` less `Date`, else `defaultTtlMs`\n * (RFC 9111 §4.2.1); `no-store`, `no-cache` and unusable values give none. The response age is the\n * larger of the apparent age from `Date` and the `Age` header plus the transit delay\n * (RFC 9111 §4.2.3).\n */\nfunction freshnessMs(\n\theaders: Headers,\n\trequestedAt: number,\n\treceivedAt: number,\n\tconfig: ResolvedConfig,\n): number {\n\tconst directives = (headers.get('cache-control') ?? '')\n\t\t.split(',')\n\t\t.map((directive) => directive.trim().toLowerCase())\n\t\t.filter((directive) => directive.length > 0);\n\tif (directives.includes('no-store') || directives.includes('no-cache')) return 0;\n\tconst date = Date.parse(headers.get('date') ?? '');\n\tconst apparentAge = Number.isNaN(date) ? 0 : Math.max(0, receivedAt - date);\n\tconst reportedAge = secondsHeader(headers, 'age');\n\tconst transit = Math.max(0, receivedAt - requestedAt);\n\tconst age = Math.max(apparentAge, (Number.isNaN(reportedAge) ? 0 : reportedAge) + transit);\n\tconst maxAge = directives.find((directive) => directive.startsWith('max-age'));\n\tlet lifetime = config.defaultTtlMs;\n\tif (maxAge !== undefined) {\n\t\tconst match = /^max-age=(\"?)(\\d{1,10})\\1$/.exec(maxAge);\n\t\tlifetime = match?.[2] === undefined ? 0 : Number(match[2]) * 1000;\n\t} else if (headers.has('expires')) {\n\t\tconst expires = Date.parse(headers.get('expires') ?? '');\n\t\tlifetime = Number.isNaN(expires) ? 0 : expires - (Number.isNaN(date) ? receivedAt : date);\n\t}\n\treturn Math.min(config.maxTtlMs, Math.max(0, lifetime - age));\n}\n\ntype BodyResult = JoseResult<Uint8Array, 'jwks_unavailable' | 'jwks_malformed'>;\n\nasync function readBounded(\n\tresponse: Response,\n\tmaxBytes: number,\n\tsignal: AbortSignal,\n): Promise<BodyResult> {\n\tconst tooLarge = joseFailure('jwks_malformed', `The JWKS response exceeds ${maxBytes} bytes`);\n\tconst declared = response.headers.get('content-length');\n\tif (declared !== null && /^\\d+$/.test(declared) && Number(declared) > maxBytes) {\n\t\tawait response.body?.cancel();\n\t\treturn tooLarge;\n\t}\n\tif (response.body === null) return successResult(new Uint8Array(0));\n\tconst reader = response.body.getReader();\n\tconst release = (): void => {\n\t\treader.cancel().catch(() => undefined);\n\t};\n\tsignal.addEventListener('abort', release, { once: true });\n\ttry {\n\t\tconst chunks: Uint8Array[] = [];\n\t\tlet total = 0;\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (signal.aborted) return unavailable('The JWKS request was cancelled');\n\t\t\tif (done) break;\n\t\t\ttotal += value.byteLength;\n\t\t\tif (total > maxBytes) {\n\t\t\t\trelease();\n\t\t\t\treturn tooLarge;\n\t\t\t}\n\t\t\tchunks.push(value);\n\t\t}\n\t\tconst body = new Uint8Array(total);\n\t\tlet offset = 0;\n\t\tfor (const chunk of chunks) {\n\t\t\tbody.set(chunk, offset);\n\t\t\toffset += chunk.byteLength;\n\t\t}\n\t\treturn successResult(body);\n\t} finally {\n\t\tsignal.removeEventListener('abort', release);\n\t}\n}\n\ninterface Fetched {\n\treadonly jwks: Jwks;\n\treadonly expiresAt: number;\n}\n\nfunction nextHop(\n\tconfig: ResolvedConfig,\n\tfrom: URL,\n\tresponse: Response,\n\tredirects: number,\n): JoseResult<URL, 'jwks_unavailable'> {\n\tconst location = response.headers.get('location');\n\tif (redirects >= config.maxRedirects || location === null) {\n\t\treturn unavailable('The JWKS endpoint redirected', response.status);\n\t}\n\tlet destination: URL;\n\ttry {\n\t\tdestination = new URL(location, from);\n\t} catch {\n\t\treturn unavailable('The JWKS redirect target is not a URL', response.status);\n\t}\n\tif (\n\t\t!isPermittedUrl(destination) ||\n\t\tdestination.username !== '' ||\n\t\tdestination.password !== '' ||\n\t\t!config.allowRedirect(destination, from)\n\t) {\n\t\treturn unavailable('The JWKS redirect target is not permitted', response.status);\n\t}\n\treturn successResult(destination);\n}\n\nasync function readJwks(\n\tconfig: ResolvedConfig,\n\tresponse: Response,\n\trequestedAt: number,\n\tsignal: AbortSignal,\n): Promise<JoseResult<Fetched, FetchFailureCode>> {\n\tif (response.status !== 200) {\n\t\tawait response.body?.cancel();\n\t\treturn unavailable('The JWKS endpoint did not answer 200', response.status);\n\t}\n\tconst receivedAt = config.now();\n\tconst body = await readBounded(response, config.maxResponseBytes, signal);\n\tif (!body.ok) return body;\n\tconst jwks = parseJwks(body.value, {\n\t\tmaxBytes: config.maxResponseBytes,\n\t\tmaxKeys: config.maxKeys,\n\t});\n\tif (!jwks.ok) return joseFailure('jwks_malformed', jwks.message);\n\treturn successResult({\n\t\tjwks: jwks.value,\n\t\texpiresAt: receivedAt + freshnessMs(response.headers, requestedAt, receivedAt, config),\n\t});\n}\n\nasync function fetchJwks(\n\tconfig: ResolvedConfig,\n\tsignal: AbortSignal,\n\trequestedAt: number,\n): Promise<JoseResult<Fetched, FetchFailureCode>> {\n\tlet url = config.url;\n\tfor (let redirects = 0; ; redirects++) {\n\t\tconst response = await config.transport(url.href, {\n\t\t\tmethod: 'GET',\n\t\t\tredirect: 'manual',\n\t\t\tcredentials: 'omit',\n\t\t\tcache: 'no-store',\n\t\t\theaders: url.origin === config.url.origin ? config.headers : {},\n\t\t\tsignal,\n\t\t});\n\t\tif (signal.aborted) {\n\t\t\tawait response.body?.cancel();\n\t\t\treturn unavailable('The JWKS request was cancelled');\n\t\t}\n\t\tif (response.type === 'opaqueredirect') {\n\t\t\treturn unavailable('The runtime hides redirects, so they cannot be validated');\n\t\t}\n\t\tif (!REDIRECT_STATUSES.has(response.status)) {\n\t\t\treturn await readJwks(config, response, requestedAt, signal);\n\t\t}\n\t\tawait response.body?.cancel();\n\t\tconst hop = nextHop(config, url, response, redirects);\n\t\tif (!hop.ok) return hop;\n\t\turl = hop.value;\n\t}\n}\n\nfunction carryOver(fetched: Fetched, previous: Snapshot | undefined): Snapshot {\n\tconst imported = new Map<string, Promise<JoseResult<CryptoKey, 'key_unsuitable'>>>();\n\tfor (const entry of fetched.jwks.keys) {\n\t\tif (entry.kind === 'unsupported') continue;\n\t\tfor (const algorithm of JWS_ALGORITHMS) {\n\t\t\tconst key = jwkEntryCacheKey(entry, algorithm);\n\t\t\tconst carried = previous?.imported.get(key);\n\t\t\tif (carried !== undefined) imported.set(key, carried);\n\t\t}\n\t}\n\treturn { jwks: fetched.jwks, expiresAt: fetched.expiresAt, imported };\n}\n\nconst TIMED_OUT: unique symbol = Symbol('micro509.jose.timedOut');\n\n/**\n * Creates a key resolver that reads a JWK Set from one trusted URL.\n *\n * Behaviour, per resolver:\n *\n * - The first verification fetches the set. Later ones reuse it while fresh. Freshness is the\n * remaining lifetime from `Cache-Control: max-age`, else `Expires`, else `defaultTtlMs`, less the\n * response age (the larger of the apparent age from `Date` and `Age` plus the transit delay),\n * capped at `maxTtlMs`. `no-store`, `no-cache` and a lifetime already spent leave none: the set\n * serves the verification that fetched it and nothing after. No heuristic freshness is applied.\n * - A set that is no longer fresh is never used, whether or not a refresh succeeds. There is no\n * stale-if-error. A refresh that fails while the cached set is still fresh keeps that set until\n * it expires.\n * - Refreshes are separate from freshness: after any attempt the next one waits `cooldownMs`.\n * Within that interval a token whose `kid` is absent gets `key_not_found`, and a token that\n * needs a set that is no longer fresh gets `jwks_unavailable`. Concurrent verifications share\n * a single request, and unknown `kid` values are never cached.\n * - A refresh replaces the whole set, so a rotated-out key stops verifying as soon as the new\n * set is read. Rotation must therefore introduce a new `kid`.\n * - The whole request, response body included, is bounded by `timeoutMs` and enforced even when\n * the transport ignores the abort signal. Redirects, bytes and keys are bounded by `redirects`,\n * `maxResponseBytes` and `maxKeys`. No retry happens inside a fetch. Cancelling the last waiting\n * verification aborts the request, and a response that finishes afterwards is discarded.\n * - Request headers go only to the configured origin. `jku`, `x5u` and `jwk` headers are never\n * used.\n *\n * Throws a `ResultError` coded {@linkcode RemoteJwksConfigErrorCode} for unusable configuration.\n * Redirect destinations, and the addresses a hostname resolves to, are limited by `redirects` and\n * the transport; this module cannot see DNS answers, and browsers hide redirect targets.\n */\nexport function createRemoteJwksKeyResolver(config: RemoteJwksConfig): JwsKeyResolver {\n\tconst settings = resolveConfig(config);\n\tlet snapshot: Snapshot | undefined;\n\tlet refresh: Refresh | undefined;\n\tlet lastAttemptAt: number | undefined;\n\n\tfunction startRefresh(): Refresh {\n\t\tconst controller = new AbortController();\n\t\tconst requestedAt = settings.now();\n\t\tconst previousAttemptAt = lastAttemptAt;\n\t\tconst previous = snapshot;\n\t\tlastAttemptAt = requestedAt;\n\n\t\tasync function run(): Promise<RefreshOutcome> {\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst deadline = new Promise<typeof TIMED_OUT>((resolve) => {\n\t\t\t\ttimer = setTimeout(() => resolve(TIMED_OUT), settings.timeoutMs);\n\t\t\t});\n\t\t\tconst work = fetchJwks(settings, controller.signal, requestedAt);\n\t\t\twork.catch(() => undefined);\n\t\t\ttry {\n\t\t\t\tconst fetched = await Promise.race([work, deadline]);\n\t\t\t\tif (fetched === TIMED_OUT) {\n\t\t\t\t\tcontroller.abort();\n\t\t\t\t\treturn { kind: 'failed', failure: unavailable('The JWKS request timed out') };\n\t\t\t\t}\n\t\t\t\tif (!fetched.ok) return { kind: 'failed', failure: fetched };\n\t\t\t\treturn { kind: 'fresh', snapshot: carryOver(fetched.value, previous) };\n\t\t\t} catch {\n\t\t\t\treturn controller.signal.aborted\n\t\t\t\t\t? { kind: 'abandoned' }\n\t\t\t\t\t: { kind: 'failed', failure: unavailable('The JWKS request failed') };\n\t\t\t} finally {\n\t\t\t\tclearTimeout(timer);\n\t\t\t}\n\t\t}\n\n\t\tconst tracked: Promise<RefreshOutcome> = run()\n\t\t\t.then((outcome): RefreshOutcome => {\n\t\t\t\tif (refresh?.promise !== tracked) return { kind: 'abandoned' };\n\t\t\t\tif (outcome.kind === 'fresh') snapshot = outcome.snapshot;\n\t\t\t\treturn outcome;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tif (refresh?.promise === tracked) refresh = undefined;\n\t\t\t});\n\t\treturn {\n\t\t\tpromise: tracked,\n\t\t\tcontroller,\n\t\t\tstartedAt: requestedAt,\n\t\t\tpreviousAttemptAt,\n\t\t\twaiters: 0,\n\t\t};\n\t}\n\n\tasync function awaitRefresh(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<RefreshOutcome | typeof ABORTED> {\n\t\tif (signal?.aborted === true) return ABORTED;\n\t\trefresh ??= startRefresh();\n\t\tconst joined = refresh;\n\t\tjoined.waiters++;\n\t\tif (signal === undefined) return await joined.promise;\n\t\treturn await new Promise<RefreshOutcome | typeof ABORTED>((resolve) => {\n\t\t\tlet settled = false;\n\t\t\tconst finish = (): void => {\n\t\t\t\tsettled = true;\n\t\t\t\tsignal.removeEventListener('abort', onAbort);\n\t\t\t};\n\t\t\tconst onAbort = (): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tfinish();\n\t\t\t\tjoined.waiters--;\n\t\t\t\tif (joined.waiters === 0) {\n\t\t\t\t\tif (refresh === joined) refresh = undefined;\n\t\t\t\t\tif (lastAttemptAt === joined.startedAt) lastAttemptAt = joined.previousAttemptAt;\n\t\t\t\t\tjoined.controller.abort();\n\t\t\t\t}\n\t\t\t\tresolve(ABORTED);\n\t\t\t};\n\t\t\tsignal.addEventListener('abort', onAbort, { once: true });\n\t\t\tif (signal.aborted) onAbort();\n\t\t\tvoid joined.promise.then((outcome) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tfinish();\n\t\t\t\tresolve(outcome);\n\t\t\t});\n\t\t});\n\t}\n\n\tfunction refreshAllowed(): boolean {\n\t\tif (refresh !== undefined || lastAttemptAt === undefined) return true;\n\t\treturn settings.now() - lastAttemptAt >= settings.cooldownMs;\n\t}\n\n\tasync function obtain(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<Snapshot | undefined, FetchFailureCode | 'aborted'>> {\n\t\tif (!refreshAllowed()) return successResult(undefined);\n\t\tconst outcome = await awaitRefresh(signal);\n\t\tif (outcome === ABORTED || outcome.kind === 'abandoned') {\n\t\t\treturn joseFailure('aborted', 'Key resolution was cancelled');\n\t\t}\n\t\tif (outcome.kind === 'failed') return outcome.failure;\n\t\treturn successResult(outcome.snapshot);\n\t}\n\n\tasync function importFrom(\n\t\tcurrent: Snapshot,\n\t\tentry: SupportedJwkEntry,\n\t\talgorithm: JwsAlgorithm,\n\t): Promise<JoseResult<CryptoKey, 'key_unsuitable'>> {\n\t\tconst key = jwkEntryCacheKey(entry, algorithm);\n\t\tconst cached = current.imported.get(key);\n\t\tif (cached !== undefined) return await cached;\n\t\tconst pending = importJwkEntry(entry, algorithm);\n\t\tcurrent.imported.set(key, pending);\n\t\treturn await pending;\n\t}\n\n\tasync function currentSnapshot(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<Snapshot, FetchFailureCode | 'aborted'>> {\n\t\tif (snapshot !== undefined && settings.now() < snapshot.expiresAt) {\n\t\t\treturn successResult(snapshot);\n\t\t}\n\t\tsnapshot = undefined;\n\t\tconst loaded = await obtain(signal);\n\t\tif (!loaded.ok) return loaded;\n\t\treturn loaded.value === undefined\n\t\t\t? unavailable('The JWKS endpoint is in cooldown')\n\t\t\t: successResult(loaded.value);\n\t}\n\n\tasync function select(\n\t\tcurrent: Snapshot,\n\t\tselector: JwkSelector,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<CryptoKey, KeyResolutionErrorCode>> {\n\t\tlet source = current;\n\t\tlet selected = selectJwk(source.jwks, selector);\n\t\tif (!selected.ok && selected.code === 'key_not_found') {\n\t\t\tconst reloaded = await obtain(signal);\n\t\t\tif (!reloaded.ok) return reloaded;\n\t\t\tif (reloaded.value !== undefined) {\n\t\t\t\tsource = reloaded.value;\n\t\t\t\tselected = selectJwk(source.jwks, selector);\n\t\t\t}\n\t\t}\n\t\tif (!selected.ok) return selected;\n\t\tconst key = await importFrom(source, selected.value, selector.algorithm);\n\t\treturn signal?.aborted === true ? joseFailure('aborted', 'Key resolution was cancelled') : key;\n\t}\n\n\treturn async (request: JwsKeyRequest) => {\n\t\tif (request.signal?.aborted === true) {\n\t\t\treturn joseFailure('aborted', 'Key resolution was cancelled');\n\t\t}\n\t\tconst current = await currentSnapshot(request.signal);\n\t\tif (!current.ok) return current;\n\t\treturn await select(\n\t\t\tcurrent.value,\n\t\t\t{ algorithm: request.algorithm, ...(request.kid === undefined ? {} : { kid: request.kid }) },\n\t\t\trequest.signal,\n\t\t);\n\t};\n}\n"],"mappings":";;;;;AAwGA,MAAMA,IAAyB,OAAO,uBAAuB,GAEvDC,IAAW;CAChB,WAAW;CACX,kBAAkB;CAClB,SAAS;CACT,cAAc;CACd,UAAU;CACV,YAAY;AACb,GAEMC,oBAAyC,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC,GAE1EC,oBAAsC,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;AAEvF,SAAS,eAAe,GAAmB;CAC1C,OACCC,EAAI,aAAa,YAAaA,EAAI,aAAa,WAAWD,EAAe,IAAIC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C2C,EAAS,IAAI,OAAOA;GACzB,AAAIA,EAAS,UAAU,KAAA,MACtB,IAASA,EAAS,OAClB,IAAWF,EAAUF,EAAO,MAAMG,CAAQ;EAE5C;EACA,IAAI,CAACF,EAAS,IAAI,OAAOA;EACzB,IAAMzB,IAAM,MAAM,WAAWwB,GAAQC,EAAS,OAAOE,EAAS,SAAS;EACvE,OAAO1C,GAAQ,YAAY,KAAOzB,EAAY,WAAW,8BAA8B,IAAIwC;CAC5F;CAEA,OAAO,OAAO,MAA2B;EACxC,IAAI6B,EAAQ,QAAQ,YAAY,IAC/B,OAAOrE,EAAY,WAAW,8BAA8B;EAE7D,IAAM4D,IAAU,MAAM,gBAAgBS,EAAQ,MAAM;EAEpD,OADKT,EAAQ,KACN,MAAM,OACZA,EAAQ,OACR;GAAE,WAAWS,EAAQ;GAAW,GAAIA,EAAQ,QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,KAAKA,EAAQ,IAAI;EAAG,GAC3FA,EAAQ,MACT,IALwBT;CAMzB;AACD"}
|
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 {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
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 {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
|
|
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 };
|
package/dist/kdf/argon2.d.ts
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Argon2 derivation and resource-policy boundary. The default backend prefers
|
|
3
|
+
* native WebCrypto and uses the TypeScript implementation when unsupported.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
1
7
|
import { Micro509Error, Result } from "../result/result.js";
|
|
2
8
|
/** RFC 9106 Argon2 variants. Use Argon2id for new password-based applications. */
|
|
3
9
|
export type Argon2Algorithm = "argon2d" | "argon2i" | "argon2id";
|
|
@@ -80,5 +86,4 @@ export interface Argon2Options {
|
|
|
80
86
|
* is erased on completion or failure.
|
|
81
87
|
* Limits apply per call, not to concurrent invocations.
|
|
82
88
|
*/
|
|
83
|
-
export declare function deriveArgon2(input: Argon2Input, options?: Argon2Options): Promise<Argon2Result>;
|
|
84
|
-
//# sourceMappingURL=argon2.d.ts.map
|
|
89
|
+
export declare function deriveArgon2(input: Argon2Input, options?: Argon2Options): Promise<Argon2Result>;
|
package/dist/kdf.d.ts
CHANGED
|
@@ -1,2 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optional byte-oriented Argon2 key derivation with explicit resource limits.
|
|
3
|
+
* Import this entrypoint directly. Certificate APIs do not load it.
|
|
4
|
+
*
|
|
5
|
+
* @module micro509/kdf
|
|
6
|
+
*/
|
|
1
7
|
import { Argon2Algorithm, Argon2Backend, Argon2ErrorCode, Argon2Input, Argon2Limits, Argon2Options, Argon2Result, Argon2Version, deriveArgon2 } from "./kdf/argon2.js";
|
|
2
8
|
export { type Argon2Algorithm, type Argon2Backend, type Argon2ErrorCode, type Argon2Input, type Argon2Limits, type Argon2Options, type Argon2Result, type Argon2Version, deriveArgon2 };
|