@owf/jose 0.0.0 → 0.8.0-alpha-20261107111939

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/dist/index.d.mts CHANGED
@@ -1217,6 +1217,8 @@ export interface SignCompactJwsResult {
1217
1217
  * @throws JoseValidationError with an `invalid_crit` issue if `crit` is invalid.
1218
1218
  * @throws JoseNotSupportedError if the payload is unencoded (`b64` is false) and not valid UTF-8.
1219
1219
  * @throws JoseInvalidArgumentError if the signer uses another algorithm than the header names, the
1220
+ * header identifies another signer (a `kid`, `x5c`, `jwk` or `trust_chain` that is not the signer's, or
1221
+ * one of another signer method), the
1220
1222
  * callback does not return a base64url encoded signature, or the payload is unencoded, not detached,
1221
1223
  * and contains a character RFC 7797 does not allow in a compact serialization: a '.', or anything
1222
1224
  * outside printable ASCII.
package/dist/index.mjs CHANGED
@@ -965,47 +965,6 @@ function resolvePayload({ serializedPayload, detachedPayload, isBase64UrlEncoded
965
965
  encodedPayload: serialized
966
966
  };
967
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
968
  // src/jws/signer.ts
1010
969
  /**
1011
970
  * The header parameters that identify the signer, as derived from a {@link JwsSigner}:
@@ -1127,6 +1086,104 @@ function jwsSignerFromHeader({ header, issuer, allowedSignerMethods, allowMultip
1127
1086
  };
1128
1087
  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
1088
  }
1089
+ // src/jws/signer-header.ts
1090
+ const isSameList = (a, b) => a.length === b.length && a.every((value, index) => value === b[index]);
1091
+ /** Same key when the RFC 7638 thumbprint members match, or all members for key types RFC 7638 doesn't cover. */
1092
+ const isSameKey = (a, b) => {
1093
+ const componentsA = zJwkThumbprintComponents.safeParse(a);
1094
+ const componentsB = zJwkThumbprintComponents.safeParse(b);
1095
+ if (componentsA.success && componentsB.success) return JSON.stringify(componentsA.data) === JSON.stringify(componentsB.data);
1096
+ if (componentsA.success || componentsB.success) return false;
1097
+ const membersOf = (jwk) => Object.keys(jwk).filter((member) => jwk[member] !== void 0);
1098
+ const membersA = membersOf(a);
1099
+ return membersA.length === membersOf(b).length && membersA.every((member) => JSON.stringify(a[member]) === JSON.stringify(b[member]));
1100
+ };
1101
+ /**
1102
+ * Rejects a header that contradicts the signer, or that also identifies a signer of another method, as
1103
+ * `jwsSignerFromHeader` would establish another signer from it. The header doesn't have to identify the signer.
1104
+ *
1105
+ * @throws JoseInvalidArgumentError if the header identifies another signer.
1106
+ */
1107
+ function assertHeaderIdentifiesSigner(header, signer, issuer) {
1108
+ const signerHeader = jwsHeaderFromSigner(signer);
1109
+ if (header.kid !== void 0 && signerHeader.kid !== void 0 && header.kid !== signerHeader.kid) throw new JoseInvalidArgumentError(`Unable to sign the JWS, the kid in the header is '${header.kid}', but the signer is identified by kid '${signerHeader.kid}'.`);
1110
+ if (header.x5c !== void 0 && signerHeader.x5c !== void 0 && !isSameList(header.x5c, signerHeader.x5c)) throw new JoseInvalidArgumentError("Unable to sign the JWS, the x5c in the header is not the certificate chain of the signer.");
1111
+ if (header.trust_chain !== void 0 && signerHeader.trust_chain !== void 0 && !isSameList(header.trust_chain, signerHeader.trust_chain)) throw new JoseInvalidArgumentError("Unable to sign the JWS, the trust_chain in the header is not the trust chain of the signer.");
1112
+ if (header.jwk !== void 0 && signerHeader.jwk !== void 0 && !isSameKey(header.jwk, signerHeader.jwk)) throw new JoseInvalidArgumentError("Unable to sign the JWS, the jwk in the header is not the public key of the signer.");
1113
+ if (signer.method === "custom") return;
1114
+ const kidIdentifiesDid = header.kid?.startsWith("did:") === true || header.kid?.startsWith("#") === true && issuer?.startsWith("did:") === true;
1115
+ const otherMethod = [
1116
+ [
1117
+ "x5c",
1118
+ "x5c",
1119
+ header.x5c !== void 0
1120
+ ],
1121
+ [
1122
+ "trust_chain",
1123
+ "federation",
1124
+ header.trust_chain !== void 0
1125
+ ],
1126
+ [
1127
+ "kid",
1128
+ "did",
1129
+ kidIdentifiesDid
1130
+ ],
1131
+ [
1132
+ "jwk",
1133
+ "jwk",
1134
+ header.jwk !== void 0
1135
+ ]
1136
+ ].find(([, method, present]) => present && method !== signer.method);
1137
+ if (otherMethod) {
1138
+ const [parameter, method] = otherMethod;
1139
+ throw new JoseInvalidArgumentError(`Unable to sign the JWS, the '${parameter}' in the header identifies a signer with method '${method}', but the signer has method '${signer.method}'.`);
1140
+ }
1141
+ }
1142
+ // src/jws/sign-jws.ts
1143
+ /**
1144
+ * Signs a JWS in compact serialization. The callback signs the exact bytes that end up in the token.
1145
+ *
1146
+ * @throws JoseValidationError if the protected header is not a valid JWS header.
1147
+ * @throws JoseValidationError with an `invalid_crit` issue if `crit` is invalid.
1148
+ * @throws JoseNotSupportedError if the payload is unencoded (`b64` is false) and not valid UTF-8.
1149
+ * @throws JoseInvalidArgumentError if the signer uses another algorithm than the header names, the
1150
+ * header identifies another signer (a `kid`, `x5c`, `jwk` or `trust_chain` that is not the signer's, or
1151
+ * one of another signer method), the
1152
+ * callback does not return a base64url encoded signature, or the payload is unencoded, not detached,
1153
+ * and contains a character RFC 7797 does not allow in a compact serialization: a '.', or anything
1154
+ * outside printable ASCII.
1155
+ */
1156
+ async function signCompactJws(options) {
1157
+ const protectedHeader = parseWithErrorHandling(zJwsProtectedHeader, options.protectedHeader, "Unable to sign the JWS, invalid header", JoseValidationError);
1158
+ assertCriticalHeaderParameters({
1159
+ protectedHeader,
1160
+ understoodCriticalParameters: protectedHeader.crit ?? []
1161
+ });
1162
+ 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}'.`);
1163
+ const jwtPayload = typeof options.payload === "object" && !(options.payload instanceof Uint8Array) ? options.payload : void 0;
1164
+ assertHeaderIdentifiesSigner(protectedHeader, options.signer, typeof jwtPayload?.iss === "string" ? jwtPayload.iss : void 0);
1165
+ const payload = typeof options.payload === "string" ? stringToBytes(options.payload) : options.payload instanceof Uint8Array ? options.payload : stringToBytes(JSON.stringify(options.payload));
1166
+ const isBase64UrlEncoded = isPayloadBase64UrlEncoded(protectedHeader);
1167
+ const encodedProtectedHeader = encodeBase64UrlJson(protectedHeader);
1168
+ const encodedPayload = isBase64UrlEncoded ? base64url.encode(payload) : decodeUnencodedPayload(payload);
1169
+ const signingInput = `${encodedProtectedHeader}.${encodedPayload}`;
1170
+ const compactPayloadIssue = !isBase64UrlEncoded && !options.detachPayload ? unencodedCompactPayloadIssue(encodedPayload) : void 0;
1171
+ if (compactPayloadIssue) throw new JoseInvalidArgumentError(`Unable to sign the JWS. ${compactPayloadIssue} Detach the payload, or leave out 'b64' so that it is base64url encoded.`);
1172
+ const { signature, signerJwk } = await options.signJwsCallback(options.signer, {
1173
+ signingInput,
1174
+ signingInputBytes: stringToBytes(signingInput),
1175
+ protectedHeader,
1176
+ payload,
1177
+ jwtPayload
1178
+ });
1179
+ 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.");
1180
+ return {
1181
+ compact: `${encodedProtectedHeader}.${options.detachPayload ? "" : encodedPayload}.${signature}`,
1182
+ signature,
1183
+ signingInput,
1184
+ signerJwk
1185
+ };
1186
+ }
1130
1187
  // src/jws/verify-jws.ts
1131
1188
  /**
1132
1189
  * The algorithm policy of {@link verifyJwsSignature}, for code that verifies a signature without a
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/error.ts","../src/jwa/algorithms.ts","../src/utils/object.ts","../src/jwa/cose-algorithm.ts","../src/jwa/key-compatibility.ts","../src/jwa/z-alg.ts","../src/jwk/z-x5c.ts","../src/jwk/z-jwk.ts","../src/utils/z-common.ts","../src/jws/z-jws.ts","../src/jwe/z-jwe.ts","../src/jwk/thumbprint.ts","../src/jwk/jwks.ts","../src/jws/critical-headers.ts","../src/utils/encoding.ts","../src/jws/parse-jws.ts","../src/jws/sign-jws.ts","../src/jws/signer.ts","../src/jws/verify-jws.ts","../src/jwt/z-jwt.ts","../src/jwt/decode-jwt.ts","../src/jwt/sign-jwt.ts","../src/jwt/verify-jwt-claims.ts","../src/jwt/verify-jwt.ts"],"sourcesContent":["import {\n type CommonValidationCode,\n IdentityError,\n type SchemaValidationCode,\n ValidationError,\n type ValidationIssueOf,\n} from '@owf/identity-common'\n\n/**\n * Base error class for `@owf/jose`. `cause` is declared here, as `Error.cause` is ES2022 and the\n * project targets ES2020.\n */\nexport class JoseError extends IdentityError {\n public readonly cause?: unknown\n\n constructor(message: string, options?: { cause?: unknown; details?: unknown }) {\n super(message, options?.details)\n\n this.cause = options?.cause\n }\n}\n\n/**\n * A token is not well-formed: a wrong structure, or a part that is not valid base64url, UTF-8 or\n * JSON. The message never includes the input, so a token is not logged by accident.\n */\nexport class JoseParseError extends JoseError {}\n\n/** An issue of a JOSE structure that does not validate, with a schema or common code */\nexport type JoseValidationIssue = ValidationIssueOf<CommonValidationCode | SchemaValidationCode>\n\n/**\n * A structure is well-formed but does not validate: its schema, `crit` or claims. Like the validation\n * errors of the other packages, it extends `ValidationError`, not {@link JoseError}.\n */\nexport class JoseValidationError extends ValidationError<JoseValidationIssue> {}\n\n/**\n * A token is well-formed but does not verify: its signature, signer or algorithm. The subclasses say\n * which. Claims that do not verify throw a {@link JoseValidationError}.\n */\nexport class JoseVerificationError extends JoseError {}\n\n/** The signature over a JWS does not verify, or the verification callback rejected it. */\nexport class JoseSignatureVerificationError extends JoseVerificationError {}\n\n/** The `alg` of a token is not among the algorithms the caller allows. */\nexport class JoseAlgorithmNotAllowedError extends JoseVerificationError {}\n\n/** The key that identifies the signer cannot be determined from the token, or is ambiguous. */\nexport class JoseSignerError extends JoseVerificationError {}\n\n/** The token uses a feature that this library does not implement. */\nexport class JoseNotSupportedError extends JoseError {}\n\n/**\n * A mistake in the calling code, not in a token: an invalid or contradicting option, or a signing\n * callback result that breaks the contract of the callback.\n */\nexport class JoseInvalidArgumentError extends JoseError {}\n","/**\n * JWA (JSON Web Algorithms) identifiers.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7518\n * @see https://www.iana.org/assignments/jose/jose.xhtml\n */\n\n/**\n * JWS signature and MAC algorithms. `none` is absent: an unsecured JWS is never accepted.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7518#section-3.1\n * @see https://www.rfc-editor.org/rfc/rfc9864 for the fully-specified EdDSA algorithms\n */\nexport enum JwaSignatureAlgorithm {\n // HMAC with SHA-2\n HS256 = 'HS256',\n HS384 = 'HS384',\n HS512 = 'HS512',\n\n // RSASSA-PKCS1-v1_5 with SHA-2\n RS256 = 'RS256',\n RS384 = 'RS384',\n RS512 = 'RS512',\n\n // RSASSA-PSS with SHA-2\n PS256 = 'PS256',\n PS384 = 'PS384',\n PS512 = 'PS512',\n\n // ECDSA\n ES256 = 'ES256',\n ES384 = 'ES384',\n ES512 = 'ES512',\n ES256K = 'ES256K',\n\n // EdDSA. `EdDSA` is polymorphic and deprecated by RFC 9864 in favour of the curve-specific names.\n EdDSA = 'EdDSA',\n Ed25519 = 'Ed25519',\n Ed448 = 'Ed448',\n}\n\n/** The signature algorithms with a symmetric key, with which every verifier can also issue a token. */\nexport const symmetricSignatureAlgorithms = [\n JwaSignatureAlgorithm.HS256,\n JwaSignatureAlgorithm.HS384,\n JwaSignatureAlgorithm.HS512,\n] as const satisfies ReadonlyArray<JwaSignatureAlgorithm>\n\n/**\n * JWE key management algorithms.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7518#section-4.1\n */\nexport enum JwaKeyManagementAlgorithm {\n RSA1_5 = 'RSA1_5',\n RSA_OAEP = 'RSA-OAEP',\n RSA_OAEP_256 = 'RSA-OAEP-256',\n A128KW = 'A128KW',\n A192KW = 'A192KW',\n A256KW = 'A256KW',\n Dir = 'dir',\n ECDH_ES = 'ECDH-ES',\n ECDH_ES_A128KW = 'ECDH-ES+A128KW',\n ECDH_ES_A192KW = 'ECDH-ES+A192KW',\n ECDH_ES_A256KW = 'ECDH-ES+A256KW',\n A128GCMKW = 'A128GCMKW',\n A192GCMKW = 'A192GCMKW',\n A256GCMKW = 'A256GCMKW',\n}\n\n/**\n * JWE content encryption algorithms.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7518#section-5.1\n */\nexport enum JwaContentEncryptionAlgorithm {\n A128CBC_HS256 = 'A128CBC-HS256',\n A192CBC_HS384 = 'A192CBC-HS384',\n A256CBC_HS512 = 'A256CBC-HS512',\n A128GCM = 'A128GCM',\n A192GCM = 'A192GCM',\n A256GCM = 'A256GCM',\n}\n\n/**\n * The key types (`kty`) a signature algorithm can be used with. Checking it prevents key confusion,\n * such as `HS256` with an RSA public key as the MAC secret.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7518#section-3.1\n * @see https://www.rfc-editor.org/rfc/rfc8725#section-3.5\n */\nexport const signatureAlgorithmKeyTypes: Record<JwaSignatureAlgorithm, ReadonlyArray<string>> = {\n [JwaSignatureAlgorithm.HS256]: ['oct'],\n [JwaSignatureAlgorithm.HS384]: ['oct'],\n [JwaSignatureAlgorithm.HS512]: ['oct'],\n\n [JwaSignatureAlgorithm.RS256]: ['RSA'],\n [JwaSignatureAlgorithm.RS384]: ['RSA'],\n [JwaSignatureAlgorithm.RS512]: ['RSA'],\n [JwaSignatureAlgorithm.PS256]: ['RSA'],\n [JwaSignatureAlgorithm.PS384]: ['RSA'],\n [JwaSignatureAlgorithm.PS512]: ['RSA'],\n\n [JwaSignatureAlgorithm.ES256]: ['EC'],\n [JwaSignatureAlgorithm.ES384]: ['EC'],\n [JwaSignatureAlgorithm.ES512]: ['EC'],\n [JwaSignatureAlgorithm.ES256K]: ['EC'],\n\n [JwaSignatureAlgorithm.EdDSA]: ['OKP'],\n [JwaSignatureAlgorithm.Ed25519]: ['OKP'],\n [JwaSignatureAlgorithm.Ed448]: ['OKP'],\n}\n\n/**\n * The curve (`crv`) of the signature algorithms that fully specify one. `EdDSA` is polymorphic.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7518#section-3.4\n * @see https://www.rfc-editor.org/rfc/rfc9864#section-2\n */\nexport const signatureAlgorithmCurves: Partial<Record<JwaSignatureAlgorithm, string>> = {\n [JwaSignatureAlgorithm.ES256]: 'P-256',\n [JwaSignatureAlgorithm.ES384]: 'P-384',\n [JwaSignatureAlgorithm.ES512]: 'P-521',\n [JwaSignatureAlgorithm.ES256K]: 'secp256k1',\n [JwaSignatureAlgorithm.Ed25519]: 'Ed25519',\n [JwaSignatureAlgorithm.Ed448]: 'Ed448',\n}\n\nexport const isJwaSignatureAlgorithm = (alg: string): alg is JwaSignatureAlgorithm =>\n Object.values(JwaSignatureAlgorithm).includes(alg as JwaSignatureAlgorithm)\n\nexport const isSymmetricSignatureAlgorithm = (alg: string): boolean =>\n symmetricSignatureAlgorithms.includes(alg as (typeof symmetricSignatureAlgorithms)[number])\n\n/**\n * Whether `alg` is a registered signature algorithm in a different casing, such as `hs256`. None of\n * the checks here recognize it, but a case-insensitive comparison downstream could verify it as the\n * registered one. Both casings are compared, as they differ outside ASCII: `ſ` upper cases to `S`.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.1\n */\nexport const isJwaSignatureAlgorithmCaseVariant = (alg: string): boolean =>\n typeof alg === 'string' &&\n !isJwaSignatureAlgorithm(alg) &&\n Object.values(JwaSignatureAlgorithm).some(\n (registered) => registered.toLowerCase() === alg.toLowerCase() || registered.toUpperCase() === alg.toUpperCase()\n )\n","/** Whether `key` is an own property of `object`, so `constructor` or `toString` are not found everywhere. */\nexport const hasOwn = (object: object, key: PropertyKey): boolean =>\n // biome-ignore lint/suspicious/noPrototypeBuiltins: `Object.hasOwn` is not in the ES2020 lib this package targets\n Object.prototype.hasOwnProperty.call(object, key)\n\n/**\n * Whether two JSON values are the same value: arrays holding the same values in the same order, and\n * objects with the same members, in whatever order. A member set to `undefined` counts as absent, as\n * it is once serialized.\n */\nexport function isSameJsonValue(a: unknown, b: unknown): boolean {\n if (Array.isArray(a) || Array.isArray(b)) {\n return (\n Array.isArray(a) &&\n Array.isArray(b) &&\n a.length === b.length &&\n a.every((value, index) => isSameJsonValue(value, b[index]))\n )\n }\n\n if (typeof a === 'object' && a !== null && typeof b === 'object' && b !== null) {\n const membersOf = (object: object) =>\n Object.keys(object).filter((member) => (object as Record<string, unknown>)[member] !== undefined)\n const membersOfA = membersOf(a)\n\n return (\n membersOfA.length === membersOf(b).length &&\n membersOfA.every(\n (member) =>\n hasOwn(b, member) &&\n isSameJsonValue((a as Record<string, unknown>)[member], (b as Record<string, unknown>)[member])\n )\n )\n }\n\n return a === b\n}\n","/**\n * Mapping between JWA and COSE algorithm identifiers. COSE identifiers are integers, so no dependency\n * on `@owf/cose` is needed.\n *\n * @see https://www.rfc-editor.org/rfc/rfc9864 Fully-Specified Algorithms for JOSE and COSE\n */\n\nimport { JoseNotSupportedError } from '../error'\nimport { hasOwn } from '../utils/object'\nimport { JwaSignatureAlgorithm } from './algorithms'\n\n/**\n * JWA signature algorithms to fully-specified COSE algorithms. The JOSE `ES256` is fully specified, so\n * it maps to `ESP256` (-9), not to the polymorphic COSE `ES256` (-7).\n */\nconst JWA_SIGNATURE_TO_COSE_ALGORITHM_MAP = {\n // EdDSA - RFC 9864 Section 2.2\n [JwaSignatureAlgorithm.Ed25519]: -19,\n [JwaSignatureAlgorithm.Ed448]: -53,\n\n // Deprecated polymorphic EdDSA - RFC 9864 Section 4.1.2.\n // Mapped to Ed25519 as it is by far the most common use case, as WebAuthn does.\n [JwaSignatureAlgorithm.EdDSA]: -19,\n\n // ECDSA - RFC 9864 Section 2.1\n [JwaSignatureAlgorithm.ES256]: -9, // ESP256\n [JwaSignatureAlgorithm.ES384]: -51, // ESP384\n [JwaSignatureAlgorithm.ES512]: -52, // ESP512\n [JwaSignatureAlgorithm.ES256K]: -47,\n\n // RSA - RFC 8812 and RFC 8230\n [JwaSignatureAlgorithm.RS256]: -257,\n [JwaSignatureAlgorithm.RS384]: -258,\n [JwaSignatureAlgorithm.RS512]: -259,\n [JwaSignatureAlgorithm.PS256]: -37,\n [JwaSignatureAlgorithm.PS384]: -38,\n [JwaSignatureAlgorithm.PS512]: -39,\n\n // HMAC - RFC 9053 Section 3.1\n [JwaSignatureAlgorithm.HS256]: 5,\n [JwaSignatureAlgorithm.HS384]: 6,\n [JwaSignatureAlgorithm.HS512]: 7,\n} as const\n\n/** The inverse of {@link JWA_SIGNATURE_TO_COSE_ALGORITHM_MAP}, plus the deprecated polymorphic COSE algorithms. */\nconst COSE_TO_JWA_SIGNATURE_ALGORITHM_MAP = {\n // EdDSA - RFC 9864 Section 2.2\n [-19]: JwaSignatureAlgorithm.Ed25519,\n [-53]: JwaSignatureAlgorithm.Ed448,\n\n // Deprecated polymorphic EdDSA - RFC 9864 Section 4.1.2 & 4.2.2\n [-8]: JwaSignatureAlgorithm.Ed25519,\n\n // ECDSA, fully specified - RFC 9864 Section 2.1\n [-9]: JwaSignatureAlgorithm.ES256, // ESP256\n [-51]: JwaSignatureAlgorithm.ES384, // ESP384\n [-52]: JwaSignatureAlgorithm.ES512, // ESP512\n [-47]: JwaSignatureAlgorithm.ES256K,\n\n // Deprecated polymorphic COSE ECDSA - RFC 9864 Section 4.2.2\n [-7]: JwaSignatureAlgorithm.ES256,\n [-35]: JwaSignatureAlgorithm.ES384,\n [-36]: JwaSignatureAlgorithm.ES512,\n\n // RSA\n [-257]: JwaSignatureAlgorithm.RS256,\n [-258]: JwaSignatureAlgorithm.RS384,\n [-259]: JwaSignatureAlgorithm.RS512,\n [-37]: JwaSignatureAlgorithm.PS256,\n [-38]: JwaSignatureAlgorithm.PS384,\n [-39]: JwaSignatureAlgorithm.PS512,\n\n // HMAC\n 5: JwaSignatureAlgorithm.HS256,\n 6: JwaSignatureAlgorithm.HS384,\n 7: JwaSignatureAlgorithm.HS512,\n} as const\n\nexport type CoseAlgorithmIdentifier = keyof typeof COSE_TO_JWA_SIGNATURE_ALGORITHM_MAP\nexport type JwaSignatureAlgorithmIdentifier = `${JwaSignatureAlgorithm}`\n\n/**\n * Transforms a JWA signature algorithm identifier into an RFC 9864 fully-specified COSE algorithm\n * identifier, or `undefined` when it has no COSE counterpart.\n *\n * @example\n * ```ts\n * jwaSignatureAlgorithmToCoseAlgorithm('ES256') // -9 (ESP256)\n * ```\n */\nexport function jwaSignatureAlgorithmToCoseAlgorithm(jwaAlg: string): CoseAlgorithmIdentifier | undefined {\n // An own property only, so `constructor` from metadata does not resolve to `Object.prototype`\n return hasOwn(JWA_SIGNATURE_TO_COSE_ALGORITHM_MAP, jwaAlg)\n ? JWA_SIGNATURE_TO_COSE_ALGORITHM_MAP[jwaAlg as JwaSignatureAlgorithm]\n : undefined\n}\n\n/**\n * Transforms a COSE algorithm identifier — fully specified or polymorphic — into a JWA signature\n * algorithm identifier, or `undefined` when it has no JWA counterpart.\n *\n * @example\n * ```ts\n * coseAlgorithmToJwaSignatureAlgorithm(-7) // 'ES256' (from the deprecated polymorphic COSE ES256)\n * ```\n */\nexport function coseAlgorithmToJwaSignatureAlgorithm(coseAlg: number): JwaSignatureAlgorithmIdentifier | undefined {\n return hasOwn(COSE_TO_JWA_SIGNATURE_ALGORITHM_MAP, coseAlg)\n ? COSE_TO_JWA_SIGNATURE_ALGORITHM_MAP[coseAlg as CoseAlgorithmIdentifier]\n : undefined\n}\n\n/**\n * Transforms JWA signature algorithm identifiers into fully-specified COSE algorithm identifiers,\n * dropping the ones that have no COSE counterpart, or throwing when `throwOnUnknownValue` is set.\n */\nexport function jwaSignatureAlgorithmsToCoseAlgorithms(\n jwaAlgs: ReadonlyArray<string>,\n throwOnUnknownValue = false\n): CoseAlgorithmIdentifier[] {\n return jwaAlgs\n .map((jwaAlg) => {\n const coseAlg = jwaSignatureAlgorithmToCoseAlgorithm(jwaAlg)\n if (coseAlg || !throwOnUnknownValue) return coseAlg\n throw new JoseNotSupportedError(`Found unknown JWA signature algorithm '${jwaAlg}'. Unable to map to COSE.`)\n })\n .filter((coseAlg): coseAlg is CoseAlgorithmIdentifier => coseAlg !== undefined)\n}\n\n/**\n * Transforms COSE algorithm identifiers into JWA signature algorithm identifiers, dropping the ones\n * that have no JWA counterpart, or throwing when `throwOnUnknownValue` is set.\n */\nexport function coseAlgorithmsToJwaSignatureAlgorithms(\n coseAlgs: ReadonlyArray<number>,\n throwOnUnknownValue = false\n): JwaSignatureAlgorithmIdentifier[] {\n return coseAlgs\n .map((coseAlg) => {\n const jwaAlg = coseAlgorithmToJwaSignatureAlgorithm(coseAlg)\n if (jwaAlg || !throwOnUnknownValue) return jwaAlg\n throw new JoseNotSupportedError(`Found unknown COSE algorithm identifier '${coseAlg}'. Unable to map to JWA.`)\n })\n .filter((jwaAlg): jwaAlg is JwaSignatureAlgorithmIdentifier => jwaAlg !== undefined)\n}\n","import { JoseAlgorithmNotAllowedError } from '../error'\nimport type { Jwk } from '../jwk/z-jwk'\nimport {\n isJwaSignatureAlgorithm,\n isJwaSignatureAlgorithmCaseVariant,\n JwaSignatureAlgorithm,\n signatureAlgorithmCurves,\n signatureAlgorithmKeyTypes,\n} from './algorithms'\n\n/** `EdDSA` with the curve fixed (RFC 9864 section 2.2). */\nconst fullySpecifiedEdDsaAlgorithms: ReadonlyArray<string> = [\n JwaSignatureAlgorithm.Ed25519,\n JwaSignatureAlgorithm.Ed448,\n]\n\n/** The curves of `EdDSA` (RFC 8037 section 3.1). `X25519` and `X448` are for key agreement. */\nconst edDsaCurves: ReadonlyArray<string> = ['Ed25519', 'Ed448']\n\n/**\n * Checks that a key can be used with a signature algorithm, as the token chooses its `alg` but not the\n * key: the key type (no key confusion), the curve where the algorithm fixes one, and the `alg`, `use`\n * and `key_ops` the key declares. `EdDSA` and `Ed25519`/`Ed448` (RFC 9864) count as the same `alg`.\n * An unregistered algorithm is left to the verification callback, but one that differs from a\n * registered algorithm only in casing is rejected.\n *\n * @throws JoseAlgorithmNotAllowedError when the key cannot be used with the algorithm.\n */\nexport function assertKeyAllowedForSignatureAlgorithm({\n jwk,\n alg,\n errorMessage = 'Unable to use the key with the algorithm of the token.',\n}: {\n jwk: Jwk\n alg: string\n errorMessage?: string\n}): void {\n const isEdDsaEquivalent =\n (jwk.alg === JwaSignatureAlgorithm.EdDSA && fullySpecifiedEdDsaAlgorithms.includes(alg)) ||\n (alg === JwaSignatureAlgorithm.EdDSA && jwk.alg !== undefined && fullySpecifiedEdDsaAlgorithms.includes(jwk.alg))\n\n if (jwk.alg !== undefined && jwk.alg !== alg && !isEdDsaEquivalent) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} The key declares alg '${jwk.alg}', but the token uses alg '${alg}'.`\n )\n }\n\n if (jwk.use !== undefined && jwk.use !== 'sig') {\n throw new JoseAlgorithmNotAllowedError(`${errorMessage} The key declares use '${jwk.use}' instead of 'sig'.`)\n }\n\n if (jwk.key_ops !== undefined && !jwk.key_ops.includes('verify') && !jwk.key_ops.includes('sign')) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} The key declares key_ops ${jwk.key_ops.map((op) => `'${op}'`).join(', ')}, which does not include 'sign' or 'verify'.`\n )\n }\n\n if (isJwaSignatureAlgorithmCaseVariant(alg)) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} The token uses alg '${alg}', which differs from a registered algorithm only in casing.`\n )\n }\n\n if (!isJwaSignatureAlgorithm(alg)) return\n\n // For a token that only says `EdDSA`, the fully specified algorithm the key declares fixes the curve\n const keyAlgorithm =\n isEdDsaEquivalent && alg === JwaSignatureAlgorithm.EdDSA ? (jwk.alg as JwaSignatureAlgorithm) : alg\n\n const keyTypes = signatureAlgorithmKeyTypes[keyAlgorithm]\n if (!keyTypes.includes(jwk.kty)) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} Algorithm '${keyAlgorithm}' requires a key with kty ${keyTypes.map((kty) => `'${kty}'`).join(' or ')}, but the key has kty '${jwk.kty}'.`\n )\n }\n\n const curve = signatureAlgorithmCurves[keyAlgorithm]\n const curves = curve !== undefined ? [curve] : keyAlgorithm === JwaSignatureAlgorithm.EdDSA ? edDsaCurves : []\n if (curves.length > 0 && (jwk.crv === undefined || !curves.includes(jwk.crv))) {\n throw new JoseAlgorithmNotAllowedError(\n `${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'}.`\n )\n }\n}\n","import { addValidationIssue, zNonEmptyString } from '@owf/identity-common'\n\n/**\n * A JWS `alg`. The registry is open and the allowed algorithms are checked at verification, so any\n * value is accepted except `none`, in any casing.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.1\n * @see https://www.rfc-editor.org/rfc/rfc8725#section-3.2\n */\nexport const zJwsAlg = zNonEmptyString.superRefine((alg, ctx) => {\n if (alg.toLowerCase() === 'none') {\n addValidationIssue(ctx, { code: 'invalid_value', message: `alg value may not be 'none'` })\n }\n})\n\n/**\n * A JWE `alg` (key management algorithm) value. `none` is not one (RFC 7518 Section 4.1), so it is\n * rejected in any casing, as for a JWS.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7516#section-4.1.1\n */\nexport const zJweAlg = zJwsAlg\n\n/** A JWE `enc` (content encryption algorithm) value. @see https://www.rfc-editor.org/rfc/rfc7516#section-4.1.2 */\nexport const zJweEnc = zNonEmptyString\n","import { addValidationIssue, base64 } from '@owf/identity-common'\nimport z from 'zod'\n\n/** The identifier octet of a DER SEQUENCE, which is what a certificate is encoded as. */\nconst DER_SEQUENCE_TAG = 0x30\n\n/**\n * Why `bytes` are not exactly one DER SEQUENCE with a minimal definite length (X.690 section 10.1), or\n * `undefined`. A certificate is far below 2^32 bytes, so a longer length encoding is rejected.\n */\nfunction derSequenceIssue(bytes: Uint8Array): string | undefined {\n if (bytes[0] !== DER_SEQUENCE_TAG) return 'they do not start with the SEQUENCE tag (0x30)'\n if (bytes.length < 2) return 'they end after the tag, without a length'\n\n let length = bytes[1]\n let contentStart = 2\n\n // The long form: the low 7 bits say how many bytes the length takes\n if (length >= 0x80) {\n const lengthSize = length & 0x7f\n if (lengthSize === 0) return 'the length is indefinite (0x80), which DER does not allow'\n if (lengthSize > 4) return 'the length is encoded in more than 4 bytes'\n if (bytes.length < 2 + lengthSize) return 'they end inside the length'\n\n length = 0\n for (let index = 2; index < 2 + lengthSize; index++) length = length * 256 + bytes[index]\n\n // DER: no leading zero byte, and the short form below 128\n if (bytes[2] === 0 || length < 0x80) return 'the length is not minimally encoded, as DER requires'\n\n contentStart = 2 + lengthSize\n }\n\n const available = bytes.length - contentStart\n if (length > available) {\n return `the SEQUENCE is truncated: its length is ${length} byte(s), but only ${available} byte(s) follow`\n }\n if (length < available) return `${available - length} byte(s) follow the SEQUENCE`\n\n return undefined\n}\n\n/**\n * One `x5c` certificate: standard base64 (RFC 4648 section 4, not base64url) of one DER SEQUENCE. The\n * certificate is not parsed: the `VerifyJwsCallback` validates the chain.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.6\n * @see https://www.rfc-editor.org/rfc/rfc7517#section-4.7\n */\nexport const zX5cCertificate = z\n .base64({ message: 'Expected a certificate in standard base64 (RFC 4648 section 4)' })\n .superRefine((value, ctx) => {\n // zod runs the refinement also when the value is not base64\n if (!z.core.regexes.base64.test(value)) return\n\n const derIssue = derSequenceIssue(base64.decode(value))\n if (derIssue) {\n addValidationIssue(ctx, {\n code: 'invalid_format',\n message: `Expected a DER encoded certificate, but the decoded bytes are not a single DER SEQUENCE: ${derIssue}`,\n context: { format: 'der' },\n })\n }\n })\n\n/**\n * The `x5c` of a JWS header, JWE header or JWK: one or more certificates, the one holding the key first.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.6\n * @see https://www.rfc-editor.org/rfc/rfc7516#section-4.1.7\n * @see https://www.rfc-editor.org/rfc/rfc7517#section-4.7\n */\nexport const zX5c = z\n .array(zX5cCertificate)\n .min(1, { message: 'Expected a certificate chain of at least one certificate' })\n","import { addValidationIssue, zNonEmptyString } from '@owf/identity-common'\nimport z from 'zod'\nimport { zX5c } from './z-x5c'\n\n/**\n * The JWK members that hold private or symmetric key material. `k` is the whole secret of an `oct` key.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7518#section-6\n */\nexport const jwkPrivateMembers = ['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'k'] as const\n\n/**\n * A JSON Web Key. Only `kty` is required, as in RFC 7517. Loose, so unknown members survive when the\n * JWK is serialized again, e.g. into a `cnf` claim or a `jwk` header.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7517#section-4\n */\nexport const zJwk = z\n .object({\n kty: zNonEmptyString,\n\n // Common parameters\n use: zNonEmptyString.optional(),\n key_ops: z.array(zNonEmptyString).optional(),\n alg: zNonEmptyString.optional(),\n kid: zNonEmptyString.optional(),\n x5u: zNonEmptyString.optional(),\n x5c: zX5c.optional(),\n x5t: zNonEmptyString.optional(),\n 'x5t#S256': zNonEmptyString.optional(),\n ext: z.boolean().optional(),\n\n // EC and OKP\n crv: zNonEmptyString.optional(),\n x: zNonEmptyString.optional(),\n y: zNonEmptyString.optional(),\n\n // RSA\n n: zNonEmptyString.optional(),\n e: zNonEmptyString.optional(),\n\n // Private and symmetric key material\n d: zNonEmptyString.optional(),\n p: zNonEmptyString.optional(),\n q: zNonEmptyString.optional(),\n dp: zNonEmptyString.optional(),\n dq: zNonEmptyString.optional(),\n qi: zNonEmptyString.optional(),\n oth: z\n .array(\n z\n .object({\n r: zNonEmptyString.optional(),\n d: zNonEmptyString.optional(),\n t: zNonEmptyString.optional(),\n })\n .loose()\n )\n .optional(),\n k: zNonEmptyString.optional(),\n })\n .loose()\n\nexport type Jwk = z.infer<typeof zJwk>\n\n/**\n * A JWK without private or symmetric key material. Use it for keys from untrusted input, such as a\n * `jwk` header, a `cnf` claim or a fetched JWK Set.\n */\nexport const zPublicJwk = zJwk.superRefine((jwk, ctx) => {\n for (const member of jwkPrivateMembers) {\n if (jwk[member] === undefined) continue\n addValidationIssue(ctx, {\n code: 'not_allowed',\n path: [member],\n message: `Expected a public jwk, but the jwk contains the private key member '${member}'`,\n })\n }\n})\n\nexport type PublicJwk = z.infer<typeof zPublicJwk>\n\n/**\n * A JWK Set.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7517#section-5\n */\nexport const zJwkSet = z.object({ keys: z.array(zJwk) }).loose()\n\nexport type JwkSet = z.infer<typeof zJwkSet>\n\n/** A JWK Set whose keys must all be public, see {@link zPublicJwk}. */\nexport const zPublicJwkSet = z.object({ keys: z.array(zPublicJwk) }).loose()\n","import { addValidationIssue, zBase64Url } from '@owf/identity-common'\nimport z from 'zod'\n\n/**\n * A StringOrURI: a string value that is compared as a case-sensitive string, and that must be a URI\n * whenever it contains a `:`.\n *\n * The URI form is not enforced: OpenID4VP client identifiers such as `x509_san_dns:example.com`\n * are used as `iss` and `aud`, but `_` is not allowed in a URI scheme (RFC 3986 section 3.1).\n *\n * @see https://www.rfc-editor.org/rfc/rfc7519#section-2\n */\nexport const zStringOrUri = z.string({\n error: `Expected a StringOrURI: a string, which must be a URI when it contains a ':'`,\n})\n\n/**\n * A compact serialization: `partCount` base64url parts separated by `.`, of which only the ones at\n * `emptyParts` may be empty. Anything else gives an `invalid_format` issue with `format` as context.\n */\nexport function zCompactSerialization(format: string, partCount: number, emptyParts: ReadonlyArray<number> = []) {\n return z.string().superRefine((value, ctx) => {\n const parts = value.split('.')\n const isCompact =\n parts.length === partCount &&\n parts.every((part, index) => (part !== '' || emptyParts.includes(index)) && zBase64Url.safeParse(part).success)\n\n if (!isCompact) {\n addValidationIssue(ctx, {\n code: 'invalid_format',\n message: `Not a valid compact ${format.toUpperCase()}`,\n context: { format },\n })\n }\n })\n}\n","import { zBase64Url, zNonEmptyString } from '@owf/identity-common'\nimport z from 'zod'\nimport { zJwsAlg } from '../jwa/z-alg'\nimport { zPublicJwk } from '../jwk/z-jwk'\nimport { zX5c } from '../jwk/z-x5c'\nimport { zCompactSerialization } from '../utils/z-common'\n\n/**\n * The registered JWS header parameters. Loose, so the parameters of a profile survive. Compose on top\n * of it to require the parameters a profile needs:\n *\n * ```ts\n * const zMyHeader = z.object({ ...zJwsProtectedHeader.shape, typ: zTyp('my+jwt') }).loose()\n * ```\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1\n */\nexport const zJwsProtectedHeader = z\n .object({\n alg: zJwsAlg,\n\n typ: zNonEmptyString.optional(),\n cty: zNonEmptyString.optional(),\n\n kid: zNonEmptyString.optional(),\n jwk: zPublicJwk.optional(),\n jku: zNonEmptyString.optional(),\n\n x5c: zX5c.optional(),\n x5u: zNonEmptyString.optional(),\n x5t: zBase64Url.min(1).optional(),\n 'x5t#S256': zBase64Url.min(1).optional(),\n\n /**\n * The header parameters a recipient must understand. Validated further in `assertCriticalHeaderParameters`.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.11\n */\n crit: z.array(zNonEmptyString).min(1).optional(),\n\n /**\n * Whether the payload is base64url encoded. `false` means it is carried and signed as it is.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7797\n */\n b64: z.boolean().optional(),\n\n /**\n * The OpenID Federation trust chain that establishes the signer.\n *\n * @see https://openid.net/specs/openid-federation-1_0.html\n */\n trust_chain: z.tuple([zNonEmptyString], zNonEmptyString).optional(),\n })\n .loose()\n\nexport type JwsProtectedHeader = z.infer<typeof zJwsProtectedHeader>\n\n/**\n * A JWS unprotected header. Untyped: it is not covered by the signature, so the library reads nothing\n * from it. A profile that needs a parameter, as JAdES does `etsiU`, validates it itself.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-7.2\n */\nexport const zJwsUnprotectedHeader = z.record(z.string(), z.unknown())\n\nexport type JwsUnprotectedHeader = z.infer<typeof zJwsUnprotectedHeader>\n\n/**\n * A JWS in compact serialization. An empty payload part is a detached payload. A JWS with an unencoded\n * payload (`b64: false`) does not match, but `parseJws` accepts it.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-7.1\n */\nexport const zCompactJws = zCompactSerialization('jws', 3, [1])\n\n/** The signature of a JSON serialized JWS. Never empty: that is an unsecured JWS. */\nconst zJwsSignature = zBase64Url.min(1, { message: 'Expected a signature, an unsecured JWS is not supported' })\n\n/**\n * A JWS in flattened JSON serialization.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-7.2.2\n */\nexport const zFlattenedJws = z\n .object({\n /** Absent for a detached payload. Not `zBase64Url`, as it is unencoded when `b64` is false. */\n payload: z.string().optional(),\n protected: zBase64Url.optional(),\n header: zJwsUnprotectedHeader.optional(),\n signature: zJwsSignature,\n })\n .loose()\n\nexport type FlattenedJws = z.infer<typeof zFlattenedJws>\n\n/**\n * A JWS in general JSON serialization.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-7.2.1\n */\nexport const zGeneralJws = z\n .object({\n payload: z.string().optional(),\n signatures: z\n .array(\n z\n .object({\n protected: zBase64Url.optional(),\n header: zJwsUnprotectedHeader.optional(),\n signature: zJwsSignature,\n })\n .loose()\n )\n .min(1),\n })\n .loose()\n\nexport type GeneralJws = z.infer<typeof zGeneralJws>\n","import { type OrPromise, zBase64Url, zNonEmptyString } from '@owf/identity-common'\nimport z from 'zod'\nimport { zJweAlg, zJweEnc } from '../jwa/z-alg'\nimport type { Jwk } from '../jwk/z-jwk'\nimport { zPublicJwk } from '../jwk/z-jwk'\nimport type { JwsSignerJwk } from '../jws/signer'\nimport { zJwsProtectedHeader } from '../jws/z-jws'\nimport { zCompactSerialization } from '../utils/z-common'\n\n/**\n * A JWE in compact serialization.\n *\n * The encrypted key part may be empty, as it is for direct key agreement (`ECDH-ES`) and direct\n * encryption (`dir`). The authentication tag may not: RFC 7516 allows an empty one for an algorithm\n * without a tag, but every registered `enc` has one.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7516#section-7.1\n */\nexport const zCompactJwe = zCompactSerialization('jwe', 5, [1])\n\n/**\n * The header parameters registered for a JWE. The ones a JWE shares with a JWS are validated as in\n * `zJwsProtectedHeader`.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7516#section-4.1\n */\nexport const zJweHeader = z\n .object({\n ...zJwsProtectedHeader.omit({ alg: true, b64: true, trust_chain: true }).shape,\n\n alg: zJweAlg,\n enc: zJweEnc,\n zip: zNonEmptyString.optional(),\n\n /** The ephemeral public key of the originator, for the key agreement algorithms. */\n epk: zPublicJwk.optional(),\n\n /** Agreement PartyUInfo, base64url encoded. */\n apu: zBase64Url.optional(),\n\n /** Agreement PartyVInfo, base64url encoded. */\n apv: zBase64Url.optional(),\n })\n .loose()\n\nexport type JweHeader = z.infer<typeof zJweHeader>\n\n/**\n * The recipient a JWE is encrypted for, and how.\n *\n * Encryption and decryption themselves are performed by callbacks: this package models the\n * structures and leaves the cryptography to the caller.\n */\nexport type JweEncryptor = JwsSignerJwk & {\n /** The content encryption algorithm. */\n enc: string\n\n /** Agreement PartyUInfo, base64url encoded. */\n apu?: string\n\n /** Agreement PartyVInfo, base64url encoded. */\n apv?: string\n}\n\n/** Encrypts `data` for `encryptor`, returning the JWE in compact serialization. */\nexport type EncryptJweCallback = (\n encryptor: JweEncryptor,\n data: string\n) => OrPromise<{\n encryptionJwk: Jwk\n jwe: string\n}>\n\nexport interface DecryptJweCallbackOptions {\n /** The key to decrypt with, when the caller knows which one applies. */\n jwk?: Jwk\n}\n\n/**\n * Decrypts a compact JWE, returning the plaintext and the JWK of the key it was decrypted with.\n *\n * Return `{ decrypted: false }` for expected failures, such as an invalid ciphertext or\n * authentication tag or a key mismatch. Throw only for unexpected failures, such as an unavailable\n * key store.\n */\nexport type DecryptJweCallback = (\n jwe: string,\n options?: DecryptJweCallbackOptions\n) => OrPromise<\n | {\n decrypted: true\n decryptionJwk: Jwk\n payload: string\n }\n | {\n decrypted: false\n decryptionJwk?: Jwk\n payload?: string\n }\n>\n","import {\n base64url,\n type HashAlgorithm,\n type Hasher,\n parseWithErrorHandling,\n zNonEmptyString,\n} from '@owf/identity-common'\nimport z from 'zod'\nimport { JoseValidationError } from '../error'\nimport type { Jwk } from './z-jwk'\n\n/**\n * The required members of a JWK per key type, in the lexicographic order RFC 7638 requires.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7638#section-3.2\n */\nexport const zJwkThumbprintComponents = z\n .discriminatedUnion('kty', [\n z.object({\n kty: z.literal('EC'),\n crv: zNonEmptyString,\n x: zNonEmptyString,\n y: zNonEmptyString,\n }),\n z.object({\n kty: z.literal('OKP'),\n crv: zNonEmptyString,\n x: zNonEmptyString,\n }),\n z.object({\n kty: z.literal('RSA'),\n e: zNonEmptyString,\n n: zNonEmptyString,\n }),\n z.object({\n kty: z.literal('oct'),\n k: zNonEmptyString,\n }),\n ])\n .transform((jwk) => {\n if (jwk.kty === 'EC') return { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }\n if (jwk.kty === 'OKP') return { crv: jwk.crv, kty: jwk.kty, x: jwk.x }\n if (jwk.kty === 'RSA') return { e: jwk.e, kty: jwk.kty, n: jwk.n }\n return { k: jwk.k, kty: jwk.kty }\n })\n\nexport interface CalculateJwkThumbprintOptions {\n /** The jwk to calculate the thumbprint for. */\n jwk: Jwk\n\n /** The hashing algorithm to use. RFC 7638 registers SHA-256 as the default. */\n hashAlgorithm: HashAlgorithm\n\n /** The hash callback used to compute the digest, e.g. `hasher` of `@owf/crypto`. */\n hashCallback: Hasher\n}\n\n/**\n * Calculates the JWK thumbprint of a key: the base64url encoded digest over the required members of\n * the key, serialized as JSON with lexicographically ordered member names and no whitespace.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7638\n */\nexport async function calculateJwkThumbprint(options: CalculateJwkThumbprintOptions): Promise<string> {\n const components = parseWithErrorHandling(\n zJwkThumbprintComponents,\n options.jwk,\n `Unable to calculate the thumbprint of the jwk. Either the 'kty' is not supported, or a member required for the thumbprint is missing`,\n JoseValidationError\n )\n\n return base64url.encode(await options.hashCallback(JSON.stringify(components), options.hashAlgorithm))\n}\n\n/**\n * Calculates the JWK thumbprint URI of a key: `urn:ietf:params:oauth:jwk-thumbprint:<hash>:<thumbprint>`.\n *\n * @see https://www.rfc-editor.org/rfc/rfc9278\n */\nexport async function calculateJwkThumbprintUri(options: CalculateJwkThumbprintOptions): Promise<string> {\n const thumbprint = await calculateJwkThumbprint(options)\n return `urn:ietf:params:oauth:jwk-thumbprint:${options.hashAlgorithm}:${thumbprint}`\n}\n","import type { Hasher } from '@owf/identity-common'\nimport { JoseSignerError } from '../error'\nimport { isSameJsonValue } from '../utils/object'\nimport { calculateJwkThumbprint, zJwkThumbprintComponents } from './thumbprint'\nimport type { Jwk, JwkSet } from './z-jwk'\n\nexport interface ExtractJwkFromJwkSetOptions {\n /** The JWK Set to select a key from. */\n jwks: JwkSet\n\n /** The `kid` of the key to select, typically taken from the header of the token to verify. */\n kid?: string\n\n /** Whether the key is used for signature verification or for encryption. */\n use: 'enc' | 'sig'\n}\n\n/**\n * The JWK when every one of `jwks` is the same, otherwise `undefined`. Two JWKs of one key that differ\n * in e.g. `alg` are ambiguous, as the selected one decides what the key is checked against.\n */\nconst onlyJwk = (jwks: ReadonlyArray<Jwk>): Jwk | undefined => {\n const [first, ...rest] = jwks\n return first && rest.every((jwk) => isSameJsonValue(jwk, first)) ? first : undefined\n}\n\n/**\n * Selects the key with `kid` from a JWK Set, or the only key for `use` without a `kid`. Keys with\n * another `use` are skipped. More than one candidate, as during a key rotation, throws.\n *\n * @throws JoseSignerError if no key, or more than one, is a candidate.\n */\nexport function extractJwkFromJwkSet(options: ExtractJwkFromJwkSetOptions): Jwk {\n const jwksForUse = options.jwks.keys.filter(({ use }) => !use || use === options.use)\n\n if (options.kid) {\n const jwksForKid = jwksForUse.filter(({ kid }) => kid === options.kid)\n if (jwksForKid.length === 0) {\n throw new JoseSignerError(\n `Unable to extract jwk from jwks for use '${options.use}'. No key with kid '${options.kid}' found.`\n )\n }\n\n const jwkForKid = onlyJwk(jwksForKid)\n if (jwkForKid) return jwkForKid\n\n throw new JoseSignerError(\n `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.`\n )\n }\n\n const jwkForUse = onlyJwk(jwksForUse)\n if (jwkForUse) return jwkForUse\n\n throw new JoseSignerError(\n `Unable to extract jwk from jwks for use '${options.use}'. No kid provided and the jwks contains ${jwksForUse.length} keys for this use.`\n )\n}\n\n/**\n * Whether `jwk` is one of `jwks`, compared by JWK thumbprint. Keys in the set without a thumbprint,\n * such as an ML-DSA `AKP` key, are skipped.\n *\n * @throws JoseValidationError if the thumbprint of `jwk` itself cannot be computed.\n */\nexport async function isJwkInSet({\n jwk,\n jwks,\n hashCallback,\n}: {\n jwk: Jwk\n jwks: ReadonlyArray<Jwk>\n hashCallback: Hasher\n}): Promise<boolean> {\n const thumbprint = await calculateJwkThumbprint({ jwk, hashAlgorithm: 'sha-256', hashCallback })\n\n for (const jwkFromSet of jwks) {\n if (!zJwkThumbprintComponents.safeParse(jwkFromSet).success) continue\n\n const thumbprintFromSet = await calculateJwkThumbprint({\n jwk: jwkFromSet,\n hashAlgorithm: 'sha-256',\n hashCallback,\n })\n\n if (thumbprintFromSet === thumbprint) return true\n }\n\n return false\n}\n","import { ValidationIssues } from '@owf/identity-common'\nimport { JoseValidationError, type JoseValidationIssue } from '../error'\nimport { hasOwn } from '../utils/object'\nimport type { JwsProtectedHeader, JwsUnprotectedHeader } from './z-jws'\n\n/**\n * The header parameters of RFC 7515, RFC 7516 and RFC 7518, which `crit` must not list. `b64` is not\n * one of them: RFC 7797 requires it in `crit`.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.11\n */\nconst registeredHeaderParameters = new Set([\n 'alg',\n 'jku',\n 'jwk',\n 'kid',\n 'x5u',\n 'x5c',\n 'x5t',\n 'x5t#S256',\n 'typ',\n 'cty',\n 'crit',\n 'enc',\n 'zip',\n 'epk',\n 'apu',\n 'apv',\n 'iv',\n 'tag',\n 'p2s',\n 'p2c',\n])\n\nexport interface AssertCriticalHeaderParametersOptions {\n /** The protected header, validated against {@link zJwsProtectedHeader}, so the shape of `crit` is checked. */\n protectedHeader: JwsProtectedHeader\n\n /** The unprotected header, if the serialization has one. */\n unprotectedHeader?: JwsUnprotectedHeader\n\n /** The extension header parameters the caller processes. A JWS that marks another one critical is rejected. */\n understoodCriticalParameters?: ReadonlyArray<string>\n}\n\n/**\n * Verifies the `crit` header parameter of a JWS.\n *\n * @throws JoseValidationError with an `invalid_crit` or `unsupported_crit` issue for each way `crit`\n * is invalid, or names a parameter that is not understood.\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.11\n */\nexport function assertCriticalHeaderParameters({\n protectedHeader,\n unprotectedHeader,\n understoodCriticalParameters = [],\n}: AssertCriticalHeaderParametersOptions): void {\n const issues = new ValidationIssues<JoseValidationIssue['code']>()\n\n // `crit` is only meaningful when it is integrity protected\n if (unprotectedHeader && hasOwn(unprotectedHeader, 'crit')) {\n issues.add({\n code: 'invalid_crit',\n path: ['crit'],\n message: `The 'crit' header parameter is present in the unprotected header, where it is not integrity protected and therefore not valid`,\n })\n }\n\n const understood = new Set(understoodCriticalParameters)\n\n protectedHeader.crit?.forEach((name, index) => {\n const path = ['crit', index]\n if (registeredHeaderParameters.has(name)) {\n issues.add({\n code: 'invalid_crit',\n path,\n message: `The 'crit' header parameter lists '${name}', which is a registered header parameter and must not be listed`,\n context: { parameter: name },\n })\n }\n // A parameter marked critical can be carried in the unprotected header\n else if (!hasOwn(protectedHeader, name) && !(unprotectedHeader && hasOwn(unprotectedHeader, name))) {\n issues.add({\n code: 'invalid_crit',\n path,\n message: `The 'crit' header parameter lists '${name}', but the header does not contain that parameter`,\n context: { parameter: name },\n })\n } else if (!understood.has(name)) {\n issues.add({\n code: 'unsupported_crit',\n path,\n message:\n name === 'b64'\n ? `The 'crit' header parameter lists 'b64' (RFC 7797), which is only accepted when 'b64' is in 'understoodCriticalParameters'`\n : `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.`,\n context: { parameter: name, understood: [...understood] },\n })\n }\n })\n\n if (issues.issues.length) throw new JoseValidationError('Invalid JWS crit header parameter', issues.issues)\n}\n\n/**\n * Whether the payload of a JWS is base64url encoded, per `b64`. RFC 7797 requires `b64` to be listed\n * in `crit`.\n *\n * @throws JoseValidationError with an `invalid_crit` issue if `b64` is used without being marked critical.\n * @see https://www.rfc-editor.org/rfc/rfc7797#section-6\n */\nexport function isPayloadBase64UrlEncoded(protectedHeader: JwsProtectedHeader): boolean {\n const b64 = protectedHeader.b64\n if (b64 === undefined) return true\n\n if (!protectedHeader.crit?.includes('b64')) {\n throw new JoseValidationError('Invalid JWS crit header parameter', [\n {\n severity: 'error',\n code: 'invalid_crit',\n path: ['crit'],\n message: `The 'b64' header parameter is used, but is not listed in the 'crit' header parameter, which RFC 7797 requires`,\n },\n ])\n }\n\n return b64\n}\n","// The only place this package decodes JOSE parts, strictly, through `@owf/identity-common`. Don't decode\n// elsewhere: two encodings of the same header would be two tokens that are treated as one.\n\nimport { base64url, base64urlDecodeJson, base64urlEncode, bytesToString } from '@owf/identity-common'\nimport { JoseNotSupportedError, JoseParseError } from '../error'\n\n/**\n * Decodes a base64url encoded JSON object, such as a JWS protected header.\n *\n * @throws JoseParseError if the input is not valid base64url, not valid UTF-8, not valid JSON, or\n * is a JSON value other than an object.\n */\nexport function decodeBase64UrlJsonObject(encoded: string, name: string): Record<string, unknown> {\n let decoded: unknown\n try {\n decoded = base64urlDecodeJson(encoded)\n } catch (error) {\n throw new JoseParseError(`Unable to decode the ${name}, it is not valid base64url encoded JSON`, { cause: error })\n }\n\n if (typeof decoded !== 'object' || decoded === null || Array.isArray(decoded)) {\n throw new JoseParseError(`Unable to decode the ${name}, it is not a JSON object`)\n }\n\n return decoded as Record<string, unknown>\n}\n\n/**\n * Decodes a base64url encoded value into bytes.\n *\n * @throws JoseParseError if the input is not valid base64url.\n */\nexport function decodeBase64UrlBytes(encoded: string, name: string): Uint8Array {\n try {\n return base64url.decode(encoded)\n } catch (error) {\n throw new JoseParseError(`Unable to decode the ${name}, it is not valid base64url`, { cause: error })\n }\n}\n\n/**\n * The payload of a JWS with `b64` false (RFC 7797), as it appears in the signing input. That is a\n * string, so a payload that is not valid UTF-8 is not supported.\n *\n * @throws JoseNotSupportedError if the payload is not valid UTF-8.\n */\nexport function decodeUnencodedPayload(payload: Uint8Array): string {\n try {\n return bytesToString(payload, { fatal: true })\n } catch (error) {\n throw new JoseNotSupportedError(`An unencoded payload ('b64' is false) that is not valid UTF-8 is not supported.`, {\n cause: error,\n })\n }\n}\n\n/**\n * Why an unencoded payload (`b64` false) cannot be carried in a compact serialization, or `undefined`\n * when it can: only printable ASCII other than '.' (%x20-2D and %x2F-7E) is allowed.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7797#section-5.2\n */\nexport function unencodedCompactPayloadIssue(payload: string): string | undefined {\n if (payload.includes('.')) {\n 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.`\n }\n\n if (!/^[\\x20-\\x7e]*$/.test(payload)) {\n 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.`\n }\n\n return undefined\n}\n\n/** Encodes a JSON value the way a JOSE part is encoded: compact JSON, base64url, no padding. */\nexport function encodeBase64UrlJson(value: unknown): string {\n return base64urlEncode(JSON.stringify(value))\n}\n","import { type BaseSchema, base64url, parseWithErrorHandling, stringToBytes, zBase64Url } from '@owf/identity-common'\nimport { JoseParseError, JoseValidationError } from '../error'\nimport {\n decodeBase64UrlBytes,\n decodeBase64UrlJsonObject,\n decodeUnencodedPayload,\n unencodedCompactPayloadIssue,\n} from '../utils/encoding'\nimport { hasOwn } from '../utils/object'\nimport type { InferSchemaOrDefaultOutput } from '../utils/zod'\nimport { assertCriticalHeaderParameters, isPayloadBase64UrlEncoded } from './critical-headers'\nimport {\n type FlattenedJws,\n type GeneralJws,\n type JwsProtectedHeader,\n zFlattenedJws,\n zGeneralJws,\n zJwsProtectedHeader,\n zJwsUnprotectedHeader,\n} from './z-jws'\n\nexport type JwsSerialization = 'compact' | 'flattened' | 'general'\n\nexport interface ParseJwsOptions<\n ProtectedHeaderSchema extends BaseSchema | undefined,\n UnprotectedHeaderSchema extends BaseSchema | undefined,\n> {\n /** The JWS. A string is always read as a compact serialization, a JSON serialization is passed as an object. */\n jws: string | FlattenedJws | GeneralJws\n\n /** Schema for the protected header. The header is always validated against {@link zJwsProtectedHeader} too. */\n protectedHeaderSchema?: ProtectedHeaderSchema\n\n /** Schema for the unprotected header of a JSON serialized JWS. */\n unprotectedHeaderSchema?: UnprotectedHeaderSchema\n\n /** The payload of a JWS that does not carry one. Rejected when the JWS does carry one. */\n detachedPayload?: string | Uint8Array\n\n /**\n * Which signature to read from a general JSON serialization.\n *\n * @default 0\n */\n signatureIndex?: number\n\n /**\n * The critical header parameters the caller understands, see {@link assertCriticalHeaderParameters}.\n * Include `b64` to accept an unencoded payload (RFC 7797).\n */\n understoodCriticalParameters?: ReadonlyArray<string>\n}\n\nexport interface ParsedJws<\n ProtectedHeaderSchema extends BaseSchema | undefined = undefined,\n UnprotectedHeaderSchema extends BaseSchema | undefined = undefined,\n> {\n serialization: JwsSerialization\n\n /** The validated protected header, as the schema that was given returned it. */\n protectedHeader: InferSchemaOrDefaultOutput<ProtectedHeaderSchema, typeof zJwsProtectedHeader>\n\n /**\n * The protected header validated against {@link zJwsProtectedHeader} alone. The checks use it, as the\n * caller's schema can change the parameters they depend on.\n */\n registeredProtectedHeader: JwsProtectedHeader\n\n /** The validated unprotected header, when there is one. Not covered by the signature. */\n unprotectedHeader?: InferSchemaOrDefaultOutput<UnprotectedHeaderSchema, typeof zJwsUnprotectedHeader>\n\n /** The protected header as it was received, base64url encoded. */\n encodedProtectedHeader: string\n\n /** The payload bytes. */\n payload: Uint8Array\n\n /**\n * The payload as it appears in the signing input: base64url encoded, or the payload itself when\n * `b64` is false.\n */\n encodedPayload: string\n\n /** The signature, base64url encoded. */\n signature: string\n\n /**\n * The bytes covered by the signature, as a string. Taken from the token as received, as re-encoding\n * the parsed header can change them.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-5.2\n */\n signingInput: string\n\n /** The compact serialization, when that was parsed and the payload is not detached. */\n compact?: string\n}\n\n/** The parts of a JWS, as they are laid out in the serialization it was received in. */\ninterface JwsParts {\n serialization: JwsSerialization\n encodedProtectedHeader: string | undefined\n unprotectedHeader: Record<string, unknown> | undefined\n /** `undefined` when the payload is detached. */\n serializedPayload: string | undefined\n signature: string\n compact?: string\n}\n\n/** Whether a compact JWS header sets `b64` to false, as then a '.' in the payload split it into more parts. */\nconst isUnencodedPayloadHeader = (encodedProtectedHeader: string): boolean => {\n try {\n return decodeBase64UrlJsonObject(encodedProtectedHeader, 'JWS protected header').b64 === false\n } catch {\n return false\n }\n}\n\nfunction compactJwsParts(jws: string): JwsParts {\n const parts = jws.split('.')\n if (parts.length > 3 && isUnencodedPayloadHeader(parts[0])) {\n // The header and the signature are base64url, so the payload is everything between them\n const issue = unencodedCompactPayloadIssue(parts.slice(1, -1).join('.'))\n throw new JoseParseError(`Unable to parse the JWS. ${issue}`)\n }\n if (parts.length !== 3) {\n throw new JoseParseError('Unable to parse the JWS, a compact JWS must consist of exactly three parts')\n }\n\n // The signature goes to the callback undecoded, so it is checked here. The payload is not: with\n // `b64` false it is not base64url.\n if (!zBase64Url.safeParse(parts[0]).success) {\n throw new JoseParseError('Unable to parse the JWS, the protected header of a compact JWS must be base64url')\n }\n if (!zBase64Url.safeParse(parts[2]).success) {\n throw new JoseParseError('Unable to parse the JWS, the signature of a compact JWS must be base64url')\n }\n\n if (parts[2] === '') {\n throw new JoseParseError(\n 'Unable to parse the JWS, it does not have a signature. An unsecured JWS is not supported.'\n )\n }\n\n const isPayloadDetached = parts[1] === ''\n\n return {\n serialization: 'compact',\n encodedProtectedHeader: parts[0],\n unprotectedHeader: undefined,\n serializedPayload: isPayloadDetached ? undefined : parts[1],\n signature: parts[2],\n compact: isPayloadDetached ? undefined : jws,\n }\n}\n\nfunction jsonJwsParts(jws: FlattenedJws | GeneralJws, signatureIndex: number): JwsParts {\n // Often what `JSON.parse` returned for an untrusted body, which can be any JSON value\n if (typeof jws !== 'object' || jws === null || Array.isArray(jws)) {\n throw new JoseParseError('Unable to parse the JWS, a JSON serialized JWS must be an object')\n }\n\n if ('signatures' in jws) {\n const general = parseWithErrorHandling(\n zGeneralJws,\n jws,\n 'Unable to parse the general JSON serialized JWS',\n JoseValidationError\n )\n const signature = general.signatures[signatureIndex]\n\n if (!signature) {\n throw new JoseParseError(\n `Unable to parse the JWS, it does not contain a signature at index ${signatureIndex}. It contains ${general.signatures.length} signature(s).`\n )\n }\n\n return {\n serialization: 'general',\n encodedProtectedHeader: signature.protected,\n unprotectedHeader: signature.header,\n serializedPayload: general.payload,\n signature: signature.signature,\n }\n }\n\n const flattened = parseWithErrorHandling(\n zFlattenedJws,\n jws,\n 'Unable to parse the flattened JSON serialized JWS',\n JoseValidationError\n )\n\n return {\n serialization: 'flattened',\n encodedProtectedHeader: flattened.protected,\n unprotectedHeader: flattened.header,\n serializedPayload: flattened.payload,\n signature: flattened.signature,\n }\n}\n\n/**\n * Parses and validates a JWS, without verifying the signature. A JWS without a protected header, so\n * without an integrity protected `alg`, is not supported.\n *\n * @throws JoseParseError if the JWS is not well-formed, which includes a compact JWS that carries an\n * unencoded payload (`b64` is false) with a '.' or a character outside printable ASCII.\n * @throws JoseValidationError if a header does not validate against its schema.\n * @throws JoseValidationError with an `invalid_crit` or `unsupported_crit` issue if `crit` is invalid\n * or names a parameter that is not understood.\n * @throws JoseNotSupportedError if the payload is unencoded (`b64` is false) and not valid UTF-8.\n */\nexport function parseJws<\n ProtectedHeaderSchema extends BaseSchema | undefined = undefined,\n UnprotectedHeaderSchema extends BaseSchema | undefined = undefined,\n>(\n options: ParseJwsOptions<ProtectedHeaderSchema, UnprotectedHeaderSchema>\n): ParsedJws<ProtectedHeaderSchema, UnprotectedHeaderSchema> {\n const parts =\n typeof options.jws === 'string'\n ? compactJwsParts(options.jws)\n : jsonJwsParts(options.jws, options.signatureIndex ?? 0)\n\n if (!parts.encodedProtectedHeader) {\n throw new JoseParseError(\n '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.'\n )\n }\n\n const protectedHeaderJson = decodeBase64UrlJsonObject(parts.encodedProtectedHeader, 'JWS protected header')\n\n if (parts.unprotectedHeader) {\n const duplicates = Object.keys(parts.unprotectedHeader).filter((name) => hasOwn(protectedHeaderJson, name))\n if (duplicates.length > 0) {\n throw new JoseParseError(\n `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`\n )\n }\n }\n\n // The checks use the registered header, so the caller's schema cannot leave `alg` or `crit` unchecked\n const registeredHeader = parseWithErrorHandling(\n zJwsProtectedHeader,\n protectedHeaderJson,\n 'Invalid JWS protected header',\n JoseValidationError\n )\n const protectedHeader = parseWithErrorHandling(\n options.protectedHeaderSchema ?? zJwsProtectedHeader,\n protectedHeaderJson,\n 'Invalid JWS protected header',\n JoseValidationError\n )\n\n const unprotectedHeader = parts.unprotectedHeader\n ? parseWithErrorHandling(\n options.unprotectedHeaderSchema ?? zJwsUnprotectedHeader,\n parts.unprotectedHeader,\n 'Invalid JWS unprotected header',\n JoseValidationError\n )\n : undefined\n\n assertCriticalHeaderParameters({\n protectedHeader: registeredHeader,\n unprotectedHeader: parts.unprotectedHeader,\n understoodCriticalParameters: options.understoodCriticalParameters,\n })\n\n const isBase64UrlEncoded = isPayloadBase64UrlEncoded(registeredHeader)\n\n // RFC 7797 section 5.2: a compact serialization only carries an unencoded payload of printable ASCII\n // other than '.'. A '.' has already split the JWS into more parts.\n const compactPayloadIssue =\n parts.serialization === 'compact' && !isBase64UrlEncoded && parts.serializedPayload !== undefined\n ? unencodedCompactPayloadIssue(parts.serializedPayload)\n : undefined\n if (compactPayloadIssue) throw new JoseParseError(`Unable to parse the JWS. ${compactPayloadIssue}`)\n\n const { payload, encodedPayload } = resolvePayload({\n serializedPayload: parts.serializedPayload,\n detachedPayload: options.detachedPayload,\n isBase64UrlEncoded,\n })\n\n return {\n serialization: parts.serialization,\n protectedHeader: protectedHeader as ParsedJws<ProtectedHeaderSchema, UnprotectedHeaderSchema>['protectedHeader'],\n registeredProtectedHeader: registeredHeader,\n unprotectedHeader: unprotectedHeader as ParsedJws<\n ProtectedHeaderSchema,\n UnprotectedHeaderSchema\n >['unprotectedHeader'],\n encodedProtectedHeader: parts.encodedProtectedHeader,\n payload,\n encodedPayload,\n signature: parts.signature,\n signingInput: `${parts.encodedProtectedHeader}.${encodedPayload}`,\n compact: parts.compact,\n }\n}\n\nfunction resolvePayload({\n serializedPayload,\n detachedPayload,\n isBase64UrlEncoded,\n}: {\n serializedPayload: string | undefined\n detachedPayload: string | Uint8Array | undefined\n isBase64UrlEncoded: boolean\n}): { payload: Uint8Array; encodedPayload: string } {\n if (serializedPayload !== undefined && detachedPayload !== undefined) {\n throw new JoseParseError(\n 'A detached payload was provided, but the JWS carries a payload. Only one of the two can be the payload that was signed.'\n )\n }\n\n if (serializedPayload === undefined && detachedPayload === undefined) {\n throw new JoseParseError(\n 'The JWS does not carry a payload and no detached payload was provided, so there is nothing to verify. Pass the payload as `detachedPayload`.'\n )\n }\n\n if (detachedPayload !== undefined) {\n const payload = typeof detachedPayload === 'string' ? stringToBytes(detachedPayload) : detachedPayload\n return {\n payload,\n encodedPayload: isBase64UrlEncoded ? base64url.encode(payload) : decodeUnencodedPayload(payload),\n }\n }\n\n const serialized = serializedPayload as string\n return {\n payload: isBase64UrlEncoded ? decodeBase64UrlBytes(serialized, 'JWS payload') : stringToBytes(serialized),\n encodedPayload: serialized,\n }\n}\n","import { base64url, parseWithErrorHandling, stringToBytes, zBase64Url } from '@owf/identity-common'\nimport type { SignJwsCallback } from '../callbacks'\nimport { JoseInvalidArgumentError, JoseValidationError } from '../error'\nimport type { Jwk } from '../jwk/z-jwk'\nimport { decodeUnencodedPayload, encodeBase64UrlJson, unencodedCompactPayloadIssue } from '../utils/encoding'\nimport { assertCriticalHeaderParameters, isPayloadBase64UrlEncoded } from './critical-headers'\nimport type { JwsSigner } from './signer'\nimport { zJwsProtectedHeader } from './z-jws'\n\nexport interface SignCompactJwsOptions {\n /** The protected header, validated against {@link zJwsProtectedHeader}. Its `alg` must be the signer's. */\n protectedHeader: Record<string, unknown>\n\n /** The payload. An object is serialized as JSON, a string is encoded as UTF-8. */\n payload: Record<string, unknown> | string | Uint8Array\n\n /** The signer, which the callback resolves into a key. */\n signer: JwsSigner\n\n /** Callback that produces the signature. */\n signJwsCallback: SignJwsCallback\n\n /**\n * Whether to leave the payload out of the compact serialization, to carry it out of band.\n *\n * @default false\n */\n detachPayload?: boolean\n}\n\nexport interface SignCompactJwsResult {\n /** The compact serialization. Its payload part is empty when `detachPayload` was set. */\n compact: string\n\n /** The signature, base64url encoded. */\n signature: string\n\n /** The bytes that were signed, as a string. */\n signingInput: string\n\n /** The public key the JWS was signed with, as reported by the callback. */\n signerJwk: Jwk\n}\n\n/**\n * Signs a JWS in compact serialization. The callback signs the exact bytes that end up in the token.\n *\n * @throws JoseValidationError if the protected header is not a valid JWS header.\n * @throws JoseValidationError with an `invalid_crit` issue if `crit` is invalid.\n * @throws JoseNotSupportedError if the payload is unencoded (`b64` is false) and not valid UTF-8.\n * @throws JoseInvalidArgumentError if the signer uses another algorithm than the header names, the\n * callback does not return a base64url encoded signature, or the payload is unencoded, not detached,\n * and contains a character RFC 7797 does not allow in a compact serialization: a '.', or anything\n * outside printable ASCII.\n */\nexport async function signCompactJws(options: SignCompactJwsOptions): Promise<SignCompactJwsResult> {\n const protectedHeader = parseWithErrorHandling(\n zJwsProtectedHeader,\n options.protectedHeader,\n 'Unable to sign the JWS, invalid header',\n JoseValidationError\n )\n\n // A producer understands what it marks critical\n assertCriticalHeaderParameters({ protectedHeader, understoodCriticalParameters: protectedHeader.crit ?? [] })\n\n if (options.signer.alg !== protectedHeader.alg) {\n throw new JoseInvalidArgumentError(\n `Unable to sign the JWS, the header says alg '${protectedHeader.alg}' but the signer signs with alg '${options.signer.alg}'.`\n )\n }\n\n const payload =\n typeof options.payload === 'string'\n ? stringToBytes(options.payload)\n : options.payload instanceof Uint8Array\n ? options.payload\n : stringToBytes(JSON.stringify(options.payload))\n\n const isBase64UrlEncoded = isPayloadBase64UrlEncoded(protectedHeader)\n\n const encodedProtectedHeader = encodeBase64UrlJson(protectedHeader)\n const encodedPayload = isBase64UrlEncoded ? base64url.encode(payload) : decodeUnencodedPayload(payload)\n const signingInput = `${encodedProtectedHeader}.${encodedPayload}`\n\n // RFC 7797 section 5.2\n const compactPayloadIssue =\n !isBase64UrlEncoded && !options.detachPayload ? unencodedCompactPayloadIssue(encodedPayload) : undefined\n if (compactPayloadIssue) {\n throw new JoseInvalidArgumentError(\n `Unable to sign the JWS. ${compactPayloadIssue} Detach the payload, or leave out 'b64' so that it is base64url encoded.`\n )\n }\n\n const { signature, signerJwk } = await options.signJwsCallback(options.signer, {\n signingInput,\n signingInputBytes: stringToBytes(signingInput),\n protectedHeader,\n payload,\n jwtPayload:\n typeof options.payload === 'object' && !(options.payload instanceof Uint8Array) ? options.payload : undefined,\n })\n\n // The signature is written into the token as it is, so it has to be what a parser accepts there\n if (!zBase64Url.min(1).safeParse(signature).success) {\n throw new JoseInvalidArgumentError(\n 'Unable to sign the JWS, the signature returned by the signing callback is not a non-empty base64url string.'\n )\n }\n\n return {\n compact: `${encodedProtectedHeader}.${options.detachPayload ? '' : encodedPayload}.${signature}`,\n signature,\n signingInput,\n signerJwk,\n }\n}\n","import { JoseSignerError } from '../error'\nimport type { Jwk } from '../jwk/z-jwk'\nimport type { JwsProtectedHeader } from './z-jws'\n\n/** The signer is identified by a DID URL, resolved to a verification method by the caller. */\nexport type JwsSignerDid = {\n method: 'did'\n didUrl: string\n alg: string\n\n /** The key id to sign with. It must match the key of `didUrl`. */\n kid?: string\n}\n\n/** The signer is identified by a public JWK, carried in the `jwk` header parameter. */\nexport type JwsSignerJwk = {\n method: 'jwk'\n publicJwk: Jwk\n alg: string\n\n /** The key id to sign with. It must match `publicJwk`, and is not added to the header. */\n kid?: string\n}\n\n/** The signer is identified by an X.509 certificate chain, carried in the `x5c` header parameter. */\nexport type JwsSignerX5c = {\n method: 'x5c'\n x5c: string[]\n alg: string\n\n /** The key id to sign with. It must match the key of the leaf certificate. */\n kid?: string\n}\n\n/** The signer is established through an OpenID Federation trust chain. */\nexport type JwsSignerFederation = {\n method: 'federation'\n trustChain?: [string, ...string[]]\n alg: string\n\n /** The key id to sign with. It must match a key in the federation. */\n kid: string\n}\n\n/** The signer is established out of band. */\nexport type JwsSignerCustom = {\n method: 'custom'\n alg: string\n\n /** The key id that should be used for signing. Added to the header as `kid`. */\n kid?: string\n}\n\nexport type JwsSigner = JwsSignerDid | JwsSignerJwk | JwsSignerX5c | JwsSignerFederation | JwsSignerCustom\n\nexport type JwsSignerMethod = JwsSigner['method']\n\n/** A {@link JwsSigner} whose public key is known, which is what verification establishes. */\nexport type JwsSignerWithJwk = JwsSigner & { publicJwk: Jwk }\n\n/**\n * The header parameters that identify the signer, as derived from a {@link JwsSigner}:\n *\n * - `did`: the DID URL, as `kid`.\n * - `federation`: `kid` and `trust_chain`. Without a trust chain that is `kid` alone, from which a\n * verifier establishes a `custom` signer.\n * - `jwk`: `jwk`. The `kid` of the signer is not added.\n * - `x5c`: `x5c`. The `kid` of the signer is not added.\n * - `custom`: `kid`, when the signer has one.\n */\nexport function jwsHeaderFromSigner(signer: JwsSigner) {\n if (signer.method === 'did') {\n return { alg: signer.alg, kid: signer.didUrl } as const\n }\n\n if (signer.method === 'federation') {\n return { alg: signer.alg, kid: signer.kid, trust_chain: signer.trustChain } as const\n }\n\n if (signer.method === 'jwk') {\n return { alg: signer.alg, jwk: signer.publicJwk } as const\n }\n\n if (signer.method === 'x5c') {\n return { alg: signer.alg, x5c: signer.x5c } as const\n }\n\n return signer.kid !== undefined ? ({ alg: signer.alg, kid: signer.kid } as const) : ({ alg: signer.alg } as const)\n}\n\nexport interface JwsSignerFromHeaderOptions {\n /** The protected header of the JWS. */\n header: JwsProtectedHeader\n\n /** The `iss` of a JWT, as a DID signer can be a DID in `iss` with a fragment in `kid`. */\n issuer?: string\n\n /** The signer methods the caller accepts. */\n allowedSignerMethods?: ReadonlyArray<JwsSignerMethod>\n\n /**\n * Whether to accept a header that identifies the signer in more than one way, taking the first allowed\n * of `x5c`, `trust_chain`, `did` and `jwk`. Off by default, so a trusted `x5c` next to an attacker's\n * `jwk` is rejected rather than resolved by precedence.\n *\n * @default false\n */\n allowMultipleSignerMethods?: boolean\n\n /**\n * Whether the DID in `kid` may differ from `iss`, as in `openid4vci-proof+jwt`, where `iss` is the\n * client id.\n *\n * @default false\n */\n allowDidKidIssuerMismatch?: boolean\n}\n\ntype FoundSigner =\n | { method: JwsSignerMethod; signer: JwsSigner; valid: true }\n | { method: JwsSignerMethod; error: string; valid: false }\n\n/**\n * The DID a DID URL refers to: everything before its path, query or fragment.\n *\n * @see https://www.w3.org/TR/did-core/#did-url-syntax\n */\nconst didOfDidUrl = (didUrl: string): string => {\n const end = didUrl.search(/[/?#]/)\n return end === -1 ? didUrl : didUrl.slice(0, end)\n}\n\n/**\n * Establishes the signer of a JWS from its header. Whether the key is trusted is for the verification\n * callback.\n *\n * @throws JoseSignerError if the signer cannot be established, or is identified in more than one way.\n */\nexport function jwsSignerFromHeader({\n header,\n issuer,\n allowedSignerMethods,\n allowMultipleSignerMethods = false,\n allowDidKidIssuerMismatch = false,\n}: JwsSignerFromHeaderOptions): JwsSigner {\n const found: FoundSigner[] = []\n\n if (header.x5c) {\n found.push({\n method: 'x5c',\n valid: true,\n signer: { method: 'x5c', alg: header.alg, x5c: header.x5c, kid: header.kid },\n })\n }\n\n if (header.trust_chain) {\n if (!header.kid) {\n found.push({\n method: 'federation',\n valid: false,\n error: `When 'trust_chain' is used in the header, the 'kid' parameter is required.`,\n })\n } else {\n found.push({\n method: 'federation',\n valid: true,\n signer: { method: 'federation', alg: header.alg, trustChain: header.trust_chain, kid: header.kid },\n })\n }\n }\n\n if (header.kid?.startsWith('did:') || issuer?.startsWith('did:')) {\n // An exact match: `did:web:example.com.evil.org` starts with `did:web:example.com`\n if (issuer && header.kid?.startsWith('did:') && didOfDidUrl(header.kid) !== issuer && !allowDidKidIssuerMismatch) {\n found.push({\n method: 'did',\n valid: false,\n error: `kid in header starts with a did that is different from the did value in 'iss'`,\n })\n } else if (!header.kid?.startsWith('did:') && !header.kid?.startsWith('#')) {\n found.push({\n method: 'did',\n valid: false,\n error: `kid in header must start with either 'did:' or '#' when the 'iss' value is a did`,\n })\n } else {\n found.push({\n method: 'did',\n valid: true,\n signer: {\n method: 'did',\n alg: header.alg,\n didUrl: header.kid.startsWith('did:') ? header.kid : `${issuer}${header.kid}`,\n },\n })\n }\n }\n\n if (header.jwk) {\n found.push({\n method: 'jwk',\n valid: true,\n signer: { method: 'jwk', alg: header.alg, publicJwk: header.jwk },\n })\n }\n\n const allowedFound = found.filter((f) => !allowedSignerMethods || allowedSignerMethods.includes(f.method))\n const allowedValid = allowedFound.filter((f) => f.valid)\n\n if (allowedValid.length > 1 && !allowMultipleSignerMethods) {\n throw new JoseSignerError(\n `Unable to establish the signer of the JWS. The header identifies the signer in ${allowedValid.length} ways (${allowedValid\n .map((f) => `'${f.method}'`)\n .join(\n ', '\n )}), and it is ambiguous which one applies. Narrow it down with 'allowedSignerMethods', or set 'allowMultipleSignerMethods'.`\n )\n }\n\n if (allowedValid.length > 0) return allowedValid[0].signer\n\n if (allowedFound.length > 0) {\n throw new JoseSignerError(\n `Unable to establish the signer of the JWS. Found ${allowedFound.length} allowed signer method(s), but they contained an invalid configuration:\\n${allowedFound\n .map((f) => (f.valid ? '' : `FAILED: method ${f.method} - ${f.error}`))\n .join('\\n')}`\n )\n }\n\n if (found.length > 0) {\n throw new JoseSignerError(\n `Unable to establish the signer of the JWS. Found ${found.length} signer method(s) that are not allowed:\\n${found\n .map((f) => (f.valid ? `SUCCEEDED: method ${f.method}` : `FAILED: method ${f.method} - ${f.error}`))\n .join('\\n')}`\n )\n }\n\n if (!allowedSignerMethods || allowedSignerMethods.includes('custom')) {\n return { method: 'custom', alg: header.alg, kid: header.kid }\n }\n\n throw new JoseSignerError(\n `Unable to establish the signer of the JWS. The header identifies no signer method, and the 'custom' signer method is not allowed.`\n )\n}\n","import { parseWithErrorHandling, stringToBytes } from '@owf/identity-common'\nimport type { VerifyJwsCallback } from '../callbacks'\nimport { JoseAlgorithmNotAllowedError, JoseSignatureVerificationError, JoseValidationError } from '../error'\nimport { isJwaSignatureAlgorithmCaseVariant, isSymmetricSignatureAlgorithm } from '../jwa/algorithms'\nimport { assertKeyAllowedForSignatureAlgorithm } from '../jwa/key-compatibility'\nimport { zJwsAlg } from '../jwa/z-alg'\nimport { zJwk } from '../jwk/z-jwk'\nimport type { JwtPayload } from '../jwt/z-jwt'\nimport type { ParsedJws } from './parse-jws'\nimport type { JwsSigner, JwsSignerMethod, JwsSignerWithJwk } from './signer'\nimport { jwsSignerFromHeader } from './signer'\nimport { zJwsProtectedHeader } from './z-jws'\n\n/**\n * The parts of a parsed JWS that verification needs. Without `registeredProtectedHeader`,\n * `protectedHeader` is validated against {@link zJwsProtectedHeader} and used instead.\n */\nexport type VerifiableJws = Pick<\n ParsedJws,\n 'protectedHeader' | 'unprotectedHeader' | 'signingInput' | 'signature' | 'payload' | 'compact'\n> &\n Partial<Pick<ParsedJws, 'registeredProtectedHeader'>>\n\nexport interface VerifyJwsSignatureOptions {\n /** The parsed JWS, as returned by `parseJws`. */\n jws: VerifiableJws\n\n /** Callback that verifies the signature and decides whether the key is trusted. */\n verifyJwsCallback: VerifyJwsCallback\n\n /**\n * The signer to verify against. Its `alg` must be the `alg` of the JWS. Established from the header\n * when not provided, see {@link jwsSignerFromHeader}.\n */\n signer?: JwsSigner\n\n /** The signer methods the caller accepts, used when the signer is established from the header. */\n allowedSignerMethods?: ReadonlyArray<JwsSignerMethod>\n\n /**\n * See {@link JwsSignerFromHeaderOptions.allowMultipleSignerMethods}.\n *\n * @default false\n */\n allowMultipleSignerMethods?: boolean\n\n /**\n * See {@link JwsSignerFromHeaderOptions.allowDidKidIssuerMismatch}.\n *\n * @default false\n */\n allowDidKidIssuerMismatch?: boolean\n\n /**\n * The algorithms the caller accepts: pass the ones the signer is known to use. Without it, any\n * algorithm is accepted except `none`, symmetric ones and registered ones in a different casing.\n */\n allowedAlgorithms?: ReadonlyArray<string>\n\n /**\n * Whether `HS256`, `HS384` and `HS512` are accepted. Off by default, as with a symmetric algorithm\n * every verifier can also issue a token.\n *\n * @default false\n */\n allowSymmetricAlgorithms?: boolean\n\n /** The payload as a JSON object, when the JWS is a JWT. Passed to the callback, and a did signer is bound to its `iss`. */\n jwtPayload?: JwtPayload\n\n /** Prefix for the error thrown when verification fails. */\n errorMessage?: string\n}\n\nexport interface AssertJwsAlgorithmAllowedOptions {\n /** The `alg` of the JWS. */\n alg: string\n\n /** The algorithms the caller accepts. See {@link VerifyJwsSignatureOptions.allowedAlgorithms}. */\n allowedAlgorithms?: ReadonlyArray<string>\n\n /** Whether a symmetric signature algorithm is acceptable. See {@link VerifyJwsSignatureOptions.allowSymmetricAlgorithms}. */\n allowSymmetricAlgorithms?: boolean\n\n /** Prefix for the error thrown when the algorithm is not accepted. */\n errorMessage?: string\n}\n\n/**\n * The algorithm policy of {@link verifyJwsSignature}, for code that verifies a signature without a\n * {@link VerifyJwsCallback}.\n *\n * @throws JoseAlgorithmNotAllowedError if the algorithm is not accepted.\n */\nexport function assertJwsAlgorithmAllowed({\n alg,\n allowedAlgorithms,\n allowSymmetricAlgorithms = false,\n errorMessage = 'Error during verification of the JWS.',\n}: AssertJwsAlgorithmAllowedOptions): void {\n // `alg` does not have to come from a parsed header\n if (!zJwsAlg.safeParse(alg).success) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} The JWS uses alg '${alg}', which is not a signature algorithm. An unsecured JWS is never accepted.`\n )\n }\n\n if (isJwaSignatureAlgorithmCaseVariant(alg)) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} The JWS uses alg '${alg}', which differs from a registered algorithm only in casing. Algorithm names are case-sensitive.`\n )\n }\n\n if (allowedAlgorithms && !allowedAlgorithms.includes(alg)) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} The JWS uses alg '${alg}', but the allowed algorithms are ${allowedAlgorithms\n .map((allowed) => `'${allowed}'`)\n .join(', ')}.`\n )\n }\n\n if (isSymmetricSignatureAlgorithm(alg) && !allowSymmetricAlgorithms) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} The JWS uses the symmetric algorithm '${alg}'. Set 'allowSymmetricAlgorithms' if a MAC is expected here.`\n )\n }\n}\n\nexport interface VerifyJwsSignatureResult {\n /** The signer, with the public key the signature was verified with. */\n signer: JwsSignerWithJwk\n}\n\n/**\n * Verifies the signature over a parsed JWS: the algorithm policy before the callback, and the key the\n * callback returns against the algorithm after it.\n *\n * @throws JoseAlgorithmNotAllowedError if the algorithm is not accepted, or does not match the key or\n * the `alg` of the given `signer`.\n * @throws JoseSignatureVerificationError if the signature does not verify.\n * @throws JoseSignerError if the signer cannot be established from the header.\n * @throws JoseValidationError if the JWS has no `registeredProtectedHeader`, and its `protectedHeader`\n * is not a valid JWS protected header.\n */\nexport async function verifyJwsSignature(options: VerifyJwsSignatureOptions): Promise<VerifyJwsSignatureResult> {\n const errorMessage = options.errorMessage ?? 'Error during verification of the JWS.'\n\n // Security checks use the registered header, not what a caller's schema made of it\n const protectedHeader =\n options.jws.registeredProtectedHeader ??\n parseWithErrorHandling(\n zJwsProtectedHeader,\n options.jws.protectedHeader,\n 'Invalid JWS protected header',\n JoseValidationError\n )\n const alg = protectedHeader.alg\n\n assertJwsAlgorithmAllowed({\n alg,\n allowedAlgorithms: options.allowedAlgorithms,\n allowSymmetricAlgorithms: options.allowSymmetricAlgorithms,\n errorMessage,\n })\n\n // The callback verifies with `signer.alg`, so it must be the alg the policy was applied to\n if (options.signer && options.signer.alg !== alg) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} The JWS uses alg '${alg}', but the signer to verify against uses alg '${options.signer.alg}'.`\n )\n }\n\n const signer =\n options.signer ??\n jwsSignerFromHeader({\n header: protectedHeader,\n issuer: typeof options.jwtPayload?.iss === 'string' ? options.jwtPayload.iss : undefined,\n allowedSignerMethods: options.allowedSignerMethods,\n allowMultipleSignerMethods: options.allowMultipleSignerMethods,\n allowDidKidIssuerMismatch: options.allowDidKidIssuerMismatch,\n })\n\n let signerJwk: JwsSignerWithJwk['publicJwk']\n try {\n const result = await options.verifyJwsCallback(signer, {\n signingInput: options.jws.signingInput,\n signingInputBytes: stringToBytes(options.jws.signingInput),\n protectedHeader,\n unprotectedHeader: options.jws.unprotectedHeader,\n payload: options.jws.payload,\n jwtPayload: options.jwtPayload,\n signature: options.jws.signature,\n compact: options.jws.compact,\n })\n\n if (!result.verified) throw new JoseSignatureVerificationError(errorMessage)\n\n // Without the key, it cannot be checked against the algorithm below\n if (!zJwk.safeParse(result.signerJwk).success) {\n throw new JoseSignatureVerificationError(\n `${errorMessage} The verification callback reported the signature as verified, but did not return the jwk it was verified with.`\n )\n }\n signerJwk = result.signerJwk\n } catch (error) {\n if (error instanceof JoseSignatureVerificationError) throw error\n throw new JoseSignatureVerificationError(errorMessage, { cause: error })\n }\n\n assertKeyAllowedForSignatureAlgorithm({\n jwk: signerJwk,\n alg,\n errorMessage: `${errorMessage} The key the JWS was verified with cannot be used with its algorithm.`,\n })\n\n return { signer: { ...signer, publicJwk: signerJwk } }\n}\n","import { addValidationIssue, zBase64Url, zNonEmptyString, zNumericDate } from '@owf/identity-common'\nimport z from 'zod'\nimport { zPublicJwk } from '../jwk/z-jwk'\nimport { zJwsProtectedHeader } from '../jws/z-jws'\nimport { zCompactSerialization, zStringOrUri } from '../utils/z-common'\n\n/**\n * The header of a JWT, which is a JWS protected header.\n *\n * Compose on top of it to require what a token type needs, in particular its `typ`:\n *\n * ```ts\n * const zKbJwtHeader = z.object({ ...zJwtHeader.shape, typ: zTyp('kb+jwt') }).loose()\n * ```\n */\nexport const zJwtHeader = zJwsProtectedHeader\n\nexport type JwtHeader = z.infer<typeof zJwtHeader>\n\n/** The `cnf` members that each name the key, of which a `cnf` has at most one. */\nconst confirmationKeyMembers = ['jwk', 'jwe', 'jku', 'jkt'] as const\n\n/**\n * The `cnf` (confirmation) claim, which names the one key a token is bound to.\n *\n * The key is named in one way only, so that every verifier binds the token to the same key:\n * - at most one of `jwk`, `jwe`, `jku` (RFC 7800 section 3.1) and `jkt` (RFC 9449)\n * - `kid` on its own, e.g. a DID URL, or with `jku` to select the key from the set (RFC 7800\n * section 3.5) or with `jkt` that the key it resolves to has to match. Not with `jwk` or `jwe`,\n * which carry the key itself, and with it its `kid`.\n *\n * A token bound to several keys carries the others in claims of its own.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7800#section-3.1\n */\nexport const zJwtConfirmation = z\n .object({\n /** The public key the token is bound to. */\n jwk: zPublicJwk.optional(),\n\n /** The JWK thumbprint of the key the token is bound to, e.g. of a DPoP key. */\n jkt: zBase64Url.min(1).optional(),\n\n /** A key id, to be resolved by the recipient. */\n kid: zNonEmptyString.optional(),\n })\n .loose()\n .superRefine((cnf, ctx) => {\n const keyMembers = confirmationKeyMembers.filter((member) => cnf[member] !== undefined)\n for (const member of keyMembers.slice(1)) {\n addValidationIssue(ctx, {\n code: 'not_allowed',\n path: [member],\n message: `The cnf claim names its key with '${keyMembers[0]}', so it may not also have '${member}'`,\n })\n }\n\n if (cnf.kid !== undefined && (cnf.jwk !== undefined || cnf.jwe !== undefined)) {\n addValidationIssue(ctx, {\n code: 'not_allowed',\n path: ['kid'],\n message: `The cnf claim carries its key in '${cnf.jwk !== undefined ? 'jwk' : 'jwe'}', so it may not also have a 'kid'`,\n })\n }\n })\n\nexport type JwtConfirmation = z.infer<typeof zJwtConfirmation>\n\n/**\n * The claims registered for a JWT.\n *\n * All of them are optional, as RFC 7519 requires none: which claims a token must carry follows from\n * the token type, and is expressed by composing on this schema and by `requiredClaims` at\n * verification time.\n *\n * The schema is loose, so claims that are not registered are carried through unvalidated.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7519#section-4.1\n */\nexport const zJwtPayload = z\n .object({\n iss: zStringOrUri.optional(),\n sub: zStringOrUri.optional(),\n aud: z.union([zStringOrUri, z.array(zStringOrUri)]).optional(),\n exp: zNumericDate.optional(),\n nbf: zNumericDate.optional(),\n iat: zNumericDate.optional(),\n jti: zNonEmptyString.optional(),\n\n /** Not registered by RFC 7519, but used the same way across OpenID Connect and OAuth 2.0. */\n nonce: zNonEmptyString.optional(),\n\n cnf: zJwtConfirmation.optional(),\n\n /** Reserved for the Token Status List. @see https://datatracker.ietf.org/doc/draft-ietf-oauth-status-list */\n status: z.record(z.string(), z.unknown()).optional(),\n\n /** Reserved for OpenID Federation. */\n trust_chain: z.tuple([zNonEmptyString], zNonEmptyString).optional(),\n })\n .loose()\n\nexport type JwtPayload = z.infer<typeof zJwtPayload>\n\n/**\n * A JWT in compact serialization.\n *\n * Unlike `zCompactJws` the payload part may not be empty: a JWT carries its claims set, so a\n * detached payload is not a JWT.\n */\nexport const zCompactJwt = zCompactSerialization('jwt', 3)\n","import { type BaseSchema, parseWithErrorHandling } from '@owf/identity-common'\nimport { JoseNotSupportedError, JoseParseError, JoseValidationError } from '../error'\nimport { zJweHeader } from '../jwe/z-jwe'\nimport { parseJws } from '../jws/parse-jws'\nimport { decodeBase64UrlJsonObject } from '../utils/encoding'\nimport type { InferSchemaOrDefaultOutput } from '../utils/zod'\nimport { type JwtHeader, type JwtPayload, zJwtHeader, zJwtPayload } from './z-jwt'\n\nexport interface DecodeJwtOptions<\n HeaderSchema extends BaseSchema | undefined,\n PayloadSchema extends BaseSchema | undefined,\n> {\n /** The compact encoded JWT. */\n jwt: string\n\n /**\n * Schema to validate the header with, on top of {@link zJwtHeader}, which is always applied.\n */\n headerSchema?: HeaderSchema\n\n /**\n * Schema to validate the payload with, on top of {@link zJwtPayload}, which is always applied so\n * that a registered claim always has the shape RFC 7519 gives it.\n */\n payloadSchema?: PayloadSchema\n\n /** The critical header parameters the caller understands. */\n understoodCriticalParameters?: ReadonlyArray<string>\n}\n\nexport interface DecodeJwtResult<\n HeaderSchema extends BaseSchema | undefined = undefined,\n PayloadSchema extends BaseSchema | undefined = undefined,\n> {\n /** The header, as `headerSchema` returned it. */\n header: InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>\n\n /** The claims set, as `payloadSchema` returned it. */\n payload: InferSchemaOrDefaultOutput<PayloadSchema, typeof zJwtPayload>\n\n /**\n * The header as validated against {@link zJwtHeader} alone, whatever `headerSchema` was given.\n *\n * `verifyJwt` makes its checks on this rather than on {@link header}: a schema of the caller's can\n * drop or change the parameters the checks depend on.\n */\n registeredHeader: JwtHeader\n\n /**\n * The claims set as validated against {@link zJwtPayload} alone, whatever `payloadSchema` was given.\n *\n * `verifyJwt` verifies the claims on this rather than on {@link payload}, so that a schema that\n * drops `exp` or fills in `iat` cannot change the outcome.\n */\n registeredPayload: JwtPayload\n\n /** The claims set as bytes, exactly as they were carried in the token. */\n payloadBytes: Uint8Array\n\n /** The signature, base64url encoded. */\n signature: string\n\n /** The bytes covered by the signature, as an ASCII string. */\n signingInput: string\n\n /** The compact JWT that was decoded. */\n compact: string\n}\n\n/**\n * Decodes a JWT and validates its header and payload, without verifying the signature.\n *\n * Everything is decoded through `@owf/identity-common`, so a token with an invalid base64url\n * alphabet, invalid UTF-8 or invalid JSON is rejected rather than being decoded into something that\n * looks close enough.\n *\n * @throws JoseParseError if the JWT is not well-formed.\n * @throws JoseValidationError if the header or payload does not validate.\n */\nexport function decodeJwt<\n HeaderSchema extends BaseSchema | undefined = undefined,\n PayloadSchema extends BaseSchema | undefined = undefined,\n>(options: DecodeJwtOptions<HeaderSchema, PayloadSchema>): DecodeJwtResult<HeaderSchema, PayloadSchema> {\n const jws = parseJws({\n jws: options.jwt,\n protectedHeaderSchema: options.headerSchema,\n understoodCriticalParameters: options.understoodCriticalParameters,\n })\n\n // RFC 7519 defines the claims set as base64url encoded JSON, so RFC 7797's unencoded payload is\n // not a JWT. Allowing it would mean a token whose claims are not where a JWT's claims are.\n if (jws.registeredProtectedHeader.b64 === false) {\n throw new JoseNotSupportedError(\n `Unable to decode the JWT, its header sets 'b64' to false. An unencoded payload is not valid for a JWT.`\n )\n }\n\n if (jws.encodedPayload === '') {\n throw new JoseParseError('Unable to decode the JWT, it does not contain a payload')\n }\n\n const payloadJson = decodeBase64UrlJsonObject(jws.encodedPayload, 'JWT payload')\n\n // Always validated against the registered claims, and only then against the caller's schema: a\n // schema describing a profile's own claims must not be able to leave `exp` unchecked as a number.\n const registeredPayload = parseWithErrorHandling(zJwtPayload, payloadJson, 'Invalid JWT payload', JoseValidationError)\n const payload = parseWithErrorHandling(\n options.payloadSchema ?? zJwtPayload,\n payloadJson,\n 'Invalid JWT payload',\n JoseValidationError\n )\n\n return {\n header: jws.protectedHeader as InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>,\n payload: payload as InferSchemaOrDefaultOutput<PayloadSchema, typeof zJwtPayload>,\n registeredHeader: jws.registeredProtectedHeader,\n registeredPayload,\n payloadBytes: jws.payload,\n signature: jws.signature,\n signingInput: jws.signingInput,\n compact: options.jwt,\n }\n}\n\nexport interface DecodeJwtHeaderOptions<HeaderSchema extends BaseSchema | undefined> {\n /** The compact encoded JWT or JWE. */\n jwt: string\n\n /**\n * Schema to validate the header with, on top of {@link zJwtHeader} — and {@link zJweHeader} for a\n * JWE — which are always applied.\n */\n headerSchema?: HeaderSchema\n}\n\n/**\n * Decodes and validates only the header of a compact JWT or JWE.\n *\n * Useful when the header decides what to do next — which key to look up, or how to decrypt — and the\n * rest of the token cannot be read yet.\n *\n * @throws JoseParseError if the token is not well-formed.\n * @throws JoseValidationError if the header does not validate.\n */\nexport function decodeJwtHeader<HeaderSchema extends BaseSchema | undefined = undefined>(\n options: DecodeJwtHeaderOptions<HeaderSchema>\n): { header: InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader> } {\n const parts = options.jwt.split('.')\n\n // Three parts for a JWS, five for a JWE.\n if (parts.length !== 3 && parts.length !== 5) {\n throw new JoseParseError(\n 'Unable to decode the header, the token is neither a compact JWS (three parts) nor a compact JWE (five parts)'\n )\n }\n\n const headerJson = decodeBase64UrlJsonObject(parts[0], 'header')\n\n // Always validated against the registered header parameters, and only then against the caller's\n // schema, the way `decodeJwt` validates a header: a schema of the caller's must not be able to let\n // `alg: none` or a private `jwk` through. A JWE is held to the JWE header parameters as well, which\n // require `enc` and an `epk` that is a public key.\n const registeredHeader = parseWithErrorHandling(zJwtHeader, headerJson, 'Invalid header', JoseValidationError)\n if (parts.length === 5) parseWithErrorHandling(zJweHeader, headerJson, 'Invalid JWE header', JoseValidationError)\n const header = options.headerSchema\n ? parseWithErrorHandling(options.headerSchema, headerJson, 'Invalid header', JoseValidationError)\n : registeredHeader\n\n return { header: header as InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader> }\n}\n","import { type BaseSchema, type MarkOptional, parseWithErrorHandling } from '@owf/identity-common'\nimport type z from 'zod'\nimport type { SignJwsCallback } from '../callbacks'\nimport { JoseNotSupportedError, JoseValidationError } from '../error'\nimport type { Jwk } from '../jwk/z-jwk'\nimport { signCompactJws } from '../jws/sign-jws'\nimport type { JwsSigner } from '../jws/signer'\nimport type { InferSchemaOrDefaultOutput } from '../utils/zod'\nimport { type JwtHeader, zJwtHeader, zJwtPayload } from './z-jwt'\n\nexport interface SignJwtOptions<\n HeaderSchema extends BaseSchema | undefined,\n PayloadSchema extends BaseSchema | undefined,\n Signer extends JwsSigner = JwsSigner,\n> {\n /**\n * The header.\n *\n * Typed from `headerSchema` when one is given, with `alg` made optional: it is taken from the\n * signer, which is what says how the token is actually signed.\n *\n * The parameters that identify the key — `kid`, `jwk`, `x5c`, `trust_chain` — are not added: which\n * of them a token carries is decided by the token type, not by how the key happens to be\n * addressed. Spread {@link jwsHeaderFromSigner} into the header to add them.\n */\n header?: HeaderSchema extends BaseSchema ? MarkOptional<z.input<HeaderSchema>, 'alg'> : Record<string, unknown>\n\n /** The claims set. Typed from `payloadSchema` when one is given. */\n payload: PayloadSchema extends BaseSchema ? z.input<PayloadSchema> : Record<string, unknown>\n\n /**\n * Schema to validate the header with, on top of {@link zJwtHeader}, which is always applied.\n *\n * Pass the same schema the recipient verifies with, so that a token is checked against the profile\n * it is meant to satisfy before it is signed rather than after it is rejected.\n */\n headerSchema?: HeaderSchema\n\n /**\n * Schema to validate the claims set with, on top of {@link zJwtPayload}, which is always applied.\n */\n payloadSchema?: PayloadSchema\n\n /** The signer, which the callback resolves into a key. */\n signer: Signer\n\n /** Callback that produces the signature. */\n signJwsCallback: SignJwsCallback\n}\n\nexport interface SignJwtResult<\n HeaderSchema extends BaseSchema | undefined = undefined,\n PayloadSchema extends BaseSchema | undefined = undefined,\n> {\n /** The signed JWT in compact serialization. */\n jwt: string\n\n /** The public key the JWT was signed with, as reported by the callback. */\n signerJwk: Jwk\n\n /** The header that was signed. */\n header: InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>\n\n /** The claims set that was signed. */\n payload: InferSchemaOrDefaultOutput<PayloadSchema, typeof zJwtPayload>\n}\n\n/**\n * Signs a JWT.\n *\n * The header and the claims set are validated before they are signed, so that a token this library\n * produces is a token it would also accept. Passing the schemas of the token type being produced\n * extends that to the profile: a key binding JWT missing its `sd_hash` fails here rather than at the\n * verifier.\n *\n * What is signed is the validated value, so a schema that fills in a default or narrows a claim\n * shapes the token rather than being checked against it and then discarded. That value is validated\n * against the registered claims as well.\n *\n * @throws JoseValidationError if the header or the claims set is not valid.\n * @throws JoseNotSupportedError if the header sets `b64` to false, which is not valid for a JWT.\n */\nexport async function signJwt<\n HeaderSchema extends BaseSchema | undefined = undefined,\n PayloadSchema extends BaseSchema | undefined = undefined,\n Signer extends JwsSigner = JwsSigner,\n>(options: SignJwtOptions<HeaderSchema, PayloadSchema, Signer>): Promise<SignJwtResult<HeaderSchema, PayloadSchema>> {\n // `alg` is applied last: the signer is what says how the token is signed, so the header must not\n // be able to claim a different algorithm than the one actually used.\n const headerJson = { ...options.header, alg: options.signer.alg }\n\n // Always validated against the registered header parameters and claims, and only then against the\n // caller's schemas, the same way `decodeJwt` validates a token that is read.\n parseWithErrorHandling(zJwtHeader, headerJson, 'Unable to sign the JWT, invalid header', JoseValidationError)\n const header = parseWithErrorHandling(\n options.headerSchema ?? zJwtHeader,\n headerJson,\n 'Unable to sign the JWT, invalid header',\n JoseValidationError\n )\n\n // RFC 7519 defines the claims set as base64url encoded JSON, so a JWT with an unencoded payload\n // (RFC 7797) would be a token that `decodeJwt` rejects. The header that is signed is the one the\n // caller's schema returned, which `signCompactJws` validates as a JWS header.\n if ((header as JwtHeader).b64 === false) {\n throw new JoseNotSupportedError(\n `Unable to sign the JWT, its header sets 'b64' to false. An unencoded payload is not valid for a JWT.`\n )\n }\n\n parseWithErrorHandling(\n zJwtPayload,\n options.payload,\n 'Unable to sign the JWT, invalid claims set',\n JoseValidationError\n )\n const payload = parseWithErrorHandling(\n options.payloadSchema ?? zJwtPayload,\n options.payload,\n 'Unable to sign the JWT, invalid claims set',\n JoseValidationError\n )\n\n // What the caller's schema returned is what gets signed, so it is validated against the registered\n // claims too: a schema that transforms or fills in a registered claim must not be able to sign one\n // that `decodeJwt` would reject.\n parseWithErrorHandling(zJwtPayload, payload, 'Unable to sign the JWT, invalid claims set', JoseValidationError)\n\n const { compact, signerJwk } = await signCompactJws({\n protectedHeader: header,\n payload,\n signer: options.signer,\n signJwsCallback: options.signJwsCallback,\n })\n\n return {\n jwt: compact,\n signerJwk,\n header: header as InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>,\n payload: payload as InferSchemaOrDefaultOutput<PayloadSchema, typeof zJwtPayload>,\n }\n}\n","import { secondsToDate, ValidationIssues } from '@owf/identity-common'\nimport { JoseInvalidArgumentError, JoseValidationError, type JoseValidationIssue } from '../error'\nimport { hasOwn } from '../utils/object'\nimport type { JwtPayload } from './z-jwt'\n\n/**\n * The options {@link verifyJwtClaims} takes.\n *\n * These are the checks that cannot be expressed in a schema, because they compare the token against\n * something outside of it: the current time, the audience the verifier is, the nonce it issued.\n * Everything that follows from the token alone — which claims a token type requires, and what shape\n * they have — belongs in the payload schema instead.\n */\nexport interface VerifyJwtClaimsOptions {\n /** The time the token is verified at. Defaults to the current time. Must be a valid date. */\n now?: Date\n\n /**\n * Clock tolerance applied to `exp`, `nbf` and `iat`, in seconds. Defaults to 30, which keeps a\n * token that only just expired — or that was issued a moment ago by a slightly fast clock —\n * usable across the small clock differences typical between issuer and verifier.\n *\n * Must be a finite number of at least 0: anything else is rejected rather than letting a time\n * check pass that was never made.\n */\n skewSeconds?: number\n\n /**\n * The claims that must be present. A claim listed here is rejected when absent; a claim that is\n * absent and not listed is simply not checked.\n *\n * A claim whose value is `null` counts as present: `null` is a value the issuer put there, unlike\n * a claim that is not in the token at all.\n */\n requiredClaims?: ReadonlyArray<string>\n\n /**\n * The value(s) `iss` is accepted with.\n *\n * A token that does not carry the claim at all is rejected too: a claim that is absent does not\n * hold the value the caller said it expects.\n */\n expectedIssuer?: string | string[]\n\n /** The value(s) `sub` is accepted with. See {@link expectedIssuer} for an absent claim. */\n expectedSubject?: string | string[]\n\n /**\n * The value(s) `aud` is accepted with. The token is accepted when any of its audiences is one of\n * these. See {@link expectedIssuer} for an absent claim.\n */\n expectedAudience?: string | string[]\n\n /** The value `nonce` is accepted with. See {@link expectedIssuer} for an absent claim. */\n expectedNonce?: string\n\n /**\n * When false, `exp` is not looked at. Its presence is not checked either way — list it in\n * {@link requiredClaims} to require it.\n */\n checkExpirationTime?: boolean\n\n /** When false, `nbf` is not looked at. See {@link checkExpirationTime} for its presence. */\n checkNotBefore?: boolean\n\n /** When false, `iat` is not looked at. See {@link checkExpirationTime} for its presence. */\n checkIssuedAt?: boolean\n\n /**\n * The maximum age of the token in seconds, counted from `iat`. For a token that proves something\n * happened recently — a key binding JWT, a DPoP proof — rather than one that states its own\n * expiry.\n *\n * A token that carries no `iat` is rejected when this is set: a token that does not say when it\n * was issued cannot be shown to be recent. The skew applies, as it does to `exp`. Must be a finite\n * number of at least 0.\n */\n maxAgeSeconds?: number\n\n /** Message of the error thrown when a claim does not verify. */\n errorMessage?: string\n}\n\nconst asArray = (value: string | string[]) => (Array.isArray(value) ? value : [value])\nconst isNonNegativeFiniteNumber = (value: number) => Number.isFinite(value) && value >= 0\nconst quoted = (values: ReadonlyArray<string>) => values.map((value) => `'${value}'`).join(', ')\n\ntype ClaimIssues = ValidationIssues<JoseValidationIssue['code']>\n\n/**\n * Verifies the claims of a JWT: that the claims the caller requires are present, that `iss`, `sub`,\n * `aud` and `nonce` are the expected ones, and that the token is within its validity window.\n *\n * Which claims a JWT must carry, and what they must contain, is decided by the token type rather\n * than by RFC 7519, so nothing is required unless `requiredClaims` says so.\n *\n * This checks the claims only. The signature over them is verified separately — `verifyJwt` does\n * both, and is what a verifier wants.\n *\n * @throws JoseValidationError with an issue for each claim that does not verify: `claim_missing` for a\n * required claim that is absent, `claim_value_mismatch` for one that is not the expected value,\n * `expired` or `not_yet_valid` for a token outside its validity window, and `invalid_type` for a\n * time claim that is not a NumericDate.\n * @throws JoseInvalidArgumentError if `now` is not a valid date, or `skewSeconds` or `maxAgeSeconds`\n * is not a finite number of at least 0.\n */\nexport function verifyJwtClaims(\n payload: JwtPayload,\n {\n now = new Date(),\n skewSeconds = 30,\n requiredClaims,\n expectedIssuer,\n expectedSubject,\n expectedAudience,\n expectedNonce,\n checkExpirationTime = true,\n checkNotBefore = true,\n checkIssuedAt = true,\n maxAgeSeconds,\n errorMessage = 'Error during verification of the JWT claims.',\n }: VerifyJwtClaimsOptions = {}\n): void {\n // Every time check compares against `now` shifted by the skew. With `NaN` in either, every such\n // comparison is false, which accepts the token rather than rejecting it. A negative skew or maximum\n // age means nothing, and an infinite one accepts any token.\n if (!(now instanceof Date) || Number.isNaN(now.getTime())) {\n throw new JoseInvalidArgumentError(`${errorMessage} The 'now' option must be a valid date.`)\n }\n if (!isNonNegativeFiniteNumber(skewSeconds)) {\n throw new JoseInvalidArgumentError(\n `${errorMessage} The 'skewSeconds' option must be a finite number of at least 0, but is '${skewSeconds}'.`\n )\n }\n if (maxAgeSeconds !== undefined && !isNonNegativeFiniteNumber(maxAgeSeconds)) {\n throw new JoseInvalidArgumentError(\n `${errorMessage} The 'maxAgeSeconds' option must be a finite number of at least 0, but is '${maxAgeSeconds}'.`\n )\n }\n\n // The time claims are compared as numbers of seconds rather than as dates, so that a NumericDate\n // outside the range of a `Date` still orders: an `exp` of 9999999999999 does not expire.\n const nowSeconds = now.getTime() / 1000\n const issues: ClaimIssues = new ValidationIssues()\n\n for (const claim of requiredClaims ?? []) {\n if (!hasOwn(payload, claim)) addClaimMissing(issues, claim, `The token has no '${claim}' claim, which is required`)\n }\n\n verifyClaimMatches(issues, 'iss', payload.iss, expectedIssuer)\n verifyClaimMatches(issues, 'sub', payload.sub, expectedSubject)\n verifyClaimMatches(issues, 'nonce', payload.nonce, expectedNonce)\n verifyAudienceMatches(issues, payload.aud, expectedAudience)\n\n // Each time claim is read once, so a claim that is not a NumericDate gives one issue.\n const expirationTime = checkExpirationTime ? numericDate(issues, 'exp', payload.exp) : undefined\n const notBefore = checkNotBefore ? numericDate(issues, 'nbf', payload.nbf) : undefined\n const issuedAt = checkIssuedAt || maxAgeSeconds !== undefined ? numericDate(issues, 'iat', payload.iat) : undefined\n\n // `exp` is the first instant the token is no longer valid (RFC 7519 says a token must not be\n // accepted \"on or after\" it), so the comparison is inclusive. It is an upper bound shifted forward\n // by the skew: a token that expired within the tolerance is still accepted.\n if (expirationTime !== undefined && expirationTime + skewSeconds <= nowSeconds) {\n issues.add({\n code: 'expired',\n path: ['exp'],\n message: `The 'exp' claim '${formatNumericDate(expirationTime)}' is in the past (compared to '${now.toISOString()}')`,\n context: { expiredAt: secondsToDate(expirationTime) },\n })\n }\n\n if (notBefore !== undefined) verifyClaimNotInFuture(issues, 'nbf', notBefore, now, skewSeconds)\n if (checkIssuedAt && issuedAt !== undefined) verifyClaimNotInFuture(issues, 'iat', issuedAt, now, skewSeconds)\n\n if (maxAgeSeconds !== undefined) {\n if (payload.iat === undefined) {\n addClaimMissing(\n issues,\n 'iat',\n `The token has no 'iat' claim, which is required to verify that it is at most ${maxAgeSeconds} seconds old`\n )\n } else if (issuedAt !== undefined && issuedAt + maxAgeSeconds + skewSeconds < nowSeconds) {\n issues.add({\n code: 'expired',\n path: ['iat'],\n message: `The 'iat' claim '${formatNumericDate(issuedAt)}' is more than ${maxAgeSeconds} seconds in the past (compared to '${now.toISOString()}')`,\n context: { expiredAt: secondsToDate(issuedAt + maxAgeSeconds) },\n })\n }\n }\n\n if (issues.issues.length) throw new JoseValidationError(errorMessage, issues.issues)\n}\n\n/** A required claim is absent. A claim is reported once, however many checks need it. */\nfunction addClaimMissing(issues: ClaimIssues, claim: string, message: string): void {\n const reported = issues.issues.some((issue) => issue.code === 'claim_missing' && issue.path[0] === claim)\n if (!reported) issues.add({ code: 'claim_missing', path: [claim], message })\n}\n\n/**\n * The NumericDate a time claim holds, or `undefined` when the token does not carry the claim or it is\n * not a NumericDate.\n *\n * A claim that is present but is not a finite number gives an issue rather than being skipped: it\n * cannot be compared against `now` (with `NaN` every comparison would be false, which would accept\n * the token), and skipping it would accept a token whose validity window was never verified. A\n * payload parsed with `zJwtPayload` cannot get here, but one that reached the caller unvalidated can.\n *\n * Any finite number is a NumericDate, including one outside the range a `Date` can hold: it is\n * compared as a number of seconds.\n */\nfunction numericDate(issues: ClaimIssues, claim: string, value: unknown): number | undefined {\n if (value === undefined) return undefined\n\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n issues.add({\n code: 'invalid_type',\n path: [claim],\n message: `The '${claim}' claim '${String(value)}' is not a NumericDate`,\n context: { expected: 'number' },\n })\n return undefined\n }\n\n return value\n}\n\n/**\n * A NumericDate as it is printed in an issue: as a date where it has one, and as the number it is\n * where it is outside the range of a `Date`.\n */\nfunction formatNumericDate(seconds: number): string {\n const date = secondsToDate(seconds)\n return Number.isNaN(date.getTime()) ? String(seconds) : date.toISOString()\n}\n\nfunction verifyClaimMatches(\n issues: ClaimIssues,\n claim: string,\n value: unknown,\n expected: string | string[] | undefined\n): void {\n if (expected === undefined) return\n\n const expectedValues = asArray(expected)\n\n // An absent claim is a mismatch rather than something to skip: a token that does not say who\n // issued it is not a token issued by the expected issuer.\n if (value === undefined) {\n addClaimMissing(\n issues,\n claim,\n `The token has no '${claim}' claim, which is required to match the expected value ${quoted(expectedValues)}`\n )\n } else if (typeof value !== 'string' || !expectedValues.includes(value)) {\n issues.add({\n code: 'claim_value_mismatch',\n path: [claim],\n message: `The '${claim}' claim '${String(value)}' does not match the expected value ${quoted(expectedValues)}`,\n context: { expected: expectedValues, actual: value },\n })\n }\n}\n\n/** `aud` may hold several audiences, and the token is for us as soon as one of them is expected. */\nfunction verifyAudienceMatches(\n issues: ClaimIssues,\n audience: string | string[] | undefined,\n expected: string | string[] | undefined\n): void {\n if (expected === undefined) return\n\n const expectedValues = asArray(expected)\n\n // See `verifyClaimMatches`: a token carrying no audience is not a token for this audience.\n if (audience === undefined) {\n addClaimMissing(\n issues,\n 'aud',\n `The token has no 'aud' claim, which is required to match the expected value ${quoted(expectedValues)}`\n )\n return\n }\n\n const audiences = asArray(audience)\n\n if (!audiences.some((value) => expectedValues.includes(value))) {\n issues.add({\n code: 'claim_value_mismatch',\n path: ['aud'],\n message: `The 'aud' claim ${quoted(audiences)} does not match the expected value ${quoted(expectedValues)}`,\n context: { expected: expectedValues, actual: audience },\n })\n }\n}\n\n/**\n * `nbf` and `iat` are lower bounds on the validity window, so they are shifted back by the skew: a\n * token whose validity starts within the tolerance is already accepted.\n */\nfunction verifyClaimNotInFuture(\n issues: ClaimIssues,\n claim: string,\n seconds: number,\n now: Date,\n skewSeconds: number\n): void {\n if (seconds - skewSeconds > now.getTime() / 1000) {\n issues.add({\n code: 'not_yet_valid',\n path: [claim],\n message: `The '${claim}' claim '${formatNumericDate(seconds)}' is in the future (compared to '${now.toISOString()}')`,\n context: { validFrom: secondsToDate(seconds) },\n })\n }\n}\n","import { type BaseSchema, parseWithErrorHandling } from '@owf/identity-common'\nimport type { VerifyJwsCallback } from '../callbacks'\nimport { JoseValidationError } from '../error'\nimport type { JwsSigner, JwsSignerMethod, JwsSignerWithJwk } from '../jws/signer'\nimport { verifyJwsSignature } from '../jws/verify-jws'\nimport type { InferSchemaOrDefaultOutput } from '../utils/zod'\nimport { type DecodeJwtResult, decodeJwt } from './decode-jwt'\nimport { type VerifyJwtClaimsOptions, verifyJwtClaims } from './verify-jwt-claims'\nimport { type JwtPayload, type zJwtHeader, zJwtPayload } from './z-jwt'\n\nexport interface VerifyJwtOptions<\n HeaderSchema extends BaseSchema | undefined,\n PayloadSchema extends BaseSchema | undefined,\n> extends VerifyJwtClaimsOptions {\n /**\n * The JWT to verify: the compact serialization, or the result of a previous {@link decodeJwt} when\n * the caller had to look at the token before it could decide how to verify it.\n */\n jwt: string | DecodeJwtResult<HeaderSchema, PayloadSchema>\n\n /** Callback that verifies the signature and decides whether the key is trusted. */\n verifyJwsCallback: VerifyJwsCallback\n\n /**\n * Schema to validate the header with, see {@link decodeJwt}. Only used when `jwt` is a compact JWT.\n *\n * What it returns is the `header` that is returned, but the checks are made on the header as\n * validated against `zJwtHeader`, which the schema cannot change.\n */\n headerSchema?: HeaderSchema\n\n /**\n * Schema to validate the payload with, see {@link decodeJwt}. Only used when `jwt` is a compact JWT.\n *\n * What it returns is the `payload` that is returned, but the claims are verified as validated\n * against `zJwtPayload`, which the schema cannot change.\n */\n payloadSchema?: PayloadSchema\n\n /** The signer to verify against. Established from the header when not provided. */\n signer?: JwsSigner\n\n /** The signer methods the caller accepts. */\n allowedSignerMethods?: ReadonlyArray<JwsSignerMethod>\n\n /** Whether a header may identify the signer in more than one way, see `verifyJwsSignature`. */\n allowMultipleSignerMethods?: boolean\n\n /**\n * Whether a `kid` whose DID is not the `iss` is accepted for a did signer. Needed for\n * `openid4vci-proof+jwt`, where `iss` is the client id rather than the did.\n *\n * @default false\n */\n allowDidKidIssuerMismatch?: boolean\n\n /** The algorithms the caller accepts, see `verifyJwsSignature`. */\n allowedAlgorithms?: ReadonlyArray<string>\n\n /** Whether a symmetric signature algorithm is acceptable, see `verifyJwsSignature`. */\n allowSymmetricAlgorithms?: boolean\n\n /** The critical header parameters the caller understands. */\n understoodCriticalParameters?: ReadonlyArray<string>\n}\n\nexport interface VerifyJwtResult<\n HeaderSchema extends BaseSchema | undefined = undefined,\n PayloadSchema extends BaseSchema | undefined = undefined,\n> {\n header: InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>\n payload: InferSchemaOrDefaultOutput<PayloadSchema, typeof zJwtPayload>\n\n /** The signer, with the public key the signature was verified with. */\n signer: JwsSignerWithJwk\n\n /** The compact JWT that was verified. */\n compact: string\n}\n\n/**\n * Verifies a JWT completely: the signature over it, and then the claims in it.\n *\n * The signature is verified first, since the claims of a token whose signer has not been established\n * say nothing about anything.\n *\n * @throws JoseParseError or JoseValidationError if the token is not a valid JWT.\n * @throws JoseAlgorithmNotAllowedError if the algorithm is not accepted, or does not match the key.\n * @throws JoseSignatureVerificationError if the signature does not verify.\n * @throws JoseValidationError with an issue for each claim that does not verify, see `verifyJwtClaims`.\n * @throws JoseInvalidArgumentError if `now`, `skewSeconds` or `maxAgeSeconds` cannot be used to\n * verify the claims.\n */\nexport async function verifyJwt<\n HeaderSchema extends BaseSchema | undefined = undefined,\n PayloadSchema extends BaseSchema | undefined = undefined,\n>(options: VerifyJwtOptions<HeaderSchema, PayloadSchema>): Promise<VerifyJwtResult<HeaderSchema, PayloadSchema>> {\n const decoded =\n typeof options.jwt === 'string'\n ? decodeJwt({\n jwt: options.jwt,\n headerSchema: options.headerSchema,\n payloadSchema: options.payloadSchema,\n understoodCriticalParameters: options.understoodCriticalParameters,\n })\n : options.jwt\n\n const header = decoded.header as InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>\n const payload = decoded.payload as InferSchemaOrDefaultOutput<PayloadSchema, typeof zJwtPayload>\n\n // Every check is made on the header and claims as validated against the registered schemas, not on\n // what the caller's schemas made of them, which may have dropped `alg` or `exp`, or filled in `iat`.\n // A decoded JWT that was put together without `decodeJwt` does not come with them, so its own\n // header and claims are validated instead.\n const registeredPayload: JwtPayload =\n decoded.registeredPayload ??\n parseWithErrorHandling(zJwtPayload, decoded.payload, 'Invalid JWT payload', JoseValidationError)\n\n const { signer } = await verifyJwsSignature({\n jws: {\n protectedHeader: header,\n registeredProtectedHeader: decoded.registeredHeader,\n signingInput: decoded.signingInput,\n signature: decoded.signature,\n // The claims set as bytes, which is the payload of the JWS that the JWT is.\n payload: decoded.payloadBytes,\n compact: decoded.compact,\n },\n jwtPayload: registeredPayload,\n verifyJwsCallback: options.verifyJwsCallback,\n signer: options.signer,\n allowedSignerMethods: options.allowedSignerMethods,\n allowMultipleSignerMethods: options.allowMultipleSignerMethods,\n allowDidKidIssuerMismatch: options.allowDidKidIssuerMismatch,\n allowedAlgorithms: options.allowedAlgorithms,\n allowSymmetricAlgorithms: options.allowSymmetricAlgorithms,\n errorMessage: options.errorMessage ?? 'Error during verification of the JWT.',\n })\n\n verifyJwtClaims(registeredPayload, options)\n\n return { header, payload, signer, compact: decoded.compact }\n}\n"],"mappings":";;;;;;;AAYA,IAAa,YAAb,cAA+B,cAAc;CAG3C,YAAY,SAAiB,SAAkD;EAC7E,MAAM,SAAS,SAAS,OAAO;E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AAQ,SAAS,uBAAuB,mBAAmB;CAEjG,MAAM,EAAE,WAAW,MAAM,mBAAmB;EAC1C,KAAK;GACH,iBAAiB;GACjB,2BAA2B,QAAQ;GACnC,cAAc,QAAQ;GACtB,WAAW,QAAQ;GAEnB,SAAS,QAAQ;GACjB,SAAS,QAAQ;EACnB;EACA,YAAY;EACZ,mBAAmB,QAAQ;EAC3B,QAAQ,QAAQ;EAChB,sBAAsB,QAAQ;EAC9B,4BAA4B,QAAQ;EACpC,2BAA2B,QAAQ;EACnC,mBAAmB,QAAQ;EAC3B,0BAA0B,QAAQ;EAClC,cAAc,QAAQ,gBAAgB;CACxC,CAAC;CAED,gBAAgB,mBAAmB,OAAO;CAE1C,OAAO;EAAE;EAAQ;EAAS;EAAQ,SAAS,QAAQ;CAAQ;AAC7D"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/error.ts","../src/jwa/algorithms.ts","../src/utils/object.ts","../src/jwa/cose-algorithm.ts","../src/jwa/key-compatibility.ts","../src/jwa/z-alg.ts","../src/jwk/z-x5c.ts","../src/jwk/z-jwk.ts","../src/utils/z-common.ts","../src/jws/z-jws.ts","../src/jwe/z-jwe.ts","../src/jwk/thumbprint.ts","../src/jwk/jwks.ts","../src/jws/critical-headers.ts","../src/utils/encoding.ts","../src/jws/parse-jws.ts","../src/jws/signer.ts","../src/jws/signer-header.ts","../src/jws/sign-jws.ts","../src/jws/verify-jws.ts","../src/jwt/z-jwt.ts","../src/jwt/decode-jwt.ts","../src/jwt/sign-jwt.ts","../src/jwt/verify-jwt-claims.ts","../src/jwt/verify-jwt.ts"],"sourcesContent":["import {\n type CommonValidationCode,\n IdentityError,\n type SchemaValidationCode,\n ValidationError,\n type ValidationIssueOf,\n} from '@owf/identity-common'\n\n/**\n * Base error class for `@owf/jose`. `cause` is declared here, as `Error.cause` is ES2022 and the\n * project targets ES2020.\n */\nexport class JoseError extends IdentityError {\n public readonly cause?: unknown\n\n constructor(message: string, options?: { cause?: unknown; details?: unknown }) {\n super(message, options?.details)\n\n this.cause = options?.cause\n }\n}\n\n/**\n * A token is not well-formed: a wrong structure, or a part that is not valid base64url, UTF-8 or\n * JSON. The message never includes the input, so a token is not logged by accident.\n */\nexport class JoseParseError extends JoseError {}\n\n/** An issue of a JOSE structure that does not validate, with a schema or common code */\nexport type JoseValidationIssue = ValidationIssueOf<CommonValidationCode | SchemaValidationCode>\n\n/**\n * A structure is well-formed but does not validate: its schema, `crit` or claims. Like the validation\n * errors of the other packages, it extends `ValidationError`, not {@link JoseError}.\n */\nexport class JoseValidationError extends ValidationError<JoseValidationIssue> {}\n\n/**\n * A token is well-formed but does not verify: its signature, signer or algorithm. The subclasses say\n * which. Claims that do not verify throw a {@link JoseValidationError}.\n */\nexport class JoseVerificationError extends JoseError {}\n\n/** The signature over a JWS does not verify, or the verification callback rejected it. */\nexport class JoseSignatureVerificationError extends JoseVerificationError {}\n\n/** The `alg` of a token is not among the algorithms the caller allows. */\nexport class JoseAlgorithmNotAllowedError extends JoseVerificationError {}\n\n/** The key that identifies the signer cannot be determined from the token, or is ambiguous. */\nexport class JoseSignerError extends JoseVerificationError {}\n\n/** The token uses a feature that this library does not implement. */\nexport class JoseNotSupportedError extends JoseError {}\n\n/**\n * A mistake in the calling code, not in a token: an invalid or contradicting option, or a signing\n * callback result that breaks the contract of the callback.\n */\nexport class JoseInvalidArgumentError extends JoseError {}\n","/**\n * JWA (JSON Web Algorithms) identifiers.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7518\n * @see https://www.iana.org/assignments/jose/jose.xhtml\n */\n\n/**\n * JWS signature and MAC algorithms. `none` is absent: an unsecured JWS is never accepted.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7518#section-3.1\n * @see https://www.rfc-editor.org/rfc/rfc9864 for the fully-specified EdDSA algorithms\n */\nexport enum JwaSignatureAlgorithm {\n // HMAC with SHA-2\n HS256 = 'HS256',\n HS384 = 'HS384',\n HS512 = 'HS512',\n\n // RSASSA-PKCS1-v1_5 with SHA-2\n RS256 = 'RS256',\n RS384 = 'RS384',\n RS512 = 'RS512',\n\n // RSASSA-PSS with SHA-2\n PS256 = 'PS256',\n PS384 = 'PS384',\n PS512 = 'PS512',\n\n // ECDSA\n ES256 = 'ES256',\n ES384 = 'ES384',\n ES512 = 'ES512',\n ES256K = 'ES256K',\n\n // EdDSA. `EdDSA` is polymorphic and deprecated by RFC 9864 in favour of the curve-specific names.\n EdDSA = 'EdDSA',\n Ed25519 = 'Ed25519',\n Ed448 = 'Ed448',\n}\n\n/** The signature algorithms with a symmetric key, with which every verifier can also issue a token. */\nexport const symmetricSignatureAlgorithms = [\n JwaSignatureAlgorithm.HS256,\n JwaSignatureAlgorithm.HS384,\n JwaSignatureAlgorithm.HS512,\n] as const satisfies ReadonlyArray<JwaSignatureAlgorithm>\n\n/**\n * JWE key management algorithms.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7518#section-4.1\n */\nexport enum JwaKeyManagementAlgorithm {\n RSA1_5 = 'RSA1_5',\n RSA_OAEP = 'RSA-OAEP',\n RSA_OAEP_256 = 'RSA-OAEP-256',\n A128KW = 'A128KW',\n A192KW = 'A192KW',\n A256KW = 'A256KW',\n Dir = 'dir',\n ECDH_ES = 'ECDH-ES',\n ECDH_ES_A128KW = 'ECDH-ES+A128KW',\n ECDH_ES_A192KW = 'ECDH-ES+A192KW',\n ECDH_ES_A256KW = 'ECDH-ES+A256KW',\n A128GCMKW = 'A128GCMKW',\n A192GCMKW = 'A192GCMKW',\n A256GCMKW = 'A256GCMKW',\n}\n\n/**\n * JWE content encryption algorithms.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7518#section-5.1\n */\nexport enum JwaContentEncryptionAlgorithm {\n A128CBC_HS256 = 'A128CBC-HS256',\n A192CBC_HS384 = 'A192CBC-HS384',\n A256CBC_HS512 = 'A256CBC-HS512',\n A128GCM = 'A128GCM',\n A192GCM = 'A192GCM',\n A256GCM = 'A256GCM',\n}\n\n/**\n * The key types (`kty`) a signature algorithm can be used with. Checking it prevents key confusion,\n * such as `HS256` with an RSA public key as the MAC secret.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7518#section-3.1\n * @see https://www.rfc-editor.org/rfc/rfc8725#section-3.5\n */\nexport const signatureAlgorithmKeyTypes: Record<JwaSignatureAlgorithm, ReadonlyArray<string>> = {\n [JwaSignatureAlgorithm.HS256]: ['oct'],\n [JwaSignatureAlgorithm.HS384]: ['oct'],\n [JwaSignatureAlgorithm.HS512]: ['oct'],\n\n [JwaSignatureAlgorithm.RS256]: ['RSA'],\n [JwaSignatureAlgorithm.RS384]: ['RSA'],\n [JwaSignatureAlgorithm.RS512]: ['RSA'],\n [JwaSignatureAlgorithm.PS256]: ['RSA'],\n [JwaSignatureAlgorithm.PS384]: ['RSA'],\n [JwaSignatureAlgorithm.PS512]: ['RSA'],\n\n [JwaSignatureAlgorithm.ES256]: ['EC'],\n [JwaSignatureAlgorithm.ES384]: ['EC'],\n [JwaSignatureAlgorithm.ES512]: ['EC'],\n [JwaSignatureAlgorithm.ES256K]: ['EC'],\n\n [JwaSignatureAlgorithm.EdDSA]: ['OKP'],\n [JwaSignatureAlgorithm.Ed25519]: ['OKP'],\n [JwaSignatureAlgorithm.Ed448]: ['OKP'],\n}\n\n/**\n * The curve (`crv`) of the signature algorithms that fully specify one. `EdDSA` is polymorphic.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7518#section-3.4\n * @see https://www.rfc-editor.org/rfc/rfc9864#section-2\n */\nexport const signatureAlgorithmCurves: Partial<Record<JwaSignatureAlgorithm, string>> = {\n [JwaSignatureAlgorithm.ES256]: 'P-256',\n [JwaSignatureAlgorithm.ES384]: 'P-384',\n [JwaSignatureAlgorithm.ES512]: 'P-521',\n [JwaSignatureAlgorithm.ES256K]: 'secp256k1',\n [JwaSignatureAlgorithm.Ed25519]: 'Ed25519',\n [JwaSignatureAlgorithm.Ed448]: 'Ed448',\n}\n\nexport const isJwaSignatureAlgorithm = (alg: string): alg is JwaSignatureAlgorithm =>\n Object.values(JwaSignatureAlgorithm).includes(alg as JwaSignatureAlgorithm)\n\nexport const isSymmetricSignatureAlgorithm = (alg: string): boolean =>\n symmetricSignatureAlgorithms.includes(alg as (typeof symmetricSignatureAlgorithms)[number])\n\n/**\n * Whether `alg` is a registered signature algorithm in a different casing, such as `hs256`. None of\n * the checks here recognize it, but a case-insensitive comparison downstream could verify it as the\n * registered one. Both casings are compared, as they differ outside ASCII: `ſ` upper cases to `S`.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.1\n */\nexport const isJwaSignatureAlgorithmCaseVariant = (alg: string): boolean =>\n typeof alg === 'string' &&\n !isJwaSignatureAlgorithm(alg) &&\n Object.values(JwaSignatureAlgorithm).some(\n (registered) => registered.toLowerCase() === alg.toLowerCase() || registered.toUpperCase() === alg.toUpperCase()\n )\n","/** Whether `key` is an own property of `object`, so `constructor` or `toString` are not found everywhere. */\nexport const hasOwn = (object: object, key: PropertyKey): boolean =>\n // biome-ignore lint/suspicious/noPrototypeBuiltins: `Object.hasOwn` is not in the ES2020 lib this package targets\n Object.prototype.hasOwnProperty.call(object, key)\n\n/**\n * Whether two JSON values are the same value: arrays holding the same values in the same order, and\n * objects with the same members, in whatever order. A member set to `undefined` counts as absent, as\n * it is once serialized.\n */\nexport function isSameJsonValue(a: unknown, b: unknown): boolean {\n if (Array.isArray(a) || Array.isArray(b)) {\n return (\n Array.isArray(a) &&\n Array.isArray(b) &&\n a.length === b.length &&\n a.every((value, index) => isSameJsonValue(value, b[index]))\n )\n }\n\n if (typeof a === 'object' && a !== null && typeof b === 'object' && b !== null) {\n const membersOf = (object: object) =>\n Object.keys(object).filter((member) => (object as Record<string, unknown>)[member] !== undefined)\n const membersOfA = membersOf(a)\n\n return (\n membersOfA.length === membersOf(b).length &&\n membersOfA.every(\n (member) =>\n hasOwn(b, member) &&\n isSameJsonValue((a as Record<string, unknown>)[member], (b as Record<string, unknown>)[member])\n )\n )\n }\n\n return a === b\n}\n","/**\n * Mapping between JWA and COSE algorithm identifiers. COSE identifiers are integers, so no dependency\n * on `@owf/cose` is needed.\n *\n * @see https://www.rfc-editor.org/rfc/rfc9864 Fully-Specified Algorithms for JOSE and COSE\n */\n\nimport { JoseNotSupportedError } from '../error'\nimport { hasOwn } from '../utils/object'\nimport { JwaSignatureAlgorithm } from './algorithms'\n\n/**\n * JWA signature algorithms to fully-specified COSE algorithms. The JOSE `ES256` is fully specified, so\n * it maps to `ESP256` (-9), not to the polymorphic COSE `ES256` (-7).\n */\nconst JWA_SIGNATURE_TO_COSE_ALGORITHM_MAP = {\n // EdDSA - RFC 9864 Section 2.2\n [JwaSignatureAlgorithm.Ed25519]: -19,\n [JwaSignatureAlgorithm.Ed448]: -53,\n\n // Deprecated polymorphic EdDSA - RFC 9864 Section 4.1.2.\n // Mapped to Ed25519 as it is by far the most common use case, as WebAuthn does.\n [JwaSignatureAlgorithm.EdDSA]: -19,\n\n // ECDSA - RFC 9864 Section 2.1\n [JwaSignatureAlgorithm.ES256]: -9, // ESP256\n [JwaSignatureAlgorithm.ES384]: -51, // ESP384\n [JwaSignatureAlgorithm.ES512]: -52, // ESP512\n [JwaSignatureAlgorithm.ES256K]: -47,\n\n // RSA - RFC 8812 and RFC 8230\n [JwaSignatureAlgorithm.RS256]: -257,\n [JwaSignatureAlgorithm.RS384]: -258,\n [JwaSignatureAlgorithm.RS512]: -259,\n [JwaSignatureAlgorithm.PS256]: -37,\n [JwaSignatureAlgorithm.PS384]: -38,\n [JwaSignatureAlgorithm.PS512]: -39,\n\n // HMAC - RFC 9053 Section 3.1\n [JwaSignatureAlgorithm.HS256]: 5,\n [JwaSignatureAlgorithm.HS384]: 6,\n [JwaSignatureAlgorithm.HS512]: 7,\n} as const\n\n/** The inverse of {@link JWA_SIGNATURE_TO_COSE_ALGORITHM_MAP}, plus the deprecated polymorphic COSE algorithms. */\nconst COSE_TO_JWA_SIGNATURE_ALGORITHM_MAP = {\n // EdDSA - RFC 9864 Section 2.2\n [-19]: JwaSignatureAlgorithm.Ed25519,\n [-53]: JwaSignatureAlgorithm.Ed448,\n\n // Deprecated polymorphic EdDSA - RFC 9864 Section 4.1.2 & 4.2.2\n [-8]: JwaSignatureAlgorithm.Ed25519,\n\n // ECDSA, fully specified - RFC 9864 Section 2.1\n [-9]: JwaSignatureAlgorithm.ES256, // ESP256\n [-51]: JwaSignatureAlgorithm.ES384, // ESP384\n [-52]: JwaSignatureAlgorithm.ES512, // ESP512\n [-47]: JwaSignatureAlgorithm.ES256K,\n\n // Deprecated polymorphic COSE ECDSA - RFC 9864 Section 4.2.2\n [-7]: JwaSignatureAlgorithm.ES256,\n [-35]: JwaSignatureAlgorithm.ES384,\n [-36]: JwaSignatureAlgorithm.ES512,\n\n // RSA\n [-257]: JwaSignatureAlgorithm.RS256,\n [-258]: JwaSignatureAlgorithm.RS384,\n [-259]: JwaSignatureAlgorithm.RS512,\n [-37]: JwaSignatureAlgorithm.PS256,\n [-38]: JwaSignatureAlgorithm.PS384,\n [-39]: JwaSignatureAlgorithm.PS512,\n\n // HMAC\n 5: JwaSignatureAlgorithm.HS256,\n 6: JwaSignatureAlgorithm.HS384,\n 7: JwaSignatureAlgorithm.HS512,\n} as const\n\nexport type CoseAlgorithmIdentifier = keyof typeof COSE_TO_JWA_SIGNATURE_ALGORITHM_MAP\nexport type JwaSignatureAlgorithmIdentifier = `${JwaSignatureAlgorithm}`\n\n/**\n * Transforms a JWA signature algorithm identifier into an RFC 9864 fully-specified COSE algorithm\n * identifier, or `undefined` when it has no COSE counterpart.\n *\n * @example\n * ```ts\n * jwaSignatureAlgorithmToCoseAlgorithm('ES256') // -9 (ESP256)\n * ```\n */\nexport function jwaSignatureAlgorithmToCoseAlgorithm(jwaAlg: string): CoseAlgorithmIdentifier | undefined {\n // An own property only, so `constructor` from metadata does not resolve to `Object.prototype`\n return hasOwn(JWA_SIGNATURE_TO_COSE_ALGORITHM_MAP, jwaAlg)\n ? JWA_SIGNATURE_TO_COSE_ALGORITHM_MAP[jwaAlg as JwaSignatureAlgorithm]\n : undefined\n}\n\n/**\n * Transforms a COSE algorithm identifier — fully specified or polymorphic — into a JWA signature\n * algorithm identifier, or `undefined` when it has no JWA counterpart.\n *\n * @example\n * ```ts\n * coseAlgorithmToJwaSignatureAlgorithm(-7) // 'ES256' (from the deprecated polymorphic COSE ES256)\n * ```\n */\nexport function coseAlgorithmToJwaSignatureAlgorithm(coseAlg: number): JwaSignatureAlgorithmIdentifier | undefined {\n return hasOwn(COSE_TO_JWA_SIGNATURE_ALGORITHM_MAP, coseAlg)\n ? COSE_TO_JWA_SIGNATURE_ALGORITHM_MAP[coseAlg as CoseAlgorithmIdentifier]\n : undefined\n}\n\n/**\n * Transforms JWA signature algorithm identifiers into fully-specified COSE algorithm identifiers,\n * dropping the ones that have no COSE counterpart, or throwing when `throwOnUnknownValue` is set.\n */\nexport function jwaSignatureAlgorithmsToCoseAlgorithms(\n jwaAlgs: ReadonlyArray<string>,\n throwOnUnknownValue = false\n): CoseAlgorithmIdentifier[] {\n return jwaAlgs\n .map((jwaAlg) => {\n const coseAlg = jwaSignatureAlgorithmToCoseAlgorithm(jwaAlg)\n if (coseAlg || !throwOnUnknownValue) return coseAlg\n throw new JoseNotSupportedError(`Found unknown JWA signature algorithm '${jwaAlg}'. Unable to map to COSE.`)\n })\n .filter((coseAlg): coseAlg is CoseAlgorithmIdentifier => coseAlg !== undefined)\n}\n\n/**\n * Transforms COSE algorithm identifiers into JWA signature algorithm identifiers, dropping the ones\n * that have no JWA counterpart, or throwing when `throwOnUnknownValue` is set.\n */\nexport function coseAlgorithmsToJwaSignatureAlgorithms(\n coseAlgs: ReadonlyArray<number>,\n throwOnUnknownValue = false\n): JwaSignatureAlgorithmIdentifier[] {\n return coseAlgs\n .map((coseAlg) => {\n const jwaAlg = coseAlgorithmToJwaSignatureAlgorithm(coseAlg)\n if (jwaAlg || !throwOnUnknownValue) return jwaAlg\n throw new JoseNotSupportedError(`Found unknown COSE algorithm identifier '${coseAlg}'. Unable to map to JWA.`)\n })\n .filter((jwaAlg): jwaAlg is JwaSignatureAlgorithmIdentifier => jwaAlg !== undefined)\n}\n","import { JoseAlgorithmNotAllowedError } from '../error'\nimport type { Jwk } from '../jwk/z-jwk'\nimport {\n isJwaSignatureAlgorithm,\n isJwaSignatureAlgorithmCaseVariant,\n JwaSignatureAlgorithm,\n signatureAlgorithmCurves,\n signatureAlgorithmKeyTypes,\n} from './algorithms'\n\n/** `EdDSA` with the curve fixed (RFC 9864 section 2.2). */\nconst fullySpecifiedEdDsaAlgorithms: ReadonlyArray<string> = [\n JwaSignatureAlgorithm.Ed25519,\n JwaSignatureAlgorithm.Ed448,\n]\n\n/** The curves of `EdDSA` (RFC 8037 section 3.1). `X25519` and `X448` are for key agreement. */\nconst edDsaCurves: ReadonlyArray<string> = ['Ed25519', 'Ed448']\n\n/**\n * Checks that a key can be used with a signature algorithm, as the token chooses its `alg` but not the\n * key: the key type (no key confusion), the curve where the algorithm fixes one, and the `alg`, `use`\n * and `key_ops` the key declares. `EdDSA` and `Ed25519`/`Ed448` (RFC 9864) count as the same `alg`.\n * An unregistered algorithm is left to the verification callback, but one that differs from a\n * registered algorithm only in casing is rejected.\n *\n * @throws JoseAlgorithmNotAllowedError when the key cannot be used with the algorithm.\n */\nexport function assertKeyAllowedForSignatureAlgorithm({\n jwk,\n alg,\n errorMessage = 'Unable to use the key with the algorithm of the token.',\n}: {\n jwk: Jwk\n alg: string\n errorMessage?: string\n}): void {\n const isEdDsaEquivalent =\n (jwk.alg === JwaSignatureAlgorithm.EdDSA && fullySpecifiedEdDsaAlgorithms.includes(alg)) ||\n (alg === JwaSignatureAlgorithm.EdDSA && jwk.alg !== undefined && fullySpecifiedEdDsaAlgorithms.includes(jwk.alg))\n\n if (jwk.alg !== undefined && jwk.alg !== alg && !isEdDsaEquivalent) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} The key declares alg '${jwk.alg}', but the token uses alg '${alg}'.`\n )\n }\n\n if (jwk.use !== undefined && jwk.use !== 'sig') {\n throw new JoseAlgorithmNotAllowedError(`${errorMessage} The key declares use '${jwk.use}' instead of 'sig'.`)\n }\n\n if (jwk.key_ops !== undefined && !jwk.key_ops.includes('verify') && !jwk.key_ops.includes('sign')) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} The key declares key_ops ${jwk.key_ops.map((op) => `'${op}'`).join(', ')}, which does not include 'sign' or 'verify'.`\n )\n }\n\n if (isJwaSignatureAlgorithmCaseVariant(alg)) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} The token uses alg '${alg}', which differs from a registered algorithm only in casing.`\n )\n }\n\n if (!isJwaSignatureAlgorithm(alg)) return\n\n // For a token that only says `EdDSA`, the fully specified algorithm the key declares fixes the curve\n const keyAlgorithm =\n isEdDsaEquivalent && alg === JwaSignatureAlgorithm.EdDSA ? (jwk.alg as JwaSignatureAlgorithm) : alg\n\n const keyTypes = signatureAlgorithmKeyTypes[keyAlgorithm]\n if (!keyTypes.includes(jwk.kty)) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} Algorithm '${keyAlgorithm}' requires a key with kty ${keyTypes.map((kty) => `'${kty}'`).join(' or ')}, but the key has kty '${jwk.kty}'.`\n )\n }\n\n const curve = signatureAlgorithmCurves[keyAlgorithm]\n const curves = curve !== undefined ? [curve] : keyAlgorithm === JwaSignatureAlgorithm.EdDSA ? edDsaCurves : []\n if (curves.length > 0 && (jwk.crv === undefined || !curves.includes(jwk.crv))) {\n throw new JoseAlgorithmNotAllowedError(\n `${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'}.`\n )\n }\n}\n","import { addValidationIssue, zNonEmptyString } from '@owf/identity-common'\n\n/**\n * A JWS `alg`. The registry is open and the allowed algorithms are checked at verification, so any\n * value is accepted except `none`, in any casing.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.1\n * @see https://www.rfc-editor.org/rfc/rfc8725#section-3.2\n */\nexport const zJwsAlg = zNonEmptyString.superRefine((alg, ctx) => {\n if (alg.toLowerCase() === 'none') {\n addValidationIssue(ctx, { code: 'invalid_value', message: `alg value may not be 'none'` })\n }\n})\n\n/**\n * A JWE `alg` (key management algorithm) value. `none` is not one (RFC 7518 Section 4.1), so it is\n * rejected in any casing, as for a JWS.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7516#section-4.1.1\n */\nexport const zJweAlg = zJwsAlg\n\n/** A JWE `enc` (content encryption algorithm) value. @see https://www.rfc-editor.org/rfc/rfc7516#section-4.1.2 */\nexport const zJweEnc = zNonEmptyString\n","import { addValidationIssue, base64 } from '@owf/identity-common'\nimport z from 'zod'\n\n/** The identifier octet of a DER SEQUENCE, which is what a certificate is encoded as. */\nconst DER_SEQUENCE_TAG = 0x30\n\n/**\n * Why `bytes` are not exactly one DER SEQUENCE with a minimal definite length (X.690 section 10.1), or\n * `undefined`. A certificate is far below 2^32 bytes, so a longer length encoding is rejected.\n */\nfunction derSequenceIssue(bytes: Uint8Array): string | undefined {\n if (bytes[0] !== DER_SEQUENCE_TAG) return 'they do not start with the SEQUENCE tag (0x30)'\n if (bytes.length < 2) return 'they end after the tag, without a length'\n\n let length = bytes[1]\n let contentStart = 2\n\n // The long form: the low 7 bits say how many bytes the length takes\n if (length >= 0x80) {\n const lengthSize = length & 0x7f\n if (lengthSize === 0) return 'the length is indefinite (0x80), which DER does not allow'\n if (lengthSize > 4) return 'the length is encoded in more than 4 bytes'\n if (bytes.length < 2 + lengthSize) return 'they end inside the length'\n\n length = 0\n for (let index = 2; index < 2 + lengthSize; index++) length = length * 256 + bytes[index]\n\n // DER: no leading zero byte, and the short form below 128\n if (bytes[2] === 0 || length < 0x80) return 'the length is not minimally encoded, as DER requires'\n\n contentStart = 2 + lengthSize\n }\n\n const available = bytes.length - contentStart\n if (length > available) {\n return `the SEQUENCE is truncated: its length is ${length} byte(s), but only ${available} byte(s) follow`\n }\n if (length < available) return `${available - length} byte(s) follow the SEQUENCE`\n\n return undefined\n}\n\n/**\n * One `x5c` certificate: standard base64 (RFC 4648 section 4, not base64url) of one DER SEQUENCE. The\n * certificate is not parsed: the `VerifyJwsCallback` validates the chain.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.6\n * @see https://www.rfc-editor.org/rfc/rfc7517#section-4.7\n */\nexport const zX5cCertificate = z\n .base64({ message: 'Expected a certificate in standard base64 (RFC 4648 section 4)' })\n .superRefine((value, ctx) => {\n // zod runs the refinement also when the value is not base64\n if (!z.core.regexes.base64.test(value)) return\n\n const derIssue = derSequenceIssue(base64.decode(value))\n if (derIssue) {\n addValidationIssue(ctx, {\n code: 'invalid_format',\n message: `Expected a DER encoded certificate, but the decoded bytes are not a single DER SEQUENCE: ${derIssue}`,\n context: { format: 'der' },\n })\n }\n })\n\n/**\n * The `x5c` of a JWS header, JWE header or JWK: one or more certificates, the one holding the key first.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.6\n * @see https://www.rfc-editor.org/rfc/rfc7516#section-4.1.7\n * @see https://www.rfc-editor.org/rfc/rfc7517#section-4.7\n */\nexport const zX5c = z\n .array(zX5cCertificate)\n .min(1, { message: 'Expected a certificate chain of at least one certificate' })\n","import { addValidationIssue, zNonEmptyString } from '@owf/identity-common'\nimport z from 'zod'\nimport { zX5c } from './z-x5c'\n\n/**\n * The JWK members that hold private or symmetric key material. `k` is the whole secret of an `oct` key.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7518#section-6\n */\nexport const jwkPrivateMembers = ['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'k'] as const\n\n/**\n * A JSON Web Key. Only `kty` is required, as in RFC 7517. Loose, so unknown members survive when the\n * JWK is serialized again, e.g. into a `cnf` claim or a `jwk` header.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7517#section-4\n */\nexport const zJwk = z\n .object({\n kty: zNonEmptyString,\n\n // Common parameters\n use: zNonEmptyString.optional(),\n key_ops: z.array(zNonEmptyString).optional(),\n alg: zNonEmptyString.optional(),\n kid: zNonEmptyString.optional(),\n x5u: zNonEmptyString.optional(),\n x5c: zX5c.optional(),\n x5t: zNonEmptyString.optional(),\n 'x5t#S256': zNonEmptyString.optional(),\n ext: z.boolean().optional(),\n\n // EC and OKP\n crv: zNonEmptyString.optional(),\n x: zNonEmptyString.optional(),\n y: zNonEmptyString.optional(),\n\n // RSA\n n: zNonEmptyString.optional(),\n e: zNonEmptyString.optional(),\n\n // Private and symmetric key material\n d: zNonEmptyString.optional(),\n p: zNonEmptyString.optional(),\n q: zNonEmptyString.optional(),\n dp: zNonEmptyString.optional(),\n dq: zNonEmptyString.optional(),\n qi: zNonEmptyString.optional(),\n oth: z\n .array(\n z\n .object({\n r: zNonEmptyString.optional(),\n d: zNonEmptyString.optional(),\n t: zNonEmptyString.optional(),\n })\n .loose()\n )\n .optional(),\n k: zNonEmptyString.optional(),\n })\n .loose()\n\nexport type Jwk = z.infer<typeof zJwk>\n\n/**\n * A JWK without private or symmetric key material. Use it for keys from untrusted input, such as a\n * `jwk` header, a `cnf` claim or a fetched JWK Set.\n */\nexport const zPublicJwk = zJwk.superRefine((jwk, ctx) => {\n for (const member of jwkPrivateMembers) {\n if (jwk[member] === undefined) continue\n addValidationIssue(ctx, {\n code: 'not_allowed',\n path: [member],\n message: `Expected a public jwk, but the jwk contains the private key member '${member}'`,\n })\n }\n})\n\nexport type PublicJwk = z.infer<typeof zPublicJwk>\n\n/**\n * A JWK Set.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7517#section-5\n */\nexport const zJwkSet = z.object({ keys: z.array(zJwk) }).loose()\n\nexport type JwkSet = z.infer<typeof zJwkSet>\n\n/** A JWK Set whose keys must all be public, see {@link zPublicJwk}. */\nexport const zPublicJwkSet = z.object({ keys: z.array(zPublicJwk) }).loose()\n","import { addValidationIssue, zBase64Url } from '@owf/identity-common'\nimport z from 'zod'\n\n/**\n * A StringOrURI: a string value that is compared as a case-sensitive string, and that must be a URI\n * whenever it contains a `:`.\n *\n * The URI form is not enforced: OpenID4VP client identifiers such as `x509_san_dns:example.com`\n * are used as `iss` and `aud`, but `_` is not allowed in a URI scheme (RFC 3986 section 3.1).\n *\n * @see https://www.rfc-editor.org/rfc/rfc7519#section-2\n */\nexport const zStringOrUri = z.string({\n error: `Expected a StringOrURI: a string, which must be a URI when it contains a ':'`,\n})\n\n/**\n * A compact serialization: `partCount` base64url parts separated by `.`, of which only the ones at\n * `emptyParts` may be empty. Anything else gives an `invalid_format` issue with `format` as context.\n */\nexport function zCompactSerialization(format: string, partCount: number, emptyParts: ReadonlyArray<number> = []) {\n return z.string().superRefine((value, ctx) => {\n const parts = value.split('.')\n const isCompact =\n parts.length === partCount &&\n parts.every((part, index) => (part !== '' || emptyParts.includes(index)) && zBase64Url.safeParse(part).success)\n\n if (!isCompact) {\n addValidationIssue(ctx, {\n code: 'invalid_format',\n message: `Not a valid compact ${format.toUpperCase()}`,\n context: { format },\n })\n }\n })\n}\n","import { zBase64Url, zNonEmptyString } from '@owf/identity-common'\nimport z from 'zod'\nimport { zJwsAlg } from '../jwa/z-alg'\nimport { zPublicJwk } from '../jwk/z-jwk'\nimport { zX5c } from '../jwk/z-x5c'\nimport { zCompactSerialization } from '../utils/z-common'\n\n/**\n * The registered JWS header parameters. Loose, so the parameters of a profile survive. Compose on top\n * of it to require the parameters a profile needs:\n *\n * ```ts\n * const zMyHeader = z.object({ ...zJwsProtectedHeader.shape, typ: zTyp('my+jwt') }).loose()\n * ```\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1\n */\nexport const zJwsProtectedHeader = z\n .object({\n alg: zJwsAlg,\n\n typ: zNonEmptyString.optional(),\n cty: zNonEmptyString.optional(),\n\n kid: zNonEmptyString.optional(),\n jwk: zPublicJwk.optional(),\n jku: zNonEmptyString.optional(),\n\n x5c: zX5c.optional(),\n x5u: zNonEmptyString.optional(),\n x5t: zBase64Url.min(1).optional(),\n 'x5t#S256': zBase64Url.min(1).optional(),\n\n /**\n * The header parameters a recipient must understand. Validated further in `assertCriticalHeaderParameters`.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.11\n */\n crit: z.array(zNonEmptyString).min(1).optional(),\n\n /**\n * Whether the payload is base64url encoded. `false` means it is carried and signed as it is.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7797\n */\n b64: z.boolean().optional(),\n\n /**\n * The OpenID Federation trust chain that establishes the signer.\n *\n * @see https://openid.net/specs/openid-federation-1_0.html\n */\n trust_chain: z.tuple([zNonEmptyString], zNonEmptyString).optional(),\n })\n .loose()\n\nexport type JwsProtectedHeader = z.infer<typeof zJwsProtectedHeader>\n\n/**\n * A JWS unprotected header. Untyped: it is not covered by the signature, so the library reads nothing\n * from it. A profile that needs a parameter, as JAdES does `etsiU`, validates it itself.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-7.2\n */\nexport const zJwsUnprotectedHeader = z.record(z.string(), z.unknown())\n\nexport type JwsUnprotectedHeader = z.infer<typeof zJwsUnprotectedHeader>\n\n/**\n * A JWS in compact serialization. An empty payload part is a detached payload. A JWS with an unencoded\n * payload (`b64: false`) does not match, but `parseJws` accepts it.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-7.1\n */\nexport const zCompactJws = zCompactSerialization('jws', 3, [1])\n\n/** The signature of a JSON serialized JWS. Never empty: that is an unsecured JWS. */\nconst zJwsSignature = zBase64Url.min(1, { message: 'Expected a signature, an unsecured JWS is not supported' })\n\n/**\n * A JWS in flattened JSON serialization.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-7.2.2\n */\nexport const zFlattenedJws = z\n .object({\n /** Absent for a detached payload. Not `zBase64Url`, as it is unencoded when `b64` is false. */\n payload: z.string().optional(),\n protected: zBase64Url.optional(),\n header: zJwsUnprotectedHeader.optional(),\n signature: zJwsSignature,\n })\n .loose()\n\nexport type FlattenedJws = z.infer<typeof zFlattenedJws>\n\n/**\n * A JWS in general JSON serialization.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-7.2.1\n */\nexport const zGeneralJws = z\n .object({\n payload: z.string().optional(),\n signatures: z\n .array(\n z\n .object({\n protected: zBase64Url.optional(),\n header: zJwsUnprotectedHeader.optional(),\n signature: zJwsSignature,\n })\n .loose()\n )\n .min(1),\n })\n .loose()\n\nexport type GeneralJws = z.infer<typeof zGeneralJws>\n","import { type OrPromise, zBase64Url, zNonEmptyString } from '@owf/identity-common'\nimport z from 'zod'\nimport { zJweAlg, zJweEnc } from '../jwa/z-alg'\nimport type { Jwk } from '../jwk/z-jwk'\nimport { zPublicJwk } from '../jwk/z-jwk'\nimport type { JwsSignerJwk } from '../jws/signer'\nimport { zJwsProtectedHeader } from '../jws/z-jws'\nimport { zCompactSerialization } from '../utils/z-common'\n\n/**\n * A JWE in compact serialization.\n *\n * The encrypted key part may be empty, as it is for direct key agreement (`ECDH-ES`) and direct\n * encryption (`dir`). The authentication tag may not: RFC 7516 allows an empty one for an algorithm\n * without a tag, but every registered `enc` has one.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7516#section-7.1\n */\nexport const zCompactJwe = zCompactSerialization('jwe', 5, [1])\n\n/**\n * The header parameters registered for a JWE. The ones a JWE shares with a JWS are validated as in\n * `zJwsProtectedHeader`.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7516#section-4.1\n */\nexport const zJweHeader = z\n .object({\n ...zJwsProtectedHeader.omit({ alg: true, b64: true, trust_chain: true }).shape,\n\n alg: zJweAlg,\n enc: zJweEnc,\n zip: zNonEmptyString.optional(),\n\n /** The ephemeral public key of the originator, for the key agreement algorithms. */\n epk: zPublicJwk.optional(),\n\n /** Agreement PartyUInfo, base64url encoded. */\n apu: zBase64Url.optional(),\n\n /** Agreement PartyVInfo, base64url encoded. */\n apv: zBase64Url.optional(),\n })\n .loose()\n\nexport type JweHeader = z.infer<typeof zJweHeader>\n\n/**\n * The recipient a JWE is encrypted for, and how.\n *\n * Encryption and decryption themselves are performed by callbacks: this package models the\n * structures and leaves the cryptography to the caller.\n */\nexport type JweEncryptor = JwsSignerJwk & {\n /** The content encryption algorithm. */\n enc: string\n\n /** Agreement PartyUInfo, base64url encoded. */\n apu?: string\n\n /** Agreement PartyVInfo, base64url encoded. */\n apv?: string\n}\n\n/** Encrypts `data` for `encryptor`, returning the JWE in compact serialization. */\nexport type EncryptJweCallback = (\n encryptor: JweEncryptor,\n data: string\n) => OrPromise<{\n encryptionJwk: Jwk\n jwe: string\n}>\n\nexport interface DecryptJweCallbackOptions {\n /** The key to decrypt with, when the caller knows which one applies. */\n jwk?: Jwk\n}\n\n/**\n * Decrypts a compact JWE, returning the plaintext and the JWK of the key it was decrypted with.\n *\n * Return `{ decrypted: false }` for expected failures, such as an invalid ciphertext or\n * authentication tag or a key mismatch. Throw only for unexpected failures, such as an unavailable\n * key store.\n */\nexport type DecryptJweCallback = (\n jwe: string,\n options?: DecryptJweCallbackOptions\n) => OrPromise<\n | {\n decrypted: true\n decryptionJwk: Jwk\n payload: string\n }\n | {\n decrypted: false\n decryptionJwk?: Jwk\n payload?: string\n }\n>\n","import {\n base64url,\n type HashAlgorithm,\n type Hasher,\n parseWithErrorHandling,\n zNonEmptyString,\n} from '@owf/identity-common'\nimport z from 'zod'\nimport { JoseValidationError } from '../error'\nimport type { Jwk } from './z-jwk'\n\n/**\n * The required members of a JWK per key type, in the lexicographic order RFC 7638 requires.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7638#section-3.2\n */\nexport const zJwkThumbprintComponents = z\n .discriminatedUnion('kty', [\n z.object({\n kty: z.literal('EC'),\n crv: zNonEmptyString,\n x: zNonEmptyString,\n y: zNonEmptyString,\n }),\n z.object({\n kty: z.literal('OKP'),\n crv: zNonEmptyString,\n x: zNonEmptyString,\n }),\n z.object({\n kty: z.literal('RSA'),\n e: zNonEmptyString,\n n: zNonEmptyString,\n }),\n z.object({\n kty: z.literal('oct'),\n k: zNonEmptyString,\n }),\n ])\n .transform((jwk) => {\n if (jwk.kty === 'EC') return { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }\n if (jwk.kty === 'OKP') return { crv: jwk.crv, kty: jwk.kty, x: jwk.x }\n if (jwk.kty === 'RSA') return { e: jwk.e, kty: jwk.kty, n: jwk.n }\n return { k: jwk.k, kty: jwk.kty }\n })\n\nexport interface CalculateJwkThumbprintOptions {\n /** The jwk to calculate the thumbprint for. */\n jwk: Jwk\n\n /** The hashing algorithm to use. RFC 7638 registers SHA-256 as the default. */\n hashAlgorithm: HashAlgorithm\n\n /** The hash callback used to compute the digest, e.g. `hasher` of `@owf/crypto`. */\n hashCallback: Hasher\n}\n\n/**\n * Calculates the JWK thumbprint of a key: the base64url encoded digest over the required members of\n * the key, serialized as JSON with lexicographically ordered member names and no whitespace.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7638\n */\nexport async function calculateJwkThumbprint(options: CalculateJwkThumbprintOptions): Promise<string> {\n const components = parseWithErrorHandling(\n zJwkThumbprintComponents,\n options.jwk,\n `Unable to calculate the thumbprint of the jwk. Either the 'kty' is not supported, or a member required for the thumbprint is missing`,\n JoseValidationError\n )\n\n return base64url.encode(await options.hashCallback(JSON.stringify(components), options.hashAlgorithm))\n}\n\n/**\n * Calculates the JWK thumbprint URI of a key: `urn:ietf:params:oauth:jwk-thumbprint:<hash>:<thumbprint>`.\n *\n * @see https://www.rfc-editor.org/rfc/rfc9278\n */\nexport async function calculateJwkThumbprintUri(options: CalculateJwkThumbprintOptions): Promise<string> {\n const thumbprint = await calculateJwkThumbprint(options)\n return `urn:ietf:params:oauth:jwk-thumbprint:${options.hashAlgorithm}:${thumbprint}`\n}\n","import type { Hasher } from '@owf/identity-common'\nimport { JoseSignerError } from '../error'\nimport { isSameJsonValue } from '../utils/object'\nimport { calculateJwkThumbprint, zJwkThumbprintComponents } from './thumbprint'\nimport type { Jwk, JwkSet } from './z-jwk'\n\nexport interface ExtractJwkFromJwkSetOptions {\n /** The JWK Set to select a key from. */\n jwks: JwkSet\n\n /** The `kid` of the key to select, typically taken from the header of the token to verify. */\n kid?: string\n\n /** Whether the key is used for signature verification or for encryption. */\n use: 'enc' | 'sig'\n}\n\n/**\n * The JWK when every one of `jwks` is the same, otherwise `undefined`. Two JWKs of one key that differ\n * in e.g. `alg` are ambiguous, as the selected one decides what the key is checked against.\n */\nconst onlyJwk = (jwks: ReadonlyArray<Jwk>): Jwk | undefined => {\n const [first, ...rest] = jwks\n return first && rest.every((jwk) => isSameJsonValue(jwk, first)) ? first : undefined\n}\n\n/**\n * Selects the key with `kid` from a JWK Set, or the only key for `use` without a `kid`. Keys with\n * another `use` are skipped. More than one candidate, as during a key rotation, throws.\n *\n * @throws JoseSignerError if no key, or more than one, is a candidate.\n */\nexport function extractJwkFromJwkSet(options: ExtractJwkFromJwkSetOptions): Jwk {\n const jwksForUse = options.jwks.keys.filter(({ use }) => !use || use === options.use)\n\n if (options.kid) {\n const jwksForKid = jwksForUse.filter(({ kid }) => kid === options.kid)\n if (jwksForKid.length === 0) {\n throw new JoseSignerError(\n `Unable to extract jwk from jwks for use '${options.use}'. No key with kid '${options.kid}' found.`\n )\n }\n\n const jwkForKid = onlyJwk(jwksForKid)\n if (jwkForKid) return jwkForKid\n\n throw new JoseSignerError(\n `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.`\n )\n }\n\n const jwkForUse = onlyJwk(jwksForUse)\n if (jwkForUse) return jwkForUse\n\n throw new JoseSignerError(\n `Unable to extract jwk from jwks for use '${options.use}'. No kid provided and the jwks contains ${jwksForUse.length} keys for this use.`\n )\n}\n\n/**\n * Whether `jwk` is one of `jwks`, compared by JWK thumbprint. Keys in the set without a thumbprint,\n * such as an ML-DSA `AKP` key, are skipped.\n *\n * @throws JoseValidationError if the thumbprint of `jwk` itself cannot be computed.\n */\nexport async function isJwkInSet({\n jwk,\n jwks,\n hashCallback,\n}: {\n jwk: Jwk\n jwks: ReadonlyArray<Jwk>\n hashCallback: Hasher\n}): Promise<boolean> {\n const thumbprint = await calculateJwkThumbprint({ jwk, hashAlgorithm: 'sha-256', hashCallback })\n\n for (const jwkFromSet of jwks) {\n if (!zJwkThumbprintComponents.safeParse(jwkFromSet).success) continue\n\n const thumbprintFromSet = await calculateJwkThumbprint({\n jwk: jwkFromSet,\n hashAlgorithm: 'sha-256',\n hashCallback,\n })\n\n if (thumbprintFromSet === thumbprint) return true\n }\n\n return false\n}\n","import { ValidationIssues } from '@owf/identity-common'\nimport { JoseValidationError, type JoseValidationIssue } from '../error'\nimport { hasOwn } from '../utils/object'\nimport type { JwsProtectedHeader, JwsUnprotectedHeader } from './z-jws'\n\n/**\n * The header parameters of RFC 7515, RFC 7516 and RFC 7518, which `crit` must not list. `b64` is not\n * one of them: RFC 7797 requires it in `crit`.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.11\n */\nconst registeredHeaderParameters = new Set([\n 'alg',\n 'jku',\n 'jwk',\n 'kid',\n 'x5u',\n 'x5c',\n 'x5t',\n 'x5t#S256',\n 'typ',\n 'cty',\n 'crit',\n 'enc',\n 'zip',\n 'epk',\n 'apu',\n 'apv',\n 'iv',\n 'tag',\n 'p2s',\n 'p2c',\n])\n\nexport interface AssertCriticalHeaderParametersOptions {\n /** The protected header, validated against {@link zJwsProtectedHeader}, so the shape of `crit` is checked. */\n protectedHeader: JwsProtectedHeader\n\n /** The unprotected header, if the serialization has one. */\n unprotectedHeader?: JwsUnprotectedHeader\n\n /** The extension header parameters the caller processes. A JWS that marks another one critical is rejected. */\n understoodCriticalParameters?: ReadonlyArray<string>\n}\n\n/**\n * Verifies the `crit` header parameter of a JWS.\n *\n * @throws JoseValidationError with an `invalid_crit` or `unsupported_crit` issue for each way `crit`\n * is invalid, or names a parameter that is not understood.\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-4.1.11\n */\nexport function assertCriticalHeaderParameters({\n protectedHeader,\n unprotectedHeader,\n understoodCriticalParameters = [],\n}: AssertCriticalHeaderParametersOptions): void {\n const issues = new ValidationIssues<JoseValidationIssue['code']>()\n\n // `crit` is only meaningful when it is integrity protected\n if (unprotectedHeader && hasOwn(unprotectedHeader, 'crit')) {\n issues.add({\n code: 'invalid_crit',\n path: ['crit'],\n message: `The 'crit' header parameter is present in the unprotected header, where it is not integrity protected and therefore not valid`,\n })\n }\n\n const understood = new Set(understoodCriticalParameters)\n\n protectedHeader.crit?.forEach((name, index) => {\n const path = ['crit', index]\n if (registeredHeaderParameters.has(name)) {\n issues.add({\n code: 'invalid_crit',\n path,\n message: `The 'crit' header parameter lists '${name}', which is a registered header parameter and must not be listed`,\n context: { parameter: name },\n })\n }\n // A parameter marked critical can be carried in the unprotected header\n else if (!hasOwn(protectedHeader, name) && !(unprotectedHeader && hasOwn(unprotectedHeader, name))) {\n issues.add({\n code: 'invalid_crit',\n path,\n message: `The 'crit' header parameter lists '${name}', but the header does not contain that parameter`,\n context: { parameter: name },\n })\n } else if (!understood.has(name)) {\n issues.add({\n code: 'unsupported_crit',\n path,\n message:\n name === 'b64'\n ? `The 'crit' header parameter lists 'b64' (RFC 7797), which is only accepted when 'b64' is in 'understoodCriticalParameters'`\n : `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.`,\n context: { parameter: name, understood: [...understood] },\n })\n }\n })\n\n if (issues.issues.length) throw new JoseValidationError('Invalid JWS crit header parameter', issues.issues)\n}\n\n/**\n * Whether the payload of a JWS is base64url encoded, per `b64`. RFC 7797 requires `b64` to be listed\n * in `crit`.\n *\n * @throws JoseValidationError with an `invalid_crit` issue if `b64` is used without being marked critical.\n * @see https://www.rfc-editor.org/rfc/rfc7797#section-6\n */\nexport function isPayloadBase64UrlEncoded(protectedHeader: JwsProtectedHeader): boolean {\n const b64 = protectedHeader.b64\n if (b64 === undefined) return true\n\n if (!protectedHeader.crit?.includes('b64')) {\n throw new JoseValidationError('Invalid JWS crit header parameter', [\n {\n severity: 'error',\n code: 'invalid_crit',\n path: ['crit'],\n message: `The 'b64' header parameter is used, but is not listed in the 'crit' header parameter, which RFC 7797 requires`,\n },\n ])\n }\n\n return b64\n}\n","// The only place this package decodes JOSE parts, strictly, through `@owf/identity-common`. Don't decode\n// elsewhere: two encodings of the same header would be two tokens that are treated as one.\n\nimport { base64url, base64urlDecodeJson, base64urlEncode, bytesToString } from '@owf/identity-common'\nimport { JoseNotSupportedError, JoseParseError } from '../error'\n\n/**\n * Decodes a base64url encoded JSON object, such as a JWS protected header.\n *\n * @throws JoseParseError if the input is not valid base64url, not valid UTF-8, not valid JSON, or\n * is a JSON value other than an object.\n */\nexport function decodeBase64UrlJsonObject(encoded: string, name: string): Record<string, unknown> {\n let decoded: unknown\n try {\n decoded = base64urlDecodeJson(encoded)\n } catch (error) {\n throw new JoseParseError(`Unable to decode the ${name}, it is not valid base64url encoded JSON`, { cause: error })\n }\n\n if (typeof decoded !== 'object' || decoded === null || Array.isArray(decoded)) {\n throw new JoseParseError(`Unable to decode the ${name}, it is not a JSON object`)\n }\n\n return decoded as Record<string, unknown>\n}\n\n/**\n * Decodes a base64url encoded value into bytes.\n *\n * @throws JoseParseError if the input is not valid base64url.\n */\nexport function decodeBase64UrlBytes(encoded: string, name: string): Uint8Array {\n try {\n return base64url.decode(encoded)\n } catch (error) {\n throw new JoseParseError(`Unable to decode the ${name}, it is not valid base64url`, { cause: error })\n }\n}\n\n/**\n * The payload of a JWS with `b64` false (RFC 7797), as it appears in the signing input. That is a\n * string, so a payload that is not valid UTF-8 is not supported.\n *\n * @throws JoseNotSupportedError if the payload is not valid UTF-8.\n */\nexport function decodeUnencodedPayload(payload: Uint8Array): string {\n try {\n return bytesToString(payload, { fatal: true })\n } catch (error) {\n throw new JoseNotSupportedError(`An unencoded payload ('b64' is false) that is not valid UTF-8 is not supported.`, {\n cause: error,\n })\n }\n}\n\n/**\n * Why an unencoded payload (`b64` false) cannot be carried in a compact serialization, or `undefined`\n * when it can: only printable ASCII other than '.' (%x20-2D and %x2F-7E) is allowed.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7797#section-5.2\n */\nexport function unencodedCompactPayloadIssue(payload: string): string | undefined {\n if (payload.includes('.')) {\n 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.`\n }\n\n if (!/^[\\x20-\\x7e]*$/.test(payload)) {\n 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.`\n }\n\n return undefined\n}\n\n/** Encodes a JSON value the way a JOSE part is encoded: compact JSON, base64url, no padding. */\nexport function encodeBase64UrlJson(value: unknown): string {\n return base64urlEncode(JSON.stringify(value))\n}\n","import { type BaseSchema, base64url, parseWithErrorHandling, stringToBytes, zBase64Url } from '@owf/identity-common'\nimport { JoseParseError, JoseValidationError } from '../error'\nimport {\n decodeBase64UrlBytes,\n decodeBase64UrlJsonObject,\n decodeUnencodedPayload,\n unencodedCompactPayloadIssue,\n} from '../utils/encoding'\nimport { hasOwn } from '../utils/object'\nimport type { InferSchemaOrDefaultOutput } from '../utils/zod'\nimport { assertCriticalHeaderParameters, isPayloadBase64UrlEncoded } from './critical-headers'\nimport {\n type FlattenedJws,\n type GeneralJws,\n type JwsProtectedHeader,\n zFlattenedJws,\n zGeneralJws,\n zJwsProtectedHeader,\n zJwsUnprotectedHeader,\n} from './z-jws'\n\nexport type JwsSerialization = 'compact' | 'flattened' | 'general'\n\nexport interface ParseJwsOptions<\n ProtectedHeaderSchema extends BaseSchema | undefined,\n UnprotectedHeaderSchema extends BaseSchema | undefined,\n> {\n /** The JWS. A string is always read as a compact serialization, a JSON serialization is passed as an object. */\n jws: string | FlattenedJws | GeneralJws\n\n /** Schema for the protected header. The header is always validated against {@link zJwsProtectedHeader} too. */\n protectedHeaderSchema?: ProtectedHeaderSchema\n\n /** Schema for the unprotected header of a JSON serialized JWS. */\n unprotectedHeaderSchema?: UnprotectedHeaderSchema\n\n /** The payload of a JWS that does not carry one. Rejected when the JWS does carry one. */\n detachedPayload?: string | Uint8Array\n\n /**\n * Which signature to read from a general JSON serialization.\n *\n * @default 0\n */\n signatureIndex?: number\n\n /**\n * The critical header parameters the caller understands, see {@link assertCriticalHeaderParameters}.\n * Include `b64` to accept an unencoded payload (RFC 7797).\n */\n understoodCriticalParameters?: ReadonlyArray<string>\n}\n\nexport interface ParsedJws<\n ProtectedHeaderSchema extends BaseSchema | undefined = undefined,\n UnprotectedHeaderSchema extends BaseSchema | undefined = undefined,\n> {\n serialization: JwsSerialization\n\n /** The validated protected header, as the schema that was given returned it. */\n protectedHeader: InferSchemaOrDefaultOutput<ProtectedHeaderSchema, typeof zJwsProtectedHeader>\n\n /**\n * The protected header validated against {@link zJwsProtectedHeader} alone. The checks use it, as the\n * caller's schema can change the parameters they depend on.\n */\n registeredProtectedHeader: JwsProtectedHeader\n\n /** The validated unprotected header, when there is one. Not covered by the signature. */\n unprotectedHeader?: InferSchemaOrDefaultOutput<UnprotectedHeaderSchema, typeof zJwsUnprotectedHeader>\n\n /** The protected header as it was received, base64url encoded. */\n encodedProtectedHeader: string\n\n /** The payload bytes. */\n payload: Uint8Array\n\n /**\n * The payload as it appears in the signing input: base64url encoded, or the payload itself when\n * `b64` is false.\n */\n encodedPayload: string\n\n /** The signature, base64url encoded. */\n signature: string\n\n /**\n * The bytes covered by the signature, as a string. Taken from the token as received, as re-encoding\n * the parsed header can change them.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7515#section-5.2\n */\n signingInput: string\n\n /** The compact serialization, when that was parsed and the payload is not detached. */\n compact?: string\n}\n\n/** The parts of a JWS, as they are laid out in the serialization it was received in. */\ninterface JwsParts {\n serialization: JwsSerialization\n encodedProtectedHeader: string | undefined\n unprotectedHeader: Record<string, unknown> | undefined\n /** `undefined` when the payload is detached. */\n serializedPayload: string | undefined\n signature: string\n compact?: string\n}\n\n/** Whether a compact JWS header sets `b64` to false, as then a '.' in the payload split it into more parts. */\nconst isUnencodedPayloadHeader = (encodedProtectedHeader: string): boolean => {\n try {\n return decodeBase64UrlJsonObject(encodedProtectedHeader, 'JWS protected header').b64 === false\n } catch {\n return false\n }\n}\n\nfunction compactJwsParts(jws: string): JwsParts {\n const parts = jws.split('.')\n if (parts.length > 3 && isUnencodedPayloadHeader(parts[0])) {\n // The header and the signature are base64url, so the payload is everything between them\n const issue = unencodedCompactPayloadIssue(parts.slice(1, -1).join('.'))\n throw new JoseParseError(`Unable to parse the JWS. ${issue}`)\n }\n if (parts.length !== 3) {\n throw new JoseParseError('Unable to parse the JWS, a compact JWS must consist of exactly three parts')\n }\n\n // The signature goes to the callback undecoded, so it is checked here. The payload is not: with\n // `b64` false it is not base64url.\n if (!zBase64Url.safeParse(parts[0]).success) {\n throw new JoseParseError('Unable to parse the JWS, the protected header of a compact JWS must be base64url')\n }\n if (!zBase64Url.safeParse(parts[2]).success) {\n throw new JoseParseError('Unable to parse the JWS, the signature of a compact JWS must be base64url')\n }\n\n if (parts[2] === '') {\n throw new JoseParseError(\n 'Unable to parse the JWS, it does not have a signature. An unsecured JWS is not supported.'\n )\n }\n\n const isPayloadDetached = parts[1] === ''\n\n return {\n serialization: 'compact',\n encodedProtectedHeader: parts[0],\n unprotectedHeader: undefined,\n serializedPayload: isPayloadDetached ? undefined : parts[1],\n signature: parts[2],\n compact: isPayloadDetached ? undefined : jws,\n }\n}\n\nfunction jsonJwsParts(jws: FlattenedJws | GeneralJws, signatureIndex: number): JwsParts {\n // Often what `JSON.parse` returned for an untrusted body, which can be any JSON value\n if (typeof jws !== 'object' || jws === null || Array.isArray(jws)) {\n throw new JoseParseError('Unable to parse the JWS, a JSON serialized JWS must be an object')\n }\n\n if ('signatures' in jws) {\n const general = parseWithErrorHandling(\n zGeneralJws,\n jws,\n 'Unable to parse the general JSON serialized JWS',\n JoseValidationError\n )\n const signature = general.signatures[signatureIndex]\n\n if (!signature) {\n throw new JoseParseError(\n `Unable to parse the JWS, it does not contain a signature at index ${signatureIndex}. It contains ${general.signatures.length} signature(s).`\n )\n }\n\n return {\n serialization: 'general',\n encodedProtectedHeader: signature.protected,\n unprotectedHeader: signature.header,\n serializedPayload: general.payload,\n signature: signature.signature,\n }\n }\n\n const flattened = parseWithErrorHandling(\n zFlattenedJws,\n jws,\n 'Unable to parse the flattened JSON serialized JWS',\n JoseValidationError\n )\n\n return {\n serialization: 'flattened',\n encodedProtectedHeader: flattened.protected,\n unprotectedHeader: flattened.header,\n serializedPayload: flattened.payload,\n signature: flattened.signature,\n }\n}\n\n/**\n * Parses and validates a JWS, without verifying the signature. A JWS without a protected header, so\n * without an integrity protected `alg`, is not supported.\n *\n * @throws JoseParseError if the JWS is not well-formed, which includes a compact JWS that carries an\n * unencoded payload (`b64` is false) with a '.' or a character outside printable ASCII.\n * @throws JoseValidationError if a header does not validate against its schema.\n * @throws JoseValidationError with an `invalid_crit` or `unsupported_crit` issue if `crit` is invalid\n * or names a parameter that is not understood.\n * @throws JoseNotSupportedError if the payload is unencoded (`b64` is false) and not valid UTF-8.\n */\nexport function parseJws<\n ProtectedHeaderSchema extends BaseSchema | undefined = undefined,\n UnprotectedHeaderSchema extends BaseSchema | undefined = undefined,\n>(\n options: ParseJwsOptions<ProtectedHeaderSchema, UnprotectedHeaderSchema>\n): ParsedJws<ProtectedHeaderSchema, UnprotectedHeaderSchema> {\n const parts =\n typeof options.jws === 'string'\n ? compactJwsParts(options.jws)\n : jsonJwsParts(options.jws, options.signatureIndex ?? 0)\n\n if (!parts.encodedProtectedHeader) {\n throw new JoseParseError(\n '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.'\n )\n }\n\n const protectedHeaderJson = decodeBase64UrlJsonObject(parts.encodedProtectedHeader, 'JWS protected header')\n\n if (parts.unprotectedHeader) {\n const duplicates = Object.keys(parts.unprotectedHeader).filter((name) => hasOwn(protectedHeaderJson, name))\n if (duplicates.length > 0) {\n throw new JoseParseError(\n `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`\n )\n }\n }\n\n // The checks use the registered header, so the caller's schema cannot leave `alg` or `crit` unchecked\n const registeredHeader = parseWithErrorHandling(\n zJwsProtectedHeader,\n protectedHeaderJson,\n 'Invalid JWS protected header',\n JoseValidationError\n )\n const protectedHeader = parseWithErrorHandling(\n options.protectedHeaderSchema ?? zJwsProtectedHeader,\n protectedHeaderJson,\n 'Invalid JWS protected header',\n JoseValidationError\n )\n\n const unprotectedHeader = parts.unprotectedHeader\n ? parseWithErrorHandling(\n options.unprotectedHeaderSchema ?? zJwsUnprotectedHeader,\n parts.unprotectedHeader,\n 'Invalid JWS unprotected header',\n JoseValidationError\n )\n : undefined\n\n assertCriticalHeaderParameters({\n protectedHeader: registeredHeader,\n unprotectedHeader: parts.unprotectedHeader,\n understoodCriticalParameters: options.understoodCriticalParameters,\n })\n\n const isBase64UrlEncoded = isPayloadBase64UrlEncoded(registeredHeader)\n\n // RFC 7797 section 5.2: a compact serialization only carries an unencoded payload of printable ASCII\n // other than '.'. A '.' has already split the JWS into more parts.\n const compactPayloadIssue =\n parts.serialization === 'compact' && !isBase64UrlEncoded && parts.serializedPayload !== undefined\n ? unencodedCompactPayloadIssue(parts.serializedPayload)\n : undefined\n if (compactPayloadIssue) throw new JoseParseError(`Unable to parse the JWS. ${compactPayloadIssue}`)\n\n const { payload, encodedPayload } = resolvePayload({\n serializedPayload: parts.serializedPayload,\n detachedPayload: options.detachedPayload,\n isBase64UrlEncoded,\n })\n\n return {\n serialization: parts.serialization,\n protectedHeader: protectedHeader as ParsedJws<ProtectedHeaderSchema, UnprotectedHeaderSchema>['protectedHeader'],\n registeredProtectedHeader: registeredHeader,\n unprotectedHeader: unprotectedHeader as ParsedJws<\n ProtectedHeaderSchema,\n UnprotectedHeaderSchema\n >['unprotectedHeader'],\n encodedProtectedHeader: parts.encodedProtectedHeader,\n payload,\n encodedPayload,\n signature: parts.signature,\n signingInput: `${parts.encodedProtectedHeader}.${encodedPayload}`,\n compact: parts.compact,\n }\n}\n\nfunction resolvePayload({\n serializedPayload,\n detachedPayload,\n isBase64UrlEncoded,\n}: {\n serializedPayload: string | undefined\n detachedPayload: string | Uint8Array | undefined\n isBase64UrlEncoded: boolean\n}): { payload: Uint8Array; encodedPayload: string } {\n if (serializedPayload !== undefined && detachedPayload !== undefined) {\n throw new JoseParseError(\n 'A detached payload was provided, but the JWS carries a payload. Only one of the two can be the payload that was signed.'\n )\n }\n\n if (serializedPayload === undefined && detachedPayload === undefined) {\n throw new JoseParseError(\n 'The JWS does not carry a payload and no detached payload was provided, so there is nothing to verify. Pass the payload as `detachedPayload`.'\n )\n }\n\n if (detachedPayload !== undefined) {\n const payload = typeof detachedPayload === 'string' ? stringToBytes(detachedPayload) : detachedPayload\n return {\n payload,\n encodedPayload: isBase64UrlEncoded ? base64url.encode(payload) : decodeUnencodedPayload(payload),\n }\n }\n\n const serialized = serializedPayload as string\n return {\n payload: isBase64UrlEncoded ? decodeBase64UrlBytes(serialized, 'JWS payload') : stringToBytes(serialized),\n encodedPayload: serialized,\n }\n}\n","import { JoseSignerError } from '../error'\nimport type { Jwk } from '../jwk/z-jwk'\nimport type { JwsProtectedHeader } from './z-jws'\n\n/** The signer is identified by a DID URL, resolved to a verification method by the caller. */\nexport type JwsSignerDid = {\n method: 'did'\n didUrl: string\n alg: string\n\n /** The key id to sign with. It must match the key of `didUrl`. */\n kid?: string\n}\n\n/** The signer is identified by a public JWK, carried in the `jwk` header parameter. */\nexport type JwsSignerJwk = {\n method: 'jwk'\n publicJwk: Jwk\n alg: string\n\n /** The key id to sign with. It must match `publicJwk`, and is not added to the header. */\n kid?: string\n}\n\n/** The signer is identified by an X.509 certificate chain, carried in the `x5c` header parameter. */\nexport type JwsSignerX5c = {\n method: 'x5c'\n x5c: string[]\n alg: string\n\n /** The key id to sign with. It must match the key of the leaf certificate. */\n kid?: string\n}\n\n/** The signer is established through an OpenID Federation trust chain. */\nexport type JwsSignerFederation = {\n method: 'federation'\n trustChain?: [string, ...string[]]\n alg: string\n\n /** The key id to sign with. It must match a key in the federation. */\n kid: string\n}\n\n/** The signer is established out of band. */\nexport type JwsSignerCustom = {\n method: 'custom'\n alg: string\n\n /** The key id that should be used for signing. Added to the header as `kid`. */\n kid?: string\n}\n\nexport type JwsSigner = JwsSignerDid | JwsSignerJwk | JwsSignerX5c | JwsSignerFederation | JwsSignerCustom\n\nexport type JwsSignerMethod = JwsSigner['method']\n\n/** A {@link JwsSigner} whose public key is known, which is what verification establishes. */\nexport type JwsSignerWithJwk = JwsSigner & { publicJwk: Jwk }\n\n/**\n * The header parameters that identify the signer, as derived from a {@link JwsSigner}:\n *\n * - `did`: the DID URL, as `kid`.\n * - `federation`: `kid` and `trust_chain`. Without a trust chain that is `kid` alone, from which a\n * verifier establishes a `custom` signer.\n * - `jwk`: `jwk`. The `kid` of the signer is not added.\n * - `x5c`: `x5c`. The `kid` of the signer is not added.\n * - `custom`: `kid`, when the signer has one.\n */\nexport function jwsHeaderFromSigner(signer: JwsSigner) {\n if (signer.method === 'did') {\n return { alg: signer.alg, kid: signer.didUrl } as const\n }\n\n if (signer.method === 'federation') {\n return { alg: signer.alg, kid: signer.kid, trust_chain: signer.trustChain } as const\n }\n\n if (signer.method === 'jwk') {\n return { alg: signer.alg, jwk: signer.publicJwk } as const\n }\n\n if (signer.method === 'x5c') {\n return { alg: signer.alg, x5c: signer.x5c } as const\n }\n\n return signer.kid !== undefined ? ({ alg: signer.alg, kid: signer.kid } as const) : ({ alg: signer.alg } as const)\n}\n\nexport interface JwsSignerFromHeaderOptions {\n /** The protected header of the JWS. */\n header: JwsProtectedHeader\n\n /** The `iss` of a JWT, as a DID signer can be a DID in `iss` with a fragment in `kid`. */\n issuer?: string\n\n /** The signer methods the caller accepts. */\n allowedSignerMethods?: ReadonlyArray<JwsSignerMethod>\n\n /**\n * Whether to accept a header that identifies the signer in more than one way, taking the first allowed\n * of `x5c`, `trust_chain`, `did` and `jwk`. Off by default, so a trusted `x5c` next to an attacker's\n * `jwk` is rejected rather than resolved by precedence.\n *\n * @default false\n */\n allowMultipleSignerMethods?: boolean\n\n /**\n * Whether the DID in `kid` may differ from `iss`, as in `openid4vci-proof+jwt`, where `iss` is the\n * client id.\n *\n * @default false\n */\n allowDidKidIssuerMismatch?: boolean\n}\n\ntype FoundSigner =\n | { method: JwsSignerMethod; signer: JwsSigner; valid: true }\n | { method: JwsSignerMethod; error: string; valid: false }\n\n/**\n * The DID a DID URL refers to: everything before its path, query or fragment.\n *\n * @see https://www.w3.org/TR/did-core/#did-url-syntax\n */\nconst didOfDidUrl = (didUrl: string): string => {\n const end = didUrl.search(/[/?#]/)\n return end === -1 ? didUrl : didUrl.slice(0, end)\n}\n\n/**\n * Establishes the signer of a JWS from its header. Whether the key is trusted is for the verification\n * callback.\n *\n * @throws JoseSignerError if the signer cannot be established, or is identified in more than one way.\n */\nexport function jwsSignerFromHeader({\n header,\n issuer,\n allowedSignerMethods,\n allowMultipleSignerMethods = false,\n allowDidKidIssuerMismatch = false,\n}: JwsSignerFromHeaderOptions): JwsSigner {\n const found: FoundSigner[] = []\n\n if (header.x5c) {\n found.push({\n method: 'x5c',\n valid: true,\n signer: { method: 'x5c', alg: header.alg, x5c: header.x5c, kid: header.kid },\n })\n }\n\n if (header.trust_chain) {\n if (!header.kid) {\n found.push({\n method: 'federation',\n valid: false,\n error: `When 'trust_chain' is used in the header, the 'kid' parameter is required.`,\n })\n } else {\n found.push({\n method: 'federation',\n valid: true,\n signer: { method: 'federation', alg: header.alg, trustChain: header.trust_chain, kid: header.kid },\n })\n }\n }\n\n if (header.kid?.startsWith('did:') || issuer?.startsWith('did:')) {\n // An exact match: `did:web:example.com.evil.org` starts with `did:web:example.com`\n if (issuer && header.kid?.startsWith('did:') && didOfDidUrl(header.kid) !== issuer && !allowDidKidIssuerMismatch) {\n found.push({\n method: 'did',\n valid: false,\n error: `kid in header starts with a did that is different from the did value in 'iss'`,\n })\n } else if (!header.kid?.startsWith('did:') && !header.kid?.startsWith('#')) {\n found.push({\n method: 'did',\n valid: false,\n error: `kid in header must start with either 'did:' or '#' when the 'iss' value is a did`,\n })\n } else {\n found.push({\n method: 'did',\n valid: true,\n signer: {\n method: 'did',\n alg: header.alg,\n didUrl: header.kid.startsWith('did:') ? header.kid : `${issuer}${header.kid}`,\n },\n })\n }\n }\n\n if (header.jwk) {\n found.push({\n method: 'jwk',\n valid: true,\n signer: { method: 'jwk', alg: header.alg, publicJwk: header.jwk },\n })\n }\n\n const allowedFound = found.filter((f) => !allowedSignerMethods || allowedSignerMethods.includes(f.method))\n const allowedValid = allowedFound.filter((f) => f.valid)\n\n if (allowedValid.length > 1 && !allowMultipleSignerMethods) {\n throw new JoseSignerError(\n `Unable to establish the signer of the JWS. The header identifies the signer in ${allowedValid.length} ways (${allowedValid\n .map((f) => `'${f.method}'`)\n .join(\n ', '\n )}), and it is ambiguous which one applies. Narrow it down with 'allowedSignerMethods', or set 'allowMultipleSignerMethods'.`\n )\n }\n\n if (allowedValid.length > 0) return allowedValid[0].signer\n\n if (allowedFound.length > 0) {\n throw new JoseSignerError(\n `Unable to establish the signer of the JWS. Found ${allowedFound.length} allowed signer method(s), but they contained an invalid configuration:\\n${allowedFound\n .map((f) => (f.valid ? '' : `FAILED: method ${f.method} - ${f.error}`))\n .join('\\n')}`\n )\n }\n\n if (found.length > 0) {\n throw new JoseSignerError(\n `Unable to establish the signer of the JWS. Found ${found.length} signer method(s) that are not allowed:\\n${found\n .map((f) => (f.valid ? `SUCCEEDED: method ${f.method}` : `FAILED: method ${f.method} - ${f.error}`))\n .join('\\n')}`\n )\n }\n\n if (!allowedSignerMethods || allowedSignerMethods.includes('custom')) {\n return { method: 'custom', alg: header.alg, kid: header.kid }\n }\n\n throw new JoseSignerError(\n `Unable to establish the signer of the JWS. The header identifies no signer method, and the 'custom' signer method is not allowed.`\n )\n}\n","import { JoseInvalidArgumentError } from '../error'\nimport { zJwkThumbprintComponents } from '../jwk/thumbprint'\nimport type { Jwk } from '../jwk/z-jwk'\nimport { type JwsSigner, type JwsSignerMethod, jwsHeaderFromSigner } from './signer'\n\nconst isSameList = (a: ReadonlyArray<string>, b: ReadonlyArray<string>): boolean =>\n a.length === b.length && a.every((value, index) => value === b[index])\n\n/** Same key when the RFC 7638 thumbprint members match, or all members for key types RFC 7638 doesn't cover. */\nconst isSameKey = (a: Jwk, b: Jwk): boolean => {\n const componentsA = zJwkThumbprintComponents.safeParse(a)\n const componentsB = zJwkThumbprintComponents.safeParse(b)\n if (componentsA.success && componentsB.success) {\n return JSON.stringify(componentsA.data) === JSON.stringify(componentsB.data)\n }\n if (componentsA.success || componentsB.success) return false\n\n const membersOf = (jwk: Jwk) => Object.keys(jwk).filter((member) => jwk[member] !== undefined)\n const membersA = membersOf(a)\n return (\n membersA.length === membersOf(b).length &&\n membersA.every((member) => JSON.stringify(a[member]) === JSON.stringify(b[member]))\n )\n}\n\n/**\n * Rejects a header that contradicts the signer, or that also identifies a signer of another method, as\n * `jwsSignerFromHeader` would establish another signer from it. The header doesn't have to identify the signer.\n *\n * @throws JoseInvalidArgumentError if the header identifies another signer.\n */\nexport function assertHeaderIdentifiesSigner(\n header: { kid?: string; jwk?: Jwk; x5c?: ReadonlyArray<string>; trust_chain?: ReadonlyArray<string> },\n signer: JwsSigner,\n issuer: string | undefined\n): void {\n const signerHeader: {\n kid?: string\n jwk?: Jwk\n x5c?: ReadonlyArray<string>\n trust_chain?: ReadonlyArray<string>\n } = jwsHeaderFromSigner(signer)\n\n if (header.kid !== undefined && signerHeader.kid !== undefined && header.kid !== signerHeader.kid) {\n throw new JoseInvalidArgumentError(\n `Unable to sign the JWS, the kid in the header is '${header.kid}', but the signer is identified by kid '${signerHeader.kid}'.`\n )\n }\n\n if (header.x5c !== undefined && signerHeader.x5c !== undefined && !isSameList(header.x5c, signerHeader.x5c)) {\n throw new JoseInvalidArgumentError(\n 'Unable to sign the JWS, the x5c in the header is not the certificate chain of the signer.'\n )\n }\n\n if (\n header.trust_chain !== undefined &&\n signerHeader.trust_chain !== undefined &&\n !isSameList(header.trust_chain, signerHeader.trust_chain)\n ) {\n throw new JoseInvalidArgumentError(\n 'Unable to sign the JWS, the trust_chain in the header is not the trust chain of the signer.'\n )\n }\n\n if (header.jwk !== undefined && signerHeader.jwk !== undefined && !isSameKey(header.jwk, signerHeader.jwk)) {\n throw new JoseInvalidArgumentError(\n 'Unable to sign the JWS, the jwk in the header is not the public key of the signer.'\n )\n }\n\n // A custom signer is established out of band, so the header can identify it in any way\n if (signer.method === 'custom') return\n\n // A `kid` fragment identifies a did signer when `iss` is a DID, as `jwsSignerFromHeader` resolves it against `iss`\n const kidIdentifiesDid =\n header.kid?.startsWith('did:') === true ||\n (header.kid?.startsWith('#') === true && issuer?.startsWith('did:') === true)\n const identifiedMethods: Array<[parameter: string, method: JwsSignerMethod, present: boolean]> = [\n ['x5c', 'x5c', header.x5c !== undefined],\n ['trust_chain', 'federation', header.trust_chain !== undefined],\n ['kid', 'did', kidIdentifiesDid],\n ['jwk', 'jwk', header.jwk !== undefined],\n ]\n const otherMethod = identifiedMethods.find(([, method, present]) => present && method !== signer.method)\n if (otherMethod) {\n const [parameter, method] = otherMethod\n throw new JoseInvalidArgumentError(\n `Unable to sign the JWS, the '${parameter}' in the header identifies a signer with method '${method}', but the signer has method '${signer.method}'.`\n )\n }\n}\n","import { base64url, parseWithErrorHandling, stringToBytes, zBase64Url } from '@owf/identity-common'\nimport type { SignJwsCallback } from '../callbacks'\nimport { JoseInvalidArgumentError, JoseValidationError } from '../error'\nimport type { Jwk } from '../jwk/z-jwk'\nimport { decodeUnencodedPayload, encodeBase64UrlJson, unencodedCompactPayloadIssue } from '../utils/encoding'\nimport { assertCriticalHeaderParameters, isPayloadBase64UrlEncoded } from './critical-headers'\nimport type { JwsSigner } from './signer'\nimport { assertHeaderIdentifiesSigner } from './signer-header'\nimport { zJwsProtectedHeader } from './z-jws'\n\nexport interface SignCompactJwsOptions {\n /** The protected header, validated against {@link zJwsProtectedHeader}. Its `alg` must be the signer's. */\n protectedHeader: Record<string, unknown>\n\n /** The payload. An object is serialized as JSON, a string is encoded as UTF-8. */\n payload: Record<string, unknown> | string | Uint8Array\n\n /** The signer, which the callback resolves into a key. */\n signer: JwsSigner\n\n /** Callback that produces the signature. */\n signJwsCallback: SignJwsCallback\n\n /**\n * Whether to leave the payload out of the compact serialization, to carry it out of band.\n *\n * @default false\n */\n detachPayload?: boolean\n}\n\nexport interface SignCompactJwsResult {\n /** The compact serialization. Its payload part is empty when `detachPayload` was set. */\n compact: string\n\n /** The signature, base64url encoded. */\n signature: string\n\n /** The bytes that were signed, as a string. */\n signingInput: string\n\n /** The public key the JWS was signed with, as reported by the callback. */\n signerJwk: Jwk\n}\n\n/**\n * Signs a JWS in compact serialization. The callback signs the exact bytes that end up in the token.\n *\n * @throws JoseValidationError if the protected header is not a valid JWS header.\n * @throws JoseValidationError with an `invalid_crit` issue if `crit` is invalid.\n * @throws JoseNotSupportedError if the payload is unencoded (`b64` is false) and not valid UTF-8.\n * @throws JoseInvalidArgumentError if the signer uses another algorithm than the header names, the\n * header identifies another signer (a `kid`, `x5c`, `jwk` or `trust_chain` that is not the signer's, or\n * one of another signer method), the\n * callback does not return a base64url encoded signature, or the payload is unencoded, not detached,\n * and contains a character RFC 7797 does not allow in a compact serialization: a '.', or anything\n * outside printable ASCII.\n */\nexport async function signCompactJws(options: SignCompactJwsOptions): Promise<SignCompactJwsResult> {\n const protectedHeader = parseWithErrorHandling(\n zJwsProtectedHeader,\n options.protectedHeader,\n 'Unable to sign the JWS, invalid header',\n JoseValidationError\n )\n\n // A producer understands what it marks critical\n assertCriticalHeaderParameters({ protectedHeader, understoodCriticalParameters: protectedHeader.crit ?? [] })\n\n if (options.signer.alg !== protectedHeader.alg) {\n throw new JoseInvalidArgumentError(\n `Unable to sign the JWS, the header says alg '${protectedHeader.alg}' but the signer signs with alg '${options.signer.alg}'.`\n )\n }\n\n const jwtPayload =\n typeof options.payload === 'object' && !(options.payload instanceof Uint8Array) ? options.payload : undefined\n assertHeaderIdentifiesSigner(\n protectedHeader,\n options.signer,\n typeof jwtPayload?.iss === 'string' ? jwtPayload.iss : undefined\n )\n\n const payload =\n typeof options.payload === 'string'\n ? stringToBytes(options.payload)\n : options.payload instanceof Uint8Array\n ? options.payload\n : stringToBytes(JSON.stringify(options.payload))\n\n const isBase64UrlEncoded = isPayloadBase64UrlEncoded(protectedHeader)\n\n const encodedProtectedHeader = encodeBase64UrlJson(protectedHeader)\n const encodedPayload = isBase64UrlEncoded ? base64url.encode(payload) : decodeUnencodedPayload(payload)\n const signingInput = `${encodedProtectedHeader}.${encodedPayload}`\n\n // RFC 7797 section 5.2\n const compactPayloadIssue =\n !isBase64UrlEncoded && !options.detachPayload ? unencodedCompactPayloadIssue(encodedPayload) : undefined\n if (compactPayloadIssue) {\n throw new JoseInvalidArgumentError(\n `Unable to sign the JWS. ${compactPayloadIssue} Detach the payload, or leave out 'b64' so that it is base64url encoded.`\n )\n }\n\n const { signature, signerJwk } = await options.signJwsCallback(options.signer, {\n signingInput,\n signingInputBytes: stringToBytes(signingInput),\n protectedHeader,\n payload,\n jwtPayload,\n })\n\n // The signature is written into the token as it is, so it has to be what a parser accepts there\n if (!zBase64Url.min(1).safeParse(signature).success) {\n throw new JoseInvalidArgumentError(\n 'Unable to sign the JWS, the signature returned by the signing callback is not a non-empty base64url string.'\n )\n }\n\n return {\n compact: `${encodedProtectedHeader}.${options.detachPayload ? '' : encodedPayload}.${signature}`,\n signature,\n signingInput,\n signerJwk,\n }\n}\n","import { parseWithErrorHandling, stringToBytes } from '@owf/identity-common'\nimport type { VerifyJwsCallback } from '../callbacks'\nimport { JoseAlgorithmNotAllowedError, JoseSignatureVerificationError, JoseValidationError } from '../error'\nimport { isJwaSignatureAlgorithmCaseVariant, isSymmetricSignatureAlgorithm } from '../jwa/algorithms'\nimport { assertKeyAllowedForSignatureAlgorithm } from '../jwa/key-compatibility'\nimport { zJwsAlg } from '../jwa/z-alg'\nimport { zJwk } from '../jwk/z-jwk'\nimport type { JwtPayload } from '../jwt/z-jwt'\nimport type { ParsedJws } from './parse-jws'\nimport type { JwsSigner, JwsSignerMethod, JwsSignerWithJwk } from './signer'\nimport { jwsSignerFromHeader } from './signer'\nimport { zJwsProtectedHeader } from './z-jws'\n\n/**\n * The parts of a parsed JWS that verification needs. Without `registeredProtectedHeader`,\n * `protectedHeader` is validated against {@link zJwsProtectedHeader} and used instead.\n */\nexport type VerifiableJws = Pick<\n ParsedJws,\n 'protectedHeader' | 'unprotectedHeader' | 'signingInput' | 'signature' | 'payload' | 'compact'\n> &\n Partial<Pick<ParsedJws, 'registeredProtectedHeader'>>\n\nexport interface VerifyJwsSignatureOptions {\n /** The parsed JWS, as returned by `parseJws`. */\n jws: VerifiableJws\n\n /** Callback that verifies the signature and decides whether the key is trusted. */\n verifyJwsCallback: VerifyJwsCallback\n\n /**\n * The signer to verify against. Its `alg` must be the `alg` of the JWS. Established from the header\n * when not provided, see {@link jwsSignerFromHeader}.\n */\n signer?: JwsSigner\n\n /** The signer methods the caller accepts, used when the signer is established from the header. */\n allowedSignerMethods?: ReadonlyArray<JwsSignerMethod>\n\n /**\n * See {@link JwsSignerFromHeaderOptions.allowMultipleSignerMethods}.\n *\n * @default false\n */\n allowMultipleSignerMethods?: boolean\n\n /**\n * See {@link JwsSignerFromHeaderOptions.allowDidKidIssuerMismatch}.\n *\n * @default false\n */\n allowDidKidIssuerMismatch?: boolean\n\n /**\n * The algorithms the caller accepts: pass the ones the signer is known to use. Without it, any\n * algorithm is accepted except `none`, symmetric ones and registered ones in a different casing.\n */\n allowedAlgorithms?: ReadonlyArray<string>\n\n /**\n * Whether `HS256`, `HS384` and `HS512` are accepted. Off by default, as with a symmetric algorithm\n * every verifier can also issue a token.\n *\n * @default false\n */\n allowSymmetricAlgorithms?: boolean\n\n /** The payload as a JSON object, when the JWS is a JWT. Passed to the callback, and a did signer is bound to its `iss`. */\n jwtPayload?: JwtPayload\n\n /** Prefix for the error thrown when verification fails. */\n errorMessage?: string\n}\n\nexport interface AssertJwsAlgorithmAllowedOptions {\n /** The `alg` of the JWS. */\n alg: string\n\n /** The algorithms the caller accepts. See {@link VerifyJwsSignatureOptions.allowedAlgorithms}. */\n allowedAlgorithms?: ReadonlyArray<string>\n\n /** Whether a symmetric signature algorithm is acceptable. See {@link VerifyJwsSignatureOptions.allowSymmetricAlgorithms}. */\n allowSymmetricAlgorithms?: boolean\n\n /** Prefix for the error thrown when the algorithm is not accepted. */\n errorMessage?: string\n}\n\n/**\n * The algorithm policy of {@link verifyJwsSignature}, for code that verifies a signature without a\n * {@link VerifyJwsCallback}.\n *\n * @throws JoseAlgorithmNotAllowedError if the algorithm is not accepted.\n */\nexport function assertJwsAlgorithmAllowed({\n alg,\n allowedAlgorithms,\n allowSymmetricAlgorithms = false,\n errorMessage = 'Error during verification of the JWS.',\n}: AssertJwsAlgorithmAllowedOptions): void {\n // `alg` does not have to come from a parsed header\n if (!zJwsAlg.safeParse(alg).success) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} The JWS uses alg '${alg}', which is not a signature algorithm. An unsecured JWS is never accepted.`\n )\n }\n\n if (isJwaSignatureAlgorithmCaseVariant(alg)) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} The JWS uses alg '${alg}', which differs from a registered algorithm only in casing. Algorithm names are case-sensitive.`\n )\n }\n\n if (allowedAlgorithms && !allowedAlgorithms.includes(alg)) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} The JWS uses alg '${alg}', but the allowed algorithms are ${allowedAlgorithms\n .map((allowed) => `'${allowed}'`)\n .join(', ')}.`\n )\n }\n\n if (isSymmetricSignatureAlgorithm(alg) && !allowSymmetricAlgorithms) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} The JWS uses the symmetric algorithm '${alg}'. Set 'allowSymmetricAlgorithms' if a MAC is expected here.`\n )\n }\n}\n\nexport interface VerifyJwsSignatureResult {\n /** The signer, with the public key the signature was verified with. */\n signer: JwsSignerWithJwk\n}\n\n/**\n * Verifies the signature over a parsed JWS: the algorithm policy before the callback, and the key the\n * callback returns against the algorithm after it.\n *\n * @throws JoseAlgorithmNotAllowedError if the algorithm is not accepted, or does not match the key or\n * the `alg` of the given `signer`.\n * @throws JoseSignatureVerificationError if the signature does not verify.\n * @throws JoseSignerError if the signer cannot be established from the header.\n * @throws JoseValidationError if the JWS has no `registeredProtectedHeader`, and its `protectedHeader`\n * is not a valid JWS protected header.\n */\nexport async function verifyJwsSignature(options: VerifyJwsSignatureOptions): Promise<VerifyJwsSignatureResult> {\n const errorMessage = options.errorMessage ?? 'Error during verification of the JWS.'\n\n // Security checks use the registered header, not what a caller's schema made of it\n const protectedHeader =\n options.jws.registeredProtectedHeader ??\n parseWithErrorHandling(\n zJwsProtectedHeader,\n options.jws.protectedHeader,\n 'Invalid JWS protected header',\n JoseValidationError\n )\n const alg = protectedHeader.alg\n\n assertJwsAlgorithmAllowed({\n alg,\n allowedAlgorithms: options.allowedAlgorithms,\n allowSymmetricAlgorithms: options.allowSymmetricAlgorithms,\n errorMessage,\n })\n\n // The callback verifies with `signer.alg`, so it must be the alg the policy was applied to\n if (options.signer && options.signer.alg !== alg) {\n throw new JoseAlgorithmNotAllowedError(\n `${errorMessage} The JWS uses alg '${alg}', but the signer to verify against uses alg '${options.signer.alg}'.`\n )\n }\n\n const signer =\n options.signer ??\n jwsSignerFromHeader({\n header: protectedHeader,\n issuer: typeof options.jwtPayload?.iss === 'string' ? options.jwtPayload.iss : undefined,\n allowedSignerMethods: options.allowedSignerMethods,\n allowMultipleSignerMethods: options.allowMultipleSignerMethods,\n allowDidKidIssuerMismatch: options.allowDidKidIssuerMismatch,\n })\n\n let signerJwk: JwsSignerWithJwk['publicJwk']\n try {\n const result = await options.verifyJwsCallback(signer, {\n signingInput: options.jws.signingInput,\n signingInputBytes: stringToBytes(options.jws.signingInput),\n protectedHeader,\n unprotectedHeader: options.jws.unprotectedHeader,\n payload: options.jws.payload,\n jwtPayload: options.jwtPayload,\n signature: options.jws.signature,\n compact: options.jws.compact,\n })\n\n if (!result.verified) throw new JoseSignatureVerificationError(errorMessage)\n\n // Without the key, it cannot be checked against the algorithm below\n if (!zJwk.safeParse(result.signerJwk).success) {\n throw new JoseSignatureVerificationError(\n `${errorMessage} The verification callback reported the signature as verified, but did not return the jwk it was verified with.`\n )\n }\n signerJwk = result.signerJwk\n } catch (error) {\n if (error instanceof JoseSignatureVerificationError) throw error\n throw new JoseSignatureVerificationError(errorMessage, { cause: error })\n }\n\n assertKeyAllowedForSignatureAlgorithm({\n jwk: signerJwk,\n alg,\n errorMessage: `${errorMessage} The key the JWS was verified with cannot be used with its algorithm.`,\n })\n\n return { signer: { ...signer, publicJwk: signerJwk } }\n}\n","import { addValidationIssue, zBase64Url, zNonEmptyString, zNumericDate } from '@owf/identity-common'\nimport z from 'zod'\nimport { zPublicJwk } from '../jwk/z-jwk'\nimport { zJwsProtectedHeader } from '../jws/z-jws'\nimport { zCompactSerialization, zStringOrUri } from '../utils/z-common'\n\n/**\n * The header of a JWT, which is a JWS protected header.\n *\n * Compose on top of it to require what a token type needs, in particular its `typ`:\n *\n * ```ts\n * const zKbJwtHeader = z.object({ ...zJwtHeader.shape, typ: zTyp('kb+jwt') }).loose()\n * ```\n */\nexport const zJwtHeader = zJwsProtectedHeader\n\nexport type JwtHeader = z.infer<typeof zJwtHeader>\n\n/** The `cnf` members that each name the key, of which a `cnf` has at most one. */\nconst confirmationKeyMembers = ['jwk', 'jwe', 'jku', 'jkt'] as const\n\n/**\n * The `cnf` (confirmation) claim, which names the one key a token is bound to.\n *\n * The key is named in one way only, so that every verifier binds the token to the same key:\n * - at most one of `jwk`, `jwe`, `jku` (RFC 7800 section 3.1) and `jkt` (RFC 9449)\n * - `kid` on its own, e.g. a DID URL, or with `jku` to select the key from the set (RFC 7800\n * section 3.5) or with `jkt` that the key it resolves to has to match. Not with `jwk` or `jwe`,\n * which carry the key itself, and with it its `kid`.\n *\n * A token bound to several keys carries the others in claims of its own.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7800#section-3.1\n */\nexport const zJwtConfirmation = z\n .object({\n /** The public key the token is bound to. */\n jwk: zPublicJwk.optional(),\n\n /** The JWK thumbprint of the key the token is bound to, e.g. of a DPoP key. */\n jkt: zBase64Url.min(1).optional(),\n\n /** A key id, to be resolved by the recipient. */\n kid: zNonEmptyString.optional(),\n })\n .loose()\n .superRefine((cnf, ctx) => {\n const keyMembers = confirmationKeyMembers.filter((member) => cnf[member] !== undefined)\n for (const member of keyMembers.slice(1)) {\n addValidationIssue(ctx, {\n code: 'not_allowed',\n path: [member],\n message: `The cnf claim names its key with '${keyMembers[0]}', so it may not also have '${member}'`,\n })\n }\n\n if (cnf.kid !== undefined && (cnf.jwk !== undefined || cnf.jwe !== undefined)) {\n addValidationIssue(ctx, {\n code: 'not_allowed',\n path: ['kid'],\n message: `The cnf claim carries its key in '${cnf.jwk !== undefined ? 'jwk' : 'jwe'}', so it may not also have a 'kid'`,\n })\n }\n })\n\nexport type JwtConfirmation = z.infer<typeof zJwtConfirmation>\n\n/**\n * The claims registered for a JWT.\n *\n * All of them are optional, as RFC 7519 requires none: which claims a token must carry follows from\n * the token type, and is expressed by composing on this schema and by `requiredClaims` at\n * verification time.\n *\n * The schema is loose, so claims that are not registered are carried through unvalidated.\n *\n * @see https://www.rfc-editor.org/rfc/rfc7519#section-4.1\n */\nexport const zJwtPayload = z\n .object({\n iss: zStringOrUri.optional(),\n sub: zStringOrUri.optional(),\n aud: z.union([zStringOrUri, z.array(zStringOrUri)]).optional(),\n exp: zNumericDate.optional(),\n nbf: zNumericDate.optional(),\n iat: zNumericDate.optional(),\n jti: zNonEmptyString.optional(),\n\n /** Not registered by RFC 7519, but used the same way across OpenID Connect and OAuth 2.0. */\n nonce: zNonEmptyString.optional(),\n\n cnf: zJwtConfirmation.optional(),\n\n /** Reserved for the Token Status List. @see https://datatracker.ietf.org/doc/draft-ietf-oauth-status-list */\n status: z.record(z.string(), z.unknown()).optional(),\n\n /** Reserved for OpenID Federation. */\n trust_chain: z.tuple([zNonEmptyString], zNonEmptyString).optional(),\n })\n .loose()\n\nexport type JwtPayload = z.infer<typeof zJwtPayload>\n\n/**\n * A JWT in compact serialization.\n *\n * Unlike `zCompactJws` the payload part may not be empty: a JWT carries its claims set, so a\n * detached payload is not a JWT.\n */\nexport const zCompactJwt = zCompactSerialization('jwt', 3)\n","import { type BaseSchema, parseWithErrorHandling } from '@owf/identity-common'\nimport { JoseNotSupportedError, JoseParseError, JoseValidationError } from '../error'\nimport { zJweHeader } from '../jwe/z-jwe'\nimport { parseJws } from '../jws/parse-jws'\nimport { decodeBase64UrlJsonObject } from '../utils/encoding'\nimport type { InferSchemaOrDefaultOutput } from '../utils/zod'\nimport { type JwtHeader, type JwtPayload, zJwtHeader, zJwtPayload } from './z-jwt'\n\nexport interface DecodeJwtOptions<\n HeaderSchema extends BaseSchema | undefined,\n PayloadSchema extends BaseSchema | undefined,\n> {\n /** The compact encoded JWT. */\n jwt: string\n\n /**\n * Schema to validate the header with, on top of {@link zJwtHeader}, which is always applied.\n */\n headerSchema?: HeaderSchema\n\n /**\n * Schema to validate the payload with, on top of {@link zJwtPayload}, which is always applied so\n * that a registered claim always has the shape RFC 7519 gives it.\n */\n payloadSchema?: PayloadSchema\n\n /** The critical header parameters the caller understands. */\n understoodCriticalParameters?: ReadonlyArray<string>\n}\n\nexport interface DecodeJwtResult<\n HeaderSchema extends BaseSchema | undefined = undefined,\n PayloadSchema extends BaseSchema | undefined = undefined,\n> {\n /** The header, as `headerSchema` returned it. */\n header: InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>\n\n /** The claims set, as `payloadSchema` returned it. */\n payload: InferSchemaOrDefaultOutput<PayloadSchema, typeof zJwtPayload>\n\n /**\n * The header as validated against {@link zJwtHeader} alone, whatever `headerSchema` was given.\n *\n * `verifyJwt` makes its checks on this rather than on {@link header}: a schema of the caller's can\n * drop or change the parameters the checks depend on.\n */\n registeredHeader: JwtHeader\n\n /**\n * The claims set as validated against {@link zJwtPayload} alone, whatever `payloadSchema` was given.\n *\n * `verifyJwt` verifies the claims on this rather than on {@link payload}, so that a schema that\n * drops `exp` or fills in `iat` cannot change the outcome.\n */\n registeredPayload: JwtPayload\n\n /** The claims set as bytes, exactly as they were carried in the token. */\n payloadBytes: Uint8Array\n\n /** The signature, base64url encoded. */\n signature: string\n\n /** The bytes covered by the signature, as an ASCII string. */\n signingInput: string\n\n /** The compact JWT that was decoded. */\n compact: string\n}\n\n/**\n * Decodes a JWT and validates its header and payload, without verifying the signature.\n *\n * Everything is decoded through `@owf/identity-common`, so a token with an invalid base64url\n * alphabet, invalid UTF-8 or invalid JSON is rejected rather than being decoded into something that\n * looks close enough.\n *\n * @throws JoseParseError if the JWT is not well-formed.\n * @throws JoseValidationError if the header or payload does not validate.\n */\nexport function decodeJwt<\n HeaderSchema extends BaseSchema | undefined = undefined,\n PayloadSchema extends BaseSchema | undefined = undefined,\n>(options: DecodeJwtOptions<HeaderSchema, PayloadSchema>): DecodeJwtResult<HeaderSchema, PayloadSchema> {\n const jws = parseJws({\n jws: options.jwt,\n protectedHeaderSchema: options.headerSchema,\n understoodCriticalParameters: options.understoodCriticalParameters,\n })\n\n // RFC 7519 defines the claims set as base64url encoded JSON, so RFC 7797's unencoded payload is\n // not a JWT. Allowing it would mean a token whose claims are not where a JWT's claims are.\n if (jws.registeredProtectedHeader.b64 === false) {\n throw new JoseNotSupportedError(\n `Unable to decode the JWT, its header sets 'b64' to false. An unencoded payload is not valid for a JWT.`\n )\n }\n\n if (jws.encodedPayload === '') {\n throw new JoseParseError('Unable to decode the JWT, it does not contain a payload')\n }\n\n const payloadJson = decodeBase64UrlJsonObject(jws.encodedPayload, 'JWT payload')\n\n // Always validated against the registered claims, and only then against the caller's schema: a\n // schema describing a profile's own claims must not be able to leave `exp` unchecked as a number.\n const registeredPayload = parseWithErrorHandling(zJwtPayload, payloadJson, 'Invalid JWT payload', JoseValidationError)\n const payload = parseWithErrorHandling(\n options.payloadSchema ?? zJwtPayload,\n payloadJson,\n 'Invalid JWT payload',\n JoseValidationError\n )\n\n return {\n header: jws.protectedHeader as InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>,\n payload: payload as InferSchemaOrDefaultOutput<PayloadSchema, typeof zJwtPayload>,\n registeredHeader: jws.registeredProtectedHeader,\n registeredPayload,\n payloadBytes: jws.payload,\n signature: jws.signature,\n signingInput: jws.signingInput,\n compact: options.jwt,\n }\n}\n\nexport interface DecodeJwtHeaderOptions<HeaderSchema extends BaseSchema | undefined> {\n /** The compact encoded JWT or JWE. */\n jwt: string\n\n /**\n * Schema to validate the header with, on top of {@link zJwtHeader} — and {@link zJweHeader} for a\n * JWE — which are always applied.\n */\n headerSchema?: HeaderSchema\n}\n\n/**\n * Decodes and validates only the header of a compact JWT or JWE.\n *\n * Useful when the header decides what to do next — which key to look up, or how to decrypt — and the\n * rest of the token cannot be read yet.\n *\n * @throws JoseParseError if the token is not well-formed.\n * @throws JoseValidationError if the header does not validate.\n */\nexport function decodeJwtHeader<HeaderSchema extends BaseSchema | undefined = undefined>(\n options: DecodeJwtHeaderOptions<HeaderSchema>\n): { header: InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader> } {\n const parts = options.jwt.split('.')\n\n // Three parts for a JWS, five for a JWE.\n if (parts.length !== 3 && parts.length !== 5) {\n throw new JoseParseError(\n 'Unable to decode the header, the token is neither a compact JWS (three parts) nor a compact JWE (five parts)'\n )\n }\n\n const headerJson = decodeBase64UrlJsonObject(parts[0], 'header')\n\n // Always validated against the registered header parameters, and only then against the caller's\n // schema, the way `decodeJwt` validates a header: a schema of the caller's must not be able to let\n // `alg: none` or a private `jwk` through. A JWE is held to the JWE header parameters as well, which\n // require `enc` and an `epk` that is a public key.\n const registeredHeader = parseWithErrorHandling(zJwtHeader, headerJson, 'Invalid header', JoseValidationError)\n if (parts.length === 5) parseWithErrorHandling(zJweHeader, headerJson, 'Invalid JWE header', JoseValidationError)\n const header = options.headerSchema\n ? parseWithErrorHandling(options.headerSchema, headerJson, 'Invalid header', JoseValidationError)\n : registeredHeader\n\n return { header: header as InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader> }\n}\n","import { type BaseSchema, type MarkOptional, parseWithErrorHandling } from '@owf/identity-common'\nimport type z from 'zod'\nimport type { SignJwsCallback } from '../callbacks'\nimport { JoseNotSupportedError, JoseValidationError } from '../error'\nimport type { Jwk } from '../jwk/z-jwk'\nimport { signCompactJws } from '../jws/sign-jws'\nimport type { JwsSigner } from '../jws/signer'\nimport type { InferSchemaOrDefaultOutput } from '../utils/zod'\nimport { type JwtHeader, zJwtHeader, zJwtPayload } from './z-jwt'\n\nexport interface SignJwtOptions<\n HeaderSchema extends BaseSchema | undefined,\n PayloadSchema extends BaseSchema | undefined,\n Signer extends JwsSigner = JwsSigner,\n> {\n /**\n * The header.\n *\n * Typed from `headerSchema` when one is given, with `alg` made optional: it is taken from the\n * signer, which is what says how the token is actually signed.\n *\n * The parameters that identify the key — `kid`, `jwk`, `x5c`, `trust_chain` — are not added: which\n * of them a token carries is decided by the token type, not by how the key happens to be\n * addressed. Spread {@link jwsHeaderFromSigner} into the header to add them.\n */\n header?: HeaderSchema extends BaseSchema ? MarkOptional<z.input<HeaderSchema>, 'alg'> : Record<string, unknown>\n\n /** The claims set. Typed from `payloadSchema` when one is given. */\n payload: PayloadSchema extends BaseSchema ? z.input<PayloadSchema> : Record<string, unknown>\n\n /**\n * Schema to validate the header with, on top of {@link zJwtHeader}, which is always applied.\n *\n * Pass the same schema the recipient verifies with, so that a token is checked against the profile\n * it is meant to satisfy before it is signed rather than after it is rejected.\n */\n headerSchema?: HeaderSchema\n\n /**\n * Schema to validate the claims set with, on top of {@link zJwtPayload}, which is always applied.\n */\n payloadSchema?: PayloadSchema\n\n /** The signer, which the callback resolves into a key. */\n signer: Signer\n\n /** Callback that produces the signature. */\n signJwsCallback: SignJwsCallback\n}\n\nexport interface SignJwtResult<\n HeaderSchema extends BaseSchema | undefined = undefined,\n PayloadSchema extends BaseSchema | undefined = undefined,\n> {\n /** The signed JWT in compact serialization. */\n jwt: string\n\n /** The public key the JWT was signed with, as reported by the callback. */\n signerJwk: Jwk\n\n /** The header that was signed. */\n header: InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>\n\n /** The claims set that was signed. */\n payload: InferSchemaOrDefaultOutput<PayloadSchema, typeof zJwtPayload>\n}\n\n/**\n * Signs a JWT.\n *\n * The header and the claims set are validated before they are signed, so that a token this library\n * produces is a token it would also accept. Passing the schemas of the token type being produced\n * extends that to the profile: a key binding JWT missing its `sd_hash` fails here rather than at the\n * verifier.\n *\n * What is signed is the validated value, so a schema that fills in a default or narrows a claim\n * shapes the token rather than being checked against it and then discarded. That value is validated\n * against the registered claims as well.\n *\n * @throws JoseValidationError if the header or the claims set is not valid.\n * @throws JoseNotSupportedError if the header sets `b64` to false, which is not valid for a JWT.\n */\nexport async function signJwt<\n HeaderSchema extends BaseSchema | undefined = undefined,\n PayloadSchema extends BaseSchema | undefined = undefined,\n Signer extends JwsSigner = JwsSigner,\n>(options: SignJwtOptions<HeaderSchema, PayloadSchema, Signer>): Promise<SignJwtResult<HeaderSchema, PayloadSchema>> {\n // `alg` is applied last: the signer is what says how the token is signed, so the header must not\n // be able to claim a different algorithm than the one actually used.\n const headerJson = { ...options.header, alg: options.signer.alg }\n\n // Always validated against the registered header parameters and claims, and only then against the\n // caller's schemas, the same way `decodeJwt` validates a token that is read.\n parseWithErrorHandling(zJwtHeader, headerJson, 'Unable to sign the JWT, invalid header', JoseValidationError)\n const header = parseWithErrorHandling(\n options.headerSchema ?? zJwtHeader,\n headerJson,\n 'Unable to sign the JWT, invalid header',\n JoseValidationError\n )\n\n // RFC 7519 defines the claims set as base64url encoded JSON, so a JWT with an unencoded payload\n // (RFC 7797) would be a token that `decodeJwt` rejects. The header that is signed is the one the\n // caller's schema returned, which `signCompactJws` validates as a JWS header.\n if ((header as JwtHeader).b64 === false) {\n throw new JoseNotSupportedError(\n `Unable to sign the JWT, its header sets 'b64' to false. An unencoded payload is not valid for a JWT.`\n )\n }\n\n parseWithErrorHandling(\n zJwtPayload,\n options.payload,\n 'Unable to sign the JWT, invalid claims set',\n JoseValidationError\n )\n const payload = parseWithErrorHandling(\n options.payloadSchema ?? zJwtPayload,\n options.payload,\n 'Unable to sign the JWT, invalid claims set',\n JoseValidationError\n )\n\n // What the caller's schema returned is what gets signed, so it is validated against the registered\n // claims too: a schema that transforms or fills in a registered claim must not be able to sign one\n // that `decodeJwt` would reject.\n parseWithErrorHandling(zJwtPayload, payload, 'Unable to sign the JWT, invalid claims set', JoseValidationError)\n\n const { compact, signerJwk } = await signCompactJws({\n protectedHeader: header,\n payload,\n signer: options.signer,\n signJwsCallback: options.signJwsCallback,\n })\n\n return {\n jwt: compact,\n signerJwk,\n header: header as InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>,\n payload: payload as InferSchemaOrDefaultOutput<PayloadSchema, typeof zJwtPayload>,\n }\n}\n","import { secondsToDate, ValidationIssues } from '@owf/identity-common'\nimport { JoseInvalidArgumentError, JoseValidationError, type JoseValidationIssue } from '../error'\nimport { hasOwn } from '../utils/object'\nimport type { JwtPayload } from './z-jwt'\n\n/**\n * The options {@link verifyJwtClaims} takes.\n *\n * These are the checks that cannot be expressed in a schema, because they compare the token against\n * something outside of it: the current time, the audience the verifier is, the nonce it issued.\n * Everything that follows from the token alone — which claims a token type requires, and what shape\n * they have — belongs in the payload schema instead.\n */\nexport interface VerifyJwtClaimsOptions {\n /** The time the token is verified at. Defaults to the current time. Must be a valid date. */\n now?: Date\n\n /**\n * Clock tolerance applied to `exp`, `nbf` and `iat`, in seconds. Defaults to 30, which keeps a\n * token that only just expired — or that was issued a moment ago by a slightly fast clock —\n * usable across the small clock differences typical between issuer and verifier.\n *\n * Must be a finite number of at least 0: anything else is rejected rather than letting a time\n * check pass that was never made.\n */\n skewSeconds?: number\n\n /**\n * The claims that must be present. A claim listed here is rejected when absent; a claim that is\n * absent and not listed is simply not checked.\n *\n * A claim whose value is `null` counts as present: `null` is a value the issuer put there, unlike\n * a claim that is not in the token at all.\n */\n requiredClaims?: ReadonlyArray<string>\n\n /**\n * The value(s) `iss` is accepted with.\n *\n * A token that does not carry the claim at all is rejected too: a claim that is absent does not\n * hold the value the caller said it expects.\n */\n expectedIssuer?: string | string[]\n\n /** The value(s) `sub` is accepted with. See {@link expectedIssuer} for an absent claim. */\n expectedSubject?: string | string[]\n\n /**\n * The value(s) `aud` is accepted with. The token is accepted when any of its audiences is one of\n * these. See {@link expectedIssuer} for an absent claim.\n */\n expectedAudience?: string | string[]\n\n /** The value `nonce` is accepted with. See {@link expectedIssuer} for an absent claim. */\n expectedNonce?: string\n\n /**\n * When false, `exp` is not looked at. Its presence is not checked either way — list it in\n * {@link requiredClaims} to require it.\n */\n checkExpirationTime?: boolean\n\n /** When false, `nbf` is not looked at. See {@link checkExpirationTime} for its presence. */\n checkNotBefore?: boolean\n\n /** When false, `iat` is not looked at. See {@link checkExpirationTime} for its presence. */\n checkIssuedAt?: boolean\n\n /**\n * The maximum age of the token in seconds, counted from `iat`. For a token that proves something\n * happened recently — a key binding JWT, a DPoP proof — rather than one that states its own\n * expiry.\n *\n * A token that carries no `iat` is rejected when this is set: a token that does not say when it\n * was issued cannot be shown to be recent. The skew applies, as it does to `exp`. Must be a finite\n * number of at least 0.\n */\n maxAgeSeconds?: number\n\n /** Message of the error thrown when a claim does not verify. */\n errorMessage?: string\n}\n\nconst asArray = (value: string | string[]) => (Array.isArray(value) ? value : [value])\nconst isNonNegativeFiniteNumber = (value: number) => Number.isFinite(value) && value >= 0\nconst quoted = (values: ReadonlyArray<string>) => values.map((value) => `'${value}'`).join(', ')\n\ntype ClaimIssues = ValidationIssues<JoseValidationIssue['code']>\n\n/**\n * Verifies the claims of a JWT: that the claims the caller requires are present, that `iss`, `sub`,\n * `aud` and `nonce` are the expected ones, and that the token is within its validity window.\n *\n * Which claims a JWT must carry, and what they must contain, is decided by the token type rather\n * than by RFC 7519, so nothing is required unless `requiredClaims` says so.\n *\n * This checks the claims only. The signature over them is verified separately — `verifyJwt` does\n * both, and is what a verifier wants.\n *\n * @throws JoseValidationError with an issue for each claim that does not verify: `claim_missing` for a\n * required claim that is absent, `claim_value_mismatch` for one that is not the expected value,\n * `expired` or `not_yet_valid` for a token outside its validity window, and `invalid_type` for a\n * time claim that is not a NumericDate.\n * @throws JoseInvalidArgumentError if `now` is not a valid date, or `skewSeconds` or `maxAgeSeconds`\n * is not a finite number of at least 0.\n */\nexport function verifyJwtClaims(\n payload: JwtPayload,\n {\n now = new Date(),\n skewSeconds = 30,\n requiredClaims,\n expectedIssuer,\n expectedSubject,\n expectedAudience,\n expectedNonce,\n checkExpirationTime = true,\n checkNotBefore = true,\n checkIssuedAt = true,\n maxAgeSeconds,\n errorMessage = 'Error during verification of the JWT claims.',\n }: VerifyJwtClaimsOptions = {}\n): void {\n // Every time check compares against `now` shifted by the skew. With `NaN` in either, every such\n // comparison is false, which accepts the token rather than rejecting it. A negative skew or maximum\n // age means nothing, and an infinite one accepts any token.\n if (!(now instanceof Date) || Number.isNaN(now.getTime())) {\n throw new JoseInvalidArgumentError(`${errorMessage} The 'now' option must be a valid date.`)\n }\n if (!isNonNegativeFiniteNumber(skewSeconds)) {\n throw new JoseInvalidArgumentError(\n `${errorMessage} The 'skewSeconds' option must be a finite number of at least 0, but is '${skewSeconds}'.`\n )\n }\n if (maxAgeSeconds !== undefined && !isNonNegativeFiniteNumber(maxAgeSeconds)) {\n throw new JoseInvalidArgumentError(\n `${errorMessage} The 'maxAgeSeconds' option must be a finite number of at least 0, but is '${maxAgeSeconds}'.`\n )\n }\n\n // The time claims are compared as numbers of seconds rather than as dates, so that a NumericDate\n // outside the range of a `Date` still orders: an `exp` of 9999999999999 does not expire.\n const nowSeconds = now.getTime() / 1000\n const issues: ClaimIssues = new ValidationIssues()\n\n for (const claim of requiredClaims ?? []) {\n if (!hasOwn(payload, claim)) addClaimMissing(issues, claim, `The token has no '${claim}' claim, which is required`)\n }\n\n verifyClaimMatches(issues, 'iss', payload.iss, expectedIssuer)\n verifyClaimMatches(issues, 'sub', payload.sub, expectedSubject)\n verifyClaimMatches(issues, 'nonce', payload.nonce, expectedNonce)\n verifyAudienceMatches(issues, payload.aud, expectedAudience)\n\n // Each time claim is read once, so a claim that is not a NumericDate gives one issue.\n const expirationTime = checkExpirationTime ? numericDate(issues, 'exp', payload.exp) : undefined\n const notBefore = checkNotBefore ? numericDate(issues, 'nbf', payload.nbf) : undefined\n const issuedAt = checkIssuedAt || maxAgeSeconds !== undefined ? numericDate(issues, 'iat', payload.iat) : undefined\n\n // `exp` is the first instant the token is no longer valid (RFC 7519 says a token must not be\n // accepted \"on or after\" it), so the comparison is inclusive. It is an upper bound shifted forward\n // by the skew: a token that expired within the tolerance is still accepted.\n if (expirationTime !== undefined && expirationTime + skewSeconds <= nowSeconds) {\n issues.add({\n code: 'expired',\n path: ['exp'],\n message: `The 'exp' claim '${formatNumericDate(expirationTime)}' is in the past (compared to '${now.toISOString()}')`,\n context: { expiredAt: secondsToDate(expirationTime) },\n })\n }\n\n if (notBefore !== undefined) verifyClaimNotInFuture(issues, 'nbf', notBefore, now, skewSeconds)\n if (checkIssuedAt && issuedAt !== undefined) verifyClaimNotInFuture(issues, 'iat', issuedAt, now, skewSeconds)\n\n if (maxAgeSeconds !== undefined) {\n if (payload.iat === undefined) {\n addClaimMissing(\n issues,\n 'iat',\n `The token has no 'iat' claim, which is required to verify that it is at most ${maxAgeSeconds} seconds old`\n )\n } else if (issuedAt !== undefined && issuedAt + maxAgeSeconds + skewSeconds < nowSeconds) {\n issues.add({\n code: 'expired',\n path: ['iat'],\n message: `The 'iat' claim '${formatNumericDate(issuedAt)}' is more than ${maxAgeSeconds} seconds in the past (compared to '${now.toISOString()}')`,\n context: { expiredAt: secondsToDate(issuedAt + maxAgeSeconds) },\n })\n }\n }\n\n if (issues.issues.length) throw new JoseValidationError(errorMessage, issues.issues)\n}\n\n/** A required claim is absent. A claim is reported once, however many checks need it. */\nfunction addClaimMissing(issues: ClaimIssues, claim: string, message: string): void {\n const reported = issues.issues.some((issue) => issue.code === 'claim_missing' && issue.path[0] === claim)\n if (!reported) issues.add({ code: 'claim_missing', path: [claim], message })\n}\n\n/**\n * The NumericDate a time claim holds, or `undefined` when the token does not carry the claim or it is\n * not a NumericDate.\n *\n * A claim that is present but is not a finite number gives an issue rather than being skipped: it\n * cannot be compared against `now` (with `NaN` every comparison would be false, which would accept\n * the token), and skipping it would accept a token whose validity window was never verified. A\n * payload parsed with `zJwtPayload` cannot get here, but one that reached the caller unvalidated can.\n *\n * Any finite number is a NumericDate, including one outside the range a `Date` can hold: it is\n * compared as a number of seconds.\n */\nfunction numericDate(issues: ClaimIssues, claim: string, value: unknown): number | undefined {\n if (value === undefined) return undefined\n\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n issues.add({\n code: 'invalid_type',\n path: [claim],\n message: `The '${claim}' claim '${String(value)}' is not a NumericDate`,\n context: { expected: 'number' },\n })\n return undefined\n }\n\n return value\n}\n\n/**\n * A NumericDate as it is printed in an issue: as a date where it has one, and as the number it is\n * where it is outside the range of a `Date`.\n */\nfunction formatNumericDate(seconds: number): string {\n const date = secondsToDate(seconds)\n return Number.isNaN(date.getTime()) ? String(seconds) : date.toISOString()\n}\n\nfunction verifyClaimMatches(\n issues: ClaimIssues,\n claim: string,\n value: unknown,\n expected: string | string[] | undefined\n): void {\n if (expected === undefined) return\n\n const expectedValues = asArray(expected)\n\n // An absent claim is a mismatch rather than something to skip: a token that does not say who\n // issued it is not a token issued by the expected issuer.\n if (value === undefined) {\n addClaimMissing(\n issues,\n claim,\n `The token has no '${claim}' claim, which is required to match the expected value ${quoted(expectedValues)}`\n )\n } else if (typeof value !== 'string' || !expectedValues.includes(value)) {\n issues.add({\n code: 'claim_value_mismatch',\n path: [claim],\n message: `The '${claim}' claim '${String(value)}' does not match the expected value ${quoted(expectedValues)}`,\n context: { expected: expectedValues, actual: value },\n })\n }\n}\n\n/** `aud` may hold several audiences, and the token is for us as soon as one of them is expected. */\nfunction verifyAudienceMatches(\n issues: ClaimIssues,\n audience: string | string[] | undefined,\n expected: string | string[] | undefined\n): void {\n if (expected === undefined) return\n\n const expectedValues = asArray(expected)\n\n // See `verifyClaimMatches`: a token carrying no audience is not a token for this audience.\n if (audience === undefined) {\n addClaimMissing(\n issues,\n 'aud',\n `The token has no 'aud' claim, which is required to match the expected value ${quoted(expectedValues)}`\n )\n return\n }\n\n const audiences = asArray(audience)\n\n if (!audiences.some((value) => expectedValues.includes(value))) {\n issues.add({\n code: 'claim_value_mismatch',\n path: ['aud'],\n message: `The 'aud' claim ${quoted(audiences)} does not match the expected value ${quoted(expectedValues)}`,\n context: { expected: expectedValues, actual: audience },\n })\n }\n}\n\n/**\n * `nbf` and `iat` are lower bounds on the validity window, so they are shifted back by the skew: a\n * token whose validity starts within the tolerance is already accepted.\n */\nfunction verifyClaimNotInFuture(\n issues: ClaimIssues,\n claim: string,\n seconds: number,\n now: Date,\n skewSeconds: number\n): void {\n if (seconds - skewSeconds > now.getTime() / 1000) {\n issues.add({\n code: 'not_yet_valid',\n path: [claim],\n message: `The '${claim}' claim '${formatNumericDate(seconds)}' is in the future (compared to '${now.toISOString()}')`,\n context: { validFrom: secondsToDate(seconds) },\n })\n }\n}\n","import { type BaseSchema, parseWithErrorHandling } from '@owf/identity-common'\nimport type { VerifyJwsCallback } from '../callbacks'\nimport { JoseValidationError } from '../error'\nimport type { JwsSigner, JwsSignerMethod, JwsSignerWithJwk } from '../jws/signer'\nimport { verifyJwsSignature } from '../jws/verify-jws'\nimport type { InferSchemaOrDefaultOutput } from '../utils/zod'\nimport { type DecodeJwtResult, decodeJwt } from './decode-jwt'\nimport { type VerifyJwtClaimsOptions, verifyJwtClaims } from './verify-jwt-claims'\nimport { type JwtPayload, type zJwtHeader, zJwtPayload } from './z-jwt'\n\nexport interface VerifyJwtOptions<\n HeaderSchema extends BaseSchema | undefined,\n PayloadSchema extends BaseSchema | undefined,\n> extends VerifyJwtClaimsOptions {\n /**\n * The JWT to verify: the compact serialization, or the result of a previous {@link decodeJwt} when\n * the caller had to look at the token before it could decide how to verify it.\n */\n jwt: string | DecodeJwtResult<HeaderSchema, PayloadSchema>\n\n /** Callback that verifies the signature and decides whether the key is trusted. */\n verifyJwsCallback: VerifyJwsCallback\n\n /**\n * Schema to validate the header with, see {@link decodeJwt}. Only used when `jwt` is a compact JWT.\n *\n * What it returns is the `header` that is returned, but the checks are made on the header as\n * validated against `zJwtHeader`, which the schema cannot change.\n */\n headerSchema?: HeaderSchema\n\n /**\n * Schema to validate the payload with, see {@link decodeJwt}. Only used when `jwt` is a compact JWT.\n *\n * What it returns is the `payload` that is returned, but the claims are verified as validated\n * against `zJwtPayload`, which the schema cannot change.\n */\n payloadSchema?: PayloadSchema\n\n /** The signer to verify against. Established from the header when not provided. */\n signer?: JwsSigner\n\n /** The signer methods the caller accepts. */\n allowedSignerMethods?: ReadonlyArray<JwsSignerMethod>\n\n /** Whether a header may identify the signer in more than one way, see `verifyJwsSignature`. */\n allowMultipleSignerMethods?: boolean\n\n /**\n * Whether a `kid` whose DID is not the `iss` is accepted for a did signer. Needed for\n * `openid4vci-proof+jwt`, where `iss` is the client id rather than the did.\n *\n * @default false\n */\n allowDidKidIssuerMismatch?: boolean\n\n /** The algorithms the caller accepts, see `verifyJwsSignature`. */\n allowedAlgorithms?: ReadonlyArray<string>\n\n /** Whether a symmetric signature algorithm is acceptable, see `verifyJwsSignature`. */\n allowSymmetricAlgorithms?: boolean\n\n /** The critical header parameters the caller understands. */\n understoodCriticalParameters?: ReadonlyArray<string>\n}\n\nexport interface VerifyJwtResult<\n HeaderSchema extends BaseSchema | undefined = undefined,\n PayloadSchema extends BaseSchema | undefined = undefined,\n> {\n header: InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>\n payload: InferSchemaOrDefaultOutput<PayloadSchema, typeof zJwtPayload>\n\n /** The signer, with the public key the signature was verified with. */\n signer: JwsSignerWithJwk\n\n /** The compact JWT that was verified. */\n compact: string\n}\n\n/**\n * Verifies a JWT completely: the signature over it, and then the claims in it.\n *\n * The signature is verified first, since the claims of a token whose signer has not been established\n * say nothing about anything.\n *\n * @throws JoseParseError or JoseValidationError if the token is not a valid JWT.\n * @throws JoseAlgorithmNotAllowedError if the algorithm is not accepted, or does not match the key.\n * @throws JoseSignatureVerificationError if the signature does not verify.\n * @throws JoseValidationError with an issue for each claim that does not verify, see `verifyJwtClaims`.\n * @throws JoseInvalidArgumentError if `now`, `skewSeconds` or `maxAgeSeconds` cannot be used to\n * verify the claims.\n */\nexport async function verifyJwt<\n HeaderSchema extends BaseSchema | undefined = undefined,\n PayloadSchema extends BaseSchema | undefined = undefined,\n>(options: VerifyJwtOptions<HeaderSchema, PayloadSchema>): Promise<VerifyJwtResult<HeaderSchema, PayloadSchema>> {\n const decoded =\n typeof options.jwt === 'string'\n ? decodeJwt({\n jwt: options.jwt,\n headerSchema: options.headerSchema,\n payloadSchema: options.payloadSchema,\n understoodCriticalParameters: options.understoodCriticalParameters,\n })\n : options.jwt\n\n const header = decoded.header as InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>\n const payload = decoded.payload as InferSchemaOrDefaultOutput<PayloadSchema, typeof zJwtPayload>\n\n // Every check is made on the header and claims as validated against the registered schemas, not on\n // what the caller's schemas made of them, which may have dropped `alg` or `exp`, or filled in `iat`.\n // A decoded JWT that was put together without `decodeJwt` does not come with them, so its own\n // header and claims are validated instead.\n const registeredPayload: JwtPayload =\n decoded.registeredPayload ??\n parseWithErrorHandling(zJwtPayload, decoded.payload, 'Invalid JWT payload', JoseValidationError)\n\n const { signer } = await verifyJwsSignature({\n jws: {\n protectedHeader: header,\n registeredProtectedHeader: decoded.registeredHeader,\n signingInput: decoded.signingInput,\n signature: decoded.signature,\n // The claims set as bytes, which is the payload of the JWS that the JWT is.\n payload: decoded.payloadBytes,\n compact: decoded.compact,\n },\n jwtPayload: registeredPayload,\n verifyJwsCallback: options.verifyJwsCallback,\n signer: options.signer,\n allowedSignerMethods: options.allowedSignerMethods,\n allowMultipleSignerMethods: options.allowMultipleSignerMethods,\n allowDidKidIssuerMismatch: options.allowDidKidIssuerMismatch,\n allowedAlgorithms: options.allowedAlgorithms,\n allowSymmetricAlgorithms: options.allowSymmetricAlgorithms,\n errorMessage: options.errorMessage ?? 'Error during verification of the JWT.',\n })\n\n verifyJwtClaims(registeredPayload, options)\n\n return { header, payload, signer, compact: decoded.compact }\n}\n"],"mappings":";;;;;;;AAYA,IAAa,YAAb,cAA+B,cAAc;CAG3C,YAAY,SAAiB,SAAkD;EAC7E,MAAM,SAAS,SAAS,OAAO;EAE/B,KAAK,QAAQ,SAAS;CACxB;AACF;;;;;AAMA,IAAa,iBAAb,cAAoC,UAAU,CAAC;;;;;AAS/C,IAAa,sBAAb,cAAyC,gBAAqC,CAAC;;;;;AAM/E,IAAa,wBAAb,cAA2C,UAAU,CAAC;;AAGtD,IAAa,iCAAb,cAAoD,sBAAsB,CAAC;;AAG3E,IAAa,+BAAb,cAAkD,sBAAsB,CAAC;;AAGzE,IAAa,kBAAb,cAAqC,sBAAsB,CAAC;;AAG5D,IAAa,wBAAb,cAA2C,UAAU,CAAC;;;;;AAMtD,IAAa,2BAAb,cAA8C,UAAU,CAAC;;;;;;;;;;;;;;AC9CzD,IAAY,wBAAL,yBAAA,uBAAA;CAEL,sBAAA,WAAA;CACA,sBAAA,WAAA;CACA,sBAAA,WAAA;CAGA,sBAAA,WAAA;CACA,sBAAA,WAAA;CACA,sBAAA,WAAA;CAGA,sBAAA,WAAA;CACA,sBAAA,WAAA;CACA,sBAAA,WAAA;CAGA,sBAAA,WAAA;CACA,sBAAA,WAAA;CACA,sBAAA,WAAA;CACA,sBAAA,YAAA;CAGA,sBAAA,WAAA;CACA,sBAAA,aAAA;CACA,sBAAA,WAAA;;AACF,EAAA,CAAA,CAAA;;AAGA,MAAa,+BAA+B;;;;AAI5C;;;;;;AAOA,IAAY,4BAAL,yBAAA,2BAAA;CACL,0BA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S,QAAQ;EACnB;EACA,YAAY;EACZ,mBAAmB,QAAQ;EAC3B,QAAQ,QAAQ;EAChB,sBAAsB,QAAQ;EAC9B,4BAA4B,QAAQ;EACpC,2BAA2B,QAAQ;EACnC,mBAAmB,QAAQ;EAC3B,0BAA0B,QAAQ;EAClC,cAAc,QAAQ,gBAAgB;CACxC,CAAC;CAED,gBAAgB,mBAAmB,OAAO;CAE1C,OAAO;EAAE;EAAQ;EAAS;EAAQ,SAAS,QAAQ;CAAQ;AAC7D"}
package/package.json CHANGED
@@ -1,12 +1,18 @@
1
1
  {
2
2
  "name": "@owf/jose",
3
- "version": "0.0.0",
3
+ "version": "0.8.0-alpha-20261107111939",
4
4
  "description": "JOSE (JWK, JWA, JWS, JWT and JWE) with strict, schema based parsing and verification",
5
5
  "files": [
6
6
  "dist"
7
7
  ],
8
8
  "license": "Apache-2.0",
9
- "exports": "./src/index.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.mts",
12
+ "default": "./dist/index.mjs"
13
+ },
14
+ "./package.json": "./package.json"
15
+ },
10
16
  "homepage": "https://github.com/openwallet-foundation-labs/identity-common-ts/tree/main/packages/jose",
11
17
  "repository": {
12
18
  "type": "git",
@@ -14,24 +20,11 @@
14
20
  "directory": "packages/jose"
15
21
  },
16
22
  "publishConfig": {
17
- "access": "public",
18
- "main": "./dist/index.mjs",
19
- "module": "./dist/index.mjs",
20
- "types": "./dist/index.d.mts",
21
- "exports": {
22
- ".": {
23
- "types": "./dist/index.d.mts",
24
- "default": "./dist/index.mjs"
25
- },
26
- "./package.json": "./package.json"
27
- }
28
- },
29
- "scripts": {
30
- "build": "tsdown src/index.ts --format esm --dts --sourcemap"
23
+ "access": "public"
31
24
  },
32
25
  "dependencies": {
33
- "@owf/identity-common": "workspace:*",
34
- "zod": "catalog:"
26
+ "zod": "^4.6.7",
27
+ "@owf/identity-common": "0.8.0-alpha-20261107111939"
35
28
  },
36
29
  "keywords": [
37
30
  "jose",
@@ -41,5 +34,11 @@
41
34
  "jwt",
42
35
  "jwe",
43
36
  "react-native"
44
- ]
45
- }
37
+ ],
38
+ "scripts": {
39
+ "build": "tsdown src/index.ts --format esm --dts --sourcemap"
40
+ },
41
+ "main": "./dist/index.mjs",
42
+ "module": "./dist/index.mjs",
43
+ "types": "./dist/index.d.mts"
44
+ }