carlos / platform Public

console: first sign-in survives a re-tap; fields don't zoom on iOS

A new person's first email sign-in spent the link, then minted their
account in the same POST (~100 serial S3 reads, ~3 s). A re-tap
cancelled it and the retry saw a spent link.

- Sign-in redirects to / once the session exists; the GET mints.
- Mint serialised per person, detached from request cancellation.
- NextAccountID reads manifests 16 at a time (census approved, #280).
- data-busy sign-in buttons; 16px fields on touch screens; full-width
  sign-in form on phones.

Astra review: round 1 one P1 (probes) fixed, round 2 READY.

Squashed from signin-first-run-mobile into main.
claude agent, operated by paul@keymail.dev 0d55ef8c455e10c4bc709c45c9b3ab7a22aabee8 parent cf76222
20 files changed, +492 −47
  • docs/superpowers/notes/census-proposal-signin-first-run-mobile.md +11 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-signin-first-run-mobile-R2.md +15 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-signin-first-run-mobile.md +19 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-signin-first-run-mobile-R2.md +92 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-signin-first-run-mobile.md +79 −0
  • internal/console/claim_invariant_probes_nonapp_test.go +10 −2
  • internal/console/claim_invariant_probes_test.go +9 −3
  • internal/console/emailsignin.go +24 −17
  • internal/console/emailsignin_test.go +21 −4
  • internal/console/landing_test.go +55 −0
  • internal/console/server.go +38 −2
  • internal/console/server_test.go +17 −0
  • internal/console/templates/check.html +2 −2
  • internal/console/templates/console_chrome.html +14 −0
  • internal/console/templates/email_link.html +1 −1
  • internal/console/templates/home.html +1 −1
  • internal/domains/mint.go +45 −15
  • internal/domains/mint_test.go +35 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-signin-first-run-mobile.tsv +3 −0

CI passed — run details

diff --git a/docs/superpowers/notes/census-proposal-signin-first-run-mobile.md b/docs/superpowers/notes/census-proposal-signin-first-run-mobile.md
new file mode 100644
index 000000000..7f3462301
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-signin-first-run-mobile.md
@@ -0,0 +1,11 @@
+# Census approval: signin-first-run-mobile
+
+Ruling `census-ruling-signin-first-run-mobile`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `internal/domains`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Seal: `61027a32e31cb7ce017304f526f668c26980999e2699a3013a82e2630164143e` → `61027a32e31cb7ce017304f526f668c26980999e2699a3013a82e2630164143e`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-signin-first-run-mobile.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-signin-first-run-mobile-R2.md b/docs/superpowers/reviews/CODEX-FINDINGS-signin-first-run-mobile-R2.md
new file mode 100644
index 000000000..01355aa69
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-signin-first-run-mobile-R2.md
@@ -0,0 +1,15 @@
+Round 1 P1: **resolved in source**—both probes check `303 → /`, verify the session, follow the landing GET, and appear in `claimSessionEnd`.
+
+Reviewed `origin/main...440f6d18994817bf2c7f86bccdfcc1a85b3517eb`.
+
+- **P1:** None.
+- **P2:** None.
+- **P3:** None.
+
+No remaining stale sign-in Location expectations found. Account destinations in the existing tests are reached through the updated landing helpers. The redirect paths, landing lock, concurrent manifest reads, and form changes revealed no additional findings.
+
+Targeted console tests could not start: the read-only sandbox prevented Go from creating its build directory. `git diff --check` passed. No files were changed.
+
+**Census: APPROVED, carried forward from round 1.** `internal/domains` is unchanged since the approved review at `71c3c5532a2a6c7653e95b64712ff1b1d364990c`; the brief requires no new census verdict.
+
+**READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-signin-first-run-mobile.md b/docs/superpowers/reviews/CODEX-FINDINGS-signin-first-run-mobile.md
new file mode 100644
index 000000000..658d52ed0
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-signin-first-run-mobile.md
@@ -0,0 +1,19 @@
+**P1 — The callback invariant probe still expects the old redirect.**
+
+At [emailsignin.go:291](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/signin-first-run-mobile/internal/console/emailsignin.go:291), successful sign-in now returns `303 Location: /`. But [claim_invariant_probes_nonapp_test.go:117](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/signin-first-run-mobile/internal/console/claim_invariant_probes_nonapp_test.go:117) still requires `/a/`. Its helper returns the callback response without following the landing hop.
+
+Consequently, `TestClaimConsoleMutationInvariant`’s callback probe will reject a successful sign-in as an “auth redirect” at [claim_invariant_probes_test.go:129](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/signin-first-run-mobile/internal/console/claim_invariant_probes_test.go:129). This is verified from the source; execution was blocked by the sandbox.
+
+**Fix:** Update the probe to expect `/`, retain its live-session assertion, and explicitly permit this successful callback in the probe census. Changing only the expected Location is insufficient: the census currently permits `/` only for signout. Add an assertion for the subsequent landing GET.
+
+**Invariant:** Every registered non-app mutation must have a passing probe that verifies its successful effect.
+
+**P2:** None. **P3:** None.
+
+Targeted console and domains tests could not start because Go could not create its build directory on the read-only filesystem. `git diff --check` passed. No files were changed.
+
+**Census verdict — APPROVE `internal/domains` envelope** at `71c3c5532a2a6c7653e95b64712ff1b1d364990c`.
+
+Reviewed [NextAccountID and its worker closure](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/signin-first-run-mobile/internal/domains/mint.go:141), the changed tests, and the reached parser, store implementations, reserved-ID logic, and mint caller. The change preserves manifest selection, claimed-ID handling, unreadable-manifest refusal, and create-only allocation. Reads are bounded to 16 concurrent operations and joined before return. It introduces no new root-readable paths or weaker validation.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-signin-first-run-mobile-R2.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-signin-first-run-mobile-R2.md
new file mode 100644
index 000000000..c6880d3f3
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-signin-first-run-mobile-R2.md
@@ -0,0 +1,92 @@
+# Review brief: branch signin-first-run-mobile, round 2 of 3
+
+Repo carlos/platform, branch `signin-first-run-mobile`, commit 9cd16b23e6c217901eb3d0d8ec99a7d9f1bbd2e2.
+Under review: the diff `origin/main...HEAD`.
+Authorities: `docs/superpowers/specs/2026-10-21-console-email-signin-design.md`
+(email sign-in), AGENTS.md (stopping rules, census).
+
+You are an independent reviewer. Read the diff, then the code it reaches,
+and check every claim in the commit message against that code.
+
+## Background
+
+Flagship 2026-11-07: a brand-new person's POST /auth/email/link spent the
+link, opened a session, then minted their personal account inside the same
+request (NextAccountID read ~100 manifests serially, ~3 s). The browser
+dropped the request (a re-tap), the mint's S3 read failed with context
+canceled, the 500 went nowhere, and the retry saw a spent link. Twice.
+
+## What to check
+
+1. `finishSignin` (internal/console/emailsignin.go) now redirects to `/` or
+ `/?next=<safe>` instead of resolving the account. Every caller: email link,
+ email code, Keymail callback (server.go ~4021), demo claim
+ (demo_claim_auth.go, demo_claim_page.go). Does any door depend on the
+ account existing before its next page loads, or on the old Location?
+ Is `next` still only ever a `safeNext` local path at both hops (no open
+ redirect via `/?next=`)? Is the 303 -> 302 chain right for a POST?
+2. `handleHome` (server.go) with a session now honours `next`. Any page that
+ sends a signed-in person to `/?next=...` today and expects the account
+ landing instead? Any loop (a next that itself redirects to `/?next=`)?
+3. `currentAccount`: per-person striped lock, membership re-check under the
+ lock, mint under `context.WithoutCancel` with a 30 s timeout. Deadlocks
+ (callers that already hold a landing or flow lock?), holding a lock across
+ S3 calls, the address key (normalised the same way everywhere?), and
+ whether a detached mint can now outlive a request in a way that matters
+ (shutdown, tests).
+4. `NextAccountID` (internal/domains/mint.go): 16 concurrent Gets. Same
+ answer as before for every bucket state, including disagreeing manifests,
+ unparseable ones, and an unreadable one (must still fail). Goroutine
+ leaks on early error? Any caller running it with a store that is not safe
+ for concurrent use?
+5. Templates: `data-busy` on the sign-in, code, "send a new link" and link
+ confirm buttons (layout.html's script delays submit 650 ms and blocks a
+ second submit). Does any of these forms need the submitter's name/value,
+ or break with JS off? CSS: `@media (pointer: coarse)` 16px fields and the
+ `max-width: 40rem` full-width sign-in form; anything else using
+ `form.signin` that this breaks?
+6. Census: `docs/superpowers/notes/census-proposal-signin-first-run-mobile.md`
+ re-pins the `internal/domains` envelope. Read every changed function in
+ that package and what it reaches, and give the census verdict the card
+ asks for (approve or reject, with reasons).
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the problem, the evidence
+(file:line, verified), the failure scenario, a concrete fix and the
+invariant or trust boundary it breaks. Then the census verdict for the
+`internal/domains` envelope. End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites; targeted `go test -run` on the
+touched packages is fine (leave GOCACHE at its default).
+
+## Round 2
+
+Earlier rounds: `docs/superpowers/reviews/CODEX-FINDINGS-signin-first-run-mobile.md`
+(round 1: one P1, the callback invariant probe; census APPROVED).
+
+First give one line for that P1: resolved, partly, or not. The fix is
+commit 9cd16b23 (claim_invariant_probes_nonapp_test.go,
+claim_invariant_probes_test.go): the callback and email-code probes want
+303 -> "/", prove the session and follow the landing GET into an account;
+both are in claimSessionEnd. `TestClaimConsoleMutationInvariant` passed
+locally on this tip. Then check whether any other test or probe still
+expects the old sign-in Location, and carry anything unresolved forward.
+The census item needs no new verdict unless internal/domains changed.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-signin-first-run-mobile.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-signin-first-run-mobile.md
new file mode 100644
index 000000000..ed12c4c5c
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-signin-first-run-mobile.md
@@ -0,0 +1,79 @@
+# Review brief: branch signin-first-run-mobile, round 1 of 3
+
+Repo carlos/platform, branch `signin-first-run-mobile`, commit: the commit
+that adds this file (its parent is 2f089741ad10c3974e39523cf7a73d00ac8941a4).
+Under review: the diff `origin/main...HEAD`.
+Authorities: `docs/superpowers/specs/2026-10-21-console-email-signin-design.md`
+(email sign-in), AGENTS.md (stopping rules, census).
+
+You are an independent reviewer. Read the diff, then the code it reaches,
+and check every claim in the commit message against that code.
+
+## Background
+
+Flagship 2026-11-07: a brand-new person's POST /auth/email/link spent the
+link, opened a session, then minted their personal account inside the same
+request (NextAccountID read ~100 manifests serially, ~3 s). The browser
+dropped the request (a re-tap), the mint's S3 read failed with context
+canceled, the 500 went nowhere, and the retry saw a spent link. Twice.
+
+## What to check
+
+1. `finishSignin` (internal/console/emailsignin.go) now redirects to `/` or
+ `/?next=<safe>` instead of resolving the account. Every caller: email link,
+ email code, Keymail callback (server.go ~4021), demo claim
+ (demo_claim_auth.go, demo_claim_page.go). Does any door depend on the
+ account existing before its next page loads, or on the old Location?
+ Is `next` still only ever a `safeNext` local path at both hops (no open
+ redirect via `/?next=`)? Is the 303 -> 302 chain right for a POST?
+2. `handleHome` (server.go) with a session now honours `next`. Any page that
+ sends a signed-in person to `/?next=...` today and expects the account
+ landing instead? Any loop (a next that itself redirects to `/?next=`)?
+3. `currentAccount`: per-person striped lock, membership re-check under the
+ lock, mint under `context.WithoutCancel` with a 30 s timeout. Deadlocks
+ (callers that already hold a landing or flow lock?), holding a lock across
+ S3 calls, the address key (normalised the same way everywhere?), and
+ whether a detached mint can now outlive a request in a way that matters
+ (shutdown, tests).
+4. `NextAccountID` (internal/domains/mint.go): 16 concurrent Gets. Same
+ answer as before for every bucket state, including disagreeing manifests,
+ unparseable ones, and an unreadable one (must still fail). Goroutine
+ leaks on early error? Any caller running it with a store that is not safe
+ for concurrent use?
+5. Templates: `data-busy` on the sign-in, code, "send a new link" and link
+ confirm buttons (layout.html's script delays submit 650 ms and blocks a
+ second submit). Does any of these forms need the submitter's name/value,
+ or break with JS off? CSS: `@media (pointer: coarse)` 16px fields and the
+ `max-width: 40rem` full-width sign-in form; anything else using
+ `form.signin` that this breaks?
+6. Census: `docs/superpowers/notes/census-proposal-signin-first-run-mobile.md`
+ re-pins the `internal/domains` envelope. Read every changed function in
+ that package and what it reaches, and give the census verdict the card
+ asks for (approve or reject, with reasons).
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the problem, the evidence
+(file:line, verified), the failure scenario, a concrete fix and the
+invariant or trust boundary it breaks. Then the census verdict for the
+`internal/domains` envelope. End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites; targeted `go test -run` on the
+touched packages is fine (leave GOCACHE at its default).
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go
index ff22fcdb1..2614ce716 100644
--- a/internal/console/claim_invariant_probes_nonapp_test.go
+++ b/internal/console/claim_invariant_probes_nonapp_test.go
@@ -114,11 +114,15 @@ func claimCallbackProbe() claimProbe {
c = newBrowser(t)
return cx.signInReply(t, c, "code-claim-callback-probe")
},
- status: http.StatusSeeOther, loc: "/a/",
+ status: http.StatusSeeOther, loc: "/",
effect: func(t *testing.T, cx *claimCase, r claimReply) string {
if !cx.signedInAs(c, claimFxOwner) {
return "no live session for " + claimFxOwner + " came out of the callback"
}
+ // The front page's GET is where the session lands.
+ if status, loc, _ := get(t, c, cx.ts.URL+"/"); status != http.StatusFound || !strings.HasPrefix(loc, "/a/") {
+ return fmt.Sprintf("the landing after the callback = %d -> %q, want 302 into an account", status, loc)
+ }
return ""
},
}
@@ -209,11 +213,15 @@ func claimEmailCodeProbe() claimProbe {
status, loc, body := postForm(t, c, cx.ts.URL+"/auth/email/code", url.Values{"code": {cx.vars["code"]}})
return cx.browserReply(c, status, loc, body)
},
- status: http.StatusSeeOther, loc: "/a/",
+ status: http.StatusSeeOther, loc: "/",
effect: func(t *testing.T, cx *claimCase, r claimReply) string {
if !cx.signedInAs(c, claimFxOwner) {
return "the emailed code opened no session"
}
+ // The front page's GET is where the session lands.
+ if status, loc, _ := get(t, c, cx.ts.URL+"/"); status != http.StatusFound || !strings.HasPrefix(loc, "/a/") {
+ return fmt.Sprintf("the landing after the code = %d -> %q, want 302 into an account", status, loc)
+ }
if _, ok := cx.st.LiveEmailChallenge(ChallengeSignIn, hashToken(cx.vars["flow"]), time.Now()); ok {
return "the challenge is still standing after its code was used"
}
diff --git a/internal/console/claim_invariant_probes_test.go b/internal/console/claim_invariant_probes_test.go
index 5bdfc3939..aa814915c 100644
--- a/internal/console/claim_invariant_probes_test.go
+++ b/internal/console/claim_invariant_probes_test.go
@@ -217,9 +217,15 @@ func claimTripwireProblems(t *testing.T, cx *claimCase, m int, before map[claimA
// claimSessionEnd are the entries whose success IS the redirect to the front
// page: ending a session sends the person there, and so does a request that
-// never had one. Their effect witness is the session itself, which is why a
-// probe of one of these may name "/" and no other probe may.
-var claimSessionEnd = map[string]bool{"route POST /auth/signout": true}
+// never had one; a sign-in sends the new session there too, where the GET
+// lands it (and mints a first account) so a re-tap cannot spend the sign-in
+// twice. Their effect witness is the session itself, which is why a probe of
+// one of these may name "/" and no other probe may.
+var claimSessionEnd = map[string]bool{
+ "route POST /auth/signout": true,
+ "route GET /auth/callback": true,
+ "route POST /auth/email/code": true,
+}
// claimProbeCensus checks the probe table against the fixture table, exactly:
// every read and nonApp entry has a probe, no other entry has one, a nonApp
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go
index 28450fe32..d663c65ce 100644
--- a/internal/console/emailsignin.go
+++ b/internal/console/emailsignin.go
@@ -188,6 +188,14 @@ func (s *Server) flowLock(flow string) *sync.Mutex {
return &s.flowLocks[sum[0]]
}
+// landingLock serialises currentAccount's mint for one person. Striped by the
+// address's hash, like flowLock: bounded memory, and two people rarely share
+// a stripe (when they do, one waits for the other's mint).
+func (s *Server) landingLock(addr string) *sync.Mutex {
+ sum := sha256.Sum256([]byte(addr))
+ return &s.landingLocks[sum[0]]
+}
+
// homeForm is what the front page's one form starts with. flow, when set, is
// the flow the caller already holds for this request.
type homeForm struct {
@@ -254,9 +262,14 @@ func safeNext(raw string) string {
// 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 ordinary redirects. The exact claim return skips account landing;
-// its explicit confirmation uses the claim person lock and account cap.
+// for minutes later. Landing is NOT resolved here: the answer is a redirect to
+// the front page (with next), whose GET resolves the current account, minting
+// one for a new person. Minting can take seconds, and a sign-in POST has
+// already spent its link or code: a person who taps again, or whose browser
+// gives up, must find a signed-in session on the retry, not a spent link
+// (2026-11-07, a first sign-in on a phone). The exact claim return skips
+// account landing; its explicit confirmation uses the claim person lock and
+// account cap.
// freshAuthTime carries the claim callback's validated Keymail gesture, if any.
// Like an email sign-in's, the presence it records is not scoped to the claim:
// for StepUpWindow it satisfies every step-up gated action of this new session,
@@ -267,24 +280,18 @@ func (s *Server) finishSignin(w http.ResponseWriter, r *http.Request, proved, ke
if len(freshAuthTime) > 0 {
authTime = freshAuthTime[0]
}
- person, ok := s.completeSigninSession(w, r, proved, keymailToken, method, authTime)
- if !ok {
+ if _, ok := s.completeSigninSession(w, r, proved, keymailToken, method, authTime); !ok {
return
}
- if n := safeNext(next); n != "" {
- if n == "/demo/claim" {
- http.Redirect(w, r, n, http.StatusSeeOther)
- return
- }
- 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
- }
+ n := safeNext(next)
+ switch n {
+ case "/demo/claim":
http.Redirect(w, r, n, http.StatusSeeOther)
- return
+ case "":
+ http.Redirect(w, r, "/", http.StatusSeeOther)
+ default:
+ http.Redirect(w, r, "/?next="+url.QueryEscape(n), http.StatusSeeOther)
}
- s.redirectToCurrentAccount(w, r, person, http.StatusSeeOther)
}
// completeSigninSession records identity and opens the browser session without
diff --git a/internal/console/emailsignin_test.go b/internal/console/emailsignin_test.go
index 4448ebd70..71271e268 100644
--- a/internal/console/emailsignin_test.go
+++ b/internal/console/emailsignin_test.go
@@ -50,7 +50,7 @@ func keymailWalk(t *testing.T, fx *consoleFixture, c *http.Client, signinQuery,
fx.fk.expectCode = code
fx.fk.mu.Unlock()
status, loc, _ = get(t, c, fx.ts.URL+"/auth/callback?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(q.Get("state")))
- return status, loc
+ return followLanding(t, fx, c, status, loc)
}
func browserCookie(t *testing.T, fx *consoleFixture, c *http.Client, name string) string {
@@ -122,7 +122,8 @@ func TestFinishSigninEmailRecordsStepUp(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
fx.srv.finishSignin(w, r, "bob@example.com", "", MethodEmail, "/invite/abc")
res := w.Result()
- if res.StatusCode != http.StatusSeeOther || res.Header.Get("Location") != "/invite/abc" {
+ // Landing (and a first sign-in's mint) waits for the front page's GET.
+ if res.StatusCode != http.StatusSeeOther || res.Header.Get("Location") != "/?next=%2Finvite%2Fabc" {
t.Fatalf("finishSignin = %d -> %q", res.StatusCode, res.Header.Get("Location"))
}
var raw string
@@ -148,6 +149,18 @@ func TestFinishSigninEmailRecordsStepUp(t *testing.T) {
if g, _ := fx.st.GrantToken("bob@example.com"); g != "" {
t.Fatalf("an email sign-in stored a grant token %q", g)
}
+ // The sign-in POST mints nothing; the front page's GET does, then follows
+ // next.
+ if accts, err := fx.st.AccountsFor("bob@example.com"); err != nil || len(accts) != 0 {
+ t.Fatalf("the sign-in itself minted: %v, %v", accts, err)
+ }
+ hw := httptest.NewRecorder()
+ hr := httptest.NewRequest(http.MethodGet, res.Header.Get("Location"), nil)
+ hr.AddCookie(&http.Cookie{Name: sessionCookie, Value: raw})
+ fx.srv.handleHome(hw, hr)
+ if hw.Code != http.StatusFound || hw.Header().Get("Location") != "/invite/abc" {
+ t.Fatalf("landing = %d -> %q, want 302 -> /invite/abc", hw.Code, hw.Header().Get("Location"))
+ }
if accts, err := fx.st.AccountsFor("bob@example.com"); err != nil || len(accts) == 0 {
t.Fatalf("no personal account minted: %v, %v", accts, err)
}
@@ -715,13 +728,17 @@ func openLink(t *testing.T, fx *consoleFixture, c *http.Client, link string) (in
// postLink submits the confirm page's form from the console's own origin.
func postLink(t *testing.T, fx *consoleFixture, c *http.Client, link, nonce string) (int, string, string) {
t.Helper()
- return postFrom(t, fx, c, "/auth/email/link", fx.ts.URL, url.Values{"t": {link}, "nonce": {nonce}})
+ status, loc, body := postFrom(t, fx, c, "/auth/email/link", fx.ts.URL, url.Values{"t": {link}, "nonce": {nonce}})
+ status, loc = followLanding(t, fx, c, status, loc)
+ return status, loc, body
}
// postCode submits the check page's code form from the console's own origin.
func postCode(t *testing.T, fx *consoleFixture, c *http.Client, code string) (int, string, string) {
t.Helper()
- return postFrom(t, fx, c, "/auth/email/code", fx.ts.URL, url.Values{"code": {code}})
+ status, loc, body := postFrom(t, fx, c, "/auth/email/code", fx.ts.URL, url.Values{"code": {code}})
+ status, loc = followLanding(t, fx, c, status, loc)
+ return status, loc, body
}
// emailSession asserts browser c holds a live email-method session for addr
diff --git a/internal/console/landing_test.go b/internal/console/landing_test.go
new file mode 100644
index 000000000..bc763d65d
--- /dev/null
+++ b/internal/console/landing_test.go
@@ -0,0 +1,55 @@
+package console
+
+import (
+ "context"
+ "sync"
+ "testing"
+)
+
+// A first sign-in's landing can arrive twice at once (a double tap, a reload
+// while the first is still minting): one personal account, not two.
+func TestCurrentAccountConcurrentLandingsMintOnce(t *testing.T) {
+ fx := newConsoleFixture(t)
+ const addr = "twice@example.com"
+ var wg sync.WaitGroup
+ got := make([]string, 8)
+ errs := make([]error, 8)
+ for i := range got {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ got[i], errs[i] = fx.srv.currentAccount(context.Background(), addr)
+ }()
+ }
+ wg.Wait()
+ for i := range got {
+ if errs[i] != nil {
+ t.Fatalf("landing %d: %v", i, errs[i])
+ }
+ if got[i] != got[0] {
+ t.Fatalf("landings disagree: %q vs %q", got[i], got[0])
+ }
+ }
+ accts, err := fx.st.AccountsFor(addr)
+ if err != nil || len(accts) != 1 {
+ t.Fatalf("accounts = %v, %v; want exactly one", accts, err)
+ }
+}
+
+// A browser that gives up mid-landing must not strand a half-minted account:
+// the mint runs to the end even when the request's context is already gone.
+func TestCurrentAccountMintSurvivesCancelledRequest(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.Releases = ctxStore{fx.srv.cfg.Releases} // metricsview_test.go
+ const addr = "gaveup@example.com"
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ sqid, err := fx.srv.currentAccount(ctx, addr)
+ if err != nil {
+ t.Fatalf("landing with a cancelled request: %v", err)
+ }
+ accts, err := fx.st.AccountsFor(addr)
+ if err != nil || len(accts) != 1 || accts[0].Sqid != sqid {
+ t.Fatalf("accounts = %v, %v; want the one minted (%s)", accts, err, sqid)
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index b4c3fdb82..77ff98605 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1258,7 +1258,9 @@ type Server struct {
// memory, one console process per deployment.
limits emailLimits
// flowLocks serialise /auth/continue per sign-in flow (flowLock).
- flowLocks [256]sync.Mutex
+ flowLocks [256]sync.Mutex
+ // landingLocks serialise a first landing's mint per person (landingLock).
+ landingLocks [256]sync.Mutex
demoClaimSelections demoClaimSelectionReceipts
demoClaimBoundary func(string) error // Test-only crash injection after durable boundaries.
demoClaimTestEnabled bool // Test-only readiness bypass.
@@ -3079,8 +3081,22 @@ func (s *Server) takeFlash(w http.ResponseWriter, r *http.Request) (flash, flash
// ---- auth handlers ----------------------------------------------------------
+// handleHome lands a signed-in person: on next when it is a safe local path,
+// else on their current account. Either way the current account is resolved
+// first, minting a personal account on a first sign-in, so every sign-in door
+// can redirect here the moment the session exists and leave the slow part to
+// a GET a reload can safely repeat.
func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) {
if addr, _, ok := s.session(r); ok {
+ if n := safeNext(r.URL.Query().Get("next")); n != "" {
+ if _, err := s.currentAccount(r.Context(), addr); err != nil {
+ log.Printf("console: landing for %s: %v", addr, err)
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not open your account. Please try again.")
+ return
+ }
+ http.Redirect(w, r, n, http.StatusFound)
+ return
+ }
s.redirectToCurrentAccount(w, r, addr, http.StatusFound)
return
}
@@ -3112,6 +3128,12 @@ func (s *Server) redirectToCurrentAccount(w http.ResponseWriter, r *http.Request
// currentAccount resolves the three landing cases in order: MRU history (only
// if still a member — an account you were removed from must not strand you),
// first membership, or mint.
+//
+// The mint is serialised per person and re-checks membership under the lock,
+// so two landings at once (a double tap, a reload while the first is still
+// minting) give one personal account, not two. It runs detached from the
+// request's cancellation, bounded by landingMintTimeout: a browser that gives
+// up mid-mint must not leave a manifest in the bucket with no console row.
func (s *Server) currentAccount(ctx context.Context, addr string) (string, error) {
a, err := s.memberAccount(addr)
if err != nil {
@@ -3120,13 +3142,27 @@ func (s *Server) currentAccount(ctx context.Context, addr string) (string, error
if a != nil {
return a.Sqid, nil
}
- m, err := s.mintAccount(ctx, addr, addr)
+ mu := s.landingLock(addr)
+ mu.Lock()
+ defer mu.Unlock()
+ if a, err := s.memberAccount(addr); err != nil {
+ return "", err
+ } else if a != nil {
+ return a.Sqid, nil
+ }
+ mctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), landingMintTimeout)
+ defer cancel()
+ m, err := s.mintAccount(mctx, addr, addr)
if err != nil {
return "", err
}
return m.Sqid, nil
}
+// landingMintTimeout bounds a landing's mint once it no longer follows the
+// request's cancellation.
+const landingMintTimeout = 30 * time.Second
+
// memberAccount is currentAccount's first two cases WITHOUT the mint: the MRU
// account if the viewer is still a member of it, else their first membership
// by creation order, else nil. Split out because pages that merely want the
diff --git a/internal/console/server_test.go b/internal/console/server_test.go
index 53a58ee41..dac6be4bd 100644
--- a/internal/console/server_test.go
+++ b/internal/console/server_test.go
@@ -292,6 +292,7 @@ func signUp(t *testing.T, fx *consoleFixture, c *http.Client, code string) {
fx.fk.expectCode = code
fx.fk.mu.Unlock()
status, loc, _ = get(t, c, fx.ts.URL+"/auth/callback?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(q.Get("state")))
+ status, loc = followLanding(t, fx, c, status, loc)
// Signing in lands you in an account — the MRU one, your first membership,
// or one minted on the spot.
if status != http.StatusSeeOther || !strings.HasPrefix(loc, "/a/") {
@@ -299,6 +300,22 @@ func signUp(t *testing.T, fx *consoleFixture, c *http.Client, code string) {
}
}
+// followLanding follows a sign-in's redirect to the front page, where the
+// landing (and a first sign-in's mint) now happens, and returns the sign-in's
+// own status with the Location the front page then gave. Any other answer is
+// returned as it came.
+func followLanding(t *testing.T, fx *consoleFixture, c *http.Client, status int, loc string) (int, string) {
+ t.Helper()
+ if status != http.StatusSeeOther || (loc != "/" && !strings.HasPrefix(loc, "/?next=")) {
+ return status, loc
+ }
+ hs, hloc, _ := get(t, c, fx.ts.URL+loc)
+ if hs != http.StatusFound {
+ t.Fatalf("landing %s = %d -> %q, want 302", loc, hs, hloc)
+ }
+ return status, hloc
+}
+
func sessionToken(t *testing.T, fx *consoleFixture, c *http.Client) string {
t.Helper()
u, _ := url.Parse(fx.ts.URL)
diff --git a/internal/console/templates/check.html b/internal/console/templates/check.html
index adafdcccb..30f5403b2 100644
--- a/internal/console/templates/check.html
+++ b/internal/console/templates/check.html
@@ -6,13 +6,13 @@
{{if .Next}}<input type="hidden" name="next" value="{{.Next}}">{{end}}
<label for="code">{{.SigninCopy.CodeLabel}}</label>
<input id="code" type="text" name="code" inputmode="numeric" autocomplete="one-time-code" required autofocus>
- <button type="submit">{{.SigninCopy.CodeButton}}</button>
+ <button type="submit" data-busy>{{.SigninCopy.CodeButton}}</button>
</form>
{{if .CodeError}}<p class="error">{{.CodeError}}</p>{{end}}
<p class="small">{{.SigninCopy.Nothing}}</p>
<form class="signin" method="post" action="/auth/continue">
<input type="hidden" name="address" value="{{.Prefill}}">
{{if .Next}}<input type="hidden" name="next" value="{{.Next}}">{{end}}
- <button type="submit">{{.SigninCopy.AgainButton}}</button>
+ <button type="submit" data-busy>{{.SigninCopy.AgainButton}}</button>
</form>
{{template "bottom" .}}{{end}}
diff --git a/internal/console/templates/console_chrome.html b/internal/console/templates/console_chrome.html
index 6c762daa3..dcfe696db 100644
--- a/internal/console/templates/console_chrome.html
+++ b/internal/console/templates/console_chrome.html
@@ -71,6 +71,13 @@
border: 1px solid var(--rst-line-strong); border-radius: var(--rst-radius-sm); padding: 0.3rem 0.5rem;
box-shadow: var(--shadow-inset);
}
+ /* iOS Safari zooms the page in when it focuses a field whose text is under
+ 16px, and never zooms back out: the page is left cut off at the right.
+ Touch screens get 16px fields so focusing one leaves the page alone. */
+ @media (pointer: coarse) {
+ select, textarea, input[type=text], input[type=search], input[type=email], input[type=number],
+ input[type=password], input[type=url], input[type=tel] { font-size: max(16px, 1rem); }
+ }
select:disabled, input:disabled {
background: var(--rst-surface-2); color: var(--muted); box-shadow: none; cursor: not-allowed;
}
@@ -538,6 +545,13 @@
form.signin { display: flex; gap: 0.6rem; flex-wrap: wrap; margin: 0 0 1rem; }
form.signin input[type=text], form.signin input[type=email] { padding: 0.55rem 0.8rem; min-width: 16rem; }
form.signin label { flex-basis: 100%; font-weight: 600; }
+ /* On a phone the sign-in field and its button share the column's full
+ width, so the form reads as one block instead of a short box over a
+ shorter button. */
+ @media (max-width: 40rem) {
+ form.signin input[type=text], form.signin input[type=email] { flex: 1 1 100%; min-width: 0; }
+ form.signin button { flex: 1 1 100%; }
+ }
/* A button is a small raised module: a fill, a hairline edge in its own
darker tone, a short lip under it that it sinks into when pressed. The
variants below only swap the --btn-* tones, so hover, press and busy
diff --git a/internal/console/templates/email_link.html b/internal/console/templates/email_link.html
index e21ab2a0d..1e2b7611f 100644
--- a/internal/console/templates/email_link.html
+++ b/internal/console/templates/email_link.html
@@ -3,6 +3,6 @@
<form class="signin" method="post" action="/auth/email/link">
<input type="hidden" name="t" value="{{.LinkToken}}">
<input type="hidden" name="nonce" value="{{.LinkNonce}}">
- <button type="submit">{{if .StepUpLink}}{{.SigninCopy.StepUpLinkButton}}{{else}}{{.SigninCopy.LinkButton}}{{end}}</button>
+ <button type="submit" data-busy>{{if .StepUpLink}}{{.SigninCopy.StepUpLinkButton}}{{else}}{{.SigninCopy.LinkButton}}{{end}}</button>
</form>
{{template "bottom" .}}{{end}}
diff --git a/internal/console/templates/home.html b/internal/console/templates/home.html
index cd9944420..66ad11d2f 100644
--- a/internal/console/templates/home.html
+++ b/internal/console/templates/home.html
@@ -12,7 +12,7 @@
<label for="address">{{.SigninCopy.EmailLabel}}</label>
<input id="address" type="email" name="address" value="{{.Prefill}}" placeholder="{{.SigninCopy.EmailPlaceholder}}" autocomplete="email" required autofocus>
{{if .Next}}<input type="hidden" name="next" value="{{.Next}}">{{end}}
- <button type="submit">{{.SigninCopy.EmailButton}}</button>
+ <button type="submit" data-busy>{{.SigninCopy.EmailButton}}</button>
</form>
<p class="small">{{.SigninCopy.Small}}</p>
{{template "bottom" .}}{{end}}
diff --git a/internal/domains/mint.go b/internal/domains/mint.go
index 1fa33bfe1..c478398ec 100644
--- a/internal/domains/mint.go
+++ b/internal/domains/mint.go
@@ -12,6 +12,7 @@ import (
"errors"
"fmt"
"strings"
+ "sync"
"time"
"github.com/carlosframework/platform/internal/release"
@@ -142,29 +143,58 @@ func NextAccountID(ctx context.Context, s release.Store) (int64, error) {
if err != nil {
return 0, fmt.Errorf("domains: list accounts: %w", err)
}
- max := int64(ReservedAccountID)
+ var manifests []string
for _, key := range keys {
- if _, ok := AccountManifestSqid(key); !ok {
- continue
- }
- body, _, err := s.Get(ctx, key)
- if err != nil {
- // Unreadable is not "free": an id we cannot see is an id we must
- // not reuse, so a read failure fails the mint rather than risking
- // a collision.
- return 0, fmt.Errorf("domains: read %s: %w", key, err)
+ if _, ok := AccountManifestSqid(key); ok {
+ manifests = append(manifests, key)
}
- var m AccountManifest
- if err := json.Unmarshal(body, &m); err != nil {
- continue // unparseable: claims no id we can honour
+ }
+ // Every manifest is read, because a manifest's body (not its key) says
+ // which id it claims. The reads run nextIDReaders at a time: one after
+ // another they took about 25 ms each, so a deployment with a hundred
+ // accounts made every new person's first sign-in wait nearly three
+ // seconds (2026-11-07).
+ ids := make([]int64, len(manifests))
+ errs := make([]error, len(manifests))
+ sem := make(chan struct{}, nextIDReaders)
+ var wg sync.WaitGroup
+ for i, key := range manifests {
+ wg.Add(1)
+ sem <- struct{}{}
+ go func() {
+ defer wg.Done()
+ defer func() { <-sem }()
+ body, _, err := s.Get(ctx, key)
+ if err != nil {
+ // Unreadable is not "free": an id we cannot see is an id we
+ // must not reuse, so a read failure fails the mint rather
+ // than risking a collision.
+ errs[i] = fmt.Errorf("domains: read %s: %w", key, err)
+ return
+ }
+ var m AccountManifest
+ if err := json.Unmarshal(body, &m); err != nil {
+ return // unparseable: claims no id we can honour
+ }
+ ids[i] = m.ID
+ }()
+ }
+ wg.Wait()
+ max := int64(ReservedAccountID)
+ for i := range manifests {
+ if errs[i] != nil {
+ return 0, errs[i]
}
- if m.ID > max {
- max = m.ID
+ if ids[i] > max {
+ max = ids[i]
}
}
return skipReservedIDs(max + 1), nil
}
+// nextIDReaders is how many account manifests NextAccountID reads at once.
+const nextIDReaders = 16
+
// MintAccount allocates the next free account id and publishes its manifest,
// returning the id and its frozen sqid.
//
diff --git a/internal/domains/mint_test.go b/internal/domains/mint_test.go
index 5114b31f2..ba9781089 100644
--- a/internal/domains/mint_test.go
+++ b/internal/domains/mint_test.go
@@ -3,6 +3,7 @@ package domains_test
import (
"context"
"encoding/json"
+ "errors"
"strings"
"testing"
"time"
@@ -248,3 +249,37 @@ func (r *racingStore) Put(ctx context.Context, key string, body []byte, ifMatch
r.beforePut(key)
return r.Store.Put(ctx, key, body, ifMatch)
}
+
+// failingGetStore refuses to read one key.
+type failingGetStore struct {
+ release.Store
+ bad string
+}
+
+func (f failingGetStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if key == f.bad {
+ return nil, "", errors.New("synthetic read failure")
+ }
+ return f.Store.Get(ctx, key)
+}
+
+// The manifests are read several at a time; the answer is still the highest
+// claim over all of them, and one unreadable manifest still fails the mint
+// (an id nobody can see must not be handed out).
+func TestNextAccountIDReadsEveryManifest(t *testing.T) {
+ ctx := t.Context()
+ s := release.NewDirStore(t.TempDir())
+ for id := int64(2); id <= 60; id++ {
+ writeManifest(t, s, id, domains.Sqid(id))
+ }
+ // A manifest whose body claims more than its key says still counts.
+ writeManifest(t, s, 90, domains.Sqid(30)+"x")
+ got, err := domains.NextAccountID(ctx, s)
+ if err != nil || got != 91 {
+ t.Fatalf("NextAccountID = %d (%v), want 91", got, err)
+ }
+ bad := failingGetStore{Store: s, bad: domains.AccountManifestKey(domains.Sqid(41))}
+ if got, err := domains.NextAccountID(ctx, bad); err == nil {
+ t.Fatalf("NextAccountID with an unreadable manifest = %d, want an error", got)
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index feebf54e9..95d483abc 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -113,3 +113,4 @@ plan14-root-reads-region-ha-g2-fixes.tsv 3c1d54d297da31d147cdb4e1ad4627f759c8cb8
plan14-root-reads-fix-asset-e2e-unsized-flake.tsv 3c1d54d297da31d147cdb4e1ad4627f759c8cb8eae2db53cc92218db35e59c7b
plan14-root-reads-region-ha-g2r-fixes.tsv 5c6f157c56e24dc835edc534c5dc0e043e6527e8116e5bb470e68e4fd271796c
plan14-root-reads-fix-incomplete-domains-pass.tsv 61027a32e31cb7ce017304f526f668c26980999e2699a3013a82e2630164143e
+plan14-root-reads-signin-first-run-mobile.tsv 61027a32e31cb7ce017304f526f668c26980999e2699a3013a82e2630164143e
diff --git a/internal/provision/testdata/plan14-root-reads-signin-first-run-mobile.tsv b/internal/provision/testdata/plan14-root-reads-signin-first-run-mobile.tsv
new file mode 100644
index 000000000..878078d6e
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-signin-first-run-mobile.tsv
@@ -0,0 +1,3 @@
+# Census overlay signin-first-run-mobile, written by census-propose (#369). census-ruling-signin-first-run-mobile, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-signin-first-run-mobile.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage internal/domains b5925d633145236d4cdff2213805dd0fba262bc67cbf9001fe12f32e43941b37