carlos / platform Public

console: people and sign-in methods (social sign-in plan 1)

Every console sign-in resolves through a sign_in_methods table (kind,
subject) to the person (users.address), backfilled offline at start.
Sessions record their method; a new-person budget gates every sign-up
path; invites accept any address the person holds; Your settings lists
sign-in methods. Spec: 2026-11-02-console-social-signin-design.md rev 3.

Co-Authored-By: GPT-6 Astra <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from design-console-social-signin into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 1a9c752d99939b76b1754711da64bce748c102da parent f54ed7a
22 files changed, +2,333 −47
  • docs/superpowers/plans/2026-11-02-console-social-signin-1-methods.md +248 −0
  • docs/superpowers/specs/2026-11-02-console-social-signin-copy-approved.json +50 −0
  • docs/superpowers/specs/2026-11-02-console-social-signin-design.md +539 −0
  • internal/console/authcli.go +27 −0
  • internal/console/billingseats.go +2 −1
  • internal/console/emailsignin.go +24 −14
  • internal/console/emailsignin_limits.go +33 −2
  • internal/console/emailsignin_limits_test.go +106 −5
  • internal/console/invite_held_address_test.go +214 −0
  • internal/console/newperson_test.go +140 −0
  • internal/console/server.go +8 −8
  • internal/console/settings_methods_test.go +161 −0
  • internal/console/signincopy.go +3 −0
  • internal/console/signinmethods_store.go +156 −0
  • internal/console/signinmethods_store_test.go +278 −0
  • internal/console/signinmethods_test.go +207 −0
  • internal/console/socialsignin_copy.go +17 −0
  • internal/console/socialsignin_copy_test.go +54 −0
  • internal/console/store.go +46 −17
  • internal/console/store_gate.go +1 −0
  • internal/console/templates/layout.html +2 −0
  • internal/console/templates/settings.html +17 −0

CI passed — run details

diff --git a/docs/superpowers/plans/2026-11-02-console-social-signin-1-methods.md b/docs/superpowers/plans/2026-11-02-console-social-signin-1-methods.md
new file mode 100644
index 000000000..dd4087843
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-02-console-social-signin-1-methods.md
@@ -0,0 +1,248 @@
+# Console social sign-in, Plan 1: people and sign-in methods
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Every sign-in resolves through a `sign_in_methods` table to a person (the `users.address` contact address). Invites can be accepted by any address the person holds. Your settings lists the person's methods. A new-person budget gates every sign-up path. After this plan, the console behaves exactly as today for every existing person, but the model that Plans 2-4 (providers, Apple, link and merge) build on is in place.
+
+**Architecture:** The new table maps `(kind, subject)` to the `users.address` the method signs in to. `finishSignin` stops trusting the proved address as the person and resolves it through the table instead, creating the person and method on a first sign-in. Sessions record the method row they came through. Invite gates check that the person holds the invited address, not that it equals the session address. No downstream table changes key.
+
+**Tech Stack:** Go, SQLite through `database/sql` (`internal/console/store.go` pattern), `html/template`, the console test fixture (`newConsoleFixture`, `newBrowser`, `keymailWalk`, `newEmailFixture`).
+
+**Spec:** `docs/superpowers/specs/2026-11-02-console-social-signin-design.md` (rev 3, approved 2026-11-02). Plan 1 covers §6.1 (model, migration, resolution), §4.4 (invites), the listing part of §4.3, and §9's new-person budget. Not covered here: providers (§5, Plans 2-3), step-up changes (§8, Plan 2), add, remove, merge and contact change (§4.3 actions, §7, Plan 4), and §6.2 (Plan 2).
+
+## Global Constraints
+
+- Migrations are additive and idempotent: `CREATE TABLE IF NOT EXISTS`, plus `ALTER ... ADD COLUMN` in the ALTER list whose "duplicate column" error is swallowed (`store.go:146-148`, `store.go:590-610`). They run on every start.
+- The migration does no network I/O. Keymail discovery (`keymailAddress` with a lookup) is never called from it.
+- Addresses are stored trimmed and lower-cased, as everywhere else in the console. `subject` for `email` and `keymail` is that form.
+- `kind` values are the existing `MethodEmail` (`"email"`) and `MethodKeymail` (`"keymail"`) constants (`emailsignin_store.go:35`). Plans 2-3 add `google`, `apple` and `github`.
+- Every new on-screen string goes through copy review before it goes into a file (copy-review skill). The house voice has no em dashes. The draft strings are in Task 0.
+- Store only what the spec allows (§3): kind, subject, person address, label, timestamps. No names, avatars or tokens.
+- Locally, run only the touched package's tests, with `-run` (`go test ./internal/console -run 'TestX|TestY'`). CI runs the full suite and the darwin/windows cross-builds. Leave `GOCACHE` at its default.
+- Commit subjects stay under 80 characters.
+
+## Review Focus
+
+- **A `users` row with no method row.** `SetLastAccount` (`store.go:1561`) and `SetOperator` (`store.go:2590`) create users for addresses that have never signed in. Their first sign-in must attach a method to that existing person, land them as that address, and not be charged as a new person. Test in Task 2.
+- **Two first sign-ins racing for one new subject** (a double click, or two tabs). Both land on the same person with one method row and no error. Test in Task 1.
+- **A budget refusal writes nothing.** No users row, method row, session or grant, and the person sees the refusal page, not a 500. Test in Task 3.
+- **An invite to a held address is accepted under the person.** The membership row is keyed by the person's contact address, never by the invite's address, so it doesn't create a ghost member that nobody can sign in as. This covers both the plain accept path and the seat path (`billingseats.go:205-216`). Test in Task 4.
+- **Restart after the migration.** Re-running the migration adds no duplicate rows and doesn't overwrite `kind`, `added_at` or `last_used_at` on existing rows. Test in Task 1.
+
+---
+
+### Task 0: Copy review for the new strings (gate, no code)
+
+Run the copy-review skill on these strings before Task 3 or Task 5 writes any of them into a file. Save the result as `docs/superpowers/specs/2026-11-02-console-social-signin-copy-approved.json` in the same shape as `2026-10-21-console-email-signin-copy-approved.json`, with an `action` and `strings[]` of `{id, text}`. Later tasks use the approved text byte for byte.
+
+| id | draft text |
+|----|------------|
+| `methods.heading` | Sign-in methods |
+| `methods.lede` | Every way you can sign in as {address}. |
+| `methods.col_method` | Method |
+| `methods.col_identity` | Signs in as |
+| `methods.col_added` | Added |
+| `methods.col_used` | Last used |
+| `methods.kind_email` | Email link or code |
+| `methods.kind_keymail` | Keymail |
+| `methods.never_used` | Not yet |
+| `signup.busy_title` | Try again later |
+| `signup.busy` | Too many new accounts have been made from here in the last hour. Try again later, or sign in to an account you already have. |
+
+- [ ] **Step 1:** Run copy-review on the table above and wait for Paul's edits.
+- [ ] **Step 2:** Write the approved JSON file and commit it: `git commit -m "copy: approved strings for console sign-in methods (plan 1)"`.
+
+---
+
+### Task 1: The `sign_in_methods` table, backfill and store API
+
+**Files:**
+- Create: `internal/console/signinmethods_store.go`
+- Modify: `internal/console/store.go` (call the new migration from `migrate()`, after the `users` and `sessions` tables and the ALTER list)
+- Test: `internal/console/signinmethods_store_test.go`
+
+**Interfaces:**
+- Produces:
+ - `type SignInMethod struct { ID int64; Kind, Subject, Address, Label string; AddedAt, LastUsedAt time.Time }`. A zero `LastUsedAt` means never used.
+ - `func (s *Store) ResolveSignIn(kind, subject string, now time.Time) (m SignInMethod, created bool, err error)`. This finds the method, or creates it, and creates the person when none exists. It also stamps `last_used_at = now`. `created` is true only when a `users` row was inserted by this call.
+ - `func (s *Store) LookupSignIn(kind, subject string) (SignInMethod, bool, error)`. A read-only lookup, used by Task 3 to decide before charging the budget.
+ - `func (s *Store) PersonWouldBeNew(kind, subject string) (bool, error)`. True when there is no method row and no `users` row for `subject`.
+ - `func (s *Store) SignInMethodsFor(address string) ([]SignInMethod, error)`, ordered by `added_at`, then `id`.
+ - `func holdsAddressTx(q queryer, person, address string) (bool, error)`. True when `address == person`, or when an `email` or `keymail` method row with `subject = address` points to `person`. Here `queryer` is the subset of `*sql.DB` and `*sql.Tx` with `QueryRow`. Reuse an existing interface if the package has one.
+
+Schema (names are this plan's choice; the spec left them to the builder):
+
+```sql
+CREATE TABLE IF NOT EXISTS sign_in_methods (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ kind TEXT NOT NULL,
+ subject TEXT NOT NULL,
+ address TEXT NOT NULL, -- users.address it signs in to
+ label TEXT NOT NULL DEFAULT '',
+ vouched_email TEXT NOT NULL DEFAULT '', -- providers only (Plan 2)
+ vouched_trusted INTEGER NOT NULL DEFAULT 0,
+ added_at INTEGER NOT NULL,
+ last_used_at INTEGER NOT NULL DEFAULT 0,
+ removed_at INTEGER NOT NULL DEFAULT 0,
+ UNIQUE(kind, subject)
+);
+CREATE INDEX IF NOT EXISTS sign_in_methods_address ON sign_in_methods (address);
+```
+
+Backfill, run on every start:
+
+```sql
+INSERT INTO sign_in_methods (kind, subject, address, added_at)
+SELECT CASE WHEN EXISTS (SELECT 1 FROM grants g WHERE g.address = u.address)
+ OR EXISTS (SELECT 1 FROM sessions x WHERE x.address = u.address AND x.method = 'keymail')
+ THEN 'keymail' ELSE 'email' END,
+ u.address, u.address, u.created_at
+FROM users u
+WHERE NOT EXISTS (SELECT 1 FROM sign_in_methods m WHERE m.address = u.address)
+ON CONFLICT(kind, subject) DO NOTHING;
+```
+
+A grant row exists only after a Keymail sign-in, and every session from before the `method` column was a Keymail one (`store.go:597`), so this needs no discovery lookup. A `users` row from `SetOperator`/`SetLastAccount` for someone who never signed in becomes an `email` method. That's harmless: if they later arrive through Keymail, `ResolveSignIn` adds a `keymail` row for the same person.
+
+Rows with `removed_at != 0` are ignored by `ResolveSignIn`'s match (Plan 4 uses them). In this plan nothing sets the column.
+
+- [ ] **Step 1: Write the failing tests** in `signinmethods_store_test.go`, each on a fresh store:
+ - `TestSignInMethodsBackfill`: insert users `a@x.test` (with a grants row), `b@x.test` (a session with `method='email'`), and `c@x.test` (no sessions, no grant). Run the migration. Assert `SignInMethodsFor` gives `a`→`keymail`, `b`→`email` and `c`→`email`, each with `Address == Subject` and `AddedAt == users.created_at`.
+ - `TestSignInMethodsBackfillIdempotent`: run the migration twice, then stamp `last_used_at` on one row and run it again. Assert the row count is unchanged and `last_used_at` is kept.
+ - `TestResolveSignInCreatesPerson`: on an empty store, `ResolveSignIn("email","new@x.test",now)` gives `created == true` and `Address == "new@x.test"`, and leaves one users row and one method row. A second call gives `created == false` and the same `ID`, with `LastUsedAt` stamped to the second `now`.
+ - `TestResolveSignInExistingUserNoMethod`: insert a users row via `SetLastAccount("op@x.test", 7)` with no method. `ResolveSignIn("keymail","op@x.test",now)` gives `created == false` and `Address == "op@x.test"`, and `LastAccount` is still 7.
+ - `TestResolveSignInFollowsMapping`: insert a method row `(email, alias@x.test) → person@x.test` directly. `ResolveSignIn("email","alias@x.test",now)` gives `Address == "person@x.test"`, `created == false`, and creates no users row for `alias@x.test`.
+ - `TestResolveSignInSecondKindSamePerson`: `ResolveSignIn("email","a@x.test")`, then `ResolveSignIn("keymail","a@x.test")`. This leaves two method rows, both with `Address == "a@x.test"`, and one users row.
+ - `TestResolveSignInConcurrent`: 8 goroutines call `ResolveSignIn("email","race@x.test",now)` at once. All return the same `ID` and `Address`, exactly one returns `created == true`, and none returns an error.
+ - `TestHoldsAddress`: with a person `p@x.test`, a method `(email, alias@x.test) → p@x.test`, and a method `(keymail, other@x.test) → q@x.test`: `holdsAddressTx(db, "p@x.test", "p@x.test")` is true, for `alias@x.test` it's true, for `other@x.test` it's false, and for `nobody@x.test` it's false.
+- [ ] **Step 2:** Run `go test ./internal/console -run 'TestSignInMethods|TestResolveSignIn|TestHoldsAddress'`. Expect FAIL (undefined).
+- [ ] **Step 3: Implement** the table, the backfill (`migrateSignInMethods(db)` called from `migrate()`) and the API in `signinmethods_store.go`. Do `ResolveSignIn` in one transaction: select the live row by `(kind, subject)`. If there is none, `INSERT INTO users ... ON CONFLICT DO NOTHING` (its `RowsAffected` decides `created`), then `INSERT INTO sign_in_methods ... ON CONFLICT(kind, subject) DO NOTHING`, then re-select. Finally update `last_used_at`. If SQLite reports busy under the concurrent test, use the store's existing retry or locking convention; check how `EnsureUser` callers cope.
+- [ ] **Step 4:** Run the same command. Expect PASS.
+- [ ] **Step 5: Commit:** `git commit -m "console: sign_in_methods table, backfill and resolution (social sign-in 1)"`
+
+---
+
+### Task 2: Sign-in resolves through methods, and sessions record the method
+
+**Files:**
+- Modify: `internal/console/emailsignin.go:258` (`finishSignin`)
+- Modify: `internal/console/store.go` (ALTER list; `CreateSessionMethod` at `:2834`)
+- Modify: the callers of `finishSignin` (`server.go` `handleCallback`, `emailsignin.go` link and code handlers) only if the signature changes
+- Test: `internal/console/emailsignin_test.go` (or a new `signinmethods_test.go` for the server-level tests)
+
+**Interfaces:**
+- Consumes: `ResolveSignIn`, `SignInMethod` (Task 1).
+- Produces:
+ - ALTER `sessions ADD COLUMN method_id INTEGER NOT NULL DEFAULT 0`. A 0 means the session predates this plan.
+ - `func (s *Store) CreateSessionVia(address, keymailToken, method string, methodID int64, now time.Time) (string, error)`. `CreateSessionMethod` becomes a call to it with `methodID` 0, so existing callers and tests keep working.
+ - `func (s *Store) SessionMethodID(rawToken string, now time.Time) (int64, bool)`, for Plan 4's removal.
+ - `finishSignin(w, r, proved, keymailToken, method, next string)` keeps its signature. `proved` is the address the door proved, and `method` is also the method kind.
+
+The new `finishSignin` order:
+1. Resolve `(method, proved)` with `ResolveSignIn` to get `m` and `created`. `person := m.Address`. This replaces `EnsureUser`. The budget check is inserted before this step in Task 3.
+2. The Keymail grant stays keyed by `proved` (`SetGrantToken(proved, ...)`), because it is that Keymail mailbox's grant. In this plan `proved == person` always.
+3. Session, `noteSeen`, `auditSignInRow`, the welcome cookie, `RecordStepUp` and the landing all use `person`. The session is created with `CreateSessionVia(person, keymailToken, method, m.ID, now)`.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `TestKeymailSigninRecordsMethod`: `keymailWalk` for `newcomer@keymail.dev`. Afterwards `SignInMethodsFor("newcomer@keymail.dev")` has one `keymail` row with a stamped `LastUsedAt`, and `SessionMethodID(raw)` equals that row's `ID`.
+ - `TestEmailSigninRecordsMethod`: an email-code sign-in for `pat@example.test` (use the existing email fixture helpers `postContinue` and `sentSignin`, then post the code). It leaves one `email` row, and the session's method ID matches.
+ - `TestSigninLandsOnMappedPerson`: insert a method `(email, alias@example.test) → person@example.test` and a users row for `person@`. An email sign-in as `alias@example.test` creates a session whose `SessionInfo` address is `person@example.test`, with no users row for `alias@` and no welcome cookie.
+ - `TestSigninExistingUserNoMethodNotWelcomed`: `SetLastAccount("inv@example.test", acctID)`, then email sign-in as `inv@example.test`. There's no welcome cookie (`created == false`), and the person lands on `acctID`'s account.
+- [ ] **Step 2:** Run `go test ./internal/console -run 'TestKeymailSigninRecordsMethod|TestEmailSigninRecordsMethod|TestSigninLandsOnMappedPerson|TestSigninExistingUserNoMethodNotWelcomed'`. Expect FAIL.
+- [ ] **Step 3: Implement** the ALTER, `CreateSessionVia`, `SessionMethodID` and the new `finishSignin` order above.
+- [ ] **Step 4:** Run the same command, plus the existing sign-in tests: `go test ./internal/console -run 'TestKeymail|TestFinishSignin|TestContinue|TestEmail|TestInvitePage|TestCLIPage'`. Expect PASS.
+- [ ] **Step 5: Commit:** `git commit -m "console: sign-in resolves through sign_in_methods; sessions record it"`
+
+---
+
+### Task 3: New-person budget on every sign-up path (spec §9)
+
+**Files:**
+- Modify: `internal/console/emailsignin_limits.go` (constants plus one method)
+- Modify: `internal/console/emailsignin.go` (`finishSignin`, before `ResolveSignIn`)
+- Create: `internal/console/socialsignin_copy.go` (the map of Task 0's approved strings), and extend `copyText` to read it after `signinCopy`
+- Test: `internal/console/emailsignin_limits_test.go`, `internal/console/socialsignin_copy_test.go`, and a server-level test
+
+**Interfaces:**
+- Consumes: `PersonWouldBeNew` (Task 1); `s.clientIP(r)`; the server's existing `emailLimits` instance (find its field on `Server`).
+- Produces:
+ - Constants `newPersonPerIPHour = 10` and `newPersonGlobalHour = 200`, mirroring `signinPerIPHour` and `signinGlobalHour`.
+ - `func (l *emailLimits) newPerson(ip string) bool`. It records and allows when both the per-IP and global hourly windows are under their caps. When refused it records nothing. It joins `sweepWindows()`.
+ - `var socialSigninCopy = map[string]string{...}`, holding exactly Task 0's approved ids.
+
+In `finishSignin`, before step 1: if `PersonWouldBeNew(method, proved)` is true and `!s.limits.newPerson(ip)`, render `renderMessage(w, r, http.StatusTooManyRequests, copyText("signup.busy_title"), copyText("signup.busy"))` and return. Nothing is written. Returning people never touch the budget.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `TestNewPersonBudget` (limits, injected clock): 10 calls from IP `a` are allowed and the 11th is refused. One call from IP `b` is still allowed. After the clock moves 61 minutes, IP `a` is allowed again. With 200 global hits spread over 20 IPs, a fresh IP is refused.
+ - `TestNewPersonBudgetRefusalWritesNothing` (server): set the budget so it is exhausted (fill the window through the limits clock), then do an email-code sign-in for a new address. The response is 429 and the body contains `copyText("signup.busy")`. `userRows` for the address is 0, there's no method row, and the browser has no session cookie.
+ - `TestNewPersonBudgetSparesReturning`: with the budget exhausted, an existing person signs in and gets a session.
+ - `TestSocialSigninCopyMatchesApproved`: `socialSigninCopy` equals the approved JSON's id and text set exactly, and no id appears in both `signinCopy` and `socialSigninCopy`. Model it on `signincopy_test.go:10`.
+- [ ] **Step 2:** Run `go test ./internal/console -run 'TestNewPersonBudget|TestSocialSigninCopyMatchesApproved'`. Expect FAIL.
+- [ ] **Step 3: Implement** the constants, `newPerson`, the `finishSignin` gate, `socialsignin_copy.go` and the `copyText` fallback.
+- [ ] **Step 4:** Run the same command. Expect PASS.
+- [ ] **Step 5: Commit:** `git commit -m "console: new-person budget across sign-up paths (social sign-in 1)"`
+
+---
+
+### Task 4: Invites accepted by any held address (spec §4.4)
+
+**Files:**
+- Modify: `internal/console/store.go:1598-1690` (`PendingInviteFor`, `AcceptInvite`, `acceptInviteTx`)
+- Modify: `internal/console/server.go:3598-3700` (invite page and accept: comments, and the address passed in)
+- Modify: `internal/console/billingseats.go:203-216` (`admitMember`)
+- Test: `internal/console/invite_held_address_test.go`
+
+**Interfaces:**
+- Consumes: `holdsAddressTx` (Task 1).
+- Produces (the signatures keep their shapes, and the second parameter is renamed `person`):
+ - `PendingInviteFor(token, person string, now time.Time) (*Invite, error)`. The address gate becomes `holdsAddressTx(s.db, person, i.Address)`. The single opaque error stays the same.
+ - `acceptInviteTx(tx, token, person string, now)`. The gate becomes `holdsAddressTx(tx, person, want)`, inside the same transaction. The membership row is inserted with `address = person`.
+ - `AcceptInvite(token, person, now)` is unchanged apart from the rename.
+
+`admitMember` already passes the session address (`addr`) into all three and into `s.store.Role(acct.ID, addr)`. That stays correct, because `addr` is the person. Check that nothing between `PendingInviteFor` and `acceptInviteTx` uses `inv.Address` as a membership or seat key. If something does, switch it to `addr` and say so in the commit.
+
+The signed-out invite page's prefill (`PendingInviteAddress`) is unchanged: signing in as the invited address resolves to whichever person holds it.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `TestInviteAcceptedByHeldAddress`: account A, an invite to `alias@example.test`, and a person `person@example.test` with a method `(email, alias@example.test) → person@`. `AcceptInvite(token, "person@example.test", now)` succeeds. `Role(A, "person@example.test") == RoleMember`, and `Role(A, "alias@example.test") == ""`.
+ - `TestInviteRefusedForUnheldAddress`: the same invite, with person `stranger@example.test` and no method. `PendingInviteFor` and `AcceptInvite` both fail, and there is no membership.
+ - `TestInviteHeldAddressEndToEnd` (server): sign in by email as `alias@example.test` when that address maps to `person@`. Open `/invite/{token}`, then POST accept. This lands in A, and the membership is under `person@`.
+ - `TestInviteSeatPathHeldAddress`: drive `admitMember` on a paid team with a seat authorisation, the same way the existing seat tests do (find them with `grep -n admitMember *_test.go`), as `person@` for an invite to `alias@`. The outcome is joined, and the membership and seat are consumed under `person@`.
+- [ ] **Step 2:** Run `go test ./internal/console -run 'TestInvite'`. Expect the new tests to FAIL and the existing ones to PASS.
+- [ ] **Step 3: Implement** the gate changes and renames.
+- [ ] **Step 4:** Run `go test ./internal/console -run 'TestInvite|TestAdmit|TestSeat'`. Expect PASS.
+- [ ] **Step 5: Commit:** `git commit -m "console: invites accept any address the person holds (social sign-in 1)"`
+
+---
+
+### Task 5: Your settings lists sign-in methods (spec §4.3, listing only)
+
+**Files:**
+- Modify: `internal/console/authcli.go:1515` (`cliPage` gains `Methods []methodRow`), and `handleCLITokens` (`:1708`)
+- Modify: `internal/console/templates/settings.html` (a new section before `<h2>Command-line access</h2>`, line 9)
+- Test: `internal/console/settings_methods_test.go`
+
+**Interfaces:**
+- Consumes: `SignInMethodsFor` (Task 1); the `socialSigninCopy` ids (Task 3).
+- Produces: `type methodRow struct { Kind, Identity string; AddedAt, LastUsed time.Time }`. `Kind` is the display label from `methods.kind_email` or `methods.kind_keymail`, and `Identity` is the method's subject for `email`/`keymail` (Plan 2 adds provider labels). Rows with `removed_at != 0` are left out.
+
+The section has the heading (`methods.heading`), the lede (`methods.lede` with `{address}` set to the session address), and a table with the four column headings. Each row shows `Kind`, `Identity`, `fmtTime AddedAt`, and `fmtTime LastUsed`, or `methods.never_used` when it is zero. It has no buttons in this plan. Follow `settings.html`'s existing table markup (`tablewrap`, `table`).
+
+If `SignInMethodsFor` errors, log it and leave the section out. The rest of the page still renders, because the CLI token list matters more.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `TestSettingsListsMethods`: a person with backfilled `email` plus an added `keymail` method for `a@example.test`. GET `/settings` (the route `handleCLITokens` serves; confirm it in `server.go`) gives a body containing `copyText("methods.heading")`, both kind labels, `a@example.test`, and the "Command-line access" heading after the methods heading.
+ - `TestSettingsMethodsNeverUsed`: a method with zero `last_used_at` shows `copyText("methods.never_used")`.
+ - `TestSettingsMethodsOnlyOwn`: another person's method `(email, b@example.test) → b@example.test` doesn't appear on `a@`'s page.
+- [ ] **Step 2:** Run `go test ./internal/console -run 'TestSettings'`. Expect FAIL.
+- [ ] **Step 3: Implement** the row type, the handler addition and the template section.
+- [ ] **Step 4:** Run `go test ./internal/console -run 'TestSettings|TestCLITokens'`. Expect PASS.
+- [ ] **Step 5: Commit:** `git commit -m "console: Your settings lists sign-in methods (social sign-in 1)"`
+
+---
+
+### Task 6: Branch gate
+
+- [ ] **Step 1:** `go vet ./internal/console/...`, then `go test ./internal/console` (the whole package, once). Expect PASS.
+- [ ] **Step 2:** Cross-build: `GOOS=darwin go build ./... && GOOS=windows go build ./...`. Expect no output.
+- [ ] **Step 3:** Push the branch, describe it with `amadan branch describe`, and wait for `amadan ci status -branch <branch>` to pass. This plan is not dormant (it changes sign-in and invite gates for everyone), so merging needs Paul's go after review.
diff --git a/docs/superpowers/specs/2026-11-02-console-social-signin-copy-approved.json b/docs/superpowers/specs/2026-11-02-console-social-signin-copy-approved.json
new file mode 100644
index 000000000..399ffd845
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-02-console-social-signin-copy-approved.json
@@ -0,0 +1,50 @@
+{
+ "action": "approve",
+ "approved_by": "Paul, in chat 2026-11-02 (\"Looks fine. Watch out for mobile wrapping.\")",
+ "strings": [
+ {
+ "id": "methods.heading",
+ "text": "Sign-in methods"
+ },
+ {
+ "id": "methods.lede",
+ "text": "Every way you can sign in as {address}."
+ },
+ {
+ "id": "methods.col_method",
+ "text": "Method"
+ },
+ {
+ "id": "methods.col_identity",
+ "text": "Signs in as"
+ },
+ {
+ "id": "methods.col_added",
+ "text": "Added"
+ },
+ {
+ "id": "methods.col_used",
+ "text": "Last used"
+ },
+ {
+ "id": "methods.kind_email",
+ "text": "Email link or code"
+ },
+ {
+ "id": "methods.kind_keymail",
+ "text": "Keymail"
+ },
+ {
+ "id": "methods.never_used",
+ "text": "Not yet"
+ },
+ {
+ "id": "signup.busy_title",
+ "text": "Try again later"
+ },
+ {
+ "id": "signup.busy",
+ "text": "Too many new accounts have been made from here in the last hour. Try again later, or sign in to an account you already have."
+ }
+ ]
+}
diff --git a/docs/superpowers/specs/2026-11-02-console-social-signin-design.md b/docs/superpowers/specs/2026-11-02-console-social-signin-design.md
new file mode 100644
index 000000000..dfea140f1
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-02-console-social-signin-design.md
@@ -0,0 +1,539 @@
+# Console sign-in with Apple, Google and GitHub, with linked sign-in methods and merging
+
+Status: rev 3, 2026-11-02, for Paul's approval (rev 1, the builder
+check's answers in §14, and Paul's P9). Follows
+[console email sign-in](2026-10-21-console-email-signin-design.md), whose
+sign-in flow, sessions and step-up this extends.
+
+## 1. Why
+
+Today the console has one way in: type an address, then get a link and code
+by email, or go to Keymail if it is a Keymail address. That works, but most
+people expect "Continue with Apple / Google / GitHub", and a magic link is
+slower than a tap, especially on a phone. Carloku is the general-use flagship,
+so its front door should look like every other modern product's.
+
+Success:
+
+- On carloku.com, a new person can sign up with Apple, Google or GitHub in
+ one tap plus the provider's own consent screen. A returning person signs in
+ the same way.
+- The page puts the button for the person's device first, as Eleven does:
+ Apple on a Mac, iPhone or iPad, Google on Android or ChromeOS, and email
+ everywhere else. Once someone has signed in, the method they used last comes
+ first.
+- A console with no provider configured, for example a self-hoster's, shows
+ exactly today's page. A console with only some providers configured shows
+ only those buttons.
+- One person can have several sign-in methods, and two console people who
+ turn out to be the same human can merge. That fixes Apple's Hide My Email
+ case: the relay address and the real address end up as one person.
+
+## 2. What Paul decided (2026-11-02)
+
+- **P1. This is about the console's own sign-in and sign-up**, not about apps
+ hosted on the platform.
+- **P2. "Default for the platform" means the device**, as on Eleven: the
+ matching provider's button comes first, then the others, with the email box
+ still there.
+- **P3. Each provider is on only when it is configured.** A console with none
+ set up stays email-only.
+- **P4. Carloku uses its own Apple, Google and GitHub registrations.**
+ Self-hosters register their own, because every console has a different web
+ address and redirect URL.
+- **P5. A provider sign-in lands on the person for the email address the
+ provider vouches for.** A first sign-in creates the person, as an email link
+ does today. (§6.2 narrows how far a provider's word on an address is
+ trusted.)
+- **P6. Re-confirmation uses the same provider where the provider can do a
+ fresh login, and an emailed code where it can't.** None of the three can:
+ Google doesn't support forced re-authentication for other sites, and
+ neither do GitHub or Apple. So all three step up by emailed code (§8),
+ unless the person holds a Keymail method (§8).
+- **P7. People can merge two console identities into one**, as on Eleven, so
+ Hide My Email and similar cases don't strand anyone. Merging needs a fresh
+ confirmation of both sides. The person chooses which address stays as the
+ contact address. Team memberships, sessions and CLI logins move across, and
+ where both were in the same team the higher role wins. Past activity keeps
+ the address it was recorded under.
+- **P8. People can add and remove sign-in methods** from Your settings, but
+ can never remove the last one.
+- **P9. GitHub's verified address needs a one-time emailed code** before it
+ can attach to or create a person. After that, GitHub signs the person
+ straight in. The same applies to a Google address that Google isn't
+ authoritative for (§6.2).
+
+## 3. Goals, non-goals, anti-goals
+
+Goals:
+
+- Apple, Google and GitHub sign-in and sign-up on the console's front page,
+ on the CLI approval page's sign-in, and wherever else the console asks
+ someone to sign in.
+- Device-first ordering plus remembering the last method used.
+- A person model with several sign-in methods each, plus link, unlink and
+ merge.
+- Step-up re-confirmation for each new method (P6).
+- Per-provider configuration that is all-or-nothing. A partly configured
+ provider stops the console at start-up, so nobody ever sees a button that
+ can't work.
+
+Non-goals:
+
+- Microsoft, passkeys and other providers. The design should make adding one
+ a small change, but this work adds three.
+- Social sign-in for apps hosted on the platform (P1).
+- A central sign-in relay shared by many consoles. Each console is its own
+ relying party with its own registrations (P4).
+- Splitting a merged person apart again. A merge is final. The confirmation
+ screen says so.
+- Changing who can sign in. Sign-up stays open and rate-limited, as ruled for
+ email (email-signin R2).
+
+Anti-goals (a failure even if it works):
+
+- **A button that fails because the provider isn't configured.** Eleven's
+ home page has this bug. Here, the console only offers what it has.
+- **A provider becoming a way into someone else's person.** A provider's
+ claim about an email address must never attach to a person unless that
+ provider is trusted for that address (§6.2). Linking from Your settings,
+ and merging, always need a fresh confirmation of the person being joined.
+ The only link without one is §4.2 step 2, where the provider is trusted
+ for the address, which is as strong as an email link to it. Even that is
+ refused for a person who holds a Keymail method.
+- **A step-up downgrade.** A session must never re-confirm with something
+ weaker than the email-signin spec already allows. A Keymail session still
+ re-confirms with Keymail (email-signin §6).
+- **A merge that leaves orphaned rows.** Every table keyed by a person's
+ address has a declared merge rule, and a test fails when a new one doesn't
+ (§7.3).
+- **Storing more about people than we need.** We keep the provider's subject
+ ID, the email it vouched for, and a display label (for example the GitHub
+ login). We don't keep names, avatars or provider tokens after sign-in.
+
+## 4. How it works for a person
+
+### 4.1 The front page
+
+The front page has one primary button, a list of other ways to sign in, and
+the email field:
+
+- **Primary:** the configured provider that matches the device (P2). If the
+ person signed in on this browser before, their last-used method comes
+ first instead. That comes from a small, non-identifying cookie that names
+ only the method, such as `google`.
+- **Others:** every other configured provider as a secondary button.
+- **Email:** the existing address field, unchanged in behaviour. A Keymail
+ address still goes to Keymail.
+
+When no provider is configured, the page is today's page byte for byte, apart
+from template whitespace.
+
+The page has to work without JavaScript, so the device is worked out on the
+server from `Sec-CH-UA-Platform` where the browser sends it, and from
+`User-Agent` otherwise. If neither gives an answer, the primary is email.
+
+### 4.2 Sign-up and sign-in are one step
+
+Pressing a provider button runs that provider's flow (§5). When it comes back:
+
+1. If this provider identity is already linked to a person, that person is
+ signed in.
+2. Otherwise, if the provider vouches for an address it is trusted for
+ (§6.2), and a person already has that address as an `email` method, the
+ provider identity is linked to that person and they are signed in. If
+ that person holds a Keymail method, they must first confirm with Keymail,
+ so a provider can never become a way around the passkey. If the identity
+ was removed from that person before (§4.3), it isn't relinked
+ automatically: the person is asked to add it from Your settings. An
+ email goes to that address saying a new sign-in method was added, with a
+ way to remove it.
+3. Otherwise, if the address is trusted but belongs to nobody, a new person
+ is created with that address as their contact address and as an `email`
+ method alongside the provider method. This goes through
+ the same first-landing path as email sign-up, which mints the personal
+ account and applies plan defaults, under the new-person limit (§9).
+4. Otherwise (the address isn't one the provider is trusted for), the
+ console asks for a one-time emailed code to that address before doing
+ step 2 or 3 (§6.2). If the console has no mailer, it says it can't finish
+ this sign-in and suggests another method.
+
+All four steps end in the existing `finishSignin` tail (session, cookies,
+`next`). The session's `method` records the provider.
+
+### 4.3 Your settings: sign-in methods
+
+"Your settings" gains a "Sign-in methods" section above "Command-line access"
+that lists each method: its kind, its label (address, or the GitHub login and
+the email it vouched for), when it was added, and when it was last used. From
+there a person can:
+
+- **Add a method.** They confirm freshly with their current session's method,
+ then run the new provider's flow (or, for an email address, receive a link
+ or code). If the identity already belongs to another person, the console
+ offers a merge (§7) and doesn't link it silently.
+- **Remove a method.** This needs a fresh confirmation, and is refused when
+ it is the last one. It ends every browser session signed in through that
+ method, and the step-ups those sessions earned. CLI tokens belong to the
+ person, not the method, so they stay, and the notice lists them with a
+ link to revoke. A removed provider identity is remembered as removed, so
+ §4.2 step 2 won't silently attach it again. Removing the method behind the contact address asks
+ the person to pick a new contact address first.
+- **Change the contact address** to any email-type address among their
+ methods, including one a provider vouched for under §6.2. This is the
+ address invites, notices and step-up emails go to.
+
+Every add, remove, merge and contact change sends a notice to the contact
+address (and, for a change of contact, to the old one too).
+
+### 4.4 Invites
+
+An invite is still sent to an address. A signed-in person can accept an
+invite addressed to any address they hold as an `email` or `keymail`
+method. A provider-vouched address counts only once it is an `email` method
+(§6.1). They no longer have to be signed in "as" exactly
+that address. The seat and billing gates on accepting stay as they are.
+
+## 5. The three providers
+
+All three use the authorization-code flow with `state` and PKCE (S256),
+reusing the console's existing auth-cookie pattern (`keymail.go`'s
+`NewVerifier`, `ChallengeS256` and the `carlos_console_auth` state and
+verifier cookie). Apple and Google also carry an OIDC `nonce` that is checked
+in the ID token. Codes are exchanged server-to-server over TLS, so the ID
+token received straight from the provider's token endpoint can be trusted
+from TLS (OIDC Core §3.1.3.7). The builder may also verify signatures against
+JWKS. The builder decides which, but must state the choice and test it.
+
+Each provider has a sign-in callback and a step-up callback, following the
+Keymail split (`/auth/callback`, `/auth/stepup/callback`), for example
+`/auth/google/callback`. The builder picks the paths. Self-hosters register
+them, and the docs list them.
+
+The flow code has one small provider interface (authorize URL, exchange,
+identity out), so a fourth provider is one new file. Keymail stays as it is
+and isn't moved onto this interface in this work.
+
+### 5.1 Google
+
+- OIDC, scope `openid email`. Identity is `sub`. The address is `email` when
+ `email_verified` is true.
+- Step-up: by emailed code (P6, §8). Google doesn't support forced
+ re-authentication requests from other sites.
+- Config: `CARLOS_CONSOLE_GOOGLE_CLIENT_ID`,
+ `CARLOS_CONSOLE_GOOGLE_CLIENT_SECRET`.
+
+### 5.2 Apple
+
+- Sign in with Apple on the web, using a Services ID and scope `email` only
+ (no `name`, see §3). Apple needs `response_mode=form_post`
+ when any scope is requested, so the callback is a **cross-site POST**. The
+ existing auth cookie is `SameSite=Lax` and won't come with it. The Apple
+ flow therefore needs its own state cookie with `SameSite=None; Secure`, or
+ state held on the server and found by the `state` value. The builder
+ chooses. Either way, the CSRF and state checks must hold, and there must be
+ a test that runs the callback as a cross-site POST.
+- The client secret is an ES256 JWT signed with the team's `.p8` key. Its
+ lifetime is at most six months, so it is minted on demand and cached, never
+ configured as a fixed string.
+- Identity is `sub`. The address is `email` when `email_verified` is true.
+ This may be a `privaterelay.appleid.com` address, which is a real,
+ deliverable address and is treated like any other.
+- Step-up: Apple has no reliable forced re-login, so step-up is by emailed
+ code to the person's contact address (P6). That address may be an Apple
+ relay address.
+- **Mail to relay addresses only arrives if the sending domain is registered
+ with Apple's Private Email Relay** (Apple Developer account, "Sign in with
+ Apple for Email Communication", with SPF and DKIM passing). For Carloku
+ that means registering `noreply@carloku.com` / `carloku.com`. The self-host
+ docs say the same for theirs.
+- Config: `CARLOS_CONSOLE_APPLE_SERVICES_ID`, `CARLOS_CONSOLE_APPLE_TEAM_ID`,
+ `CARLOS_CONSOLE_APPLE_KEY_ID`, `CARLOS_CONSOLE_APPLE_KEY` (the `.p8` PEM
+ text).
+
+### 5.3 GitHub
+
+- A GitHub OAuth App (not a GitHub App), scope `user:email`, with PKCE.
+ Identity is the numeric user `id`, never the login, which can change. The
+ label is the login. The address is the primary, verified entry from
+ `/user/emails`. If there is none, the sign-in stops and asks the person to
+ verify an email on GitHub or use another method.
+- The provider access token is used for those two calls and then dropped,
+ never stored.
+- Step-up: GitHub has no forced re-login, so step-up is by emailed code
+ (P6).
+- Config: `CARLOS_CONSOLE_GITHUB_CLIENT_ID`,
+ `CARLOS_CONSOLE_GITHUB_CLIENT_SECRET`.
+
+### 5.4 Configuration and secrets
+
+- Each provider's settings are all-or-nothing. All set turns the provider on,
+ none set turns it off, and some set stops the console at start-up with an
+ error naming the missing settings.
+- The settings are read in `cmd/console/main.go` with the others and listed
+ in its header comment. Until #453 lands, they are delivered the way
+ `CARLOS_STRIPE_*` is today, through the console unit's environment file.
+ Once #453 lands, the secret ones (client secrets, the Apple key) go
+ through `carlos secrets set -app console`, sealed to the console-only key.
+ Nothing in this design depends on #453.
+- Secrets never appear in logs, error messages, the ops pages or the
+ rendered page.
+
+## 6. Identity model
+
+### 6.1 People and sign-in methods
+
+The person stays keyed by their address in `users.address`, which is now
+called the **contact address**. Everything downstream that keys on it
+(memberships, CLI tokens, sessions, alert subscriptions, app stars and so
+on) is unchanged. So this design adds a mapping and doesn't rewrite the
+schema.
+
+A new table, `sign_in_methods`, is keyed by `(kind, subject)`:
+
+- `kind`: `email`, `keymail`, `google`, `apple` or `github`.
+- `subject`: the lower-cased address for `email` and `keymail`, and the
+ provider's stable ID for the rest.
+- `address`: the person, which is the `users.address` it signs in to.
+- `vouched_email`: for providers, the verified address the provider gave
+ most recently, together with whether it is trusted under §6.2. This is
+ informational. Holding an address always means having an `email` (or
+ `keymail`) method for it, created at sign-up (§4.2 step 3), after a §6.2
+ code, or from Your settings. A later different address from the provider
+ only updates `vouched_email`: it never adds, moves or removes an `email`
+ method. Removing a provider method doesn't remove the `email` method it
+ created.
+- `removed_at`: set when the person removes it (§4.3). The row stays, so
+ the identity can't silently relink.
+- `label`, `added_at`, `last_used_at`.
+
+Migration: every existing user gets one method row for their own address,
+`keymail` if the address is a Keymail address (`keymailAddress`), otherwise
+`email`. This is additive and idempotent, as the store's migration rule
+requires.
+
+Resolving a sign-in, by any method, means looking up `(kind, subject)` and
+signing in as the `address` found. An email link to an address that is
+another person's method after a merge therefore lands on the surviving
+person. An email link to an address that is nobody's method creates a person,
+as it does today.
+
+`sessions.method` gains `google`, `apple` and `github`, and sessions also
+record which method row they signed in through, so §4.3 can end them.
+Today the step-up gate sends every method other than `email`, including an
+unreadable one, down the Keymail path (`stepup.go:283-306`). The new gate
+names each method explicitly, and an unknown or unreadable value is refused
+outright rather than routed to Keymail.
+
+### 6.2 When a provider's word on an address is trusted
+
+Provider-verified emails aren't equally strong. A GitHub account can keep a
+"verified" work address long after its owner has left the company. Linking
+or creating a person by email (§4.2 steps 2 and 3) only trusts the provider
+for these cases:
+
+- **Google:** `email_verified` is true, and either the address is
+ `@gmail.com` or the ID token carries an `hd` (Workspace) claim that equals
+ the address's domain. This follows Google's own guidance on which emails
+ Google is authoritative for.
+- **Apple:** `email_verified` is true. Apple confirms both real addresses and
+ the relay addresses it issues.
+- **GitHub:** never on its own (P9). A GitHub sign-in whose address would attach
+ to an existing person, or create a new one, first needs a one-time emailed
+ code to that address (§4.2 step 4). After that, the GitHub identity is
+ linked and later sign-ins go straight through (§4.2 step 1).
+
+An untrusted address is never used to reach a person or accept an invite
+until it has been confirmed once by email.
+
+## 7. Merging
+
+### 7.1 When it is offered
+
+The console offers a merge when someone signed in as person A tries to add a
+method that already belongs to person B. This happens from Your settings, and
+also from the Hide My Email sign-in. For that case, Your settings has an
+"I already have an account with another address" action, which runs a
+sign-in by the other method in a step-up-style flow.
+
+Operators are left out of merging. A merge or a contact-address change is
+refused for a person whose address holds the fleet-operator bit
+(`users.operator`, `store.go:2585`) or appears in an address allowlist
+(`CARLOS_SYSTEM_OPERATORS`, store operators, `apistore.go:644`). Those
+authorities are granted to exact addresses by deployment config, and moving
+them by a self-service merge would be a way to gain them. The refusal says
+to ask the platform's operators. Adding and removing sign-in methods is
+still allowed for operators.
+
+### 7.2 What the person sees and confirms
+
+1. A fresh confirmation of A (A's session method).
+2. A fresh confirmation of B, by signing in with B's method in the step-up
+ flow, never by being signed in as B elsewhere.
+3. A summary: B's teams and roles, CLI logins and open invites that will
+ move, and a choice of which address stays as the contact address (A's or
+ B's).
+4. Confirm. The summary says a merge can't be undone.
+
+The merge happens in one store transaction. Afterwards, both people's
+methods point to the survivor, the other `users` row is gone, and notices go
+to both former contact addresses.
+
+### 7.3 The merge registry
+
+Every table with a column that holds a person's address declares one rule:
+
+- **move**: rewrite the address to the survivor's. Examples are
+ `cli_tokens`, `sessions`, `app_stars` and alert subscriptions.
+- **union**: move, but resolve key clashes. `memberships` keeps the higher
+ role per team (owner beats member). If both are members of a paid team,
+ the merge must not leave a seat billed twice, and the builder settles seat
+ counts with the billing code's existing rules.
+- **history**: leave as recorded. Examples are `audit`, the `*_by` columns
+ and billing records.
+- **refuse**: block the merge, with a clear reason, while a row of this kind
+ exists. An example is a live pending action or step-up for B.
+
+A test reads the live schema, finds every column that holds a person's
+address (by name: `address`, `owner_address`, `*_by`, `invited_by`, and any
+the registry adds), and fails if a table isn't in the registry. That stops a
+future table from silently orphaning rows on a merge.
+
+The `grants` table (Keymail grant per address) and `owners` (legacy) need
+their own rules. The builder sets them from what the code still reads, and
+says so in the plan.
+
+## 8. Re-confirmation (step-up)
+
+- **A person who holds a Keymail method always re-confirms with Keymail**,
+ whichever method this session used. Linking a provider must never weaken
+ a passkey person's step-up.
+- Otherwise `email` is unchanged (a fresh link or code to that address).
+- Otherwise `google`, `apple` and `github` get an emailed code to the
+ person's contact address (P6).
+
+This isn't a downgrade (§3), because email is already an allowed way to sign
+in for these people. A console with no mailer can't step up provider
+sessions, so for those people sensitive actions are refused with a message
+that says why. The console's start-up log warns when a provider is on
+without a mailer.
+
+The CLI approval page (`authcli.go`) needs nothing new beyond this: it uses
+the same session and the same step-up gate.
+
+## 9. Rate limits and abuse
+
+- There is no new-person limit today: the email limits count submits, sends
+ and wrong codes (`emailsignin_limits.go:19`), and `finishSignin` creates
+ users ungated. This work adds one **new-person budget**, per client IP and
+ overall, checked where a `users` row would be created by any path (email,
+ Keymail, provider). Returning sign-ins don't count against it. Provider
+ traffic never spends the email-send budgets, apart from the codes it
+ actually sends.
+- Provider callbacks are limited per client IP, as the email submit is.
+- §4.2 step 4 and §6.2 codes use the existing email-challenge store and its
+ caps.
+- A provider error, or a state or nonce mismatch, shows one plain
+ "That sign-in didn't work. Try again." page and logs a reason code, never
+ the provider's raw response.
+
+## 10. Copy
+
+New on-screen text includes: the three buttons, the "other ways to sign in"
+heading, the "Sign-in methods" section and its actions, the merge screens,
+the confirmation-code request for §4.2 step 4, the GitHub "no verified email"
+message, the "this console can't finish this sign-in" message, and the
+notices. All of it goes through copy review before it goes into templates or
+`signincopy.go`, in the house voice (no em dashes). Provider button text and
+logos follow each provider's brand guidelines, which are strict for Apple.
+
+## 11. Tests that prove it
+
+- Each provider runs against a fake provider (an httptest authorize, token
+ and user/JWKS server), wired through the real console handlers, not a
+ stubbed handler:
+ - first sign-in creates a person
+ - second sign-in finds the same person
+ - state, nonce and PKCE mismatches are refused
+ - an unverified email is refused
+ - the Apple cross-site POST callback works with real cookie attributes
+- Configuration: none set gives today's page (golden compare), all set shows
+ the button, some set means start-up fails and names the missing setting.
+- §6.2: a GitHub address matching an existing person needs the code. A
+ Google non-Gmail address without `hd` needs the code. A Google `hd` match
+ and an Apple verified address don't.
+- Merge: the registry completeness test (§7.3). A merge with overlapping
+ teams keeps the higher role. CLI tokens keep working for the survivor. Old
+ sessions of B now act as the survivor. A refused merge changes nothing.
+- Step-up per method: the emailed code for each provider, Keymail for a
+ person holding Keymail whatever the session's method, refusal of an
+ unknown method, and the no-mailer refusal.
+- Removal ends that method's sessions and prevents automatic relinking.
+- Operators: merge and contact change are refused.
+- Device ordering: a table of user agents and `Sec-CH-UA-Platform` values
+ against the expected primary.
+
+## 12. Rollout
+
+The code is dormant until configured, so it can merge on review and CI under
+the standing rule, then ship in a normal release, dev first.
+
+What Paul does outside the repo (the "platform default" registrations, P4):
+
+1. **Google:** create an OAuth client (Web) in a Carloku Google Cloud
+ project, add the carloku.com redirect URLs, and publish the consent screen
+ (in-production status, with the app name, logo and privacy link).
+2. **Apple:** in the Apple Developer account, create a Services ID with the
+ carloku.com domain and return URL and a Sign in with Apple key (`.p8`),
+ and register carloku.com for Private Email Relay.
+3. **GitHub:** create an OAuth App under the `carlosframework` org with the
+ carloku.com callback URL.
+4. Put the secrets in 1Password and deliver them to the flagship console's
+ environment (or through `carlos secrets set` once #453 is in), then
+ restart it on a roll.
+
+Dev gets its own registrations pointing at the dev console's address, so it
+can be checked end to end before flagship. Live checks on each: sign up with
+each provider, sign in again, link a second method, merge a Hide My Email
+person into a real-address person, approve a CLI login after each kind of
+sign-in, and trigger a step-up with each kind.
+
+Self-hosters get a docs page: what to register with each provider, the
+callback paths, the settings, and the Apple relay step.
+
+## 13. Left to the builder
+
+- Callback paths, table and column names, and the provider interface's
+ shape.
+- TLS-trusted ID tokens or JWKS verification (§5), stated and tested.
+- How the Apple flow keeps state across the cross-site POST (§5.2).
+- The merge rules for `grants` and `owners` (§7.3), and seat settlement for
+ shared paid teams.
+- How the provider buttons are drawn (inline SVG, assets), within the
+ providers' brand rules.
+- Splitting this into plans. A natural cut: (1) the person and method model,
+ migration, invites by any held address, and Your settings listing; (2)
+ Google and GitHub with step-up; (3) Apple; (4) link, unlink and merge.
+
+## 14. Builder check (rev 1 → rev 2)
+
+Astra read rev 1 as a builder. Its questions, and how they were settled
+(all as the designer's calls unless marked otherwise):
+
+1. §3 and §4.2 contradicted each other on automatic linking. Settled:
+ automatic linking only for a trusted address, never to a Keymail holder
+ (§4.2 step 2, §3).
+2. Google has no forced re-login, so P6 leaves all three providers stepping
+ up by email (P6, §5.1, §8). Keymail holders always step up with Keymail.
+3. What a vouched address owns. Settled: holding means an `email` method.
+ `vouched_email` is informational and later changes don't move anything
+ (§6.1, §4.4).
+4. What removal revokes. Settled: that method's sessions and step-ups, not
+ CLI tokens, plus a removed marker against relinking (§4.3, §6.1).
+5. Operators and merge. Settled: refused for operators and allowlisted
+ addresses (§7.1).
+6. Which events share the sign-up limit. Settled: a new new-person budget
+ across all paths (§9), since none exists today.
+
+It also corrected two claims about the code: the step-up fail-closed path
+(§6.1) and the existing sign-up limits (§9).
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index 6c4607db8..a9cf39535 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -1510,6 +1510,11 @@ func (s *Server) notifyCLIIssued(address, rawToken string) {
}
}
+type methodRow struct {
+ Kind, Identity string
+ AddedAt, LastUsed time.Time
+}
+
// cliPage is the approval and tokens pages' data. It embeds page so the
// shared chrome ("top"/"bottom") keeps working unchanged.
type cliPage struct {
@@ -1522,6 +1527,7 @@ type cliPage struct {
Console string // this deployment's origin — the -console the CLI needs
Request *CLIAuthRequest
Tokens []CLIToken
+ Methods []methodRow
Days int
// ServiceAccounts maps a service credential's account id to that
// account's sqid, so the read-only mirror can say WHERE a row is managed
@@ -1533,6 +1539,10 @@ type cliPage struct {
ServiceAccounts map[int64]string
}
+func (p cliPage) MethodsText(id string) string {
+ return copyText("methods."+id, "address", p.Address)
+}
+
func (s *Server) renderCLI(w http.ResponseWriter, status int, name string, p cliPage) {
s.chrome(&p.page)
_ = s.writeTemplate(w, status, name, p)
@@ -1720,6 +1730,23 @@ func (s *Server) handleCLITokens(w http.ResponseWriter, r *http.Request) {
p := cliPage{page: page{Title: "Your settings", Address: addr, CSRF: raw, MobileParent: &navLink{Label: "Accounts", Href: "/accounts"}},
Tokens: toks, Console: s.cfg.Origin, Days: int(CLITokenTTL / (24 * time.Hour)),
ServiceAccounts: s.serviceAccountSqids(toks)}
+ methods, err := s.store.SignInMethodsFor(addr)
+ if err != nil {
+ log.Printf("console: settings sign-in methods: %v", err)
+ } else {
+ for _, m := range methods {
+ var kind string
+ switch m.Kind {
+ case MethodEmail:
+ kind = copyText("methods.kind_email")
+ case MethodKeymail:
+ kind = copyText("methods.kind_keymail")
+ default:
+ continue
+ }
+ p.Methods = append(p.Methods, methodRow{Kind: kind, Identity: m.Subject, AddedAt: m.AddedAt, LastUsed: m.LastUsedAt})
+ }
+ }
p.Flash, p.FlashErr = s.takeFlash(w, r)
s.renderCLI(w, http.StatusOK, "settings", p)
}
diff --git a/internal/console/billingseats.go b/internal/console/billingseats.go
index 4deb7f2e8..7a6d9bfba 100644
--- a/internal/console/billingseats.go
+++ b/internal/console/billingseats.go
@@ -199,7 +199,8 @@ var errAdmitRead = errors.New("console: accept: read failed")
// membership transition; a billing team's join is admitted under the billing
// hold (admitSeatLocked). The error accompanies the outcome: a refusal's
// reason (a billingRefusal or a planCapError) with admitRefused, otherwise
-// what to log.
+// what to log. addr is the session's person; membership and seat counts use
+// that person even when the invite names another address they hold.
func (s *Server) admitMember(ctx context.Context, acct *Account, token, addr string, now time.Time) (admitOutcome, error) {
defer s.lockMembers(acct.Sqid)()
inv, err := s.store.PendingInviteFor(token, addr, now)
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go
index 344e7f697..c261d6080 100644
--- a/internal/console/emailsignin.go
+++ b/internal/console/emailsignin.go
@@ -249,54 +249,64 @@ func safeNext(raw string) string {
}
// finishSignin is what signing in does once a door has proved an address,
-// shared by the Keymail callback and the email link and code handlers: record
-// the user, store the Keymail grant (Keymail only), open a session that
-// remembers its method, set the cookies, then land. An email sign-in also
+// shared by the Keymail callback and the email link and code handlers: resolve
+// the person, store the Keymail grant (Keymail only), open a session that
+// remembers its method row, set the cookies, then land. An email sign-in also
// records a step-up at the moment of use, the same proof a step-up would ask
// for minutes later. The current account is resolved (minted for a new user)
// before any redirect, so onboarding runs before next.
-func (s *Server) finishSignin(w http.ResponseWriter, r *http.Request, addr, keymailToken, method, next string) {
+func (s *Server) finishSignin(w http.ResponseWriter, r *http.Request, proved, keymailToken, method, next string) {
+ fresh, err := s.store.PersonWouldBeNew(method, proved)
+ if err != nil {
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not record your account. Please try again.")
+ return
+ }
+ if fresh && !s.limits.newPerson(s.clientIP(r)) {
+ s.renderMessage(w, r, http.StatusTooManyRequests, copyText("signup.busy_title"), copyText("signup.busy"))
+ return
+ }
now := time.Now()
- created, err := s.store.EnsureUser(addr, now)
+ m, created, err := s.store.ResolveSignIn(method, proved, now)
if err != nil {
s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not record your account. Please try again.")
return
}
+ person := m.Address
if keymailToken != "" {
- if err := s.store.SetGrantToken(addr, keymailToken, now); err != nil {
+ if err := s.store.SetGrantToken(proved, keymailToken, now); err != nil {
s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not store your sign-in grant. Please try again.")
return
}
}
- raw, err := s.store.CreateSessionMethod(addr, keymailToken, method, now)
+ raw, err := s.store.CreateSessionVia(person, keymailToken, method, m.ID, now)
if err != nil {
s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not create your session. Please try again.")
return
}
- s.noteSeen(addr, now)
- s.auditSignInRow(addr, created)
+ s.noteSeen(person, now)
+ s.auditSignInRow(person, created)
s.clearCookie(w, authCookie)
s.setCookie(w, sessionCookie, raw, int(SessionTTL.Seconds()))
if created {
s.setCookie(w, welcomeCookie, "1", 300)
}
if method == MethodEmail {
- if err := s.store.RecordStepUp(raw, addr, now, now); err != nil {
+ if err := s.store.RecordStepUp(raw, person, now, now); err != nil {
// Not fatal: the session is good, and the first sensitive action
// will ask for a fresh proof.
- log.Printf("console: step-up record for %s: %v", addr, err)
+ log.Printf("console: step-up record for %s: %v", person, err)
}
}
if n := safeNext(next); n != "" {
- if _, err := s.currentAccount(r.Context(), addr); err != nil {
- log.Printf("console: landing for %s: %v", addr, err)
+ if _, err := s.currentAccount(r.Context(), person); err != nil {
+ log.Printf("console: landing for %s: %v", person, err)
s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not open your account. Please try again.")
return
}
http.Redirect(w, r, n, http.StatusSeeOther)
return
}
- s.redirectToCurrentAccount(w, r, addr, http.StatusSeeOther)
+ s.redirectToCurrentAccount(w, r, person, http.StatusSeeOther)
}
// renderLinkExpired is the answer to an unknown, expired or spent link.
diff --git a/internal/console/emailsignin_limits.go b/internal/console/emailsignin_limits.go
index f9955dc6c..c7c297cad 100644
--- a/internal/console/emailsignin_limits.go
+++ b/internal/console/emailsignin_limits.go
@@ -21,6 +21,8 @@ const (
signinPerAddrDay = 20 // sign-in emails per address
signinPerIPHour = 10 // sign-in emails per IP
signinGlobalHour = 200 // sign-in emails console-wide
+ newPersonPerIPHour = 10 // new people per IP
+ newPersonGlobalHour = 200 // new people console-wide
stepUpPerAddrHour = 10 // step-up emails per address
wrongCodesPerAddrDay = 10 // wrong codes per address
wrongCodesPerIPHour = 30 // wrong codes per IP
@@ -140,7 +142,9 @@ type emailLimits struct {
addrWrong keyedWindow // wrong codes, by address
ipWrong keyedWindow // wrong codes, by IP
- alertConfirms keyedWindow // alert confirmation sends, by alert scope
+ alertConfirms keyedWindow // alert confirmation sends, by alert scope
+ ipNewPeople keyedWindow // new people, by IP
+ globalNewPeople []time.Time // new people, console-wide
sweepNext int // index into sweepWindows() where the next sweep starts
}
@@ -170,7 +174,34 @@ func (l *emailLimits) submit(ip string) bool {
}
func (l *emailLimits) sweepWindows() []*keyedWindow {
- return []*keyedWindow{&l.submits, &l.addrSends, &l.ipSends, &l.stepUps, &l.addrWrong, &l.ipWrong, &l.alertConfirms}
+ return []*keyedWindow{&l.submits, &l.addrSends, &l.ipSends, &l.stepUps, &l.addrWrong, &l.ipWrong, &l.alertConfirms, &l.ipNewPeople}
+}
+
+// newPerson reserves one new-person slot across all sign-in paths (social
+// sign-in spec §9). A refusal charges neither hourly window.
+func (l *emailLimits) newPerson(ip string) bool {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ now := l.clock()
+ hour := now.Add(-time.Hour)
+ l.sweep(now)
+ l.ipNewPeople.trim(ip, now)
+ if l.ipNewPeople.count(ip, hour) >= newPersonPerIPHour {
+ return false
+ }
+ kept := l.globalNewPeople[:0]
+ for _, t := range l.globalNewPeople {
+ if t.After(hour) {
+ kept = append(kept, t)
+ }
+ }
+ l.globalNewPeople = kept
+ if len(kept) >= newPersonGlobalHour {
+ return false
+ }
+ l.ipNewPeople.add(ip, now)
+ l.globalNewPeople = append(l.globalNewPeople, now)
+ return true
}
// sweep is one bounded step of cleanup: it inspects at most limitSweepBudget
diff --git a/internal/console/emailsignin_limits_test.go b/internal/console/emailsignin_limits_test.go
index fffd5ba11..74d7994cd 100644
--- a/internal/console/emailsignin_limits_test.go
+++ b/internal/console/emailsignin_limits_test.go
@@ -19,6 +19,107 @@ func (c *limitClock) advance(d time.Duration) { c.t = c.t.Add(d) }
func newTestLimits(c *limitClock) *emailLimits { return &emailLimits{now: c.now} }
+func TestNewPersonBudget(t *testing.T) {
+ c := newLimitClock()
+ l := newTestLimits(c)
+ for i := 0; i < 10; i++ {
+ if !l.newPerson("a") {
+ t.Fatalf("new person %d from a refused", i+1)
+ }
+ }
+ for i := 0; i < 200; i++ {
+ if l.newPerson("a") {
+ t.Fatal("11th new person from a allowed")
+ }
+ }
+ if !l.newPerson("b") {
+ t.Fatal("new person from b refused")
+ }
+ // Refusals from a must leave all 189 remaining global slots available.
+ for i := 0; i < 189; i++ {
+ if !l.newPerson(fmt.Sprintf("other%d", i)) {
+ t.Fatalf("global slot %d refused after IP refusals", i+12)
+ }
+ }
+ c.advance(61 * time.Minute)
+ if !l.newPerson("a") {
+ t.Fatal("new person from a refused after the hour")
+ }
+
+ c = newLimitClock()
+ l = newTestLimits(c)
+ for i := 0; i < 200; i++ {
+ if !l.newPerson(fmt.Sprintf("ip%d", i/10)) {
+ t.Fatalf("new person %d console-wide refused", i+1)
+ }
+ }
+ c.advance(30 * time.Minute)
+ for i := 0; i < 20; i++ {
+ if l.newPerson("fresh") {
+ t.Fatal("201st new person console-wide allowed")
+ }
+ }
+ c.advance(31 * time.Minute)
+ for i := 0; i < 10; i++ {
+ if !l.newPerson("fresh") {
+ t.Fatalf("new person %d refused: global refusals charged a window", i+1)
+ }
+ }
+}
+
+func TestNewPersonBudgetConcurrentBoundary(t *testing.T) {
+ for _, global := range []bool{false, true} {
+ t.Run(fmt.Sprintf("global=%v", global), func(t *testing.T) {
+ l := newTestLimits(newLimitClock())
+ ip := func(i int) string { return "a" }
+ cap := 10
+ if global {
+ ip = func(i int) string { return fmt.Sprintf("ip%d", i) }
+ cap = 200
+ }
+ for i := 0; i < cap-1; i++ {
+ if !l.newPerson(ip(i)) {
+ t.Fatal("setup refused")
+ }
+ }
+ var wg sync.WaitGroup
+ var allowed atomic.Int32
+ start := make(chan struct{})
+ for i := 0; i < 32; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ <-start
+ if l.newPerson(ip(cap + i)) {
+ allowed.Add(1)
+ }
+ }(i)
+ }
+ close(start)
+ wg.Wait()
+ if got := allowed.Load(); got != 1 {
+ t.Fatalf("%d concurrent calls allowed at boundary, want 1", got)
+ }
+ })
+ }
+}
+
+func TestNewPersonBudgetSwept(t *testing.T) {
+ c := newLimitClock()
+ l := newTestLimits(c)
+ if !l.newPerson("old") {
+ t.Fatal("first new person refused")
+ }
+ if got := limitKeyCount(l); got != 1 {
+ t.Fatalf("%d keys before sweep, want new-person IP", got)
+ }
+ c.advance(25 * time.Hour)
+ l.submit("live")
+ if got := limitKeyCount(l); got != 1 {
+ t.Fatalf("%d keys after sweep, want only live submit", got)
+ }
+}
+
func TestSigninSendLimits(t *testing.T) {
c := newLimitClock()
l := newTestLimits(c)
@@ -397,21 +498,21 @@ func TestSigninSendSweepIsBounded(t *testing.T) {
func TestSigninSendSweepCleansStaleAcrossCalls(t *testing.T) {
c := newLimitClock()
l := newTestLimits(c)
- // 50 stale keys in each of the seven windows: 350 in all, well over one
- // call's budget, including stepUps and the alert confirmations.
+ // 50 stale keys in each window, well over one call's budget.
+ stale := 50 * len(l.sweepWindows())
for i := 0; i < 50; i++ {
for _, w := range l.sweepWindows() {
w.add(fmt.Sprintf("old%d", i), c.now())
}
}
- if got := limitKeyCount(l); got != 350 {
+ if got := limitKeyCount(l); got != stale {
t.Fatalf("setup: %d keys", got)
}
c.advance(25 * time.Hour)
l.submit("11.0.0.1")
left := limitKeyCount(l)
- if left == 0 || left < 350+1-limitSweepBudget {
- t.Fatalf("one submit left %d of 351 keys; want a bounded step (dropped at most %d)", left, limitSweepBudget)
+ if left == 0 || left < stale+1-limitSweepBudget {
+ t.Fatalf("one submit left %d of %d keys; want a bounded step (dropped at most %d)", left, stale+1, limitSweepBudget)
}
for i := 0; i < 20 && limitKeyCount(l) > 1; i++ {
l.submit("11.0.0.1")
diff --git a/internal/console/invite_held_address_test.go b/internal/console/invite_held_address_test.go
new file mode 100644
index 000000000..396ca6525
--- /dev/null
+++ b/internal/console/invite_held_address_test.go
@@ -0,0 +1,214 @@
+package console
+
+import (
+ "context"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+)
+
+func addInviteHeldMethod(t *testing.T, st *Store, kind string, now time.Time) {
+ t.Helper()
+ if _, err := st.EnsureUser("person@example.test", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.db.Exec(`INSERT INTO sign_in_methods (kind, subject, address, added_at)
+VALUES (?, ?, ?, ?)`, kind, "alias@example.test", "person@example.test", now.Unix()); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func wantInviteRole(t *testing.T, st *Store, accountID int64, address, want string) {
+ t.Helper()
+ if role, err := st.Role(accountID, address); err != nil || role != want {
+ t.Fatalf("Role(%d, %q) = %q, %v; want %q", accountID, address, role, err, want)
+ }
+}
+
+func TestInviteAcceptedByHeldAddress(t *testing.T) {
+ for _, kind := range []string{MethodEmail, MethodKeymail} {
+ t.Run(kind, func(t *testing.T) {
+ st := openTestStore(t)
+ now := time.Now()
+ addInviteHeldMethod(t, st, kind, now)
+ if err := st.CreateAccount(42, "cdef", "A", "owner@example.test", now); err != nil {
+ t.Fatal(err)
+ }
+ token, err := st.CreateInvite(42, "alias@example.test", "owner@example.test", now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if inv, err := st.PendingInviteFor(token, "person@example.test", now); err != nil || inv.AccountID != 42 || inv.Address != "alias@example.test" {
+ t.Errorf("PendingInviteFor = %+v, %v", inv, err)
+ }
+ if id, err := st.AcceptInvite(token, "person@example.test", now); err != nil || id != 42 {
+ t.Fatalf("AcceptInvite = %d, %v; want 42, nil", id, err)
+ }
+ wantInviteRole(t, st, 42, "person@example.test", RoleMember)
+ wantInviteRole(t, st, 42, "alias@example.test", "")
+ if _, err := st.PendingInviteFor(token, "person@example.test", now); err == nil {
+ t.Error("accepted invite still available for confirmation")
+ }
+ if _, err := st.AcceptInvite(token, "person@example.test", now); err == nil {
+ t.Error("accepted invite worked twice")
+ }
+ })
+ }
+}
+
+func TestInviteRefusedForUnheldAddress(t *testing.T) {
+ for _, tc := range []struct {
+ name, kind, person string
+ removed bool
+ }{
+ {"stranger", MethodEmail, "stranger@example.test", false},
+ {"provider", "google", "person@example.test", false},
+ {"removed-email", MethodEmail, "person@example.test", true},
+ {"removed-keymail", MethodKeymail, "person@example.test", true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ st := openTestStore(t)
+ now := time.Now()
+ addInviteHeldMethod(t, st, tc.kind, now)
+ if tc.removed {
+ if _, err := st.db.Exec(`UPDATE sign_in_methods SET removed_at = ?`, now.Unix()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := st.CreateAccount(42, "cdef", "A", "owner@example.test", now); err != nil {
+ t.Fatal(err)
+ }
+ token, err := st.CreateInvite(42, "alias@example.test", "owner@example.test", now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.PendingInviteFor(token, tc.person, now); err == nil || err.Error() != "console: that invite cannot be used by "+tc.person {
+ t.Errorf("PendingInviteFor refusal = %v", err)
+ }
+ if _, err := st.AcceptInvite(token, tc.person, now); err == nil {
+ t.Error("unheld address accepted")
+ }
+ wantInviteRole(t, st, 42, tc.person, "")
+ wantInviteRole(t, st, 42, "alias@example.test", "")
+ if _, ok := st.PendingInviteAddress(token, now); !ok {
+ t.Error("refused invite was consumed")
+ }
+ })
+ }
+}
+
+func TestInviteHeldAddressRecheckedAtAccept(t *testing.T) {
+ st := openTestStore(t)
+ now := time.Now()
+ addInviteHeldMethod(t, st, MethodEmail, now)
+ if err := st.CreateAccount(42, "cdef", "A", "owner@example.test", now); err != nil {
+ t.Fatal(err)
+ }
+ token, err := st.CreateInvite(42, "alias@example.test", "owner@example.test", now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.PendingInviteFor(token, "person@example.test", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.db.Exec(`UPDATE sign_in_methods SET removed_at = ?`, now.Unix()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.AcceptInvite(token, "person@example.test", now); err == nil {
+ t.Error("accept trusted the earlier address check")
+ }
+ wantInviteRole(t, st, 42, "person@example.test", "")
+ wantInviteRole(t, st, 42, "alias@example.test", "")
+ if _, ok := st.PendingInviteAddress(token, now); !ok {
+ t.Error("refused invite was consumed")
+ }
+}
+
+func TestInviteHeldAddressEndToEnd(t *testing.T) {
+ fx, mail := newEmailFixture(t, true)
+ now := time.Now()
+ addInviteHeldMethod(t, fx.st, MethodEmail, now)
+ accountID := testAccountID()
+ if err := fx.st.CreateAccount(accountID, "cdef", "A", "owner@example.test", now); err != nil {
+ t.Fatal(err)
+ }
+ token, err := fx.st.CreateInvite(accountID, "alias@example.test", "owner@example.test", now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ next := "/invite/" + token
+ c := newBrowser(t)
+ if status, _, body := get(t, c, fx.ts.URL+next); status != http.StatusOK || !strings.Contains(body, `value="alias@example.test"`) {
+ t.Fatalf("signed-out invite = %d, missing alias prefill", status)
+ }
+ lookupAnswers(fx, "alias@example.test", http.StatusNotFound)
+ code, _ := askSignin(t, fx, mail, c, "alias@example.test", next)
+ if status, loc, _ := postCode(t, fx, c, code); status != http.StatusSeeOther || loc != next {
+ t.Fatalf("sign-in = %d -> %q; want 303 -> %q", status, loc, next)
+ }
+ raw := emailSession(t, fx, c, "person@example.test")
+ if status, _, body := get(t, c, fx.ts.URL+next); status != http.StatusOK || !strings.Contains(body, `action="`+next+`"`) {
+ t.Fatalf("invite page = %d, missing confirm form", status)
+ }
+ wantInviteRole(t, fx.st, accountID, "person@example.test", "")
+ if status, _, _ := postForm(t, c, fx.ts.URL+next, url.Values{}); status != http.StatusForbidden {
+ t.Fatalf("accept without CSRF = %d; want 403", status)
+ }
+ wantInviteRole(t, fx.st, accountID, "person@example.test", "")
+ if status, loc, _ := postForm(t, c, fx.ts.URL+next, url.Values{"csrf": {raw}}); status != http.StatusSeeOther || loc != "/a/cdef/" {
+ t.Fatalf("accept = %d -> %q; want 303 -> /a/cdef/", status, loc)
+ }
+ wantInviteRole(t, fx.st, accountID, "person@example.test", RoleMember)
+ wantInviteRole(t, fx.st, accountID, "alias@example.test", "")
+ if id, err := fx.st.LastAccount("person@example.test"); err != nil || id != accountID {
+ t.Fatalf("LastAccount = %d, %v; want %d", id, err, accountID)
+ }
+ if status, _, _ := get(t, c, fx.ts.URL+"/a/cdef/"); status != http.StatusOK {
+ t.Fatalf("joined account = %d; want 200", status)
+ }
+}
+
+func TestInviteSeatPathHeldAddress(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ now := time.Now()
+ addInviteHeldMethod(t, o.st, MethodEmail, now)
+ token := o.authorisedInvite(t, "alias@example.test")
+ out, err := o.srv.admitMember(context.Background(), o.acct, token, "person@example.test", now)
+ if err != nil || out != admitJoined {
+ t.Fatalf("admitMember = %v, %v; want joined", out, err)
+ }
+ wantInviteRole(t, o.st, o.acct.ID, "person@example.test", RoleMember)
+ wantInviteRole(t, o.st, o.acct.ID, "alias@example.test", "")
+ if o.members(t) != 11 || o.seatQty(t) != 11 {
+ t.Fatalf("members %d seats %d; want 11 and 11", o.members(t), o.seatQty(t))
+ }
+ op := o.lastOp(t)
+ if op.Kind != opSeat || op.State != opApplied || op.InviteToken != token || op.AuthorisedBy != token ||
+ op.StartQuantity == nil || *op.StartQuantity != 10 || changeBodyOf(t, op.Prepared).Proration != billing.ProrateNow {
+ t.Fatalf("seat op = %+v", op)
+ }
+ if a := o.authorisation(t, token); a == nil || a.ConsumedAt.IsZero() {
+ t.Fatalf("authorisation not consumed: %+v", a)
+ }
+ if b := o.billingRow(t); b.PaidSeats != 11 || b.Seats != 11 {
+ t.Fatalf("billing row seats %d paid %d; want 11 and 11", b.Seats, b.PaidSeats)
+ }
+ if o.pendingInvite(t, token) {
+ t.Fatal("joined invite still pending")
+ }
+ o.reset()
+ second := o.authorisedInvite(t, "alias@example.test")
+ if out, err := o.srv.admitMember(context.Background(), o.acct, second, "person@example.test", now); err != nil || out != admitJoined {
+ t.Fatalf("existing member accept = %v, %v; want joined", out, err)
+ }
+ if o.members(t) != 11 || o.seatQty(t) != 11 || o.counts()["Send"] != 0 {
+ t.Fatalf("existing member changed seats: members %d seats %d calls %v", o.members(t), o.seatQty(t), o.counts())
+ }
+ if a := o.authorisation(t, second); a == nil || !a.ConsumedAt.IsZero() {
+ t.Fatalf("existing member consumed a seat authorisation: %+v", a)
+ }
+}
diff --git a/internal/console/newperson_test.go b/internal/console/newperson_test.go
new file mode 100644
index 000000000..f2efaf10c
--- /dev/null
+++ b/internal/console/newperson_test.go
@@ -0,0 +1,140 @@
+package console
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func exhaustNewPersonBudget(t *testing.T, fx *consoleFixture, global bool) {
+ t.Helper()
+ c := newLimitClock()
+ fx.srv.limits.mu.Lock()
+ fx.srv.limits.now = c.now
+ fx.srv.limits.mu.Unlock()
+ n := 10
+ if global {
+ n = 200
+ }
+ for i := 0; i < n; i++ {
+ ip := "127.0.0.1"
+ if global {
+ ip = fmt.Sprintf("192.0.2.%d", i/10+1)
+ }
+ if !fx.srv.limits.newPerson(ip) {
+ t.Fatalf("budget setup refused new person %d", i+1)
+ }
+ }
+}
+
+func assertNoNewPerson(t *testing.T, fx *consoleFixture, addr string) {
+ t.Helper()
+ if n := userRows(t, fx, addr); n != 0 {
+ t.Errorf("refusal created %d user rows", n)
+ }
+ for _, table := range []string{"sign_in_methods", "sessions", "grants"} {
+ var n int
+ if err := fx.st.db.QueryRow(`SELECT COUNT(*) FROM `+table+` WHERE address = ?`, addr).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ if n != 0 {
+ t.Errorf("refusal created %d rows in %s", n, table)
+ }
+ }
+ if accts, err := fx.st.AccountsFor(addr); err != nil || len(accts) != 0 {
+ t.Errorf("accounts after refusal = %v, %v", accts, err)
+ }
+}
+
+func TestNewPersonBudgetRefusalWritesNothing(t *testing.T) {
+ for _, global := range []bool{false, true} {
+ for _, path := range []string{"code", "link", "keymail"} {
+ t.Run(fmt.Sprintf("%s/global=%v", path, global), func(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ exhaustNewPersonBudget(t, fx, global)
+ const addr = "newperson@example.com"
+ c := newBrowser(t)
+ var status int
+ var body string
+ if path == "keymail" {
+ fx.setUser(addr)
+ status, _ = keymailWalk(t, fx, c, "", "newperson-code")
+ } else {
+ lookupAnswers(fx, addr, http.StatusNotFound)
+ code, link := askSignin(t, fx, m, c, addr, "")
+ if path == "code" {
+ status, _, body = postCode(t, fx, c, code)
+ } else {
+ _, _, nonce := openLink(t, fx, c, link)
+ status, _, body = postLink(t, fx, c, link, nonce)
+ }
+ }
+ if status != http.StatusTooManyRequests {
+ t.Fatalf("sign-in = %d, want 429: %s", status, body)
+ }
+ if path != "keymail" && !strings.Contains(body, copyText("signup.busy")) {
+ t.Errorf("refusal missing approved copy: %s", body)
+ }
+ assertNoNewPerson(t, fx, addr)
+ if raw := browserCookie(t, fx, c, sessionCookie); raw != "" {
+ t.Error("refusal set a session cookie")
+ }
+ })
+ }
+ }
+}
+
+func TestNewPersonBudgetSparesReturning(t *testing.T) {
+ for _, legacy := range []bool{false, true} {
+ t.Run(fmt.Sprintf("legacy=%v", legacy), func(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ const addr = "returning@example.com"
+ if legacy {
+ if _, err := fx.st.EnsureUser(addr, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ } else if _, _, err := fx.st.ResolveSignIn(MethodEmail, addr, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ exhaustNewPersonBudget(t, fx, true)
+ lookupAnswers(fx, addr, http.StatusNotFound)
+ c := newBrowser(t)
+ code, _ := askSignin(t, fx, m, c, addr, "")
+ status, _, body := postCode(t, fx, c, code)
+ if status != http.StatusSeeOther {
+ t.Fatalf("returning sign-in = %d: %s", status, body)
+ }
+ emailSession(t, fx, c, addr)
+ // Even consulting the budget for a returning person is a failure.
+ fx.srv.limits.mu.Lock()
+ fx.srv.limits.now = func() time.Time { panic("returning person touched budget") }
+ fx.srv.limits.mu.Unlock()
+ w := httptest.NewRecorder()
+ fx.srv.finishSignin(w, httptest.NewRequest(http.MethodGet, "/", nil), addr, "", MethodEmail, "")
+ if w.Code != http.StatusSeeOther {
+ t.Fatalf("returning finishSignin = %d", w.Code)
+ }
+ })
+ }
+}
+
+func TestNewPersonBudgetLookupError(t *testing.T) {
+ fx := newConsoleFixture(t)
+ if err := fx.st.Close(); err != nil {
+ t.Fatal(err)
+ }
+ fx.srv.limits.now = func() time.Time { panic("lookup error touched budget") }
+ w := httptest.NewRecorder()
+ fx.srv.finishSignin(w, httptest.NewRequest(http.MethodGet, "/", nil), "newperson@example.com", "", MethodEmail, "")
+ if w.Code != http.StatusInternalServerError || !strings.Contains(w.Body.String(), "Could not record your account. Please try again.") {
+ t.Fatalf("lookup error = %d: %s", w.Code, w.Body.String())
+ }
+ for _, ck := range w.Result().Cookies() {
+ if ck.Name == sessionCookie {
+ t.Error("lookup error set a session cookie")
+ }
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index 1883966c3..9bffd5743 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -76,6 +76,7 @@ var tmplFS embed.FS
var templates = template.Must(template.New("").Funcs(template.FuncMap{
"fmtTime": func(t time.Time) string { return t.UTC().Format("2006-01-02 15:04 UTC") },
+ "fmtDay": func(t time.Time) string { return t.UTC().Format("2 Jan 2006") },
// billingText is a billing page string (billingpage_copy.go).
"billingText": func(key string) string { return billingCopy[key] },
// alertText is an Alerts page or alert door string (alertpages.go).
@@ -3595,11 +3596,10 @@ func (s *Server) invitationGone(w http.ResponseWriter, r *http.Request) {
// top-level navigation (discussion #219, item 4). Links already sent keep
// working; they land on this page.
//
-// It requires a session as the invited address: the link reaches one
-// address and is worthless to anyone else. Signed out, it is the front page
-// with the invited address filled in and next set back to this link, so
-// either sign-in door returns here (spec 8). An unknown or spent token gets
-// the plain front page.
+// It requires a session for a person who holds the invited address.
+// Signed out, it is the front page with the invited address filled in and
+// next set back to this link, so either sign-in door returns here (spec 8).
+// An unknown or spent token gets the plain front page.
func (s *Server) handleInvitePage(w http.ResponseWriter, r *http.Request) {
token := r.PathValue("token")
addr, raw, ok := s.session(r)
@@ -3642,9 +3642,9 @@ func (s *Server) handleInvitePage(w http.ResponseWriter, r *http.Request) {
// handleAcceptInvite is the confirm page's button: it consumes the invite and
// makes the account the person's current one. Session, then CSRF, then the
-// invite's own gates (AcceptInvite: unused, addressed to this session,
-// unexpired), which play the owner check's part. No passkey step: joining
-// gives the joiner nothing over anybody else, and it is their own choice.
+// invite's own gates (AcceptInvite: unused, addressed to an address the person
+// holds, unexpired), which play the owner check's part. No passkey step:
+// joining gives the joiner nothing over anybody else, and it is their own choice.
func (s *Server) handleAcceptInvite(w http.ResponseWriter, r *http.Request) {
addr, raw, ok := s.session(r)
if !ok {
diff --git a/internal/console/settings_methods_test.go b/internal/console/settings_methods_test.go
new file mode 100644
index 000000000..241a74e04
--- /dev/null
+++ b/internal/console/settings_methods_test.go
@@ -0,0 +1,161 @@
+package console
+
+import (
+ "net/http"
+ "net/url"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+)
+
+func settingsMethodsFixture(t *testing.T) (*consoleFixture, *http.Client) {
+ t.Helper()
+ fx := newConsoleFixture(t)
+ if _, err := fx.st.EnsureUser("a@example.test", time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)); err != nil {
+ t.Fatal(err)
+ }
+ if err := migrateSignInMethods(fx.st.db); err != nil {
+ t.Fatal(err)
+ }
+ raw, err := fx.st.CreateSessionMethod("a@example.test", "", MethodEmail, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ c := newBrowser(t)
+ u, err := url.Parse(fx.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ c.Jar.SetCookies(u, []*http.Cookie{{Name: sessionCookie, Value: raw, Path: "/"}})
+ return fx, c
+}
+
+func settingsMethodsBody(t *testing.T, fx *consoleFixture, c *http.Client) string {
+ t.Helper()
+ status, _, body := get(t, c, fx.ts.URL+"/settings")
+ if status != http.StatusOK {
+ t.Fatalf("GET /settings = %d", status)
+ }
+ return body
+}
+
+func settingsMethodsSection(t *testing.T, body string) string {
+ t.Helper()
+ start := strings.Index(body, "<h2>"+copyText("methods.heading")+"</h2>")
+ end := strings.Index(body, "<h2>Command-line access</h2>")
+ if start < 0 || end <= start {
+ t.Fatal("sign-in methods must appear before Command-line access")
+ }
+ return body[start:end]
+}
+
+func TestSettingsListsMethods(t *testing.T) {
+ fx, c := settingsMethodsFixture(t)
+ added := time.Date(2026, 11, 2, 10, 0, 0, 0, time.UTC)
+ if _, _, err := fx.st.ResolveSignIn(MethodKeymail, "a@example.test", added); err != nil {
+ t.Fatal(err)
+ }
+ used := time.Date(2026, 11, 4, 0, 30, 0, 0, time.FixedZone("UTC+2", 2*60*60))
+ if _, _, err := fx.st.ResolveSignIn(MethodKeymail, "a@example.test", used); err != nil {
+ t.Fatal(err)
+ }
+ section := settingsMethodsSection(t, settingsMethodsBody(t, fx, c))
+ for _, want := range []string{
+ copyText("methods.lede", "address", "a@example.test"),
+ copyText("methods.kind_email"), copyText("methods.kind_keymail"),
+ copyText("methods.col_method"), copyText("methods.col_identity"),
+ copyText("methods.col_added"), copyText("methods.col_used"),
+ "<td>a@example.test</td>", `<td class="added">1 Nov 2026</td>`,
+ `<td class="added">2 Nov 2026</td>`, "<td>3 Nov 2026</td>",
+ } {
+ if !strings.Contains(section, want) {
+ t.Errorf("methods section missing %q", want)
+ }
+ }
+ if strings.Contains(section, "<button") || strings.Contains(section, "<form") {
+ t.Error("methods section must be read-only")
+ }
+}
+
+func TestSettingsMethodsNeverUsed(t *testing.T) {
+ fx, c := settingsMethodsFixture(t)
+ section := settingsMethodsSection(t, settingsMethodsBody(t, fx, c))
+ if !strings.Contains(section, copyText("methods.never_used")) {
+ t.Error("unused method missing approved never-used text")
+ }
+}
+
+func TestSettingsMethodsOnlyOwn(t *testing.T) {
+ fx, c := settingsMethodsFixture(t)
+ if _, _, err := fx.st.ResolveSignIn(MethodEmail, "b@example.test", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.db.Exec(`INSERT INTO sign_in_methods
+(kind, subject, address, label, added_at) VALUES ('keymail', 'alias@example.test', 'a@example.test', 'unused label', 1)`); err != nil {
+ t.Fatal(err)
+ }
+ body := settingsMethodsBody(t, fx, c)
+ section := settingsMethodsSection(t, body)
+ if strings.Contains(body, "b@example.test") {
+ t.Error("another person's method appeared on settings")
+ }
+ if !strings.Contains(section, "<td>alias@example.test</td>") || strings.Contains(section, "unused label") {
+ t.Error("method identity must use its subject")
+ }
+}
+
+func TestSettingsMethodsExcludeRemoved(t *testing.T) {
+ fx, c := settingsMethodsFixture(t)
+ if _, err := fx.st.db.Exec(`INSERT INTO sign_in_methods
+(kind, subject, address, added_at, removed_at) VALUES ('keymail', 'removed@example.test', 'a@example.test', 1, 2)`); err != nil {
+ t.Fatal(err)
+ }
+ body := settingsMethodsBody(t, fx, c)
+ settingsMethodsSection(t, body)
+ if strings.Contains(body, "removed@example.test") {
+ t.Error("removed method appeared on settings")
+ }
+}
+
+func TestSettingsMethodsDatesDoNotWrap(t *testing.T) {
+ fx, c := settingsMethodsFixture(t)
+ body := settingsMethodsBody(t, fx, c)
+ section := settingsMethodsSection(t, body)
+ if !strings.Contains(section, "<div class=\"tablewrap\">\n<table class=\"methods\">") {
+ t.Error("methods table needs its class inside a tablewrap")
+ }
+ if !strings.Contains(body, ".methods td:nth-child(3), .methods td:nth-child(4) { white-space: nowrap; }") {
+ t.Error("rendered layout must keep both method date cells on one line")
+ }
+}
+
+func TestSettingsMethodsHideAddedOnPhones(t *testing.T) {
+ fx, c := settingsMethodsFixture(t)
+ body := settingsMethodsBody(t, fx, c)
+ section := settingsMethodsSection(t, body)
+ if !strings.Contains(section, `<th class="added">`+copyText("methods.col_added")+`</th>`) {
+ t.Error("Added header needs the phone visibility class")
+ }
+ if !strings.Contains(section, `<td class="added">1 Nov 2026</td>`) {
+ t.Error("Added cells need the phone visibility class")
+ }
+ phoneRule := regexp.MustCompile(`(?s)@media\s*\(max-width:\s*40rem\)\s*\{(?:[^{}]|\{[^{}]*\})*?table\.methods\s+\.added\s*\{\s*display:\s*none;\s*\}`)
+ if !phoneRule.MatchString(body) {
+ t.Error("rendered layout must hide methods Added cells inside the 40rem phone breakpoint")
+ }
+}
+
+func TestSettingsMethodsReadErrorKeepsCLIAccess(t *testing.T) {
+ fx, c := settingsMethodsFixture(t)
+ if _, err := fx.st.db.Exec(`DROP TABLE sign_in_methods`); err != nil {
+ t.Fatal(err)
+ }
+ body := settingsMethodsBody(t, fx, c)
+ if strings.Contains(body, copyText("methods.heading")) {
+ t.Error("failed methods query must omit the section")
+ }
+ if !strings.Contains(body, "<h2>Command-line access</h2>") {
+ t.Error("failed methods query hid Command-line access")
+ }
+}
diff --git a/internal/console/signincopy.go b/internal/console/signincopy.go
index 9f1a848d5..18835b295 100644
--- a/internal/console/signincopy.go
+++ b/internal/console/signincopy.go
@@ -52,6 +52,9 @@ var signinCopy = map[string]string{
// a programming error and panics, so a typo cannot ship blank copy.
func copyText(id string, kv ...string) string {
text, ok := signinCopy[id]
+ if !ok {
+ text, ok = socialSigninCopy[id]
+ }
if !ok {
panic("console: unknown copy id " + id)
}
diff --git a/internal/console/signinmethods_store.go b/internal/console/signinmethods_store.go
new file mode 100644
index 000000000..cf75813fc
--- /dev/null
+++ b/internal/console/signinmethods_store.go
@@ -0,0 +1,156 @@
+package console
+
+import (
+ "database/sql"
+ "time"
+)
+
+type SignInMethod struct {
+ ID int64
+ Kind, Subject string
+ Address, Label string
+ AddedAt, LastUsedAt time.Time
+}
+
+func migrateSignInMethods(db sqlExecer) error {
+ for _, stmt := range []string{
+ `CREATE TABLE IF NOT EXISTS sign_in_methods (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ kind TEXT NOT NULL,
+ subject TEXT NOT NULL,
+ address TEXT NOT NULL,
+ label TEXT NOT NULL DEFAULT '',
+ vouched_email TEXT NOT NULL DEFAULT '',
+ vouched_trusted INTEGER NOT NULL DEFAULT 0,
+ added_at INTEGER NOT NULL,
+ last_used_at INTEGER NOT NULL DEFAULT 0,
+ removed_at INTEGER NOT NULL DEFAULT 0,
+ UNIQUE(kind, subject)
+);`,
+ `CREATE INDEX IF NOT EXISTS sign_in_methods_address ON sign_in_methods (address);`,
+ `INSERT INTO sign_in_methods (kind, subject, address, added_at)
+SELECT CASE WHEN u.address IN (SELECT address FROM grants
+ UNION SELECT address FROM sessions WHERE method = 'keymail')
+ THEN 'keymail' ELSE 'email' END,
+ u.address, u.address, u.created_at
+FROM users u
+WHERE NOT EXISTS (SELECT 1 FROM sign_in_methods m WHERE m.address = u.address)
+ON CONFLICT(kind, subject) DO NOTHING;`,
+ } {
+ if _, err := db.Exec(stmt); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+const signInMethodColumns = `id, kind, subject, address, label, added_at, last_used_at`
+
+func scanSignInMethod(row interface{ Scan(...any) error }) (SignInMethod, error) {
+ var m SignInMethod
+ var added, used int64
+ if err := row.Scan(&m.ID, &m.Kind, &m.Subject, &m.Address, &m.Label, &added, &used); err != nil {
+ return SignInMethod{}, err
+ }
+ m.AddedAt = time.Unix(added, 0)
+ if used != 0 {
+ m.LastUsedAt = time.Unix(used, 0)
+ }
+ return m, nil
+}
+
+func lookupSignIn(q sqlQueryRower, kind, subject string) (SignInMethod, bool, error) {
+ m, err := scanSignInMethod(q.QueryRow(`SELECT `+signInMethodColumns+`
+FROM sign_in_methods WHERE kind = ? AND subject = ? AND removed_at = 0`, kind, subject))
+ if err == sql.ErrNoRows {
+ return SignInMethod{}, false, nil
+ }
+ return m, err == nil, err
+}
+
+func (s *Store) LookupSignIn(kind, subject string) (SignInMethod, bool, error) {
+ return lookupSignIn(s.db, kind, subject)
+}
+
+func (s *Store) PersonWouldBeNew(kind, subject string) (bool, error) {
+ var fresh bool
+ err := s.db.QueryRow(`SELECT NOT EXISTS (
+SELECT 1 FROM sign_in_methods WHERE kind = ? AND subject = ?
+) AND NOT EXISTS (SELECT 1 FROM users WHERE address = ?)`, kind, subject, subject).Scan(&fresh)
+ return fresh, err
+}
+
+func (s *Store) ResolveSignIn(kind, subject string, now time.Time) (SignInMethod, bool, error) {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return SignInMethod{}, false, err
+ }
+ defer tx.Rollback()
+ m, found, err := lookupSignIn(tx, kind, subject)
+ if err != nil {
+ return SignInMethod{}, false, err
+ }
+ created := false
+ if !found {
+ res, err := tx.Exec(`INSERT INTO users (address, created_at) VALUES (?, ?)
+ON CONFLICT(address) DO NOTHING`, subject, now.Unix())
+ if err != nil {
+ return SignInMethod{}, false, err
+ }
+ n, err := res.RowsAffected()
+ if err != nil {
+ return SignInMethod{}, false, err
+ }
+ created = n > 0
+ if _, err := tx.Exec(`INSERT INTO sign_in_methods (kind, subject, address, added_at)
+VALUES (?, ?, ?, ?) ON CONFLICT(kind, subject) DO NOTHING`, kind, subject, subject, now.Unix()); err != nil {
+ return SignInMethod{}, false, err
+ }
+ m, found, err = lookupSignIn(tx, kind, subject)
+ if err != nil {
+ return SignInMethod{}, false, err
+ }
+ if !found {
+ return SignInMethod{}, false, sql.ErrNoRows
+ }
+ }
+ if _, err := tx.Exec(`UPDATE sign_in_methods SET last_used_at = ? WHERE id = ?`, now.Unix(), m.ID); err != nil {
+ return SignInMethod{}, false, err
+ }
+ if err := tx.Commit(); err != nil {
+ return SignInMethod{}, false, err
+ }
+ m.LastUsedAt = time.Time{}
+ if now.Unix() != 0 {
+ m.LastUsedAt = time.Unix(now.Unix(), 0)
+ }
+ return m, created, nil
+}
+
+func (s *Store) SignInMethodsFor(address string) ([]SignInMethod, error) {
+ rows, err := s.db.Query(`SELECT `+signInMethodColumns+`
+FROM sign_in_methods WHERE address = ? AND removed_at = 0 ORDER BY added_at, id`, address)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var methods []SignInMethod
+ for rows.Next() {
+ m, err := scanSignInMethod(rows)
+ if err != nil {
+ return nil, err
+ }
+ methods = append(methods, m)
+ }
+ return methods, rows.Err()
+}
+
+func holdsAddressTx(q sqlQueryRower, person, address string) (bool, error) {
+ if address == person {
+ return true, nil
+ }
+ var holds bool
+ err := q.QueryRow(`SELECT EXISTS (SELECT 1 FROM sign_in_methods
+WHERE address = ? AND subject = ? AND kind IN ('email', 'keymail') AND removed_at = 0)`, person, address).Scan(&holds)
+ return holds, err
+}
diff --git a/internal/console/signinmethods_store_test.go b/internal/console/signinmethods_store_test.go
new file mode 100644
index 000000000..613031f41
--- /dev/null
+++ b/internal/console/signinmethods_store_test.go
@@ -0,0 +1,278 @@
+package console
+
+import (
+ "database/sql"
+ "errors"
+ "sync"
+ "testing"
+ "time"
+)
+
+func TestSignInMethodsBackfill(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Unix(1700000000, 0)
+ for _, address := range []string{"a@x.test", "b@x.test", "c@x.test", "d@x.test"} {
+ if _, err := s.EnsureUser(address, now); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := s.SetGrantToken("a@x.test", "grant", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.db.Exec(`INSERT INTO sessions (token_hash, address, created_at, expires_at, method)
+VALUES ('email-session', 'b@x.test', ?, ?, 'email')`, now.Unix(), now.Add(time.Hour).Unix()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.CreateSession("d@x.test", "", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.migrate(); err != nil {
+ t.Fatal(err)
+ }
+ for address, kind := range map[string]string{
+ "a@x.test": "keymail", "b@x.test": "email", "c@x.test": "email", "d@x.test": "keymail",
+ } {
+ methods, err := s.SignInMethodsFor(address)
+ if err != nil || len(methods) != 1 {
+ t.Fatalf("SignInMethodsFor(%q) = %v, %v", address, methods, err)
+ }
+ m := methods[0]
+ if m.Kind != kind || m.Subject != address || m.Address != address || !m.AddedAt.Equal(now) || !m.LastUsedAt.IsZero() {
+ t.Errorf("backfill %q = %+v", address, m)
+ }
+ }
+}
+
+func TestSignInMethodsBackfillIdempotent(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Unix(1700000000, 0)
+ if _, err := s.EnsureUser("a@x.test", now); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 2; i++ {
+ if err := migrateSignInMethods(s.db); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err := s.db.Exec(`UPDATE sign_in_methods SET last_used_at = ?`, now.Add(time.Hour).Unix()); err != nil {
+ t.Fatal(err)
+ }
+ if err := migrateSignInMethods(s.db); err != nil {
+ t.Fatal(err)
+ }
+ methods, err := s.SignInMethodsFor("a@x.test")
+ if err != nil || len(methods) != 1 || !methods[0].LastUsedAt.Equal(now.Add(time.Hour)) {
+ t.Fatalf("after repeated migration = %v, %v", methods, err)
+ }
+ assertSignInCounts(t, s, 1, 1)
+}
+
+func TestResolveSignInCreatesPerson(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Unix(1700000000, 0)
+ m, created, err := s.ResolveSignIn("email", "new@x.test", now)
+ if err != nil || !created || m.Address != "new@x.test" || m.Subject != "new@x.test" || m.Kind != "email" || m.ID == 0 || !m.AddedAt.Equal(now) || !m.LastUsedAt.Equal(now) {
+ t.Fatalf("first ResolveSignIn = %+v, %v, %v", m, created, err)
+ }
+ assertSignInCounts(t, s, 1, 1)
+ next := now.Add(time.Hour)
+ second, created, err := s.ResolveSignIn("email", "new@x.test", next)
+ if err != nil || created || second.ID != m.ID || !second.AddedAt.Equal(now) || !second.LastUsedAt.Equal(next) {
+ t.Fatalf("second ResolveSignIn = %+v, %v, %v", second, created, err)
+ }
+ stored, found, err := s.LookupSignIn("email", "new@x.test")
+ if err != nil || !found || stored != second {
+ t.Fatalf("stored method = %+v, %v, %v; want %+v", stored, found, err, second)
+ }
+ assertSignInCounts(t, s, 1, 1)
+}
+
+func TestResolveSignInExistingUserNoMethod(t *testing.T) {
+ s := openTestStore(t)
+ if err := s.SetLastAccount("op@x.test", 7); err != nil {
+ t.Fatal(err)
+ }
+ m, created, err := s.ResolveSignIn("keymail", "op@x.test", time.Unix(1700000000, 0))
+ if err != nil || created || m.Address != "op@x.test" {
+ t.Fatalf("ResolveSignIn = %+v, %v, %v", m, created, err)
+ }
+ if id, err := s.LastAccount("op@x.test"); err != nil || id != 7 {
+ t.Fatalf("LastAccount = %d, %v", id, err)
+ }
+ assertSignInCounts(t, s, 1, 1)
+}
+
+func TestResolveSignInFollowsMapping(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Unix(1700000000, 0)
+ if _, err := s.EnsureUser("person@x.test", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.db.Exec(`INSERT INTO sign_in_methods (kind, subject, address, label, added_at)
+VALUES ('email', 'alias@x.test', 'person@x.test', 'Alias', ?)`, now.Unix()); err != nil {
+ t.Fatal(err)
+ }
+ m, created, err := s.ResolveSignIn("email", "alias@x.test", now.Add(time.Hour))
+ if err != nil || created || m.Address != "person@x.test" || m.Label != "Alias" {
+ t.Fatalf("ResolveSignIn = %+v, %v, %v", m, created, err)
+ }
+ var n int
+ if err := s.db.QueryRow(`SELECT COUNT(*) FROM users WHERE address = 'alias@x.test'`).Scan(&n); err != nil || n != 0 {
+ t.Fatalf("alias user count = %d, %v", n, err)
+ }
+ assertSignInCounts(t, s, 1, 1)
+}
+
+func TestResolveSignInSecondKindSamePerson(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Unix(1700000000, 0)
+ for i, kind := range []string{"email", "keymail"} {
+ m, created, err := s.ResolveSignIn(kind, "a@x.test", now)
+ if err != nil || created != (i == 0) || m.Address != "a@x.test" || m.Kind != kind {
+ t.Fatalf("ResolveSignIn(%q) = %+v, %v, %v", kind, m, created, err)
+ }
+ }
+ assertSignInCounts(t, s, 1, 2)
+}
+
+func TestResolveSignInConcurrent(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Unix(1700000000, 0)
+ type result struct {
+ method SignInMethod
+ created bool
+ err error
+ }
+ results := make([]result, 8)
+ start := make(chan struct{})
+ var wg sync.WaitGroup
+ for i := range results {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-start
+ results[i].method, results[i].created, results[i].err = s.ResolveSignIn("email", "race@x.test", now)
+ }()
+ }
+ close(start)
+ wg.Wait()
+ created := 0
+ for _, r := range results {
+ if r.err != nil || r.method.ID == 0 || r.method.ID != results[0].method.ID || r.method.Address != "race@x.test" {
+ t.Errorf("concurrent ResolveSignIn = %+v", r)
+ }
+ if r.created {
+ created++
+ }
+ }
+ if created != 1 {
+ t.Fatalf("created count = %d, want 1", created)
+ }
+ assertSignInCounts(t, s, 1, 1)
+}
+
+func TestHoldsAddress(t *testing.T) {
+ s := openTestStore(t)
+ if _, err := s.db.Exec(`INSERT INTO sign_in_methods (kind, subject, address, added_at) VALUES
+('email', 'alias@x.test', 'p@x.test', 1),
+('keymail', 'other@x.test', 'q@x.test', 1),
+('keymail', 'key@x.test', 'p@x.test', 1),
+('google', 'provider@x.test', 'p@x.test', 1)`); err != nil {
+ t.Fatal(err)
+ }
+ check := func(q sqlQueryRower) {
+ t.Helper()
+ for address, want := range map[string]bool{
+ "p@x.test": true, "alias@x.test": true, "other@x.test": false,
+ "nobody@x.test": false, "key@x.test": true, "provider@x.test": false,
+ } {
+ got, err := holdsAddressTx(q, "p@x.test", address)
+ if err != nil || got != want {
+ t.Errorf("holdsAddressTx(%q) = %v, %v; want %v", address, got, err, want)
+ }
+ }
+ }
+ check(s.db)
+ tx, err := s.db.Begin()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback()
+ check(tx)
+}
+
+func TestSignInMethodsReadOnly(t *testing.T) {
+ s := openTestStore(t)
+ if _, found, err := s.LookupSignIn("email", "new@x.test"); err != nil || found {
+ t.Fatalf("missing lookup = %v, %v", found, err)
+ }
+ if got, err := s.PersonWouldBeNew("email", "new@x.test"); err != nil || !got {
+ t.Fatalf("new person = %v, %v", got, err)
+ }
+ assertSignInCounts(t, s, 0, 0)
+ if err := s.SetLastAccount("person@x.test", 7); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.db.Exec(`INSERT INTO sign_in_methods (kind, subject, address, label, added_at) VALUES
+('email', 'later@x.test', 'person@x.test', 'Later', 20),
+('email', 'alias@x.test', 'person@x.test', 'First', 10),
+('keymail', 'alias@x.test', 'person@x.test', 'Second', 10)`); err != nil {
+ t.Fatal(err)
+ }
+ for _, subject := range []string{"person@x.test", "alias@x.test"} {
+ if got, err := s.PersonWouldBeNew("email", subject); err != nil || got {
+ t.Errorf("PersonWouldBeNew(%q) = %v, %v", subject, got, err)
+ }
+ }
+ m, found, err := s.LookupSignIn("email", "alias@x.test")
+ if err != nil || !found || m.Address != "person@x.test" || !m.LastUsedAt.IsZero() {
+ t.Fatalf("lookup = %+v, %v, %v", m, found, err)
+ }
+ methods, err := s.SignInMethodsFor("person@x.test")
+ if err != nil || len(methods) != 3 {
+ t.Fatalf("methods = %+v, %v", methods, err)
+ }
+ for i, label := range []string{"First", "Second", "Later"} {
+ if methods[i].Label != label || !methods[i].LastUsedAt.IsZero() {
+ t.Errorf("method %d = %+v, want %s unused", i, methods[i], label)
+ }
+ }
+ assertSignInCounts(t, s, 1, 3)
+}
+
+func TestResolveSignInRemovedMapping(t *testing.T) {
+ s := openTestStore(t)
+ if _, err := s.db.Exec(`INSERT INTO sign_in_methods (kind, subject, address, added_at, removed_at)
+VALUES ('email', 'alias@x.test', 'person@x.test', 1, 2)`); err != nil {
+ t.Fatal(err)
+ }
+ m, created, err := s.ResolveSignIn("email", "alias@x.test", time.Unix(1700000000, 0))
+ if !errors.Is(err, sql.ErrNoRows) || created || m.ID != 0 {
+ t.Fatalf("removed ResolveSignIn = %+v, %v, %v", m, created, err)
+ }
+ assertSignInCounts(t, s, 0, 1)
+}
+
+func TestResolveSignInRollback(t *testing.T) {
+ s := openTestStore(t)
+ if _, err := s.db.Exec(`CREATE TRIGGER reject_sign_in_use BEFORE UPDATE OF last_used_at ON sign_in_methods
+BEGIN SELECT RAISE(ABORT, 'test refusal'); END`); err != nil {
+ t.Fatal(err)
+ }
+ _, created, err := s.ResolveSignIn("email", "new@x.test", time.Unix(1700000000, 0))
+ if err == nil || created {
+ t.Fatalf("failed ResolveSignIn = %v, %v", created, err)
+ }
+ assertSignInCounts(t, s, 0, 0)
+}
+
+func assertSignInCounts(t *testing.T, s *Store, users, methods int) {
+ t.Helper()
+ var gotUsers, gotMethods int
+ if err := s.db.QueryRow(`SELECT (SELECT COUNT(*) FROM users), (SELECT COUNT(*) FROM sign_in_methods)`).Scan(&gotUsers, &gotMethods); err != nil {
+ t.Fatal(err)
+ }
+ if gotUsers != users || gotMethods != methods {
+ t.Fatalf("counts = users %d, methods %d; want %d, %d", gotUsers, gotMethods, users, methods)
+ }
+}
diff --git a/internal/console/signinmethods_test.go b/internal/console/signinmethods_test.go
new file mode 100644
index 000000000..9c9bd8dd9
--- /dev/null
+++ b/internal/console/signinmethods_test.go
@@ -0,0 +1,207 @@
+package console
+
+import (
+ "net/http"
+ "net/url"
+ "testing"
+ "time"
+)
+
+func TestKeymailSigninRecordsMethod(t *testing.T) {
+ fx := newConsoleFixture(t)
+ const addr = "newcomer@keymail.dev"
+ fx.setUser(addr)
+ c := newBrowser(t)
+ before := time.Now().Truncate(time.Second)
+ if status, loc := keymailWalk(t, fx, c, "", "code-method"); status != http.StatusSeeOther {
+ t.Fatalf("callback = %d -> %q", status, loc)
+ }
+ methods, err := fx.st.SignInMethodsFor(addr)
+ if err != nil || len(methods) != 1 {
+ t.Fatalf("methods = %v, %v; want one", methods, err)
+ }
+ m := methods[0]
+ if m.Kind != MethodKeymail || m.Subject != addr || m.LastUsedAt.Before(before) || m.LastUsedAt.After(time.Now()) {
+ t.Fatalf("method = %+v", m)
+ }
+ if id, ok := fx.st.SessionMethodID(sessionToken(t, fx, c), time.Now()); !ok || id != m.ID {
+ t.Fatalf("session method = %d, %v; want %d, true", id, ok, m.ID)
+ }
+}
+
+func TestEmailSigninRecordsMethod(t *testing.T) {
+ for _, door := range []string{"code", "link"} {
+ t.Run(door, func(t *testing.T) {
+ fx, mail := newEmailFixture(t, true)
+ const addr = "pat@example.test"
+ lookupAnswers(fx, addr, http.StatusNotFound)
+ c := newBrowser(t)
+ if status, _, body := postContinue(t, fx, c, url.Values{"address": {addr}}); status != http.StatusOK {
+ t.Fatalf("continue = %d: %s", status, body)
+ }
+ waitChallengeSent(t, fx, 1)
+ to, code, link := sentSignin(t, mail)
+ if to != addr {
+ t.Fatalf("recipient = %q, want %q", to, addr)
+ }
+ before := time.Now().Truncate(time.Second)
+ var status int
+ if door == "code" {
+ status, _, _ = postCode(t, fx, c, code)
+ } else {
+ pageStatus, _, nonce := openLink(t, fx, c, link)
+ if pageStatus != http.StatusOK || nonce == "" {
+ t.Fatalf("link page = %d, nonce %q", pageStatus, nonce)
+ }
+ status, _, _ = postLink(t, fx, c, link, nonce)
+ }
+ if status != http.StatusSeeOther {
+ t.Fatalf("sign-in = %d", status)
+ }
+ raw := emailSession(t, fx, c, addr)
+ methods, err := fx.st.SignInMethodsFor(addr)
+ if err != nil || len(methods) != 1 {
+ t.Fatalf("methods = %v, %v; want one", methods, err)
+ }
+ m := methods[0]
+ if m.Kind != MethodEmail || m.Subject != addr || m.LastUsedAt.Before(before) || m.LastUsedAt.After(time.Now()) {
+ t.Fatalf("method = %+v", m)
+ }
+ if id, ok := fx.st.SessionMethodID(raw, time.Now()); !ok || id != m.ID {
+ t.Fatalf("session method = %d, %v; want %d, true", id, ok, m.ID)
+ }
+ })
+ }
+}
+
+func TestSigninLandsOnMappedPerson(t *testing.T) {
+ fx, mail := newEmailFixture(t, true)
+ const alias, person = "alias@example.test", "person@example.test"
+ now := time.Now()
+ if _, err := fx.st.EnsureUser(person, now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.db.Exec(`INSERT INTO sign_in_methods (kind, subject, address, added_at) VALUES (?, ?, ?, ?)`, MethodEmail, alias, person, now.Unix()); err != nil {
+ t.Fatal(err)
+ }
+ acctID := testAccountID()
+ if err := fx.st.CreateAccount(acctID, "cdef", "Demo", person, now); err != nil {
+ t.Fatal(err)
+ }
+ lookupAnswers(fx, alias, http.StatusNotFound)
+ c := newBrowser(t)
+ code, _ := askSignin(t, fx, mail, c, alias, "")
+ if status, loc, _ := postCode(t, fx, c, code); status != http.StatusSeeOther || loc != "/a/cdef/" {
+ t.Fatalf("sign-in = %d -> %q, want 303 -> /a/cdef/", status, loc)
+ }
+ raw := emailSession(t, fx, c, person)
+ m, found, err := fx.st.LookupSignIn(MethodEmail, alias)
+ if err != nil || !found {
+ t.Fatalf("method = %+v, %v, %v", m, found, err)
+ }
+ if id, ok := fx.st.SessionMethodID(raw, time.Now()); !ok || id != m.ID {
+ t.Fatalf("session method = %d, %v; want %d, true", id, ok, m.ID)
+ }
+ if userRows(t, fx, alias) != 0 {
+ t.Fatal("sign-in created an alias user")
+ }
+ if browserCookie(t, fx, c, welcomeCookie) != "" {
+ t.Fatal("existing person got a welcome cookie")
+ }
+ var seen int64
+ if err := fx.st.db.QueryRow(`SELECT last_seen FROM users WHERE address = ?`, person).Scan(&seen); err != nil || seen < now.Unix() {
+ t.Fatalf("person last seen = %d, %v", seen, err)
+ }
+ var auditAddr, action string
+ if err := fx.st.db.QueryRow(`SELECT address, action FROM audit WHERE action IN (?, ?)`, auditSignin, auditFirstSignin).Scan(&auditAddr, &action); err != nil || auditAddr != person || action != auditSignin {
+ t.Fatalf("sign-in audit = %q, %q, %v", auditAddr, action, err)
+ }
+}
+
+func TestSigninExistingUserNoMethodNotWelcomed(t *testing.T) {
+ fx, mail := newEmailFixture(t, true)
+ const addr = "inv@example.test"
+ acctID := testAccountID()
+ if err := fx.st.CreateAccount(acctID, "cdef", "Demo", addr, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.SetLastAccount(addr, acctID); err != nil {
+ t.Fatal(err)
+ }
+ if methods, err := fx.st.SignInMethodsFor(addr); err != nil || len(methods) != 0 {
+ t.Fatalf("methods before sign-in = %v, %v; want none", methods, err)
+ }
+ lookupAnswers(fx, addr, http.StatusNotFound)
+ c := newBrowser(t)
+ code, _ := askSignin(t, fx, mail, c, addr, "")
+ if status, loc, _ := postCode(t, fx, c, code); status != http.StatusSeeOther || loc != "/a/cdef/" {
+ t.Fatalf("sign-in = %d -> %q, want 303 -> /a/cdef/", status, loc)
+ }
+ emailSession(t, fx, c, addr)
+ if browserCookie(t, fx, c, welcomeCookie) != "" {
+ t.Fatal("existing user got a welcome cookie")
+ }
+ if methods, err := fx.st.SignInMethodsFor(addr); err != nil || len(methods) != 1 {
+ t.Fatalf("methods after sign-in = %v, %v; want one", methods, err)
+ }
+ if id, err := fx.st.LastAccount(addr); err != nil || id != acctID {
+ t.Fatalf("last account = %d, %v; want %d", id, err, acctID)
+ }
+}
+
+func TestSessionMethodID(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Now().Truncate(time.Second)
+ for _, methodID := range []int64{0, 42} {
+ var raw string
+ var err error
+ if methodID == 0 {
+ raw, err = s.CreateSessionMethod("pat@example.test", "", MethodEmail, now)
+ } else {
+ raw, err = s.CreateSessionVia("pat@example.test", "", MethodEmail, methodID, now)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, at := range []time.Time{now, now.Add(SessionTTL)} {
+ if id, ok := s.SessionMethodID(raw, at); !ok || id != methodID {
+ t.Fatalf("session method = %d, %v; want %d, true", id, ok, methodID)
+ }
+ }
+ if id, ok := s.SessionMethodID(raw, now.Add(SessionTTL+time.Second)); ok || id != 0 {
+ t.Fatalf("expired session method = %d, %v", id, ok)
+ }
+ if err := s.DeleteSession(raw); err != nil {
+ t.Fatal(err)
+ }
+ if id, ok := s.SessionMethodID(raw, now); ok || id != 0 {
+ t.Fatalf("deleted session method = %d, %v", id, ok)
+ }
+ }
+ if id, ok := s.SessionMethodID("unknown", now); ok || id != 0 {
+ t.Fatalf("unknown session method = %d, %v", id, ok)
+ }
+}
+
+func TestSessionMethodIDMigration(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Now().Truncate(time.Second)
+ raw, err := s.CreateSession("pat@example.test", "keymail-grant", now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.db.Exec(`ALTER TABLE sessions DROP COLUMN method_id`); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 2; i++ {
+ if err := s.migrate(); err != nil {
+ t.Fatal(err)
+ }
+ if id, ok := s.SessionMethodID(raw, now); !ok || id != 0 {
+ t.Fatalf("legacy session method = %d, %v; want 0, true", id, ok)
+ }
+ if addr, method, ok := s.SessionInfo(raw, now); !ok || addr != "pat@example.test" || method != MethodKeymail {
+ t.Fatalf("legacy session = %q, %q, %v", addr, method, ok)
+ }
+ }
+}
diff --git a/internal/console/socialsignin_copy.go b/internal/console/socialsignin_copy.go
new file mode 100644
index 000000000..43fbe93ed
--- /dev/null
+++ b/internal/console/socialsignin_copy.go
@@ -0,0 +1,17 @@
+package console
+
+// socialSigninCopy is pinned to the approved Plan 1 copy by
+// TestSocialSigninCopyMatchesApproved.
+var socialSigninCopy = map[string]string{
+ "methods.heading": "Sign-in methods",
+ "methods.lede": "Every way you can sign in as {address}.",
+ "methods.col_method": "Method",
+ "methods.col_identity": "Signs in as",
+ "methods.col_added": "Added",
+ "methods.col_used": "Last used",
+ "methods.kind_email": "Email link or code",
+ "methods.kind_keymail": "Keymail",
+ "methods.never_used": "Not yet",
+ "signup.busy_title": "Try again later",
+ "signup.busy": "Too many new accounts have been made from here in the last hour. Try again later, or sign in to an account you already have.",
+}
diff --git a/internal/console/socialsignin_copy_test.go b/internal/console/socialsignin_copy_test.go
new file mode 100644
index 000000000..f3b4b5751
--- /dev/null
+++ b/internal/console/socialsignin_copy_test.go
@@ -0,0 +1,54 @@
+package console
+
+import (
+ "encoding/json"
+ "os"
+ "testing"
+)
+
+func TestSocialSigninCopyMatchesApproved(t *testing.T) {
+ raw, err := os.ReadFile("../../docs/superpowers/specs/2026-11-02-console-social-signin-copy-approved.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var approved struct {
+ Action string `json:"action"`
+ Strings []struct {
+ ID string `json:"id"`
+ Text string `json:"text"`
+ } `json:"strings"`
+ }
+ if err := json.Unmarshal(raw, &approved); err != nil {
+ t.Fatal(err)
+ }
+ if approved.Action != "approve" {
+ t.Fatalf("action = %q, want approve", approved.Action)
+ }
+ seen := map[string]bool{}
+ for _, s := range approved.Strings {
+ if seen[s.ID] {
+ t.Errorf("duplicate approved id %q", s.ID)
+ }
+ seen[s.ID] = true
+ if got, ok := socialSigninCopy[s.ID]; !ok || got != s.Text {
+ t.Errorf("socialSigninCopy[%q] = %q (present %v), approved %q", s.ID, got, ok, s.Text)
+ }
+ }
+ for id, text := range socialSigninCopy {
+ if !seen[id] {
+ t.Errorf("unapproved socialSigninCopy id %q", id)
+ }
+ if _, ok := signinCopy[id]; ok {
+ t.Errorf("copy id %q appears in both maps", id)
+ }
+ if got := copyText(id); got != text {
+ t.Errorf("copyText(%q) = %q, want %q", id, got, text)
+ }
+ }
+ if len(socialSigninCopy) != len(approved.Strings) {
+ t.Errorf("socialSigninCopy has %d strings, approved copy has %d", len(socialSigninCopy), len(approved.Strings))
+ }
+ if got := copyText("methods.lede", "address", "bob@example.com"); got != "Every way you can sign in as bob@example.com." {
+ t.Errorf("social copy placeholder = %q", got)
+ }
+}
diff --git a/internal/console/store.go b/internal/console/store.go
index ff6039fc9..ef5b7328c 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -595,6 +595,7 @@ func (s *Store) migrate() error {
// that predates the column was made through Keymail, so the default
// is the backfill.
`ALTER TABLE sessions ADD COLUMN method TEXT NOT NULL DEFAULT 'keymail';`,
+ `ALTER TABLE sessions ADD COLUMN method_id INTEGER NOT NULL DEFAULT 0;`,
// A team invite's seat authorisation (plans 6b, Call 11): what the
// owner agreed a new paid seat would cost when they invited, and when
// the charge it authorised applied (single use, Invariant 2). An
@@ -611,6 +612,9 @@ func (s *Store) migrate() error {
return err
}
}
+ if err := migrateSignInMethods(s.db); err != nil {
+ return err
+ }
// The one-shot backfill of mail_sender_counts from mail_counts (senders
// design §8). It runs AFTER the ALTER list because mail_counts.deliveries
// is added there, and it runs at most once for the life of the database:
@@ -1595,10 +1599,10 @@ VALUES (?, ?, ?, ?, ?, ?)`,
}
// PendingInviteFor reads an invite without consuming it, behind the same
-// three gates AcceptInvite applies: unaccepted, addressed to address, and
-// unexpired. Any failure is one error, so the confirm page that shows it can
-// answer every refusal the same way.
-func (s *Store) PendingInviteFor(token, address string, now time.Time) (*Invite, error) {
+// three gates AcceptInvite applies: unaccepted, addressed to an address the
+// person holds, and unexpired. Any refusal gets the same error, so the
+// confirm page can answer every refusal the same way.
+func (s *Store) PendingInviteFor(token, person string, now time.Time) (*Invite, error) {
var i Invite
var created, expires, accepted int64
err := s.db.QueryRow(`SELECT token, account_id, address, invited_by, created_at, expires_at, accepted_at
@@ -1606,8 +1610,12 @@ FROM invites WHERE token = ?`, token).Scan(&i.Token, &i.AccountID, &i.Address, &
if err != nil {
return nil, err
}
- if accepted != 0 || i.Address != address || now.Unix() > expires {
- return nil, fmt.Errorf("console: that invite cannot be used by %s", address)
+ holds, err := holdsAddressTx(s.db, person, i.Address)
+ if err != nil {
+ return nil, err
+ }
+ if accepted != 0 || !holds || now.Unix() > expires {
+ return nil, fmt.Errorf("console: that invite cannot be used by %s", person)
}
i.CreatedAt = time.Unix(created, 0).UTC()
i.ExpiresAt = time.Unix(expires, 0).UTC()
@@ -1630,16 +1638,15 @@ func (s *Store) PendingInviteAddress(token string, now time.Time) (string, bool)
// AcceptInvite consumes an invite and creates the membership, in one
// transaction. Three gates, all inside it: the token must be unaccepted, the
-// address must be the one it was addressed to (an invite is not a bearer
-// token — the link lands in ONE keymail inbox and only that identity can use
-// it), and it must not have expired.
-func (s *Store) AcceptInvite(token, address string, now time.Time) (int64, error) {
+// person must hold the invited address, and it must not have expired.
+// The membership belongs to the person, even when the invite names an alias.
+func (s *Store) AcceptInvite(token, person string, now time.Time) (int64, error) {
tx, err := s.db.Begin()
if err != nil {
return 0, err
}
defer tx.Rollback()
- accountID, err := acceptInviteTx(tx, token, address, now)
+ accountID, err := acceptInviteTx(tx, token, person, now)
if err != nil {
return 0, err
}
@@ -1651,7 +1658,7 @@ func (s *Store) AcceptInvite(token, address string, now time.Time) (int64, error
// acceptInviteTx is AcceptInvite inside the caller's transaction (a
// MembershipTransition write), with the same three gates. It never commits.
-func acceptInviteTx(tx *sql.Tx, token, address string, now time.Time) (int64, error) {
+func acceptInviteTx(tx *sql.Tx, token, person string, now time.Time) (int64, error) {
var accountID, expires, accepted int64
var want string
err := tx.QueryRow(`SELECT account_id, address, expires_at, accepted_at FROM invites WHERE token = ?`,
@@ -1665,7 +1672,11 @@ func acceptInviteTx(tx *sql.Tx, token, address string, now time.Time) (int64, er
if accepted != 0 {
return 0, fmt.Errorf("console: that invite has already been used")
}
- if want != address {
+ holds, err := holdsAddressTx(tx, person, want)
+ if err != nil {
+ return 0, err
+ }
+ if !holds {
return 0, fmt.Errorf("console: that invite was sent to a different address")
}
if now.Unix() > expires {
@@ -1677,7 +1688,7 @@ func acceptInviteTx(tx *sql.Tx, token, address string, now time.Time) (int64, er
// An invite always grants member; owners are promoted deliberately.
if _, err := tx.Exec(`INSERT INTO memberships (account_id, address, role, added_at)
VALUES (?, ?, ?, ?) ON CONFLICT(account_id, address) DO NOTHING`,
- accountID, address, RoleMember, now.Unix()); err != nil {
+ accountID, person, RoleMember, now.Unix()); err != nil {
return 0, err
}
return accountID, nil
@@ -2832,13 +2843,19 @@ func (s *Store) CreateSession(address, keymailToken string, now time.Time) (stri
// CreateSessionMethod is CreateSession with the way the session was proved
// recorded: MethodKeymail or MethodEmail.
func (s *Store) CreateSessionMethod(address, keymailToken, method string, now time.Time) (string, error) {
+ return s.CreateSessionVia(address, keymailToken, method, 0, now)
+}
+
+// CreateSessionVia records the sign-in method row behind the session.
+// A zero methodID keeps sessions made by legacy callers readable.
+func (s *Store) CreateSessionVia(address, keymailToken, method string, methodID int64, now time.Time) (string, error) {
raw, err := randomToken()
if err != nil {
return "", err
}
- _, err = s.db.Exec(`INSERT INTO sessions (token_hash, address, keymail_token, method, created_at, expires_at)
-VALUES (?, ?, ?, ?, ?, ?)`,
- hashToken(raw), address, keymailToken, method, now.Unix(), now.Add(SessionTTL).Unix())
+ _, err = s.db.Exec(`INSERT INTO sessions (token_hash, address, keymail_token, method, method_id, created_at, expires_at)
+VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ hashToken(raw), address, keymailToken, method, methodID, now.Unix(), now.Add(SessionTTL).Unix())
if err != nil {
return "", err
}
@@ -2870,6 +2887,18 @@ func (s *Store) SessionInfo(rawToken string, now time.Time) (address, method str
return address, method, true
}
+// SessionMethodID returns the sign-in method row for a live session.
+// Sessions predating method tracking return zero with ok true.
+func (s *Store) SessionMethodID(rawToken string, now time.Time) (int64, bool) {
+ var id, exp int64
+ err := s.db.QueryRow(`SELECT method_id, expires_at FROM sessions WHERE token_hash = ?`,
+ hashToken(rawToken)).Scan(&id, &exp)
+ if err != nil || now.Unix() > exp {
+ return 0, false
+ }
+ return id, true
+}
+
// DeleteSession removes a session by its raw token.
func (s *Store) DeleteSession(rawToken string) error {
_, err := s.db.Exec(`DELETE FROM sessions WHERE token_hash = ?`, hashToken(rawToken))
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index 03da3023d..542652107 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -220,6 +220,7 @@ var claimSQLTables = map[string]claimSQLTable{
// ---- not app-scoped: each with its reason ----
"sessions": {NonApp: "browser sessions, keyed by token hash and address"},
"users": {NonApp: "people, keyed by address"},
+ "sign_in_methods": {NonApp: "sign-in identities mapped to people, keyed by kind and subject; names no app"},
"grants": {NonApp: "keymail grants, keyed by address"},
"confirmations": {NonApp: "sign-in confirmation links, keyed by token hash and address"},
"keys": {NonApp: "the console's own signing keys"},
diff --git a/internal/console/templates/layout.html b/internal/console/templates/layout.html
index c884d723c..777b334a0 100644
--- a/internal/console/templates/layout.html
+++ b/internal/console/templates/layout.html
@@ -278,6 +278,7 @@
.tablewrap:has(> table.packs) { background: none; border: 0; border-radius: 0; box-shadow: none; margin: 0; }
.instances .instance-address { white-space: nowrap; }
.instances td:nth-child(2) { white-space: nowrap; }
+ .methods td:nth-child(3), .methods td:nth-child(4) { white-space: nowrap; }
.instance-open { display: inline-flex; padding: .25rem; }
.instance-group th { text-align: left; padding-top: 1rem; background: var(--accent-soft); }
.instance-group .small { font-weight: normal; }
@@ -1020,6 +1021,7 @@
.billing-includes { grid-template-columns: repeat(2, auto); }
}
@media (max-width: 40rem) {
+ table.methods .added { display: none; }
.billing-now { padding: 1rem 1.1rem 1.1rem; }
.done-actions { flex-direction: column; align-items: stretch; margin-top: 1.75rem; }
.done-actions .btn { text-align: center; }
diff --git a/internal/console/templates/settings.html b/internal/console/templates/settings.html
index 396ec8d20..a7852926c 100644
--- a/internal/console/templates/settings.html
+++ b/internal/console/templates/settings.html
@@ -6,6 +6,23 @@
<h1>Your settings</h1>
<p class="lede">Yours across every account — not any one account's.</p>
</div>
+{{if .Methods}}
+<h2>{{.MethodsText "heading"}}</h2>
+<p class="small">{{.MethodsText "lede"}}</p>
+<div class="tablewrap">
+<table class="methods">
+ <tr><th>{{.MethodsText "col_method"}}</th><th>{{.MethodsText "col_identity"}}</th><th class="added">{{.MethodsText "col_added"}}</th><th>{{.MethodsText "col_used"}}</th></tr>
+ {{range .Methods}}
+ <tr>
+ <td>{{.Kind}}</td>
+ <td>{{.Identity}}</td>
+ <td class="added">{{fmtDay .AddedAt}}</td>
+ <td>{{if .LastUsed.IsZero}}{{$.MethodsText "never_used"}}{{else}}{{fmtDay .LastUsed}}{{end}}</td>
+ </tr>
+ {{end}}
+</table>
+</div>
+{{end}}
<h2>Command-line access</h2>
<p class="small">Every terminal that can act as {{.Address}}.</p>
{{if .Tokens}}