Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

REFACTOR (docs): Plan email two-factor authentication

Rostislav Dugin3e0cd1904f8c
diff --git a/openspec/changes/add-email-two-factor-auth/.openspec.yaml b/openspec/changes/add-email-two-factor-auth/.openspec.yaml
new file mode 100644
index 00000000..cbd245e4
--- /dev/null
+++ b/openspec/changes/add-email-two-factor-auth/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-09-20
diff --git a/openspec/changes/add-email-two-factor-auth/design.md b/openspec/changes/add-email-two-factor-auth/design.md
new file mode 100644
index 00000000..a1b8cac3
--- /dev/null
+++ b/openspec/changes/add-email-two-factor-auth/design.md
@@ -0,0 +1,136 @@
+## Context
+
+See proposal.md - Why for the motivation, and specs/two-factor-authentication/spec.md for the behavior contract. What shapes the approach is which parts already exist and two traps: one in the existing mail sender, one in what the frontend believes about it.
+
+The password-reset flow is the working precedent for everything the code needs to do. `SendResetPasswordCode` (`backend/internal/features/users/services/user_services.go:545-660`) draws six digits from `crypto/rand`, stores them hashed with an expiry in `password_reset_codes` (`backend/internal/features/users/models/password_reset_code.go`), mails them, and validates them through `IsValid()`. Its controller guards the send with the scoped rate limiter, three attempts an hour per address (`backend/internal/features/users/controllers/user_controller.go:449-467`).
+
+Sign-in today verifies the password and immediately issues a ten-year token (`user_services.go:180-200`), and the frontend stores whatever token comes back inside the API call itself (`frontend/src/entity/users/api/userApi.ts:48-60`). The global settings row already carries three authentication switches (`backend/internal/features/users/models/users_settings.go`), rendered on the settings screen at `frontend/src/features/settings/ui/SettingsComponent.tsx`, and the frontend reads a runtime flag `IS_EMAIL_CONFIGURED` (`frontend/src/constants.ts:37-39`) to decide whether to offer password recovery on the sign-in screen (`SignInComponent.tsx:170`).
+
+The trap: `SendEmail` returns `nil` when SMTP is not configured, after logging a warning and sending nothing (`backend/internal/features/email/email.go:32-36`). Anything that treats a `nil` return as "the code is on its way" would hand the user a code-entry screen for a code that was never sent. The fail-closed requirement therefore cannot rest on that return value alone; see the decision below.
+
+A second trap sits next to it. `IS_EMAIL_CONFIGURED` is not the backend's opinion: the container entrypoint sets it from `SMTP_HOST` and `DATABASUS_URL` (`docker/start.sh:138-144`), the backend sets its own flag from `SMTP_HOST` and `SMTP_PORT` (`backend/internal/features/email/di.go:13-22`), and `DATABASUS_URL` only decides whether an invitation message carries a link (`workspaces/services/membership_service.go:371-376`). The two disagree in both directions, so the settings screen cannot use the frontend flag to predict what the gate will do.
+
+Two things the tests need do not exist yet. `MockEmailSender` (`backend/internal/features/users/testing/mocks.go`) records sent messages but cannot report itself as unconfigured, and the audit entries the controller tests produce go into a writer with an empty body (`controllers/e2e_test.go:255-258`). `replace-seeded-admin-with-first-signup` replaces that writer with a recording one; this change adds the configured-state answer to the mail sender mock.
+
+This change is constrained by [`backend/AGENTS.md`](../../../backend/AGENTS.md) for the migration and controller-test conventions, by [`frontend/AGENTS.md`](../../../frontend/AGENTS.md) for the dictionary rule that keeps every user-facing string out of components, and by [`website/AGENTS.md`](../../../website/AGENTS.md) and [`assets/readme/AGENTS.md`](../../../assets/readme/AGENTS.md) for the six-language documentation.
+
+## Goals / Non-Goals
+
+**Goals:**
+
+- Add the second step without changing how a token is minted or how long it lives.
+- Make the failure modes loud: a refusal to enable, an explicit send failure, a console way out.
+- Reuse the reset-code machinery rather than inventing a parallel one.
+
+**Non-Goals:**
+
+- A pluggable second-factor channel. Email is the only one, and the design does not pretend otherwise.
+- Any change to the OAuth callbacks.
+- Restructuring the settings screen beyond adding one row.
+
+## Decisions
+
+### Keep the pending sign-in in a table, not in a token
+
+A new `two_factor_codes` table holds `user_id`, the hashed code, `expires_at`, `is_used`, a count of failed attempts and `created_at` - the reset-code shape plus the counter. The sign-in response carries the row's identifier, and the verify call is keyed on that identifier rather than on the address.
+
+Alternatives rejected:
+
+- **A short-lived pre-authentication token carrying the user id.** No migration, but nowhere to put the attempt counter and nothing to mark as used, so the same token can be replayed until it expires and guesses cannot be bounded without a server-side store anyway. Adding that store is the table, arriving by a longer road.
+- **Reusing `password_reset_codes` with a purpose column.** One table instead of two, but it entangles two flows with different lifetimes, different rate limits and different consequences for a bug. A wrong lookup would let a reset code complete a sign-in.
+- **Keying verification on the email address, the way password reset does.** Then anyone who knows an address can burn another user's five attempts and force them back to the password step. The opaque identifier is only known to whoever supplied the correct password.
+
+### Check that mail is configured explicitly, not through the send result
+
+The sign-in path asks the mail sender whether it is configured before creating a pending sign-in, and treats "not configured" and "send failed" as the same explicit failure. This is what makes the fail-closed requirement real given `email.go:32-36`.
+
+To ask the question, the `EmailSender` interface the users feature depends on (`backend/internal/features/users/interfaces/interfaces.go:13-15`) gains an `IsConfigured() bool` method, implemented by exposing the flag the sender already computes in `backend/internal/features/email/di.go:13-22`. `MockEmailSender` implements it from a field the tests set, so a test can produce an unconfigured sender without touching the environment.
+
+The same answer is what the settings screen needs, so the settings response carries it as a field rather than leaving the screen to guess from `IS_EMAIL_CONFIGURED`. One question, asked in one place, answered by the component that owns it.
+
+Alternatives rejected:
+
+- **Reading the SMTP environment variables in the users feature.** It would duplicate the configured-ness rule that `di.go` already owns, and the two would drift.
+- **Making `SendEmail` return an error when unconfigured.** Cleaner in the abstract, but every existing caller treats the unconfigured case as a silent skip - notifications, invitations, reset codes - and changing that is a behavior change well outside this change's scope.
+- **Fixing `docker/start.sh` so the frontend flag matches the backend rule.** The right end state, but that flag also decides whether the sign-in screen offers password recovery (`SignInComponent.tsx:170`) and whether other email features appear, and the published configuration page states the current rule as documentation (`website/app/(en)/advanced-config/page.tsx:239-248`). Correcting it changes screens this change does not touch and six languages of documentation, so it belongs to its own change; the proposal records it as out of scope.
+
+### Gate the setting on real administrator addresses, using the same rule the API already enforces
+
+Turning the setting on checks every active administrator's address with the same validation the profile update applies, so the settings gate and the profile form cannot disagree about what counts as an address. `UpdateUserInfoRequestDTO` binds `omitempty,email` (`backend/internal/features/users/dto/dto.go:42`), so the rule comes from the binding validator and the gate calls it directly rather than reimplementing a pattern.
+
+Alternatives rejected:
+
+- **Checking only the recorded bootstrap administrator.** Any other administrator could equally be holding an unusable address, and the point of the gate is that no administrator is locked out.
+- **Checking every user, not only administrators.** A member with a broken address loses their own access, which password reset already handles; an administrator with a broken address can leave the instance with nobody able to turn the setting back off through the interface.
+- **A regular expression in the settings service.** Two definitions of "valid address" in one codebase is how the gate and the form end up disagreeing.
+
+### Re-check the account at the verification step
+
+The pending sign-in proves that a password was correct ten minutes ago, not that the account may be let in now. Before issuing the token, the verification step reloads the account and repeats the checks the first step made: the account exists, it is active (`user_services.go:168-178`), and its `PasswordCreationTime` still matches the value recorded when the pending sign-in was created. It also re-reads the setting, so a pending sign-in started while the second factor was on still completes after an operator has switched it off.
+
+The password timestamp matters because `GenerateAccessToken` embeds it (`user_services.go:271-276`) and the change of a password is what invalidates issued tokens. Without the check, an owner who reacts to a stolen password by changing it would leave a ten-minute window in which the thief's pending sign-in still mints a valid token.
+
+Alternative rejected: destroying every pending sign-in for an account whenever it is deactivated or its password changes. It spreads knowledge of the second factor into the deactivation and password paths; checking at the moment of use keeps it in one place and covers cases those paths do not know about.
+
+### Cap issued codes, not only resends
+
+A resend limit alone is bounded per pending sign-in, and nothing stops a caller from starting a new one. `SendResetPasswordCode` already meets the same problem with a count of recent rows for the account (`user_services.go:562-570`), and the second factor reuses that shape: five codes an hour per account, counted over the pending sign-in table, refused before any mail is sent. The resend limits sit inside that ceiling.
+
+This bounds an annoyance rather than an attack, because a code is only issued after a correct password. What it protects is the mailbox of somebody whose password has leaked and the instance's SMTP quota.
+
+Alternative rejected: relying on the sign-in rate limiter (ten attempts a minute per address, `user_controller.go:148`). It is scoped to protect password guessing and is far too generous for sending mail.
+
+### Sweep expired codes instead of keeping them forever
+
+The pending sign-in table is written on every sign-in and read once. Rows that have expired are of no use to anyone, and `password_reset_codes` shows what happens without a sweep: `DeleteExpiredCodes` (`password_reset_repository.go:43-47`) was written for exactly this and is called from nowhere, so the table has only ever grown.
+
+One background task registered with the others (`cmd/main.go:317`) deletes expired rows from both tables on an interval. Adopting the reset codes in the same task costs one call and fixes a table that is already accumulating rows in every deployment.
+
+Alternative rejected: deleting the pending sign-in inline when it expires. Nothing reads an expired row, so nothing would trigger the deletion for the rows that matter - the ones nobody ever comes back for.
+
+### The new endpoints inherit the protections sign-in already has
+
+`POST /users/signin` and `POST /users/send-reset-password-code` both verify Cloudflare Turnstile when it is enabled (`user_controller.go:124-143`, `:427-447`) and both pass through the scoped rate limiter. The verification and resend endpoints do the same: resend sends mail, and verification submits a guess. Leaving them unguarded would make the second step the softest part of the sign-in path.
+
+Alternative rejected: carrying the Turnstile result from the first step over to the second. The pending sign-in identifier already proves the first step happened, but a challenge answered once would then cover every later request that quotes the identifier, which is the thing the challenge is there to prevent.
+
+### Move the audit trail to the point where access is actually granted
+
+The "User signed in" audit entry (`user_services.go:194-198`) moves to the verification step, so the log records a completed sign-in rather than a correct password. A pending sign-in destroyed by five wrong codes gets its own entry, because that is the shape of an attack worth seeing in the log. Both are asserted through the recording audit writer `replace-seeded-admin-with-first-signup` installs in the controller test routers.
+
+Alternative rejected: keeping the existing entry where it is and adding a second one for verification. The log would then show a sign-in for every attempt that never completed, which is exactly the signal the second factor is supposed to make visible.
+
+### One flag, named for what people search for
+
+The console command is `--disable-2fa`, parsed beside `--test-storage`, `--new-password` and `--email` in `backend/cmd/main.go:154-166` and dispatched from the same startup point as the password reset (`main.go:115`), after the database is ready. It flips the global setting off, reports whether anything changed, and exits.
+
+The name carries a digit, which the repository's other flags do not. That is deliberate: it is the term an owner in trouble will type and search for, and the alternative `--disable-two-factor-auth` optimizes for internal consistency at the expense of the person who needs it most.
+
+Alternative rejected: an authenticated endpoint. The caller who needs this cannot sign in, which is the whole reason the command exists.
+
+### The frontend stops trusting every sign-in response to carry a token
+
+`userApi.signIn` currently saves the token and notifies listeners inside the call (`frontend/src/entity/users/api/userApi.ts:48-60`). It changes to return a result the caller discriminates: either a completed sign-in or a pending one carrying its identifier. Only the completed shape stores a token. The verification call stores the token on success.
+
+`AuthPageComponent` gains a fourth authentication mode beside `signIn`, `signUp`, `requestReset` and `resetPassword` (`frontend/src/pages/AuthPageComponent.tsx:21`), holding the pending identifier and the address to display. The code-entry screen follows `ResetPasswordComponent` (`frontend/src/features/users/ui/ResetPasswordComponent.tsx`), which already validates a six-digit code, plus a resend control.
+
+Alternative rejected: a separate route for the code step. The authentication screen is already a mode machine on one route, and a route would have to defend the pending identifier against a reload and a direct visit for no gain.
+
+### Linking the toggle to the SMTP documentation
+
+`WEBSITE_PAGES` (`frontend/src/shared/i18n/websitePages.ts`) gains an entry for the configuration page with the anchor `email-smtp`, which is the heading id the page already publishes (`website/app/(en)/advanced-config/page.tsx:237`). The path `advanced-config` is in `TRANSLATED_PATHS` (`website/app/i18n.ts:45`), so the entry is marked as translated and the link follows the interface language. `websitePages.test.ts` keeps the two lists in sync.
+
+## Risks / Trade-offs
+
+- **Fail-closed plus a dead mail server locks out the whole instance.** → This is the accepted cost of not letting a broken mail server silently downgrade authentication. `--disable-2fa` is the way back in, it ships in the same change, and it is documented on the same page as password recovery precisely because that is where a locked-out owner looks.
+- **Whoever controls the instance's environment can remove the SMTP variables and then disable the second factor from the console.** → Both actions require shell access to the running container, which already grants control of the database and every stored credential. The second factor defends against a stolen password, not against an attacker who is already inside the host.
+- **External identity providers bypass the second factor.** → Recorded in the specs as a deliberate exception rather than left implicit, and the interface copy must not claim coverage it does not have. An instance that wants the second factor to be total does not configure Google or GitHub sign-in.
+- **Mail latency eats the ten-minute window.** → The window is measured from issuance, the resend is available after a minute, and a resend invalidates the previous code so a late-arriving message cannot be used afterwards.
+- **A slow SMTP server makes the sign-in request slow.** The send is synchronous, because the response has to tell the user whether the code is coming. The sender's timeout is five seconds (`backend/internal/features/email/email.go:15`), which bounds it.
+- **The ten-year token is untouched.** → Stated in the proposal's out-of-scope list rather than glossed over: a token stolen after a successful two-step sign-in is as durable as before.
+- **The gate is checked when the setting is turned on, not afterwards.** -> Nothing re-checks it when an administrator is later appointed or SMTP is removed from the environment. An appointed administrator holds a validated address by construction, and a mail server that disappears is the fail-closed case `--disable-2fa` answers. Re-validating on every sign-in would make each sign-in depend on scanning the administrator list for no gain over failing closed.
+- **The change edits documentation created by `replace-seeded-admin-with-first-signup`.** → The task list applies it after that change is in place, and the tasks say which existing section each edit extends.
+
+## Migration Plan
+
+One migration, with both directions as the repository requires: the up step adds the settings column with a `false` default and creates the pending-code table, the down step drops both. Since the default is off, deploying the change alters nothing about how anyone signs in until an administrator turns it on. Rolling the binary back with the setting off is uneventful; rolling it back with the setting on leaves a column the old code ignores, so sign-in silently reverts to one factor - worth stating in the completion notes, because it means a rollback is also an unannounced security downgrade.
diff --git a/openspec/changes/add-email-two-factor-auth/proposal.md b/openspec/changes/add-email-two-factor-auth/proposal.md
new file mode 100644
index 00000000..336181a9
--- /dev/null
+++ b/openspec/changes/add-email-two-factor-auth/proposal.md
@@ -0,0 +1,61 @@
+## Why
+
+Databasus signs a user in with an email address and a password, and hands back a token that stays valid for ten years (`backend/internal/features/users/services/user_services.go:269`). A leaked or guessed password is therefore full, durable access to every database credential, storage key and backup the instance manages. For a tool whose whole purpose is holding the keys to someone's production data, a single factor is thin.
+
+The pieces for an email second factor are already in the codebase and proven by the password-reset flow: six-digit codes from `crypto/rand`, hashed and single-use with an expiry (`user_services.go:572-607`), an SMTP sender that reports whether it is configured (`backend/internal/features/email/di.go`), and a scoped rate limiter (`user_controller.go:449`). What is missing is the second step at sign-in and an administrator switch to turn it on.
+
+## Depends on
+
+`replace-seeded-admin-with-first-signup`. That change makes the administrator of a new instance the first account registered on it, so it holds a real address from the start, records which account that is, and lets an upgraded instance move off the placeholder login `admin`. Without it, the most privileged account on a fresh install has that literal string in its address column and no mailbox, so a second factor could only be enforced by locking that account out.
+
+## Governing docs
+
+This change answers to [`AGENTS.md`](../../../AGENTS.md) at the repo root, [`backend/AGENTS.md`](../../../backend/AGENTS.md), [`frontend/AGENTS.md`](../../../frontend/AGENTS.md), [`website/AGENTS.md`](../../../website/AGENTS.md) and [`assets/readme/AGENTS.md`](../../../assets/readme/AGENTS.md). No verification agent code changes, so [`agent/verification/AGENTS.md`](../../../agent/verification/AGENTS.md) does not apply.
+
+## What Changes
+
+- Add a global setting, off by default, that requires a second factor for password sign-in. It sits on the existing settings screen, below the other authentication settings, and only an administrator can change it.
+- Refuse to turn the setting on unless the instance can actually deliver the codes: SMTP must be configured, and every active administrator must hold a real email address. The refusal names what is missing, and the settings screen links to the SMTP section of the published configuration documentation.
+- Let the settings screen ask the backend whether mail is configured, instead of reading the build-time flag `IS_EMAIL_CONFIGURED`. The flag is generated from `SMTP_HOST` and `DATABASUS_URL` (`docker/start.sh:138-144`), while the backend treats mail as configured when `SMTP_HOST` and `SMTP_PORT` are set (`backend/internal/features/email/di.go:13-22`). Those two answers disagree in both directions, so a toggle driven by the flag would be greyed out on an instance the backend would accept, or offered on one it refuses.
+- **BREAKING** change to the sign-in contract: `POST /users/signin` no longer always returns a token. When the setting is on and the password is correct, it returns a challenge identifier instead, and the token comes from a second call that carries the identifier and the emailed code. Callers that assumed a token in every successful response must handle both shapes. No compatibility shim is kept.
+- Send a six-digit code to the account's address after the password is verified, never before, so a wrong password neither sends mail nor reveals whether the account exists.
+- Expire a code ten minutes after it is issued, burn it after five wrong attempts, and accept it once. Offer a resend, limited to one per minute and five per hour for the same address.
+- Cap issued codes at five per hour per address, counting every code the account receives rather than only the resends. Without that cap, repeating the first step with a correct password mints a fresh pending sign-in each time, and the sign-in limiter of ten attempts a minute (`backend/internal/features/users/controllers/user_controller.go:148`) leaves room for hundreds of messages an hour into one mailbox.
+- Check at the verification step that the account may still be let in: it exists, it is still active, its password has not changed since the pending sign-in was created, and the second factor is still on. A pending sign-in otherwise survives a deactivation for ten minutes and then issues a token.
+- Guard the verification and resend endpoints with the same Cloudflare Turnstile check that already guards password sign-in and the reset-code request (`user_controller.go:124-143`, `:427-447`), since the resend sends mail.
+- Delete pending sign-in codes once they expire, through a background sweep. The same sweep takes over `DeleteExpiredCodes` (`backend/internal/features/users/repositories/password_reset_repository.go:43-47`), which exists for password reset codes and is called from nowhere, so that table has been growing without bound since it was introduced.
+- **Fail closed**: if the code cannot be sent, the sign-in fails with an explicit "could not send the code" response rather than letting the caller in. This means a broken SMTP server locks everybody out, which is why the next item exists.
+- Fix the settings audit trail the new switch joins. `UpdateSettings` builds its message after assigning the new value (`backend/internal/features/users/services/settings_service.go:42-64`), so both existing switches log `false -> false` instead of the transition, and the third switch logs nothing at all (`:66-68`). Copying that shape for a security switch would hide who turned the second factor on and off, so the existing messages are corrected and the missing one added.
+- Add a console escape hatch: `docker exec -it databasus ./main --disable-2fa` turns the global setting off, so an owner whose mail server has died can get back in without editing the database by hand.
+- Leave sign-in through Google and GitHub unchanged. Those providers run their own multi-factor checks, and adding a second email code on top of them buys little. This is a deliberate gap and the specs record it as one.
+- Document the feature where the product's security story already lives: the root `README.md` security section, the website's security page, and the security answer of the website's home-page FAQ. Document `--disable-2fa` on the website password page and in the FAQ entry that `replace-seeded-admin-with-first-signup` introduces. Each of those exists in six languages and is updated in all of them.
+
+### Out of scope
+
+- Authenticator apps, hardware keys and recovery codes. Email is the only channel here, and it is the only one the instance already has.
+- Per-user opt-in. The setting is global, matching the other authentication settings on the same screen.
+- Trusting a device so the code is asked for less often. Every password sign-in asks.
+- Shortening the ten-year token lifetime, or revoking issued tokens. A second factor guards the door; the lifetime of what is handed out on the way through is a separate problem and this change does not touch it.
+- Requiring a code during sign-up, including sign-up from an invitation. Registration issues a token directly (`backend/internal/features/users/controllers/user_controller.go:95-103`), and for an ordinary registration that token opens a brand-new member account with no access to anything. The one registration that creates an administrator is the first one on an empty instance, where the second factor cannot be on, because no administrator has existed to turn it on. The invitation branch is weaker than that: it sets a password on a row an administrator created earlier (`user_services.go:68-101`), so whoever knows an invited address can complete that sign-up without a code and inherit whatever the invitation carried. That is a hole in the invitation flow rather than in the second factor - it needs no password today either - and closing it means giving invitations a secret, which is its own change. Recorded here as an accepted gap so the change that gives invitations a token knows the second factor depends on it.
+- Reconciling the three definitions of "email is configured". The backend (`email/di.go:13-22`), the container entrypoint that generates the frontend flag (`docker/start.sh:138-144`) and the published configuration page (`website/app/(en)/advanced-config/page.tsx:239-248`) each state a different rule, and `DATABASUS_URL` only ever adds a link to an invitation message (`workspaces/services/membership_service.go:371-376`). This change stops the second factor from depending on the disagreement by asking the backend, and leaves the disagreement itself, which also drives the sign-in screen's forgot-password link, to a change that can walk every consumer.
+- Requiring a code on top of the password-reset flow. That flow already proves control of the mailbox, which is the same evidence the second factor asks for.
+- Verifying that an administrator's stored address receives mail before the setting is switched on. The setting checks that the address is a real address and that SMTP is configured; delivery is proven the first time a code is sent.
+
+## Capabilities
+
+### New Capabilities
+
+- `two-factor-authentication`: the global second-factor setting, its preconditions, the two-step sign-in it produces, and the console command that disables it.
+
+### Modified Capabilities
+
+None. `root-admin-account` is introduced by `replace-seeded-admin-with-first-signup` and reaches `openspec/specs/` only when that change is archived, so there is nothing here to delta against. The behavior that touches it - the bootstrap administrator being subject to the second factor like any other account, and the console escape hatch when mail delivery dies - is second-factor behavior and belongs to the new capability.
+
+## Impact
+
+- **Database**: a new column on the global settings row, and a new table holding pending sign-in codes.
+- **Backend**: the sign-in service and controller, the settings service, its validation and its response, the email sender's configured-state check, the rate limiter, the background task list, and a new command-line flag in `backend/cmd/main.go`.
+- **Test support**: `MockEmailSender` (`backend/internal/features/users/testing/mocks.go`) gains the configured-state answer with a settable value, and the recording audit-log writer that `replace-seeded-admin-with-first-signup` adds to `users/testing` is what the moved sign-in entry is asserted against.
+- **API**: `POST /users/signin` gains a second response shape; two new endpoints verify a code and request a resend. The generated API documentation changes with them.
+- **Frontend**: the authentication screen gains a code-entry step between the sign-in form and the application, the settings screen gains the toggle, the client stops storing a token from every sign-in response, and six interface dictionaries gain the new copy. The table of linked website pages gains the configuration page so the toggle can link to its SMTP section.
+- **Docs**: root `README.md` and its five translations; the website's security page, its home-page FAQ in both its visible and structured-data form, its password page, and the five translated copies of each.
diff --git a/openspec/changes/add-email-two-factor-auth/specs/two-factor-authentication/spec.md b/openspec/changes/add-email-two-factor-auth/specs/two-factor-authentication/spec.md
new file mode 100644
index 00000000..d71dbd1d
--- /dev/null
+++ b/openspec/changes/add-email-two-factor-auth/specs/two-factor-authentication/spec.md
@@ -0,0 +1,204 @@
+## Purpose
+
+Lets the owner of an instance require a second, emailed factor before a password sign-in succeeds, with the preconditions that keep the switch from locking everyone out and a console path back when mail delivery stops working.
+
+## ADDED Requirements
+
+### Requirement: An administrator controls the second factor for the whole instance
+
+The instance SHALL offer a single global setting that requires a second factor for password sign-in. It SHALL be off until an administrator turns it on, SHALL apply to every account on the instance once on, and SHALL be changeable only by an administrator.
+
+#### Scenario: Default state
+
+- **WHEN** an instance is deployed and claimed for the first time
+- **THEN** the second factor is off and sign-in works with an address and a password alone
+
+#### Scenario: A non-administrator tries to change it
+
+- **WHEN** a member submits a settings update that turns the second factor on
+- **THEN** the update is refused and the setting is unchanged
+
+### Requirement: The second factor cannot be turned on unless the instance can deliver codes
+
+Turning the setting on SHALL be refused unless both conditions hold: the instance has a configured mail server, and every active administrator holds a syntactically valid email address. The refusal SHALL name which condition failed and, when an administrator address is the problem, which account it is.
+
+The interface offering the setting SHALL explain the mail server requirement and link to the published documentation for configuring it. It SHALL decide whether the mail server is configured from the instance's own answer, so that the interface and the refusal never disagree about the same instance.
+
+#### Scenario: No mail server
+
+- **WHEN** an administrator turns the setting on while the instance has no mail server configured
+- **THEN** the change is refused with a message naming the missing mail server
+- **AND** the interface offers a link to the documentation for configuring it
+
+#### Scenario: An administrator has no usable address
+
+- **WHEN** an administrator turns the setting on while another active administrator still holds a value that is not an email address, such as the login `admin` an instance created before the administrator account was reworked
+- **THEN** the change is refused, the message names that account, and the setting stays off
+
+#### Scenario: Both conditions satisfied
+
+- **WHEN** an administrator turns the setting on with a mail server configured and every active administrator holding a real address
+- **THEN** the change is accepted and takes effect for the next sign-in
+
+#### Scenario: The interface and the instance agree
+
+- **WHEN** an administrator opens the settings screen
+- **THEN** whether the setting is offered or explained as unavailable follows the same judgement about the mail server that a refusal would apply
+
+### Requirement: Password sign-in asks for an emailed code when the second factor is on
+
+With the setting on, a correct address and password SHALL NOT by itself produce an access token. The instance SHALL instead send a six-digit numeric code to the account's address and answer with an identifier for that pending sign-in. Presenting that identifier together with the matching code SHALL produce the access token.
+
+The code SHALL be generated from a cryptographically secure source, SHALL be stored so that reading the stored form does not reveal it, and SHALL be usable once.
+
+This applies to every account on the instance, including the recorded bootstrap administrator.
+
+#### Scenario: Completing a two-step sign-in
+
+- **WHEN** a user submits a correct address and password on an instance with the second factor on
+- **THEN** no access token is returned, a six-digit code arrives at that address, and the response identifies the pending sign-in
+- **AND** submitting that identifier with the received code returns an access token
+
+#### Scenario: The bootstrap administrator signs in
+
+- **WHEN** the recorded bootstrap administrator signs in with a correct password
+- **THEN** a code is required exactly as for any other account
+
+#### Scenario: Reusing a code
+
+- **WHEN** a user submits a code that has already completed a sign-in
+- **THEN** the attempt is rejected and no second token is issued
+
+### Requirement: A code is sent only after the password is verified
+
+The instance SHALL verify the password before generating or sending any code. A sign-in attempt with an unknown address or a wrong password SHALL send no mail, SHALL create no pending sign-in, and SHALL answer exactly as it does with the second factor off, so the response does not disclose whether the address exists or whether the second factor is on.
+
+#### Scenario: Wrong password
+
+- **WHEN** someone submits a known address with an incorrect password
+- **THEN** no mail is sent and the response is the same one the instance gives with the second factor off
+
+#### Scenario: Unknown address
+
+- **WHEN** someone submits an address that belongs to no account
+- **THEN** no mail is sent and no pending sign-in exists
+
+### Requirement: A pending sign-in expires, tolerates few wrong guesses, and can be resent
+
+A pending sign-in SHALL expire ten minutes after its code is issued. It SHALL be destroyed after five incorrect code submissions, after which the user starts again from the password step. An expired, destroyed or already-used pending sign-in SHALL never produce a token.
+
+The user SHALL be able to request a new code for a pending sign-in. Resends SHALL be limited to one per minute and five per hour for the same address; a request beyond those limits SHALL be refused without sending mail.
+
+Codes SHALL be limited to five per hour for the same account however they were requested, so that repeating the password step cannot send more mail than resending would. A request beyond that limit SHALL be refused without sending mail and without leaving a usable pending sign-in.
+
+A pending sign-in SHALL NOT be retained after it expires.
+
+#### Scenario: Code expires
+
+- **WHEN** a user submits a correct code eleven minutes after it was issued
+- **THEN** the attempt is rejected and no token is issued
+
+#### Scenario: Guessing the code
+
+- **WHEN** someone submits five incorrect codes for the same pending sign-in
+- **THEN** the pending sign-in is destroyed, and the correct code submitted afterwards is also rejected
+
+#### Scenario: Requesting another code
+
+- **WHEN** a user whose code has not arrived requests a resend more than a minute after the last one
+- **THEN** a new code is sent and the previous one no longer works
+
+#### Scenario: Resending too often
+
+- **WHEN** a user requests a second resend within the same minute
+- **THEN** the request is refused and no mail is sent
+
+#### Scenario: Restarting the password step to send more mail
+
+- **WHEN** someone who knows an account's password completes the password step repeatedly until that account has received five codes within an hour, then completes it once more
+- **THEN** no further mail is sent and no usable pending sign-in is produced
+
+#### Scenario: Expired pending sign-ins are not kept
+
+- **WHEN** pending sign-ins have expired without being used
+- **THEN** the instance no longer holds them
+
+### Requirement: The verification step re-checks what the password step checked
+
+Before issuing an access token, the instance SHALL confirm that the account behind a pending sign-in may still be let in: it still exists, it is still active, and its password has not changed since the pending sign-in was created. A pending sign-in that fails any of these SHALL be refused, whatever code it carries.
+
+A pending sign-in created while the second factor was on SHALL still be completable after the setting has been switched off.
+
+#### Scenario: The account is deactivated while the code is in flight
+
+- **WHEN** an administrator deactivates an account after its password step succeeded but before its code is submitted
+- **THEN** submitting the correct code is refused and no access token is issued
+
+#### Scenario: The password changes while the code is in flight
+
+- **WHEN** the account's password is changed after its password step succeeded but before its code is submitted
+- **THEN** submitting the correct code is refused and no access token is issued
+
+#### Scenario: The setting is switched off while the code is in flight
+
+- **WHEN** an operator switches the second factor off after a user's password step succeeded
+- **THEN** that user can still complete the sign-in with the code they received
+
+### Requirement: The second step is protected like the first
+
+The endpoints that verify a code and request a resend SHALL carry the same automated-abuse protection the instance applies to password sign-in and to the password-reset code request, including its human-verification challenge when the instance has one configured.
+
+#### Scenario: Human verification is configured
+
+- **WHEN** an instance with human verification configured receives a code verification or a resend request without a valid challenge answer
+- **THEN** the request is refused before any code is checked and before any mail is sent
+
+### Requirement: Sign-in fails closed when the code cannot be sent
+
+If the instance cannot send the code, the sign-in SHALL fail with a response that says the code could not be sent, and SHALL NOT issue an access token. An instance whose mail server has stopped working therefore admits nobody through password sign-in while the setting is on.
+
+#### Scenario: Mail server unreachable
+
+- **WHEN** a user submits a correct address and password while the mail server refuses the message
+- **THEN** the response states that the code could not be sent and carries no access token
+
+### Requirement: Sign-in through an external identity provider is not covered by the second factor
+
+Sign-in through Google or GitHub SHALL continue to issue an access token directly, with no emailed code, whether or not the setting is on. This is a deliberate exception: those providers run their own multi-factor checks, and an instance that allows them accepts that the second factor guards only password sign-in.
+
+Any interface or documentation that describes the second factor SHALL NOT claim it covers external identity providers.
+
+#### Scenario: Signing in with Google while the second factor is on
+
+- **WHEN** a user completes Google sign-in on an instance with the second factor on
+- **THEN** an access token is issued without an emailed code
+
+### Requirement: An operator can switch the second factor off from the host
+
+An operator with shell access to the running instance SHALL be able to turn the global setting off with a single command, so that an instance whose mail server has died can be entered again without editing its database by hand. The command SHALL report what it changed, and SHALL succeed without complaint when the setting is already off.
+
+The command SHALL be available only to a caller who can already execute commands inside the running instance, the same trust level the password-reset and administrator-listing commands require.
+
+#### Scenario: Recovering from a dead mail server
+
+- **WHEN** an operator who cannot receive codes runs the disable command on the host
+- **THEN** the setting is off and the next password sign-in completes without a code
+
+#### Scenario: Running it twice
+
+- **WHEN** the operator runs the disable command on an instance where the setting is already off
+- **THEN** the command reports no change and exits successfully
+
+### Requirement: The second factor is documented as part of the product's security story
+
+The published documentation SHALL state that the instance can require an emailed second factor at sign-in, in the security material of both the repository readme and the website - the website's dedicated security page as well as the security question answered on its home page - in every language each ships. The console command that switches the second factor off SHALL be documented beside the other recovery commands, so an owner locked out by a broken mail server finds it where they already look for password recovery.
+
+#### Scenario: A reader looks up what protects sign-in
+
+- **WHEN** a reader consults the published security material in any of the six languages
+- **THEN** it states that sign-in can require an emailed code, and does not claim that this covers sign-in through an external identity provider
+
+#### Scenario: An owner locked out by a broken mail server
+
+- **WHEN** that owner reads the published password and recovery documentation
+- **THEN** it names the command that switches the second factor off and shows how to run it
diff --git a/openspec/changes/add-email-two-factor-auth/tasks.md b/openspec/changes/add-email-two-factor-auth/tasks.md
new file mode 100644
index 00000000..7cb687c4
--- /dev/null
+++ b/openspec/changes/add-email-two-factor-auth/tasks.md
@@ -0,0 +1,72 @@
+This change extends behavior and documentation introduced by `replace-seeded-admin-with-first-signup`. Apply it after that change is in the working tree, or the documentation tasks in sections 7 and 8 have nothing to extend and the recording audit-log writer the tests below assert against does not exist.
+
+## 1. Storage and settings
+
+- [ ] 1.1 Create the migration with `make migration-create` under `backend/`, adding the second-factor flag to the global settings row with a `false` default and creating the pending sign-in code table with its user reference, hashed code, expiry, used flag, failed-attempt count and creation time; follow the migration rules in `backend/AGENTS.md` (timestamps as `TIMESTAMPTZ`, the foreign key and the lookup index on the user reference as separate statements), and write the down step that drops the table and the column. Verify with `make migration-up` then `make migration-down` on a scratch database.
+- [ ] 1.2 Add the settings field to the global settings model and carry it through the settings read and update paths; while adding the audit message for it, fix the two existing ones in `UpdateSettings` (`backend/internal/features/users/services/settings_service.go:42-64`), which format the value after assigning it and therefore report `false -> false`, and add the message `IsMemberAllowedToCreateWorkspaces` never writes (`:66-68`). Verify with a controller test that reads the setting, turns it on and reads back the new value, and with tests that assert through the recording audit writer that each of the four switches reports its old and new value once.
+- [ ] 1.3 Add `IsConfigured() bool` to the mail sender and to the `EmailSender` interface the users feature depends on (`backend/internal/features/users/interfaces/interfaces.go:13-15`), exposing the flag already computed in `backend/internal/features/email/di.go:13-22`, and implement it in `MockEmailSender` (`backend/internal/features/users/testing/mocks.go`) from a field a test can set; verify with `make test` in `backend/` that the existing email and users suites still pass.
+- [ ] 1.4 Carry the mail sender's own answer into the settings response so the settings screen stops predicting the gate from the build-time flag `IS_EMAIL_CONFIGURED`, whose rule differs (`docker/start.sh:138-144`); verify with a controller test that reads the settings with a configured and with an unconfigured mail sender and sees the field follow the sender.
+- [ ] 1.5 Gate turning the setting on: refuse when mail is not configured, and refuse when any active administrator's address fails the same validation the profile update binds; verify with controller tests covering both refusals, the account named in the administrator refusal, the accepted case, and that a refusal leaves the stored setting off.
+- [ ] 1.6 Run `make lint` in `backend/`.
+
+## 2. Two-step sign-in
+
+- [ ] 2.1 Add the pending sign-in repository and the code issuance path: six digits from a cryptographically secure source, stored hashed, expiring ten minutes after issuance; verify with a test that a stored row never contains the plain code and that an expired row is rejected as invalid.
+- [ ] 2.2 Change `POST /users/signin` so that, with the setting on and the password correct, it issues a code and returns the pending sign-in identifier instead of a token; verify with a controller test asserting the response carries no token, a code row exists, and the mock sender received one message addressed to the account.
+- [ ] 2.3 Make the send failure explicit: check that mail is configured before creating the pending sign-in, and fail the request with a "could not send the code" response when either the check or the send fails, leaving no usable pending sign-in behind; verify with a controller test using a sender that reports itself unconfigured and another that returns an error, asserting in both cases that no pending sign-in row remains usable.
+- [ ] 2.4 Add the verification endpoint that exchanges the pending identifier and the code for a token, marking the code used; verify with controller tests covering success, a reused code, an expired code, a code belonging to a different pending sign-in, and an identifier that never existed.
+- [ ] 2.5 Enforce five wrong attempts per pending sign-in, after which it is destroyed and the correct code no longer works; verify with a controller test that submits five wrong codes and then the right one.
+- [ ] 2.6 Add the resend endpoint, invalidating the previous code and limited through the existing scoped rate limiter to one per minute and five per hour for the same address; verify with a controller test that a second immediate resend is refused and that the previous code stops working after a successful resend.
+- [ ] 2.7 Cap issued codes at five an hour per account, counted over the pending sign-in rows the way `SendResetPasswordCode` counts reset codes (`user_services.go:562-570`), and refuse beyond that before any mail is sent; verify with a controller test that completes the password step six times and asserts the sixth sends no mail and returns no usable pending sign-in.
+- [ ] 2.8 Re-check the account at the verification step: it exists, it is still active, its password creation time still matches the one recorded with the pending sign-in, and the setting being switched off in the meantime does not block the user; verify with controller tests for a deactivated account, a password changed between the two steps, and a sign-in completed after `--disable-2fa` ran.
+- [ ] 2.9 Apply to the verification and resend endpoints the Cloudflare Turnstile check and the scoped rate limiting that sign-in and the reset-code request already carry (`user_controller.go:124-143`, `:427-467`); verify with controller tests that, with the challenge enabled, both endpoints refuse a request without a valid answer before checking any code or sending any mail.
+- [ ] 2.10 Confirm the paths that must not change: a wrong password and an unknown address send no mail and answer as they do with the setting off, sign-in with the setting off still returns a token in one step, and the Google and GitHub callbacks still issue a token directly with the setting on; verify with controller tests for each.
+- [ ] 2.11 Move the "User signed in" audit entry to the verification step and add an entry for a pending sign-in destroyed by wrong codes; verify with controller tests that assert through the recording audit writer that a completed sign-in writes one entry at the verification step and none at the password step, and that an abandoned one writes the destruction entry.
+- [ ] 2.12 Add a background task beside the others in `runBackgroundTasks` (`backend/cmd/main.go:317`) that deletes expired pending sign-in codes and calls `DeleteExpiredCodes` (`backend/internal/features/users/repositories/password_reset_repository.go:43-47`), which no caller has ever invoked; verify with tests that seed an expired and a live row in each table and confirm one sweep removes only the expired ones.
+- [ ] 2.13 Regenerate the API documentation with `make swagger`, confirm the sign-in endpoint documents both response shapes, and run `make test` and `make lint` in `backend/`.
+
+## 3. Console escape hatch
+
+- [ ] 3.1 Add the `--disable-2fa` flag to `parseCommandLineOptions` (`backend/cmd/main.go:154`) and dispatch it from the same startup point as the password reset (`main.go:115`), turning the setting off, reporting whether anything changed and exiting; verify by running the binary against a database with the setting on and confirming the next password sign-in completes without a code.
+- [ ] 3.2 Add tests covering the command on an instance where the setting is already off, expecting a success exit and a "no change" report, and on one where it is on, expecting the stored setting to be off afterwards; verify with `make test` in `backend/`.
+
+## 4. Settings screen
+
+- [ ] 4.1 Add the toggle to `frontend/src/features/settings/ui/SettingsComponent.tsx` below the existing authentication switches, disabled with an explanation when the settings response reports no mail server, and carrying a link to the configuration documentation's SMTP section; verify in the running application with mail configured and with it unconfigured.
+- [ ] 4.2 Add the configuration page to `WEBSITE_PAGES` (`frontend/src/shared/i18n/websitePages.ts`) with the `email-smtp` anchor, marked as translated, and extend `websitePages.test.ts`; verify with `pnpm test` in `frontend/`.
+- [ ] 4.3 Surface the backend's refusal on the settings screen so an administrator sees which condition failed; verify by turning the setting on while another administrator holds the bootstrap login and reading the message.
+
+## 5. Code-entry step
+
+- [ ] 5.1 Change the sign-in client call so it returns either a completed sign-in or a pending one and stores a token only for the completed shape (`frontend/src/entity/users/api/userApi.ts:48-60`), and add the verification and resend calls; put the decision between the two shapes in a plain function beside the API module and cover it with a unit test for both shapes and for a response carrying neither, following the module-level test style already used under `frontend/src/entity`. Verify with `pnpm test` in `frontend/`.
+- [ ] 5.2 Add the code-entry screen as a fourth mode in `frontend/src/pages/AuthPageComponent.tsx`, following `ResetPasswordComponent` for the six-digit input, showing which address the code went to, and offering a resend; verify by completing a two-step sign-in in the running application.
+- [ ] 5.3 Handle the failure paths in the interface: a wrong code, an expired or destroyed pending sign-in that sends the user back to the password step, a refused resend, and the "could not send the code" response; verify each by driving the corresponding backend condition.
+- [ ] 5.4 Add the new copy to all six dictionaries under `frontend/src/shared/i18n/locales/`, with no user-facing string left in a component; verify with `pnpm test` in `frontend/` that the dictionary parity suite (`dictionaries.test.ts`) keeps the six files in step.
+- [ ] 5.5 Confirm sign-in with the setting off behaves exactly as before, including sign-up, which still receives a token directly; verify by signing in and registering on an instance with the setting off.
+- [ ] 5.6 Run `pnpm lint`, `pnpm format`, `pnpm test` and `pnpm build` in `frontend/`.
+
+## 6. English documentation
+
+- [ ] 6.1 Add the second factor to the security feature list in the root `README.md` (the "Enterprise-grade security" section at line 91), as one line naming email delivery as the channel; verify the claim matches what the specs say, including that it does not cover external identity providers.
+- [ ] 6.2 Document `--disable-2fa` in the root `README.md` recovery section, beside the password reset and administrator listing commands that `replace-seeded-admin-with-first-signup` documents there; verify the command line is copy-pasteable against a running container.
+- [ ] 6.3 Add the second factor to the website's security page (`website/app/(en)/security/page.tsx`), stating what it covers and that external identity providers are outside it, and pointing at the recovery command; verify with `npm run build` in `website/` and by loading the page.
+- [ ] 6.4 Add one line about the second factor to the security answer of the website's home-page FAQ (`website/app/(en)/page.tsx`), in both the visible answer at line 1295 and the structured-data copy at line 181; verify both copies carry the same wording and `npm run build` passes in `website/`.
+- [ ] 6.5 Extend the website password page (`website/app/(en)/password/page.tsx`) with the disable command, and extend the "I forgot my admin email or password" FAQ entry from `replace-seeded-admin-with-first-signup` to mention it; verify with `npm run build` in `website/`.
+- [ ] 6.6 Run `npm run lint` in `website/`.
+
+## 7. Translations
+
+- [ ] 7.1 Mirror the website changes into Russian: the security page section in `website/app/[lang]/security/content/ru.tsx`, the FAQ security answer and the recovery FAQ entry in the Russian home-page content, and the password page section in `website/app/[lang]/password/content/ru.tsx`; verify with `npm run build` in `website/` and by reading the pages under `/ru/`.
+- [ ] 7.2 Repeat for Spanish (`es`).
+- [ ] 7.3 Repeat for Portuguese (`pt`).
+- [ ] 7.4 Repeat for Chinese (`zh`).
+- [ ] 7.5 Repeat for French (`fr`).
+- [ ] 7.6 Mirror the README changes into `assets/readme/README.{ru,es,pt,zh,fr}.md` following `assets/readme/AGENTS.md`; verify each file keeps the command lines byte-identical to the English ones.
+
+## 8. Verification and review
+
+- [ ] 8.1 Run `make test` and `make lint` in `backend/`, `pnpm lint`, `pnpm format`, `pnpm test` and `pnpm build` in `frontend/`, and `npm run lint` and `npm run build` in `website/`; fix every failure.
+- [ ] 8.2 Confirm every endpoint this change adds or changes has a controller test for its success path and for each refusal the specs name, and that no behavior in `specs/two-factor-authentication/spec.md` is left with a scenario nothing exercises.
+- [ ] 8.3 Walk the whole feature on a running instance: turn the setting on with mail configured, sign in in two steps, exhaust the attempts, resend a code, break the mail configuration and confirm sign-in fails closed, then recover with `--disable-2fa`.
+- [ ] 8.4 Record in the change's completion notes that rolling the binary back with the setting on silently returns the instance to one factor, as described in design.md - Migration Plan.
+- [ ] 8.5 Complete the mandatory compliance review for the finished diff and resolve every CHANGES REQUIRED finding.