@owf/jose 0.0.0-stage → 0.0.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/README.md +172 -2
- package/dist/index.d.mts +1609 -0
- package/dist/index.mjs +1569 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +43 -4
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1569 @@
|
|
|
1
|
+
import { IdentityError, ValidationError, ValidationIssues, addValidationIssue, base64, base64url, base64urlDecodeJson, base64urlEncode, bytesToString, parseWithErrorHandling, secondsToDate, stringToBytes, zBase64Url, zNonEmptyString, zNumericDate } from "@owf/identity-common";
|
|
2
|
+
import z from "zod";
|
|
3
|
+
// src/error.ts
|
|
4
|
+
/**
|
|
5
|
+
* Base error class for `@owf/jose`. `cause` is declared here, as `Error.cause` is ES2022 and the
|
|
6
|
+
* project targets ES2020.
|
|
7
|
+
*/
|
|
8
|
+
var JoseError = class extends IdentityError {
|
|
9
|
+
constructor(message, options) {
|
|
10
|
+
super(message, options?.details);
|
|
11
|
+
this.cause = options?.cause;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* A token is not well-formed: a wrong structure, or a part that is not valid base64url, UTF-8 or
|
|
16
|
+
* JSON. The message never includes the input, so a token is not logged by accident.
|
|
17
|
+
*/
|
|
18
|
+
var JoseParseError = class extends JoseError {};
|
|
19
|
+
/**
|
|
20
|
+
* A structure is well-formed but does not validate: its schema, `crit` or claims. Like the validation
|
|
21
|
+
* errors of the other packages, it extends `ValidationError`, not {@link JoseError}.
|
|
22
|
+
*/
|
|
23
|
+
var JoseValidationError = class extends ValidationError {};
|
|
24
|
+
/**
|
|
25
|
+
* A token is well-formed but does not verify: its signature, signer or algorithm. The subclasses say
|
|
26
|
+
* which. Claims that do not verify throw a {@link JoseValidationError}.
|
|
27
|
+
*/
|
|
28
|
+
var JoseVerificationError = class extends JoseError {};
|
|
29
|
+
/** The signature over a JWS does not verify, or the verification callback rejected it. */
|
|
30
|
+
var JoseSignatureVerificationError = class extends JoseVerificationError {};
|
|
31
|
+
/** The `alg` of a token is not among the algorithms the caller allows. */
|
|
32
|
+
var JoseAlgorithmNotAllowedError = class extends JoseVerificationError {};
|
|
33
|
+
/** The key that identifies the signer cannot be determined from the token, or is ambiguous. */
|
|
34
|
+
var JoseSignerError = class extends JoseVerificationError {};
|
|
35
|
+
/** The token uses a feature that this library does not implement. */
|
|
36
|
+
var JoseNotSupportedError = class extends JoseError {};
|
|
37
|
+
/**
|
|
38
|
+
* A mistake in the calling code, not in a token: an invalid or contradicting option, or a signing
|
|
39
|
+
* callback result that breaks the contract of the callback.
|
|
40
|
+
*/
|
|
41
|
+
var JoseInvalidArgumentError = class extends JoseError {};
|
|
42
|
+
// src/jwa/algorithms.ts
|
|
43
|
+
/**
|
|
44
|
+
* JWA (JSON Web Algorithms) identifiers.
|
|
45
|
+
*
|
|
46
|
+
* @see https://www.rfc-editor.org/rfc/rfc7518
|
|
47
|
+
* @see https://www.iana.org/assignments/jose/jose.xhtml
|
|
48
|
+
*/
|
|
49
|
+
/**
|
|
50
|
+
* JWS signature and MAC algorithms. `none` is absent: an unsecured JWS is never accepted.
|
|
51
|
+
*
|
|
52
|
+
* @see https://www.rfc-editor.org/rfc/rfc7518#section-3.1
|
|
53
|
+
* @see https://www.rfc-editor.org/rfc/rfc9864 for the fully-specified EdDSA algorithms
|
|
54
|
+
*/
|
|
55
|
+
let JwaSignatureAlgorithm = /* @__PURE__ */ function(JwaSignatureAlgorithm) {
|
|
56
|
+
JwaSignatureAlgorithm["HS256"] = "HS256";
|
|
57
|
+
JwaSignatureAlgorithm["HS384"] = "HS384";
|
|
58
|
+
JwaSignatureAlgorithm["HS512"] = "HS512";
|
|
59
|
+
JwaSignatureAlgorithm["RS256"] = "RS256";
|
|
60
|
+
JwaSignatureAlgorithm["RS384"] = "RS384";
|
|
61
|
+
JwaSignatureAlgorithm["RS512"] = "RS512";
|
|
62
|
+
JwaSignatureAlgorithm["PS256"] = "PS256";
|
|
63
|
+
JwaSignatureAlgorithm["PS384"] = "PS384";
|
|
64
|
+
JwaSignatureAlgorithm["PS512"] = "PS512";
|
|
65
|
+
JwaSignatureAlgorithm["ES256"] = "ES256";
|
|
66
|
+
JwaSignatureAlgorithm["ES384"] = "ES384";
|
|
67
|
+
JwaSignatureAlgorithm["ES512"] = "ES512";
|
|
68
|
+
JwaSignatureAlgorithm["ES256K"] = "ES256K";
|
|
69
|
+
JwaSignatureAlgorithm["EdDSA"] = "EdDSA";
|
|
70
|
+
JwaSignatureAlgorithm["Ed25519"] = "Ed25519";
|
|
71
|
+
JwaSignatureAlgorithm["Ed448"] = "Ed448";
|
|
72
|
+
return JwaSignatureAlgorithm;
|
|
73
|
+
}({});
|
|
74
|
+
/** The signature algorithms with a symmetric key, with which every verifier can also issue a token. */
|
|
75
|
+
const symmetricSignatureAlgorithms = [
|
|
76
|
+
"HS256",
|
|
77
|
+
"HS384",
|
|
78
|
+
"HS512"
|
|
79
|
+
];
|
|
80
|
+
/**
|
|
81
|
+
* JWE key management algorithms.
|
|
82
|
+
*
|
|
83
|
+
* @see https://www.rfc-editor.org/rfc/rfc7518#section-4.1
|
|
84
|
+
*/
|
|
85
|
+
let JwaKeyManagementAlgorithm = /* @__PURE__ */ function(JwaKeyManagementAlgorithm) {
|
|
86
|
+
JwaKeyManagementAlgorithm["RSA1_5"] = "RSA1_5";
|
|
87
|
+
JwaKeyManagementAlgorithm["RSA_OAEP"] = "RSA-OAEP";
|
|
88
|
+
JwaKeyManagementAlgorithm["RSA_OAEP_256"] = "RSA-OAEP-256";
|
|
89
|
+
JwaKeyManagementAlgorithm["A128KW"] = "A128KW";
|
|
90
|
+
JwaKeyManagementAlgorithm["A192KW"] = "A192KW";
|
|
91
|
+
JwaKeyManagementAlgorithm["A256KW"] = "A256KW";
|
|
92
|
+
JwaKeyManagementAlgorithm["Dir"] = "dir";
|
|
93
|
+
JwaKeyManagementAlgorithm["ECDH_ES"] = "ECDH-ES";
|
|
94
|
+
JwaKeyManagementAlgorithm["ECDH_ES_A128KW"] = "ECDH-ES+A128KW";
|
|
95
|
+
JwaKeyManagementAlgorithm["ECDH_ES_A192KW"] = "ECDH-ES+A192KW";
|
|
96
|
+
JwaKeyManagementAlgorithm["ECDH_ES_A256KW"] = "ECDH-ES+A256KW";
|
|
97
|
+
JwaKeyManagementAlgorithm["A128GCMKW"] = "A128GCMKW";
|
|
98
|
+
JwaKeyManagementAlgorithm["A192GCMKW"] = "A192GCMKW";
|
|
99
|
+
JwaKeyManagementAlgorithm["A256GCMKW"] = "A256GCMKW";
|
|
100
|
+
return JwaKeyManagementAlgorithm;
|
|
101
|
+
}({});
|
|
102
|
+
/**
|
|
103
|
+
* JWE content encryption algorithms.
|
|
104
|
+
*
|
|
105
|
+
* @see https://www.rfc-editor.org/rfc/rfc7518#section-5.1
|
|
106
|
+
*/
|
|
107
|
+
let JwaContentEncryptionAlgorithm = /* @__PURE__ */ function(JwaContentEncryptionAlgorithm) {
|
|
108
|
+
JwaContentEncryptionAlgorithm["A128CBC_HS256"] = "A128CBC-HS256";
|
|
109
|
+
JwaContentEncryptionAlgorithm["A192CBC_HS384"] = "A192CBC-HS384";
|
|
110
|
+
JwaContentEncryptionAlgorithm["A256CBC_HS512"] = "A256CBC-HS512";
|
|
111
|
+
JwaContentEncryptionAlgorithm["A128GCM"] = "A128GCM";
|
|
112
|
+
JwaContentEncryptionAlgorithm["A192GCM"] = "A192GCM";
|
|
113
|
+
JwaContentEncryptionAlgorithm["A256GCM"] = "A256GCM";
|
|
114
|
+
return JwaContentEncryptionAlgorithm;
|
|
115
|
+
}({});
|
|
116
|
+
/**
|
|
117
|
+
* The key types (`kty`) a signature algorithm can be used with. Checking it prevents key confusion,
|
|
118
|
+
* such as `HS256` with an RSA public key as the MAC secret.
|
|
119
|
+
*
|
|
120
|
+
* @see https://www.rfc-editor.org/rfc/rfc7518#section-3.1
|
|
121
|
+
* @see https://www.rfc-editor.org/rfc/rfc8725#section-3.5
|
|
122
|
+
*/
|
|
123
|
+
const signatureAlgorithmKeyTypes = {
|
|
124
|
+
["HS256"]: ["oct"],
|
|
125
|
+
["HS384"]: ["oct"],
|
|
126
|
+
["HS512"]: ["oct"],
|
|
127
|
+
["RS256"]: ["RSA"],
|
|
128
|
+
["RS384"]: ["RSA"],
|
|
129
|
+
["RS512"]: ["RSA"],
|
|
130
|
+
["PS256"]: ["RSA"],
|
|
131
|
+
["PS384"]: ["RSA"],
|
|
132
|
+
["PS512"]: ["RSA"],
|
|
133
|
+
["ES256"]: ["EC"],
|
|
134
|
+
["ES384"]: ["EC"],
|
|
135
|
+
["ES512"]: ["EC"],
|
|
136
|
+
["ES256K"]: ["EC"],
|
|
137
|
+
["EdDSA"]: ["OKP"],
|
|
138
|
+
["Ed25519"]: ["OKP"],
|
|
139
|
+
["Ed448"]: ["OKP"]
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* The curve (`crv`) of the signature algorithms that fully specify one. `EdDSA` is polymorphic.
|
|
143
|
+
*
|
|
144
|
+
* @see https://www.rfc-editor.org/rfc/rfc7518#section-3.4
|
|
145
|
+
* @see https://www.rfc-editor.org/rfc/rfc9864#section-2
|
|
146
|
+
*/
|
|
147
|
+
const signatureAlgorithmCurves = {
|
|
148
|
+
["ES256"]: "P-256",
|
|
149
|
+
["ES384"]: "P-384",
|
|
150
|
+
["ES512"]: "P-521",
|
|
151
|
+
["ES256K"]: "secp256k1",
|
|
152
|
+
["Ed25519"]: "Ed25519",
|
|
153
|
+
["Ed448"]: "Ed448"
|
|
154
|
+
};
|
|
155
|
+
const isJwaSignatureAlgorithm = (alg) => Object.values(JwaSignatureAlgorithm).includes(alg);
|
|
156
|
+
const isSymmetricSignatureAlgorithm = (alg) => symmetricSignatureAlgorithms.includes(alg);
|
|
157
|
+
/**
|
|
158
|
+
* Whether `alg` is a registered signature algorithm in a different casing, such as `hs256`. None of
|
|
159
|
+
* the checks here recognize it, but a case-insensitive comparison downstream could verify it as the
|
|
160
|
+
* registered one. Both casings are compared, as they differ outside ASCII: `ſ` upper cases to `S`.
|
|
161
|
+
*
|
|
162
|
+
* @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.1
|
|
163
|
+
*/
|
|
164
|
+
const isJwaSignatureAlgorithmCaseVariant = (alg) => typeof alg === "string" && !isJwaSignatureAlgorithm(alg) && Object.values(JwaSignatureAlgorithm).some((registered) => registered.toLowerCase() === alg.toLowerCase() || registered.toUpperCase() === alg.toUpperCase());
|
|
165
|
+
// src/utils/object.ts
|
|
166
|
+
/** Whether `key` is an own property of `object`, so `constructor` or `toString` are not found everywhere. */
|
|
167
|
+
const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
|
|
168
|
+
/**
|
|
169
|
+
* Whether two JSON values are the same value: arrays holding the same values in the same order, and
|
|
170
|
+
* objects with the same members, in whatever order. A member set to `undefined` counts as absent, as
|
|
171
|
+
* it is once serialized.
|
|
172
|
+
*/
|
|
173
|
+
function isSameJsonValue(a, b) {
|
|
174
|
+
if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((value, index) => isSameJsonValue(value, b[index]));
|
|
175
|
+
if (typeof a === "object" && a !== null && typeof b === "object" && b !== null) {
|
|
176
|
+
const membersOf = (object) => Object.keys(object).filter((member) => object[member] !== void 0);
|
|
177
|
+
const membersOfA = membersOf(a);
|
|
178
|
+
return membersOfA.length === membersOf(b).length && membersOfA.every((member) => hasOwn(b, member) && isSameJsonValue(a[member], b[member]));
|
|
179
|
+
}
|
|
180
|
+
return a === b;
|
|
181
|
+
}
|
|
182
|
+
// src/jwa/cose-algorithm.ts
|
|
183
|
+
/**
|
|
184
|
+
* Mapping between JWA and COSE algorithm identifiers. COSE identifiers are integers, so no dependency
|
|
185
|
+
* on `@owf/cose` is needed.
|
|
186
|
+
*
|
|
187
|
+
* @see https://www.rfc-editor.org/rfc/rfc9864 Fully-Specified Algorithms for JOSE and COSE
|
|
188
|
+
*/
|
|
189
|
+
/**
|
|
190
|
+
* JWA signature algorithms to fully-specified COSE algorithms. The JOSE `ES256` is fully specified, so
|
|
191
|
+
* it maps to `ESP256` (-9), not to the polymorphic COSE `ES256` (-7).
|
|
192
|
+
*/
|
|
193
|
+
const JWA_SIGNATURE_TO_COSE_ALGORITHM_MAP = {
|
|
194
|
+
["Ed25519"]: -19,
|
|
195
|
+
["Ed448"]: -53,
|
|
196
|
+
["EdDSA"]: -19,
|
|
197
|
+
["ES256"]: -9,
|
|
198
|
+
["ES384"]: -51,
|
|
199
|
+
["ES512"]: -52,
|
|
200
|
+
["ES256K"]: -47,
|
|
201
|
+
["RS256"]: -257,
|
|
202
|
+
["RS384"]: -258,
|
|
203
|
+
["RS512"]: -259,
|
|
204
|
+
["PS256"]: -37,
|
|
205
|
+
["PS384"]: -38,
|
|
206
|
+
["PS512"]: -39,
|
|
207
|
+
["HS256"]: 5,
|
|
208
|
+
["HS384"]: 6,
|
|
209
|
+
["HS512"]: 7
|
|
210
|
+
};
|
|
211
|
+
/** The inverse of {@link JWA_SIGNATURE_TO_COSE_ALGORITHM_MAP}, plus the deprecated polymorphic COSE algorithms. */
|
|
212
|
+
const COSE_TO_JWA_SIGNATURE_ALGORITHM_MAP = {
|
|
213
|
+
[-19]: "Ed25519",
|
|
214
|
+
[-53]: "Ed448",
|
|
215
|
+
[-8]: "Ed25519",
|
|
216
|
+
[-9]: "ES256",
|
|
217
|
+
[-51]: "ES384",
|
|
218
|
+
[-52]: "ES512",
|
|
219
|
+
[-47]: "ES256K",
|
|
220
|
+
[-7]: "ES256",
|
|
221
|
+
[-35]: "ES384",
|
|
222
|
+
[-36]: "ES512",
|
|
223
|
+
[-257]: "RS256",
|
|
224
|
+
[-258]: "RS384",
|
|
225
|
+
[-259]: "RS512",
|
|
226
|
+
[-37]: "PS256",
|
|
227
|
+
[-38]: "PS384",
|
|
228
|
+
[-39]: "PS512",
|
|
229
|
+
5: "HS256",
|
|
230
|
+
6: "HS384",
|
|
231
|
+
7: "HS512"
|
|
232
|
+
};
|
|
233
|
+
/**
|
|
234
|
+
* Transforms a JWA signature algorithm identifier into an RFC 9864 fully-specified COSE algorithm
|
|
235
|
+
* identifier, or `undefined` when it has no COSE counterpart.
|
|
236
|
+
*
|
|
237
|
+
* @example
|
|
238
|
+
* ```ts
|
|
239
|
+
* jwaSignatureAlgorithmToCoseAlgorithm('ES256') // -9 (ESP256)
|
|
240
|
+
* ```
|
|
241
|
+
*/
|
|
242
|
+
function jwaSignatureAlgorithmToCoseAlgorithm(jwaAlg) {
|
|
243
|
+
return hasOwn(JWA_SIGNATURE_TO_COSE_ALGORITHM_MAP, jwaAlg) ? JWA_SIGNATURE_TO_COSE_ALGORITHM_MAP[jwaAlg] : void 0;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Transforms a COSE algorithm identifier — fully specified or polymorphic — into a JWA signature
|
|
247
|
+
* algorithm identifier, or `undefined` when it has no JWA counterpart.
|
|
248
|
+
*
|
|
249
|
+
* @example
|
|
250
|
+
* ```ts
|
|
251
|
+
* coseAlgorithmToJwaSignatureAlgorithm(-7) // 'ES256' (from the deprecated polymorphic COSE ES256)
|
|
252
|
+
* ```
|
|
253
|
+
*/
|
|
254
|
+
function coseAlgorithmToJwaSignatureAlgorithm(coseAlg) {
|
|
255
|
+
return hasOwn(COSE_TO_JWA_SIGNATURE_ALGORITHM_MAP, coseAlg) ? COSE_TO_JWA_SIGNATURE_ALGORITHM_MAP[coseAlg] : void 0;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Transforms JWA signature algorithm identifiers into fully-specified COSE algorithm identifiers,
|
|
259
|
+
* dropping the ones that have no COSE counterpart, or throwing when `throwOnUnknownValue` is set.
|
|
260
|
+
*/
|
|
261
|
+
function jwaSignatureAlgorithmsToCoseAlgorithms(jwaAlgs, throwOnUnknownValue = false) {
|
|
262
|
+
return jwaAlgs.map((jwaAlg) => {
|
|
263
|
+
const coseAlg = jwaSignatureAlgorithmToCoseAlgorithm(jwaAlg);
|
|
264
|
+
if (coseAlg || !throwOnUnknownValue) return coseAlg;
|
|
265
|
+
throw new JoseNotSupportedError(`Found unknown JWA signature algorithm '${jwaAlg}'. Unable to map to COSE.`);
|
|
266
|
+
}).filter((coseAlg) => coseAlg !== void 0);
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Transforms COSE algorithm identifiers into JWA signature algorithm identifiers, dropping the ones
|
|
270
|
+
* that have no JWA counterpart, or throwing when `throwOnUnknownValue` is set.
|
|
271
|
+
*/
|
|
272
|
+
function coseAlgorithmsToJwaSignatureAlgorithms(coseAlgs, throwOnUnknownValue = false) {
|
|
273
|
+
return coseAlgs.map((coseAlg) => {
|
|
274
|
+
const jwaAlg = coseAlgorithmToJwaSignatureAlgorithm(coseAlg);
|
|
275
|
+
if (jwaAlg || !throwOnUnknownValue) return jwaAlg;
|
|
276
|
+
throw new JoseNotSupportedError(`Found unknown COSE algorithm identifier '${coseAlg}'. Unable to map to JWA.`);
|
|
277
|
+
}).filter((jwaAlg) => jwaAlg !== void 0);
|
|
278
|
+
}
|
|
279
|
+
// src/jwa/key-compatibility.ts
|
|
280
|
+
/** `EdDSA` with the curve fixed (RFC 9864 section 2.2). */
|
|
281
|
+
const fullySpecifiedEdDsaAlgorithms = ["Ed25519", "Ed448"];
|
|
282
|
+
/** The curves of `EdDSA` (RFC 8037 section 3.1). `X25519` and `X448` are for key agreement. */
|
|
283
|
+
const edDsaCurves = ["Ed25519", "Ed448"];
|
|
284
|
+
/**
|
|
285
|
+
* Checks that a key can be used with a signature algorithm, as the token chooses its `alg` but not the
|
|
286
|
+
* key: the key type (no key confusion), the curve where the algorithm fixes one, and the `alg`, `use`
|
|
287
|
+
* and `key_ops` the key declares. `EdDSA` and `Ed25519`/`Ed448` (RFC 9864) count as the same `alg`.
|
|
288
|
+
* An unregistered algorithm is left to the verification callback, but one that differs from a
|
|
289
|
+
* registered algorithm only in casing is rejected.
|
|
290
|
+
*
|
|
291
|
+
* @throws JoseAlgorithmNotAllowedError when the key cannot be used with the algorithm.
|
|
292
|
+
*/
|
|
293
|
+
function assertKeyAllowedForSignatureAlgorithm({ jwk, alg, errorMessage = "Unable to use the key with the algorithm of the token." }) {
|
|
294
|
+
const isEdDsaEquivalent = jwk.alg === "EdDSA" && fullySpecifiedEdDsaAlgorithms.includes(alg) || alg === "EdDSA" && jwk.alg !== void 0 && fullySpecifiedEdDsaAlgorithms.includes(jwk.alg);
|
|
295
|
+
if (jwk.alg !== void 0 && jwk.alg !== alg && !isEdDsaEquivalent) throw new JoseAlgorithmNotAllowedError(`${errorMessage} The key declares alg '${jwk.alg}', but the token uses alg '${alg}'.`);
|
|
296
|
+
if (jwk.use !== void 0 && jwk.use !== "sig") throw new JoseAlgorithmNotAllowedError(`${errorMessage} The key declares use '${jwk.use}' instead of 'sig'.`);
|
|
297
|
+
if (jwk.key_ops !== void 0 && !jwk.key_ops.includes("verify") && !jwk.key_ops.includes("sign")) throw new JoseAlgorithmNotAllowedError(`${errorMessage} The key declares key_ops ${jwk.key_ops.map((op) => `'${op}'`).join(", ")}, which does not include 'sign' or 'verify'.`);
|
|
298
|
+
if (isJwaSignatureAlgorithmCaseVariant(alg)) throw new JoseAlgorithmNotAllowedError(`${errorMessage} The token uses alg '${alg}', which differs from a registered algorithm only in casing.`);
|
|
299
|
+
if (!isJwaSignatureAlgorithm(alg)) return;
|
|
300
|
+
const keyAlgorithm = isEdDsaEquivalent && alg === "EdDSA" ? jwk.alg : alg;
|
|
301
|
+
const keyTypes = signatureAlgorithmKeyTypes[keyAlgorithm];
|
|
302
|
+
if (!keyTypes.includes(jwk.kty)) throw new JoseAlgorithmNotAllowedError(`${errorMessage} Algorithm '${keyAlgorithm}' requires a key with kty ${keyTypes.map((kty) => `'${kty}'`).join(" or ")}, but the key has kty '${jwk.kty}'.`);
|
|
303
|
+
const curve = signatureAlgorithmCurves[keyAlgorithm];
|
|
304
|
+
const curves = curve !== void 0 ? [curve] : keyAlgorithm === "EdDSA" ? edDsaCurves : [];
|
|
305
|
+
if (curves.length > 0 && (jwk.crv === void 0 || !curves.includes(jwk.crv))) throw new JoseAlgorithmNotAllowedError(`${errorMessage} Algorithm '${keyAlgorithm}' requires a key with crv ${curves.map((crv) => `'${crv}'`).join(" or ")}, but the key has ${jwk.crv ? `crv '${jwk.crv}'` : "no crv"}.`);
|
|
306
|
+
}
|
|
307
|
+
// src/jwa/z-alg.ts
|
|
308
|
+
/**
|
|
309
|
+
* A JWS `alg`. The registry is open and the allowed algorithms are checked at verification, so any
|
|
310
|
+
* value is accepted except `none`, in any casing.
|
|
311
|
+
*
|
|
312
|
+
* @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.1
|
|
313
|
+
* @see https://www.rfc-editor.org/rfc/rfc8725#section-3.2
|
|
314
|
+
*/
|
|
315
|
+
const zJwsAlg = zNonEmptyString.superRefine((alg, ctx) => {
|
|
316
|
+
if (alg.toLowerCase() === "none") addValidationIssue(ctx, {
|
|
317
|
+
code: "invalid_value",
|
|
318
|
+
message: `alg value may not be 'none'`
|
|
319
|
+
});
|
|
320
|
+
});
|
|
321
|
+
/**
|
|
322
|
+
* A JWE `alg` (key management algorithm) value. `none` is not one (RFC 7518 Section 4.1), so it is
|
|
323
|
+
* rejected in any casing, as for a JWS.
|
|
324
|
+
*
|
|
325
|
+
* @see https://www.rfc-editor.org/rfc/rfc7516#section-4.1.1
|
|
326
|
+
*/
|
|
327
|
+
const zJweAlg = zJwsAlg;
|
|
328
|
+
/** A JWE `enc` (content encryption algorithm) value. @see https://www.rfc-editor.org/rfc/rfc7516#section-4.1.2 */
|
|
329
|
+
const zJweEnc = zNonEmptyString;
|
|
330
|
+
// src/jwk/z-x5c.ts
|
|
331
|
+
/** The identifier octet of a DER SEQUENCE, which is what a certificate is encoded as. */
|
|
332
|
+
const DER_SEQUENCE_TAG = 48;
|
|
333
|
+
/**
|
|
334
|
+
* Why `bytes` are not exactly one DER SEQUENCE with a minimal definite length (X.690 section 10.1), or
|
|
335
|
+
* `undefined`. A certificate is far below 2^32 bytes, so a longer length encoding is rejected.
|
|
336
|
+
*/
|
|
337
|
+
function derSequenceIssue(bytes) {
|
|
338
|
+
if (bytes[0] !== DER_SEQUENCE_TAG) return "they do not start with the SEQUENCE tag (0x30)";
|
|
339
|
+
if (bytes.length < 2) return "they end after the tag, without a length";
|
|
340
|
+
let length = bytes[1];
|
|
341
|
+
let contentStart = 2;
|
|
342
|
+
if (length >= 128) {
|
|
343
|
+
const lengthSize = length & 127;
|
|
344
|
+
if (lengthSize === 0) return "the length is indefinite (0x80), which DER does not allow";
|
|
345
|
+
if (lengthSize > 4) return "the length is encoded in more than 4 bytes";
|
|
346
|
+
if (bytes.length < 2 + lengthSize) return "they end inside the length";
|
|
347
|
+
length = 0;
|
|
348
|
+
for (let index = 2; index < 2 + lengthSize; index++) length = length * 256 + bytes[index];
|
|
349
|
+
if (bytes[2] === 0 || length < 128) return "the length is not minimally encoded, as DER requires";
|
|
350
|
+
contentStart = 2 + lengthSize;
|
|
351
|
+
}
|
|
352
|
+
const available = bytes.length - contentStart;
|
|
353
|
+
if (length > available) return `the SEQUENCE is truncated: its length is ${length} byte(s), but only ${available} byte(s) follow`;
|
|
354
|
+
if (length < available) return `${available - length} byte(s) follow the SEQUENCE`;
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* One `x5c` certificate: standard base64 (RFC 4648 section 4, not base64url) of one DER SEQUENCE. The
|
|
358
|
+
* certificate is not parsed: the `VerifyJwsCallback` validates the chain.
|
|
359
|
+
*
|
|
360
|
+
* @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.6
|
|
361
|
+
* @see https://www.rfc-editor.org/rfc/rfc7517#section-4.7
|
|
362
|
+
*/
|
|
363
|
+
const zX5cCertificate = z.base64({ message: "Expected a certificate in standard base64 (RFC 4648 section 4)" }).superRefine((value, ctx) => {
|
|
364
|
+
if (!z.core.regexes.base64.test(value)) return;
|
|
365
|
+
const derIssue = derSequenceIssue(base64.decode(value));
|
|
366
|
+
if (derIssue) addValidationIssue(ctx, {
|
|
367
|
+
code: "invalid_format",
|
|
368
|
+
message: `Expected a DER encoded certificate, but the decoded bytes are not a single DER SEQUENCE: ${derIssue}`,
|
|
369
|
+
context: { format: "der" }
|
|
370
|
+
});
|
|
371
|
+
});
|
|
372
|
+
/**
|
|
373
|
+
* The `x5c` of a JWS header, JWE header or JWK: one or more certificates, the one holding the key first.
|
|
374
|
+
*
|
|
375
|
+
* @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.6
|
|
376
|
+
* @see https://www.rfc-editor.org/rfc/rfc7516#section-4.1.7
|
|
377
|
+
* @see https://www.rfc-editor.org/rfc/rfc7517#section-4.7
|
|
378
|
+
*/
|
|
379
|
+
const zX5c = z.array(zX5cCertificate).min(1, { message: "Expected a certificate chain of at least one certificate" });
|
|
380
|
+
// src/jwk/z-jwk.ts
|
|
381
|
+
/**
|
|
382
|
+
* The JWK members that hold private or symmetric key material. `k` is the whole secret of an `oct` key.
|
|
383
|
+
*
|
|
384
|
+
* @see https://www.rfc-editor.org/rfc/rfc7518#section-6
|
|
385
|
+
*/
|
|
386
|
+
const jwkPrivateMembers = [
|
|
387
|
+
"d",
|
|
388
|
+
"p",
|
|
389
|
+
"q",
|
|
390
|
+
"dp",
|
|
391
|
+
"dq",
|
|
392
|
+
"qi",
|
|
393
|
+
"oth",
|
|
394
|
+
"k"
|
|
395
|
+
];
|
|
396
|
+
/**
|
|
397
|
+
* A JSON Web Key. Only `kty` is required, as in RFC 7517. Loose, so unknown members survive when the
|
|
398
|
+
* JWK is serialized again, e.g. into a `cnf` claim or a `jwk` header.
|
|
399
|
+
*
|
|
400
|
+
* @see https://www.rfc-editor.org/rfc/rfc7517#section-4
|
|
401
|
+
*/
|
|
402
|
+
const zJwk = z.object({
|
|
403
|
+
kty: zNonEmptyString,
|
|
404
|
+
use: zNonEmptyString.optional(),
|
|
405
|
+
key_ops: z.array(zNonEmptyString).optional(),
|
|
406
|
+
alg: zNonEmptyString.optional(),
|
|
407
|
+
kid: zNonEmptyString.optional(),
|
|
408
|
+
x5u: zNonEmptyString.optional(),
|
|
409
|
+
x5c: zX5c.optional(),
|
|
410
|
+
x5t: zNonEmptyString.optional(),
|
|
411
|
+
"x5t#S256": zNonEmptyString.optional(),
|
|
412
|
+
ext: z.boolean().optional(),
|
|
413
|
+
crv: zNonEmptyString.optional(),
|
|
414
|
+
x: zNonEmptyString.optional(),
|
|
415
|
+
y: zNonEmptyString.optional(),
|
|
416
|
+
n: zNonEmptyString.optional(),
|
|
417
|
+
e: zNonEmptyString.optional(),
|
|
418
|
+
d: zNonEmptyString.optional(),
|
|
419
|
+
p: zNonEmptyString.optional(),
|
|
420
|
+
q: zNonEmptyString.optional(),
|
|
421
|
+
dp: zNonEmptyString.optional(),
|
|
422
|
+
dq: zNonEmptyString.optional(),
|
|
423
|
+
qi: zNonEmptyString.optional(),
|
|
424
|
+
oth: z.array(z.object({
|
|
425
|
+
r: zNonEmptyString.optional(),
|
|
426
|
+
d: zNonEmptyString.optional(),
|
|
427
|
+
t: zNonEmptyString.optional()
|
|
428
|
+
}).loose()).optional(),
|
|
429
|
+
k: zNonEmptyString.optional()
|
|
430
|
+
}).loose();
|
|
431
|
+
/**
|
|
432
|
+
* A JWK without private or symmetric key material. Use it for keys from untrusted input, such as a
|
|
433
|
+
* `jwk` header, a `cnf` claim or a fetched JWK Set.
|
|
434
|
+
*/
|
|
435
|
+
const zPublicJwk = zJwk.superRefine((jwk, ctx) => {
|
|
436
|
+
for (const member of jwkPrivateMembers) {
|
|
437
|
+
if (jwk[member] === void 0) continue;
|
|
438
|
+
addValidationIssue(ctx, {
|
|
439
|
+
code: "not_allowed",
|
|
440
|
+
path: [member],
|
|
441
|
+
message: `Expected a public jwk, but the jwk contains the private key member '${member}'`
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
});
|
|
445
|
+
/**
|
|
446
|
+
* A JWK Set.
|
|
447
|
+
*
|
|
448
|
+
* @see https://www.rfc-editor.org/rfc/rfc7517#section-5
|
|
449
|
+
*/
|
|
450
|
+
const zJwkSet = z.object({ keys: z.array(zJwk) }).loose();
|
|
451
|
+
/** A JWK Set whose keys must all be public, see {@link zPublicJwk}. */
|
|
452
|
+
const zPublicJwkSet = z.object({ keys: z.array(zPublicJwk) }).loose();
|
|
453
|
+
// src/utils/z-common.ts
|
|
454
|
+
/**
|
|
455
|
+
* A StringOrURI: a string value that is compared as a case-sensitive string, and that must be a URI
|
|
456
|
+
* whenever it contains a `:`.
|
|
457
|
+
*
|
|
458
|
+
* The URI form is not enforced: OpenID4VP client identifiers such as `x509_san_dns:example.com`
|
|
459
|
+
* are used as `iss` and `aud`, but `_` is not allowed in a URI scheme (RFC 3986 section 3.1).
|
|
460
|
+
*
|
|
461
|
+
* @see https://www.rfc-editor.org/rfc/rfc7519#section-2
|
|
462
|
+
*/
|
|
463
|
+
const zStringOrUri = z.string({ error: `Expected a StringOrURI: a string, which must be a URI when it contains a ':'` });
|
|
464
|
+
/**
|
|
465
|
+
* A compact serialization: `partCount` base64url parts separated by `.`, of which only the ones at
|
|
466
|
+
* `emptyParts` may be empty. Anything else gives an `invalid_format` issue with `format` as context.
|
|
467
|
+
*/
|
|
468
|
+
function zCompactSerialization(format, partCount, emptyParts = []) {
|
|
469
|
+
return z.string().superRefine((value, ctx) => {
|
|
470
|
+
const parts = value.split(".");
|
|
471
|
+
if (!(parts.length === partCount && parts.every((part, index) => (part !== "" || emptyParts.includes(index)) && zBase64Url.safeParse(part).success))) addValidationIssue(ctx, {
|
|
472
|
+
code: "invalid_format",
|
|
473
|
+
message: `Not a valid compact ${format.toUpperCase()}`,
|
|
474
|
+
context: { format }
|
|
475
|
+
});
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
// src/jws/z-jws.ts
|
|
479
|
+
/**
|
|
480
|
+
* The registered JWS header parameters. Loose, so the parameters of a profile survive. Compose on top
|
|
481
|
+
* of it to require the parameters a profile needs:
|
|
482
|
+
*
|
|
483
|
+
* ```ts
|
|
484
|
+
* const zMyHeader = z.object({ ...zJwsProtectedHeader.shape, typ: zTyp('my+jwt') }).loose()
|
|
485
|
+
* ```
|
|
486
|
+
*
|
|
487
|
+
* @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1
|
|
488
|
+
*/
|
|
489
|
+
const zJwsProtectedHeader = z.object({
|
|
490
|
+
alg: zJwsAlg,
|
|
491
|
+
typ: zNonEmptyString.optional(),
|
|
492
|
+
cty: zNonEmptyString.optional(),
|
|
493
|
+
kid: zNonEmptyString.optional(),
|
|
494
|
+
jwk: zPublicJwk.optional(),
|
|
495
|
+
jku: zNonEmptyString.optional(),
|
|
496
|
+
x5c: zX5c.optional(),
|
|
497
|
+
x5u: zNonEmptyString.optional(),
|
|
498
|
+
x5t: zBase64Url.min(1).optional(),
|
|
499
|
+
"x5t#S256": zBase64Url.min(1).optional(),
|
|
500
|
+
/**
|
|
501
|
+
* The header parameters a recipient must understand. Validated further in `assertCriticalHeaderParameters`.
|
|
502
|
+
*
|
|
503
|
+
* @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.11
|
|
504
|
+
*/
|
|
505
|
+
crit: z.array(zNonEmptyString).min(1).optional(),
|
|
506
|
+
/**
|
|
507
|
+
* Whether the payload is base64url encoded. `false` means it is carried and signed as it is.
|
|
508
|
+
*
|
|
509
|
+
* @see https://www.rfc-editor.org/rfc/rfc7797
|
|
510
|
+
*/
|
|
511
|
+
b64: z.boolean().optional(),
|
|
512
|
+
/**
|
|
513
|
+
* The OpenID Federation trust chain that establishes the signer.
|
|
514
|
+
*
|
|
515
|
+
* @see https://openid.net/specs/openid-federation-1_0.html
|
|
516
|
+
*/
|
|
517
|
+
trust_chain: z.tuple([zNonEmptyString], zNonEmptyString).optional()
|
|
518
|
+
}).loose();
|
|
519
|
+
/**
|
|
520
|
+
* A JWS unprotected header. Untyped: it is not covered by the signature, so the library reads nothing
|
|
521
|
+
* from it. A profile that needs a parameter, as JAdES does `etsiU`, validates it itself.
|
|
522
|
+
*
|
|
523
|
+
* @see https://www.rfc-editor.org/rfc/rfc7515#section-7.2
|
|
524
|
+
*/
|
|
525
|
+
const zJwsUnprotectedHeader = z.record(z.string(), z.unknown());
|
|
526
|
+
/**
|
|
527
|
+
* A JWS in compact serialization. An empty payload part is a detached payload. A JWS with an unencoded
|
|
528
|
+
* payload (`b64: false`) does not match, but `parseJws` accepts it.
|
|
529
|
+
*
|
|
530
|
+
* @see https://www.rfc-editor.org/rfc/rfc7515#section-7.1
|
|
531
|
+
*/
|
|
532
|
+
const zCompactJws = zCompactSerialization("jws", 3, [1]);
|
|
533
|
+
/** The signature of a JSON serialized JWS. Never empty: that is an unsecured JWS. */
|
|
534
|
+
const zJwsSignature = zBase64Url.min(1, { message: "Expected a signature, an unsecured JWS is not supported" });
|
|
535
|
+
/**
|
|
536
|
+
* A JWS in flattened JSON serialization.
|
|
537
|
+
*
|
|
538
|
+
* @see https://www.rfc-editor.org/rfc/rfc7515#section-7.2.2
|
|
539
|
+
*/
|
|
540
|
+
const zFlattenedJws = z.object({
|
|
541
|
+
/** Absent for a detached payload. Not `zBase64Url`, as it is unencoded when `b64` is false. */
|
|
542
|
+
payload: z.string().optional(),
|
|
543
|
+
protected: zBase64Url.optional(),
|
|
544
|
+
header: zJwsUnprotectedHeader.optional(),
|
|
545
|
+
signature: zJwsSignature
|
|
546
|
+
}).loose();
|
|
547
|
+
/**
|
|
548
|
+
* A JWS in general JSON serialization.
|
|
549
|
+
*
|
|
550
|
+
* @see https://www.rfc-editor.org/rfc/rfc7515#section-7.2.1
|
|
551
|
+
*/
|
|
552
|
+
const zGeneralJws = z.object({
|
|
553
|
+
payload: z.string().optional(),
|
|
554
|
+
signatures: z.array(z.object({
|
|
555
|
+
protected: zBase64Url.optional(),
|
|
556
|
+
header: zJwsUnprotectedHeader.optional(),
|
|
557
|
+
signature: zJwsSignature
|
|
558
|
+
}).loose()).min(1)
|
|
559
|
+
}).loose();
|
|
560
|
+
// src/jwe/z-jwe.ts
|
|
561
|
+
/**
|
|
562
|
+
* A JWE in compact serialization.
|
|
563
|
+
*
|
|
564
|
+
* The encrypted key part may be empty, as it is for direct key agreement (`ECDH-ES`) and direct
|
|
565
|
+
* encryption (`dir`). The authentication tag may not: RFC 7516 allows an empty one for an algorithm
|
|
566
|
+
* without a tag, but every registered `enc` has one.
|
|
567
|
+
*
|
|
568
|
+
* @see https://www.rfc-editor.org/rfc/rfc7516#section-7.1
|
|
569
|
+
*/
|
|
570
|
+
const zCompactJwe = zCompactSerialization("jwe", 5, [1]);
|
|
571
|
+
/**
|
|
572
|
+
* The header parameters registered for a JWE. The ones a JWE shares with a JWS are validated as in
|
|
573
|
+
* `zJwsProtectedHeader`.
|
|
574
|
+
*
|
|
575
|
+
* @see https://www.rfc-editor.org/rfc/rfc7516#section-4.1
|
|
576
|
+
*/
|
|
577
|
+
const zJweHeader = z.object({
|
|
578
|
+
...zJwsProtectedHeader.omit({
|
|
579
|
+
alg: true,
|
|
580
|
+
b64: true,
|
|
581
|
+
trust_chain: true
|
|
582
|
+
}).shape,
|
|
583
|
+
alg: zJweAlg,
|
|
584
|
+
enc: zJweEnc,
|
|
585
|
+
zip: zNonEmptyString.optional(),
|
|
586
|
+
/** The ephemeral public key of the originator, for the key agreement algorithms. */
|
|
587
|
+
epk: zPublicJwk.optional(),
|
|
588
|
+
/** Agreement PartyUInfo, base64url encoded. */
|
|
589
|
+
apu: zBase64Url.optional(),
|
|
590
|
+
/** Agreement PartyVInfo, base64url encoded. */
|
|
591
|
+
apv: zBase64Url.optional()
|
|
592
|
+
}).loose();
|
|
593
|
+
// src/jwk/thumbprint.ts
|
|
594
|
+
/**
|
|
595
|
+
* The required members of a JWK per key type, in the lexicographic order RFC 7638 requires.
|
|
596
|
+
*
|
|
597
|
+
* @see https://www.rfc-editor.org/rfc/rfc7638#section-3.2
|
|
598
|
+
*/
|
|
599
|
+
const zJwkThumbprintComponents = z.discriminatedUnion("kty", [
|
|
600
|
+
z.object({
|
|
601
|
+
kty: z.literal("EC"),
|
|
602
|
+
crv: zNonEmptyString,
|
|
603
|
+
x: zNonEmptyString,
|
|
604
|
+
y: zNonEmptyString
|
|
605
|
+
}),
|
|
606
|
+
z.object({
|
|
607
|
+
kty: z.literal("OKP"),
|
|
608
|
+
crv: zNonEmptyString,
|
|
609
|
+
x: zNonEmptyString
|
|
610
|
+
}),
|
|
611
|
+
z.object({
|
|
612
|
+
kty: z.literal("RSA"),
|
|
613
|
+
e: zNonEmptyString,
|
|
614
|
+
n: zNonEmptyString
|
|
615
|
+
}),
|
|
616
|
+
z.object({
|
|
617
|
+
kty: z.literal("oct"),
|
|
618
|
+
k: zNonEmptyString
|
|
619
|
+
})
|
|
620
|
+
]).transform((jwk) => {
|
|
621
|
+
if (jwk.kty === "EC") return {
|
|
622
|
+
crv: jwk.crv,
|
|
623
|
+
kty: jwk.kty,
|
|
624
|
+
x: jwk.x,
|
|
625
|
+
y: jwk.y
|
|
626
|
+
};
|
|
627
|
+
if (jwk.kty === "OKP") return {
|
|
628
|
+
crv: jwk.crv,
|
|
629
|
+
kty: jwk.kty,
|
|
630
|
+
x: jwk.x
|
|
631
|
+
};
|
|
632
|
+
if (jwk.kty === "RSA") return {
|
|
633
|
+
e: jwk.e,
|
|
634
|
+
kty: jwk.kty,
|
|
635
|
+
n: jwk.n
|
|
636
|
+
};
|
|
637
|
+
return {
|
|
638
|
+
k: jwk.k,
|
|
639
|
+
kty: jwk.kty
|
|
640
|
+
};
|
|
641
|
+
});
|
|
642
|
+
/**
|
|
643
|
+
* Calculates the JWK thumbprint of a key: the base64url encoded digest over the required members of
|
|
644
|
+
* the key, serialized as JSON with lexicographically ordered member names and no whitespace.
|
|
645
|
+
*
|
|
646
|
+
* @see https://www.rfc-editor.org/rfc/rfc7638
|
|
647
|
+
*/
|
|
648
|
+
async function calculateJwkThumbprint(options) {
|
|
649
|
+
const components = parseWithErrorHandling(zJwkThumbprintComponents, options.jwk, `Unable to calculate the thumbprint of the jwk. Either the 'kty' is not supported, or a member required for the thumbprint is missing`, JoseValidationError);
|
|
650
|
+
return base64url.encode(await options.hashCallback(JSON.stringify(components), options.hashAlgorithm));
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* Calculates the JWK thumbprint URI of a key: `urn:ietf:params:oauth:jwk-thumbprint:<hash>:<thumbprint>`.
|
|
654
|
+
*
|
|
655
|
+
* @see https://www.rfc-editor.org/rfc/rfc9278
|
|
656
|
+
*/
|
|
657
|
+
async function calculateJwkThumbprintUri(options) {
|
|
658
|
+
const thumbprint = await calculateJwkThumbprint(options);
|
|
659
|
+
return `urn:ietf:params:oauth:jwk-thumbprint:${options.hashAlgorithm}:${thumbprint}`;
|
|
660
|
+
}
|
|
661
|
+
// src/jwk/jwks.ts
|
|
662
|
+
/**
|
|
663
|
+
* The JWK when every one of `jwks` is the same, otherwise `undefined`. Two JWKs of one key that differ
|
|
664
|
+
* in e.g. `alg` are ambiguous, as the selected one decides what the key is checked against.
|
|
665
|
+
*/
|
|
666
|
+
const onlyJwk = (jwks) => {
|
|
667
|
+
const [first, ...rest] = jwks;
|
|
668
|
+
return first && rest.every((jwk) => isSameJsonValue(jwk, first)) ? first : void 0;
|
|
669
|
+
};
|
|
670
|
+
/**
|
|
671
|
+
* Selects the key with `kid` from a JWK Set, or the only key for `use` without a `kid`. Keys with
|
|
672
|
+
* another `use` are skipped. More than one candidate, as during a key rotation, throws.
|
|
673
|
+
*
|
|
674
|
+
* @throws JoseSignerError if no key, or more than one, is a candidate.
|
|
675
|
+
*/
|
|
676
|
+
function extractJwkFromJwkSet(options) {
|
|
677
|
+
const jwksForUse = options.jwks.keys.filter(({ use }) => !use || use === options.use);
|
|
678
|
+
if (options.kid) {
|
|
679
|
+
const jwksForKid = jwksForUse.filter(({ kid }) => kid === options.kid);
|
|
680
|
+
if (jwksForKid.length === 0) throw new JoseSignerError(`Unable to extract jwk from jwks for use '${options.use}'. No key with kid '${options.kid}' found.`);
|
|
681
|
+
const jwkForKid = onlyJwk(jwksForKid);
|
|
682
|
+
if (jwkForKid) return jwkForKid;
|
|
683
|
+
throw new JoseSignerError(`Unable to extract jwk from jwks for use '${options.use}'. The jwks contains ${jwksForKid.length} keys with kid '${options.kid}' that differ, and it is ambiguous which one applies.`);
|
|
684
|
+
}
|
|
685
|
+
const jwkForUse = onlyJwk(jwksForUse);
|
|
686
|
+
if (jwkForUse) return jwkForUse;
|
|
687
|
+
throw new JoseSignerError(`Unable to extract jwk from jwks for use '${options.use}'. No kid provided and the jwks contains ${jwksForUse.length} keys for this use.`);
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* Whether `jwk` is one of `jwks`, compared by JWK thumbprint. Keys in the set without a thumbprint,
|
|
691
|
+
* such as an ML-DSA `AKP` key, are skipped.
|
|
692
|
+
*
|
|
693
|
+
* @throws JoseValidationError if the thumbprint of `jwk` itself cannot be computed.
|
|
694
|
+
*/
|
|
695
|
+
async function isJwkInSet({ jwk, jwks, hashCallback }) {
|
|
696
|
+
const thumbprint = await calculateJwkThumbprint({
|
|
697
|
+
jwk,
|
|
698
|
+
hashAlgorithm: "sha-256",
|
|
699
|
+
hashCallback
|
|
700
|
+
});
|
|
701
|
+
for (const jwkFromSet of jwks) {
|
|
702
|
+
if (!zJwkThumbprintComponents.safeParse(jwkFromSet).success) continue;
|
|
703
|
+
if (await calculateJwkThumbprint({
|
|
704
|
+
jwk: jwkFromSet,
|
|
705
|
+
hashAlgorithm: "sha-256",
|
|
706
|
+
hashCallback
|
|
707
|
+
}) === thumbprint) return true;
|
|
708
|
+
}
|
|
709
|
+
return false;
|
|
710
|
+
}
|
|
711
|
+
// src/jws/critical-headers.ts
|
|
712
|
+
/**
|
|
713
|
+
* The header parameters of RFC 7515, RFC 7516 and RFC 7518, which `crit` must not list. `b64` is not
|
|
714
|
+
* one of them: RFC 7797 requires it in `crit`.
|
|
715
|
+
*
|
|
716
|
+
* @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.11
|
|
717
|
+
*/
|
|
718
|
+
const registeredHeaderParameters = /* @__PURE__ */ new Set([
|
|
719
|
+
"alg",
|
|
720
|
+
"jku",
|
|
721
|
+
"jwk",
|
|
722
|
+
"kid",
|
|
723
|
+
"x5u",
|
|
724
|
+
"x5c",
|
|
725
|
+
"x5t",
|
|
726
|
+
"x5t#S256",
|
|
727
|
+
"typ",
|
|
728
|
+
"cty",
|
|
729
|
+
"crit",
|
|
730
|
+
"enc",
|
|
731
|
+
"zip",
|
|
732
|
+
"epk",
|
|
733
|
+
"apu",
|
|
734
|
+
"apv",
|
|
735
|
+
"iv",
|
|
736
|
+
"tag",
|
|
737
|
+
"p2s",
|
|
738
|
+
"p2c"
|
|
739
|
+
]);
|
|
740
|
+
/**
|
|
741
|
+
* Verifies the `crit` header parameter of a JWS.
|
|
742
|
+
*
|
|
743
|
+
* @throws JoseValidationError with an `invalid_crit` or `unsupported_crit` issue for each way `crit`
|
|
744
|
+
* is invalid, or names a parameter that is not understood.
|
|
745
|
+
* @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.11
|
|
746
|
+
*/
|
|
747
|
+
function assertCriticalHeaderParameters({ protectedHeader, unprotectedHeader, understoodCriticalParameters = [] }) {
|
|
748
|
+
const issues = new ValidationIssues();
|
|
749
|
+
if (unprotectedHeader && hasOwn(unprotectedHeader, "crit")) issues.add({
|
|
750
|
+
code: "invalid_crit",
|
|
751
|
+
path: ["crit"],
|
|
752
|
+
message: `The 'crit' header parameter is present in the unprotected header, where it is not integrity protected and therefore not valid`
|
|
753
|
+
});
|
|
754
|
+
const understood = new Set(understoodCriticalParameters);
|
|
755
|
+
protectedHeader.crit?.forEach((name, index) => {
|
|
756
|
+
const path = ["crit", index];
|
|
757
|
+
if (registeredHeaderParameters.has(name)) issues.add({
|
|
758
|
+
code: "invalid_crit",
|
|
759
|
+
path,
|
|
760
|
+
message: `The 'crit' header parameter lists '${name}', which is a registered header parameter and must not be listed`,
|
|
761
|
+
context: { parameter: name }
|
|
762
|
+
});
|
|
763
|
+
else if (!hasOwn(protectedHeader, name) && !(unprotectedHeader && hasOwn(unprotectedHeader, name))) issues.add({
|
|
764
|
+
code: "invalid_crit",
|
|
765
|
+
path,
|
|
766
|
+
message: `The 'crit' header parameter lists '${name}', but the header does not contain that parameter`,
|
|
767
|
+
context: { parameter: name }
|
|
768
|
+
});
|
|
769
|
+
else if (!understood.has(name)) issues.add({
|
|
770
|
+
code: "unsupported_crit",
|
|
771
|
+
path,
|
|
772
|
+
message: name === "b64" ? `The 'crit' header parameter lists 'b64' (RFC 7797), which is only accepted when 'b64' is in 'understoodCriticalParameters'` : `The 'crit' header parameter lists '${name}', which is not understood. A JWS that marks a header parameter as critical can only be accepted when that parameter is processed.`,
|
|
773
|
+
context: {
|
|
774
|
+
parameter: name,
|
|
775
|
+
understood: [...understood]
|
|
776
|
+
}
|
|
777
|
+
});
|
|
778
|
+
});
|
|
779
|
+
if (issues.issues.length) throw new JoseValidationError("Invalid JWS crit header parameter", issues.issues);
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* Whether the payload of a JWS is base64url encoded, per `b64`. RFC 7797 requires `b64` to be listed
|
|
783
|
+
* in `crit`.
|
|
784
|
+
*
|
|
785
|
+
* @throws JoseValidationError with an `invalid_crit` issue if `b64` is used without being marked critical.
|
|
786
|
+
* @see https://www.rfc-editor.org/rfc/rfc7797#section-6
|
|
787
|
+
*/
|
|
788
|
+
function isPayloadBase64UrlEncoded(protectedHeader) {
|
|
789
|
+
const b64 = protectedHeader.b64;
|
|
790
|
+
if (b64 === void 0) return true;
|
|
791
|
+
if (!protectedHeader.crit?.includes("b64")) throw new JoseValidationError("Invalid JWS crit header parameter", [{
|
|
792
|
+
severity: "error",
|
|
793
|
+
code: "invalid_crit",
|
|
794
|
+
path: ["crit"],
|
|
795
|
+
message: `The 'b64' header parameter is used, but is not listed in the 'crit' header parameter, which RFC 7797 requires`
|
|
796
|
+
}]);
|
|
797
|
+
return b64;
|
|
798
|
+
}
|
|
799
|
+
// src/utils/encoding.ts
|
|
800
|
+
/**
|
|
801
|
+
* Decodes a base64url encoded JSON object, such as a JWS protected header.
|
|
802
|
+
*
|
|
803
|
+
* @throws JoseParseError if the input is not valid base64url, not valid UTF-8, not valid JSON, or
|
|
804
|
+
* is a JSON value other than an object.
|
|
805
|
+
*/
|
|
806
|
+
function decodeBase64UrlJsonObject(encoded, name) {
|
|
807
|
+
let decoded;
|
|
808
|
+
try {
|
|
809
|
+
decoded = base64urlDecodeJson(encoded);
|
|
810
|
+
} catch (error) {
|
|
811
|
+
throw new JoseParseError(`Unable to decode the ${name}, it is not valid base64url encoded JSON`, { cause: error });
|
|
812
|
+
}
|
|
813
|
+
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) throw new JoseParseError(`Unable to decode the ${name}, it is not a JSON object`);
|
|
814
|
+
return decoded;
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* Decodes a base64url encoded value into bytes.
|
|
818
|
+
*
|
|
819
|
+
* @throws JoseParseError if the input is not valid base64url.
|
|
820
|
+
*/
|
|
821
|
+
function decodeBase64UrlBytes(encoded, name) {
|
|
822
|
+
try {
|
|
823
|
+
return base64url.decode(encoded);
|
|
824
|
+
} catch (error) {
|
|
825
|
+
throw new JoseParseError(`Unable to decode the ${name}, it is not valid base64url`, { cause: error });
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* The payload of a JWS with `b64` false (RFC 7797), as it appears in the signing input. That is a
|
|
830
|
+
* string, so a payload that is not valid UTF-8 is not supported.
|
|
831
|
+
*
|
|
832
|
+
* @throws JoseNotSupportedError if the payload is not valid UTF-8.
|
|
833
|
+
*/
|
|
834
|
+
function decodeUnencodedPayload(payload) {
|
|
835
|
+
try {
|
|
836
|
+
return bytesToString(payload, { fatal: true });
|
|
837
|
+
} catch (error) {
|
|
838
|
+
throw new JoseNotSupportedError(`An unencoded payload ('b64' is false) that is not valid UTF-8 is not supported.`, { cause: error });
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Why an unencoded payload (`b64` false) cannot be carried in a compact serialization, or `undefined`
|
|
843
|
+
* when it can: only printable ASCII other than '.' (%x20-2D and %x2F-7E) is allowed.
|
|
844
|
+
*
|
|
845
|
+
* @see https://www.rfc-editor.org/rfc/rfc7797#section-5.2
|
|
846
|
+
*/
|
|
847
|
+
function unencodedCompactPayloadIssue(payload) {
|
|
848
|
+
if (payload.includes(".")) return `The payload is unencoded ('b64' is false) and contains a '.', which RFC 7797 section 5.2 does not allow in a compact serialization, where it separates the parts.`;
|
|
849
|
+
if (!/^[\x20-\x7e]*$/.test(payload)) return `The payload is unencoded ('b64' is false) and contains a character outside printable ASCII, which RFC 7797 section 5.2 does not allow in a compact serialization.`;
|
|
850
|
+
}
|
|
851
|
+
/** Encodes a JSON value the way a JOSE part is encoded: compact JSON, base64url, no padding. */
|
|
852
|
+
function encodeBase64UrlJson(value) {
|
|
853
|
+
return base64urlEncode(JSON.stringify(value));
|
|
854
|
+
}
|
|
855
|
+
// src/jws/parse-jws.ts
|
|
856
|
+
/** Whether a compact JWS header sets `b64` to false, as then a '.' in the payload split it into more parts. */
|
|
857
|
+
const isUnencodedPayloadHeader = (encodedProtectedHeader) => {
|
|
858
|
+
try {
|
|
859
|
+
return decodeBase64UrlJsonObject(encodedProtectedHeader, "JWS protected header").b64 === false;
|
|
860
|
+
} catch {
|
|
861
|
+
return false;
|
|
862
|
+
}
|
|
863
|
+
};
|
|
864
|
+
function compactJwsParts(jws) {
|
|
865
|
+
const parts = jws.split(".");
|
|
866
|
+
if (parts.length > 3 && isUnencodedPayloadHeader(parts[0])) throw new JoseParseError(`Unable to parse the JWS. ${unencodedCompactPayloadIssue(parts.slice(1, -1).join("."))}`);
|
|
867
|
+
if (parts.length !== 3) throw new JoseParseError("Unable to parse the JWS, a compact JWS must consist of exactly three parts");
|
|
868
|
+
if (!zBase64Url.safeParse(parts[0]).success) throw new JoseParseError("Unable to parse the JWS, the protected header of a compact JWS must be base64url");
|
|
869
|
+
if (!zBase64Url.safeParse(parts[2]).success) throw new JoseParseError("Unable to parse the JWS, the signature of a compact JWS must be base64url");
|
|
870
|
+
if (parts[2] === "") throw new JoseParseError("Unable to parse the JWS, it does not have a signature. An unsecured JWS is not supported.");
|
|
871
|
+
const isPayloadDetached = parts[1] === "";
|
|
872
|
+
return {
|
|
873
|
+
serialization: "compact",
|
|
874
|
+
encodedProtectedHeader: parts[0],
|
|
875
|
+
unprotectedHeader: void 0,
|
|
876
|
+
serializedPayload: isPayloadDetached ? void 0 : parts[1],
|
|
877
|
+
signature: parts[2],
|
|
878
|
+
compact: isPayloadDetached ? void 0 : jws
|
|
879
|
+
};
|
|
880
|
+
}
|
|
881
|
+
function jsonJwsParts(jws, signatureIndex) {
|
|
882
|
+
if (typeof jws !== "object" || jws === null || Array.isArray(jws)) throw new JoseParseError("Unable to parse the JWS, a JSON serialized JWS must be an object");
|
|
883
|
+
if ("signatures" in jws) {
|
|
884
|
+
const general = parseWithErrorHandling(zGeneralJws, jws, "Unable to parse the general JSON serialized JWS", JoseValidationError);
|
|
885
|
+
const signature = general.signatures[signatureIndex];
|
|
886
|
+
if (!signature) throw new JoseParseError(`Unable to parse the JWS, it does not contain a signature at index ${signatureIndex}. It contains ${general.signatures.length} signature(s).`);
|
|
887
|
+
return {
|
|
888
|
+
serialization: "general",
|
|
889
|
+
encodedProtectedHeader: signature.protected,
|
|
890
|
+
unprotectedHeader: signature.header,
|
|
891
|
+
serializedPayload: general.payload,
|
|
892
|
+
signature: signature.signature
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
const flattened = parseWithErrorHandling(zFlattenedJws, jws, "Unable to parse the flattened JSON serialized JWS", JoseValidationError);
|
|
896
|
+
return {
|
|
897
|
+
serialization: "flattened",
|
|
898
|
+
encodedProtectedHeader: flattened.protected,
|
|
899
|
+
unprotectedHeader: flattened.header,
|
|
900
|
+
serializedPayload: flattened.payload,
|
|
901
|
+
signature: flattened.signature
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
/**
|
|
905
|
+
* Parses and validates a JWS, without verifying the signature. A JWS without a protected header, so
|
|
906
|
+
* without an integrity protected `alg`, is not supported.
|
|
907
|
+
*
|
|
908
|
+
* @throws JoseParseError if the JWS is not well-formed, which includes a compact JWS that carries an
|
|
909
|
+
* unencoded payload (`b64` is false) with a '.' or a character outside printable ASCII.
|
|
910
|
+
* @throws JoseValidationError if a header does not validate against its schema.
|
|
911
|
+
* @throws JoseValidationError with an `invalid_crit` or `unsupported_crit` issue if `crit` is invalid
|
|
912
|
+
* or names a parameter that is not understood.
|
|
913
|
+
* @throws JoseNotSupportedError if the payload is unencoded (`b64` is false) and not valid UTF-8.
|
|
914
|
+
*/
|
|
915
|
+
function parseJws(options) {
|
|
916
|
+
const parts = typeof options.jws === "string" ? compactJwsParts(options.jws) : jsonJwsParts(options.jws, options.signatureIndex ?? 0);
|
|
917
|
+
if (!parts.encodedProtectedHeader) throw new JoseParseError("Unable to parse the JWS, it does not have a protected header. A JWS without a protected header does not integrity protect its own algorithm, and is not supported.");
|
|
918
|
+
const protectedHeaderJson = decodeBase64UrlJsonObject(parts.encodedProtectedHeader, "JWS protected header");
|
|
919
|
+
if (parts.unprotectedHeader) {
|
|
920
|
+
const duplicates = Object.keys(parts.unprotectedHeader).filter((name) => hasOwn(protectedHeaderJson, name));
|
|
921
|
+
if (duplicates.length > 0) throw new JoseParseError(`Unable to parse the JWS, the header parameter(s) ${duplicates.map((name) => `'${name}'`).join(", ")} are present in both the protected and the unprotected header, which must be disjoint`);
|
|
922
|
+
}
|
|
923
|
+
const registeredHeader = parseWithErrorHandling(zJwsProtectedHeader, protectedHeaderJson, "Invalid JWS protected header", JoseValidationError);
|
|
924
|
+
const protectedHeader = parseWithErrorHandling(options.protectedHeaderSchema ?? zJwsProtectedHeader, protectedHeaderJson, "Invalid JWS protected header", JoseValidationError);
|
|
925
|
+
const unprotectedHeader = parts.unprotectedHeader ? parseWithErrorHandling(options.unprotectedHeaderSchema ?? zJwsUnprotectedHeader, parts.unprotectedHeader, "Invalid JWS unprotected header", JoseValidationError) : void 0;
|
|
926
|
+
assertCriticalHeaderParameters({
|
|
927
|
+
protectedHeader: registeredHeader,
|
|
928
|
+
unprotectedHeader: parts.unprotectedHeader,
|
|
929
|
+
understoodCriticalParameters: options.understoodCriticalParameters
|
|
930
|
+
});
|
|
931
|
+
const isBase64UrlEncoded = isPayloadBase64UrlEncoded(registeredHeader);
|
|
932
|
+
const compactPayloadIssue = parts.serialization === "compact" && !isBase64UrlEncoded && parts.serializedPayload !== void 0 ? unencodedCompactPayloadIssue(parts.serializedPayload) : void 0;
|
|
933
|
+
if (compactPayloadIssue) throw new JoseParseError(`Unable to parse the JWS. ${compactPayloadIssue}`);
|
|
934
|
+
const { payload, encodedPayload } = resolvePayload({
|
|
935
|
+
serializedPayload: parts.serializedPayload,
|
|
936
|
+
detachedPayload: options.detachedPayload,
|
|
937
|
+
isBase64UrlEncoded
|
|
938
|
+
});
|
|
939
|
+
return {
|
|
940
|
+
serialization: parts.serialization,
|
|
941
|
+
protectedHeader,
|
|
942
|
+
registeredProtectedHeader: registeredHeader,
|
|
943
|
+
unprotectedHeader,
|
|
944
|
+
encodedProtectedHeader: parts.encodedProtectedHeader,
|
|
945
|
+
payload,
|
|
946
|
+
encodedPayload,
|
|
947
|
+
signature: parts.signature,
|
|
948
|
+
signingInput: `${parts.encodedProtectedHeader}.${encodedPayload}`,
|
|
949
|
+
compact: parts.compact
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
function resolvePayload({ serializedPayload, detachedPayload, isBase64UrlEncoded }) {
|
|
953
|
+
if (serializedPayload !== void 0 && detachedPayload !== void 0) throw new JoseParseError("A detached payload was provided, but the JWS carries a payload. Only one of the two can be the payload that was signed.");
|
|
954
|
+
if (serializedPayload === void 0 && detachedPayload === void 0) throw new JoseParseError("The JWS does not carry a payload and no detached payload was provided, so there is nothing to verify. Pass the payload as `detachedPayload`.");
|
|
955
|
+
if (detachedPayload !== void 0) {
|
|
956
|
+
const payload = typeof detachedPayload === "string" ? stringToBytes(detachedPayload) : detachedPayload;
|
|
957
|
+
return {
|
|
958
|
+
payload,
|
|
959
|
+
encodedPayload: isBase64UrlEncoded ? base64url.encode(payload) : decodeUnencodedPayload(payload)
|
|
960
|
+
};
|
|
961
|
+
}
|
|
962
|
+
const serialized = serializedPayload;
|
|
963
|
+
return {
|
|
964
|
+
payload: isBase64UrlEncoded ? decodeBase64UrlBytes(serialized, "JWS payload") : stringToBytes(serialized),
|
|
965
|
+
encodedPayload: serialized
|
|
966
|
+
};
|
|
967
|
+
}
|
|
968
|
+
// src/jws/sign-jws.ts
|
|
969
|
+
/**
|
|
970
|
+
* Signs a JWS in compact serialization. The callback signs the exact bytes that end up in the token.
|
|
971
|
+
*
|
|
972
|
+
* @throws JoseValidationError if the protected header is not a valid JWS header.
|
|
973
|
+
* @throws JoseValidationError with an `invalid_crit` issue if `crit` is invalid.
|
|
974
|
+
* @throws JoseNotSupportedError if the payload is unencoded (`b64` is false) and not valid UTF-8.
|
|
975
|
+
* @throws JoseInvalidArgumentError if the signer uses another algorithm than the header names, the
|
|
976
|
+
* callback does not return a base64url encoded signature, or the payload is unencoded, not detached,
|
|
977
|
+
* and contains a character RFC 7797 does not allow in a compact serialization: a '.', or anything
|
|
978
|
+
* outside printable ASCII.
|
|
979
|
+
*/
|
|
980
|
+
async function signCompactJws(options) {
|
|
981
|
+
const protectedHeader = parseWithErrorHandling(zJwsProtectedHeader, options.protectedHeader, "Unable to sign the JWS, invalid header", JoseValidationError);
|
|
982
|
+
assertCriticalHeaderParameters({
|
|
983
|
+
protectedHeader,
|
|
984
|
+
understoodCriticalParameters: protectedHeader.crit ?? []
|
|
985
|
+
});
|
|
986
|
+
if (options.signer.alg !== protectedHeader.alg) throw new JoseInvalidArgumentError(`Unable to sign the JWS, the header says alg '${protectedHeader.alg}' but the signer signs with alg '${options.signer.alg}'.`);
|
|
987
|
+
const payload = typeof options.payload === "string" ? stringToBytes(options.payload) : options.payload instanceof Uint8Array ? options.payload : stringToBytes(JSON.stringify(options.payload));
|
|
988
|
+
const isBase64UrlEncoded = isPayloadBase64UrlEncoded(protectedHeader);
|
|
989
|
+
const encodedProtectedHeader = encodeBase64UrlJson(protectedHeader);
|
|
990
|
+
const encodedPayload = isBase64UrlEncoded ? base64url.encode(payload) : decodeUnencodedPayload(payload);
|
|
991
|
+
const signingInput = `${encodedProtectedHeader}.${encodedPayload}`;
|
|
992
|
+
const compactPayloadIssue = !isBase64UrlEncoded && !options.detachPayload ? unencodedCompactPayloadIssue(encodedPayload) : void 0;
|
|
993
|
+
if (compactPayloadIssue) throw new JoseInvalidArgumentError(`Unable to sign the JWS. ${compactPayloadIssue} Detach the payload, or leave out 'b64' so that it is base64url encoded.`);
|
|
994
|
+
const { signature, signerJwk } = await options.signJwsCallback(options.signer, {
|
|
995
|
+
signingInput,
|
|
996
|
+
signingInputBytes: stringToBytes(signingInput),
|
|
997
|
+
protectedHeader,
|
|
998
|
+
payload,
|
|
999
|
+
jwtPayload: typeof options.payload === "object" && !(options.payload instanceof Uint8Array) ? options.payload : void 0
|
|
1000
|
+
});
|
|
1001
|
+
if (!zBase64Url.min(1).safeParse(signature).success) throw new JoseInvalidArgumentError("Unable to sign the JWS, the signature returned by the signing callback is not a non-empty base64url string.");
|
|
1002
|
+
return {
|
|
1003
|
+
compact: `${encodedProtectedHeader}.${options.detachPayload ? "" : encodedPayload}.${signature}`,
|
|
1004
|
+
signature,
|
|
1005
|
+
signingInput,
|
|
1006
|
+
signerJwk
|
|
1007
|
+
};
|
|
1008
|
+
}
|
|
1009
|
+
// src/jws/signer.ts
|
|
1010
|
+
/**
|
|
1011
|
+
* The header parameters that identify the signer, as derived from a {@link JwsSigner}:
|
|
1012
|
+
*
|
|
1013
|
+
* - `did`: the DID URL, as `kid`.
|
|
1014
|
+
* - `federation`: `kid` and `trust_chain`. Without a trust chain that is `kid` alone, from which a
|
|
1015
|
+
* verifier establishes a `custom` signer.
|
|
1016
|
+
* - `jwk`: `jwk`. The `kid` of the signer is not added.
|
|
1017
|
+
* - `x5c`: `x5c`. The `kid` of the signer is not added.
|
|
1018
|
+
* - `custom`: `kid`, when the signer has one.
|
|
1019
|
+
*/
|
|
1020
|
+
function jwsHeaderFromSigner(signer) {
|
|
1021
|
+
if (signer.method === "did") return {
|
|
1022
|
+
alg: signer.alg,
|
|
1023
|
+
kid: signer.didUrl
|
|
1024
|
+
};
|
|
1025
|
+
if (signer.method === "federation") return {
|
|
1026
|
+
alg: signer.alg,
|
|
1027
|
+
kid: signer.kid,
|
|
1028
|
+
trust_chain: signer.trustChain
|
|
1029
|
+
};
|
|
1030
|
+
if (signer.method === "jwk") return {
|
|
1031
|
+
alg: signer.alg,
|
|
1032
|
+
jwk: signer.publicJwk
|
|
1033
|
+
};
|
|
1034
|
+
if (signer.method === "x5c") return {
|
|
1035
|
+
alg: signer.alg,
|
|
1036
|
+
x5c: signer.x5c
|
|
1037
|
+
};
|
|
1038
|
+
return signer.kid !== void 0 ? {
|
|
1039
|
+
alg: signer.alg,
|
|
1040
|
+
kid: signer.kid
|
|
1041
|
+
} : { alg: signer.alg };
|
|
1042
|
+
}
|
|
1043
|
+
/**
|
|
1044
|
+
* The DID a DID URL refers to: everything before its path, query or fragment.
|
|
1045
|
+
*
|
|
1046
|
+
* @see https://www.w3.org/TR/did-core/#did-url-syntax
|
|
1047
|
+
*/
|
|
1048
|
+
const didOfDidUrl = (didUrl) => {
|
|
1049
|
+
const end = didUrl.search(/[/?#]/);
|
|
1050
|
+
return end === -1 ? didUrl : didUrl.slice(0, end);
|
|
1051
|
+
};
|
|
1052
|
+
/**
|
|
1053
|
+
* Establishes the signer of a JWS from its header. Whether the key is trusted is for the verification
|
|
1054
|
+
* callback.
|
|
1055
|
+
*
|
|
1056
|
+
* @throws JoseSignerError if the signer cannot be established, or is identified in more than one way.
|
|
1057
|
+
*/
|
|
1058
|
+
function jwsSignerFromHeader({ header, issuer, allowedSignerMethods, allowMultipleSignerMethods = false, allowDidKidIssuerMismatch = false }) {
|
|
1059
|
+
const found = [];
|
|
1060
|
+
if (header.x5c) found.push({
|
|
1061
|
+
method: "x5c",
|
|
1062
|
+
valid: true,
|
|
1063
|
+
signer: {
|
|
1064
|
+
method: "x5c",
|
|
1065
|
+
alg: header.alg,
|
|
1066
|
+
x5c: header.x5c,
|
|
1067
|
+
kid: header.kid
|
|
1068
|
+
}
|
|
1069
|
+
});
|
|
1070
|
+
if (header.trust_chain) {
|
|
1071
|
+
if (!header.kid) found.push({
|
|
1072
|
+
method: "federation",
|
|
1073
|
+
valid: false,
|
|
1074
|
+
error: `When 'trust_chain' is used in the header, the 'kid' parameter is required.`
|
|
1075
|
+
});
|
|
1076
|
+
else found.push({
|
|
1077
|
+
method: "federation",
|
|
1078
|
+
valid: true,
|
|
1079
|
+
signer: {
|
|
1080
|
+
method: "federation",
|
|
1081
|
+
alg: header.alg,
|
|
1082
|
+
trustChain: header.trust_chain,
|
|
1083
|
+
kid: header.kid
|
|
1084
|
+
}
|
|
1085
|
+
});
|
|
1086
|
+
}
|
|
1087
|
+
if (header.kid?.startsWith("did:") || issuer?.startsWith("did:")) {
|
|
1088
|
+
if (issuer && header.kid?.startsWith("did:") && didOfDidUrl(header.kid) !== issuer && !allowDidKidIssuerMismatch) found.push({
|
|
1089
|
+
method: "did",
|
|
1090
|
+
valid: false,
|
|
1091
|
+
error: `kid in header starts with a did that is different from the did value in 'iss'`
|
|
1092
|
+
});
|
|
1093
|
+
else if (!header.kid?.startsWith("did:") && !header.kid?.startsWith("#")) found.push({
|
|
1094
|
+
method: "did",
|
|
1095
|
+
valid: false,
|
|
1096
|
+
error: `kid in header must start with either 'did:' or '#' when the 'iss' value is a did`
|
|
1097
|
+
});
|
|
1098
|
+
else found.push({
|
|
1099
|
+
method: "did",
|
|
1100
|
+
valid: true,
|
|
1101
|
+
signer: {
|
|
1102
|
+
method: "did",
|
|
1103
|
+
alg: header.alg,
|
|
1104
|
+
didUrl: header.kid.startsWith("did:") ? header.kid : `${issuer}${header.kid}`
|
|
1105
|
+
}
|
|
1106
|
+
});
|
|
1107
|
+
}
|
|
1108
|
+
if (header.jwk) found.push({
|
|
1109
|
+
method: "jwk",
|
|
1110
|
+
valid: true,
|
|
1111
|
+
signer: {
|
|
1112
|
+
method: "jwk",
|
|
1113
|
+
alg: header.alg,
|
|
1114
|
+
publicJwk: header.jwk
|
|
1115
|
+
}
|
|
1116
|
+
});
|
|
1117
|
+
const allowedFound = found.filter((f) => !allowedSignerMethods || allowedSignerMethods.includes(f.method));
|
|
1118
|
+
const allowedValid = allowedFound.filter((f) => f.valid);
|
|
1119
|
+
if (allowedValid.length > 1 && !allowMultipleSignerMethods) throw new JoseSignerError(`Unable to establish the signer of the JWS. The header identifies the signer in ${allowedValid.length} ways (${allowedValid.map((f) => `'${f.method}'`).join(", ")}), and it is ambiguous which one applies. Narrow it down with 'allowedSignerMethods', or set 'allowMultipleSignerMethods'.`);
|
|
1120
|
+
if (allowedValid.length > 0) return allowedValid[0].signer;
|
|
1121
|
+
if (allowedFound.length > 0) throw new JoseSignerError(`Unable to establish the signer of the JWS. Found ${allowedFound.length} allowed signer method(s), but they contained an invalid configuration:\n${allowedFound.map((f) => f.valid ? "" : `FAILED: method ${f.method} - ${f.error}`).join("\n")}`);
|
|
1122
|
+
if (found.length > 0) throw new JoseSignerError(`Unable to establish the signer of the JWS. Found ${found.length} signer method(s) that are not allowed:\n${found.map((f) => f.valid ? `SUCCEEDED: method ${f.method}` : `FAILED: method ${f.method} - ${f.error}`).join("\n")}`);
|
|
1123
|
+
if (!allowedSignerMethods || allowedSignerMethods.includes("custom")) return {
|
|
1124
|
+
method: "custom",
|
|
1125
|
+
alg: header.alg,
|
|
1126
|
+
kid: header.kid
|
|
1127
|
+
};
|
|
1128
|
+
throw new JoseSignerError(`Unable to establish the signer of the JWS. The header identifies no signer method, and the 'custom' signer method is not allowed.`);
|
|
1129
|
+
}
|
|
1130
|
+
// src/jws/verify-jws.ts
|
|
1131
|
+
/**
|
|
1132
|
+
* The algorithm policy of {@link verifyJwsSignature}, for code that verifies a signature without a
|
|
1133
|
+
* {@link VerifyJwsCallback}.
|
|
1134
|
+
*
|
|
1135
|
+
* @throws JoseAlgorithmNotAllowedError if the algorithm is not accepted.
|
|
1136
|
+
*/
|
|
1137
|
+
function assertJwsAlgorithmAllowed({ alg, allowedAlgorithms, allowSymmetricAlgorithms = false, errorMessage = "Error during verification of the JWS." }) {
|
|
1138
|
+
if (!zJwsAlg.safeParse(alg).success) throw new JoseAlgorithmNotAllowedError(`${errorMessage} The JWS uses alg '${alg}', which is not a signature algorithm. An unsecured JWS is never accepted.`);
|
|
1139
|
+
if (isJwaSignatureAlgorithmCaseVariant(alg)) throw new JoseAlgorithmNotAllowedError(`${errorMessage} The JWS uses alg '${alg}', which differs from a registered algorithm only in casing. Algorithm names are case-sensitive.`);
|
|
1140
|
+
if (allowedAlgorithms && !allowedAlgorithms.includes(alg)) throw new JoseAlgorithmNotAllowedError(`${errorMessage} The JWS uses alg '${alg}', but the allowed algorithms are ${allowedAlgorithms.map((allowed) => `'${allowed}'`).join(", ")}.`);
|
|
1141
|
+
if (isSymmetricSignatureAlgorithm(alg) && !allowSymmetricAlgorithms) throw new JoseAlgorithmNotAllowedError(`${errorMessage} The JWS uses the symmetric algorithm '${alg}'. Set 'allowSymmetricAlgorithms' if a MAC is expected here.`);
|
|
1142
|
+
}
|
|
1143
|
+
/**
|
|
1144
|
+
* Verifies the signature over a parsed JWS: the algorithm policy before the callback, and the key the
|
|
1145
|
+
* callback returns against the algorithm after it.
|
|
1146
|
+
*
|
|
1147
|
+
* @throws JoseAlgorithmNotAllowedError if the algorithm is not accepted, or does not match the key or
|
|
1148
|
+
* the `alg` of the given `signer`.
|
|
1149
|
+
* @throws JoseSignatureVerificationError if the signature does not verify.
|
|
1150
|
+
* @throws JoseSignerError if the signer cannot be established from the header.
|
|
1151
|
+
* @throws JoseValidationError if the JWS has no `registeredProtectedHeader`, and its `protectedHeader`
|
|
1152
|
+
* is not a valid JWS protected header.
|
|
1153
|
+
*/
|
|
1154
|
+
async function verifyJwsSignature(options) {
|
|
1155
|
+
const errorMessage = options.errorMessage ?? "Error during verification of the JWS.";
|
|
1156
|
+
const protectedHeader = options.jws.registeredProtectedHeader ?? parseWithErrorHandling(zJwsProtectedHeader, options.jws.protectedHeader, "Invalid JWS protected header", JoseValidationError);
|
|
1157
|
+
const alg = protectedHeader.alg;
|
|
1158
|
+
assertJwsAlgorithmAllowed({
|
|
1159
|
+
alg,
|
|
1160
|
+
allowedAlgorithms: options.allowedAlgorithms,
|
|
1161
|
+
allowSymmetricAlgorithms: options.allowSymmetricAlgorithms,
|
|
1162
|
+
errorMessage
|
|
1163
|
+
});
|
|
1164
|
+
if (options.signer && options.signer.alg !== alg) throw new JoseAlgorithmNotAllowedError(`${errorMessage} The JWS uses alg '${alg}', but the signer to verify against uses alg '${options.signer.alg}'.`);
|
|
1165
|
+
const signer = options.signer ?? jwsSignerFromHeader({
|
|
1166
|
+
header: protectedHeader,
|
|
1167
|
+
issuer: typeof options.jwtPayload?.iss === "string" ? options.jwtPayload.iss : void 0,
|
|
1168
|
+
allowedSignerMethods: options.allowedSignerMethods,
|
|
1169
|
+
allowMultipleSignerMethods: options.allowMultipleSignerMethods,
|
|
1170
|
+
allowDidKidIssuerMismatch: options.allowDidKidIssuerMismatch
|
|
1171
|
+
});
|
|
1172
|
+
let signerJwk;
|
|
1173
|
+
try {
|
|
1174
|
+
const result = await options.verifyJwsCallback(signer, {
|
|
1175
|
+
signingInput: options.jws.signingInput,
|
|
1176
|
+
signingInputBytes: stringToBytes(options.jws.signingInput),
|
|
1177
|
+
protectedHeader,
|
|
1178
|
+
unprotectedHeader: options.jws.unprotectedHeader,
|
|
1179
|
+
payload: options.jws.payload,
|
|
1180
|
+
jwtPayload: options.jwtPayload,
|
|
1181
|
+
signature: options.jws.signature,
|
|
1182
|
+
compact: options.jws.compact
|
|
1183
|
+
});
|
|
1184
|
+
if (!result.verified) throw new JoseSignatureVerificationError(errorMessage);
|
|
1185
|
+
if (!zJwk.safeParse(result.signerJwk).success) throw new JoseSignatureVerificationError(`${errorMessage} The verification callback reported the signature as verified, but did not return the jwk it was verified with.`);
|
|
1186
|
+
signerJwk = result.signerJwk;
|
|
1187
|
+
} catch (error) {
|
|
1188
|
+
if (error instanceof JoseSignatureVerificationError) throw error;
|
|
1189
|
+
throw new JoseSignatureVerificationError(errorMessage, { cause: error });
|
|
1190
|
+
}
|
|
1191
|
+
assertKeyAllowedForSignatureAlgorithm({
|
|
1192
|
+
jwk: signerJwk,
|
|
1193
|
+
alg,
|
|
1194
|
+
errorMessage: `${errorMessage} The key the JWS was verified with cannot be used with its algorithm.`
|
|
1195
|
+
});
|
|
1196
|
+
return { signer: {
|
|
1197
|
+
...signer,
|
|
1198
|
+
publicJwk: signerJwk
|
|
1199
|
+
} };
|
|
1200
|
+
}
|
|
1201
|
+
// src/jwt/z-jwt.ts
|
|
1202
|
+
/**
|
|
1203
|
+
* The header of a JWT, which is a JWS protected header.
|
|
1204
|
+
*
|
|
1205
|
+
* Compose on top of it to require what a token type needs, in particular its `typ`:
|
|
1206
|
+
*
|
|
1207
|
+
* ```ts
|
|
1208
|
+
* const zKbJwtHeader = z.object({ ...zJwtHeader.shape, typ: zTyp('kb+jwt') }).loose()
|
|
1209
|
+
* ```
|
|
1210
|
+
*/
|
|
1211
|
+
const zJwtHeader = zJwsProtectedHeader;
|
|
1212
|
+
/** The `cnf` members that each name the key, of which a `cnf` has at most one. */
|
|
1213
|
+
const confirmationKeyMembers = [
|
|
1214
|
+
"jwk",
|
|
1215
|
+
"jwe",
|
|
1216
|
+
"jku",
|
|
1217
|
+
"jkt"
|
|
1218
|
+
];
|
|
1219
|
+
/**
|
|
1220
|
+
* The `cnf` (confirmation) claim, which names the one key a token is bound to.
|
|
1221
|
+
*
|
|
1222
|
+
* The key is named in one way only, so that every verifier binds the token to the same key:
|
|
1223
|
+
* - at most one of `jwk`, `jwe`, `jku` (RFC 7800 section 3.1) and `jkt` (RFC 9449)
|
|
1224
|
+
* - `kid` on its own, e.g. a DID URL, or with `jku` to select the key from the set (RFC 7800
|
|
1225
|
+
* section 3.5) or with `jkt` that the key it resolves to has to match. Not with `jwk` or `jwe`,
|
|
1226
|
+
* which carry the key itself, and with it its `kid`.
|
|
1227
|
+
*
|
|
1228
|
+
* A token bound to several keys carries the others in claims of its own.
|
|
1229
|
+
*
|
|
1230
|
+
* @see https://www.rfc-editor.org/rfc/rfc7800#section-3.1
|
|
1231
|
+
*/
|
|
1232
|
+
const zJwtConfirmation = z.object({
|
|
1233
|
+
/** The public key the token is bound to. */
|
|
1234
|
+
jwk: zPublicJwk.optional(),
|
|
1235
|
+
/** The JWK thumbprint of the key the token is bound to, e.g. of a DPoP key. */
|
|
1236
|
+
jkt: zBase64Url.min(1).optional(),
|
|
1237
|
+
/** A key id, to be resolved by the recipient. */
|
|
1238
|
+
kid: zNonEmptyString.optional()
|
|
1239
|
+
}).loose().superRefine((cnf, ctx) => {
|
|
1240
|
+
const keyMembers = confirmationKeyMembers.filter((member) => cnf[member] !== void 0);
|
|
1241
|
+
for (const member of keyMembers.slice(1)) addValidationIssue(ctx, {
|
|
1242
|
+
code: "not_allowed",
|
|
1243
|
+
path: [member],
|
|
1244
|
+
message: `The cnf claim names its key with '${keyMembers[0]}', so it may not also have '${member}'`
|
|
1245
|
+
});
|
|
1246
|
+
if (cnf.kid !== void 0 && (cnf.jwk !== void 0 || cnf.jwe !== void 0)) addValidationIssue(ctx, {
|
|
1247
|
+
code: "not_allowed",
|
|
1248
|
+
path: ["kid"],
|
|
1249
|
+
message: `The cnf claim carries its key in '${cnf.jwk !== void 0 ? "jwk" : "jwe"}', so it may not also have a 'kid'`
|
|
1250
|
+
});
|
|
1251
|
+
});
|
|
1252
|
+
/**
|
|
1253
|
+
* The claims registered for a JWT.
|
|
1254
|
+
*
|
|
1255
|
+
* All of them are optional, as RFC 7519 requires none: which claims a token must carry follows from
|
|
1256
|
+
* the token type, and is expressed by composing on this schema and by `requiredClaims` at
|
|
1257
|
+
* verification time.
|
|
1258
|
+
*
|
|
1259
|
+
* The schema is loose, so claims that are not registered are carried through unvalidated.
|
|
1260
|
+
*
|
|
1261
|
+
* @see https://www.rfc-editor.org/rfc/rfc7519#section-4.1
|
|
1262
|
+
*/
|
|
1263
|
+
const zJwtPayload = z.object({
|
|
1264
|
+
iss: zStringOrUri.optional(),
|
|
1265
|
+
sub: zStringOrUri.optional(),
|
|
1266
|
+
aud: z.union([zStringOrUri, z.array(zStringOrUri)]).optional(),
|
|
1267
|
+
exp: zNumericDate.optional(),
|
|
1268
|
+
nbf: zNumericDate.optional(),
|
|
1269
|
+
iat: zNumericDate.optional(),
|
|
1270
|
+
jti: zNonEmptyString.optional(),
|
|
1271
|
+
/** Not registered by RFC 7519, but used the same way across OpenID Connect and OAuth 2.0. */
|
|
1272
|
+
nonce: zNonEmptyString.optional(),
|
|
1273
|
+
cnf: zJwtConfirmation.optional(),
|
|
1274
|
+
/** Reserved for the Token Status List. @see https://datatracker.ietf.org/doc/draft-ietf-oauth-status-list */
|
|
1275
|
+
status: z.record(z.string(), z.unknown()).optional(),
|
|
1276
|
+
/** Reserved for OpenID Federation. */
|
|
1277
|
+
trust_chain: z.tuple([zNonEmptyString], zNonEmptyString).optional()
|
|
1278
|
+
}).loose();
|
|
1279
|
+
/**
|
|
1280
|
+
* A JWT in compact serialization.
|
|
1281
|
+
*
|
|
1282
|
+
* Unlike `zCompactJws` the payload part may not be empty: a JWT carries its claims set, so a
|
|
1283
|
+
* detached payload is not a JWT.
|
|
1284
|
+
*/
|
|
1285
|
+
const zCompactJwt = zCompactSerialization("jwt", 3);
|
|
1286
|
+
// src/jwt/decode-jwt.ts
|
|
1287
|
+
/**
|
|
1288
|
+
* Decodes a JWT and validates its header and payload, without verifying the signature.
|
|
1289
|
+
*
|
|
1290
|
+
* Everything is decoded through `@owf/identity-common`, so a token with an invalid base64url
|
|
1291
|
+
* alphabet, invalid UTF-8 or invalid JSON is rejected rather than being decoded into something that
|
|
1292
|
+
* looks close enough.
|
|
1293
|
+
*
|
|
1294
|
+
* @throws JoseParseError if the JWT is not well-formed.
|
|
1295
|
+
* @throws JoseValidationError if the header or payload does not validate.
|
|
1296
|
+
*/
|
|
1297
|
+
function decodeJwt(options) {
|
|
1298
|
+
const jws = parseJws({
|
|
1299
|
+
jws: options.jwt,
|
|
1300
|
+
protectedHeaderSchema: options.headerSchema,
|
|
1301
|
+
understoodCriticalParameters: options.understoodCriticalParameters
|
|
1302
|
+
});
|
|
1303
|
+
if (jws.registeredProtectedHeader.b64 === false) throw new JoseNotSupportedError(`Unable to decode the JWT, its header sets 'b64' to false. An unencoded payload is not valid for a JWT.`);
|
|
1304
|
+
if (jws.encodedPayload === "") throw new JoseParseError("Unable to decode the JWT, it does not contain a payload");
|
|
1305
|
+
const payloadJson = decodeBase64UrlJsonObject(jws.encodedPayload, "JWT payload");
|
|
1306
|
+
const registeredPayload = parseWithErrorHandling(zJwtPayload, payloadJson, "Invalid JWT payload", JoseValidationError);
|
|
1307
|
+
const payload = parseWithErrorHandling(options.payloadSchema ?? zJwtPayload, payloadJson, "Invalid JWT payload", JoseValidationError);
|
|
1308
|
+
return {
|
|
1309
|
+
header: jws.protectedHeader,
|
|
1310
|
+
payload,
|
|
1311
|
+
registeredHeader: jws.registeredProtectedHeader,
|
|
1312
|
+
registeredPayload,
|
|
1313
|
+
payloadBytes: jws.payload,
|
|
1314
|
+
signature: jws.signature,
|
|
1315
|
+
signingInput: jws.signingInput,
|
|
1316
|
+
compact: options.jwt
|
|
1317
|
+
};
|
|
1318
|
+
}
|
|
1319
|
+
/**
|
|
1320
|
+
* Decodes and validates only the header of a compact JWT or JWE.
|
|
1321
|
+
*
|
|
1322
|
+
* Useful when the header decides what to do next — which key to look up, or how to decrypt — and the
|
|
1323
|
+
* rest of the token cannot be read yet.
|
|
1324
|
+
*
|
|
1325
|
+
* @throws JoseParseError if the token is not well-formed.
|
|
1326
|
+
* @throws JoseValidationError if the header does not validate.
|
|
1327
|
+
*/
|
|
1328
|
+
function decodeJwtHeader(options) {
|
|
1329
|
+
const parts = options.jwt.split(".");
|
|
1330
|
+
if (parts.length !== 3 && parts.length !== 5) throw new JoseParseError("Unable to decode the header, the token is neither a compact JWS (three parts) nor a compact JWE (five parts)");
|
|
1331
|
+
const headerJson = decodeBase64UrlJsonObject(parts[0], "header");
|
|
1332
|
+
const registeredHeader = parseWithErrorHandling(zJwtHeader, headerJson, "Invalid header", JoseValidationError);
|
|
1333
|
+
if (parts.length === 5) parseWithErrorHandling(zJweHeader, headerJson, "Invalid JWE header", JoseValidationError);
|
|
1334
|
+
return { header: options.headerSchema ? parseWithErrorHandling(options.headerSchema, headerJson, "Invalid header", JoseValidationError) : registeredHeader };
|
|
1335
|
+
}
|
|
1336
|
+
// src/jwt/sign-jwt.ts
|
|
1337
|
+
/**
|
|
1338
|
+
* Signs a JWT.
|
|
1339
|
+
*
|
|
1340
|
+
* The header and the claims set are validated before they are signed, so that a token this library
|
|
1341
|
+
* produces is a token it would also accept. Passing the schemas of the token type being produced
|
|
1342
|
+
* extends that to the profile: a key binding JWT missing its `sd_hash` fails here rather than at the
|
|
1343
|
+
* verifier.
|
|
1344
|
+
*
|
|
1345
|
+
* What is signed is the validated value, so a schema that fills in a default or narrows a claim
|
|
1346
|
+
* shapes the token rather than being checked against it and then discarded. That value is validated
|
|
1347
|
+
* against the registered claims as well.
|
|
1348
|
+
*
|
|
1349
|
+
* @throws JoseValidationError if the header or the claims set is not valid.
|
|
1350
|
+
* @throws JoseNotSupportedError if the header sets `b64` to false, which is not valid for a JWT.
|
|
1351
|
+
*/
|
|
1352
|
+
async function signJwt(options) {
|
|
1353
|
+
const headerJson = {
|
|
1354
|
+
...options.header,
|
|
1355
|
+
alg: options.signer.alg
|
|
1356
|
+
};
|
|
1357
|
+
parseWithErrorHandling(zJwtHeader, headerJson, "Unable to sign the JWT, invalid header", JoseValidationError);
|
|
1358
|
+
const header = parseWithErrorHandling(options.headerSchema ?? zJwtHeader, headerJson, "Unable to sign the JWT, invalid header", JoseValidationError);
|
|
1359
|
+
if (header.b64 === false) throw new JoseNotSupportedError(`Unable to sign the JWT, its header sets 'b64' to false. An unencoded payload is not valid for a JWT.`);
|
|
1360
|
+
parseWithErrorHandling(zJwtPayload, options.payload, "Unable to sign the JWT, invalid claims set", JoseValidationError);
|
|
1361
|
+
const payload = parseWithErrorHandling(options.payloadSchema ?? zJwtPayload, options.payload, "Unable to sign the JWT, invalid claims set", JoseValidationError);
|
|
1362
|
+
parseWithErrorHandling(zJwtPayload, payload, "Unable to sign the JWT, invalid claims set", JoseValidationError);
|
|
1363
|
+
const { compact, signerJwk } = await signCompactJws({
|
|
1364
|
+
protectedHeader: header,
|
|
1365
|
+
payload,
|
|
1366
|
+
signer: options.signer,
|
|
1367
|
+
signJwsCallback: options.signJwsCallback
|
|
1368
|
+
});
|
|
1369
|
+
return {
|
|
1370
|
+
jwt: compact,
|
|
1371
|
+
signerJwk,
|
|
1372
|
+
header,
|
|
1373
|
+
payload
|
|
1374
|
+
};
|
|
1375
|
+
}
|
|
1376
|
+
// src/jwt/verify-jwt-claims.ts
|
|
1377
|
+
const asArray = (value) => Array.isArray(value) ? value : [value];
|
|
1378
|
+
const isNonNegativeFiniteNumber = (value) => Number.isFinite(value) && value >= 0;
|
|
1379
|
+
const quoted = (values) => values.map((value) => `'${value}'`).join(", ");
|
|
1380
|
+
/**
|
|
1381
|
+
* Verifies the claims of a JWT: that the claims the caller requires are present, that `iss`, `sub`,
|
|
1382
|
+
* `aud` and `nonce` are the expected ones, and that the token is within its validity window.
|
|
1383
|
+
*
|
|
1384
|
+
* Which claims a JWT must carry, and what they must contain, is decided by the token type rather
|
|
1385
|
+
* than by RFC 7519, so nothing is required unless `requiredClaims` says so.
|
|
1386
|
+
*
|
|
1387
|
+
* This checks the claims only. The signature over them is verified separately — `verifyJwt` does
|
|
1388
|
+
* both, and is what a verifier wants.
|
|
1389
|
+
*
|
|
1390
|
+
* @throws JoseValidationError with an issue for each claim that does not verify: `claim_missing` for a
|
|
1391
|
+
* required claim that is absent, `claim_value_mismatch` for one that is not the expected value,
|
|
1392
|
+
* `expired` or `not_yet_valid` for a token outside its validity window, and `invalid_type` for a
|
|
1393
|
+
* time claim that is not a NumericDate.
|
|
1394
|
+
* @throws JoseInvalidArgumentError if `now` is not a valid date, or `skewSeconds` or `maxAgeSeconds`
|
|
1395
|
+
* is not a finite number of at least 0.
|
|
1396
|
+
*/
|
|
1397
|
+
function verifyJwtClaims(payload, { now = /* @__PURE__ */ new Date(), skewSeconds = 30, requiredClaims, expectedIssuer, expectedSubject, expectedAudience, expectedNonce, checkExpirationTime = true, checkNotBefore = true, checkIssuedAt = true, maxAgeSeconds, errorMessage = "Error during verification of the JWT claims." } = {}) {
|
|
1398
|
+
if (!(now instanceof Date) || Number.isNaN(now.getTime())) throw new JoseInvalidArgumentError(`${errorMessage} The 'now' option must be a valid date.`);
|
|
1399
|
+
if (!isNonNegativeFiniteNumber(skewSeconds)) throw new JoseInvalidArgumentError(`${errorMessage} The 'skewSeconds' option must be a finite number of at least 0, but is '${skewSeconds}'.`);
|
|
1400
|
+
if (maxAgeSeconds !== void 0 && !isNonNegativeFiniteNumber(maxAgeSeconds)) throw new JoseInvalidArgumentError(`${errorMessage} The 'maxAgeSeconds' option must be a finite number of at least 0, but is '${maxAgeSeconds}'.`);
|
|
1401
|
+
const nowSeconds = now.getTime() / 1e3;
|
|
1402
|
+
const issues = new ValidationIssues();
|
|
1403
|
+
for (const claim of requiredClaims ?? []) if (!hasOwn(payload, claim)) addClaimMissing(issues, claim, `The token has no '${claim}' claim, which is required`);
|
|
1404
|
+
verifyClaimMatches(issues, "iss", payload.iss, expectedIssuer);
|
|
1405
|
+
verifyClaimMatches(issues, "sub", payload.sub, expectedSubject);
|
|
1406
|
+
verifyClaimMatches(issues, "nonce", payload.nonce, expectedNonce);
|
|
1407
|
+
verifyAudienceMatches(issues, payload.aud, expectedAudience);
|
|
1408
|
+
const expirationTime = checkExpirationTime ? numericDate(issues, "exp", payload.exp) : void 0;
|
|
1409
|
+
const notBefore = checkNotBefore ? numericDate(issues, "nbf", payload.nbf) : void 0;
|
|
1410
|
+
const issuedAt = checkIssuedAt || maxAgeSeconds !== void 0 ? numericDate(issues, "iat", payload.iat) : void 0;
|
|
1411
|
+
if (expirationTime !== void 0 && expirationTime + skewSeconds <= nowSeconds) issues.add({
|
|
1412
|
+
code: "expired",
|
|
1413
|
+
path: ["exp"],
|
|
1414
|
+
message: `The 'exp' claim '${formatNumericDate(expirationTime)}' is in the past (compared to '${now.toISOString()}')`,
|
|
1415
|
+
context: { expiredAt: secondsToDate(expirationTime) }
|
|
1416
|
+
});
|
|
1417
|
+
if (notBefore !== void 0) verifyClaimNotInFuture(issues, "nbf", notBefore, now, skewSeconds);
|
|
1418
|
+
if (checkIssuedAt && issuedAt !== void 0) verifyClaimNotInFuture(issues, "iat", issuedAt, now, skewSeconds);
|
|
1419
|
+
if (maxAgeSeconds !== void 0) {
|
|
1420
|
+
if (payload.iat === void 0) addClaimMissing(issues, "iat", `The token has no 'iat' claim, which is required to verify that it is at most ${maxAgeSeconds} seconds old`);
|
|
1421
|
+
else if (issuedAt !== void 0 && issuedAt + maxAgeSeconds + skewSeconds < nowSeconds) issues.add({
|
|
1422
|
+
code: "expired",
|
|
1423
|
+
path: ["iat"],
|
|
1424
|
+
message: `The 'iat' claim '${formatNumericDate(issuedAt)}' is more than ${maxAgeSeconds} seconds in the past (compared to '${now.toISOString()}')`,
|
|
1425
|
+
context: { expiredAt: secondsToDate(issuedAt + maxAgeSeconds) }
|
|
1426
|
+
});
|
|
1427
|
+
}
|
|
1428
|
+
if (issues.issues.length) throw new JoseValidationError(errorMessage, issues.issues);
|
|
1429
|
+
}
|
|
1430
|
+
/** A required claim is absent. A claim is reported once, however many checks need it. */
|
|
1431
|
+
function addClaimMissing(issues, claim, message) {
|
|
1432
|
+
if (!issues.issues.some((issue) => issue.code === "claim_missing" && issue.path[0] === claim)) issues.add({
|
|
1433
|
+
code: "claim_missing",
|
|
1434
|
+
path: [claim],
|
|
1435
|
+
message
|
|
1436
|
+
});
|
|
1437
|
+
}
|
|
1438
|
+
/**
|
|
1439
|
+
* The NumericDate a time claim holds, or `undefined` when the token does not carry the claim or it is
|
|
1440
|
+
* not a NumericDate.
|
|
1441
|
+
*
|
|
1442
|
+
* A claim that is present but is not a finite number gives an issue rather than being skipped: it
|
|
1443
|
+
* cannot be compared against `now` (with `NaN` every comparison would be false, which would accept
|
|
1444
|
+
* the token), and skipping it would accept a token whose validity window was never verified. A
|
|
1445
|
+
* payload parsed with `zJwtPayload` cannot get here, but one that reached the caller unvalidated can.
|
|
1446
|
+
*
|
|
1447
|
+
* Any finite number is a NumericDate, including one outside the range a `Date` can hold: it is
|
|
1448
|
+
* compared as a number of seconds.
|
|
1449
|
+
*/
|
|
1450
|
+
function numericDate(issues, claim, value) {
|
|
1451
|
+
if (value === void 0) return void 0;
|
|
1452
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
1453
|
+
issues.add({
|
|
1454
|
+
code: "invalid_type",
|
|
1455
|
+
path: [claim],
|
|
1456
|
+
message: `The '${claim}' claim '${String(value)}' is not a NumericDate`,
|
|
1457
|
+
context: { expected: "number" }
|
|
1458
|
+
});
|
|
1459
|
+
return;
|
|
1460
|
+
}
|
|
1461
|
+
return value;
|
|
1462
|
+
}
|
|
1463
|
+
/**
|
|
1464
|
+
* A NumericDate as it is printed in an issue: as a date where it has one, and as the number it is
|
|
1465
|
+
* where it is outside the range of a `Date`.
|
|
1466
|
+
*/
|
|
1467
|
+
function formatNumericDate(seconds) {
|
|
1468
|
+
const date = secondsToDate(seconds);
|
|
1469
|
+
return Number.isNaN(date.getTime()) ? String(seconds) : date.toISOString();
|
|
1470
|
+
}
|
|
1471
|
+
function verifyClaimMatches(issues, claim, value, expected) {
|
|
1472
|
+
if (expected === void 0) return;
|
|
1473
|
+
const expectedValues = asArray(expected);
|
|
1474
|
+
if (value === void 0) addClaimMissing(issues, claim, `The token has no '${claim}' claim, which is required to match the expected value ${quoted(expectedValues)}`);
|
|
1475
|
+
else if (typeof value !== "string" || !expectedValues.includes(value)) issues.add({
|
|
1476
|
+
code: "claim_value_mismatch",
|
|
1477
|
+
path: [claim],
|
|
1478
|
+
message: `The '${claim}' claim '${String(value)}' does not match the expected value ${quoted(expectedValues)}`,
|
|
1479
|
+
context: {
|
|
1480
|
+
expected: expectedValues,
|
|
1481
|
+
actual: value
|
|
1482
|
+
}
|
|
1483
|
+
});
|
|
1484
|
+
}
|
|
1485
|
+
/** `aud` may hold several audiences, and the token is for us as soon as one of them is expected. */
|
|
1486
|
+
function verifyAudienceMatches(issues, audience, expected) {
|
|
1487
|
+
if (expected === void 0) return;
|
|
1488
|
+
const expectedValues = asArray(expected);
|
|
1489
|
+
if (audience === void 0) {
|
|
1490
|
+
addClaimMissing(issues, "aud", `The token has no 'aud' claim, which is required to match the expected value ${quoted(expectedValues)}`);
|
|
1491
|
+
return;
|
|
1492
|
+
}
|
|
1493
|
+
const audiences = asArray(audience);
|
|
1494
|
+
if (!audiences.some((value) => expectedValues.includes(value))) issues.add({
|
|
1495
|
+
code: "claim_value_mismatch",
|
|
1496
|
+
path: ["aud"],
|
|
1497
|
+
message: `The 'aud' claim ${quoted(audiences)} does not match the expected value ${quoted(expectedValues)}`,
|
|
1498
|
+
context: {
|
|
1499
|
+
expected: expectedValues,
|
|
1500
|
+
actual: audience
|
|
1501
|
+
}
|
|
1502
|
+
});
|
|
1503
|
+
}
|
|
1504
|
+
/**
|
|
1505
|
+
* `nbf` and `iat` are lower bounds on the validity window, so they are shifted back by the skew: a
|
|
1506
|
+
* token whose validity starts within the tolerance is already accepted.
|
|
1507
|
+
*/
|
|
1508
|
+
function verifyClaimNotInFuture(issues, claim, seconds, now, skewSeconds) {
|
|
1509
|
+
if (seconds - skewSeconds > now.getTime() / 1e3) issues.add({
|
|
1510
|
+
code: "not_yet_valid",
|
|
1511
|
+
path: [claim],
|
|
1512
|
+
message: `The '${claim}' claim '${formatNumericDate(seconds)}' is in the future (compared to '${now.toISOString()}')`,
|
|
1513
|
+
context: { validFrom: secondsToDate(seconds) }
|
|
1514
|
+
});
|
|
1515
|
+
}
|
|
1516
|
+
// src/jwt/verify-jwt.ts
|
|
1517
|
+
/**
|
|
1518
|
+
* Verifies a JWT completely: the signature over it, and then the claims in it.
|
|
1519
|
+
*
|
|
1520
|
+
* The signature is verified first, since the claims of a token whose signer has not been established
|
|
1521
|
+
* say nothing about anything.
|
|
1522
|
+
*
|
|
1523
|
+
* @throws JoseParseError or JoseValidationError if the token is not a valid JWT.
|
|
1524
|
+
* @throws JoseAlgorithmNotAllowedError if the algorithm is not accepted, or does not match the key.
|
|
1525
|
+
* @throws JoseSignatureVerificationError if the signature does not verify.
|
|
1526
|
+
* @throws JoseValidationError with an issue for each claim that does not verify, see `verifyJwtClaims`.
|
|
1527
|
+
* @throws JoseInvalidArgumentError if `now`, `skewSeconds` or `maxAgeSeconds` cannot be used to
|
|
1528
|
+
* verify the claims.
|
|
1529
|
+
*/
|
|
1530
|
+
async function verifyJwt(options) {
|
|
1531
|
+
const decoded = typeof options.jwt === "string" ? decodeJwt({
|
|
1532
|
+
jwt: options.jwt,
|
|
1533
|
+
headerSchema: options.headerSchema,
|
|
1534
|
+
payloadSchema: options.payloadSchema,
|
|
1535
|
+
understoodCriticalParameters: options.understoodCriticalParameters
|
|
1536
|
+
}) : options.jwt;
|
|
1537
|
+
const header = decoded.header;
|
|
1538
|
+
const payload = decoded.payload;
|
|
1539
|
+
const registeredPayload = decoded.registeredPayload ?? parseWithErrorHandling(zJwtPayload, decoded.payload, "Invalid JWT payload", JoseValidationError);
|
|
1540
|
+
const { signer } = await verifyJwsSignature({
|
|
1541
|
+
jws: {
|
|
1542
|
+
protectedHeader: header,
|
|
1543
|
+
registeredProtectedHeader: decoded.registeredHeader,
|
|
1544
|
+
signingInput: decoded.signingInput,
|
|
1545
|
+
signature: decoded.signature,
|
|
1546
|
+
payload: decoded.payloadBytes,
|
|
1547
|
+
compact: decoded.compact
|
|
1548
|
+
},
|
|
1549
|
+
jwtPayload: registeredPayload,
|
|
1550
|
+
verifyJwsCallback: options.verifyJwsCallback,
|
|
1551
|
+
signer: options.signer,
|
|
1552
|
+
allowedSignerMethods: options.allowedSignerMethods,
|
|
1553
|
+
allowMultipleSignerMethods: options.allowMultipleSignerMethods,
|
|
1554
|
+
allowDidKidIssuerMismatch: options.allowDidKidIssuerMismatch,
|
|
1555
|
+
allowedAlgorithms: options.allowedAlgorithms,
|
|
1556
|
+
allowSymmetricAlgorithms: options.allowSymmetricAlgorithms,
|
|
1557
|
+
errorMessage: options.errorMessage ?? "Error during verification of the JWT."
|
|
1558
|
+
});
|
|
1559
|
+
verifyJwtClaims(registeredPayload, options);
|
|
1560
|
+
return {
|
|
1561
|
+
header,
|
|
1562
|
+
payload,
|
|
1563
|
+
signer,
|
|
1564
|
+
compact: decoded.compact
|
|
1565
|
+
};
|
|
1566
|
+
}
|
|
1567
|
+
export { JoseAlgorithmNotAllowedError, JoseError, JoseInvalidArgumentError, JoseNotSupportedError, JoseParseError, JoseSignatureVerificationError, JoseSignerError, JoseValidationError, JoseVerificationError, JwaContentEncryptionAlgorithm, JwaKeyManagementAlgorithm, JwaSignatureAlgorithm, assertCriticalHeaderParameters, assertJwsAlgorithmAllowed, assertKeyAllowedForSignatureAlgorithm, calculateJwkThumbprint, calculateJwkThumbprintUri, coseAlgorithmToJwaSignatureAlgorithm, coseAlgorithmsToJwaSignatureAlgorithms, decodeBase64UrlBytes, decodeBase64UrlJsonObject, decodeJwt, decodeJwtHeader, encodeBase64UrlJson, extractJwkFromJwkSet, isJwaSignatureAlgorithm, isJwaSignatureAlgorithmCaseVariant, isJwkInSet, isPayloadBase64UrlEncoded, isSymmetricSignatureAlgorithm, jwaSignatureAlgorithmToCoseAlgorithm, jwaSignatureAlgorithmsToCoseAlgorithms, jwkPrivateMembers, jwsHeaderFromSigner, jwsSignerFromHeader, parseJws, signCompactJws, signJwt, signatureAlgorithmCurves, signatureAlgorithmKeyTypes, symmetricSignatureAlgorithms, verifyJwsSignature, verifyJwt, verifyJwtClaims, zCompactJwe, zCompactJws, zCompactJwt, zFlattenedJws, zGeneralJws, zJweAlg, zJweEnc, zJweHeader, zJwk, zJwkSet, zJwkThumbprintComponents, zJwsAlg, zJwsProtectedHeader, zJwsUnprotectedHeader, zJwtConfirmation, zJwtHeader, zJwtPayload, zPublicJwk, zPublicJwkSet, zStringOrUri, zX5c, zX5cCertificate };
|
|
1568
|
+
|
|
1569
|
+
//# sourceMappingURL=index.mjs.map
|