@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.
Files changed (111) hide show
  1. package/.env.example +159 -0
  2. package/CHANGELOG.md +63 -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 +61 -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 +783 -0
@@ -0,0 +1,15 @@
1
+ import { SESSION_KINDS } from '../config/constants.js';
2
+
3
+ /**
4
+ * The kind of a session (refresh-token) row. Rows written since 0.4.0 carry `kind` explicitly. Older
5
+ * rows don't: an OAuth2 grant always stored `claims: { clientId, scopes: [...] }`, so that shape is
6
+ * read as `oauth2`; anything else as `first_party`. The inference fails closed — a first-party row
7
+ * whose consumer claims happen to look like that is refused by `/refresh`, forcing a fresh login,
8
+ * never accepted somewhere it shouldn't be.
9
+ */
10
+ export function sessionKindOf(session) {
11
+ if (session?.kind === SESSION_KINDS.FIRST_PARTY || session?.kind === SESSION_KINDS.OAUTH2) return session.kind;
12
+ const claims = session?.claims;
13
+ if (claims && typeof claims.clientId === 'string' && Array.isArray(claims.scopes)) return SESSION_KINDS.OAUTH2;
14
+ return SESSION_KINDS.FIRST_PARTY;
15
+ }
@@ -0,0 +1,17 @@
1
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);
2
+
3
+ export const isLoopbackHost = (host) => LOOPBACK.has(host);
4
+
5
+ /**
6
+ * https, or http to this machine — or any http with NODE_ENV=development (a docker-compose service
7
+ * name such as http://idp:4000). Elsewhere an unset NODE_ENV counts as production.
8
+ */
9
+ export function isSecureUrl(value) {
10
+ try {
11
+ const url = new URL(value);
12
+ if (url.protocol === 'https:') return true;
13
+ return url.protocol === 'http:' && (LOOPBACK.has(url.hostname) || process.env.NODE_ENV === 'development');
14
+ } catch {
15
+ return false;
16
+ }
17
+ }
@@ -0,0 +1,126 @@
1
+ import crypto from 'crypto';
2
+ import { generateAuthenticationOptions } from '@simplewebauthn/server';
3
+ import { getState } from '../config/state.js';
4
+ import { assertTrustedOrigin } from '../middleware/csrf.js';
5
+ import { IdpError } from '../errors/idp-error.js';
6
+ import { getWebauthnConfig } from './config.js';
7
+ import { storeChallenge, consumeChallenge } from './challenge-store.js';
8
+ import { auditLog } from '../hooks/index.js';
9
+ import { verifyStoredCredentialAssertion } from './shared.js';
10
+ import { issueSession, setSessionCookies, resolveClaims, assertUsableStatus, refreshTokenInBody } from '../password-auth/controllers.js';
11
+ import { tokenHashKeys, HASH_PURPOSES } from '../signing/token.service.js';
12
+ import { enforceRateLimit } from '../rate-limit/enforce.js';
13
+ import { ipKey } from '../rate-limit/keys.js';
14
+
15
+ /**
16
+ * Primary/passwordless login — no prior session or password required. This
17
+ * is a genuinely different starting point than the MFA-second-factor flow
18
+ * (src/webauthn/mfa.controller.js): here, WHICH user is authenticating is
19
+ * established entirely by the credential ID in the assertion response
20
+ * (globally unique per the WebAuthn spec) — there's no `mfaChallengeToken`
21
+ * or prior password check identifying them first.
22
+ *
23
+ * Because the passkey alone logs the user in, user verification (PIN /
24
+ * biometric) is REQUIRED: possession plus verification is what makes a
25
+ * passkey login multi-factor. An assertion without the UV flag is refused.
26
+ *
27
+ * The pending challenge has no natural "known user" key to store it under
28
+ * for a usernameless ceremony, so it's keyed by the challenge value itself
29
+ * (decoded back out of the assertion response at verify time).
30
+ */
31
+ function decodeChallengeFromResponse(response) {
32
+ try {
33
+ const clientDataJSON = JSON.parse(Buffer.from(response.response.clientDataJSON, 'base64url').toString('utf8'));
34
+ return typeof clientDataJSON.challenge === 'string' ? clientDataJSON.challenge : null;
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ const VERIFICATION_FAILED = (message = 'WebAuthn assertion verification failed') => new IdpError({ code: 'WEBAUTHN_VERIFICATION_FAILED', httpStatus: 400, message });
41
+
42
+ /**
43
+ * POST /webauthn/authentication/options
44
+ *
45
+ * By default this always answers a usernameless/discoverable-credential challenge (the browser
46
+ * lets the user pick a passkey) and ignores `email`: listing an account's credential ids for an
47
+ * email tells anyone who asks whether that address has an account with passkeys. Set
48
+ * `config.webauthn.allowCredentialsByEmail: true` to scope the challenge to the email's
49
+ * credentials (needed only for non-discoverable credentials); unknown addresses then get a stable
50
+ * decoy id, so they look like an account with one passkey.
51
+ */
52
+ export async function generateAuthenticationOptionsHandler(req, res, next) {
53
+ try {
54
+ const state = getState();
55
+ await enforceRateLimit(state, `webauthn-authn:ip:${ipKey(req.ip)}`, state.config.rateLimiting.webauthnAuthentication, { failMode: 'closed' });
56
+ const { rpID } = getWebauthnConfig(state);
57
+ const { email } = req.body || {};
58
+
59
+ let allowCredentials;
60
+ if (email && state.config.webauthn?.allowCredentialsByEmail === true) {
61
+ const user = await state.storage.userRepository.findByEmail(email);
62
+ const credentials = user ? await state.storage.credentialRepository.findByUserId(user.id) : [];
63
+ // No transports: they'd distinguish real credentials from the decoy.
64
+ allowCredentials = credentials.length > 0
65
+ ? credentials.map((c) => ({ id: c.credentialId }))
66
+ : [{ id: decoyCredentialId(state, email) }];
67
+ }
68
+
69
+ const options = await generateAuthenticationOptions({ rpID, allowCredentials, userVerification: 'required' });
70
+
71
+ await storeChallenge(state, `authn:${options.challenge}`, true);
72
+
73
+ res.json(options);
74
+ } catch (err) {
75
+ next(err);
76
+ }
77
+ }
78
+
79
+ function decoyCredentialId(state, email) {
80
+ return crypto.createHmac('sha256', tokenHashKeys(state, HASH_PURPOSES.WEBAUTHN_DECOY)[0]).update(state.normalizeEmail(email)).digest('base64url');
81
+ }
82
+
83
+ /** POST /webauthn/authentication/verify — issues a full session through the same resolveAuthContext + issueSession path every other login method uses. */
84
+ export async function verifyAuthenticationHandler(req, res, next) {
85
+ try {
86
+ const state = getState();
87
+ assertTrustedOrigin(state, req); // sets session cookies — refuse login CSRF (see middleware/csrf.js)
88
+ await enforceRateLimit(state, `webauthn-authn:ip:${ipKey(req.ip)}`, state.config.rateLimiting.webauthnAuthentication, { failMode: 'closed' });
89
+ const { response } = req.body;
90
+
91
+ const challenge = decodeChallengeFromResponse(response);
92
+ if (!challenge) throw new IdpError({ code: 'INVALID_REQUEST', httpStatus: 400, message: 'Malformed WebAuthn assertion response' });
93
+
94
+ const consumed = await consumeChallenge(state, `authn:${challenge}`);
95
+ if (!consumed) throw new IdpError({ code: 'WEBAUTHN_CHALLENGE_EXPIRED', httpStatus: 400, message: 'Authentication challenge expired or not found — restart login' });
96
+
97
+ const credentialDoc = await verifyStoredCredentialAssertion(state, { response, expectedChallenge: challenge, requireUserVerification: true });
98
+
99
+ // A discoverable credential reports the user handle it was registered with (our user id). It
100
+ // must name the credential's owner — never trust one without the other.
101
+ const userHandle = response.response?.userHandle;
102
+ if (userHandle && Buffer.from(String(userHandle), 'base64url').toString('utf8') !== String(credentialDoc.user)) {
103
+ throw VERIFICATION_FAILED('Credential user handle does not match its owner');
104
+ }
105
+
106
+ const user = await state.storage.userRepository.findById(credentialDoc.user);
107
+ if (!user) throw new IdpError({ code: 'USER_NOT_FOUND', httpStatus: 404, message: 'User not found' });
108
+ assertUsableStatus(user);
109
+
110
+ const claims = await resolveClaims(state, user, { isNewUser: false, method: 'webauthn' });
111
+ const session = await issueSession(state, { user, claims, req, loginChallenge: req.body.login_challenge });
112
+
113
+ await auditLog(state.logger, state.hooks, 'WEBAUTHN_LOGIN', { userId: String(user.id), credentialId: credentialDoc.credentialId });
114
+
115
+ setSessionCookies(req, res, state, session);
116
+ res.json({
117
+ accessToken: session.accessToken.token,
118
+ accessTokenExpiresAt: session.accessToken.expiresAt,
119
+ ...refreshTokenInBody(state, req, session.refreshTokenValue),
120
+ refreshTokenExpiresAt: session.refreshExpiresAt,
121
+ userId: String(user.id),
122
+ });
123
+ } catch (err) {
124
+ next(err);
125
+ }
126
+ }
@@ -0,0 +1,17 @@
1
+ import { CACHE_KEY_PREFIXES } from '../config/constants.js';
2
+
3
+ /**
4
+ * Ephemeral, single-use storage for the challenge issued by
5
+ * generateRegistrationOptions/generateAuthenticationOptions, keyed by
6
+ * whatever identifies this specific ceremony (a userId for registration and
7
+ * MFA-scoped authentication; the challenge value itself for usernameless
8
+ * primary-login authentication).
9
+ */
10
+ export async function storeChallenge(state, key, challenge) {
11
+ await state.cache.set(`${CACHE_KEY_PREFIXES.WEBAUTHN_CHALLENGE}:${key}`, challenge, state.config.ttls.webauthnChallenge);
12
+ }
13
+
14
+ /** Atomic get-and-delete (`cache.take`): two concurrent verifies can never both redeem one challenge. */
15
+ export async function consumeChallenge(state, key) {
16
+ return (await state.cache.take(`${CACHE_KEY_PREFIXES.WEBAUTHN_CHALLENGE}:${key}`)) ?? null;
17
+ }
@@ -0,0 +1,25 @@
1
+ import { IdpError } from '../errors/idp-error.js';
2
+
3
+ /**
4
+ * WebAuthn is opt-in — `config.webauthn` isn't validated at
5
+ * `initIdentityProvider()` time so consumers who don't use passkeys never
6
+ * need to think about it. Validated lazily, here, on first actual use.
7
+ *
8
+ * `rpID` must be the **frontend's** registrable domain (the origin that
9
+ * calls `navigator.credentials.create()/.get()`), which is not necessarily
10
+ * this API's own hostname if the API is deployed on a subdomain like
11
+ * `api.example.com` serving a frontend at `example.com` — the RP ID must be
12
+ * the common parent (`example.com`) in that case.
13
+ */
14
+ export function getWebauthnConfig(state) {
15
+ const cfg = state.config.webauthn || {};
16
+ if (!cfg.rpID || !cfg.rpName || !cfg.origin) {
17
+ throw new IdpError({
18
+ code: 'WEBAUTHN_NOT_CONFIGURED',
19
+ httpStatus: 500,
20
+ message: 'config.webauthn.{rpID, rpName, origin} must be set to use passkey/WebAuthn endpoints. ' +
21
+ 'rpID is the frontend\'s registrable domain (not necessarily this API\'s own host); origin is the frontend\'s full URL (or an array of allowed origins).',
22
+ });
23
+ }
24
+ return cfg;
25
+ }
@@ -0,0 +1,119 @@
1
+ import { generateAuthenticationOptions } from '@simplewebauthn/server';
2
+ import { getState } from '../config/state.js';
3
+ import { assertTrustedOrigin } from '../middleware/csrf.js';
4
+ import { IdpError } from '../errors/idp-error.js';
5
+ import { isActiveAccount } from '../utils/account-status.js';
6
+ import { getWebauthnConfig } from './config.js';
7
+ import { storeChallenge, consumeChallenge } from './challenge-store.js';
8
+ import { auditLog } from '../hooks/index.js';
9
+ import { verifyStoredCredentialAssertion } from './shared.js';
10
+ import { issueSession, setSessionCookies, resolveClaims, refreshTokenInBody } from '../password-auth/controllers.js';
11
+ import { enforceRateLimit } from '../rate-limit/enforce.js';
12
+ import { ipKey } from '../rate-limit/keys.js';
13
+ import { guardMfaAttempt } from '../mfa/attempt-guard.js';
14
+ import { verifyChallengeToken, assertChallengeCurrent, spendChallenge } from '../mfa/controller.js';
15
+
16
+ // A failed assertion is a failed second-factor attempt, counted against the
17
+ // same per-account limit as a wrong TOTP/recovery code. An expired or missing
18
+ // challenge isn't — no guess was made.
19
+ const ASSERTION_FAILURE_CODES = new Set(['WEBAUTHN_VERIFICATION_FAILED', 'CREDENTIAL_NOT_FOUND', 'INVALID_REQUEST']);
20
+ const isAssertionFailure = (err) => ASSERTION_FAILURE_CODES.has(err?.code);
21
+
22
+ /**
23
+ * Passkey as a *second factor* — an alternative to `verifyMfaChallengeHandler`
24
+ * (TOTP) for completing the MFA gate `loginHandler` puts up when
25
+ * `user.mfaEnabled`. Distinct from primary passwordless login
26
+ * (authentication.controller.js) because the user is already partially
27
+ * authenticated (password checked, `mfaChallengeToken` proves it) — so
28
+ * unlike primary login, the server already knows exactly which user is
29
+ * completing the ceremony and must verify the submitted credential actually
30
+ * belongs to THAT user, not just that it's some valid registered passkey.
31
+ */
32
+
33
+ /** POST /webauthn/mfa/options */
34
+ export async function generateMfaWebauthnChallengeOptionsHandler(req, res, next) {
35
+ try {
36
+ const state = getState();
37
+ const { rpID } = getWebauthnConfig(state);
38
+ const { mfaChallengeToken } = req.body;
39
+
40
+ const { sub: userId } = verifyChallengeToken(state, mfaChallengeToken);
41
+
42
+ const credentials = await state.storage.credentialRepository.findByUserId(userId);
43
+ if (credentials.length === 0) {
44
+ throw new IdpError({ code: 'CREDENTIAL_NOT_FOUND', httpStatus: 400, message: 'No passkeys registered for this account' });
45
+ }
46
+
47
+ const options = await generateAuthenticationOptions({
48
+ rpID,
49
+ allowCredentials: credentials.map((c) => ({ id: c.credentialId, transports: c.transports })),
50
+ // Discouraged (not "preferred"/"required") per SimpleWebAuthn's own
51
+ // guidance for a 2FA step — the password already established user
52
+ // presence/verification; re-demanding it here just adds friction.
53
+ userVerification: 'discouraged',
54
+ });
55
+
56
+ await storeChallenge(state, `mfa-webauthn:${userId}`, options.challenge);
57
+
58
+ res.json(options);
59
+ } catch (err) {
60
+ next(err);
61
+ }
62
+ }
63
+
64
+ /** POST /webauthn/mfa/verify */
65
+ export async function verifyMfaWebauthnChallengeHandler(req, res, next) {
66
+ try {
67
+ const state = getState();
68
+ assertTrustedOrigin(state, req); // sets session cookies — refuse login CSRF (see middleware/csrf.js)
69
+ const { mfaChallengeToken, response } = req.body;
70
+
71
+ await enforceRateLimit(state, `mfa-challenge:ip:${ipKey(req.ip)}`, state.config.rateLimiting.mfaChallenge, { failMode: 'closed' });
72
+
73
+ const challenge = verifyChallengeToken(state, mfaChallengeToken);
74
+ const userId = challenge.sub;
75
+ const user = await state.storage.userRepository.findById(userId);
76
+ if (!isActiveAccount(user)) {
77
+ throw new IdpError({ code: 'USER_NOT_ACTIVE', httpStatus: 403, message: 'User account is not active' });
78
+ }
79
+ assertChallengeCurrent(user, challenge);
80
+
81
+ await guardMfaAttempt(state, userId, { method: 'webauthn', isFailure: isAssertionFailure }, async () => {
82
+ const expectedChallenge = await consumeChallenge(state, `mfa-webauthn:${userId}`);
83
+ if (!expectedChallenge) {
84
+ throw new IdpError({ code: 'WEBAUTHN_CHALLENGE_EXPIRED', httpStatus: 400, message: 'MFA challenge expired or not found — restart login' });
85
+ }
86
+
87
+ // Matches the options' `userVerification: 'discouraged'`: the password was the knowledge
88
+ // factor, so a PIN-less security key (presence only) is a valid second factor here.
89
+ const credentialDoc = await verifyStoredCredentialAssertion(state, { response, expectedChallenge, requireUserVerification: false });
90
+
91
+ // Defense in depth: allowCredentials scoping in the browser should
92
+ // already prevent this, but a malicious client could submit any
93
+ // credential id in the assertion response — independently confirm the
94
+ // verified credential belongs to the SAME user the password step
95
+ // already authenticated, not merely some valid registered passkey.
96
+ if (String(credentialDoc.user) !== String(userId)) {
97
+ throw new IdpError({ code: 'WEBAUTHN_VERIFICATION_FAILED', httpStatus: 401, message: 'Credential does not belong to the challenged account' });
98
+ }
99
+ });
100
+
101
+ await spendChallenge(state, challenge);
102
+
103
+ const claims = await resolveClaims(state, user, { isNewUser: false, method: 'webauthn-mfa' });
104
+ const session = await issueSession(state, { user, claims, req, sessionEpoch: challenge.sep, loginChallenge: challenge.lch });
105
+
106
+ await auditLog(state.logger, state.hooks, 'MFA_VERIFIED', { userId, method: 'webauthn' });
107
+
108
+ setSessionCookies(req, res, state, session);
109
+ res.json({
110
+ accessToken: session.accessToken.token,
111
+ accessTokenExpiresAt: session.accessToken.expiresAt,
112
+ ...refreshTokenInBody(state, req, session.refreshTokenValue),
113
+ refreshTokenExpiresAt: session.refreshExpiresAt,
114
+ userId,
115
+ });
116
+ } catch (err) {
117
+ next(err);
118
+ }
119
+ }
@@ -0,0 +1,128 @@
1
+ import { generateRegistrationOptions, verifyRegistrationResponse } from '@simplewebauthn/server';
2
+ import { getState } from '../config/state.js';
3
+ import { IdpError } from '../errors/idp-error.js';
4
+ import { getWebauthnConfig } from './config.js';
5
+ import { storeChallenge, consumeChallenge } from './challenge-store.js';
6
+ import { auditLog } from '../hooks/index.js';
7
+
8
+ /**
9
+ * POST /webauthn/registration/options
10
+ *
11
+ * Always requires an authenticated caller — a passkey is added to an
12
+ * already-established account (via password, magic link, SSO, ...), the
13
+ * same way every serious WebAuthn implementation works. There is no
14
+ * "register a passkey for a brand-new anonymous user" ceremony in this
15
+ * package; combine a magic-link signup with an immediate call here if you
16
+ * want that UX (see README).
17
+ */
18
+ export async function generateRegistrationOptionsHandler(req, res, next) {
19
+ try {
20
+ const state = getState();
21
+ if (!req.auth?.userId) throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Authentication required' });
22
+ const { rpID, rpName } = getWebauthnConfig(state);
23
+
24
+ const user = await state.storage.userRepository.findById(req.auth.userId);
25
+ if (!user) throw new IdpError({ code: 'USER_NOT_FOUND', httpStatus: 404, message: 'User not found' });
26
+
27
+ const existingCredentials = await state.storage.credentialRepository.findByUserId(user.id);
28
+
29
+ const options = await generateRegistrationOptions({
30
+ rpName,
31
+ rpID,
32
+ userName: user.email,
33
+ userDisplayName: user.profile?.displayName || user.email,
34
+ userID: new TextEncoder().encode(String(user.id)),
35
+ attestationType: 'none',
36
+ excludeCredentials: existingCredentials.map((c) => ({ id: c.credentialId, transports: c.transports })),
37
+ // A passkey can log in on its own, so it must be one that verifies its user (PIN / biometric).
38
+ authenticatorSelection: { residentKey: 'preferred', userVerification: 'required' },
39
+ });
40
+
41
+ await storeChallenge(state, `reg:${user.id}`, options.challenge);
42
+
43
+ res.json(options);
44
+ } catch (err) {
45
+ next(err);
46
+ }
47
+ }
48
+
49
+ /** POST /webauthn/registration/verify */
50
+ export async function verifyRegistrationHandler(req, res, next) {
51
+ try {
52
+ const state = getState();
53
+ if (!req.auth?.userId) throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Authentication required' });
54
+ const { rpID, origin } = getWebauthnConfig(state);
55
+
56
+ const expectedChallenge = await consumeChallenge(state, `reg:${req.auth.userId}`);
57
+ if (!expectedChallenge) {
58
+ throw new IdpError({ code: 'WEBAUTHN_CHALLENGE_EXPIRED', httpStatus: 400, message: 'Registration challenge expired or not found — restart registration' });
59
+ }
60
+
61
+ const { response, name } = req.body;
62
+
63
+ let result;
64
+ try {
65
+ result = await verifyRegistrationResponse({ response, expectedChallenge, expectedOrigin: origin, expectedRPID: rpID, requireUserVerification: true });
66
+ } catch (cause) {
67
+ throw new IdpError({ code: 'WEBAUTHN_VERIFICATION_FAILED', httpStatus: 400, message: 'WebAuthn registration verification failed', cause });
68
+ }
69
+ if (!result.verified) {
70
+ throw new IdpError({ code: 'WEBAUTHN_VERIFICATION_FAILED', httpStatus: 400, message: 'WebAuthn registration verification failed' });
71
+ }
72
+
73
+ const { credential, credentialDeviceType, credentialBackedUp } = result.registrationInfo;
74
+
75
+ const saved = await state.storage.credentialRepository.create({
76
+ userId: req.auth.userId,
77
+ credentialId: credential.id,
78
+ publicKey: Buffer.from(credential.publicKey).toString('base64'),
79
+ counter: credential.counter,
80
+ transports: credential.transports || [],
81
+ deviceType: credentialDeviceType,
82
+ backedUp: credentialBackedUp,
83
+ name: name || null,
84
+ });
85
+
86
+ await auditLog(state.logger, state.hooks, 'WEBAUTHN_CREDENTIAL_REGISTERED', { userId: req.auth.userId, credentialId: credential.id });
87
+
88
+ res.status(201).json({ id: saved.id, credentialId: saved.credentialId, deviceType: saved.deviceType, backedUp: saved.backedUp, name: saved.name });
89
+ } catch (err) {
90
+ next(err);
91
+ }
92
+ }
93
+
94
+ /** GET /me/passkeys — the caller's registered passkeys (never the public keys or counters). */
95
+ export async function listPasskeysHandler(req, res, next) {
96
+ try {
97
+ const state = getState();
98
+ if (!req.auth?.userId) throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Authentication required' });
99
+ const credentials = await state.storage.credentialRepository.findByUserId(req.auth.userId);
100
+ res.json(credentials.map((c) => ({
101
+ credentialId: c.credentialId, name: c.name ?? null, deviceType: c.deviceType, backedUp: c.backedUp,
102
+ createdAt: c.createdAt ?? null, lastUsedAt: c.lastUsedAt ?? null,
103
+ })));
104
+ } catch (err) {
105
+ next(err);
106
+ }
107
+ }
108
+
109
+ /**
110
+ * DELETE /me/passkeys/:credentialId — removes one of the caller's passkeys (scoped to the caller:
111
+ * someone else's credential id answers 404). Lets the owner evict a passkey they don't recognise.
112
+ */
113
+ export async function deletePasskeyHandler(req, res, next) {
114
+ try {
115
+ const state = getState();
116
+ if (!req.auth?.userId) throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Authentication required' });
117
+ const { credentialId } = req.params;
118
+
119
+ const owned = (await state.storage.credentialRepository.findByUserId(req.auth.userId)).some((c) => c.credentialId === credentialId);
120
+ if (!owned) throw new IdpError({ code: 'CREDENTIAL_NOT_FOUND', httpStatus: 404, message: 'Passkey not found' });
121
+ await state.storage.credentialRepository.deleteByCredentialId(credentialId, req.auth.userId);
122
+
123
+ await auditLog(state.logger, state.hooks, 'WEBAUTHN_CREDENTIAL_DELETED', { userId: req.auth.userId, credentialId });
124
+ res.json({ status: 'ok' });
125
+ } catch (err) {
126
+ next(err);
127
+ }
128
+ }
@@ -0,0 +1,41 @@
1
+ import { z } from 'zod';
2
+ import { loginChallengeSchema } from '../oauth2/login-challenge.js';
3
+
4
+ // WebAuthn response bodies are large, deeply-nested JSON objects defined by
5
+ // the browser/authenticator (RegistrationResponseJSON / AuthenticationResponseJSON)
6
+ // — validated structurally at the top level only (required fields every
7
+ // conformant response has) rather than fully modeled field-by-field, which
8
+ // would just duplicate @simplewebauthn/server's own parsing and go stale
9
+ // against future WebAuthn spec additions.
10
+ const webauthnResponseSchema = z.object({
11
+ id: z.string().min(1),
12
+ rawId: z.string().min(1),
13
+ type: z.string().min(1),
14
+ response: z.record(z.string(), z.unknown()),
15
+ clientExtensionResults: z.record(z.string(), z.unknown()).optional(),
16
+ }).passthrough();
17
+
18
+ export const registrationOptionsSchema = z.object({}).strict();
19
+
20
+ export const verifyRegistrationSchema = z.object({
21
+ response: webauthnResponseSchema,
22
+ name: z.string().max(120).optional(),
23
+ }).strict();
24
+
25
+ export const authenticationOptionsSchema = z.object({
26
+ email: z.string().trim().toLowerCase().email().optional(),
27
+ }).strict();
28
+
29
+ export const verifyAuthenticationSchema = z.object({
30
+ response: webauthnResponseSchema,
31
+ login_challenge: loginChallengeSchema.optional(),
32
+ }).strict();
33
+
34
+ export const mfaWebauthnOptionsSchema = z.object({
35
+ mfaChallengeToken: z.string().min(1),
36
+ }).strict();
37
+
38
+ export const verifyMfaWebauthnSchema = z.object({
39
+ mfaChallengeToken: z.string().min(1),
40
+ response: webauthnResponseSchema,
41
+ }).strict();
@@ -0,0 +1,63 @@
1
+ import { verifyAuthenticationResponse } from '@simplewebauthn/server';
2
+ import { IdpError } from '../errors/idp-error.js';
3
+ import { getWebauthnConfig } from './config.js';
4
+
5
+ /**
6
+ * Looks up the stored credential for an incoming assertion response,
7
+ * reconstructs it into the shape `@simplewebauthn/server` expects, verifies
8
+ * the assertion (which itself enforces the signature-counter-must-increase
9
+ * replay check), and persists the new counter on success.
10
+ *
11
+ * Shared by both the primary-passwordless-login and MFA-second-factor
12
+ * verify handlers — everything about *establishing who's authenticating*
13
+ * differs between those two (see their respective controllers), but the
14
+ * cryptographic verify-and-update-counter step is identical either way.
15
+ *
16
+ * @returns the stored credential document (with its `user` field) on success
17
+ * @throws {IdpError} CREDENTIAL_NOT_FOUND | WEBAUTHN_VERIFICATION_FAILED
18
+ */
19
+ export async function verifyStoredCredentialAssertion(state, { response, expectedChallenge, requireUserVerification }) {
20
+ if (typeof requireUserVerification !== 'boolean') throw new Error('verifyStoredCredentialAssertion: requireUserVerification must be set explicitly');
21
+ const { rpID, origin } = getWebauthnConfig(state);
22
+
23
+ const credentialId = response?.id;
24
+ if (!credentialId) throw new IdpError({ code: 'INVALID_REQUEST', httpStatus: 400, message: 'Malformed WebAuthn assertion response' });
25
+
26
+ const stored = await state.storage.credentialRepository.findByCredentialId(credentialId);
27
+ if (!stored) throw new IdpError({ code: 'CREDENTIAL_NOT_FOUND', httpStatus: 400, message: 'Unknown credential' });
28
+
29
+ const webAuthnCredential = {
30
+ id: stored.credentialId,
31
+ publicKey: Buffer.from(stored.publicKey, 'base64'),
32
+ counter: stored.counter,
33
+ transports: stored.transports,
34
+ };
35
+
36
+ let result;
37
+ try {
38
+ result = await verifyAuthenticationResponse({
39
+ response,
40
+ expectedChallenge,
41
+ expectedOrigin: origin,
42
+ expectedRPID: rpID,
43
+ credential: webAuthnCredential,
44
+ requireUserVerification,
45
+ });
46
+ } catch (cause) {
47
+ throw new IdpError({ code: 'WEBAUTHN_VERIFICATION_FAILED', httpStatus: 400, message: 'WebAuthn assertion verification failed', cause });
48
+ }
49
+
50
+ if (!result.verified) {
51
+ throw new IdpError({ code: 'WEBAUTHN_VERIFICATION_FAILED', httpStatus: 400, message: 'WebAuthn assertion verification failed' });
52
+ }
53
+
54
+ // The library compared against the counter read above; the conditional write closes the window
55
+ // in which two concurrent uses of one assertion both pass that comparison. (`undefined` from an
56
+ // adapter predating the boolean return is treated as success.)
57
+ const advanced = await state.storage.credentialRepository.updateCounter(stored.credentialId, result.authenticationInfo.newCounter);
58
+ if (advanced === false) {
59
+ throw new IdpError({ code: 'WEBAUTHN_VERIFICATION_FAILED', httpStatus: 400, message: 'WebAuthn assertion verification failed (signature counter did not advance)' });
60
+ }
61
+
62
+ return stored;
63
+ }