@npmatomicauthy/node 0.0.0-stage → 1.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/README.md +273 -2
- package/dist/index.d.ts +380 -0
- package/dist/index.js +629 -0
- package/package.json +33 -4
package/README.md
CHANGED
|
@@ -1,3 +1,274 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Authly Node.js SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The official Authly SDK for Node.js server applications. It provides OAuth 2.0 / OpenID Connect login helpers, PKCE generation, RS256 JWT verification using Authly JWKS, user management API access, and webhook signature verification. It has no runtime dependencies and uses Node.js built-in APIs.
|
|
4
|
+
|
|
5
|
+
> **License notice:** This package is marked `UNLICENSED`. No open-source license is granted. Use and redistribution require authorization from the package owner.
|
|
6
|
+
|
|
7
|
+
## Requirements
|
|
8
|
+
|
|
9
|
+
- Node.js 22 or newer.
|
|
10
|
+
- An Authly issuer URL and a registered OAuth client for login and token verification.
|
|
11
|
+
- A server-side confidential client secret only when the OAuth client is registered as confidential.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
npm install @authly/node
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Configure the OAuth client
|
|
20
|
+
|
|
21
|
+
Keep OAuth client secrets, session secrets, management API keys, and tokens on the server. For example, load these values from a secrets manager or a server-only `.env` file:
|
|
22
|
+
|
|
23
|
+
```dotenv
|
|
24
|
+
AUTHLY_ISSUER=https://auth.example.com
|
|
25
|
+
AUTHLY_CLIENT_ID=your-client-id
|
|
26
|
+
AUTHLY_CLIENT_SECRET=your-confidential-client-secret
|
|
27
|
+
AUTHLY_CALLBACK_URL=https://app.example.com/auth/callback
|
|
28
|
+
AUTHLY_LOGOUT_REDIRECT_URL=https://app.example.com/
|
|
29
|
+
AUTHLY_AUDIENCE=https://api.example.com
|
|
30
|
+
AUTHLY_SCOPES=openid profile email offline_access
|
|
31
|
+
SESSION_SECRET=use-a-long-random-secret
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Initialize the OAuth client in server-only code:
|
|
35
|
+
|
|
36
|
+
```js
|
|
37
|
+
import { AuthlyOAuthClient, AuthlyTokenVerifier } from '@authly/node';
|
|
38
|
+
|
|
39
|
+
const issuer = process.env.AUTHLY_ISSUER;
|
|
40
|
+
const clientId = process.env.AUTHLY_CLIENT_ID;
|
|
41
|
+
const callbackUrl = process.env.AUTHLY_CALLBACK_URL;
|
|
42
|
+
|
|
43
|
+
if (!issuer || !clientId || !callbackUrl) {
|
|
44
|
+
throw new Error('AUTHLY_ISSUER, AUTHLY_CLIENT_ID, and AUTHLY_CALLBACK_URL are required');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export const authlyOAuth = new AuthlyOAuthClient({
|
|
48
|
+
issuer,
|
|
49
|
+
clientId,
|
|
50
|
+
clientSecret: process.env.AUTHLY_CLIENT_SECRET,
|
|
51
|
+
redirectUri: callbackUrl,
|
|
52
|
+
postLogoutRedirectUri: process.env.AUTHLY_LOGOUT_REDIRECT_URL,
|
|
53
|
+
scopes: (process.env.AUTHLY_SCOPES ?? 'openid profile email offline_access').split(/\s+/),
|
|
54
|
+
audience: process.env.AUTHLY_AUDIENCE,
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
export const authlyTokenVerifier = new AuthlyTokenVerifier({
|
|
58
|
+
issuer,
|
|
59
|
+
audience: process.env.AUTHLY_AUDIENCE || clientId,
|
|
60
|
+
});
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
For a public client, omit `clientSecret`. Never put a confidential client secret or a management API key in browser code or a `NEXT_PUBLIC_*` variable.
|
|
64
|
+
|
|
65
|
+
## OAuth 2.0 / OpenID Connect login
|
|
66
|
+
|
|
67
|
+
The SDK provides the protocol operations; your application must maintain an authenticated server-side session. The following Express example uses `express-session` to keep the PKCE verifier, state, and nonce server-side. Configure a production-grade session store (the default in-memory store is not suitable for production).
|
|
68
|
+
|
|
69
|
+
Install `express` and `express-session` separately if you use this example; they are application dependencies, not SDK dependencies.
|
|
70
|
+
|
|
71
|
+
```js
|
|
72
|
+
import express from 'express';
|
|
73
|
+
import session from 'express-session';
|
|
74
|
+
import { AuthlyOAuthClient } from '@authly/node';
|
|
75
|
+
import { authlyOAuth, authlyTokenVerifier } from './authly.js';
|
|
76
|
+
|
|
77
|
+
const app = express();
|
|
78
|
+
|
|
79
|
+
app.use(session({
|
|
80
|
+
secret: process.env.SESSION_SECRET,
|
|
81
|
+
resave: false,
|
|
82
|
+
saveUninitialized: false,
|
|
83
|
+
cookie: {
|
|
84
|
+
httpOnly: true,
|
|
85
|
+
sameSite: 'lax',
|
|
86
|
+
secure: process.env.NODE_ENV === 'production',
|
|
87
|
+
},
|
|
88
|
+
}));
|
|
89
|
+
|
|
90
|
+
app.get('/auth/login', (req, res) => {
|
|
91
|
+
const pkce = AuthlyOAuthClient.generatePkce();
|
|
92
|
+
req.session.authlyTransaction = {
|
|
93
|
+
verifier: pkce.verifier,
|
|
94
|
+
state: pkce.state,
|
|
95
|
+
nonce: pkce.nonce,
|
|
96
|
+
};
|
|
97
|
+
res.redirect(authlyOAuth.buildAuthorizeUrl({
|
|
98
|
+
codeChallenge: pkce.challenge,
|
|
99
|
+
state: pkce.state,
|
|
100
|
+
nonce: pkce.nonce,
|
|
101
|
+
}));
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
app.get('/auth/callback', async (req, res, next) => {
|
|
105
|
+
const code = typeof req.query.code === 'string' ? req.query.code : '';
|
|
106
|
+
const state = typeof req.query.state === 'string' ? req.query.state : '';
|
|
107
|
+
const transaction = req.session.authlyTransaction;
|
|
108
|
+
|
|
109
|
+
if (!code || !transaction || state !== transaction.state) {
|
|
110
|
+
return res.status(400).send('Invalid OAuth state or callback');
|
|
111
|
+
}
|
|
112
|
+
delete req.session.authlyTransaction;
|
|
113
|
+
|
|
114
|
+
try {
|
|
115
|
+
const tokens = await authlyOAuth.exchangeCode({
|
|
116
|
+
code,
|
|
117
|
+
codeVerifier: transaction.verifier,
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
if (!tokens.id_token) {
|
|
121
|
+
return res.status(400).send('Authly did not return an ID token');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const claims = await authlyTokenVerifier.verifyToken(tokens.id_token, {
|
|
125
|
+
audience: process.env.AUTHLY_CLIENT_ID,
|
|
126
|
+
});
|
|
127
|
+
if (claims.nonce !== transaction.nonce) {
|
|
128
|
+
return res.status(400).send('Invalid ID token nonce');
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const user = await authlyOAuth.getUserInfo(tokens.access_token);
|
|
132
|
+
req.session.authlyUser = { sub: user.sub, email: user.email };
|
|
133
|
+
req.session.authlyTokens = {
|
|
134
|
+
accessToken: tokens.access_token,
|
|
135
|
+
refreshToken: tokens.refresh_token,
|
|
136
|
+
idToken: tokens.id_token,
|
|
137
|
+
};
|
|
138
|
+
res.redirect('/account');
|
|
139
|
+
} catch (error) {
|
|
140
|
+
next(error);
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
The callback must compare the returned `state`, use the same PKCE verifier generated before redirecting, verify the ID token and its nonce, and create your application's own session. The session property declarations above are application-specific; add matching `express-session` TypeScript declaration merging if using TypeScript.
|
|
146
|
+
|
|
147
|
+
## Protecting API routes
|
|
148
|
+
|
|
149
|
+
`AuthlyTokenVerifier` retrieves and caches JWKS from `<issuer>/oauth/jwks` by default, pins verification to RS256, and validates the signature, issuer, audience, expiry, and not-before time. You can override the JWKS endpoint with `jwksUri`, or supply `staticJwks` for offline use.
|
|
150
|
+
|
|
151
|
+
```js
|
|
152
|
+
app.get('/api/profile', authlyTokenVerifier.middleware(), (req, res) => {
|
|
153
|
+
res.json({ sub: req.authlyUser.sub, email: req.authlyUser.email });
|
|
154
|
+
});
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
The middleware returns a 401 JSON response for missing or invalid bearer tokens. For direct verification outside Express/Connect middleware:
|
|
158
|
+
|
|
159
|
+
```js
|
|
160
|
+
const claims = await authlyTokenVerifier.verifyToken(accessToken);
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Only use claims after successful verification. Never trust a user ID supplied by the request body or an unverified token.
|
|
164
|
+
|
|
165
|
+
## User information, refresh, revocation, and logout
|
|
166
|
+
|
|
167
|
+
```js
|
|
168
|
+
const user = await authlyOAuth.getUserInfo(accessToken);
|
|
169
|
+
|
|
170
|
+
if (refreshToken) {
|
|
171
|
+
const refreshed = await authlyOAuth.refreshToken(refreshToken);
|
|
172
|
+
// Persist the replacement tokens securely; refresh tokens may rotate.
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
await authlyOAuth.revokeToken(accessToken);
|
|
176
|
+
const logoutUrl = authlyOAuth.buildLogoutUrl({ idTokenHint });
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
Redirect the browser to the returned logout URL to end the Authly session. Clear your application's session as part of logout. The OAuth client also accepts a `postLogoutRedirectUri` at initialization or as an option to `buildLogoutUrl`.
|
|
180
|
+
|
|
181
|
+
## Management API
|
|
182
|
+
|
|
183
|
+
`AuthlyManagementClient` uses a project-scoped `authly_sk_...` key and must only be instantiated on a trusted server:
|
|
184
|
+
|
|
185
|
+
```js
|
|
186
|
+
import { AuthlyManagementClient } from '@authly/node';
|
|
187
|
+
|
|
188
|
+
const management = new AuthlyManagementClient({
|
|
189
|
+
baseUrl: process.env.AUTHLY_ISSUER,
|
|
190
|
+
managementApiKey: process.env.AUTHLY_MANAGEMENT_API_KEY,
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
const users = await management.listUsers({ limit: 25, page: 1 });
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
Available operations include listing, retrieving, updating, suspending, reactivating, and deleting users, revoking user sessions, resending verification, and triggering password resets.
|
|
197
|
+
|
|
198
|
+
## Webhook signatures
|
|
199
|
+
|
|
200
|
+
Verify the raw request payload with its Authly timestamp and signature headers before processing a webhook:
|
|
201
|
+
|
|
202
|
+
```js
|
|
203
|
+
import { verifyAuthlyWebhookSignature } from '@authly/node';
|
|
204
|
+
|
|
205
|
+
const timestamp = request.headers['x-authly-timestamp'];
|
|
206
|
+
const signature = request.headers['x-authly-signature'];
|
|
207
|
+
if (typeof timestamp !== 'string' || typeof signature !== 'string') {
|
|
208
|
+
throw new Error('Missing Authly webhook signature headers');
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const valid = verifyAuthlyWebhookSignature({
|
|
212
|
+
payload: rawRequestBody,
|
|
213
|
+
timestamp,
|
|
214
|
+
signature,
|
|
215
|
+
secret: process.env.AUTHLY_WEBHOOK_SECRET,
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
if (!valid) {
|
|
219
|
+
throw new Error('Invalid or expired Authly webhook signature');
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
Pass the exact payload bytes/string used to calculate the signature. The verifier rejects timestamps outside its default five-minute tolerance; set `toleranceSeconds` only when your delivery requirements justify it.
|
|
224
|
+
|
|
225
|
+
## Errors
|
|
226
|
+
|
|
227
|
+
OAuth HTTP failures from `exchangeCode`, `refreshToken`, `getUserInfo`, and `revokeToken` throw `AuthlyManagementError`, which includes `status` and `code`. Token parsing, signature, issuer, audience, and JWKS failures throw `AuthlyTokenError`, which includes a typed `code`. Catch these errors at your application boundary, log safe diagnostic details, and never log secrets or tokens.
|
|
228
|
+
|
|
229
|
+
```js
|
|
230
|
+
import { AuthlyManagementError, AuthlyTokenError } from '@authly/node';
|
|
231
|
+
|
|
232
|
+
try {
|
|
233
|
+
const claims = await authlyTokenVerifier.verifyToken(token);
|
|
234
|
+
} catch (error) {
|
|
235
|
+
if (error instanceof AuthlyTokenError) {
|
|
236
|
+
// Reject the request; use error.code for safe diagnostics.
|
|
237
|
+
} else if (error instanceof AuthlyManagementError) {
|
|
238
|
+
// Handle an Authly HTTP error using status and code.
|
|
239
|
+
} else {
|
|
240
|
+
throw error;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
## Security recommendations
|
|
246
|
+
|
|
247
|
+
- Keep client secrets, management keys, webhook secrets, session secrets, and tokens in server-side secret storage.
|
|
248
|
+
- Use HTTPS for the issuer and application in production.
|
|
249
|
+
- Use secure, HttpOnly, SameSite cookies and a production session store; rotate/regenerate the app session after login.
|
|
250
|
+
- Bind each login transaction to its own session state, PKCE verifier, and nonce; enforce single use and short lifetimes.
|
|
251
|
+
- Validate the audience appropriate to the token you verify. Do not treat an ID token as an API access token.
|
|
252
|
+
- Do not log, expose, or persist bearer/refresh tokens in browser-accessible storage.
|
|
253
|
+
|
|
254
|
+
Authly's SDK source and integration guidance are maintained in the Authly monorepo under `packages/node-sdk` and `docs/INTEGRATION_GUIDE.md`.
|
|
255
|
+
|
|
256
|
+
## Universal Post-Login Redirects, Signed Sessions & App-Scoped RBAC (Local Workspace Updates)
|
|
257
|
+
|
|
258
|
+
> **Version note:** Published npm `@npmatomicauthy/node@1.0.0` exports `AuthlyOAuthClient`, `AuthlyTokenVerifier`, `AuthlyManagementClient`, and webhook verification. Additional helpers added in this workspace (`startAuthTransaction`, `completeCallback`, `sanitizeReturnTo`, `createSignedSessionCookie`, `readSignedSessionCookie`, `requireAuthSession`, `requireRole`, `requirePermission`, and `AuthlyManagementClient` role methods) remain local until the next npm release is approved.
|
|
259
|
+
|
|
260
|
+
```js
|
|
261
|
+
const { url, transaction } = authlyOAuth.startAuthTransaction({
|
|
262
|
+
returnTo: req.query.returnTo,
|
|
263
|
+
allowedReturnUrls: ['https://app.example.com'],
|
|
264
|
+
defaultReturnTo: '/dashboard',
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
// Inside callback handler:
|
|
268
|
+
const result = await authlyOAuth.completeCallback({
|
|
269
|
+
code: req.query.code,
|
|
270
|
+
state: req.query.state,
|
|
271
|
+
transaction,
|
|
272
|
+
});
|
|
273
|
+
// result.identityKey === "<issuer>|<sub>", result.roles, result.permissions, result.returnTo
|
|
274
|
+
```
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import { type JsonWebKey } from 'node:crypto';
|
|
2
|
+
export interface AuthlyNodeConfig {
|
|
3
|
+
/** Authly server base URL (e.g. https://auth.example.com) */
|
|
4
|
+
baseUrl: string;
|
|
5
|
+
/** Project-scoped Management API key (authly_sk_...). Server-side ONLY. */
|
|
6
|
+
managementApiKey: string;
|
|
7
|
+
/** Optional request timeout in ms (default 10000) */
|
|
8
|
+
timeoutMs?: number;
|
|
9
|
+
}
|
|
10
|
+
export interface ManagedUser {
|
|
11
|
+
id: string;
|
|
12
|
+
projectId: string;
|
|
13
|
+
email: string;
|
|
14
|
+
username: string | null;
|
|
15
|
+
displayName: string;
|
|
16
|
+
phone: string | null;
|
|
17
|
+
status: string;
|
|
18
|
+
emailVerified: boolean;
|
|
19
|
+
lastLoginAt: string | null;
|
|
20
|
+
createdAt: string;
|
|
21
|
+
}
|
|
22
|
+
export interface PaginatedUsers {
|
|
23
|
+
items: ManagedUser[];
|
|
24
|
+
total: number;
|
|
25
|
+
limit: number;
|
|
26
|
+
page: number;
|
|
27
|
+
hasMore: boolean;
|
|
28
|
+
nextCursor: string | null;
|
|
29
|
+
}
|
|
30
|
+
export interface VerifiedAuthlyClaims {
|
|
31
|
+
sub: string;
|
|
32
|
+
iss: string;
|
|
33
|
+
aud: string | string[];
|
|
34
|
+
exp: number;
|
|
35
|
+
iat: number;
|
|
36
|
+
nbf?: number;
|
|
37
|
+
nonce?: string;
|
|
38
|
+
email?: string;
|
|
39
|
+
email_verified?: boolean;
|
|
40
|
+
name?: string;
|
|
41
|
+
roles?: string[];
|
|
42
|
+
permissions?: string[];
|
|
43
|
+
scope?: string;
|
|
44
|
+
client_id?: string;
|
|
45
|
+
project_id?: string;
|
|
46
|
+
[key: string]: unknown;
|
|
47
|
+
}
|
|
48
|
+
export interface AuthlyUserIdentity {
|
|
49
|
+
sub: string;
|
|
50
|
+
email?: string;
|
|
51
|
+
email_verified?: boolean;
|
|
52
|
+
name?: string;
|
|
53
|
+
roles?: string[];
|
|
54
|
+
permissions?: string[];
|
|
55
|
+
project_id?: string;
|
|
56
|
+
}
|
|
57
|
+
export interface AuthlySessionData {
|
|
58
|
+
identityKey: string;
|
|
59
|
+
sub: string;
|
|
60
|
+
iss: string;
|
|
61
|
+
email?: string;
|
|
62
|
+
name?: string;
|
|
63
|
+
roles: string[];
|
|
64
|
+
permissions: string[];
|
|
65
|
+
exp: number;
|
|
66
|
+
}
|
|
67
|
+
export interface AuthlyOAuthTransaction {
|
|
68
|
+
state: string;
|
|
69
|
+
verifier: string;
|
|
70
|
+
challenge: string;
|
|
71
|
+
nonce: string;
|
|
72
|
+
returnTo: string;
|
|
73
|
+
createdAt: number;
|
|
74
|
+
}
|
|
75
|
+
export interface CompletedAuthlyCallback {
|
|
76
|
+
tokens: AuthlyOAuthTokenResponse;
|
|
77
|
+
claims: VerifiedAuthlyClaims | null;
|
|
78
|
+
userInfo: AuthlyUserIdentity;
|
|
79
|
+
identityKey: string;
|
|
80
|
+
roles: string[];
|
|
81
|
+
permissions: string[];
|
|
82
|
+
returnTo: string;
|
|
83
|
+
}
|
|
84
|
+
export interface ApplicationRoleRecord {
|
|
85
|
+
id: string;
|
|
86
|
+
name: string;
|
|
87
|
+
description?: string | null;
|
|
88
|
+
permissions: string[];
|
|
89
|
+
isDefault: boolean;
|
|
90
|
+
clientId?: string | null;
|
|
91
|
+
}
|
|
92
|
+
export interface AuthlyOAuthTokenResponse {
|
|
93
|
+
access_token: string;
|
|
94
|
+
token_type: string;
|
|
95
|
+
expires_in: number;
|
|
96
|
+
id_token?: string;
|
|
97
|
+
refresh_token?: string;
|
|
98
|
+
scope?: string;
|
|
99
|
+
}
|
|
100
|
+
export declare class AuthlyManagementError extends Error {
|
|
101
|
+
readonly status: number;
|
|
102
|
+
readonly code: string;
|
|
103
|
+
constructor(status: number, code: string, message: string);
|
|
104
|
+
}
|
|
105
|
+
export declare class AuthlyTokenError extends Error {
|
|
106
|
+
readonly code: 'missing_token' | 'malformed_token' | 'unsupported_alg' | 'unknown_kid' | 'invalid_signature' | 'token_expired' | 'token_not_active' | 'invalid_issuer' | 'invalid_audience' | 'invalid_nonce' | 'jwks_fetch_failed';
|
|
107
|
+
constructor(code: 'missing_token' | 'malformed_token' | 'unsupported_alg' | 'unknown_kid' | 'invalid_signature' | 'token_expired' | 'token_not_active' | 'invalid_issuer' | 'invalid_audience' | 'invalid_nonce' | 'jwks_fetch_failed', message: string);
|
|
108
|
+
}
|
|
109
|
+
export interface AuthlyTokenVerifierConfig {
|
|
110
|
+
/** Expected OIDC issuer (e.g. https://auth.example.com) */
|
|
111
|
+
issuer: string;
|
|
112
|
+
/** Expected audience (API resource identifier or client_id for ID tokens) */
|
|
113
|
+
audience: string;
|
|
114
|
+
/** Optional explicit JWKS URL (defaults to <issuer>/oauth/jwks) */
|
|
115
|
+
jwksUri?: string;
|
|
116
|
+
/** Optional static JWKS for tests or offline verification */
|
|
117
|
+
staticJwks?: {
|
|
118
|
+
keys: Array<JsonWebKey & {
|
|
119
|
+
kid?: string;
|
|
120
|
+
alg?: string;
|
|
121
|
+
use?: string;
|
|
122
|
+
}>;
|
|
123
|
+
};
|
|
124
|
+
/** Clock skew tolerance in seconds (default 30) */
|
|
125
|
+
clockToleranceSeconds?: number;
|
|
126
|
+
/** JWKS cache TTL in ms (default 300000 = 5 minutes) */
|
|
127
|
+
jwksCacheTtlMs?: number;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Zero-dependency RS256 JWKS JWT verifier for Node.js resource servers and backends.
|
|
131
|
+
* Verifies cryptographic signature, issuer, audience, expiration, and not-before claims.
|
|
132
|
+
* Never trusts an unverified user ID from request bodies or headers.
|
|
133
|
+
*/
|
|
134
|
+
export declare class AuthlyTokenVerifier {
|
|
135
|
+
private readonly config;
|
|
136
|
+
private readonly issuer;
|
|
137
|
+
private readonly audience;
|
|
138
|
+
private readonly jwksUri;
|
|
139
|
+
private readonly clockTolerance;
|
|
140
|
+
private readonly cacheTtlMs;
|
|
141
|
+
private keyCache;
|
|
142
|
+
private allKeys;
|
|
143
|
+
private cacheExpiresAt;
|
|
144
|
+
constructor(config: AuthlyTokenVerifierConfig);
|
|
145
|
+
private loadKeys;
|
|
146
|
+
private ensureKeys;
|
|
147
|
+
verifyToken(token: string, opts?: {
|
|
148
|
+
nowSeconds?: number;
|
|
149
|
+
audience?: string;
|
|
150
|
+
nonce?: string;
|
|
151
|
+
}): Promise<VerifiedAuthlyClaims>;
|
|
152
|
+
/**
|
|
153
|
+
* Express / Connect middleware that verifies `Authorization: Bearer <token>` against Authly JWKS
|
|
154
|
+
* and attaches verified claims to `req.authlyUser` (never trusting client-submitted user IDs).
|
|
155
|
+
*/
|
|
156
|
+
middleware(): (req: {
|
|
157
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
158
|
+
authlyUser?: VerifiedAuthlyClaims;
|
|
159
|
+
}, res: {
|
|
160
|
+
status: (code: number) => {
|
|
161
|
+
json: (body: unknown) => void;
|
|
162
|
+
};
|
|
163
|
+
}, next: (err?: unknown) => void) => Promise<void>;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Validates a post-login return destination against an allowlist and rejects open redirects
|
|
167
|
+
* (`//evil.com`, `/\evil.com`, `javascript:`, or untrusted external origins).
|
|
168
|
+
*/
|
|
169
|
+
export declare function sanitizeReturnTo(rawDestination: string | null | undefined, opts?: {
|
|
170
|
+
allowedUrls?: string[];
|
|
171
|
+
defaultReturnTo?: string;
|
|
172
|
+
isProduction?: boolean;
|
|
173
|
+
}): string;
|
|
174
|
+
export interface AuthlyOAuthClientConfig {
|
|
175
|
+
issuer: string;
|
|
176
|
+
clientId: string;
|
|
177
|
+
/** Server-side confidential secret (never expose to browsers or mobile apps). */
|
|
178
|
+
clientSecret?: string;
|
|
179
|
+
redirectUri: string;
|
|
180
|
+
postLogoutRedirectUri?: string;
|
|
181
|
+
/** Default destination when no safe `returnTo` URL is present (default `/`). */
|
|
182
|
+
defaultReturnTo?: string;
|
|
183
|
+
/** Explicit allowlist of external origins/URLs permitted for post-login redirects. */
|
|
184
|
+
allowedReturnUrls?: string[];
|
|
185
|
+
scopes?: string[];
|
|
186
|
+
audience?: string;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Server-side OAuth 2.0 / OIDC client for confidential Node.js and Next.js applications.
|
|
190
|
+
* Supports Authorization Code + PKCE S256, safe return destination binding, token exchange,
|
|
191
|
+
* verified ID token / nonce validation, refresh rotation, UserInfo, revocation, and logout.
|
|
192
|
+
*/
|
|
193
|
+
export declare class AuthlyOAuthClient {
|
|
194
|
+
private readonly config;
|
|
195
|
+
private readonly issuer;
|
|
196
|
+
private defaultVerifier;
|
|
197
|
+
constructor(config: AuthlyOAuthClientConfig);
|
|
198
|
+
private getVerifier;
|
|
199
|
+
static generatePkce(): {
|
|
200
|
+
verifier: string;
|
|
201
|
+
challenge: string;
|
|
202
|
+
state: string;
|
|
203
|
+
nonce: string;
|
|
204
|
+
};
|
|
205
|
+
/**
|
|
206
|
+
* Starts a complete PKCE + state + nonce login transaction paired with a sanitized return destination.
|
|
207
|
+
* Store the returned `transaction` in an HttpOnly signed cookie or server session before redirecting to `url`.
|
|
208
|
+
*/
|
|
209
|
+
startAuthTransaction(opts?: {
|
|
210
|
+
returnTo?: string | null;
|
|
211
|
+
allowedReturnUrls?: string[];
|
|
212
|
+
defaultReturnTo?: string;
|
|
213
|
+
isProduction?: boolean;
|
|
214
|
+
extra?: Record<string, string>;
|
|
215
|
+
}): {
|
|
216
|
+
url: string;
|
|
217
|
+
transaction: AuthlyOAuthTransaction;
|
|
218
|
+
};
|
|
219
|
+
buildAuthorizeUrl(params: {
|
|
220
|
+
codeChallenge: string;
|
|
221
|
+
state: string;
|
|
222
|
+
nonce?: string;
|
|
223
|
+
extra?: Record<string, string>;
|
|
224
|
+
}): string;
|
|
225
|
+
private authHeaders;
|
|
226
|
+
exchangeCode(input: {
|
|
227
|
+
code: string;
|
|
228
|
+
codeVerifier: string;
|
|
229
|
+
}): Promise<AuthlyOAuthTokenResponse>;
|
|
230
|
+
refreshToken(refreshToken: string): Promise<AuthlyOAuthTokenResponse>;
|
|
231
|
+
getUserInfo(accessToken: string): Promise<AuthlyUserIdentity>;
|
|
232
|
+
revokeToken(token: string): Promise<void>;
|
|
233
|
+
buildLogoutUrl(opts?: {
|
|
234
|
+
idTokenHint?: string;
|
|
235
|
+
postLogoutRedirectUri?: string;
|
|
236
|
+
}): string;
|
|
237
|
+
/**
|
|
238
|
+
* Completes the OAuth 2.0 / OIDC callback securely:
|
|
239
|
+
* validates state, exchanges code with PKCE verifier, verifies ID token signature + iss/aud/exp/nonce,
|
|
240
|
+
* fetches authoritative UserInfo claims, binds canonical `(iss, sub)` identity, and sanitizes `returnTo`.
|
|
241
|
+
*/
|
|
242
|
+
completeCallback(input: {
|
|
243
|
+
code?: string | null;
|
|
244
|
+
state?: string | null;
|
|
245
|
+
error?: string | null;
|
|
246
|
+
errorDescription?: string | null;
|
|
247
|
+
transaction?: AuthlyOAuthTransaction | null;
|
|
248
|
+
allowedReturnUrls?: string[];
|
|
249
|
+
defaultReturnTo?: string;
|
|
250
|
+
isProduction?: boolean;
|
|
251
|
+
verifier?: AuthlyTokenVerifier;
|
|
252
|
+
}): Promise<CompletedAuthlyCallback>;
|
|
253
|
+
}
|
|
254
|
+
export declare class AuthlyManagementClient {
|
|
255
|
+
private readonly baseUrl;
|
|
256
|
+
private readonly apiKey;
|
|
257
|
+
private readonly timeoutMs;
|
|
258
|
+
constructor(config: AuthlyNodeConfig);
|
|
259
|
+
private req;
|
|
260
|
+
listUsers(params?: {
|
|
261
|
+
search?: string;
|
|
262
|
+
status?: string;
|
|
263
|
+
verified?: 'true' | 'false';
|
|
264
|
+
limit?: number;
|
|
265
|
+
page?: number;
|
|
266
|
+
cursor?: string;
|
|
267
|
+
}): Promise<PaginatedUsers>;
|
|
268
|
+
getUser(id: string): Promise<{
|
|
269
|
+
user: ManagedUser;
|
|
270
|
+
sessions: unknown[];
|
|
271
|
+
authEvents: unknown[];
|
|
272
|
+
adminHistory: unknown[];
|
|
273
|
+
}>;
|
|
274
|
+
updateUser(id: string, patch: {
|
|
275
|
+
displayName?: string;
|
|
276
|
+
phone?: string | null;
|
|
277
|
+
profileData?: Record<string, unknown>;
|
|
278
|
+
}): Promise<{
|
|
279
|
+
user: ManagedUser;
|
|
280
|
+
}>;
|
|
281
|
+
suspendUser(id: string): Promise<{
|
|
282
|
+
user: ManagedUser;
|
|
283
|
+
}>;
|
|
284
|
+
reactivateUser(id: string): Promise<{
|
|
285
|
+
user: ManagedUser;
|
|
286
|
+
}>;
|
|
287
|
+
revokeUserSessions(id: string): Promise<{
|
|
288
|
+
ok: true;
|
|
289
|
+
revokedCount: number;
|
|
290
|
+
}>;
|
|
291
|
+
resendVerification(id: string): Promise<{
|
|
292
|
+
ok: true;
|
|
293
|
+
}>;
|
|
294
|
+
triggerPasswordReset(id: string): Promise<{
|
|
295
|
+
ok: true;
|
|
296
|
+
}>;
|
|
297
|
+
deleteUser(id: string, hard?: boolean): Promise<{
|
|
298
|
+
ok: true;
|
|
299
|
+
}>;
|
|
300
|
+
listRoles(): Promise<{
|
|
301
|
+
roles: ApplicationRoleRecord[];
|
|
302
|
+
}>;
|
|
303
|
+
createRole(input: {
|
|
304
|
+
name: string;
|
|
305
|
+
description?: string;
|
|
306
|
+
permissions?: string[];
|
|
307
|
+
isDefault?: boolean;
|
|
308
|
+
clientId?: string;
|
|
309
|
+
}): Promise<{
|
|
310
|
+
role: ApplicationRoleRecord;
|
|
311
|
+
}>;
|
|
312
|
+
getUserRoles(userId: string, clientId?: string): Promise<{
|
|
313
|
+
roles: string[];
|
|
314
|
+
permissions: string[];
|
|
315
|
+
assignments: unknown[];
|
|
316
|
+
}>;
|
|
317
|
+
setUserRoles(userId: string, input: {
|
|
318
|
+
roleIds?: string[];
|
|
319
|
+
roleNames?: string[];
|
|
320
|
+
}): Promise<{
|
|
321
|
+
roles: string[];
|
|
322
|
+
permissions: string[];
|
|
323
|
+
}>;
|
|
324
|
+
}
|
|
325
|
+
export declare function parseCookieHeader(cookieHeader: string | undefined): Record<string, string>;
|
|
326
|
+
export declare function signAuthlyCookiePayload(secret: string, payload: unknown): string;
|
|
327
|
+
export declare function verifyAuthlyCookiePayload<T>(secret: string, rawToken: string | undefined): T | null;
|
|
328
|
+
export declare function createSignedSessionCookie(secret: string, session: Omit<AuthlySessionData, 'exp'> & {
|
|
329
|
+
exp?: number;
|
|
330
|
+
}, opts?: {
|
|
331
|
+
cookieName?: string;
|
|
332
|
+
maxAgeSeconds?: number;
|
|
333
|
+
secure?: boolean;
|
|
334
|
+
sameSite?: 'Lax' | 'Strict' | 'None';
|
|
335
|
+
}): string;
|
|
336
|
+
export declare function createSignedTransactionCookie(secret: string, transaction: AuthlyOAuthTransaction, opts?: {
|
|
337
|
+
cookieName?: string;
|
|
338
|
+
maxAgeSeconds?: number;
|
|
339
|
+
secure?: boolean;
|
|
340
|
+
}): string;
|
|
341
|
+
export declare function clearAuthlyCookieHeader(name: string, opts?: {
|
|
342
|
+
path?: string;
|
|
343
|
+
secure?: boolean;
|
|
344
|
+
}): string;
|
|
345
|
+
export declare function readSignedSessionCookie(cookieHeader: string | undefined, secret: string, cookieName?: string): AuthlySessionData | null;
|
|
346
|
+
export declare function readSignedTransactionCookie(cookieHeader: string | undefined, secret: string, cookieName?: string): AuthlyOAuthTransaction | null;
|
|
347
|
+
export declare function getUserRoles(subject: {
|
|
348
|
+
roles?: string[];
|
|
349
|
+
} | null | undefined): string[];
|
|
350
|
+
export declare function hasRole(subject: {
|
|
351
|
+
roles?: string[];
|
|
352
|
+
} | null | undefined, required: string | string[]): boolean;
|
|
353
|
+
export declare function hasPermission(subject: {
|
|
354
|
+
permissions?: string[];
|
|
355
|
+
} | null | undefined, required: string | string[]): boolean;
|
|
356
|
+
type ExpressLikeReq = {
|
|
357
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
358
|
+
authlyUser?: VerifiedAuthlyClaims;
|
|
359
|
+
authlySession?: AuthlySessionData;
|
|
360
|
+
};
|
|
361
|
+
type ExpressLikeRes = {
|
|
362
|
+
status: (code: number) => {
|
|
363
|
+
json: (body: unknown) => void;
|
|
364
|
+
};
|
|
365
|
+
};
|
|
366
|
+
export declare function requireAuthSession(opts: {
|
|
367
|
+
secret: string;
|
|
368
|
+
cookieName?: string;
|
|
369
|
+
}): (req: ExpressLikeReq, res: ExpressLikeRes, next: (err?: unknown) => void) => void;
|
|
370
|
+
export declare function requireRole(requiredRoles: string | string[]): (req: ExpressLikeReq, res: ExpressLikeRes, next: (err?: unknown) => void) => void;
|
|
371
|
+
export declare function requirePermission(requiredPermissions: string | string[]): (req: ExpressLikeReq, res: ExpressLikeRes, next: (err?: unknown) => void) => void;
|
|
372
|
+
/** Verifies an Authly HMAC-SHA256 webhook signature (`X-Authly-Signature` + `X-Authly-Timestamp`). */
|
|
373
|
+
export declare function verifyAuthlyWebhookSignature(opts: {
|
|
374
|
+
payload: string | Buffer;
|
|
375
|
+
timestamp: string;
|
|
376
|
+
signature: string;
|
|
377
|
+
secret: string;
|
|
378
|
+
toleranceSeconds?: number;
|
|
379
|
+
}): boolean;
|
|
380
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
import { createHash, createHmac, createPublicKey, randomBytes, timingSafeEqual, verify as cryptoVerify } from 'node:crypto';
|
|
2
|
+
export class AuthlyManagementError extends Error {
|
|
3
|
+
status;
|
|
4
|
+
code;
|
|
5
|
+
constructor(status, code, message) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.status = status;
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.name = 'AuthlyManagementError';
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export class AuthlyTokenError extends Error {
|
|
13
|
+
code;
|
|
14
|
+
constructor(code, message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.code = code;
|
|
17
|
+
this.name = 'AuthlyTokenError';
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function decodeBase64UrlJson(segment) {
|
|
21
|
+
const json = Buffer.from(segment, 'base64url').toString('utf8');
|
|
22
|
+
return JSON.parse(json);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Zero-dependency RS256 JWKS JWT verifier for Node.js resource servers and backends.
|
|
26
|
+
* Verifies cryptographic signature, issuer, audience, expiration, and not-before claims.
|
|
27
|
+
* Never trusts an unverified user ID from request bodies or headers.
|
|
28
|
+
*/
|
|
29
|
+
export class AuthlyTokenVerifier {
|
|
30
|
+
config;
|
|
31
|
+
issuer;
|
|
32
|
+
audience;
|
|
33
|
+
jwksUri;
|
|
34
|
+
clockTolerance;
|
|
35
|
+
cacheTtlMs;
|
|
36
|
+
keyCache = new Map();
|
|
37
|
+
allKeys = [];
|
|
38
|
+
cacheExpiresAt = 0;
|
|
39
|
+
constructor(config) {
|
|
40
|
+
this.config = config;
|
|
41
|
+
this.issuer = config.issuer.replace(/\/+$/, '');
|
|
42
|
+
this.audience = config.audience;
|
|
43
|
+
this.jwksUri = config.jwksUri ?? `${this.issuer}/oauth/jwks`;
|
|
44
|
+
this.clockTolerance = config.clockToleranceSeconds ?? 30;
|
|
45
|
+
this.cacheTtlMs = config.jwksCacheTtlMs ?? 300_000;
|
|
46
|
+
if (config.staticJwks) {
|
|
47
|
+
this.loadKeys(config.staticJwks.keys);
|
|
48
|
+
this.cacheExpiresAt = Number.POSITIVE_INFINITY;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
loadKeys(keys) {
|
|
52
|
+
const map = new Map();
|
|
53
|
+
const list = [];
|
|
54
|
+
for (const jwk of keys) {
|
|
55
|
+
const keyObj = createPublicKey({ key: jwk, format: 'jwk' });
|
|
56
|
+
list.push(keyObj);
|
|
57
|
+
if (jwk.kid)
|
|
58
|
+
map.set(jwk.kid, keyObj);
|
|
59
|
+
}
|
|
60
|
+
this.keyCache = map;
|
|
61
|
+
this.allKeys = list;
|
|
62
|
+
}
|
|
63
|
+
async ensureKeys(kid, forceRefresh = false) {
|
|
64
|
+
if (!this.config.staticJwks && (forceRefresh || Date.now() >= this.cacheExpiresAt || (kid && !this.keyCache.has(kid)))) {
|
|
65
|
+
const res = await fetch(this.jwksUri, { headers: { Accept: 'application/json' } }).catch(() => null);
|
|
66
|
+
if (!res || !res.ok)
|
|
67
|
+
throw new AuthlyTokenError('jwks_fetch_failed', 'Failed to fetch JWKS from Authly.');
|
|
68
|
+
const body = (await res.json());
|
|
69
|
+
if (!Array.isArray(body.keys) || body.keys.length === 0) {
|
|
70
|
+
throw new AuthlyTokenError('jwks_fetch_failed', 'JWKS response contained no keys.');
|
|
71
|
+
}
|
|
72
|
+
this.loadKeys(body.keys);
|
|
73
|
+
this.cacheExpiresAt = Date.now() + this.cacheTtlMs;
|
|
74
|
+
}
|
|
75
|
+
if (kid) {
|
|
76
|
+
const exact = this.keyCache.get(kid);
|
|
77
|
+
if (!exact)
|
|
78
|
+
throw new AuthlyTokenError('unknown_kid', 'Signing key ID not found in JWKS.');
|
|
79
|
+
return [exact];
|
|
80
|
+
}
|
|
81
|
+
return this.allKeys;
|
|
82
|
+
}
|
|
83
|
+
async verifyToken(token, opts = {}) {
|
|
84
|
+
const parts = token.trim().split('.');
|
|
85
|
+
if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) {
|
|
86
|
+
throw new AuthlyTokenError('malformed_token', 'Token is not a valid compact JWT.');
|
|
87
|
+
}
|
|
88
|
+
let header;
|
|
89
|
+
let payload;
|
|
90
|
+
try {
|
|
91
|
+
header = decodeBase64UrlJson(parts[0]);
|
|
92
|
+
payload = decodeBase64UrlJson(parts[1]);
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
throw new AuthlyTokenError('malformed_token', 'Token header or payload is not valid JSON.');
|
|
96
|
+
}
|
|
97
|
+
// Pin RS256 to prevent algorithm-confusion attacks (alg=none or HS256).
|
|
98
|
+
if (header.alg !== 'RS256') {
|
|
99
|
+
throw new AuthlyTokenError('unsupported_alg', `Unsupported JWT algorithm: ${String(header.alg)}`);
|
|
100
|
+
}
|
|
101
|
+
const keys = await this.ensureKeys(header.kid);
|
|
102
|
+
const signingInput = Buffer.from(`${parts[0]}.${parts[1]}`, 'utf8');
|
|
103
|
+
const signature = Buffer.from(parts[2], 'base64url');
|
|
104
|
+
const validSig = keys.some((key) => cryptoVerify('RSA-SHA256', signingInput, key, signature));
|
|
105
|
+
if (!validSig) {
|
|
106
|
+
throw new AuthlyTokenError('invalid_signature', 'JWT signature verification failed.');
|
|
107
|
+
}
|
|
108
|
+
const now = opts.nowSeconds ?? Math.floor(Date.now() / 1000);
|
|
109
|
+
if (typeof payload.exp !== 'number' || now >= payload.exp + this.clockTolerance) {
|
|
110
|
+
throw new AuthlyTokenError('token_expired', 'JWT has expired.');
|
|
111
|
+
}
|
|
112
|
+
if (typeof payload.nbf === 'number' && now + this.clockTolerance < payload.nbf) {
|
|
113
|
+
throw new AuthlyTokenError('token_not_active', 'JWT is not yet valid.');
|
|
114
|
+
}
|
|
115
|
+
const tokenIssuer = typeof payload.iss === 'string' ? payload.iss.replace(/\/+$/, '') : '';
|
|
116
|
+
if (tokenIssuer !== this.issuer) {
|
|
117
|
+
throw new AuthlyTokenError('invalid_issuer', 'JWT issuer does not match expected Authly issuer.');
|
|
118
|
+
}
|
|
119
|
+
const expectedAud = opts.audience ?? this.audience;
|
|
120
|
+
const audList = Array.isArray(payload.aud) ? payload.aud : typeof payload.aud === 'string' ? [payload.aud] : [];
|
|
121
|
+
if (!audList.includes(expectedAud)) {
|
|
122
|
+
throw new AuthlyTokenError('invalid_audience', 'JWT audience does not match this application.');
|
|
123
|
+
}
|
|
124
|
+
if (typeof payload.sub !== 'string' || !payload.sub) {
|
|
125
|
+
throw new AuthlyTokenError('malformed_token', 'JWT subject claim (sub) is missing.');
|
|
126
|
+
}
|
|
127
|
+
if (opts.nonce !== undefined && payload.nonce !== opts.nonce) {
|
|
128
|
+
throw new AuthlyTokenError('invalid_nonce', 'JWT nonce claim does not match the login transaction.');
|
|
129
|
+
}
|
|
130
|
+
return payload;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Express / Connect middleware that verifies `Authorization: Bearer <token>` against Authly JWKS
|
|
134
|
+
* and attaches verified claims to `req.authlyUser` (never trusting client-submitted user IDs).
|
|
135
|
+
*/
|
|
136
|
+
middleware() {
|
|
137
|
+
return async (req, res, next) => {
|
|
138
|
+
const authHeader = req.headers?.authorization;
|
|
139
|
+
const raw = typeof authHeader === 'string' ? authHeader : '';
|
|
140
|
+
if (!raw.startsWith('Bearer ')) {
|
|
141
|
+
return res.status(401).json({ error: { code: 'missing_token', message: 'Authorization Bearer token is required.' } });
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
req.authlyUser = await this.verifyToken(raw.slice(7).trim());
|
|
145
|
+
next();
|
|
146
|
+
}
|
|
147
|
+
catch (err) {
|
|
148
|
+
const te = err instanceof AuthlyTokenError ? err : new AuthlyTokenError('invalid_signature', 'Invalid access token.');
|
|
149
|
+
res.status(401).json({ error: { code: te.code, message: te.message } });
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
const isLocalHost = (hostname) => ['localhost', '127.0.0.1', '[::1]'].includes(hostname);
|
|
155
|
+
/**
|
|
156
|
+
* Validates a post-login return destination against an allowlist and rejects open redirects
|
|
157
|
+
* (`//evil.com`, `/\evil.com`, `javascript:`, or untrusted external origins).
|
|
158
|
+
*/
|
|
159
|
+
export function sanitizeReturnTo(rawDestination, opts = {}) {
|
|
160
|
+
const fallback = opts.defaultReturnTo && opts.defaultReturnTo.trim() ? opts.defaultReturnTo.trim() : '/';
|
|
161
|
+
const candidate = typeof rawDestination === 'string' ? rawDestination.trim() : '';
|
|
162
|
+
if (!candidate)
|
|
163
|
+
return fallback;
|
|
164
|
+
if (candidate.startsWith('/') && !candidate.startsWith('//') && !candidate.startsWith('/\\')) {
|
|
165
|
+
return candidate;
|
|
166
|
+
}
|
|
167
|
+
try {
|
|
168
|
+
const parsed = new URL(candidate);
|
|
169
|
+
if (!['http:', 'https:'].includes(parsed.protocol))
|
|
170
|
+
return fallback;
|
|
171
|
+
if (parsed.protocol === 'http:' && (opts.isProduction || !isLocalHost(parsed.hostname)))
|
|
172
|
+
return fallback;
|
|
173
|
+
const allowedOrigins = new Set();
|
|
174
|
+
for (const u of opts.allowedUrls ?? []) {
|
|
175
|
+
try {
|
|
176
|
+
allowedOrigins.add(new URL(u).origin);
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
// Skip relative or malformed entries
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (allowedOrigins.has(parsed.origin))
|
|
183
|
+
return parsed.toString();
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
// Reject unparseable destinations
|
|
187
|
+
}
|
|
188
|
+
return fallback;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Server-side OAuth 2.0 / OIDC client for confidential Node.js and Next.js applications.
|
|
192
|
+
* Supports Authorization Code + PKCE S256, safe return destination binding, token exchange,
|
|
193
|
+
* verified ID token / nonce validation, refresh rotation, UserInfo, revocation, and logout.
|
|
194
|
+
*/
|
|
195
|
+
export class AuthlyOAuthClient {
|
|
196
|
+
config;
|
|
197
|
+
issuer;
|
|
198
|
+
defaultVerifier = null;
|
|
199
|
+
constructor(config) {
|
|
200
|
+
this.config = config;
|
|
201
|
+
this.issuer = config.issuer.replace(/\/+$/, '');
|
|
202
|
+
}
|
|
203
|
+
getVerifier(override) {
|
|
204
|
+
if (override)
|
|
205
|
+
return override;
|
|
206
|
+
if (!this.defaultVerifier) {
|
|
207
|
+
this.defaultVerifier = new AuthlyTokenVerifier({
|
|
208
|
+
issuer: this.issuer,
|
|
209
|
+
audience: this.config.clientId,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
return this.defaultVerifier;
|
|
213
|
+
}
|
|
214
|
+
static generatePkce() {
|
|
215
|
+
const verifier = randomBytes(32).toString('base64url');
|
|
216
|
+
const challenge = createHash('sha256').update(verifier).digest('base64url');
|
|
217
|
+
const state = randomBytes(16).toString('base64url');
|
|
218
|
+
const nonce = randomBytes(16).toString('base64url');
|
|
219
|
+
return { verifier, challenge, state, nonce };
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Starts a complete PKCE + state + nonce login transaction paired with a sanitized return destination.
|
|
223
|
+
* Store the returned `transaction` in an HttpOnly signed cookie or server session before redirecting to `url`.
|
|
224
|
+
*/
|
|
225
|
+
startAuthTransaction(opts = {}) {
|
|
226
|
+
const pkce = AuthlyOAuthClient.generatePkce();
|
|
227
|
+
const safeReturnTo = sanitizeReturnTo(opts.returnTo, {
|
|
228
|
+
allowedUrls: opts.allowedReturnUrls ?? this.config.allowedReturnUrls ?? [this.config.redirectUri],
|
|
229
|
+
defaultReturnTo: opts.defaultReturnTo ?? this.config.defaultReturnTo ?? '/',
|
|
230
|
+
isProduction: opts.isProduction,
|
|
231
|
+
});
|
|
232
|
+
const transaction = {
|
|
233
|
+
state: pkce.state,
|
|
234
|
+
verifier: pkce.verifier,
|
|
235
|
+
challenge: pkce.challenge,
|
|
236
|
+
nonce: pkce.nonce,
|
|
237
|
+
returnTo: safeReturnTo,
|
|
238
|
+
createdAt: Date.now(),
|
|
239
|
+
};
|
|
240
|
+
const url = this.buildAuthorizeUrl({
|
|
241
|
+
codeChallenge: pkce.challenge,
|
|
242
|
+
state: pkce.state,
|
|
243
|
+
nonce: pkce.nonce,
|
|
244
|
+
extra: opts.extra,
|
|
245
|
+
});
|
|
246
|
+
return { url, transaction };
|
|
247
|
+
}
|
|
248
|
+
buildAuthorizeUrl(params) {
|
|
249
|
+
const url = new URL(`${this.issuer}/oauth/authorize`);
|
|
250
|
+
url.searchParams.set('client_id', this.config.clientId);
|
|
251
|
+
url.searchParams.set('redirect_uri', this.config.redirectUri);
|
|
252
|
+
url.searchParams.set('response_type', 'code');
|
|
253
|
+
url.searchParams.set('scope', (this.config.scopes ?? ['openid', 'profile', 'email', 'roles', 'offline_access']).join(' '));
|
|
254
|
+
url.searchParams.set('code_challenge', params.codeChallenge);
|
|
255
|
+
url.searchParams.set('code_challenge_method', 'S256');
|
|
256
|
+
url.searchParams.set('state', params.state);
|
|
257
|
+
if (params.nonce)
|
|
258
|
+
url.searchParams.set('nonce', params.nonce);
|
|
259
|
+
if (this.config.audience)
|
|
260
|
+
url.searchParams.set('resource', this.config.audience);
|
|
261
|
+
for (const [k, v] of Object.entries(params.extra ?? {}))
|
|
262
|
+
url.searchParams.set(k, v);
|
|
263
|
+
return url.toString();
|
|
264
|
+
}
|
|
265
|
+
authHeaders(body) {
|
|
266
|
+
const headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
|
|
267
|
+
if (this.config.clientSecret) {
|
|
268
|
+
headers.Authorization = `Basic ${Buffer.from(`${encodeURIComponent(this.config.clientId)}:${encodeURIComponent(this.config.clientSecret)}`).toString('base64')}`;
|
|
269
|
+
}
|
|
270
|
+
else {
|
|
271
|
+
body.set('client_id', this.config.clientId);
|
|
272
|
+
}
|
|
273
|
+
return headers;
|
|
274
|
+
}
|
|
275
|
+
async exchangeCode(input) {
|
|
276
|
+
const body = new URLSearchParams({
|
|
277
|
+
grant_type: 'authorization_code',
|
|
278
|
+
code: input.code,
|
|
279
|
+
redirect_uri: this.config.redirectUri,
|
|
280
|
+
code_verifier: input.codeVerifier,
|
|
281
|
+
});
|
|
282
|
+
const res = await fetch(`${this.issuer}/oauth/token`, {
|
|
283
|
+
method: 'POST',
|
|
284
|
+
headers: this.authHeaders(body),
|
|
285
|
+
body: body.toString(),
|
|
286
|
+
});
|
|
287
|
+
const json = (await res.json().catch(() => ({})));
|
|
288
|
+
if (!res.ok) {
|
|
289
|
+
throw new AuthlyManagementError(res.status, String(json.error ?? 'token_error'), String(json.error_description ?? 'Authorization code exchange failed.'));
|
|
290
|
+
}
|
|
291
|
+
return json;
|
|
292
|
+
}
|
|
293
|
+
async refreshToken(refreshToken) {
|
|
294
|
+
const body = new URLSearchParams({
|
|
295
|
+
grant_type: 'refresh_token',
|
|
296
|
+
refresh_token: refreshToken,
|
|
297
|
+
});
|
|
298
|
+
const res = await fetch(`${this.issuer}/oauth/token`, {
|
|
299
|
+
method: 'POST',
|
|
300
|
+
headers: this.authHeaders(body),
|
|
301
|
+
body: body.toString(),
|
|
302
|
+
});
|
|
303
|
+
const json = (await res.json().catch(() => ({})));
|
|
304
|
+
if (!res.ok) {
|
|
305
|
+
throw new AuthlyManagementError(res.status, String(json.error ?? 'refresh_error'), String(json.error_description ?? 'Token refresh failed.'));
|
|
306
|
+
}
|
|
307
|
+
return json;
|
|
308
|
+
}
|
|
309
|
+
async getUserInfo(accessToken) {
|
|
310
|
+
const res = await fetch(`${this.issuer}/oauth/userinfo`, {
|
|
311
|
+
headers: { Authorization: `Bearer ${accessToken}`, Accept: 'application/json' },
|
|
312
|
+
});
|
|
313
|
+
const json = (await res.json().catch(() => ({})));
|
|
314
|
+
if (!res.ok) {
|
|
315
|
+
throw new AuthlyManagementError(res.status, String(json.error ?? 'userinfo_error'), String(json.error_description ?? 'Failed to fetch user info.'));
|
|
316
|
+
}
|
|
317
|
+
return json;
|
|
318
|
+
}
|
|
319
|
+
async revokeToken(token) {
|
|
320
|
+
const body = new URLSearchParams({ token });
|
|
321
|
+
const res = await fetch(`${this.issuer}/oauth/revoke`, {
|
|
322
|
+
method: 'POST',
|
|
323
|
+
headers: this.authHeaders(body),
|
|
324
|
+
body: body.toString(),
|
|
325
|
+
});
|
|
326
|
+
if (!res.ok) {
|
|
327
|
+
throw new AuthlyManagementError(res.status, 'revocation_failed', 'Token revocation failed.');
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
buildLogoutUrl(opts = {}) {
|
|
331
|
+
const url = new URL(`${this.issuer}/oauth/logout`);
|
|
332
|
+
if (opts.idTokenHint)
|
|
333
|
+
url.searchParams.set('id_token_hint', opts.idTokenHint);
|
|
334
|
+
const redirect = opts.postLogoutRedirectUri ?? this.config.postLogoutRedirectUri;
|
|
335
|
+
if (redirect)
|
|
336
|
+
url.searchParams.set('post_logout_redirect_uri', redirect);
|
|
337
|
+
return url.toString();
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Completes the OAuth 2.0 / OIDC callback securely:
|
|
341
|
+
* validates state, exchanges code with PKCE verifier, verifies ID token signature + iss/aud/exp/nonce,
|
|
342
|
+
* fetches authoritative UserInfo claims, binds canonical `(iss, sub)` identity, and sanitizes `returnTo`.
|
|
343
|
+
*/
|
|
344
|
+
async completeCallback(input) {
|
|
345
|
+
if (input.error) {
|
|
346
|
+
throw new AuthlyManagementError(400, input.error, input.errorDescription ?? input.error);
|
|
347
|
+
}
|
|
348
|
+
const tx = input.transaction;
|
|
349
|
+
if (!tx || !input.code || !input.state || input.state !== tx.state) {
|
|
350
|
+
throw new AuthlyManagementError(400, 'invalid_state', 'Missing or invalid OAuth transaction state.');
|
|
351
|
+
}
|
|
352
|
+
const tokens = await this.exchangeCode({ code: input.code, codeVerifier: tx.verifier });
|
|
353
|
+
let claims = null;
|
|
354
|
+
if (tokens.id_token) {
|
|
355
|
+
claims = await this.getVerifier(input.verifier).verifyToken(tokens.id_token, {
|
|
356
|
+
audience: this.config.clientId,
|
|
357
|
+
nonce: tx.nonce,
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
const userInfo = await this.getUserInfo(tokens.access_token);
|
|
361
|
+
const sub = claims?.sub ?? userInfo.sub;
|
|
362
|
+
const iss = (claims?.iss ?? this.issuer).replace(/\/+$/, '');
|
|
363
|
+
const roles = Array.from(new Set([...(claims?.roles ?? []), ...(userInfo.roles ?? [])].map(String)));
|
|
364
|
+
const permissions = Array.from(new Set([...(claims?.permissions ?? []), ...(userInfo.permissions ?? [])].map(String)));
|
|
365
|
+
const safeReturnTo = sanitizeReturnTo(tx.returnTo, {
|
|
366
|
+
allowedUrls: input.allowedReturnUrls ?? this.config.allowedReturnUrls ?? [this.config.redirectUri],
|
|
367
|
+
defaultReturnTo: input.defaultReturnTo ?? this.config.defaultReturnTo ?? '/',
|
|
368
|
+
isProduction: input.isProduction,
|
|
369
|
+
});
|
|
370
|
+
return {
|
|
371
|
+
tokens,
|
|
372
|
+
claims,
|
|
373
|
+
userInfo,
|
|
374
|
+
identityKey: `${iss}|${sub}`,
|
|
375
|
+
roles,
|
|
376
|
+
permissions,
|
|
377
|
+
returnTo: safeReturnTo,
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
export class AuthlyManagementClient {
|
|
382
|
+
baseUrl;
|
|
383
|
+
apiKey;
|
|
384
|
+
timeoutMs;
|
|
385
|
+
constructor(config) {
|
|
386
|
+
if (!config.managementApiKey.startsWith('authly_sk_')) {
|
|
387
|
+
throw new Error('Invalid Authly Management API key format.');
|
|
388
|
+
}
|
|
389
|
+
this.baseUrl = config.baseUrl.replace(/\/+$/, '');
|
|
390
|
+
this.apiKey = config.managementApiKey;
|
|
391
|
+
this.timeoutMs = config.timeoutMs ?? 10_000;
|
|
392
|
+
}
|
|
393
|
+
async req(path, init = {}) {
|
|
394
|
+
const controller = new AbortController();
|
|
395
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
396
|
+
try {
|
|
397
|
+
const res = await fetch(`${this.baseUrl}/v1/management${path}`, {
|
|
398
|
+
...init,
|
|
399
|
+
signal: controller.signal,
|
|
400
|
+
headers: {
|
|
401
|
+
'Content-Type': 'application/json',
|
|
402
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
403
|
+
...(init.headers ?? {}),
|
|
404
|
+
},
|
|
405
|
+
});
|
|
406
|
+
const json = await res.json().catch(() => ({}));
|
|
407
|
+
if (!res.ok) {
|
|
408
|
+
const err = json.error;
|
|
409
|
+
throw new AuthlyManagementError(res.status, err?.code ?? 'management_error', err?.message ?? 'Management API error');
|
|
410
|
+
}
|
|
411
|
+
return json;
|
|
412
|
+
}
|
|
413
|
+
finally {
|
|
414
|
+
clearTimeout(timer);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
listUsers(params = {}) {
|
|
418
|
+
const q = new URLSearchParams();
|
|
419
|
+
for (const [k, v] of Object.entries(params)) {
|
|
420
|
+
if (v !== undefined)
|
|
421
|
+
q.set(k, String(v));
|
|
422
|
+
}
|
|
423
|
+
const qs = q.toString();
|
|
424
|
+
return this.req(`/users${qs ? `?${qs}` : ''}`);
|
|
425
|
+
}
|
|
426
|
+
getUser(id) {
|
|
427
|
+
return this.req(`/users/${encodeURIComponent(id)}`);
|
|
428
|
+
}
|
|
429
|
+
updateUser(id, patch) {
|
|
430
|
+
return this.req(`/users/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify(patch) });
|
|
431
|
+
}
|
|
432
|
+
suspendUser(id) {
|
|
433
|
+
return this.req(`/users/${encodeURIComponent(id)}/suspend`, { method: 'POST', body: '{}' });
|
|
434
|
+
}
|
|
435
|
+
reactivateUser(id) {
|
|
436
|
+
return this.req(`/users/${encodeURIComponent(id)}/reactivate`, { method: 'POST', body: '{}' });
|
|
437
|
+
}
|
|
438
|
+
revokeUserSessions(id) {
|
|
439
|
+
return this.req(`/users/${encodeURIComponent(id)}/revoke-sessions`, { method: 'POST', body: '{}' });
|
|
440
|
+
}
|
|
441
|
+
resendVerification(id) {
|
|
442
|
+
return this.req(`/users/${encodeURIComponent(id)}/resend-verification`, { method: 'POST', body: '{}' });
|
|
443
|
+
}
|
|
444
|
+
triggerPasswordReset(id) {
|
|
445
|
+
return this.req(`/users/${encodeURIComponent(id)}/password-reset`, { method: 'POST', body: '{}' });
|
|
446
|
+
}
|
|
447
|
+
deleteUser(id, hard = false) {
|
|
448
|
+
return this.req(`/users/${encodeURIComponent(id)}${hard ? '?hard=true' : ''}`, { method: 'DELETE' });
|
|
449
|
+
}
|
|
450
|
+
listRoles() {
|
|
451
|
+
return this.req('/roles');
|
|
452
|
+
}
|
|
453
|
+
createRole(input) {
|
|
454
|
+
return this.req('/roles', { method: 'POST', body: JSON.stringify(input) });
|
|
455
|
+
}
|
|
456
|
+
getUserRoles(userId, clientId) {
|
|
457
|
+
const qs = clientId ? `?clientId=${encodeURIComponent(clientId)}` : '';
|
|
458
|
+
return this.req(`/users/${encodeURIComponent(userId)}/roles${qs}`);
|
|
459
|
+
}
|
|
460
|
+
setUserRoles(userId, input) {
|
|
461
|
+
return this.req(`/users/${encodeURIComponent(userId)}/roles`, {
|
|
462
|
+
method: 'PUT',
|
|
463
|
+
body: JSON.stringify(input),
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
export function parseCookieHeader(cookieHeader) {
|
|
468
|
+
const out = {};
|
|
469
|
+
if (!cookieHeader)
|
|
470
|
+
return out;
|
|
471
|
+
for (const part of cookieHeader.split(';')) {
|
|
472
|
+
const idx = part.indexOf('=');
|
|
473
|
+
if (idx <= 0)
|
|
474
|
+
continue;
|
|
475
|
+
const key = part.slice(0, idx).trim();
|
|
476
|
+
const val = part.slice(idx + 1).trim();
|
|
477
|
+
try {
|
|
478
|
+
out[key] = decodeURIComponent(val);
|
|
479
|
+
}
|
|
480
|
+
catch {
|
|
481
|
+
out[key] = val;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
return out;
|
|
485
|
+
}
|
|
486
|
+
export function signAuthlyCookiePayload(secret, payload) {
|
|
487
|
+
if (!secret || secret.length < 16) {
|
|
488
|
+
throw new Error('Cookie signing secret must be at least 16 characters.');
|
|
489
|
+
}
|
|
490
|
+
const body = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');
|
|
491
|
+
const sig = createHmac('sha256', secret).update(body).digest('base64url');
|
|
492
|
+
return `${body}.${sig}`;
|
|
493
|
+
}
|
|
494
|
+
export function verifyAuthlyCookiePayload(secret, rawToken) {
|
|
495
|
+
if (!secret || !rawToken)
|
|
496
|
+
return null;
|
|
497
|
+
const dot = rawToken.indexOf('.');
|
|
498
|
+
if (dot <= 0)
|
|
499
|
+
return null;
|
|
500
|
+
const body = rawToken.slice(0, dot);
|
|
501
|
+
const sig = rawToken.slice(dot + 1);
|
|
502
|
+
const expected = createHmac('sha256', secret).update(body).digest('base64url');
|
|
503
|
+
const a = Buffer.from(sig);
|
|
504
|
+
const b = Buffer.from(expected);
|
|
505
|
+
if (a.length !== b.length || !timingSafeEqual(a, b))
|
|
506
|
+
return null;
|
|
507
|
+
try {
|
|
508
|
+
return JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
|
|
509
|
+
}
|
|
510
|
+
catch {
|
|
511
|
+
return null;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
function serializeSetCookie(name, value, opts = {}) {
|
|
515
|
+
const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${opts.path ?? '/'}`];
|
|
516
|
+
if (opts.maxAgeSeconds !== undefined)
|
|
517
|
+
parts.push(`Max-Age=${Math.max(0, Math.floor(opts.maxAgeSeconds))}`);
|
|
518
|
+
if (opts.httpOnly !== false)
|
|
519
|
+
parts.push('HttpOnly');
|
|
520
|
+
parts.push(`SameSite=${opts.sameSite ?? 'Lax'}`);
|
|
521
|
+
if (opts.secure)
|
|
522
|
+
parts.push('Secure');
|
|
523
|
+
return parts.join('; ');
|
|
524
|
+
}
|
|
525
|
+
export function createSignedSessionCookie(secret, session, opts = {}) {
|
|
526
|
+
const maxAge = opts.maxAgeSeconds ?? 8 * 3600;
|
|
527
|
+
const exp = session.exp ?? Math.floor(Date.now() / 1000) + maxAge;
|
|
528
|
+
const token = signAuthlyCookiePayload(secret, { ...session, exp });
|
|
529
|
+
return serializeSetCookie(opts.cookieName ?? 'authly_app_session', token, {
|
|
530
|
+
maxAgeSeconds: maxAge,
|
|
531
|
+
secure: opts.secure,
|
|
532
|
+
sameSite: opts.sameSite ?? 'Lax',
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
export function createSignedTransactionCookie(secret, transaction, opts = {}) {
|
|
536
|
+
const maxAge = opts.maxAgeSeconds ?? 600;
|
|
537
|
+
return serializeSetCookie(opts.cookieName ?? 'authly_oauth_tx', signAuthlyCookiePayload(secret, transaction), {
|
|
538
|
+
maxAgeSeconds: maxAge,
|
|
539
|
+
secure: opts.secure,
|
|
540
|
+
sameSite: 'Lax',
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
export function clearAuthlyCookieHeader(name, opts = {}) {
|
|
544
|
+
return serializeSetCookie(name, '', { maxAgeSeconds: 0, path: opts.path, secure: opts.secure });
|
|
545
|
+
}
|
|
546
|
+
export function readSignedSessionCookie(cookieHeader, secret, cookieName = 'authly_app_session') {
|
|
547
|
+
const parsed = parseCookieHeader(cookieHeader);
|
|
548
|
+
const data = verifyAuthlyCookiePayload(secret, parsed[cookieName]);
|
|
549
|
+
if (!data || typeof data.sub !== 'string' || typeof data.exp !== 'number')
|
|
550
|
+
return null;
|
|
551
|
+
if (Math.floor(Date.now() / 1000) >= data.exp)
|
|
552
|
+
return null;
|
|
553
|
+
return {
|
|
554
|
+
...data,
|
|
555
|
+
roles: Array.isArray(data.roles) ? data.roles : [],
|
|
556
|
+
permissions: Array.isArray(data.permissions) ? data.permissions : [],
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
export function readSignedTransactionCookie(cookieHeader, secret, cookieName = 'authly_oauth_tx') {
|
|
560
|
+
const parsed = parseCookieHeader(cookieHeader);
|
|
561
|
+
const tx = verifyAuthlyCookiePayload(secret, parsed[cookieName]);
|
|
562
|
+
if (!tx || typeof tx.state !== 'string' || typeof tx.verifier !== 'string' || typeof tx.createdAt !== 'number') {
|
|
563
|
+
return null;
|
|
564
|
+
}
|
|
565
|
+
if (Date.now() - tx.createdAt > 15 * 60_000)
|
|
566
|
+
return null;
|
|
567
|
+
return tx;
|
|
568
|
+
}
|
|
569
|
+
export function getUserRoles(subject) {
|
|
570
|
+
return Array.isArray(subject?.roles) ? subject.roles : [];
|
|
571
|
+
}
|
|
572
|
+
export function hasRole(subject, required) {
|
|
573
|
+
const list = Array.isArray(required) ? required : [required];
|
|
574
|
+
const owned = new Set(getUserRoles(subject));
|
|
575
|
+
return list.some((r) => owned.has(r));
|
|
576
|
+
}
|
|
577
|
+
export function hasPermission(subject, required) {
|
|
578
|
+
const list = Array.isArray(required) ? required : [required];
|
|
579
|
+
const owned = new Set(Array.isArray(subject?.permissions) ? subject.permissions : []);
|
|
580
|
+
return list.some((p) => owned.has(p));
|
|
581
|
+
}
|
|
582
|
+
export function requireAuthSession(opts) {
|
|
583
|
+
return (req, res, next) => {
|
|
584
|
+
const rawHeader = typeof req.headers?.cookie === 'string' ? req.headers.cookie : undefined;
|
|
585
|
+
const session = readSignedSessionCookie(rawHeader, opts.secret, opts.cookieName);
|
|
586
|
+
if (!session) {
|
|
587
|
+
return res.status(401).json({ error: { code: 'unauthenticated', message: 'Valid application session is required.' } });
|
|
588
|
+
}
|
|
589
|
+
req.authlySession = session;
|
|
590
|
+
next();
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
export function requireRole(requiredRoles) {
|
|
594
|
+
return (req, res, next) => {
|
|
595
|
+
const subject = req.authlySession ?? req.authlyUser;
|
|
596
|
+
if (!subject) {
|
|
597
|
+
return res.status(401).json({ error: { code: 'unauthenticated', message: 'Authentication is required.' } });
|
|
598
|
+
}
|
|
599
|
+
if (!hasRole(subject, requiredRoles)) {
|
|
600
|
+
return res.status(403).json({ error: { code: 'forbidden', message: 'You do not have the required application role.' } });
|
|
601
|
+
}
|
|
602
|
+
next();
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
export function requirePermission(requiredPermissions) {
|
|
606
|
+
return (req, res, next) => {
|
|
607
|
+
const subject = req.authlySession ?? req.authlyUser;
|
|
608
|
+
if (!subject) {
|
|
609
|
+
return res.status(401).json({ error: { code: 'unauthenticated', message: 'Authentication is required.' } });
|
|
610
|
+
}
|
|
611
|
+
if (!hasPermission(subject, requiredPermissions)) {
|
|
612
|
+
return res.status(403).json({ error: { code: 'forbidden', message: 'You do not have the required application permission.' } });
|
|
613
|
+
}
|
|
614
|
+
next();
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
/** Verifies an Authly HMAC-SHA256 webhook signature (`X-Authly-Signature` + `X-Authly-Timestamp`). */
|
|
618
|
+
export function verifyAuthlyWebhookSignature(opts) {
|
|
619
|
+
const tolerance = opts.toleranceSeconds ?? 300;
|
|
620
|
+
const tsNum = Number(opts.timestamp);
|
|
621
|
+
if (!Number.isFinite(tsNum) || Math.abs(Math.floor(Date.now() / 1000) - tsNum) > tolerance) {
|
|
622
|
+
return false;
|
|
623
|
+
}
|
|
624
|
+
const signedContent = `${opts.timestamp}.${typeof opts.payload === 'string' ? opts.payload : opts.payload.toString('utf8')}`;
|
|
625
|
+
const expected = `v1=${createHmac('sha256', opts.secret).update(signedContent).digest('hex')}`;
|
|
626
|
+
const a = Buffer.from(expected);
|
|
627
|
+
const b = Buffer.from(opts.signature);
|
|
628
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
629
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@npmatomicauthy/node",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Official Authly authentication SDK for Node.js",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md"
|
|
18
|
+
],
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public"
|
|
21
|
+
},
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=22"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
|
|
27
|
+
"build": "tsc -p tsconfig.build.json",
|
|
28
|
+
"typecheck": "tsc --noEmit",
|
|
29
|
+
"prepublishOnly": "npm run clean && npm run build && npm run typecheck"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@types/node": "^22.20.5",
|
|
33
|
+
"typescript": "^5.9.3"
|
|
34
|
+
}
|
|
35
|
+
}
|