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.
- package/CHANGELOG.md +130 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +3 -3
- package/dist/internal/jose/base64url.js +40 -0
- package/dist/internal/jose/base64url.js.map +1 -0
- package/dist/internal/jose/strict-json.d.ts +9 -0
- package/dist/internal/jose/strict-json.js +155 -0
- package/dist/internal/jose/strict-json.js.map +1 -0
- package/dist/internal/verify/spki-distrust.js +23 -0
- package/dist/internal/verify/spki-distrust.js.map +1 -0
- package/dist/internal/verify/verify-path.js +77 -60
- package/dist/internal/verify/verify-path.js.map +1 -1
- package/dist/jose/errors.d.ts +44 -0
- package/dist/jose/errors.js +11 -0
- package/dist/jose/errors.js.map +1 -0
- package/dist/jose/jwks.d.ts +93 -0
- package/dist/jose/jwks.js +193 -0
- package/dist/jose/jwks.js.map +1 -0
- package/dist/jose/jws.d.ts +158 -0
- package/dist/jose/jws.js +362 -0
- package/dist/jose/jws.js.map +1 -0
- package/dist/jose/jwt.d.ts +91 -0
- package/dist/jose/jwt.js +187 -0
- package/dist/jose/jwt.js.map +1 -0
- package/dist/jose/remote-jwks.d.ts +95 -0
- package/dist/jose/remote-jwks.js +298 -0
- package/dist/jose/remote-jwks.js.map +1 -0
- package/dist/jose.d.ts +7 -0
- package/dist/jose.js +5 -0
- package/dist/kdf/argon2.d.ts +78 -0
- package/dist/kdf/argon2.js +167 -0
- package/dist/kdf/argon2.js.map +1 -0
- package/dist/kdf.d.ts +2 -0
- package/dist/kdf.js +1 -0
- package/dist/keys/keys.d.ts +11 -8
- package/dist/keys/keys.js.map +1 -1
- package/dist/revocation/crl.js +2 -7
- package/dist/revocation/crl.js.map +1 -1
- package/dist/ssh/ssh.d.ts +200 -0
- package/dist/ssh/ssh.js +648 -0
- package/dist/ssh/ssh.js.map +1 -0
- package/dist/ssh/wire.d.ts +3 -0
- package/dist/ssh/wire.js +105 -0
- package/dist/ssh/wire.js.map +1 -0
- package/dist/ssh.d.ts +3 -0
- package/dist/ssh.js +1 -0
- package/dist/verify/verify.d.ts +32 -1
- package/dist/verify/verify.js +100 -58
- package/dist/verify/verify.js.map +1 -1
- package/dist/x509/fingerprint.d.ts +11 -0
- package/dist/x509/fingerprint.js +19 -1
- package/dist/x509/fingerprint.js.map +1 -1
- package/dist/x509.d.ts +2 -2
- package/dist/x509.js +3 -3
- package/package.json +20 -6
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { successResult as e } from "../result/result.js";
|
|
2
|
+
import { importPublicJwk as t } from "../keys/keys.js";
|
|
3
|
+
import { base64UrlDecode as n } from "../internal/jose/base64url.js";
|
|
4
|
+
import { isJsonArray as r, isJsonObject as i, parseStrictJson as a } from "../internal/jose/strict-json.js";
|
|
5
|
+
import { joseFailure as o } from "./errors.js";
|
|
6
|
+
import { checkRs256VerificationKey as s, validRsaPublicExponent as c } from "./jws.js";
|
|
7
|
+
// src/jose/jwks.ts
|
|
8
|
+
/**
|
|
9
|
+
* JSON Web Key Set (RFC 7517) parsing, key selection and a local key resolver. Nothing here
|
|
10
|
+
* performs network access.
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
/** The limits applied when a caller supplies none. */
|
|
15
|
+
const l = {
|
|
16
|
+
maxBytes: 65536,
|
|
17
|
+
maxKeys: 32
|
|
18
|
+
};
|
|
19
|
+
function malformed(e) {
|
|
20
|
+
return o("jwks_malformed", e);
|
|
21
|
+
}
|
|
22
|
+
function memberString(e, t) {
|
|
23
|
+
if (!Object.hasOwn(e, t)) return;
|
|
24
|
+
let n = e[t];
|
|
25
|
+
return typeof n == "string" ? n : null;
|
|
26
|
+
}
|
|
27
|
+
function memberStrings(e, t) {
|
|
28
|
+
if (!Object.hasOwn(e, t)) return;
|
|
29
|
+
let n = e[t];
|
|
30
|
+
if (!r(n)) return null;
|
|
31
|
+
let i = [];
|
|
32
|
+
for (let e of n) {
|
|
33
|
+
if (typeof e != "string" || i.includes(e)) return null;
|
|
34
|
+
i.push(e);
|
|
35
|
+
}
|
|
36
|
+
return i;
|
|
37
|
+
}
|
|
38
|
+
function parseEntry(t) {
|
|
39
|
+
if (!i(t)) return malformed("JWK Set key is not an object");
|
|
40
|
+
let n = memberString(t, "kty"), r = memberString(t, "kid"), a = memberString(t, "use"), o = memberString(t, "alg"), s = memberStrings(t, "key_ops");
|
|
41
|
+
if (typeof n != "string" || r === null || a === null || o === null || s === null) return e({
|
|
42
|
+
kind: "unsupported",
|
|
43
|
+
...typeof n == "string" ? { kty: n } : {},
|
|
44
|
+
members: t
|
|
45
|
+
});
|
|
46
|
+
let c = {
|
|
47
|
+
...r === void 0 ? {} : { kid: r },
|
|
48
|
+
...a === void 0 ? {} : { use: a },
|
|
49
|
+
...o === void 0 ? {} : { alg: o },
|
|
50
|
+
...s === void 0 ? {} : { keyOps: s }
|
|
51
|
+
}, l = t.n, u = t.e;
|
|
52
|
+
return e(n !== "RSA" || typeof l != "string" || typeof u != "string" ? {
|
|
53
|
+
kind: "unsupported",
|
|
54
|
+
kty: n,
|
|
55
|
+
...c,
|
|
56
|
+
members: t
|
|
57
|
+
} : {
|
|
58
|
+
kind: "rsa",
|
|
59
|
+
n: l,
|
|
60
|
+
e: u,
|
|
61
|
+
...c,
|
|
62
|
+
members: t
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Parses a JWK Set document.
|
|
67
|
+
*
|
|
68
|
+
* The document must be duplicate-free JSON with a `keys` array within `limits`. Keys with a `kty`
|
|
69
|
+
* other than `RSA`, and keys with missing or wrongly typed members, are kept as `unsupported`
|
|
70
|
+
* entries and never selected (RFC 7517 §5). A set that is not a duplicate-free object with a
|
|
71
|
+
* `keys` array of objects is `jwks_malformed`.
|
|
72
|
+
*/
|
|
73
|
+
function parseJwks(e, t) {
|
|
74
|
+
let n = resolveJwksLimits(t);
|
|
75
|
+
return n.ok ? parseWithLimits(e, n.value) : n;
|
|
76
|
+
}
|
|
77
|
+
const u = 16777216, d = 1024;
|
|
78
|
+
function resolveJwksLimits(t) {
|
|
79
|
+
if (t !== void 0 && (typeof t != "object" || !t)) return o("invalid_options", "limits must be an object");
|
|
80
|
+
let n = t?.maxBytes === void 0 ? l.maxBytes : t.maxBytes, r = t?.maxKeys === void 0 ? l.maxKeys : t.maxKeys;
|
|
81
|
+
return !Number.isSafeInteger(n) || n < 1 || n > u ? o("invalid_options", `limits.maxBytes must be from 1 to ${u}`) : !Number.isSafeInteger(r) || r < 1 || r > d ? o("invalid_options", `limits.maxKeys must be from 1 to ${d}`) : e({
|
|
82
|
+
maxBytes: n,
|
|
83
|
+
maxKeys: r
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
function parseWithLimits(t, n) {
|
|
87
|
+
if (typeof t == "string" && t.length > n.maxBytes) return o("limit_exceeded", `JWK Set exceeds ${n.maxBytes} bytes`);
|
|
88
|
+
if (typeof t != "string" && !(t instanceof Uint8Array)) return malformed("JWK Set input is neither a string nor bytes");
|
|
89
|
+
let s = typeof t == "string" ? new TextEncoder().encode(t) : t;
|
|
90
|
+
if (s.byteLength > n.maxBytes) return o("limit_exceeded", `JWK Set exceeds ${n.maxBytes} bytes`);
|
|
91
|
+
let c;
|
|
92
|
+
try {
|
|
93
|
+
c = new TextDecoder("utf-8", {
|
|
94
|
+
fatal: !0,
|
|
95
|
+
ignoreBOM: !0
|
|
96
|
+
}).decode(s);
|
|
97
|
+
} catch {
|
|
98
|
+
return malformed("JWK Set is not valid UTF-8");
|
|
99
|
+
}
|
|
100
|
+
let l = a(c, {
|
|
101
|
+
maxDepth: 8,
|
|
102
|
+
maxNodes: n.maxKeys * 64 + 64
|
|
103
|
+
});
|
|
104
|
+
if (!l.ok) return l.code === "limit_exceeded" ? o("limit_exceeded", `JWK Set: ${l.message}`) : malformed(`JWK Set: ${l.message}`);
|
|
105
|
+
let u = l.value;
|
|
106
|
+
if (!i(u)) return malformed("JWK Set is not an object");
|
|
107
|
+
let d = u.keys;
|
|
108
|
+
if (!r(d)) return malformed("JWK Set \"keys\" is not an array");
|
|
109
|
+
if (d.length > n.maxKeys) return o("limit_exceeded", `JWK Set holds more than ${n.maxKeys} keys`);
|
|
110
|
+
let f = [];
|
|
111
|
+
for (let e of d) {
|
|
112
|
+
let t = parseEntry(e);
|
|
113
|
+
if (!t.ok) return t;
|
|
114
|
+
f.push(t.value);
|
|
115
|
+
}
|
|
116
|
+
return e({
|
|
117
|
+
keys: f,
|
|
118
|
+
members: u
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
/** Why a key entry cannot verify a given algorithm, or `undefined` when it can. */
|
|
122
|
+
function unsuitableReason(e, t) {
|
|
123
|
+
if (e.kind !== "rsa") return "key type does not match the algorithm";
|
|
124
|
+
if (e.use !== void 0 && e.use !== "sig") return "\"use\" is not \"sig\"";
|
|
125
|
+
if (e.keyOps !== void 0 && !e.keyOps.includes("verify")) return "\"key_ops\" does not include \"verify\"";
|
|
126
|
+
if (e.use === "sig" && e.keyOps?.some((e) => e !== "sign" && e !== "verify")) return "\"use\" and \"key_ops\" are inconsistent";
|
|
127
|
+
if (e.alg !== void 0 && e.alg !== t) return "\"alg\" names another algorithm";
|
|
128
|
+
let r = n(e.n), i = n(e.e);
|
|
129
|
+
if (r === void 0 || i === void 0 || r.length === 0) return "RSA parameters are not canonical base64url";
|
|
130
|
+
if (r[0] === 0 || i[0] === 0 || i.length === 0) return "RSA parameters have leading zero octets";
|
|
131
|
+
if (r.length > 1024) return "RSA modulus is too large";
|
|
132
|
+
if ((r.length - 1) * 8 + 32 - Math.clz32(r[0] ?? 0) < 2048) return "RSA modulus is too small";
|
|
133
|
+
if (!c(i, r)) return "RSA public exponent is invalid";
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Selects the one key of a set that can verify `selector`.
|
|
137
|
+
*
|
|
138
|
+
* Keys are filtered by `kid` (when the token has one), key type, `use`, `key_ops`, `alg` and RSA
|
|
139
|
+
* parameters. No match is `key_not_found`, or `key_unsuitable` when `kid` matched only keys that
|
|
140
|
+
* fail the other checks. More than one match is `ambiguous_key`: a token without `kid` therefore
|
|
141
|
+
* resolves only against a set with a single usable key.
|
|
142
|
+
*/
|
|
143
|
+
function selectJwk(t, n) {
|
|
144
|
+
let r = t.keys.filter((e) => n.kid === void 0 || e.kid === n.kid), i = n.kid === void 0 ? {} : { kid: n.kid };
|
|
145
|
+
if (r.length === 0) return o("key_not_found", "No key matches the token", i);
|
|
146
|
+
let a = [];
|
|
147
|
+
for (let e of r) e.kind === "rsa" && unsuitableReason(e, n.algorithm) === void 0 && a.push(e);
|
|
148
|
+
let [s, c] = a;
|
|
149
|
+
return s === void 0 ? o("key_unsuitable", "No matching key can verify this algorithm", i) : c === void 0 ? e(s) : o("ambiguous_key", "More than one key matches the token", i);
|
|
150
|
+
}
|
|
151
|
+
/** Imports a selected entry as a verify-only RS256 `CryptoKey`. */
|
|
152
|
+
async function importJwkEntry(n) {
|
|
153
|
+
let r = unsuitableReason(n, "RS256");
|
|
154
|
+
if (r !== void 0) return o("key_unsuitable", r, n.kid === void 0 ? void 0 : { kid: n.kid });
|
|
155
|
+
let i = await t({
|
|
156
|
+
kty: "RSA",
|
|
157
|
+
n: n.n,
|
|
158
|
+
e: n.e,
|
|
159
|
+
alg: "RS256",
|
|
160
|
+
key_ops: ["verify"],
|
|
161
|
+
ext: !0
|
|
162
|
+
}, {
|
|
163
|
+
kind: "rsa",
|
|
164
|
+
scheme: "pkcs1-v1_5",
|
|
165
|
+
hash: "SHA-256"
|
|
166
|
+
});
|
|
167
|
+
if (!i.ok) return o("key_unsuitable", "The RSA JWK cannot be imported", { ...n.kid === void 0 ? {} : { kid: n.kid } });
|
|
168
|
+
let a = s(i.value);
|
|
169
|
+
return a.ok ? e(i.value) : a;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Creates a key resolver over a fixed JWK Set.
|
|
173
|
+
*
|
|
174
|
+
* The resolver selects with {@linkcode selectJwk} and imports each key once, so repeated
|
|
175
|
+
* verifications reuse the same `CryptoKey`.
|
|
176
|
+
*/
|
|
177
|
+
function createJwksKeyResolver(e) {
|
|
178
|
+
let t = /* @__PURE__ */ new Map();
|
|
179
|
+
return async (n) => {
|
|
180
|
+
let r = selectJwk(e, {
|
|
181
|
+
algorithm: n.algorithm,
|
|
182
|
+
...n.kid === void 0 ? {} : { kid: n.kid }
|
|
183
|
+
});
|
|
184
|
+
if (!r.ok) return r;
|
|
185
|
+
let i = t.get(r.value);
|
|
186
|
+
if (i !== void 0) return await i;
|
|
187
|
+
let a = importJwkEntry(r.value);
|
|
188
|
+
return t.set(r.value, a), await a;
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
export { l as DEFAULT_JWKS_LIMITS, createJwksKeyResolver, importJwkEntry, parseJwks, selectJwk };
|
|
192
|
+
|
|
193
|
+
//# sourceMappingURL=jwks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jwks.js","names":["DEFAULT_JWKS_LIMITS","joseFailure","message","object","name","value","isJsonArray","items","item","isJsonObject","kty","kid","use","alg","ops","successResult","metadata","n","e","bounds","limits","input","MAX_JWKS_BYTES_LIMIT","MAX_JWKS_KEYS_LIMIT","overrides","maxBytes","maxKeys","bytes","text","parsed","parseStrictJson","document","keys","entries","key","entry","op","algorithm","modulus","base64UrlDecode","exponent","validRsaPublicExponent","named","jwks","selector","details","usable","only","second","reason","imported","importPublicJwk","suitable","checkRs256VerificationKey","selected","request","cached","pending"],"sources":["../../src/jose/jwks.ts"],"sourcesContent":["/**\n * JSON Web Key Set (RFC 7517) parsing, key selection and a local key resolver. Nothing here\n * performs network access.\n *\n * @module\n */\n\nimport { base64UrlDecode } from '#micro509/internal/jose/base64url';\nimport type { JsonObject, JsonValue } from '#micro509/internal/jose/strict-json';\nimport { isJsonArray, isJsonObject, parseStrictJson } from '#micro509/internal/jose/strict-json';\nimport type { JoseErrorResult, JoseResult, KeyResolutionErrorCode } from '#micro509/jose/errors';\nimport { joseFailure } from '#micro509/jose/errors';\nimport type { JwsAlgorithm, JwsKeyResolver } from '#micro509/jose/jws';\nimport {\n\tcheckRs256VerificationKey,\n\tMIN_RS256_MODULUS_BITS,\n\tvalidRsaPublicExponent,\n} from '#micro509/jose/jws';\nimport { importPublicJwk } from '#micro509/keys/keys';\nimport { successResult } from '#micro509/result/result';\n\n/** Bounds applied while parsing a JWK Set. */\nexport interface JwksLimits {\n\t/** Maximum JWK Set size in bytes. Default `65536`. */\n\treadonly maxBytes: number;\n\t/** Maximum number of keys in the set. Default `32`. */\n\treadonly maxKeys: number;\n}\n\n/** The limits applied when a caller supplies none. */\nexport const DEFAULT_JWKS_LIMITS: JwksLimits = { maxBytes: 65_536, maxKeys: 32 };\n\nconst MAX_RSA_MODULUS_BYTES = 1024;\nconst MAX_JWKS_JSON_DEPTH = 8;\n\n/** Members every JWK entry carries beside its key material. */\nexport interface JwkMetadata {\n\t/** Key identifier. */\n\treadonly kid?: string;\n\t/** Intended use: `sig` or `enc`, or another value kept verbatim. */\n\treadonly use?: string;\n\t/** Permitted operations, verbatim. */\n\treadonly keyOps?: readonly string[];\n\t/** The algorithm the key is restricted to. */\n\treadonly alg?: string;\n}\n\n/** Members shared by every parsed entry. */\nexport interface JwkEntryBase extends JwkMetadata {\n\t/** Every member the entry carried, as parsed, including key material this module does not read. */\n\treadonly members: JsonObject;\n}\n\n/** An RSA public key entry. */\nexport interface RsaJwkEntry extends JwkEntryBase {\n\t/** Discriminant. */\n\treadonly kind: 'rsa';\n\t/** Base64url modulus. */\n\treadonly n: string;\n\t/** Base64url public exponent. */\n\treadonly e: string;\n}\n\n/**\n * An entry this module never selects: a `kty` other than `RSA`, or an entry with missing or\n * wrongly typed members (RFC 7517 §5). Kept so callers can inspect the whole set.\n */\nexport interface UnsupportedJwkEntry extends JwkEntryBase {\n\t/** Discriminant. */\n\treadonly kind: 'unsupported';\n\t/** The `kty` the entry carried, when it was a string. */\n\treadonly kty?: string;\n}\n\n/** One key of a JWK Set. */\nexport type JwkEntry = RsaJwkEntry | UnsupportedJwkEntry;\n\n/** A parsed JWK Set. */\nexport interface Jwks {\n\t/** The keys, in document order. */\n\treadonly keys: readonly JwkEntry[];\n\t/** Every top-level member of the document, as parsed. */\n\treadonly members: JsonObject;\n}\n\n/** Codes {@linkcode parseJwks} returns. */\nexport type ParseJwksErrorCode = 'jwks_malformed' | 'limit_exceeded' | 'invalid_options';\n\nfunction malformed(message: string): JoseErrorResult<'jwks_malformed'> {\n\treturn joseFailure('jwks_malformed', message);\n}\n\nfunction memberString(object: JsonObject, name: string): string | undefined | null {\n\tif (!Object.hasOwn(object, name)) return undefined;\n\tconst value = object[name];\n\treturn typeof value === 'string' ? value : null;\n}\n\nfunction memberStrings(object: JsonObject, name: string): readonly string[] | undefined | null {\n\tif (!Object.hasOwn(object, name)) return undefined;\n\tconst value: JsonValue | undefined = object[name];\n\tif (!isJsonArray(value)) return null;\n\tconst items: string[] = [];\n\tfor (const item of value) {\n\t\tif (typeof item !== 'string' || items.includes(item)) return null;\n\t\titems.push(item);\n\t}\n\treturn items;\n}\n\nfunction parseEntry(value: JsonValue): JoseResult<JwkEntry, 'jwks_malformed'> {\n\tif (!isJsonObject(value)) {\n\t\treturn malformed('JWK Set key is not an object');\n\t}\n\tconst kty = memberString(value, 'kty');\n\tconst kid = memberString(value, 'kid');\n\tconst use = memberString(value, 'use');\n\tconst alg = memberString(value, 'alg');\n\tconst ops = memberStrings(value, 'key_ops');\n\tif (typeof kty !== 'string' || kid === null || use === null || alg === null || ops === null) {\n\t\treturn successResult({\n\t\t\tkind: 'unsupported',\n\t\t\t...(typeof kty === 'string' ? { kty } : {}),\n\t\t\tmembers: value,\n\t\t});\n\t}\n\tconst metadata: JwkMetadata = {\n\t\t...(kid === undefined ? {} : { kid }),\n\t\t...(use === undefined ? {} : { use }),\n\t\t...(alg === undefined ? {} : { alg }),\n\t\t...(ops === undefined ? {} : { keyOps: ops }),\n\t};\n\tconst n = value.n;\n\tconst e = value.e;\n\tif (kty !== 'RSA' || typeof n !== 'string' || typeof e !== 'string') {\n\t\treturn successResult({ kind: 'unsupported', kty, ...metadata, members: value });\n\t}\n\treturn successResult({ kind: 'rsa', n, e, ...metadata, members: value });\n}\n\n/**\n * Parses a JWK Set document.\n *\n * The document must be duplicate-free JSON with a `keys` array within `limits`. Keys with a `kty`\n * other than `RSA`, and keys with missing or wrongly typed members, are kept as `unsupported`\n * entries and never selected (RFC 7517 §5). A set that is not a duplicate-free object with a\n * `keys` array of objects is `jwks_malformed`.\n */\nexport function parseJwks(\n\tinput: string | Uint8Array,\n\tlimits?: Partial<JwksLimits>,\n): JoseResult<Jwks, ParseJwksErrorCode> {\n\tconst bounds = resolveJwksLimits(limits);\n\tif (!bounds.ok) return bounds;\n\treturn parseWithLimits(input, bounds.value);\n}\n\nconst MAX_JWKS_BYTES_LIMIT = 16_777_216;\nconst MAX_JWKS_KEYS_LIMIT = 1024;\n\nfunction resolveJwksLimits(\n\toverrides: Partial<JwksLimits> | undefined,\n): JoseResult<JwksLimits, 'invalid_options'> {\n\tif (overrides !== undefined && (typeof overrides !== 'object' || overrides === null)) {\n\t\treturn joseFailure('invalid_options', 'limits must be an object');\n\t}\n\tconst maxBytes =\n\t\toverrides?.maxBytes === undefined ? DEFAULT_JWKS_LIMITS.maxBytes : overrides.maxBytes;\n\tconst maxKeys =\n\t\toverrides?.maxKeys === undefined ? DEFAULT_JWKS_LIMITS.maxKeys : overrides.maxKeys;\n\tif (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_JWKS_BYTES_LIMIT) {\n\t\treturn joseFailure(\n\t\t\t'invalid_options',\n\t\t\t`limits.maxBytes must be from 1 to ${MAX_JWKS_BYTES_LIMIT}`,\n\t\t);\n\t}\n\tif (!Number.isSafeInteger(maxKeys) || maxKeys < 1 || maxKeys > MAX_JWKS_KEYS_LIMIT) {\n\t\treturn joseFailure(\n\t\t\t'invalid_options',\n\t\t\t`limits.maxKeys must be from 1 to ${MAX_JWKS_KEYS_LIMIT}`,\n\t\t);\n\t}\n\treturn successResult({ maxBytes, maxKeys });\n}\n\nfunction parseWithLimits(\n\tinput: string | Uint8Array,\n\tbounds: JwksLimits,\n): JoseResult<Jwks, 'jwks_malformed' | 'limit_exceeded'> {\n\tif (typeof input === 'string' && input.length > bounds.maxBytes) {\n\t\treturn joseFailure('limit_exceeded', `JWK Set exceeds ${bounds.maxBytes} bytes`);\n\t}\n\tif (typeof input !== 'string' && !(input instanceof Uint8Array)) {\n\t\treturn malformed('JWK Set input is neither a string nor bytes');\n\t}\n\tconst bytes = typeof input === 'string' ? new TextEncoder().encode(input) : input;\n\tif (bytes.byteLength > bounds.maxBytes) {\n\t\treturn joseFailure('limit_exceeded', `JWK Set exceeds ${bounds.maxBytes} bytes`);\n\t}\n\tlet text: string;\n\ttry {\n\t\ttext = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);\n\t} catch {\n\t\treturn malformed('JWK Set is not valid UTF-8');\n\t}\n\tconst parsed = parseStrictJson(text, {\n\t\tmaxDepth: MAX_JWKS_JSON_DEPTH,\n\t\tmaxNodes: bounds.maxKeys * 64 + 64,\n\t});\n\tif (!parsed.ok) {\n\t\treturn parsed.code === 'limit_exceeded'\n\t\t\t? joseFailure('limit_exceeded', `JWK Set: ${parsed.message}`)\n\t\t\t: malformed(`JWK Set: ${parsed.message}`);\n\t}\n\tconst document = parsed.value;\n\tif (!isJsonObject(document)) {\n\t\treturn malformed('JWK Set is not an object');\n\t}\n\tconst keys = document.keys;\n\tif (!isJsonArray(keys)) return malformed('JWK Set \"keys\" is not an array');\n\tif (keys.length > bounds.maxKeys) {\n\t\treturn joseFailure('limit_exceeded', `JWK Set holds more than ${bounds.maxKeys} keys`);\n\t}\n\tconst entries: JwkEntry[] = [];\n\tfor (const key of keys) {\n\t\tconst entry = parseEntry(key);\n\t\tif (!entry.ok) return entry;\n\t\tentries.push(entry.value);\n\t}\n\treturn successResult({ keys: entries, members: document });\n}\n\n/** Why a key entry cannot verify a given algorithm, or `undefined` when it can. */\nfunction unsuitableReason(entry: JwkEntry, algorithm: JwsAlgorithm): string | undefined {\n\tif (entry.kind !== 'rsa') return 'key type does not match the algorithm';\n\tif (entry.use !== undefined && entry.use !== 'sig') return '\"use\" is not \"sig\"';\n\tif (entry.keyOps !== undefined && !entry.keyOps.includes('verify')) {\n\t\treturn '\"key_ops\" does not include \"verify\"';\n\t}\n\tif (entry.use === 'sig' && entry.keyOps?.some((op) => op !== 'sign' && op !== 'verify')) {\n\t\treturn '\"use\" and \"key_ops\" are inconsistent';\n\t}\n\tif (entry.alg !== undefined && entry.alg !== algorithm) return '\"alg\" names another algorithm';\n\tconst modulus = base64UrlDecode(entry.n);\n\tconst exponent = base64UrlDecode(entry.e);\n\tif (modulus === undefined || exponent === undefined || modulus.length === 0) {\n\t\treturn 'RSA parameters are not canonical base64url';\n\t}\n\tif (modulus[0] === 0 || exponent[0] === 0 || exponent.length === 0) {\n\t\treturn 'RSA parameters have leading zero octets';\n\t}\n\tif (modulus.length > MAX_RSA_MODULUS_BYTES) return 'RSA modulus is too large';\n\tconst modulusBits = (modulus.length - 1) * 8 + 32 - Math.clz32(modulus[0] ?? 0);\n\tif (modulusBits < MIN_RS256_MODULUS_BITS) return 'RSA modulus is too small';\n\tif (!validRsaPublicExponent(exponent, modulus)) return 'RSA public exponent is invalid';\n\treturn undefined;\n}\n\n/** What {@linkcode selectJwk} matches against. */\nexport interface JwkSelector {\n\t/** The algorithm the token uses. */\n\treadonly algorithm: JwsAlgorithm;\n\t/** The token's `kid`, when it carries one. */\n\treadonly kid?: string;\n}\n\n/**\n * Selects the one key of a set that can verify `selector`.\n *\n * Keys are filtered by `kid` (when the token has one), key type, `use`, `key_ops`, `alg` and RSA\n * parameters. No match is `key_not_found`, or `key_unsuitable` when `kid` matched only keys that\n * fail the other checks. More than one match is `ambiguous_key`: a token without `kid` therefore\n * resolves only against a set with a single usable key.\n */\nexport function selectJwk(\n\tjwks: Jwks,\n\tselector: JwkSelector,\n): JoseResult<RsaJwkEntry, Exclude<KeyResolutionErrorCode, 'jwks_unavailable' | 'aborted'>> {\n\tconst named = jwks.keys.filter(\n\t\t(entry) => selector.kid === undefined || entry.kid === selector.kid,\n\t);\n\tconst details = selector.kid === undefined ? {} : { kid: selector.kid };\n\tif (named.length === 0) return joseFailure('key_not_found', 'No key matches the token', details);\n\tconst usable: RsaJwkEntry[] = [];\n\tfor (const entry of named) {\n\t\tif (entry.kind === 'rsa' && unsuitableReason(entry, selector.algorithm) === undefined) {\n\t\t\tusable.push(entry);\n\t\t}\n\t}\n\tconst [only, second] = usable;\n\tif (only === undefined) {\n\t\treturn joseFailure('key_unsuitable', 'No matching key can verify this algorithm', details);\n\t}\n\tif (second !== undefined) {\n\t\treturn joseFailure('ambiguous_key', 'More than one key matches the token', details);\n\t}\n\treturn successResult(only);\n}\n\n/** Imports a selected entry as a verify-only RS256 `CryptoKey`. */\nexport async function importJwkEntry(\n\tentry: RsaJwkEntry,\n): Promise<JoseResult<CryptoKey, 'key_unsuitable'>> {\n\tconst reason = unsuitableReason(entry, 'RS256');\n\tif (reason !== undefined) {\n\t\treturn joseFailure(\n\t\t\t'key_unsuitable',\n\t\t\treason,\n\t\t\tentry.kid === undefined ? undefined : { kid: entry.kid },\n\t\t);\n\t}\n\tconst imported = await importPublicJwk(\n\t\t{ kty: 'RSA', n: entry.n, e: entry.e, alg: 'RS256', key_ops: ['verify'], ext: true },\n\t\t{ kind: 'rsa', scheme: 'pkcs1-v1_5', hash: 'SHA-256' },\n\t);\n\tif (!imported.ok) {\n\t\treturn joseFailure('key_unsuitable', 'The RSA JWK cannot be imported', {\n\t\t\t...(entry.kid === undefined ? {} : { kid: entry.kid }),\n\t\t});\n\t}\n\tconst suitable = checkRs256VerificationKey(imported.value);\n\treturn suitable.ok ? successResult(imported.value) : suitable;\n}\n\n/**\n * Creates a key resolver over a fixed JWK Set.\n *\n * The resolver selects with {@linkcode selectJwk} and imports each key once, so repeated\n * verifications reuse the same `CryptoKey`.\n */\nexport function createJwksKeyResolver(jwks: Jwks): JwsKeyResolver {\n\tconst imported = new Map<RsaJwkEntry, Promise<JoseResult<CryptoKey, 'key_unsuitable'>>>();\n\treturn async (request) => {\n\t\tconst selected = selectJwk(jwks, {\n\t\t\talgorithm: request.algorithm,\n\t\t\t...(request.kid === undefined ? {} : { kid: request.kid }),\n\t\t});\n\t\tif (!selected.ok) return selected;\n\t\tconst cached = imported.get(selected.value);\n\t\tif (cached !== undefined) return await cached;\n\t\tconst pending = importJwkEntry(selected.value);\n\t\timported.set(selected.value, pending);\n\t\treturn await pending;\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAaA,IAAkC;CAAE,UAAU;CAAQ,SAAS;AAAG;AA0D/E,SAAS,UAAU,GAAoD;CACtE,OAAOC,EAAY,kBAAkBC,CAAO;AAC7C;AAEA,SAAS,aAAa,GAAoB,GAAyC;CAClF,IAAI,CAAC,OAAO,OAAOC,GAAQC,CAAI,GAAG;CAClC,IAAMC,IAAQF,EAAOC;CACrB,OAAO,OAAOC,KAAU,WAAWA,IAAQ;AAC5C;AAEA,SAAS,cAAc,GAAoB,GAAoD;CAC9F,IAAI,CAAC,OAAO,OAAOF,GAAQC,CAAI,GAAG;CAClC,IAAMC,IAA+BF,EAAOC;CAC5C,IAAI,CAACE,EAAYD,CAAK,GAAG,OAAO;CAChC,IAAME,IAAkB,CAAC;CACzB,KAAK,IAAMC,KAAQH,GAAO;EACzB,IAAI,OAAOG,KAAS,YAAYD,EAAM,SAASC,CAAI,GAAG,OAAO;EAC7D,EAAM,KAAKA,CAAI;CAChB;CACA,OAAOD;AACR;AAEA,SAAS,WAAW,GAA0D;CAC7E,IAAI,CAACE,EAAaJ,CAAK,GACtB,OAAO,UAAU,8BAA8B;CAEhD,IAAMK,IAAM,aAAaL,GAAO,KAAK,GAC/BM,IAAM,aAAaN,GAAO,KAAK,GAC/BO,IAAM,aA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GACnB,GAAIA,EAAQ,QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,KAAKA,EAAQ,IAAI;EACzD,CAAC;EACD,IAAI,CAACD,EAAS,IAAI,OAAOA;EACzB,IAAME,IAASN,EAAS,IAAII,EAAS,KAAK;EAC1C,IAAIE,MAAW,KAAA,GAAW,OAAO,MAAMA;EACvC,IAAMC,IAAU,eAAeH,EAAS,KAAK;EAE7C,OADAJ,EAAS,IAAII,EAAS,OAAOG,CAAO,GAC7B,MAAMA;CACd;AACD"}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { JsonObject } from "../internal/jose/strict-json.js";
|
|
2
|
+
import { JoseResult, JwsParseErrorCode, KeyResolutionErrorCode, VerifyJwsErrorCode } from "./errors.js";
|
|
3
|
+
/** Signature algorithms this module signs and verifies. */
|
|
4
|
+
export type JwsAlgorithm = "RS256";
|
|
5
|
+
/** Every {@linkcode JwsAlgorithm}. */
|
|
6
|
+
export declare const JWS_ALGORITHMS: readonly JwsAlgorithm[];
|
|
7
|
+
/** Smallest RSA modulus RS256 accepts (RFC 7518 §3.3). */
|
|
8
|
+
export declare const MIN_RS256_MODULUS_BITS = 2048;
|
|
9
|
+
/** Size and structure bounds enforced before any expensive parsing. */
|
|
10
|
+
export interface JoseLimits {
|
|
11
|
+
/** Maximum compact serialization length in characters. Default `32768`. */
|
|
12
|
+
readonly maxTokenLength: number;
|
|
13
|
+
/** Maximum decoded protected header size in bytes. Default `4096`. */
|
|
14
|
+
readonly maxHeaderBytes: number;
|
|
15
|
+
/** Maximum decoded payload size in bytes. Default `16384`. */
|
|
16
|
+
readonly maxPayloadBytes: number;
|
|
17
|
+
/** Maximum decoded signature size in bytes. Default `1024`. */
|
|
18
|
+
readonly maxSignatureBytes: number;
|
|
19
|
+
/** Maximum JSON nesting in the header and payload. Default `16`. */
|
|
20
|
+
readonly maxJsonDepth: number;
|
|
21
|
+
/** Maximum JSON values in the header or payload. Default `2048`. */
|
|
22
|
+
readonly maxJsonNodes: number;
|
|
23
|
+
}
|
|
24
|
+
/** The limits applied when a caller supplies none. */
|
|
25
|
+
export declare const DEFAULT_JOSE_LIMITS: JoseLimits;
|
|
26
|
+
/** A protected header. Every member the token carried stays reachable through `members`. */
|
|
27
|
+
export interface JwsHeader<TAlgorithm extends string = string> {
|
|
28
|
+
/** The `alg` member. */
|
|
29
|
+
readonly alg: TAlgorithm;
|
|
30
|
+
/** The `typ` member, when present. */
|
|
31
|
+
readonly typ?: string;
|
|
32
|
+
/** The `kid` member, when present. */
|
|
33
|
+
readonly kid?: string;
|
|
34
|
+
/** The `cty` member, when present. */
|
|
35
|
+
readonly cty?: string;
|
|
36
|
+
/** Every header member as the token carried it. */
|
|
37
|
+
readonly members: JsonObject;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* A parsed token whose signature has not been checked. Nothing in it is trustworthy until
|
|
41
|
+
* {@linkcode verifyCompactJws} succeeds.
|
|
42
|
+
*/
|
|
43
|
+
export interface UnverifiedJws {
|
|
44
|
+
/** Always `false`. */
|
|
45
|
+
readonly verified: false;
|
|
46
|
+
/** The header, unauthenticated. */
|
|
47
|
+
readonly header: JwsHeader;
|
|
48
|
+
/** The payload bytes, unauthenticated. */
|
|
49
|
+
readonly payload: Uint8Array;
|
|
50
|
+
/** ASCII bytes of `BASE64URL(header) || '.' || BASE64URL(payload)`. */
|
|
51
|
+
readonly signingInput: Uint8Array;
|
|
52
|
+
/** The decoded signature bytes. */
|
|
53
|
+
readonly signature: Uint8Array;
|
|
54
|
+
}
|
|
55
|
+
/** A token whose signature verified under the caller's algorithm and key policy. */
|
|
56
|
+
export interface VerifiedJws {
|
|
57
|
+
/** Always `true`. */
|
|
58
|
+
readonly verified: true;
|
|
59
|
+
/** The authenticated protected header. */
|
|
60
|
+
readonly header: JwsHeader<JwsAlgorithm>;
|
|
61
|
+
/** The authenticated payload bytes. */
|
|
62
|
+
readonly payload: Uint8Array;
|
|
63
|
+
}
|
|
64
|
+
/** What a key resolver is asked for. The header is unauthenticated. */
|
|
65
|
+
export interface JwsKeyRequest {
|
|
66
|
+
/** The unauthenticated header of the token being verified. */
|
|
67
|
+
readonly header: JwsHeader<JwsAlgorithm>;
|
|
68
|
+
/** The algorithm the policy admitted for this token. */
|
|
69
|
+
readonly algorithm: JwsAlgorithm;
|
|
70
|
+
/** The `kid` header, when present. */
|
|
71
|
+
readonly kid?: string;
|
|
72
|
+
/** Cancellation from {@linkcode VerifyJwsOptions.signal}. */
|
|
73
|
+
readonly signal?: AbortSignal;
|
|
74
|
+
}
|
|
75
|
+
/** Supplies the verification key for a token. */
|
|
76
|
+
export type JwsKeyResolver = (request: JwsKeyRequest) => Promise<JoseResult<CryptoKey, KeyResolutionErrorCode>>;
|
|
77
|
+
/** Marks a policy dimension as deliberately not checked. */
|
|
78
|
+
export interface Unchecked {
|
|
79
|
+
/** Always `true`. */
|
|
80
|
+
readonly unchecked: true;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Expectation for the `typ` header (RFC 7515 §4.1.9, RFC 8725 §3.11).
|
|
84
|
+
*
|
|
85
|
+
* A string requires that media type, compared case-insensitively with an omitted `application/`
|
|
86
|
+
* prefix restored. `{ absent: true }` requires the header to be missing. `{ unchecked: true }`
|
|
87
|
+
* accepts any value.
|
|
88
|
+
*/
|
|
89
|
+
export type TokenTypePolicy = string | {
|
|
90
|
+
readonly absent: true;
|
|
91
|
+
} | Unchecked;
|
|
92
|
+
/** Options for {@linkcode verifyCompactJws}. */
|
|
93
|
+
export interface VerifyJwsOptions {
|
|
94
|
+
/** Algorithms admitted for this token use. Never derived from the token. */
|
|
95
|
+
readonly algorithms: readonly [JwsAlgorithm, ...JwsAlgorithm[]];
|
|
96
|
+
/** A fixed verification key, or a resolver chosen by the caller. */
|
|
97
|
+
readonly key: CryptoKey | JwsKeyResolver;
|
|
98
|
+
/** The token type this verification accepts. */
|
|
99
|
+
readonly tokenType: TokenTypePolicy;
|
|
100
|
+
/** Overrides for {@linkcode DEFAULT_JOSE_LIMITS}. */
|
|
101
|
+
readonly limits?: Partial<JoseLimits>;
|
|
102
|
+
/** Cancels key resolution. */
|
|
103
|
+
readonly signal?: AbortSignal;
|
|
104
|
+
}
|
|
105
|
+
/** Header members {@linkcode signCompactJws} sets beside `alg`. */
|
|
106
|
+
export interface JwsHeaderInput {
|
|
107
|
+
/** Token type. */
|
|
108
|
+
readonly typ?: string;
|
|
109
|
+
/** Key identifier. */
|
|
110
|
+
readonly kid?: string;
|
|
111
|
+
/** Content type. */
|
|
112
|
+
readonly cty?: string;
|
|
113
|
+
}
|
|
114
|
+
/** Input for {@linkcode signCompactJws}. */
|
|
115
|
+
export interface SignJwsInput {
|
|
116
|
+
/** An RSASSA-PKCS1-v1_5 SHA-256 private key of at least 2048 bits. */
|
|
117
|
+
readonly privateKey: CryptoKey;
|
|
118
|
+
/** The signature algorithm. */
|
|
119
|
+
readonly algorithm: JwsAlgorithm;
|
|
120
|
+
/** The payload bytes. */
|
|
121
|
+
readonly payload: Uint8Array;
|
|
122
|
+
/** Header members beside `alg`. */
|
|
123
|
+
readonly header?: JwsHeaderInput;
|
|
124
|
+
}
|
|
125
|
+
/** Codes {@linkcode signCompactJws} and {@linkcode signJwt} throw. */
|
|
126
|
+
export type SignJoseErrorCode = "unsupported_algorithm" | "incompatible_key" | "invalid_header" | "invalid_claims";
|
|
127
|
+
/**
|
|
128
|
+
* Parses a compact JWS without checking its signature.
|
|
129
|
+
*
|
|
130
|
+
* Refuses tokens that are oversized, do not have exactly three segments, carry non-canonical
|
|
131
|
+
* base64url, invalid UTF-8, a header that is not a duplicate-free JSON object with a string `alg`,
|
|
132
|
+
* a `crit` list, or an unencoded payload (`b64: false`). The result is {@linkcode UnverifiedJws};
|
|
133
|
+
* pass the token to {@linkcode verifyCompactJws} before trusting any of it.
|
|
134
|
+
*/
|
|
135
|
+
export declare function parseCompactJws(token: string, limits?: Partial<JoseLimits>): JoseResult<UnverifiedJws, JwsParseErrorCode | "invalid_options">;
|
|
136
|
+
/**
|
|
137
|
+
* Verifies a compact JWS.
|
|
138
|
+
*
|
|
139
|
+
* The caller's `algorithms` list decides what is accepted; the token's `alg` only selects among
|
|
140
|
+
* them, and `none` is always refused as `unsigned_token`. The `tokenType` policy is applied before
|
|
141
|
+
* any key is resolved. A fixed key or the resolver's key must be an RSASSA-PKCS1-v1_5 SHA-256
|
|
142
|
+
* public key of at least 2048 bits for RS256. Header members such as `jku`, `jwk`, `x5u` and
|
|
143
|
+
* `x5c` are never used to find a key. A resolver that throws or returns something other than a
|
|
144
|
+
* result is reported as `key_resolution_failed` without its message.
|
|
145
|
+
*
|
|
146
|
+
* Returns a {@linkcode VerifiedJws} on success. Failures carry a stable code and never echo the
|
|
147
|
+
* token.
|
|
148
|
+
*/
|
|
149
|
+
export declare function verifyCompactJws(token: string, options: VerifyJwsOptions): Promise<JoseResult<VerifiedJws, VerifyJwsErrorCode>>;
|
|
150
|
+
/**
|
|
151
|
+
* Signs a compact JWS with an existing private `CryptoKey`.
|
|
152
|
+
*
|
|
153
|
+
* The header is `alg` followed by the optional `typ`, `kid` and `cty`. Throws a `ResultError`
|
|
154
|
+
* (see `isResultError`) coded {@linkcode SignJoseErrorCode} when the algorithm, key or header
|
|
155
|
+
* input is invalid. Intended for issuing tokens and for building synthetic tokens in tests.
|
|
156
|
+
*/
|
|
157
|
+
export declare function signCompactJws(input: SignJwsInput): Promise<string>;
|
|
158
|
+
//# sourceMappingURL=jws.d.ts.map
|