@naylence/runtime 0.3.5-test.910 → 0.3.5-test.911
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/dist/browser/index.cjs +1847 -1054
- package/dist/browser/index.mjs +1842 -1049
- package/dist/cjs/naylence/fame/factory-manifest.js +2 -0
- package/dist/cjs/naylence/fame/http/oauth2-token-router.js +751 -88
- package/dist/cjs/naylence/fame/node/admission/admission-profile-factory.js +61 -0
- package/dist/cjs/naylence/fame/security/auth/oauth2-pkce-token-provider-factory.js +171 -0
- package/dist/cjs/naylence/fame/security/auth/oauth2-pkce-token-provider.js +560 -0
- package/dist/cjs/naylence/fame/telemetry/open-telemetry-trace-emitter-factory.js +19 -2
- package/dist/cjs/naylence/fame/telemetry/open-telemetry-trace-emitter.js +19 -9
- package/dist/cjs/naylence/fame/util/register-runtime-factories.js +6 -0
- package/dist/cjs/version.js +2 -2
- package/dist/esm/naylence/fame/factory-manifest.js +2 -0
- package/dist/esm/naylence/fame/http/oauth2-token-router.js +751 -88
- package/dist/esm/naylence/fame/node/admission/admission-profile-factory.js +61 -0
- package/dist/esm/naylence/fame/security/auth/oauth2-pkce-token-provider-factory.js +134 -0
- package/dist/esm/naylence/fame/security/auth/oauth2-pkce-token-provider.js +555 -0
- package/dist/esm/naylence/fame/telemetry/open-telemetry-trace-emitter-factory.js +19 -2
- package/dist/esm/naylence/fame/telemetry/open-telemetry-trace-emitter.js +19 -9
- package/dist/esm/naylence/fame/util/register-runtime-factories.js +6 -0
- package/dist/esm/version.js +2 -2
- package/dist/node/index.cjs +1843 -1050
- package/dist/node/index.mjs +1842 -1049
- package/dist/node/node.cjs +2658 -1202
- package/dist/node/node.mjs +2657 -1201
- package/dist/types/naylence/fame/factory-manifest.d.ts +1 -1
- package/dist/types/naylence/fame/http/oauth2-token-router.d.ts +73 -17
- package/dist/types/naylence/fame/security/auth/oauth2-pkce-token-provider-factory.d.ts +27 -0
- package/dist/types/naylence/fame/security/auth/oauth2-pkce-token-provider.d.ts +42 -0
- package/dist/types/naylence/fame/telemetry/open-telemetry-trace-emitter.d.ts +4 -0
- package/dist/types/version.d.ts +1 -1
- package/package.json +3 -1
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* OAuth2 client credentials grant
|
|
2
|
+
* OAuth2 client credentials and authorization code (PKCE) grant router for Express
|
|
3
3
|
*
|
|
4
|
-
* Provides /oauth/token
|
|
5
|
-
* Implements OAuth2 client credentials grant with JWT token issuance
|
|
4
|
+
* Provides /oauth/token and /oauth/authorize endpoints for local development and testing.
|
|
5
|
+
* Implements OAuth2 client credentials grant with JWT token issuance and
|
|
6
|
+
* OAuth2 authorization code grant with PKCE verification.
|
|
6
7
|
*/
|
|
7
8
|
import express from 'express';
|
|
9
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
8
10
|
import { JWTTokenIssuer } from '../security/auth/jwt-token-issuer.js';
|
|
9
11
|
import { getLogger } from '../util/logging.js';
|
|
10
12
|
const logger = getLogger('naylence.fame.http.oauth2_token_router');
|
|
@@ -15,7 +17,21 @@ const ENV_VAR_ALLOWED_SCOPES = 'FAME_JWT_ALLOWED_SCOPES';
|
|
|
15
17
|
const ENV_VAR_JWT_ISSUER = 'FAME_JWT_ISSUER';
|
|
16
18
|
const ENV_VAR_JWT_ALGORITHM = 'FAME_JWT_ALGORITHM';
|
|
17
19
|
const ENV_VAR_JWT_AUDIENCE = 'FAME_JWT_AUDIENCE';
|
|
20
|
+
const ENV_VAR_ENABLE_PKCE = 'FAME_OAUTH_ENABLE_PKCE';
|
|
21
|
+
const ENV_VAR_ALLOW_PUBLIC_CLIENTS = 'FAME_OAUTH_ALLOW_PUBLIC_CLIENTS';
|
|
22
|
+
const ENV_VAR_AUTHORIZATION_CODE_TTL = 'FAME_OAUTH_CODE_TTL_SEC';
|
|
23
|
+
const ENV_VAR_ENABLE_DEV_LOGIN = 'FAME_OAUTH_ENABLE_DEV_LOGIN';
|
|
24
|
+
const ENV_VAR_DEV_LOGIN_USERNAME = 'FAME_OAUTH_DEV_USERNAME';
|
|
25
|
+
const ENV_VAR_DEV_LOGIN_PASSWORD = 'FAME_OAUTH_DEV_PASSWORD';
|
|
26
|
+
const ENV_VAR_SESSION_TTL = 'FAME_OAUTH_SESSION_TTL_SEC';
|
|
27
|
+
const ENV_VAR_SESSION_COOKIE_NAME = 'FAME_OAUTH_SESSION_COOKIE_NAME';
|
|
28
|
+
const ENV_VAR_SESSION_SECURE_COOKIE = 'FAME_OAUTH_SESSION_SECURE';
|
|
29
|
+
const ENV_VAR_LOGIN_TITLE = 'FAME_OAUTH_LOGIN_TITLE';
|
|
18
30
|
const DEFAULT_JWT_ALGORITHM = 'EdDSA';
|
|
31
|
+
const DEFAULT_AUTHORIZATION_CODE_TTL_SEC = 300;
|
|
32
|
+
const DEFAULT_SESSION_TTL_SEC = 3600;
|
|
33
|
+
const DEFAULT_SESSION_COOKIE_NAME = 'naylence_dev_session';
|
|
34
|
+
const DEFAULT_LOGIN_TITLE = 'Developer Login';
|
|
19
35
|
function coerceString(value) {
|
|
20
36
|
if (typeof value !== 'string') {
|
|
21
37
|
return undefined;
|
|
@@ -35,6 +51,29 @@ function coerceNumber(value) {
|
|
|
35
51
|
}
|
|
36
52
|
return undefined;
|
|
37
53
|
}
|
|
54
|
+
function coerceBoolean(value) {
|
|
55
|
+
if (typeof value === 'boolean') {
|
|
56
|
+
return value;
|
|
57
|
+
}
|
|
58
|
+
if (typeof value === 'string') {
|
|
59
|
+
const normalized = value.trim().toLowerCase();
|
|
60
|
+
if (normalized === 'true' || normalized === '1' || normalized === 'yes') {
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
if (normalized === 'false' || normalized === '0' || normalized === 'no') {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (typeof value === 'number' && Number.isFinite(value)) {
|
|
68
|
+
if (value === 0) {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
if (value === 1) {
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
38
77
|
function coerceStringArray(value) {
|
|
39
78
|
if (Array.isArray(value)) {
|
|
40
79
|
const entries = value
|
|
@@ -66,6 +105,26 @@ function normalizeCreateOAuth2TokenRouterOptions(options) {
|
|
|
66
105
|
coerceString(descriptor.algorithm);
|
|
67
106
|
const tokenTtlSec = coerceNumber(descriptor.tokenTtlSec) ??
|
|
68
107
|
coerceNumber(descriptor.token_ttl_sec);
|
|
108
|
+
const enablePkce = coerceBoolean(descriptor.enablePkce) ??
|
|
109
|
+
coerceBoolean(descriptor.enable_pkce);
|
|
110
|
+
const allowPublicClients = coerceBoolean(descriptor.allowPublicClients) ??
|
|
111
|
+
coerceBoolean(descriptor.allow_public_clients);
|
|
112
|
+
const authorizationCodeTtlSec = coerceNumber(descriptor.authorizationCodeTtlSec) ??
|
|
113
|
+
coerceNumber(descriptor.authorization_code_ttl_sec);
|
|
114
|
+
const enableDevLogin = coerceBoolean(descriptor.enableDevLogin) ??
|
|
115
|
+
coerceBoolean(descriptor.enable_dev_login);
|
|
116
|
+
const devLoginUsername = coerceString(descriptor.devLoginUsername) ??
|
|
117
|
+
coerceString(descriptor.dev_login_username);
|
|
118
|
+
const devLoginPassword = coerceString(descriptor.devLoginPassword) ??
|
|
119
|
+
coerceString(descriptor.dev_login_password);
|
|
120
|
+
const devLoginSessionTtlSec = coerceNumber(descriptor.devLoginSessionTtlSec) ??
|
|
121
|
+
coerceNumber(descriptor.dev_login_session_ttl_sec);
|
|
122
|
+
const devLoginCookieName = coerceString(descriptor.devLoginCookieName) ??
|
|
123
|
+
coerceString(descriptor.dev_login_cookie_name);
|
|
124
|
+
const devLoginSecureCookie = coerceBoolean(descriptor.devLoginSecureCookie) ??
|
|
125
|
+
coerceBoolean(descriptor.dev_login_secure_cookie);
|
|
126
|
+
const devLoginTitle = coerceString(descriptor.devLoginTitle) ??
|
|
127
|
+
coerceString(descriptor.dev_login_title);
|
|
69
128
|
return {
|
|
70
129
|
cryptoProvider,
|
|
71
130
|
prefix,
|
|
@@ -74,6 +133,16 @@ function normalizeCreateOAuth2TokenRouterOptions(options) {
|
|
|
74
133
|
allowedScopes,
|
|
75
134
|
algorithm,
|
|
76
135
|
tokenTtlSec,
|
|
136
|
+
enablePkce,
|
|
137
|
+
allowPublicClients,
|
|
138
|
+
authorizationCodeTtlSec,
|
|
139
|
+
enableDevLogin,
|
|
140
|
+
devLoginUsername,
|
|
141
|
+
devLoginPassword,
|
|
142
|
+
devLoginSessionTtlSec,
|
|
143
|
+
devLoginCookieName,
|
|
144
|
+
devLoginSecureCookie,
|
|
145
|
+
devLoginTitle,
|
|
77
146
|
};
|
|
78
147
|
}
|
|
79
148
|
/**
|
|
@@ -139,11 +208,234 @@ function validateScope(requestedScope, allowedScopes) {
|
|
|
139
208
|
const grantedScopes = requestedScopes.filter((scope) => allowedScopes.includes(scope));
|
|
140
209
|
return grantedScopes.length > 0 ? grantedScopes : allowedScopes;
|
|
141
210
|
}
|
|
211
|
+
function base64UrlEncode(buffer) {
|
|
212
|
+
return Buffer.from(buffer)
|
|
213
|
+
.toString('base64')
|
|
214
|
+
.replace(/\+/g, '-')
|
|
215
|
+
.replace(/\//g, '_')
|
|
216
|
+
.replace(/=+$/u, '');
|
|
217
|
+
}
|
|
218
|
+
function computeS256Challenge(verifier) {
|
|
219
|
+
const digest = createHash('sha256').update(verifier, 'utf8').digest();
|
|
220
|
+
return base64UrlEncode(digest);
|
|
221
|
+
}
|
|
222
|
+
function safeTimingEqual(expected, actual) {
|
|
223
|
+
const expectedBuffer = Buffer.from(expected);
|
|
224
|
+
const actualBuffer = Buffer.from(actual);
|
|
225
|
+
if (expectedBuffer.length !== actualBuffer.length) {
|
|
226
|
+
return false;
|
|
227
|
+
}
|
|
228
|
+
return timingSafeEqual(expectedBuffer, actualBuffer);
|
|
229
|
+
}
|
|
230
|
+
function isValidCodeVerifier(value) {
|
|
231
|
+
if (!value) {
|
|
232
|
+
return false;
|
|
233
|
+
}
|
|
234
|
+
if (value.length < 43 || value.length > 128) {
|
|
235
|
+
return false;
|
|
236
|
+
}
|
|
237
|
+
return /^[A-Za-z0-9\-._~]+$/u.test(value);
|
|
238
|
+
}
|
|
239
|
+
function isValidCodeChallenge(value) {
|
|
240
|
+
if (!value) {
|
|
241
|
+
return false;
|
|
242
|
+
}
|
|
243
|
+
if (value.length < 43 || value.length > 128) {
|
|
244
|
+
return false;
|
|
245
|
+
}
|
|
246
|
+
return /^[A-Za-z0-9\-._~]+$/u.test(value);
|
|
247
|
+
}
|
|
248
|
+
function generateAuthorizationCode() {
|
|
249
|
+
return base64UrlEncode(randomBytes(32));
|
|
250
|
+
}
|
|
251
|
+
function generateSessionId() {
|
|
252
|
+
return base64UrlEncode(randomBytes(32));
|
|
253
|
+
}
|
|
254
|
+
function cleanupAuthorizationCodes(store, nowMs) {
|
|
255
|
+
for (const [code, record] of store.entries()) {
|
|
256
|
+
if (record.expiresAt <= nowMs) {
|
|
257
|
+
store.delete(code);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
function toSingleQueryValue(value) {
|
|
262
|
+
if (Array.isArray(value)) {
|
|
263
|
+
return value.length > 0 ? coerceString(value[0]) : undefined;
|
|
264
|
+
}
|
|
265
|
+
return coerceString(value);
|
|
266
|
+
}
|
|
267
|
+
function ensurePositiveInteger(value) {
|
|
268
|
+
if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
|
|
269
|
+
return Math.floor(value);
|
|
270
|
+
}
|
|
271
|
+
return undefined;
|
|
272
|
+
}
|
|
273
|
+
function parseCookies(cookieHeader) {
|
|
274
|
+
if (!cookieHeader) {
|
|
275
|
+
return {};
|
|
276
|
+
}
|
|
277
|
+
return cookieHeader.split(';').reduce((acc, entry) => {
|
|
278
|
+
const [rawName, ...rawValueParts] = entry.split('=');
|
|
279
|
+
const name = rawName?.trim();
|
|
280
|
+
if (!name) {
|
|
281
|
+
return acc;
|
|
282
|
+
}
|
|
283
|
+
const rawValue = rawValueParts.join('=').trim();
|
|
284
|
+
if (rawValue.length === 0) {
|
|
285
|
+
return acc;
|
|
286
|
+
}
|
|
287
|
+
try {
|
|
288
|
+
acc[name] = decodeURIComponent(rawValue);
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
acc[name] = rawValue;
|
|
292
|
+
}
|
|
293
|
+
return acc;
|
|
294
|
+
}, {});
|
|
295
|
+
}
|
|
296
|
+
function sanitizeReturnTo(value, allowedPrefix, fallback) {
|
|
297
|
+
if (!value) {
|
|
298
|
+
return fallback;
|
|
299
|
+
}
|
|
300
|
+
try {
|
|
301
|
+
const candidate = new URL(value, 'http://localhost');
|
|
302
|
+
if (candidate.origin !== 'http://localhost') {
|
|
303
|
+
return fallback;
|
|
304
|
+
}
|
|
305
|
+
if (!candidate.pathname.startsWith(allowedPrefix)) {
|
|
306
|
+
return fallback;
|
|
307
|
+
}
|
|
308
|
+
return `${candidate.pathname}${candidate.search}${candidate.hash}`;
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
return fallback;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
function escapeHtml(text) {
|
|
315
|
+
if (!text) {
|
|
316
|
+
return '';
|
|
317
|
+
}
|
|
318
|
+
return text
|
|
319
|
+
.replace(/&/g, '&')
|
|
320
|
+
.replace(/</g, '<')
|
|
321
|
+
.replace(/>/g, '>')
|
|
322
|
+
.replace(/"/g, '"')
|
|
323
|
+
.replace(/'/g, ''');
|
|
324
|
+
}
|
|
325
|
+
function renderLoginPage(options) {
|
|
326
|
+
const { title, prefix, returnTo, username, errorMessage } = options;
|
|
327
|
+
return `<!DOCTYPE html>
|
|
328
|
+
<html lang="en">
|
|
329
|
+
<head>
|
|
330
|
+
<meta charset="utf-8" />
|
|
331
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
332
|
+
<title>${escapeHtml(title)}</title>
|
|
333
|
+
<style>
|
|
334
|
+
:root { color-scheme: light dark; }
|
|
335
|
+
body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #0f172a; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 16px; }
|
|
336
|
+
.card { width: min(360px, 100%); background: rgba(15, 23, 42, 0.92); border-radius: 16px; padding: 32px; box-shadow: 0 20px 45px rgba(15, 23, 42, 0.25); color: #e2e8f0; backdrop-filter: blur(20px); }
|
|
337
|
+
h1 { margin: 0 0 24px; font-size: 24px; font-weight: 600; text-align: center; }
|
|
338
|
+
label { display: block; font-size: 14px; margin-bottom: 8px; color: #cbd5f5; }
|
|
339
|
+
input[type="text"], input[type="password"] { width: 100%; padding: 12px 14px; border-radius: 10px; border: 1px solid rgba(148, 163, 184, 0.4); background: rgba(15, 23, 42, 0.6); color: inherit; font-size: 15px; transition: border-color 0.2s, box-shadow 0.2s; }
|
|
340
|
+
input[type="text"]:focus, input[type="password"]:focus { outline: none; border-color: #38bdf8; box-shadow: 0 0 0 3px rgba(56, 189, 248, 0.25); }
|
|
341
|
+
.field { margin-bottom: 18px; }
|
|
342
|
+
button { width: 100%; padding: 12px 14px; border-radius: 10px; border: none; background: linear-gradient(135deg, #38bdf8, #818cf8); color: #0f172a; font-weight: 600; font-size: 15px; cursor: pointer; transition: transform 0.15s, box-shadow 0.15s; }
|
|
343
|
+
button:hover { transform: translateY(-1px); box-shadow: 0 10px 25px rgba(129, 140, 248, 0.35); }
|
|
344
|
+
.error { margin-bottom: 18px; padding: 12px 14px; border-radius: 10px; background: rgba(239, 68, 68, 0.18); color: #fecaca; font-size: 13px; }
|
|
345
|
+
.support { margin-top: 16px; font-size: 12px; text-align: center; color: rgba(148, 163, 184, 0.75); }
|
|
346
|
+
a { color: #38bdf8; text-decoration: none; }
|
|
347
|
+
a:hover { text-decoration: underline; }
|
|
348
|
+
.brand { text-align: center; font-size: 14px; letter-spacing: 0.08em; text-transform: uppercase; color: rgba(148, 163, 184, 0.9); margin-bottom: 12px; }
|
|
349
|
+
</style>
|
|
350
|
+
</head>
|
|
351
|
+
<body>
|
|
352
|
+
<main class="card">
|
|
353
|
+
<div class="brand">NAYLENCE</div>
|
|
354
|
+
<h1>${escapeHtml(title)}</h1>
|
|
355
|
+
${errorMessage ? `<div class="error">${escapeHtml(errorMessage)}</div>` : ''}
|
|
356
|
+
<form method="post" action="${escapeHtml(`${prefix}/login`)}">
|
|
357
|
+
<div class="field">
|
|
358
|
+
<label for="username">Username</label>
|
|
359
|
+
<input
|
|
360
|
+
id="username"
|
|
361
|
+
name="username"
|
|
362
|
+
type="text"
|
|
363
|
+
autocomplete="username"
|
|
364
|
+
value="${escapeHtml(username ?? '')}"
|
|
365
|
+
required
|
|
366
|
+
/>
|
|
367
|
+
</div>
|
|
368
|
+
<div class="field">
|
|
369
|
+
<label for="password">Password</label>
|
|
370
|
+
<input
|
|
371
|
+
id="password"
|
|
372
|
+
name="password"
|
|
373
|
+
type="password"
|
|
374
|
+
autocomplete="current-password"
|
|
375
|
+
required
|
|
376
|
+
/>
|
|
377
|
+
</div>
|
|
378
|
+
<input type="hidden" name="return_to" value="${escapeHtml(returnTo)}" />
|
|
379
|
+
<button type="submit">Sign in</button>
|
|
380
|
+
</form>
|
|
381
|
+
<p class="support">Cookies are used to keep your session active in this local environment.</p>
|
|
382
|
+
</main>
|
|
383
|
+
</body>
|
|
384
|
+
</html>`;
|
|
385
|
+
}
|
|
386
|
+
function normalizeCookiePath(prefix) {
|
|
387
|
+
if (!prefix || prefix === '/') {
|
|
388
|
+
return '/';
|
|
389
|
+
}
|
|
390
|
+
return prefix.endsWith('/') && prefix.length > 1
|
|
391
|
+
? prefix.slice(0, -1)
|
|
392
|
+
: prefix;
|
|
393
|
+
}
|
|
394
|
+
function cleanupLoginSessions(store, nowMs) {
|
|
395
|
+
for (const [key, record] of store.entries()) {
|
|
396
|
+
if (record.expiresAt <= nowMs) {
|
|
397
|
+
store.delete(key);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
function getActiveSession(req, store, cookieName, sessionTtlMs) {
|
|
402
|
+
const cookies = parseCookies(req.headers.cookie);
|
|
403
|
+
const sessionId = cookies[cookieName];
|
|
404
|
+
if (!sessionId) {
|
|
405
|
+
return undefined;
|
|
406
|
+
}
|
|
407
|
+
const record = store.get(sessionId);
|
|
408
|
+
if (!record) {
|
|
409
|
+
return undefined;
|
|
410
|
+
}
|
|
411
|
+
const now = Date.now();
|
|
412
|
+
if (record.expiresAt <= now) {
|
|
413
|
+
store.delete(sessionId);
|
|
414
|
+
return undefined;
|
|
415
|
+
}
|
|
416
|
+
record.expiresAt = now + sessionTtlMs;
|
|
417
|
+
store.set(sessionId, record);
|
|
418
|
+
return record;
|
|
419
|
+
}
|
|
420
|
+
function setNoCacheHeaders(res) {
|
|
421
|
+
res.set('Cache-Control', 'no-store');
|
|
422
|
+
res.set('Pragma', 'no-cache');
|
|
423
|
+
}
|
|
424
|
+
function respondInvalidClient(res) {
|
|
425
|
+
res
|
|
426
|
+
.status(401)
|
|
427
|
+
.set('WWW-Authenticate', 'Basic')
|
|
428
|
+
.json({
|
|
429
|
+
error: 'invalid_client',
|
|
430
|
+
error_description: 'Invalid client credentials',
|
|
431
|
+
});
|
|
432
|
+
}
|
|
142
433
|
/**
|
|
143
|
-
* Create an Express router that implements OAuth2
|
|
434
|
+
* Create an Express router that implements OAuth2 token and authorization endpoints
|
|
435
|
+
* with support for client credentials and authorization code (PKCE) grants.
|
|
144
436
|
*
|
|
145
437
|
* @param options - Router configuration options
|
|
146
|
-
* @returns Express router with OAuth2 token
|
|
438
|
+
* @returns Express router with OAuth2 token and authorization endpoints
|
|
147
439
|
*
|
|
148
440
|
* Environment Variables:
|
|
149
441
|
* FAME_JWT_CLIENT_ID: OAuth2 client identifier
|
|
@@ -152,26 +444,17 @@ function validateScope(requestedScope, allowedScopes) {
|
|
|
152
444
|
* FAME_JWT_AUDIENCE: JWT audience claim (optional)
|
|
153
445
|
* FAME_JWT_ALGORITHM: JWT signing algorithm (optional, default: EdDSA)
|
|
154
446
|
* FAME_JWT_ALLOWED_SCOPES: Allowed scopes (optional, default: node.connect)
|
|
155
|
-
*
|
|
156
|
-
*
|
|
157
|
-
*
|
|
158
|
-
* import express from 'express';
|
|
159
|
-
* import { createOAuth2TokenRouter } from '@naylence/runtime';
|
|
160
|
-
*
|
|
161
|
-
* const app = express();
|
|
162
|
-
* app.use(express.urlencoded({ extended: true }));
|
|
163
|
-
*
|
|
164
|
-
* const cryptoProvider = new MyCryptoProvider();
|
|
165
|
-
* app.use(createOAuth2TokenRouter({ cryptoProvider }));
|
|
166
|
-
* ```
|
|
447
|
+
* FAME_OAUTH_ENABLE_PKCE: Enable PKCE authorization endpoints (optional, default: true)
|
|
448
|
+
* FAME_OAUTH_ALLOW_PUBLIC_CLIENTS: Allow PKCE exchanges without client_secret (optional, default: true)
|
|
449
|
+
* FAME_OAUTH_CODE_TTL_SEC: Authorization code TTL in seconds (optional, default: 300)
|
|
167
450
|
*/
|
|
168
451
|
export function createOAuth2TokenRouter(options) {
|
|
169
452
|
const router = express.Router();
|
|
170
|
-
const { cryptoProvider, prefix = DEFAULT_PREFIX, issuer, audience, tokenTtlSec, allowedScopes: configAllowedScopes, algorithm: configAlgorithm, } = normalizeCreateOAuth2TokenRouterOptions(options);
|
|
453
|
+
const { cryptoProvider, prefix = DEFAULT_PREFIX, issuer, audience, tokenTtlSec, allowedScopes: configAllowedScopes, algorithm: configAlgorithm, enablePkce: configEnablePkce, allowPublicClients: configAllowPublicClients, authorizationCodeTtlSec: configAuthorizationCodeTtlSec, enableDevLogin: configEnableDevLogin, devLoginUsername: configDevLoginUsername, devLoginPassword: configDevLoginPassword, devLoginSessionTtlSec: configDevLoginSessionTtlSec, devLoginCookieName: configDevLoginCookieName, devLoginSecureCookie: configDevLoginSecureCookie, devLoginTitle: configDevLoginTitle, } = normalizeCreateOAuth2TokenRouterOptions(options);
|
|
171
454
|
if (!cryptoProvider) {
|
|
172
455
|
throw new Error('cryptoProvider is required to create OAuth2 token router');
|
|
173
456
|
}
|
|
174
|
-
|
|
457
|
+
const provider = cryptoProvider;
|
|
175
458
|
const defaultIssuer = process.env[ENV_VAR_JWT_ISSUER] ?? issuer ?? 'https://auth.fame.fabric';
|
|
176
459
|
const defaultAudience = process.env[ENV_VAR_JWT_AUDIENCE] ?? audience ?? 'fame-fabric';
|
|
177
460
|
const algorithm = process.env[ENV_VAR_JWT_ALGORITHM] ??
|
|
@@ -179,6 +462,38 @@ export function createOAuth2TokenRouter(options) {
|
|
|
179
462
|
DEFAULT_JWT_ALGORITHM;
|
|
180
463
|
const allowedScopes = getAllowedScopes(configAllowedScopes);
|
|
181
464
|
const resolvedTokenTtlSec = tokenTtlSec ?? 3600;
|
|
465
|
+
const enablePkce = coerceBoolean(process.env[ENV_VAR_ENABLE_PKCE]) ??
|
|
466
|
+
(configEnablePkce ?? true);
|
|
467
|
+
const allowPublicClients = coerceBoolean(process.env[ENV_VAR_ALLOW_PUBLIC_CLIENTS]) ??
|
|
468
|
+
(configAllowPublicClients ?? true);
|
|
469
|
+
const authorizationCodeTtlSec = ensurePositiveInteger(coerceNumber(process.env[ENV_VAR_AUTHORIZATION_CODE_TTL]) ??
|
|
470
|
+
configAuthorizationCodeTtlSec) ?? DEFAULT_AUTHORIZATION_CODE_TTL_SEC;
|
|
471
|
+
const devLoginExplicitlyEnabled = coerceBoolean(process.env[ENV_VAR_ENABLE_DEV_LOGIN]) ??
|
|
472
|
+
configEnableDevLogin;
|
|
473
|
+
const devLoginUsername = coerceString(process.env[ENV_VAR_DEV_LOGIN_USERNAME]) ??
|
|
474
|
+
configDevLoginUsername;
|
|
475
|
+
const devLoginPassword = coerceString(process.env[ENV_VAR_DEV_LOGIN_PASSWORD]) ??
|
|
476
|
+
configDevLoginPassword;
|
|
477
|
+
const devLoginSessionTtlSec = ensurePositiveInteger(coerceNumber(process.env[ENV_VAR_SESSION_TTL]) ??
|
|
478
|
+
configDevLoginSessionTtlSec) ?? DEFAULT_SESSION_TTL_SEC;
|
|
479
|
+
const devLoginCookieName = coerceString(process.env[ENV_VAR_SESSION_COOKIE_NAME]) ??
|
|
480
|
+
configDevLoginCookieName ??
|
|
481
|
+
DEFAULT_SESSION_COOKIE_NAME;
|
|
482
|
+
const devLoginSecureCookie = coerceBoolean(process.env[ENV_VAR_SESSION_SECURE_COOKIE]) ??
|
|
483
|
+
(configDevLoginSecureCookie ?? false);
|
|
484
|
+
const devLoginTitle = coerceString(process.env[ENV_VAR_LOGIN_TITLE]) ??
|
|
485
|
+
configDevLoginTitle ??
|
|
486
|
+
DEFAULT_LOGIN_TITLE;
|
|
487
|
+
const devLoginCredentialsConfigured = !!devLoginUsername && !!devLoginPassword;
|
|
488
|
+
const devLoginEnabled = (devLoginExplicitlyEnabled ?? false) || devLoginCredentialsConfigured;
|
|
489
|
+
if (devLoginEnabled && !devLoginCredentialsConfigured) {
|
|
490
|
+
throw new Error('Developer login is enabled but credentials are not configured');
|
|
491
|
+
}
|
|
492
|
+
const sessionCookiePath = normalizeCookiePath(prefix);
|
|
493
|
+
const authorizationRedirectPath = prefix.endsWith('/')
|
|
494
|
+
? `${prefix}authorize`
|
|
495
|
+
: `${prefix}/authorize`;
|
|
496
|
+
const devLoginSessionTtlMs = devLoginSessionTtlSec * 1000;
|
|
182
497
|
logger.debug('oauth2_router_created', {
|
|
183
498
|
prefix,
|
|
184
499
|
issuer: defaultIssuer,
|
|
@@ -186,20 +501,265 @@ export function createOAuth2TokenRouter(options) {
|
|
|
186
501
|
algorithm,
|
|
187
502
|
allowedScopes,
|
|
188
503
|
tokenTtlSec: resolvedTokenTtlSec,
|
|
504
|
+
enablePkce,
|
|
505
|
+
allowPublicClients,
|
|
506
|
+
authorizationCodeTtlSec,
|
|
507
|
+
devLoginEnabled,
|
|
508
|
+
devLoginSessionTtlSec,
|
|
509
|
+
devLoginCookieName,
|
|
510
|
+
devLoginSecureCookie,
|
|
189
511
|
});
|
|
190
|
-
|
|
512
|
+
const authorizationCodes = new Map();
|
|
513
|
+
const loginSessions = new Map();
|
|
514
|
+
if (devLoginEnabled) {
|
|
515
|
+
logger.info('oauth2_dev_login_enabled', {
|
|
516
|
+
loginTitle: devLoginTitle,
|
|
517
|
+
cookieName: devLoginCookieName,
|
|
518
|
+
sessionTtlSec: devLoginSessionTtlSec,
|
|
519
|
+
secureCookie: devLoginSecureCookie,
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
router.get(`${prefix}/authorize`, (req, res) => {
|
|
523
|
+
if (!enablePkce) {
|
|
524
|
+
res.status(404).json({
|
|
525
|
+
error: 'endpoint_disabled',
|
|
526
|
+
error_description: 'PKCE authorization endpoint is disabled',
|
|
527
|
+
});
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
cleanupAuthorizationCodes(authorizationCodes, Date.now());
|
|
531
|
+
if (devLoginEnabled) {
|
|
532
|
+
cleanupLoginSessions(loginSessions, Date.now());
|
|
533
|
+
const activeSession = getActiveSession(req, loginSessions, devLoginCookieName, devLoginSessionTtlMs);
|
|
534
|
+
if (!activeSession) {
|
|
535
|
+
const returnTo = sanitizeReturnTo(req.originalUrl, sessionCookiePath, authorizationRedirectPath);
|
|
536
|
+
const loginLocation = `${prefix}/login?return_to=${encodeURIComponent(returnTo)}`;
|
|
537
|
+
setNoCacheHeaders(res);
|
|
538
|
+
res.redirect(302, loginLocation);
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
let configuredCreds;
|
|
543
|
+
try {
|
|
544
|
+
configuredCreds = getConfiguredClientCredentials();
|
|
545
|
+
}
|
|
546
|
+
catch (error) {
|
|
547
|
+
logger.error('oauth2_config_error', {
|
|
548
|
+
error: error.message,
|
|
549
|
+
});
|
|
550
|
+
res.status(500).json({
|
|
551
|
+
error: 'server_error',
|
|
552
|
+
error_description: 'Server configuration error',
|
|
553
|
+
});
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
const responseType = toSingleQueryValue(req.query.response_type);
|
|
557
|
+
if (responseType !== 'code') {
|
|
558
|
+
res.status(400).json({
|
|
559
|
+
error: 'unsupported_response_type',
|
|
560
|
+
error_description: 'Only authorization code response type is supported',
|
|
561
|
+
});
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
const clientId = toSingleQueryValue(req.query.client_id);
|
|
565
|
+
if (!clientId) {
|
|
566
|
+
res.status(400).json({
|
|
567
|
+
error: 'invalid_request',
|
|
568
|
+
error_description: 'client_id is required',
|
|
569
|
+
});
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
if (clientId !== configuredCreds.clientId) {
|
|
573
|
+
logger.warning('oauth2_authorize_invalid_client', { clientId });
|
|
574
|
+
respondInvalidClient(res);
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
const redirectUriText = toSingleQueryValue(req.query.redirect_uri);
|
|
578
|
+
if (!redirectUriText) {
|
|
579
|
+
res.status(400).json({
|
|
580
|
+
error: 'invalid_request',
|
|
581
|
+
error_description: 'redirect_uri is required',
|
|
582
|
+
});
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
585
|
+
let redirectUrl;
|
|
586
|
+
try {
|
|
587
|
+
redirectUrl = new URL(redirectUriText);
|
|
588
|
+
}
|
|
589
|
+
catch {
|
|
590
|
+
res.status(400).json({
|
|
591
|
+
error: 'invalid_request',
|
|
592
|
+
error_description: 'redirect_uri must be a valid absolute URL',
|
|
593
|
+
});
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
const requestedScope = toSingleQueryValue(req.query.scope);
|
|
597
|
+
const grantedScopes = validateScope(requestedScope, allowedScopes);
|
|
598
|
+
const codeChallenge = toSingleQueryValue(req.query.code_challenge);
|
|
599
|
+
if (!isValidCodeChallenge(codeChallenge)) {
|
|
600
|
+
res.status(400).json({
|
|
601
|
+
error: 'invalid_request',
|
|
602
|
+
error_description: 'code_challenge is invalid or missing',
|
|
603
|
+
});
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
const codeChallengeMethodCandidate = (toSingleQueryValue(req.query.code_challenge_method) ?? 'S256').toUpperCase();
|
|
607
|
+
const codeChallengeMethod = codeChallengeMethodCandidate === 'PLAIN' ? 'PLAIN' : 'S256';
|
|
608
|
+
const state = toSingleQueryValue(req.query.state);
|
|
609
|
+
const authorizationCode = generateAuthorizationCode();
|
|
610
|
+
const expiresAt = Date.now() + authorizationCodeTtlSec * 1000;
|
|
611
|
+
authorizationCodes.set(authorizationCode, {
|
|
612
|
+
code: authorizationCode,
|
|
613
|
+
clientId,
|
|
614
|
+
redirectUri: redirectUrl.toString(),
|
|
615
|
+
scope: grantedScopes,
|
|
616
|
+
codeChallenge,
|
|
617
|
+
codeChallengeMethod,
|
|
618
|
+
expiresAt,
|
|
619
|
+
requestedState: state,
|
|
620
|
+
});
|
|
621
|
+
logger.debug('oauth2_authorization_code_issued', {
|
|
622
|
+
clientId,
|
|
623
|
+
scope: grantedScopes,
|
|
624
|
+
method: codeChallengeMethod,
|
|
625
|
+
expiresAt,
|
|
626
|
+
});
|
|
627
|
+
const redirectLocation = new URL(redirectUrl.toString());
|
|
628
|
+
redirectLocation.searchParams.set('code', authorizationCode);
|
|
629
|
+
if (state) {
|
|
630
|
+
redirectLocation.searchParams.set('state', state);
|
|
631
|
+
}
|
|
632
|
+
if (grantedScopes.length > 0) {
|
|
633
|
+
redirectLocation.searchParams.set('scope', grantedScopes.join(' '));
|
|
634
|
+
}
|
|
635
|
+
setNoCacheHeaders(res);
|
|
636
|
+
res.redirect(302, redirectLocation.toString());
|
|
637
|
+
});
|
|
638
|
+
router.get(`${prefix}/login`, (req, res) => {
|
|
639
|
+
if (!devLoginEnabled) {
|
|
640
|
+
res.status(404).json({
|
|
641
|
+
error: 'endpoint_disabled',
|
|
642
|
+
error_description: 'Developer login is disabled',
|
|
643
|
+
});
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
cleanupLoginSessions(loginSessions, Date.now());
|
|
647
|
+
const returnTo = sanitizeReturnTo(toSingleQueryValue(req.query.return_to), sessionCookiePath, authorizationRedirectPath);
|
|
648
|
+
const session = getActiveSession(req, loginSessions, devLoginCookieName, devLoginSessionTtlMs);
|
|
649
|
+
if (session) {
|
|
650
|
+
setNoCacheHeaders(res);
|
|
651
|
+
res.redirect(302, returnTo);
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
const html = renderLoginPage({
|
|
655
|
+
title: devLoginTitle,
|
|
656
|
+
prefix,
|
|
657
|
+
returnTo,
|
|
658
|
+
username: undefined,
|
|
659
|
+
errorMessage: undefined,
|
|
660
|
+
});
|
|
661
|
+
setNoCacheHeaders(res);
|
|
662
|
+
res.status(200).type('html').send(html);
|
|
663
|
+
});
|
|
664
|
+
router.post(`${prefix}/login`, (req, res) => {
|
|
665
|
+
if (!devLoginEnabled) {
|
|
666
|
+
res.status(404).json({
|
|
667
|
+
error: 'endpoint_disabled',
|
|
668
|
+
error_description: 'Developer login is disabled',
|
|
669
|
+
});
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
cleanupLoginSessions(loginSessions, Date.now());
|
|
673
|
+
const username = coerceString(req.body?.username);
|
|
674
|
+
const password = coerceString(req.body?.password);
|
|
675
|
+
const returnTo = sanitizeReturnTo(coerceString(req.body?.return_to), sessionCookiePath, authorizationRedirectPath);
|
|
676
|
+
if (!username || !password) {
|
|
677
|
+
const html = renderLoginPage({
|
|
678
|
+
title: devLoginTitle,
|
|
679
|
+
prefix,
|
|
680
|
+
returnTo,
|
|
681
|
+
username: username ?? undefined,
|
|
682
|
+
errorMessage: 'Username and password are required.',
|
|
683
|
+
});
|
|
684
|
+
setNoCacheHeaders(res);
|
|
685
|
+
res.status(400).type('html').send(html);
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
if (username !== devLoginUsername || password !== devLoginPassword) {
|
|
689
|
+
logger.warning('oauth2_dev_login_failed', { username });
|
|
690
|
+
const html = renderLoginPage({
|
|
691
|
+
title: devLoginTitle,
|
|
692
|
+
prefix,
|
|
693
|
+
returnTo,
|
|
694
|
+
username,
|
|
695
|
+
errorMessage: 'Invalid username or password.',
|
|
696
|
+
});
|
|
697
|
+
setNoCacheHeaders(res);
|
|
698
|
+
res.status(401).type('html').send(html);
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
const sessionId = generateSessionId();
|
|
702
|
+
const expiresAt = Date.now() + devLoginSessionTtlMs;
|
|
703
|
+
loginSessions.set(sessionId, {
|
|
704
|
+
id: sessionId,
|
|
705
|
+
username,
|
|
706
|
+
expiresAt,
|
|
707
|
+
});
|
|
708
|
+
const cookieOptions = {
|
|
709
|
+
httpOnly: true,
|
|
710
|
+
sameSite: 'lax',
|
|
711
|
+
path: sessionCookiePath,
|
|
712
|
+
maxAge: devLoginSessionTtlMs,
|
|
713
|
+
};
|
|
714
|
+
if (devLoginSecureCookie) {
|
|
715
|
+
cookieOptions.secure = true;
|
|
716
|
+
}
|
|
717
|
+
res.cookie(devLoginCookieName, sessionId, cookieOptions);
|
|
718
|
+
logger.info('oauth2_dev_login_success', { username });
|
|
719
|
+
setNoCacheHeaders(res);
|
|
720
|
+
res.redirect(302, returnTo);
|
|
721
|
+
});
|
|
722
|
+
const logoutHandler = (req, res) => {
|
|
723
|
+
if (!devLoginEnabled) {
|
|
724
|
+
res.status(404).json({
|
|
725
|
+
error: 'endpoint_disabled',
|
|
726
|
+
error_description: 'Developer login is disabled',
|
|
727
|
+
});
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
cleanupLoginSessions(loginSessions, Date.now());
|
|
731
|
+
const cookies = parseCookies(req.headers.cookie);
|
|
732
|
+
const sessionId = cookies[devLoginCookieName];
|
|
733
|
+
if (sessionId) {
|
|
734
|
+
loginSessions.delete(sessionId);
|
|
735
|
+
}
|
|
736
|
+
const cookieOptions = {
|
|
737
|
+
httpOnly: true,
|
|
738
|
+
sameSite: 'lax',
|
|
739
|
+
path: sessionCookiePath,
|
|
740
|
+
maxAge: 0,
|
|
741
|
+
};
|
|
742
|
+
if (devLoginSecureCookie) {
|
|
743
|
+
cookieOptions.secure = true;
|
|
744
|
+
}
|
|
745
|
+
res.cookie(devLoginCookieName, '', cookieOptions);
|
|
746
|
+
setNoCacheHeaders(res);
|
|
747
|
+
res.redirect(302, `${prefix}/login`);
|
|
748
|
+
};
|
|
749
|
+
router.post(`${prefix}/logout`, logoutHandler);
|
|
750
|
+
router.get(`${prefix}/logout`, logoutHandler);
|
|
191
751
|
router.post(`${prefix}/token`, async (req, res, next) => {
|
|
192
752
|
try {
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
if (grant_type !== 'client_credentials'
|
|
753
|
+
cleanupAuthorizationCodes(authorizationCodes, Date.now());
|
|
754
|
+
const { grant_type, client_id, client_secret, scope, audience: reqAudience, code, redirect_uri, code_verifier, } = req.body ?? {};
|
|
755
|
+
if (grant_type !== 'client_credentials' &&
|
|
756
|
+
grant_type !== 'authorization_code') {
|
|
196
757
|
res.status(400).json({
|
|
197
758
|
error: 'unsupported_grant_type',
|
|
198
|
-
error_description: 'Only client_credentials grant
|
|
759
|
+
error_description: 'Only client_credentials and authorization_code grant types are supported',
|
|
199
760
|
});
|
|
200
761
|
return;
|
|
201
762
|
}
|
|
202
|
-
// Get configured credentials
|
|
203
763
|
let configuredCreds;
|
|
204
764
|
try {
|
|
205
765
|
configuredCreds = getConfiguredClientCredentials();
|
|
@@ -214,43 +774,148 @@ export function createOAuth2TokenRouter(options) {
|
|
|
214
774
|
});
|
|
215
775
|
return;
|
|
216
776
|
}
|
|
217
|
-
// Extract client credentials from request
|
|
218
|
-
let requestCreds = null;
|
|
219
|
-
// Try Basic Auth first
|
|
220
777
|
const authHeader = req.headers.authorization;
|
|
221
|
-
|
|
222
|
-
|
|
778
|
+
const basicAuthCreds = parseBasicAuth(authHeader);
|
|
779
|
+
const bodyClientId = coerceString(client_id);
|
|
780
|
+
const bodyClientSecret = coerceString(client_secret);
|
|
781
|
+
const resolvedClientId = basicAuthCreds?.clientId ?? bodyClientId;
|
|
782
|
+
if (!resolvedClientId) {
|
|
783
|
+
res.status(400).json({
|
|
784
|
+
error: 'invalid_request',
|
|
785
|
+
error_description: 'client_id is required',
|
|
786
|
+
});
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
if (resolvedClientId !== configuredCreds.clientId) {
|
|
790
|
+
logger.warning('oauth2_invalid_client_id', {
|
|
791
|
+
clientId: resolvedClientId,
|
|
792
|
+
});
|
|
793
|
+
respondInvalidClient(res);
|
|
794
|
+
return;
|
|
223
795
|
}
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
796
|
+
const providedSecret = basicAuthCreds?.clientSecret ?? bodyClientSecret ?? undefined;
|
|
797
|
+
let clientAuthenticated = false;
|
|
798
|
+
if (providedSecret !== undefined) {
|
|
799
|
+
clientAuthenticated = verifyClientCredentials({ clientId: resolvedClientId, clientSecret: providedSecret }, configuredCreds);
|
|
800
|
+
if (!clientAuthenticated) {
|
|
801
|
+
logger.warning('oauth2_invalid_credentials', {
|
|
802
|
+
clientId: resolvedClientId,
|
|
803
|
+
});
|
|
804
|
+
respondInvalidClient(res);
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
227
807
|
}
|
|
228
|
-
if (
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
808
|
+
if (grant_type === 'client_credentials') {
|
|
809
|
+
if (!clientAuthenticated) {
|
|
810
|
+
respondInvalidClient(res);
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
if (!provider.signingPrivatePem || !provider.signatureKeyId) {
|
|
814
|
+
logger.error('oauth2_missing_keys', {
|
|
815
|
+
hasPrivateKey: !!provider.signingPrivatePem,
|
|
816
|
+
hasKeyId: !!provider.signatureKeyId,
|
|
817
|
+
});
|
|
818
|
+
res.status(500).json({
|
|
819
|
+
error: 'server_error',
|
|
820
|
+
error_description: 'Server cryptographic configuration error',
|
|
821
|
+
});
|
|
822
|
+
return;
|
|
823
|
+
}
|
|
824
|
+
const grantedScopes = validateScope(scope, allowedScopes);
|
|
825
|
+
const response = await issueTokenResponse({
|
|
826
|
+
clientId: resolvedClientId,
|
|
827
|
+
scopes: grantedScopes,
|
|
828
|
+
audience: coerceString(reqAudience),
|
|
232
829
|
});
|
|
830
|
+
setNoCacheHeaders(res);
|
|
831
|
+
res.json(response);
|
|
233
832
|
return;
|
|
234
833
|
}
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
834
|
+
if (!enablePkce) {
|
|
835
|
+
res.status(400).json({
|
|
836
|
+
error: 'unsupported_grant_type',
|
|
837
|
+
error_description: 'PKCE support is disabled',
|
|
838
|
+
});
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
if (!clientAuthenticated && !allowPublicClients) {
|
|
842
|
+
respondInvalidClient(res);
|
|
843
|
+
return;
|
|
844
|
+
}
|
|
845
|
+
const authorizationCode = coerceString(code);
|
|
846
|
+
const redirectUriText = coerceString(redirect_uri);
|
|
847
|
+
const verifier = coerceString(code_verifier);
|
|
848
|
+
if (!authorizationCode ||
|
|
849
|
+
!redirectUriText ||
|
|
850
|
+
!isValidCodeVerifier(verifier)) {
|
|
851
|
+
res.status(400).json({
|
|
852
|
+
error: 'invalid_request',
|
|
853
|
+
error_description: 'code, redirect_uri, and a valid code_verifier are required for PKCE',
|
|
854
|
+
});
|
|
855
|
+
return;
|
|
856
|
+
}
|
|
857
|
+
let redirectUrl;
|
|
858
|
+
try {
|
|
859
|
+
redirectUrl = new URL(redirectUriText);
|
|
860
|
+
}
|
|
861
|
+
catch {
|
|
862
|
+
res.status(400).json({
|
|
863
|
+
error: 'invalid_request',
|
|
864
|
+
error_description: 'redirect_uri must be a valid absolute URL',
|
|
239
865
|
});
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
const record = authorizationCodes.get(authorizationCode);
|
|
869
|
+
if (!record) {
|
|
870
|
+
res.status(400).json({
|
|
871
|
+
error: 'invalid_grant',
|
|
872
|
+
error_description: 'Authorization code is invalid or expired',
|
|
243
873
|
});
|
|
244
874
|
return;
|
|
245
875
|
}
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
876
|
+
if (record.expiresAt <= Date.now()) {
|
|
877
|
+
authorizationCodes.delete(authorizationCode);
|
|
878
|
+
res.status(400).json({
|
|
879
|
+
error: 'invalid_grant',
|
|
880
|
+
error_description: 'Authorization code has expired',
|
|
881
|
+
});
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
if (record.clientId !== resolvedClientId) {
|
|
885
|
+
authorizationCodes.delete(authorizationCode);
|
|
886
|
+
respondInvalidClient(res);
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
if (record.redirectUri !== redirectUrl.toString()) {
|
|
890
|
+
authorizationCodes.delete(authorizationCode);
|
|
891
|
+
res.status(400).json({
|
|
892
|
+
error: 'invalid_grant',
|
|
893
|
+
error_description: 'redirect_uri does not match authorization request',
|
|
894
|
+
});
|
|
895
|
+
return;
|
|
896
|
+
}
|
|
897
|
+
let pkceValid = false;
|
|
898
|
+
if (record.codeChallengeMethod === 'S256') {
|
|
899
|
+
const expected = record.codeChallenge;
|
|
900
|
+
const actual = computeS256Challenge(verifier);
|
|
901
|
+
pkceValid = safeTimingEqual(expected, actual);
|
|
902
|
+
}
|
|
903
|
+
else {
|
|
904
|
+
pkceValid = safeTimingEqual(record.codeChallenge, verifier);
|
|
905
|
+
}
|
|
906
|
+
if (!pkceValid) {
|
|
907
|
+
authorizationCodes.delete(authorizationCode);
|
|
908
|
+
res.status(400).json({
|
|
909
|
+
error: 'invalid_grant',
|
|
910
|
+
error_description: 'code_verifier does not match code_challenge',
|
|
911
|
+
});
|
|
912
|
+
return;
|
|
913
|
+
}
|
|
914
|
+
authorizationCodes.delete(authorizationCode);
|
|
915
|
+
if (!provider.signingPrivatePem || !provider.signatureKeyId) {
|
|
251
916
|
logger.error('oauth2_missing_keys', {
|
|
252
|
-
hasPrivateKey: !!
|
|
253
|
-
hasKeyId: !!
|
|
917
|
+
hasPrivateKey: !!provider.signingPrivatePem,
|
|
918
|
+
hasKeyId: !!provider.signatureKeyId,
|
|
254
919
|
});
|
|
255
920
|
res.status(500).json({
|
|
256
921
|
error: 'server_error',
|
|
@@ -258,44 +923,12 @@ export function createOAuth2TokenRouter(options) {
|
|
|
258
923
|
});
|
|
259
924
|
return;
|
|
260
925
|
}
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
issuer: defaultIssuer,
|
|
266
|
-
algorithm,
|
|
267
|
-
ttlSec: resolvedTokenTtlSec,
|
|
268
|
-
audience: defaultAudience,
|
|
926
|
+
const response = await issueTokenResponse({
|
|
927
|
+
clientId: resolvedClientId,
|
|
928
|
+
scopes: record.scope,
|
|
929
|
+
audience: coerceString(reqAudience),
|
|
269
930
|
});
|
|
270
|
-
|
|
271
|
-
const claims = {
|
|
272
|
-
sub: requestCreds.clientId,
|
|
273
|
-
client_id: requestCreds.clientId,
|
|
274
|
-
scope: grantedScopes.join(' '),
|
|
275
|
-
};
|
|
276
|
-
// Add audience claim
|
|
277
|
-
if (reqAudience) {
|
|
278
|
-
claims.aud = reqAudience;
|
|
279
|
-
}
|
|
280
|
-
else if (defaultAudience) {
|
|
281
|
-
claims.aud = defaultAudience;
|
|
282
|
-
}
|
|
283
|
-
// Issue the token (async)
|
|
284
|
-
const accessToken = await tokenIssuer.issue(claims);
|
|
285
|
-
logger.debug('oauth2_token_issued', {
|
|
286
|
-
clientId: requestCreds.clientId,
|
|
287
|
-
scopes: grantedScopes,
|
|
288
|
-
algorithm,
|
|
289
|
-
});
|
|
290
|
-
// Return token response
|
|
291
|
-
const response = {
|
|
292
|
-
access_token: accessToken,
|
|
293
|
-
token_type: 'Bearer',
|
|
294
|
-
expires_in: resolvedTokenTtlSec,
|
|
295
|
-
};
|
|
296
|
-
if (grantedScopes.length > 0) {
|
|
297
|
-
response.scope = grantedScopes.join(' ');
|
|
298
|
-
}
|
|
931
|
+
setNoCacheHeaders(res);
|
|
299
932
|
res.json(response);
|
|
300
933
|
}
|
|
301
934
|
catch (error) {
|
|
@@ -303,5 +936,35 @@ export function createOAuth2TokenRouter(options) {
|
|
|
303
936
|
next(error);
|
|
304
937
|
}
|
|
305
938
|
});
|
|
939
|
+
async function issueTokenResponse(params) {
|
|
940
|
+
const tokenIssuer = new JWTTokenIssuer({
|
|
941
|
+
signingKeyPem: provider.signingPrivatePem ?? undefined,
|
|
942
|
+
kid: provider.signatureKeyId ?? undefined,
|
|
943
|
+
issuer: defaultIssuer,
|
|
944
|
+
algorithm,
|
|
945
|
+
ttlSec: resolvedTokenTtlSec,
|
|
946
|
+
audience: params.audience ?? defaultAudience,
|
|
947
|
+
});
|
|
948
|
+
const claims = {
|
|
949
|
+
sub: params.clientId,
|
|
950
|
+
client_id: params.clientId,
|
|
951
|
+
scope: params.scopes.join(' '),
|
|
952
|
+
};
|
|
953
|
+
const accessToken = await tokenIssuer.issue(claims);
|
|
954
|
+
logger.debug('oauth2_token_issued', {
|
|
955
|
+
clientId: params.clientId,
|
|
956
|
+
scopes: params.scopes,
|
|
957
|
+
algorithm,
|
|
958
|
+
});
|
|
959
|
+
const response = {
|
|
960
|
+
access_token: accessToken,
|
|
961
|
+
token_type: 'Bearer',
|
|
962
|
+
expires_in: resolvedTokenTtlSec,
|
|
963
|
+
};
|
|
964
|
+
if (params.scopes.length > 0) {
|
|
965
|
+
response.scope = params.scopes.join(' ');
|
|
966
|
+
}
|
|
967
|
+
return response;
|
|
968
|
+
}
|
|
306
969
|
return router;
|
|
307
970
|
}
|