PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
REFACTOR (docs): Archive the email two-factor change and add its spec
Rostislav Dugin3dd1734f2e40
diff --git a/openspec/changes/add-email-two-factor-auth/design.md b/openspec/changes/add-email-two-factor-auth/design.mddeleted file mode 100644index a1b8cac3..00000000--- a/openspec/changes/add-email-two-factor-auth/design.md+++ /dev/null@@ -1,136 +0,0 @@-## 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.mddeleted file mode 100644index 336181a9..00000000--- a/openspec/changes/add-email-two-factor-auth/proposal.md+++ /dev/null@@ -1,61 +0,0 @@-## 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/tasks.md b/openspec/changes/add-email-two-factor-auth/tasks.mddeleted file mode 100644index 7cb687c4..00000000--- a/openspec/changes/add-email-two-factor-auth/tasks.md+++ /dev/null@@ -1,72 +0,0 @@-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.diff --git a/openspec/changes/add-email-two-factor-auth/.openspec.yaml b/openspec/changes/archive/2026-09-21-add-email-two-factor-auth/.openspec.yamlsimilarity index 100%rename from openspec/changes/add-email-two-factor-auth/.openspec.yamlrename to openspec/changes/archive/2026-09-21-add-email-two-factor-auth/.openspec.yamldiff --git a/openspec/changes/archive/2026-09-21-add-email-two-factor-auth/design.md b/openspec/changes/archive/2026-09-21-add-email-two-factor-auth/design.mdnew file mode 100644index 00000000..dea4a2c7--- /dev/null+++ b/openspec/changes/archive/2026-09-21-add-email-two-factor-auth/design.md@@ -0,0 +1,188 @@+## 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:497-610`) 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:436-446`).++Sign-in today verifies the password and immediately issues a ten-year token (`user_services.go:136-198`), and the frontend stores whatever token comes back inside the API call itself (`frontend/src/entity/users/api/userApi.ts:46-58`). 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:172`).++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:144-149`), 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.++One thing the tests need does not exist yet. `MockEmailSender` (`backend/internal/features/users/testing/mocks.go:5-33`) records sent messages but cannot report itself as unconfigured, so this change adds the configured-state answer to it. The recording audit-log writer the assertions need arrived with `replace-seeded-admin-with-first-signup` and is already installed by the controller tests (`backend/internal/features/users/testing/audit_log_utils.go:12-77`, called from `controllers/e2e_test.go:181`). One detail of the mock shapes the send-failure tests: it appends the message before returning the failure `ShouldFail` asks for (`mocks.go:23-32`), so a failed send is proven by the absence of a usable pending sign-in rather than by an empty `SentEmails`.++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, the account's password creation time, `expires_at`, `is_used`, a count of failed attempts and `created_at` - the reset-code shape plus the counter and the timestamp the verification step re-checks. One row is one issued code, so the response that issues a code carries that row's identifier, and the verify call is keyed on the identifier rather than on the address.++The rows are also the evidence the hourly cap counts, which is why they outlive the code they carry. A row is usable for ten minutes and kept for an hour; the retention decision below explains why the two numbers differ.++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:172`) 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.++### The settings endpoints get their own request and response types++`GET` and `PUT /users/settings` currently send and receive the persisted model itself (`backend/internal/features/users/controllers/settings_controller.go:19-25`, `backend/internal/features/users/models/users_settings.go`), and the repository saves the object the service returns. The answer about the mail server is derived, not stored, so putting it on that model would let a client send it back and would ask the persistence layer to ignore a field it can see. A `SettingsResponseDTO` carries the four switches plus `isEmailConfigured`; an `UpdateSettingsRequestDTO` carries the four switches alone. The frontend already models settings without the stored identifier (`frontend/src/entity/users/model/UsersSettings.ts`), so the response it receives stays the shape it expects, with two fields added.++`GET` stays open to any authenticated caller, because members read `isMemberAllowedToCreateWorkspaces` from it. That makes the new switch and the mail-server answer readable by members, which is acceptable: a member learns whether the second factor is on by signing in.++Alternatives rejected:++- **Adding the derived field to the model with `gorm:"-"`.** It keeps one type for three jobs and relies on every future writer noticing the tag. The request would still accept a field the server computes.+- **A separate endpoint answering only whether mail is configured.** Two calls where the settings screen already makes one, and a second place for the same question to be answered differently.++### 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:40-43`), 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:162-166`), 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:265-273`) 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:513-522`), and the second factor reuses that shape: five codes an hour per account, counted over the pending sign-in rows the instance still holds, refused before any mail is sent.++That count is the only hourly ceiling in the feature. The resend keeps a throttle of one a minute and no hourly number of its own, because a resend issues a code like every other path and is already counted. Two numbers for one quantity would eventually disagree, and the one a reader checks would not be the one enforced.++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. Two consequences follow, both settled below: the count is only as good as how long the rows survive, and an ordinary user must not spend the allowance by reloading a page.++Alternatives rejected:++- **Relying on the sign-in rate limiter** (ten attempts a minute per address, `user_controller.go:144-153`). It is scoped to protect password guessing and is far too generous for sending mail.+- **Counting through the scoped rate limiter instead of the rows.** Its counter lives in memory (`backend/internal/util/ratelimiter/global.go`, `backend/internal/util/cache/global.go`), so a restart would reset the ceiling with nothing to show for it, and the limiter is wired into controllers while the decision to send belongs to the service - a wrong password must never spend the allowance.++### The password step returns a pending sign-in that is already live++The pending identifier lives in the page, not in the address bar and not in storage, so a reload loses it and the user submits the password again. If every password step minted a code, five reloads would exhaust the hourly allowance of somebody who has done nothing wrong, and the instance would refuse to sign them in for the rest of the hour.++The password step therefore looks for a pending sign-in for that account that has not expired, has not been used, has not been destroyed by wrong guesses and was started with the password the account holds now, and returns it unchanged: same identifier, same code, no new message. The password condition matters because the verification step refuses a row whose password has changed: without it, an owner who changes a leaked password and signs in again would be handed the thief's pending sign-in, refused at the code step, sent back to the password step and handed it again until it expired.++The lookup, the hourly count and the insert run in one transaction that first locks the account's row in `users`. Two password steps arriving together would otherwise both find nothing live, both stay under the cap and both send a code. Somebody who never received the first message asks for a resend, which is throttled to one a minute and issues a code the cap counts.++A resend is the one thing that moves the identifier. Because the cap counts rows, a resent code is a new row, so the resend supersedes the pending sign-in it replaces: it issues the new row first, marks the previous one used once the message is on its way, and answers with the identifier of the new one. The caller keeps whichever identifier the instance handed it last, and a refused resend leaves it holding the code it already has.++Alternatives rejected:++- **Keeping the identifier in `sessionStorage`.** It survives a reload in one tab and nothing else - a second device or a closed tab is the same situation again - and it puts a sign-in secret where every script on the page can read it.+- **Minting a new code on every password step and raising the cap to absorb reloads.** The cap exists to bound how much mail one mailbox receives; raising it to make room for reloads gives up the thing being bounded.+- **Invalidating the live pending sign-in and sending a fresh code.** The same mail volume as minting, and it breaks the user who is at that moment typing the code from the first message.++### Claim an attempt before comparing the code++The verification step spends one of the five attempts with a conditional `UPDATE ... RETURNING` before it compares the code, and spends the code itself with a second conditional update that succeeds only while the row is still unused. Counting after the comparison would let a burst of simultaneous guesses all be compared before the counter reached five, and an unconditional "mark used" would let two requests carrying the same correct code both receive a token. A correct code spends an attempt as well, which changes nothing, because the row is spent with it.++### Refusals carry a code, not only a status++Every refusal from the sign-in, verification and resend endpoints carries a machine-readable `code` beside the message: `sign_in_code_incorrect`, `pending_sign_in_not_usable`, `sign_in_code_not_sent`, `too_many_sign_in_codes`, `sign_in_code_resent_too_soon`, and `rate_limit_exceeded` from the shared limiter. The status alone does not identify the cause: a wrong code and a failed Turnstile challenge are both 400, and a resend inside its minute and an exhausted hourly cap are both 429 but ask the user to wait a minute and an hour respectively. The interface translates them through `translateApiError`, so the password step shows the same translated text as the code step, and it leaves the code step only on `pending_sign_in_not_usable`.++### Delete a pending sign-in an hour after it was created, not when its code expires++The pending sign-in table has two readers that want different lifetimes. The verification step needs a row while its code is usable, which is ten minutes. The hourly cap needs to count the rows an account collected over the last hour. Deleting a row when its code expires would empty that window six times over and leave the cap counting almost nothing, so the sixth, seventh and eighth code of an hour would all be sent.++The sweep therefore deletes a pending sign-in an hour after `created_at`, whatever state it is in. A row older than that can neither produce a token nor change a count, so nothing observable depends on it.++`password_reset_codes` shows what happens with no sweep at all: `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:137`, `:345`) sweeps both tables on an interval. Reset codes expire after an hour and their own cap counts the same hour, so for them expiry and retention already coincide and `DeleteExpiredCodes` is adopted as it stands.++Alternatives rejected:++- **Deleting a pending sign-in as soon as its code expires.** It reads as the tidy choice and silently removes the hourly cap, which is the security property, not a housekeeping detail.+- **Deleting the pending sign-in inline at the moment it expires.** Nothing reads an expired row on its own, so nothing would trigger the deletion for the rows that matter - the ones nobody ever comes back for.+- **Keeping every row and filtering by date at query time.** That is the `password_reset_codes` situation this change is fixing.++### 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:122-142`, `:414-434`) 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.++Both requests name the pending sign-in by the identifier the instance returned last, from the password step or from a resend, and carry no email address. The limiter keys on the account the server resolves from the row, not on a value the caller supplies, so a stranger cannot spend another account's resend allowance by naming its address.++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:191-195`) 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. The console command that switches the setting off writes one too: a security switch that can be moved from the host without a trace is a hole in the same log. All three are asserted through the recording audit writer the controller tests install (`backend/internal/features/users/testing/audit_log_utils.go:61-73`).++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`, `--list-admins`, `--new-password` and `--email` in `backend/cmd/main.go:151-168` and dispatched from the same startup point as the password reset (`main.go:111`), after the database is ready. It flips the global setting off, reports whether anything changed, and exits. Like the password reset, it installs the audit-log dependencies first (`main.go:204`), so the switch it moves is recorded.++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:46-58`). 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 fifth authentication mode beside `signIn`, `signUp`, `requestReset` and `resetPassword` (`frontend/src/pages/AuthPageComponent.tsx:20-22`), holding the pending identifier and the address to display, and replacing the identifier with the one a resend hands back. 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.+- **Turning the setting on guards the next sign-in and ends nothing already running.** → Tokens issued before the switch keep working for their full ten years (`user_services.go:265-272`), so an owner reacting to a leaked password has to change that password, which is what invalidates them. The settings screen and the documentation say this, because a security switch that implies more than it does is worse than none.+- **Every signed-in user can read the settings response.** → `GET /users/settings` is open to any authenticated caller (`settings_controller.go:19`), because members read `isMemberAllowedToCreateWorkspaces` from it, so the new switch and the mail-server answer are visible to members as well as administrators. Neither is a secret: a member learns whether the second factor is on by signing in once.+- **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, with the foreign key and the lookup index as separate statements and `ON DELETE CASCADE` on the user reference, so deleting an account takes its pending sign-ins with it. The down step drops the table and the column. 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/archive/2026-09-21-add-email-two-factor-auth/proposal.md b/openspec/changes/archive/2026-09-21-add-email-two-factor-auth/proposal.mdnew file mode 100644index 00000000..b1b20b62--- /dev/null+++ b/openspec/changes/archive/2026-09-21-add-email-two-factor-auth/proposal.md@@ -0,0 +1,65 @@+## 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:265-272`). 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:543-558`), an SMTP sender that reports whether it is configured (`backend/internal/features/email/di.go`), and a scoped rate limiter (`user_controller.go:436-446`). 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`, which is archived: its behavior is in [`openspec/specs/root-admin-account/spec.md`](../../../specs/root-admin-account/spec.md) and its code is in the working tree. That change made the administrator of a new instance the first account registered on it, so it holds a real address from the start, the instance records which account that is, and an upgraded instance can move off the placeholder login `admin`. Without it, the most privileged account on a fresh install had that literal string in its address column and no mailbox, so a second factor could only have been enforced by locking that account out. This change also builds on two things that arrived with it: the recorded bootstrap administrator, and the recording audit-log writer the controller tests use (`backend/internal/features/users/testing/audit_log_utils.go:12-77`).++## 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:144-149`), 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 a minute for the same account. The hourly ceiling on resends is the cap on issued codes below, so there is one hourly number rather than two that can disagree.+- Cap issued codes at five an hour per account, 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:144-153`) leaves room for hundreds of messages an hour into one mailbox. The count runs over the pending sign-ins the instance still holds, so those rows are kept for the hour the count covers instead of being removed the moment they expire.+- Hand back the pending sign-in that is already live rather than issuing a second code for the same account. Whoever reloads the code screen loses the identifier the response carried and repeats the password step, which would otherwise spend one of those five codes on every reload. The password step therefore returns the pending sign-in still waiting for that account and sends nothing; a fresh code comes only from the resend.+- 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:122-142`, `:414-434`), since the resend sends mail.+- Let the verification and resend requests name the pending sign-in by its identifier alone, never by an email address. The identifier is known only to whoever supplied the correct password, which is what keeps a stranger from burning another account's attempts or its hourly allowance.+- Delete a pending sign-in once no limit still counts it, an hour after it was created, through a background sweep. Deleting it the moment its code expires, ten minutes in, would empty the window the hourly cap counts over and quietly remove that cap. 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 report the value they were just given on both sides of the arrow - turning one on logs `true -> true` - 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.+- Give the settings endpoints their own request and response types. The persisted model is currently both the body a client sends and the body it receives (`backend/internal/features/users/controllers/settings_controller.go:19-25`), so the derived answer about the mail server would arrive back in the next update and the stored row would carry whatever the client claimed. The response carries the switches plus that derived answer; the request carries the switches alone.+- 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. The command writes an audit entry, so switching a security setting off from the host leaves the same trace as switching it off from the settings screen.+- Say plainly, on the settings screen and in the published documentation, that turning the setting on guards the next sign-in and ends nothing that is already running. Tokens issued before the switch keep working for their full ten years; changing the password is what invalidates them.+- 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, including the ones that already exist when an administrator turns the setting on. 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. What the change does owe the reader is not pretending otherwise, which is why the switch says what it does and does not do.+- 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:93-101`), 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:74-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:144-149`) 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 in `openspec/specs/` now, and nothing here contradicts it: the bootstrap administrator keeps its address, its password reset and its recovery commands, and gains a second factor like every other account. Its requirement that setting up and recovering an instance are documented asks for the password reset and the administrator listing to be documented together and in every language; adding a third recovery command to those same pages satisfies that requirement rather than changing it. The behavior this change introduces - the bootstrap administrator being subject to the second factor, 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 the request and response types its endpoints gain, 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. `GET /users/settings` answers with a field about the mail server that `PUT /users/settings` does not accept. 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 settings type gains the switch and the read-only answer about the mail server, 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/archive/2026-09-21-add-email-two-factor-auth/specs/two-factor-authentication/spec.mdsimilarity index 65%rename from openspec/changes/add-email-two-factor-auth/specs/two-factor-authentication/spec.mdrename to openspec/changes/archive/2026-09-21-add-email-two-factor-auth/specs/two-factor-authentication/spec.mdindex d71dbd1d..b55fc74f 100644--- a/openspec/changes/add-email-two-factor-auth/specs/two-factor-authentication/spec.md+++ b/openspec/changes/archive/2026-09-21-add-email-two-factor-auth/specs/two-factor-authentication/spec.md@@ -8,6 +8,8 @@ Lets the owner of an instance require a second, emailed factor before a passwordThe 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.+Turning the setting on SHALL NOT end sessions that already exist. An access token issued before the change SHALL keep working until it expires or a password change invalidates it, and the interface offering the setting SHALL say so, so that an administrator reacting to a leaked password knows the switch alone does not shut that password's session out.+#### Scenario: Default state- **WHEN** an instance is deployed and claimed for the first time@@ -18,6 +20,11 @@ The instance SHALL offer a single global setting that requires a second factor f- **WHEN** a member submits a settings update that turns the second factor on- **THEN** the update is refused and the setting is unchanged+#### Scenario: A session that predates the switch++- **WHEN** an administrator turns the second factor on while another user is already signed in+- **THEN** that user's session keeps working, and the interface has told the administrator that the setting applies to the next sign-in+### Requirement: The second factor cannot be turned on unless the instance can deliver codesTurning 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.@@ -45,12 +52,19 @@ The interface offering the setting SHALL explain the mail server requirement and- **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+#### Scenario: Switching off after the mail server is gone++- **WHEN** the second factor is on and the instance has since lost its mail server+- **THEN** an administrator who is still signed in can switch the setting off from the settings screen, because only turning it on is refused+### Requirement: Password sign-in asks for an emailed code when the second factor is onWith 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.+The message carrying the code SHALL state the code, SHALL say that it stops working ten minutes after it was sent, and SHALL say that requesting another code replaces it.+This applies to every account on the instance, including the recorded bootstrap administrator.#### Scenario: Completing a two-step sign-in@@ -69,6 +83,16 @@ This applies to every account on the instance, including the recorded bootstrap- **WHEN** a user submits a code that has already completed a sign-in- **THEN** the attempt is rejected and no second token is issued+#### Scenario: The same code submitted twice at once++- **WHEN** two requests carrying the same correct code for the same pending sign-in arrive at the same time+- **THEN** exactly one of them returns an access token++#### Scenario: What the message says++- **WHEN** a code arrives at an account's address+- **THEN** the message carries the six digits, says the code stops working in ten minutes, and says that requesting another code replaces it+### Requirement: A code is sent only after the password is verifiedThe 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.@@ -85,13 +109,15 @@ The instance SHALL verify the password before generating or sending any code. A### 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.+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. Submissions that arrive at the same time SHALL count against the same five, so no more than five codes are ever checked against one pending sign-in.++The user SHALL be able to request a new code for a pending sign-in. A resend SHALL supersede the pending sign-in it replaces: the previous code SHALL stop working, and the answer SHALL carry the identifier that names the new one. Resends SHALL be limited to one a minute for the same account; a request inside that minute SHALL be refused without sending mail.-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 an 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, and the caller SHALL be told that too many codes have been requested, rather than being shown a code screen for a message that will never arrive. This SHALL be the only hourly limit on codes, so that no second limit can disagree with it.-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.+Repeating the password step while a pending sign-in for that account is still live - not expired, not used, not destroyed by wrong guesses, and started with the password the account holds now - SHALL return that same pending sign-in and SHALL send no further mail. Password steps that arrive at the same time SHALL produce one pending sign-in and one message between them. Reaching the code screen again therefore costs nothing from the hourly limit, and the code already delivered stays the one that works.-A pending sign-in SHALL NOT be retained after it expires.+A pending sign-in SHALL be kept for as long as the hourly limit counts it and SHALL NOT be kept after that. Being kept SHALL never make an expired, used or destroyed pending sign-in usable.#### Scenario: Code expires@@ -103,24 +129,39 @@ A pending sign-in SHALL NOT be retained after it expires.- **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: Guessing the code in parallel++- **WHEN** someone submits ten incorrect codes for the same pending sign-in at the same time+- **THEN** five of them are checked, the pending sign-in is destroyed, and the other five are refused without being checked+#### 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+- **THEN** a new code is sent, the answer carries the identifier that names it, and the previous code 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: Reaching the code screen again++- **WHEN** a user who has reached the code screen loses the pending sign-in it was showing, by reloading the page or opening the instance on another device, and submits the correct password again while the first code is still live+- **THEN** the instance answers with the same pending sign-in, sends no second message, and the code already in the mailbox still works++#### Scenario: Signing in again after changing the password++- **WHEN** a user whose pending sign-in is still live changes the password, for example after an unexpected code revealed that someone else knows it, and then signs in with the new password+- **THEN** the instance sends a fresh code and answers with a new pending sign-in, instead of handing back the one the old password started, which can no longer be completed+#### 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+- **WHEN** someone who knows an account's password lets each pending sign-in lapse and repeats the password step until that account has received five codes within an hour, then completes it once more+- **THEN** no further mail is sent, no usable pending sign-in is produced, and the response says that too many codes have been requested-#### Scenario: Expired pending sign-ins are not kept+#### Scenario: Old pending sign-ins are not kept-- **WHEN** pending sign-ins have expired without being used+- **WHEN** pending sign-ins are older than the hour their limits are counted over- **THEN** the instance no longer holds them### Requirement: The verification step re-checks what the password step checked@@ -148,11 +189,18 @@ A pending sign-in created while the second factor was on SHALL still be completaThe 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.+Both requests SHALL name the pending sign-in by the identifier the instance returned most recently, from the password step or from a resend, and SHALL NOT accept an email address as a way to name it. Knowing an address therefore gives no way to spend another account's attempts, resends or hourly allowance.+#### 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+#### Scenario: Naming an account by its address++- **WHEN** somebody who knows another user's address tries to verify a code or request a resend for that account, without an identifier the instance issued to that account+- **THEN** the request has no way to name the account, so it consumes none of that account's attempts, resends or hourly allowance+### Requirement: Sign-in fails closed when the code cannot be sentIf 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.@@ -177,6 +225,8 @@ Any interface or documentation that describes the second factor SHALL NOT claimAn 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.+A run that switches the setting off SHALL be recorded in the audit log, so that the log explains why an instance stopped asking for codes and the host is not a way to move a security switch unobserved.+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@@ -189,6 +239,11 @@ The command SHALL be available only to a caller who can already execute commands- **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+#### Scenario: The disable command leaves a trace++- **WHEN** the operator runs the disable command on an instance where the setting is on+- **THEN** the audit log holds an entry recording that the second factor was switched off from the host+### Requirement: The second factor is documented as part of the product's security storyThe 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.diff --git a/openspec/changes/archive/2026-09-21-add-email-two-factor-auth/tasks.md b/openspec/changes/archive/2026-09-21-add-email-two-factor-auth/tasks.mdnew file mode 100644index 00000000..f8f3a666--- /dev/null+++ b/openspec/changes/archive/2026-09-21-add-email-two-factor-auth/tasks.md@@ -0,0 +1,89 @@+This change extends behavior and documentation introduced by `replace-seeded-admin-with-first-signup`, which is archived and in the working tree. The sections it left behind are what tasks 6 and 7 extend, and the recording audit-log writer the tests below assert against is `backend/internal/features/users/testing/audit_log_utils.go`, installed through `InstallAuditLogRecorder`.++## 1. Storage and settings++- [x] 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), give the foreign key `ON DELETE CASCADE` so deleting an account takes its pending sign-ins with it, index the creation time the hourly count and the sweep both read, 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, and by deleting a user that has a pending sign-in and seeing the row go with it.+- [x] 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 print the new value on both sides of the arrow - turning a switch on logs `true -> true` - 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.+- [x] 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.+- [x] 1.4 Give the settings endpoints their own types: a response carrying the four switches plus the mail sender's own answer about being configured, and a request carrying the four switches alone, so the settings screen stops predicting the gate from the build-time flag `IS_EMAIL_CONFIGURED`, whose rule differs (`docker/start.sh:144-149`), and so the derived answer cannot be written back. Today both bodies are the persisted model (`backend/internal/features/users/controllers/settings_controller.go:19-25`). Verify with controller tests that read the settings with a configured and with an unconfigured mail sender and see the field follow the sender, and that an update sending the derived field leaves the stored row untouched.+- [x] 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.+- [x] 1.6 Run `make lint` in `backend/`.++## 2. Two-step sign-in++- [x] 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.+- [x] 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.+- [x] 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. Assert the failure through the absence of a usable row rather than an empty `SentEmails`, because `MockEmailSender` records the message before it returns the failure (`backend/internal/features/users/testing/mocks.go:23-32`).+- [x] 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.+- [x] 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.+- [x] 2.6 Add the resend endpoint, invalidating the previous code and throttled through the existing scoped rate limiter to one a minute for the same account, with no hourly limit of its own because the cap in 2.7 counts resent codes too; verify with a controller test that a second immediate resend is refused and that the previous code stops working after a successful resend.+- [x] 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:513-522`), and refuse beyond that before any mail is sent, answering with "too many codes requested" rather than a code screen; verify with a controller test that reaches the cap through expired pending sign-ins and resends, then asserts the next password step sends no mail, returns no usable pending sign-in and says why.+- [x] 2.8 Return the pending sign-in that is already live instead of issuing a second code: when the password step succeeds and the account has a pending sign-in that has not expired, been used or been destroyed, answer with that identifier and send nothing; verify with a controller test that two password steps in a row produce one message and the same identifier, that the first code still works, and that the hourly count went up by one rather than two.+- [x] 2.9 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.+- [x] 2.10 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:122-142`, `:414-446`), and let both requests name the pending sign-in by its identifier alone, with no email field to key on; 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, and that the request bodies carry no address.+- [x] 2.11 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.+- [x] 2.12 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.+- [x] 2.13 Add a background task beside the others in `runBackgroundTasks` (`backend/cmd/main.go:345`) that deletes pending sign-ins an hour after they were created - not when their code expires ten minutes in, which would empty the window the cap in 2.7 counts over - 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 rows of both ages in each table, confirm one sweep removes only the ones past their retention, and confirm the cap still refuses a sixth code after a sweep has run.+- [x] 2.14 Write the message that carries the code, following the reset-code template (`user_services.go:563-599`): the six digits, that the code stops working ten minutes after it was sent, and that requesting another code replaces it; verify with a controller test that the message the mock sender received carries the code and both statements.+- [x] 2.15 Regenerate the API documentation with `make swagger`, confirm the sign-in endpoint documents both response shapes and that the settings response documents the field its request does not accept, and run `make test` and `make lint` in `backend/`.++## 3. Console escape hatch++- [x] 3.1 Add the `--disable-2fa` flag to `parseCommandLineOptions` (`backend/cmd/main.go:151-168`) and dispatch it from the same startup point as the password reset (`main.go:111`), installing the audit-log dependencies the way that command does (`main.go:204`), turning the setting off, writing an audit entry when it changed something, reporting what it did 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.+- [x] 3.2 Add tests covering the command on an instance where the setting is already off, expecting a success exit, a "no change" report and no audit entry, and on one where it is on, expecting the stored setting to be off afterwards and an entry in the recording audit writer; verify with `make test` in `backend/`.++## 4. Settings screen++- [x] 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, carrying a link to the configuration documentation's SMTP section, and saying that the setting applies to the next sign-in and leaves sessions already open untouched; verify in the running application with mail configured and with it unconfigured.+- [x] 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/`.+- [x] 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++- [x] 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:46-58`), 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/`.+- [x] 5.2 Add the code-entry screen as a fifth 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.+- [x] 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 resend refused inside its minute, the hourly cap refusing a password step that would have sent a sixth code, and the "could not send the code" response; verify each by driving the corresponding backend condition.+- [x] 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.+- [x] 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.+- [x] 5.6 Run `pnpm lint`, `pnpm format`, `pnpm test` and `pnpm build` in `frontend/`.++## 6. English documentation++- [x] 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.+- [x] 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.+- [x] 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.+- [x] 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, the `FaqItem` whose question is "How does Databasus ensure security?" (`:1301-1304`), and the structured-data copy of the same answer (`:176-182`); verify both copies carry the same wording and `npm run build` passes in `website/`.+- [x] 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/`.+- [x] 6.6 Run `npm run lint` in `website/`.++## 7. Translations++- [x] 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/`.+- [x] 7.2 Repeat for Spanish (`es`).+- [x] 7.3 Repeat for Portuguese (`pt`).+- [x] 7.4 Repeat for Chinese (`zh`).+- [x] 7.5 Repeat for French (`fr`).+- [x] 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++- [x] 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.+- [x] 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.+- [x] 8.3 Walk the whole feature on a running instance: turn the setting on with mail configured, sign in in two steps, reload the code screen and confirm the password step brings back the same pending sign-in with no second message, exhaust the attempts, resend a code, break the mail configuration and confirm sign-in fails closed, then recover with `--disable-2fa` and find that run in the audit log.+- [x] 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.+- [x] 8.5 Complete the mandatory compliance review for the finished diff and resolve every CHANGES REQUIRED finding.++## 9. Review follow-up++- [x] 9.1 Hand back a live pending sign-in only when it was started with the account's current password, so signing in after a password change sends a fresh code instead of looping on a pending sign-in the code step refuses; verify with a controller test that changes the password during a pending sign-in and completes a sign-in with the new one.+- [x] 9.2 Claim an attempt before comparing the code and spend the code with a conditional update; verify with controller tests that send the same correct code four times at once and ten wrong codes at once.+- [x] 9.3 Run the live lookup, the hourly count and the insert in one transaction under a lock on the account's row; verify with a controller test that sends three password steps at once and sees one message.+- [x] 9.4 Give every sign-in, verification and resend refusal a machine-readable code, translate the codes through `translateApiError` in all six dictionaries, and leave the code step only on `pending_sign_in_not_usable`; verify with a controller test asserting the codes and a `translateApiError` test that tells the two 429 refusals apart.+- [x] 9.5 Reset the Turnstile answer after every resend, successful or not, and keep the toggle enabled while the setting is on so it can be switched off without a mail server.+- [x] 9.6 Correct the security page in all six languages: a pending sign-in is discarded after five wrong guesses rather than surviving them, and turning the setting on leaves open sessions working; link the recovery sentence to the password page's `disable-two-factor` section.++## Completion notes++- **Rolling the binary back with the second factor on is an unannounced security downgrade.** The migration adds `users_settings.is_two_factor_auth_required` with a `false` default and creates `two_factor_codes`, so deploying the change alters nothing until an administrator turns the setting on. Rolling back with it off is uneventful. Rolling back with it on leaves a column the old code never reads, so password sign-in silently returns to one factor while the interface and the database still say the second factor is required. Nobody is locked out and nothing warns anybody, which is why it is written down: an operator rolling back has to know the instance stops asking for codes. See design.md - Migration Plan.+- **During a mail outage the sixth sign-in attempt within an hour reports the wrong cause.** A send that fails leaves its row behind, because the row is what the hourly cap counts, so after five failed sends the cap answers "too many codes requested" instead of "could not send the code". An operator diagnosing a dead mail server sees the misleading message from the sixth attempt on; `--disable-2fa` is the way out either way.+- **The pending sign-in records the account's password creation time.** The table carries `password_creation_time` beyond the columns task 1.1 enumerates, because the verification step refuses a pending sign-in whose account changed its password in between (design.md - Re-check the account at the verification step), and that check needs the value the password step saw. design.md - Keep the pending sign-in in a table now lists the column.diff --git a/openspec/specs/two-factor-authentication/spec.md b/openspec/specs/two-factor-authentication/spec.mdnew file mode 100644index 00000000..cb035355--- /dev/null+++ b/openspec/specs/two-factor-authentication/spec.md@@ -0,0 +1,261 @@+# Two-Factor Authentication Specification++## 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.++## 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.++Turning the setting on SHALL NOT end sessions that already exist. An access token issued before the change SHALL keep working until it expires or a password change invalidates it, and the interface offering the setting SHALL say so, so that an administrator reacting to a leaked password knows the switch alone does not shut that password's session out.++#### 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++#### Scenario: A session that predates the switch++- **WHEN** an administrator turns the second factor on while another user is already signed in+- **THEN** that user's session keeps working, and the interface has told the administrator that the setting applies to the next sign-in++### 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++#### Scenario: Switching off after the mail server is gone++- **WHEN** the second factor is on and the instance has since lost its mail server+- **THEN** an administrator who is still signed in can switch the setting off from the settings screen, because only turning it on is refused++### 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.++The message carrying the code SHALL state the code, SHALL say that it stops working ten minutes after it was sent, and SHALL say that requesting another code replaces it.++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++#### Scenario: The same code submitted twice at once++- **WHEN** two requests carrying the same correct code for the same pending sign-in arrive at the same time+- **THEN** exactly one of them returns an access token++#### Scenario: What the message says++- **WHEN** a code arrives at an account's address+- **THEN** the message carries the six digits, says the code stops working in ten minutes, and says that requesting another code replaces it++### 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. Submissions that arrive at the same time SHALL count against the same five, so no more than five codes are ever checked against one pending sign-in.++The user SHALL be able to request a new code for a pending sign-in. A resend SHALL supersede the pending sign-in it replaces: the previous code SHALL stop working, and the answer SHALL carry the identifier that names the new one. Resends SHALL be limited to one a minute for the same account; a request inside that minute SHALL be refused without sending mail.++Codes SHALL be limited to five an 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, and the caller SHALL be told that too many codes have been requested, rather than being shown a code screen for a message that will never arrive. This SHALL be the only hourly limit on codes, so that no second limit can disagree with it.++Repeating the password step while a pending sign-in for that account is still live - not expired, not used, not destroyed by wrong guesses, and started with the password the account holds now - SHALL return that same pending sign-in and SHALL send no further mail. Password steps that arrive at the same time SHALL produce one pending sign-in and one message between them. Reaching the code screen again therefore costs nothing from the hourly limit, and the code already delivered stays the one that works.++A pending sign-in SHALL be kept for as long as the hourly limit counts it and SHALL NOT be kept after that. Being kept SHALL never make an expired, used or destroyed pending sign-in usable.++#### 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: Guessing the code in parallel++- **WHEN** someone submits ten incorrect codes for the same pending sign-in at the same time+- **THEN** five of them are checked, the pending sign-in is destroyed, and the other five are refused without being checked++#### 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, the answer carries the identifier that names it, and the previous code 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: Reaching the code screen again++- **WHEN** a user who has reached the code screen loses the pending sign-in it was showing, by reloading the page or opening the instance on another device, and submits the correct password again while the first code is still live+- **THEN** the instance answers with the same pending sign-in, sends no second message, and the code already in the mailbox still works++#### Scenario: Signing in again after changing the password++- **WHEN** a user whose pending sign-in is still live changes the password, for example after an unexpected code revealed that someone else knows it, and then signs in with the new password+- **THEN** the instance sends a fresh code and answers with a new pending sign-in, instead of handing back the one the old password started, which can no longer be completed++#### Scenario: Restarting the password step to send more mail++- **WHEN** someone who knows an account's password lets each pending sign-in lapse and repeats the password step until that account has received five codes within an hour, then completes it once more+- **THEN** no further mail is sent, no usable pending sign-in is produced, and the response says that too many codes have been requested++#### Scenario: Old pending sign-ins are not kept++- **WHEN** pending sign-ins are older than the hour their limits are counted over+- **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.++Both requests SHALL name the pending sign-in by the identifier the instance returned most recently, from the password step or from a resend, and SHALL NOT accept an email address as a way to name it. Knowing an address therefore gives no way to spend another account's attempts, resends or hourly allowance.++#### 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++#### Scenario: Naming an account by its address++- **WHEN** somebody who knows another user's address tries to verify a code or request a resend for that account, without an identifier the instance issued to that account+- **THEN** the request has no way to name the account, so it consumes none of that account's attempts, resends or hourly allowance++### 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.++A run that switches the setting off SHALL be recorded in the audit log, so that the log explains why an instance stopped asking for codes and the host is not a way to move a security switch unobserved.++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++#### Scenario: The disable command leaves a trace++- **WHEN** the operator runs the disable command on an instance where the setting is on+- **THEN** the audit log holds an entry recording that the second factor was switched off from the host++### 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