micro509 0.15.0 → 0.17.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 (55) hide show
  1. package/CHANGELOG.md +130 -1
  2. package/dist/index.d.ts +2 -2
  3. package/dist/index.js +3 -3
  4. package/dist/internal/jose/base64url.js +40 -0
  5. package/dist/internal/jose/base64url.js.map +1 -0
  6. package/dist/internal/jose/strict-json.d.ts +9 -0
  7. package/dist/internal/jose/strict-json.js +155 -0
  8. package/dist/internal/jose/strict-json.js.map +1 -0
  9. package/dist/internal/verify/spki-distrust.js +23 -0
  10. package/dist/internal/verify/spki-distrust.js.map +1 -0
  11. package/dist/internal/verify/verify-path.js +77 -60
  12. package/dist/internal/verify/verify-path.js.map +1 -1
  13. package/dist/jose/errors.d.ts +44 -0
  14. package/dist/jose/errors.js +11 -0
  15. package/dist/jose/errors.js.map +1 -0
  16. package/dist/jose/jwks.d.ts +93 -0
  17. package/dist/jose/jwks.js +193 -0
  18. package/dist/jose/jwks.js.map +1 -0
  19. package/dist/jose/jws.d.ts +158 -0
  20. package/dist/jose/jws.js +362 -0
  21. package/dist/jose/jws.js.map +1 -0
  22. package/dist/jose/jwt.d.ts +91 -0
  23. package/dist/jose/jwt.js +187 -0
  24. package/dist/jose/jwt.js.map +1 -0
  25. package/dist/jose/remote-jwks.d.ts +95 -0
  26. package/dist/jose/remote-jwks.js +298 -0
  27. package/dist/jose/remote-jwks.js.map +1 -0
  28. package/dist/jose.d.ts +7 -0
  29. package/dist/jose.js +5 -0
  30. package/dist/kdf/argon2.d.ts +78 -0
  31. package/dist/kdf/argon2.js +167 -0
  32. package/dist/kdf/argon2.js.map +1 -0
  33. package/dist/kdf.d.ts +2 -0
  34. package/dist/kdf.js +1 -0
  35. package/dist/keys/keys.d.ts +11 -8
  36. package/dist/keys/keys.js.map +1 -1
  37. package/dist/revocation/crl.js +2 -7
  38. package/dist/revocation/crl.js.map +1 -1
  39. package/dist/ssh/ssh.d.ts +200 -0
  40. package/dist/ssh/ssh.js +648 -0
  41. package/dist/ssh/ssh.js.map +1 -0
  42. package/dist/ssh/wire.d.ts +3 -0
  43. package/dist/ssh/wire.js +105 -0
  44. package/dist/ssh/wire.js.map +1 -0
  45. package/dist/ssh.d.ts +3 -0
  46. package/dist/ssh.js +1 -0
  47. package/dist/verify/verify.d.ts +32 -1
  48. package/dist/verify/verify.js +100 -58
  49. package/dist/verify/verify.js.map +1 -1
  50. package/dist/x509/fingerprint.d.ts +11 -0
  51. package/dist/x509/fingerprint.js +19 -1
  52. package/dist/x509/fingerprint.js.map +1 -1
  53. package/dist/x509.d.ts +2 -2
  54. package/dist/x509.js +3 -3
  55. package/package.json +20 -6
@@ -0,0 +1,362 @@
1
+ import { successResult as e, throwMicro509Error as t } from "../result/result.js";
2
+ import { OIDS as n } from "../internal/asn1/oids2.js";
3
+ import { signData as r, verifySignatureWithKey as i } from "../crypto/crypto.js";
4
+ import { base64UrlDecode as a, base64UrlEncode as o } from "../internal/jose/base64url.js";
5
+ import { isJsonArray as s, isJsonObject as c, parseStrictJson as l } from "../internal/jose/strict-json.js";
6
+ import { joseFailure as u } from "./errors.js";
7
+ // src/jose/jws.ts
8
+ /**
9
+ * Compact JWS (RFC 7515) parsing, signing and verification with an explicit algorithm and token
10
+ * type policy. Parsing yields an {@linkcode UnverifiedJws}; only {@linkcode verifyCompactJws}
11
+ * yields a {@linkcode VerifiedJws}.
12
+ *
13
+ * @module
14
+ */
15
+ /** Every {@linkcode JwsAlgorithm}. */
16
+ const d = ["RS256"], f = 2048, p = {
17
+ maxTokenLength: 32768,
18
+ maxHeaderBytes: 4096,
19
+ maxPayloadBytes: 16384,
20
+ maxSignatureBytes: 1024,
21
+ maxJsonDepth: 16,
22
+ maxJsonNodes: 2048
23
+ }, m = [
24
+ "maxTokenLength",
25
+ "maxHeaderBytes",
26
+ "maxPayloadBytes",
27
+ "maxSignatureBytes",
28
+ "maxJsonDepth",
29
+ "maxJsonNodes"
30
+ ];
31
+ /**
32
+ * Resolves caller-supplied limit overrides against {@linkcode DEFAULT_JOSE_LIMITS}. An omitted or
33
+ * `undefined` field takes its default; any other value must be a positive safe integer, and
34
+ * `maxJsonDepth` may not exceed {@linkcode MAX_JSON_DEPTH_LIMIT}.
35
+ */
36
+ function resolveJoseLimits(t) {
37
+ if (t !== void 0 && (typeof t != "object" || !t)) return u("invalid_options", "limits must be an object");
38
+ let n = { ...p };
39
+ for (let e of m) {
40
+ let r = t?.[e];
41
+ if (r === void 0) continue;
42
+ let i = e === "maxJsonDepth" ? 64 : 2 ** 53 - 1;
43
+ if (!Number.isSafeInteger(r) || r < 1 || r > i) return u("invalid_options", `limits.${e} must be a positive safe integer`);
44
+ n[e] = r;
45
+ }
46
+ return e(n);
47
+ }
48
+ const h = new TextEncoder(), g = new TextDecoder("utf-8", {
49
+ fatal: !0,
50
+ ignoreBOM: !0
51
+ });
52
+ function maxEncodedLength(e) {
53
+ return Math.ceil(e * 4 / 3);
54
+ }
55
+ function parseFailure(e, t) {
56
+ return u(e, t);
57
+ }
58
+ function decodeSegment(t, n, r) {
59
+ if (t.length > maxEncodedLength(n)) return parseFailure("limit_exceeded", `JWS ${r} exceeds ${n} bytes`);
60
+ let i = a(t);
61
+ return i === void 0 ? parseFailure("invalid_encoding", `JWS ${r} is not canonical base64url`) : e(i);
62
+ }
63
+ /** Decodes UTF-8 strictly and parses it as a JSON object with no duplicate members. */
64
+ function decodeJsonObject(t, n, r, i) {
65
+ let a;
66
+ try {
67
+ a = g.decode(t);
68
+ } catch {
69
+ return parseFailure("invalid_utf8", `JWS ${r} is not valid UTF-8`);
70
+ }
71
+ let o = l(a, {
72
+ maxDepth: n.maxJsonDepth,
73
+ maxNodes: n.maxJsonNodes
74
+ });
75
+ if (!o.ok) return parseFailure(o.code, `JWS ${r}: ${o.message}`);
76
+ let s = o.value;
77
+ return c(s) ? e(s) : parseFailure(i, `JWS ${r} is not a JSON object`);
78
+ }
79
+ function optionalString(t, n) {
80
+ if (!Object.hasOwn(t, n)) return e(void 0);
81
+ let r = t[n];
82
+ return typeof r == "string" ? e(r) : parseFailure("invalid_header", `JWS header "${n}" is not a string`);
83
+ }
84
+ function criticalNames(t) {
85
+ if (!Object.hasOwn(t, "crit")) return e([]);
86
+ let n = t.crit;
87
+ if (!s(n) || n.length === 0) return parseFailure("invalid_header", "JWS header \"crit\" is not a non-empty array");
88
+ let r = [];
89
+ for (let e of n) {
90
+ if (typeof e != "string" || r.includes(e)) return parseFailure("invalid_header", "JWS header \"crit\" holds a non-string or repeated name");
91
+ r.push(e);
92
+ }
93
+ return e(r);
94
+ }
95
+ function parseHeader(t, n) {
96
+ let r = decodeJsonObject(t, n, "header", "invalid_header");
97
+ if (!r.ok) return r;
98
+ let i = r.value, a = i.alg;
99
+ if (typeof a != "string" || a.length === 0) return parseFailure("invalid_header", "JWS header \"alg\" is missing or not a string");
100
+ let o = optionalString(i, "typ");
101
+ if (!o.ok) return o;
102
+ let s = optionalString(i, "kid");
103
+ if (!s.ok) return s;
104
+ let c = optionalString(i, "cty");
105
+ if (!c.ok) return c;
106
+ let l = criticalNames(i);
107
+ return l.ok ? i.b64 === !1 || l.value.includes("b64") ? parseFailure("unsupported_unencoded_payload", "Unencoded and detached payloads (RFC 7797) are not supported") : Object.hasOwn(i, "b64") && typeof i.b64 != "boolean" ? parseFailure("invalid_header", "JWS header \"b64\" is not a boolean") : l.value.length > 0 ? u("unsupported_critical_header", "JWS header lists critical extensions", {
108
+ alg: a,
109
+ crit: l.value
110
+ }) : e({
111
+ alg: a,
112
+ ...o.value === void 0 ? {} : { typ: o.value },
113
+ ...s.value === void 0 ? {} : { kid: s.value },
114
+ ...c.value === void 0 ? {} : { cty: c.value },
115
+ members: i
116
+ }) : l;
117
+ }
118
+ /**
119
+ * Parses a compact JWS without checking its signature.
120
+ *
121
+ * Refuses tokens that are oversized, do not have exactly three segments, carry non-canonical
122
+ * base64url, invalid UTF-8, a header that is not a duplicate-free JSON object with a string `alg`,
123
+ * a `crit` list, or an unencoded payload (`b64: false`). The result is {@linkcode UnverifiedJws};
124
+ * pass the token to {@linkcode verifyCompactJws} before trusting any of it.
125
+ */
126
+ function parseCompactJws(e, t) {
127
+ let n = resolveJoseLimits(t);
128
+ return n.ok ? parseWithLimits(e, n.value) : n;
129
+ }
130
+ function parseWithLimits(t, n) {
131
+ if (typeof t != "string") return parseFailure("malformed_token", "JWS token is not a string");
132
+ if (t.length > n.maxTokenLength) return parseFailure("token_too_large", `JWS token exceeds ${n.maxTokenLength} characters`);
133
+ let r = t.split("."), [i, a, o] = r;
134
+ if (r.length !== 3 || i === void 0 || a === void 0 || o === void 0 || i.length === 0) return parseFailure("malformed_token", "JWS compact serialization needs three segments");
135
+ let s = decodeSegment(i, n.maxHeaderBytes, "header");
136
+ if (!s.ok) return s;
137
+ let c = parseHeader(s.value, n);
138
+ if (!c.ok) return c;
139
+ let l = decodeSegment(a, n.maxPayloadBytes, "payload");
140
+ if (!l.ok) return l;
141
+ let u = decodeSegment(o, n.maxSignatureBytes, "signature");
142
+ return u.ok ? e({
143
+ verified: !1,
144
+ header: c.value,
145
+ payload: l.value,
146
+ signingInput: h.encode(`${i}.${a}`),
147
+ signature: u.value
148
+ }) : u;
149
+ }
150
+ /**
151
+ * Comparison key for a media type per RFC 7515 §4.1.9: type, subtype and parameter names fold to
152
+ * lower case, an omitted `application/` is restored, and parameter values stay exact.
153
+ */
154
+ function mediaTypeKey(e) {
155
+ let [t = "", ...n] = e.split(";"), r = t.trim().toLowerCase(), i = n.map((e) => {
156
+ let t = e.indexOf("=");
157
+ return t < 0 ? e.trim().toLowerCase() : `${e.slice(0, t).trim().toLowerCase()}=${e.slice(t + 1).trim()}`;
158
+ });
159
+ return [r.includes("/") ? r : `application/${r}`, ...i].join(";");
160
+ }
161
+ /** Whether `value` is exactly `{ unchecked: true }`. */
162
+ function isUncheckedPolicy(e) {
163
+ return soleTrueMember(e) === "unchecked";
164
+ }
165
+ function soleTrueMember(e) {
166
+ if (typeof e != "object" || !e || Array.isArray(e)) return;
167
+ let t = Object.keys(e), [n] = t;
168
+ if (t.length === 1 && n !== void 0) return Reflect.get(e, n) === !0 ? n : void 0;
169
+ }
170
+ function normalizeTokenType(e) {
171
+ if (typeof e == "string") return {
172
+ kind: "media",
173
+ key: mediaTypeKey(e)
174
+ };
175
+ let t = soleTrueMember(e);
176
+ if (t === "absent") return { kind: "absent" };
177
+ if (t === "unchecked") return { kind: "unchecked" };
178
+ }
179
+ function matchesTokenType(e, t) {
180
+ switch (t.kind) {
181
+ case "media": return e.typ !== void 0 && mediaTypeKey(e.typ) === t.key;
182
+ case "unchecked": return !0;
183
+ case "absent": return e.typ === void 0;
184
+ default: return t;
185
+ }
186
+ }
187
+ function isAlgorithmAdmitted(e, t) {
188
+ return t.includes(e) && d.some((t) => t === e);
189
+ }
190
+ /** Checks the observable RSA exponent constraints in RFC 8017 section 3.1. */
191
+ function validRsaPublicExponent(e, t) {
192
+ let n = e.findIndex((e) => e !== 0), r = e[e.length - 1] ?? 0;
193
+ if (n < 0 || !(r & 1)) return !1;
194
+ let i = e.length - n;
195
+ if (i === 1 && r < 3) return !1;
196
+ if (t === void 0) return !0;
197
+ if (i !== t.length) return i < t.length;
198
+ for (let r = 0; r < i; r++) {
199
+ let i = e[n + r] ?? 0, a = t[r] ?? 0;
200
+ if (i !== a) return i < a;
201
+ }
202
+ return !1;
203
+ }
204
+ /**
205
+ * Checks a key may verify RS256 (RFC 7518 §3.3, RFC 8725 §3.1) and returns the signature length
206
+ * in bytes it requires (RFC 8017 §8.2.2).
207
+ */
208
+ function checkRs256VerificationKey(e) {
209
+ try {
210
+ return inspectRs256VerificationKey(e);
211
+ } catch {
212
+ return u("key_unsuitable", "The key cannot be inspected");
213
+ }
214
+ }
215
+ function inspectRs256VerificationKey(t) {
216
+ let n = t.algorithm;
217
+ return t.type !== "public" || !t.usages.includes("verify") ? u("key_unsuitable", "RS256 needs a public key with verify usage") : n.name !== "RSASSA-PKCS1-v1_5" || !("hash" in n) || typeof n.hash != "object" || n.hash === null || !("name" in n.hash) || n.hash.name !== "SHA-256" ? u("key_unsuitable", "RS256 needs an RSASSA-PKCS1-v1_5 SHA-256 key") : !("modulusLength" in n) || typeof n.modulusLength != "number" || n.modulusLength < 2048 ? u("key_unsuitable", `RS256 needs an RSA modulus of at least ${f} bits`) : !("publicExponent" in n) || !(n.publicExponent instanceof Uint8Array) || !validRsaPublicExponent(n.publicExponent) ? u("key_unsuitable", "RS256 needs a valid odd RSA public exponent of at least 3") : e(Math.ceil(n.modulusLength / 8));
218
+ }
219
+ function isCryptoKey(e) {
220
+ return e instanceof CryptoKey;
221
+ }
222
+ /** Validates and copies verification options. Everything the run reads is captured here. */
223
+ function prepareVerify(t) {
224
+ if (typeof t != "object" || !t) return u("invalid_options", "Verification options are required");
225
+ let { algorithms: n, key: r, tokenType: i, limits: a, signal: o } = t;
226
+ if (!Array.isArray(n) || n.length === 0) return u("invalid_options", "An explicit, non-empty algorithm list is required");
227
+ let s = [];
228
+ for (let e of n) {
229
+ let t = d.find((t) => t === e);
230
+ if (t === void 0) return u("invalid_options", "The algorithm list names an unsupported algorithm");
231
+ s.push(t);
232
+ }
233
+ if (typeof r != "function" && !isCryptoKey(r)) return u("invalid_options", "A key or key resolver is required");
234
+ let c = normalizeTokenType(i);
235
+ if (c === void 0) return u("invalid_options", "A token type policy is required");
236
+ if (o !== void 0 && !(o instanceof AbortSignal)) return u("invalid_options", "signal must be an AbortSignal");
237
+ let l = resolveJoseLimits(a);
238
+ return l.ok ? e({
239
+ algorithms: s,
240
+ key: r,
241
+ typeRule: c,
242
+ limits: l.value,
243
+ signal: o
244
+ }) : l;
245
+ }
246
+ async function resolveKey(t, n) {
247
+ let { key: r, signal: i } = t;
248
+ if (typeof r != "function") return e(r);
249
+ let a;
250
+ try {
251
+ a = await r({
252
+ header: n,
253
+ algorithm: n.alg,
254
+ ...n.kid === void 0 ? {} : { kid: n.kid },
255
+ ...i === void 0 ? {} : { signal: i }
256
+ });
257
+ } catch {
258
+ return i?.aborted === !0 ? u("aborted", "Key resolution was cancelled") : u("key_resolution_failed", "The key resolver failed");
259
+ }
260
+ if (typeof a != "object" || !a) return u("key_resolution_failed", "The key resolver returned no result");
261
+ if (Reflect.get(a, "ok") === !0) {
262
+ let t = Reflect.get(a, "value");
263
+ return isCryptoKey(t) ? e(t) : u("key_resolution_failed", "The key resolver returned no key");
264
+ }
265
+ let o = Reflect.get(a, "code");
266
+ switch (o) {
267
+ case "key_not_found":
268
+ case "ambiguous_key":
269
+ case "key_unsuitable":
270
+ case "key_resolution_failed":
271
+ case "jwks_unavailable":
272
+ case "jwks_malformed":
273
+ case "aborted": return u(o, `Key resolution failed: ${o}`, resolverDetails(a));
274
+ default: return u("key_resolution_failed", "The key resolver returned an unknown failure");
275
+ }
276
+ }
277
+ function resolverDetails(e) {
278
+ let t = Reflect.get(e, "details");
279
+ if (typeof t != "object" || !t) return;
280
+ let n = Reflect.get(t, "kid"), r = Reflect.get(t, "status");
281
+ return {
282
+ ...typeof n == "string" ? { kid: n } : {},
283
+ ...typeof r == "number" && Number.isSafeInteger(r) ? { status: r } : {}
284
+ };
285
+ }
286
+ /**
287
+ * Verifies a compact JWS.
288
+ *
289
+ * The caller's `algorithms` list decides what is accepted; the token's `alg` only selects among
290
+ * them, and `none` is always refused as `unsigned_token`. The `tokenType` policy is applied before
291
+ * any key is resolved. A fixed key or the resolver's key must be an RSASSA-PKCS1-v1_5 SHA-256
292
+ * public key of at least 2048 bits for RS256. Header members such as `jku`, `jwk`, `x5u` and
293
+ * `x5c` are never used to find a key. A resolver that throws or returns something other than a
294
+ * result is reported as `key_resolution_failed` without its message.
295
+ *
296
+ * Returns a {@linkcode VerifiedJws} on success. Failures carry a stable code and never echo the
297
+ * token.
298
+ */
299
+ async function verifyCompactJws(e, t) {
300
+ let n = prepareVerify(t);
301
+ return n.ok ? await verifyPrepared(e, n.value) : n;
302
+ }
303
+ /** Verifies `token` under options already checked by {@linkcode prepareVerify}. */
304
+ async function verifyPrepared(t, r) {
305
+ let a = parseWithLimits(t, r.limits);
306
+ if (!a.ok) return a;
307
+ let o = a.value, s = o.header.alg;
308
+ if (s === "none") return u("unsigned_token", "Unsigned tokens are never accepted", { alg: s });
309
+ if (!isAlgorithmAdmitted(s, r.algorithms)) return u("algorithm_not_allowed", "The token algorithm is not in the allowed list", { alg: s });
310
+ if (!matchesTokenType(o.header, r.typeRule)) return u("token_type_mismatch", "The token \"typ\" does not match the expected type", { alg: s });
311
+ let c = {
312
+ ...o.header,
313
+ alg: s
314
+ }, l = await resolveKey(r, c);
315
+ if (!l.ok) return l;
316
+ let d = checkRs256VerificationKey(l.value);
317
+ if (!d.ok) return d;
318
+ if (o.signature.length !== d.value) return u("invalid_signature", "The signature length differs from the modulus", { alg: s });
319
+ let f = u("invalid_signature", "The signature does not verify", {
320
+ alg: s,
321
+ ...c.kid === void 0 ? {} : { kid: c.kid }
322
+ }), p = await i({
323
+ publicKey: l.value,
324
+ signatureAlgorithm: { oid: n.sha256WithRSAEncryption },
325
+ signatureEncoding: "raw",
326
+ signature: o.signature,
327
+ data: o.signingInput
328
+ });
329
+ return !p.ok || !p.valid ? f : e({
330
+ verified: !0,
331
+ header: c,
332
+ payload: o.payload
333
+ });
334
+ }
335
+ function assertSigningKey(e) {
336
+ let n = e.privateKey.algorithm;
337
+ d.includes(e.algorithm) || t("unsupported_algorithm", "Unsupported JWS algorithm"), (e.privateKey.type !== "private" || !e.privateKey.usages.includes("sign") || n.name !== "RSASSA-PKCS1-v1_5" || !("hash" in n) || typeof n.hash != "object" || n.hash === null || !("name" in n.hash) || n.hash.name !== "SHA-256" || !("modulusLength" in n) || typeof n.modulusLength != "number" || n.modulusLength < 2048) && t("incompatible_key", `RS256 signing needs an RSASSA-PKCS1-v1_5 SHA-256 private key of at least ${f} bits`);
338
+ }
339
+ /**
340
+ * Signs a compact JWS with an existing private `CryptoKey`.
341
+ *
342
+ * The header is `alg` followed by the optional `typ`, `kid` and `cty`. Throws a `ResultError`
343
+ * (see `isResultError`) coded {@linkcode SignJoseErrorCode} when the algorithm, key or header
344
+ * input is invalid. Intended for issuing tokens and for building synthetic tokens in tests.
345
+ */
346
+ async function signCompactJws(e) {
347
+ assertSigningKey(e);
348
+ let n = { alg: e.algorithm };
349
+ for (let r of [
350
+ "typ",
351
+ "kid",
352
+ "cty"
353
+ ]) {
354
+ let i = e.header?.[r];
355
+ i !== void 0 && (typeof i != "string" && t("invalid_header", `Header "${r}" must be a string`), n[r] = i);
356
+ }
357
+ let i = `${o(h.encode(JSON.stringify(n)))}.${o(e.payload)}`, { signature: a } = await r(e.privateKey, h.encode(i));
358
+ return `${i}.${o(a)}`;
359
+ }
360
+ export { p as DEFAULT_JOSE_LIMITS, d as JWS_ALGORITHMS, f as MIN_RS256_MODULUS_BITS, checkRs256VerificationKey, decodeJsonObject, isUncheckedPolicy, mediaTypeKey, parseCompactJws, prepareVerify, resolveJoseLimits, signCompactJws, validRsaPublicExponent, verifyCompactJws, verifyPrepared };
361
+
362
+ //# sourceMappingURL=jws.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jws.js","names":["_exhaustive","JWS_ALGORITHMS","MIN_RS256_MODULUS_BITS","DEFAULT_JOSE_LIMITS","LIMIT_NAMES","overrides","joseFailure","resolved","name","value","ceiling","successResult","textEncoder","strictDecoder","decodedBytes","code","message","segment","maxBytes","bytes","base64UrlDecode","text","parsed","parseStrictJson","limits","isJsonObject","notObjectCode","members","crit","isJsonArray","names","entry","object","alg","typ","kid","cty","token","bounds","segments","headerSegment","payloadSegment","signatureSegment","headerBytes","header","payload","signature","essence","parameters","type","normalized","separator","parameter","policy","member","rule","admitted","algorithm","supported","first","exponent","byte","last","length","modulus","i","left","right","key","options","algorithms","candidate","typeRule","tokenType","signal","prepared","details","status","unverified","signatureBytes","failure","verification","verifySignatureWithKey","OIDS","input","throwMicro509Error","signingInput","base64UrlEncode","signData"],"sources":["../../src/jose/jws.ts"],"sourcesContent":["/**\n * Compact JWS (RFC 7515) parsing, signing and verification with an explicit algorithm and token\n * type policy. Parsing yields an {@linkcode UnverifiedJws}; only {@linkcode verifyCompactJws}\n * yields a {@linkcode VerifiedJws}.\n *\n * @module\n */\n\nimport { signData, verifySignatureWithKey } from '#micro509/crypto/crypto';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { base64UrlDecode, base64UrlEncode } from '#micro509/internal/jose/base64url';\nimport type { JsonObject, JsonValue } from '#micro509/internal/jose/strict-json';\nimport { isJsonArray, isJsonObject, parseStrictJson } from '#micro509/internal/jose/strict-json';\nimport type {\n\tJoseErrorDetails,\n\tJoseErrorResult,\n\tJoseResult,\n\tJwsParseErrorCode,\n\tKeyResolutionErrorCode,\n\tVerifyJwsErrorCode,\n} from '#micro509/jose/errors';\nimport { joseFailure } from '#micro509/jose/errors';\nimport { successResult, throwMicro509Error } from '#micro509/result/result';\n\n/** Signature algorithms this module signs and verifies. */\nexport type JwsAlgorithm = 'RS256';\n\n/** Every {@linkcode JwsAlgorithm}. */\nexport const JWS_ALGORITHMS: readonly JwsAlgorithm[] = ['RS256'];\n\n/** Smallest RSA modulus RS256 accepts (RFC 7518 §3.3). */\nexport const MIN_RS256_MODULUS_BITS = 2048;\n\n/** Size and structure bounds enforced before any expensive parsing. */\nexport interface JoseLimits {\n\t/** Maximum compact serialization length in characters. Default `32768`. */\n\treadonly maxTokenLength: number;\n\t/** Maximum decoded protected header size in bytes. Default `4096`. */\n\treadonly maxHeaderBytes: number;\n\t/** Maximum decoded payload size in bytes. Default `16384`. */\n\treadonly maxPayloadBytes: number;\n\t/** Maximum decoded signature size in bytes. Default `1024`. */\n\treadonly maxSignatureBytes: number;\n\t/** Maximum JSON nesting in the header and payload. Default `16`. */\n\treadonly maxJsonDepth: number;\n\t/** Maximum JSON values in the header or payload. Default `2048`. */\n\treadonly maxJsonNodes: number;\n}\n\n/** The limits applied when a caller supplies none. */\nexport const DEFAULT_JOSE_LIMITS: JoseLimits = {\n\tmaxTokenLength: 32_768,\n\tmaxHeaderBytes: 4096,\n\tmaxPayloadBytes: 16_384,\n\tmaxSignatureBytes: 1024,\n\tmaxJsonDepth: 16,\n\tmaxJsonNodes: 2048,\n};\n\nconst LIMIT_NAMES = [\n\t'maxTokenLength',\n\t'maxHeaderBytes',\n\t'maxPayloadBytes',\n\t'maxSignatureBytes',\n\t'maxJsonDepth',\n\t'maxJsonNodes',\n] as const;\n\n/** Deepest JSON nesting any limit may allow; keeps the recursive parser inside the stack. */\nexport const MAX_JSON_DEPTH_LIMIT = 64;\n\n/**\n * Resolves caller-supplied limit overrides against {@linkcode DEFAULT_JOSE_LIMITS}. An omitted or\n * `undefined` field takes its default; any other value must be a positive safe integer, and\n * `maxJsonDepth` may not exceed {@linkcode MAX_JSON_DEPTH_LIMIT}.\n */\nexport function resolveJoseLimits(\n\toverrides: Partial<JoseLimits> | undefined,\n): JoseResult<JoseLimits, 'invalid_options'> {\n\tif (overrides !== undefined && (typeof overrides !== 'object' || overrides === null)) {\n\t\treturn joseFailure('invalid_options', 'limits must be an object');\n\t}\n\tconst resolved: { -readonly [Name in keyof JoseLimits]: JoseLimits[Name] } = {\n\t\t...DEFAULT_JOSE_LIMITS,\n\t};\n\tfor (const name of LIMIT_NAMES) {\n\t\tconst value = overrides?.[name];\n\t\tif (value === undefined) continue;\n\t\tconst ceiling = name === 'maxJsonDepth' ? MAX_JSON_DEPTH_LIMIT : Number.MAX_SAFE_INTEGER;\n\t\tif (!Number.isSafeInteger(value) || value < 1 || value > ceiling) {\n\t\t\treturn joseFailure('invalid_options', `limits.${name} must be a positive safe integer`);\n\t\t}\n\t\tresolved[name] = value;\n\t}\n\treturn successResult(resolved);\n}\n\n/** A protected header. Every member the token carried stays reachable through `members`. */\nexport interface JwsHeader<TAlgorithm extends string = string> {\n\t/** The `alg` member. */\n\treadonly alg: TAlgorithm;\n\t/** The `typ` member, when present. */\n\treadonly typ?: string;\n\t/** The `kid` member, when present. */\n\treadonly kid?: string;\n\t/** The `cty` member, when present. */\n\treadonly cty?: string;\n\t/** Every header member as the token carried it. */\n\treadonly members: JsonObject;\n}\n\n/**\n * A parsed token whose signature has not been checked. Nothing in it is trustworthy until\n * {@linkcode verifyCompactJws} succeeds.\n */\nexport interface UnverifiedJws {\n\t/** Always `false`. */\n\treadonly verified: false;\n\t/** The header, unauthenticated. */\n\treadonly header: JwsHeader;\n\t/** The payload bytes, unauthenticated. */\n\treadonly payload: Uint8Array;\n\t/** ASCII bytes of `BASE64URL(header) || '.' || BASE64URL(payload)`. */\n\treadonly signingInput: Uint8Array;\n\t/** The decoded signature bytes. */\n\treadonly signature: Uint8Array;\n}\n\n/** A token whose signature verified under the caller's algorithm and key policy. */\nexport interface VerifiedJws {\n\t/** Always `true`. */\n\treadonly verified: true;\n\t/** The authenticated protected header. */\n\treadonly header: JwsHeader<JwsAlgorithm>;\n\t/** The authenticated payload bytes. */\n\treadonly payload: Uint8Array;\n}\n\n/** What a key resolver is asked for. The header is unauthenticated. */\nexport interface JwsKeyRequest {\n\t/** The unauthenticated header of the token being verified. */\n\treadonly header: JwsHeader<JwsAlgorithm>;\n\t/** The algorithm the policy admitted for this token. */\n\treadonly algorithm: JwsAlgorithm;\n\t/** The `kid` header, when present. */\n\treadonly kid?: string;\n\t/** Cancellation from {@linkcode VerifyJwsOptions.signal}. */\n\treadonly signal?: AbortSignal;\n}\n\n/** Supplies the verification key for a token. */\nexport type JwsKeyResolver = (\n\trequest: JwsKeyRequest,\n) => Promise<JoseResult<CryptoKey, KeyResolutionErrorCode>>;\n\n/** Marks a policy dimension as deliberately not checked. */\nexport interface Unchecked {\n\t/** Always `true`. */\n\treadonly unchecked: true;\n}\n\n/**\n * Expectation for the `typ` header (RFC 7515 §4.1.9, RFC 8725 §3.11).\n *\n * A string requires that media type, compared case-insensitively with an omitted `application/`\n * prefix restored. `{ absent: true }` requires the header to be missing. `{ unchecked: true }`\n * accepts any value.\n */\nexport type TokenTypePolicy = string | { readonly absent: true } | Unchecked;\n\n/** Options for {@linkcode verifyCompactJws}. */\nexport interface VerifyJwsOptions {\n\t/** Algorithms admitted for this token use. Never derived from the token. */\n\treadonly algorithms: readonly [JwsAlgorithm, ...JwsAlgorithm[]];\n\t/** A fixed verification key, or a resolver chosen by the caller. */\n\treadonly key: CryptoKey | JwsKeyResolver;\n\t/** The token type this verification accepts. */\n\treadonly tokenType: TokenTypePolicy;\n\t/** Overrides for {@linkcode DEFAULT_JOSE_LIMITS}. */\n\treadonly limits?: Partial<JoseLimits>;\n\t/** Cancels key resolution. */\n\treadonly signal?: AbortSignal;\n}\n\n/** Header members {@linkcode signCompactJws} sets beside `alg`. */\nexport interface JwsHeaderInput {\n\t/** Token type. */\n\treadonly typ?: string;\n\t/** Key identifier. */\n\treadonly kid?: string;\n\t/** Content type. */\n\treadonly cty?: string;\n}\n\n/** Input for {@linkcode signCompactJws}. */\nexport interface SignJwsInput {\n\t/** An RSASSA-PKCS1-v1_5 SHA-256 private key of at least 2048 bits. */\n\treadonly privateKey: CryptoKey;\n\t/** The signature algorithm. */\n\treadonly algorithm: JwsAlgorithm;\n\t/** The payload bytes. */\n\treadonly payload: Uint8Array;\n\t/** Header members beside `alg`. */\n\treadonly header?: JwsHeaderInput;\n}\n\n/** Codes {@linkcode signCompactJws} and {@linkcode signJwt} throw. */\nexport type SignJoseErrorCode =\n\t| 'unsupported_algorithm'\n\t| 'incompatible_key'\n\t| 'invalid_header'\n\t| 'invalid_claims';\n\nconst textEncoder = new TextEncoder();\nconst strictDecoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });\n\nfunction maxEncodedLength(decodedBytes: number): number {\n\treturn Math.ceil((decodedBytes * 4) / 3);\n}\n\nfunction parseFailure(\n\tcode: JwsParseErrorCode,\n\tmessage: string,\n): JoseErrorResult<JwsParseErrorCode> {\n\treturn joseFailure(code, message);\n}\n\nfunction decodeSegment(\n\tsegment: string,\n\tmaxBytes: number,\n\tname: string,\n): JoseResult<Uint8Array, JwsParseErrorCode> {\n\tif (segment.length > maxEncodedLength(maxBytes)) {\n\t\treturn parseFailure('limit_exceeded', `JWS ${name} exceeds ${maxBytes} bytes`);\n\t}\n\tconst bytes = base64UrlDecode(segment);\n\tif (bytes === undefined) {\n\t\treturn parseFailure('invalid_encoding', `JWS ${name} is not canonical base64url`);\n\t}\n\treturn successResult(bytes);\n}\n\n/** Decodes UTF-8 strictly and parses it as a JSON object with no duplicate members. */\nexport function decodeJsonObject(\n\tbytes: Uint8Array,\n\tlimits: JoseLimits,\n\tname: string,\n\tnotObjectCode: 'invalid_header' | 'invalid_payload',\n): JoseResult<JsonObject, JwsParseErrorCode> {\n\tlet text: string;\n\ttry {\n\t\ttext = strictDecoder.decode(bytes);\n\t} catch {\n\t\treturn parseFailure('invalid_utf8', `JWS ${name} is not valid UTF-8`);\n\t}\n\tconst parsed = parseStrictJson(text, {\n\t\tmaxDepth: limits.maxJsonDepth,\n\t\tmaxNodes: limits.maxJsonNodes,\n\t});\n\tif (!parsed.ok) {\n\t\treturn parseFailure(parsed.code, `JWS ${name}: ${parsed.message}`);\n\t}\n\tconst value = parsed.value;\n\tif (!isJsonObject(value)) {\n\t\treturn parseFailure(notObjectCode, `JWS ${name} is not a JSON object`);\n\t}\n\treturn successResult(value);\n}\n\nfunction optionalString(\n\tmembers: JsonObject,\n\tname: string,\n): JoseResult<string | undefined, JwsParseErrorCode> {\n\tif (!Object.hasOwn(members, name)) return successResult(undefined);\n\tconst value = members[name];\n\tif (typeof value !== 'string') {\n\t\treturn parseFailure('invalid_header', `JWS header \"${name}\" is not a string`);\n\t}\n\treturn successResult(value);\n}\n\nfunction criticalNames(members: JsonObject): JoseResult<readonly string[], JwsParseErrorCode> {\n\tif (!Object.hasOwn(members, 'crit')) return successResult([]);\n\tconst crit: JsonValue | undefined = members.crit;\n\tif (!isJsonArray(crit) || crit.length === 0) {\n\t\treturn parseFailure('invalid_header', 'JWS header \"crit\" is not a non-empty array');\n\t}\n\tconst names: string[] = [];\n\tfor (const entry of crit) {\n\t\tif (typeof entry !== 'string' || names.includes(entry)) {\n\t\t\treturn parseFailure(\n\t\t\t\t'invalid_header',\n\t\t\t\t'JWS header \"crit\" holds a non-string or repeated name',\n\t\t\t);\n\t\t}\n\t\tnames.push(entry);\n\t}\n\treturn successResult(names);\n}\n\nfunction parseHeader(\n\tbytes: Uint8Array,\n\tlimits: JoseLimits,\n): JoseResult<JwsHeader, JwsParseErrorCode> {\n\tconst object = decodeJsonObject(bytes, limits, 'header', 'invalid_header');\n\tif (!object.ok) return object;\n\tconst members = object.value;\n\tconst alg = members.alg;\n\tif (typeof alg !== 'string' || alg.length === 0) {\n\t\treturn parseFailure('invalid_header', 'JWS header \"alg\" is missing or not a string');\n\t}\n\tconst typ = optionalString(members, 'typ');\n\tif (!typ.ok) return typ;\n\tconst kid = optionalString(members, 'kid');\n\tif (!kid.ok) return kid;\n\tconst cty = optionalString(members, 'cty');\n\tif (!cty.ok) return cty;\n\tconst crit = criticalNames(members);\n\tif (!crit.ok) return crit;\n\tif (members.b64 === false || crit.value.includes('b64')) {\n\t\treturn parseFailure(\n\t\t\t'unsupported_unencoded_payload',\n\t\t\t'Unencoded and detached payloads (RFC 7797) are not supported',\n\t\t);\n\t}\n\tif (Object.hasOwn(members, 'b64') && typeof members.b64 !== 'boolean') {\n\t\treturn parseFailure('invalid_header', 'JWS header \"b64\" is not a boolean');\n\t}\n\tif (crit.value.length > 0) {\n\t\treturn joseFailure('unsupported_critical_header', 'JWS header lists critical extensions', {\n\t\t\talg,\n\t\t\tcrit: crit.value,\n\t\t});\n\t}\n\treturn successResult({\n\t\talg,\n\t\t...(typ.value === undefined ? {} : { typ: typ.value }),\n\t\t...(kid.value === undefined ? {} : { kid: kid.value }),\n\t\t...(cty.value === undefined ? {} : { cty: cty.value }),\n\t\tmembers,\n\t});\n}\n\n/**\n * Parses a compact JWS without checking its signature.\n *\n * Refuses tokens that are oversized, do not have exactly three segments, carry non-canonical\n * base64url, invalid UTF-8, a header that is not a duplicate-free JSON object with a string `alg`,\n * a `crit` list, or an unencoded payload (`b64: false`). The result is {@linkcode UnverifiedJws};\n * pass the token to {@linkcode verifyCompactJws} before trusting any of it.\n */\nexport function parseCompactJws(\n\ttoken: string,\n\tlimits?: Partial<JoseLimits>,\n): JoseResult<UnverifiedJws, JwsParseErrorCode | 'invalid_options'> {\n\tconst resolved = resolveJoseLimits(limits);\n\tif (!resolved.ok) return resolved;\n\treturn parseWithLimits(token, resolved.value);\n}\n\nfunction parseWithLimits(\n\ttoken: string,\n\tbounds: JoseLimits,\n): JoseResult<UnverifiedJws, JwsParseErrorCode> {\n\tif (typeof token !== 'string') {\n\t\treturn parseFailure('malformed_token', 'JWS token is not a string');\n\t}\n\tif (token.length > bounds.maxTokenLength) {\n\t\treturn parseFailure('token_too_large', `JWS token exceeds ${bounds.maxTokenLength} characters`);\n\t}\n\tconst segments = token.split('.');\n\tconst [headerSegment, payloadSegment, signatureSegment] = segments;\n\tif (\n\t\tsegments.length !== 3 ||\n\t\theaderSegment === undefined ||\n\t\tpayloadSegment === undefined ||\n\t\tsignatureSegment === undefined ||\n\t\theaderSegment.length === 0\n\t) {\n\t\treturn parseFailure('malformed_token', 'JWS compact serialization needs three segments');\n\t}\n\tconst headerBytes = decodeSegment(headerSegment, bounds.maxHeaderBytes, 'header');\n\tif (!headerBytes.ok) return headerBytes;\n\tconst header = parseHeader(headerBytes.value, bounds);\n\tif (!header.ok) return header;\n\tconst payload = decodeSegment(payloadSegment, bounds.maxPayloadBytes, 'payload');\n\tif (!payload.ok) return payload;\n\tconst signature = decodeSegment(signatureSegment, bounds.maxSignatureBytes, 'signature');\n\tif (!signature.ok) return signature;\n\treturn successResult({\n\t\tverified: false,\n\t\theader: header.value,\n\t\tpayload: payload.value,\n\t\tsigningInput: textEncoder.encode(`${headerSegment}.${payloadSegment}`),\n\t\tsignature: signature.value,\n\t});\n}\n\n/**\n * Comparison key for a media type per RFC 7515 §4.1.9: type, subtype and parameter names fold to\n * lower case, an omitted `application/` is restored, and parameter values stay exact.\n */\nexport function mediaTypeKey(value: string): string {\n\tconst [essence = '', ...parameters] = value.split(';');\n\tconst type = essence.trim().toLowerCase();\n\tconst normalized = parameters.map((parameter) => {\n\t\tconst separator = parameter.indexOf('=');\n\t\treturn separator < 0\n\t\t\t? parameter.trim().toLowerCase()\n\t\t\t: `${parameter.slice(0, separator).trim().toLowerCase()}=${parameter.slice(separator + 1).trim()}`;\n\t});\n\treturn [type.includes('/') ? type : `application/${type}`, ...normalized].join(';');\n}\n\n/** A token type policy reduced to the one form verification compares against. */\nexport type TypeRule =\n\t| { readonly kind: 'media'; readonly key: string }\n\t| { readonly kind: 'absent' }\n\t| { readonly kind: 'unchecked' };\n\n/** Whether `value` is exactly `{ unchecked: true }`. */\nexport function isUncheckedPolicy(value: unknown): boolean {\n\treturn soleTrueMember(value) === 'unchecked';\n}\n\nfunction soleTrueMember(value: unknown): string | undefined {\n\tif (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n\tconst names = Object.keys(value);\n\tconst [name] = names;\n\tif (names.length !== 1 || name === undefined) return undefined;\n\treturn Reflect.get(value, name) === true ? name : undefined;\n}\n\nfunction normalizeTokenType(policy: unknown): TypeRule | undefined {\n\tif (typeof policy === 'string') return { kind: 'media', key: mediaTypeKey(policy) };\n\tconst member = soleTrueMember(policy);\n\tif (member === 'absent') return { kind: 'absent' };\n\tif (member === 'unchecked') return { kind: 'unchecked' };\n\treturn undefined;\n}\n\nfunction matchesTokenType(header: JwsHeader, rule: TypeRule): boolean {\n\tswitch (rule.kind) {\n\t\tcase 'media':\n\t\t\treturn header.typ !== undefined && mediaTypeKey(header.typ) === rule.key;\n\t\tcase 'unchecked':\n\t\t\treturn true;\n\t\tcase 'absent':\n\t\t\treturn header.typ === undefined;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = rule;\n\t\t\treturn _exhaustive;\n\t\t}\n\t}\n}\n\nfunction isAlgorithmAdmitted(\n\talgorithm: string,\n\tadmitted: readonly string[],\n): algorithm is JwsAlgorithm {\n\treturn (\n\t\tadmitted.includes(algorithm) && JWS_ALGORITHMS.some((supported) => supported === algorithm)\n\t);\n}\n\n/** Checks the observable RSA exponent constraints in RFC 8017 section 3.1. */\nexport function validRsaPublicExponent(exponent: Uint8Array, modulus?: Uint8Array): boolean {\n\tconst first = exponent.findIndex((byte) => byte !== 0);\n\tconst last = exponent[exponent.length - 1] ?? 0;\n\tif (first < 0 || (last & 1) === 0) return false;\n\tconst length = exponent.length - first;\n\tif (length === 1 && last < 3) return false;\n\tif (modulus === undefined) return true;\n\tif (length !== modulus.length) return length < modulus.length;\n\tfor (let i = 0; i < length; i++) {\n\t\tconst left = exponent[first + i] ?? 0;\n\t\tconst right = modulus[i] ?? 0;\n\t\tif (left !== right) return left < right;\n\t}\n\treturn false;\n}\n\n/**\n * Checks a key may verify RS256 (RFC 7518 §3.3, RFC 8725 §3.1) and returns the signature length\n * in bytes it requires (RFC 8017 §8.2.2).\n */\nexport function checkRs256VerificationKey(key: CryptoKey): JoseResult<number, 'key_unsuitable'> {\n\ttry {\n\t\treturn inspectRs256VerificationKey(key);\n\t} catch {\n\t\treturn joseFailure('key_unsuitable', 'The key cannot be inspected');\n\t}\n}\n\nfunction inspectRs256VerificationKey(key: CryptoKey): JoseResult<number, 'key_unsuitable'> {\n\tconst algorithm = key.algorithm;\n\tif (key.type !== 'public' || !key.usages.includes('verify')) {\n\t\treturn joseFailure('key_unsuitable', 'RS256 needs a public key with verify usage');\n\t}\n\tif (\n\t\talgorithm.name !== 'RSASSA-PKCS1-v1_5' ||\n\t\t!('hash' in algorithm) ||\n\t\ttypeof algorithm.hash !== 'object' ||\n\t\talgorithm.hash === null ||\n\t\t!('name' in algorithm.hash) ||\n\t\talgorithm.hash.name !== 'SHA-256'\n\t) {\n\t\treturn joseFailure('key_unsuitable', 'RS256 needs an RSASSA-PKCS1-v1_5 SHA-256 key');\n\t}\n\tif (\n\t\t!('modulusLength' in algorithm) ||\n\t\ttypeof algorithm.modulusLength !== 'number' ||\n\t\talgorithm.modulusLength < MIN_RS256_MODULUS_BITS\n\t) {\n\t\treturn joseFailure(\n\t\t\t'key_unsuitable',\n\t\t\t`RS256 needs an RSA modulus of at least ${MIN_RS256_MODULUS_BITS} bits`,\n\t\t);\n\t}\n\tif (\n\t\t!('publicExponent' in algorithm) ||\n\t\t!(algorithm.publicExponent instanceof Uint8Array) ||\n\t\t!validRsaPublicExponent(algorithm.publicExponent)\n\t) {\n\t\treturn joseFailure(\n\t\t\t'key_unsuitable',\n\t\t\t'RS256 needs a valid odd RSA public exponent of at least 3',\n\t\t);\n\t}\n\treturn successResult(Math.ceil(algorithm.modulusLength / 8));\n}\n\n/** Verification options validated once and copied, so later changes by the caller cannot alter a run. */\nexport interface PreparedVerify {\n\t/** The admitted algorithms. */\n\treadonly algorithms: readonly JwsAlgorithm[];\n\t/** The fixed key or the resolver. */\n\treadonly key: CryptoKey | JwsKeyResolver;\n\t/** The token type rule. */\n\treadonly typeRule: TypeRule;\n\t/** The resolved limits. */\n\treadonly limits: JoseLimits;\n\t/** Cancellation for key resolution. */\n\treadonly signal: AbortSignal | undefined;\n}\n\nfunction isCryptoKey(value: unknown): value is CryptoKey {\n\treturn value instanceof CryptoKey;\n}\n\n/** Validates and copies verification options. Everything the run reads is captured here. */\nexport function prepareVerify(\n\toptions: VerifyJwsOptions,\n): JoseResult<PreparedVerify, 'invalid_options'> {\n\tif (typeof options !== 'object' || options === null) {\n\t\treturn joseFailure('invalid_options', 'Verification options are required');\n\t}\n\tconst { algorithms, key, tokenType, limits, signal } = options;\n\tif (!Array.isArray(algorithms) || algorithms.length === 0) {\n\t\treturn joseFailure('invalid_options', 'An explicit, non-empty algorithm list is required');\n\t}\n\tconst admitted: JwsAlgorithm[] = [];\n\tfor (const algorithm of algorithms) {\n\t\tconst supported = JWS_ALGORITHMS.find((candidate) => candidate === algorithm);\n\t\tif (supported === undefined) {\n\t\t\treturn joseFailure('invalid_options', 'The algorithm list names an unsupported algorithm');\n\t\t}\n\t\tadmitted.push(supported);\n\t}\n\tif (typeof key !== 'function' && !isCryptoKey(key)) {\n\t\treturn joseFailure('invalid_options', 'A key or key resolver is required');\n\t}\n\tconst typeRule = normalizeTokenType(tokenType);\n\tif (typeRule === undefined) {\n\t\treturn joseFailure('invalid_options', 'A token type policy is required');\n\t}\n\tif (signal !== undefined && !(signal instanceof AbortSignal)) {\n\t\treturn joseFailure('invalid_options', 'signal must be an AbortSignal');\n\t}\n\tconst bounds = resolveJoseLimits(limits);\n\tif (!bounds.ok) return bounds;\n\treturn successResult({ algorithms: admitted, key, typeRule, limits: bounds.value, signal });\n}\n\nasync function resolveKey(\n\tprepared: PreparedVerify,\n\theader: JwsHeader<JwsAlgorithm>,\n): Promise<JoseResult<CryptoKey, KeyResolutionErrorCode>> {\n\tconst { key, signal } = prepared;\n\tif (typeof key !== 'function') return successResult(key);\n\tlet resolved: unknown;\n\ttry {\n\t\tresolved = await key({\n\t\t\theader,\n\t\t\talgorithm: header.alg,\n\t\t\t...(header.kid === undefined ? {} : { kid: header.kid }),\n\t\t\t...(signal === undefined ? {} : { signal }),\n\t\t});\n\t} catch {\n\t\treturn signal?.aborted === true\n\t\t\t? joseFailure('aborted', 'Key resolution was cancelled')\n\t\t\t: joseFailure('key_resolution_failed', 'The key resolver failed');\n\t}\n\tif (typeof resolved !== 'object' || resolved === null) {\n\t\treturn joseFailure('key_resolution_failed', 'The key resolver returned no result');\n\t}\n\tif (Reflect.get(resolved, 'ok') === true) {\n\t\tconst value: unknown = Reflect.get(resolved, 'value');\n\t\treturn isCryptoKey(value)\n\t\t\t? successResult(value)\n\t\t\t: joseFailure('key_resolution_failed', 'The key resolver returned no key');\n\t}\n\tconst code: unknown = Reflect.get(resolved, 'code');\n\tswitch (code) {\n\t\tcase 'key_not_found':\n\t\tcase 'ambiguous_key':\n\t\tcase 'key_unsuitable':\n\t\tcase 'key_resolution_failed':\n\t\tcase 'jwks_unavailable':\n\t\tcase 'jwks_malformed':\n\t\tcase 'aborted':\n\t\t\treturn joseFailure(code, `Key resolution failed: ${code}`, resolverDetails(resolved));\n\t\tdefault:\n\t\t\treturn joseFailure('key_resolution_failed', 'The key resolver returned an unknown failure');\n\t}\n}\n\nfunction resolverDetails(resolved: object): JoseErrorDetails | undefined {\n\tconst details: unknown = Reflect.get(resolved, 'details');\n\tif (typeof details !== 'object' || details === null) return undefined;\n\tconst kid: unknown = Reflect.get(details, 'kid');\n\tconst status: unknown = Reflect.get(details, 'status');\n\treturn {\n\t\t...(typeof kid === 'string' ? { kid } : {}),\n\t\t...(typeof status === 'number' && Number.isSafeInteger(status) ? { status } : {}),\n\t};\n}\n\n/**\n * Verifies a compact JWS.\n *\n * The caller's `algorithms` list decides what is accepted; the token's `alg` only selects among\n * them, and `none` is always refused as `unsigned_token`. The `tokenType` policy is applied before\n * any key is resolved. A fixed key or the resolver's key must be an RSASSA-PKCS1-v1_5 SHA-256\n * public key of at least 2048 bits for RS256. Header members such as `jku`, `jwk`, `x5u` and\n * `x5c` are never used to find a key. A resolver that throws or returns something other than a\n * result is reported as `key_resolution_failed` without its message.\n *\n * Returns a {@linkcode VerifiedJws} on success. Failures carry a stable code and never echo the\n * token.\n */\nexport async function verifyCompactJws(\n\ttoken: string,\n\toptions: VerifyJwsOptions,\n): Promise<JoseResult<VerifiedJws, VerifyJwsErrorCode>> {\n\tconst prepared = prepareVerify(options);\n\tif (!prepared.ok) return prepared;\n\treturn await verifyPrepared(token, prepared.value);\n}\n\n/** Verifies `token` under options already checked by {@linkcode prepareVerify}. */\nexport async function verifyPrepared(\n\ttoken: string,\n\tprepared: PreparedVerify,\n): Promise<JoseResult<VerifiedJws, VerifyJwsErrorCode>> {\n\tconst parsed = parseWithLimits(token, prepared.limits);\n\tif (!parsed.ok) return parsed;\n\tconst unverified = parsed.value;\n\tconst alg = unverified.header.alg;\n\tif (alg === 'none') {\n\t\treturn joseFailure('unsigned_token', 'Unsigned tokens are never accepted', { alg });\n\t}\n\tif (!isAlgorithmAdmitted(alg, prepared.algorithms)) {\n\t\treturn joseFailure('algorithm_not_allowed', 'The token algorithm is not in the allowed list', {\n\t\t\talg,\n\t\t});\n\t}\n\tif (!matchesTokenType(unverified.header, prepared.typeRule)) {\n\t\treturn joseFailure('token_type_mismatch', 'The token \"typ\" does not match the expected type', {\n\t\t\talg,\n\t\t});\n\t}\n\tconst header: JwsHeader<JwsAlgorithm> = { ...unverified.header, alg };\n\tconst key = await resolveKey(prepared, header);\n\tif (!key.ok) return key;\n\tconst signatureBytes = checkRs256VerificationKey(key.value);\n\tif (!signatureBytes.ok) return signatureBytes;\n\tif (unverified.signature.length !== signatureBytes.value) {\n\t\treturn joseFailure('invalid_signature', 'The signature length differs from the modulus', {\n\t\t\talg,\n\t\t});\n\t}\n\tconst failure = joseFailure('invalid_signature', 'The signature does not verify', {\n\t\talg,\n\t\t...(header.kid === undefined ? {} : { kid: header.kid }),\n\t});\n\tconst verification = await verifySignatureWithKey({\n\t\tpublicKey: key.value,\n\t\tsignatureAlgorithm: { oid: OIDS.sha256WithRSAEncryption },\n\t\tsignatureEncoding: 'raw',\n\t\tsignature: unverified.signature,\n\t\tdata: unverified.signingInput,\n\t});\n\tif (!verification.ok || !verification.valid) return failure;\n\treturn successResult({ verified: true, header, payload: unverified.payload });\n}\n\nfunction assertSigningKey(input: SignJwsInput): void {\n\tconst algorithm = input.privateKey.algorithm;\n\tif (!JWS_ALGORITHMS.includes(input.algorithm)) {\n\t\tthrowMicro509Error('unsupported_algorithm', 'Unsupported JWS algorithm');\n\t}\n\tif (\n\t\tinput.privateKey.type !== 'private' ||\n\t\t!input.privateKey.usages.includes('sign') ||\n\t\talgorithm.name !== 'RSASSA-PKCS1-v1_5' ||\n\t\t!('hash' in algorithm) ||\n\t\ttypeof algorithm.hash !== 'object' ||\n\t\talgorithm.hash === null ||\n\t\t!('name' in algorithm.hash) ||\n\t\talgorithm.hash.name !== 'SHA-256' ||\n\t\t!('modulusLength' in algorithm) ||\n\t\ttypeof algorithm.modulusLength !== 'number' ||\n\t\talgorithm.modulusLength < MIN_RS256_MODULUS_BITS\n\t) {\n\t\tthrowMicro509Error(\n\t\t\t'incompatible_key',\n\t\t\t`RS256 signing needs an RSASSA-PKCS1-v1_5 SHA-256 private key of at least ${MIN_RS256_MODULUS_BITS} bits`,\n\t\t);\n\t}\n}\n\n/**\n * Signs a compact JWS with an existing private `CryptoKey`.\n *\n * The header is `alg` followed by the optional `typ`, `kid` and `cty`. Throws a `ResultError`\n * (see `isResultError`) coded {@linkcode SignJoseErrorCode} when the algorithm, key or header\n * input is invalid. Intended for issuing tokens and for building synthetic tokens in tests.\n */\nexport async function signCompactJws(input: SignJwsInput): Promise<string> {\n\tassertSigningKey(input);\n\tconst header: Record<string, string> = { alg: input.algorithm };\n\tfor (const name of ['typ', 'kid', 'cty'] as const) {\n\t\tconst value = input.header?.[name];\n\t\tif (value === undefined) continue;\n\t\tif (typeof value !== 'string') {\n\t\t\tthrowMicro509Error('invalid_header', `Header \"${name}\" must be a string`);\n\t\t}\n\t\theader[name] = value;\n\t}\n\tconst signingInput = `${base64UrlEncode(textEncoder.encode(JSON.stringify(header)))}.${base64UrlEncode(input.payload)}`;\n\tconst { signature } = await signData(input.privateKey, textEncoder.encode(signingInput));\n\treturn `${signingInput}.${base64UrlEncode(signature)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,MAAaC,IAA0C,CAAC,OAAO,GAGlDC,IAAyB,MAmBzBC,IAAkC;CAC9C,gBAAgB;CAChB,gBAAgB;CAChB,iBAAiB;CACjB,mBAAmB;CACnB,cAAc;CACd,cAAc;AACf,GAEMC,IAAc;CACnB;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;AAUA,SAAgB,kBACf,GAC4C;CAC5C,IAAIC,MAAc,KAAA,MAAc,OAAOA,KAAc,aAAYA,IAChE,OAAOC,EAAY,mBAAmB,0BAA0B;CAEjE,IAAMC,IAAuE,EAC5E,GAAGJ,EACJ;CACA,KAAK,IAAMK,KAAQJ,GAAa;EAC/B,IAAMK,IAAQJ,IAAYG;EAC1B,IAAIC,MAAU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,EAAOA,KAAQC;CAChB;CACA,IAAM6E,IAAe,GAAGC,EAAgB3E,EAAY,OAAO,KAAK,UAAUgC,CAAM,CAAC,CAAC,EAAE,GAAG2C,EAAgBH,EAAM,OAAO,KAC9G,EAAE,iBAAc,MAAMI,EAASJ,EAAM,YAAYxE,EAAY,OAAO0E,CAAY,CAAC;CACvF,OAAO,GAAGA,EAAa,GAAGC,EAAgBzC,CAAS;AACpD"}
@@ -0,0 +1,91 @@
1
+ import { JsonObject } from "../internal/jose/strict-json.js";
2
+ import { JoseResult, JwsParseErrorCode, VerifyJwtErrorCode } from "./errors.js";
3
+ import { JoseLimits, JwsAlgorithm, JwsHeader, SignJwsInput, Unchecked, VerifyJwsOptions } from "./jws.js";
4
+ /** Largest clock tolerance {@linkcode JwtClaimsPolicy.clockToleranceSeconds} accepts. */
5
+ export declare const MAX_CLOCK_TOLERANCE_SECONDS = 600;
6
+ /** The RFC 7519 §4.1 registered claims, each checked against its defined type. */
7
+ export interface RegisteredClaims {
8
+ /** Issuer. */
9
+ readonly iss?: string;
10
+ /** Subject. */
11
+ readonly sub?: string;
12
+ /** Audience, as the token carried it: a string or an array of strings. */
13
+ readonly aud?: string | readonly string[];
14
+ /** Expiration time in seconds since the epoch. */
15
+ readonly exp?: number;
16
+ /** Not-before time in seconds since the epoch. */
17
+ readonly nbf?: number;
18
+ /** Issued-at time in seconds since the epoch. */
19
+ readonly iat?: number;
20
+ /** Token identifier. */
21
+ readonly jti?: string;
22
+ }
23
+ /** A decoded JWT whose signature has not been checked. */
24
+ export interface UnverifiedJwt {
25
+ /** Always `false`. */
26
+ readonly verified: false;
27
+ /** The header, unauthenticated. */
28
+ readonly header: JwsHeader;
29
+ /** The claims, unauthenticated and not policy-checked. */
30
+ readonly claims: JsonObject;
31
+ }
32
+ /** A JWT whose signature and claims both passed the caller's policy. */
33
+ export interface VerifiedJwt {
34
+ /** Always `true`. */
35
+ readonly verified: true;
36
+ /** The authenticated protected header. */
37
+ readonly header: JwsHeader<JwsAlgorithm>;
38
+ /** Every authenticated claim, exactly as the token carried it. */
39
+ readonly claims: JsonObject;
40
+ /** The registered claims, validated against their types. */
41
+ readonly registered: RegisteredClaims;
42
+ }
43
+ /** Whether an `iat` later than the clock is accepted. */
44
+ export type FutureIssuedAtPolicy = "reject" | "allow";
45
+ /** Claims policy for {@linkcode verifyJwt}. Application authorization stays with the caller. */
46
+ export interface JwtClaimsPolicy {
47
+ /** Accepted `iss` values (any one may match), or `{ unchecked: true }`. */
48
+ readonly issuer: string | readonly string[] | Unchecked;
49
+ /** Accepted `aud` values (any one may match), or `{ unchecked: true }`. */
50
+ readonly audience: string | readonly string[] | Unchecked;
51
+ /** Claims that must be present. Default `['exp']`. */
52
+ readonly requiredClaims?: readonly string[];
53
+ /** The clock. Default is the system time. */
54
+ readonly now?: () => Date;
55
+ /** Leeway in seconds for `exp`, `nbf` and `iat`, from 0 to 600. Default `0`. */
56
+ readonly clockToleranceSeconds?: number;
57
+ /** Oldest acceptable token age in seconds, measured from `iat`. Requires `iat`. */
58
+ readonly maxAgeSeconds?: number;
59
+ /** Whether `iat` after the clock is accepted. Default `'reject'`. */
60
+ readonly futureIssuedAt?: FutureIssuedAtPolicy;
61
+ }
62
+ /** Options for {@linkcode verifyJwt}. */
63
+ export interface VerifyJwtOptions extends VerifyJwsOptions {
64
+ /** Claims policy. */
65
+ readonly claims: JwtClaimsPolicy;
66
+ }
67
+ /** Input for {@linkcode signJwt}. */
68
+ export interface SignJwtInput extends Omit<SignJwsInput, "payload"> {
69
+ /** The claims to sign. Must be JSON-serializable. */
70
+ readonly claims: JsonObject;
71
+ }
72
+ /** Decodes a JWT without checking its signature. Every field of the result is unauthenticated. */
73
+ export declare function decodeJwtUnverified(token: string, limits?: Partial<JoseLimits>): JoseResult<UnverifiedJwt, JwsParseErrorCode | "invalid_options">;
74
+ /**
75
+ * Verifies a JWT: the signature and `tokenType` policy as {@linkcode verifyCompactJws} applies
76
+ * them, then the payload as a duplicate-free JSON object, then `claims`.
77
+ *
78
+ * `iss` and `aud` must be stated explicitly. Time claims follow RFC 7519 §4.1.4 and §4.1.5: the
79
+ * token is expired when the clock is at or after `exp` and not yet valid when it is before
80
+ * `nbf`, each moved by `clockToleranceSeconds`. Time claims must be JSON numbers; strings are never
81
+ * coerced. `exp` is required unless `requiredClaims` says otherwise.
82
+ */
83
+ export declare function verifyJwt(token: string, options: VerifyJwtOptions): Promise<JoseResult<VerifiedJwt, VerifyJwtErrorCode>>;
84
+ /**
85
+ * Signs a JWT. The header carries `typ: "JWT"` unless `header.typ` says otherwise.
86
+ *
87
+ * Throws a `ResultError` coded `SignJoseErrorCode` for an unusable key, algorithm or header, and
88
+ * `invalid_claims` when `claims` cannot be serialized.
89
+ */
90
+ export declare function signJwt(input: SignJwtInput): Promise<string>;
91
+ //# sourceMappingURL=jwt.d.ts.map