@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,927 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
import { getState } from '../config/state.js';
|
|
3
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
4
|
+
import { IDENTITY_STATUS, COOKIE_NAMES, CACHE_KEY_PREFIXES, SESSION_KINDS } from '../config/constants.js';
|
|
5
|
+
import { sessionKindOf } from '../utils/session-kind.js';
|
|
6
|
+
import { issueAccessToken, issueMfaChallengeToken, hashOpaqueToken, generateOpaqueToken, lookupByTokenHash, opaqueTokenHashes, HASH_PURPOSES } from '../signing/token.service.js';
|
|
7
|
+
import { hashPassword, verifyPassword, compareDummyPassword } from '../utils/password.js';
|
|
8
|
+
import { buildDeviceFingerprint, notifyNewDevice } from '../utils/device-fingerprint.js';
|
|
9
|
+
import { newFamilyId, familyOf, familyEndsAt, cappedExpiry, handleRefreshReuse, revokeAllUserSessions, assertChainNotRevoked, assertFamilyNotRevoked, peekRefreshRow, currentSessionEpoch, resolveRefreshTokenHash } from '../utils/session-family.js';
|
|
10
|
+
import { auditLog, auditLogDetached, safeInvokeHook, invokeHookDetached } from '../hooks/index.js';
|
|
11
|
+
import { enforceRateLimit } from '../rate-limit/enforce.js';
|
|
12
|
+
import { ipKey, emailKey } from '../rate-limit/keys.js';
|
|
13
|
+
import { withAttemptBudget } from '../security/attempt-budget.js';
|
|
14
|
+
import { assertTrustedOrigin } from '../middleware/csrf.js';
|
|
15
|
+
import { effectiveStatus, isActiveAccount, isPasswordLocked } from '../utils/account-status.js';
|
|
16
|
+
import { sessionCookieName, cookiesAreSecure, hostCookieName, readCookie, refreshCookieNames, sessionCookiePath, refreshCookieBinding, readRefreshCookie } from '../utils/cookies.js';
|
|
17
|
+
import { bindLoginChallenge } from '../oauth2/login-challenge.js';
|
|
18
|
+
|
|
19
|
+
function cookieOptions(state) {
|
|
20
|
+
const c = state.config.cookies || {};
|
|
21
|
+
return {
|
|
22
|
+
httpOnly: true,
|
|
23
|
+
secure: cookiesAreSecure(state),
|
|
24
|
+
sameSite: c.sameSite || 'lax',
|
|
25
|
+
path: '/',
|
|
26
|
+
...(c.domain ? { domain: c.domain } : {}),
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function resolveClaims(state, user, ctx) {
|
|
31
|
+
const hook = state.hooks?.resolveAuthContext;
|
|
32
|
+
if (typeof hook !== 'function') return {};
|
|
33
|
+
const result = await hook(user, ctx);
|
|
34
|
+
return result?.claims ?? {};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Builds and persists one full login session (access + refresh token pair) — shared by login, MFA-verify-challenge, and SSO callback. */
|
|
38
|
+
/**
|
|
39
|
+
* The session is created in the user's `sessionEpoch` as read when this sign-in loaded the user —
|
|
40
|
+
* before it checked any credential — or, completing an MFA challenge, the epoch the challenge carries
|
|
41
|
+
* (read before the first factor). A "sign out everywhere" after that read (e.g. a password reset that
|
|
42
|
+
* landed while the old password was being checked) ends the session this call creates.
|
|
43
|
+
*/
|
|
44
|
+
async function issueSession(state, { user, claims, req, sessionEpoch: epochOverride, loginChallenge }) {
|
|
45
|
+
const sessionEpoch = Number.isInteger(epochOverride) ? epochOverride
|
|
46
|
+
: Number.isInteger(user.sessionEpoch) ? user.sessionEpoch : await currentSessionEpoch(state, user.id);
|
|
47
|
+
const wasFirstLogin = !user.lastLoginAt;
|
|
48
|
+
const deviceInfo = req.headers['user-agent'] || '';
|
|
49
|
+
const deviceFingerprint = buildDeviceFingerprint(deviceInfo);
|
|
50
|
+
|
|
51
|
+
// Every caller of issueSession has just authenticated the user (password+MFA, magic link, SSO, passkey).
|
|
52
|
+
const authTime = Math.floor(Date.now() / 1000);
|
|
53
|
+
const familyCreatedAt = new Date(authTime * 1000);
|
|
54
|
+
const accessToken = await issueAccessToken(state, { sub: String(user.id), email: user.email, claims }, { authTime });
|
|
55
|
+
const refreshTokenValue = generateOpaqueToken();
|
|
56
|
+
const refreshTokenHash = hashOpaqueToken(state, refreshTokenValue, HASH_PURPOSES.REFRESH_TOKEN);
|
|
57
|
+
const expiresAt = cappedExpiry(state, familyCreatedAt, state.config.ttls.refreshToken);
|
|
58
|
+
|
|
59
|
+
// Decided BEFORE this login's own session row exists — afterwards the device is always "known".
|
|
60
|
+
const isNewDevice = await isNewDeviceForUser(state, { user, deviceInfo, deviceFingerprint, wasFirstLogin });
|
|
61
|
+
|
|
62
|
+
// The login below clears the failed-password counter and lockUntil. A row locked before 0.4.0 also
|
|
63
|
+
// carries status LOCKED, which without a lockUntil would read as an administrative lock — so it is
|
|
64
|
+
// normalised here (see account-status.js).
|
|
65
|
+
if (user.status === IDENTITY_STATUS.LOCKED && user.lockUntil) {
|
|
66
|
+
await state.storage.userRepository.updateById(user.id, { status: IDENTITY_STATUS.ACTIVE });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const familyId = newFamilyId();
|
|
70
|
+
await state.storage.sessionRepository.createSessionForLogin({
|
|
71
|
+
accessTokenAudit: { user: user.id, tokenHash: hashOpaqueToken(state, accessToken.token, HASH_PURPOSES.ACCESS_TOKEN_AUDIT), expiresAt: accessToken.expiresAt, kid: accessToken.kid, jti: accessToken.jti, ipAddress: req.ip, deviceInfo },
|
|
72
|
+
session: {
|
|
73
|
+
user: user.id,
|
|
74
|
+
tokenHash: refreshTokenHash,
|
|
75
|
+
expiresAt,
|
|
76
|
+
kid: accessToken.kid,
|
|
77
|
+
// Shared correlation key: the session's jti equals the paired
|
|
78
|
+
// access token's jti, so a revocation-cache write keyed by this
|
|
79
|
+
// jti is checked by authContextMiddleware against the presented
|
|
80
|
+
// access token without a second lookup.
|
|
81
|
+
jti: accessToken.jti,
|
|
82
|
+
ipAddress: req.ip,
|
|
83
|
+
deviceInfo,
|
|
84
|
+
deviceFingerprint,
|
|
85
|
+
kind: SESSION_KINDS.FIRST_PARTY,
|
|
86
|
+
authTime: familyCreatedAt,
|
|
87
|
+
familyId,
|
|
88
|
+
familyCreatedAt,
|
|
89
|
+
sessionEpoch,
|
|
90
|
+
claims,
|
|
91
|
+
},
|
|
92
|
+
userId: user.id,
|
|
93
|
+
lastLoginAt: new Date(),
|
|
94
|
+
});
|
|
95
|
+
await assertChainNotRevoked(state, user.id, sessionEpoch, refreshTokenHash, familyId);
|
|
96
|
+
await bindLoginChallenge(state, loginChallenge, familyId);
|
|
97
|
+
|
|
98
|
+
if (isNewDevice) {
|
|
99
|
+
notifyNewDevice({ hooks: state.hooks, logger: state.logger, req, user }).catch((err) => {
|
|
100
|
+
state.logger?.warn?.({ err }, 'New-device notification failed (non-fatal)');
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return { accessToken, refreshTokenValue, refreshExpiresAt: expiresAt };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function isNewDeviceForUser(state, { user, deviceInfo, deviceFingerprint, wasFirstLogin }) {
|
|
108
|
+
if (wasFirstLogin || !deviceInfo) return false;
|
|
109
|
+
try {
|
|
110
|
+
return !(await state.storage.sessionRepository.existsForDevice(user.id, deviceFingerprint, deviceInfo));
|
|
111
|
+
} catch (err) {
|
|
112
|
+
state.logger?.warn?.({ err }, 'New-device detection failed (non-fatal)');
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Clears the session cookies with the attributes they were set with — a clear without the same `domain`/`path` leaves a domain cookie in place. */
|
|
118
|
+
function clearSessionCookies(req, res, state) {
|
|
119
|
+
const { httpOnly, secure, sameSite, path, domain } = cookieOptions(state);
|
|
120
|
+
const opts = { httpOnly, secure, sameSite, path, ...(domain ? { domain } : {}) };
|
|
121
|
+
const names = refreshCookieNames(state);
|
|
122
|
+
res.clearCookie(sessionCookieName(state, COOKIE_NAMES.ACCESS_TOKEN), opts);
|
|
123
|
+
res.clearCookie(names.token, { ...opts, path: sessionCookiePath(state, req) });
|
|
124
|
+
res.clearCookie(names.binding, opts);
|
|
125
|
+
// The refresh cookie of earlier 0.4.0 builds (Path=/) — so a browser doesn't keep sending a live token everywhere.
|
|
126
|
+
res.clearCookie(sessionCookieName(state, COOKIE_NAMES.REFRESH_TOKEN), opts);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Whether the refresh token also appears in a login/refresh JSON body (`config.cookies.refreshTokenInBody`):
|
|
131
|
+
* - `'auto'` (default) — only for non-browser clients. A browser request (it carries `Sec-Fetch-Site`
|
|
132
|
+
* or `Origin`, which page script can't remove) gets the token in its httpOnly cookie only, so script
|
|
133
|
+
* on the page (an XSS) never reads the long-lived token the cookie is protecting;
|
|
134
|
+
* - `true` — always (a browser app that keeps the refresh token itself, e.g. cross-site without cookies);
|
|
135
|
+
* - `false` — never.
|
|
136
|
+
*/
|
|
137
|
+
function refreshTokenInBody(state, req, value) {
|
|
138
|
+
const mode = state.config.cookies?.refreshTokenInBody ?? 'auto';
|
|
139
|
+
if (mode === false) return {};
|
|
140
|
+
if (mode === 'auto' && (req.headers?.['sec-fetch-site'] !== undefined || req.headers?.origin !== undefined)) return {};
|
|
141
|
+
return { refreshToken: value };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The access-token cookie (`Path=/`), and the refresh-token cookie scoped to the session endpoints with its binding (see readRefreshCookie). */
|
|
145
|
+
function setSessionCookies(req, res, state, { accessToken, refreshTokenValue, refreshExpiresAt }) {
|
|
146
|
+
const opts = cookieOptions(state);
|
|
147
|
+
const names = refreshCookieNames(state);
|
|
148
|
+
res.cookie(sessionCookieName(state, COOKIE_NAMES.ACCESS_TOKEN), accessToken.token, { ...opts, expires: accessToken.expiresAt });
|
|
149
|
+
res.cookie(names.token, refreshTokenValue, { ...opts, path: sessionCookiePath(state, req), expires: refreshExpiresAt });
|
|
150
|
+
res.cookie(names.binding, refreshCookieBinding(state, refreshTokenValue), { ...opts, expires: refreshExpiresAt });
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// ── Register ────────────────────────────────────────────────────────────────
|
|
154
|
+
|
|
155
|
+
export async function registerHandler(req, res, next) {
|
|
156
|
+
try {
|
|
157
|
+
const state = getState();
|
|
158
|
+
const { email, password, firstName, lastName, metadata } = req.body;
|
|
159
|
+
|
|
160
|
+
await enforceRateLimit(state, `register:ip:${ipKey(req.ip)}`, state.config.rateLimiting.register, { failMode: 'closed' });
|
|
161
|
+
await enforceRateLimit(state, `verification-email:${emailKey(state, email)}`, state.config.rateLimiting.verificationEmailByEmail, { failMode: 'closed' });
|
|
162
|
+
|
|
163
|
+
// Hashed on every path, so timing doesn't leak whether the email was new.
|
|
164
|
+
const passwordHash = await hashPassword(password, state.config.security.bcryptRounds);
|
|
165
|
+
const existing = await state.storage.userRepository.findByEmail(email);
|
|
166
|
+
// Every answer carries a ticket for the address (see issueVerificationTicket).
|
|
167
|
+
const ticket = await issueVerificationTicket(state, req, res, email);
|
|
168
|
+
const answer = () => res.status(201).json({ status: 'ok', verificationTicket: ticket });
|
|
169
|
+
|
|
170
|
+
if (existing?.status === IDENTITY_STATUS.PENDING_VERIFICATION) {
|
|
171
|
+
// A second registration for an address nobody has proven they own. Either order is an
|
|
172
|
+
// attack on the inbox owner: "attacker first" makes the victim's verification activate the
|
|
173
|
+
// attacker's password; "victim first" lets the attacker re-register right after the victim,
|
|
174
|
+
// so the newest code in the victim's inbox activates the attacker's password. So each code
|
|
175
|
+
// is bound to the password registered with it (on its own row), earlier codes stay valid,
|
|
176
|
+
// and from now on verifying needs that password too (`registrationContested`): the inbox
|
|
177
|
+
// owner activates THEIR registration, and a code from anyone else's is useless to them.
|
|
178
|
+
// (The account's profile stays as the first registration set it.)
|
|
179
|
+
// Conditional on the account STILL being pending: if its owner activated it since it was read
|
|
180
|
+
// (verify-email, magic link, SSO, reset), an unconditional write would put this registrant's
|
|
181
|
+
// password on a live account.
|
|
182
|
+
const contested = await state.storage.userRepository.updateByIdIfStatus(existing.id, IDENTITY_STATUS.PENDING_VERIFICATION, { passwordHash, registrationContested: true });
|
|
183
|
+
if (!contested) return answer();
|
|
184
|
+
const { token: verificationToken, verificationCode } = await createEmailVerificationToken(state, existing.id, passwordHash, email);
|
|
185
|
+
auditLogDetached(state.logger, state.hooks, 'REGISTRATION_REPEATED', { userId: String(existing.id) });
|
|
186
|
+
invokeHookDetached(state.logger, state.hooks, 'onVerificationEmailRequested', { email, firstName, lastName, verificationToken, verificationCode });
|
|
187
|
+
return answer();
|
|
188
|
+
}
|
|
189
|
+
if (existing) {
|
|
190
|
+
// An active (or otherwise settled) account is never touched by a registration.
|
|
191
|
+
return answer();
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const user = await state.storage.userRepository.create({
|
|
195
|
+
email,
|
|
196
|
+
passwordHash,
|
|
197
|
+
status: IDENTITY_STATUS.PENDING_VERIFICATION,
|
|
198
|
+
profile: { firstName, lastName },
|
|
199
|
+
// Written by whoever registers — persisted only when the app opted in (see registerSchema).
|
|
200
|
+
metadata: state.config.registration.acceptMetadata === true ? (metadata || {}) : {},
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
const { token: verificationToken, verificationCode } = await createEmailVerificationToken(state, user.id, passwordHash, email);
|
|
204
|
+
|
|
205
|
+
auditLogDetached(state.logger, state.hooks, 'REGISTERED', { userId: String(user.id), email });
|
|
206
|
+
invokeHookDetached(state.logger, state.hooks, 'onVerificationEmailRequested', { email, firstName, lastName, verificationToken, verificationCode });
|
|
207
|
+
|
|
208
|
+
answer();
|
|
209
|
+
} catch (err) {
|
|
210
|
+
next(err);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const INVALID_VERIFICATION = () => new IdpError({ code: 'INVALID_OR_EXPIRED_TOKEN', httpStatus: 400, message: 'Invalid or expired verification token' });
|
|
215
|
+
const VERIFICATION_LOCKED = () => new IdpError({ code: 'VERIFICATION_LOCKED', httpStatus: 429, message: 'Too many failed verification attempts — use the link in the verification email.' });
|
|
216
|
+
/** The lifetime cap's window: long enough to outlive any pending registration's codes. */
|
|
217
|
+
const CODE_LIFETIME_CAP_SECONDS = 365 * 24 * 60 * 60;
|
|
218
|
+
const REGISTRATION_PASSWORD_REQUIRED = () => new IdpError({
|
|
219
|
+
code: 'REGISTRATION_PASSWORD_REQUIRED',
|
|
220
|
+
httpStatus: 400,
|
|
221
|
+
message: 'This address was registered more than once before it was verified — enter the password you registered with, together with the code from that registration\'s email.',
|
|
222
|
+
});
|
|
223
|
+
const LEGACY_CODE = /^\d{6}$/;
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Verification tickets. The 6-digit code is guessable, so attempts at it are budgeted — and a budget
|
|
227
|
+
* anyone can spend is one a stranger can use up for the address's owner. So whoever registers (or asks
|
|
228
|
+
* for a resend) gets a ticket — a host-only cookie, also in the JSON body for clients without cookies —
|
|
229
|
+
* and code attempts carrying a ticket issued for that ADDRESS spend the ticket's own budget. Attempts
|
|
230
|
+
* without one share a per-address budget, which a stranger can use up without affecting the browser
|
|
231
|
+
* that registered (and the emailed link always works).
|
|
232
|
+
*
|
|
233
|
+
* Tickets are per address, not per account, and are stored for every caller whether or not the address
|
|
234
|
+
* has an account: what a ticket can do never depends on the account, so it can't tell anyone whether
|
|
235
|
+
* there is one. At most MAX_VERIFICATION_TICKETS are stored per address and code lifetime (later ones
|
|
236
|
+
* are handed out but not stored); a caller that already holds a live ticket for the address keeps it.
|
|
237
|
+
* Every budget lasts the code's lifetime, so the guesses at a code are bounded:
|
|
238
|
+
* maxFailedAttempts × (1 + MAX_VERIFICATION_TICKETS).
|
|
239
|
+
*/
|
|
240
|
+
const MAX_VERIFICATION_TICKETS = 5;
|
|
241
|
+
const ticketCookie = (state) => hostCookieName(cookiesAreSecure(state), 'verification_ticket');
|
|
242
|
+
const ticketKey = (state, email, hash) => `verification-ticket:${emailKey(state, email)}:${hash}`;
|
|
243
|
+
|
|
244
|
+
/** The code budgets' limits: never shorter than the code's lifetime, whatever is configured. */
|
|
245
|
+
function codeBudgetLimits(state) {
|
|
246
|
+
const ttl = state.config.ttls.emailVerification;
|
|
247
|
+
const { maxFailedAttempts, windowSeconds, lockSeconds } = state.config.security.verificationCodeLockout;
|
|
248
|
+
return { maxFailedAttempts, windowSeconds: Math.max(windowSeconds, ttl), lockSeconds: Math.max(lockSeconds, ttl) };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** The live ticket for `email` the request carries (`raw` from the body if given, else the cookie): `{ raw, hash }` or null. */
|
|
252
|
+
async function presentedTicket(state, email, raw) {
|
|
253
|
+
if (typeof raw !== 'string' || !raw) return null;
|
|
254
|
+
for (const hash of opaqueTokenHashes(state, raw, HASH_PURPOSES.EMAIL_VERIFICATION_TICKET)) {
|
|
255
|
+
const entry = await state.attemptCounters.get(ticketKey(state, email, hash));
|
|
256
|
+
if (entry && new Date(entry.windowExpiresAt) > new Date()) return { raw, hash };
|
|
257
|
+
}
|
|
258
|
+
return null;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Sets (and returns) the caller's ticket for `email` — the live one it holds, or a new one. Same work for every address. */
|
|
262
|
+
async function issueVerificationTicket(state, req, res, email) {
|
|
263
|
+
let ticket = (await presentedTicket(state, email, readCookie(req, ticketCookie(state))))?.raw;
|
|
264
|
+
if (!ticket) {
|
|
265
|
+
ticket = generateOpaqueToken(32);
|
|
266
|
+
const ttl = state.config.ttls.emailVerification;
|
|
267
|
+
const quota = await state.attemptCounters.recordFailure(`verification-tickets:${emailKey(state, email)}`, { max: MAX_VERIFICATION_TICKETS, windowSeconds: ttl, lockSeconds: ttl });
|
|
268
|
+
if (quota.count <= MAX_VERIFICATION_TICKETS) {
|
|
269
|
+
await state.attemptCounters.recordFailure(ticketKey(state, email, hashOpaqueToken(state, ticket, HASH_PURPOSES.EMAIL_VERIFICATION_TICKET)), { max: 1, windowSeconds: ttl, lockSeconds: ttl });
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
res.cookie(ticketCookie(state), ticket, {
|
|
273
|
+
httpOnly: true, secure: cookiesAreSecure(state), sameSite: 'lax', path: '/', maxAge: state.config.ttls.emailVerification * 1000,
|
|
274
|
+
});
|
|
275
|
+
return ticket;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** The password a verification activates: the one bound to its code (rows from before 0.4.0: the account's). */
|
|
279
|
+
const boundPasswordHash = (row, user) => row.passwordHash ?? user.passwordHash ?? null;
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* At most this many 6-digit codes are issued per address per code lifetime; later verification emails
|
|
283
|
+
* carry only the link (`verificationCode: null`). Every live code is a target for each guess (a
|
|
284
|
+
* contested registration keeps several live), so this bounds how many a guess is tried against.
|
|
285
|
+
*/
|
|
286
|
+
const MAX_CODES_PER_ADDRESS = 3;
|
|
287
|
+
|
|
288
|
+
/** `passwordHash`: the password of the registration this code verifies — the one it activates. */
|
|
289
|
+
async function createEmailVerificationToken(state, userId, passwordHash, email) {
|
|
290
|
+
const ttl = state.config.ttls.emailVerification;
|
|
291
|
+
const token = generateOpaqueToken(32);
|
|
292
|
+
const tokenHash = hashOpaqueToken(state, token, HASH_PURPOSES.EMAIL_VERIFICATION_LINK);
|
|
293
|
+
const quota = await state.attemptCounters.recordFailure(`verification-codes:${emailKey(state, email)}`, { max: MAX_CODES_PER_ADDRESS, windowSeconds: ttl, lockSeconds: ttl });
|
|
294
|
+
const verificationCode = quota.count <= MAX_CODES_PER_ADDRESS ? crypto.randomInt(100000, 1000000).toString() : null;
|
|
295
|
+
await state.storage.verificationTokenRepository.create('email_verification', {
|
|
296
|
+
user: userId,
|
|
297
|
+
tokenHash,
|
|
298
|
+
// Stored as an HMAC like every other token — a database read must not yield a usable code.
|
|
299
|
+
verificationCode: verificationCode ? hashOpaqueToken(state, verificationCode, HASH_PURPOSES.EMAIL_VERIFICATION_CODE) : null,
|
|
300
|
+
passwordHash: passwordHash ?? null,
|
|
301
|
+
expiresAt: new Date(Date.now() + ttl * 1000),
|
|
302
|
+
});
|
|
303
|
+
return { token, verificationCode };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export async function verifyEmailHandler(req, res, next) {
|
|
307
|
+
try {
|
|
308
|
+
const state = getState();
|
|
309
|
+
const { email, token, code, password } = req.body;
|
|
310
|
+
|
|
311
|
+
await enforceRateLimit(state, `email-verification:ip:${ipKey(req.ip)}`, state.config.rateLimiting.emailVerification, { failMode: 'closed' });
|
|
312
|
+
|
|
313
|
+
// One answer for an unknown address, an already-verified one, and a wrong code — none of
|
|
314
|
+
// them may reveal whether an account exists.
|
|
315
|
+
const user = await state.storage.userRepository.findByEmail(email, { select: '+passwordHash' });
|
|
316
|
+
const tokens = state.storage.verificationTokenRepository;
|
|
317
|
+
|
|
318
|
+
const verify = async () => {
|
|
319
|
+
if (!user || user.status !== IDENTITY_STATUS.PENDING_VERIFICATION) throw INVALID_VERIFICATION();
|
|
320
|
+
// Read, check, THEN consume — a refused attempt never takes the code out of circulation.
|
|
321
|
+
const row = token
|
|
322
|
+
? (await lookupByTokenHash(state, token, HASH_PURPOSES.EMAIL_VERIFICATION_LINK, (tokenHash) => tokens.findActive('email_verification', { tokenHash }, user.id))).result
|
|
323
|
+
: (await lookupByTokenHash(state, code, HASH_PURPOSES.EMAIL_VERIFICATION_CODE, (verificationCode) => tokens.findActive('email_verification', { verificationCode }, user.id))).result
|
|
324
|
+
// Codes issued before 0.4.0 were stored in plain text (they expire within a day). Only
|
|
325
|
+
// a real 6-digit code is tried that way — never a value read from the database, which
|
|
326
|
+
// is now the code's HMAC and would otherwise be accepted as-is.
|
|
327
|
+
?? (LEGACY_CODE.test(code) ? await tokens.findActive('email_verification', { verificationCode: code }, user.id) : null);
|
|
328
|
+
if (!row) throw INVALID_VERIFICATION();
|
|
329
|
+
if (user.registrationContested) {
|
|
330
|
+
// No password: say what's missing. A wrong one: the same answer as a wrong code.
|
|
331
|
+
if (!password) throw REGISTRATION_PASSWORD_REQUIRED();
|
|
332
|
+
if (!(await verifyPassword(password, boundPasswordHash(row, user)))) throw INVALID_VERIFICATION();
|
|
333
|
+
}
|
|
334
|
+
const consumed = token
|
|
335
|
+
? await tokens.consumeByHash('email_verification', row.tokenHash, user.id)
|
|
336
|
+
: await tokens.consumeByCode('email_verification', row.verificationCode, user.id);
|
|
337
|
+
if (!consumed) throw INVALID_VERIFICATION(); // a concurrent request used it first
|
|
338
|
+
return consumed;
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
// The 6-digit CODE is guessable, so attempts at it are budgeted: per verification ticket when the
|
|
342
|
+
// request carries a live one for this address (see issueVerificationTicket), otherwise per ADDRESS
|
|
343
|
+
// — the same for unknown, verified and pending addresses, so nothing here says which it is. A
|
|
344
|
+
// spent budget locks only its own attempts: the codes stay valid for the ticket holder, and the
|
|
345
|
+
// 256-bit link can't be guessed at all.
|
|
346
|
+
const pendingUser = user?.status === IDENTITY_STATUS.PENDING_VERIFICATION ? user : null;
|
|
347
|
+
const ticket = token ? null : await presentedTicket(state, email, typeof req.body.ticket === 'string' ? req.body.ticket : readCookie(req, ticketCookie(state)));
|
|
348
|
+
const budgetKey = ticket ? `email-verification:ticket:${ticket.hash}` : `email-verification:${emailKey(state, email)}`;
|
|
349
|
+
// Inside that budget, every guess also counts toward the address's year-long cap
|
|
350
|
+
// (`maxTotalFailedAttempts`, ticket or not): however long someone keeps registering and guessing,
|
|
351
|
+
// codes for this address are guessed at most that many times a year — then only the link works.
|
|
352
|
+
// The trade-off, deliberately: anyone can spend the cap and switch an address to link-only (for its
|
|
353
|
+
// registrant too). Exempting the registrant's ticket would also exempt an attacker who registers
|
|
354
|
+
// the same address, and each such ticket would be guesses beyond any bound.
|
|
355
|
+
const capped = () => withAttemptBudget(state, `email-verification-total:${emailKey(state, email)}`, {
|
|
356
|
+
maxFailedAttempts: state.config.security.verificationCodeLockout.maxTotalFailedAttempts, windowSeconds: CODE_LIFETIME_CAP_SECONDS, lockSeconds: CODE_LIFETIME_CAP_SECONDS,
|
|
357
|
+
}, { lockedError: VERIFICATION_LOCKED }, verify);
|
|
358
|
+
const found = token ? await verify() : await withAttemptBudget(state, budgetKey, codeBudgetLimits(state), {
|
|
359
|
+
lockedError: VERIFICATION_LOCKED,
|
|
360
|
+
onLocked: async () => {
|
|
361
|
+
if (!pendingUser) return;
|
|
362
|
+
await auditLog(state.logger, state.hooks, 'EMAIL_VERIFICATION_LOCKED', { userId: String(pendingUser.id), withTicket: Boolean(ticket) });
|
|
363
|
+
},
|
|
364
|
+
}, capped);
|
|
365
|
+
|
|
366
|
+
const activated = await state.storage.userRepository.updateByIdIfStatus(user.id, IDENTITY_STATUS.PENDING_VERIFICATION, {
|
|
367
|
+
status: IDENTITY_STATUS.ACTIVE, failedLoginAttempts: 0, lockUntil: null,
|
|
368
|
+
passwordHash: boundPasswordHash(found, user), registrationContested: false,
|
|
369
|
+
});
|
|
370
|
+
if (!activated) throw INVALID_VERIFICATION(); // settled meanwhile by another path
|
|
371
|
+
await state.storage.verificationTokenRepository.deleteAllForUser('email_verification', user.id);
|
|
372
|
+
if (ticket) await state.attemptCounters.reset(ticketKey(state, email, ticket.hash));
|
|
373
|
+
res.clearCookie(ticketCookie(state), { httpOnly: true, secure: cookiesAreSecure(state), sameSite: 'lax', path: '/' });
|
|
374
|
+
|
|
375
|
+
await auditLog(state.logger, state.hooks, 'EMAIL_VERIFIED', { userId: String(user.id), email });
|
|
376
|
+
|
|
377
|
+
res.json({ status: 'ok', userId: String(user.id), email: user.email });
|
|
378
|
+
} catch (err) {
|
|
379
|
+
next(err);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export async function resendVerificationEmailHandler(req, res, next) {
|
|
384
|
+
try {
|
|
385
|
+
const state = getState();
|
|
386
|
+
const { email } = req.body;
|
|
387
|
+
|
|
388
|
+
await enforceRateLimit(state, `register:ip:${ipKey(req.ip)}`, state.config.rateLimiting.register, { failMode: 'closed' });
|
|
389
|
+
await enforceRateLimit(state, `verification-email:${emailKey(state, email)}`, state.config.rateLimiting.verificationEmailByEmail, { failMode: 'closed' });
|
|
390
|
+
|
|
391
|
+
// Same answer — and the same timing — for unknown, already-verified and pending addresses: the
|
|
392
|
+
// lookup and the writes run after the response (see runAfterResponse). The ticket is issued the
|
|
393
|
+
// same way for every address (see issueVerificationTicket).
|
|
394
|
+
const ticket = await issueVerificationTicket(state, req, res, email);
|
|
395
|
+
res.json({ status: 'ok', verificationTicket: ticket });
|
|
396
|
+
runAfterResponse(state, 'Resend of the verification email', async () => {
|
|
397
|
+
const user = await state.storage.userRepository.findByEmail(email, { select: '+passwordHash' });
|
|
398
|
+
if (!user || user.status !== IDENTITY_STATUS.PENDING_VERIFICATION) return;
|
|
399
|
+
|
|
400
|
+
// Normally only the newest code works. While registrations compete for the address, each
|
|
401
|
+
// one's code stays valid (the new one is bound to the most recent registration's password).
|
|
402
|
+
if (!user.registrationContested) await state.storage.verificationTokenRepository.deleteAllForUser('email_verification', user.id);
|
|
403
|
+
const { token, verificationCode } = await createEmailVerificationToken(state, user.id, user.passwordHash, email);
|
|
404
|
+
|
|
405
|
+
auditLogDetached(state.logger, state.hooks, 'VERIFICATION_TOKEN_REGENERATED', { userId: String(user.id) });
|
|
406
|
+
invokeHookDetached(state.logger, state.hooks, 'onVerificationEmailRequested', {
|
|
407
|
+
email, firstName: user.profile?.firstName, lastName: user.profile?.lastName, verificationToken: token, verificationCode,
|
|
408
|
+
});
|
|
409
|
+
});
|
|
410
|
+
} catch (err) {
|
|
411
|
+
next(err);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* For the enumeration-sensitive "send me an email" endpoints: the answer is the same for every address,
|
|
417
|
+
* and so must be the time it takes — a lookup plus writes for a real account, nothing for an unknown
|
|
418
|
+
* one, is measurable. The work runs after the response is sent; a failure is logged (the caller has
|
|
419
|
+
* been told "ok" either way, exactly as it would be for an unknown address).
|
|
420
|
+
*/
|
|
421
|
+
function runAfterResponse(state, what, work) {
|
|
422
|
+
setImmediate(() => {
|
|
423
|
+
work().catch((err) => state.logger?.error?.({ err }, `${what} failed`));
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// ── Login ────────────────────────────────────────────────────────────────
|
|
428
|
+
|
|
429
|
+
export async function loginHandler(req, res, next) {
|
|
430
|
+
try {
|
|
431
|
+
const state = getState();
|
|
432
|
+
const { email, password } = req.body;
|
|
433
|
+
assertTrustedOrigin(state, req); // sets session cookies — refuse login CSRF (see middleware/csrf.js)
|
|
434
|
+
|
|
435
|
+
await enforceRateLimit(state, `login:ip:${ipKey(req.ip)}`, state.config.rateLimiting.login, { failMode: 'closed' });
|
|
436
|
+
await enforceRateLimit(state, `login:email:${emailKey(state, email)}`, state.config.rateLimiting.loginByEmail, { failMode: 'closed' });
|
|
437
|
+
|
|
438
|
+
// Loaded BEFORE the password is checked: its sessionEpoch is the one the new session belongs to.
|
|
439
|
+
const user = await state.storage.userRepository.findByEmail(email, { select: '+passwordHash' });
|
|
440
|
+
|
|
441
|
+
if (user?.lockUntil && new Date(user.lockUntil) <= new Date()) {
|
|
442
|
+
// A lock recorded on the account before 0.4.0 has run out (it was also a LOCKED status then).
|
|
443
|
+
const statusFix = user.status === IDENTITY_STATUS.LOCKED ? { status: IDENTITY_STATUS.ACTIVE } : {};
|
|
444
|
+
await state.storage.userRepository.updateById(user.id, { failedLoginAttempts: 0, lockUntil: null, ...statusFix });
|
|
445
|
+
Object.assign(user, { failedLoginAttempts: 0, lockUntil: null, ...statusFix });
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
const passwordValid = user ? await checkPasswordWithBudget(state, user, password) : (await compareDummyPassword(password), false);
|
|
449
|
+
|
|
450
|
+
// While password login is locked, the right password and a wrong one get the same answer —
|
|
451
|
+
// otherwise the lock becomes a password oracle: guessing continues, and the one guess answered
|
|
452
|
+
// "locked" instead of "invalid" is the password, ready for when the lock lifts. (The lock itself
|
|
453
|
+
// was announced through onSuspiciousActivityDetected; a password reset lifts it, and every other
|
|
454
|
+
// sign-in method keeps working meanwhile.)
|
|
455
|
+
//
|
|
456
|
+
// A not-yet-verified account answers the same as a wrong password, right password or not: a
|
|
457
|
+
// distinct "pending" answer for the right one tells whoever registered it whether their password
|
|
458
|
+
// is still the current one — i.e. exactly when someone else registered the same address.
|
|
459
|
+
if (!user || !passwordValid || isPasswordLocked(user) || effectiveStatus(user) === IDENTITY_STATUS.PENDING_VERIFICATION) {
|
|
460
|
+
throw new IdpError({ code: 'INVALID_CREDENTIALS', httpStatus: 401, message: 'Invalid email or password' });
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
assertUsableStatus(user);
|
|
464
|
+
|
|
465
|
+
const loginChallenge = req.body.login_challenge;
|
|
466
|
+
if (user.mfaEnabled) return res.json(await mfaChallengeResponse(state, user, { loginChallenge }));
|
|
467
|
+
|
|
468
|
+
const claims = await resolveClaims(state, user, { isNewUser: false, method: 'password' });
|
|
469
|
+
const session = await issueSession(state, { user, claims, req, loginChallenge });
|
|
470
|
+
|
|
471
|
+
await auditLog(state.logger, state.hooks, 'LOGIN', { userId: String(user.id), email });
|
|
472
|
+
|
|
473
|
+
setSessionCookies(req, res, state, session);
|
|
474
|
+
res.json({
|
|
475
|
+
accessToken: session.accessToken.token,
|
|
476
|
+
accessTokenExpiresAt: session.accessToken.expiresAt,
|
|
477
|
+
...refreshTokenInBody(state, req, session.refreshTokenValue),
|
|
478
|
+
refreshTokenExpiresAt: session.refreshExpiresAt,
|
|
479
|
+
userId: String(user.id),
|
|
480
|
+
});
|
|
481
|
+
} catch (err) {
|
|
482
|
+
next(err);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
const passwordLoginKey = (userId) => `password-login:${userId}`;
|
|
487
|
+
const WRONG_PASSWORD = 'WRONG_PASSWORD';
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* Checks the password inside the per-account attempt budget (`maxFailedLoginAttempts` per
|
|
491
|
+
* `accountLockDurationMs`, then locked as long) — PASSWORD login only, never the account. The attempt
|
|
492
|
+
* is counted BEFORE bcrypt runs, so a concurrent burst gets no more guesses than the budget (counting
|
|
493
|
+
* after a failure let every request of a burst be checked). A success resets the count; other sign-in
|
|
494
|
+
* methods don't touch it, so the owner signing in by magic link doesn't hand a guesser a fresh budget.
|
|
495
|
+
* Returns whether the password is right; false while locked. A locked attempt still spends a bcrypt
|
|
496
|
+
* compare, so its timing doesn't stand out.
|
|
497
|
+
*/
|
|
498
|
+
async function checkPasswordWithBudget(state, user, password) {
|
|
499
|
+
// Nothing to guess (no password) or nothing to sign in to yet (pending): no budget to spend, and no
|
|
500
|
+
// "suspicious activity" mail an attacker could trigger at will. The compare still runs, for timing.
|
|
501
|
+
if (!user.passwordHash || !isActiveAccount(user)) return verifyPassword(password, user.passwordHash);
|
|
502
|
+
const { maxFailedLoginAttempts, accountLockDurationMs } = state.config.security;
|
|
503
|
+
const seconds = Math.ceil(accountLockDurationMs / 1000);
|
|
504
|
+
let checked = false;
|
|
505
|
+
try {
|
|
506
|
+
return await withAttemptBudget(state, passwordLoginKey(user.id), { maxFailedAttempts: maxFailedLoginAttempts, windowSeconds: seconds, lockSeconds: seconds }, {
|
|
507
|
+
lockedError: () => Object.assign(new Error('password login locked'), { code: 'PASSWORD_LOGIN_LOCKED' }),
|
|
508
|
+
isFailure: (err) => err?.code === WRONG_PASSWORD,
|
|
509
|
+
onLocked: (entry) => onPasswordLoginLocked(state, user, entry),
|
|
510
|
+
}, async () => {
|
|
511
|
+
checked = true;
|
|
512
|
+
if (!(await verifyPassword(password, user.passwordHash))) throw Object.assign(new Error('wrong password'), { code: WRONG_PASSWORD });
|
|
513
|
+
return true;
|
|
514
|
+
});
|
|
515
|
+
} catch (err) {
|
|
516
|
+
if (err?.code === WRONG_PASSWORD) return false;
|
|
517
|
+
if (err?.code === 'PASSWORD_LOGIN_LOCKED') {
|
|
518
|
+
if (!checked) await compareDummyPassword(password);
|
|
519
|
+
return false;
|
|
520
|
+
}
|
|
521
|
+
throw err;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
async function onPasswordLoginLocked(state, user, entry) {
|
|
526
|
+
const failedAttempts = entry?.count ?? state.config.security.maxFailedLoginAttempts;
|
|
527
|
+
const unlocksAt = new Date(Date.now() + state.config.security.accountLockDurationMs);
|
|
528
|
+
await auditLog(state.logger, state.hooks, 'ACCOUNT_LOCKED', { userId: String(user.id), failedAttempts });
|
|
529
|
+
await safeInvokeHook(state.logger, state.hooks, 'onSuspiciousActivityDetected', {
|
|
530
|
+
userId: String(user.id), email: user.email, firstName: user.profile?.firstName || '', lastName: user.profile?.lastName || '',
|
|
531
|
+
locale: user.profile?.locale || 'en', when: new Date().toISOString(), failedAttempts, unlocksAt: unlocksAt.toISOString(),
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* The response every first-factor login (password, magic link, SSO) gives instead of a session when
|
|
537
|
+
* the account has MFA: a short-lived challenge token to complete at /mfa/verify or /webauthn/mfa/verify.
|
|
538
|
+
*/
|
|
539
|
+
async function mfaChallengeResponse(state, user, { loginChallenge } = {}) {
|
|
540
|
+
// `user` was loaded before its first factor was checked: the challenge carries that epoch.
|
|
541
|
+
const sessionEpoch = Number.isInteger(user.sessionEpoch) ? user.sessionEpoch : await currentSessionEpoch(state, user.id);
|
|
542
|
+
const mfaChallengeToken = await issueMfaChallengeToken(state, user.id, { sessionEpoch, loginChallenge });
|
|
543
|
+
return { mfaRequired: true, mfaChallengeToken, expiresIn: state.config.ttls.mfaChallenge };
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/** Refuses an account that may not sign in. A password lockout is not checked here — see account-status.js. */
|
|
547
|
+
function assertUsableStatus(user) {
|
|
548
|
+
switch (effectiveStatus(user)) {
|
|
549
|
+
case IDENTITY_STATUS.LOCKED:
|
|
550
|
+
throw new IdpError({ code: 'ACCOUNT_LOCKED', httpStatus: 423, message: 'Account is locked' });
|
|
551
|
+
case IDENTITY_STATUS.SUSPENDED:
|
|
552
|
+
case IDENTITY_STATUS.DISABLED:
|
|
553
|
+
throw new IdpError({ code: 'ACCOUNT_SUSPENDED', httpStatus: 403, message: 'Account is suspended' });
|
|
554
|
+
case IDENTITY_STATUS.PENDING_VERIFICATION:
|
|
555
|
+
case IDENTITY_STATUS.INVITED:
|
|
556
|
+
throw new IdpError({ code: 'PENDING_VERIFICATION', httpStatus: 403, message: 'Account is pending verification' });
|
|
557
|
+
case IDENTITY_STATUS.DELETED:
|
|
558
|
+
throw new IdpError({ code: 'INVALID_CREDENTIALS', httpStatus: 401, message: 'Invalid email or password' });
|
|
559
|
+
case IDENTITY_STATUS.ACTIVE:
|
|
560
|
+
return;
|
|
561
|
+
default:
|
|
562
|
+
throw new IdpError({ code: 'USER_NOT_ACTIVE', httpStatus: 403, message: 'User account is not active' });
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// ── Refresh / logout ────────────────────────────────────────────────────────
|
|
567
|
+
|
|
568
|
+
export async function refreshTokenHandler(req, res, next) {
|
|
569
|
+
try {
|
|
570
|
+
const state = getState();
|
|
571
|
+
await enforceRateLimit(state, `refresh:ip:${ipKey(req.ip)}`, state.config.rateLimiting.refreshToken);
|
|
572
|
+
|
|
573
|
+
// Checked first, and for a body token too: /session/refresh sets session cookies, so a form posting
|
|
574
|
+
// the ATTACKER's refresh token from a sibling origin would sign the victim's browser into the
|
|
575
|
+
// attacker's account.
|
|
576
|
+
assertTrustedOrigin(state, req);
|
|
577
|
+
// A token in the body is explicit and wins over the cookie.
|
|
578
|
+
const refreshTokenValue = req.body?.refreshToken || readRefreshCookie(state, req);
|
|
579
|
+
if (!refreshTokenValue) throw new IdpError({ code: 'REFRESH_TOKEN_REQUIRED', httpStatus: 400, message: 'Refresh token is required' });
|
|
580
|
+
|
|
581
|
+
const tokenHash = await resolveRefreshTokenHash(state, refreshTokenValue);
|
|
582
|
+
// Everything that can refuse or fail runs BEFORE the token is consumed: a refusal (an inactive
|
|
583
|
+
// account, a claims hook that throws, the family's end) must not burn it — a burnt token's
|
|
584
|
+
// retry would look like reuse and revoke the whole family.
|
|
585
|
+
const row = await peekRefreshRow(state, tokenHash);
|
|
586
|
+
if (!row) {
|
|
587
|
+
await handleRefreshReuse(state, tokenHash);
|
|
588
|
+
throw new IdpError({ code: 'INVALID_REFRESH_TOKEN', httpStatus: 401, message: 'Invalid or expired refresh token' });
|
|
589
|
+
}
|
|
590
|
+
// An OAuth2 client's refresh token is redeemable only at /oauth2/token by that client — never
|
|
591
|
+
// here, where it would mint a first-party session without client authentication. It is revoked
|
|
592
|
+
// (not as a rotation), since a client token showing up here means it leaked.
|
|
593
|
+
if (sessionKindOf(row) !== SESSION_KINDS.FIRST_PARTY) {
|
|
594
|
+
await state.storage.sessionRepository.revokeByRefreshTokenHash(tokenHash, { reason: 'misused' });
|
|
595
|
+
state.logger?.warn?.({ userId: String(row.user) }, 'OAuth2 refresh token presented at /refresh — refused and revoked');
|
|
596
|
+
throw new IdpError({ code: 'INVALID_REFRESH_TOKEN', httpStatus: 401, message: 'Invalid or expired refresh token' });
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// A full user, so resolveAuthContext gets the same shape of `user` as on every login path.
|
|
600
|
+
const user = await state.storage.userRepository.findById(row.user);
|
|
601
|
+
if (!isActiveAccount(user)) throw new IdpError({ code: 'USER_NOT_ACTIVE', httpStatus: 403, message: 'User account is not active' });
|
|
602
|
+
|
|
603
|
+
// The family's absolute end applies however actively it's been refreshed.
|
|
604
|
+
const { familyId, familyCreatedAt } = familyOf(row);
|
|
605
|
+
if (familyEndsAt(state, familyCreatedAt) <= new Date()) {
|
|
606
|
+
throw new IdpError({ code: 'INVALID_REFRESH_TOKEN', httpStatus: 401, message: 'Session has reached its maximum lifetime — please sign in again' });
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
const claims = state.config.session.reresolveClaimsOnRefresh
|
|
610
|
+
? await resolveClaims(state, user, { isNewUser: false, method: 'refresh' })
|
|
611
|
+
: row.claims || {};
|
|
612
|
+
|
|
613
|
+
// Now consume — atomically: of two concurrent refreshes with one token, only one gets here.
|
|
614
|
+
const existing = await state.storage.sessionRepository.revokeByRefreshTokenHash(tokenHash, { reason: 'rotated' });
|
|
615
|
+
if (!existing) {
|
|
616
|
+
await handleRefreshReuse(state, tokenHash);
|
|
617
|
+
throw new IdpError({ code: 'INVALID_REFRESH_TOKEN', httpStatus: 401, message: 'Invalid or expired refresh token' });
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
// A refresh is not an authentication: the original login time carries over (a row from
|
|
621
|
+
// before 0.4.0 has none, which requireRecentAuth treats as "not recent").
|
|
622
|
+
const authTime = existing.authTime ? Math.floor(new Date(existing.authTime).getTime() / 1000) : undefined;
|
|
623
|
+
const accessToken = await issueAccessToken(state, { sub: String(user.id), email: user.email, claims }, { authTime });
|
|
624
|
+
const newRefreshTokenValue = generateOpaqueToken();
|
|
625
|
+
const newRefreshTokenHash = hashOpaqueToken(state, newRefreshTokenValue, HASH_PURPOSES.REFRESH_TOKEN);
|
|
626
|
+
const refreshExpiresAt = cappedExpiry(state, familyCreatedAt, state.config.ttls.refreshToken);
|
|
627
|
+
const deviceInfo = req.headers['user-agent'] || existing.deviceInfo || '';
|
|
628
|
+
|
|
629
|
+
await state.storage.sessionRepository.createSession({
|
|
630
|
+
user: user.id,
|
|
631
|
+
tokenHash: newRefreshTokenHash,
|
|
632
|
+
expiresAt: refreshExpiresAt,
|
|
633
|
+
kid: accessToken.kid,
|
|
634
|
+
jti: accessToken.jti,
|
|
635
|
+
ipAddress: req.ip,
|
|
636
|
+
deviceInfo,
|
|
637
|
+
deviceFingerprint: buildDeviceFingerprint(deviceInfo),
|
|
638
|
+
kind: SESSION_KINDS.FIRST_PARTY,
|
|
639
|
+
authTime: existing.authTime ?? null,
|
|
640
|
+
familyId,
|
|
641
|
+
familyCreatedAt,
|
|
642
|
+
sessionEpoch: existing.sessionEpoch ?? 0,
|
|
643
|
+
claims,
|
|
644
|
+
});
|
|
645
|
+
await assertChainNotRevoked(state, user.id, existing.sessionEpoch ?? 0, newRefreshTokenHash, familyId);
|
|
646
|
+
await assertFamilyNotRevoked(state, familyId, newRefreshTokenHash);
|
|
647
|
+
|
|
648
|
+
await state.cache.set(`${CACHE_KEY_PREFIXES.REVOKED_REFRESH_TOKEN}:${existing.jti}`, '1', state.config.ttls.revocationCache);
|
|
649
|
+
|
|
650
|
+
await auditLog(state.logger, state.hooks, 'TOKEN_REFRESHED', { userId: String(user.id) });
|
|
651
|
+
|
|
652
|
+
setSessionCookies(req, res, state, { accessToken, refreshTokenValue: newRefreshTokenValue, refreshExpiresAt });
|
|
653
|
+
res.json({ accessToken: accessToken.token, accessTokenExpiresAt: accessToken.expiresAt, ...refreshTokenInBody(state, req, newRefreshTokenValue), refreshTokenExpiresAt: refreshExpiresAt });
|
|
654
|
+
} catch (err) {
|
|
655
|
+
next(err);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
export async function logoutHandler(req, res, next) {
|
|
660
|
+
try {
|
|
661
|
+
const state = getState();
|
|
662
|
+
// Every browser request, body token or not: logout clears the session cookies, so a cross-site
|
|
663
|
+
// form posting any token would otherwise sign the victim out (logout CSRF).
|
|
664
|
+
assertTrustedOrigin(state, req);
|
|
665
|
+
let refreshTokenValue;
|
|
666
|
+
try {
|
|
667
|
+
refreshTokenValue = req.body?.refreshToken || readRefreshCookie(state, req);
|
|
668
|
+
} catch (err) {
|
|
669
|
+
clearSessionCookies(req, res, state); // conflicting cookies (cookies.domain): still sign the browser out
|
|
670
|
+
throw err;
|
|
671
|
+
}
|
|
672
|
+
if (!refreshTokenValue) {
|
|
673
|
+
// Nothing usable to revoke (no cookie, or only one planted without its binding): the browser's
|
|
674
|
+
// cookies are cleared all the same.
|
|
675
|
+
clearSessionCookies(req, res, state);
|
|
676
|
+
throw new IdpError({ code: 'REFRESH_TOKEN_REQUIRED', httpStatus: 400, message: 'Refresh token is required to log out' });
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
const tokenHash = await resolveRefreshTokenHash(state, refreshTokenValue);
|
|
680
|
+
const existing = await state.storage.sessionRepository.revokeByRefreshTokenHash(tokenHash, { onlyIfActive: false });
|
|
681
|
+
if (existing?.jti) {
|
|
682
|
+
await state.cache.set(`${CACHE_KEY_PREFIXES.REVOKED_REFRESH_TOKEN}:${existing.jti}`, '1', state.config.ttls.revocationCache);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
await auditLog(state.logger, state.hooks, 'LOGOUT', { userId: String(existing?.user ?? req.auth?.userId ?? 'unknown') });
|
|
686
|
+
clearSessionCookies(req, res, state);
|
|
687
|
+
res.json({ status: 'ok' });
|
|
688
|
+
} catch (err) {
|
|
689
|
+
next(err);
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
export async function logoutAllHandler(req, res, next) {
|
|
694
|
+
try {
|
|
695
|
+
const state = getState();
|
|
696
|
+
if (!req.auth?.userId) throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Authentication required' });
|
|
697
|
+
|
|
698
|
+
await revokeAllUserSessions(state, req.auth.userId);
|
|
699
|
+
await auditLog(state.logger, state.hooks, 'LOGOUT_ALL', { userId: req.auth.userId });
|
|
700
|
+
res.json({ status: 'ok' });
|
|
701
|
+
} catch (err) {
|
|
702
|
+
next(err);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// ── Password ─────────────────────────────────────────────────────────────
|
|
707
|
+
|
|
708
|
+
export async function forgotPasswordHandler(req, res, next) {
|
|
709
|
+
try {
|
|
710
|
+
const state = getState();
|
|
711
|
+
const { email } = req.body;
|
|
712
|
+
|
|
713
|
+
await enforceRateLimit(state, `password-reset:ip:${ipKey(req.ip)}`, state.config.rateLimiting.passwordReset, { failMode: 'closed' });
|
|
714
|
+
// Per address too: per-IP alone lets a distributed sender flood one inbox.
|
|
715
|
+
await enforceRateLimit(state, `password-reset:email:${emailKey(state, email)}`, state.config.rateLimiting.passwordResetByEmail, { failMode: 'closed' });
|
|
716
|
+
|
|
717
|
+
// Enumeration-safe: the same answer at the same speed for every address.
|
|
718
|
+
res.json({ status: 'ok' });
|
|
719
|
+
runAfterResponse(state, 'Password-reset request', async () => {
|
|
720
|
+
const user = await state.storage.userRepository.findByEmail(email);
|
|
721
|
+
if (!user || user.status === IDENTITY_STATUS.DELETED) return;
|
|
722
|
+
|
|
723
|
+
// Only the newest link works: requesting another replaces the earlier one (atomically, so
|
|
724
|
+
// concurrent requests can't leave several live links).
|
|
725
|
+
const resetToken = generateOpaqueToken(32);
|
|
726
|
+
await state.storage.verificationTokenRepository.replaceForUser('password_reset', user.id, {
|
|
727
|
+
tokenHash: hashOpaqueToken(state, resetToken, HASH_PURPOSES.PASSWORD_RESET),
|
|
728
|
+
expiresAt: new Date(Date.now() + state.config.ttls.passwordReset * 1000),
|
|
729
|
+
});
|
|
730
|
+
|
|
731
|
+
invokeHookDetached(state.logger, state.hooks, 'onPasswordResetRequested', {
|
|
732
|
+
email, resetToken, firstName: user.profile?.firstName, lastName: user.profile?.lastName,
|
|
733
|
+
});
|
|
734
|
+
});
|
|
735
|
+
} catch (err) {
|
|
736
|
+
next(err);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
export async function resetPasswordHandler(req, res, next) {
|
|
741
|
+
try {
|
|
742
|
+
const state = getState();
|
|
743
|
+
const { email, token, newPassword } = req.body;
|
|
744
|
+
|
|
745
|
+
const user = await state.storage.userRepository.findByEmail(email);
|
|
746
|
+
if (!user) throw new IdpError({ code: 'INVALID_OR_EXPIRED_TOKEN', httpStatus: 400, message: 'Invalid or expired token' });
|
|
747
|
+
|
|
748
|
+
const { result: record } = await lookupByTokenHash(state, token, HASH_PURPOSES.PASSWORD_RESET, (hash) => state.storage.verificationTokenRepository.consumeByHash('password_reset', hash, user.id));
|
|
749
|
+
if (!record) throw new IdpError({ code: 'INVALID_OR_EXPIRED_TOKEN', httpStatus: 400, message: 'Invalid or expired token' });
|
|
750
|
+
|
|
751
|
+
const passwordHash = await hashPassword(newPassword, state.config.security.bcryptRounds);
|
|
752
|
+
// Proving the inbox and setting a new password also lifts a lockout (the lock exists to stop
|
|
753
|
+
// password guessing — the guessed password is gone).
|
|
754
|
+
const changes = { passwordHash, passwordChangedAt: new Date(), failedLoginAttempts: 0, lockUntil: null };
|
|
755
|
+
// On a never-verified account the reset is ALSO the verification — it proved the inbox, like a
|
|
756
|
+
// magic link. Left pending, the account's outstanding verification code (bound to whichever
|
|
757
|
+
// password registered it — possibly an attacker's pre-registration) would later activate THAT
|
|
758
|
+
// password over the one just set.
|
|
759
|
+
const activated = user.status === IDENTITY_STATUS.PENDING_VERIFICATION
|
|
760
|
+
&& await state.storage.userRepository.updateByIdIfStatus(record.user, IDENTITY_STATUS.PENDING_VERIFICATION, {
|
|
761
|
+
...changes, status: IDENTITY_STATUS.ACTIVE, registrationContested: false,
|
|
762
|
+
mfaEnabled: false, mfaSecret: null, mfaTempSecret: null, mfaRecoveryCodes: [],
|
|
763
|
+
});
|
|
764
|
+
await state.attemptCounters.reset(passwordLoginKey(record.user));
|
|
765
|
+
if (activated) {
|
|
766
|
+
await state.storage.verificationTokenRepository.deleteAllForUser('email_verification', record.user);
|
|
767
|
+
} else {
|
|
768
|
+
// (Not an administrative lock — a LOCKED status without a lockUntil; see account-status.js.)
|
|
769
|
+
const legacyLock = user.status === IDENTITY_STATUS.LOCKED && user.lockUntil ? { status: IDENTITY_STATUS.ACTIVE } : {};
|
|
770
|
+
await state.storage.userRepository.updateById(record.user, { ...changes, ...legacyLock });
|
|
771
|
+
}
|
|
772
|
+
await revokeAllUserSessions(state, record.user);
|
|
773
|
+
// Any other outstanding reset links die with this one.
|
|
774
|
+
await state.storage.verificationTokenRepository.deleteAllForUser('password_reset', record.user);
|
|
775
|
+
|
|
776
|
+
await auditLog(state.logger, state.hooks, 'PASSWORD_RESET', { userId: String(record.user) });
|
|
777
|
+
res.json({ status: 'ok' });
|
|
778
|
+
} catch (err) {
|
|
779
|
+
next(err);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
const PASSWORD_CHANGE_LOCKED = () => new IdpError({ code: 'PASSWORD_CHANGE_LOCKED', httpStatus: 429, message: 'Too many wrong passwords — try again later, or reset your password by email.' });
|
|
784
|
+
|
|
785
|
+
export async function changePasswordHandler(req, res, next) {
|
|
786
|
+
try {
|
|
787
|
+
const state = getState();
|
|
788
|
+
const userId = req.auth?.userId;
|
|
789
|
+
if (!userId) throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Authentication required' });
|
|
790
|
+
|
|
791
|
+
const { currentPassword, newPassword } = req.body;
|
|
792
|
+
const user = await state.storage.userRepository.findById(userId, { select: '+passwordHash' });
|
|
793
|
+
if (!user) throw new IdpError({ code: 'USER_NOT_FOUND', httpStatus: 404, message: 'User not found' });
|
|
794
|
+
|
|
795
|
+
// Reached with a session, not a password: without a budget this is an unlimited password
|
|
796
|
+
// oracle for whoever holds a stolen access token.
|
|
797
|
+
await withAttemptBudget(state, `password-change:${userId}`, state.config.security.passwordChangeLockout, {
|
|
798
|
+
lockedError: PASSWORD_CHANGE_LOCKED,
|
|
799
|
+
isFailure: (err) => err?.code === 'CURRENT_PASSWORD_INCORRECT',
|
|
800
|
+
onLocked: () => auditLog(state.logger, state.hooks, 'PASSWORD_CHANGE_LOCKED', { userId }),
|
|
801
|
+
}, async () => {
|
|
802
|
+
if (!(await verifyPassword(currentPassword, user.passwordHash))) {
|
|
803
|
+
throw new IdpError({ code: 'CURRENT_PASSWORD_INCORRECT', httpStatus: 400, message: 'Current password is incorrect' });
|
|
804
|
+
}
|
|
805
|
+
});
|
|
806
|
+
|
|
807
|
+
const passwordHash = await hashPassword(newPassword, state.config.security.bcryptRounds);
|
|
808
|
+
await state.storage.userRepository.updateById(userId, { passwordHash, passwordChangedAt: new Date() });
|
|
809
|
+
await revokeAllUserSessions(state, userId);
|
|
810
|
+
|
|
811
|
+
await auditLog(state.logger, state.hooks, 'PASSWORD_CHANGED', { userId });
|
|
812
|
+
await safeInvokeHook(state.logger, state.hooks, 'onPasswordChanged', {
|
|
813
|
+
userId, email: user.email, firstName: user.profile?.firstName || '', lastName: user.profile?.lastName || '',
|
|
814
|
+
locale: user.profile?.locale || 'en', when: new Date().toISOString(), deviceInfo: req.headers['user-agent'] || '', ipAddress: req.ip || '',
|
|
815
|
+
});
|
|
816
|
+
|
|
817
|
+
res.json({ status: 'ok' });
|
|
818
|
+
} catch (err) {
|
|
819
|
+
next(err);
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
// ── Self-service identity ("me") ────────────────────────────────────────────
|
|
824
|
+
|
|
825
|
+
export async function getMeHandler(req, res, next) {
|
|
826
|
+
try {
|
|
827
|
+
const state = getState();
|
|
828
|
+
if (!req.auth?.userId) throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Authentication required' });
|
|
829
|
+
|
|
830
|
+
const user = await state.storage.userRepository.findById(req.auth.userId, { select: 'email status lockUntil mfaEnabled profile createdAt updatedAt' });
|
|
831
|
+
if (!user) throw new IdpError({ code: 'USER_NOT_FOUND', httpStatus: 404, message: 'User not found' });
|
|
832
|
+
|
|
833
|
+
res.json({
|
|
834
|
+
userId: String(user.id),
|
|
835
|
+
email: user.email,
|
|
836
|
+
emailVerified: user.status !== IDENTITY_STATUS.PENDING_VERIFICATION,
|
|
837
|
+
// (A pre-0.4.0 automatic lock reads as ACTIVE — see account-status.js.)
|
|
838
|
+
isActive: isActiveAccount(user),
|
|
839
|
+
status: effectiveStatus(user),
|
|
840
|
+
mfaEnabled: user.mfaEnabled,
|
|
841
|
+
profile: user.profile,
|
|
842
|
+
createdAt: user.createdAt,
|
|
843
|
+
updatedAt: user.updatedAt,
|
|
844
|
+
});
|
|
845
|
+
} catch (err) {
|
|
846
|
+
next(err);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
export async function updateMeHandler(req, res, next) {
|
|
851
|
+
try {
|
|
852
|
+
const state = getState();
|
|
853
|
+
if (!req.auth?.userId) throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Authentication required' });
|
|
854
|
+
|
|
855
|
+
const patch = {};
|
|
856
|
+
for (const key of ['firstName', 'lastName', 'displayName', 'avatarUrl', 'locale', 'zoneinfo']) {
|
|
857
|
+
if (req.body[key] !== undefined) patch[`profile.${key}`] = req.body[key];
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
const user = await state.storage.userRepository.updateById(req.auth.userId, patch);
|
|
861
|
+
if (!user) throw new IdpError({ code: 'USER_NOT_FOUND', httpStatus: 404, message: 'User not found' });
|
|
862
|
+
|
|
863
|
+
await auditLog(state.logger, state.hooks, 'PROFILE_UPDATED', { userId: req.auth.userId });
|
|
864
|
+
res.json({ userId: String(user.id), profile: user.profile, updatedAt: user.updatedAt });
|
|
865
|
+
} catch (err) {
|
|
866
|
+
next(err);
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
export async function deleteMeHandler(req, res, next) {
|
|
871
|
+
try {
|
|
872
|
+
const state = getState();
|
|
873
|
+
if (!req.auth?.userId) throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Authentication required' });
|
|
874
|
+
|
|
875
|
+
const user = await state.storage.userRepository.updateById(req.auth.userId, { status: IDENTITY_STATUS.DELETED });
|
|
876
|
+
if (!user) throw new IdpError({ code: 'USER_NOT_FOUND', httpStatus: 404, message: 'User not found' });
|
|
877
|
+
|
|
878
|
+
await revokeAllUserSessions(state, req.auth.userId);
|
|
879
|
+
await auditLog(state.logger, state.hooks, 'ACCOUNT_DELETED', { userId: req.auth.userId });
|
|
880
|
+
res.json({ status: 'ok' });
|
|
881
|
+
} catch (err) {
|
|
882
|
+
next(err);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
export async function listSessionsHandler(req, res, next) {
|
|
887
|
+
try {
|
|
888
|
+
const state = getState();
|
|
889
|
+
if (!req.auth?.userId) throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Authentication required' });
|
|
890
|
+
|
|
891
|
+
const sessions = await state.storage.sessionRepository.listActiveForUser(req.auth.userId);
|
|
892
|
+
res.json(sessions.map((s) => ({ id: s.id, ipAddress: s.ipAddress, deviceInfo: s.deviceInfo, createdAt: s.createdAt, expiresAt: s.expiresAt })));
|
|
893
|
+
} catch (err) {
|
|
894
|
+
next(err);
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
export async function revokeSessionHandler(req, res, next) {
|
|
899
|
+
try {
|
|
900
|
+
const state = getState();
|
|
901
|
+
if (!req.auth?.userId) throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Authentication required' });
|
|
902
|
+
|
|
903
|
+
const session = await state.storage.sessionRepository.revokeById(req.params.id, req.auth.userId);
|
|
904
|
+
if (!session) throw new IdpError({ code: 'REFRESH_TOKEN_NOT_FOUND', httpStatus: 404, message: 'Session not found' });
|
|
905
|
+
|
|
906
|
+
if (session.jti) await state.cache.set(`${CACHE_KEY_PREFIXES.REVOKED_REFRESH_TOKEN}:${session.jti}`, '1', state.config.ttls.revocationCache);
|
|
907
|
+
await auditLog(state.logger, state.hooks, 'SESSION_REVOKED', { userId: req.auth.userId, sessionId: req.params.id });
|
|
908
|
+
res.json({ status: 'ok' });
|
|
909
|
+
} catch (err) {
|
|
910
|
+
next(err);
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
export async function revokeAllSessionsHandler(req, res, next) {
|
|
915
|
+
try {
|
|
916
|
+
const state = getState();
|
|
917
|
+
if (!req.auth?.userId) throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Authentication required' });
|
|
918
|
+
|
|
919
|
+
const result = await revokeAllUserSessions(state, req.auth.userId);
|
|
920
|
+
await auditLog(state.logger, state.hooks, 'SESSIONS_REVOKED_ALL', { userId: req.auth.userId, revokedCount: result.revokedCount });
|
|
921
|
+
res.json({ status: 'ok', revokedCount: result.revokedCount });
|
|
922
|
+
} catch (err) {
|
|
923
|
+
next(err);
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
export { issueSession, setSessionCookies, clearSessionCookies, refreshTokenInBody, resolveClaims, cookieOptions, assertUsableStatus, mfaChallengeResponse };
|