@buwigs/auth-sdk 0.0.0-stage → 0.2.0-alpha.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 +202 -0
- package/NOTICE +11 -0
- package/README.md +72 -2
- package/package.json +33 -4
- package/src/index.d.ts +77 -0
- package/src/index.js +247 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Buwigs Auth SDK
|
|
2
|
+
Copyright 2026 Buwigs.
|
|
3
|
+
|
|
4
|
+
This distribution contains SDK source code authored and maintained by Buwigs.
|
|
5
|
+
No third-party implementation source is bundled in this package. Runtime
|
|
6
|
+
libraries are declared as package dependencies, distributed separately, and
|
|
7
|
+
remain subject to their own license terms and notices.
|
|
8
|
+
|
|
9
|
+
The Buwigs Auth server implementation and its private repository are separate
|
|
10
|
+
works and are not licensed under this notice or the Apache License 2.0 copy
|
|
11
|
+
accompanying this SDK package.
|
package/README.md
CHANGED
|
@@ -1,3 +1,73 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@buwigs/auth-sdk`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Provider-independent OIDC helpers for Node.js 20+ and TypeScript. The package
|
|
4
|
+
includes TypeScript declarations and is released as a standalone npm tarball.
|
|
5
|
+
|
|
6
|
+
Install after the package is published to npm:
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
npm install @buwigs/auth-sdk@0.2.0-alpha.1
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Configure the exact trusted issuer, OIDC client ID, API audience, and exact
|
|
13
|
+
registered callback URI. Production issuer and callback URLs require HTTPS.
|
|
14
|
+
Local HTTP is permitted only with `allowLocalHttp: true` and loopback hosts.
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { OidcClient } from '@buwigs/auth-sdk'
|
|
18
|
+
|
|
19
|
+
const oidc = await OidcClient.discover({
|
|
20
|
+
issuer: process.env.BUWIGS_AUTH_ISSUER!,
|
|
21
|
+
clientId: process.env.BUWIGS_AUTH_CLIENT_ID!,
|
|
22
|
+
apiAudience: process.env.BUWIGS_AUTH_API_AUDIENCE!,
|
|
23
|
+
redirectUri: process.env.BUWIGS_AUTH_REDIRECT_URI!,
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
const transaction = oidc.authorizationRequest(['openid', 'profile'])
|
|
27
|
+
// Store state, nonce, and verifier in a session-bound, one-time server-side record.
|
|
28
|
+
// Redirect the browser to transaction.url; validate returned state before exchange.
|
|
29
|
+
oidc.validateState(expectedState, callbackState)
|
|
30
|
+
const tokens = await oidc.exchangeCode(code, transaction.verifier)
|
|
31
|
+
const identity = await oidc.verifyIdToken(tokens.id_token as string, {
|
|
32
|
+
expectedNonce: transaction.nonce,
|
|
33
|
+
})
|
|
34
|
+
const apiPrincipal = await oidc.verifyAccessToken(tokens.access_token as string)
|
|
35
|
+
const profile = await oidc.getUserInfo(tokens.access_token as string, identity)
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Access-token verification is pinned to the configured issuer and API audience;
|
|
39
|
+
ID-token verification uses the configured client audience and transaction
|
|
40
|
+
nonce. RS256 is the only accepted signing algorithm. Identity is exactly
|
|
41
|
+
`(issuer, subject)`; email and phone are not account-linking keys.
|
|
42
|
+
|
|
43
|
+
`refreshToken` performs exactly one refresh exchange and returns the provider
|
|
44
|
+
rotation response. The caller must atomically replace refresh credentials in
|
|
45
|
+
secure storage. `revokeToken` is available only when discovery advertises it;
|
|
46
|
+
`endSessionUrl` builds a logout navigation URL from discovery and restricts the
|
|
47
|
+
post-logout redirect to the configured client origin. UserInfo `sub` must match
|
|
48
|
+
the verified principal. The SDK does not persist credentials, retry exchanges,
|
|
49
|
+
manage local sessions, or enforce business authorization. Never put a
|
|
50
|
+
confidential client secret in browser code.
|
|
51
|
+
|
|
52
|
+
### Backend middleware
|
|
53
|
+
|
|
54
|
+
The SDK exports `expressAuth(oidc)` and `fastifyAuth(oidc)` for bearer-token
|
|
55
|
+
authentication. They validate the configured issuer, API audience, RS256
|
|
56
|
+
signature, expiry, subject, and authorized party (`azp`), then attach an
|
|
57
|
+
immutable `req.auth` / `request.auth` principal. They return a generic 401 for
|
|
58
|
+
missing or invalid tokens. This authenticates the caller only: each application
|
|
59
|
+
must still check its own tenant membership, roles, and permissions.
|
|
60
|
+
|
|
61
|
+
Use these hooks only on API routes. Do not accept an identity or role from
|
|
62
|
+
request JSON, and never use the decoded token without SDK verification.
|
|
63
|
+
|
|
64
|
+
The Node test suite includes an end-to-end client flow against a local synthetic
|
|
65
|
+
OIDC provider. That verifies discovery, S256 authorization request, callback
|
|
66
|
+
state, code exchange, nonce, ID/access token validation, UserInfo, revocation,
|
|
67
|
+
logout URL construction, and replay rejection. It is a protocol mock, not a
|
|
68
|
+
live deployment or conformance certification.
|
|
69
|
+
|
|
70
|
+
## License
|
|
71
|
+
|
|
72
|
+
This SDK source is licensed under Apache-2.0. See the bundled `LICENSE` and
|
|
73
|
+
`NOTICE`. The Buwigs Auth server is separate proprietary software.
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@buwigs/auth-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0-alpha.1",
|
|
4
|
+
"description": "Buwigs Auth OIDC SDK",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"main": "./src/index.js",
|
|
8
|
+
"module": "./src/index.js",
|
|
9
|
+
"publishConfig": {
|
|
10
|
+
"access": "public"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"src/**",
|
|
14
|
+
"README.md",
|
|
15
|
+
"LICENSE",
|
|
16
|
+
"NOTICE"
|
|
17
|
+
],
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./src/index.d.ts",
|
|
21
|
+
"import": "./src/index.js"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"types": "./src/index.d.ts",
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=20"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"test": "node --test"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"jose": "6.2.17"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {}
|
|
35
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
export interface Principal {
|
|
4
|
+
issuer: string
|
|
5
|
+
subject: string
|
|
6
|
+
audience: string[]
|
|
7
|
+
claims: Record<string, unknown>
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface PkcePair {
|
|
11
|
+
verifier: string
|
|
12
|
+
challenge: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface AuthorizationRequest {
|
|
16
|
+
url: string
|
|
17
|
+
state: string
|
|
18
|
+
nonce: string
|
|
19
|
+
verifier: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface OidcClientConfig {
|
|
23
|
+
issuer: string
|
|
24
|
+
clientId: string
|
|
25
|
+
apiAudience: string
|
|
26
|
+
redirectUri: string
|
|
27
|
+
allowLocalHttp?: boolean
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface AuthenticatedRequest {
|
|
31
|
+
auth: Principal
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type ExpressAuthMiddleware = (
|
|
35
|
+
request: AuthenticatedRequest & { headers: Record<string, string | string[] | undefined> },
|
|
36
|
+
response: { setHeader(name: string, value: string): unknown; status(code: number): { json(body: unknown): unknown } },
|
|
37
|
+
next: (error?: unknown) => unknown,
|
|
38
|
+
) => Promise<unknown>
|
|
39
|
+
|
|
40
|
+
export type FastifyAuthHook = (
|
|
41
|
+
request: AuthenticatedRequest & { headers: Record<string, string | string[] | undefined> },
|
|
42
|
+
reply: { header(name: string, value: string): unknown; code(status: number): { send(body: unknown): unknown } },
|
|
43
|
+
) => Promise<unknown>
|
|
44
|
+
|
|
45
|
+
export interface IdTokenValidationOptions {
|
|
46
|
+
expectedNonce?: string
|
|
47
|
+
expectedNonceHash?: string
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function createPkcePair(): PkcePair
|
|
51
|
+
|
|
52
|
+
export class OidcClient {
|
|
53
|
+
static discover(config: OidcClientConfig): Promise<OidcClient>
|
|
54
|
+
authorizationRequest(scopes?: string[]): AuthorizationRequest
|
|
55
|
+
validateState(expected: string, received: string): void
|
|
56
|
+
exchangeCode(code: string, verifier: string, clientSecret?: string): Promise<Record<string, unknown>>
|
|
57
|
+
refreshToken(refreshToken: string, clientSecret?: string): Promise<Record<string, unknown>>
|
|
58
|
+
revokeToken(token: string, tokenTypeHint?: 'access_token' | 'refresh_token', clientSecret?: string): Promise<void>
|
|
59
|
+
getUserInfo(accessToken: string, authenticatedPrincipal: Principal): Promise<Record<string, unknown>>
|
|
60
|
+
endSessionUrl(options: {
|
|
61
|
+
idTokenHint?: string
|
|
62
|
+
postLogoutRedirectUri?: string
|
|
63
|
+
state?: string
|
|
64
|
+
}): string
|
|
65
|
+
verifyAccessToken(token: string, audience?: string): Promise<Principal>
|
|
66
|
+
verifyIdToken(token: string, options: IdTokenValidationOptions): Promise<Principal>
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Authentication only; consuming applications still authorize tenants and roles. */
|
|
70
|
+
export function expressAuth(oidc: OidcClient): ExpressAuthMiddleware
|
|
71
|
+
/** Fastify onRequest hook. Register it only on routes that need authentication. */
|
|
72
|
+
export function fastifyAuth(oidc: OidcClient): FastifyAuthHook
|
|
73
|
+
|
|
74
|
+
export function verifyAccessToken(
|
|
75
|
+
token: string,
|
|
76
|
+
options: { issuer: string; audience: string; clientId: string; jwks: unknown; allowLocalHttp?: boolean },
|
|
77
|
+
): Promise<Principal>
|
package/src/index.js
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
|
|
4
|
+
import { createRemoteJWKSet, jwtVerify } from 'jose'
|
|
5
|
+
|
|
6
|
+
function secureUrl(value, { loopback = false } = {}) {
|
|
7
|
+
const url = new URL(value)
|
|
8
|
+
const localHttp = loopback && url.protocol === 'http:' && ['localhost', '127.0.0.1'].includes(url.hostname)
|
|
9
|
+
if (url.protocol !== 'https:' && !localHttp) throw new TypeError('HTTPS is required')
|
|
10
|
+
if (url.username || url.password || url.hash || url.search) throw new TypeError('URL credentials, query strings and fragments are forbidden')
|
|
11
|
+
return url
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function createPkcePair() {
|
|
15
|
+
const verifier = randomBytes(48).toString('base64url')
|
|
16
|
+
const challenge = createHash('sha256').update(verifier).digest('base64url')
|
|
17
|
+
return { verifier, challenge }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export class OidcClient {
|
|
21
|
+
constructor(config, discovery, jwks) {
|
|
22
|
+
this.issuer = config.issuer.replace(/\/$/, '')
|
|
23
|
+
this.clientId = config.clientId
|
|
24
|
+
this.apiAudience = config.apiAudience
|
|
25
|
+
this.redirectUri = config.redirectUri
|
|
26
|
+
this.allowLocalHttp = config.allowLocalHttp
|
|
27
|
+
this.discovery = discovery
|
|
28
|
+
this.jwks = jwks
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
static async discover({ issuer, clientId, apiAudience, redirectUri, allowLocalHttp = false }) {
|
|
32
|
+
const issuerUrl = secureUrl(issuer, { loopback: allowLocalHttp })
|
|
33
|
+
const redirect = secureUrl(redirectUri, { loopback: allowLocalHttp })
|
|
34
|
+
if (!clientId?.trim() || !apiAudience?.trim()) throw new TypeError('client ID and API audience are required')
|
|
35
|
+
const normalizedIssuer = issuerUrl.toString().replace(/\/$/, '')
|
|
36
|
+
const discoveryUrl = `${normalizedIssuer}/.well-known/openid-configuration`
|
|
37
|
+
const response = await fetch(discoveryUrl, { redirect: 'error', signal: AbortSignal.timeout(5000) })
|
|
38
|
+
if (!response.ok) throw new Error('OIDC discovery failed')
|
|
39
|
+
const discovery = await response.json()
|
|
40
|
+
if (discovery.issuer !== normalizedIssuer) throw new Error('OIDC issuer mismatch')
|
|
41
|
+
for (const key of ['authorization_endpoint', 'token_endpoint', 'jwks_uri', 'userinfo_endpoint', 'revocation_endpoint', 'end_session_endpoint']) {
|
|
42
|
+
if (!(key in discovery)) {
|
|
43
|
+
if (['authorization_endpoint', 'token_endpoint', 'jwks_uri'].includes(key)) throw new Error('OIDC discovery is missing a required endpoint')
|
|
44
|
+
continue
|
|
45
|
+
}
|
|
46
|
+
const endpoint = secureUrl(discovery[key], { loopback: allowLocalHttp })
|
|
47
|
+
const issuerPath = issuerUrl.pathname.replace(/\/$/, '')
|
|
48
|
+
if (endpoint.origin !== issuerUrl.origin || !endpoint.pathname.startsWith(`${issuerPath}/`) || endpoint.search) {
|
|
49
|
+
throw new Error('OIDC discovery endpoint must stay under the configured issuer origin and path')
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return new OidcClient({ issuer: normalizedIssuer, clientId, apiAudience, redirectUri: redirect.toString(), allowLocalHttp },
|
|
53
|
+
discovery, createRemoteJWKSet(new URL(discovery.jwks_uri), { timeoutDuration: 5000, cooldownDuration: 5000, cacheMaxAge: 300000 }))
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
authorizationRequest(scopes = ['openid', 'profile']) {
|
|
57
|
+
const { verifier, challenge } = createPkcePair()
|
|
58
|
+
const state = randomBytes(32).toString('base64url')
|
|
59
|
+
const nonce = randomBytes(32).toString('base64url')
|
|
60
|
+
const url = new URL(this.discovery.authorization_endpoint)
|
|
61
|
+
url.search = new URLSearchParams({ client_id: this.clientId, redirect_uri: this.redirectUri,
|
|
62
|
+
response_type: 'code', response_mode: 'query', scope: scopes.join(' '), state, nonce,
|
|
63
|
+
code_challenge: challenge, code_challenge_method: 'S256' }).toString()
|
|
64
|
+
return { url: url.toString(), state, nonce, verifier }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
validateState(expected, received) {
|
|
68
|
+
if (typeof expected !== 'string' || typeof received !== 'string') throw new Error('OIDC state mismatch')
|
|
69
|
+
const a = Buffer.from(expected); const b = Buffer.from(received)
|
|
70
|
+
if (a.length !== b.length || !timingSafeEqual(a, b)) throw new Error('OIDC state mismatch')
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async exchangeCode(code, verifier, clientSecret) {
|
|
74
|
+
if (typeof code !== 'string' || !code || typeof verifier !== 'string' || verifier.length < 43 || verifier.length > 128) throw new TypeError('invalid authorization response')
|
|
75
|
+
const body = new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: this.redirectUri,
|
|
76
|
+
client_id: this.clientId, code_verifier: verifier })
|
|
77
|
+
const headers = { 'content-type': 'application/x-www-form-urlencoded' }
|
|
78
|
+
if (clientSecret) headers.authorization = `Basic ${Buffer.from(`${this.clientId}:${clientSecret}`).toString('base64')}`
|
|
79
|
+
const response = await fetch(this.discovery.token_endpoint, { method: 'POST', headers, body, redirect: 'error', signal: AbortSignal.timeout(5000) })
|
|
80
|
+
if (!response.ok) throw new Error('authorization code exchange failed')
|
|
81
|
+
return response.json()
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async refreshToken(refreshToken, clientSecret) {
|
|
85
|
+
if (typeof refreshToken !== 'string' || !refreshToken) throw new TypeError('refresh token is required')
|
|
86
|
+
const body = new URLSearchParams({ grant_type: 'refresh_token', refresh_token: refreshToken, client_id: this.clientId })
|
|
87
|
+
const headers = { 'content-type': 'application/x-www-form-urlencoded' }
|
|
88
|
+
if (clientSecret) {
|
|
89
|
+
headers.authorization = `Basic ${Buffer.from(`${this.clientId}:${clientSecret}`).toString('base64')}`
|
|
90
|
+
body.delete('client_id')
|
|
91
|
+
}
|
|
92
|
+
const response = await fetch(this.discovery.token_endpoint, {
|
|
93
|
+
method: 'POST', headers, body, redirect: 'error', signal: AbortSignal.timeout(5000),
|
|
94
|
+
})
|
|
95
|
+
if (!response.ok) throw new Error('refresh token exchange failed')
|
|
96
|
+
// Return the rotation response unchanged. The caller must atomically replace
|
|
97
|
+
// securely stored refresh credentials; this method never persists or retries.
|
|
98
|
+
return response.json()
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async revokeToken(token, tokenTypeHint = 'refresh_token', clientSecret) {
|
|
102
|
+
if (!this.discovery.revocation_endpoint) throw new Error('provider does not advertise token revocation')
|
|
103
|
+
if (typeof token !== 'string' || !token || !['access_token', 'refresh_token'].includes(tokenTypeHint)) {
|
|
104
|
+
throw new TypeError('invalid token revocation request')
|
|
105
|
+
}
|
|
106
|
+
const body = new URLSearchParams({ token, token_type_hint: tokenTypeHint, client_id: this.clientId })
|
|
107
|
+
const headers = { 'content-type': 'application/x-www-form-urlencoded' }
|
|
108
|
+
if (clientSecret) {
|
|
109
|
+
headers.authorization = `Basic ${Buffer.from(`${this.clientId}:${clientSecret}`).toString('base64')}`
|
|
110
|
+
body.delete('client_id')
|
|
111
|
+
}
|
|
112
|
+
const response = await fetch(this.discovery.revocation_endpoint, {
|
|
113
|
+
method: 'POST', headers, body, redirect: 'error', signal: AbortSignal.timeout(5000),
|
|
114
|
+
})
|
|
115
|
+
if (!response.ok) throw new Error('token revocation failed')
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async getUserInfo(accessToken, authenticatedPrincipal) {
|
|
119
|
+
if (!this.discovery.userinfo_endpoint) throw new Error('provider does not advertise UserInfo')
|
|
120
|
+
if (typeof accessToken !== 'string' || !accessToken || authenticatedPrincipal?.issuer !== this.issuer) {
|
|
121
|
+
throw new TypeError('access token and principal from this issuer are required')
|
|
122
|
+
}
|
|
123
|
+
const response = await fetch(this.discovery.userinfo_endpoint, {
|
|
124
|
+
headers: { authorization: `Bearer ${accessToken}` },
|
|
125
|
+
redirect: 'error', signal: AbortSignal.timeout(5000),
|
|
126
|
+
})
|
|
127
|
+
if (!response.ok) throw new Error('UserInfo request failed')
|
|
128
|
+
const claims = await response.json()
|
|
129
|
+
if (!claims || typeof claims !== 'object' || typeof claims.sub !== 'string' || claims.sub !== authenticatedPrincipal.subject) {
|
|
130
|
+
throw new Error('UserInfo subject does not match the authenticated principal')
|
|
131
|
+
}
|
|
132
|
+
return claims
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
endSessionUrl({ idTokenHint, postLogoutRedirectUri, state } = {}) {
|
|
136
|
+
if (!this.discovery.end_session_endpoint) throw new Error('provider does not advertise an end-session endpoint')
|
|
137
|
+
if (idTokenHint !== undefined && (typeof idTokenHint !== 'string' || !idTokenHint)) throw new TypeError('invalid ID token hint')
|
|
138
|
+
if (postLogoutRedirectUri !== undefined) {
|
|
139
|
+
const redirect = secureUrl(postLogoutRedirectUri, { loopback: this.allowLocalHttp })
|
|
140
|
+
if (redirect.origin !== new URL(this.redirectUri).origin) throw new TypeError('post-logout redirect must use the configured client origin')
|
|
141
|
+
if (typeof state !== 'string' || state.length < 16) throw new TypeError('logout redirect requires strong state')
|
|
142
|
+
} else if (state !== undefined) {
|
|
143
|
+
throw new TypeError('logout state requires a post-logout redirect URI')
|
|
144
|
+
}
|
|
145
|
+
if (idTokenHint === undefined && postLogoutRedirectUri === undefined) throw new TypeError('logout requires an ID token hint or post-logout redirect URI')
|
|
146
|
+
const url = new URL(this.discovery.end_session_endpoint)
|
|
147
|
+
if (idTokenHint !== undefined) url.searchParams.set('id_token_hint', idTokenHint)
|
|
148
|
+
if (postLogoutRedirectUri !== undefined) {
|
|
149
|
+
url.searchParams.set('post_logout_redirect_uri', postLogoutRedirectUri)
|
|
150
|
+
url.searchParams.set('state', state)
|
|
151
|
+
}
|
|
152
|
+
return url.toString()
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async verifyAccessToken(token, audience = this.apiAudience) {
|
|
156
|
+
if (audience !== this.apiAudience) throw new Error('requested audience differs from configured audience')
|
|
157
|
+
return verifyAccessToken(token, { issuer: this.issuer, audience, clientId: this.clientId, jwks: this.jwks, allowLocalHttp: this.allowLocalHttp })
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async verifyIdToken(token, { expectedNonce, expectedNonceHash } = {}) {
|
|
161
|
+
if ((typeof expectedNonce === 'string') === (typeof expectedNonceHash === 'string')) throw new TypeError('provide exactly one nonce expectation')
|
|
162
|
+
const { payload, protectedHeader } = await jwtVerify(token, this.jwks, {
|
|
163
|
+
issuer: this.issuer, audience: this.clientId, algorithms: ['RS256'],
|
|
164
|
+
requiredClaims: ['iss', 'sub', 'aud', 'exp', 'nonce'], clockTolerance: 0,
|
|
165
|
+
})
|
|
166
|
+
const actualNonce = typeof payload.nonce === 'string' ? payload.nonce : ''
|
|
167
|
+
const comparedNonce = Buffer.from(typeof expectedNonceHash === 'string'
|
|
168
|
+
? createHash('sha256').update(actualNonce).digest('hex') : actualNonce)
|
|
169
|
+
const expected = Buffer.from(typeof expectedNonceHash === 'string' ? expectedNonceHash : expectedNonce)
|
|
170
|
+
const nonceMatches = comparedNonce.length === expected.length && timingSafeEqual(comparedNonce, expected)
|
|
171
|
+
if (protectedHeader.alg !== 'RS256' || typeof payload.sub !== 'string' || !payload.sub || !nonceMatches) throw new Error('ID token validation failed')
|
|
172
|
+
const audiences = Array.isArray(payload.aud) ? payload.aud : [payload.aud]
|
|
173
|
+
if ((audiences.length > 1 || payload.azp !== undefined) && payload.azp !== this.clientId) throw new Error('ID token authorized party mismatch')
|
|
174
|
+
return { issuer: this.issuer, subject: payload.sub, audience: audiences, claims: payload }
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export async function verifyAccessToken(token, { issuer, audience, clientId, jwks, allowLocalHttp = false }) {
|
|
179
|
+
if (!issuer || !audience || !clientId || !jwks) throw new TypeError('trusted issuer, audience, client ID, and JWKS resolver are required')
|
|
180
|
+
secureUrl(issuer, { loopback: allowLocalHttp })
|
|
181
|
+
const { payload, protectedHeader } = await jwtVerify(token, jwks, {
|
|
182
|
+
issuer, audience, algorithms: ['RS256'], requiredClaims: ['iss', 'sub', 'aud', 'exp'], clockTolerance: 0,
|
|
183
|
+
})
|
|
184
|
+
if (protectedHeader.alg !== 'RS256' || typeof payload.sub !== 'string' || !payload.sub || payload.azp !== clientId) throw new Error('invalid access token')
|
|
185
|
+
const audiences = Array.isArray(payload.aud) ? payload.aud : [payload.aud]
|
|
186
|
+
return { issuer, subject: payload.sub, audience: audiences, claims: payload }
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function bearerFromRequest(request) {
|
|
190
|
+
const value = request?.headers?.authorization
|
|
191
|
+
if (typeof value !== 'string') return undefined
|
|
192
|
+
const match = /^Bearer ([A-Za-z0-9._~+\-/]+=*)$/i.exec(value)
|
|
193
|
+
return match?.[1]
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function attachPrincipal(request, principal) {
|
|
197
|
+
Object.defineProperty(request, 'auth', {
|
|
198
|
+
configurable: false,
|
|
199
|
+
enumerable: false,
|
|
200
|
+
writable: false,
|
|
201
|
+
value: principal,
|
|
202
|
+
})
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Express middleware: validates a Buwigs Auth access token and attaches `req.auth`.
|
|
206
|
+
* It authenticates only; the consuming application still authorizes its own roles and tenants.
|
|
207
|
+
*/
|
|
208
|
+
export function expressAuth(oidc) {
|
|
209
|
+
if (!oidc || typeof oidc.verifyAccessToken !== 'function') throw new TypeError('a configured OidcClient is required')
|
|
210
|
+
return async function buwigsAuthMiddleware(request, response, next) {
|
|
211
|
+
const token = bearerFromRequest(request)
|
|
212
|
+
if (!token) {
|
|
213
|
+
response.setHeader('WWW-Authenticate', 'Bearer')
|
|
214
|
+
return response.status(401).json({ error: 'unauthorized' })
|
|
215
|
+
}
|
|
216
|
+
let principal
|
|
217
|
+
try {
|
|
218
|
+
principal = await oidc.verifyAccessToken(token)
|
|
219
|
+
} catch {
|
|
220
|
+
response.setHeader('WWW-Authenticate', 'Bearer error="invalid_token"')
|
|
221
|
+
return response.status(401).json({ error: 'unauthorized' })
|
|
222
|
+
}
|
|
223
|
+
attachPrincipal(request, principal)
|
|
224
|
+
return next()
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Fastify onRequest hook: validates a Buwigs Auth access token and attaches `request.auth`.
|
|
229
|
+
* Register only on protected routes; business authorization remains application-owned.
|
|
230
|
+
*/
|
|
231
|
+
export function fastifyAuth(oidc) {
|
|
232
|
+
if (!oidc || typeof oidc.verifyAccessToken !== 'function') throw new TypeError('a configured OidcClient is required')
|
|
233
|
+
return async function buwigsAuthHook(request, reply) {
|
|
234
|
+
const token = bearerFromRequest(request)
|
|
235
|
+
if (!token) {
|
|
236
|
+
reply.header('WWW-Authenticate', 'Bearer')
|
|
237
|
+
return reply.code(401).send({ error: 'unauthorized' })
|
|
238
|
+
}
|
|
239
|
+
try {
|
|
240
|
+
const principal = await oidc.verifyAccessToken(token)
|
|
241
|
+
attachPrincipal(request, principal)
|
|
242
|
+
} catch {
|
|
243
|
+
reply.header('WWW-Authenticate', 'Bearer error="invalid_token"')
|
|
244
|
+
return reply.code(401).send({ error: 'unauthorized' })
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|