micro509 0.16.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.
package/CHANGELOG.md CHANGED
@@ -19,6 +19,79 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
19
19
 
20
20
  ## [Unreleased]
21
21
 
22
+ ## [0.17.0] - 2026-10-25
23
+
24
+ Work with OpenSSH keys, derive encryption keys with Argon2, and sign and verify
25
+ JWTs with local or remote JWK Sets. Three optional entrypoints extend micro509
26
+ beyond certificate workflows: `micro509/ssh`, `micro509/kdf` and `micro509/jose`.
27
+
28
+ The new guides follow complete workflows with runnable examples, inspectable
29
+ key material and returned verification results. Navigation distinguishes PR
30
+ previews from published versions and makes the version list usable on mobile.
31
+
32
+ ### Added
33
+
34
+ - `micro509/ssh` entrypoint for OpenSSH key material: public-key lines
35
+ (`importSshPublicKey`, `exportSshPublicKey`), unencrypted single-key
36
+ `openssh-key-v1` private files (`importOpenSshPrivateKey`,
37
+ `exportOpenSshPrivateKey`) and `SHA256:` fingerprints
38
+ (`sshFingerprintSha256`) for RSA, Ed25519 and ECDSA P-256/P-384/P-521.
39
+ Imports check the private key against its embedded public key, bound input
40
+ sizes and RSA moduli, and return typed `malformed`, `unsupported`,
41
+ `limit_exceeded` and `key_mismatch` results. Encrypted files and files with
42
+ several keys return `unsupported`. `minRsaModulusBits` and
43
+ `acceptCompressedEcPoints` expose the choices the standards leave open.
44
+ [#190](https://github.com/kjanat/micro509/issues/190)
45
+ - Optional `micro509/kdf` entrypoint for Argon2id and Argon2d raw key
46
+ derivation, with explicit versions, per-call resource limits and typed
47
+ failures. The native WebCrypto adapter supports version `0x13` on
48
+ compatible runtimes. An explicit backend callback supports separately
49
+ installed implementations, including legacy `0x10` handling.
50
+ [#189](https://github.com/kjanat/micro509/issues/189)
51
+ - **Verify JWTs with `micro509/jose`.** The optional entrypoint signs and
52
+ verifies compact JWS and JWT with RS256 and returns typed failures. Callers
53
+ state the algorithm list, token type, issuer and audience; `exp` is required
54
+ by default, and `iat`, `nbf`, maximum age and clock tolerance are checked
55
+ against a caller-supplied clock. Parsing rejects non-canonical base64url,
56
+ invalid UTF-8, duplicate members, `crit`, `b64: false` and nested JWTs, and
57
+ bounds token, header, payload and JSON size. `VerifiedJwt` and `UnverifiedJwt`
58
+ are separate types. [#148](https://github.com/kjanat/micro509/issues/148)
59
+ - **Select keys from a JWK Set.** `parseJwks`, `selectJwk` and
60
+ `createJwksKeyResolver` match `kid`, key type, `use`, `key_ops` and `alg`, and
61
+ reject ambiguous matches.
62
+ - **Read a JWK Set from a trusted URL.** `createRemoteJwksKeyResolver` is
63
+ opt-in and keeps a cache per source. It bounds timeout, streamed bytes, key
64
+ count and redirects, shares concurrent fetches, refreshes at most once per
65
+ cooldown, enforces its deadline even when a transport ignores cancellation,
66
+ and never reuses an expired set after a failed refresh.
67
+
68
+ ### Changed
69
+
70
+ - **Follow complete SSH, Argon2 and JWT workflows.** The SSH guide uses one
71
+ key through import, conversion, export and fingerprint comparison. The
72
+ Argon2 guide derives an encryption key, saves the salt and parameters, and
73
+ derives it again to decrypt. The JWT guide verifies the same token with a
74
+ direct key, local JWKS and remote resolver, then demonstrates rejection for
75
+ the wrong audience. Short sidebar labels link to descriptive articles and
76
+ their API references. [#201](https://github.com/kjanat/micro509/pull/201)
77
+
78
+ ### Fixed
79
+
80
+ - Multiline LiveCode output, including PEM keys and JSON, starts below its
81
+ label so readers can inspect and copy complete blocks.
82
+ - Mobile navigation uses compact rows and an inline version list that expands
83
+ like VitePress's own screen-menu groups, scrolling with the menu instead of
84
+ inside a nested box. The version button toggles the list, and Escape or an
85
+ outside click closes it. Desktop version lists scroll within the viewport,
86
+ and the navbar's overflow menu renders both as flat panel rows.
87
+ [#188](https://github.com/kjanat/micro509/issues/188)
88
+ - PR previews have a separate version entry alongside production's `next` and
89
+ release entries. Switching from a preview opens the matching production page.
90
+ - The version list shows one entry per release instead of one per published
91
+ base, so the latest release no longer appears twice, and it reads in
92
+ timeline order: this preview, `next`, the latest release, then the archives.
93
+ Entries without a version number say which channel they are.
94
+
22
95
  ## [0.16.0] - 2026-10-24
23
96
 
24
97
  Block a compromised public key across every certificate that carries it,
@@ -1955,7 +2028,8 @@ Initial prerelease. API may change before 1.0.
1955
2028
  - Zero runtime dependencies, WebCrypto-native, tree-shakeable subpath exports;
1956
2029
  runs on Node, Bun, Deno, browsers, and Cloudflare Workers.
1957
2030
 
1958
- [Unreleased]: https://github.com/kjanat/micro509/compare/v0.16.0...HEAD
2031
+ [Unreleased]: https://github.com/kjanat/micro509/compare/v0.17.0...HEAD
2032
+ [0.17.0]: https://github.com/kjanat/micro509/compare/v0.16.0...v0.17.0
1959
2033
  [0.16.0]: https://github.com/kjanat/micro509/compare/v0.15.0...v0.16.0
1960
2034
  [0.15.0]: https://github.com/kjanat/micro509/compare/v0.14.0...v0.15.0
1961
2035
  [0.14.0]: https://github.com/kjanat/micro509/compare/v0.13.0...v0.14.0
@@ -0,0 +1,40 @@
1
+ // src/internal/jose/base64url.ts
2
+ const e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", t = (() => {
3
+ let t = (/* @__PURE__ */ new Int8Array(128)).fill(-1);
4
+ for (let n = 0; n < 64; n++) t[e.charCodeAt(n)] = n;
5
+ return t;
6
+ })();
7
+ /** Encodes bytes as unpadded base64url (RFC 4648 §5, RFC 7515 §2). */
8
+ function base64UrlEncode(t) {
9
+ let n = "", r = 0;
10
+ for (; r + 2 < t.length; r += 3) {
11
+ let i = (t[r] ?? 0) * 65536 + (t[r + 1] ?? 0) * 256 + (t[r + 2] ?? 0);
12
+ n += e[i >> 18 & 63] ?? "", n += e[i >> 12 & 63] ?? "", n += e[i >> 6 & 63] ?? "", n += e[i & 63] ?? "";
13
+ }
14
+ let i = t.length - r;
15
+ if (i === 1) {
16
+ let i = (t[r] ?? 0) * 65536;
17
+ n += e[i >> 18 & 63] ?? "", n += e[i >> 12 & 63] ?? "";
18
+ } else if (i === 2) {
19
+ let i = (t[r] ?? 0) * 65536 + (t[r + 1] ?? 0) * 256;
20
+ n += e[i >> 18 & 63] ?? "", n += e[i >> 12 & 63] ?? "", n += e[i >> 6 & 63] ?? "";
21
+ }
22
+ return n;
23
+ }
24
+ /**
25
+ * Decodes canonical unpadded base64url. Returns `undefined` for any character outside the URL-safe
26
+ * alphabet, padding, whitespace, an impossible length, or non-zero trailing bits.
27
+ */
28
+ function base64UrlDecode(e) {
29
+ if (e.length % 4 == 1) return;
30
+ let n = new Uint8Array(Math.floor(e.length * 3 / 4)), r = 0, i = 0, a = 0;
31
+ for (let o = 0; o < e.length; o++) {
32
+ let s = e.charCodeAt(o), c = s < 128 ? t[s] ?? -1 : -1;
33
+ if (c < 0) return;
34
+ i = i << 6 | c, a += 6, a >= 8 && (a -= 8, n[r++] = i >> a & 255, i &= (1 << a) - 1);
35
+ }
36
+ if (i === 0) return n;
37
+ }
38
+ export { base64UrlDecode, base64UrlEncode };
39
+
40
+ //# sourceMappingURL=base64url.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base64url.js","names":["ALPHABET","DECODE_TABLE","table","index","out","bytes","chunk","remaining","value","written","buffer","bits","code","sextet"],"sources":["../../../src/internal/jose/base64url.ts"],"sourcesContent":["const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\n\nconst DECODE_TABLE: Int8Array = (() => {\n\tconst table = new Int8Array(128).fill(-1);\n\tfor (let index = 0; index < ALPHABET.length; index++) {\n\t\ttable[ALPHABET.charCodeAt(index)] = index;\n\t}\n\treturn table;\n})();\n\n/** Encodes bytes as unpadded base64url (RFC 4648 §5, RFC 7515 §2). */\nexport function base64UrlEncode(bytes: Uint8Array): string {\n\tlet out = '';\n\tlet index = 0;\n\tfor (; index + 2 < bytes.length; index += 3) {\n\t\tconst chunk =\n\t\t\t(bytes[index] ?? 0) * 65536 + (bytes[index + 1] ?? 0) * 256 + (bytes[index + 2] ?? 0);\n\t\tout += ALPHABET[(chunk >> 18) & 63] ?? '';\n\t\tout += ALPHABET[(chunk >> 12) & 63] ?? '';\n\t\tout += ALPHABET[(chunk >> 6) & 63] ?? '';\n\t\tout += ALPHABET[chunk & 63] ?? '';\n\t}\n\tconst remaining = bytes.length - index;\n\tif (remaining === 1) {\n\t\tconst chunk = (bytes[index] ?? 0) * 65536;\n\t\tout += ALPHABET[(chunk >> 18) & 63] ?? '';\n\t\tout += ALPHABET[(chunk >> 12) & 63] ?? '';\n\t} else if (remaining === 2) {\n\t\tconst chunk = (bytes[index] ?? 0) * 65536 + (bytes[index + 1] ?? 0) * 256;\n\t\tout += ALPHABET[(chunk >> 18) & 63] ?? '';\n\t\tout += ALPHABET[(chunk >> 12) & 63] ?? '';\n\t\tout += ALPHABET[(chunk >> 6) & 63] ?? '';\n\t}\n\treturn out;\n}\n\n/**\n * Decodes canonical unpadded base64url. Returns `undefined` for any character outside the URL-safe\n * alphabet, padding, whitespace, an impossible length, or non-zero trailing bits.\n */\nexport function base64UrlDecode(value: string): Uint8Array | undefined {\n\tconst remainder = value.length % 4;\n\tif (remainder === 1) return undefined;\n\tconst bytes = new Uint8Array(Math.floor((value.length * 3) / 4));\n\tlet written = 0;\n\tlet buffer = 0;\n\tlet bits = 0;\n\tfor (let index = 0; index < value.length; index++) {\n\t\tconst code = value.charCodeAt(index);\n\t\tconst sextet = code < 128 ? (DECODE_TABLE[code] ?? -1) : -1;\n\t\tif (sextet < 0) return undefined;\n\t\tbuffer = (buffer << 6) | sextet;\n\t\tbits += 6;\n\t\tif (bits >= 8) {\n\t\t\tbits -= 8;\n\t\t\tbytes[written++] = (buffer >> bits) & 0xff;\n\t\t\tbuffer &= (1 << bits) - 1;\n\t\t}\n\t}\n\tif (buffer !== 0) return undefined;\n\treturn bytes;\n}\n"],"mappings":";AAAA,MAAMA,IAAW,oEAEXC,WAAiC;CACtC,IAAMC,qBAAQ,IAAI,UAAU,GAAG,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IAASD,IAAO,MAAOX,EAAaW,MAAS,KAAM;EACzD,IAAIC,IAAS,GAAG;EAGhB,AAFA,IAAUH,KAAU,IAAKG,GACzB,KAAQ,GACJF,KAAQ,MACX,KAAQ,GACR,EAAM,OAAcD,KAAUC,IAAQ,KACtC,MAAW,KAAKA,KAAQ;CAE1B;CACA,IAAID,MAAW,GACf,OAAOL;AACR"}
@@ -0,0 +1,9 @@
1
+ /** A parsed JSON value. Objects are plain records whose members are all own data properties. */
2
+ export type JsonValue = null | boolean | number | string | readonly JsonValue[] | {
3
+ readonly [member: string]: JsonValue;
4
+ };
5
+ /** A parsed JSON object. */
6
+ export type JsonObject = {
7
+ readonly [member: string]: JsonValue;
8
+ };
9
+ //# sourceMappingURL=strict-json.d.ts.map
@@ -0,0 +1,155 @@
1
+ // src/internal/jose/strict-json.ts
2
+ const e = Symbol("micro509.jose.strictJsonFailure");
3
+ function refuse(t, n) {
4
+ throw {
5
+ [e]: !0,
6
+ code: t,
7
+ message: n
8
+ };
9
+ }
10
+ function isRefusal(t) {
11
+ return typeof t == "object" && !!t && e in t;
12
+ }
13
+ /**
14
+ * Parses RFC 8259 JSON text, refusing duplicate object member names, lone surrogate escapes,
15
+ * non-finite numbers, and documents beyond the given depth and node bounds.
16
+ */
17
+ function parseStrictJson(e, t) {
18
+ let n = {
19
+ text: e,
20
+ index: 0,
21
+ nodes: 0,
22
+ limits: t
23
+ };
24
+ try {
25
+ skipWhitespace(n);
26
+ let t = parseValue(n, 0);
27
+ return skipWhitespace(n), n.index !== e.length && refuse("invalid_json", "Trailing characters after JSON value"), {
28
+ ok: !0,
29
+ value: t
30
+ };
31
+ } catch (e) {
32
+ if (isRefusal(e)) return {
33
+ ok: !1,
34
+ code: e.code,
35
+ message: e.message
36
+ };
37
+ throw e;
38
+ }
39
+ }
40
+ function skipWhitespace(e) {
41
+ for (; e.index < e.text.length;) {
42
+ let t = e.text.charCodeAt(e.index);
43
+ if (t !== 32 && t !== 9 && t !== 10 && t !== 13) return;
44
+ e.index++;
45
+ }
46
+ }
47
+ function countNode(e) {
48
+ e.nodes++, e.nodes > e.limits.maxNodes && refuse("limit_exceeded", "JSON document exceeds the node limit");
49
+ }
50
+ function parseValue(e, t) {
51
+ switch (countNode(e), e.text[e.index]) {
52
+ case "{": return parseObject(e, t + 1);
53
+ case "[": return parseArray(e, t + 1);
54
+ case "\"": return parseString(e);
55
+ case "t": return parseLiteral(e, "true", !0);
56
+ case "f": return parseLiteral(e, "false", !1);
57
+ case "n": return parseLiteral(e, "null", null);
58
+ default: return parseNumber(e);
59
+ }
60
+ }
61
+ function parseLiteral(e, t, n) {
62
+ return e.text.startsWith(t, e.index) || refuse("invalid_json", "Unexpected token in JSON"), e.index += t.length, n;
63
+ }
64
+ const t = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
65
+ function parseNumber(e) {
66
+ t.lastIndex = e.index;
67
+ let n = t.exec(e.text);
68
+ n === null && refuse("invalid_json", "Unexpected token in JSON"), e.index += n[0].length;
69
+ let r = Number(n[0]);
70
+ return Number.isFinite(r) || refuse("invalid_json", "JSON number is not finite"), r;
71
+ }
72
+ function enter(e, t) {
73
+ t > e.limits.maxDepth && refuse("limit_exceeded", "JSON document exceeds the nesting limit");
74
+ }
75
+ function parseArray(e, t) {
76
+ enter(e, t), e.index++;
77
+ let n = [];
78
+ if (skipWhitespace(e), e.text[e.index] === "]") return e.index++, n;
79
+ for (;;) {
80
+ skipWhitespace(e), n.push(parseValue(e, t)), skipWhitespace(e);
81
+ let r = e.text[e.index++];
82
+ if (r === "]") return n;
83
+ r !== "," && refuse("invalid_json", "Expected \",\" or \"]\" in JSON array");
84
+ }
85
+ }
86
+ function parseObject(e, t) {
87
+ enter(e, t), e.index++;
88
+ let n = /* @__PURE__ */ new Map();
89
+ if (skipWhitespace(e), e.text[e.index] === "}") return e.index++, {};
90
+ for (;;) {
91
+ skipWhitespace(e), e.text[e.index] !== "\"" && refuse("invalid_json", "Expected member name in JSON object"), countNode(e);
92
+ let r = parseString(e);
93
+ n.has(r) && refuse("duplicate_member", "JSON object repeats a member name"), skipWhitespace(e), e.text[e.index++] !== ":" && refuse("invalid_json", "Expected \":\" in JSON object"), skipWhitespace(e), n.set(r, parseValue(e, t)), skipWhitespace(e);
94
+ let i = e.text[e.index++];
95
+ if (i === "}") break;
96
+ i !== "," && refuse("invalid_json", "Expected \",\" or \"}\" in JSON object");
97
+ }
98
+ let r = {};
99
+ for (let [e, t] of n) Object.defineProperty(r, e, {
100
+ value: t,
101
+ enumerable: !0,
102
+ writable: !0,
103
+ configurable: !0
104
+ });
105
+ return r;
106
+ }
107
+ const n = /[0-9a-fA-F]{4}/y;
108
+ function readEscapedUnit(e) {
109
+ n.lastIndex = e.index;
110
+ let t = n.exec(e.text);
111
+ return t === null && refuse("invalid_json", "Invalid unicode escape in JSON string"), e.index += 4, Number.parseInt(t[0], 16);
112
+ }
113
+ function parseString(e) {
114
+ e.index++;
115
+ let t = "", n = e.index;
116
+ for (;;) {
117
+ e.index >= e.text.length && refuse("invalid_json", "Unterminated JSON string");
118
+ let r = e.text.charCodeAt(e.index);
119
+ if (r === 34) return t += e.text.slice(n, e.index), e.index++, t;
120
+ r < 32 && refuse("invalid_json", "Control character in JSON string"), r === 92 ? (t += e.text.slice(n, e.index), e.index++, t += parseEscape(e), n = e.index) : e.index++;
121
+ }
122
+ }
123
+ const r = {
124
+ "\"": "\"",
125
+ "\\": "\\",
126
+ "/": "/",
127
+ b: "\b",
128
+ f: "\f",
129
+ n: "\n",
130
+ r: "\r",
131
+ t: " "
132
+ };
133
+ function parseEscape(e) {
134
+ let t = e.text[e.index++];
135
+ if (t === void 0 && refuse("invalid_json", "Unterminated JSON string"), t !== "u") {
136
+ let e = Object.hasOwn(r, t) ? r[t] : void 0;
137
+ return e === void 0 && refuse("invalid_json", "Invalid escape in JSON string"), e;
138
+ }
139
+ let n = readEscapedUnit(e);
140
+ if (n >= 56320 && n <= 57343 && refuse("invalid_json", "Lone low surrogate escape in JSON string"), n < 55296 || n > 56319) return String.fromCharCode(n);
141
+ e.text.startsWith("\\u", e.index) || refuse("invalid_json", "Lone high surrogate escape in JSON string"), e.index += 2;
142
+ let i = readEscapedUnit(e);
143
+ return (i < 56320 || i > 57343) && refuse("invalid_json", "High surrogate escape without a low surrogate"), String.fromCharCode(n, i);
144
+ }
145
+ /** Narrows a parsed value to a JSON object. */
146
+ function isJsonObject(e) {
147
+ return typeof e == "object" && !!e && !Array.isArray(e);
148
+ }
149
+ /** Narrows a parsed value to a JSON array. */
150
+ function isJsonArray(e) {
151
+ return Array.isArray(e);
152
+ }
153
+ export { isJsonArray, isJsonObject, parseStrictJson };
154
+
155
+ //# sourceMappingURL=strict-json.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strict-json.js","names":["failureBrand","value","cursor","text","error","char","depth","literal","NUMBER_PATTERN","match","items","members","name","object","HEX4","out","runStart","code","SIMPLE_ESCAPES","marker","simple","unit","low"],"sources":["../../../src/internal/jose/strict-json.ts"],"sourcesContent":["/** A parsed JSON value. Objects are plain records whose members are all own data properties. */\nexport type JsonValue =\n\t| null\n\t| boolean\n\t| number\n\t| string\n\t| readonly JsonValue[]\n\t| { readonly [member: string]: JsonValue };\n\n/** A parsed JSON object. */\nexport type JsonObject = { readonly [member: string]: JsonValue };\n\n/** Reason strict JSON parsing refused its input. */\nexport type StrictJsonFailureCode = 'invalid_json' | 'duplicate_member' | 'limit_exceeded';\n\n/** Failure of {@linkcode parseStrictJson}. */\nexport interface StrictJsonFailure {\n\treadonly ok: false;\n\treadonly code: StrictJsonFailureCode;\n\treadonly message: string;\n}\n\n/** Result of {@linkcode parseStrictJson}. */\nexport type StrictJsonResult = { readonly ok: true; readonly value: JsonValue } | StrictJsonFailure;\n\n/** Bounds applied while parsing. */\nexport interface StrictJsonLimits {\n\t/** Maximum array and object nesting. */\n\treadonly maxDepth: number;\n\t/** Maximum number of values (scalars, arrays, objects and members) in the document. */\n\treadonly maxNodes: number;\n}\n\ninterface Cursor {\n\treadonly text: string;\n\tindex: number;\n\tnodes: number;\n\treadonly limits: StrictJsonLimits;\n}\n\nconst failureBrand = Symbol('micro509.jose.strictJsonFailure');\n\ninterface Refusal {\n\treadonly [failureBrand]: true;\n\treadonly code: StrictJsonFailureCode;\n\treadonly message: string;\n}\n\nfunction refuse(code: StrictJsonFailureCode, message: string): never {\n\tconst refusal: Refusal = { [failureBrand]: true, code, message };\n\tthrow refusal;\n}\n\nfunction isRefusal(value: unknown): value is Refusal {\n\treturn typeof value === 'object' && value !== null && failureBrand in value;\n}\n\n/**\n * Parses RFC 8259 JSON text, refusing duplicate object member names, lone surrogate escapes,\n * non-finite numbers, and documents beyond the given depth and node bounds.\n */\nexport function parseStrictJson(text: string, limits: StrictJsonLimits): StrictJsonResult {\n\tconst cursor: Cursor = { text, index: 0, nodes: 0, limits };\n\ttry {\n\t\tskipWhitespace(cursor);\n\t\tconst value = parseValue(cursor, 0);\n\t\tskipWhitespace(cursor);\n\t\tif (cursor.index !== text.length)\n\t\t\trefuse('invalid_json', 'Trailing characters after JSON value');\n\t\treturn { ok: true, value };\n\t} catch (error) {\n\t\tif (isRefusal(error)) return { ok: false, code: error.code, message: error.message };\n\t\tthrow error;\n\t}\n}\n\nfunction skipWhitespace(cursor: Cursor): void {\n\twhile (cursor.index < cursor.text.length) {\n\t\tconst char = cursor.text.charCodeAt(cursor.index);\n\t\tif (char !== 0x20 && char !== 0x09 && char !== 0x0a && char !== 0x0d) return;\n\t\tcursor.index++;\n\t}\n}\n\nfunction countNode(cursor: Cursor): void {\n\tcursor.nodes++;\n\tif (cursor.nodes > cursor.limits.maxNodes) {\n\t\trefuse('limit_exceeded', 'JSON document exceeds the node limit');\n\t}\n}\n\nfunction parseValue(cursor: Cursor, depth: number): JsonValue {\n\tcountNode(cursor);\n\tconst char = cursor.text[cursor.index];\n\tswitch (char) {\n\t\tcase '{':\n\t\t\treturn parseObject(cursor, depth + 1);\n\t\tcase '[':\n\t\t\treturn parseArray(cursor, depth + 1);\n\t\tcase '\"':\n\t\t\treturn parseString(cursor);\n\t\tcase 't':\n\t\t\treturn parseLiteral(cursor, 'true', true);\n\t\tcase 'f':\n\t\t\treturn parseLiteral(cursor, 'false', false);\n\t\tcase 'n':\n\t\t\treturn parseLiteral(cursor, 'null', null);\n\t\tdefault:\n\t\t\treturn parseNumber(cursor);\n\t}\n}\n\nfunction parseLiteral<TValue extends boolean | null>(\n\tcursor: Cursor,\n\tliteral: string,\n\tvalue: TValue,\n): TValue {\n\tif (!cursor.text.startsWith(literal, cursor.index)) {\n\t\trefuse('invalid_json', 'Unexpected token in JSON');\n\t}\n\tcursor.index += literal.length;\n\treturn value;\n}\n\nconst NUMBER_PATTERN = /-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;\n\nfunction parseNumber(cursor: Cursor): number {\n\tNUMBER_PATTERN.lastIndex = cursor.index;\n\tconst match = NUMBER_PATTERN.exec(cursor.text);\n\tif (match === null) refuse('invalid_json', 'Unexpected token in JSON');\n\tcursor.index += match[0].length;\n\tconst value = Number(match[0]);\n\tif (!Number.isFinite(value)) refuse('invalid_json', 'JSON number is not finite');\n\treturn value;\n}\n\nfunction enter(cursor: Cursor, depth: number): void {\n\tif (depth > cursor.limits.maxDepth) {\n\t\trefuse('limit_exceeded', 'JSON document exceeds the nesting limit');\n\t}\n}\n\nfunction parseArray(cursor: Cursor, depth: number): readonly JsonValue[] {\n\tenter(cursor, depth);\n\tcursor.index++;\n\tconst items: JsonValue[] = [];\n\tskipWhitespace(cursor);\n\tif (cursor.text[cursor.index] === ']') {\n\t\tcursor.index++;\n\t\treturn items;\n\t}\n\tfor (;;) {\n\t\tskipWhitespace(cursor);\n\t\titems.push(parseValue(cursor, depth));\n\t\tskipWhitespace(cursor);\n\t\tconst char = cursor.text[cursor.index++];\n\t\tif (char === ']') return items;\n\t\tif (char !== ',') refuse('invalid_json', 'Expected \",\" or \"]\" in JSON array');\n\t}\n}\n\nfunction parseObject(cursor: Cursor, depth: number): JsonObject {\n\tenter(cursor, depth);\n\tcursor.index++;\n\tconst members = new Map<string, JsonValue>();\n\tskipWhitespace(cursor);\n\tif (cursor.text[cursor.index] === '}') {\n\t\tcursor.index++;\n\t\treturn {};\n\t}\n\tfor (;;) {\n\t\tskipWhitespace(cursor);\n\t\tif (cursor.text[cursor.index] !== '\"')\n\t\t\trefuse('invalid_json', 'Expected member name in JSON object');\n\t\tcountNode(cursor);\n\t\tconst name = parseString(cursor);\n\t\tif (members.has(name)) refuse('duplicate_member', 'JSON object repeats a member name');\n\t\tskipWhitespace(cursor);\n\t\tif (cursor.text[cursor.index++] !== ':') refuse('invalid_json', 'Expected \":\" in JSON object');\n\t\tskipWhitespace(cursor);\n\t\tmembers.set(name, parseValue(cursor, depth));\n\t\tskipWhitespace(cursor);\n\t\tconst char = cursor.text[cursor.index++];\n\t\tif (char === '}') break;\n\t\tif (char !== ',') refuse('invalid_json', 'Expected \",\" or \"}\" in JSON object');\n\t}\n\tconst object: Record<string, JsonValue> = {};\n\tfor (const [name, value] of members) {\n\t\tObject.defineProperty(object, name, {\n\t\t\tvalue,\n\t\t\tenumerable: true,\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\treturn object;\n}\n\nconst HEX4 = /[0-9a-fA-F]{4}/y;\n\nfunction readEscapedUnit(cursor: Cursor): number {\n\tHEX4.lastIndex = cursor.index;\n\tconst match = HEX4.exec(cursor.text);\n\tif (match === null) refuse('invalid_json', 'Invalid unicode escape in JSON string');\n\tcursor.index += 4;\n\treturn Number.parseInt(match[0], 16);\n}\n\nfunction parseString(cursor: Cursor): string {\n\tcursor.index++;\n\tlet out = '';\n\tlet runStart = cursor.index;\n\tfor (;;) {\n\t\tif (cursor.index >= cursor.text.length) refuse('invalid_json', 'Unterminated JSON string');\n\t\tconst code = cursor.text.charCodeAt(cursor.index);\n\t\tif (code === 0x22) {\n\t\t\tout += cursor.text.slice(runStart, cursor.index);\n\t\t\tcursor.index++;\n\t\t\treturn out;\n\t\t}\n\t\tif (code < 0x20) refuse('invalid_json', 'Control character in JSON string');\n\t\tif (code !== 0x5c) {\n\t\t\tcursor.index++;\n\t\t\tcontinue;\n\t\t}\n\t\tout += cursor.text.slice(runStart, cursor.index);\n\t\tcursor.index++;\n\t\tout += parseEscape(cursor);\n\t\trunStart = cursor.index;\n\t}\n}\n\nconst SIMPLE_ESCAPES: Readonly<Record<string, string>> = {\n\t'\"': '\"',\n\t'\\\\': '\\\\',\n\t'/': '/',\n\tb: '\\b',\n\tf: '\\f',\n\tn: '\\n',\n\tr: '\\r',\n\tt: '\\t',\n};\n\nfunction parseEscape(cursor: Cursor): string {\n\tconst marker = cursor.text[cursor.index++];\n\tif (marker === undefined) refuse('invalid_json', 'Unterminated JSON string');\n\tif (marker !== 'u') {\n\t\tconst simple = Object.hasOwn(SIMPLE_ESCAPES, marker) ? SIMPLE_ESCAPES[marker] : undefined;\n\t\tif (simple === undefined) refuse('invalid_json', 'Invalid escape in JSON string');\n\t\treturn simple;\n\t}\n\tconst unit = readEscapedUnit(cursor);\n\tif (unit >= 0xdc00 && unit <= 0xdfff) {\n\t\trefuse('invalid_json', 'Lone low surrogate escape in JSON string');\n\t}\n\tif (unit < 0xd800 || unit > 0xdbff) return String.fromCharCode(unit);\n\tif (!cursor.text.startsWith('\\\\u', cursor.index)) {\n\t\trefuse('invalid_json', 'Lone high surrogate escape in JSON string');\n\t}\n\tcursor.index += 2;\n\tconst low = readEscapedUnit(cursor);\n\tif (low < 0xdc00 || low > 0xdfff) {\n\t\trefuse('invalid_json', 'High surrogate escape without a low surrogate');\n\t}\n\treturn String.fromCharCode(unit, low);\n}\n\n/** Narrows a parsed value to a JSON object. */\nexport function isJsonObject(value: JsonValue | undefined): value is JsonObject {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Narrows a parsed value to a JSON array. */\nexport function isJsonArray(value: JsonValue | undefined): value is readonly JsonValue[] {\n\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QA,CAAK;AAC3B"}
@@ -0,0 +1,44 @@
1
+ import { ErrorResult, Micro509Error } from "../result/result.js";
2
+ /** Reasons a compact serialization is refused before any signature is checked. */
3
+ export type JwsParseErrorCode = "token_too_large" | "malformed_token" | "invalid_encoding" | "invalid_utf8" | "invalid_json" | "duplicate_member" | "limit_exceeded" | "invalid_header" | "unsupported_critical_header" | "unsupported_unencoded_payload" | "unsupported_nested_jwt" | "invalid_payload";
4
+ /** Reasons a signing key cannot be resolved for a token. */
5
+ export type KeyResolutionErrorCode = "key_not_found" | "ambiguous_key" | "key_unsuitable" | "key_resolution_failed" | "jwks_unavailable" | "jwks_malformed" | "aborted";
6
+ /** Reasons a well-formed token is refused by the verification policy or its signature. */
7
+ export type JwsPolicyErrorCode = "invalid_options" | "unsigned_token" | "algorithm_not_allowed" | "token_type_mismatch" | "invalid_signature";
8
+ /** Reasons a signature-verified token fails the claims policy. */
9
+ export type JwtClaimsErrorCode = "missing_claim" | "invalid_claim" | "issuer_mismatch" | "audience_mismatch" | "expired" | "not_yet_valid" | "issued_in_future" | "token_too_old";
10
+ /** Failure codes of {@linkcode verifyCompactJws}. */
11
+ export type VerifyJwsErrorCode = JwsParseErrorCode | KeyResolutionErrorCode | JwsPolicyErrorCode;
12
+ /** Failure codes of {@linkcode verifyJwt}. */
13
+ export type VerifyJwtErrorCode = VerifyJwsErrorCode | JwtClaimsErrorCode;
14
+ /** Every code a JOSE API reports. */
15
+ export type JoseErrorCode = VerifyJwtErrorCode;
16
+ /**
17
+ * Structured context for a failure. Holds names and short identifiers only, never token
18
+ * segments, claim values or key material.
19
+ */
20
+ export interface JoseErrorDetails {
21
+ /** The `alg` header value the token carried. */
22
+ readonly alg?: string;
23
+ /** The `kid` header value the token carried, truncated to 64 characters. */
24
+ readonly kid?: string;
25
+ /** The claim name a claims failure concerns. */
26
+ readonly claim?: string;
27
+ /** The critical header names that were refused. */
28
+ readonly crit?: readonly string[];
29
+ /** The HTTP status a JWKS endpoint answered with. */
30
+ readonly status?: number;
31
+ }
32
+ /** Failure payload of the JOSE APIs. */
33
+ export interface JoseFailure<TCode extends string = JoseErrorCode> extends Micro509Error<TCode, JoseErrorDetails> {
34
+ /** Always `false` for failures. */
35
+ readonly ok: false;
36
+ }
37
+ /** A flattened failed result carrying a {@linkcode JoseFailure}. */
38
+ export type JoseErrorResult<TCode extends string = JoseErrorCode> = ErrorResult<TCode, JoseErrorDetails, JoseFailure<TCode>>;
39
+ /** Success-or-failure result of a JOSE API. */
40
+ export type JoseResult<TValue, TCode extends string = JoseErrorCode> = {
41
+ readonly ok: true;
42
+ readonly value: TValue;
43
+ } | JoseErrorResult<TCode>;
44
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1,11 @@
1
+ import { failureResult as e } from "../result/result.js";
2
+ /** Builds a failed result, truncating any reported `kid`. */
3
+ function joseFailure(t, n, r) {
4
+ return e(t, n, r?.kid === void 0 ? r : {
5
+ ...r,
6
+ kid: r.kid.slice(0, 64)
7
+ });
8
+ }
9
+ export { joseFailure };
10
+
11
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","names":["failureResult","code","message","details"],"sources":["../../src/jose/errors.ts"],"sourcesContent":["/**\n * Typed failures shared by the JOSE parsing, verification and key-resolution APIs.\n *\n * @module\n */\n\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult } from '#micro509/result/result';\n\n/** Longest `kid` echoed into {@linkcode JoseErrorDetails}. */\nconst MAX_REPORTED_KID_LENGTH = 64;\n\n/** Reasons a compact serialization is refused before any signature is checked. */\nexport type JwsParseErrorCode =\n\t| 'token_too_large'\n\t| 'malformed_token'\n\t| 'invalid_encoding'\n\t| 'invalid_utf8'\n\t| 'invalid_json'\n\t| 'duplicate_member'\n\t| 'limit_exceeded'\n\t| 'invalid_header'\n\t| 'unsupported_critical_header'\n\t| 'unsupported_unencoded_payload'\n\t| 'unsupported_nested_jwt'\n\t| 'invalid_payload';\n\n/** Reasons a signing key cannot be resolved for a token. */\nexport type KeyResolutionErrorCode =\n\t| 'key_not_found'\n\t| 'ambiguous_key'\n\t| 'key_unsuitable'\n\t| 'key_resolution_failed'\n\t| 'jwks_unavailable'\n\t| 'jwks_malformed'\n\t| 'aborted';\n\n/** Reasons a well-formed token is refused by the verification policy or its signature. */\nexport type JwsPolicyErrorCode =\n\t| 'invalid_options'\n\t| 'unsigned_token'\n\t| 'algorithm_not_allowed'\n\t| 'token_type_mismatch'\n\t| 'invalid_signature';\n\n/** Reasons a signature-verified token fails the claims policy. */\nexport type JwtClaimsErrorCode =\n\t| 'missing_claim'\n\t| 'invalid_claim'\n\t| 'issuer_mismatch'\n\t| 'audience_mismatch'\n\t| 'expired'\n\t| 'not_yet_valid'\n\t| 'issued_in_future'\n\t| 'token_too_old';\n\n/** Failure codes of {@linkcode verifyCompactJws}. */\nexport type VerifyJwsErrorCode = JwsParseErrorCode | KeyResolutionErrorCode | JwsPolicyErrorCode;\n\n/** Failure codes of {@linkcode verifyJwt}. */\nexport type VerifyJwtErrorCode = VerifyJwsErrorCode | JwtClaimsErrorCode;\n\n/** Every code a JOSE API reports. */\nexport type JoseErrorCode = VerifyJwtErrorCode;\n\n/**\n * Structured context for a failure. Holds names and short identifiers only, never token\n * segments, claim values or key material.\n */\nexport interface JoseErrorDetails {\n\t/** The `alg` header value the token carried. */\n\treadonly alg?: string;\n\t/** The `kid` header value the token carried, truncated to 64 characters. */\n\treadonly kid?: string;\n\t/** The claim name a claims failure concerns. */\n\treadonly claim?: string;\n\t/** The critical header names that were refused. */\n\treadonly crit?: readonly string[];\n\t/** The HTTP status a JWKS endpoint answered with. */\n\treadonly status?: number;\n}\n\n/** Failure payload of the JOSE APIs. */\nexport interface JoseFailure<TCode extends string = JoseErrorCode>\n\textends Micro509Error<TCode, JoseErrorDetails> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** A flattened failed result carrying a {@linkcode JoseFailure}. */\nexport type JoseErrorResult<TCode extends string = JoseErrorCode> = ErrorResult<\n\tTCode,\n\tJoseErrorDetails,\n\tJoseFailure<TCode>\n>;\n\n/** Success-or-failure result of a JOSE API. */\nexport type JoseResult<TValue, TCode extends string = JoseErrorCode> =\n\t| { readonly ok: true; readonly value: TValue }\n\t| JoseErrorResult<TCode>;\n\n/** Builds a failed result, truncating any reported `kid`. */\nexport function joseFailure<TCode extends JoseErrorCode>(\n\tcode: TCode,\n\tmessage: string,\n\tdetails?: JoseErrorDetails,\n): JoseErrorResult<TCode> {\n\treturn failureResult(\n\t\tcode,\n\t\tmessage,\n\t\tdetails?.kid === undefined\n\t\t\t? details\n\t\t\t: { ...details, kid: details.kid.slice(0, MAX_REPORTED_KID_LENGTH) },\n\t);\n}\n"],"mappings":";;AAsGA,SAAgB,YACf,GACA,GACA,GACyB;CACzB,OAAOA,EACNC,GACAC,GACAC,GAAS,QAAQ,KAAA,IACdA,IACA;EAAE,GAAGA;EAAS,KAAKA,EAAQ,IAAI,MAAM,GAAG,EAAuB;CAAE,CACrE;AACD"}
@@ -0,0 +1,93 @@
1
+ import { JsonObject } from "../internal/jose/strict-json.js";
2
+ import { JoseResult, KeyResolutionErrorCode } from "./errors.js";
3
+ import { JwsAlgorithm, JwsKeyResolver } from "./jws.js";
4
+ /** Bounds applied while parsing a JWK Set. */
5
+ export interface JwksLimits {
6
+ /** Maximum JWK Set size in bytes. Default `65536`. */
7
+ readonly maxBytes: number;
8
+ /** Maximum number of keys in the set. Default `32`. */
9
+ readonly maxKeys: number;
10
+ }
11
+ /** The limits applied when a caller supplies none. */
12
+ export declare const DEFAULT_JWKS_LIMITS: JwksLimits;
13
+ /** Members every JWK entry carries beside its key material. */
14
+ export interface JwkMetadata {
15
+ /** Key identifier. */
16
+ readonly kid?: string;
17
+ /** Intended use: `sig` or `enc`, or another value kept verbatim. */
18
+ readonly use?: string;
19
+ /** Permitted operations, verbatim. */
20
+ readonly keyOps?: readonly string[];
21
+ /** The algorithm the key is restricted to. */
22
+ readonly alg?: string;
23
+ }
24
+ /** Members shared by every parsed entry. */
25
+ export interface JwkEntryBase extends JwkMetadata {
26
+ /** Every member the entry carried, as parsed, including key material this module does not read. */
27
+ readonly members: JsonObject;
28
+ }
29
+ /** An RSA public key entry. */
30
+ export interface RsaJwkEntry extends JwkEntryBase {
31
+ /** Discriminant. */
32
+ readonly kind: "rsa";
33
+ /** Base64url modulus. */
34
+ readonly n: string;
35
+ /** Base64url public exponent. */
36
+ readonly e: string;
37
+ }
38
+ /**
39
+ * An entry this module never selects: a `kty` other than `RSA`, or an entry with missing or
40
+ * wrongly typed members (RFC 7517 §5). Kept so callers can inspect the whole set.
41
+ */
42
+ export interface UnsupportedJwkEntry extends JwkEntryBase {
43
+ /** Discriminant. */
44
+ readonly kind: "unsupported";
45
+ /** The `kty` the entry carried, when it was a string. */
46
+ readonly kty?: string;
47
+ }
48
+ /** One key of a JWK Set. */
49
+ export type JwkEntry = RsaJwkEntry | UnsupportedJwkEntry;
50
+ /** A parsed JWK Set. */
51
+ export interface Jwks {
52
+ /** The keys, in document order. */
53
+ readonly keys: readonly JwkEntry[];
54
+ /** Every top-level member of the document, as parsed. */
55
+ readonly members: JsonObject;
56
+ }
57
+ /** Codes {@linkcode parseJwks} returns. */
58
+ export type ParseJwksErrorCode = "jwks_malformed" | "limit_exceeded" | "invalid_options";
59
+ /**
60
+ * Parses a JWK Set document.
61
+ *
62
+ * The document must be duplicate-free JSON with a `keys` array within `limits`. Keys with a `kty`
63
+ * other than `RSA`, and keys with missing or wrongly typed members, are kept as `unsupported`
64
+ * entries and never selected (RFC 7517 §5). A set that is not a duplicate-free object with a
65
+ * `keys` array of objects is `jwks_malformed`.
66
+ */
67
+ export declare function parseJwks(input: string | Uint8Array, limits?: Partial<JwksLimits>): JoseResult<Jwks, ParseJwksErrorCode>;
68
+ /** What {@linkcode selectJwk} matches against. */
69
+ export interface JwkSelector {
70
+ /** The algorithm the token uses. */
71
+ readonly algorithm: JwsAlgorithm;
72
+ /** The token's `kid`, when it carries one. */
73
+ readonly kid?: string;
74
+ }
75
+ /**
76
+ * Selects the one key of a set that can verify `selector`.
77
+ *
78
+ * Keys are filtered by `kid` (when the token has one), key type, `use`, `key_ops`, `alg` and RSA
79
+ * parameters. No match is `key_not_found`, or `key_unsuitable` when `kid` matched only keys that
80
+ * fail the other checks. More than one match is `ambiguous_key`: a token without `kid` therefore
81
+ * resolves only against a set with a single usable key.
82
+ */
83
+ export declare function selectJwk(jwks: Jwks, selector: JwkSelector): JoseResult<RsaJwkEntry, Exclude<KeyResolutionErrorCode, "jwks_unavailable" | "aborted">>;
84
+ /** Imports a selected entry as a verify-only RS256 `CryptoKey`. */
85
+ export declare function importJwkEntry(entry: RsaJwkEntry): Promise<JoseResult<CryptoKey, "key_unsuitable">>;
86
+ /**
87
+ * Creates a key resolver over a fixed JWK Set.
88
+ *
89
+ * The resolver selects with {@linkcode selectJwk} and imports each key once, so repeated
90
+ * verifications reuse the same `CryptoKey`.
91
+ */
92
+ export declare function createJwksKeyResolver(jwks: Jwks): JwsKeyResolver;
93
+ //# sourceMappingURL=jwks.d.ts.map