@okeav/idp-pg 0.0.0-stage → 0.1.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 +58 -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 +48 -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 +777 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { getState } from '../config/state.js';
|
|
2
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
3
|
+
import { AesGcmSecretCipher } from './secret-cipher.js';
|
|
4
|
+
|
|
5
|
+
// otplib's generateSecret() emits RFC 4648 base32. Anything of that shape is
|
|
6
|
+
// a secret written before encryption at rest existed (≤0.2.x); everything
|
|
7
|
+
// else is ciphertext. The built-in format always contains ':', which base32
|
|
8
|
+
// never does.
|
|
9
|
+
const PLAINTEXT_SECRET = /^[A-Z2-7]+=*$/i;
|
|
10
|
+
|
|
11
|
+
export function isPlaintextMfaSecret(value) {
|
|
12
|
+
return typeof value === 'string' && PLAINTEXT_SECRET.test(value);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** `config.mfa.secretCipher` wins; otherwise `encryptionKey` builds the AES-256-GCM cipher; otherwise null. */
|
|
16
|
+
export function createMfaSecretCipher(mfaConfig = {}) {
|
|
17
|
+
if (mfaConfig.secretCipher) {
|
|
18
|
+
const c = mfaConfig.secretCipher;
|
|
19
|
+
if (typeof c.encrypt !== 'function' || typeof c.decrypt !== 'function') {
|
|
20
|
+
throw new Error('config.mfa.secretCipher must implement encrypt(plaintext, { context }) and decrypt(ciphertext, { context })');
|
|
21
|
+
}
|
|
22
|
+
return c;
|
|
23
|
+
}
|
|
24
|
+
if (mfaConfig.encryptionKey) {
|
|
25
|
+
return new AesGcmSecretCipher({ currentKey: mfaConfig.encryptionKey, previousKeys: mfaConfig.previousEncryptionKeys || [] });
|
|
26
|
+
}
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Startup validation — called from initIdentityProvider(). MFA is on by
|
|
32
|
+
* default, so a deployment that never set a key fails here, on boot, rather
|
|
33
|
+
* than silently writing TOTP secrets in plain text.
|
|
34
|
+
*/
|
|
35
|
+
export function assertMfaSecretConfig(mfaConfig, cipher, logger) {
|
|
36
|
+
if (mfaConfig.requireEncrypted && !cipher) {
|
|
37
|
+
throw new Error('config.mfa.requireEncrypted is set but no config.mfa.encryptionKey or config.mfa.secretCipher is configured');
|
|
38
|
+
}
|
|
39
|
+
if (!mfaConfig.enabled || cipher) return;
|
|
40
|
+
if (!mfaConfig.allowPlaintext) {
|
|
41
|
+
throw new Error(
|
|
42
|
+
'MFA secrets must be encrypted at rest: set config.mfa.encryptionKey (32 bytes, base64 — `openssl rand -base64 32`) ' +
|
|
43
|
+
'or config.mfa.secretCipher. For local development only, config.mfa.allowPlaintext: true opts out. ' +
|
|
44
|
+
'If this deployment does not use TOTP MFA at all, set config.mfa.enabled: false.'
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
logger?.warn?.(
|
|
48
|
+
{},
|
|
49
|
+
'!!! @okeav/idp-pg: config.mfa.allowPlaintext is ON — TOTP secrets are being stored UNENCRYPTED. ' +
|
|
50
|
+
'Development use only. Set config.mfa.encryptionKey before deploying anywhere real. !!!'
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Encrypts a TOTP secret for storage. Plain text only when the app explicitly opted into `allowPlaintext` and has no key. */
|
|
55
|
+
export async function sealMfaSecret(state, plaintext, userId) {
|
|
56
|
+
if (state.mfaCipher) {
|
|
57
|
+
const sealed = await state.mfaCipher.encrypt(plaintext, { context: String(userId) });
|
|
58
|
+
// Stored verbatim — and a bare base32 string is how a legacy plain-text secret is recognised, so a
|
|
59
|
+
// custom cipher that returned one would have its output read back as the secret itself.
|
|
60
|
+
if (typeof sealed !== 'string' || sealed.length === 0 || /^[A-Z2-7]+=*$/i.test(sealed)) {
|
|
61
|
+
throw new IdpError({ code: 'MFA_SECRET_UNREADABLE', httpStatus: 500, message: 'config.mfa.secretCipher.encrypt() must return a non-empty string that is not bare base32 (prefix it, e.g. "kms:")' });
|
|
62
|
+
}
|
|
63
|
+
return sealed;
|
|
64
|
+
}
|
|
65
|
+
if (state.config.mfa.allowPlaintext) return plaintext;
|
|
66
|
+
throw new IdpError({ code: 'MFA_ENCRYPTION_NOT_CONFIGURED', httpStatus: 500, message: 'MFA secret encryption is not configured' });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Reads a stored TOTP secret. Fails closed: undecryptable ciphertext (tampered,
|
|
71
|
+
* wrong key, copied from another user) throws rather than being treated as
|
|
72
|
+
* "no secret". `needsUpgrade` is true for a legacy plain-text value (or one
|
|
73
|
+
* under a retired key) that the caller should re-seal after a successful verify.
|
|
74
|
+
*
|
|
75
|
+
* @returns {Promise<{ secret: string, needsUpgrade: boolean } | null>}
|
|
76
|
+
*/
|
|
77
|
+
export async function openMfaSecret(state, stored, userId) {
|
|
78
|
+
if (!stored) return null;
|
|
79
|
+
const cipher = state.mfaCipher;
|
|
80
|
+
|
|
81
|
+
if (isPlaintextMfaSecret(stored)) {
|
|
82
|
+
if (state.config.mfa.requireEncrypted) {
|
|
83
|
+
state.logger?.error?.({ userId: String(userId) }, 'Refusing a plain-text MFA secret (config.mfa.requireEncrypted is set) — run migrateMfaSecrets()');
|
|
84
|
+
throw new IdpError({ code: 'MFA_SECRET_NOT_ENCRYPTED', httpStatus: 500, message: 'MFA secret is not encrypted' });
|
|
85
|
+
}
|
|
86
|
+
return { secret: stored, needsUpgrade: Boolean(cipher) };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (!cipher) {
|
|
90
|
+
throw new IdpError({ code: 'MFA_ENCRYPTION_NOT_CONFIGURED', httpStatus: 500, message: 'MFA secret is encrypted but no key is configured' });
|
|
91
|
+
}
|
|
92
|
+
let secret;
|
|
93
|
+
try {
|
|
94
|
+
secret = await cipher.decrypt(stored, { context: String(userId) });
|
|
95
|
+
} catch (cause) {
|
|
96
|
+
state.logger?.error?.({ userId: String(userId), err: cause }, 'Failed to decrypt MFA secret — tampered, wrong key, or key id not configured');
|
|
97
|
+
throw new IdpError({ code: 'MFA_SECRET_UNREADABLE', httpStatus: 500, message: 'Unable to read MFA secret', cause });
|
|
98
|
+
}
|
|
99
|
+
return { secret, needsUpgrade: typeof cipher.needsRotation === 'function' && cipher.needsRotation(stored) === true };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Encrypts every plain-text `mfaSecret`/`mfaTempSecret` in one pass, and
|
|
104
|
+
* re-encrypts any written under a non-current key. Idempotent and safe to
|
|
105
|
+
* run while the app is serving traffic (a concurrent lazy re-encryption
|
|
106
|
+
* writes an equivalent value). Users created during the run are already
|
|
107
|
+
* written encrypted, so a page that shifts under it skips nothing that matters.
|
|
108
|
+
*
|
|
109
|
+
* Works with any storage adapter: it only uses `countAll`, `findMany`,
|
|
110
|
+
* `findById` and `updateById`.
|
|
111
|
+
*
|
|
112
|
+
* @param {{ batchSize?: number, dryRun?: boolean }} [opts]
|
|
113
|
+
* @returns {Promise<{ scanned: number, encrypted: number, reencrypted: number, failed: Array<{ userId: string, error: string }> }>}
|
|
114
|
+
*/
|
|
115
|
+
export async function migrateMfaSecrets({ batchSize = 100, dryRun = false } = {}) {
|
|
116
|
+
const state = getState();
|
|
117
|
+
const cipher = state.mfaCipher;
|
|
118
|
+
if (!cipher) throw new Error('migrateMfaSecrets() needs config.mfa.encryptionKey or config.mfa.secretCipher');
|
|
119
|
+
const repo = state.storage.userRepository;
|
|
120
|
+
|
|
121
|
+
const total = await repo.countAll();
|
|
122
|
+
const ids = new Set();
|
|
123
|
+
for (let skip = 0; skip < total; skip += batchSize) {
|
|
124
|
+
const page = await repo.findMany({ skip, limit: batchSize });
|
|
125
|
+
if (!page.length) break;
|
|
126
|
+
for (const u of page) ids.add(String(u.id ?? u._id));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const result = { scanned: 0, encrypted: 0, reencrypted: 0, failed: [] };
|
|
130
|
+
for (const userId of ids) {
|
|
131
|
+
result.scanned += 1;
|
|
132
|
+
try {
|
|
133
|
+
const user = await repo.findById(userId, { select: '+mfaSecret +mfaTempSecret' });
|
|
134
|
+
if (!user) continue;
|
|
135
|
+
const patch = {};
|
|
136
|
+
for (const field of ['mfaSecret', 'mfaTempSecret']) {
|
|
137
|
+
const stored = user[field];
|
|
138
|
+
if (!stored) continue;
|
|
139
|
+
if (isPlaintextMfaSecret(stored)) {
|
|
140
|
+
patch[field] = await cipher.encrypt(stored, { context: userId });
|
|
141
|
+
result.encrypted += 1;
|
|
142
|
+
} else if (typeof cipher.needsRotation === 'function' && cipher.needsRotation(stored)) {
|
|
143
|
+
const plaintext = await cipher.decrypt(stored, { context: userId });
|
|
144
|
+
patch[field] = await cipher.encrypt(plaintext, { context: userId });
|
|
145
|
+
result.reencrypted += 1;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (!dryRun && Object.keys(patch).length > 0) await repo.updateById(userId, patch);
|
|
149
|
+
} catch (err) {
|
|
150
|
+
result.failed.push({ userId, error: err.message });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
state.logger?.info?.({ ...result, failed: result.failed.length, dryRun }, 'migrateMfaSecrets finished');
|
|
155
|
+
return result;
|
|
156
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { getState } from '../config/state.js';
|
|
2
|
+
import { verifyAccessToken, classifyAccessToken } from '../signing/token.service.js';
|
|
3
|
+
import { isRevoked } from '../cache/index.js';
|
|
4
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
5
|
+
import { CACHE_KEY_PREFIXES, COOKIE_NAMES, ACCESS_TOKEN_KINDS, GRANT_TYPES, OAUTH_CLIENT_STATUS } from '../config/constants.js';
|
|
6
|
+
import { readSessionCookie } from '../utils/cookies.js';
|
|
7
|
+
import { assertTrustedOrigin } from './csrf.js';
|
|
8
|
+
|
|
9
|
+
function parseBearer(header) {
|
|
10
|
+
if (!header || typeof header !== 'string') return null;
|
|
11
|
+
const match = header.match(/^Bearer\s+(.+)$/i);
|
|
12
|
+
return match ? match[1].trim() : null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Authenticates the caller and sets `req.auth = { userId, email, claims, tokenMeta }`.
|
|
17
|
+
* `claims` is whatever opaque object the consumer put on the token at issuance
|
|
18
|
+
* (role/scopes/capabilities/tenant id/anything) — this package never reads it.
|
|
19
|
+
*
|
|
20
|
+
* Accepts either the `access_token` cookie (browser flows, paired with
|
|
21
|
+
* `cookieParser()`) or an `Authorization: Bearer` header (API/service
|
|
22
|
+
* clients). This is broader than the audited source, which only supported
|
|
23
|
+
* cookies plus a BFF-forwarded-context header — see the Phase 3 report for
|
|
24
|
+
* why the forwarded-header mode and the replay-nonce/timestamp check were
|
|
25
|
+
* dropped rather than ported.
|
|
26
|
+
*
|
|
27
|
+
* @param {{ issuer?: string, optional?: boolean }} [opts] - `optional: true`
|
|
28
|
+
* populates `req.auth` when a valid token is present but calls `next()`
|
|
29
|
+
* with no error (and `req.auth` left `undefined`) when no token is
|
|
30
|
+
* presented at all, instead of rejecting. A malformed/expired/revoked
|
|
31
|
+
* token still rejects even in optional mode — "optional" means "anonymous
|
|
32
|
+
* is allowed," not "an invalid token is silently ignored." Needed by
|
|
33
|
+
* endpoints like `/oauth2/authorize` that behave differently for
|
|
34
|
+
* logged-in vs anonymous callers rather than requiring auth outright.
|
|
35
|
+
* @param {Array<'first-party'|'oauth2-user'|'oauth2-client'>} [opts.accept] - which kinds of
|
|
36
|
+
* access token are credentials here. Default `['first-party']`: a token this IdP issued to a
|
|
37
|
+
* third-party OAuth2 client is never accepted on the IdP's own routes. A resource server that
|
|
38
|
+
* serves OAuth2 clients opts in with `accept: ['oauth2-user']` (and/or `'oauth2-client'` for
|
|
39
|
+
* client_credentials machine tokens) — then check `req.auth.scopes`.
|
|
40
|
+
* @param {string|string[]} [opts.audience] - the `aud` a first-party token must carry (default: the issuer).
|
|
41
|
+
*/
|
|
42
|
+
export function authContextMiddleware(opts = {}) {
|
|
43
|
+
const accept = opts.accept ?? [ACCESS_TOKEN_KINDS.FIRST_PARTY];
|
|
44
|
+
if (!Array.isArray(accept) || accept.length === 0 || accept.some((k) => !Object.values(ACCESS_TOKEN_KINDS).includes(k))) {
|
|
45
|
+
throw new Error(`authContextMiddleware: opts.accept must be a non-empty array of ${Object.values(ACCESS_TOKEN_KINDS).join(', ')}`);
|
|
46
|
+
}
|
|
47
|
+
return async function (req, _res, next) {
|
|
48
|
+
try {
|
|
49
|
+
const state = getState();
|
|
50
|
+
// An explicit Authorization header wins: the cookie is whatever the browser holds, which a
|
|
51
|
+
// sibling subdomain may have planted.
|
|
52
|
+
const bearerToken = parseBearer(req.headers.authorization);
|
|
53
|
+
const cookieToken = bearerToken ? undefined : readSessionCookie(state, req, COOKIE_NAMES.ACCESS_TOKEN);
|
|
54
|
+
const token = bearerToken || cookieToken;
|
|
55
|
+
|
|
56
|
+
if (!token) {
|
|
57
|
+
if (opts.optional) return next();
|
|
58
|
+
throw new IdpError({ code: 'AUTH_REQUIRED', httpStatus: 401, message: 'Authentication is required to access this resource' });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// The cookie is attached by the browser whoever builds the request — so it must come from a trusted origin.
|
|
62
|
+
if (token === cookieToken) assertTrustedOrigin(state, req);
|
|
63
|
+
const payload = await verifyAccessToken(state, token, { issuer: opts.issuer, audience: opts.audience, accept });
|
|
64
|
+
await assertSessionLive(state, payload);
|
|
65
|
+
await assertClientStillActive(state, payload);
|
|
66
|
+
|
|
67
|
+
const kind = classifyAccessToken(payload);
|
|
68
|
+
const isClientToken = kind === ACCESS_TOKEN_KINDS.OAUTH2_CLIENT;
|
|
69
|
+
req.auth = {
|
|
70
|
+
// A client_credentials token has no user — never surface the client id as a userId.
|
|
71
|
+
userId: isClientToken ? undefined : payload.sub,
|
|
72
|
+
email: payload.email,
|
|
73
|
+
claims: payload.claims || {},
|
|
74
|
+
tokenKind: kind,
|
|
75
|
+
...(payload.client_id ? { clientId: payload.client_id, scopes: String(payload.scope || '').split(' ').filter(Boolean) } : {}),
|
|
76
|
+
tokenMeta: { issuedAt: payload.iat, expiresAt: payload.exp, jti: payload.jti, authTime: payload.auth_time ?? null, sessionless: payload.sessionless === true },
|
|
77
|
+
};
|
|
78
|
+
next();
|
|
79
|
+
} catch (err) {
|
|
80
|
+
logRejection(req, err);
|
|
81
|
+
next(err);
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const REVOKED = () => new IdpError({ code: 'TOKEN_REVOKED', httpStatus: 401, message: 'Session has been revoked' });
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Revocation check. The per-process cache is only ever a fast path: a cache
|
|
90
|
+
* "revoked" short-circuits, but a cache "not revoked" (or a miss) never
|
|
91
|
+
* skips the storage check while `session.verifyOnEachRequest` is on — the
|
|
92
|
+
* session row is the authority, and the only thing every instance shares.
|
|
93
|
+
*
|
|
94
|
+
* Tokens carrying `sessionless: true` (client_credentials grants and the
|
|
95
|
+
* public `issueAccessToken()` export — neither has a session row) skip the
|
|
96
|
+
* storage check; they were never tied to a session to revoke.
|
|
97
|
+
*/
|
|
98
|
+
/**
|
|
99
|
+
* A client_credentials token has no session row to revoke, so it is checked against its client: a
|
|
100
|
+
* deactivated (or deleted) client's machine tokens stop working at once, not when they expire.
|
|
101
|
+
*/
|
|
102
|
+
async function assertClientStillActive(state, payload) {
|
|
103
|
+
if (classifyAccessToken(payload) !== ACCESS_TOKEN_KINDS.OAUTH2_CLIENT) return;
|
|
104
|
+
const client = await state.storage.oauthClientRepository.findByClientId(payload.client_id);
|
|
105
|
+
if (!client || client.status !== OAUTH_CLIENT_STATUS.ACTIVE) throw REVOKED();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function assertSessionLive(state, payload) {
|
|
109
|
+
const verifyInStorage = state.config.session?.verifyOnEachRequest === true
|
|
110
|
+
&& payload.sessionless !== true
|
|
111
|
+
&& typeof state.storage.sessionRepository?.findByJti === 'function';
|
|
112
|
+
const revokedKey = `${CACHE_KEY_PREFIXES.REVOKED_REFRESH_TOKEN}:${payload.jti}`;
|
|
113
|
+
|
|
114
|
+
if (!verifyInStorage) {
|
|
115
|
+
// Cache-only mode (opted out, or an adapter without findByJti): the
|
|
116
|
+
// cache is all there is, so a cache error must fail closed.
|
|
117
|
+
if (await isRevoked(state.cache, revokedKey)) throw REVOKED();
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
let cachedRevoked = false;
|
|
122
|
+
try {
|
|
123
|
+
cachedRevoked = Boolean(await state.cache.get(revokedKey));
|
|
124
|
+
} catch (err) {
|
|
125
|
+
// Storage is about to be asked anyway — a cache outage costs the
|
|
126
|
+
// fast path, not availability.
|
|
127
|
+
state.logger?.warn?.({ err }, 'Revocation cache unavailable — relying on the session store');
|
|
128
|
+
}
|
|
129
|
+
if (cachedRevoked) throw REVOKED();
|
|
130
|
+
|
|
131
|
+
let session;
|
|
132
|
+
try {
|
|
133
|
+
session = await state.storage.sessionRepository.findByJti(payload.jti);
|
|
134
|
+
} catch (cause) {
|
|
135
|
+
throw new IdpError({ code: 'SESSION_STORE_UNAVAILABLE', httpStatus: 503, message: 'Unable to verify session status', cause });
|
|
136
|
+
}
|
|
137
|
+
if (!session || session.revokedAt || !(new Date(session.expiresAt) > new Date()) || String(session.user) !== String(payload.sub)) {
|
|
138
|
+
throw REVOKED();
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function logRejection(req, err) {
|
|
143
|
+
try {
|
|
144
|
+
// The path only — a query string can carry tokens (end-session's id_token_hint, an SSO code).
|
|
145
|
+
getState().logger?.warn?.({ err, path: req.path }, 'authContextMiddleware rejected request');
|
|
146
|
+
} catch {
|
|
147
|
+
// state not initialized — nothing to log through
|
|
148
|
+
}
|
|
149
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
2
|
+
|
|
3
|
+
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* CSRF defence for requests whose credential is a COOKIE (session cookie, refresh cookie). A cookie
|
|
7
|
+
* is attached by the browser whoever builds the request; SameSite=Lax keeps it off cross-SITE
|
|
8
|
+
* POSTs, but not off requests from a sibling subdomain (same site, different origin), and not at
|
|
9
|
+
* all under `cookies.sameSite: 'none'`. So a state-changing cookie request must also come from a
|
|
10
|
+
* trusted origin:
|
|
11
|
+
*
|
|
12
|
+
* - `Sec-Fetch-Site: same-origin` → allowed;
|
|
13
|
+
* - an `Origin` header → it must be the issuer's origin or one of `config.cookies.trustedOrigins`
|
|
14
|
+
* (your frontends' origins);
|
|
15
|
+
* - neither header → not a browser (browsers send `Origin` on every cross-origin unsafe request) →
|
|
16
|
+
* allowed.
|
|
17
|
+
*
|
|
18
|
+
* Requests authenticated by an `Authorization: Bearer` header are not affected: a browser never
|
|
19
|
+
* attaches that on its own.
|
|
20
|
+
*/
|
|
21
|
+
export function assertTrustedOrigin(state, req) {
|
|
22
|
+
if (SAFE_METHODS.has(String(req.method).toUpperCase())) return;
|
|
23
|
+
const fetchSite = req.headers['sec-fetch-site'];
|
|
24
|
+
if (fetchSite === 'same-origin') return;
|
|
25
|
+
|
|
26
|
+
const origin = req.headers.origin;
|
|
27
|
+
if (origin !== undefined) {
|
|
28
|
+
if (trustedOrigins(state).has(origin)) return;
|
|
29
|
+
throw CSRF_REJECTED();
|
|
30
|
+
}
|
|
31
|
+
if (fetchSite !== undefined && fetchSite !== 'none') throw CSRF_REJECTED();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function trustedOrigins(state) {
|
|
35
|
+
const set = new Set(state.config.cookies?.trustedOrigins || []);
|
|
36
|
+
try {
|
|
37
|
+
set.add(new URL(state.config.issuer).origin);
|
|
38
|
+
} catch {
|
|
39
|
+
// an issuer that isn't a URL contributes no origin
|
|
40
|
+
}
|
|
41
|
+
return set;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const CSRF_REJECTED = () => new IdpError({
|
|
45
|
+
code: 'CSRF_ORIGIN_REJECTED',
|
|
46
|
+
httpStatus: 403,
|
|
47
|
+
message: 'Cross-origin request refused — add your frontend origin to config.cookies.trustedOrigins',
|
|
48
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { getState } from '../config/state.js';
|
|
2
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Step-up gate for changes that would let a stolen session outlive itself — adding a passkey,
|
|
6
|
+
* enrolling MFA, deleting a passkey or the account. Mount after `authContextMiddleware()`.
|
|
7
|
+
*
|
|
8
|
+
* Passes only when the user actually authenticated (password + MFA, magic link, SSO, passkey —
|
|
9
|
+
* not a token refresh) within `maxAgeSeconds` (default `config.session.recentAuthMaxAgeSeconds`,
|
|
10
|
+
* 15 minutes). Otherwise answers 401 `REAUTHENTICATION_REQUIRED`: the client sends the user
|
|
11
|
+
* through a login again and retries with the new token. A token without `auth_time` (one minted
|
|
12
|
+
* through the public `issueAccessToken()` export, or refreshed from a pre-0.4.0 session) never
|
|
13
|
+
* counts as recent.
|
|
14
|
+
*
|
|
15
|
+
* @param {{ maxAgeSeconds?: number }} [opts]
|
|
16
|
+
*/
|
|
17
|
+
export function requireRecentAuth(opts = {}) {
|
|
18
|
+
if (opts.maxAgeSeconds !== undefined && !(Number.isInteger(opts.maxAgeSeconds) && opts.maxAgeSeconds > 0)) {
|
|
19
|
+
throw new Error('requireRecentAuth: maxAgeSeconds must be a positive integer');
|
|
20
|
+
}
|
|
21
|
+
return function (req, _res, next) {
|
|
22
|
+
const maxAge = opts.maxAgeSeconds ?? getState().config.session.recentAuthMaxAgeSeconds;
|
|
23
|
+
const authTime = req.auth?.tokenMeta?.authTime;
|
|
24
|
+
const now = Math.floor(Date.now() / 1000);
|
|
25
|
+
if (!Number.isInteger(authTime) || authTime > now + 60 || now - authTime > maxAge) {
|
|
26
|
+
return next(new IdpError({ code: 'REAUTHENTICATION_REQUIRED', httpStatus: 401, message: 'Please sign in again to continue' }));
|
|
27
|
+
}
|
|
28
|
+
next();
|
|
29
|
+
};
|
|
30
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
2
|
+
import { getState } from '../config/state.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Pins an internal endpoint to a specific set of upstream services. Runs
|
|
6
|
+
* AFTER `serviceContextMiddleware`. Name-allowlist only — not an RBAC
|
|
7
|
+
* decision, so it stays in scope per the Phase 2 exclusion of scope-catalogue
|
|
8
|
+
* logic.
|
|
9
|
+
*/
|
|
10
|
+
export function requireServiceCallerMiddleware(...allowedCallers) {
|
|
11
|
+
if (allowedCallers.length === 0) throw new Error('requireServiceCallerMiddleware: at least one allowed caller is required');
|
|
12
|
+
const allowed = new Set(allowedCallers);
|
|
13
|
+
|
|
14
|
+
return (req, _res, next) => {
|
|
15
|
+
const caller = req.serviceCaller;
|
|
16
|
+
if (!caller) {
|
|
17
|
+
return next(new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'No authenticated service caller — mount serviceContextMiddleware first' }));
|
|
18
|
+
}
|
|
19
|
+
if (!allowed.has(caller.name)) {
|
|
20
|
+
return next(new IdpError({ code: 'FORBIDDEN', httpStatus: 403, message: `Service '${caller.name}' is not allowed to call this endpoint` }));
|
|
21
|
+
}
|
|
22
|
+
if (caller.source === 'legacy-secret') {
|
|
23
|
+
// The name came from an unverified header: anyone with the shared secret can claim any name.
|
|
24
|
+
const state = getState();
|
|
25
|
+
if (state.config.serviceMesh?.allowLegacySecretCallers !== true) {
|
|
26
|
+
return next(new IdpError({ code: 'FORBIDDEN', httpStatus: 403, message: 'This endpoint requires a signed service token (shared-secret callers are not identifiable)' }));
|
|
27
|
+
}
|
|
28
|
+
state.logger?.warn?.({ caller: caller.name, path: req.originalUrl }, 'Caller identity taken from a header under the shared secret (allowLegacySecretCallers) — not verified');
|
|
29
|
+
}
|
|
30
|
+
next();
|
|
31
|
+
};
|
|
32
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { getState } from '../config/state.js';
|
|
2
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
3
|
+
import { verifyServiceTokenWith } from '../service-mesh/verify-service-token.js';
|
|
4
|
+
import { localKeyLookup } from '../service-mesh/local-key-lookup.js';
|
|
5
|
+
import { safeEqualSecret } from '../utils/safe-equal.js';
|
|
6
|
+
|
|
7
|
+
function parseBearer(header) {
|
|
8
|
+
if (!header || typeof header !== 'string') return null;
|
|
9
|
+
const match = header.match(/^Bearer\s+(.+)$/i);
|
|
10
|
+
return match ? match[1].trim() : null;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Authenticates an inbound service-to-service request against this IDP's own
|
|
15
|
+
* service-key registry (in-process — no HTTP round trip). Sets
|
|
16
|
+
* `req.serviceCaller = { name, scopes, region, source }`.
|
|
17
|
+
*
|
|
18
|
+
* Mode is `config.serviceMesh.tokenMode` ('token' | 'secret' | 'both',
|
|
19
|
+
* default 'token'). 'secret' and 'both' are a legacy shared-secret fallback for
|
|
20
|
+
* staged rollouts — the caller's claimed name (`x-service-name` header) is NOT
|
|
21
|
+
* verified under it, so `requireServiceCallerMiddleware` refuses such callers
|
|
22
|
+
* unless `serviceMesh.allowLegacySecretCallers` is true.
|
|
23
|
+
*
|
|
24
|
+
* @param {{ ownServiceName: string }} opts - this service's own name (the token `aud` it expects)
|
|
25
|
+
*/
|
|
26
|
+
export function serviceContextMiddleware(opts = {}) {
|
|
27
|
+
return async function (req, _res, next) {
|
|
28
|
+
const state = getState();
|
|
29
|
+
const mode = state.config.serviceMesh?.tokenMode || 'token';
|
|
30
|
+
const ownName = opts.ownServiceName || state.config.serviceMesh?.ownServiceName;
|
|
31
|
+
|
|
32
|
+
try {
|
|
33
|
+
// Without its own name this service can't check a token's audience. That is a configuration
|
|
34
|
+
// error — never a reason to fall back to the shared secret.
|
|
35
|
+
if (!ownName && mode !== 'secret') {
|
|
36
|
+
return next(new IdpError({ code: 'SERVICE_NOT_CONFIGURED', httpStatus: 500, message: 'serviceContextMiddleware: ownServiceName (or config.serviceMesh.ownServiceName) is required' }));
|
|
37
|
+
}
|
|
38
|
+
const bearer = parseBearer(req.headers.authorization);
|
|
39
|
+
const presentedSecret = req.headers['x-internal-service-secret'];
|
|
40
|
+
|
|
41
|
+
if (bearer && (mode === 'token' || mode === 'both')) {
|
|
42
|
+
try {
|
|
43
|
+
const lookup = localKeyLookup(state.storage.serviceKeyRepository, { rotationGraceSeconds: state.config.serviceMesh?.rotationGraceSeconds });
|
|
44
|
+
const payload = await verifyServiceTokenWith(bearer, { expectedAud: ownName }, lookup);
|
|
45
|
+
req.serviceCaller = { name: payload.iss, scopes: payload.scope ? payload.scope.split(' ') : [], region: payload.region, source: 'token' };
|
|
46
|
+
return next();
|
|
47
|
+
} catch (err) {
|
|
48
|
+
if (mode === 'token') return next(err);
|
|
49
|
+
state.logger?.warn?.({ err: err.message }, 'S2S token failed; falling back to legacy secret check (tokenMode=both)');
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (mode === 'secret' || mode === 'both') {
|
|
54
|
+
const expected = state.config.serviceMesh?.sharedSecret;
|
|
55
|
+
if (!expected) {
|
|
56
|
+
return next(new IdpError({ code: 'SERVICE_NOT_CONFIGURED', httpStatus: 500, message: 'No serviceMesh.sharedSecret configured and no valid S2S token presented' }));
|
|
57
|
+
}
|
|
58
|
+
if (!safeEqualSecret(presentedSecret, expected)) {
|
|
59
|
+
return next(new IdpError({ code: 'SERVICE_AUTH_FAILED', httpStatus: 401, message: 'Service authentication failed' }));
|
|
60
|
+
}
|
|
61
|
+
req.serviceCaller = { name: req.headers['x-service-name'] || 'unknown', source: 'legacy-secret' };
|
|
62
|
+
return next();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return next(new IdpError({ code: 'SERVICE_AUTH_FAILED', httpStatus: 401, message: 'Service authentication failed' }));
|
|
66
|
+
} catch (err) {
|
|
67
|
+
next(err);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
2
|
+
|
|
3
|
+
/** Works unchanged on Express 4 and 5 — `req.body` is writable on both. */
|
|
4
|
+
export function validateBody(schema) {
|
|
5
|
+
if (!schema || typeof schema.parse !== 'function') {
|
|
6
|
+
throw new Error('validateBody expects a zod schema (an object with .parse())');
|
|
7
|
+
}
|
|
8
|
+
return function (req, _res, next) {
|
|
9
|
+
try {
|
|
10
|
+
req.body = schema.parse(req.body);
|
|
11
|
+
next();
|
|
12
|
+
} catch (err) {
|
|
13
|
+
next(new IdpError({ code: 'VALIDATION_ERROR', httpStatus: 400, message: 'Request body validation failed', cause: err }));
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Express 5 makes `req.query` a read-only getter, so it can't be reassigned
|
|
5
|
+
* the way `validateBody` reassigns `req.body` (this broke in the audited
|
|
6
|
+
* source's Express-5 upgrade). Storing the parsed result on
|
|
7
|
+
* `req.validatedQuery` instead works unchanged on both Express 4 and 5 —
|
|
8
|
+
* handlers read `req.validatedQuery`, not `req.query`, after this runs.
|
|
9
|
+
*/
|
|
10
|
+
export function validateQuery(schema) {
|
|
11
|
+
if (!schema || typeof schema.parse !== 'function') {
|
|
12
|
+
throw new Error('validateQuery expects a zod schema (an object with .parse())');
|
|
13
|
+
}
|
|
14
|
+
return function (req, _res, next) {
|
|
15
|
+
try {
|
|
16
|
+
req.validatedQuery = schema.parse(req.query);
|
|
17
|
+
next();
|
|
18
|
+
} catch (err) {
|
|
19
|
+
next(new IdpError({ code: 'VALIDATION_ERROR', httpStatus: 400, message: 'Request query validation failed', cause: err }));
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
}
|