//go:build browser package headless import ( "context" "crypto/rand" "encoding/base64" "strconv" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/browsertest" "amadan.net/oficina/equipo/internal/thintest" "amadan.net/oficina/equipo/internal/wire" "github.com/chromedp/chromedp" "golang.org/x/crypto/nacl/box" ) // A Claude connection from a pasted setup token (Paul, 2026-11-09: // "really, really easy"), in a browser against a fake runner whose seal // key the test made, so the test opens what the page sealed. // canaryToken is an obviously fake setup token. const canaryToken = "sk-ant-oat01-CANARY-not-a-real-token-CANARY" // sealedWords stand beside the token field: what is trusted, and what // the server can and cannot do with the token. const sealedWords = "Sealed in your browser to your runner's key. This trusts the Equipo page that does the sealing. Equipo's server only passes on a sealed copy it cannot open." // tokenDay is where this feature's screenshots go. const tokenDay = "2026-11-10" type frameIn struct { frame wire.Frame body any } // fakeRunner is a runner the test speaks for: its hello carries the // seal key, and every frame it receives arrives on frames. type fakeRunner struct { *thintest.FakeRunner frames chan frameIn public *[32]byte private *[32]byte generation int64 n int } func dialFake(t *testing.T, inst *thintest.Instance) *fakeRunner { t.Helper() return dialFakeAt(t, inst, 0) } // dialFakeAt is dialFake for a runner that speaks protocol (0: the // hello's default). func dialFakeAt(t *testing.T, inst *thintest.Instance, protocol int) *fakeRunner { t.Helper() public, private, err := box.GenerateKey(rand.Reader) if err != nil { t.Fatal(err) } fr, err := thintest.DialRunnerHello(t.Context(), inst.URL, inst.EnrolRunner(t).Token, wire.Hello{Protocol: protocol, Repos: []string{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test"}, SealKey: base64.StdEncoding.EncodeToString(public[:])}) if err != nil { t.Fatal(err) } t.Cleanup(fr.Close) r := &fakeRunner{FakeRunner: fr, frames: make(chan frameIn, 64), public: public, private: private, generation: fr.Welcome.Generation} // One reader for the life of the connection: a read with a deadline // would close the socket when it passes. go func() { defer close(r.frames) for { _, raw, err := fr.Conn.Read(context.Background()) if err != nil { return } f, body, err := wire.ParseFrame(raw) if err != nil { return } r.frames <- frameIn{f, body} } }() return r } // expect waits for a frame of kind and acks it. func (r *fakeRunner) expect(t *testing.T, kind string) any { t.Helper() deadline := time.After(15 * time.Second) for { select { case in, ok := <-r.frames: if !ok { t.Fatalf("the runner's connection closed waiting for %s", kind) } if in.frame.Type != kind { continue } r.send(t, wire.FrameAck, wire.Ack{ID: in.frame.ID}) return in.body case <-deadline: t.Fatalf("no %s frame", kind) } } } func (r *fakeRunner) send(t *testing.T, kind string, body any) { t.Helper() r.n++ if err := r.Send(t.Context(), "f"+strconv.Itoa(r.n), kind, body); err != nil { t.Fatal(err) } } // hello says the runner holds conns, as its heartbeat does. func (r *fakeRunner) hello(t *testing.T, conns ...wire.HeldConnection) { t.Helper() r.send(t, wire.FrameHello, wire.Hello{Generation: r.generation, Repos: []string{}, Connections: append([]wire.HeldConnection{}, conns...), Versions: map[string]string{"runner": "test"}, SealKey: base64.StdEncoding.EncodeToString(r.public[:])}) } // open opens a box sealed to this runner (libsodium crypto_box_seal). func (r *fakeRunner) open(t *testing.T, s wire.Sealed) wire.SealedPayload { t.Helper() raw, err := base64.StdEncoding.DecodeString(s.Box) if err != nil { t.Fatal(err) } msg, ok := box.OpenAnonymous(nil, raw, r.public, r.private) if !ok { t.Fatal("the page's box does not open with box.OpenAnonymous") } var p wire.SealedPayload if err := wire.Strict(msg, &p); err != nil { t.Fatalf("the page's payload: %v", err) } return p } // recordPosts keeps every request body the page's scripts send. const recordPosts = `(()=>{window.__posts=[];const f=window.fetch;window.fetch=function(url,init){if(init&&init.method==='POST')window.__posts.push({url:String(url),body:String(init.body||'')});return f.apply(this,arguments)};return true})()` func TestBrowserConnectionsToken(t *testing.T) { for _, width := range []int64{1280, 390} { t.Run(strconv.FormatInt(width, 10), func(t *testing.T) { inst := thintest.StartInstance(t) runner := dialFake(t, inst) c := inst.Cookie() p := openPage(t, inst.URL, c.Name, c.Value, width, 900, width > 600) t.Cleanup(p.stop) shot := func(name string) { t.Helper(); connShotOn(t, p, tokenDay, name, width) } p.run(chromedp.Navigate(inst.URL+"/conversation/settings/connections/add"), browsertest.Wait(`!!document.querySelector('[data-connections]') && !!window.EquipoSeal && !!window.nacl`)) p.check(`(()=>{window.__equipoStayed=true;return true})()`, "mark") p.check(recordPosts, "record posts") // The chooser: Paste a token you already have, the quiet link // beside Claude's sign-in by a link (TestBrowserConnectionsSignIn). p.check(`(()=>{const alt=document.querySelector('[equipo-conn-chooser] [data-paste-instead]');return !!alt && alt.textContent==='Paste a token you already have' && alt.checkVisibility()})()`, "the chooser does not offer Paste a token you already have") shot("token-chooser") p.check(`(()=>{document.querySelector('[equipo-conn-chooser] [data-paste-instead]').click();return !!document.querySelector('[data-connecting][data-provider="claude"]')})()`, "no card the instant Paste a token is chosen") p.run(waitLong(`!!document.querySelector('[data-token-form]')`)) if cmd := runner.expect(t, wire.FrameConnect).(*wire.ConnectCommand); cmd.Kind != wire.KindToken || cmd.Provider != "claude" { t.Fatalf("connect frame %+v", cmd) } // The card: the Codex card's three steps. p.check(`(()=>{const card=document.querySelector('[data-connecting][data-kind="token"]');const steps=card.querySelectorAll('[data-token-steps] > li');const field=card.querySelector('[data-token-field]');return card.querySelector('h3').textContent==='Connect Claude' && steps.length===3 && steps[0].textContent.includes('On any computer with Claude Code, run') && steps[0].querySelector('[data-command]').textContent==='claude setup-token' && steps[0].querySelector('[data-copy]').dataset.copy==='claude setup-token' && steps[1].textContent.includes('Approve in the browser.') && steps[2].textContent.includes('Paste the token here.') && field.type==='password' && !field.name && !!card.querySelector('[data-token-connect]') && field.form.querySelector('[data-token-trust]')?.textContent===`+jsonString(sealedWords)+` && field.form.querySelector('[data-token-trust]').checkVisibility() && !card.textContent.includes('never sees') && !!card.dataset.sealKey && card.querySelector('[data-token-steps]').checkVisibility() && document.documentElement.scrollWidth<=innerWidth+1})()`, "the token card is not the three steps with a password field") shot("token-card") // A bad format is refused here, quietly, with no request. p.check(`(()=>{window.__posts=[];const f=document.querySelector('[data-token-field]');f.value='sk-proj-not-claude';f.form.requestSubmit();const note=document.querySelector('[data-token-note]');return f.value==='' && !note.hidden && note.textContent.startsWith('That is not a Claude token.') && window.__posts.length===0})()`, "a bad token was not refused before any request") shot("token-bad") // A good one: sealed here, posted, the field cleared at once, // then the living waiting line. p.check(`(()=>{const f=document.querySelector('[data-token-field]');f.value=`+jsonString(canaryToken)+`;f.form.requestSubmit();return f.value===''})()`, "the field was not cleared at once") p.run(waitLong(`window.__posts.length===1 && !!document.querySelector('[data-connecting][data-kind="token"] [equipo-conn-waiting]') && document.querySelector('[data-connecting][data-kind="token"] [equipo-conn-waiting]').checkVisibility()`)) p.check(`(()=>{const post=window.__posts[0];const b=JSON.parse(post.body);return post.url.endsWith('/secret') && !post.body.includes('CANARY') && !post.body.includes('sk-ant') && typeof b.box==='string' && b.attempt===1 && b.provider==='claude' && b.endpoint==='https://api.anthropic.com:443' && !document.documentElement.outerHTML.includes('CANARY')})()`, "the request or the page holds the token") shot("token-waiting") cmd := runner.expect(t, wire.FrameSecret).(*wire.SecretCommand) opened := runner.open(t, cmd.Sealed) s := cmd.Sealed if opened.Secret != canaryToken || opened.RunnerID != s.RunnerID || opened.ConnectionID != s.ConnectionID || opened.ConnectionID != cmd.Connection || opened.Provider != "claude" || opened.Endpoint != wire.EndpointAnthropic || opened.Attempt != 1 || !opened.ExpiresAt.Equal(s.ExpiresAt) { t.Fatal("the opened payload does not match its clear binding") } if left := time.Until(opened.ExpiresAt); left < 8*time.Minute || left > wire.SealedTTL { t.Fatalf("the box expires in %v", left) } // The server's own card waits too (the stream refreshed it). p.run(waitLong(`!document.querySelector('[data-token-form]') && !!document.querySelector('[data-connecting][data-kind="token"] [equipo-conn-waiting]')`)) // The runner's healthy report: the flourish, then the row with // the account and the token's expiry. // Neither the token nor the CLI says when it expires: the date // is an estimate, and the row says about. expires := time.Now().UTC().Add(wire.TokenLifetime) runner.send(t, wire.FrameConnection, wire.ConnectionReport{Connection: cmd.Connection, Person: thintest.Owner, LocalID: "claude-1", Provider: "claude", State: wire.ConnHealthy, Label: second}) runner.hello(t, wire.HeldConnection{LocalID: "claude-1", Person: thintest.Owner, Provider: "claude", Kind: wire.KindToken, Label: second, State: wire.ConnHealthy, ExpiresAt: &expires, ExpiresEstimated: true}) want := "Expires about " + expires.Format("2 Jan 2006") p.check(stayed, "the page reloaded or navigated before the token connected") p.run(waitLong(`location.pathname==='/conversation/settings/connections' && [...document.querySelectorAll('[equipo-conn-row][data-provider="claude"]')].some(e=>!e.hidden && e.textContent.includes('` + second + `') && e.querySelector('[data-token-expires]')?.textContent==='` + want + `') && !document.querySelector('[data-token-renew]')`)) shot("token-connected") p.check(`(()=>{window.__equipoStayed=true;return true})()`, "mark") // Within six weeks of the estimated expiry: a quiet line asks // to sign in again (the sign-in by a link first). soon := time.Now().UTC().Add(40 * 24 * time.Hour) runner.hello(t, wire.HeldConnection{LocalID: "claude-1", Person: thintest.Owner, Provider: "claude", Kind: wire.KindToken, Label: second, State: wire.ConnHealthy, ExpiresAt: &soon, ExpiresEstimated: true}) p.run(waitLong(`!!document.querySelector('[data-token-renew]') && document.querySelector('[data-token-renew]').textContent.includes('It expires soon.') && document.querySelector('[data-token-renew] [data-renew]').textContent==='Sign in again' && !document.querySelector('[data-token-renew] input[name="kind"]')`)) shot("token-renew") // Rejected: sign in again, said for a token. runner.hello(t, wire.HeldConnection{LocalID: "claude-1", Person: thintest.Owner, Provider: "claude", Kind: wire.KindToken, Label: second, State: wire.ConnSignInAgain, ExpiresAt: &soon, ExpiresEstimated: true}) p.run(waitLong(`(()=>{const row=document.querySelector('[equipo-conn-row][data-provider="claude"][data-state="sign_in_again"]');return !!row && row.querySelector('[data-connection-state]').textContent==='This token was rejected.' && row.querySelector('[data-recover]').textContent==='Sign in again'})()`)) shot("token-rejected") p.check(stayed, "the page reloaded or navigated") // Sign in again is the sign-in by a link, on the Add page, its // card offering the paste second. p.check(`(()=>{document.querySelector('[equipo-conn-row][data-state="sign_in_again"] [data-recover]').click();return true})()`, "Sign in again") again := runner.expect(t, wire.FrameConnect).(*wire.ConnectCommand) if again.Kind != wire.KindSubscription || again.Provider != "claude" { t.Fatalf("Sign in again started %+v", again) } runner.send(t, wire.FrameConnection, wire.ConnectionReport{Connection: again.Connection, Person: thintest.Owner, Provider: "claude", State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptAuthorize, URL: signInLinks[0], Attempt: 1}}) p.run(waitLong(`location.pathname==='/conversation/settings/connections/add' && !!document.querySelector('[data-code-steps] [data-open-anthropic]') && !!document.querySelector('[data-connecting] [data-paste-instead]') && !document.querySelector('[data-token-form]')`)) }) } } // Paul, 2026-11-09: "a 'Copy URL' in addition to open, in case I want to // open it in a different browser." The Codex card and the Claude sign-in // card each have Copy link beside their Open button; it copies the link // and says Copied. func TestBrowserConnectionsCopyLink(t *testing.T) { for _, width := range []int64{1280, 390} { t.Run(strconv.FormatInt(width, 10), func(t *testing.T) { inst := thintest.StartInstance(t) runner := dialFake(t, inst) client := thintest.NewClient(inst.URL, inst.DeviceToken(t)) c := inst.Cookie() p := openPage(t, inst.URL, c.Name, c.Value, width, 900, width > 600) t.Cleanup(p.stop) p.run(chromedp.Navigate(inst.URL+"/conversation/settings/connections/add"), browsertest.Wait(`!!document.querySelector('[data-connections]')`)) p.check(`(()=>{window.__equipoStayed=true;window.__copied=[];navigator.clipboard.writeText=t=>{window.__copied.push(t);return Promise.resolve()};return true})()`, "clipboard") const device = "https://auth.openai.com/codex/device" codex, err := client.Connect(t.Context(), wire.Connect{Provider: "codex"}) if err != nil { t.Fatal(err) } runner.expect(t, wire.FrameConnect) runner.send(t, wire.FrameConnection, wire.ConnectionReport{Connection: codex.ID, Person: thintest.Owner, Provider: "codex", State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptDeviceCode, URL: device, Code: "FAKE-1234"}}) p.run(waitLong(`!!document.querySelector('[data-device-code] [data-copy-link]')`)) besides := `(()=>{const open=document.querySelector('%[1]s');const copy=open.parentElement.querySelector('[data-copy-link]');const a=open.getBoundingClientRect(),b=copy.getBoundingClientRect();return copy.textContent==='Copy link' && copy.getAttribute('rst-btn')==='' && copy.dataset.copy===open.getAttribute('href') && Math.abs(a.top-b.top)<4 && b.left>a.right && !copy.closest('li').textContent.includes(open.getAttribute('href'))})()` p.check(strings.ReplaceAll(besides, "%[1]s", "[data-open-provider]"), "Copy link is not beside Open OpenAI") p.check(`(()=>{document.querySelector('[data-device-code] [data-copy-link]').click();return true})()`, "Copy link") p.run(waitLong(`document.querySelector('[data-device-code] [data-copy-link]').textContent==='Copied' && window.__copied[0]==='` + device + `'`)) connShotOn(t, p, tokenDay, "codex-copy-link", width) p.run(waitLong(`document.querySelector('[data-device-code] [data-copy-link]').textContent==='Copy link'`)) if _, err := client.CancelConnection(t.Context(), codex.ID); err != nil { t.Fatal(err) } runner.expect(t, wire.FrameCancelConnect) // Claude: the sign-in card, its link from the runner's own // setup-token. Open Anthropic is wider than Open OpenAI: on a // phone Copy link may sit under it. claude, err := client.Connect(t.Context(), wire.Connect{Provider: "claude"}) if err != nil { t.Fatal(err) } runner.expect(t, wire.FrameConnect) runner.send(t, wire.FrameConnection, wire.ConnectionReport{Connection: claude.ID, Person: thintest.Owner, Provider: "claude", State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptAuthorize, URL: signInLinks[0], Attempt: 1}}) p.run(waitLong(`!!document.querySelector('[data-code-steps] [data-copy-link]')`)) p.check(`(()=>{const open=document.querySelector('[data-open-anthropic]');const copy=open.parentElement.querySelector('[data-copy-link]');const a=open.getBoundingClientRect(),b=copy.getBoundingClientRect();return copy.textContent==='Copy link' && copy.dataset.copy===open.getAttribute('href') && (Math.abs(a.top-b.top)<4 && b.left>a.right || b.top>=a.bottom && Math.abs(a.left-b.left)<2)})()`, "Copy link is not beside Open Anthropic") p.check(`(()=>{document.querySelector('[data-code-steps] [data-copy-link]').click();return true})()`, "Copy link") p.run(waitLong(`document.querySelector('[data-code-steps] [data-copy-link]').textContent==='Copied' && window.__copied[1]===` + jsonString(signInLinks[0]))) connShotOn(t, p, tokenDay, "claude-copy-link", width) p.check(stayed, "the page reloaded or navigated") }) } }