@owf/jose 0.0.0-stage → 0.8.0-alpha-20261107082516

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/README.md CHANGED
@@ -1,3 +1,173 @@
1
- # Temporary Holding Version
1
+ # @owf/jose
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/npm/v/@owf/jose)](https://npmjs.com/package/@owf/jose)
4
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/openwallet-foundation-labs/identity-common-ts/blob/main/LICENSE)
5
+
6
+ JOSE (JWK, JWA, JWS, JWT and JWE) for [Identity Common TypeScript](https://github.com/openwallet-foundation-labs/identity-common-ts). Tokens are parsed and verified strictly, against zod schemas.
7
+
8
+ ## Installation
9
+
10
+ ```bash
11
+ # Using npm
12
+ npm install @owf/jose
13
+
14
+ # Using pnpm
15
+ pnpm add @owf/jose
16
+
17
+ # Using yarn
18
+ yarn add @owf/jose
19
+ ```
20
+
21
+ ## Design
22
+
23
+ Every base64url, UTF-8 and JSON decode goes through `@owf/identity-common`. It accepts only the base64url alphabet without padding, decodes UTF-8 with `fatal: true`, and throws the same opaque error for every failure. A header encoded with the standard base64 alphabet, or a payload with invalid UTF-8, is rejected.
24
+
25
+ A token type is described by a schema. Compose the exported schemas into the header and claims a token must have, and `decodeJwt` checks everything that follows from the token alone:
26
+
27
+ ```typescript
28
+ import { zTyp } from '@owf/identity-common'
29
+ import { decodeJwt, zJwtHeader, zJwtPayload } from '@owf/jose'
30
+ import z from 'zod'
31
+
32
+ const zKbJwtHeader = z.object({ ...zJwtHeader.shape, typ: zTyp('kb+jwt') }).loose()
33
+ const zKbJwtPayload = z
34
+ .object({ ...zJwtPayload.shape, iat: z.number(), aud: z.string(), nonce: z.string(), sd_hash: z.string().min(1) })
35
+ .loose()
36
+
37
+ // `header` and `payload` are typed from the schemas
38
+ const { header, payload } = decodeJwt({
39
+ jwt,
40
+ headerSchema: zKeyBindingJwtHeader,
41
+ payloadSchema: zKeyBindingJwtPayload,
42
+ })
43
+ ```
44
+
45
+ `decodeJwt` also validates the header against `zJwtHeader` and the payload against `zJwtPayload`. The checks run on those results, so a profile schema cannot leave `alg`, `crit` or `exp` unchecked.
46
+
47
+ The current time, the audience of the verifier and the nonce it issued are options of `verifyJwt`, as a schema cannot express them.
48
+
49
+ ## Signing and verifying
50
+
51
+ The caller provides the cryptography. This package computes the bytes to sign, and the callback signs or verifies exactly those bytes.
52
+
53
+ ```typescript
54
+ import { base64url, dateToSeconds } from '@owf/identity-common'
55
+ import {
56
+ type JwsSigner,
57
+ jwsHeaderFromSigner,
58
+ type SignJwsCallback,
59
+ signJwt,
60
+ type VerifyJwsCallback,
61
+ verifyJwt,
62
+ } from '@owf/jose'
63
+
64
+ // `kms`, `resolveKey` and `resolveTrustedKey` stand in for your own key management
65
+ const signJws: SignJwsCallback = async (signer, { signingInputBytes }) => {
66
+ const { keyId, publicJwk } = await resolveKey(signer)
67
+ const signature = await kms.sign({ keyId, algorithm: signer.alg, data: signingInputBytes })
68
+
69
+ return { signature: base64url.encode(signature), signerJwk: publicJwk }
70
+ }
71
+
72
+ const verifyJws: VerifyJwsCallback = async (signer, { signingInputBytes, signature }) => {
73
+ // Throws when the key the header names is not one this verifier trusts
74
+ const publicJwk = await resolveTrustedKey(signer)
75
+ const verified = await kms.verify({
76
+ publicJwk,
77
+ algorithm: signer.alg,
78
+ data: signingInputBytes,
79
+ signature: base64url.decode(signature),
80
+ })
81
+
82
+ return verified ? { verified: true, signerJwk: publicJwk } : { verified: false }
83
+ }
84
+
85
+ const signer: JwsSigner = { method: 'jwk', alg: 'ES256', publicJwk }
86
+
87
+ const { jwt } = await signJwt({
88
+ // The parameters that identify the key are only in the header when they are put there
89
+ header: { typ: 'example+jwt', ...jwsHeaderFromSigner(signer) },
90
+ payload: { iss: 'https://issuer.example', aud: 'https://verifier.example', iat: dateToSeconds(new Date()) },
91
+ signer,
92
+ signJwsCallback: signJws,
93
+ })
94
+
95
+ // The signer is established from the header, here from its `jwk`
96
+ const { payload, signer: verifiedSigner } = await verifyJwt({
97
+ jwt,
98
+ verifyJwsCallback: verifyJws,
99
+ allowedAlgorithms: ['ES256'],
100
+ expectedIssuer: 'https://issuer.example',
101
+ expectedAudience: 'https://verifier.example',
102
+ requiredClaims: ['iat'],
103
+ })
104
+ ```
105
+
106
+ The verification callback decides whether the key is trusted, for example whether a certificate chain chains to a trusted root or whether a DID is acceptable. This package only establishes which key signed.
107
+
108
+ `signJwt` validates the header and the claims set before signing them. It does not add the header parameters that identify the key, because the token type decides which of them a token carries. Spread `jwsHeaderFromSigner(signer)` into the header to add them. It returns:
109
+
110
+ - for a `did` signer, its DID URL as `kid`
111
+ - for a `federation` signer, `kid` and `trust_chain`. Without a trust chain it gives `kid` alone, and a verifier then establishes a `custom` signer
112
+ - for a `jwk` or `x5c` signer, `jwk` or `x5c`, without the `kid` of the signer
113
+ - for a `custom` signer, its `kid` when it has one, as the key id is all a verifier has to find a key that is established out of band
114
+
115
+ ## Certificate chains
116
+
117
+ `x5c`, in a JWS header, a JWE header and a JWK, is validated when it is parsed, as RFC 7515 and RFC 7517 define it: a chain of at least one certificate, with the certificate that holds the key first. Each entry is the standard base64 (RFC 4648 section 4) of a DER encoded certificate. An entry is rejected when it has base64url characters, whitespace or line breaks, or missing or extra `=` padding. It is also rejected when it does not decode to exactly one DER SEQUENCE with a definite, minimally encoded length. The issue has the path of the entry and the code `invalid_format`, with `base64` or `der` as the format.
118
+
119
+ The certificates themselves are not parsed. The verification callback gets the `x5c` signer and decides whether the entries are valid X.509 certificates, whether the chain is in order and chains to a trusted root, and whether the first certificate holds the key that signed. A profile that validates a certificate chain in its own schema can use `zX5c` and `zX5cCertificate`.
120
+
121
+ ## What is checked
122
+
123
+ Besides validating the structures, verification applies these rules:
124
+
125
+ - `alg` is never `none`, in any casing, and a JWS without a signature is rejected. A caller can restrict verification to the algorithms an issuer is known to use. Symmetric algorithms are rejected unless explicitly allowed, since anyone who can verify such a token can also issue one. A registered algorithm in a different casing (`hs256`) is rejected too.
126
+ - The key a signature was verified with has to be usable with the algorithm of the token: `HS256` over an RSA public key is rejected, and so is a key that declares a different `alg`, `use` or `key_ops`. `EdDSA` and its fully specified forms `Ed25519` and `Ed448` (RFC 9864) count as the same `alg`, as long as the key is on the curve they require.
127
+ - When the signer is established for a token that carries an `iss`, a DID in `kid` has to be exactly the DID in `iss`, unless `allowDidKidIssuerMismatch` is set. A prefix match is not enough. Without an `iss`, the verification callback decides whether the DID is trusted.
128
+ - A `jwk` header parameter can never carry private key material, and an `x5c` is a chain of base64 encoded DER certificates, see [Certificate chains](#certificate-chains).
129
+ - `crit` is processed. A JWS is rejected when it marks a header parameter critical that the caller does not understand, or when `crit` is in the unprotected header, empty, or names a registered parameter. The error has an issue for each of these.
130
+ - Security relevant header parameters are read from the protected header only, and a parameter present in both the protected and the unprotected header is rejected.
131
+ - A header that identifies the signer in more than one way is rejected. No precedence is applied.
132
+ - `extractJwkFromJwkSet` selects a key from a JWK Set by its `kid` and `use`. The selection is rejected when no key in the set has the `kid`, or when several keys that differ have it. Without a `kid`, it is rejected when the set holds more than one key for the use. The same JWK listed twice counts as one key.
133
+ - An unencoded payload (RFC 7797, `b64: false`) is opt-in: `parseJws` rejects a JWS with `b64` in `crit` unless `understoodCriticalParameters` includes `'b64'`. In a compact serialization, such a payload can only hold printable ASCII other than `.`, as RFC 7797 requires. Signing refuses anything else, and parsing rejects it. A detached payload, or one in a JSON serialization, is not limited this way.
134
+ - A `cnf` claim names its key in one way only: with one of `jwk`, `jwe`, `jku` (RFC 7800) and `jkt` (RFC 9449). A `kid`, for example a DID URL, is allowed on its own, with `jku` to select the key from the set, or with `jkt`, but not next to a `jwk` or `jwe`.
135
+ - The signature is verified before the claims, since the claims of a token mean nothing until its signer is established.
136
+ - The claims are verified against `now` (the current time unless it is given), with a clock skew of 30 seconds for `exp`, `nbf` and `iat` unless `skewSeconds` says otherwise. Shifted by that skew, a token is rejected from its `exp` on, at `exp` itself too, and while its `nbf` or `iat` is in the future. An `expected*` option rejects a token that does not carry the claim at all.
137
+ - The time claims are compared as numbers of seconds, so a NumericDate outside the range of a JavaScript `Date` is still ordered: an `exp` of `9999999999999` does not expire, and an `exp` of `-1e13` has expired. A time claim that is not a finite number gives an `invalid_type` issue.
138
+
139
+ Options that a check cannot be made with are rejected rather than letting the check pass. A `now` that is not a valid date, or a `skewSeconds` or `maxAgeSeconds` that is not a finite number of at least 0, throws a `JoseInvalidArgumentError`: with a skew of `NaN`, every comparison against the current time would accept the token. `signCompactJws` and `signJwt` throw the same error for a signer whose `alg` is not the `alg` of the header, for an unencoded payload that a compact serialization cannot carry, and for a signing callback that does not return a non-empty base64url signature. `verifyJwsSignature` throws a `JoseAlgorithmNotAllowedError` when the `signer` it is given has another `alg` than the JWS.
140
+
141
+ ## Errors
142
+
143
+ The errors of this package extend `IdentityError` from `@owf/identity-common`. The class says what went wrong:
144
+
145
+ - `JoseParseError`: the token is not well formed.
146
+ - `JoseValidationError`: the token does not match the schema it was parsed with. It extends the `ValidationError` of `@owf/identity-common` and has the `issues` of the validation, e.g. `invalid_typ` for a wrong `typ`. It is also thrown for a `crit` that does not verify (`invalid_crit`, `unsupported_crit`), and for a claim that does not verify (e.g. `expired`, with `expiredAt` as context). `error.findIssue('expired')` returns the issue with that code, typed by it.
147
+ - `JoseVerificationError`: the token does not verify. Its subclasses are `JoseSignatureVerificationError`, `JoseAlgorithmNotAllowedError` and `JoseSignerError`.
148
+ - `JoseNotSupportedError`: the token uses a feature this package does not implement.
149
+ - `JoseInvalidArgumentError`: the calling code passed an option that cannot be used, or a signing callback returned an unusable result. A verification callback that reports success without a usable `signerJwk` gives a `JoseSignatureVerificationError` instead.
150
+
151
+ ## Not supported
152
+
153
+ - An unsecured JWS (`alg: none`), and a JWS without a protected header.
154
+ - JWE encryption and decryption. The package provides the JWE structures (`zCompactJwe`, `zJweHeader`, and `decodeJwtHeader` to read the header of a compact JWE) and the callback types (`EncryptJweCallback`, `DecryptJweCallback`), and leaves the cryptography to the caller.
155
+ - Nested JWTs. `decodeJwt` expects the claims set as the payload: decrypt an outer JWE, or read an outer JWS with `parseJws`, and decode the inner JWT from its payload.
156
+ - Signing a JWS in a JSON serialization. `parseJws` and `verifyJwsSignature` read the flattened and general JSON serializations, but `signCompactJws` and `signJwt` produce the compact serialization only.
157
+ - An unencoded payload (`b64: false`) in a JWT, and an unencoded payload that is not valid UTF-8.
158
+
159
+ ## Platform support
160
+
161
+ This library works in:
162
+
163
+ - Node.js (>=20)
164
+ - Browsers with ES2020 support
165
+ - React Native
166
+
167
+ ## Contributing
168
+
169
+ See the [Contributing Guide](https://github.com/openwallet-foundation-labs/identity-common-ts/blob/main/CONTRIBUTING.md) for details on how to contribute to this project.
170
+
171
+ ## License
172
+
173
+ This project is licensed under the [Apache License Version 2.0](https://github.com/openwallet-foundation-labs/identity-common-ts/blob/main/LICENSE) (Apache-2.0).