@okeav/idp-pg 0.0.0-stage → 0.2.0
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/.env.example +159 -0
- package/CHANGELOG.md +63 -0
- package/LICENSE +21 -0
- package/README.md +275 -3
- package/package.json +78 -6
- package/src/cache/cache-adapter.js +22 -0
- package/src/cache/index.js +68 -0
- package/src/cache/memory.adapter.js +85 -0
- package/src/cache/redis.adapter.js +96 -0
- package/src/config/console-logger.js +10 -0
- package/src/config/constants.js +178 -0
- package/src/config/defaults.js +100 -0
- package/src/config/from-env.js +150 -0
- package/src/config/init.js +286 -0
- package/src/config/state.js +22 -0
- package/src/errors/error-codes.js +97 -0
- package/src/errors/idp-error.js +75 -0
- package/src/hooks/index.js +85 -0
- package/src/index.js +167 -0
- package/src/magic-link/controller.js +129 -0
- package/src/magic-link/schemas.js +12 -0
- package/src/mfa/attempt-guard.js +48 -0
- package/src/mfa/controller.js +309 -0
- package/src/mfa/factor-store.js +37 -0
- package/src/mfa/memory-attempt-counter.js +58 -0
- package/src/mfa/schemas.js +11 -0
- package/src/mfa/secret-cipher.js +133 -0
- package/src/mfa/secrets.js +156 -0
- package/src/middleware/auth-context.middleware.js +149 -0
- package/src/middleware/cookie-parser.js +4 -0
- package/src/middleware/csrf.js +48 -0
- package/src/middleware/require-recent-auth.middleware.js +30 -0
- package/src/middleware/require-service-caller.middleware.js +32 -0
- package/src/middleware/service-context.middleware.js +70 -0
- package/src/middleware/validate-body.js +16 -0
- package/src/middleware/validate-query.js +22 -0
- package/src/oauth2/authorize.controller.js +233 -0
- package/src/oauth2/client-auth.js +77 -0
- package/src/oauth2/client.controller.js +122 -0
- package/src/oauth2/consent.controller.js +63 -0
- package/src/oauth2/login-challenge.js +50 -0
- package/src/oauth2/redirect-uri.js +25 -0
- package/src/oauth2/schemas.js +103 -0
- package/src/oauth2/token.controller.js +370 -0
- package/src/oidc/discovery.controller.js +36 -0
- package/src/oidc/end-session.controller.js +137 -0
- package/src/oidc/userinfo.controller.js +49 -0
- package/src/password-auth/controllers.js +927 -0
- package/src/password-auth/schemas.js +76 -0
- package/src/rate-limit/enforce.js +35 -0
- package/src/rate-limit/index.js +61 -0
- package/src/rate-limit/keys.js +36 -0
- package/src/rate-limit/memory.adapter.js +75 -0
- package/src/rate-limit/noop.adapter.js +14 -0
- package/src/rate-limit/rate-limiter.js +18 -0
- package/src/rate-limit/redis.adapter.js +71 -0
- package/src/routes/build-router.js +238 -0
- package/src/security/attempt-budget.js +47 -0
- package/src/security/clock-skew.js +63 -0
- package/src/service-mesh/key-status.js +22 -0
- package/src/service-mesh/local-key-lookup.js +12 -0
- package/src/service-mesh/remote-jwks-key-lookup.js +74 -0
- package/src/service-mesh/s2s-bootstrap.middleware.js +41 -0
- package/src/service-mesh/service-identity.client.js +89 -0
- package/src/service-mesh/service-key.controller.js +170 -0
- package/src/service-mesh/verify-service-token.js +75 -0
- package/src/signing/jwks.controller.js +30 -0
- package/src/signing/jwks.js +24 -0
- package/src/signing/key-registry.js +97 -0
- package/src/signing/token.service.js +336 -0
- package/src/sso/binding.js +30 -0
- package/src/sso/callback.controller.js +186 -0
- package/src/sso/initiate.controller.js +92 -0
- package/src/sso/providers.js +237 -0
- package/src/sso/schemas.js +7 -0
- package/src/storage/interfaces.js +178 -0
- package/src/storage/postgres/db.js +68 -0
- package/src/storage/postgres/index.js +160 -0
- package/src/storage/postgres/migrations/run-migrations.js +122 -0
- package/src/storage/postgres/migrations/sql/0001_init.sql +253 -0
- package/src/storage/postgres/repositories/attempt-counter.repository.js +65 -0
- package/src/storage/postgres/repositories/authorization-code.repository.js +104 -0
- package/src/storage/postgres/repositories/consent.repository.js +68 -0
- package/src/storage/postgres/repositories/credential.repository.js +75 -0
- package/src/storage/postgres/repositories/oauth-client.repository.js +122 -0
- package/src/storage/postgres/repositories/service-key.repository.js +76 -0
- package/src/storage/postgres/repositories/session.repository.js +290 -0
- package/src/storage/postgres/repositories/user.repository.js +328 -0
- package/src/storage/postgres/repositories/verification-token.repository.js +138 -0
- package/src/storage/postgres/run.js +22 -0
- package/src/utils/account-status.js +26 -0
- package/src/utils/cookies.js +129 -0
- package/src/utils/device-fingerprint.js +58 -0
- package/src/utils/email-hash.js +23 -0
- package/src/utils/oauth-client-credentials.js +51 -0
- package/src/utils/password.js +40 -0
- package/src/utils/safe-equal.js +12 -0
- package/src/utils/session-family.js +158 -0
- package/src/utils/session-kind.js +15 -0
- package/src/utils/url.js +17 -0
- package/src/webauthn/authentication.controller.js +126 -0
- package/src/webauthn/challenge-store.js +17 -0
- package/src/webauthn/config.js +25 -0
- package/src/webauthn/mfa.controller.js +119 -0
- package/src/webauthn/registration.controller.js +128 -0
- package/src/webauthn/schemas.js +41 -0
- package/src/webauthn/shared.js +63 -0
- package/src/webhooks/dispatcher.js +135 -0
- package/src/webhooks/sign.js +55 -0
- package/src/webhooks/wrap-hooks.js +51 -0
- package/types/index.d.ts +783 -0
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { PASSWORD_POLICY_DEFAULTS, NAME_REGEX, MAX_EMAIL_LENGTH, MAX_NAME_LENGTH } from '../config/constants.js';
|
|
3
|
+
import { loginChallengeSchema } from '../oauth2/login-challenge.js';
|
|
4
|
+
|
|
5
|
+
const email = () => z.string().trim().toLowerCase().email('Must be a valid email address').max(MAX_EMAIL_LENGTH);
|
|
6
|
+
const name = () => z.string().trim().max(MAX_NAME_LENGTH).regex(NAME_REGEX, 'Contains invalid characters');
|
|
7
|
+
// bcrypt only reads the first 72 BYTES of a password: anything after that is silently ignored, so two
|
|
8
|
+
// long passwords sharing a 72-byte prefix would both log in. Longer passwords are refused instead
|
|
9
|
+
// (72 bytes is 72 ASCII characters, fewer for multi-byte UTF-8).
|
|
10
|
+
const BCRYPT_MAX_BYTES = 72;
|
|
11
|
+
const password = () =>
|
|
12
|
+
z.string()
|
|
13
|
+
.min(PASSWORD_POLICY_DEFAULTS.minLength, `Password must be at least ${PASSWORD_POLICY_DEFAULTS.minLength} characters`)
|
|
14
|
+
.max(PASSWORD_POLICY_DEFAULTS.maxLength)
|
|
15
|
+
.refine((v) => Buffer.byteLength(v, 'utf8') <= BCRYPT_MAX_BYTES, `Password must be at most ${BCRYPT_MAX_BYTES} bytes`)
|
|
16
|
+
.regex(PASSWORD_POLICY_DEFAULTS.uppercase, 'Password must contain at least one uppercase letter')
|
|
17
|
+
.regex(PASSWORD_POLICY_DEFAULTS.lowercase, 'Password must contain at least one lowercase letter')
|
|
18
|
+
.regex(PASSWORD_POLICY_DEFAULTS.number, 'Password must contain at least one number')
|
|
19
|
+
.regex(PASSWORD_POLICY_DEFAULTS.special, 'Password must contain at least one special character');
|
|
20
|
+
|
|
21
|
+
export const registerSchema = z.object({
|
|
22
|
+
email: email(),
|
|
23
|
+
password: password(),
|
|
24
|
+
firstName: name().optional(),
|
|
25
|
+
lastName: name().optional(),
|
|
26
|
+
// Opaque bag persisted on the user record — but only when config.registration.acceptMetadata is
|
|
27
|
+
// true (ignored otherwise): it is written by the person registering, so it must never hold
|
|
28
|
+
// anything an app trusts (a role, a tenant, a plan).
|
|
29
|
+
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
30
|
+
}).strict();
|
|
31
|
+
|
|
32
|
+
export const verifyEmailSchema = z.object({
|
|
33
|
+
email: email(),
|
|
34
|
+
token: z.string().optional(),
|
|
35
|
+
code: z.string().max(128).optional(),
|
|
36
|
+
// Required (checked against the registration the code belongs to) only when the address was
|
|
37
|
+
// registered more than once before verification — see REGISTRATION_PASSWORD_REQUIRED.
|
|
38
|
+
password: z.string().min(1).max(1024).optional(),
|
|
39
|
+
// The verification ticket /register or /register/resend-verification returned (also sent as a
|
|
40
|
+
// cookie) — for clients that don't keep cookies.
|
|
41
|
+
ticket: z.string().max(256).optional(),
|
|
42
|
+
}).strict().refine((v) => v.token || v.code, { message: 'Either token or code is required' });
|
|
43
|
+
|
|
44
|
+
export const resendVerificationSchema = z.object({ email: email() }).strict();
|
|
45
|
+
|
|
46
|
+
// login_challenge: from an /oauth2/authorize login_required answer — the new session is bound to it.
|
|
47
|
+
export const loginSchema = z.object({ email: email(), password: z.string().min(1).max(1024), login_challenge: loginChallengeSchema.optional() }).strict();
|
|
48
|
+
|
|
49
|
+
export const forgotPasswordSchema = z.object({ email: email() }).strict();
|
|
50
|
+
|
|
51
|
+
export const resetPasswordSchema = z.object({
|
|
52
|
+
email: email(),
|
|
53
|
+
token: z.string().min(1),
|
|
54
|
+
newPassword: password(),
|
|
55
|
+
}).strict();
|
|
56
|
+
|
|
57
|
+
export const changePasswordSchema = z.object({
|
|
58
|
+
currentPassword: z.string().min(1),
|
|
59
|
+
newPassword: password(),
|
|
60
|
+
}).strict();
|
|
61
|
+
|
|
62
|
+
// refreshToken is optional: browser clients send it as the httpOnly refresh_token cookie instead, which logoutHandler also reads.
|
|
63
|
+
export const logoutSchema = z.object({ refreshToken: z.string().min(1).max(512).optional() }).strict().optional();
|
|
64
|
+
// Same shape for /refresh: a non-string refreshToken used to reach the token hasher and 500.
|
|
65
|
+
export const refreshSchema = logoutSchema;
|
|
66
|
+
|
|
67
|
+
export const updateProfileSchema = z.object({
|
|
68
|
+
firstName: name().optional(),
|
|
69
|
+
lastName: name().optional(),
|
|
70
|
+
displayName: z.string().trim().max(150).optional(),
|
|
71
|
+
// Released as the ID token's `picture` claim, which relying parties render: https only (never
|
|
72
|
+
// javascript: / data:).
|
|
73
|
+
avatarUrl: z.string().max(2048).refine((v) => { try { return new URL(v).protocol === 'https:'; } catch { return false; } }, 'avatarUrl must be an https URL').optional(),
|
|
74
|
+
locale: z.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/, 'locale must be a BCP 47 language tag').max(35).optional(),
|
|
75
|
+
zoneinfo: z.string().regex(/^[A-Za-z0-9_+-/]{1,64}$/, 'zoneinfo must be an IANA time zone name').optional(),
|
|
76
|
+
}).strict();
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Throws `RATE_LIMIT_EXCEEDED` (429) when the given key has exceeded its
|
|
5
|
+
* window.
|
|
6
|
+
*
|
|
7
|
+
* `failMode` decides what a rate-limiter *backend* error (Redis down,
|
|
8
|
+
* timeout) does:
|
|
9
|
+
* - `'closed'` — reject with `RATE_LIMITER_UNAVAILABLE` (503). Used for
|
|
10
|
+
* every key guarding a credential check (login, MFA, password reset,
|
|
11
|
+
* magic link): an attacker who can knock the limiter over must not get
|
|
12
|
+
* unlimited guesses as a result.
|
|
13
|
+
* - `'open'` (the default, kept only where a call site chooses it) — log
|
|
14
|
+
* and let the request through, for limits whose job is load-shedding
|
|
15
|
+
* rather than brute-force protection (e.g. token refresh).
|
|
16
|
+
*
|
|
17
|
+
* @param {{ max: number, windowSeconds: number }} rule
|
|
18
|
+
* @param {{ failMode?: 'open' | 'closed' }} [opts]
|
|
19
|
+
*/
|
|
20
|
+
export async function enforceRateLimit(state, key, { max, windowSeconds }, { failMode = 'open' } = {}) {
|
|
21
|
+
let result;
|
|
22
|
+
try {
|
|
23
|
+
result = await state.rateLimiter.increment(key, { max, windowSeconds });
|
|
24
|
+
} catch (err) {
|
|
25
|
+
if (failMode === 'closed') {
|
|
26
|
+
state.logger?.error?.({ err, key }, 'Rate limiter backend errored — rejecting the request (fail-closed)');
|
|
27
|
+
throw new IdpError({ code: 'RATE_LIMITER_UNAVAILABLE', httpStatus: 503, message: 'Service temporarily unavailable — please try again shortly.', cause: err });
|
|
28
|
+
}
|
|
29
|
+
state.logger?.warn?.({ err, key }, 'Rate limiter backend errored — allowing the request through (fail-open)');
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
if (!result.allowed) {
|
|
33
|
+
throw new IdpError({ code: 'RATE_LIMIT_EXCEEDED', httpStatus: 429, message: 'Too many requests — please try again later.' });
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { MemoryRateLimiter } from './memory.adapter.js';
|
|
2
|
+
import { createRedisRateLimiter } from './redis.adapter.js';
|
|
3
|
+
import { NoopRateLimiter } from './noop.adapter.js';
|
|
4
|
+
|
|
5
|
+
export { BaseRateLimiter } from './rate-limiter.js';
|
|
6
|
+
export { MemoryRateLimiter } from './memory.adapter.js';
|
|
7
|
+
export { RedisRateLimiter, createRedisRateLimiter } from './redis.adapter.js';
|
|
8
|
+
export { NoopRateLimiter } from './noop.adapter.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {object} [config]
|
|
12
|
+
* @param {boolean} [config.enabled=true] - set false to disable entirely (e.g. you already rate-limit at a gateway/CDN)
|
|
13
|
+
* @param {'memory'|'redis'} [config.adapter='memory']
|
|
14
|
+
* @param {import('./rate-limiter.js').RateLimiter} [config.limiter] - the app's own limiter (e.g. counting in its database), instead of an adapter
|
|
15
|
+
* @param {string} [config.keyPrefix='ratelimit:']
|
|
16
|
+
* @param {object} [config.redis] - { host, port, password, db } — only read if adapter === 'redis' and no shared client is available
|
|
17
|
+
* @param {import('ioredis').Redis} [sharedRedisClient] - reused automatically when config.cache.adapter === 'redis' and rateLimiting.adapter is also 'redis' with no separate connection details of its own
|
|
18
|
+
* @returns {Promise<import('./rate-limiter.js').RateLimiter>}
|
|
19
|
+
*/
|
|
20
|
+
export async function createRateLimiter(config = {}, sharedRedisClient = null) {
|
|
21
|
+
assertLimiter(config);
|
|
22
|
+
if (config.enabled === false) return prefixed(new NoopRateLimiter(), '');
|
|
23
|
+
|
|
24
|
+
const prefix = config.keyPrefix ?? 'ratelimit:';
|
|
25
|
+
if (config.limiter !== undefined) return prefixed(config.limiter, prefix);
|
|
26
|
+
const adapter = config.adapter || 'memory';
|
|
27
|
+
|
|
28
|
+
let raw;
|
|
29
|
+
if (adapter === 'redis') {
|
|
30
|
+
// Explicit connection details in config.rateLimiting.redis win; otherwise
|
|
31
|
+
// reuse the cache adapter's Redis client if one is already connected.
|
|
32
|
+
raw = config.redis?.host
|
|
33
|
+
? await createRedisRateLimiter(config.redis)
|
|
34
|
+
: await createRedisRateLimiter({ redis: sharedRedisClient });
|
|
35
|
+
} else if (adapter === 'memory') {
|
|
36
|
+
raw = new MemoryRateLimiter();
|
|
37
|
+
} else {
|
|
38
|
+
throw new Error(`Unknown rate limiter adapter "${adapter}" — expected "memory" or "redis"`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return prefixed(raw, prefix);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A limiter that can't count would fail every sign-in, or none: refused at startup, whether or not limiting is enabled. */
|
|
45
|
+
function assertLimiter({ limiter, adapter }) {
|
|
46
|
+
if (limiter === undefined) return;
|
|
47
|
+
// 'memory' is what an unset adapter resolves to, so only a chosen Redis contradicts a limiter.
|
|
48
|
+
if (adapter === 'redis') throw new Error("config.rateLimiting takes a limiter or adapter 'redis', not both");
|
|
49
|
+
for (const method of ['check', 'increment', 'reset']) {
|
|
50
|
+
if (typeof limiter?.[method] !== 'function') throw new Error(`config.rateLimiting.limiter needs a ${method}() method`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function prefixed(limiter, prefix) {
|
|
55
|
+
const k = (key) => `${prefix}${key}`;
|
|
56
|
+
return {
|
|
57
|
+
check: (key) => limiter.check(k(key)),
|
|
58
|
+
increment: (key, opts) => limiter.increment(k(key), opts),
|
|
59
|
+
reset: (key) => limiter.reset(k(key)),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import net from 'net';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The part of a client IP that identifies one client for rate limiting. IPv4 as-is (an IPv4-mapped
|
|
5
|
+
* IPv6 address `::ffff:a.b.c.d` is IPv4); IPv6 collapsed to its /64 prefix — a single host is
|
|
6
|
+
* routinely handed a whole /64, so keying on the full address gives an attacker 2^64 fresh buckets.
|
|
7
|
+
*
|
|
8
|
+
* `req.ip` is only as good as Express's `trust proxy` setting: set it to your proxy hop count or
|
|
9
|
+
* subnet (never `true`, which trusts any client-supplied X-Forwarded-For).
|
|
10
|
+
*/
|
|
11
|
+
export function ipKey(ip) {
|
|
12
|
+
if (typeof ip !== 'string' || ip.length === 0) return 'unknown';
|
|
13
|
+
const mapped = ip.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);
|
|
14
|
+
if (mapped) return mapped[1];
|
|
15
|
+
if (net.isIPv6(ip)) {
|
|
16
|
+
const [head] = ip.split('%'); // drop a zone id
|
|
17
|
+
const expanded = expandIpv6(head);
|
|
18
|
+
return expanded ? `${expanded.slice(0, 4).join(':')}::/64` : head;
|
|
19
|
+
}
|
|
20
|
+
return ip;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function expandIpv6(addr) {
|
|
24
|
+
const halves = addr.split('::');
|
|
25
|
+
if (halves.length > 2) return null;
|
|
26
|
+
const left = halves[0] ? halves[0].split(':') : [];
|
|
27
|
+
const right = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
|
|
28
|
+
const missing = 8 - left.length - right.length;
|
|
29
|
+
if (missing < 0 || (halves.length === 1 && missing !== 0)) return null;
|
|
30
|
+
return [...left, ...Array(halves.length === 2 ? missing : 0).fill('0'), ...right].map((h) => h.toLowerCase().replace(/^0+(?=.)/, ''));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Per-address rate-limit keys use the email's keyed hash: limiter backends (Redis) and logs never see the address. */
|
|
34
|
+
export function emailKey(state, email) {
|
|
35
|
+
return state.hashEmail(email) ?? 'none';
|
|
36
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { BaseRateLimiter } from './rate-limiter.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Zero-config default. Fixed-window counter, single-process only — same
|
|
5
|
+
* caveat as MemoryCacheAdapter: fine for local dev or a genuinely
|
|
6
|
+
* single-instance deployment, wrong for anything horizontally scaled (each
|
|
7
|
+
* instance would enforce its own independent limit).
|
|
8
|
+
*/
|
|
9
|
+
export class MemoryRateLimiter extends BaseRateLimiter {
|
|
10
|
+
/**
|
|
11
|
+
* @param {{ sweepIntervalMs?: number, maxKeys?: number }} [opts] - `maxKeys` bounds memory. When full
|
|
12
|
+
* (after sweeping expired windows), the oldest counters that have NOT reached their limit are
|
|
13
|
+
* evicted to make room. Refusing new keys instead turned a flood of distinct keys (one IPv6 /48
|
|
14
|
+
* has 65k /64s) into a 503 for every new client — a global lockout. Evicting an exhausted
|
|
15
|
+
* counter would release a block, so those are kept; flushing an unexhausted one gives an attacker
|
|
16
|
+
* at most one window's worth of attempts back, once per 500k keys sent. Only when every key is
|
|
17
|
+
* exhausted is a new key refused (an error, which fail-closed call sites turn into 503).
|
|
18
|
+
*/
|
|
19
|
+
constructor({ sweepIntervalMs = 60_000, maxKeys = 500_000 } = {}) {
|
|
20
|
+
super();
|
|
21
|
+
this._maxKeys = maxKeys;
|
|
22
|
+
this._store = new Map(); // key -> { count, resetAt }
|
|
23
|
+
this._sweepInterval = setInterval(() => this._sweep(), sweepIntervalMs);
|
|
24
|
+
this._sweepInterval.unref?.();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async check(key) {
|
|
28
|
+
const entry = this._store.get(key);
|
|
29
|
+
if (!entry || entry.resetAt <= Date.now()) return { allowed: true, remaining: Infinity, resetAt: 0 };
|
|
30
|
+
return { allowed: true, remaining: Infinity, resetAt: entry.resetAt }; // max unknown without opts — see increment()
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async increment(key, { max, windowSeconds }) {
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
let entry = this._store.get(key);
|
|
36
|
+
if (!entry || entry.resetAt <= now) {
|
|
37
|
+
if (!entry && this._store.size >= this._maxKeys) {
|
|
38
|
+
this._sweep();
|
|
39
|
+
if (this._store.size >= this._maxKeys) this._evictUnexhausted();
|
|
40
|
+
if (this._store.size >= this._maxKeys) throw new Error('MemoryRateLimiter is full (maxKeys) — refusing to track a new key');
|
|
41
|
+
}
|
|
42
|
+
entry = { count: 0, max, resetAt: now + windowSeconds * 1000 };
|
|
43
|
+
}
|
|
44
|
+
entry.count += 1;
|
|
45
|
+
this._store.set(key, entry);
|
|
46
|
+
return { allowed: entry.count <= max, remaining: Math.max(0, max - entry.count), resetAt: entry.resetAt };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async reset(key) {
|
|
50
|
+
this._store.delete(key);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Drops the oldest counters below their limit — a batch, so a full store isn't scanned per request. */
|
|
54
|
+
_evictUnexhausted() {
|
|
55
|
+
let toEvict = Math.max(1, Math.ceil(this._maxKeys / 100));
|
|
56
|
+
for (const [key, entry] of this._store) {
|
|
57
|
+
if (toEvict === 0) break;
|
|
58
|
+
if (entry.count < (entry.max ?? Infinity)) {
|
|
59
|
+
this._store.delete(key);
|
|
60
|
+
toEvict -= 1;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
_sweep() {
|
|
66
|
+
const now = Date.now();
|
|
67
|
+
for (const [key, entry] of this._store) {
|
|
68
|
+
if (entry.resetAt <= now) this._store.delete(key);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
close() {
|
|
73
|
+
clearInterval(this._sweepInterval);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { BaseRateLimiter } from './rate-limiter.js';
|
|
2
|
+
|
|
3
|
+
/** Used when `config.rateLimiting.enabled === false` — every check passes, no storage touched. */
|
|
4
|
+
export class NoopRateLimiter extends BaseRateLimiter {
|
|
5
|
+
async check() {
|
|
6
|
+
return { allowed: true, remaining: Infinity, resetAt: 0 };
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
async increment() {
|
|
10
|
+
return { allowed: true, remaining: Infinity, resetAt: 0 };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
async reset() {}
|
|
14
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @typedef {Object} RateLimitResult
|
|
3
|
+
* @property {boolean} allowed
|
|
4
|
+
* @property {number} remaining
|
|
5
|
+
* @property {number} resetAt - epoch ms when the window resets
|
|
6
|
+
*
|
|
7
|
+
* @typedef {Object} RateLimiter
|
|
8
|
+
* @property {(key: string) => Promise<RateLimitResult>} check - read-only peek, does not consume an attempt
|
|
9
|
+
* @property {(key: string, opts: {max: number, windowSeconds: number}) => Promise<RateLimitResult>} increment - atomically consumes one attempt against a fixed window, creating it if absent
|
|
10
|
+
* @property {(key: string) => Promise<void>} reset - clears a key (e.g. on successful login)
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Base class purely for documentation / instanceof checks — adapters aren't required to extend it. */
|
|
14
|
+
export class BaseRateLimiter {
|
|
15
|
+
async check(_key) { throw new Error('RateLimiter.check() not implemented'); }
|
|
16
|
+
async increment(_key, _opts) { throw new Error('RateLimiter.increment() not implemented'); }
|
|
17
|
+
async reset(_key) { throw new Error('RateLimiter.reset() not implemented'); }
|
|
18
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { BaseRateLimiter } from './rate-limiter.js';
|
|
2
|
+
|
|
3
|
+
// Atomic incr-and-maybe-set-expiry, so a concurrent burst of requests can
|
|
4
|
+
// never race past the check the way a separate INCR + EXPIRE pair could.
|
|
5
|
+
// The expiry is set whenever the key has none (TTL -1), not only on the first
|
|
6
|
+
// increment: if that EXPIRE ever failed after INCR committed, the key would
|
|
7
|
+
// otherwise never expire and its owner would stay limited forever.
|
|
8
|
+
const INCREMENT_SCRIPT = `
|
|
9
|
+
local count = redis.call('INCR', KEYS[1])
|
|
10
|
+
if redis.call('TTL', KEYS[1]) == -1 then
|
|
11
|
+
redis.call('EXPIRE', KEYS[1], ARGV[1])
|
|
12
|
+
end
|
|
13
|
+
local ttl = redis.call('TTL', KEYS[1])
|
|
14
|
+
return { count, ttl }
|
|
15
|
+
`;
|
|
16
|
+
|
|
17
|
+
export class RedisRateLimiter extends BaseRateLimiter {
|
|
18
|
+
/** @param {{ redis: import('ioredis').Redis }} opts - a connected ioredis client, shared or dedicated */
|
|
19
|
+
constructor({ redis } = {}) {
|
|
20
|
+
super();
|
|
21
|
+
if (!redis) throw new Error('RedisRateLimiter requires a connected ioredis client instance (pass via { redis })');
|
|
22
|
+
this._redis = redis;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async check(key) {
|
|
26
|
+
const [raw, ttl] = await Promise.all([this._redis.get(key), this._redis.ttl(key)]);
|
|
27
|
+
const count = raw ? Number(raw) : 0;
|
|
28
|
+
return { allowed: true, remaining: Infinity, resetAt: ttl > 0 ? Date.now() + ttl * 1000 : 0, count };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async increment(key, { max, windowSeconds }) {
|
|
32
|
+
const [count, ttl] = await this._redis.eval(INCREMENT_SCRIPT, 1, key, Math.max(1, Math.ceil(windowSeconds)));
|
|
33
|
+
const resetAt = Date.now() + Math.max(ttl, 0) * 1000;
|
|
34
|
+
return { allowed: count <= max, remaining: Math.max(0, max - count), resetAt };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async reset(key) {
|
|
38
|
+
await this._redis.del(key);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* @param {{ redis?: import('ioredis').Redis, host?: string, port?: number, password?: string, db?: number }} opts
|
|
44
|
+
* Pass an existing connected client via `redis` to share the cache
|
|
45
|
+
* adapter's connection; otherwise a new one is created from host/port/etc,
|
|
46
|
+
* dynamically importing `ioredis` (peerDependency, only loaded if used).
|
|
47
|
+
*/
|
|
48
|
+
export async function createRedisRateLimiter(opts = {}) {
|
|
49
|
+
if (opts.redis) return new RedisRateLimiter({ redis: opts.redis });
|
|
50
|
+
if (!opts.host) {
|
|
51
|
+
throw new Error('Rate limiter adapter "redis" needs config.rateLimiting.redis.host, or config.cache.adapter "redis" to share its connection — refusing to connect to an unconfigured localhost');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
let IORedis;
|
|
55
|
+
try {
|
|
56
|
+
({ default: IORedis } = await import('ioredis'));
|
|
57
|
+
} catch {
|
|
58
|
+
throw new Error(
|
|
59
|
+
'Rate limiter adapter "redis" was configured but the "ioredis" peer dependency is not installed. ' +
|
|
60
|
+
'Run `npm install ioredis`, share an existing client via config.rateLimiting.redis, or switch to "memory".'
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const redis = new IORedis({
|
|
65
|
+
host: opts.host, port: opts.port, username: opts.username, password: opts.password, db: opts.db ?? 0,
|
|
66
|
+
...(opts.tls ? { tls: opts.tls === true ? {} : opts.tls } : {}),
|
|
67
|
+
lazyConnect: true, maxRetriesPerRequest: 3,
|
|
68
|
+
});
|
|
69
|
+
await redis.connect();
|
|
70
|
+
return new RedisRateLimiter({ redis });
|
|
71
|
+
}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import express from 'express';
|
|
2
|
+
|
|
3
|
+
import { authContextMiddleware } from '../middleware/auth-context.middleware.js';
|
|
4
|
+
import { requireRecentAuth } from '../middleware/require-recent-auth.middleware.js';
|
|
5
|
+
import { serviceContextMiddleware } from '../middleware/service-context.middleware.js';
|
|
6
|
+
import { validateBody } from '../middleware/validate-body.js';
|
|
7
|
+
import { validateQuery } from '../middleware/validate-query.js';
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
registerHandler, verifyEmailHandler, resendVerificationEmailHandler,
|
|
11
|
+
loginHandler, refreshTokenHandler, logoutHandler, logoutAllHandler,
|
|
12
|
+
forgotPasswordHandler, resetPasswordHandler, changePasswordHandler,
|
|
13
|
+
getMeHandler, updateMeHandler, deleteMeHandler,
|
|
14
|
+
listSessionsHandler, revokeSessionHandler, revokeAllSessionsHandler,
|
|
15
|
+
} from '../password-auth/controllers.js';
|
|
16
|
+
import {
|
|
17
|
+
registerSchema, verifyEmailSchema, resendVerificationSchema, loginSchema,
|
|
18
|
+
forgotPasswordSchema, resetPasswordSchema, changePasswordSchema, logoutSchema, refreshSchema, updateProfileSchema,
|
|
19
|
+
} from '../password-auth/schemas.js';
|
|
20
|
+
|
|
21
|
+
import { requestMagicLinkHandler, verifyMagicLinkHandler } from '../magic-link/controller.js';
|
|
22
|
+
import { requestMagicLinkSchema, verifyMagicLinkSchema } from '../magic-link/schemas.js';
|
|
23
|
+
|
|
24
|
+
import { generateRegistrationOptionsHandler, verifyRegistrationHandler, listPasskeysHandler, deletePasskeyHandler } from '../webauthn/registration.controller.js';
|
|
25
|
+
import { generateAuthenticationOptionsHandler, verifyAuthenticationHandler } from '../webauthn/authentication.controller.js';
|
|
26
|
+
import { generateMfaWebauthnChallengeOptionsHandler, verifyMfaWebauthnChallengeHandler } from '../webauthn/mfa.controller.js';
|
|
27
|
+
import {
|
|
28
|
+
registrationOptionsSchema, verifyRegistrationSchema, authenticationOptionsSchema,
|
|
29
|
+
verifyAuthenticationSchema, mfaWebauthnOptionsSchema, verifyMfaWebauthnSchema,
|
|
30
|
+
} from '../webauthn/schemas.js';
|
|
31
|
+
|
|
32
|
+
import {
|
|
33
|
+
getMfaStatusHandler, setupMfaHandler, confirmMfaHandler, disableMfaHandler,
|
|
34
|
+
regenerateRecoveryCodesHandler, verifyMfaChallengeHandler,
|
|
35
|
+
} from '../mfa/controller.js';
|
|
36
|
+
import { confirmMfaSchema, disableMfaSchema, regenerateRecoveryCodesSchema, verifyMfaChallengeSchema } from '../mfa/schemas.js';
|
|
37
|
+
|
|
38
|
+
import { authorizeHandler, confirmConsentHandler, denyConsentHandler } from '../oauth2/authorize.controller.js';
|
|
39
|
+
import { tokenHandler, revokeTokenHandler, introspectTokenHandler } from '../oauth2/token.controller.js';
|
|
40
|
+
import { getConsentHandler, listConsentsHandler, revokeConsentHandler } from '../oauth2/consent.controller.js';
|
|
41
|
+
import {
|
|
42
|
+
registerOAuthClientHandler, getOAuthClientHandler, listOAuthClientsHandler, updateOAuthClientHandler,
|
|
43
|
+
rotateOAuthClientSecretHandler, deactivateOAuthClientHandler, approveOAuthClientHandler,
|
|
44
|
+
} from '../oauth2/client.controller.js';
|
|
45
|
+
import {
|
|
46
|
+
authorizeQuerySchema, confirmAuthorizeSchema, denyAuthorizeSchema, tokenSchema, revokeTokenSchema,
|
|
47
|
+
introspectTokenSchema, registerOAuthClientSchema, updateOAuthClientSchema, consentQuerySchema,
|
|
48
|
+
} from '../oauth2/schemas.js';
|
|
49
|
+
|
|
50
|
+
import { userinfoHandler } from '../oidc/userinfo.controller.js';
|
|
51
|
+
import { endSessionHandler } from '../oidc/end-session.controller.js';
|
|
52
|
+
import { openidConfigurationHandler } from '../oidc/discovery.controller.js';
|
|
53
|
+
|
|
54
|
+
import { initiateSsoHandler } from '../sso/initiate.controller.js';
|
|
55
|
+
import { ssoCallbackHandler } from '../sso/callback.controller.js';
|
|
56
|
+
import { ssoInitiateQuerySchema } from '../sso/schemas.js';
|
|
57
|
+
|
|
58
|
+
import { jwksHandler, authPublicKeyHandler } from '../signing/jwks.controller.js';
|
|
59
|
+
import { registerServiceKeyHandler, getServicesJwksHandler } from '../service-mesh/service-key.controller.js';
|
|
60
|
+
import { s2sBootstrapMiddleware } from '../service-mesh/s2s-bootstrap.middleware.js';
|
|
61
|
+
|
|
62
|
+
const FEATURE_NAMES = ['magicLink', 'webauthn', 'sso', 'oauth2', 'oidc', 'serviceMesh'];
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Assembles a fully-wired `express.Router()` covering the routes this
|
|
66
|
+
* package implements, using sensible default paths. Entirely optional — if
|
|
67
|
+
* your app wants different paths or custom rate limiting, mount the
|
|
68
|
+
* individual handler exports on your own router instead of calling this.
|
|
69
|
+
*
|
|
70
|
+
* @param {object} [opts]
|
|
71
|
+
* @param {{ middleware: import('express').RequestHandler | import('express').RequestHandler[] }} [opts.clientManagement]
|
|
72
|
+
* OAuth2 client (relying-party) administration — register, list, get,
|
|
73
|
+
* update, approve, rotate-secret, deactivate under `/oauth2/clients`. NOT
|
|
74
|
+
* mounted unless this is given, because this package has no admin-role
|
|
75
|
+
* concept of its own: you supply the admin authentication/authorization as
|
|
76
|
+
* `middleware`, which runs before every one of those routes. At least one
|
|
77
|
+
* middleware is required — passing `clientManagement` without any throws.
|
|
78
|
+
* @param {Partial<Record<'magicLink'|'webauthn'|'sso'|'oauth2'|'oidc'|'serviceMesh', boolean>>} [opts.features]
|
|
79
|
+
* Set a surface to `false` to leave its routes unmounted. Everything
|
|
80
|
+
* defaults to `true` (mounted).
|
|
81
|
+
*/
|
|
82
|
+
export function buildRouter(opts = {}) {
|
|
83
|
+
const features = resolveFeatures(opts.features);
|
|
84
|
+
const clientManagementMiddleware = resolveClientManagement(opts.clientManagement);
|
|
85
|
+
const router = express.Router();
|
|
86
|
+
|
|
87
|
+
// Every response here may carry tokens, codes or account data: never cache it. Discovery and
|
|
88
|
+
// JWKS handlers set their own (public) Cache-Control, overriding this.
|
|
89
|
+
router.use((_req, res, next) => {
|
|
90
|
+
res.set('Cache-Control', 'no-store');
|
|
91
|
+
next();
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
// Password / email identity
|
|
95
|
+
router.post('/register', validateBody(registerSchema), registerHandler);
|
|
96
|
+
router.post('/register/verify-email', validateBody(verifyEmailSchema), verifyEmailHandler);
|
|
97
|
+
router.post('/register/resend-verification', validateBody(resendVerificationSchema), resendVerificationEmailHandler);
|
|
98
|
+
router.post('/login', validateBody(loginSchema), loginHandler);
|
|
99
|
+
router.post('/mfa/verify', validateBody(verifyMfaChallengeSchema), verifyMfaChallengeHandler);
|
|
100
|
+
// Everything that reads the refresh cookie lives under /session — the only path it is sent to
|
|
101
|
+
// (see utils/cookies.js readRefreshCookie).
|
|
102
|
+
router.post('/session/refresh', validateBody(refreshSchema), refreshTokenHandler);
|
|
103
|
+
router.post('/session/logout', validateBody(logoutSchema), logoutHandler); // refreshToken in the body OR the httpOnly cookie
|
|
104
|
+
router.post('/session/logout/all', authContextMiddleware(), logoutAllHandler);
|
|
105
|
+
router.post('/password/forgot', validateBody(forgotPasswordSchema), forgotPasswordHandler);
|
|
106
|
+
router.post('/password/reset', validateBody(resetPasswordSchema), resetPasswordHandler);
|
|
107
|
+
router.post('/password/change', authContextMiddleware(), validateBody(changePasswordSchema), changePasswordHandler);
|
|
108
|
+
|
|
109
|
+
// Magic link (passwordless email login)
|
|
110
|
+
if (features.magicLink) {
|
|
111
|
+
router.post('/magic-link/request', validateBody(requestMagicLinkSchema), requestMagicLinkHandler);
|
|
112
|
+
router.post('/magic-link/verify', validateBody(verifyMagicLinkSchema), verifyMagicLinkHandler);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Self-service identity ("me")
|
|
116
|
+
router.get('/me', authContextMiddleware(), getMeHandler);
|
|
117
|
+
router.patch('/me', authContextMiddleware(), validateBody(updateProfileSchema), updateMeHandler);
|
|
118
|
+
router.delete('/me', authContextMiddleware(), requireRecentAuth(), deleteMeHandler);
|
|
119
|
+
router.get('/me/sessions', authContextMiddleware(), listSessionsHandler);
|
|
120
|
+
router.delete('/me/sessions/:id', authContextMiddleware(), revokeSessionHandler);
|
|
121
|
+
router.delete('/me/sessions', authContextMiddleware(), revokeAllSessionsHandler);
|
|
122
|
+
|
|
123
|
+
// MFA
|
|
124
|
+
router.get('/me/mfa', authContextMiddleware(), getMfaStatusHandler);
|
|
125
|
+
// Enrolling a second factor requires a recent login: otherwise a stolen session could enrol
|
|
126
|
+
// the attacker's authenticator on an account that has none, locking the owner out.
|
|
127
|
+
router.post('/me/mfa/setup', authContextMiddleware(), requireRecentAuth(), setupMfaHandler);
|
|
128
|
+
router.post('/me/mfa/confirm', authContextMiddleware(), requireRecentAuth(), validateBody(confirmMfaSchema), confirmMfaHandler);
|
|
129
|
+
router.delete('/me/mfa', authContextMiddleware(), validateBody(disableMfaSchema), disableMfaHandler);
|
|
130
|
+
router.post('/me/mfa/recovery-codes', authContextMiddleware(), validateBody(regenerateRecoveryCodesSchema), regenerateRecoveryCodesHandler);
|
|
131
|
+
|
|
132
|
+
if (features.webauthn) {
|
|
133
|
+
// WebAuthn / passkeys — registering a credential requires an authenticated caller who
|
|
134
|
+
// logged in recently: a passkey is a permanent login, so a stolen session must not be
|
|
135
|
+
// able to add one.
|
|
136
|
+
router.post('/webauthn/registration/options', authContextMiddleware(), requireRecentAuth(), validateBody(registrationOptionsSchema), generateRegistrationOptionsHandler);
|
|
137
|
+
router.post('/webauthn/registration/verify', authContextMiddleware(), requireRecentAuth(), validateBody(verifyRegistrationSchema), verifyRegistrationHandler);
|
|
138
|
+
router.get('/me/passkeys', authContextMiddleware(), listPasskeysHandler);
|
|
139
|
+
router.delete('/me/passkeys/:credentialId', authContextMiddleware(), requireRecentAuth(), deletePasskeyHandler);
|
|
140
|
+
|
|
141
|
+
// Primary passwordless login — no prior auth required.
|
|
142
|
+
router.post('/webauthn/authentication/options', validateBody(authenticationOptionsSchema), generateAuthenticationOptionsHandler);
|
|
143
|
+
router.post('/webauthn/authentication/verify', validateBody(verifyAuthenticationSchema), verifyAuthenticationHandler);
|
|
144
|
+
|
|
145
|
+
// Passkey as an MFA second factor — completes the challenge loginHandler
|
|
146
|
+
// issued when user.mfaEnabled, as an alternative to /mfa/verify (TOTP).
|
|
147
|
+
router.post('/webauthn/mfa/options', validateBody(mfaWebauthnOptionsSchema), generateMfaWebauthnChallengeOptionsHandler);
|
|
148
|
+
router.post('/webauthn/mfa/verify', validateBody(verifyMfaWebauthnSchema), verifyMfaWebauthnChallengeHandler);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// OAuth2 authorization server
|
|
152
|
+
if (features.oauth2) {
|
|
153
|
+
router.get('/oauth2/authorize', validateQuery(authorizeQuerySchema), authContextMiddleware({ optional: true }), authorizeHandler);
|
|
154
|
+
router.post('/oauth2/authorize/confirm', authContextMiddleware(), validateBody(confirmAuthorizeSchema), confirmConsentHandler);
|
|
155
|
+
router.post('/oauth2/authorize/deny', authContextMiddleware(), validateBody(denyAuthorizeSchema), denyConsentHandler);
|
|
156
|
+
router.post('/oauth2/token', validateBody(tokenSchema), tokenHandler);
|
|
157
|
+
router.post('/oauth2/token/revoke', validateBody(revokeTokenSchema), revokeTokenHandler);
|
|
158
|
+
// Revoke and introspect authenticate the calling client (RFC 7009 / RFC 7662), not a user.
|
|
159
|
+
router.post('/oauth2/token/introspect', validateBody(introspectTokenSchema), introspectTokenHandler);
|
|
160
|
+
router.get('/oauth2/consent', authContextMiddleware(), validateQuery(consentQuerySchema), getConsentHandler);
|
|
161
|
+
router.get('/oauth2/consent/sessions', authContextMiddleware(), listConsentsHandler);
|
|
162
|
+
router.delete('/oauth2/consent/sessions/:clientId', authContextMiddleware(), revokeConsentHandler);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// OAuth2 client (relying party) management — only behind the caller's
|
|
166
|
+
// own admin middleware, never by default. Every route lives on a
|
|
167
|
+
// sub-router whose first handlers are that middleware, so nothing under
|
|
168
|
+
// /oauth2/clients is reachable without passing it.
|
|
169
|
+
if (clientManagementMiddleware) {
|
|
170
|
+
const clients = express.Router();
|
|
171
|
+
clients.use(...clientManagementMiddleware);
|
|
172
|
+
clients.post('/', validateBody(registerOAuthClientSchema), registerOAuthClientHandler);
|
|
173
|
+
clients.get('/', listOAuthClientsHandler);
|
|
174
|
+
clients.get('/:clientId', getOAuthClientHandler);
|
|
175
|
+
clients.patch('/:clientId', validateBody(updateOAuthClientSchema), updateOAuthClientHandler);
|
|
176
|
+
clients.post('/:clientId/approve', approveOAuthClientHandler);
|
|
177
|
+
clients.post('/:clientId/rotate-secret', rotateOAuthClientSecretHandler);
|
|
178
|
+
clients.delete('/:clientId', deactivateOAuthClientHandler);
|
|
179
|
+
router.use('/oauth2/clients', clients);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// OIDC
|
|
183
|
+
if (features.oidc) {
|
|
184
|
+
// The one IdP route a relying party calls with the access token it was issued.
|
|
185
|
+
router.get('/userinfo', authContextMiddleware({ accept: ['oauth2-user'] }), userinfoHandler);
|
|
186
|
+
router.get('/session/end', authContextMiddleware({ optional: true }), endSessionHandler);
|
|
187
|
+
// The confirmed form of the same request (see end-session.controller.js) — JSON or an HTML form.
|
|
188
|
+
router.post('/session/end', express.urlencoded({ extended: false }), authContextMiddleware({ optional: true }), endSessionHandler);
|
|
189
|
+
router.get('/.well-known/openid-configuration', openidConfigurationHandler);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// SSO
|
|
193
|
+
if (features.sso) {
|
|
194
|
+
router.get('/sso/:provider', validateQuery(ssoInitiateQuerySchema), initiateSsoHandler);
|
|
195
|
+
router.get('/sso/:provider/callback', ssoCallbackHandler);
|
|
196
|
+
router.post('/sso/:provider/callback', express.urlencoded({ extended: false }), ssoCallbackHandler);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// JWKS — always mounted: every relying party and resource server needs
|
|
200
|
+
// these to verify the access tokens this IdP issues.
|
|
201
|
+
router.get('/.well-known/jwks.json', jwksHandler);
|
|
202
|
+
router.get('/keys/:kid', authPublicKeyHandler);
|
|
203
|
+
|
|
204
|
+
// Service mesh (S2S JWKS trust)
|
|
205
|
+
if (features.serviceMesh) {
|
|
206
|
+
router.post('/internal/service-keys', s2sBootstrapMiddleware, registerServiceKeyHandler);
|
|
207
|
+
router.get('/.well-known/services-jwks.json', getServicesJwksHandler);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return router;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function resolveFeatures(input = {}) {
|
|
214
|
+
if (input === null || typeof input !== 'object') throw new Error('buildRouter: opts.features must be an object');
|
|
215
|
+
const unknown = Object.keys(input).filter((k) => !FEATURE_NAMES.includes(k));
|
|
216
|
+
if (unknown.length > 0) {
|
|
217
|
+
throw new Error(`buildRouter: unknown opts.features key(s): ${unknown.join(', ')} — expected any of ${FEATURE_NAMES.join(', ')}`);
|
|
218
|
+
}
|
|
219
|
+
return Object.fromEntries(FEATURE_NAMES.map((name) => [name, input[name] !== false]));
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** null when client management isn't requested; otherwise the validated, non-empty middleware list. Misconfiguration throws at startup rather than mounting the routes open. */
|
|
223
|
+
function resolveClientManagement(input) {
|
|
224
|
+
if (input === undefined || input === null || input === false) return null;
|
|
225
|
+
const list = typeof input.middleware === 'function' ? [input.middleware] : input.middleware;
|
|
226
|
+
if (!Array.isArray(list) || list.length === 0) {
|
|
227
|
+
throw new Error(
|
|
228
|
+
'buildRouter: opts.clientManagement requires at least one middleware (your admin authentication/authorization) ' +
|
|
229
|
+
'in opts.clientManagement.middleware — the OAuth2 client routes are never mounted unauthenticated.'
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
if (!list.every((fn) => typeof fn === 'function')) {
|
|
233
|
+
throw new Error('buildRouter: every entry in opts.clientManagement.middleware must be a middleware function');
|
|
234
|
+
}
|
|
235
|
+
return list;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export { serviceContextMiddleware }; // re-exported for building your own protected internal routes alongside this router
|