@npmatomicauthy/node 1.0.0 → 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 +20 -0
- package/dist/index.d.ts +160 -3
- package/dist/index.js +288 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -252,3 +252,23 @@ try {
|
|
|
252
252
|
- Do not log, expose, or persist bearer/refresh tokens in browser-accessible storage.
|
|
253
253
|
|
|
254
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
CHANGED
|
@@ -34,10 +34,12 @@ export interface VerifiedAuthlyClaims {
|
|
|
34
34
|
exp: number;
|
|
35
35
|
iat: number;
|
|
36
36
|
nbf?: number;
|
|
37
|
+
nonce?: string;
|
|
37
38
|
email?: string;
|
|
38
39
|
email_verified?: boolean;
|
|
39
40
|
name?: string;
|
|
40
41
|
roles?: string[];
|
|
42
|
+
permissions?: string[];
|
|
41
43
|
scope?: string;
|
|
42
44
|
client_id?: string;
|
|
43
45
|
project_id?: string;
|
|
@@ -49,8 +51,44 @@ export interface AuthlyUserIdentity {
|
|
|
49
51
|
email_verified?: boolean;
|
|
50
52
|
name?: string;
|
|
51
53
|
roles?: string[];
|
|
54
|
+
permissions?: string[];
|
|
52
55
|
project_id?: string;
|
|
53
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
|
+
}
|
|
54
92
|
export interface AuthlyOAuthTokenResponse {
|
|
55
93
|
access_token: string;
|
|
56
94
|
token_type: string;
|
|
@@ -65,8 +103,8 @@ export declare class AuthlyManagementError extends Error {
|
|
|
65
103
|
constructor(status: number, code: string, message: string);
|
|
66
104
|
}
|
|
67
105
|
export declare class AuthlyTokenError extends Error {
|
|
68
|
-
readonly code: 'missing_token' | 'malformed_token' | 'unsupported_alg' | 'unknown_kid' | 'invalid_signature' | 'token_expired' | 'token_not_active' | 'invalid_issuer' | 'invalid_audience' | 'jwks_fetch_failed';
|
|
69
|
-
constructor(code: 'missing_token' | 'malformed_token' | 'unsupported_alg' | 'unknown_kid' | 'invalid_signature' | 'token_expired' | 'token_not_active' | 'invalid_issuer' | 'invalid_audience' | 'jwks_fetch_failed', message: string);
|
|
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);
|
|
70
108
|
}
|
|
71
109
|
export interface AuthlyTokenVerifierConfig {
|
|
72
110
|
/** Expected OIDC issuer (e.g. https://auth.example.com) */
|
|
@@ -109,6 +147,7 @@ export declare class AuthlyTokenVerifier {
|
|
|
109
147
|
verifyToken(token: string, opts?: {
|
|
110
148
|
nowSeconds?: number;
|
|
111
149
|
audience?: string;
|
|
150
|
+
nonce?: string;
|
|
112
151
|
}): Promise<VerifiedAuthlyClaims>;
|
|
113
152
|
/**
|
|
114
153
|
* Express / Connect middleware that verifies `Authorization: Bearer <token>` against Authly JWKS
|
|
@@ -123,6 +162,15 @@ export declare class AuthlyTokenVerifier {
|
|
|
123
162
|
};
|
|
124
163
|
}, next: (err?: unknown) => void) => Promise<void>;
|
|
125
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;
|
|
126
174
|
export interface AuthlyOAuthClientConfig {
|
|
127
175
|
issuer: string;
|
|
128
176
|
clientId: string;
|
|
@@ -130,23 +178,44 @@ export interface AuthlyOAuthClientConfig {
|
|
|
130
178
|
clientSecret?: string;
|
|
131
179
|
redirectUri: string;
|
|
132
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[];
|
|
133
185
|
scopes?: string[];
|
|
134
186
|
audience?: string;
|
|
135
187
|
}
|
|
136
188
|
/**
|
|
137
189
|
* Server-side OAuth 2.0 / OIDC client for confidential Node.js and Next.js applications.
|
|
138
|
-
* Supports Authorization Code + PKCE S256,
|
|
190
|
+
* Supports Authorization Code + PKCE S256, safe return destination binding, token exchange,
|
|
191
|
+
* verified ID token / nonce validation, refresh rotation, UserInfo, revocation, and logout.
|
|
139
192
|
*/
|
|
140
193
|
export declare class AuthlyOAuthClient {
|
|
141
194
|
private readonly config;
|
|
142
195
|
private readonly issuer;
|
|
196
|
+
private defaultVerifier;
|
|
143
197
|
constructor(config: AuthlyOAuthClientConfig);
|
|
198
|
+
private getVerifier;
|
|
144
199
|
static generatePkce(): {
|
|
145
200
|
verifier: string;
|
|
146
201
|
challenge: string;
|
|
147
202
|
state: string;
|
|
148
203
|
nonce: string;
|
|
149
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
|
+
};
|
|
150
219
|
buildAuthorizeUrl(params: {
|
|
151
220
|
codeChallenge: string;
|
|
152
221
|
state: string;
|
|
@@ -165,6 +234,22 @@ export declare class AuthlyOAuthClient {
|
|
|
165
234
|
idTokenHint?: string;
|
|
166
235
|
postLogoutRedirectUri?: string;
|
|
167
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>;
|
|
168
253
|
}
|
|
169
254
|
export declare class AuthlyManagementClient {
|
|
170
255
|
private readonly baseUrl;
|
|
@@ -212,7 +297,78 @@ export declare class AuthlyManagementClient {
|
|
|
212
297
|
deleteUser(id: string, hard?: boolean): Promise<{
|
|
213
298
|
ok: true;
|
|
214
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
|
+
}>;
|
|
215
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;
|
|
216
372
|
/** Verifies an Authly HMAC-SHA256 webhook signature (`X-Authly-Signature` + `X-Authly-Timestamp`). */
|
|
217
373
|
export declare function verifyAuthlyWebhookSignature(opts: {
|
|
218
374
|
payload: string | Buffer;
|
|
@@ -221,3 +377,4 @@ export declare function verifyAuthlyWebhookSignature(opts: {
|
|
|
221
377
|
secret: string;
|
|
222
378
|
toleranceSeconds?: number;
|
|
223
379
|
}): boolean;
|
|
380
|
+
export {};
|
package/dist/index.js
CHANGED
|
@@ -124,6 +124,9 @@ export class AuthlyTokenVerifier {
|
|
|
124
124
|
if (typeof payload.sub !== 'string' || !payload.sub) {
|
|
125
125
|
throw new AuthlyTokenError('malformed_token', 'JWT subject claim (sub) is missing.');
|
|
126
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
|
+
}
|
|
127
130
|
return payload;
|
|
128
131
|
}
|
|
129
132
|
/**
|
|
@@ -148,17 +151,66 @@ export class AuthlyTokenVerifier {
|
|
|
148
151
|
};
|
|
149
152
|
}
|
|
150
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
|
+
}
|
|
151
190
|
/**
|
|
152
191
|
* Server-side OAuth 2.0 / OIDC client for confidential Node.js and Next.js applications.
|
|
153
|
-
* Supports Authorization Code + PKCE S256,
|
|
192
|
+
* Supports Authorization Code + PKCE S256, safe return destination binding, token exchange,
|
|
193
|
+
* verified ID token / nonce validation, refresh rotation, UserInfo, revocation, and logout.
|
|
154
194
|
*/
|
|
155
195
|
export class AuthlyOAuthClient {
|
|
156
196
|
config;
|
|
157
197
|
issuer;
|
|
198
|
+
defaultVerifier = null;
|
|
158
199
|
constructor(config) {
|
|
159
200
|
this.config = config;
|
|
160
201
|
this.issuer = config.issuer.replace(/\/+$/, '');
|
|
161
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
|
+
}
|
|
162
214
|
static generatePkce() {
|
|
163
215
|
const verifier = randomBytes(32).toString('base64url');
|
|
164
216
|
const challenge = createHash('sha256').update(verifier).digest('base64url');
|
|
@@ -166,12 +218,39 @@ export class AuthlyOAuthClient {
|
|
|
166
218
|
const nonce = randomBytes(16).toString('base64url');
|
|
167
219
|
return { verifier, challenge, state, nonce };
|
|
168
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
|
+
}
|
|
169
248
|
buildAuthorizeUrl(params) {
|
|
170
249
|
const url = new URL(`${this.issuer}/oauth/authorize`);
|
|
171
250
|
url.searchParams.set('client_id', this.config.clientId);
|
|
172
251
|
url.searchParams.set('redirect_uri', this.config.redirectUri);
|
|
173
252
|
url.searchParams.set('response_type', 'code');
|
|
174
|
-
url.searchParams.set('scope', (this.config.scopes ?? ['openid', 'profile', 'email', 'offline_access']).join(' '));
|
|
253
|
+
url.searchParams.set('scope', (this.config.scopes ?? ['openid', 'profile', 'email', 'roles', 'offline_access']).join(' '));
|
|
175
254
|
url.searchParams.set('code_challenge', params.codeChallenge);
|
|
176
255
|
url.searchParams.set('code_challenge_method', 'S256');
|
|
177
256
|
url.searchParams.set('state', params.state);
|
|
@@ -257,6 +336,47 @@ export class AuthlyOAuthClient {
|
|
|
257
336
|
url.searchParams.set('post_logout_redirect_uri', redirect);
|
|
258
337
|
return url.toString();
|
|
259
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
|
+
}
|
|
260
380
|
}
|
|
261
381
|
export class AuthlyManagementClient {
|
|
262
382
|
baseUrl;
|
|
@@ -327,6 +447,172 @@ export class AuthlyManagementClient {
|
|
|
327
447
|
deleteUser(id, hard = false) {
|
|
328
448
|
return this.req(`/users/${encodeURIComponent(id)}${hard ? '?hard=true' : ''}`, { method: 'DELETE' });
|
|
329
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
|
+
};
|
|
330
616
|
}
|
|
331
617
|
/** Verifies an Authly HMAC-SHA256 webhook signature (`X-Authly-Signature` + `X-Authly-Timestamp`). */
|
|
332
618
|
export function verifyAuthlyWebhookSignature(opts) {
|