@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,309 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
import { generateSecret, generateURI, verify as verifyTotp } from 'otplib';
|
|
3
|
+
import { getState } from '../config/state.js';
|
|
4
|
+
import { assertTrustedOrigin } from '../middleware/csrf.js';
|
|
5
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
6
|
+
import { isActiveAccount } from '../utils/account-status.js';
|
|
7
|
+
import { verifyPassword } from '../utils/password.js';
|
|
8
|
+
import { hashOpaqueToken, opaqueTokenHashes, HASH_PURPOSES, verifyMfaChallengeToken as verifyMfaChallengeTokenJwt } from '../signing/token.service.js';
|
|
9
|
+
import { auditLog } from '../hooks/index.js';
|
|
10
|
+
import { issueSession, setSessionCookies, resolveClaims, refreshTokenInBody } from '../password-auth/controllers.js';
|
|
11
|
+
import { enforceRateLimit } from '../rate-limit/enforce.js';
|
|
12
|
+
import { ipKey } from '../rate-limit/keys.js';
|
|
13
|
+
import { sealMfaSecret, openMfaSecret } from './secrets.js';
|
|
14
|
+
import { guardMfaAttempt } from './attempt-guard.js';
|
|
15
|
+
import { claimTotpStep, consumeRecoveryCode, claimMfaChallenge } from './factor-store.js';
|
|
16
|
+
import { revokeOtherUserSessions } from '../utils/session-family.js';
|
|
17
|
+
|
|
18
|
+
// otplib v13's functional API takes `strategy` (default 'totp', so this is
|
|
19
|
+
// actually redundant but kept for clarity) and `epochTolerance` — a seconds-
|
|
20
|
+
// based clock-skew allowance, NOT the old v12 `window` (steps) option. 30s
|
|
21
|
+
// covers one period either side of the default 30s TOTP step, matching the
|
|
22
|
+
// intended "current ± 1 step" tolerance without depending on step size.
|
|
23
|
+
const TOTP_OPTIONS = { strategy: 'totp', epochTolerance: 30 };
|
|
24
|
+
|
|
25
|
+
// otplib v13 throws (TokenLengthError) on anything that isn't exactly 6
|
|
26
|
+
// digits — including every recovery code (XXXXXX-XXXXXX). Such a code just
|
|
27
|
+
// isn't a valid TOTP; it must fall through to the recovery-code check, not 500.
|
|
28
|
+
/** The matched TOTP time step, or null when the code doesn't verify. */
|
|
29
|
+
async function totpStep(code, secret) {
|
|
30
|
+
if (!secret || !/^\d{6}$/.test(code)) return null;
|
|
31
|
+
const result = await verifyTotp({ token: code, secret, ...TOTP_OPTIONS });
|
|
32
|
+
return result.valid ? result.timeStep : null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* True when `code` verifies against `secret` AND its time step hasn't been accepted for this account
|
|
37
|
+
* before. Without the second check a code seen once (shoulder-surfed, logged, replayed from a
|
|
38
|
+
* captured request) works again for the rest of its ±30s window.
|
|
39
|
+
*/
|
|
40
|
+
async function totpAccepted(state, userId, code, secret) {
|
|
41
|
+
const step = await totpStep(code, secret);
|
|
42
|
+
return step !== null && claimTotpStep(state, userId, step);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const isWrongCode = (err) => err?.code === 'INVALID_MFA_CODE';
|
|
46
|
+
// For the re-authenticating MFA routes (disable, regenerate codes) a wrong password is a guess too.
|
|
47
|
+
const isWrongCodeOrPassword = (err) => isWrongCode(err) || err?.code === 'CURRENT_PASSWORD_INCORRECT';
|
|
48
|
+
|
|
49
|
+
function invalidCode(message = 'Invalid TOTP code') {
|
|
50
|
+
return new IdpError({ code: 'INVALID_MFA_CODE', httpStatus: 400, message });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const INVALID_CHALLENGE = () => new IdpError({ code: 'INVALID_MFA_CHALLENGE_TOKEN', httpStatus: 401, message: 'Invalid or expired MFA challenge token' });
|
|
54
|
+
|
|
55
|
+
function assertMfaFeatureEnabled(state) {
|
|
56
|
+
if (state.config.mfa.enabled === false) {
|
|
57
|
+
throw new IdpError({ code: 'FEATURE_DISABLED', httpStatus: 404, message: 'MFA is not enabled on this server' });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Crockford base32: no I, L, O, U — nothing to misread when typing a code off paper.
|
|
62
|
+
const RECOVERY_ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 20 characters of base32 = 100 bits, shown as XXXXX-XXXXX-XXXXX-XXXXX. (0.3.0 used 48 bits: with the
|
|
66
|
+
* database and the HMAC key, every user's codes fell to one offline search.)
|
|
67
|
+
*/
|
|
68
|
+
function generateRecoveryCode() {
|
|
69
|
+
const chars = Array.from({ length: 20 }, () => RECOVERY_ALPHABET[crypto.randomInt(RECOVERY_ALPHABET.length)]).join('');
|
|
70
|
+
return chars.match(/.{5}/g).join('-');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Accept a code however it's typed: any case, spaces or dashes, and O/I/L for 0/1. */
|
|
74
|
+
const normalizeRecoveryCode = (code) => String(code).toUpperCase().replace(/[\s-]/g, '').replace(/O/g, '0').replace(/[IL]/g, '1');
|
|
75
|
+
|
|
76
|
+
/** Keyed hash of a recovery code, bound to its user — one guess can't be tested against everyone's codes at once. */
|
|
77
|
+
const recoveryCodeInput = (userId, code) => `${userId}:${normalizeRecoveryCode(code)}`;
|
|
78
|
+
const recoveryCodeHash = (state, userId, code) => hashOpaqueToken(state, recoveryCodeInput(userId, code), HASH_PURPOSES.MFA_RECOVERY_CODE);
|
|
79
|
+
|
|
80
|
+
function newRecoveryCodes(state, userId) {
|
|
81
|
+
const rawCodes = Array.from({ length: state.config.mfa.recoveryCodeCount }, generateRecoveryCode);
|
|
82
|
+
return { rawCodes, stored: rawCodes.map((c) => ({ codeHash: recoveryCodeHash(state, userId, c), usedAt: null })) };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Re-authentication for the routes that weaken or re-issue the second factor: the password (when the account has one). */
|
|
86
|
+
async function assertPassword(user, password) {
|
|
87
|
+
if (!user.passwordHash) return; // passwordless account (SSO / magic link): the TOTP code is the re-authentication
|
|
88
|
+
if (!(await verifyPassword(password ?? '', user.passwordHash))) {
|
|
89
|
+
throw new IdpError({ code: 'CURRENT_PASSWORD_INCORRECT', httpStatus: 400, message: 'Incorrect password' });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Verifies an MFA challenge token for completing a login, and that it's still current: a challenge
|
|
95
|
+
* issued before the account's last password change is void (it was earned with the old password).
|
|
96
|
+
* Shared with WebAuthn-as-MFA.
|
|
97
|
+
*/
|
|
98
|
+
export function verifyChallengeToken(state, mfaChallengeToken) {
|
|
99
|
+
try {
|
|
100
|
+
const claims = verifyMfaChallengeTokenJwt(state, mfaChallengeToken);
|
|
101
|
+
if (!claims.jti) throw INVALID_CHALLENGE();
|
|
102
|
+
return claims;
|
|
103
|
+
} catch {
|
|
104
|
+
throw INVALID_CHALLENGE();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* A challenge is void once the user's sessions were revoked after it was issued (password reset or
|
|
110
|
+
* change, logout-all): compared by the sessionEpoch it carries — a counter, not the app servers'
|
|
111
|
+
* clocks. A challenge without one (issued before 0.4.0) falls back to passwordChangedAt.
|
|
112
|
+
*/
|
|
113
|
+
export function assertChallengeCurrent(user, challengeClaims) {
|
|
114
|
+
if (Number.isInteger(challengeClaims.sep)) {
|
|
115
|
+
if (user.sessionEpoch !== challengeClaims.sep) throw INVALID_CHALLENGE();
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const changedAt = user.passwordChangedAt ? Math.floor(new Date(user.passwordChangedAt).getTime() / 1000) : null;
|
|
119
|
+
if (changedAt !== null && challengeClaims.iat < changedAt) throw INVALID_CHALLENGE();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Spends the challenge token (one token, one login) — after the factor checked out. */
|
|
123
|
+
export async function spendChallenge(state, challengeClaims) {
|
|
124
|
+
if (!(await claimMfaChallenge(state, challengeClaims))) throw INVALID_CHALLENGE();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export async function getMfaStatusHandler(req, res, next) {
|
|
128
|
+
try {
|
|
129
|
+
const state = getState();
|
|
130
|
+
const user = await state.storage.userRepository.findById(req.auth.userId, { select: 'mfaEnabled' });
|
|
131
|
+
if (!user) throw new IdpError({ code: 'USER_NOT_FOUND', httpStatus: 404, message: 'User not found' });
|
|
132
|
+
res.json({ mfaEnabled: Boolean(user.mfaEnabled) });
|
|
133
|
+
} catch (err) {
|
|
134
|
+
next(err);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Returns the raw `otpauth://` URI only — this package does not depend on a
|
|
140
|
+
* QR-code renderer. The consumer renders their own QR code client-side from
|
|
141
|
+
* the URI (e.g. with the `qrcode` npm package, or a frontend QR component).
|
|
142
|
+
*/
|
|
143
|
+
export async function setupMfaHandler(req, res, next) {
|
|
144
|
+
try {
|
|
145
|
+
const state = getState();
|
|
146
|
+
assertMfaFeatureEnabled(state);
|
|
147
|
+
const user = await state.storage.userRepository.findById(req.auth.userId, { select: '+mfaTempSecret mfaEnabled email' });
|
|
148
|
+
if (!user) throw new IdpError({ code: 'USER_NOT_FOUND', httpStatus: 404, message: 'User not found' });
|
|
149
|
+
if (user.mfaEnabled) throw new IdpError({ code: 'MFA_ALREADY_ENABLED', httpStatus: 400, message: 'MFA is already enabled on this account' });
|
|
150
|
+
|
|
151
|
+
const secret = generateSecret();
|
|
152
|
+
const otpauthUrl = generateURI({ secret, label: user.email, issuer: state.config.mfa.issuerLabel, strategy: 'totp' });
|
|
153
|
+
|
|
154
|
+
await state.storage.userRepository.updateById(req.auth.userId, { mfaTempSecret: await sealMfaSecret(state, secret, req.auth.userId) });
|
|
155
|
+
await auditLog(state.logger, state.hooks, 'MFA_SETUP_INITIATED', { userId: req.auth.userId });
|
|
156
|
+
|
|
157
|
+
res.set('Cache-Control', 'no-store');
|
|
158
|
+
res.json({ secret, otpauthUrl });
|
|
159
|
+
} catch (err) {
|
|
160
|
+
next(err);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export async function confirmMfaHandler(req, res, next) {
|
|
165
|
+
try {
|
|
166
|
+
const state = getState();
|
|
167
|
+
assertMfaFeatureEnabled(state);
|
|
168
|
+
const { code } = req.body;
|
|
169
|
+
const userId = req.auth.userId;
|
|
170
|
+
const user = await state.storage.userRepository.findById(userId, { select: '+mfaTempSecret mfaEnabled' });
|
|
171
|
+
if (!user) throw new IdpError({ code: 'USER_NOT_FOUND', httpStatus: 404, message: 'User not found' });
|
|
172
|
+
if (user.mfaEnabled) throw new IdpError({ code: 'MFA_ALREADY_ENABLED', httpStatus: 400, message: 'MFA is already enabled on this account' });
|
|
173
|
+
if (!user.mfaTempSecret) throw new IdpError({ code: 'MFA_SETUP_REQUIRED', httpStatus: 400, message: 'MFA setup not initiated — call setupMfaHandler first' });
|
|
174
|
+
|
|
175
|
+
const { secret } = await openMfaSecret(state, user.mfaTempSecret, userId);
|
|
176
|
+
await guardMfaAttempt(state, userId, { method: 'totp-enrolment', isFailure: isWrongCode }, async () => {
|
|
177
|
+
// Claims the step too, so the code that confirmed enrolment can't then complete a login.
|
|
178
|
+
if (!(await totpAccepted(state, userId, code, secret))) throw invalidCode();
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
const { rawCodes, stored } = newRecoveryCodes(state, userId);
|
|
182
|
+
await state.storage.userRepository.updateById(userId, {
|
|
183
|
+
mfaEnabled: true,
|
|
184
|
+
// Re-sealed rather than copied: a temp secret written before
|
|
185
|
+
// encryption existed is plain text, and the permanent one never should be.
|
|
186
|
+
mfaSecret: await sealMfaSecret(state, secret, userId),
|
|
187
|
+
mfaTempSecret: null,
|
|
188
|
+
mfaRecoveryCodes: stored,
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
// Any other session may predate the account being secured (or be an attacker's): end them, keep this one.
|
|
192
|
+
// With the same watermark as "sign out everywhere", minus this session's family — so a refresh of
|
|
193
|
+
// another session that was already in flight is caught as well.
|
|
194
|
+
const { revokedCount } = await revokeOtherUserSessions(state, userId, { exceptJti: req.auth.tokenMeta?.jti });
|
|
195
|
+
await auditLog(state.logger, state.hooks, 'MFA_ENABLED', { userId: req.auth.userId, revokedOtherSessions: revokedCount });
|
|
196
|
+
res.set('Cache-Control', 'no-store');
|
|
197
|
+
res.json({ mfaEnabled: true, recoveryCodes: rawCodes }); // shown once — caller must save these
|
|
198
|
+
} catch (err) {
|
|
199
|
+
next(err);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export async function disableMfaHandler(req, res, next) {
|
|
204
|
+
try {
|
|
205
|
+
const state = getState();
|
|
206
|
+
const { password, code } = req.body;
|
|
207
|
+
const userId = req.auth.userId;
|
|
208
|
+
const user = await state.storage.userRepository.findById(userId, { select: '+passwordHash +mfaSecret mfaEnabled' });
|
|
209
|
+
if (!user) throw new IdpError({ code: 'USER_NOT_FOUND', httpStatus: 404, message: 'User not found' });
|
|
210
|
+
if (!user.mfaEnabled) throw new IdpError({ code: 'MFA_NOT_ENABLED', httpStatus: 400, message: 'MFA is not enabled on this account' });
|
|
211
|
+
|
|
212
|
+
// Counted before the password is checked too, so this route is no
|
|
213
|
+
// password oracle, locked or not.
|
|
214
|
+
await guardMfaAttempt(state, userId, { method: 'totp-disable', isFailure: isWrongCodeOrPassword }, async () => {
|
|
215
|
+
await assertPassword(user, password);
|
|
216
|
+
const opened = await openMfaSecret(state, user.mfaSecret, userId);
|
|
217
|
+
if (!(await totpAccepted(state, userId, code, opened?.secret))) throw invalidCode();
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
await state.storage.userRepository.updateById(userId, { mfaEnabled: false, mfaSecret: null, mfaTempSecret: null, mfaRecoveryCodes: [], mfaLastTotpStep: null });
|
|
221
|
+
await auditLog(state.logger, state.hooks, 'MFA_DISABLED', { userId: req.auth.userId });
|
|
222
|
+
res.json({ mfaEnabled: false });
|
|
223
|
+
} catch (err) {
|
|
224
|
+
next(err);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Re-issues the recovery codes. Requires a current TOTP code as well as the password: whoever holds only a session (or only the password) must not mint themselves a fresh set of second factors. */
|
|
229
|
+
export async function regenerateRecoveryCodesHandler(req, res, next) {
|
|
230
|
+
try {
|
|
231
|
+
const state = getState();
|
|
232
|
+
const { password, code } = req.body;
|
|
233
|
+
const userId = req.auth.userId;
|
|
234
|
+
const user = await state.storage.userRepository.findById(userId, { select: '+passwordHash +mfaSecret mfaEnabled' });
|
|
235
|
+
if (!user) throw new IdpError({ code: 'USER_NOT_FOUND', httpStatus: 404, message: 'User not found' });
|
|
236
|
+
if (!user.mfaEnabled) throw new IdpError({ code: 'MFA_NOT_ENABLED', httpStatus: 400, message: 'MFA is not enabled on this account' });
|
|
237
|
+
|
|
238
|
+
await guardMfaAttempt(state, userId, { method: 'recovery-codes', isFailure: isWrongCodeOrPassword }, async () => {
|
|
239
|
+
await assertPassword(user, password);
|
|
240
|
+
const opened = await openMfaSecret(state, user.mfaSecret, userId);
|
|
241
|
+
if (!(await totpAccepted(state, userId, code, opened?.secret))) throw invalidCode();
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
const { rawCodes, stored } = newRecoveryCodes(state, userId);
|
|
245
|
+
await state.storage.userRepository.updateById(userId, { mfaRecoveryCodes: stored });
|
|
246
|
+
|
|
247
|
+
await auditLog(state.logger, state.hooks, 'MFA_RECOVERY_CODES_REGENERATED', { userId });
|
|
248
|
+
res.set('Cache-Control', 'no-store');
|
|
249
|
+
res.json({ recoveryCodes: rawCodes });
|
|
250
|
+
} catch (err) {
|
|
251
|
+
next(err);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Completes login after a first factor returned `{ mfaRequired: true }`. Accepts a TOTP code or an unused recovery code. */
|
|
256
|
+
export async function verifyMfaChallengeHandler(req, res, next) {
|
|
257
|
+
try {
|
|
258
|
+
const state = getState();
|
|
259
|
+
assertTrustedOrigin(state, req); // sets session cookies — refuse login CSRF (see middleware/csrf.js)
|
|
260
|
+
const { mfaChallengeToken, code } = req.body;
|
|
261
|
+
|
|
262
|
+
await enforceRateLimit(state, `mfa-challenge:ip:${ipKey(req.ip)}`, state.config.rateLimiting.mfaChallenge, { failMode: 'closed' });
|
|
263
|
+
|
|
264
|
+
const challenge = verifyChallengeToken(state, mfaChallengeToken);
|
|
265
|
+
const userId = challenge.sub;
|
|
266
|
+
const user = await state.storage.userRepository.findById(userId, { select: '+mfaSecret +mfaRecoveryCodes' });
|
|
267
|
+
if (!isActiveAccount(user)) throw new IdpError({ code: 'USER_NOT_ACTIVE', httpStatus: 403, message: 'User account is not active' });
|
|
268
|
+
if (!user.mfaEnabled) throw INVALID_CHALLENGE();
|
|
269
|
+
assertChallengeCurrent(user, challenge);
|
|
270
|
+
|
|
271
|
+
// TOTP and recovery codes share one per-account counter: a guess is a
|
|
272
|
+
// guess whichever kind of code it's aimed at. Each is spent atomically
|
|
273
|
+
// inside the guard, so neither can be used twice — not even by two
|
|
274
|
+
// requests racing with the same code.
|
|
275
|
+
const { opened, method } = await guardMfaAttempt(state, userId, { method: 'totp', isFailure: isWrongCode }, async () => {
|
|
276
|
+
const opened = await openMfaSecret(state, user.mfaSecret, userId);
|
|
277
|
+
if (await totpAccepted(state, userId, code, opened?.secret)) return { opened, method: 'totp' };
|
|
278
|
+
|
|
279
|
+
// Codes generated before a tokenHashSecret rotation are stored under a previous key.
|
|
280
|
+
for (const codeHash of opaqueTokenHashes(state, recoveryCodeInput(user.id, code), HASH_PURPOSES.MFA_RECOVERY_CODE)) {
|
|
281
|
+
if (await consumeRecoveryCode(state, user, codeHash)) return { opened, method: 'recovery-code' };
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
throw invalidCode('Invalid MFA code');
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
await spendChallenge(state, challenge);
|
|
288
|
+
|
|
289
|
+
// Lazy migration: a plain-text secret (or one under a retired key) is
|
|
290
|
+
// re-sealed under the current key on the first successful verify.
|
|
291
|
+
if (opened?.needsUpgrade) await state.storage.userRepository.updateById(userId, { mfaSecret: await sealMfaSecret(state, opened.secret, userId) });
|
|
292
|
+
|
|
293
|
+
const claims = await resolveClaims(state, user, { isNewUser: false, method: 'mfa' });
|
|
294
|
+
const session = await issueSession(state, { user, claims, req, sessionEpoch: challenge.sep, loginChallenge: challenge.lch });
|
|
295
|
+
|
|
296
|
+
await auditLog(state.logger, state.hooks, 'MFA_VERIFIED', { userId, method });
|
|
297
|
+
|
|
298
|
+
setSessionCookies(req, res, state, session);
|
|
299
|
+
res.json({
|
|
300
|
+
accessToken: session.accessToken.token,
|
|
301
|
+
accessTokenExpiresAt: session.accessToken.expiresAt,
|
|
302
|
+
...refreshTokenInBody(state, req, session.refreshTokenValue),
|
|
303
|
+
refreshTokenExpiresAt: session.refreshExpiresAt,
|
|
304
|
+
userId,
|
|
305
|
+
});
|
|
306
|
+
} catch (err) {
|
|
307
|
+
next(err);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Single-use bookkeeping for second factors. Each prefers the storage adapter's atomic method and
|
|
3
|
+
* falls back to a read-then-write for adapters that don't have it yet (initIdentityProvider warns
|
|
4
|
+
* about those at startup — the fallback is correct for sequential requests but racy under
|
|
5
|
+
* concurrency).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Claims TOTP time step `step` for the user; false if it (or a later one) was already used. */
|
|
9
|
+
export async function claimTotpStep(state, userId, step) {
|
|
10
|
+
const repo = state.storage.userRepository;
|
|
11
|
+
if (typeof repo.claimTotpStep === 'function') return repo.claimTotpStep(userId, step);
|
|
12
|
+
const user = await repo.findById(userId, { select: '+mfaLastTotpStep' });
|
|
13
|
+
if (user?.mfaLastTotpStep != null && user.mfaLastTotpStep >= step) return false;
|
|
14
|
+
await repo.updateById(userId, { mfaLastTotpStep: step });
|
|
15
|
+
return true;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Spends the unused recovery code whose hash is `codeHash`; false if there is none. */
|
|
19
|
+
export async function consumeRecoveryCode(state, user, codeHash) {
|
|
20
|
+
const repo = state.storage.userRepository;
|
|
21
|
+
if (typeof repo.consumeRecoveryCode === 'function') return repo.consumeRecoveryCode(user.id, codeHash);
|
|
22
|
+
const idx = (user.mfaRecoveryCodes || []).findIndex((rc) => !rc.usedAt && rc.codeHash === codeHash);
|
|
23
|
+
if (idx < 0) return false;
|
|
24
|
+
await repo.updateById(user.id, { [`mfaRecoveryCodes.${idx}.usedAt`]: new Date() });
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Lets an MFA challenge token complete exactly one login. Claimed in the shared attempt-counter
|
|
30
|
+
* store (atomic, visible to every instance) under the token's `jti`, for as long as the token lives.
|
|
31
|
+
* Returns false if the token was already used.
|
|
32
|
+
*/
|
|
33
|
+
export async function claimMfaChallenge(state, challengeClaims) {
|
|
34
|
+
const ttl = Math.max(1, (challengeClaims.exp ?? 0) - Math.floor(Date.now() / 1000) + 60);
|
|
35
|
+
const entry = await state.attemptCounters.recordFailure(`mfa-challenge-used:${challengeClaims.jti}`, { max: 1, windowSeconds: ttl, lockSeconds: ttl });
|
|
36
|
+
return entry.count === 1;
|
|
37
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-process `AttemptCounterRepository` — the fallback used when a storage
|
|
3
|
+
* adapter doesn't provide `attemptCounterRepository` yet. Same caveat as
|
|
4
|
+
* MemoryRateLimiter: correct for a single instance, but each instance of a
|
|
5
|
+
* horizontally-scaled deployment keeps its own count. initIdentityProvider()
|
|
6
|
+
* logs a warning when it falls back to this.
|
|
7
|
+
*
|
|
8
|
+
* @implements {import('../storage/interfaces.js').AttemptCounterRepository}
|
|
9
|
+
*/
|
|
10
|
+
export class MemoryAttemptCounterRepository {
|
|
11
|
+
constructor({ now = () => Date.now() } = {}) {
|
|
12
|
+
this._now = now;
|
|
13
|
+
this._store = new Map(); // key -> { count, windowExpiresAt, lockedUntil }
|
|
14
|
+
this._writes = 0;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async get(key) {
|
|
18
|
+
const entry = this._store.get(key);
|
|
19
|
+
return entry ? toResult(entry) : null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async recordFailure(key, { max, windowSeconds, lockSeconds }) {
|
|
23
|
+
const now = this._now();
|
|
24
|
+
const prev = this._store.get(key);
|
|
25
|
+
// Start over when the window has run out or a lock has expired — but
|
|
26
|
+
// never while a lock is still active.
|
|
27
|
+
const lockActive = prev?.lockedUntil != null && prev.lockedUntil > now;
|
|
28
|
+
const fresh = !prev || (!lockActive && (prev.windowExpiresAt <= now || prev.lockedUntil !== null));
|
|
29
|
+
const entry = fresh
|
|
30
|
+
? { count: 1, windowExpiresAt: now + windowSeconds * 1000, lockedUntil: null }
|
|
31
|
+
: { ...prev, count: prev.count + 1 };
|
|
32
|
+
if (entry.count >= max && entry.lockedUntil === null) entry.lockedUntil = now + lockSeconds * 1000;
|
|
33
|
+
this._store.set(key, entry);
|
|
34
|
+
// Keys can be chosen by callers (e.g. an address): drop expired entries now and then, so the map doesn't grow without bound.
|
|
35
|
+
if ((this._writes += 1) % 1000 === 0) await this.pruneExpired();
|
|
36
|
+
return toResult(entry);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async reset(key) {
|
|
40
|
+
this._store.delete(key);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async pruneExpired() {
|
|
44
|
+
const now = this._now();
|
|
45
|
+
let deletedCount = 0;
|
|
46
|
+
for (const [key, e] of this._store) {
|
|
47
|
+
if (e.windowExpiresAt <= now && (e.lockedUntil === null || e.lockedUntil <= now)) {
|
|
48
|
+
this._store.delete(key);
|
|
49
|
+
deletedCount += 1;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return { deletedCount };
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function toResult(e) {
|
|
57
|
+
return { count: e.count, windowExpiresAt: new Date(e.windowExpiresAt), lockedUntil: e.lockedUntil === null ? null : new Date(e.lockedUntil) };
|
|
58
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
export const confirmMfaSchema = z.object({ code: z.string().min(6).max(10) }).strict();
|
|
4
|
+
// `password` is required when the account has one; a passwordless (SSO / magic-link) account re-authenticates with the code alone.
|
|
5
|
+
export const disableMfaSchema = z.object({ password: z.string().min(1).optional(), code: z.string().min(6).max(10) }).strict();
|
|
6
|
+
export const regenerateRecoveryCodesSchema = z.object({ password: z.string().min(1).optional(), code: z.string().min(6).max(10) }).strict();
|
|
7
|
+
export const verifyMfaChallengeSchema = z.object({
|
|
8
|
+
mfaChallengeToken: z.string().min(1),
|
|
9
|
+
// Room for a recovery code (`XXXXX-XXXXX-XXXXX-XXXXX`, 23 chars, typed with spaces too) as well as a TOTP code.
|
|
10
|
+
code: z.string().min(6).max(32),
|
|
11
|
+
}).strict();
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
|
|
3
|
+
const FORMAT_VERSION = 'v1';
|
|
4
|
+
const KEY_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
|
5
|
+
const IV_BYTES = 12; // 96-bit nonce — the GCM-recommended size
|
|
6
|
+
const TAG_BYTES = 16;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @typedef {Object} SecretCipher
|
|
10
|
+
* Pluggable at-rest encryption for TOTP secrets (`mfaSecret`/`mfaTempSecret`).
|
|
11
|
+
* Supply your own via `config.mfa.secretCipher` to route through a KMS/HSM;
|
|
12
|
+
* otherwise `config.mfa.encryptionKey` builds the built-in AES-256-GCM one.
|
|
13
|
+
*
|
|
14
|
+
* Whatever `encrypt` returns is stored verbatim. It must NOT look like a bare
|
|
15
|
+
* base32 string (`/^[A-Z2-7]+=*$/i`) — that shape is how a not-yet-migrated
|
|
16
|
+
* plain-text secret is recognised (see secrets.js). A prefix such as `kms:`
|
|
17
|
+
* is enough.
|
|
18
|
+
*
|
|
19
|
+
* `context` is the owning user's id. Bind it to the ciphertext (the built-in
|
|
20
|
+
* cipher uses it as GCM additional authenticated data) so an encrypted
|
|
21
|
+
* secret copied onto another user's row fails to decrypt.
|
|
22
|
+
*
|
|
23
|
+
* @property {(plaintext: string, opts: { context: string }) => string | Promise<string>} encrypt
|
|
24
|
+
* @property {(ciphertext: string, opts: { context: string }) => string | Promise<string>} decrypt
|
|
25
|
+
* @property {(ciphertext: string) => boolean} [needsRotation] - true when `ciphertext` was written under a key that's no longer current; triggers re-encryption on the next successful verify
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Built-in AES-256-GCM cipher. Stored format:
|
|
30
|
+
* `v1:<keyId>:<iv>:<ciphertext>:<tag>` (each binary part base64url).
|
|
31
|
+
*
|
|
32
|
+
* Rotation: encryption always uses `currentKey`; decryption accepts any key
|
|
33
|
+
* whose id appears in `currentKey` or `previousKeys`. Move the old key into
|
|
34
|
+
* `previousKeys`, set the new one as current, and either let secrets
|
|
35
|
+
* re-encrypt lazily on each user's next successful verify or run
|
|
36
|
+
* `migrateMfaSecrets()` to do them all at once.
|
|
37
|
+
*/
|
|
38
|
+
export class AesGcmSecretCipher {
|
|
39
|
+
/**
|
|
40
|
+
* @param {{ currentKey: string | { id?: string, key: string }, previousKeys?: Array<string | { id?: string, key: string }> }} opts
|
|
41
|
+
* Each key is 32 bytes, base64-encoded. A bare string's id is derived
|
|
42
|
+
* from a SHA-256 fingerprint of the key, so a single-key setup needs no
|
|
43
|
+
* id at all; pass `{ id, key }` to name keys explicitly.
|
|
44
|
+
*/
|
|
45
|
+
constructor({ currentKey, previousKeys = [] } = {}) {
|
|
46
|
+
if (!currentKey) throw new Error('AesGcmSecretCipher requires currentKey');
|
|
47
|
+
const current = normalizeKey(currentKey);
|
|
48
|
+
this._currentId = current.id;
|
|
49
|
+
this._keys = new Map([[current.id, current.key]]);
|
|
50
|
+
for (const entry of previousKeys) {
|
|
51
|
+
const { id, key } = normalizeKey(entry);
|
|
52
|
+
if (this._keys.has(id) && !this._keys.get(id).equals(key)) {
|
|
53
|
+
throw new Error(`MFA encryption key id "${id}" is configured twice with different key material`);
|
|
54
|
+
}
|
|
55
|
+
this._keys.set(id, key);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
get currentKeyId() {
|
|
60
|
+
return this._currentId;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
encrypt(plaintext, { context = '' } = {}) {
|
|
64
|
+
const iv = crypto.randomBytes(IV_BYTES);
|
|
65
|
+
const cipher = crypto.createCipheriv('aes-256-gcm', this._keys.get(this._currentId), iv, { authTagLength: TAG_BYTES });
|
|
66
|
+
cipher.setAAD(aad(context));
|
|
67
|
+
const ciphertext = Buffer.concat([cipher.update(String(plaintext), 'utf8'), cipher.final()]);
|
|
68
|
+
const tag = cipher.getAuthTag();
|
|
69
|
+
return [FORMAT_VERSION, this._currentId, b64u(iv), b64u(ciphertext), b64u(tag)].join(':');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
decrypt(stored, { context = '' } = {}) {
|
|
73
|
+
const { keyId, iv, ciphertext, tag } = parseStored(stored);
|
|
74
|
+
const key = this._keys.get(keyId);
|
|
75
|
+
if (!key) throw new Error(`No MFA encryption key configured for key id "${keyId}"`);
|
|
76
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv, { authTagLength: TAG_BYTES });
|
|
77
|
+
decipher.setAAD(aad(context));
|
|
78
|
+
decipher.setAuthTag(tag);
|
|
79
|
+
// final() throws on any tag mismatch — tampered ciphertext, wrong key
|
|
80
|
+
// material under a known id, or a different user's context all fail here.
|
|
81
|
+
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
needsRotation(stored) {
|
|
85
|
+
try {
|
|
86
|
+
return parseStored(stored).keyId !== this._currentId;
|
|
87
|
+
} catch {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Fingerprint-derived id for a key given without one — stable, short, and reveals nothing usable about a random 256-bit key. */
|
|
94
|
+
export function deriveKeyId(keyBuffer) {
|
|
95
|
+
return crypto.createHash('sha256').update(keyBuffer).digest('hex').slice(0, 12);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function normalizeKey(entry) {
|
|
99
|
+
const raw = typeof entry === 'string' ? entry : entry?.key;
|
|
100
|
+
if (typeof raw !== 'string' || raw.length === 0) throw new Error('MFA encryption key must be a base64-encoded string');
|
|
101
|
+
const key = Buffer.from(raw, 'base64');
|
|
102
|
+
// Buffer.from ignores anything it can't decode, so trailing garbage (or a typo) would silently
|
|
103
|
+
// yield a different key. The input must be exactly the base64 (or base64url) of the 32 bytes.
|
|
104
|
+
const canonical = (s) => s.trim().replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, '');
|
|
105
|
+
if (canonical(key.toString('base64')) !== canonical(raw)) {
|
|
106
|
+
throw new Error('MFA encryption key is not valid base64 — generate one with `openssl rand -base64 32`');
|
|
107
|
+
}
|
|
108
|
+
if (key.length !== 32) {
|
|
109
|
+
throw new Error(`MFA encryption key must decode to exactly 32 bytes (got ${key.length}) — generate one with \`openssl rand -base64 32\``);
|
|
110
|
+
}
|
|
111
|
+
const id = typeof entry === 'object' && entry.id ? entry.id : deriveKeyId(key);
|
|
112
|
+
if (!KEY_ID_PATTERN.test(id)) throw new Error(`MFA encryption key id "${id}" must match ${KEY_ID_PATTERN}`);
|
|
113
|
+
return { id, key };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function parseStored(stored) {
|
|
117
|
+
const parts = typeof stored === 'string' ? stored.split(':') : [];
|
|
118
|
+
if (parts.length !== 5 || parts[0] !== FORMAT_VERSION) throw new Error('Unrecognised encrypted MFA secret format');
|
|
119
|
+
const [, keyId, iv, ciphertext, tag] = parts;
|
|
120
|
+
return { keyId, iv: fromB64u(iv), ciphertext: fromB64u(ciphertext), tag: fromB64u(tag) };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function aad(context) {
|
|
124
|
+
return Buffer.from(`idp-mfa-secret:${context}`, 'utf8');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function b64u(buf) {
|
|
128
|
+
return buf.toString('base64url');
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function fromB64u(str) {
|
|
132
|
+
return Buffer.from(str, 'base64url');
|
|
133
|
+
}
|