@therank/identity-bridge-server 0.0.0-stage → 0.0.1

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
+ # @therank/identity-bridge-server
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
+ Server SDK for [identity-bridge](https://github.com/theRank/identity-bridge). It verifies, in your product's
4
+ backend, the bridge access tokens your clients send and the user lifecycle events the bridge delivers.
5
+ Clients get the tokens with
6
+ [`@therank/identity-bridge-client`](https://www.npmjs.com/package/@therank/identity-bridge-client).
7
+
8
+ Web APIs only, with [jose](https://github.com/panva/jose) as its one dependency. Runs on Node.js 22.12 or newer,
9
+ Cloudflare Workers, Deno and Bun. The package is an ES module only; see [Module format](#module-format).
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install @therank/identity-bridge-server
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ Create one verifier and reuse it, so the bridge's keys stay cached between requests:
20
+
21
+ ```ts
22
+ import { BridgeTokenError, createVerifier } from '@therank/identity-bridge-server'
23
+
24
+ const verifier = createVerifier({
25
+ issuer: 'https://id.acme.example', // the bridge
26
+ audience: 'acme', // your product's id in the bridge configuration
27
+ })
28
+ ```
29
+
30
+ ### Access tokens
31
+
32
+ ```ts
33
+ async function me(request: Request): Promise<Response> {
34
+ let user
35
+ try {
36
+ user = await verifier.verifyRequest(request) // reads Authorization: Bearer <token>
37
+ } catch (error) {
38
+ if (!(error instanceof BridgeTokenError)) throw error
39
+ if (error.reason === 'jwks_unavailable') return new Response(null, { status: 503 })
40
+ return new Response(null, { status: 401, headers: { 'www-authenticate': 'Bearer' } })
41
+ }
42
+ return Response.json({ id: user.userId, email: user.email })
43
+ }
44
+ ```
45
+
46
+ `verifyAccessToken(token)` does the same for a token you already hold.
47
+
48
+ `userId` is the user's id in the bridge, the same whichever identity provider they sign in with: key your own
49
+ data by it. The token carries no roles or permissions; authorization stays in your product. The identity
50
+ provider the user signed in with is deliberately not exposed, so that no product logic depends on it.
51
+
52
+ ### Events
53
+
54
+ The bridge POSTs each event to your product's events URL, the event token being the whole request body:
55
+
56
+ ```ts
57
+ async function events(request: Request): Promise<Response> {
58
+ let event
59
+ try {
60
+ event = await verifier.verifyEvent(await request.text())
61
+ } catch (error) {
62
+ if (!(error instanceof BridgeTokenError)) throw error
63
+ return new Response(null, { status: error.reason === 'jwks_unavailable' ? 503 : 400 })
64
+ }
65
+ if (!(await seen(event.jti))) await apply(event) // store it durably before answering
66
+ return new Response(null, { status: 202 })
67
+ }
68
+ ```
69
+
70
+ Answer `202` once the event is stored. The bridge counts any `2xx` answer as delivered, and any other answer,
71
+ a redirect included, as a failed delivery, which it sends again later. A delivery can also be repeated after
72
+ it succeeded, so the same event can arrive more than once, always with the same `jti`: process each `jti`
73
+ once. An event can also arrive after the user's first request with an access token.
74
+
75
+ ## API
76
+
77
+ ### `createVerifier(options)`
78
+
79
+ | Option | Type | Description |
80
+ |---|---|---|
81
+ | `issuer` | `string` | Required, not empty. The bridge's issuer URL, without a trailing slash. The keys are fetched from `${issuer}/.well-known/jwks.json`. |
82
+ | `audience` | `string` | Required, not empty. Your product's id in the bridge configuration. |
83
+ | `clockToleranceSeconds` | `number` | Leeway for `exp` and `nbf`, from `0` to `60`. Default `60`. |
84
+ | `fetch` | `typeof fetch` | Used to fetch the keys. Default: the global `fetch`. |
85
+
86
+ Invalid options throw from `createVerifier`: a `TypeError` when `issuer` or `audience` is not a non-empty
87
+ string, or when `clockToleranceSeconds` is not a number, such as the string `'30'` read from an environment
88
+ variable; a `RangeError` when `clockToleranceSeconds` is outside `0` to `60`. So a missing setting fails at
89
+ startup instead of letting other products' tokens through.
90
+
91
+ The keys are cached for 10 minutes; a token whose key is not among them makes the verifier fetch the keys
92
+ again, at most once every 30 seconds. A fetch that has not completed after 5 seconds fails.
93
+
94
+ Returns a verifier with:
95
+
96
+ - `verifyAccessToken(token: string): Promise<BridgeUser>`
97
+ - `verifyRequest(request: Request): Promise<BridgeUser>`: verifies the bearer token of the `Authorization`
98
+ header.
99
+ - `verifyEvent(body: string): Promise<BridgeEvent>`: verifies the body of an event delivery.
100
+
101
+ An access token must be signed by a key of the bridge with ES256, have `typ` `at+jwt` (or
102
+ `application/at+jwt`), be issued by `issuer` for `audience`, carry `exp`, `iat` and `sub`, and not have
103
+ expired. An event must be signed the same way, have `typ` `secevent+jwt` (or `application/secevent+jwt`),
104
+ be issued by `issuer` for `audience`, carry `iat`, `jti` and `sub`, and hold exactly one event of a known
105
+ type. Events carry no `exp`. Both kinds of token are signed with the same keys, so the `typ` check is what
106
+ keeps an event, which never expires, from being accepted as an access token.
107
+
108
+ ### `BridgeUser`
109
+
110
+ | Property | Type | Description |
111
+ |---|---|---|
112
+ | `userId` | `string` | The user's id: a lowercase UUID. |
113
+ | `email` | `string?` | Present only when the identity provider verified it. |
114
+ | `phoneNumber` | `string?` | E.164, present only when the identity provider verified it. |
115
+ | `name` | `string?` | Display name. |
116
+ | `picture` | `string?` | Avatar URL. |
117
+ | `region` | `string?` | The bridge deployment's region label, such as `us`, when it has one. |
118
+ | `expiresAt` | `number` | When the token expires, in seconds since the epoch. |
119
+
120
+ ### `BridgeEvent`
121
+
122
+ | Property | Type | Description |
123
+ |---|---|---|
124
+ | `jti` | `string` | The event's id, the same on every delivery of the event. |
125
+ | `type` | `'user-created' \| 'user-updated' \| 'user-deleted'` | What happened. |
126
+ | `userId` | `string` | The user's id, as in `BridgeUser`. |
127
+ | `profile` | `{ email?, phoneNumber?, name?, picture? }` | The user's current profile, with the same rules as `BridgeUser`. Empty for `user-deleted`. |
128
+ | `issuedAt` | `number` | When the bridge signed the event, in seconds since the epoch. |
129
+
130
+ ### `BridgeTokenError`
131
+
132
+ Every verification failure rejects with a `BridgeTokenError` whose `reason` says why. It has no `cause`, and
133
+ its message holds the reason alone, never the token or its claims, so it is safe to log.
134
+
135
+ Only two other kinds of error can occur. Invalid options throw from `createVerifier`, above. And a runtime
136
+ that lacks a Web API the verifier needs, such as `AbortSignal.timeout`, can make `verifyAccessToken`,
137
+ `verifyRequest` or `verifyEvent` reject with the runtime's own error, passed on unchanged: it is a defect of
138
+ the runtime, not a verdict on the token, and it holds nothing from the token. The examples above rethrow it.
139
+
140
+ | `reason` | Meaning |
141
+ |---|---|
142
+ | `missing` | No token: an empty token, or no `Authorization: Bearer` header. |
143
+ | `malformed` | Not a well-formed token, or a time claim that is not a number. |
144
+ | `wrong_algorithm` | Not signed with ES256. |
145
+ | `unknown_key` | No single key of the bridge matches the token. |
146
+ | `bad_signature` | The signature does not verify. |
147
+ | `expired` | The token expired, beyond the clock tolerance. |
148
+ | `wrong_type` | The wrong kind of token, such as an event given to `verifyAccessToken`. |
149
+ | `wrong_issuer` | Issued by another bridge, or no issuer. |
150
+ | `wrong_audience` | Issued for another product, or no audience. |
151
+ | `invalid_claims` | A required claim is missing or invalid, the token is not valid yet, or the event is not exactly one known event. |
152
+ | `jwks_unavailable` | The bridge's keys could not be fetched or used. Try again later. |
153
+
154
+ ## Module format
155
+
156
+ The package is an ES module only; `import` it. From CommonJS:
157
+
158
+ - **Node.js**: `require('@therank/identity-bridge-server')` works on Node.js 22.12 or newer, through Node's
159
+ support for `require()` of ES modules.
160
+ - **TypeScript compiled to CommonJS**: set `module` and `moduleResolution` to `nodenext` and write `import`
161
+ statements; TypeScript 5.8 or newer turns them into `require()` calls. With `module` set to `node16`,
162
+ TypeScript refuses to load an ES module from CommonJS. When a bundler builds your code, `moduleResolution`
163
+ `bundler` works too.
164
+
165
+ ## Support
166
+
167
+ Node.js 22.12 or newer, Cloudflare Workers, Deno and Bun. jose 6 needs Node.js 20 or newer, Node.js 20 reached
168
+ its end of life in April 2026, and 22.12 is the first Node.js 22 that loads ES modules through `require()`
169
+ without a flag.
170
+
171
+ ## License
172
+
173
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,64 @@
1
+ export interface VerifierOptions {
2
+ /** The bridge's issuer URL, without a trailing slash. The keys are fetched from `${issuer}/.well-known/jwks.json`. */
3
+ issuer: string;
4
+ /** Your product's id in the bridge configuration. */
5
+ audience: string;
6
+ /** Leeway for `exp` and `nbf`, from 0 to 60. Default 60. */
7
+ clockToleranceSeconds?: number | undefined;
8
+ /** Used to fetch the keys. Default: the global `fetch`. */
9
+ fetch?: typeof fetch | undefined;
10
+ }
11
+ export interface Verifier {
12
+ /** Verifies a bridge access token. */
13
+ verifyAccessToken(token: string): Promise<BridgeUser>;
14
+ /** Verifies the bearer token of the request's `Authorization` header. */
15
+ verifyRequest(request: Request): Promise<BridgeUser>;
16
+ /** Verifies the body of an event delivery, which is the event token itself. */
17
+ verifyEvent(body: string): Promise<BridgeEvent>;
18
+ }
19
+ /** Email and phone number are present only when the identity provider verified them. */
20
+ export interface BridgeProfile {
21
+ email?: string;
22
+ /** E.164. */
23
+ phoneNumber?: string;
24
+ name?: string;
25
+ /** An avatar URL. */
26
+ picture?: string;
27
+ }
28
+ /** The user of a verified access token. */
29
+ export interface BridgeUser extends BridgeProfile {
30
+ /** The user's id in the bridge, a lowercase UUID, the same whichever identity provider they sign in with. */
31
+ userId: string;
32
+ /** The bridge deployment's region label, when it has one. */
33
+ region?: string;
34
+ /** When the token expires, in seconds since the epoch. */
35
+ expiresAt: number;
36
+ }
37
+ export type BridgeEventType = 'user-created' | 'user-updated' | 'user-deleted';
38
+ /** A verified user lifecycle event. */
39
+ export interface BridgeEvent {
40
+ /** The event's id, the same on every delivery of the event: process each `jti` once. */
41
+ jti: string;
42
+ type: BridgeEventType;
43
+ userId: string;
44
+ /** The user's current profile; empty for `user-deleted`. */
45
+ profile: BridgeProfile;
46
+ /** When the bridge signed the event, in seconds since the epoch. */
47
+ issuedAt: number;
48
+ }
49
+ export type BridgeTokenErrorReason = 'missing' | 'malformed' | 'wrong_algorithm' | 'unknown_key' | 'bad_signature' | 'expired' | 'wrong_type' | 'wrong_issuer' | 'wrong_audience' | 'invalid_claims' | 'jwks_unavailable';
50
+ /**
51
+ * A verification failure, with its `reason`. It has no `cause`, and its message holds the reason alone, never the
52
+ * token or its claims, so it is safe to log.
53
+ */
54
+ export declare class BridgeTokenError extends Error {
55
+ name: string;
56
+ readonly reason: BridgeTokenErrorReason;
57
+ constructor(reason: BridgeTokenErrorReason);
58
+ }
59
+ /**
60
+ * A verifier of bridge access tokens and event tokens for one product. Create one and reuse it, so the bridge's
61
+ * keys stay cached. Throws a `TypeError` or `RangeError` for invalid options. Every verification failure rejects
62
+ * with a `BridgeTokenError`; a runtime missing a required Web API can reject with its own error.
63
+ */
64
+ export declare function createVerifier(options: VerifierOptions): Verifier;
package/dist/index.js ADDED
@@ -0,0 +1,222 @@
1
+ import { createRemoteJWKSet, customFetch, errors, jwtVerify } from 'jose';
2
+ /**
3
+ * A verification failure, with its `reason`. It has no `cause`, and its message holds the reason alone, never the
4
+ * token or its claims, so it is safe to log.
5
+ */
6
+ export class BridgeTokenError extends Error {
7
+ name = 'BridgeTokenError';
8
+ reason;
9
+ // No cause, as jose's errors hold the decoded claims, email and phone included
10
+ constructor(reason) {
11
+ super(`bridge token rejected: ${reason}`);
12
+ this.reason = reason;
13
+ }
14
+ }
15
+ const JWKS_TIMEOUT_MS = 5000;
16
+ const MAX_CLOCK_TOLERANCE_SECONDS = 60;
17
+ const USER_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
18
+ const BEARER = /^Bearer +(\S+)$/i;
19
+ // A Map, so a member such as __proto__ never finds an Object.prototype member
20
+ const EVENT_TYPES = new Map([
21
+ ['urn:identity-bridge:event:user-created', 'user-created'],
22
+ ['urn:identity-bridge:event:user-updated', 'user-updated'],
23
+ ['urn:identity-bridge:event:user-deleted', 'user-deleted'],
24
+ ]);
25
+ // Never quotes the response
26
+ class JwksFetchError extends Error {
27
+ name = 'JwksFetchError';
28
+ }
29
+ class InvalidClaims extends Error {
30
+ }
31
+ /**
32
+ * A verifier of bridge access tokens and event tokens for one product. Create one and reuse it, so the bridge's
33
+ * keys stay cached. Throws a `TypeError` or `RangeError` for invalid options. Every verification failure rejects
34
+ * with a `BridgeTokenError`; a runtime missing a required Web API can reject with its own error.
35
+ */
36
+ export function createVerifier(options) {
37
+ const { issuer, audience, clockToleranceSeconds = MAX_CLOCK_TOLERANCE_SECONDS } = options;
38
+ // jose skips the aud check when audience is undefined, as from an unset environment variable, which would accept
39
+ // every product's tokens
40
+ if (typeof issuer !== 'string' || issuer === '')
41
+ throw new TypeError('issuer must be a non-empty string');
42
+ if (typeof audience !== 'string' || audience === '')
43
+ throw new TypeError('audience must be a non-empty string');
44
+ if (typeof clockToleranceSeconds !== 'number')
45
+ throw new TypeError('clockToleranceSeconds must be a number');
46
+ if (!(clockToleranceSeconds >= 0 && clockToleranceSeconds <= MAX_CLOCK_TOLERANCE_SECONDS)) {
47
+ throw new RangeError(`clockToleranceSeconds must be between 0 and ${MAX_CLOCK_TOLERANCE_SECONDS}`);
48
+ }
49
+ // One key set per verifier, so its keys and refetch cooldown carry across calls
50
+ const jwks = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`), {
51
+ [customFetch]: jwksFetch(options.fetch),
52
+ timeoutDuration: JWKS_TIMEOUT_MS,
53
+ });
54
+ async function verify(token, typ, requiredClaims) {
55
+ if (typeof token !== 'string' || token === '')
56
+ throw new BridgeTokenError('missing');
57
+ try {
58
+ const { payload } = await jwtVerify(token, jwks, { algorithms: ['ES256'], issuer, audience, typ, requiredClaims, clockTolerance: clockToleranceSeconds });
59
+ return payload;
60
+ }
61
+ catch (error) {
62
+ const reason = failureReason(error, () => jwks.jwks() !== undefined);
63
+ if (reason === undefined)
64
+ throw error;
65
+ throw new BridgeTokenError(reason);
66
+ }
67
+ }
68
+ // typ is normalized by jose, so application/at+jwt and application/secevent+jwt are accepted too. Both kinds
69
+ // are signed with the same keys, and an event has no exp: the typ check keeps one from passing as the other.
70
+ async function verifyAccessToken(token) {
71
+ return checked(bridgeUser, await verify(token, 'at+jwt', ['exp', 'iat', 'sub']));
72
+ }
73
+ return {
74
+ verifyAccessToken,
75
+ async verifyRequest(request) {
76
+ const match = BEARER.exec(request.headers.get('authorization') ?? '');
77
+ if (match === null)
78
+ throw new BridgeTokenError('missing');
79
+ return verifyAccessToken(match[1]);
80
+ },
81
+ async verifyEvent(body) {
82
+ return checked(bridgeEvent, await verify(body, 'secevent+jwt', ['iat', 'jti', 'sub']));
83
+ },
84
+ };
85
+ }
86
+ function checked(read, payload) {
87
+ try {
88
+ return read(payload);
89
+ }
90
+ catch (error) {
91
+ if (error instanceof InvalidClaims)
92
+ throw new BridgeTokenError('invalid_claims');
93
+ throw error;
94
+ }
95
+ }
96
+ // The idp claim is left out on purpose: products must not branch on the identity provider
97
+ function bridgeUser(payload) {
98
+ const user = { userId: userId(payload.sub), ...profile(payload), expiresAt: payload.exp };
99
+ const region = optionalString(payload.region);
100
+ if (region !== undefined)
101
+ user.region = region;
102
+ return user;
103
+ }
104
+ // Exactly one event, of a known type, whose payload is an object; a deletion carries no profile
105
+ function bridgeEvent(payload) {
106
+ const { jti, events } = payload;
107
+ if (typeof jti !== 'string' || jti === '' || !isRecord(events))
108
+ throw new InvalidClaims();
109
+ const names = Object.keys(events);
110
+ const type = names.length === 1 ? EVENT_TYPES.get(names[0]) : undefined;
111
+ const event = names.length === 1 ? events[names[0]] : undefined;
112
+ if (type === undefined || !isRecord(event))
113
+ throw new InvalidClaims();
114
+ return { jti, type, userId: userId(payload.sub), profile: type === 'user-deleted' ? {} : profile(event), issuedAt: payload.iat };
115
+ }
116
+ function profile(claims) {
117
+ const result = {};
118
+ const email = optionalString(claims.email);
119
+ const phoneNumber = optionalString(claims.phone_number);
120
+ const name = optionalString(claims.name);
121
+ const picture = optionalString(claims.picture);
122
+ if (email !== undefined)
123
+ result.email = email;
124
+ if (phoneNumber !== undefined)
125
+ result.phoneNumber = phoneNumber;
126
+ if (name !== undefined)
127
+ result.name = name;
128
+ if (picture !== undefined)
129
+ result.picture = picture;
130
+ return result;
131
+ }
132
+ function userId(sub) {
133
+ if (typeof sub !== 'string' || !USER_ID.test(sub))
134
+ throw new InvalidClaims();
135
+ return sub;
136
+ }
137
+ function optionalString(value) {
138
+ if (value !== undefined && typeof value !== 'string')
139
+ throw new InvalidClaims();
140
+ return value;
141
+ }
142
+ function isRecord(value) {
143
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
144
+ }
145
+ // Rows in order: several reasons share an error class and differ only in claim or reason
146
+ function failureReason(error, keysFetched) {
147
+ if (error instanceof errors.JWSInvalid || error instanceof errors.JWTInvalid || error instanceof errors.JOSENotSupported)
148
+ return 'malformed';
149
+ if (error instanceof errors.JWTClaimValidationFailed && error.reason === 'invalid')
150
+ return 'malformed';
151
+ if (error instanceof errors.JOSEAlgNotAllowed)
152
+ return 'wrong_algorithm';
153
+ if (error instanceof errors.JWKSNoMatchingKey || error instanceof errors.JWKSMultipleMatchingKeys)
154
+ return 'unknown_key';
155
+ if (error instanceof errors.JWSSignatureVerificationFailed)
156
+ return 'bad_signature';
157
+ if (error instanceof errors.JWTExpired)
158
+ return 'expired';
159
+ if (error instanceof errors.JWTClaimValidationFailed) {
160
+ if (error.claim === 'typ')
161
+ return 'wrong_type';
162
+ if (error.claim === 'iss')
163
+ return 'wrong_issuer';
164
+ if (error.claim === 'aud')
165
+ return 'wrong_audience';
166
+ return 'invalid_claims';
167
+ }
168
+ if (error instanceof JwksFetchError || error instanceof errors.JWKSTimeout || error instanceof errors.JWKSInvalid)
169
+ return 'jwks_unavailable';
170
+ // jose raises these while importing a published key it cannot use. One raised before any key set was fetched,
171
+ // as for a missing runtime API, is not the bridge's doing.
172
+ if ((error instanceof TypeError || isDomException(error)) && keysFetched())
173
+ return 'jwks_unavailable';
174
+ return undefined;
175
+ }
176
+ // Not every runtime defines DOMException
177
+ function isDomException(error) {
178
+ return typeof DOMException !== 'undefined' && error instanceof DOMException;
179
+ }
180
+ // jose throws a generic JOSEError for a non-200 or non-JSON answer, which could not be told apart from other
181
+ // failures, so every failure here is a JwksFetchError. The timer races jose's abort signal because a runtime
182
+ // without AbortController cannot abort the fetch; it covers reading the body too.
183
+ function jwksFetch(given) {
184
+ return (url, init) => withTimeout(load(given ?? fetch, url, init), JWKS_TIMEOUT_MS);
185
+ }
186
+ async function load(fetchJwks, url, init) {
187
+ let response;
188
+ try {
189
+ response = await fetchJwks(url, init);
190
+ }
191
+ catch {
192
+ throw new JwksFetchError('JWKS request failed');
193
+ }
194
+ if (response.status !== 200) {
195
+ // Releases the connection rather than leaving the body unread
196
+ await response.body?.cancel().catch(() => { });
197
+ throw new JwksFetchError('JWKS response status is not 200');
198
+ }
199
+ let text;
200
+ try {
201
+ text = new TextDecoder().decode(await response.arrayBuffer());
202
+ }
203
+ catch {
204
+ throw new JwksFetchError('JWKS response body could not be read');
205
+ }
206
+ let body;
207
+ try {
208
+ body = JSON.parse(text);
209
+ }
210
+ catch {
211
+ throw new JwksFetchError('JWKS response is not JSON');
212
+ }
213
+ if (typeof body !== 'object' || body === null || Array.isArray(body))
214
+ throw new JwksFetchError('JWKS response is not a JSON object');
215
+ return new Response(text, { status: 200, headers: { 'content-type': 'application/json' } });
216
+ }
217
+ function withTimeout(work, ms) {
218
+ return new Promise((resolve, reject) => {
219
+ const timer = setTimeout(() => reject(new JwksFetchError('JWKS request timed out')), ms);
220
+ work.then(resolve, reject).finally(() => clearTimeout(timer));
221
+ });
222
+ }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
- "name": "@therank/identity-bridge-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@therank/identity-bridge-server",
3
+ "version": "0.0.1",
4
+ "description": "Server SDK for identity-bridge: verify bridge access tokens and lifecycle events",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/theRank/identity-bridge.git",
9
+ "directory": "packages/server"
10
+ },
11
+ "type": "module",
12
+ "engines": {
13
+ "node": ">=22.12"
14
+ },
15
+ "main": "./dist/index.js",
16
+ "exports": {
17
+ ".": "./dist/index.js"
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "scripts": {
23
+ "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p .",
24
+ "prepack": "npm run build",
25
+ "test:node": "node test-node/verify.mjs"
26
+ },
27
+ "dependencies": {
28
+ "jose": "^6.2.17"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ }
33
+ }