carlos / platform Public

console: sign-in resolves through sign_in_methods; sessions record it

Co-Authored-By: GPT-6 Astra <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 17ca335f6c6188d6b8bd2e1e7e98bd218a920f6f parent 8ed6e41
3 files changed, +244 −17
  • internal/console/emailsignin.go +15 −14
  • internal/console/signinmethods_test.go +207 −0
  • internal/console/store.go +22 −3

Intent

Human

<task-notification> <task-id>bvo5g21b7</task-id> <tool-use-id>toolu_01Xaqug53FEm7ENqCRB5vrSP</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/1730ddc5-7bb6-4ebb-ab9b-85efe2e437e3/tasks/bvo5g21b7.output</output-file> <status>completed</status> <summary>Background command "Resume Task 1 with the census answer" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a20557a613632a75f</task-id> <tool-use-id>toolu_01KAeT15YQu2M2tjSTzdH67Y</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/1730ddc5-7bb6-4ebb-ab9b-85efe2e437e3/tasks/a20557a613632a75f.output</output-file> <status>completed</status> <summary>Agent "Review Task 1 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>- **Spec verdict:** ✅ Compliant. One item can't be verified here: the full console package run timed out at 600 s, so CI has to be the full check. Separately, Task 3 or Plan 2 should say how an email or Keymail sign-in reaches its person when the address is only held as another kind's alias. Today that sign-in would create a separate person. - **Quality verdict:** Approved. - **Critical/Important:** none. The review is at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-social-signin/.superpowers/sdd/2026-11-02-console-social-signin-1-methods/task-1-review.md`. It lists five Minor items: - The address-ownership check hard-codes `'email'` and `'keymail'` instead of using the existing constants. - The exported type and methods have no doc comments. - The code that sets the last-used time after a sign-in is roundabout. - The re-run test doesn't change its inputs between runs, so it never shows that `kind` is kept. - A note that the race safety depends on the store's single database connection.</result> <usage><subagent_tokens>63503</subagent_tokens><tool_uses>5</tool_uses><duration_ms>92730</duration_ms></usage> </task-notification>

Attributed to this commit: 14.3 g CO₂e (1,776,946 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-console-social-signin, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go
index 344e7f697..ebbbf7bd7 100644
--- a/internal/console/emailsignin.go
+++ b/internal/console/emailsignin.go
@@ -249,54 +249,55 @@ 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) {
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/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/store.go b/internal/console/store.go
index 3b1a37af4..12cc689af 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
@@ -2835,13 +2836,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
}
@@ -2873,6 +2880,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))