@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.
Files changed (111) hide show
  1. package/.env.example +159 -0
  2. package/CHANGELOG.md +58 -0
  3. package/LICENSE +21 -0
  4. package/README.md +275 -3
  5. package/package.json +78 -6
  6. package/src/cache/cache-adapter.js +22 -0
  7. package/src/cache/index.js +68 -0
  8. package/src/cache/memory.adapter.js +85 -0
  9. package/src/cache/redis.adapter.js +96 -0
  10. package/src/config/console-logger.js +10 -0
  11. package/src/config/constants.js +178 -0
  12. package/src/config/defaults.js +100 -0
  13. package/src/config/from-env.js +150 -0
  14. package/src/config/init.js +286 -0
  15. package/src/config/state.js +22 -0
  16. package/src/errors/error-codes.js +97 -0
  17. package/src/errors/idp-error.js +75 -0
  18. package/src/hooks/index.js +85 -0
  19. package/src/index.js +167 -0
  20. package/src/magic-link/controller.js +129 -0
  21. package/src/magic-link/schemas.js +12 -0
  22. package/src/mfa/attempt-guard.js +48 -0
  23. package/src/mfa/controller.js +309 -0
  24. package/src/mfa/factor-store.js +37 -0
  25. package/src/mfa/memory-attempt-counter.js +58 -0
  26. package/src/mfa/schemas.js +11 -0
  27. package/src/mfa/secret-cipher.js +133 -0
  28. package/src/mfa/secrets.js +156 -0
  29. package/src/middleware/auth-context.middleware.js +149 -0
  30. package/src/middleware/cookie-parser.js +4 -0
  31. package/src/middleware/csrf.js +48 -0
  32. package/src/middleware/require-recent-auth.middleware.js +30 -0
  33. package/src/middleware/require-service-caller.middleware.js +32 -0
  34. package/src/middleware/service-context.middleware.js +70 -0
  35. package/src/middleware/validate-body.js +16 -0
  36. package/src/middleware/validate-query.js +22 -0
  37. package/src/oauth2/authorize.controller.js +233 -0
  38. package/src/oauth2/client-auth.js +77 -0
  39. package/src/oauth2/client.controller.js +122 -0
  40. package/src/oauth2/consent.controller.js +63 -0
  41. package/src/oauth2/login-challenge.js +50 -0
  42. package/src/oauth2/redirect-uri.js +25 -0
  43. package/src/oauth2/schemas.js +103 -0
  44. package/src/oauth2/token.controller.js +370 -0
  45. package/src/oidc/discovery.controller.js +36 -0
  46. package/src/oidc/end-session.controller.js +137 -0
  47. package/src/oidc/userinfo.controller.js +49 -0
  48. package/src/password-auth/controllers.js +927 -0
  49. package/src/password-auth/schemas.js +76 -0
  50. package/src/rate-limit/enforce.js +35 -0
  51. package/src/rate-limit/index.js +48 -0
  52. package/src/rate-limit/keys.js +36 -0
  53. package/src/rate-limit/memory.adapter.js +75 -0
  54. package/src/rate-limit/noop.adapter.js +14 -0
  55. package/src/rate-limit/rate-limiter.js +18 -0
  56. package/src/rate-limit/redis.adapter.js +71 -0
  57. package/src/routes/build-router.js +238 -0
  58. package/src/security/attempt-budget.js +47 -0
  59. package/src/security/clock-skew.js +63 -0
  60. package/src/service-mesh/key-status.js +22 -0
  61. package/src/service-mesh/local-key-lookup.js +12 -0
  62. package/src/service-mesh/remote-jwks-key-lookup.js +74 -0
  63. package/src/service-mesh/s2s-bootstrap.middleware.js +41 -0
  64. package/src/service-mesh/service-identity.client.js +89 -0
  65. package/src/service-mesh/service-key.controller.js +170 -0
  66. package/src/service-mesh/verify-service-token.js +75 -0
  67. package/src/signing/jwks.controller.js +30 -0
  68. package/src/signing/jwks.js +24 -0
  69. package/src/signing/key-registry.js +97 -0
  70. package/src/signing/token.service.js +336 -0
  71. package/src/sso/binding.js +30 -0
  72. package/src/sso/callback.controller.js +186 -0
  73. package/src/sso/initiate.controller.js +92 -0
  74. package/src/sso/providers.js +237 -0
  75. package/src/sso/schemas.js +7 -0
  76. package/src/storage/interfaces.js +178 -0
  77. package/src/storage/postgres/db.js +68 -0
  78. package/src/storage/postgres/index.js +160 -0
  79. package/src/storage/postgres/migrations/run-migrations.js +122 -0
  80. package/src/storage/postgres/migrations/sql/0001_init.sql +253 -0
  81. package/src/storage/postgres/repositories/attempt-counter.repository.js +65 -0
  82. package/src/storage/postgres/repositories/authorization-code.repository.js +104 -0
  83. package/src/storage/postgres/repositories/consent.repository.js +68 -0
  84. package/src/storage/postgres/repositories/credential.repository.js +75 -0
  85. package/src/storage/postgres/repositories/oauth-client.repository.js +122 -0
  86. package/src/storage/postgres/repositories/service-key.repository.js +76 -0
  87. package/src/storage/postgres/repositories/session.repository.js +290 -0
  88. package/src/storage/postgres/repositories/user.repository.js +328 -0
  89. package/src/storage/postgres/repositories/verification-token.repository.js +138 -0
  90. package/src/storage/postgres/run.js +22 -0
  91. package/src/utils/account-status.js +26 -0
  92. package/src/utils/cookies.js +129 -0
  93. package/src/utils/device-fingerprint.js +58 -0
  94. package/src/utils/email-hash.js +23 -0
  95. package/src/utils/oauth-client-credentials.js +51 -0
  96. package/src/utils/password.js +40 -0
  97. package/src/utils/safe-equal.js +12 -0
  98. package/src/utils/session-family.js +158 -0
  99. package/src/utils/session-kind.js +15 -0
  100. package/src/utils/url.js +17 -0
  101. package/src/webauthn/authentication.controller.js +126 -0
  102. package/src/webauthn/challenge-store.js +17 -0
  103. package/src/webauthn/config.js +25 -0
  104. package/src/webauthn/mfa.controller.js +119 -0
  105. package/src/webauthn/registration.controller.js +128 -0
  106. package/src/webauthn/schemas.js +41 -0
  107. package/src/webauthn/shared.js +63 -0
  108. package/src/webhooks/dispatcher.js +135 -0
  109. package/src/webhooks/sign.js +55 -0
  110. package/src/webhooks/wrap-hooks.js +51 -0
  111. package/types/index.d.ts +777 -0
@@ -0,0 +1,85 @@
1
+ /**
2
+ * All hooks are optional and default to no-ops. They replace every
3
+ * `publishEvent(...)` call the audited Okeav auth-service made against
4
+ * RabbitMQ — this package never talks to a message bus itself; a hook
5
+ * implementation can publish to one if the consumer wants that.
6
+ *
7
+ * `onAuditLog` is a single generic firehose covering every audit-style event
8
+ * (login, logout, password change, MFA changes, OAuth2/OIDC/SSO/admin
9
+ * actions, etc.) — see README "Event hooks" table for the full list of
10
+ * `action` values it's called with. The five `on*` notification hooks below
11
+ * are the only ones that carry a payload rich enough to actually send a
12
+ * notification (email/SMS/push) and so get their own named callback.
13
+ */
14
+ export function defaultHooks() {
15
+ return {
16
+ onAuditLog: () => {},
17
+ onVerificationEmailRequested: () => {},
18
+ onPasswordResetRequested: () => {},
19
+ onPasswordChanged: () => {},
20
+ onSuspiciousActivityDetected: () => {},
21
+ onNewDeviceLogin: () => {},
22
+ onMagicLinkRequested: () => {},
23
+ };
24
+ }
25
+
26
+ export function mergeHooks(userHooks = {}) {
27
+ return { ...defaultHooks(), ...userHooks };
28
+ }
29
+
30
+ // A hook is waited for at most this long (`config.hookTimeoutMs`, default 10 s). It keeps running in
31
+ // the background afterwards, but a hung consumer callback (a stalled mail API, say) can't hold a
32
+ // login or a token response hostage.
33
+ let hookTimeoutMs = 10_000;
34
+ export function setHookTimeout(ms) {
35
+ hookTimeoutMs = ms;
36
+ }
37
+
38
+ /**
39
+ * Invokes a hook without letting it affect the caller: awaits it — up to the hook timeout — (so async
40
+ * hooks normally complete before the process could exit, e.g. serverless) but swallows and logs
41
+ * any rejection/throw rather than propagating it into the request lifecycle. A misbehaving consumer
42
+ * hook must never break login.
43
+ */
44
+ export async function safeInvokeHook(logger, hooks, hookName, payload) {
45
+ const fn = hooks?.[hookName];
46
+ if (typeof fn !== 'function') return;
47
+ let timer;
48
+ try {
49
+ const timeout = new Promise((resolve) => {
50
+ timer = setTimeout(() => {
51
+ logger?.warn?.({ hook: hookName, timeoutMs: hookTimeoutMs }, `Hook "${hookName}" is still running — not waiting for it`);
52
+ resolve();
53
+ }, hookTimeoutMs);
54
+ timer.unref?.();
55
+ });
56
+ await Promise.race([Promise.resolve(fn(payload)), timeout]);
57
+ } catch (err) {
58
+ // Name and message only: a consumer's error (an HTTP client's, say) often embeds the request it
59
+ // made — here, the reset token or magic link being mailed.
60
+ logger?.warn?.({ err: { name: err?.name, message: err?.message }, hook: hookName }, `Hook "${hookName}" threw — ignoring`);
61
+ } finally {
62
+ clearTimeout(timer);
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Starts a hook without waiting for it at all. For the notifications on endpoints that must not
68
+ * reveal whether an account exists (register, resend verification, forgot password, magic link):
69
+ * if the response waited for the hook — which typically sends an email — it would come back
70
+ * measurably later for a known address than for an unknown one. The hook itself is still called
71
+ * synchronously (its first synchronous step runs before the response); only its promise is not
72
+ * awaited. In a serverless runtime, make such hooks hand off quickly (enqueue, don't send inline).
73
+ */
74
+ export function invokeHookDetached(logger, hooks, hookName, payload) {
75
+ safeInvokeHook(logger, hooks, hookName, payload).catch(() => { /* safeInvokeHook never rejects */ });
76
+ }
77
+
78
+ export function auditLog(logger, hooks, action, payload) {
79
+ return safeInvokeHook(logger, hooks, 'onAuditLog', { action, ...payload, timestamp: new Date().toISOString() });
80
+ }
81
+
82
+ /** auditLog, not awaited — for the same enumeration-sensitive endpoints as invokeHookDetached. */
83
+ export function auditLogDetached(logger, hooks, action, payload) {
84
+ invokeHookDetached(logger, hooks, 'onAuditLog', { action, ...payload, timestamp: new Date().toISOString() });
85
+ }
package/src/index.js ADDED
@@ -0,0 +1,167 @@
1
+ import { getState } from './config/state.js';
2
+ import * as tokenService from './signing/token.service.js';
3
+ import { currentSessionEpoch } from './utils/session-family.js';
4
+ import { checkSkew } from './security/clock-skew.js';
5
+
6
+ // ── Bootstrap ────────────────────────────────────────────────────────────
7
+ export { initIdentityProvider } from './config/init.js';
8
+ export { configFromEnv } from './config/from-env.js';
9
+
10
+ // ── PostgreSQL ───────────────────────────────────────────────────────────
11
+ export { runMigrations } from './storage/postgres/run.js';
12
+ export { createPostgresStorage, MIN_POSTGRES_VERSION } from './storage/postgres/index.js';
13
+ export { MIGRATION_LOCK_KEY } from './storage/postgres/migrations/run-migrations.js';
14
+
15
+ // ── Errors ───────────────────────────────────────────────────────────────
16
+ export { IdpError, isIdpError, idpErrorHandler } from './errors/idp-error.js';
17
+ export { ERROR_CODES } from './errors/error-codes.js';
18
+
19
+ // ── Token issuance / verification (RS256) ───────────────────────────────
20
+ // Thin wrappers over signing/token.service.js that inject the singleton
21
+ // state, so the public signatures match the design doc exactly — no
22
+ // internal state object leaks into the public API.
23
+ // Tokens minted directly through this export have no session row, so they're
24
+ // marked `sessionless` (exempt from `session.verifyOnEachRequest`) unless the
25
+ // caller passes `sessionless: false` because it created a matching session itself.
26
+ export async function issueAccessToken(input, opts = {}) {
27
+ return tokenService.issueAccessToken(getState(), input, { sessionless: true, ...opts });
28
+ }
29
+ export async function verifyAccessToken(token, opts) {
30
+ return tokenService.verifyAccessToken(getState(), token, opts);
31
+ }
32
+ export async function issueIdToken(user, audience, nonce, opts) {
33
+ return tokenService.issueIdToken(getState(), user, audience, nonce, opts);
34
+ }
35
+ export async function issueOAuth2AccessToken(subject, client, scopes, opts) {
36
+ return tokenService.issueOAuth2AccessToken(getState(), subject, client, scopes, { sessionless: true, ...opts });
37
+ }
38
+ export async function issueMfaChallengeToken(subjectId) {
39
+ const state = getState();
40
+ // Bound to the user's current session epoch, like the challenges the IdP issues itself.
41
+ return tokenService.issueMfaChallengeToken(state, subjectId, { sessionEpoch: await currentSessionEpoch(state, subjectId) });
42
+ }
43
+ /**
44
+ * For health checks: this server's clock vs the database's — `{ skewMs, ok, level }` (level 'ok',
45
+ * 'warn', 'error', or 'unknown' when the storage adapter can't tell the time).
46
+ */
47
+ export async function checkClockSkew() {
48
+ const state = getState();
49
+ return checkSkew(state.storage, state.config.clock);
50
+ }
51
+ export function verifyMfaChallengeToken(token) {
52
+ return tokenService.verifyMfaChallengeToken(getState(), token);
53
+ }
54
+ export function verifyIssuedToken(token, opts) {
55
+ return tokenService.verifyIssuedToken(getState(), token, opts);
56
+ }
57
+
58
+ // ── JWKS / discovery (own user-token keys) ──────────────────────────────
59
+ export { jwksHandler, authPublicKeyHandler } from './signing/jwks.controller.js';
60
+ export { openidConfigurationHandler } from './oidc/discovery.controller.js';
61
+
62
+ // ── Service mesh — S2S JWKS trust (kept in scope as a differentiator) ──
63
+ export { registerServiceKeyHandler, getServicesJwksHandler, revokeServiceKey } from './service-mesh/service-key.controller.js';
64
+ export { s2sBootstrapMiddleware } from './service-mesh/s2s-bootstrap.middleware.js';
65
+ export {
66
+ initServiceIdentity,
67
+ mintServiceToken,
68
+ mintServiceToken as issueServiceToken,
69
+ getServiceIdentity,
70
+ verifyServiceTokenRemote,
71
+ } from './service-mesh/service-identity.client.js';
72
+
73
+ // ── Middleware ───────────────────────────────────────────────────────────
74
+ export { authContextMiddleware } from './middleware/auth-context.middleware.js';
75
+ export { requireRecentAuth } from './middleware/require-recent-auth.middleware.js';
76
+ export { serviceContextMiddleware } from './middleware/service-context.middleware.js';
77
+ export { requireServiceCallerMiddleware } from './middleware/require-service-caller.middleware.js';
78
+ export { validateBody } from './middleware/validate-body.js';
79
+ export { validateQuery } from './middleware/validate-query.js';
80
+ export { cookieParser } from './middleware/cookie-parser.js';
81
+
82
+ // ── Password / email identity flows ─────────────────────────────────────
83
+ export {
84
+ registerHandler,
85
+ verifyEmailHandler,
86
+ resendVerificationEmailHandler,
87
+ loginHandler,
88
+ refreshTokenHandler,
89
+ logoutHandler,
90
+ logoutAllHandler,
91
+ forgotPasswordHandler,
92
+ resetPasswordHandler,
93
+ changePasswordHandler,
94
+ getMeHandler,
95
+ updateMeHandler,
96
+ deleteMeHandler,
97
+ listSessionsHandler,
98
+ revokeSessionHandler,
99
+ revokeAllSessionsHandler,
100
+ } from './password-auth/controllers.js';
101
+
102
+ // ── MFA ──────────────────────────────────────────────────────────────────
103
+ export {
104
+ getMfaStatusHandler,
105
+ setupMfaHandler,
106
+ confirmMfaHandler,
107
+ disableMfaHandler,
108
+ regenerateRecoveryCodesHandler,
109
+ verifyMfaChallengeHandler,
110
+ } from './mfa/controller.js';
111
+
112
+ // ── OAuth2 authorization server + OIDC ───────────────────────────────────
113
+ export {
114
+ registerOAuthClientHandler,
115
+ getOAuthClientHandler,
116
+ listOAuthClientsHandler,
117
+ updateOAuthClientHandler,
118
+ rotateOAuthClientSecretHandler,
119
+ deactivateOAuthClientHandler,
120
+ approveOAuthClientHandler,
121
+ } from './oauth2/client.controller.js';
122
+ export { authorizeHandler, confirmConsentHandler, denyConsentHandler } from './oauth2/authorize.controller.js';
123
+ export { tokenHandler, revokeTokenHandler, introspectTokenHandler } from './oauth2/token.controller.js';
124
+ export { getConsentHandler, listConsentsHandler, revokeConsentHandler } from './oauth2/consent.controller.js';
125
+ export { userinfoHandler } from './oidc/userinfo.controller.js';
126
+ export { endSessionHandler } from './oidc/end-session.controller.js';
127
+
128
+ // ── SSO (social login) — single-step ─────────────────────────────────────
129
+ export { initiateSsoHandler } from './sso/initiate.controller.js';
130
+ export { ssoCallbackHandler } from './sso/callback.controller.js';
131
+
132
+ // ── Magic link (passwordless email login) ───────────────────────────────
133
+ export { requestMagicLinkHandler, verifyMagicLinkHandler } from './magic-link/controller.js';
134
+
135
+ // ── MFA secret encryption (advanced — most consumers just set config.mfa.encryptionKey) ──
136
+ export { migrateMfaSecrets } from './mfa/secrets.js';
137
+ export { AesGcmSecretCipher } from './mfa/secret-cipher.js';
138
+
139
+ // ── WebAuthn / passkeys ──────────────────────────────────────────────────
140
+ export { generateRegistrationOptionsHandler, verifyRegistrationHandler, listPasskeysHandler, deletePasskeyHandler } from './webauthn/registration.controller.js';
141
+ export { generateAuthenticationOptionsHandler, verifyAuthenticationHandler } from './webauthn/authentication.controller.js';
142
+ export { generateMfaWebauthnChallengeOptionsHandler, verifyMfaWebauthnChallengeHandler } from './webauthn/mfa.controller.js';
143
+
144
+ // ── Cache adapters (advanced — most consumers just use config.cache) ────
145
+ export { MemoryCacheAdapter } from './cache/memory.adapter.js';
146
+ export { RedisCacheAdapter, createRedisCacheAdapter } from './cache/redis.adapter.js';
147
+
148
+ // ── Rate limiter adapters (advanced — most consumers just use config.rateLimiting) ──
149
+ export { MemoryRateLimiter } from './rate-limit/memory.adapter.js';
150
+ export { RedisRateLimiter, createRedisRateLimiter } from './rate-limit/redis.adapter.js';
151
+ export { NoopRateLimiter } from './rate-limit/noop.adapter.js';
152
+
153
+ // ── Outbound webhooks (advanced — most consumers just use config.webhooks) ──
154
+ export { WebhookDispatcher } from './webhooks/dispatcher.js';
155
+ export { verifyWebhookSignature } from './webhooks/sign.js';
156
+
157
+ // ── Request-validation schemas (zod) — reuse or extend in your own routes ──
158
+ import * as passwordAuthSchemas from './password-auth/schemas.js';
159
+ import * as mfaSchemas from './mfa/schemas.js';
160
+ import * as oauth2Schemas from './oauth2/schemas.js';
161
+ import * as ssoSchemas from './sso/schemas.js';
162
+ import * as magicLinkSchemas from './magic-link/schemas.js';
163
+ import * as webauthnSchemas from './webauthn/schemas.js';
164
+ export const schemas = { ...passwordAuthSchemas, ...mfaSchemas, ...oauth2Schemas, ...ssoSchemas, ...magicLinkSchemas, ...webauthnSchemas };
165
+
166
+ // ── Optional convenience: a fully-wired express.Router() ────────────────
167
+ export { buildRouter } from './routes/build-router.js';
@@ -0,0 +1,129 @@
1
+ import { getState } from '../config/state.js';
2
+ import { assertTrustedOrigin } from '../middleware/csrf.js';
3
+ import { IdpError } from '../errors/idp-error.js';
4
+ import { IDENTITY_STATUS } from '../config/constants.js';
5
+ import { hashOpaqueToken, generateOpaqueToken, lookupByTokenHash, HASH_PURPOSES } from '../signing/token.service.js';
6
+ import { auditLog, auditLogDetached, invokeHookDetached } from '../hooks/index.js';
7
+ import { enforceRateLimit } from '../rate-limit/enforce.js';
8
+ import { ipKey, emailKey } from '../rate-limit/keys.js';
9
+ import { issueSession, setSessionCookies, resolveClaims, assertUsableStatus, mfaChallengeResponse, refreshTokenInBody } from '../password-auth/controllers.js';
10
+
11
+ /**
12
+ * POST /magic-link/request
13
+ *
14
+ * Enumeration-safe: always responds `{ status: 'ok' }` regardless of whether
15
+ * the email belongs to an existing account, a newly-created one, or neither.
16
+ * When `config.magicLink.allowSignupViaMagicLink` is true (the default), an
17
+ * unknown email creates a new (passwordless) user in PENDING_VERIFICATION —
18
+ * the same state a password-based registration starts in — which
19
+ * `verifyMagicLinkHandler` promotes to ACTIVE on first successful click,
20
+ * exactly mirroring the register→verify-email flow but collapsed into one
21
+ * link instead of two steps.
22
+ */
23
+ export async function requestMagicLinkHandler(req, res, next) {
24
+ try {
25
+ const state = getState();
26
+ const { email } = req.body;
27
+
28
+ await enforceRateLimit(state, `magic-link:ip:${ipKey(req.ip)}`, state.config.rateLimiting.magicLink, { failMode: 'closed' });
29
+ // Per address too: per-IP alone lets a distributed sender flood one inbox.
30
+ await enforceRateLimit(state, `magic-link:email:${emailKey(state, email)}`, state.config.rateLimiting.magicLinkByEmail, { failMode: 'closed' });
31
+
32
+ let user = await state.storage.userRepository.findByEmail(email);
33
+ let isNewUser = false;
34
+
35
+ if (!user) {
36
+ if (!state.config.magicLink.allowSignupViaMagicLink) {
37
+ return res.json({ status: 'ok' }); // invite-only mode — stay enumeration-safe, no link issued
38
+ }
39
+ user = await state.storage.userRepository.create({ email, status: IDENTITY_STATUS.PENDING_VERIFICATION, profile: {} });
40
+ isNewUser = true;
41
+ } else if (user.status === IDENTITY_STATUS.DELETED) {
42
+ return res.json({ status: 'ok' }); // don't resurrect a deleted account via magic link
43
+ }
44
+
45
+ // Only the newest link works: requesting another replaces the earlier one (atomically).
46
+ const token = generateOpaqueToken(32);
47
+ await state.storage.verificationTokenRepository.replaceForUser('magic_link', user.id, {
48
+ tokenHash: hashOpaqueToken(state, token, HASH_PURPOSES.MAGIC_LINK),
49
+ expiresAt: new Date(Date.now() + state.config.ttls.magicLink * 1000),
50
+ });
51
+
52
+ auditLogDetached(state.logger, state.hooks, 'MAGIC_LINK_REQUESTED', { userId: String(user.id), email, isNewUser });
53
+ invokeHookDetached(state.logger, state.hooks, 'onMagicLinkRequested', {
54
+ email, magicLinkToken: token, firstName: user.profile?.firstName, lastName: user.profile?.lastName, isNewUser,
55
+ });
56
+
57
+ res.json({ status: 'ok' });
58
+ } catch (err) {
59
+ next(err);
60
+ }
61
+ }
62
+
63
+ /**
64
+ * POST /magic-link/verify
65
+ *
66
+ * Consumes the token and issues a full session through the same
67
+ * `resolveAuthContext` + `issueSession` path every other login method uses —
68
+ * magic-link login is not a shortcut around claims resolution.
69
+ */
70
+ export async function verifyMagicLinkHandler(req, res, next) {
71
+ try {
72
+ const state = getState();
73
+ assertTrustedOrigin(state, req); // sets session cookies — refuse login CSRF (see middleware/csrf.js)
74
+ const { token } = req.body;
75
+
76
+ const { result: record } = await lookupByTokenHash(state, token, HASH_PURPOSES.MAGIC_LINK, (hash) => state.storage.verificationTokenRepository.consumeByHash('magic_link', hash));
77
+ if (!record) throw new IdpError({ code: 'INVALID_OR_EXPIRED_TOKEN', httpStatus: 400, message: 'Invalid or expired magic link' });
78
+
79
+ let user = await state.storage.userRepository.findById(record.user);
80
+ if (!user) throw new IdpError({ code: 'USER_NOT_FOUND', httpStatus: 404, message: 'User not found' });
81
+
82
+ const isNewUser = user.status === IDENTITY_STATUS.PENDING_VERIFICATION;
83
+ if (isNewUser) {
84
+ // Clicking the link proves ownership of the address — but NOT of any password set on this
85
+ // still-unverified account, which anyone could have registered with. Activating it with that
86
+ // password intact hands the account to whoever pre-registered the victim's email; it is
87
+ // discarded instead (the owner can set one through password reset).
88
+ // Conditional on still being pending: if the account was activated meanwhile (with whatever
89
+ // password its owner verified), it must not be wiped — it is then just a sign-in.
90
+ const activated = await state.storage.userRepository.updateByIdIfStatus(user.id, IDENTITY_STATUS.PENDING_VERIFICATION, {
91
+ status: IDENTITY_STATUS.ACTIVE, failedLoginAttempts: 0, lockUntil: null,
92
+ passwordHash: null, registrationContested: false, mfaEnabled: false, mfaSecret: null, mfaTempSecret: null, mfaRecoveryCodes: [],
93
+ });
94
+ if (activated) {
95
+ user = activated;
96
+ await state.storage.verificationTokenRepository.deleteAllForUser('email_verification', user.id);
97
+ } else {
98
+ user = await state.storage.userRepository.findById(record.user);
99
+ if (!user) throw new IdpError({ code: 'USER_NOT_FOUND', httpStatus: 404, message: 'User not found' });
100
+ assertUsableStatus(user);
101
+ }
102
+ } else {
103
+ assertUsableStatus(user);
104
+ }
105
+
106
+ // A magic link is one factor (the inbox). An account with MFA still has to present it.
107
+ if (user.mfaEnabled) {
108
+ await auditLog(state.logger, state.hooks, 'MAGIC_LINK_MFA_REQUIRED', { userId: String(user.id) });
109
+ return res.json(await mfaChallengeResponse(state, user, { loginChallenge: req.body.login_challenge }));
110
+ }
111
+
112
+ const claims = await resolveClaims(state, user, { isNewUser, method: 'magic_link' });
113
+ const session = await issueSession(state, { user, claims, req, loginChallenge: req.body.login_challenge });
114
+
115
+ await auditLog(state.logger, state.hooks, 'MAGIC_LINK_LOGIN', { userId: String(user.id), isNewUser });
116
+
117
+ setSessionCookies(req, res, state, session);
118
+ res.json({
119
+ accessToken: session.accessToken.token,
120
+ accessTokenExpiresAt: session.accessToken.expiresAt,
121
+ ...refreshTokenInBody(state, req, session.refreshTokenValue),
122
+ refreshTokenExpiresAt: session.refreshExpiresAt,
123
+ userId: String(user.id),
124
+ isNewUser,
125
+ });
126
+ } catch (err) {
127
+ next(err);
128
+ }
129
+ }
@@ -0,0 +1,12 @@
1
+ import { z } from 'zod';
2
+ import { MAX_EMAIL_LENGTH } from '../config/constants.js';
3
+ import { loginChallengeSchema } from '../oauth2/login-challenge.js';
4
+
5
+ export const requestMagicLinkSchema = z.object({
6
+ email: z.string().trim().toLowerCase().email('Must be a valid email address').max(MAX_EMAIL_LENGTH),
7
+ }).strict();
8
+
9
+ export const verifyMagicLinkSchema = z.object({
10
+ token: z.string().min(1),
11
+ login_challenge: loginChallengeSchema.optional(),
12
+ }).strict();
@@ -0,0 +1,48 @@
1
+ import { IdpError } from '../errors/idp-error.js';
2
+ import { auditLog } from '../hooks/index.js';
3
+ import { withAttemptBudget } from '../security/attempt-budget.js';
4
+
5
+ /**
6
+ * Per-account limit on failed second-factor attempts, shared by every way a
7
+ * code or assertion is checked: TOTP and recovery codes at /mfa/verify,
8
+ * WebAuthn-as-MFA at /webauthn/mfa/verify, and the codes that confirm
9
+ * enrolment, disable MFA, and regenerate recovery codes. All of them count
10
+ * against one key per user, so an attacker who already has the password can't
11
+ * spread guesses across factors — or across IPs, which is all the per-IP
12
+ * `mfaChallenge` rate limit sees.
13
+ *
14
+ * Counted in `state.attemptCounters` — the storage adapter's
15
+ * `attemptCounterRepository` (shared by every instance) or, for an adapter
16
+ * that doesn't implement one yet, an in-process fallback. Attempts are counted
17
+ * before the code is checked (see security/attempt-budget.js), so a concurrent
18
+ * burst gets no more guesses than the budget. A backend error propagates, so
19
+ * the check fails closed.
20
+ */
21
+
22
+ const LOCKED_ERROR = () => new IdpError({
23
+ code: 'MFA_LOCKED',
24
+ httpStatus: 429,
25
+ message: 'Too many failed verification attempts — try again later.',
26
+ });
27
+
28
+ const keyFor = (userId) => `mfa:${userId}`;
29
+
30
+ /**
31
+ * Runs `verify` (which throws on a wrong code/assertion) under the lockout.
32
+ * `isFailure(err)` says whether an error was a wrong guess; the failed guess
33
+ * that uses up the budget is answered with MFA_LOCKED and emits one
34
+ * `MFA_LOCKED` audit event.
35
+ */
36
+ export async function guardMfaAttempt(state, userId, { method, isFailure }, verify) {
37
+ return withAttemptBudget(state, keyFor(userId), state.config.mfa.lockout, {
38
+ lockedError: LOCKED_ERROR,
39
+ isFailure,
40
+ onLocked: (entry) => auditLog(state.logger, state.hooks, 'MFA_LOCKED', {
41
+ userId: String(userId), method, failedAttempts: entry.count, lockedUntil: new Date(entry.lockedUntil).toISOString(),
42
+ }),
43
+ }, verify);
44
+ }
45
+
46
+ export async function clearMfaFailures(state, userId) {
47
+ await state.attemptCounters.reset(keyFor(userId));
48
+ }