package thintest import ( "bytes" "encoding/base64" "html" "net/http" "net/url" "os" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/sealbox" "amadan.net/oficina/equipo/internal/wire" ) // canaryCode is an obviously fake sign-in code. const canaryCode = "CANARYCODE-not-a-real-code#CANARYSTATE" // signInLink is the authorize link a runner's setup-token printed (fake). const signInLink = "https://claude.com/cai/oauth/authorize?code=true&client_id=fake&response_type=code&redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback&state=s1" // TestContractSignInCode (Paul, 2026-11-10): Claude with the browser // elsewhere starts the runner's own setup-token (kind subscription, the // card starting); the runner's link goes on the card with its attempt; // a sealed code bound to the code endpoint and that attempt goes to the // runner as a durable secret frame, one per card, the card waiting; a // wrong code's new card takes the next; healthy turns the record into a // token connection. A box the card did not ask for is refused. The // code's plaintext and the box appear nowhere on the instance. func TestContractSignInCode(t *testing.T) { r := newRig(t) rec := &recorder{} r.client.HTTP.Transport = rec keys := sealKeys(t) runner := r.dial(0) hello := held() hello.Generation, hello.SealKey = runner.Welcome.Generation, keys.PublicString() if err := runner.Send(r.ctx, "h1", wire.FrameHello, hello); err != nil { t.Fatal(err) } r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) var runnerID string waitFor(t, "the seal key published", func() bool { list, err := r.client.Runners(r.ctx) if err != nil || len(list.Items) != 1 { return false } runnerID = list.Items[0].ID return list.Items[0].SealKey == keys.PublicString() }) attempt, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude"}) if err != nil || attempt.Kind != wire.KindSubscription || attempt.Prompt == nil || attempt.Prompt.Kind != wire.PromptAuthorize || attempt.Prompt.URL != "" || attempt.Prompt.Attempt != 0 { t.Fatalf("sign-in attempt %+v %v", attempt, err) } f, body, err := runner.Expect(r.ctx, wire.FrameConnect) if err != nil { t.Fatal(err) } if cmd := body.(*wire.ConnectCommand); cmd.Kind != wire.KindSubscription || cmd.SameMachine || cmd.Provider != "claude" { t.Fatalf("connect frame %+v", cmd) } _ = runner.Send(r.ctx, "a-connect", wire.FrameAck, wire.Ack{ID: f.ID}) seal := func(code string, n int64, endpoint string) wire.Sealed { t.Helper() s, err := sealbox.Seal(keys.PublicString(), wire.SealedPayload{Secret: code, RunnerID: runnerID, ConnectionID: attempt.ID, Provider: "claude", Endpoint: endpoint, Attempt: n, ExpiresAt: time.Now().UTC().Add(wire.SealedTTL).Truncate(time.Second)}) if err != nil { t.Fatal(err) } return s } // No link yet: nothing to answer. if _, err = r.client.Secret(r.ctx, attempt.ID, seal(canaryCode, 1, wire.EndpointClaudeCode)); Status(err) != 409 { t.Fatalf("a code before the link: %v", err) } if err = runner.Send(r.ctx, "r-link", wire.FrameConnection, wire.ConnectionReport{Connection: attempt.ID, Person: Owner, Provider: "claude", State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptAuthorize, URL: signInLink, Attempt: 1}}); err != nil { t.Fatal(err) } r.wait("the link on the card", func(c *Conversation) bool { p := c.Connections[attempt.ID].Prompt return p != nil && p.URL == signInLink && p.Attempt == 1 }) page := html.UnescapeString(r.inst.Get(t, "/conversation/settings/connections/add")) for _, want := range []string{"Open Anthropic", "Copy link", "Paste the code Anthropic shows you", `data-attempt="1"`, `data-endpoint="` + wire.EndpointClaudeCode + `"`, `data-seal-key="` + keys.PublicString() + `"`, "Paste a token you already have"} { if !strings.Contains(page, want) { t.Fatalf("the card lacks %q", want) } } if strings.Contains(page, "That code did not work.") { t.Fatal("a first card says the code was wrong") } for name, box := range map[string]wire.Sealed{ "attempt 0": seal(canaryCode, 0, wire.EndpointClaudeCode), "past the last": seal(canaryCode, wire.MaxCodeAttempts+1, wire.EndpointClaudeCode), "a token's binding": seal(canaryCode, 1, wire.EndpointAnthropic), "another endpoint": seal(canaryCode, 1, "https://platform.claude.com/oauth/other"), } { if _, err := r.client.Secret(r.ctx, attempt.ID, box); Status(err) != 422 { t.Fatalf("%s: %v", name, err) } } if _, err := r.client.Secret(r.ctx, attempt.ID, seal(canaryCode, 2, wire.EndpointClaudeCode)); Status(err) != 409 { t.Fatalf("an attempt the card did not ask for: %v", err) } first := seal(canaryCode, 1, wire.EndpointClaudeCode) posted, err := r.client.Secret(r.ctx, attempt.ID, first) if err != nil || posted.Prompt == nil || posted.Prompt.Kind != wire.PromptAuthorize || posted.Prompt.URL != "" || posted.Prompt.Attempt != 1 { t.Fatalf("code %+v %v", posted, err) } if _, err := r.client.Secret(r.ctx, attempt.ID, first); Status(err) != 409 { t.Fatalf("a second box for one card: %v", err) } if page := r.inst.Get(t, "/conversation/settings/connections/add"); !strings.Contains(page, "Your runner is finishing the sign-in") || strings.Contains(page, "Open Anthropic") { t.Fatal("the card does not wait for the runner") } f, body, err = runner.Expect(r.ctx, wire.FrameSecret) if err != nil { t.Fatal(err) } cmd := body.(*wire.SecretCommand) if opened, err := keys.Open(cmd.Sealed, time.Now()); err != nil || opened.Secret != canaryCode || opened.Endpoint != wire.EndpointClaudeCode || opened.Attempt != 1 { t.Fatalf("the runner's box: %v", err) } _ = runner.Send(r.ctx, "a-secret", wire.FrameAck, wire.Ack{ID: f.ID}) // A wrong code: the runner's next card says so and takes attempt 2. if err = runner.Send(r.ctx, "r-wrong", wire.FrameConnection, wire.ConnectionReport{Connection: attempt.ID, Person: Owner, Provider: "claude", State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptAuthorize, URL: signInLink, Attempt: 2, WrongCode: true}}); err != nil { t.Fatal(err) } r.wait("the wrong-code card", func(c *Conversation) bool { p := c.Connections[attempt.ID].Prompt return p != nil && p.Attempt == 2 && p.WrongCode && p.URL != "" }) if got, err := r.client.Connection(r.ctx, attempt.ID); err != nil { t.Fatal(err) } else { shape(t, "api/connection-signing-in-claude.json", got) } if page := r.inst.Get(t, "/conversation/settings/connections/add"); !strings.Contains(page, "That code did not work. Open Anthropic again and paste the new code.") || !strings.Contains(page, `data-attempt="2"`) { t.Fatal("the card does not say the code was wrong") } second := seal(canaryCode, 2, wire.EndpointClaudeCode) shape(t, "api/connection-code.json", second) if _, err = r.client.Secret(r.ctx, attempt.ID, second); err != nil { t.Fatal(err) } f, _, err = runner.Expect(r.ctx, wire.FrameSecret) if err != nil { t.Fatal(err) } _ = runner.Send(r.ctx, "a-secret-2", wire.FrameAck, wire.Ack{ID: f.ID}) // Healthy: a token connection now, its expiry an estimate. if err = runner.Send(r.ctx, "r-healthy", wire.FrameConnection, wire.ConnectionReport{Connection: attempt.ID, Person: Owner, LocalID: "claude-1", Provider: "claude", State: wire.ConnHealthy, Label: Owner}); err != nil { t.Fatal(err) } r.wait("healthy", func(c *Conversation) bool { return c.Connections[attempt.ID].State == wire.ConnHealthy }) if got, err := r.client.Connection(r.ctx, attempt.ID); err != nil || got.Kind != wire.KindToken || got.ExpiresAt == nil || !got.ExpiresEstimated || got.Prompt != nil { t.Fatalf("connection %+v %v", got, err) } // A sign-in that ends refused says so plainly: not "This token was // rejected", and it stays a subscription attempt. other, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude"}) if err != nil { t.Fatal(err) } if err = runner.Send(r.ctx, "r-refused", wire.FrameConnection, wire.ConnectionReport{Connection: other.ID, Person: Owner, Provider: "claude", State: wire.ConnError, Reason: "provider_refused"}); err != nil { t.Fatal(err) } r.wait("refused", func(c *Conversation) bool { return c.Connections[other.ID].State == wire.ConnError }) if got, _ := r.client.Connection(r.ctx, other.ID); got.Kind != wire.KindSubscription { t.Fatalf("ended %+v", got) } if page := r.inst.Get(t, "/conversation/settings/connections/add"); !strings.Contains(page, "The provider did not complete the sign-in.") || strings.Contains(page, "This token was rejected") { t.Fatal("the ended sign-in's note") } // The sweep: pages, API responses, events, logs, rows, database and // WAL bytes. var sinks []string for _, path := range []string{"/conversation/settings/connections", "/conversation/settings/connections/add", "/conversation"} { sinks = append(sinks, r.inst.Get(t, path)) } if _, err := r.client.Connections(r.ctx); err != nil { t.Fatal(err) } var events, rows string _ = r.inst.DB.Writer().QueryRow("SELECT coalesce(group_concat(body, '|'), '') FROM chat_events").Scan(&events) _ = r.inst.DB.Writer().QueryRow("SELECT coalesce(group_concat(coalesce(prompt,'') || label || state || kind, '|'), '') FROM chat_connections").Scan(&rows) sinks = append(sinks, rawEvents(t, r), rec.String(), r.inst.Logs(), events, rows) canaries := []string{canaryCode, "CANARYCODE", "CANARYSTATE", base64.StdEncoding.EncodeToString([]byte(canaryCode))} for i, s := range sinks { for _, c := range canaries { if strings.Contains(s, c) { t.Fatalf("sink %d holds the code %q", i, c) } } for _, box := range []wire.Sealed{first, second} { if strings.Contains(s, box.Box[:24]) { t.Fatalf("sink %d holds a sealed box", i) } } } for _, suffix := range []string{"", "-wal", "-shm"} { raw, err := os.ReadFile(r.inst.Path + suffix) if err != nil { if os.IsNotExist(err) && suffix != "" { continue } t.Fatal(err) } for _, c := range canaries { if bytes.Contains(raw, []byte(c)) { t.Fatalf("database%s holds the code %q", suffix, c) } } } } // Recovering a Claude token connection is the sign-in by a link first, // as on the Add page: the rejected row's Sign in again and the renewal // line's Sign in again post no token kind, and start a sign-in attempt // whose card offers the paste second. A rejected row says only that the // token was rejected (its button says what to do). func TestContractTokenRecoverySignsIn(t *testing.T) { r := newRig(t) soon := time.Now().UTC().Add(10 * 24 * time.Hour) runner, err := DialRunnerHello(r.ctx, r.inst.URL, r.runner, held( wire.HeldConnection{LocalID: "claude-8", Person: Owner, Provider: "claude", Kind: wire.KindToken, Label: "old@example.com", State: wire.ConnSignInAgain}, wire.HeldConnection{LocalID: "claude-9", Person: Owner, Provider: "claude", Kind: wire.KindToken, Label: "soon@example.com", State: wire.ConnHealthy, ExpiresAt: &soon, ExpiresEstimated: true}, )) if err != nil { t.Fatal(err) } t.Cleanup(runner.Close) r.wait("the token connections", func(c *Conversation) bool { return len(c.Connections) == 2 }) page := r.inst.Get(t, "/conversation/settings/connections") rows := strings.Split(page, "