carlos / platform Public

console + carlos CLI: log an agent in by tapping a link

An agent session (e.g. Claude Code in the cloud, driven from a phone)
logs in with taps: carlos auth login prints the approval link with its
code; --no-wait/--wait let an agent relay it. The console's approval
page resolves the code from the link (Paul's R1), behind a lookup
budget checked before resolution; decisions keep their own budget,
CSRF and step-up. After Approve: go back to the agent, open your apps.

Spec docs/superpowers/specs/2026-11-07-agent-login-link-design.md
(rev 3.1; Astra spec rounds 1-3; any-browser email code cut by Paul).
Build: 5 tasks, task reviews, Astra branch rounds 1-3 READY; pending
login files never delete another attempt (Paul). Census approved
(#280). Copy: Luna under Paul's delegation.

Squashed from design-agent-login-link into main.
claude agent, operated by paul@keymail.dev f864af5efe6ad301a3e507e99c5c07589c24a186 parent a0133a5
31 files changed, +2,295 −180
  • auth.go +150 −56
  • auth_test.go +4 −7
  • authpending.go +146 −0
  • authpending_test.go +338 −0
  • docs/site/cli.md +12 −6
  • docs/superpowers/notes/census-proposal-agent-login-link.md +16 −0
  • docs/superpowers/plans/2026-11-07-agent-login-link.md +161 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-agent-login-link-branch-R2.md +38 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-agent-login-link-branch-R3.md +27 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-agent-login-link-branch.md +38 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-agent-login-link-branch-R2.md +27 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-agent-login-link-branch-R3.md +32 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-agent-login-link-branch.md +63 −0
  • docs/superpowers/reviews/agent-login-link-deferred.md +21 −0
  • docs/superpowers/specs/2026-11-07-agent-login-link-design.md +255 −0
  • docs/superpowers/specs/CODEX-FINDINGS-agent-login-link-R2.md +66 −0
  • docs/superpowers/specs/CODEX-FINDINGS-agent-login-link-R3.md +27 −0
  • docs/superpowers/specs/CODEX-FINDINGS-agent-login-link.md +85 −0
  • docs/superpowers/specs/CODEX-REVIEW-BRIEF-agent-login-link-R2.md +80 −0
  • docs/superpowers/specs/CODEX-REVIEW-BRIEF-agent-login-link-R3.md +85 −0
  • docs/superpowers/specs/CODEX-REVIEW-BRIEF-agent-login-link.md +68 −0
  • internal/console/authcli.go +149 −48
  • internal/console/authcli_test.go +296 −31
  • internal/console/claim_invariant_probes_read_test.go +1 −1
  • internal/console/cliplace.go +56 −0
  • internal/console/emailsignin_test.go +1 −1
  • internal/console/emailstepup_test.go +1 −1
  • internal/console/signincopy.go +26 −0
  • internal/console/templates/cli_approve.html +17 −29
  • internal/provision/testdata/plan14-root-reads-agent-login-link.tsv +8 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0

CI passed — run details

diff --git a/auth.go b/auth.go
index a721fa7bf..e9ed0a058 100644
--- a/auth.go
+++ b/auth.go
@@ -697,61 +697,52 @@ func loginConsole(flagValue string) (string, error) {
return normalizeConsole(base)
}
-func authLogin(out io.Writer, args []string) error {
- fs := flag.NewFlagSet("auth login", flag.ContinueOnError)
- fs.SetOutput(out)
- console := consoleOption(fs, "the console to log in to (default: the configured default, else "+defaultConsole+")")
- label := fs.String("label", "", "what to call this terminal on the console (default: user@host)")
- fs.Usage = flagUsage(fs, "")
- if err := fs.Parse(args); err != nil {
- return err
- }
- base, err := loginConsole(*console)
- if err != nil {
- return err
- }
- if *label == "" {
- *label = defaultLabel()
- }
- ctx := context.Background()
- c := newConsoleClient(base, "")
- var start startResponse
- if _, err := c.do(ctx, http.MethodPost, "/auth/cli/start", map[string]string{"label": *label}, &start); err != nil {
- return fmt.Errorf("starting the login at %s: %w", base, err)
+// Copy for the login screen. Plain words, no dashes.
+const (
+ loginOpenLink = "Open this link to approve this login:"
+ loginCheckCode = "The page will show the code %s. Approve only if it matches."
+)
+
+// agentLabel names a terminal that is an AI agent, so the approval page and
+// the token list say what asked rather than user@host. CLAUDECODE=1 is set by
+// Claude Code in every command it runs.
+func agentLabel(env func(string) string, fallback string) string {
+ if env("CLAUDECODE") != "1" {
+ return fallback
}
- if start.DeviceCode == "" || start.UserCode == "" {
- return fmt.Errorf("%s did not return a login code — is that a CARLOS console?", base)
- }
- // The BARE verification URI plus the code, never the ready-made
- // ?code=… link, even though the console offers one.
- //
- // A link that lands one click from an Approve button is the whole
- // device-code phishing attack: an attacker starts this flow, sends you
- // their link, and one click hands them a 90-day credential that acts as
- // you. The console refuses to approve from a prefilled code for that
- // reason, and printing the complete URL here would teach people that
- // following such a link is the normal way to do this — which is exactly
- // the habit the attack needs. Type the code.
- link := start.VerifyURI
- if link == "" {
- link = base + "/auth/cli"
+ host, err := os.Hostname()
+ if err != nil || host == "" {
+ host = "unknown-host"
}
- // Printed, never opened: this frequently runs over SSH, where opening a
- // browser would open it on the wrong machine.
- pal := colorFor(out)
- fmt.Fprintf(out, "\nOpen this in a browser signed in to %s:\n\n %s\n\n", base, pal.link(link))
- // The code is the one thing here a person has to read off the screen and
- // type somewhere else, so it is the one thing given weight.
- fmt.Fprintf(out, "and type this code:\n\n %s\n\n", pal.head(start.UserCode))
- mutedf(out, "Waiting for approval (this code expires in %d minutes)…", start.ExpiresIn/60)
+ return "Claude Code on " + host
+}
- deadline := loginDeadline(time.Now(), start.ExpiresIn)
- wait := pollWait(start.Interval)
+// loginWaitCap bounds one --wait whatever the pending file says. A variable
+// only so a test can cut a wait short without reaching the code's expiry.
+var loginWaitCap = maxLoginWait
+
+// errLoginGaveUp is pollLogin running out of time, not the console's verdict.
+var errLoginGaveUp = errors.New("gave up waiting for approval. run this again when you're at a browser")
+
+// loginExpiredMsg is the draft copy for a code that ran out its own life.
+const loginExpiredMsg = "that login code expired before it was approved; start again with carlos auth login --no-wait"
+
+// terminalLoginError marks a poll outcome after which the login can never be
+// approved (denied, expired, unknown), as opposed to a failure worth retrying.
+type terminalLoginError struct{ error }
+
+func (e terminalLoginError) Unwrap() error { return e.error }
+
+// pollLogin waits for the console to approve deviceCode and stores the
+// credential. Terminal outcomes come back as terminalLoginError.
+func pollLogin(ctx context.Context, c *consoleClient, base, deviceCode, label string, interval int, deadline time.Time, out io.Writer) error {
+ pal := colorFor(out)
+ wait := pollWait(interval)
for time.Now().Before(deadline) {
time.Sleep(wait)
var poll pollResponse
if _, err := c.do(ctx, http.MethodPost, "/auth/cli/poll",
- map[string]string{"device_code": start.DeviceCode}, &poll); err != nil {
+ map[string]string{"device_code": deviceCode}, &poll); err != nil {
// A hiccup mid-poll is not a failed login: keep waiting, the
// human is mid-approval.
continue
@@ -763,14 +754,14 @@ func authLogin(out io.Writer, args []string) error {
case "pending":
continue
case "denied":
- return errors.New("the console says that login was denied — nothing was issued")
+ return terminalLoginError{errors.New("the console says that login was denied. nothing was issued")}
case "expired":
- return errors.New("that login code expired before it was approved — run this again")
+ return terminalLoginError{errors.New("that login code expired before it was approved. run this again")}
case "unknown":
- return errors.New("the console does not recognise this login — run this again")
+ return terminalLoginError{errors.New("the console does not recognise this login. run this again")}
case "approved":
if poll.Token == "" {
- return errors.New("the console approved the login but returned no token")
+ return terminalLoginError{errors.New("the console approved the login but returned no token. run carlos auth login again")}
}
now := time.Now().UTC()
expires := now.Add(90 * 24 * time.Hour)
@@ -779,14 +770,16 @@ func authLogin(out io.Writer, args []string) error {
expires = t
}
}
+ // From here the console has consumed the attempt: a retry would be
+ // told "unknown". So a storage failure ends the attempt too.
f, err := loadCredentials()
if err != nil {
- return err
+ return terminalLoginError{fmt.Errorf("the console approved this login but the token could not be saved (%w). start a new login with carlos auth login", err)}
}
f.put(credential{Console: base, Address: poll.Address, Token: poll.Token,
- Label: *label, CreatedAt: now, ExpiresAt: expires})
+ Label: label, CreatedAt: now, ExpiresAt: expires})
if err := f.save(); err != nil {
- return fmt.Errorf("storing the credential: %w", err)
+ return terminalLoginError{fmt.Errorf("the console approved this login but the token could not be saved (%w). start a new login with carlos auth login", err)}
}
// Checked here as well as in whoami: this is the moment a bearer
// token first exists on this machine, and a pre-existing file with
@@ -803,7 +796,108 @@ func authLogin(out io.Writer, args []string) error {
return fmt.Errorf("the console answered with an unknown status %q", poll.Status)
}
}
- return errors.New("gave up waiting for approval — run this again when you're at a browser")
+ return errLoginGaveUp
+}
+
+func authLogin(out io.Writer, args []string) error {
+ fs := flag.NewFlagSet("auth login", flag.ContinueOnError)
+ fs.SetOutput(out)
+ console := consoleOption(fs, "the console to log in to (default: the configured default, else "+defaultConsole+")")
+ label := fs.String("label", "", "what to call this terminal on the console (default: user@host)")
+ noWait := fs.Bool("no-wait", false, "print the approval link and exit; finish with --wait (for agents that only see output when a command ends)")
+ wait := fs.Bool("wait", false, "finish a login started with --no-wait")
+ fs.Usage = flagUsage(fs, "")
+ if err := fs.Parse(args); err != nil {
+ return err
+ }
+ if *noWait && *wait {
+ return errors.New("--no-wait and --wait cannot be used together")
+ }
+ ctx := context.Background()
+ if *wait {
+ p, err := loadPendingLogin()
+ if err != nil {
+ return err
+ }
+ if p == nil {
+ return errors.New("no login waiting: run carlos auth login --no-wait first")
+ }
+ // The console comes from the file, not -console or the defaults: the
+ // code in it only means something there.
+ now := time.Now()
+ deadline := now.Add(loginWaitCap)
+ if !p.ExpiresAt.IsZero() && p.ExpiresAt.Before(deadline) {
+ deadline = p.ExpiresAt
+ }
+ if !p.ExpiresAt.IsZero() && !now.Before(p.ExpiresAt) {
+ // Already past its life: nothing to poll for.
+ if cerr := clearPendingLoginIf(p.DeviceCode); cerr != nil {
+ warnf(out, "Could not remove %s: %v", pendingLoginPath(), cerr)
+ }
+ return errors.New(loginExpiredMsg)
+ }
+ err = pollLogin(ctx, newConsoleClient(p.Console, ""), p.Console, p.DeviceCode, p.Label, p.Interval, deadline, out)
+ if errors.Is(err, errLoginGaveUp) && !p.ExpiresAt.IsZero() && !time.Now().Before(p.ExpiresAt) {
+ // The wait ended at the code's own expiry, which ends the attempt.
+ err = terminalLoginError{errors.New(loginExpiredMsg)}
+ }
+ var term terminalLoginError
+ if err == nil || errors.As(err, &term) {
+ if cerr := clearPendingLoginIf(p.DeviceCode); cerr != nil {
+ warnf(out, "Could not remove %s: %v", pendingLoginPath(), cerr)
+ }
+ }
+ return err
+ }
+ base, err := loginConsole(*console)
+ if err != nil {
+ return err
+ }
+ if *label == "" {
+ *label = agentLabel(os.Getenv, defaultLabel())
+ }
+ c := newConsoleClient(base, "")
+ var start startResponse
+ if _, err := c.do(ctx, http.MethodPost, "/auth/cli/start", map[string]string{"label": *label}, &start); err != nil {
+ return fmt.Errorf("starting the login at %s: %w", base, err)
+ }
+ if start.DeviceCode == "" || start.UserCode == "" {
+ return fmt.Errorf("%s did not return a login code. is it the right console?", base)
+ }
+ // The ready-made ?code= link is printed (Paul's ruling R1). Typing a code
+ // into a bare page is no help to an agent, whose human often reads the
+ // link out of a transcript, and the link is only a convenience: it
+ // approves nothing by itself. The controls that remain are on the
+ // console. The page shows the code, to be checked against this screen,
+ // and says what is asking. Approving needs a signed-in session plus a
+ // step-up on the Approve button. The account owner gets an email when a
+ // credential is issued, with a "That wasn't me" link that revokes it. And
+ // the code lapses after 10 minutes.
+ link := start.VerifyURIFull
+ if link == "" {
+ link = start.VerifyURI
+ }
+ if link == "" {
+ link = base + "/auth/cli"
+ }
+ // Printed, never opened: this frequently runs over SSH, where opening a
+ // browser would open it on the wrong machine.
+ pal := colorFor(out)
+ fmt.Fprintf(out, "\n%s\n\n %s\n\n", loginOpenLink, pal.link(link))
+ // The code is the one thing a person compares against the page, so it is
+ // the one thing given weight.
+ fmt.Fprintf(out, loginCheckCode+"\n\n", pal.head(start.UserCode))
+ deadline := loginDeadline(time.Now(), start.ExpiresIn)
+ if *noWait {
+ if err := savePendingLogin(pendingLogin{Console: base, DeviceCode: start.DeviceCode,
+ UserCode: start.UserCode, Label: *label, ExpiresAt: deadline, Interval: start.Interval}); err != nil {
+ return fmt.Errorf("saving the pending login: %w", err)
+ }
+ mutedf(out, "Once it is approved, run: carlos auth login --wait")
+ return nil
+ }
+ mutedf(out, "Waiting for approval (this code expires in %d minutes)…", start.ExpiresIn/60)
+ return pollLogin(ctx, c, base, start.DeviceCode, *label, start.Interval, deadline, out)
}
func authWhoami(out io.Writer, args []string) error {
diff --git a/auth_test.go b/auth_test.go
index b15d338bb..a6878f1f3 100644
--- a/auth_test.go
+++ b/auth_test.go
@@ -289,17 +289,14 @@ func TestAuthLoginStoresACredential(t *testing.T) {
if err := authLogin(&out, []string{"-console", fc.ts.URL, "-label", "paul@laptop"}); err != nil {
t.Fatalf("authLogin: %v\n%s", err, out.String())
}
- // The human is told where to go and what to TYPE — that IS the flow.
- for _, want := range []string{fc.ts.URL + "/auth/cli", "type this code", "WXYZ-4823", "paul@keymail.dev"} {
+ // The human is given the approval link and the code to check against it.
+ for _, want := range []string{fc.ts.URL + "/auth/cli?code=WXYZ-4823", "WXYZ-4823", "paul@keymail.dev"} {
if !strings.Contains(out.String(), want) {
t.Fatalf("login output missing %q:\n%s", want, out.String())
}
}
- // And never the ready-made ?code= link. Printing that would teach people
- // that following a link somebody sent them is how this works, which is
- // precisely the habit device-code phishing needs.
- if strings.Contains(out.String(), "?code=") {
- t.Fatalf("login printed a one-click approval link:\n%s", out.String())
+ if strings.Contains(out.String(), "type this code") {
+ t.Fatalf("login still asks to type the code:\n%s", out.String())
}
if got, _ := fc.label.Load().(string); got != "paul@laptop" {
t.Fatalf("label sent = %q, want paul@laptop", got)
diff --git a/authpending.go b/authpending.go
new file mode 100644
index 000000000..1e90747f8
--- /dev/null
+++ b/authpending.go
@@ -0,0 +1,146 @@
+package main
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+)
+
+// pendingLogin is a login started with --no-wait and not yet finished. It
+// records the console it was started against so --wait goes back to the same
+// place whatever -console or the defaults say by then.
+type pendingLogin struct {
+ Console string `json:"console"`
+ DeviceCode string `json:"device_code"`
+ UserCode string `json:"user_code"`
+ Label string `json:"label"`
+ ExpiresAt time.Time `json:"expires_at"`
+ Interval int `json:"interval"`
+}
+
+// pendingLoginPath is a directory beside the credentials file (so one
+// override, CARLOS_CREDENTIALS, moves both) holding one file per attempt.
+// One file per attempt means no process ever rewrites or removes another
+// attempt's file: a finishing --wait removes only its own exact path, so it
+// cannot take a newer --no-wait with it, and no OS lock is needed.
+func pendingLoginPath() string {
+ return filepath.Join(filepath.Dir(credentialsPath()), "login-pending.d")
+}
+
+// pendingLoginFile is the exact path for one attempt, named by a short hash
+// of its device code so the secret itself is not in a file name.
+func pendingLoginFile(deviceCode string) string {
+ sum := sha256.Sum256([]byte(deviceCode))
+ return filepath.Join(pendingLoginPath(), hex.EncodeToString(sum[:16])+".json")
+}
+
+// savePendingLogin writes this attempt's own file, 0600 through a temp file
+// in the same directory, and deletes no other live attempt: several can sit side by side. The device code is a secret until the login is claimed.
+func savePendingLogin(p pendingLogin) error {
+ dir := pendingLoginPath()
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return err
+ }
+ body, err := json.MarshalIndent(p, "", " ")
+ if err != nil {
+ return err
+ }
+ body = append(body, '\n')
+ tmp, err := os.CreateTemp(dir, ".pending-*")
+ if err != nil {
+ return err
+ }
+ defer os.Remove(tmp.Name())
+ if err := tmp.Chmod(0o600); err != nil {
+ tmp.Close()
+ return err
+ }
+ if _, err := tmp.Write(body); err != nil {
+ tmp.Close()
+ return err
+ }
+ if err := tmp.Close(); err != nil {
+ return err
+ }
+ if err := os.Rename(tmp.Name(), pendingLoginFile(p.DeviceCode)); err != nil {
+ return err
+ }
+ // Nothing else is touched except attempts that have already expired.
+ _, err = readPendingLogins(true)
+ return err
+}
+
+// readPendingLogins lists every attempt file. With sweep set it also removes
+// the expired ones, by exact path: an expired attempt is dead, so anyone may.
+// It never removes an unexpired file. The result holds unexpired attempts only.
+func readPendingLogins(sweep bool) ([]pendingLogin, error) {
+ dir := pendingLoginPath()
+ entries, err := os.ReadDir(dir)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ now := time.Now()
+ var live []pendingLogin
+ for _, e := range entries {
+ if !strings.HasSuffix(e.Name(), ".json") {
+ continue
+ }
+ path := filepath.Join(dir, e.Name())
+ raw, err := os.ReadFile(path)
+ if errors.Is(err, os.ErrNotExist) {
+ continue
+ }
+ if err != nil {
+ return nil, err
+ }
+ var p pendingLogin
+ if err := json.Unmarshal(raw, &p); err != nil {
+ return nil, errors.New(path + " is not readable as a pending login; delete it and run carlos auth login --no-wait again")
+ }
+ if !p.ExpiresAt.IsZero() && !now.Before(p.ExpiresAt) {
+ if sweep {
+ if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return nil, err
+ }
+ }
+ continue
+ }
+ live = append(live, p)
+ }
+ return live, nil
+}
+
+// loadPendingLogin returns the newest unexpired attempt (latest ExpiresAt),
+// or nil, nil when none is waiting. Expired files met on the way are removed.
+func loadPendingLogin() (*pendingLogin, error) {
+ live, err := readPendingLogins(true)
+ if err != nil || len(live) == 0 {
+ return nil, err
+ }
+ best := live[0]
+ for _, p := range live[1:] {
+ if p.ExpiresAt.After(best.ExpiresAt) {
+ best = p
+ }
+ }
+ return &best, nil
+}
+
+// clearPendingLoginIf removes the file for exactly this attempt, by its own
+// path. It never reads or removes another attempt's file, so a --wait that
+// finishes late cannot delete a login a newer --no-wait started. The name is
+// kept from the single-file version; the "if" is now the path itself.
+func clearPendingLoginIf(deviceCode string) error {
+ if err := os.Remove(pendingLoginFile(deviceCode)); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ return nil
+}
diff --git a/authpending_test.go b/authpending_test.go
new file mode 100644
index 000000000..c5a62d90c
--- /dev/null
+++ b/authpending_test.go
@@ -0,0 +1,338 @@
+package main
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestPendingLoginNewerSurvivesOlderWait(t *testing.T) {
+ useTempCredentials(t)
+ a := pendingLogin{Console: "https://a.example", DeviceCode: "dev-A", UserCode: "AAAA-1111", ExpiresAt: time.Now().Add(time.Minute)}
+ b := pendingLogin{Console: "https://b.example", DeviceCode: "dev-B", UserCode: "BBBB-2222", ExpiresAt: time.Now().Add(time.Minute)}
+ if err := savePendingLogin(a); err != nil {
+ t.Fatal(err)
+ }
+ if err := savePendingLogin(b); err != nil {
+ t.Fatal(err)
+ }
+ if err := clearPendingLoginIf(a.DeviceCode); err != nil {
+ t.Fatal(err)
+ }
+ got, err := loadPendingLogin()
+ if err != nil || got == nil || got.DeviceCode != "dev-B" {
+ t.Fatalf("after clearing A, pending = %+v, %v; want B kept", got, err)
+ }
+ if err := clearPendingLoginIf("dev-B"); err != nil {
+ t.Fatal(err)
+ }
+ if got, err := loadPendingLogin(); got != nil || err != nil {
+ t.Fatalf("after clearing B, pending = %+v, %v; want nil, nil", got, err)
+ }
+ // Clearing when nothing is there is not an error.
+ if err := clearPendingLoginIf("dev-B"); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// A --wait that loaded attempt A, then a --no-wait saved B, then A's cleanup
+// ran: B must survive and be what the next --wait picks.
+func TestPendingLoginInterleavedCleanupKeepsNewer(t *testing.T) {
+ useTempCredentials(t)
+ a := pendingLogin{Console: "https://a.example", DeviceCode: "dev-A", ExpiresAt: time.Now().Add(time.Minute)}
+ if err := savePendingLogin(a); err != nil {
+ t.Fatal(err)
+ }
+ loaded, err := loadPendingLogin() // the older --wait has A in hand
+ if err != nil || loaded == nil || loaded.DeviceCode != "dev-A" {
+ t.Fatalf("loaded = %+v, %v", loaded, err)
+ }
+ b := pendingLogin{Console: "https://b.example", DeviceCode: "dev-B", ExpiresAt: time.Now().Add(2 * time.Minute)}
+ if err := savePendingLogin(b); err != nil { // a newer --no-wait lands
+ t.Fatal(err)
+ }
+ if err := clearPendingLoginIf(loaded.DeviceCode); err != nil { // A's cleanup runs late
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(pendingLoginFile("dev-B")); err != nil {
+ t.Fatalf("B's file is gone: %v", err)
+ }
+ if got, _ := loadPendingLogin(); got == nil || got.DeviceCode != "dev-B" {
+ t.Fatalf("next --wait would pick %+v, want B", got)
+ }
+}
+
+// Two concurrent --no-wait writers: neither may delete the other's attempt.
+func TestPendingLoginConcurrentWritersKeepBoth(t *testing.T) {
+ useTempCredentials(t)
+ a := pendingLogin{Console: "https://a.example", DeviceCode: "dev-A", ExpiresAt: time.Now().Add(time.Minute)}
+ b := pendingLogin{Console: "https://b.example", DeviceCode: "dev-B", ExpiresAt: time.Now().Add(2 * time.Minute)}
+ if err := savePendingLogin(a); err != nil {
+ t.Fatal(err)
+ }
+ if err := savePendingLogin(b); err != nil {
+ t.Fatal(err)
+ }
+ // Each writer's post-save step runs again (its sweep of expired files).
+ if _, err := readPendingLogins(true); err != nil {
+ t.Fatal(err)
+ }
+ for _, c := range []string{"dev-A", "dev-B"} {
+ if _, err := os.Stat(pendingLoginFile(c)); err != nil {
+ t.Fatalf("%s's file is gone: %v", c, err)
+ }
+ }
+ if got, _ := loadPendingLogin(); got == nil || got.DeviceCode != "dev-B" {
+ t.Fatalf("load picked %+v, want B", got)
+ }
+}
+
+func TestPendingLoginExpiredFilesAreSweptOthersKept(t *testing.T) {
+ useTempCredentials(t)
+ dead := pendingLogin{Console: "https://a.example", DeviceCode: "dev-dead", ExpiresAt: time.Now().Add(-time.Second)}
+ live := pendingLogin{Console: "https://b.example", DeviceCode: "dev-live", ExpiresAt: time.Now().Add(time.Minute)}
+ if err := savePendingLogin(dead); err != nil {
+ t.Fatal(err)
+ }
+ if err := savePendingLogin(live); err != nil { // the save sweeps the dead one
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(pendingLoginFile("dev-dead")); !os.IsNotExist(err) {
+ t.Fatalf("expired file survived a save: %v", err)
+ }
+ if _, err := os.Stat(pendingLoginFile("dev-live")); err != nil {
+ t.Fatalf("unexpired file removed: %v", err)
+ }
+ // And a load sweeps too.
+ if err := savePendingLogin(pendingLogin{Console: "https://c.example", DeviceCode: "dev-dead2", ExpiresAt: time.Now().Add(-time.Second)}); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := loadPendingLogin(); got == nil || got.DeviceCode != "dev-live" {
+ t.Fatalf("load picked %+v, want live", got)
+ }
+ if _, err := os.Stat(pendingLoginFile("dev-dead2")); !os.IsNotExist(err) {
+ t.Fatal("expired file survived a load")
+ }
+}
+
+func TestAuthLoginApprovedButUnsavableEndsTheAttempt(t *testing.T) {
+ path := useTempCredentials(t)
+ fc := newFakeConsole(t)
+ var out bytes.Buffer
+ if err := authLogin(&out, []string{"-console", fc.ts.URL, "--no-wait"}); err != nil {
+ t.Fatal(err)
+ }
+ // A directory where the credentials file should be: load and save both fail.
+ if err := os.MkdirAll(path, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ err := authLogin(&out, []string{"--wait"})
+ if err == nil || !strings.Contains(err.Error(), "approved") || !strings.Contains(err.Error(), "could not be saved") {
+ t.Fatalf("err = %v, want approved-but-not-saved", err)
+ }
+ if p, _ := loadPendingLogin(); p != nil {
+ t.Fatalf("pending file survived a consumed attempt: %+v", p)
+ }
+}
+
+func TestPendingLoginFileMode(t *testing.T) {
+ useTempCredentials(t)
+ if err := savePendingLogin(pendingLogin{Console: "https://a.example", DeviceCode: "d"}); err != nil {
+ t.Fatal(err)
+ }
+ fi, err := os.Stat(pendingLoginFile("d"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fi.Mode().Perm() != 0o600 {
+ t.Fatalf("pending mode = %v, want 0600", fi.Mode().Perm())
+ }
+}
+
+func TestAuthLoginNoWaitThenWait(t *testing.T) {
+ useTempCredentials(t)
+ fc := newFakeConsole(t)
+ var out bytes.Buffer
+ if err := authLogin(&out, []string{"-console", fc.ts.URL, "--no-wait"}); err != nil {
+ t.Fatalf("--no-wait: %v\n%s", err, out.String())
+ }
+ if fc.polls.Load() != 0 {
+ t.Fatal("--no-wait polled")
+ }
+ if !strings.Contains(out.String(), fc.ts.URL+"/auth/cli?code=WXYZ-4823") {
+ t.Fatalf("--no-wait did not print the link:\n%s", out.String())
+ }
+ p, err := loadPendingLogin()
+ if err != nil || p == nil || p.Console != fc.ts.URL || p.DeviceCode != "device-secret" || p.UserCode != "WXYZ-4823" {
+ t.Fatalf("pending = %+v, %v", p, err)
+ }
+ if strings.Contains(out.String(), "device-secret") {
+ t.Fatal("printed the device code")
+ }
+
+ out.Reset()
+ // A different -console must be ignored: the pending file names the console.
+ if err := authLogin(&out, []string{"-console", "http://127.0.0.1:1", "--wait"}); err != nil {
+ t.Fatalf("--wait: %v\n%s", err, out.String())
+ }
+ f, _ := loadCredentials()
+ if c := f.find(fc.ts.URL); c == nil || c.Token != "cli-token" {
+ t.Fatalf("stored credential = %+v", c)
+ }
+ if p, _ := loadPendingLogin(); p != nil {
+ t.Fatalf("pending file survived an approved wait: %+v", p)
+ }
+}
+
+func TestAuthLoginPlainNeverTouchesPending(t *testing.T) {
+ useTempCredentials(t)
+ fc := newFakeConsole(t)
+ keep := pendingLogin{Console: "https://a.example", DeviceCode: "dev-keep", ExpiresAt: time.Now().Add(time.Minute)}
+ if err := savePendingLogin(keep); err != nil {
+ t.Fatal(err)
+ }
+ var out bytes.Buffer
+ if err := authLogin(&out, []string{"-console", fc.ts.URL}); err != nil {
+ t.Fatal(err)
+ }
+ if p, _ := loadPendingLogin(); p == nil || p.DeviceCode != "dev-keep" {
+ t.Fatalf("plain login changed the pending file: %+v", p)
+ }
+}
+
+func TestAuthLoginFlagsConflict(t *testing.T) {
+ useTempCredentials(t)
+ var out bytes.Buffer
+ if err := authLogin(&out, []string{"--wait", "--no-wait"}); err == nil {
+ t.Fatal("both flags accepted")
+ }
+}
+
+func TestAuthLoginWaitNoPending(t *testing.T) {
+ useTempCredentials(t)
+ var out bytes.Buffer
+ err := authLogin(&out, []string{"--wait"})
+ if err == nil || !strings.Contains(err.Error(), "no login waiting") {
+ t.Fatalf("--wait with nothing pending = %v", err)
+ }
+}
+
+func TestAuthLoginWaitTerminalStatesClear(t *testing.T) {
+ for _, status := range []string{"denied", "unknown", "expired"} {
+ t.Run(status, func(t *testing.T) {
+ useTempCredentials(t)
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]any{"status": status, "interval": 0})
+ }))
+ defer ts.Close()
+ if err := savePendingLogin(pendingLogin{Console: ts.URL, DeviceCode: "d1", ExpiresAt: time.Now().Add(time.Minute)}); err != nil {
+ t.Fatal(err)
+ }
+ var out bytes.Buffer
+ if err := authLogin(&out, []string{"--wait"}); err == nil {
+ t.Fatal("want an error")
+ }
+ if p, _ := loadPendingLogin(); p != nil {
+ t.Fatalf("%s left the pending file: %+v", status, p)
+ }
+ })
+ }
+ t.Run("transient keeps", func(t *testing.T) {
+ useTempCredentials(t)
+ old := loginWaitCap
+ loginWaitCap = 1500 * time.Millisecond
+ defer func() { loginWaitCap = old }()
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusBadGateway)
+ }))
+ defer ts.Close()
+ // Expiry is far away: the wait is cut short by the cap, not by the code's life.
+ if err := savePendingLogin(pendingLogin{Console: ts.URL, DeviceCode: "d1", ExpiresAt: time.Now().Add(time.Minute)}); err != nil {
+ t.Fatal(err)
+ }
+ var out bytes.Buffer
+ if err := authLogin(&out, []string{"--wait"}); err == nil {
+ t.Fatal("want an error")
+ }
+ if p, _ := loadPendingLogin(); p == nil {
+ t.Fatal("a transient failure removed the pending file")
+ }
+ })
+ t.Run("own expiry clears", func(t *testing.T) {
+ useTempCredentials(t)
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusBadGateway)
+ }))
+ defer ts.Close()
+ if err := savePendingLogin(pendingLogin{Console: ts.URL, DeviceCode: "d1", ExpiresAt: time.Now().Add(1500 * time.Millisecond)}); err != nil {
+ t.Fatal(err)
+ }
+ var out bytes.Buffer
+ err := authLogin(&out, []string{"--wait"})
+ if err == nil || !strings.Contains(err.Error(), "expired") {
+ t.Fatalf("err = %v, want expired", err)
+ }
+ if p, _ := loadPendingLogin(); p != nil {
+ t.Fatalf("expiry left the pending file: %+v", p)
+ }
+ })
+ t.Run("already expired does not poll", func(t *testing.T) {
+ useTempCredentials(t)
+ var polls atomic.Int32
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ polls.Add(1)
+ json.NewEncoder(w).Encode(map[string]any{"status": "pending"})
+ }))
+ defer ts.Close()
+ if err := savePendingLogin(pendingLogin{Console: ts.URL, DeviceCode: "d1", ExpiresAt: time.Now().Add(-time.Second)}); err != nil {
+ t.Fatal(err)
+ }
+ start := time.Now()
+ var out bytes.Buffer
+ err := authLogin(&out, []string{"--wait"})
+ // A dead attempt is swept on load, so there is nothing waiting.
+ if err == nil || !strings.Contains(err.Error(), "no login waiting") {
+ t.Fatalf("err = %v, want no login waiting", err)
+ }
+ if polls.Load() != 0 || time.Since(start) > 500*time.Millisecond {
+ t.Fatalf("polls = %d after %v, want none, prompt", polls.Load(), time.Since(start))
+ }
+ if p, _ := loadPendingLogin(); p != nil {
+ t.Fatal("pending file survived")
+ }
+ })
+}
+
+func TestAgentLabel(t *testing.T) {
+ host, _ := os.Hostname()
+ env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } }
+ if got := agentLabel(env(map[string]string{"CLAUDECODE": "1"}), "me@box"); got != "Claude Code on "+host {
+ t.Fatalf("agent label = %q", got)
+ }
+ if got := agentLabel(env(nil), "me@box"); got != "me@box" {
+ t.Fatalf("plain label = %q", got)
+ }
+
+ useTempCredentials(t)
+ t.Setenv("CLAUDECODE", "1")
+ fc := newFakeConsole(t)
+ var out bytes.Buffer
+ if err := authLogin(&out, []string{"-console", fc.ts.URL, "--no-wait"}); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := fc.label.Load().(string); got != "Claude Code on "+host {
+ t.Fatalf("sent label = %q", got)
+ }
+ if err := authLogin(&out, []string{"-console", fc.ts.URL, "-label", "mine", "--no-wait"}); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := fc.label.Load().(string); got != "mine" {
+ t.Fatalf("-label did not win: %q", got)
+ }
+}
diff --git a/docs/site/cli.md b/docs/site/cli.md
index fd2b2132a..c5a22399a 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -51,18 +51,24 @@ the platform holds itself to, and a command that broke it would be a bug.
### carlos auth
-Logs this terminal in to a console. `carlos auth login` prints a short code
-that you approve in a browser already signed in to that console, and the
-browser does not have to be on this machine, so this works over SSH. The
-token lands in `~/.carlos/credentials` at mode 0600, one entry per console,
-so a laptop can hold credentials for the flagship and your own deployment at
-once.
+Signs the agent or terminal in to a console. `carlos auth login` prints a link to
+open and a short code. Open the link in a browser already signed in to that
+console, check that the page shows the same code, and approve. The browser
+does not have to be on this machine, so this works over SSH. The token lands
+in `~/.carlos/credentials` at mode 0600, one entry per console, so a laptop
+can hold credentials for the flagship and your own deployment at once.
```sh
carlos auth login
carlos auth whoami
```
+Some agents, Claude Code among them, only show you a command's output when
+the command ends. For those, run `carlos auth login --no-wait`. It prints the
+link and the code, then exits. Show the link to the person, and once they
+have approved it, run `carlos auth login --wait` to finish. A code lasts ten
+minutes. If it runs out, start again with `--no-wait`.
+
Do not do this on a box. A box has no browser and no human, and the
long-lived token you would leave behind is a standing credential nobody is
watching; pass `--owner <address>` to
diff --git a/docs/superpowers/notes/census-proposal-agent-login-link.md b/docs/superpowers/notes/census-proposal-agent-login-link.md
new file mode 100644
index 000000000..c7dd5f07c
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-agent-login-link.md
@@ -0,0 +1,16 @@
+# Census approval: agent-login-link
+
+Ruling `census-ruling-agent-login-link`. The independent reviewer approves or rejects every change below, 2 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `.`.
+
+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.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `authpending.go:readPendingLogins`: reads +file:ReadDir, +file:ReadFile; written legacy, accepted-legacy, frozen
+- new `authpending.go:savePendingLogin`: reads +file:CreateTemp; written legacy, accepted-legacy, frozen
+
+Seal: `3dc3f6657527133a251c028772315bdd333b04c318fbbc6d90ef5047f15408ed` → `e820ef22ac677cd49aa9ca3f70d6bca9dea061bce3184ca86f0a3fc98f8de0eb`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-agent-login-link.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-11-07-agent-login-link.md b/docs/superpowers/plans/2026-11-07-agent-login-link.md
new file mode 100644
index 000000000..08a32805d
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-07-agent-login-link.md
@@ -0,0 +1,161 @@
+# Agent Login by Link Implementation Plan
+
+> **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:** An agent session (e.g. Claude Code in the cloud, driven from a phone) logs in to a CARLOS console by showing the person one link that they tap and approve; no typed code.
+
+**Architecture:** Console side: `GET /auth/cli?code=X` resolves the code behind a pre-checked lookup budget and renders the description + Approve/Deny; decisions keep their own pre-checked budget behind CSRF; new copy says "agent or terminal". CLI side: `carlos auth login` prints `verification_uri_complete`, labels agent sessions, and gains `--no-wait` / `--wait` with a 0600 pending-login file.
+
+**Tech Stack:** Go (net/http, html/template), the console's SQLite store, the module-root `carlos` CLI.
+
+**Spec:** `docs/superpowers/specs/2026-11-07-agent-login-link-design.md` (rev 3.1, approved by Paul 2026-11-07). Read it first.
+
+## Global Constraints
+
+- R2 is WITHDRAWN: email sign-in is unchanged. Do not touch `internal/console/emailsignin*.go` behaviour.
+- Approve stays a POST with the session CSRF token and `requireFreshAuth`; Deny stays ungated; `notifyCLIIssued` unchanged; request TTL `CLIAuthTTL` (10 min) unchanged.
+- No codes or tokens in logs; the only code in a URL is the user code in `verification_uri_complete`.
+- Every page works with JavaScript off.
+- All new or changed user-facing strings are DRAFTS until copy review; put them in `internal/console/signincopy.go` (console) or as consts in `auth.go` (CLI), never inline in several places. Copy rules: no em or en dashes, no customer or tenant names.
+- Locally run only the touched packages' tests with `-run`; CI runs the full suite. Leave GOCACHE at its default (sandbox off for go commands).
+- Census: `auth.go` is in the module-root package (census scope). Run `make census-card` at the end; the envelope re-pin needs a cross-family approval recorded on #280.
+- Land with `amadan branch merge carlos/platform <branch> -squash -expect <full sha>`.
+
+## Review Focus
+
+1. A signed-in browser forced (top-level GET) to many bad `/auth/cli?code=` links must still be able to Approve a real code afterwards. (Task 1 test)
+2. Past the lookup budget, a VALID code on GET must get the same 429 as a bad one: no oracle. Same for POST decisions. (Task 1 tests)
+3. A code that is approved, denied or expired, followed from the link, must not render an Approve button. (Task 2 test)
+4. An old `--wait` finishing after a newer `--no-wait` must leave the newer pending file in place. (Task 4 test)
+5. `--wait` run with a different `-console` or default must still poll the console that started the login. (Task 4 test)
+
+---
+
+### Task 1: Pre-checked guess budgets for CLI code lookups
+
+**Files:**
+- Modify: `internal/console/authcli.go` (cliLimits, newCLILimits, handleCLIApprove)
+- Test: `internal/console/authcli_test.go`
+
+**Interfaces:**
+- Produces: `cliLimits.lookAddr, lookIP *rateLimiter` (GET lookup budget, burst `cliGuessBurst`, window `cliRateWindow`); `func (s *Server) cliBudgetOpen(addrL, ipL *rateLimiter, addr, ip string, now time.Time) bool` (true when neither key is tripped; read-only, uses `rateLimiter.tripped`); `func (s *Server) cliBudgetSpend(addrL, ipL *rateLimiter, addr, ip string, now time.Time)` (calls `allow` on both). Existing `guessAddr/guessIP` become the DECISION budget.
+
+- [ ] **Step 1: Write the failing tests**
+
+`TestCLIDecisionBudgetRefusesValidCodeOnceSpent`: sign up, spend the decision budget with `cliGuessBurst` wrong `continue` POSTs, start a real login, POST `continue` with the VALID code → want 429 and body NOT containing the label. Same for `approve` (via `postGated`).
+
+- [ ] **Step 2: Run to verify failure**
+
+Run: `go test ./internal/console -run 'TestCLIDecisionBudget' -count=1`
+Expected: FAIL (today a valid code still resolves after the budget is spent).
+
+- [ ] **Step 3: Implement**
+
+In `handleCLIApprove`, before any `CLIAuthByUserCode` / `ApproveCLIAuth` / `DenyCLIAuth`, refuse with the existing "Too many attempts" 429 when `!s.cliBudgetOpen(s.cli.guessAddr, s.cli.guessIP, addr, ip, now)`. After a lookup or decision that finds nothing, `s.cliBudgetSpend(...)` (replacing the current `badCode` closure). Concurrency: `rateLimiter` is already mutex-guarded; the check-then-spend gap may let a burst exceed the budget by the number of concurrent requests, which is acceptable (note it in a comment).
+
+- [ ] **Step 4: Run tests**
+
+Run: `go test ./internal/console -run 'TestCLI' -count=1`
+Expected: PASS.
+
+- [ ] **Step 5: Commit** `console: check the CLI code budget before resolving a code`
+
+### Task 2: The approval page acts on the code in the link
+
+**Files:**
+- Modify: `internal/console/authcli.go` (handleCLIApprovePage, cliPage), `internal/console/templates/cli_approve.html`, `internal/console/signincopy.go`
+- Create: `internal/console/cliplace.go` (location line)
+- Test: `internal/console/authcli_test.go` (replace `TestCLIApprovalPageNeverApprovesFromALink`)
+
+**Interfaces:**
+- Consumes: Task 1's `cliBudgetOpen/cliBudgetSpend`, `lookAddr/lookIP`.
+- Produces: `type cliPlace struct{ Text, Attribution, AttributionURL string }`; `func (s *Server) cliPlaceFor(remoteAddr string) cliPlace` (one `s.cfg.GeoIPReader.Lookup` snapshot via `geoip.FromSnapshot`; Text = "Subdivision, Country" or "Country"; attribution from `geoip.AttributionFor(a.Source)`; empty when reader nil, StateOff or StateMiss); `cliPage.Place cliPlace`, `cliPage.Started time.Duration` (age of the request).
+
+- [ ] **Step 1: Write the failing tests**
+
+`TestCLIApprovalPageResolvesTheLinkCode`: sign up; start with label "Claude Code on box"; GET `/auth/cli?code=<code>` → 200, body contains the code, "Claude Code on box", `value="approve"`, `value="deny"`; poll still `pending` (GET changed nothing).
+`TestCLIApprovalPageStaleCodeShowsTheBox`: approve a code, then GET its link → body has the typed-code input and NO `value="approve"`; same for a denied code and an unknown code.
+`TestCLIApprovalPageLookupBudget`: GET bad codes until 429; then GET a VALID code → 429 and no label in body.
+`TestCLIForcedLookupsLeaveDecisionsWorking` (from Task 1): forced bad GETs past the lookup budget, then `postGated` approve of a real code → "Approved".
+`TestCLIPlaceAttribution`: with a fixture GeoIP reader (reuse apigeo tests' fixture) whose source is `DBIP-...`, `cliPlaceFor` returns non-empty Attribution "IP Geolocation by DB-IP"; with a nil reader returns zero `cliPlace`.
+
+- [ ] **Step 2: Run to verify failure**
+
+Run: `go test ./internal/console -run 'TestCLIApprovalPage|TestCLIForcedLookups|TestCLIPlace' -count=1`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**
+
+`handleCLIApprovePage` (signed in): normalise `?code=`; if code-shaped and `cliBudgetOpen(lookAddr, lookIP)` is false → 429 "Too many attempts"; else `CLIAuthByUserCode`; found → `p.Request`, `p.Place = s.cliPlaceFor(req.RemoteAddr)`, `p.Started = now.Sub(req.CreatedAt)`; not found → `cliBudgetSpend(lookAddr, lookIP)` and render the typed-code form with `p.Error = copyText("cli.link_unknown")`. Signed-out path unchanged except the banner copy key. Delete the "IT DELIBERATELY DOES NOT ACT ON ?code=" comment; replace with R1's reason and the controls that remain (session, CSRF on POST, step-up on Approve, issuance notice, deny, TTL, budgets). Template: when `.Request`, show code large, label + self-reported caveat, "From" IP + `.Place.Text` + attribution link when set, started-ago, expiry, the check question, Approve / That wasn't me. Remove "Nothing here is ever approved by following a link" text.
+
+Draft copy keys (signincopy.go; copy review later): `cli.title` "Approve a sign-in"; `cli.lede` "{label} is asking to use Carloku as you." (the console's brand name, from the same config the header brand uses (CARLOS_CONSOLE_NAME), never a literal "Carloku"); `cli.check` "Does your agent show this code?"; `cli.not_me` "If you didn't just ask an agent or terminal to log in, press That wasn't me."; `cli.link_unknown` "That link's code has expired or was already used. Ask your agent to start the login again."; `home.cli_prompt` "Sign in to connect your agent or terminal."
+
+- [ ] **Step 4: Run tests**
+
+Run: `go test ./internal/console -run 'TestCLI|TestClaimConsoleMutationInvariant' -count=1`
+Expected: PASS (update any probe in `claim_invariant_probes_*` that asserted the old page text).
+
+- [ ] **Step 5: Commit** `console: approve a CLI login from the code in its link`
+
+### Task 3: After approval, no dead end
+
+**Files:**
+- Modify: `internal/console/templates/cli_approve.html` (cli_decided), `internal/console/authcli.go` (handleCLIApprove approve branch), `internal/console/signincopy.go`
+- Test: `internal/console/authcli_test.go`
+
+**Interfaces:**
+- Consumes: Task 2's `cliPage`.
+- Produces: `cliPage.Label string`. The apps link is `href="/"`: the front page lands a signed-in person in their current account (handleHome), minting one if needed.
+
+- [ ] **Step 1: Write the failing test**
+
+`TestCLIApprovedPagePointsBack`: approve a login labelled "Claude Code on box" → body contains "Claude Code on box" and `href="/"`, and does not contain "terminal".
+
+- [ ] **Step 2: Run** `go test ./internal/console -run TestCLIApprovedPagePointsBack -count=1` → FAIL.
+
+- [ ] **Step 3: Implement** Read the request's label before approving (CLIAuthByUserCode) so the decided page can name it. Draft copy: `cli.approved` "Connected. Go back to {label}; it carries on by itself."; `cli.open_apps` "Open your apps"; `cli.denied` "Nothing was issued. That sign-in can't be approved now; if it wasn't yours, whoever started it got nothing."; settings link text `cli.settings_link` "agents and terminals".
+
+- [ ] **Step 4: Run** `go test ./internal/console -run 'TestCLI' -count=1` → PASS.
+
+- [ ] **Step 5: Commit** `console: approved sign-in says go back to the agent`
+
+### Task 4: CLI prints the link, labels agents, and can relay
+
+**Files:**
+- Modify: `auth.go` (authLogin, defaultLabel, the print block ~725-747)
+- Create: `authpending.go` (pending-login file)
+- Test: `auth_test.go`, create `authpending_test.go`
+
+**Interfaces:**
+- Produces: `type pendingLogin struct{ Console, DeviceCode, UserCode, Label string; ExpiresAt time.Time; Interval int }`; `func pendingLoginPath() string` (beside `credentialsPath()`: same dir, name `login-pending`); `func savePendingLogin(p pendingLogin) error` (atomic 0600, same pattern as `credentialFile.save`); `func loadPendingLogin() (*pendingLogin, error)` (missing file → nil, nil); `func clearPendingLoginIf(deviceCode string) error` (delete only when the file still holds deviceCode); `func agentLabel(env func(string) string, fallback string) string` ("Claude Code on <host>" when `CLAUDECODE=1`, else fallback); `func pollLogin(ctx, c *consoleClient, base, deviceCode, label string, interval int, deadline time.Time, out io.Writer) error` (today's poll loop extracted; stores the credential on approval).
+
+- [ ] **Step 1: Write the failing tests**
+
+Update `TestAuthLoginStoresACredential`: output now CONTAINS `fc.ts.URL + "/auth/cli?code=WXYZ-4823"` and "WXYZ-4823", and no longer "type this code" (remove the "never ?code=" assertion and its comment).
+`TestAuthLoginNoWaitThenWait`: `authLogin(-console X, --no-wait)` returns nil immediately with the link printed; `loadPendingLogin` has Console X; then `authLogin(--wait)` with a DIFFERENT `-console` stores a credential for X and removes the pending file.
+`TestAuthLoginWaitNoPending`: `--wait` with no file → error mentioning "no login waiting".
+`TestPendingLoginNewerSurvivesOlderWait`: save A; save B; `clearPendingLoginIf(A.DeviceCode)`; file still holds B.
+`TestPendingLoginFileMode`: saved file mode is 0600.
+`TestAuthLoginWaitTerminalStatesClear` (denied/unknown/expired via the fake console): file removed; transient poll error keeps it.
+`TestAgentLabel`: `CLAUDECODE=1` → "Claude Code on <host>"; unset → fallback; `-label` still wins (via authLogin).
+
+- [ ] **Step 2: Run** `go test . -run 'TestAuthLogin|TestPendingLogin|TestAgentLabel' -count=1` → FAIL.
+
+- [ ] **Step 3: Implement** Flags `--no-wait` and `--wait` (mutually exclusive; error if both). `--no-wait`: start, print, `savePendingLogin`, return. `--wait`: load (nil → error "no login waiting: run carlos auth login --no-wait first"), `pollLogin` against `p.Console` (ignore `-console`), then `clearPendingLoginIf(p.DeviceCode)` on approved/denied/unknown/expired; keep the file on transient errors. Plain login: unchanged flow, never touches the pending file. Replace the print block: draft CLI copy consts `loginOpenLink` "Open this link to approve this login:" and `loginCheckCode` "The page will show the code %s. Approve only if it matches."; replace the phishing comment with R1's reason and the remaining controls. `--help` text for `--no-wait`: "print the approval link and exit; finish with --wait (for agents that only see output when a command ends)".
+
+- [ ] **Step 4: Run** `go test . -run 'TestAuth|TestPendingLogin|TestAgentLabel' -count=1` → PASS. Then `GOOS=darwin go build ./... && GOOS=windows go build ./...`.
+
+- [ ] **Step 5: Commit** `carlos auth login: print the approval link; --no-wait and --wait`
+
+### Task 5: Docs, copy review, census, branch review
+
+**Files:**
+- Modify: `docs/site/cli.md` (auth login section: link flow, agents use `--no-wait` then `--wait`)
+- Create: `copy-review/strings.json` on the branch (every draft string from Tasks 2-4 and the docs paragraph)
+- Census overlay via `make census-propose`
+
+- [ ] **Step 1:** Docs paragraph (draft): how an agent logs in (`--no-wait`, show the link, `--wait`).
+- [ ] **Step 2:** Copy review of all drafts (copy-review skill; Paul edits). Apply approved text verbatim to signincopy.go, auth.go consts, templates, docs; rerun Tasks 2-4 tests.
+- [ ] **Step 3:** `make census-card`; write CLAIMS; `make census-propose NAME=agent-login-link CLAIMS=<file>`; `go test ./internal/provision -run TestPlan14RootReadCensus -count=1` → PASS.
+- [ ] **Step 4:** Whole-branch review (Astra, cross-family, brief from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`, includes the census verdict). Fix per stopping rules.
+- [ ] **Step 5:** CI green on the tip; ask Paul to merge; release via the agent manager (8a3d302) like v0.34.21 (console + CLI: publish, tap, apt; dev console then flagship console in a #421 lock).
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-agent-login-link-branch-R2.md b/docs/superpowers/reviews/CODEX-FINDINGS-agent-login-link-branch-R2.md
new file mode 100644
index 000000000..3f4fb6665
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-agent-login-link-branch-R2.md
@@ -0,0 +1,38 @@
+Reviewed `d532ad9b..47eefded7a1a89803327365c7124e35f1e75bb6e`, branch round 2 of 3.
+
+- **Round-1 P1: partly resolved.** Exact-path waiter cleanup is safe, but concurrent writers can still erase the newest attempt.
+- **Round-1 P2: resolved.** Credential load/save failures after approval now return `terminalLoginError`, preserve the underlying error, explain that another login is needed, and trigger pending-file cleanup.
+
+**P1 — Concurrent `--no-wait` processes can delete both pending attempts.**
+
+Verified by source inspection at [authpending.go:75](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/authpending.go:75). Each writer publishes its file, lists the directory, then unconditionally removes every other `.json` file.
+
+A valid interleaving is:
+
+1. A publishes its file.
+2. Newer B publishes its file.
+3. A and B each list both files.
+4. A deletes B; B deletes A.
+5. Both return success. A subsequent `--wait` reports no pending login.
+
+The new test runs saves sequentially, so it cannot catch this. An in-memory model of the publication, directory snapshot and removal steps confirmed the failing interleaving; this was not execution of the Go implementation.
+
+**Invariant / fault family:** Completing an older attempt must never erase its replacement; newest-wins must survive concurrent writers.
+
+**Fix direction:** Enforce publication and retirement through one cross-process ownership protocol, with a deterministic test forcing this interleaving. This is the second consecutive round in the same fault family, so stopping rule 2 applies before another fix. The choices are to refuse concurrent starts before creating an attempt, cut replacement support, or enforce the invariant centrally with a guard test. I recommend the third.
+
+No additional P2 or P3 findings in the scoped fixes.
+
+The census verdicts below concern root authority and do not waive the P1:
+
+| Census item | Verdict | Evidence and reason |
+|---|---|---|
+| `loadPendingLogin` | **Approve** | [authpending.go:94](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/authpending.go:94): `ReadDir` and `ReadFile` remain within operator-selected CLI authentication state. `accepted-legacy` fits these reads. |
+| `savePendingLogin` | **Approve** | [authpending.go:45](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/authpending.go:45): temporary-file creation and directory enumeration remain beside the credential store; no new root-service input or execution authority. |
+| Module-root envelope `.` | **Approve** | Reviewed the changed pending-file functions and [approval handling](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/auth.go:762), including their callers. No expanded root authority or weakened root validation in this fix range. |
+
+Round-1 deferred-minors triage otherwise remains unchanged; its approved-then-storage-failure item is resolved.
+
+Targeted Go tests and Darwin/Windows build attempts all stopped before compilation because the sandbox denied creation of Go’s build directory. Cross-platform build and runtime behavior therefore remain unverified. Changed Go files pass formatting and whitespace checks; the full diff reports trailing whitespace in the recorded round-1 findings. No files were edited.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-agent-login-link-branch-R3.md b/docs/superpowers/reviews/CODEX-FINDINGS-agent-login-link-branch-R3.md
new file mode 100644
index 000000000..173046b3c
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-agent-login-link-branch-R3.md
@@ -0,0 +1,27 @@
+Reviewed `47eefded..8f34d188ea21cd9aa6503e626e5ceb5bffdd46d7`, round 3 of 3.
+
+**Round-2 P1: resolved.** Writers publish separate files and sweep only expired attempts. Temporary files are excluded. Fresh attempts use fresh device codes, so publication cannot replace the expired path a sweeper has read. Waiter cleanup removes only its own path. `loadPendingLogin` selects the latest expiry among unexpired attempts. Evidence: [publication and sweep](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/authpending.go:54), [selection and cleanup](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/authpending.go:123).
+
+No new P1 or P2 findings.
+
+**P3 — The new tests overstate their coverage.** Verified by source inspection:
+
+- [Concurrent-writers test](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/authpending_test.go:72) saves sequentially; it does not exercise overlapping publication and sweeping.
+- [Expiry-sweep test](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/authpending_test.go:96) saves already-expired fixtures, which are immediately swept by `savePendingLogin`. Consequently, the load assertion would pass even if loading stopped sweeping.
+
+Follow-up: force overlapping writer/sweeper steps and place an expired fixture directly on disk before testing load cleanup. **Invariant:** regression tests must exercise the lifecycle operations they claim to protect. This does not reopen review.
+
+The census verdicts apply to the pinned commit:
+
+| Item | Verdict and evidence |
+|---|---|
+| `readPendingLogins` | **Approve.** [Line 81](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/authpending.go:81): directory and file reads remain within operator-selected CLI authentication state; `accepted-legacy` fits. |
+| `savePendingLogin` | **Approve.** [Line 44](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/authpending.go:44): retains the temporary-file, 0600, rename pattern; subsequent sweeping introduces no root-service input or execution authority. |
+| `loadPendingLogin` delegation | **Approve.** [Line 123](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/authpending.go:123): reads through `readPendingLogins`; no separate direct-read disposition is needed. |
+| Module-root envelope `.` | **Approve.** Reviewed the root-package changes against `origin/main`, including [authentication callers](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/auth.go:801) and credential persistence. No expanded root authority or weakened root validation. |
+
+Previous deferred-minor triage remains unchanged. Add the test-coverage item to the follow-up list.
+
+Targeted login and census tests both stopped before compilation because the read-only sandbox prevented Go from creating its work directory; runtime and census checks remain unverified. Changed Go files pass formatting, and the scoped diff passes whitespace checks. No files were edited.
+
+**READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-agent-login-link-branch.md b/docs/superpowers/reviews/CODEX-FINDINGS-agent-login-link-branch.md
new file mode 100644
index 000000000..f9bfbd6ef
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-agent-login-link-branch.md
@@ -0,0 +1,38 @@
+Reviewed `432135ae..d532ad9b`, branch review round 1. Two findings: one P1 and one P2. Evidence below is verified by source inspection. Targeted tests could not start because the read-only sandbox prevented Go from creating its build directory. Formatting and `git diff --check` passed.
+
+1. **P1 — An older wait can delete a newer pending login.**
+ Evidence: [authpending.go:82](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/authpending.go:82), together with replacement at line 58.
+
+ `clearPendingLoginIf(A)` reads A, another process saves B through `os.Rename`, then A’s cleanup removes the path now holding B. B’s device code is lost, so its subsequent `--wait` cannot complete. The “two syscalls wide” comment acknowledges the window but does not protect it. The existing test replaces A before cleanup starts, so it misses this interleaving.
+
+ **Fix:** Serialize replacement and compare/remove under the same cross-process lock, with Darwin and Windows support, or use an equivalent safe ownership protocol. Add a test that forces replacement between the comparison and deletion.
+
+ **Invariant / fault family:** Completing an older attempt must never erase its replacement.
+
+2. **P2 — Approval followed by a credential-storage failure leaves an uncollectable pending attempt.**
+ Evidence: [auth.go:773](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/auth.go:773) and [auth.go:842](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/auth.go:842). The server consumes the attempt when returning the token: [authstore.go:593](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/authstore.go:593).
+
+ If approval succeeds but loading or saving credentials fails, `pollLogin` returns an ordinary error. Cleanup consequently retains the pending file, although the server has already consumed the attempt. Retrying cannot recover that token; it receives `unknown`.
+
+ **Fix:** Track the terminal server outcome independently of credential-storage success. Clear only the matching pending attempt after an approved response, preserve the storage error, and explain that a new login is needed. Cover the storage-failure case.
+
+ **Invariant / fault family:** Approved attempts end the pending-file lifecycle; only retryable attempts remain.
+
+No additional P3 findings.
+
+The census verdicts apply to the pinned commit and the card’s root-authority criteria; they do not waive the lifecycle findings.
+
+| Census item | Verdict | Evidence and reason |
+|---|---|---|
+| `authpending.go:loadPendingLogin` | **Approve** | [Line 62](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/authpending.go:62): reads the operator’s pending file beside the existing credential store. Calls originate from explicit CLI login operations. The recorded `accepted-legacy` disposition fits this read. |
+| `authpending.go:savePendingLogin` | **Approve** | [Line 31](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/authpending.go:31): uses the existing credential-store pattern—same-directory temporary file, mode 0600 before writing, close, rename. No new root-service input or execution authority. |
+| Module-root envelope `.` | **Approve** | Reviewed the changed functions in `auth.go` and `authpending.go`, their callers, credential persistence, console client, and [auth dispatch](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/main.go:180). Changes remain within user-invoked authentication; no root, termination, or production-storage behavior changes. |
+
+Deferred-minors triage:
+
+- **Must fix before merge:** Task 4’s approved-then-store-failure item, covered by P2 above.
+- **Already addressed:** The lede explicitly calls the label self-reported. Template em dashes were removed.
+- **May remain deferred:** Budget-ordering and POST refusal-body test gaps; expired-GET and hostile-label test gaps; attribution layout and `noreferrer`; duplicated 429 copy; stale copy comments/key; misplaced test comment; unused receiver, deny-label lookup, and decided-page `Days`; test-only mutable wait cap; sleep overshoot.
+- **No change required:** The accepted shared-NAT budget trade-off, decided-page simplification, settings-link placement, and `emptyOrDash` ruling. `loginDeadline` remains used when starting an attempt.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-agent-login-link-branch-R2.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-agent-login-link-branch-R2.md
new file mode 100644
index 000000000..5fef91cdf
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-agent-login-link-branch-R2.md
@@ -0,0 +1,27 @@
+# Review brief: branch agent-login-link build, round 2 of 3 (scoped)
+
+Repo carlos/platform, branch `design-agent-login-link`, commit: the commit
+that adds this file. Round 1: `CODEX-FINDINGS-agent-login-link-branch.md`
+beside this file (P1 pending-file race, P2 approved-then-store-failure;
+census APPROVED at d532ad9b).
+
+Scope: the fix range d532ad9b..HEAD only (commit 349cb549 "one pending file
+per attempt; approved ends the attempt", plus the re-proposed census
+overlay).
+
+1. One line per round-1 finding: resolved, partly, or not. The P1 fix is a
+ controller ruling: one file per attempt under login-pending.d/ named by a
+ hash of the device code; --no-wait removes other attempts' files;
+ --wait loads the newest unexpired and removes only its own exact path.
+ Check that no interleaving of concurrent `--no-wait` and `--wait`
+ processes can delete a newer attempt's file, that newest-wins still
+ holds, and that it builds and behaves on darwin and windows.
+2. New breakage in the fix range only.
+3. CENSUS: `docs/superpowers/notes/census-proposal-agent-login-link.md`,
+ re-proposed (loadPendingLogin and savePendingLogin now also ReadDir).
+ Give the census verdict per unit and for the envelope.
+
+Severity as round 1 (P1 blocks; P2 fixed without another round; P3 follow-up).
+End with exactly one verdict: READY, READY AFTER FIXES, or NOT READY.
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents. No
+full suites; targeted go test -run is fine.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-agent-login-link-branch-R3.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-agent-login-link-branch-R3.md
new file mode 100644
index 000000000..96f5da644
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-agent-login-link-branch-R3.md
@@ -0,0 +1,32 @@
+# Review brief: branch agent-login-link build, round 3 of 3 (scoped, final)
+
+Repo carlos/platform, branch `design-agent-login-link`, commit: the commit
+that adds this file. Earlier rounds beside this file:
+`CODEX-FINDINGS-agent-login-link-branch.md` (round 1) and `-R2.md` (round 2).
+
+Paul's ruling after round 2 (stopping rule 2), recorded in the spec §2: a
+process NEVER deletes another unexpired attempt's pending file. A file is
+removed only by its own `--wait` (approved, denied, unknown, expired,
+approved-but-unsavable) by exact path, or by anyone once it has expired.
+`--wait` picks the newest unexpired attempt. Several live attempts may
+coexist up to the 10-minute lifetime (accepted cost). Do not re-argue it.
+
+Scope: 47eefded..HEAD (commit 1201ebcc "never delete another attempt's
+pending file", the spec update, and the re-proposed census overlay).
+
+1. One line for round 2's P1: resolved, partly, or not. Check that no
+ interleaving of concurrent `--no-wait` and `--wait` processes can delete
+ an unexpired attempt that is not the deleter's own (including the expiry
+ sweep racing a writer that is saving a fresh file), and that `--wait`
+ still finds the newest unexpired attempt.
+2. New breakage in the fix range only.
+3. CENSUS: `docs/superpowers/notes/census-proposal-agent-login-link.md`
+ re-proposed (new readPendingLogins; savePendingLogin changed;
+ loadPendingLogin now reads through readPendingLogins). Verdict per unit
+ and for the envelope.
+
+This is the last round: a NOT READY also says whether the P1s share one
+cause and whether refusing the case up front or cutting the feature would
+remove them. Severity as before. End with exactly one verdict: READY, READY
+AFTER FIXES, or NOT READY. Do not edit files. No subagents. Targeted go test
+-run only.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-agent-login-link-branch.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-agent-login-link-branch.md
new file mode 100644
index 000000000..961cb20b7
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-agent-login-link-branch.md
@@ -0,0 +1,63 @@
+# Review brief: branch agent-login-link build, round 1 of 3
+
+Repo carlos/platform, branch `design-agent-login-link`, commit: the commit
+that adds this file. Under review: the diff `432135aefefdd871414ee24a823ae275491c73b0..HEAD` (main already merged
+in; review only this branch's changes).
+Authorities: `docs/superpowers/specs/2026-11-07-agent-login-link-design.md`
+(rev 3.1, approved by Paul) and its plan
+`docs/superpowers/plans/2026-11-07-agent-login-link.md`.
+
+You are an independent reviewer. Read the spec, then the diff and the code it
+reaches, and check the build against the spec.
+
+## Fixed: do not re-argue
+
+- Paul's rulings in the spec's "Why" (R1 approve by link after checking the
+ code; R2 withdrawn: email sign-in unchanged; R3 later slice).
+- Copy text was approved by Luna under Paul's delegation (rows in the
+ commit "copy: agent login by link"); review meaning and safety only.
+- Controller rulings and deferred minors so far:
+ `docs/superpowers/reviews/agent-login-link-deferred.md`. Triage which
+ deferred minors must be fixed before merge.
+
+## What to check
+
+1. The approval gate: GET /auth/cli?code=X resolves only behind the GET
+ lookup budget, writes nothing else, never spends the decision budget;
+ POST continue/approve/deny check the decision budget before resolving;
+ CSRF and step-up on Approve intact; Deny ungated; same 429 whatever the
+ code past a budget; no Approve button for stale codes; output escaped;
+ no code or token logged.
+2. The CLI: `--no-wait` prints verification_uri_complete and the code and
+ exits; the pending file (0600, atomic, beside credentials, records the
+ console); `--wait` uses the stored console, deletes only its own attempt,
+ ends on approved/denied/unknown/expired (including its own expiry), keeps
+ the file on transient failure; plain login untouched; token never printed;
+ darwin/windows portability.
+3. Anything the spec requires that the build misses, or the build adds that
+ the spec doesn't ask for.
+4. CENSUS: `docs/superpowers/notes/census-proposal-agent-login-link.md`
+ (two new units authpending.go:loadPendingLogin and savePendingLogin; the
+ module-root envelope re-pinned). Give the census verdict the card asks for
+ (approve or reject per unit and for the envelope, 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. 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 with evidence (file:line, verified), failure
+scenario, fix, and the invariant it breaks. Then the census verdict. Then the
+deferred-minors triage (must-fix before merge or not). End with exactly one
+verdict: **READY**, **READY AFTER FIXES** (no P1; listed P2s fixed without
+another round) or **NOT READY**.
+
+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 touched
+packages is fine (default GOCACHE).
diff --git a/docs/superpowers/reviews/agent-login-link-deferred.md b/docs/superpowers/reviews/agent-login-link-deferred.md
new file mode 100644
index 000000000..68e84bcaf
--- /dev/null
+++ b/docs/superpowers/reviews/agent-login-link-deferred.md
@@ -0,0 +1,21 @@
+Ruling: build on design-agent-login-link (spec + plan + code one branch, squash at merge) — one page for Paul — cost if wrong: none, squash collapses it.
+Ruling: implementers Sonnet (T1, T3, T4) / Opus (T2, security gate + template); task reviews Opus for T1/T2 (security gate), Sonnet for T3/T4; final review Astra (cross-family, also census) — cost if wrong: extra review spend only.
+Task 1: minor (deferred): test doesn't pin budget-before-step-up ordering (use postForm for approve past budget)
+Task 1: minor (deferred): test doesn't compare past-budget 429 body for wrong vs valid code
+Task 1: minor (deferred): spec-accepted trade-off: spent IP budget on shared NAT can block Deny/Approve for a window
+Task 1: minor (deferred): unused receiver on cliBudgetOpen/cliBudgetSpend (signature mandated)
+Ruling: Task 2 banner uses new key cli.signin_prompt; home.cli_prompt is pinned to approved copy by a test, retire it in Task 5 after copy review — cost if wrong: one dead copy key until T5
+Ruling: location line renders the country NAME (countryName, analyticsdisplay.go) with the subdivision code in brackets, e.g. "United Kingdom (GB-ENG)", instead of "GB-ENG, GB" — spec says "country and subdivision as handleAPIGeo gives them"; names serve the person checking "is that where I am" — cost if wrong: one formatting change at copy review
+Task 2: minor (deferred): GeoLite2 attribution is a long sentence on the From line; consider own small line; add rel="noreferrer" on the attribution link
+Task 2: minor (deferred): lede states the self-reported label as fact; raise at copy review
+Task 2: minor (deferred): 429 text duplicated at GET and POST; share a helper/copy key so bodies can't drift
+Task 2: minor (deferred): no GET test for an expired code
+Task 2: minor (deferred): legacy em dashes in cli_approve.html text + old "No login is waiting" error; Task 5 copy review
+Ruling: cli.settings_link ('agents and terminals') belongs on the APPROVAL page's revoke sentence (spec §5 'Settings: command-line access becomes agents and terminals'), not the decided page; decided page keeps only Open your apps — cost if wrong: one link placement
+Task 3: minor (deferred): new test splits TestCLILoginDeny from its comment; move it
+Task 3: minor (deferred): no test for denied page or hostile-label escaping
+Task 3: minor (deferred): approved page dropped 30-day expiry / Keymail note / revoke link (copy review to confirm); Days unused there
+Task 3: minor (deferred): label read on deny is unused work
+Task 4: minor (deferred): approved-then-store-failure keeps file (retry gets unknown, clears later); confusing error
+Task 4: minor (deferred): package-level loginWaitCap would race if --wait tests go parallel; loginDeadline maybe dead on --wait path; first sleep can overshoot expiry by one interval
+Ruling: decline Luna's emptyOrDash row ("—" → "Not available"): emptyOrDash is a shared template helper used across many console pages, out of this branch's scope — cost if wrong: one dash left on the approval page's empty fields
diff --git a/docs/superpowers/specs/2026-11-07-agent-login-link-design.md b/docs/superpowers/specs/2026-11-07-agent-login-link-design.md
new file mode 100644
index 000000000..9d38cc0ac
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-07-agent-login-link-design.md
@@ -0,0 +1,255 @@
+# Agent login by link
+
+Status: rev 3.1 for Paul, 2026-11-07. Astra rounds 1-3:
+`CODEX-FINDINGS-agent-login-link.md`, `-R2.md`, `-R3.md`; round 3 READY
+AFTER FIXES, its one P2 applied (R3-1). Accepted findings are
+marked **(codex N)** for round 1 and **(codex R2-N)** for round 2; none
+declined. Round 2's two P1s and round 1's three P1s were all in the
+any-browser code, which Paul cut (R2 below). First slice of "agent-first onboarding
+and console parity"; the later slices are listed under Non-goals.
+
+## Why
+
+On 2026-11-07 a new Carloku user drove a Claude Code cloud session from a
+phone. Getting that session logged in took him through the console's
+front page, two email round trips, a "Link expired" (fixed in v0.34.21),
+an email code that only works in the browser that asked for it, and
+finally a page titled "Approve a terminal" asking him to type a code he
+had to read out of the chat. He was using Claude, not a terminal, and
+afterwards the console gave him no idea what to do next.
+
+Paul's goal: a person gets a deployed app with as little friction as
+possible. Simplifying login is the first step.
+
+Paul's rulings (2026-11-07, in this session):
+
+- R1. An agent may be approved by following a link that carries its code,
+ after the person checks the code matches the one the agent shows. This
+ deliberately reverses "nothing is approved by following a link"
+ (authcli.go handleCLIApprovePage, auth.go's bare-URI print). GitHub and
+ Google accept the same risk.
+- R2. An emailed sign-in code works in any browser, entered with its
+ address, keeping the per-address guess limits. **Withdrawn by Paul,
+ 2026-11-07, after Astra rounds 1-2** found five holes in one family
+ (address-wide code matching: search widening, link burning, login CSRF,
+ local challenges blocking, challenge-state oracle). The emailed LINK
+ already works in any browser and carries the pending approval with it,
+ so the code stays same-browser and the link is the cross-browser path.
+- R3. Secrets are the person's choice: through the agent, or entered on
+ Carloku themselves. (Later slice; recorded here so this slice doesn't
+ close it off.)
+
+## Goals
+
+1. From an agent session, logging in takes taps, not typing: one link,
+ one sign-in if not already signed in, one Approve.
+2. It works when the link, the email and the approval open in different
+ browsers on one phone (the Claude app's in-app browser, Safari, a mail
+ app's viewer), by following links: the emailed sign-in link works in
+ any browser and lands that browser on the approval page.
+3. It works for agents that only see a command's output when the command
+ ends (Claude Code's Bash tool returns output at exit; default timeout
+ 2 minutes, the login lasts 10).
+4. No dead end: after approving, the page says the agent is connected and
+ to go back to it, and offers the next useful place in the console.
+5. The words fit an agent as well as a terminal.
+
+## Non-goals (later slices, separate designs)
+
+- A Carloku MCP connector for Claude chat users.
+- Setting secrets in the console (R3), a first-run "what next" page beyond
+ the approval page's pointer, and the CLI / console / MCP parity table
+ and its guard test.
+- Loopback-redirect login for a CLI on the same machine as the browser.
+- Changing token lifetime, scopes or the revoke page.
+
+## Anti-goals
+
+- A link that approves with no human checking anything. The person still
+ sees the code and what is asking, and still presses Approve.
+- Losing detection: the issuance notice (notifyCLIIssued) and "That wasn't
+ me" stay exactly as they are.
+- Making approval cheaper than a fresh sign-in: the step-up on Approve
+ stays (requireFreshAuth). An email sign-in minutes ago already counts.
+- Codes or tokens in logs, or in any URL other than the user code that
+ `verification_uri_complete` already carries.
+
+## Design
+
+### 1. The CLI prints the link
+
+`carlos auth login` prints `verification_uri_complete` (the console
+already returns it) as the thing to open, and the code as the thing to
+check, not to type:
+
+ Open this link to approve this login:
+
+ https://console.carloku.com/auth/cli?code=WXYZ-4823
+
+ The page will show the code WXYZ-4823. Approve only if it matches.
+
+The comment block in auth.go explaining why the bare URI is printed is
+replaced with the reason for R1 and the controls that remain.
+
+Default label: when the environment shows the CLI is running under an
+agent (Claude Code sets `CLAUDECODE=1`; others can be added), the default
+label names it, e.g. "Claude Code on <host>". `--label` still wins. The
+label stays self-reported and the page keeps saying so.
+
+### 2. A login an agent can relay
+
+Two flags make the wait optional:
+
+- `carlos auth login --no-wait` starts the login, prints the link and
+ code, stores the pending device code beside the credentials file (mode
+ 0600, expires with the login), and exits 0 at once.
+- `carlos auth login --wait` collects a pending login: it polls until
+ approved, denied or expired, then stores the token as today. With no
+ pending login it says so and exits non-zero.
+
+Plain `carlos auth login` keeps today's behaviour (print, then wait).
+`carlos auth login --help` and the docs page for agents say: agents use
+`--no-wait`, show the person the link, then run `--wait`.
+
+Each attempt gets its own pending file, in a directory beside the
+credentials file (`login-pending.d/`, 0700; files 0600, written with the
+credential store's atomic pattern). A file records the console origin, the
+device code, its expiry and the label, so `--wait` polls the console that
+started it whatever `--console` or default is in force later.
+
+**Paul's ruling, 2026-11-08 (after branch review rounds 1-2 found the same
+race twice):** a process never deletes another attempt's file. A file is
+removed only by its own `--wait` (approved, denied, unknown, expired,
+including an approved login whose token could not be saved), or by anyone
+once it has expired. `--wait` picks the newest unexpired attempt. Several
+unexpired attempts can sit side by side for up to the 10-minute login
+lifetime; that is the accepted cost. A transient network failure keeps the
+file. A plain `carlos auth login` never touches the directory.
+
+### 3. The approval page acts on the code in the link
+
+`GET /auth/cli?code=X`, signed in:
+
+- The code is resolved (it is no longer only echoed). A live, pending
+ request renders the description that today appears only after typing:
+ the code, large; the label with its "supplied by the machine asking"
+ caveat; where it dialled from (IP, plus country and subdivision from the
+ platform GeoIP answer, as handleAPIGeo gives them; the answer has no
+ city; IP alone when there is no answer) **(codex 8)**, with the
+ attribution credit from the same lookup snapshot whenever AttributionFor
+ returns one **(codex R2-5)**; how long ago it started; when it expires.
+ Then: Approve, and "That wasn't me".
+- The question on the page is the check R1 depends on, in plain words:
+ "Does your agent show this code?" plus "If you didn't just ask an agent
+ or terminal to log in, press That wasn't me."
+- Unknown, expired or already-decided codes say so and show the typed-code
+ box as today (it stays as the fallback for a code read off a screen).
+- Resolving on GET writes nothing but its own lookup budget, and Approve
+ and Deny stay POSTs with the session's CSRF token.
+- Guess budgets are checked BEFORE any resolution **(codex 4)**. Today
+ handleCLIApprove resolves first and counts only failures (authcli.go
+ ~1666, ~1688), so a caller past the limit still learns whether a code is
+ live. Two separate, concurrency-safe budgets, each per signed-in address
+ and per IP, are consulted first:
+ - the GET budget, spent by GET lookups that find nothing. A top-level
+ navigation carries the Lax session cookie without any CSRF token, so
+ it must never touch the decision budget **(codex R2-3)**;
+ - the decision budget, spent by POST continue, approve and deny that
+ find nothing, behind the CSRF check as today.
+ Past a budget, every answer on that path is the same 429 whatever the
+ code. Tests prove a VALID code is refused once its path's budget is
+ spent, and that forced GETs to bad codes leave a valid Approve working.
+
+`GET /auth/cli?code=X`, signed out: unchanged. The front page asks the
+person to sign in with next=/auth/cli?code=X. The email link and code
+carry next on the challenge row and, since v0.34.21, land via `/?next=`,
+so whichever browser opens the email link arrives on the approval page
+with the code. (The emailed code works only in the browser that asked, as
+today; it lands that browser on the approval page the same way.) Keymail is narrower
+**(codex 6)**: its ceremony keeps next in a cookie and must finish in the
+browser that started it (state and PKCE live there, server.go ~4020), and
+an ordinary Keymail sign-in records no step-up, so a Keymail person gets
+one passkey confirmation on Approve. Both stay as they are in this slice.
+
+Approve stays a POST with the session's CSRF token and the step-up gate.
+Deny stays ungated. A person who signed in by email just now is fresh and
+is not asked again (email sign-in records a step-up at use). An older
+email session gets today's step-up: a confirmation email whose link only
+works in the browser that asked, but whose code can be typed on the
+waiting page. Making step-up links work in any browser is out of scope
+for this slice (my call); the code box is the path.
+
+### 4. Email sign-in across browsers
+
+No change to email sign-in itself. The cross-browser path is the emailed
+link: it works in any browser (handleEmailLinkPage / handleEmailLink) and
+carries next, so it lands that browser on the approval page. The code
+stays bound to the browser that asked, with today's limits and burn.
+
+Stated precisely, because round 2 caught the earlier wording out
+**(codex R2-4, R3-1)**: only the newest email a browser was SENT works.
+An accepted request in the same browser creates a new challenge, and that
+kills the browser's earlier email, link and code alike
+(CreateEmailChallenge; emailsignin_test.go asserts it). A refused resend (a
+double tap, or a request inside the resend gap) creates nothing and keeps
+the existing live challenge (HoldEmailChallenge), so the email already
+sent keeps working. So the
+"Check your email" page's advice stays as it is: use the newest email. If
+an older email arrives late, its link says "Link expired" and the newest
+one is the one to tap. (A gentler answer for that case belongs with the
+first-run work, not here.)
+
+### 5. Words
+
+Drafts only; every string goes through copy review when built.
+
+- Title: "Approve a sign-in" (not "Approve a terminal"). Lede: "{label}
+ is asking to use Carloku as you."
+- Front-page banner when next is /auth/cli: "Sign in to connect your agent
+ or terminal."
+- After Approve: "Connected. Go back to {label}; it carries on by itself."
+ Then one link: the person's current account ("Open your apps").
+- After Deny: unchanged meaning, new wording to match.
+- Settings: "command-line access" becomes "agents and terminals".
+
+## Constraints
+
+- Console plus the CLI; no box, edge or root behaviour changes. The CLI's
+ auth.go is in the module-root package, which is inside the census scope,
+ so expect an envelope re-pin needing a cross-family approval on #280
+ (`make census-card` says exactly).
+- Everything works with JavaScript off.
+- Release follows the v0.34.21 pattern: dev console, then flagship
+ console inside a #421 window lock. The CLI change ships in the normal
+ release (tap, apt).
+
+## Test plan (for the builder)
+
+- Approval page resolves a live code from the link and shows the
+ description; Approve issues the token; Deny kills it.
+- Signed-out link → sign in by email link in a second browser → lands on
+ the approval page with the code → Approve works.
+- Wrong or stale codes in the link count against the limiters; the page
+ answers unknown and expired codes the same way the form does.
+- Cross-browser by link: sign in by the emailed link in a second browser
+ starting from /auth/cli?code=X; that browser lands on the approval page
+ with the code.
+- CLI approval: a VALID code is refused (same 429) once its path's budget
+ is spent, on GET and on POST; forced GETs to bad codes leave a valid
+ Approve working.
+- The location line carries the GeoIP attribution when the snapshot has
+ one.
+- CLI pending file: an old `--wait` finishing after a newer `--no-wait`
+ leaves the newer file in place.
+- CLI: `--no-wait` exits at once with the link and stores the pending
+ login; `--wait` completes it; plain login unchanged; labels under
+ CLAUDECODE=1.
+- The claim invariant probes (claim_invariant_probes_*) cover the changed
+ routes.
+
+## Left to the builder
+
+File names, flag spellings beyond `--no-wait` and `--wait`, how the GeoIP
+place is formatted, and test structure. Marked "my call" above: the
+pending-login file's contents and lifecycle; step-up links stay
+same-browser.
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-agent-login-link-R2.md b/docs/superpowers/specs/CODEX-FINDINGS-agent-login-link-R2.md
new file mode 100644
index 000000000..f5cb0e3a7
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-FINDINGS-agent-login-link-R2.md
@@ -0,0 +1,66 @@
+- R1 finding 1, P1 — **Resolved:** cross-browser matching excludes unsent rows and caps candidates at three.
+- R1 finding 2, P1 — **Resolved:** cross-browser failures no longer burn challenges or their links.
+- R1 finding 3, P1 — **Resolved:** code submissions require a browser-bound nonce before lookup.
+- R1 finding 4, P2 — **Resolved:** CLI resolution now requires a shared, concurrency-safe budget check first.
+- R1 finding 5, P2 — **Partly resolved:** replacement and code-success cleanup are explicit; the older-email link claim remains false.
+- R1 finding 6, P2 — **Resolved:** Keymail’s browser binding and separate step-up are correctly qualified.
+- R1 finding 7, P2 — **Resolved:** pending-file cleanup compares attempts, with terminal and transient outcomes specified.
+- R1 finding 8, P2 — **Partly resolved:** country/subdivision replaces city, but required attribution remains unspecified.
+
+Reviewed `519ccd5d42c4c599a425a91f7cb090fcbb02cc9a`. The referenced implementation matches local `origin/main` at `0d55ef8c455e10c4bc709c45c9b3ab7a22aabee8`. No files changed, subagents spawned, or test suites run.
+
+1. **P1 — §4: a local challenge prevents “any browser” code redemption.**
+
+ Path 1 checks only the browser’s own challenge; path 2 runs **otherwise**, rather than after a non-match. See [design:186](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/docs/superpowers/specs/2026-11-07-agent-login-link-design.md:186).
+
+ **Failure scenario:** browser A requests an email. Browser B requests the same address within the resend interval and receives an unsent placeholder. The person enters A’s valid emailed code in B. B selects its placeholder through path 1 and rejects the code; cross-browser matching never runs. This follows directly from [server.go:3935](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/server.go:3935) and [emailsignin_store.go:151](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/emailsignin_store.go:151). Two browsers with different sent challenges have the same problem.
+
+ **Concrete fix required if retained:** define one bounded matching operation that can accept another browser’s eligible sent code even when a local challenge exists. A local mismatch must not spend an additional guess or burn a challenge before that operation finishes. Include the refused-send placeholder scenario in the acceptance tests.
+
+ **Invariant / family:** R2’s address-wide matching must accept an eligible emailed code independently of the receiving browser’s existing flow.
+
+2. **P1 — §4: conditional address accounting exposes a live-challenge oracle.**
+
+ The design requires a distinct “today’s throttled reply” after three cross-browser failures, but creates address counters only when a live sent challenge exists. See [design:208](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/docs/superpowers/specs/2026-11-07-agent-login-link-design.md:208). Today’s handler distinguishes throttled and wrong-code replies at [emailsignin.go:462](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/emailsignin.go:462) and [emailsignin.go:473](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/emailsignin.go:473).
+
+ **Failure scenario:** from a browser without a challenge, obtain the form nonce and submit four incorrect codes for an address. A live sent challenge produces the address-hour throttle on submission four. Without one, only four of the IP’s thirty guesses have been spent, so that throttle does not occur. This reveals active sign-in state, rather than necessarily account membership. Saying “the reply is identical” for the no-challenge case does not reconcile these different response transitions.
+
+ **Concrete fix required if retained:** specify indistinguishable responses for wrong, absent, expired and address-throttled cross-browser attempts, including consistent IP accounting and bounded equivalent work. Test the complete response sequence across those states, through and beyond the address cap.
+
+ **Invariant / family:** R2’s address-wide matching must not expose another browser’s challenge or throttle state. This conflicts with the flow-cookie protection recorded at [email-signin design:521](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/docs/superpowers/specs/2026-10-21-console-email-signin-design.md:521).
+
+3. **P2 — §3: GET can spend the victim’s approval budget.**
+
+ “Resolving on GET changes no state” conflicts with charging failed GET lookups to the signed-in address and sharing that budget with POST decisions. See [design:133](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/docs/superpowers/specs/2026-11-07-agent-login-link-design.md:133). Session cookies are `SameSite=Lax` at [server.go:3041](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/server.go:3041); current POST accounting occurs behind the CSRF check at [authcli.go:1626](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/authcli.go:1626).
+
+ **Failure scenario:** an attacker repeatedly navigates a signed-in browser to invalid approval links. Those top-level GETs carry its session cookie and exhaust its shared budget without a CSRF token. Valid Approve and Deny submissions then receive 429 until the window resets.
+
+ **Concrete fix:** give GET resolution a separate bounded budget that cannot exhaust POST decision capacity; retain CSRF-protected accounting for POSTs. Describe the limiter mutation accurately and test forced GETs followed by a valid decision.
+
+ **Invariant:** unsolicited navigation must not spend the browser’s protected decision budget.
+
+4. **P2 — §4, carried from R1 finding 5: a replaced email’s link does not remain usable.**
+
+ [Design:200](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/docs/superpowers/specs/2026-11-07-agent-login-link-design.md:200) says replacement kills the earlier link, then says the late older-email case is handled by that link.
+
+ **Failure scenario:** two successful requests occur in the same flow, and the first email arrives last. Its link returns “Link expired” in every browser. `CreateEmailChallenge` deletes the earlier row at [emailsignin_store.go:139](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/emailsignin_store.go:139); [emailsignin_test.go:1018](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/emailsignin_test.go:1018) explicitly asserts that result.
+
+ **Concrete fix:** state that only the newest successful same-flow issuance works. Restrict the cross-browser-link fallback claim to challenges that remain live.
+
+ **Invariant:** the documented recovery path must agree with challenge replacement.
+
+5. **P2 — §3, carried from R1 finding 8: GeoIP attribution is still missing.**
+
+ [Design:124](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/docs/superpowers/specs/2026-11-07-agent-login-link-design.md:124) now names supported location fields but omits their source attribution. The API supplies attribution at [apigeo.go:58](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/apigeo.go:58), and [pointer.go:101](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/geoip/pointer.go:101) defines the credit a page displaying that data must carry.
+
+ **Failure scenario:** the builder renders country/subdivision as specified but drops the accompanying required credit.
+
+ **Concrete fix:** require attribution from the same lookup snapshot whenever `AttributionFor` returns one, with a rendering check.
+
+ **Invariant:** displaying GeoIP data preserves the platform’s attribution contract.
+
+No P3 findings. The `next` chain preserves `?code=` through email challenges, `finishSignin`, `handleHome`, and same-browser Keymail. Session, CSRF and fresh-auth approval gates remain compatible with R1.
+
+Rev 2 closes the three original P1 mechanisms, but **does not close their address-wide-matching fault family**. Further corrective work would be needed in that family for a second consecutive round. Under the stopping rule, recommend cutting any-browser code redemption from this slice and retaining cross-browser emailed links, rather than starting another patch cycle. That scope change requires Paul’s decision because R2 remains a fixed ruling.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-agent-login-link-R3.md b/docs/superpowers/specs/CODEX-FINDINGS-agent-login-link-R3.md
new file mode 100644
index 000000000..442555a9d
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-FINDINGS-agent-login-link-R3.md
@@ -0,0 +1,27 @@
+- R2 finding 1, P1 — **Resolved by the cut:** cross-browser email-code matching is removed.
+- R2 finding 2, P1 — **Resolved by the cut:** conditional address accounting is removed.
+- R2 finding 3, P2 — **Resolved:** GET lookups and CSRF-protected decisions have separate budgets.
+- R2 finding 4, P2 — **Partly resolved:** replacement invalidates older links, but the wording still incorrectly includes refused resend requests.
+- R2 finding 5, P2 — **Resolved:** attribution from the same GeoIP snapshot is required.
+
+Reviewed commit `1018f8bfed673828ccc6c65bf7bc06997cf01143`. The referenced implementation matches local `origin/main` at `0d55ef8c455e10c4bc709c45c9b3ab7a22aabee8`. No files changed, subagents spawned, or tests run.
+
+No P1 findings.
+
+1. **P2 — §4: requesting another email does not always invalidate the previous one.**
+
+ **Problem:** [design:186](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/docs/superpowers/specs/2026-11-07-agent-login-link-design.md:186) says asking again kills the earlier link and code. Replacement happens only when a new challenge is created.
+
+ **Evidence:** a rate-limited resend calls `HoldEmailChallenge` at [server.go:3936](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/server.go:3936), which preserves an existing live challenge at [emailsignin_store.go:171](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/emailsignin_store.go:171). The existing test explicitly checks successful redemption after refused requests at [emailsignin_test.go:1107](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/emailsignin_test.go:1107).
+
+ **Failure scenario:** someone double-taps Continue or immediately requests another email. The second request is throttled; no replacement email arrives, and the first link remains valid despite the specification saying it was killed.
+
+ **Concrete fix:** qualify replacement as occurring when an accepted request creates a new challenge. Explicitly state that a refused resend preserves the existing live challenge. No implementation change is needed.
+
+ **Invariant:** documented challenge replacement must preserve the existing double-click and throttled-resend recovery behaviour.
+
+No P3 findings. No remaining operative text depends on cross-browser email codes. The split-budget requirements preserve decision capacity against forced GETs and require refusal before resolution. The `next` chain, retained approval gates, and pending-file requirements are compatible with the current code.
+
+Fix the P2 without another review round.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-agent-login-link.md b/docs/superpowers/specs/CODEX-FINDINGS-agent-login-link.md
new file mode 100644
index 000000000..4dc5da3ea
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-FINDINGS-agent-login-link.md
@@ -0,0 +1,85 @@
+Reviewed `5128198f710f6083bbcab604b8ad3084fc844c03`, round 1. The referenced implementation matches `origin/main`. No files changed or test suites run.
+
+1. **P1 — §4: unsent challenges defeat the claimed five-code bound.**
+
+ The spec says send limits bound address-wide matching to five live codes. However, refused sends create ordinary challenges with random, redeemable codes: [server.go:3935](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/server.go:3935), [emailsignin_store.go:151](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/emailsignin_store.go:151), and [emailsignin_store.go:204](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/emailsignin_store.go:204).
+
+ An attacker can create fresh flows for a victim’s address, accumulating unsent challenges beyond the five-email limit. Under “ANY live challenge,” each submitted guess tests all those codes. Additional IPs multiply the candidate set without increasing the address’s guess count.
+
+ **Fix:** distinguish refused-send placeholders from redeemable challenges, exclude placeholders from successful matching, and enforce an explicit address-wide candidate bound. Preserve indistinguishable failure responses.
+
+ **Invariant:** a refused send must not expand the authentication search space.
+
+2. **P1 — §4: another browser can burn the victim’s emailed link.**
+
+ Keeping “five wrong codes burn a challenge” while selecting challenges by a supplied address exposes another browser’s challenge to destructive guesses. The fifth failure deletes the entire row, including its link: [emailsignin_store.go:332](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/emailsignin_store.go:332). Today the lookup is restricted to the requester’s flow: [emailsignin.go:453](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/emailsignin.go:453).
+
+ With one live challenge for the victim, an attacker submits five wrong codes using that address. Both the victim’s code and emailed link stop working. This breaks the retained protection that other browsers’ links survive guessing, stated in the email-sign-in authority at [line 204](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/docs/superpowers/specs/2026-10-21-console-email-signin-design.md:204).
+
+ **Fix:** separate code exhaustion from link validity. Address-wide failures may exhaust the code budget, but must leave the high-entropy link redeemable. Specify attempt accounting across multiple candidate rows.
+
+ **Invariant:** knowing an address does not authorize destroying its mailbox holder’s sign-in link.
+
+3. **P1 — §4: removing flow binding removes the fallback login-CSRF protection.**
+
+ `sameOrigin` deliberately accepts requests carrying neither `Origin` nor `Sec-Fetch-Site`: [emailsignin.go:70](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/emailsignin.go:70). The existing code handler then requires the browser’s challenge-bearing flow. The earlier design explicitly relies on that cookie for CSRF protection: [email-signin design:229](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/docs/superpowers/specs/2026-10-21-console-email-signin-design.md:229).
+
+ In a supported browser that omits both headers, an attacker can auto-submit their own address and valid emailed code into the victim’s browser. The proposed fallback accepts it without a flow cookie and signs the victim into the attacker’s account.
+
+ **Fix:** require a browser-bound form nonce for every code submission, including “I already have a code.” The nonce can be independent of the challenge, preserving R2.
+
+ **Invariant:** possession of a valid code does not authorize signing an unrelated browser into that identity.
+
+4. **P2 — §3: the existing CLI limiter does not actually bound lookups.**
+
+ The current handler resolves the code first and increments the limiter only after failure: [authcli.go:1688](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/authcli.go:1688). Approval and denial have the same ordering at [line 1666](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/authcli.go:1666).
+
+ After exhausting the budget, a caller can continue probing: misses return 429, while a live code still produces its description or succeeds. Copying this mechanism onto GET preserves an unlimited oracle, despite the spec’s reliance on a guessing bound. This defect already exists in the POST path.
+
+ **Fix:** require a shared budget check before resolution or decision, with concurrency-safe accounting. Test a valid code after exhausting the budget, rather than merely checking that wrong codes eventually return 429.
+
+ **Invariant:** exhausted guessing budgets prevent further code validation.
+
+5. **P2 — §4: challenge replacement and successful cleanup are described incorrectly.**
+
+ The spec presents address-wide cleanup as existing behaviour and motivates older-email acceptance by asking twice. Today, creating another challenge deletes earlier challenges in the same flow, and successful redemption clears that flow—not the address: [emailsignin_store.go:128](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/emailsignin_store.go:128), [emailsignin_store.go:185](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/emailsignin_store.go:185), and [emailsignin_store.go:349](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/emailsignin_store.go:349).
+
+ A second successful request in the same browser therefore makes the older email unusable before the proposed matching runs. Keeping today’s redemption code also leaves other flows’ challenges alive.
+
+ **Fix:** explicitly specify the required storage changes, whether older same-flow emails remain valid, and atomic address-wide invalidation on success. Reconcile “own flow first,” “newest,” and “ANY” into one algorithm.
+
+ **Invariant:** issuance, matching and consumption must agree on which challenges remain valid.
+
+6. **P2 — §3: the Keymail promises exceed current behaviour.**
+
+ Keymail carries `next`, including `?code=`, when its ceremony stays in one browser. A callback in another browser fails without the original state/PKCE cookie: [server.go:4020](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/server.go:4020).
+
+ Also, an ordinary fresh Keymail sign-in does not establish step-up freshness. Only the special fresh ceremony supplies `authTime`; email sign-in records freshness automatically: [server.go:4053](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/server.go:4053), [emailsignin.go:335](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/emailsignin.go:335).
+
+ **Failure scenario:** moving the OAuth callback between browsers fails; completing ordinary Keymail sign-in still requires another confirmation on Approve.
+
+ **Fix:** qualify both promises, or explicitly extend the validated fresh-Keymail ceremony to CLI sign-in. Do not infer freshness merely from session creation.
+
+ **Invariant:** browser continuity and fresh authentication require their respective proofs.
+
+7. **P2 — §2: pending-file cleanup can violate “newest wins.”**
+
+ The spec allows replacement while a previous `--wait` may still be running, then instructs successful waits to delete the pending file.
+
+ **Failure scenario:** wait A reads login A; another command saves login B; A succeeds and deletes B. B then cannot be collected. Denied and unknown terminal states also lack an explicit cleanup rule; both exist today at [auth.go:762](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/auth.go:762).
+
+ **Fix:** serialize pending-file updates and delete only when the stored attempt still matches the completing attempt. Specify terminal-state cleanup and retention on transient failures. Reuse the credential store’s atomic 0600 write pattern at [auth.go:174](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/auth.go:174).
+
+ **Invariant:** completion of an older attempt cannot erase its replacement.
+
+8. **P2 — §3: the existing GeoIP answer has no city.**
+
+ The cited API supplies country, subdivision and coordinates, not city: [apigeo.go:16](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/console/apigeo.go:16). The underlying answer likewise has no city field: [answer.go:39](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-agent-login-link/internal/geoip/answer.go:39).
+
+ **Failure scenario:** the builder cannot render the promised city from the specified interface.
+
+ **Fix:** specify country/subdivision with IP fallback and required source attribution, or explicitly scope the additional city-data work.
+
+ **Invariant:** displayed location must be supported by the available data.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-agent-login-link-R2.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-agent-login-link-R2.md
new file mode 100644
index 000000000..90f041d2b
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-agent-login-link-R2.md
@@ -0,0 +1,80 @@
+# Review brief: spec "Agent login by link", round 2 of 3
+
+Repo carlos/platform, branch `design-agent-login-link`, commit: the commit
+that adds this file.
+Under review: `docs/superpowers/specs/2026-11-07-agent-login-link-design.md`.
+Authorities: main's code (internal/console/authcli.go, emailsignin.go,
+emailsignin_store.go, emailsignin_limits.go, stepup.go,
+templates/cli_approve.html, the module-root auth.go) and
+`docs/superpowers/specs/2026-10-21-console-email-signin-design.md`.
+
+You are an independent reviewer. Read the document, then the code it
+names, and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- Paul's rulings R1 (approve by link after checking the code), R2 (email
+ code in any browser with per-address limits), R3 (secrets: the person's
+ choice, later slice), recorded in the spec's "Why". Report only
+ mechanisms that fail to honour them, or that weaken a control the spec
+ says it keeps.
+
+## What to check
+
+1. Device-code phishing after R1: with the typed code gone, do the kept
+ controls (session, CSRF, step-up on Approve, issuance notice, deny,
+ 10-minute TTL, the page's "does your agent show this code?") still do
+ what the spec claims? Is anything that today depends on typing (e.g.
+ the wrong-code limiters as an oracle bound, the "describe before
+ approve" step) silently lost? Is resolving the code on GET a new
+ oracle or a CSRF-able state change?
+2. R2 edges as specified (form address wins, any live challenge matches
+ as one guess, limiter keying only when a live challenge exists): any
+ enumeration oracle (timing, limiter behaviour, different replies), any
+ way to burn or lock out someone else's challenge, any conflict with
+ the email sign-in spec's flow-cookie reasons (throttle oracles, the
+ double-click race).
+3. The next= path: signed out at /auth/cli?code=X, sign in by email link or
+ code or Keymail in another browser, land on the approval page. Does
+ main's code (v0.34.21: sign-in redirects to /?next=, handleHome
+ honours next) actually carry ?code= through safeNext, the challenge
+ row's next, and the Keymail next cookie?
+4. CLI `--no-wait` / `--wait`: is the pending-file design sound
+ (permissions, stale/expired handling, wrong console), and does it fit
+ how auth.go stores credentials today?
+5. Anything the spec claims about current code that is false.
+
+## Severity
+
+- **P1**: unsafe, would not work, or contradicts the code. Blocks approval.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. 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 section, the problem, the
+evidence (file:line, verified), the failure scenario, a concrete fix and
+the invariant or trust boundary it breaks. 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.
+
+## Round 2
+
+Earlier rounds: `docs/superpowers/specs/CODEX-FINDINGS-agent-login-link.md`
+(round 1: P1 x3, P2 x5, all accepted; marked **(codex N)** in the spec).
+
+First give one line per round-1 P1 and P2: resolved, partly, or not. Carry
+every unresolved or partly resolved finding forward at its current
+severity, then add new findings. The three P1s were one fault family
+(R2's address-wide matching); say whether rev 2's section 4 closes that
+family or whether a fourth fix would be needed (in which case recommend
+refusing the case up front or cutting the any-browser code instead).
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-agent-login-link-R3.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-agent-login-link-R3.md
new file mode 100644
index 000000000..6d8f56490
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-agent-login-link-R3.md
@@ -0,0 +1,85 @@
+# Review brief: spec "Agent login by link", round 3 of 3
+
+Repo carlos/platform, branch `design-agent-login-link`, commit: the commit
+that adds this file.
+Under review: `docs/superpowers/specs/2026-11-07-agent-login-link-design.md`.
+Authorities: main's code (internal/console/authcli.go, emailsignin.go,
+emailsignin_store.go, emailsignin_limits.go, stepup.go,
+templates/cli_approve.html, the module-root auth.go) and
+`docs/superpowers/specs/2026-10-21-console-email-signin-design.md`.
+
+You are an independent reviewer. Read the document, then the code it
+names, and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- Paul's rulings R1 (approve by link after checking the code), R2 (email
+ code in any browser with per-address limits), R3 (secrets: the person's
+ choice, later slice), recorded in the spec's "Why". Report only
+ mechanisms that fail to honour them, or that weaken a control the spec
+ says it keeps.
+
+## What to check
+
+1. Device-code phishing after R1: with the typed code gone, do the kept
+ controls (session, CSRF, step-up on Approve, issuance notice, deny,
+ 10-minute TTL, the page's "does your agent show this code?") still do
+ what the spec claims? Is anything that today depends on typing (e.g.
+ the wrong-code limiters as an oracle bound, the "describe before
+ approve" step) silently lost? Is resolving the code on GET a new
+ oracle or a CSRF-able state change?
+2. R2 edges as specified (form address wins, any live challenge matches
+ as one guess, limiter keying only when a live challenge exists): any
+ enumeration oracle (timing, limiter behaviour, different replies), any
+ way to burn or lock out someone else's challenge, any conflict with
+ the email sign-in spec's flow-cookie reasons (throttle oracles, the
+ double-click race).
+3. The next= path: signed out at /auth/cli?code=X, sign in by email link or
+ code or Keymail in another browser, land on the approval page. Does
+ main's code (v0.34.21: sign-in redirects to /?next=, handleHome
+ honours next) actually carry ?code= through safeNext, the challenge
+ row's next, and the Keymail next cookie?
+4. CLI `--no-wait` / `--wait`: is the pending-file design sound
+ (permissions, stale/expired handling, wrong console), and does it fit
+ how auth.go stores credentials today?
+5. Anything the spec claims about current code that is false.
+
+## Severity
+
+- **P1**: unsafe, would not work, or contradicts the code. Blocks approval.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. 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 section, the problem, the
+evidence (file:line, verified), the failure scenario, a concrete fix and
+the invariant or trust boundary it breaks. 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.
+
+## Round 3 (final)
+
+Earlier rounds: `CODEX-FINDINGS-agent-login-link.md` (round 1) and
+`CODEX-FINDINGS-agent-login-link-R2.md` (round 2), beside the spec.
+
+Paul's decision after round 2 (stopping rule 2): R2 is WITHDRAWN. The
+any-browser emailed CODE is cut; the emailed LINK (already any-browser) is
+the cross-browser path; email sign-in itself is unchanged. Do not review
+the cut design. Item 2 of "What to check" no longer applies.
+
+First give one line per round-2 finding (P1 1-2, P2 3-5): resolved (by the
+cut or a fix), partly, or not. Then check rev 3 for anything new, especially
+that no text still relies on the cut feature and that the two-budget CLI
+limiter (GET vs decision) is sound. This is the last round: a NOT READY
+also says whether the P1s share one cause and whether refusing the case up
+front or cutting the feature would remove them.
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-agent-login-link.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-agent-login-link.md
new file mode 100644
index 000000000..c06cfea7c
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-agent-login-link.md
@@ -0,0 +1,68 @@
+# Review brief: spec "Agent login by link", round 1 of 3
+
+Repo carlos/platform, branch `design-agent-login-link`, commit: the commit
+that adds this file.
+Under review: `docs/superpowers/specs/2026-11-07-agent-login-link-design.md`.
+Authorities: main's code (internal/console/authcli.go, emailsignin.go,
+emailsignin_store.go, emailsignin_limits.go, stepup.go,
+templates/cli_approve.html, the module-root auth.go) and
+`docs/superpowers/specs/2026-10-21-console-email-signin-design.md`.
+
+You are an independent reviewer. Read the document, then the code it
+names, and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- Paul's rulings R1 (approve by link after checking the code), R2 (email
+ code in any browser with per-address limits), R3 (secrets: the person's
+ choice, later slice), recorded in the spec's "Why". Report only
+ mechanisms that fail to honour them, or that weaken a control the spec
+ says it keeps.
+
+## What to check
+
+1. Device-code phishing after R1: with the typed code gone, do the kept
+ controls (session, CSRF, step-up on Approve, issuance notice, deny,
+ 10-minute TTL, the page's "does your agent show this code?") still do
+ what the spec claims? Is anything that today depends on typing (e.g.
+ the wrong-code limiters as an oracle bound, the "describe before
+ approve" step) silently lost? Is resolving the code on GET a new
+ oracle or a CSRF-able state change?
+2. R2 edges as specified (form address wins, any live challenge matches
+ as one guess, limiter keying only when a live challenge exists): any
+ enumeration oracle (timing, limiter behaviour, different replies), any
+ way to burn or lock out someone else's challenge, any conflict with
+ the email sign-in spec's flow-cookie reasons (throttle oracles, the
+ double-click race).
+3. The next= path: signed out at /auth/cli?code=X, sign in by email link or
+ code or Keymail in another browser, land on the approval page. Does
+ main's code (v0.34.21: sign-in redirects to /?next=, handleHome
+ honours next) actually carry ?code= through safeNext, the challenge
+ row's next, and the Keymail next cookie?
+4. CLI `--no-wait` / `--wait`: is the pending-file design sound
+ (permissions, stale/expired handling, wrong console), and does it fit
+ how auth.go stores credentials today?
+5. Anything the spec claims about current code that is false.
+
+## Severity
+
+- **P1**: unsafe, would not work, or contradicts the code. Blocks approval.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. 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 section, the problem, the
+evidence (file:line, verified), the failure scenario, a concrete fix and
+the invariant or trust boundary it breaks. 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.
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index f33b71d0e..6de2f2688 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -333,8 +333,8 @@ func retryAfter(w http.ResponseWriter, d time.Duration) {
// cliLimits is the set of limiters the CLI endpoints share, hung off the
// Server so a test gets a fresh set per fixture.
type cliLimits struct {
- managedEnrolIP, managedEnrolGlobal *rateLimiter
- start, poll, pollIP, guessAddr, guessIP, write, ship, instances, create *rateLimiter
+ managedEnrolIP, managedEnrolGlobal *rateLimiter
+ start, poll, pollIP, guessAddr, guessIP, lookAddr, lookIP, write, ship, instances, create *rateLimiter
// db is the `carlos db` door's own budget, keyed by token (cliDBBurst,
// apidb.go): a restore is dozens of reads, a different shape from the
// instance verbs.
@@ -377,8 +377,12 @@ func newCLILimits() *cliLimits {
// Wrong codes are counted against the signed-in ADDRESS and the client
// IP, never the session token: a session is re-minted by signing in
// again, so a token-keyed counter is one the attacker resets at will.
+ // guessAddr/guessIP are the DECISION budget (the POST that resolves a
+ // typed code); lookAddr/lookIP are the GET lookup budget.
guessAddr: newRateLimiter(cliGuessBurst, cliRateWindow),
guessIP: newRateLimiter(cliGuessBurst, cliRateWindow),
+ lookAddr: newRateLimiter(cliGuessBurst, cliRateWindow),
+ lookIP: newRateLimiter(cliGuessBurst, cliRateWindow),
write: newRateLimiter(cliWriteBurst, cliRateWindow),
// Ship gets its own budget, on its own window, keyed by token rather
// than address (see handleAPIShip) — an upload is a different shape
@@ -1548,16 +1552,19 @@ type methodRow struct {
// shared chrome ("top"/"bottom") keeps working unchanged.
type cliPage struct {
page
- Code string // the code the human typed, echoed back into the form
- // LinkCode is the code carried by the ?code= in the URL they followed.
- // Shown ONLY as something to check against the terminal's screen — never
- // prefilled into the form, never resolved. See handleCLIApprovePage.
- LinkCode string
- Console string // this deployment's origin — the -console the CLI needs
- Request *CLIAuthRequest
- Tokens []CLIToken
- Methods []methodRow
- Days int
+ Code string // the code the human typed, echoed back into the form
+ Console string // this deployment's origin — the -console the CLI needs
+ Request *CLIAuthRequest
+ // Place is where Request dialled from, by GeoIP (cliplace.go), and
+ // Started how long ago it began; both only beside a described Request.
+ Place cliPlace
+ Started time.Duration
+ // Label names the agent or terminal a decision was made about, for the
+ // decided page.
+ Label string
+ 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
// and link there. Built here rather than hung on CLIToken because the
@@ -1572,6 +1579,39 @@ func (p cliPage) MethodsText(id string) string {
return copyText("methods."+id, "address", p.Address)
}
+// CLIText is the approval page's copy by id (signincopy.go).
+func (p cliPage) CLIText(id string) string { return copyText(id) }
+
+// Lede names what is asking and the console it is asking to use, by the
+// same name the page's header gives it (Brand, filled by chrome).
+func (p cliPage) Lede() string {
+ label := ""
+ if p.Request != nil {
+ label = p.Request.Label
+ }
+ if label == "" {
+ label = copyText("cli.unnamed")
+ }
+ return copyText("cli.lede", "label", label, "console", p.Brand)
+}
+
+// ApprovedText sends the person back to the agent that asked.
+func (p cliPage) ApprovedText() string {
+ label := p.Label
+ if label == "" {
+ label = copyText("cli.unnamed")
+ }
+ return copyText("cli.approved", "label", label)
+}
+
+// StartedText says how long ago the described login began.
+func (p cliPage) StartedText() string {
+ if p.Started < time.Minute {
+ return copyText("cli.started_now")
+ }
+ return copyText("cli.started", "ago", humanAge(p.Started))
+}
+
func (s *Server) renderCLI(w http.ResponseWriter, status int, name string, p cliPage) {
s.chrome(&p.page)
_ = s.writeTemplate(w, status, name, p)
@@ -1579,38 +1619,96 @@ func (s *Server) renderCLI(w http.ResponseWriter, status int, name string, p cli
// handleCLIApprovePage is where the printed link lands. A signed-out visitor
// gets the front page, asked to sign in, with next set back here (spec 8). A
-// code-shaped ?code= rides along in next only so it can be shown again for
-// comparison; the console never carries a pending approval through an
-// authentication it has not finished.
+// code-shaped ?code= rides along in next; the console never carries a
+// pending approval through an authentication it has not finished.
+//
+// SIGNED IN, IT ACTS ON ?code=: it looks the code up and, for a live login,
+// describes it and offers Approve. This reverses the old rule that nothing is
+// approved by following a link (Paul's ruling R1, agent login by link spec
+// §3). An agent can relay a link but cannot make a person type a code, and
+// the check that matters, "does your agent show this code?", is one the
+// person can still make by eye. GitHub and Google accept the same risk. What
+// stands between a phished link and a credential:
//
-// IT DELIBERATELY DOES NOT ACT ON ?code=. Not to resolve it, not to look it
-// up, and above all not to render an Approve button for it. A prefilled code
-// that arrives one click from approval is the device-code phishing attack that
-// has been run at scale against Microsoft tenants: the attacker starts the
-// flow, sends the victim the ready-made link with a plausible pretext, and one
-// click binds a 90-day credential — held by the attacker — to the victim's
-// identity. Requiring the code to be TYPED is what breaks it: to type it you
-// have to be reading it off a terminal you started, and a code you cannot see
-// is one you cannot transcribe. The value from the URL is shown only as
-// something to check against your screen, never as something to submit.
+// - a session: a signed-out visitor gets the front page and nothing more;
+// - Approve and Deny are POSTs carrying the session's CSRF token, so this
+// GET only ever describes;
+// - Approve needs a fresh step-up (requireFreshAuth); Deny stays ungated;
+// - the page shows the code, the self-reported label with its caveat,
+// where the login dialled from and when, and asks the check question;
+// - issuance tells the person (notifyCLIIssued), "That wasn't me" kills
+// the request, and a request lives only CLIAuthTTL;
+// - a GET lookup budget per signed-in address and per IP, checked BEFORE
+// the lookup and spent only by lookups that find nothing, so past it a
+// valid code gets the same 429 as a wrong one. It is separate from the
+// decision budget the POSTs spend: a top-level navigation carries no
+// CSRF token, so forced GETs must never lock a person out of Approve.
+//
+// Looking up writes nothing but that budget.
func (s *Server) handleCLIApprovePage(w http.ResponseWriter, r *http.Request) {
+ code := NormalizeUserCode(r.URL.Query().Get("code"))
+ codeShaped := len(code) == userCodeLen+1
addr, raw, ok := s.session(r)
if !ok {
next := "/auth/cli"
- if c := NormalizeUserCode(r.URL.Query().Get("code")); len(c) == userCodeLen+1 {
- next += "?code=" + url.QueryEscape(c)
+ if codeShaped {
+ next += "?code=" + url.QueryEscape(code)
}
- s.renderHome(w, r, homeForm{Next: next, Banner: copyText("home.cli_prompt")})
+ s.renderHome(w, r, homeForm{Next: next, Banner: copyText("cli.signin_prompt")})
return
}
- p := cliPage{page: page{Title: "Approve a terminal", Address: addr, CSRF: raw},
+ p := cliPage{page: page{Title: copyText("cli.title"), Address: addr, CSRF: raw},
Days: int(CLITokenTTL / (24 * time.Hour))}
- // Echoed for comparison only — no store lookup, which also means this page
- // is not an oracle for enumerating live codes.
- p.LinkCode = NormalizeUserCode(r.URL.Query().Get("code"))
+ switch {
+ case code == "":
+ // The bare page: the typed-code box, nothing to look up.
+ case !codeShaped:
+ // No code has this shape, so there is nothing to look up and nothing
+ // to guess: say the link's code is no good.
+ p.Error = copyText("cli.link_unknown")
+ default:
+ now := time.Now()
+ ip := s.clientIP(r)
+ if !s.cliBudgetOpen(s.cli.lookAddr, s.cli.lookIP, addr, ip, now) {
+ s.renderMessage(w, r, http.StatusTooManyRequests, "Too many attempts",
+ "Too many bad login codes. Wait a minute, then try again.")
+ return
+ }
+ req, err := s.store.CLIAuthByUserCode(code, now)
+ if err != nil {
+ s.cliBudgetSpend(s.cli.lookAddr, s.cli.lookIP, addr, ip, now)
+ p.Error = copyText("cli.link_unknown")
+ break
+ }
+ s.describeCLI(&p, req, now)
+ }
s.renderCLI(w, http.StatusOK, "cli_approve", p)
}
+// describeCLI fills everything the approval page says about a live login,
+// for both ways of reaching it (the link's GET and the typed code's POST
+// continue), so neither can describe a login less truthfully than the other.
+func (s *Server) describeCLI(p *cliPage, req *CLIAuthRequest, now time.Time) {
+ p.Request = req
+ p.Place = s.cliPlaceFor(req.RemoteAddr)
+ p.Started = now.Sub(req.CreatedAt)
+}
+
+// cliBudgetOpen reports whether neither key is over its guess budget. It is
+// read-only (rateLimiter.tripped), so asking never spends: callers check it
+// BEFORE resolving a code and spend only on a miss with cliBudgetSpend.
+// The check-then-spend gap lets a burst of concurrent requests overshoot the
+// budget by at most the number in flight, which is acceptable here.
+func (s *Server) cliBudgetOpen(addrL, ipL *rateLimiter, addr, ip string, now time.Time) bool {
+ return !addrL.tripped(addr, now) && !ipL.tripped(ip, now)
+}
+
+// cliBudgetSpend records one miss against both keys.
+func (s *Server) cliBudgetSpend(addrL, ipL *rateLimiter, addr, ip string, now time.Time) {
+ addrL.allow(addr, now)
+ ipL.allow(ip, now)
+}
+
// handleCLIApprove is both steps a human takes, distinguished by action:
//
// continue — a typed code is looked up and the terminal asking is DESCRIBED
@@ -1635,7 +1733,7 @@ func (s *Server) handleCLIApprove(w http.ResponseWriter, r *http.Request) {
code := NormalizeUserCode(r.FormValue("code"))
action := r.FormValue("action")
now := time.Now()
- p := cliPage{page: page{Title: "Approve a terminal", Address: addr, CSRF: raw},
+ p := cliPage{page: page{Title: copyText("cli.title"), Address: addr, CSRF: raw},
Code: code, Days: int(CLITokenTTL / (24 * time.Hour))}
// Wrong codes are counted wherever a code is resolved, and against both
@@ -1644,17 +1742,20 @@ func (s *Server) handleCLIApprove(w http.ResponseWriter, r *http.Request) {
// binds THEIR terminal to YOUR address, which is the inverted-payoff half
// of this flow and the reason the counter has to exist even though ~39
// bits in ten minutes is not findable.
- badCode := func() bool {
- ip := s.clientIP(r)
- okAddr := s.cli.guessAddr.allow(addr, now)
- okIP := s.cli.guessIP.allow(ip, now)
- return okAddr && okIP
- }
+ //
+ // The budget is checked BEFORE any resolution, so a caller past the limit
+ // is refused whether or not the code is live and learns nothing.
+ ip := s.clientIP(r)
tooMany := func() {
s.renderMessage(w, r, http.StatusTooManyRequests, "Too many attempts",
"Too many bad login codes. Wait a minute, then try again.")
}
+ if !s.cliBudgetOpen(s.cli.guessAddr, s.cli.guessIP, addr, ip, now) {
+ tooMany()
+ return
+ }
+
switch action {
case "approve", "deny":
// Passkey step-up on APPROVE only (spec §7a, stepup.go). Approving
@@ -1668,6 +1769,12 @@ func (s *Server) handleCLIApprove(w http.ResponseWriter, r *http.Request) {
if action == "approve" && !s.requireFreshAuth(w, r, addr, raw) {
return
}
+ // Read the label first so the decided page can name the agent. A
+ // failed read changes nothing: the decision below reports the error
+ // and spends the budget exactly as before.
+ if req, lerr := s.store.CLIAuthByUserCode(code, now); lerr == nil {
+ p.Label = req.Label
+ }
var err error
if action == "deny" {
err = s.store.DenyCLIAuth(code, now)
@@ -1675,10 +1782,7 @@ func (s *Server) handleCLIApprove(w http.ResponseWriter, r *http.Request) {
err = s.store.ApproveCLIAuth(code, addr, now)
}
if err != nil {
- if !badCode() {
- tooMany()
- return
- }
+ s.cliBudgetSpend(s.cli.guessAddr, s.cli.guessIP, addr, ip, now)
p.Error = "That code has expired or was already used. Run carlos auth login again for a fresh one."
s.renderCLI(w, http.StatusOK, "cli_approve", p)
return
@@ -1692,16 +1796,13 @@ func (s *Server) handleCLIApprove(w http.ResponseWriter, r *http.Request) {
// "continue": describe the terminal, then let the human decide.
req, err := s.store.CLIAuthByUserCode(code, now)
if err != nil {
- if !badCode() {
- tooMany()
- return
- }
+ s.cliBudgetSpend(s.cli.guessAddr, s.cli.guessIP, addr, ip, now)
p.Error = "No login is waiting on that code — check what your terminal printed. " +
"Codes last ten minutes."
s.renderCLI(w, http.StatusOK, "cli_approve", p)
return
}
- p.Request = req
+ s.describeCLI(&p, req, now)
s.renderCLI(w, http.StatusOK, "cli_approve", p)
}
}
diff --git a/internal/console/authcli_test.go b/internal/console/authcli_test.go
index 14580fbd8..be3a3fa15 100644
--- a/internal/console/authcli_test.go
+++ b/internal/console/authcli_test.go
@@ -7,12 +7,14 @@ import (
"io"
"net/http"
"net/url"
+ "os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
+ "github.com/carlosframework/platform/internal/geo"
"github.com/carlosframework/platform/internal/svcrole"
)
@@ -101,8 +103,9 @@ func TestCLILoginEndToEnd(t *testing.T) {
t.Fatalf("poll before approval = %v, want pending", poll)
}
- // Typing the code is what produces a described terminal — following a
- // link never does (see TestCLIApprovalPageNeverApprovesFromALink).
+ // Typing the code still produces a described terminal (the fallback for a
+ // code read off a screen); following the link does too (see
+ // TestCLIApprovalPageResolvesTheLinkCode).
csrf := sessionToken(t, fx, browser)
code, _, body := postForm(t, browser, fx.ts.URL+"/auth/cli/approve",
url.Values{"code": {userCode}, "action": {"continue"}, "csrf": {csrf}})
@@ -197,50 +200,257 @@ func TestCLILoginEndToEnd(t *testing.T) {
}
}
-// The device-code phishing attack, refused. An attacker starts a login, sends
-// the victim the ready-made verification_uri_complete with a pretext, and the
-// victim clicks it while signed in. If that page rendered an Approve button
-// for the attacker's code, one click would bind a 90-day credential — held by
-// the attacker — to the victim's identity. This is the campaign that has been
-// run against Microsoft tenants at scale, so the page must not do it: no
-// lookup, no description, no Approve button, and an EMPTY input the human has
-// to type into off their own screen.
-func TestCLIApprovalPageNeverApprovesFromALink(t *testing.T) {
+// The link an agent prints carries its code, and following it while signed
+// in now describes that login and offers Approve (spec §3, Paul's R1): the
+// person checks the code against the one their agent shows. GET only looks,
+// so the login is still pending afterwards.
+func TestCLIApprovalPageResolvesTheLinkCode(t *testing.T) {
fx := newConsoleFixture(t)
- victim := newBrowser(t)
- signUp(t, fx, victim, "code-phish")
-
- // The attacker's terminal, started from somewhere else entirely.
- _, start := postJSON(t, fx.ts.URL+"/auth/cli/start", map[string]string{"label": "attacker@vps"}, "")
+ browser := newBrowser(t)
+ signUp(t, fx, browser, "code-link")
+ _, start := postJSON(t, fx.ts.URL+"/auth/cli/start", map[string]string{"label": "Claude Code on box"}, "")
userCode := str(t, start, "user_code")
- status, _, body := get(t, victim, fx.ts.URL+"/auth/cli?code="+url.QueryEscape(userCode))
+ status, _, body := get(t, browser, fx.ts.URL+"/auth/cli?code="+url.QueryEscape(userCode))
if status != http.StatusOK {
t.Fatalf("approval page = %d", status)
}
- // The code is echoed to be CHECKED against the terminal's screen…
- if !strings.Contains(body, userCode) {
- t.Fatalf("the page hides the code the link carried, so it cannot be checked:\n%s", body)
- }
- // …but never described (that would also make this an enumeration oracle)…
- if strings.Contains(body, "attacker@vps") {
- t.Fatalf("the page resolved a code from a URL:\n%s", body)
+ for _, want := range []string{userCode, "Claude Code on box", `value="approve"`, `value="deny"`,
+ esc(copyText("cli.check")), esc(copyText("cli.not_me")),
+ esc(copyText("cli.lede", "label", "Claude Code on box", "console", fx.srv.brandName()))} {
+ if !strings.Contains(body, want) {
+ t.Fatalf("approval page missing %q:\n%s", want, body)
+ }
}
- // …and never one click from approval.
- if strings.Contains(body, `value="approve"`) {
- t.Fatalf("the page rendered an Approve button for a code from a URL:\n%s", body)
+ if !strings.Contains(body, `<a href="/settings">agents and terminals</a>`) || strings.Contains(body, "command-line access") {
+ t.Fatalf("approval page settings link is not \"agents and terminals\":\n%s", body)
}
- if strings.Contains(body, `name="code" value="`+userCode) {
- t.Fatalf("the page prefilled the typed-code field from the URL:\n%s", body)
+ // The code is the one the approve form submits, not one typed again.
+ if !strings.Contains(body, `name="code" value="`+userCode+`"`) {
+ t.Fatalf("the approve form does not carry the link's code:\n%s", body)
}
- // The request really is still pending — the page did not consume it, it
- // simply refused to act on it.
_, poll := postJSON(t, fx.ts.URL+"/auth/cli/poll", map[string]string{"device_code": str(t, start, "device_code")}, "")
if str(t, poll, "status") != CLIAuthPending {
t.Fatalf("poll = %v, want the request untouched and pending", poll)
}
}
+// A link whose code is no longer pending (approved, denied, or never issued)
+// says so and offers the typed-code box, never an Approve button.
+func TestCLIApprovalPageStaleCodeShowsTheBox(t *testing.T) {
+ fx := newConsoleFixture(t)
+ browser := newBrowser(t)
+ signUp(t, fx, browser, "code-stale")
+ now := time.Now()
+ approved, _, err := fx.st.NewCLIAuth("approved@box", "192.0.2.1", now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.ApproveCLIAuth(approved, "paul@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ denied, _, err := fx.st.NewCLIAuth("denied@box", "192.0.2.1", now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.DenyCLIAuth(denied, now); err != nil {
+ t.Fatal(err)
+ }
+ for name, code := range map[string]string{"approved": approved, "denied": denied, "unknown": "ZZZZ-ZZZZ"} {
+ status, _, body := get(t, browser, fx.ts.URL+"/auth/cli?code="+url.QueryEscape(code))
+ if status != http.StatusOK {
+ t.Fatalf("%s: approval page = %d", name, status)
+ }
+ if strings.Contains(body, `value="approve"`) {
+ t.Fatalf("%s: a stale code rendered an Approve button:\n%s", name, body)
+ }
+ if !strings.Contains(body, `name="code" value=""`) || !strings.Contains(body, `value="continue"`) {
+ t.Fatalf("%s: no typed-code box:\n%s", name, body)
+ }
+ if !strings.Contains(body, esc(copyText("cli.link_unknown"))) {
+ t.Fatalf("%s: the page does not say the link's code is spent:\n%s", name, body)
+ }
+ if strings.Contains(body, name+"@box") {
+ t.Fatalf("%s: a stale code was described:\n%s", name, body)
+ }
+ }
+}
+
+// GET lookups that find nothing spend their own budget, and past it a VALID
+// code is refused exactly like a wrong one: the page is not an oracle.
+func TestCLIApprovalPageLookupBudget(t *testing.T) {
+ fx := newConsoleFixture(t)
+ browser := newBrowser(t)
+ signUp(t, fx, browser, "code-look")
+ refusedBody := ""
+ for i := 0; i < cliGuessBurst+3 && refusedBody == ""; i++ {
+ status, _, body := get(t, browser, fx.ts.URL+"/auth/cli?code=ZZZZ-ZZZZ")
+ switch status {
+ case http.StatusOK:
+ case http.StatusTooManyRequests:
+ refusedBody = body
+ default:
+ t.Fatalf("bad code %d = %d", i, status)
+ }
+ }
+ if refusedBody == "" {
+ t.Fatalf("bad link codes were never rate-limited in %d lookups", cliGuessBurst+3)
+ }
+ _, start := postJSON(t, fx.ts.URL+"/auth/cli/start", map[string]string{"label": "look@laptop"}, "")
+ userCode := str(t, start, "user_code")
+ status, _, body := get(t, browser, fx.ts.URL+"/auth/cli?code="+url.QueryEscape(userCode))
+ if status != http.StatusTooManyRequests {
+ t.Fatalf("valid code past the lookup budget = %d, want 429", status)
+ }
+ if strings.Contains(body, "look@laptop") || strings.Contains(body, userCode) {
+ t.Fatalf("a refused lookup described the login:\n%s", body)
+ }
+ if body != refusedBody {
+ t.Fatalf("the refusal differs for a valid code:\nbad:\n%s\nvalid:\n%s", refusedBody, body)
+ }
+ // The bare page, with no code to look up, is never refused.
+ if status, _, _ := get(t, browser, fx.ts.URL+"/auth/cli"); status != http.StatusOK {
+ t.Fatalf("bare approval page past the lookup budget = %d, want 200", status)
+ }
+}
+
+// A signed-in top-level navigation carries no CSRF token, so forcing GETs to
+// bad codes must never spend the decision budget: Approve still works.
+func TestCLIForcedLookupsLeaveDecisionsWorking(t *testing.T) {
+ fx := newConsoleFixture(t)
+ browser := newBrowser(t)
+ signUp(t, fx, browser, "code-forced")
+ limited := false
+ for i := 0; i < cliGuessBurst+3; i++ {
+ if status, _, _ := get(t, browser, fx.ts.URL+"/auth/cli?code=ZZZZ-ZZZZ"); status == http.StatusTooManyRequests {
+ limited = true
+ }
+ }
+ if !limited {
+ t.Fatal("precondition: the lookup budget was never spent")
+ }
+ _, start := postJSON(t, fx.ts.URL+"/auth/cli/start", map[string]string{"label": "forced@laptop"}, "")
+ code, _, body := postGated(t, fx, browser, fx.ts.URL+"/auth/cli/approve",
+ url.Values{"code": {str(t, start, "user_code")}, "action": {"approve"}, "csrf": {sessionToken(t, fx, browser)}})
+ if code != http.StatusOK || !strings.Contains(body, "Approved") {
+ t.Fatalf("approve after forced lookups = %d:\n%s", code, body)
+ }
+}
+
+// dbipReader is the apigeo tests' GeoIP2-City fixture relabelled as a DB-IP
+// database: the metadata's database_type is rewritten in place (same length),
+// so the source the snapshot reports is one AttributionFor credits.
+func dbipReader(t *testing.T) *geo.Swappable {
+ t.Helper()
+ raw, err := os.ReadFile("../geo/testdata/GeoIP2-City-Test.mmdb")
+ if err != nil {
+ t.Fatal(err)
+ }
+ meta := bytes.LastIndex(raw, []byte("\xab\xcd\xefMaxMind.com"))
+ if meta < 0 || bytes.Count(raw[meta:], []byte("GeoIP2-City")) != 1 {
+ t.Fatal("fixture metadata not as expected")
+ }
+ raw = append(raw[:meta:meta], bytes.Replace(raw[meta:], []byte("GeoIP2-City"), []byte("DBIP-City-L"), 1)...)
+ path := filepath.Join(t.TempDir(), "dbip.mmdb")
+ if err := os.WriteFile(path, raw, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ db, err := geo.OpenMMDB(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sw := geo.NewSwappable()
+ sw.Swap(db)
+ t.Cleanup(func() { sw.Swap(nil) })
+ return sw
+}
+
+// Where a login dialled from: the platform GeoIP answer, with the credit its
+// database's licence asks for from the same snapshot, and nothing at all
+// when there is no answer.
+func TestCLIPlaceAttribution(t *testing.T) {
+ fx := newConsoleFixture(t)
+ if got := fx.srv.cliPlaceFor("81.2.69.142"); got != (cliPlace{}) {
+ t.Fatalf("nil reader = %+v, want nothing", got)
+ }
+ empty := geo.NewSwappable()
+ fx.srv.cfg.GeoIPReader = empty
+ if got := fx.srv.cliPlaceFor("81.2.69.142"); got != (cliPlace{}) {
+ t.Fatalf("empty reader = %+v, want nothing", got)
+ }
+ fx.srv.cfg.GeoIPReader = dbipReader(t)
+ want := cliPlace{Text: "United Kingdom (GB-ENG)", Attribution: "IP Geolocation by DB-IP", AttributionURL: "https://db-ip.com"}
+ for _, addr := range []string{"81.2.69.142", "81.2.69.142:52114"} {
+ if got := fx.srv.cliPlaceFor(addr); got != want {
+ t.Fatalf("cliPlaceFor(%q) = %+v, want %+v", addr, got, want)
+ }
+ }
+ for _, addr := range []string{"10.0.0.1", "", "not-an-ip"} {
+ if got := fx.srv.cliPlaceFor(addr); got != (cliPlace{}) {
+ t.Fatalf("cliPlaceFor(%q) = %+v, want nothing", addr, got)
+ }
+ }
+
+ // And the page shows it beside the address.
+ browser := newBrowser(t)
+ signUp(t, fx, browser, "code-place")
+ userCode, _, err := fx.st.NewCLIAuth("place@laptop", "81.2.69.142", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ status, _, body := get(t, browser, fx.ts.URL+"/auth/cli?code="+url.QueryEscape(userCode))
+ if status != http.StatusOK {
+ t.Fatalf("approval page = %d", status)
+ }
+ for _, want := range []string{"81.2.69.142", "United Kingdom (GB-ENG)", `<a href="https://db-ip.com">IP Geolocation by DB-IP</a>`} {
+ if !strings.Contains(body, want) {
+ t.Fatalf("approval page missing %q:\n%s", want, body)
+ }
+ }
+}
+
+// The place line names the country, with the subdivision code in brackets
+// when there is one, and falls back to the code for a country it cannot name.
+func TestCLIPlaceText(t *testing.T) {
+ for _, tc := range []struct{ country, sub, want string }{
+ {"GB", "GB-ENG", "United Kingdom (GB-ENG)"},
+ {"GB", "", "United Kingdom"},
+ {"QQ", "", "QQ"},
+ {"QQ", "QQ-1", "QQ (QQ-1)"},
+ } {
+ if got := cliPlaceText(tc.country, tc.sub); got != tc.want {
+ t.Errorf("cliPlaceText(%q, %q) = %q, want %q", tc.country, tc.sub, got, tc.want)
+ }
+ }
+}
+
+// The typed-code path describes a login exactly as the link does: its age
+// and where it dialled from, not "just now" and no place.
+func TestCLITypedCodeDescribesAgeAndPlace(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.GeoIPReader = dbipReader(t)
+ browser := newBrowser(t)
+ signUp(t, fx, browser, "code-typed-age")
+ userCode, _, err := fx.st.NewCLIAuth("typed@laptop", "81.2.69.142", time.Now().Add(-3*time.Minute))
+ if err != nil {
+ t.Fatal(err)
+ }
+ status, _, body := postForm(t, browser, fx.ts.URL+"/auth/cli/approve",
+ url.Values{"code": {userCode}, "action": {"continue"}, "csrf": {sessionToken(t, fx, browser)}})
+ if status != http.StatusOK || !strings.Contains(body, "typed@laptop") {
+ t.Fatalf("continue = %d:\n%s", status, body)
+ }
+ if strings.Contains(body, esc(copyText("cli.started_now"))) {
+ t.Fatalf("a three-minute-old login reads as just started:\n%s", body)
+ }
+ for _, want := range []string{esc(copyText("cli.started", "ago", "3m")), "United Kingdom (GB-ENG)",
+ `<a href="https://db-ip.com">IP Geolocation by DB-IP</a>`} {
+ if !strings.Contains(body, want) {
+ t.Fatalf("continue page missing %q:\n%s", want, body)
+ }
+ }
+}
+
// Issuing a credential tells the human, in the inbox their identity is
// anchored to. Every other defence here is preventive; this is the one that
// makes a phished approval detectable afterwards.
@@ -366,6 +576,26 @@ func TestCleanLabelIsPrintableASCII(t *testing.T) {
}
// A denied login is final and tells the terminal so.
+func TestCLIApprovedPagePointsBack(t *testing.T) {
+ fx := newConsoleFixture(t)
+ browser := newBrowser(t)
+ signUp(t, fx, browser, "code-approved-back")
+ _, start := postJSON(t, fx.ts.URL+"/auth/cli/start", map[string]string{"label": "Claude Code on box"}, "")
+ status, _, body := postGated(t, fx, browser, fx.ts.URL+"/auth/cli/approve",
+ url.Values{"code": {str(t, start, "user_code")}, "action": {"approve"}, "csrf": {sessionToken(t, fx, browser)}})
+ if status != http.StatusOK {
+ t.Fatalf("approve = %d:\n%s", status, body)
+ }
+ for _, want := range []string{"Claude Code on box", `href="/"`, esc(copyText("cli.open_apps"))} {
+ if !strings.Contains(body, want) {
+ t.Fatalf("approved page missing %q:\n%s", want, body)
+ }
+ }
+ if strings.Contains(body, "terminal") {
+ t.Fatalf("approved page still says terminal:\n%s", body)
+ }
+}
+
func TestCLILoginDeny(t *testing.T) {
fx := newConsoleFixture(t)
browser := newBrowser(t)
@@ -450,6 +680,41 @@ func TestCLIApproveRateLimitsWrongCodes(t *testing.T) {
}
}
+// The decision budget is checked BEFORE a code is resolved, so a caller past
+// the limit cannot learn whether a code is live: the VALID code is refused
+// exactly like a wrong one.
+func TestCLIDecisionBudgetRefusesValidCodeOnceSpent(t *testing.T) {
+ for _, action := range []string{"continue", "approve", "deny"} {
+ t.Run(action, func(t *testing.T) {
+ fx := newConsoleFixture(t)
+ browser := newBrowser(t)
+ signUp(t, fx, browser, "code-budget-"+action)
+ csrf := sessionToken(t, fx, browser)
+ for i := 0; i < cliGuessBurst; i++ {
+ status, _, _ := postForm(t, browser, fx.ts.URL+"/auth/cli/approve",
+ url.Values{"code": {"AAAA-AAAA"}, "action": {"continue"}, "csrf": {csrf}})
+ if status != http.StatusOK {
+ t.Fatalf("wrong code %d = %d, want 200 inside the budget", i, status)
+ }
+ }
+ _, start := postJSON(t, fx.ts.URL+"/auth/cli/start", map[string]string{"label": "budget@laptop"}, "")
+ userCode := str(t, start, "user_code")
+ code, _, body := postGated(t, fx, browser, fx.ts.URL+"/auth/cli/approve",
+ url.Values{"code": {userCode}, "action": {action}, "csrf": {csrf}})
+ if code != http.StatusTooManyRequests {
+ t.Fatalf("valid code past the budget = %d, want 429", code)
+ }
+ if strings.Contains(body, "budget@laptop") {
+ t.Fatalf("a refused lookup described the terminal:\n%s", body)
+ }
+ _, poll := postJSON(t, fx.ts.URL+"/auth/cli/poll", map[string]string{"device_code": str(t, start, "device_code")}, "")
+ if str(t, poll, "status") != CLIAuthPending {
+ t.Fatalf("poll = %v, want the request untouched and pending", poll)
+ }
+ })
+ }
+}
+
func TestCLIPollUnknownDeviceCode(t *testing.T) {
fx := newConsoleFixture(t)
status, poll := postJSON(t, fx.ts.URL+"/auth/cli/poll", map[string]string{"device_code": "nope"}, "")
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go
index 93b667531..c0ffa21ab 100644
--- a/internal/console/claim_invariant_probes_read_test.go
+++ b/internal/console/claim_invariant_probes_read_test.go
@@ -217,7 +217,7 @@ var claimReadProbes = map[string]claimProbe{
"route GET /a/{sqid}/{$}": claimPageRead(nil, "/a/bab/", "kass"),
"route GET /accounts/new": claimPageRead(nil, "/accounts/new", "<h1>New account</h1>"),
"route GET /settings": claimPageRead(nil, "/settings", "<h1>Your settings</h1>"),
- "route GET /auth/cli": claimPageRead(nil, "/auth/cli", "<h1>Approve a terminal</h1>"),
+ "route GET /auth/cli": claimPageRead(claimDeviceLogin, "/auth/cli?code=<usercode>", "<h1>Approve a sign-in</h1>", "census terminal", `value="approve"`),
"route GET /invite/{token}": claimInvitePageProbe(),
"route GET /fleet": claimPageRead(nil, "/fleet", "<h1>Dashboard</h1>"),
"route GET /fleet/activity": claimPageRead(nil, "/fleet/activity", "<h1>Activity</h1>"),
diff --git a/internal/console/cliplace.go b/internal/console/cliplace.go
new file mode 100644
index 000000000..ee748fb0b
--- /dev/null
+++ b/internal/console/cliplace.go
@@ -0,0 +1,56 @@
+package console
+
+// The approval page's location line (agent login by link, spec §3): where a
+// login dialled from, as the platform GeoIP answer gives it. The answer has
+// no city, so this is a country and perhaps a subdivision; with no answer it
+// is empty and the page shows the address alone. The country is shown by
+// name, the subdivision by its code in brackets (cliPlaceText).
+
+import (
+ "net"
+
+ "github.com/carlosframework/platform/internal/geoip"
+)
+
+// cliPlace is the location beside a login's address, with the credit the
+// answering database's licence asks for when it asks for one.
+type cliPlace struct{ Text, Attribution, AttributionURL string }
+
+// cliPlaceFor looks remoteAddr up once. The place, its source and its
+// attribution all come from that one snapshot, so a database swap between
+// the lookup and the render can never credit the wrong database (geoip spec
+// §5.4). remoteAddr is a stored CLIAuthRequest.RemoteAddr, "ip" or
+// "ip:port"; anything else, a nil or empty reader, and a miss all answer the
+// zero cliPlace. The address is never logged.
+func (s *Server) cliPlaceFor(remoteAddr string) cliPlace {
+ if s.cfg.GeoIPReader == nil {
+ return cliPlace{}
+ }
+ host := remoteAddr
+ if h, _, err := net.SplitHostPort(remoteAddr); err == nil {
+ host = h
+ }
+ ip := net.ParseIP(host)
+ if ip == nil {
+ return cliPlace{}
+ }
+ a := geoip.FromSnapshot(s.cfg.GeoIPReader.Lookup(ip))
+ if a.State != geoip.StateHit || a.Country == "" {
+ return cliPlace{}
+ }
+ p := cliPlace{Text: cliPlaceText(a.Country, a.Subdivision)}
+ if at, ok := geoip.AttributionFor(a.Source); ok {
+ p.Attribution, p.AttributionURL = at.Text, at.URL
+ }
+ return p
+}
+
+// cliPlaceText names the country (countryName, falling back to the code it
+// cannot name) with the subdivision code in brackets when there is one:
+// "United Kingdom (GB-ENG)", or "United Kingdom".
+func cliPlaceText(country, subdivision string) string {
+ if subdivision != "" {
+ return countryName(country) + " (" + subdivision + ")"
+ }
+ return countryName(country)
+}
diff --git a/internal/console/emailsignin_test.go b/internal/console/emailsignin_test.go
index 71271e268..22b8178bd 100644
--- a/internal/console/emailsignin_test.go
+++ b/internal/console/emailsignin_test.go
@@ -616,7 +616,7 @@ func TestInvitePageSignedOutPrefills(t *testing.T) {
func TestCLIPageSignedOutBanner(t *testing.T) {
fx := newConsoleFixture(t)
status, _, body := get(t, newBrowser(t), fx.ts.URL+"/auth/cli")
- if status != http.StatusOK || !strings.Contains(body, esc(copyText("home.cli_prompt"))) ||
+ if status != http.StatusOK || !strings.Contains(body, esc(copyText("cli.signin_prompt"))) ||
!strings.Contains(body, `name="next" value="/auth/cli"`) || !strings.Contains(body, `action="/auth/continue"`) {
t.Fatalf("signed-out /auth/cli = %d:\n%s", status, body)
}
diff --git a/internal/console/emailstepup_test.go b/internal/console/emailstepup_test.go
index e12257250..28902cfd9 100644
--- a/internal/console/emailstepup_test.go
+++ b/internal/console/emailstepup_test.go
@@ -401,7 +401,7 @@ func TestCLILoginByEmailUserOneEmail(t *testing.T) {
c := newBrowser(t)
status, _, body := get(t, c, fx.ts.URL+"/auth/cli")
- if status != http.StatusOK || !strings.Contains(body, esc(copyText("home.cli_prompt"))) ||
+ if status != http.StatusOK || !strings.Contains(body, esc(copyText("cli.signin_prompt"))) ||
!strings.Contains(body, `name="next" value="/auth/cli"`) {
t.Fatalf("signed-out /auth/cli = %d:\n%s", status, body)
}
diff --git a/internal/console/signincopy.go b/internal/console/signincopy.go
index 18835b295..36a4634a4 100644
--- a/internal/console/signincopy.go
+++ b/internal/console/signincopy.go
@@ -47,6 +47,29 @@ var signinCopy = map[string]string{
"team.bad_address": "That doesn't look like an email address.",
}
+// agentLoginCopy holds the approval page's strings for agent login by link
+// (2026-11-07-agent-login-link-design.md §3, §5). DRAFTS, awaiting copy
+// review (the plan's Task 5 applies the approved text verbatim). Kept apart
+// from signinCopy, which TestSigninCopyMatchesApproved pins to approved copy
+// byte for byte. cli.signin_prompt replaces home.cli_prompt on the front
+// page; the approved home.cli_prompt stays in signinCopy until that review
+// retires it.
+var agentLoginCopy = map[string]string{
+ "cli.title": "Approve a sign-in",
+ "cli.lede": "A machine calling itself {label} is asking to use {console} as you.",
+ "cli.unnamed": "An unnamed agent or terminal",
+ "cli.check": "Does your agent or terminal show this code?",
+ "cli.not_me": "If you didn't just ask an agent or terminal to log in, press That wasn't me.",
+ "cli.started": "Started {ago} ago.",
+ "cli.started_now": "Started just now.",
+ "cli.link_unknown": "That link's code has expired or was already used. Start the login again from your agent or terminal.",
+ "cli.signin_prompt": "Sign in to connect your agent or terminal.",
+ "cli.approved": "Connected. Go back to {label}. It carries on by itself.",
+ "cli.open_apps": "Open your apps",
+ "cli.denied": "Nothing was issued. That sign-in can't be approved now; if it wasn't yours, whoever started it got nothing.",
+ "cli.settings_link": "agents and terminals",
+}
+
// copyText returns the approved string for id with each {key} placeholder
// replaced by its value (kv is key, value, key, value, ...). An unknown id is
// a programming error and panics, so a typo cannot ship blank copy.
@@ -55,6 +78,9 @@ func copyText(id string, kv ...string) string {
if !ok {
text, ok = socialSigninCopy[id]
}
+ if !ok {
+ text, ok = agentLoginCopy[id]
+ }
if !ok {
panic("console: unknown copy id " + id)
}
diff --git a/internal/console/templates/cli_approve.html b/internal/console/templates/cli_approve.html
index dae971dcc..e89d33430 100644
--- a/internal/console/templates/cli_approve.html
+++ b/internal/console/templates/cli_approve.html
@@ -1,20 +1,23 @@
{{define "cli_approve"}}{{template "top" .}}
-<h1>Approve a terminal</h1>
+<h1>{{.CLIText "cli.title"}}</h1>
{{if .Error}}<p class="error">{{.Error}}</p>{{end}}
{{if .Request}}
-<p class="lede">A command line asked to sign in as you.</p>
+<p class="lede">{{.Lede}}</p>
+<p class="tile-value"><code>{{.Request.UserCode}}</code></p>
+<p><strong>{{.CLIText "cli.check"}}</strong></p>
<div class="banner">
- <p><strong>Code</strong> <code>{{.Request.UserCode}}</code></p>
- <p><strong>Terminal</strong> {{emptyOrDash .Request.Label}}
- <span class="small">— this name was supplied by the machine asking. Trust
+ <p><strong>Agent or terminal</strong> {{emptyOrDash .Request.Label}}.
+ <span class="small">This name was supplied by the machine asking. Trust
it only if it matches the machine in front of you.</span></p>
- <p><strong>From</strong> {{emptyOrDash .Request.RemoteAddr}}</p>
- <p class="small">Expires {{fmtTime .Request.ExpiresAt}}</p>
+ <p><strong>From</strong> {{emptyOrDash .Request.RemoteAddr}}{{if .Place.Text}}, {{.Place.Text}}{{end}}
+ {{- if .Place.Attribution}} <span class="small">(<a href="{{.Place.AttributionURL}}">{{.Place.Attribution}}</a>)</span>{{end}}</p>
+ <p class="small">{{.StartedText}} Expires {{fmtTime .Request.ExpiresAt}}</p>
</div>
-<p>Approving gives that terminal your identity — every account you belong to —
+<p>Approving gives that agent or terminal your identity, including every account you belong to,
for {{.Days}} days. You can revoke it at any time from
-<a href="/settings">command-line access</a>, and a note goes to your
+<a href="/settings">{{.CLIText "cli.settings_link"}}</a>, and a note goes to your
Keymail inbox the moment it is issued.</p>
+<p>{{.CLIText "cli.not_me"}}</p>
<form class="signin" method="post" action="/auth/cli/approve">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<input type="hidden" name="code" value="{{.Request.UserCode}}">
@@ -23,37 +26,22 @@ Keymail inbox the moment it is issued.</p>
</form>
{{else}}
<p class="lede">Type the code your terminal printed.</p>
-{{if .LinkCode}}
-<div class="banner">
- <p>The link you followed carries the code <code>{{.LinkCode}}</code>.</p>
- <p class="small"><strong>Check it against your own screen before typing it.</strong>
- If you did not just run <code>carlos auth login</code> yourself, or that is not
- the code your terminal printed, close this page: somebody else is asking to
- become you, and typing their code is what would let them.</p>
-</div>
-{{end}}
<form class="signin" method="post" action="/auth/cli/approve">
<input type="text" name="code" value="" placeholder="XXXX-XXXX" autocomplete="off" spellcheck="false">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<button type="submit" name="action" value="continue">Continue</button>
</form>
-<p class="small">Codes look like <code>WXYZ-4823</code> and last ten minutes.
-Nothing here is ever approved by following a link — the code has to be typed,
-which means it has to be on a screen in front of you.</p>
+<p class="small">Codes look like <code>WXYZ-4823</code> and last ten minutes.</p>
{{end}}
{{template "bottom" .}}{{end}}
{{define "cli_decided"}}{{template "top" .}}
<h1>{{.Title}}</h1>
{{if eq .Title "Approved"}}
-<p>Your terminal has the credential — it should say so within a couple of
-seconds. It expires in {{.Days}} days, and a note is on its way to your Keymail
-inbox.</p>
-<p><a href="/settings">See every terminal signed in as you</a>, and
-revoke any you don't recognise.</p>
+<p class="lede">{{.ApprovedText}}</p>
+<p><a href="/">{{.CLIText "cli.open_apps"}}</a></p>
{{else}}
-<p>Nothing was issued. That login attempt is dead and cannot be approved
-afterwards; if it wasn't yours, whoever started it got nothing.</p>
+<p>{{.CLIText "cli.denied"}}</p>
+<p><a href="/">{{.CLIText "cli.open_apps"}}</a></p>
{{end}}
-<p class="small"><a href="/">Back to the console</a></p>
{{template "bottom" .}}{{end}}
diff --git a/internal/provision/testdata/plan14-root-reads-agent-login-link.tsv b/internal/provision/testdata/plan14-root-reads-agent-login-link.tsv
new file mode 100644
index 000000000..09fc11369
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-agent-login-link.tsv
@@ -0,0 +1,8 @@
+# Census overlay agent-login-link, written by census-propose (#369). census-ruling-agent-login-link, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-agent-login-link.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 2 new dispositions: 0 reads re-frozen at their disposition with the claim, 2 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 8c041c2731437fddfe69896ac8af61a3da72e3a211484818be8f1fe935943cf4 authpending.go readPendingLogins legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-login-link;basis=new: lists login-pending.d/ beside the CLI credentials file and reads each attempt file file:ReadDir@105,file:ReadFile@404 6551b22b2ccf9ec9b2fd705a3980856af45e3cf678939758ad2f04563344af8d
+@legacy 02a09284e001222ccb12e15602065490046b3452a7194758b6b1d713ad412540 authpending.go savePendingLogin legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-login-link;basis=changed: writes only its own attempt file, never lists or deletes other unexpired attempts file:CreateTemp@257 e0ec5e37e2ee9e1cb59550f4a54031d94e60d0401054a7ca05e4c8cc8c867c12
+authpending.go readPendingLogins legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-login-link;basis=new: lists login-pending.d/ beside the CLI credentials file and reads each attempt file file:ReadDir@105,file:ReadFile@404 6551b22b2ccf9ec9b2fd705a3980856af45e3cf678939758ad2f04563344af8d
+authpending.go savePendingLogin legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-login-link;basis=changed: writes only its own attempt file, never lists or deletes other unexpired attempts file:CreateTemp@257 e0ec5e37e2ee9e1cb59550f4a54031d94e60d0401054a7ca05e4c8cc8c867c12
+@coverage . b69c9ead0225439f30e9b3fc46bce77b19db4e5661674e4a0346c1386415217a
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 74904f782..2f64c1076 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -123,3 +123,4 @@ plan14-root-reads-claim-source.tsv 9cdff432a5de2ffeaa147fdafd6a486c61c27a0c38f77
plan14-root-reads-region-ha-graceful-terminate-t1.tsv 3273ecae03559a8d450027f4cdf4dff24af9c54705231bc4f7c77b72582b517c
plan14-root-reads-region-ha-graceful-terminate-t2.tsv 687cf7744aecdf8a238dcdb80562b0ef191b3e247c28851de44c01866dbeca13
plan14-root-reads-static-sweep-periodic.tsv 3dc3f6657527133a251c028772315bdd333b04c318fbbc6d90ef5047f15408ed
+plan14-root-reads-agent-login-link.tsv e820ef22ac677cd49aa9ca3f70d6bca9dea061bce3184ca86f0a3fc98f8de0eb