vouchly 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +324 -2
- package/dist/index.d.mts +349 -0
- package/dist/index.mjs +715 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +65 -5
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 2026 Peter Placzek
|
|
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,325 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://raw.githubusercontent.com/tada5hi/vouchly/master/.github/assets/logo.svg" alt="" width="96" height="96">
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
<h1 align="center">vouchly</h1>
|
|
6
|
+
|
|
7
|
+
<p align="center">
|
|
8
|
+
<strong>Verify OAuth2 and OIDC tokens against trusted issuers: JWT, introspection and certificate-bound tokens, on any Web runtime.</strong>
|
|
9
|
+
</p>
|
|
10
|
+
|
|
11
|
+
<p align="center">
|
|
12
|
+
You list the issuers you trust. vouchly picks the right one per token, finds its key, checks the claims and tells you why a token was refused.
|
|
13
|
+
</p>
|
|
14
|
+
|
|
15
|
+
<p align="center">
|
|
16
|
+
<a href="https://npmjs.com/package/vouchly"><img src="https://badge.fury.io/js/vouchly.svg" alt="npm version"></a>
|
|
17
|
+
<a href="https://github.com/tada5hi/vouchly/actions/workflows/main.yml"><img src="https://github.com/tada5hi/vouchly/actions/workflows/main.yml/badge.svg" alt="CI"></a>
|
|
18
|
+
</p>
|
|
19
|
+
|
|
20
|
+
<p align="center">
|
|
21
|
+
<a href="#why-vouchly">Why</a> ·
|
|
22
|
+
<a href="#installation">Installation</a> ·
|
|
23
|
+
<a href="#usage">Usage</a> ·
|
|
24
|
+
<a href="#issuer-options">Options</a> ·
|
|
25
|
+
<a href="#errors">Errors</a> ·
|
|
26
|
+
<a href="#api">API</a> ·
|
|
27
|
+
<a href="#notes">Notes</a>
|
|
28
|
+
</p>
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## Why vouchly?
|
|
33
|
+
|
|
34
|
+
A service that accepts tokens from more than one place (your own identity provider, GitHub Actions, a partner's OIDC provider) ends up writing the same code each time: decode the token, look at `iss`, find the JWKS for that issuer, refuse a key that should never verify anything, check `aud` and `exp`, maybe ask an introspection endpoint instead, cache the answer, and turn a dozen library errors into something an HTTP handler can map. Each of those steps has a well-known way to get it wrong.
|
|
35
|
+
|
|
36
|
+
| Concern | Without it | With vouchly |
|
|
37
|
+
|---------|------------|-------------|
|
|
38
|
+
| Which issuer? | Read `iss` yourself and branch | An allowlist of `Issuer` configs; an unknown `iss` fails with `issuer_untrusted` before any request goes out |
|
|
39
|
+
| Where the keys come from | Wire `jwks_uri` per issuer by hand | `discovery()` reads it from the issuer's `/.well-known/openid-configuration`; `jwks()`, `staticKeys()` and `cachedKeys()` for everything else |
|
|
40
|
+
| Algorithm confusion | Hope the allowed algorithms are set everywhere | Symmetric keys and RSA keys under 2048 bits are refused; a JWK that names its `alg` decides the algorithm, one without is imported with the header's `alg`, restricted to what its key type supports, and `algorithms` pins it |
|
|
41
|
+
| Malformed input | Whatever the decoder tolerates | Exactly three base64url segments, no padding, no whitespace, checked before the cache or any key lookup |
|
|
42
|
+
| Opaque and revocable tokens | A second code path with its own HTTP client | `verification: 'remote'` per issuer (RFC 7662), with a cache bound you choose |
|
|
43
|
+
| Certificate-bound tokens | Compare `cnf.x5t#S256` yourself, and remember it on cache hits | RFC 8705 binding checked on every call, cache hits included, failing closed |
|
|
44
|
+
| Repeated verification | Cache the decoded payload and hope it expires | A bounded cache keyed by the token's SHA-256, never kept past `exp` |
|
|
45
|
+
| Errors | jose errors, `TypeError`s, fetch failures | One `VouchlyError` with one of nine codes, the original kept as `cause` |
|
|
46
|
+
|
|
47
|
+
The same verifier accepts tokens from GitHub Actions and from your own provider; each issuer keeps its own rules:
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { createVerifier } from 'vouchly';
|
|
51
|
+
|
|
52
|
+
const verifier = createVerifier({
|
|
53
|
+
issuers: [
|
|
54
|
+
{
|
|
55
|
+
id: 'github',
|
|
56
|
+
issuer: 'https://token.actions.githubusercontent.com',
|
|
57
|
+
audience: 'https://api.example.com',
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
id: 'internal',
|
|
61
|
+
issuer: 'https://id.example.com',
|
|
62
|
+
audience: 'api',
|
|
63
|
+
},
|
|
64
|
+
],
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
const { claims, issuer } = await verifier.verify(token);
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
<p align="center">
|
|
71
|
+
<img src="https://raw.githubusercontent.com/tada5hi/vouchly/master/.github/assets/verify.svg" alt="verify(token) parses the token strictly, looks up its SHA-256 in the token cache, selects a trusted issuer from the unverified iss claim, verifies the token locally with the issuer's key source or by RFC 7662 introspection, and finally checks the RFC 8705 certificate binding. A cache hit skips the key lookup and the signature, not the verifier's claim rules, then goes on to the binding check. Each step fails with its own VouchlyError code: token_malformed, issuer_untrusted, key_unavailable or signature_invalid or claim_invalid or introspection_failed, and binding_mismatch. Nothing is fetched before an issuer is selected." width="100%">
|
|
72
|
+
</p>
|
|
73
|
+
|
|
74
|
+
## Installation
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
npm install vouchly
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
- ESM only, with TypeScript declarations included.
|
|
81
|
+
- Node.js `>= 22`. The source uses Web APIs only (`fetch`, WebCrypto, `TextEncoder`) and imports no `node:*` module, so it also runs on other Web runtimes.
|
|
82
|
+
- One runtime dependency: [`jose`](https://github.com/panva/jose).
|
|
83
|
+
|
|
84
|
+
## Usage
|
|
85
|
+
|
|
86
|
+
### GitHub Actions OIDC tokens
|
|
87
|
+
|
|
88
|
+
A string `issuer` is matched exactly against `iss`, and its keys are found through OIDC discovery. A `claims` predicate adds rules of your own; it runs after the signature and the standard claims were checked, so it only ever sees verified claims.
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
import { createVerifier, isVouchlyError } from 'vouchly';
|
|
92
|
+
|
|
93
|
+
const verifier = createVerifier({
|
|
94
|
+
issuers: [
|
|
95
|
+
{
|
|
96
|
+
id: 'github',
|
|
97
|
+
issuer: 'https://token.actions.githubusercontent.com',
|
|
98
|
+
audience: 'https://deploy.example.com',
|
|
99
|
+
claims: (claims) => claims.repository === 'acme/website' &&
|
|
100
|
+
claims.ref === 'refs/heads/main',
|
|
101
|
+
},
|
|
102
|
+
],
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
try {
|
|
106
|
+
const { claims } = await verifier.verify(token);
|
|
107
|
+
console.log(`deploy requested by ${claims.actor}`);
|
|
108
|
+
} catch (e) {
|
|
109
|
+
if (isVouchlyError(e)) {
|
|
110
|
+
console.log(e.code); // e.g. 'claim_invalid'
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
throw e;
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
- The predicate must return `true`. Anything else, or a throw, fails as `claim_invalid`.
|
|
118
|
+
- `audience` is passed to jose: some `aud` value must be one of the configured ones.
|
|
119
|
+
|
|
120
|
+
### Many issuers behind one pattern
|
|
121
|
+
|
|
122
|
+
When issuers appear at runtime (one per tenant or realm), match `iss` with a function and supply the keys yourself. The function sees **unverified** claims: it only selects this config and never replaces verification. Because a function issuer has no fixed URL, `discovery()` refuses it, and the constructor requires a `keys` source.
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
import type { JWK } from 'jose';
|
|
126
|
+
import { cachedKeys, createVerifier } from 'vouchly';
|
|
127
|
+
|
|
128
|
+
const baseUrl = 'https://auth.example.com';
|
|
129
|
+
|
|
130
|
+
const verifier = createVerifier({
|
|
131
|
+
issuers: [
|
|
132
|
+
{
|
|
133
|
+
id: 'realms',
|
|
134
|
+
issuer: (claims) => typeof claims.iss === 'string' &&
|
|
135
|
+
claims.iss.startsWith(`${baseUrl}/realms/`),
|
|
136
|
+
keys: cachedKeys(
|
|
137
|
+
async ({ token, fetch }) => {
|
|
138
|
+
const realm = String(token.claims.realm_id).toLowerCase();
|
|
139
|
+
const kid = String(token.header.kid).toLowerCase();
|
|
140
|
+
const response = await fetch(`${baseUrl}/realms/${encodeURIComponent(realm)}/jwks/${encodeURIComponent(kid)}`);
|
|
141
|
+
if (!response.ok) {
|
|
142
|
+
throw new Error(`The key endpoint answered ${response.status}.`);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return await response.json() as JWK;
|
|
146
|
+
},
|
|
147
|
+
{
|
|
148
|
+
key: ({ token }) => `${String(token.claims.realm_id)}:${String(token.header.kid)}`,
|
|
149
|
+
ttl: 300,
|
|
150
|
+
},
|
|
151
|
+
),
|
|
152
|
+
},
|
|
153
|
+
],
|
|
154
|
+
});
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
- The loader only builds URLs from your own `baseUrl`. Never fetch from a URL taken out of the token.
|
|
158
|
+
- `cachedKeys` shares one in-flight load per cache key, keeps a key for `ttl` seconds (default 300), gives up after `timeout` seconds (default 10) and holds at most `max` keys (default 100, an integer of at least 1). A failed load is never cached.
|
|
159
|
+
- Whatever a key source returns still passes the key policy: a JWK with `kty: oct`, a `use` other than `sig`, or an RSA key under 2048 bits fails as `key_unavailable`.
|
|
160
|
+
|
|
161
|
+
### Key sources
|
|
162
|
+
|
|
163
|
+
| Source | Use it for |
|
|
164
|
+
|--------|------------|
|
|
165
|
+
| `discovery({ cacheMaxAge })` | Default for a string `issuer`. Reads `jwks_uri` from `<issuer>/.well-known/openid-configuration`, which must name the same `issuer`. Metadata is reused for `cacheMaxAge` seconds (default 600); after a failed fetch the issuer is not asked again for 30 seconds, and keys fail fast as `key_unavailable` meanwhile. |
|
|
166
|
+
| `jwks(url, { cacheMaxAge, cooldownDuration, timeoutDuration })` | A known JWKS URL. Wraps jose's `createRemoteJWKSet`; the three options are milliseconds, as in jose. |
|
|
167
|
+
| `staticKeys(keys)` | Keys you ship with the service, as JWKs. |
|
|
168
|
+
| `cachedKeys(load, { key, ttl, timeout, max })` | A custom loader, with a per-key TTL and shared in-flight loads. |
|
|
169
|
+
|
|
170
|
+
A key source is any `(context) => Promise<CryptoKey | JWK>`; `context` carries the parsed token, the matched issuer and the verifier's `fetch`.
|
|
171
|
+
|
|
172
|
+
### Introspection
|
|
173
|
+
|
|
174
|
+
Set `verification: 'remote'` to ask the issuer about each token (RFC 7662) instead of checking a signature. This is the way to notice a revoked token before it expires, and the only way to accept opaque tokens.
|
|
175
|
+
|
|
176
|
+
```ts
|
|
177
|
+
import { createVerifier } from 'vouchly';
|
|
178
|
+
|
|
179
|
+
const verifier = createVerifier({
|
|
180
|
+
issuers: [
|
|
181
|
+
{
|
|
182
|
+
id: 'id-provider',
|
|
183
|
+
issuer: 'https://id.example.com',
|
|
184
|
+
verification: 'remote',
|
|
185
|
+
introspection: {
|
|
186
|
+
authorization: { clientId: 'resource-server', clientSecret: process.env.CLIENT_SECRET! },
|
|
187
|
+
maxCacheTTL: 30,
|
|
188
|
+
},
|
|
189
|
+
},
|
|
190
|
+
],
|
|
191
|
+
opaque: 'id-provider',
|
|
192
|
+
});
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
- The endpoint is `introspection.endpoint`, else the `introspection_endpoint` discovered for a string `issuer`. A function issuer needs an explicit `endpoint`.
|
|
196
|
+
- `authorization` is either client credentials, sent as HTTP Basic, or a function returning the whole `Authorization` header value (for a bearer token of your own).
|
|
197
|
+
- `active` other than `true` fails as `token_inactive`; a failed request, a non-2xx answer or a body that is not a JSON object fails as `introspection_failed`.
|
|
198
|
+
- The issuer's `audience` and `claims` predicate apply to the introspection response too.
|
|
199
|
+
- `opaque` names the issuer that introspects tokens which are not JWTs at all. Without it, such a token fails as `token_malformed`.
|
|
200
|
+
- A result is cached for the shorter of `exp - now` and `maxCacheTTL` seconds; with neither, it is not cached.
|
|
201
|
+
|
|
202
|
+
### Certificate-bound tokens
|
|
203
|
+
|
|
204
|
+
A token carrying `cnf` is bound to a client certificate (RFC 8705). Pass the SHA-256 thumbprint of the certificate the caller presented, base64url encoded:
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
const { claims } = await verifier.verify(token, {
|
|
208
|
+
certificateThumbprint: () => thumbprintOf(request),
|
|
209
|
+
});
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
- A token with `cnf` fails as `binding_mismatch` unless `cnf.x5t#S256` equals the thumbprint. That includes a `cnf` that carries no `x5t#S256` at all, such as a DPoP `jkt`.
|
|
213
|
+
- A function is only called for a bound token, so it costs nothing for the rest.
|
|
214
|
+
- The check runs on every call, also when the result comes from the cache.
|
|
215
|
+
- A JWT verified by introspection is held to its own `cnf` as well as the response's: the token's claims are unverified, so they can only add a requirement. When either carries a thumbprint, the presented one must match every thumbprint present.
|
|
216
|
+
|
|
217
|
+
### Caching
|
|
218
|
+
|
|
219
|
+
By default each verifier keeps its own `MemoryTokenCache` with up to 10000 entries (least recently used first out; `max` must be an integer of at least 1). Pass `cache: false` to turn it off, or your own `ITokenCache` to share results between processes, for example between replicas of one service. A cache you pass in needs a `cacheNamespace`, and every verifier using that namespace must have the same issuer configuration: a cache hit skips the key lookup and the signature check, so an entry is only as trustworthy as the configuration that wrote it.
|
|
220
|
+
|
|
221
|
+
```ts
|
|
222
|
+
import type { ITokenCache, TokenCacheEntry } from 'vouchly';
|
|
223
|
+
import { createVerifier } from 'vouchly';
|
|
224
|
+
|
|
225
|
+
declare const redis: {
|
|
226
|
+
get(key: string): Promise<string | null>,
|
|
227
|
+
set(key: string, value: string, options: { EX: number }): Promise<unknown>,
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
const cache: ITokenCache = {
|
|
231
|
+
async get(key) {
|
|
232
|
+
const value = await redis.get(`vouchly:${key}`);
|
|
233
|
+
return value ? JSON.parse(value) as TokenCacheEntry : undefined;
|
|
234
|
+
},
|
|
235
|
+
async set(key, entry, ttl) {
|
|
236
|
+
if (ttl > 0) {
|
|
237
|
+
await redis.set(`vouchly:${key}`, JSON.stringify(entry), { EX: Math.ceil(ttl) });
|
|
238
|
+
}
|
|
239
|
+
},
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
const verifier = createVerifier({
|
|
243
|
+
issuers: [{ issuer: 'https://id.example.com' }],
|
|
244
|
+
cache,
|
|
245
|
+
cacheNamespace: 'orders-api',
|
|
246
|
+
});
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
- The key is the hex SHA-256 of the verifier's `cacheNamespace` (which may not contain NUL), a NUL character and the token, so the token itself is never stored as a key.
|
|
250
|
+
- `ttl` is in seconds, fractional, and never runs past the token's `exp`. A local token without `exp` is not cached. A cache that keeps an entry longer (one that rounds `ttl` up, say) still cannot serve it: a hit at or after `exp` (beyond the issuer's `clockTolerance`) fails as `token_expired`.
|
|
251
|
+
- A cache that throws counts as a miss on `get` and is ignored on `set`; it never fails a verification.
|
|
252
|
+
- A cache hit skips the key lookup and the signature check, so it cannot apply this verifier's key source, and the introspection settings of the verifier that wrote the entry are the ones that counted. That is why one namespace means one configuration.
|
|
253
|
+
- As a second line, a hit is still held to the rules that need no key: it is served only under the issuer this verifier would select for the token, and only after this verifier's `audience`, `requiredClaims`, `typ`, `algorithms`, `nbf` (with its `clockTolerance`), `exp` and `claims` predicate passed on the cached entry. A rule that fails gives the same error code as an uncached verify.
|
|
254
|
+
|
|
255
|
+
## Issuer options
|
|
256
|
+
|
|
257
|
+
| Option | Type | Default | Description |
|
|
258
|
+
|--------|------|---------|-------------|
|
|
259
|
+
| `id` | `string` | the issuer's index | Names the config. Required for `opaque`; must be unique. |
|
|
260
|
+
| `issuer` | `string \| (claims) => boolean` | | A string must equal `iss`. A function sees unverified claims and only selects the config; it matches only when it returns exactly `true`. |
|
|
261
|
+
| `keys` | `KeySource` | `discovery()` for a string issuer | Required for a function issuer verified locally. |
|
|
262
|
+
| `verification` | `'local' \| 'remote'` | `'local'` | Check the signature, or ask the introspection endpoint. |
|
|
263
|
+
| `introspection` | `{ endpoint?, authorization?, maxCacheTTL? }` | | See [Introspection](#introspection). `maxCacheTTL` is in seconds. |
|
|
264
|
+
| `audience` | `string \| string[]` | not checked | Some `aud` value must be in the list. |
|
|
265
|
+
| `algorithms` | `string[]` | what the resolved key implies | The key's own `alg` when the JWK names one. A JWK without `alg` is imported with the token header's `alg`, restricted to algorithms its key type supports (an RSA key can then verify `RS*` or `PS*`); set `algorithms` to pin it. |
|
|
266
|
+
| `typ` | `string` | not checked | The expected `typ` header, e.g. `at+jwt`. |
|
|
267
|
+
| `clockTolerance` | `number` | `0` | Seconds of leeway for `exp` and `nbf`. |
|
|
268
|
+
| `requiredClaims` | `string[]` | `['exp']` | Claims that must be present. |
|
|
269
|
+
| `claims` | `(claims) => boolean \| Promise<boolean>` | | Your own rules over the verified claims. |
|
|
270
|
+
|
|
271
|
+
The verifier itself takes `issuers`, `cache` (`ITokenCache` or `false`), `cacheNamespace` (see [Caching](#caching)), `fetch` (defaults to the global `fetch`) and `opaque` (the `id` of the issuer that introspects non-JWT tokens). The constructor throws a `TypeError` for a configuration that cannot work: no issuers, a duplicate `id`, a function issuer verified locally without `keys`, or an `opaque` id that names no issuer.
|
|
272
|
+
|
|
273
|
+
## Errors
|
|
274
|
+
|
|
275
|
+
Every error `verify` throws is a `VouchlyError` with a `code`. The underlying error, when there is one, is kept as `cause`.
|
|
276
|
+
|
|
277
|
+
| Code | When |
|
|
278
|
+
|------|------|
|
|
279
|
+
| `token_malformed` | Not exactly three base64url segments, or a header or payload that is not a JSON object. |
|
|
280
|
+
| `token_expired` | `exp` is in the past (beyond `clockTolerance`). |
|
|
281
|
+
| `token_inactive` | Introspection answered `active` other than `true`. |
|
|
282
|
+
| `issuer_untrusted` | No configured issuer matches `iss`. |
|
|
283
|
+
| `key_unavailable` | Discovery or the key fetch failed, no key matches the `kid`, or the key policy refused the key. |
|
|
284
|
+
| `signature_invalid` | The signature does not verify. |
|
|
285
|
+
| `claim_invalid` | `aud`, `iss`, `typ`, `nbf`, a required claim, the algorithm or the `claims` predicate. |
|
|
286
|
+
| `introspection_failed` | The introspection request failed, answered non-2xx, or did not answer a JSON object. |
|
|
287
|
+
| `binding_mismatch` | The token is certificate-bound and the presented thumbprint does not match. |
|
|
288
|
+
|
|
289
|
+
Use `isVouchlyError(error)` rather than `instanceof`: it checks a `Symbol.for('vouchly.error')` marker, so it still matches when two copies of vouchly are installed.
|
|
290
|
+
|
|
291
|
+
## API
|
|
292
|
+
|
|
293
|
+
| Export | Kind | Purpose |
|
|
294
|
+
|--------|------|---------|
|
|
295
|
+
| `createVerifier(options)`, `Verifier` | function, class | The verifier; `verify(token, options?)` answers `{ claims, issuer, source }`. |
|
|
296
|
+
| `discovery`, `jwks`, `staticKeys`, `cachedKeys` | functions | Key sources, see [Key sources](#key-sources). |
|
|
297
|
+
| `resolveVerificationKey(source, context)` | function | Runs a key source through the key policy; what the verifier uses. |
|
|
298
|
+
| `fetchProviderMetadata(issuer, fetch, options?)` | function | Reads and checks an issuer's OIDC discovery document. |
|
|
299
|
+
| `introspect(token, issuer, fetch)` | function | One RFC 7662 request; applies no claim rules of its own. |
|
|
300
|
+
| `assertCertificateBinding(claims, thumbprint)` | function | The RFC 8705 check on its own. |
|
|
301
|
+
| `MemoryTokenCache`, `ITokenCache`, `hashToken` | class, interface, function | The default cache, the cache port and the key derivation. |
|
|
302
|
+
| `parseToken`, `isCompactToken` | functions | Strict parsing without verification. |
|
|
303
|
+
| `matchIssuer`, `selectIssuer` | functions | The issuer allowlist on its own. |
|
|
304
|
+
| `VouchlyError`, `VouchlyErrorCode`, `isVouchlyError` | class, enum, function | Errors. |
|
|
305
|
+
|
|
306
|
+
## Notes
|
|
307
|
+
|
|
308
|
+
- **A locally verified token is valid until `exp`.** A signature cannot tell that the token was revoked. If revocation must take effect sooner, use introspection with a short `maxCacheTTL`, or keep access tokens short-lived.
|
|
309
|
+
- **Nothing is fetched from a URL inside the token.** Discovery, JWKS and introspection URLs come from your configuration; a function issuer therefore needs its own key source or an explicit introspection endpoint.
|
|
310
|
+
- **Keys stay in process memory.** `CryptoKey`s cannot be serialised, so key caches (`jwks`, `discovery`, `cachedKeys`) are per process even when the token cache is shared.
|
|
311
|
+
- **Key caches live on the key source instance.** Each `discovery()`, `jwks()` and `cachedKeys()` call creates its own cache, and a string issuer without `keys` gets a `discovery()` of its own per verifier. Discovery metadata is shared by every verifier using the default `fetch` (or the same `fetch` function), but the JWKS behind it is not. If you build verifiers at runtime (one per request, per tenant), create the key source once and pass the same instance to each of them, or every verifier fetches the keys again.
|
|
312
|
+
- **Results are copies.** Every result, including a cache hit, is a fresh `structuredClone`; changing it does not change the cached entry.
|
|
313
|
+
- **No permission model.** vouchly answers whether a token is genuine and which issuer it came from. Deciding what the caller may do is up to you.
|
|
314
|
+
|
|
315
|
+
## Contributing
|
|
316
|
+
|
|
317
|
+
Before starting to work on a pull request, it is important to review the guidelines for
|
|
318
|
+
[contributing](./CONTRIBUTING.md) and the [code of conduct](./CODE_OF_CONDUCT.md).
|
|
319
|
+
These guidelines will help to ensure that contributions are made effectively and are accepted.
|
|
320
|
+
|
|
321
|
+
## License
|
|
322
|
+
|
|
323
|
+
Made with 💚
|
|
324
|
+
|
|
325
|
+
Published under [Apache-2.0 License](./LICENSE).
|