Skip to content

feat: mfa authenticator devices - totp + recovery codes - #3232

Merged
tada5hi merged 5 commits into
masterfrom
feat/mfa-authenticator-devices
Jul 12, 2026
Merged

tada5hi merged 5 commits into
masterfrom
feat/mfa-authenticator-devices

Conversation

@tada5hi

@tada5hi tada5hi commented Jul 12, 2026 •

Copy link
Copy Markdown
Collaborator

Part 1/5 of the MFA family (roadmap Wave 3, plans 049 + 050). Stacked — review in order; this PR targets master.

What

Ships authup's first second factor: the polymorphic auth_user_authenticators device model with TOTP + single-use recovery codes, enforced at the interactive /authorize flow and the direct password grant via an inline otp parameter.

  • Domain/DB: UserAuthenticator (core-kit) + auth_user_authenticators TypeORM entity; one dual-dialect migration 1783856507391-Default.ts (also adds auth_sessions.mfa_at + auth_sessions.auth_method, consumed by later PRs). Verified run → revert → re-run on MySQL + Postgres.
  • Crypto: new AES-256-GCM SymmetricCipher in @authup/server-kit for the reversible TOTP seed at rest (fail-closed without MFA_ENCRYPTION_KEY). Recovery codes are bcrypt-hashed, single-use.
  • Service: UserAuthenticatorService — two-step enrollment (create → confirm), self-access vs USER_AUTHENTICATOR_* gates with per-row realm-match, per-account exponential backoff (cache-keyed, 429 mfa_attempt_throttled), secret/codes select:false + stripped from every read.
  • Enforcement: OAuth2Authorization backstop (dedicated mfa_required error, not login_required) + GET/POST /authenticators/challenge (stamps session.mfa_at); password grant rejects password-only login for enrolled users, accepting a TOTP/recovery otp (classified by shape).
  • Wiring: config mfaEnabled / mfaRequired / mfaEncryptionKey (boot-validated), 4 permissions + provisioning grants, mfaEnrolled|mfaRemoved|mfaVerified|mfaChallengeFailed events, typed client.userAuthenticator.*, i18n error catalog ×4, otpauth + qrcode (server-rendered QR) deps.

Product decisions (settled with maintainer)

Enforcement = interactive + otp param; not-configured = configure-inline; dedicated mfa_required code; MFA_ENCRYPTION_KEY operator-provided / fail-closed.

Tests

Service matrix (enroll/confirm/verify, backoff, single-use, select:false), permission surfaces, and an end-to-end grant-password-mfa spec (enroll → confirm → grant gated → otp accepted → authorize backstop → challenge stamps mfa_at → authorize passes; recovery replay rejected).

Docs: .agents/architecture.md MFA section.

Summary by CodeRabbit

  • New Features

    • Added multi-factor authentication using TOTP and recovery-code authenticators.
    • Introduced authenticator enrollment/confirmation, management endpoints, and challenge/verification endpoints.
    • Added MFA enforcement to interactive authorization and password grants, including session tracking.
    • Added MFA configuration (enabled/required) and fail-closed setup behavior when misconfigured.
  • Documentation

    • Updated server configuration and deployment guide with MFA settings.
  • Bug Fixes

    • Improved reliability of MFA verification via per-user throttling/lockout and one-time recovery-code enforcement.
  • Tests

    • Added unit and integration coverage for MFA lifecycle, replay resistance, throttling, permissions, and authorization gating.
  • Chores

    • Added new cache “set-if-absent” support plus Redis/memory test coverage.

Plan 049 stage 1 + the /token otp gate (roadmap wave 3.1):

- auth_user_authenticators: polymorphic device rows (kind totp/recovery;
  email/webauthn reserved); TOTP seeds AES-256-GCM-encrypted at rest
  (new SymmetricCipher in @authup/server-kit) under MFA_ENCRYPTION_KEY
  (fail-closed), recovery codes bcrypt-hashed, single-use, regenerated
  as a set; secret/codes select:false and stripped from every read.
- two-step enrollment (create unconfirmed -> confirm with code) on
  /users/:id/authenticators (+ @me), admin management via new
  USER_AUTHENTICATOR_* permissions (realm_admin own-scoped CUD).
- session-bound proof: auth_sessions.mfa_at (+ auth_method column for
  plan 050, coordinated into one migration pair) stamped by
  POST /authenticators/challenge or the password grant otp param; the
  OAuth2Authorization backstop throws a dedicated mfa_required error
  when a confirmed-device user authorizes without it; the password
  grant rejects password-only logins for enrolled users (otp accepts a
  totp or recovery code, classified by shape).
- per-account exponential backoff (cache-keyed, 429
  mfa_attempt_throttled), mfaEnrolled/mfaRemoved/mfaVerified/
  mfaChallengeFailed events, mfa_required authorize metric outcome,
  typed client.userAuthenticator.*, config mfaEnabled/mfaRequired/
  mfaEncryptionKey (boot-validated), i18n error catalog x4 locales,
  migrations verified via run/revert/re-run on mysql + postgres.
Copilot AI review requested due to automatic review settings July 12, 2026 14:17

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@tada5hi, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 37 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fb12ebb6-d31a-4fa1-84d7-3750ea217b08

📥 Commits

Reviewing files that changed from the base of the PR and between 5a30950 and 0d7f79c.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (88)
  • .agents/architecture.md
  • apps/server-core/package.json
  • apps/server-core/src/adapters/database/data-source/options/module.ts
  • apps/server-core/src/adapters/database/domains/index.ts
  • apps/server-core/src/adapters/database/domains/session/entity.ts
  • apps/server-core/src/adapters/database/domains/user-authenticator/entity.ts
  • apps/server-core/src/adapters/database/domains/user-authenticator/index.ts
  • apps/server-core/src/adapters/database/migrations/mysql/1783856507391-Default.ts
  • apps/server-core/src/adapters/database/migrations/postgres/1783856507391-Default.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/types.ts
  • apps/server-core/src/adapters/http/controllers/entities/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/user-authenticator/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/user-authenticator/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/authenticator-challenge/index.ts
  • apps/server-core/src/adapters/http/controllers/workflows/authenticator-challenge/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/authorize/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/authorize/types.ts
  • apps/server-core/src/adapters/http/controllers/workflows/index.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/types.ts
  • apps/server-core/src/app/modules/config/constants.ts
  • apps/server-core/src/app/modules/config/normalize.ts
  • apps/server-core/src/app/modules/config/read/env.ts
  • apps/server-core/src/app/modules/config/types.ts
  • apps/server-core/src/app/modules/config/validator.ts
  • apps/server-core/src/app/modules/database/repositories/index.ts
  • apps/server-core/src/app/modules/database/repositories/user-authenticator/index.ts
  • apps/server-core/src/app/modules/database/repositories/user-authenticator/repository.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/provisioning/sources/default/module.ts
  • apps/server-core/src/core/authentication/session/module.ts
  • apps/server-core/src/core/authentication/session/types.ts
  • apps/server-core/src/core/entities/index.ts
  • apps/server-core/src/core/entities/user-authenticator/constants.ts
  • apps/server-core/src/core/entities/user-authenticator/helpers.ts
  • apps/server-core/src/core/entities/user-authenticator/index.ts
  • apps/server-core/src/core/entities/user-authenticator/service.ts
  • apps/server-core/src/core/entities/user-authenticator/types.ts
  • apps/server-core/src/core/metrics/types.ts
  • apps/server-core/src/core/oauth2/authorization/module.ts
  • apps/server-core/src/core/oauth2/authorization/types.ts
  • apps/server-core/src/core/oauth2/grant-types/password.ts
  • apps/server-core/test/unit/config/index.spec.ts
  • apps/server-core/test/unit/core/entities/user-authenticator/fake-repository.ts
  • apps/server-core/test/unit/core/entities/user-authenticator/service.spec.ts
  • apps/server-core/test/unit/core/helpers/fake-session-manager.ts
  • apps/server-core/test/unit/http/controllers/entities/user-authenticator.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-password-mfa.spec.ts
  • docs/src/guide/deployment/configuration-server-core.md
  • packages/core-http-kit/src/client/module.ts
  • packages/core-http-kit/src/client/type.ts
  • packages/core-http-kit/src/domains/entities/index.ts
  • packages/core-http-kit/src/domains/entities/user-authenticator/index.ts
  • packages/core-http-kit/src/domains/entities/user-authenticator/module.ts
  • packages/core-http-kit/src/domains/entities/user-authenticator/types.ts
  • packages/core-kit/src/domains/event/constants.ts
  • packages/core-kit/src/domains/index.ts
  • packages/core-kit/src/domains/permission/constants.ts
  • packages/core-kit/src/domains/session/constants.ts
  • packages/core-kit/src/domains/session/entity.ts
  • packages/core-kit/src/domains/session/index.ts
  • packages/core-kit/src/domains/user-authenticator/constants.ts
  • packages/core-kit/src/domains/user-authenticator/entity.ts
  • packages/core-kit/src/domains/user-authenticator/index.ts
  • packages/core-kit/src/domains/user-authenticator/validator.ts
  • packages/errors/src/built-in/check.ts
  • packages/errors/src/built-in/index.ts
  • packages/errors/src/built-in/mfa-throttled.ts
  • packages/errors/src/constants.ts
  • packages/errors/src/status.ts
  • packages/i18n/src/catalogs/de/error.ts
  • packages/i18n/src/catalogs/en/error.ts
  • packages/i18n/src/catalogs/es/error.ts
  • packages/i18n/src/catalogs/fr/error.ts
  • packages/server-kit/src/cache/adapters/memory.ts
  • packages/server-kit/src/cache/adapters/redis.ts
  • packages/server-kit/src/cache/types.ts
  • packages/server-kit/src/crypto/index.ts
  • packages/server-kit/src/crypto/symmetric-cipher/index.ts
  • packages/server-kit/src/crypto/symmetric-cipher/module.ts
  • packages/server-kit/src/crypto/symmetric-cipher/types.ts
  • packages/server-kit/test/unit/cache-memory.spec.ts
  • packages/server-kit/test/unit/symmetric-cipher.spec.ts
  • packages/specs/src/oauth2/check.ts
  • packages/specs/src/oauth2/constants.ts
  • packages/specs/src/oauth2/error/index.ts
  • packages/specs/src/oauth2/error/mfa-required.ts
📝 Walkthrough

Walkthrough

Adds MFA authenticator devices with TOTP and recovery-code support, encrypted secret storage, lifecycle APIs, challenge verification, OAuth2 enforcement, session tracking, throttling errors, configuration, typed client APIs, and tests.

Changes

MFA authenticator platform

Layer / File(s) Summary
Contracts, configuration, and security primitives
packages/core-kit/src/domains/user-authenticator/*, apps/server-core/src/core/entities/user-authenticator/*, packages/server-kit/src/crypto/symmetric-cipher/*, packages/errors/src/built-in/*, apps/server-core/src/app/modules/config/*
Defines authenticator types, permissions, events, MFA configuration, AES-256-GCM encryption, throttling errors, and OAuth2 MFA-required errors.
Persistence and repository
apps/server-core/src/adapters/database/domains/user-authenticator/*, apps/server-core/src/adapters/database/migrations/*/1783856507391-Default.ts, apps/server-core/src/app/modules/database/repositories/user-authenticator/*
Adds the authenticator entity and database schema, session MFA columns, secret-select boundaries, and repository queries.
Authenticator lifecycle service
apps/server-core/src/core/entities/user-authenticator/service.ts, apps/server-core/test/unit/core/entities/user-authenticator/*
Implements enrollment, confirmation, deletion, challenge status, TOTP and recovery verification, one-time recovery use, permissions, events, and exponential backoff.
HTTP and OAuth2 enforcement
apps/server-core/src/adapters/http/controllers/entities/user-authenticator/*, apps/server-core/src/adapters/http/controllers/workflows/authenticator-challenge/*, apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts, apps/server-core/src/core/oauth2/*
Adds authenticator and challenge endpoints, injects MFA services into HTTP flows, requires OTPs for password grants, and gates authorization codes on session MFA proof.
Client API and integration coverage
packages/core-http-kit/src/domains/entities/user-authenticator/*, apps/server-core/test/unit/http/controllers/**/*mfa*, docs/src/guide/deployment/configuration-server-core.md
Publishes typed client methods, validates controller isolation and challenge flows, tests password-grant MFA and recovery-code replay, and documents configuration variables.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant TokenController
  participant UserAuthenticatorService
  participant SessionManager
  participant OAuth2Authorization
  Client->>TokenController: Submit password grant and optional OTP
  TokenController->>UserAuthenticatorService: Challenge and verify second factor
  UserAuthenticatorService-->>TokenController: Verification result
  TokenController->>SessionManager: Create session with mfa_at
  Client->>OAuth2Authorization: Request authorization code
  OAuth2Authorization->>UserAuthenticatorService: Read MFA challenge status
  OAuth2Authorization->>SessionManager: Check session mfa_at
  OAuth2Authorization-->>Client: Authorization code or MFA-required error
Loading

Possibly related issues

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately summarizes the main change: adding MFA authenticator devices for TOTP and recovery codes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/mfa-authenticator-devices

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-new Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

authup

npm i https://pkg.pr.new/authup@3232

@authup/client-web

npm i https://pkg.pr.new/@authup/client-web@3232

@authup/server-core

npm i https://pkg.pr.new/@authup/server-core@3232

@authup/access

npm i https://pkg.pr.new/@authup/access@3232

@authup/client-web-kit

npm i https://pkg.pr.new/@authup/client-web-kit@3232

@authup/client-web-kit-theme

npm i https://pkg.pr.new/@authup/client-web-kit-theme@3232

@authup/client-web-nuxt

npm i https://pkg.pr.new/@authup/client-web-nuxt@3232

@authup/client-web-theme

npm i https://pkg.pr.new/@authup/client-web-theme@3232

@authup/core-http-kit

npm i https://pkg.pr.new/@authup/core-http-kit@3232

@authup/core-kit

npm i https://pkg.pr.new/@authup/core-kit@3232

@authup/core-realtime-kit

npm i https://pkg.pr.new/@authup/core-realtime-kit@3232

@authup/errors

npm i https://pkg.pr.new/@authup/errors@3232

@authup/i18n

npm i https://pkg.pr.new/@authup/i18n@3232

@authup/kit

npm i https://pkg.pr.new/@authup/kit@3232

@authup/server-adapter-kit

npm i https://pkg.pr.new/@authup/server-adapter-kit@3232

@authup/server-adapter-node

npm i https://pkg.pr.new/@authup/server-adapter-node@3232

@authup/server-adapter-socket-io

npm i https://pkg.pr.new/@authup/server-adapter-socket-io@3232

@authup/server-adapter-web

npm i https://pkg.pr.new/@authup/server-adapter-web@3232

@authup/server-kit

npm i https://pkg.pr.new/@authup/server-kit@3232

@authup/server-test-kit

npm i https://pkg.pr.new/@authup/server-test-kit@3232

@authup/specs

npm i https://pkg.pr.new/@authup/specs@3232

commit: 0d7f79c

@tada5hi tada5hi changed the title feat: mfa authenticator devices — totp + recovery codes (plan 049 stage 1) feat: mfa authenticator devices - totp + recovery codes Jul 12, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

🧹 Nitpick comments (2)
apps/server-core/src/core/entities/user-authenticator/helpers.ts (1)

15-28: 🔒 Security & Privacy | 🔵 Trivial | 💤 Low value

Modulo bias in recovery code generation.

bytes[i] % RECOVERY_CODE_ALPHABET.length introduces a slight bias: 256 is not evenly divisible by 31, so the first 8 alphabet characters are ~12.5% more likely than the remaining 23. The entropy loss per character is negligible (~0.01 bits), and for single-use recovery codes this is not a practical risk, but rejection sampling would eliminate it entirely.

Optional: rejection sampling to eliminate modulo bias
 export function generateRecoveryCode(): string {
     const size = RECOVERY_CODE_GROUP_LENGTH * 2;
     const bytes = getRandomValues(new Uint8Array(size));
 
     let output = '';
     for (let i = 0; i < size; i++) {
         if (i === RECOVERY_CODE_GROUP_LENGTH) {
             output += '-';
         }
-        output += RECOVERY_CODE_ALPHABET[bytes[i] % RECOVERY_CODE_ALPHABET.length];
+        // Reject values that would introduce modulo bias (256 % 31 = 8)
+        const limit = 256 - (256 % RECOVERY_CODE_ALPHABET.length);
+        let byte = bytes[i];
+        while (byte >= limit) {
+            byte = getRandomValues(new Uint8Array(1))[0];
+        }
+        output += RECOVERY_CODE_ALPHABET[byte % RECOVERY_CODE_ALPHABET.length];
     }
 
     return output;
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/server-core/src/core/entities/user-authenticator/helpers.ts` around
lines 15 - 28, Update generateRecoveryCode to eliminate modulo bias by using
rejection sampling when selecting characters from RECOVERY_CODE_ALPHABET:
discard random bytes outside the largest evenly divisible range, then map
accepted bytes to indices. Preserve the existing two-group format and output
length.
apps/server-core/test/unit/core/entities/user-authenticator/service.spec.ts (1)

264-288: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Real 1.1s setTimeout makes this test slow and borderline-flaky.

The test waits on a real timer to cross the 1-second backoff window with only a 100ms margin. Under CI load this margin is tight, and the test unconditionally costs ~1.1s. Consider vi.useFakeTimers()/vi.advanceTimersByTime() (with vi.setSystemTime() if the throttle reads wall-clock time) for a deterministic, fast test.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/server-core/test/unit/core/entities/user-authenticator/service.spec.ts`
around lines 264 - 288, The per-account backoff test uses a real 1.1-second
timer, making it slow and timing-sensitive. Update the “locks after a failed
attempt and releases after the window” test to use Vitest fake timers, advancing
the clock past the one-second window and setting system time as needed if the
throttling logic reads wall-clock time; restore real timers after the test while
preserving the existing assertions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@apps/server-core/src/adapters/http/controllers/entities/user-authenticator/module.ts`:
- Around line 50-59: Update resolveUserId so that when isSelfToken(id) is true
but useRequestIdentity(event) is absent or not IdentityType.USER, it throws an
explicit error instead of returning the literal self-token. Preserve returning
identity.id for USER identities and returning id unchanged for non-self tokens.

In
`@apps/server-core/src/adapters/http/controllers/workflows/authenticator-challenge/module.ts`:
- Around line 87-112: Update the verification flow around service.verify and
sessionManager.markMfaVerified so recovery-code consumption and session MFA
stamping succeed or fail atomically. Use the existing transaction mechanism to
encompass both persistence operations, or defer recovery-code consumption until
after the session stamp succeeds, while preserving the current sessionId and
session lookup behavior.

In `@apps/server-core/src/app/modules/config/normalize.ts`:
- Around line 143-151: Update the mfaEncryptionKey validation in the config
normalization flow to reject whitespace-only values, invalid base64, and keys
whose decoded length is not exactly 32 bytes whenever config.mfaEnabled is true.
Keep the existing AuthupError boot-time failure behavior and message context,
validating the decoded key rather than only its raw-string truthiness.

In `@apps/server-core/src/app/modules/http/modules/controller.ts`:
- Around line 782-784: Update the MFA configuration validation/normalization
before the `SymmetricCipher` construction in the controller flow to decode
`config.mfaEncryptionKey` and require exactly 32 bytes. Reject invalid-length or
malformed keys during boot-time configuration parsing, while preserving the
existing null behavior when no key is configured.

In `@apps/server-core/src/core/entities/user-authenticator/service.ts`:
- Around line 457-481: The verifyTotp method must prevent TOTP replay by
retrieving the validated token’s counter/step, rejecting it when it is less than
or equal to the device’s last consumed step, and persisting the new step before
returning success. Update the device model/persistence flow used by verify so
the last accepted step is stored alongside last_used_at, while preserving the
existing window and parameter handling.
- Around line 299-327: Wrap the recovery-code replacement flow in enrollRecovery
with a repository transaction, including removeAllByUser and the subsequent
recovery entity creation and save, so the old set is restored if persistence
fails. Keep event recording and the returned sanitized entity/codes behavior
intact, using the repository’s existing transaction mechanism.
- Around line 572-585: The bumpAttempts method currently performs a non-atomic
read-modify-write through ICache.get and ICache.set, allowing concurrent MFA
failures to overwrite attempt counts. Add and use an atomic increment/CAS
operation for the per-user attempt state, or acquire a short-lived per-user lock
before reading and updating it, while preserving the existing exponential delay,
maximum lock duration, and TTL behavior.
- Around line 409-455: Update verify and the recovery-code path around
verifyRecovery so reading the authenticator, marking the recovery code used, and
saving the updated row occur atomically. Use the repository/transaction
mechanism to lock the selected UserAuthenticatorEntity row during verification,
or enforce equivalent optimistic concurrency, ensuring concurrent requests
cannot both accept the same recovery code or overwrite used_at updates.

In `@packages/server-kit/src/crypto/symmetric-cipher/module.ts`:
- Around line 25-42: Update the SymmetricCipher constructor and importKey flow
so key-import failures are handled during eager construction rather than leaving
this.key as an unobserved rejected promise; attach the required rejection
handling or use an initialization pattern that validates before construction
completes, while preserving encrypt/decrypt access to the resolved CryptoKey.

---

Nitpick comments:
In `@apps/server-core/src/core/entities/user-authenticator/helpers.ts`:
- Around line 15-28: Update generateRecoveryCode to eliminate modulo bias by
using rejection sampling when selecting characters from RECOVERY_CODE_ALPHABET:
discard random bytes outside the largest evenly divisible range, then map
accepted bytes to indices. Preserve the existing two-group format and output
length.

In `@apps/server-core/test/unit/core/entities/user-authenticator/service.spec.ts`:
- Around line 264-288: The per-account backoff test uses a real 1.1-second
timer, making it slow and timing-sensitive. Update the “locks after a failed
attempt and releases after the window” test to use Vitest fake timers, advancing
the clock past the one-second window and setting system time as needed if the
throttling logic reads wall-clock time; restore real timers after the test while
preserving the existing assertions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: aca07a88-0f6d-412f-bb5e-970681f08d1f

📥 Commits

Reviewing files that changed from the base of the PR and between 5a30950 and a7d98c5.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (83)
  • .agents/architecture.md
  • apps/server-core/package.json
  • apps/server-core/src/adapters/database/data-source/options/module.ts
  • apps/server-core/src/adapters/database/domains/index.ts
  • apps/server-core/src/adapters/database/domains/session/entity.ts
  • apps/server-core/src/adapters/database/domains/user-authenticator/entity.ts
  • apps/server-core/src/adapters/database/domains/user-authenticator/index.ts
  • apps/server-core/src/adapters/database/migrations/mysql/1783856507391-Default.ts
  • apps/server-core/src/adapters/database/migrations/postgres/1783856507391-Default.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/types.ts
  • apps/server-core/src/adapters/http/controllers/entities/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/user-authenticator/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/user-authenticator/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/authenticator-challenge/index.ts
  • apps/server-core/src/adapters/http/controllers/workflows/authenticator-challenge/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/authorize/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/authorize/types.ts
  • apps/server-core/src/adapters/http/controllers/workflows/index.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/types.ts
  • apps/server-core/src/app/modules/config/constants.ts
  • apps/server-core/src/app/modules/config/normalize.ts
  • apps/server-core/src/app/modules/config/read/env.ts
  • apps/server-core/src/app/modules/config/types.ts
  • apps/server-core/src/app/modules/config/validator.ts
  • apps/server-core/src/app/modules/database/repositories/index.ts
  • apps/server-core/src/app/modules/database/repositories/user-authenticator/index.ts
  • apps/server-core/src/app/modules/database/repositories/user-authenticator/repository.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/provisioning/sources/default/module.ts
  • apps/server-core/src/core/authentication/session/module.ts
  • apps/server-core/src/core/authentication/session/types.ts
  • apps/server-core/src/core/entities/index.ts
  • apps/server-core/src/core/entities/user-authenticator/constants.ts
  • apps/server-core/src/core/entities/user-authenticator/helpers.ts
  • apps/server-core/src/core/entities/user-authenticator/index.ts
  • apps/server-core/src/core/entities/user-authenticator/service.ts
  • apps/server-core/src/core/entities/user-authenticator/types.ts
  • apps/server-core/src/core/metrics/types.ts
  • apps/server-core/src/core/oauth2/authorization/module.ts
  • apps/server-core/src/core/oauth2/authorization/types.ts
  • apps/server-core/src/core/oauth2/grant-types/password.ts
  • apps/server-core/test/unit/core/entities/user-authenticator/fake-repository.ts
  • apps/server-core/test/unit/core/entities/user-authenticator/service.spec.ts
  • apps/server-core/test/unit/core/helpers/fake-session-manager.ts
  • apps/server-core/test/unit/http/controllers/entities/user-authenticator.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-password-mfa.spec.ts
  • docs/src/guide/deployment/configuration-server-core.md
  • packages/core-http-kit/src/client/module.ts
  • packages/core-http-kit/src/client/type.ts
  • packages/core-http-kit/src/domains/entities/index.ts
  • packages/core-http-kit/src/domains/entities/user-authenticator/index.ts
  • packages/core-http-kit/src/domains/entities/user-authenticator/module.ts
  • packages/core-http-kit/src/domains/entities/user-authenticator/types.ts
  • packages/core-kit/src/domains/event/constants.ts
  • packages/core-kit/src/domains/index.ts
  • packages/core-kit/src/domains/permission/constants.ts
  • packages/core-kit/src/domains/session/constants.ts
  • packages/core-kit/src/domains/session/entity.ts
  • packages/core-kit/src/domains/session/index.ts
  • packages/core-kit/src/domains/user-authenticator/constants.ts
  • packages/core-kit/src/domains/user-authenticator/entity.ts
  • packages/core-kit/src/domains/user-authenticator/index.ts
  • packages/core-kit/src/domains/user-authenticator/validator.ts
  • packages/errors/src/built-in/check.ts
  • packages/errors/src/built-in/index.ts
  • packages/errors/src/built-in/mfa-throttled.ts
  • packages/errors/src/constants.ts
  • packages/errors/src/status.ts
  • packages/i18n/src/catalogs/de/error.ts
  • packages/i18n/src/catalogs/en/error.ts
  • packages/i18n/src/catalogs/es/error.ts
  • packages/i18n/src/catalogs/fr/error.ts
  • packages/server-kit/src/crypto/index.ts
  • packages/server-kit/src/crypto/symmetric-cipher/index.ts
  • packages/server-kit/src/crypto/symmetric-cipher/module.ts
  • packages/server-kit/src/crypto/symmetric-cipher/types.ts
  • packages/server-kit/test/unit/symmetric-cipher.spec.ts
  • packages/specs/src/oauth2/check.ts
  • packages/specs/src/oauth2/constants.ts
  • packages/specs/src/oauth2/error/index.ts
  • packages/specs/src/oauth2/error/mfa-required.ts

@tada5hi

tada5hi commented Jul 12, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai pause

…ery atomicity

- validate mfaEncryptionKey decodes to exactly 32 bytes at config time
  (normalize) instead of only truthiness — a wrong-length/whitespace key
  now fails loud at boot, not asynchronously at first encrypt/decrypt.
- SymmetricCipher validates the key length synchronously in the
  constructor, so a bad key throws at construction (DI mount) rather than
  leaving an unobserved promise rejection.
- resolveUserId throws BadRequestError when a non-user identity uses
  @me/@self, instead of letting the literal token match zero rows.
- enrollRecovery reuses the existing recovery row via a single atomic
  save instead of delete-then-insert, so a mid-op failure can never
  leave the user with no codes.
- verify-path concurrency/replay hardening (TOTP step reuse, recovery
  race, attempt-counter atomicity, session-stamp atomicity) tracked in #3237.

Refs #3232
@coderabbitai

coderabbitai Bot commented Jul 12, 2026

Copy link
Copy Markdown
✅ Action performed

Reviews paused.

tada5hi added 3 commits July 12, 2026 17:23
Folds the schema-dependent hardening from #3237 into the still-unreleased
auth_user_authenticators migration so no future migration is needed:

- add a @VersionColumn (`version`) to the authenticator row (folded into
  1783856507391-Default.ts, both dialects; run/revert/re-run verified on
  mysql + postgres). The verify path now consumes a factor exactly once
  under concurrency — a racing second save fails the version check, which
  the repository adapter translates to EntityConflictError and the service
  treats as a failed attempt (fixes recovery-code race, CR #602).
- persist the last accepted TOTP step and reject any step <= it, closing
  the in-window replay window (RFC 6238 §5.2, CR #604). Tracked only on the
  login-verify path (not confirm), so a first login in the confirmation
  window still works.

The two schema-FREE items from #3237 (attempt-counter atomicity via an
ICache atomic-increment; cross-aggregate session-stamp) stay open there —
deferring them needs no migration.

Refs #3232 #3237
The anti-replay step tracking rejects reusing one TOTP code for two
successful verifications; the e2e now generates the password-grant otp
from the previous ±1-window step so it stays behind the later challenge
code. Refs #3232 #3237
Replace the @VersionColumn optimistic-lock guard on the MFA verify path
with a per-user cache lock so a single factor (TOTP step / recovery code)
is consumed exactly once under concurrency, without a schema column.

Add ICache.add — atomic set-if-absent (Redis `SET … NX`, memory
single-tick check-set) — as the lock primitive. Acquisition fails open so
a cache outage cannot break MFA login; the TOTP step-counter and recovery
`used_at` flags remain the correctness backstop. A held lock means another
verify is mid-flight, so the request bails without penalty rather than
risk a double-consume.

Drop the version column from the entity, the core-kit domain type, and the
still-unreleased 1783856507391 migration (both dialects).
@tada5hi

tada5hi commented Jul 12, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai resume

@coderabbitai

coderabbitai Bot commented Jul 12, 2026

Copy link
Copy Markdown
✅ Action performed

Reviews resumed.

@tada5hi

tada5hi commented Jul 12, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.


Your plan includes PR reviews subject to rate limits. More reviews will be available in 59 minutes.

@tada5hi

tada5hi commented Jul 12, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.


Your plan includes PR reviews subject to rate limits. More reviews will be available in 37 minutes.

@tada5hi
tada5hi merged commit 6d0422a into master Jul 12, 2026
14 checks passed
@tada5hi
tada5hi deleted the feat/mfa-authenticator-devices branch July 12, 2026 17:10
@github-actions github-actions Bot mentioned this pull request Jul 12, 2026
tada5hi added a commit that referenced this pull request Jul 12, 2026
)

* feat: mfa authenticator devices with totp + recovery codes

Plan 049 stage 1 + the /token otp gate (roadmap wave 3.1):

- auth_user_authenticators: polymorphic device rows (kind totp/recovery;
  email/webauthn reserved); TOTP seeds AES-256-GCM-encrypted at rest
  (new SymmetricCipher in @authup/server-kit) under MFA_ENCRYPTION_KEY
  (fail-closed), recovery codes bcrypt-hashed, single-use, regenerated
  as a set; secret/codes select:false and stripped from every read.
- two-step enrollment (create unconfirmed -> confirm with code) on
  /users/:id/authenticators (+ @me), admin management via new
  USER_AUTHENTICATOR_* permissions (realm_admin own-scoped CUD).
- session-bound proof: auth_sessions.mfa_at (+ auth_method column for
  plan 050, coordinated into one migration pair) stamped by
  POST /authenticators/challenge or the password grant otp param; the
  OAuth2Authorization backstop throws a dedicated mfa_required error
  when a confirmed-device user authorizes without it; the password
  grant rejects password-only logins for enrolled users (otp accepts a
  totp or recovery code, classified by shape).
- per-account exponential backoff (cache-keyed, 429
  mfa_attempt_throttled), mfaEnrolled/mfaRemoved/mfaVerified/
  mfaChallengeFailed events, mfa_required authorize metric outcome,
  typed client.userAuthenticator.*, config mfaEnabled/mfaRequired/
  mfaEncryptionKey (boot-validated), i18n error catalog x4 locales,
  migrations verified via run/revert/re-run on mysql + postgres.

* feat: session auth-method recording with amr/acr claims and acr step-up

Plan 050 stages 1-3 (roadmap wave 3.1, second half):

- every session-creation site stamps auth_method (pwd/ext/client/robot;
  ldap reserved for the deferred stage 1b) — the federated IdP callback
  threads it through the authorization-code blob so the /token
  fallback-create inherits it, and the interactive /authorize threads
  the bearer session's method the same way.
- amr/acr derive at the /token exchange from the RESOLVED session
  (deriveAmrAcr): pwd/ldap -> ['pwd'], ext -> ['ext'], + 'otp' when the
  session carries a second-factor proof (mfa_at); acr urn:authup:mfa vs
  urn:authup:pwd (urn-style, never the reserved "0"). Emitted on every
  token kind (intentional — resource servers read the method without
  parsing an id_token); NULL auth_method (pre-column session) emits none.
- acr_values accepted on /authorize (case-sensitive mount, persisted on
  the code blob) and advertised via discovery acr_values_supported;
  urn:authup:mfa acts as a step-up trigger enforced only while the user
  holds a confirmed factor (voluntary per OIDC Core 5.5.1.1 otherwise):
  session.mfa_at must be within mfaFreshnessMaxAge (default 60s, NOT the
  plan's 0 — a 0-window could never absorb the challenge round-trip and
  would loop the hosted ladder).
- session list read surface exposes mfa_at/auth_method.

* fix(mfa): address review — key validation, cipher construction, recovery atomicity

- validate mfaEncryptionKey decodes to exactly 32 bytes at config time
  (normalize) instead of only truthiness — a wrong-length/whitespace key
  now fails loud at boot, not asynchronously at first encrypt/decrypt.
- SymmetricCipher validates the key length synchronously in the
  constructor, so a bad key throws at construction (DI mount) rather than
  leaving an unobserved promise rejection.
- resolveUserId throws BadRequestError when a non-user identity uses
  @me/@self, instead of letting the literal token match zero rows.
- enrollRecovery reuses the existing recovery row via a single atomic
  save instead of delete-then-insert, so a mid-op failure can never
  leave the user with no codes.
- verify-path concurrency/replay hardening (TOTP step reuse, recovery
  race, attempt-counter atomicity, session-stamp atomicity) tracked in #3237.

Refs #3232

* fix(mfa): optimistic-lock + totp replay protection (#3237, schema half)

Folds the schema-dependent hardening from #3237 into the still-unreleased
auth_user_authenticators migration so no future migration is needed:

- add a @VersionColumn (`version`) to the authenticator row (folded into
  1783856507391-Default.ts, both dialects; run/revert/re-run verified on
  mysql + postgres). The verify path now consumes a factor exactly once
  under concurrency — a racing second save fails the version check, which
  the repository adapter translates to EntityConflictError and the service
  treats as a failed attempt (fixes recovery-code race, CR #602).
- persist the last accepted TOTP step and reject any step <= it, closing
  the in-window replay window (RFC 6238 §5.2, CR #604). Tracked only on the
  login-verify path (not confirm), so a first login in the confirmation
  window still works.

The two schema-FREE items from #3237 (attempt-counter atomicity via an
ICache atomic-increment; cross-aggregate session-stamp) stay open there —
deferring them needs no migration.

Refs #3232 #3237

* test(mfa): use distinct totp steps for sequential verifies (#3237)

The anti-replay step tracking rejects reusing one TOTP code for two
successful verifications; the e2e now generates the password-grant otp
from the previous ±1-window step so it stays behind the later challenge
code. Refs #3232 #3237

* refactor(mfa): serialize verify with a per-user cache lock (#3237)

Replace the @VersionColumn optimistic-lock guard on the MFA verify path
with a per-user cache lock so a single factor (TOTP step / recovery code)
is consumed exactly once under concurrency, without a schema column.

Add ICache.add — atomic set-if-absent (Redis `SET … NX`, memory
single-tick check-set) — as the lock primitive. Acquisition fails open so
a cache outage cannot break MFA login; the TOTP step-counter and recovery
`used_at` flags remain the correctness backstop. A held lock means another
verify is mid-flight, so the request bails without penalty rather than
risk a double-consume.

Drop the version column from the entity, the core-kit domain type, and the
still-unreleased 1783856507391 migration (both dialects).

* fix(oauth2): emit amr/acr on the direct password and identity grants (#3233)

The direct password (ROPC) and identity grants stamped `auth_method` on the
session but issued tokens without the derived `amr`/`acr` claims, so a
resource server receiving a direct-grant token could not read how the subject
authenticated — unlike the authorization_code exchange, which already spreads
`deriveAmrAcr(session)` onto its payload.

Both grants now derive and spread the claims from the same session fields,
mirroring authorize.ts. M2M grants (client/robot) are unaffected —
`deriveAmrAcr` returns nothing for their methods.

* refactor(core-kit): constrain auth_method to the SessionAuthMethod value-union (#3233)

`Session.auth_method`, `OAuth2AuthorizationCode.auth_method`, the session
TypeORM entity column, and the authorization-code issuer option were typed
`string | null`, permitting invalid persisted values while downstream claim
derivation only recognizes defined methods. Narrow all four to
`` `${SessionAuthMethod}` | null `` (matching the existing `UserAuthenticator.kind`
convention) so the type mirrors the actual value set. Pure type narrowing —
every write site already passes a `SessionAuthMethod` member or null.
tada5hi added a commit that referenced this pull request Jul 13, 2026
…dmin tabs (#3234)

* feat: mfa authenticator devices with totp + recovery codes

Plan 049 stage 1 + the /token otp gate (roadmap wave 3.1):

- auth_user_authenticators: polymorphic device rows (kind totp/recovery;
  email/webauthn reserved); TOTP seeds AES-256-GCM-encrypted at rest
  (new SymmetricCipher in @authup/server-kit) under MFA_ENCRYPTION_KEY
  (fail-closed), recovery codes bcrypt-hashed, single-use, regenerated
  as a set; secret/codes select:false and stripped from every read.
- two-step enrollment (create unconfirmed -> confirm with code) on
  /users/:id/authenticators (+ @me), admin management via new
  USER_AUTHENTICATOR_* permissions (realm_admin own-scoped CUD).
- session-bound proof: auth_sessions.mfa_at (+ auth_method column for
  plan 050, coordinated into one migration pair) stamped by
  POST /authenticators/challenge or the password grant otp param; the
  OAuth2Authorization backstop throws a dedicated mfa_required error
  when a confirmed-device user authorizes without it; the password
  grant rejects password-only logins for enrolled users (otp accepts a
  totp or recovery code, classified by shape).
- per-account exponential backoff (cache-keyed, 429
  mfa_attempt_throttled), mfaEnrolled/mfaRemoved/mfaVerified/
  mfaChallengeFailed events, mfa_required authorize metric outcome,
  typed client.userAuthenticator.*, config mfaEnabled/mfaRequired/
  mfaEncryptionKey (boot-validated), i18n error catalog x4 locales,
  migrations verified via run/revert/re-run on mysql + postgres.

* feat: session auth-method recording with amr/acr claims and acr step-up

Plan 050 stages 1-3 (roadmap wave 3.1, second half):

- every session-creation site stamps auth_method (pwd/ext/client/robot;
  ldap reserved for the deferred stage 1b) — the federated IdP callback
  threads it through the authorization-code blob so the /token
  fallback-create inherits it, and the interactive /authorize threads
  the bearer session's method the same way.
- amr/acr derive at the /token exchange from the RESOLVED session
  (deriveAmrAcr): pwd/ldap -> ['pwd'], ext -> ['ext'], + 'otp' when the
  session carries a second-factor proof (mfa_at); acr urn:authup:mfa vs
  urn:authup:pwd (urn-style, never the reserved "0"). Emitted on every
  token kind (intentional — resource servers read the method without
  parsing an id_token); NULL auth_method (pre-column session) emits none.
- acr_values accepted on /authorize (case-sensitive mount, persisted on
  the code blob) and advertised via discovery acr_values_supported;
  urn:authup:mfa acts as a step-up trigger enforced only while the user
  holds a confirmed factor (voluntary per OIDC Core 5.5.1.1 otherwise):
  session.mfa_at must be within mfaFreshnessMaxAge (default 60s, NOT the
  plan's 0 — a 0-window could never absorb the challenge round-trip and
  would loop the hosted ladder).
- session list read surface exposes mfa_at/auth_method.

* feat(client-web-kit): mfa challenge step, enrollment ui, settings + admin tabs

Plan 049 UI (roadmap wave 3.1):

- AMfaChallengeForm (workflows/mfa) — code input posting to
  client.userAuthenticator.verifyChallenge, recovery-code fallback
  toggle, extractErrorContext failures.
- Authorize.vue ladder: after login a watch(loggedIn) fetches
  GET /authenticators/challenge; consent blocks until it resolves
  (built_in auto-consent must not fire first); required -> the
  challenge form before consent (its done = mfa_at stamped, so the
  consent POST passes the server backstop); enrollmentRequired ->
  inline AUserAuthenticatorEnroll (configure-inline). Interactive only;
  silent flows let the auto-consent hit the backstop -> interaction_required.
- AUserAuthenticatorEnroll (QR data-uri + confirm code / recovery codes
  with download) + AUserAuthenticators (list + delete + embedded enroll);
  hosted on settings security tab (@me) and an admin authenticators tab
  gated on USER_AUTHENTICATOR_READ.
- MFA_* (authupClient) + AUTHENTICATOR/MFA_SECURITY_* (authupApp) keys
  across all four locales (parity test green); kit component test.

* fix(mfa): address review — key validation, cipher construction, recovery atomicity

- validate mfaEncryptionKey decodes to exactly 32 bytes at config time
  (normalize) instead of only truthiness — a wrong-length/whitespace key
  now fails loud at boot, not asynchronously at first encrypt/decrypt.
- SymmetricCipher validates the key length synchronously in the
  constructor, so a bad key throws at construction (DI mount) rather than
  leaving an unobserved promise rejection.
- resolveUserId throws BadRequestError when a non-user identity uses
  @me/@self, instead of letting the literal token match zero rows.
- enrollRecovery reuses the existing recovery row via a single atomic
  save instead of delete-then-insert, so a mid-op failure can never
  leave the user with no codes.
- verify-path concurrency/replay hardening (TOTP step reuse, recovery
  race, attempt-counter atomicity, session-stamp atomicity) tracked in #3237.

Refs #3232

* fix(mfa): optimistic-lock + totp replay protection (#3237, schema half)

Folds the schema-dependent hardening from #3237 into the still-unreleased
auth_user_authenticators migration so no future migration is needed:

- add a @VersionColumn (`version`) to the authenticator row (folded into
  1783856507391-Default.ts, both dialects; run/revert/re-run verified on
  mysql + postgres). The verify path now consumes a factor exactly once
  under concurrency — a racing second save fails the version check, which
  the repository adapter translates to EntityConflictError and the service
  treats as a failed attempt (fixes recovery-code race, CR #602).
- persist the last accepted TOTP step and reject any step <= it, closing
  the in-window replay window (RFC 6238 §5.2, CR #604). Tracked only on the
  login-verify path (not confirm), so a first login in the confirmation
  window still works.

The two schema-FREE items from #3237 (attempt-counter atomicity via an
ICache atomic-increment; cross-aggregate session-stamp) stay open there —
deferring them needs no migration.

Refs #3232 #3237

* test(mfa): use distinct totp steps for sequential verifies (#3237)

The anti-replay step tracking rejects reusing one TOTP code for two
successful verifications; the e2e now generates the password-grant otp
from the previous ±1-window step so it stays behind the later challenge
code. Refs #3232 #3237

* refactor(mfa): serialize verify with a per-user cache lock (#3237)

Replace the @VersionColumn optimistic-lock guard on the MFA verify path
with a per-user cache lock so a single factor (TOTP step / recovery code)
is consumed exactly once under concurrency, without a schema column.

Add ICache.add — atomic set-if-absent (Redis `SET … NX`, memory
single-tick check-set) — as the lock primitive. Acquisition fails open so
a cache outage cannot break MFA login; the TOTP step-counter and recovery
`used_at` flags remain the correctness backstop. A held lock means another
verify is mid-flight, so the request bails without penalty rather than
risk a double-consume.

Drop the version column from the entity, the core-kit domain type, and the
still-unreleased 1783856507391 migration (both dialects).

* fix(oauth2): emit amr/acr on the direct password and identity grants (#3233)

The direct password (ROPC) and identity grants stamped `auth_method` on the
session but issued tokens without the derived `amr`/`acr` claims, so a
resource server receiving a direct-grant token could not read how the subject
authenticated — unlike the authorization_code exchange, which already spreads
`deriveAmrAcr(session)` onto its payload.

Both grants now derive and spread the claims from the same session fields,
mirroring authorize.ts. M2M grants (client/robot) are unaffected —
`deriveAmrAcr` returns nothing for their methods.

* refactor(core-kit): constrain auth_method to the SessionAuthMethod value-union (#3233)

`Session.auth_method`, `OAuth2AuthorizationCode.auth_method`, the session
TypeORM entity column, and the authorization-code issuer option were typed
`string | null`, permitting invalid persisted values while downstream claim
derivation only recognizes defined methods. Narrow all four to
`` `${SessionAuthMethod}` | null `` (matching the existing `UserAuthenticator.kind`
convention) so the type mirrors the actual value set. Pure type narrowing —
every write site already passes a `SessionAuthMethod` member or null.

* fix(client-web-kit): address MFA UI review feedback (#3234)

- AUserAuthenticatorEnroll: add a Close action to the recovery-codes view so
  the user can return to the kind picker after generating codes (it previously
  stuck there — recovery enroll never reset the view, unlike the TOTP path).
- AUserAuthenticators: confirm before deleting an authenticator via
  useAlertDialog — removing a factor is irreversible and weakens the account's
  security posture (matches the other destructive kit actions).
- Authorize: retry the MFA challenge lookup once before failing open, so a
  transient blip does not permanently disable the client-side gate for the
  render lifecycle (the server /authorize backstop stays authoritative).
- i18n(de): AUTHENTICATOR -> 'Authentifikatoren' (plural device noun, matching
  en/fr/es) instead of 'Authentifizierung' (the process).
tada5hi added a commit that referenced this pull request Jul 13, 2026
* feat: mfa authenticator devices with totp + recovery codes

Plan 049 stage 1 + the /token otp gate (roadmap wave 3.1):

- auth_user_authenticators: polymorphic device rows (kind totp/recovery;
  email/webauthn reserved); TOTP seeds AES-256-GCM-encrypted at rest
  (new SymmetricCipher in @authup/server-kit) under MFA_ENCRYPTION_KEY
  (fail-closed), recovery codes bcrypt-hashed, single-use, regenerated
  as a set; secret/codes select:false and stripped from every read.
- two-step enrollment (create unconfirmed -> confirm with code) on
  /users/:id/authenticators (+ @me), admin management via new
  USER_AUTHENTICATOR_* permissions (realm_admin own-scoped CUD).
- session-bound proof: auth_sessions.mfa_at (+ auth_method column for
  plan 050, coordinated into one migration pair) stamped by
  POST /authenticators/challenge or the password grant otp param; the
  OAuth2Authorization backstop throws a dedicated mfa_required error
  when a confirmed-device user authorizes without it; the password
  grant rejects password-only logins for enrolled users (otp accepts a
  totp or recovery code, classified by shape).
- per-account exponential backoff (cache-keyed, 429
  mfa_attempt_throttled), mfaEnrolled/mfaRemoved/mfaVerified/
  mfaChallengeFailed events, mfa_required authorize metric outcome,
  typed client.userAuthenticator.*, config mfaEnabled/mfaRequired/
  mfaEncryptionKey (boot-validated), i18n error catalog x4 locales,
  migrations verified via run/revert/re-run on mysql + postgres.

* feat: session auth-method recording with amr/acr claims and acr step-up

Plan 050 stages 1-3 (roadmap wave 3.1, second half):

- every session-creation site stamps auth_method (pwd/ext/client/robot;
  ldap reserved for the deferred stage 1b) — the federated IdP callback
  threads it through the authorization-code blob so the /token
  fallback-create inherits it, and the interactive /authorize threads
  the bearer session's method the same way.
- amr/acr derive at the /token exchange from the RESOLVED session
  (deriveAmrAcr): pwd/ldap -> ['pwd'], ext -> ['ext'], + 'otp' when the
  session carries a second-factor proof (mfa_at); acr urn:authup:mfa vs
  urn:authup:pwd (urn-style, never the reserved "0"). Emitted on every
  token kind (intentional — resource servers read the method without
  parsing an id_token); NULL auth_method (pre-column session) emits none.
- acr_values accepted on /authorize (case-sensitive mount, persisted on
  the code blob) and advertised via discovery acr_values_supported;
  urn:authup:mfa acts as a step-up trigger enforced only while the user
  holds a confirmed factor (voluntary per OIDC Core 5.5.1.1 otherwise):
  session.mfa_at must be within mfaFreshnessMaxAge (default 60s, NOT the
  plan's 0 — a 0-window could never absorb the challenge round-trip and
  would loop the hosted ladder).
- session list read surface exposes mfa_at/auth_method.

* feat(client-web-kit): mfa challenge step, enrollment ui, settings + admin tabs

Plan 049 UI (roadmap wave 3.1):

- AMfaChallengeForm (workflows/mfa) — code input posting to
  client.userAuthenticator.verifyChallenge, recovery-code fallback
  toggle, extractErrorContext failures.
- Authorize.vue ladder: after login a watch(loggedIn) fetches
  GET /authenticators/challenge; consent blocks until it resolves
  (built_in auto-consent must not fire first); required -> the
  challenge form before consent (its done = mfa_at stamped, so the
  consent POST passes the server backstop); enrollmentRequired ->
  inline AUserAuthenticatorEnroll (configure-inline). Interactive only;
  silent flows let the auto-consent hit the backstop -> interaction_required.
- AUserAuthenticatorEnroll (QR data-uri + confirm code / recovery codes
  with download) + AUserAuthenticators (list + delete + embedded enroll);
  hosted on settings security tab (@me) and an admin authenticators tab
  gated on USER_AUTHENTICATOR_READ.
- MFA_* (authupClient) + AUTHENTICATOR/MFA_SECURITY_* (authupApp) keys
  across all four locales (parity test green); kit component test.

* feat: email otp as a second-factor kind (plan 049 stage 1.5)

- kind:'email' rows mark a verified mailbox as an enrolled factor
  (confirmed on create; enrollment force-loads the select:false email
  via findOneByWithEmail). The code is transient: sendChallenge
  generates a 6-digit numeric code, bcrypt-hashes it into the cache
  (mfaEmailCode:<user_id>, 10-min TTL) and mails it via a new
  MailTemplateName.MFA_EMAIL_OTP template (authupMail i18n x4);
  verify compares the cached hash + expiry and single-uses it.
- POST /authenticators/challenge/send { kind } issues the challenge
  (uniform 200 — no enrollment/status oracle; only a confirmed email
  factor triggers a mail); client.userAuthenticator.sendChallenge.
- MailModule.setup honors a pre-registered MailInjectionKey (test fake
  wins, mirroring UIHttpClient) so tests can capture mailed codes.
- kit: AMfaChallengeForm gains an email branch (send-code button ->
  code input) + kind switcher; enroll picker gains an email option.
- tests: service (enroll/send/verify/single-use/fail-closed), mail
  renderer + smoke matrix, kit challenge email flow, HTTP e2e.

* fix(mfa): address review — key validation, cipher construction, recovery atomicity

- validate mfaEncryptionKey decodes to exactly 32 bytes at config time
  (normalize) instead of only truthiness — a wrong-length/whitespace key
  now fails loud at boot, not asynchronously at first encrypt/decrypt.
- SymmetricCipher validates the key length synchronously in the
  constructor, so a bad key throws at construction (DI mount) rather than
  leaving an unobserved promise rejection.
- resolveUserId throws BadRequestError when a non-user identity uses
  @me/@self, instead of letting the literal token match zero rows.
- enrollRecovery reuses the existing recovery row via a single atomic
  save instead of delete-then-insert, so a mid-op failure can never
  leave the user with no codes.
- verify-path concurrency/replay hardening (TOTP step reuse, recovery
  race, attempt-counter atomicity, session-stamp atomicity) tracked in #3237.

Refs #3232

* fix(mfa): optimistic-lock + totp replay protection (#3237, schema half)

Folds the schema-dependent hardening from #3237 into the still-unreleased
auth_user_authenticators migration so no future migration is needed:

- add a @VersionColumn (`version`) to the authenticator row (folded into
  1783856507391-Default.ts, both dialects; run/revert/re-run verified on
  mysql + postgres). The verify path now consumes a factor exactly once
  under concurrency — a racing second save fails the version check, which
  the repository adapter translates to EntityConflictError and the service
  treats as a failed attempt (fixes recovery-code race, CR #602).
- persist the last accepted TOTP step and reject any step <= it, closing
  the in-window replay window (RFC 6238 §5.2, CR #604). Tracked only on the
  login-verify path (not confirm), so a first login in the confirmation
  window still works.

The two schema-FREE items from #3237 (attempt-counter atomicity via an
ICache atomic-increment; cross-aggregate session-stamp) stay open there —
deferring them needs no migration.

Refs #3232 #3237

* test(mfa): use distinct totp steps for sequential verifies (#3237)

The anti-replay step tracking rejects reusing one TOTP code for two
successful verifications; the e2e now generates the password-grant otp
from the previous ±1-window step so it stays behind the later challenge
code. Refs #3232 #3237

* refactor(mfa): serialize verify with a per-user cache lock (#3237)

Replace the @VersionColumn optimistic-lock guard on the MFA verify path
with a per-user cache lock so a single factor (TOTP step / recovery code)
is consumed exactly once under concurrency, without a schema column.

Add ICache.add — atomic set-if-absent (Redis `SET … NX`, memory
single-tick check-set) — as the lock primitive. Acquisition fails open so
a cache outage cannot break MFA login; the TOTP step-counter and recovery
`used_at` flags remain the correctness backstop. A held lock means another
verify is mid-flight, so the request bails without penalty rather than
risk a double-consume.

Drop the version column from the entity, the core-kit domain type, and the
still-unreleased 1783856507391 migration (both dialects).

* fix(oauth2): emit amr/acr on the direct password and identity grants (#3233)

The direct password (ROPC) and identity grants stamped `auth_method` on the
session but issued tokens without the derived `amr`/`acr` claims, so a
resource server receiving a direct-grant token could not read how the subject
authenticated — unlike the authorization_code exchange, which already spreads
`deriveAmrAcr(session)` onto its payload.

Both grants now derive and spread the claims from the same session fields,
mirroring authorize.ts. M2M grants (client/robot) are unaffected —
`deriveAmrAcr` returns nothing for their methods.

* refactor(core-kit): constrain auth_method to the SessionAuthMethod value-union (#3233)

`Session.auth_method`, `OAuth2AuthorizationCode.auth_method`, the session
TypeORM entity column, and the authorization-code issuer option were typed
`string | null`, permitting invalid persisted values while downstream claim
derivation only recognizes defined methods. Narrow all four to
`` `${SessionAuthMethod}` | null `` (matching the existing `UserAuthenticator.kind`
convention) so the type mirrors the actual value set. Pure type narrowing —
every write site already passes a `SessionAuthMethod` member or null.

* fix(client-web-kit): address MFA UI review feedback (#3234)

- AUserAuthenticatorEnroll: add a Close action to the recovery-codes view so
  the user can return to the kind picker after generating codes (it previously
  stuck there — recovery enroll never reset the view, unlike the TOTP path).
- AUserAuthenticators: confirm before deleting an authenticator via
  useAlertDialog — removing a factor is irreversible and weakens the account's
  security posture (matches the other destructive kit actions).
- Authorize: retry the MFA challenge lookup once before failing open, so a
  transient blip does not permanently disable the client-side gate for the
  render lifecycle (the server /authorize backstop stays authoritative).
- i18n(de): AUTHENTICATOR -> 'Authentifikatoren' (plural device noun, matching
  en/fr/es) instead of 'Authentifizierung' (the process).

* fix(mfa): harden email-OTP factor per review feedback (#3235)

- enrollEmail: update the existing email marker row in place instead of
  remove-then-create, so a failed save can never leave the user with no email
  factor (the row carries no secret/codes — an in-place update is equivalent).
- verify: EMAIL has no persisted anti-replay backstop (its single-use rides on
  the verify lock + cache drop), so it must NOT ride the lock's fail-open path.
  acquireVerifyLock now reports acquired | busy | unavailable; EMAIL fails
  closed when the lock is unavailable (cache down), while TOTP/recovery keep
  proceeding on their persisted backstops. Only release a lock we actually hold.
- sendChallenge: add a per-user send cooldown (atomic set-if-absent, fails open
  on cache error) so an authenticated caller cannot spray unlimited OTP mails;
  a resend within the window throws MfaThrottledError (429).
- AMfaChallengeForm: emit the original exception through `failed` (was a string)
  so consumers can inspect status/context, matching AUserAuthenticatorEnroll;
  add a resend action to the email verification form (a delayed/expired code
  otherwise dead-ends the flow — the server cooldown backs it).
tada5hi added a commit that referenced this pull request Jul 13, 2026
* feat: mfa authenticator devices with totp + recovery codes

Plan 049 stage 1 + the /token otp gate (roadmap wave 3.1):

- auth_user_authenticators: polymorphic device rows (kind totp/recovery;
  email/webauthn reserved); TOTP seeds AES-256-GCM-encrypted at rest
  (new SymmetricCipher in @authup/server-kit) under MFA_ENCRYPTION_KEY
  (fail-closed), recovery codes bcrypt-hashed, single-use, regenerated
  as a set; secret/codes select:false and stripped from every read.
- two-step enrollment (create unconfirmed -> confirm with code) on
  /users/:id/authenticators (+ @me), admin management via new
  USER_AUTHENTICATOR_* permissions (realm_admin own-scoped CUD).
- session-bound proof: auth_sessions.mfa_at (+ auth_method column for
  plan 050, coordinated into one migration pair) stamped by
  POST /authenticators/challenge or the password grant otp param; the
  OAuth2Authorization backstop throws a dedicated mfa_required error
  when a confirmed-device user authorizes without it; the password
  grant rejects password-only logins for enrolled users (otp accepts a
  totp or recovery code, classified by shape).
- per-account exponential backoff (cache-keyed, 429
  mfa_attempt_throttled), mfaEnrolled/mfaRemoved/mfaVerified/
  mfaChallengeFailed events, mfa_required authorize metric outcome,
  typed client.userAuthenticator.*, config mfaEnabled/mfaRequired/
  mfaEncryptionKey (boot-validated), i18n error catalog x4 locales,
  migrations verified via run/revert/re-run on mysql + postgres.

* feat: session auth-method recording with amr/acr claims and acr step-up

Plan 050 stages 1-3 (roadmap wave 3.1, second half):

- every session-creation site stamps auth_method (pwd/ext/client/robot;
  ldap reserved for the deferred stage 1b) — the federated IdP callback
  threads it through the authorization-code blob so the /token
  fallback-create inherits it, and the interactive /authorize threads
  the bearer session's method the same way.
- amr/acr derive at the /token exchange from the RESOLVED session
  (deriveAmrAcr): pwd/ldap -> ['pwd'], ext -> ['ext'], + 'otp' when the
  session carries a second-factor proof (mfa_at); acr urn:authup:mfa vs
  urn:authup:pwd (urn-style, never the reserved "0"). Emitted on every
  token kind (intentional — resource servers read the method without
  parsing an id_token); NULL auth_method (pre-column session) emits none.
- acr_values accepted on /authorize (case-sensitive mount, persisted on
  the code blob) and advertised via discovery acr_values_supported;
  urn:authup:mfa acts as a step-up trigger enforced only while the user
  holds a confirmed factor (voluntary per OIDC Core 5.5.1.1 otherwise):
  session.mfa_at must be within mfaFreshnessMaxAge (default 60s, NOT the
  plan's 0 — a 0-window could never absorb the challenge round-trip and
  would loop the hosted ladder).
- session list read surface exposes mfa_at/auth_method.

* feat(client-web-kit): mfa challenge step, enrollment ui, settings + admin tabs

Plan 049 UI (roadmap wave 3.1):

- AMfaChallengeForm (workflows/mfa) — code input posting to
  client.userAuthenticator.verifyChallenge, recovery-code fallback
  toggle, extractErrorContext failures.
- Authorize.vue ladder: after login a watch(loggedIn) fetches
  GET /authenticators/challenge; consent blocks until it resolves
  (built_in auto-consent must not fire first); required -> the
  challenge form before consent (its done = mfa_at stamped, so the
  consent POST passes the server backstop); enrollmentRequired ->
  inline AUserAuthenticatorEnroll (configure-inline). Interactive only;
  silent flows let the auto-consent hit the backstop -> interaction_required.
- AUserAuthenticatorEnroll (QR data-uri + confirm code / recovery codes
  with download) + AUserAuthenticators (list + delete + embedded enroll);
  hosted on settings security tab (@me) and an admin authenticators tab
  gated on USER_AUTHENTICATOR_READ.
- MFA_* (authupClient) + AUTHENTICATOR/MFA_SECURITY_* (authupApp) keys
  across all four locales (parity test green); kit component test.

* feat: email otp as a second-factor kind (plan 049 stage 1.5)

- kind:'email' rows mark a verified mailbox as an enrolled factor
  (confirmed on create; enrollment force-loads the select:false email
  via findOneByWithEmail). The code is transient: sendChallenge
  generates a 6-digit numeric code, bcrypt-hashes it into the cache
  (mfaEmailCode:<user_id>, 10-min TTL) and mails it via a new
  MailTemplateName.MFA_EMAIL_OTP template (authupMail i18n x4);
  verify compares the cached hash + expiry and single-uses it.
- POST /authenticators/challenge/send { kind } issues the challenge
  (uniform 200 — no enrollment/status oracle; only a confirmed email
  factor triggers a mail); client.userAuthenticator.sendChallenge.
- MailModule.setup honors a pre-registered MailInjectionKey (test fake
  wins, mirroring UIHttpClient) so tests can capture mailed codes.
- kit: AMfaChallengeForm gains an email branch (send-code button ->
  code input) + kind switcher; enroll picker gains an email option.
- tests: service (enroll/send/verify/single-use/fail-closed), mail
  renderer + smoke matrix, kit challenge email flow, HTTP e2e.

* feat: webauthn/passkeys as a second factor (plan 049 stage 2)

- kind:'webauthn' rows store the registered credential (base64url id +
  public key, signature counter, transports) in parameters JSON. The
  ceremony rides @simplewebauthn/server (webauthn.ts); the relying-party
  context (rpId/rpName/origin) derives from publicUrl — the hosted
  /authorize origin (plan 041), so no per-RP plumbing (absent publicUrl
  -> refused).
- registration: enroll returns creation options + a cached challenge
  (mfaWebauthnReg, 5-min) and an unconfirmed row; confirm verifies the
  attestation and stores the credential. authentication is kind-generic:
  challenge() surfaces request options under status.challenge.webauthn
  (caching the nonce), verify matches the assertion to its credential
  row, verifies against the cached challenge, and bumps the stored
  counter (replay defense). second-factor only.
- kit: AMfaChallengeForm gains a passkey button (@simplewebauthn/browser
  startAuthentication, webauthn preferred first); enroll picker gains a
  passkey option (startRegistration -> confirm).
- deps: @simplewebauthn/{server,browser} as stateless-leaf dependencies.
- tests: service (enroll options + cached challenge, auth-options in
  challenge, fail-closed without rp, malformed attestation) + kit
  ceremony (mocked browser lib).

* fix(mfa): address review — key validation, cipher construction, recovery atomicity

- validate mfaEncryptionKey decodes to exactly 32 bytes at config time
  (normalize) instead of only truthiness — a wrong-length/whitespace key
  now fails loud at boot, not asynchronously at first encrypt/decrypt.
- SymmetricCipher validates the key length synchronously in the
  constructor, so a bad key throws at construction (DI mount) rather than
  leaving an unobserved promise rejection.
- resolveUserId throws BadRequestError when a non-user identity uses
  @me/@self, instead of letting the literal token match zero rows.
- enrollRecovery reuses the existing recovery row via a single atomic
  save instead of delete-then-insert, so a mid-op failure can never
  leave the user with no codes.
- verify-path concurrency/replay hardening (TOTP step reuse, recovery
  race, attempt-counter atomicity, session-stamp atomicity) tracked in #3237.

Refs #3232

* fix(mfa): optimistic-lock + totp replay protection (#3237, schema half)

Folds the schema-dependent hardening from #3237 into the still-unreleased
auth_user_authenticators migration so no future migration is needed:

- add a @VersionColumn (`version`) to the authenticator row (folded into
  1783856507391-Default.ts, both dialects; run/revert/re-run verified on
  mysql + postgres). The verify path now consumes a factor exactly once
  under concurrency — a racing second save fails the version check, which
  the repository adapter translates to EntityConflictError and the service
  treats as a failed attempt (fixes recovery-code race, CR #602).
- persist the last accepted TOTP step and reject any step <= it, closing
  the in-window replay window (RFC 6238 §5.2, CR #604). Tracked only on the
  login-verify path (not confirm), so a first login in the confirmation
  window still works.

The two schema-FREE items from #3237 (attempt-counter atomicity via an
ICache atomic-increment; cross-aggregate session-stamp) stay open there —
deferring them needs no migration.

Refs #3232 #3237

* test(mfa): use distinct totp steps for sequential verifies (#3237)

The anti-replay step tracking rejects reusing one TOTP code for two
successful verifications; the e2e now generates the password-grant otp
from the previous ±1-window step so it stays behind the later challenge
code. Refs #3232 #3237

* refactor(mfa): serialize verify with a per-user cache lock (#3237)

Replace the @VersionColumn optimistic-lock guard on the MFA verify path
with a per-user cache lock so a single factor (TOTP step / recovery code)
is consumed exactly once under concurrency, without a schema column.

Add ICache.add — atomic set-if-absent (Redis `SET … NX`, memory
single-tick check-set) — as the lock primitive. Acquisition fails open so
a cache outage cannot break MFA login; the TOTP step-counter and recovery
`used_at` flags remain the correctness backstop. A held lock means another
verify is mid-flight, so the request bails without penalty rather than
risk a double-consume.

Drop the version column from the entity, the core-kit domain type, and the
still-unreleased 1783856507391 migration (both dialects).

* fix(oauth2): emit amr/acr on the direct password and identity grants (#3233)

The direct password (ROPC) and identity grants stamped `auth_method` on the
session but issued tokens without the derived `amr`/`acr` claims, so a
resource server receiving a direct-grant token could not read how the subject
authenticated — unlike the authorization_code exchange, which already spreads
`deriveAmrAcr(session)` onto its payload.

Both grants now derive and spread the claims from the same session fields,
mirroring authorize.ts. M2M grants (client/robot) are unaffected —
`deriveAmrAcr` returns nothing for their methods.

* refactor(core-kit): constrain auth_method to the SessionAuthMethod value-union (#3233)

`Session.auth_method`, `OAuth2AuthorizationCode.auth_method`, the session
TypeORM entity column, and the authorization-code issuer option were typed
`string | null`, permitting invalid persisted values while downstream claim
derivation only recognizes defined methods. Narrow all four to
`` `${SessionAuthMethod}` | null `` (matching the existing `UserAuthenticator.kind`
convention) so the type mirrors the actual value set. Pure type narrowing —
every write site already passes a `SessionAuthMethod` member or null.

* fix(client-web-kit): address MFA UI review feedback (#3234)

- AUserAuthenticatorEnroll: add a Close action to the recovery-codes view so
  the user can return to the kind picker after generating codes (it previously
  stuck there — recovery enroll never reset the view, unlike the TOTP path).
- AUserAuthenticators: confirm before deleting an authenticator via
  useAlertDialog — removing a factor is irreversible and weakens the account's
  security posture (matches the other destructive kit actions).
- Authorize: retry the MFA challenge lookup once before failing open, so a
  transient blip does not permanently disable the client-side gate for the
  render lifecycle (the server /authorize backstop stays authoritative).
- i18n(de): AUTHENTICATOR -> 'Authentifikatoren' (plural device noun, matching
  en/fr/es) instead of 'Authentifizierung' (the process).

* fix(mfa): harden email-OTP factor per review feedback (#3235)

- enrollEmail: update the existing email marker row in place instead of
  remove-then-create, so a failed save can never leave the user with no email
  factor (the row carries no secret/codes — an in-place update is equivalent).
- verify: EMAIL has no persisted anti-replay backstop (its single-use rides on
  the verify lock + cache drop), so it must NOT ride the lock's fail-open path.
  acquireVerifyLock now reports acquired | busy | unavailable; EMAIL fails
  closed when the lock is unavailable (cache down), while TOTP/recovery keep
  proceeding on their persisted backstops. Only release a lock we actually hold.
- sendChallenge: add a per-user send cooldown (atomic set-if-absent, fails open
  on cache error) so an authenticated caller cannot spray unlimited OTP mails;
  a resend within the window throws MfaThrottledError (429).
- AMfaChallengeForm: emit the original exception through `failed` (was a string)
  so consumers can inspect status/context, matching AUserAuthenticatorEnroll;
  add a resend action to the email verification form (a delayed/expired code
  otherwise dead-ends the flow — the server cooldown backs it).

* fix(mfa): harden webauthn factor per review feedback (#3236)

- enrollWebauthn/confirmWebauthn: key the registration challenge by the new
  row id instead of the user id, so overlapping enrollment ceremonies (a
  second tab, a retry after a cancelled prompt) no longer overwrite each
  other's challenge and make the first confirmation fail spuriously. The row
  is created before the challenge is cached.
- confirmWebauthn: apply the same brute-force throttle lifecycle as the TOTP
  confirm branch (assertNotThrottled / bumpAttempts on a credential-invalid /
  resetAttempts on success) — the attestation verify is a real crypto call
  and must not be retryable without backoff.
- AUserAuthenticatorEnroll: require the server's WebAuthn registration options
  before startRegistration (clear error instead of an empty-object fallback
  that fails obscurely in the browser), and replace the `as never` cast with a
  documented assertion to PublicKeyCredentialCreationOptionsJSON.
- AMfaChallengeForm: disable the passkey button when the challenge carries no
  webauthn options, so it can't present a dead button (the user switches
  factors instead).

Tests: per-enrollment challenge keying + concurrent-ceremony isolation, and
the webauthn confirm throttle. Also corrects two pre-existing webauthn cache
assertions that passed vacuously (toBeDefined on a null miss / wrong key
separator — buildCacheKey uses `#p#`, not `:`).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants