//go:build browser package headless import ( "strconv" "testing" "time" "amadan.net/oficina/equipo/internal/browsertest" "amadan.net/oficina/equipo/internal/thintest" "amadan.net/oficina/equipo/internal/wire" "github.com/chromedp/chromedp" ) // signInDay is where the sign-in card's screenshots go. const signInDay = "2026-11-10" // canarySignInCode is an obviously fake sign-in code. const canarySignInCode = "CANARY-sign-in-code-not-real#CANARYSTATE" // signInLinks are the authorize links the fake runner's CLI printed. var signInLinks = []string{ "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=first", "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=second", } // Paul, 2026-11-10: "Can you not run this on the server and get a link // to give to the browser?" Claude in the chooser is the sign-in by a // link, with Paste a token you already have beside it. The card arrives // at once, then the runner's link: Open Anthropic with Copy link beside // it (under it when a phone is too narrow), and // Paste the code Anthropic shows you with a field and Connect. A code is // checked here, sealed here to the runner's key for the code endpoint // and the card's attempt, the field cleared at once; the card waits. A // wrong code's card says so with the next attempt; the right one // connects, with the flourish, and the row has the token's expiry. func TestBrowserConnectionsSignIn(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, signInDay, 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;window.__copied=[];navigator.clipboard.writeText=t=>{window.__copied.push(t);return Promise.resolve()};return true})()`, "mark") p.check(recordPosts, "record posts") // The chooser: Claude signs in at Anthropic; the token is the // quiet second way. p.check(`(()=>{const how=document.querySelector('[data-add="claude"] [data-sign-in-how]');const alt=document.querySelector('[equipo-conn-chooser] [data-paste-instead]');return !!how && how.textContent==='Sign in at Anthropic' && how.checkVisibility() && !!alt && alt.textContent==='Paste a token you already have' && alt.checkVisibility() && !document.querySelector('[data-paste-token],[data-sign-in-instead],[data-same-machine],[data-finish-on]')})()`, "the chooser is not the sign-in by a link with Paste a token beside it") p.run(waitLong(`document.getAnimations().every(a=>a.playState!=='running'||a.effect&&a.effect.getTiming().iterations===Infinity)`)) shot("signin-chooser") p.check(`(()=>{document.querySelector('[data-add="claude"]').click();return !!document.querySelector('[data-connecting][data-provider="claude"] [data-loading]')})()`, "no card the instant Claude is chosen") cmd := runner.expect(t, wire.FrameConnect).(*wire.ConnectCommand) if cmd.Provider != "claude" || cmd.Kind != wire.KindSubscription || cmd.SameMachine { t.Fatalf("connect frame %+v", cmd) } // The server's card: still starting, until the runner's link. p.run(waitLong(`!!document.querySelector('[data-connecting][data-connection="` + cmd.Connection + `"] [data-loading]')`)) runner.send(t, wire.FrameConnection, wire.ConnectionReport{Connection: cmd.Connection, 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]')`)) p.check(`(()=>{const card=document.querySelector('[data-connecting][data-kind="sign_in"]');const steps=card.querySelectorAll('[data-code-steps] > li');const open=card.querySelector('[data-open-anthropic]');const copy=open.parentElement.querySelector('[data-copy-link]');const field=card.querySelector('[data-code-field]');const a=open.getBoundingClientRect(),b=copy.getBoundingClientRect();return card.querySelector('h3').textContent==='Connect Claude' && steps.length===2 && open.textContent.trim()==='Open Anthropic' && open.getAttribute('rst-btn')==='primary' && open.getAttribute('href')===`+jsonString(signInLinks[0])+` && open.target==='_blank' && 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) && steps[1].querySelector('label').textContent==='Paste the code Anthropic shows you' && field.type==='password' && !field.name && card.querySelector('[data-code-connect]').textContent==='Connect' && field.form.querySelector('[data-token-trust]').textContent===`+jsonString(sealedWords)+` && !card.querySelector('[data-code-wrong]') && card.dataset.attempt==='1' && card.dataset.endpoint==='`+wire.EndpointClaudeCode+`' && !!card.dataset.sealKey && card.querySelector('[equipo-conn-card-foot] [data-paste-instead]').textContent==='Paste a token you already have' && !card.textContent.includes('claude.com') && document.documentElement.scrollWidth<=innerWidth+1})()`, "the sign-in card is not Open Anthropic with Copy link, then the code field") p.run(waitLong(`document.getAnimations().every(a=>a.playState!=='running'||a.effect&&a.effect.getTiming().iterations===Infinity)`)) shot("signin-card") 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[0]===` + jsonString(signInLinks[0]))) // Not a code: said here, no request; a token pasted as the code // is not one either. for _, bad := range []string{"abc", "sk-ant-oat01-a-token-in-the-code-field"} { p.check(`(()=>{window.__posts=[];const f=document.querySelector('[data-code-field]');f.value=`+jsonString(bad)+`;f.form.requestSubmit();const note=document.querySelector('[data-code-steps] [data-token-note]');return f.value==='' && !note.hidden && note.textContent==="That is not the code. Copy the whole code from Anthropic's page." && window.__posts.length===0})()`, "a bad code was not refused before any request: "+bad) } shot("signin-bad") // A code: sealed here, posted, the field cleared at once, the // card waiting. p.check(`(()=>{window.__posts=[];const f=document.querySelector('[data-code-field]');f.value=`+jsonString(canarySignInCode)+`;f.form.requestSubmit();return f.value===''})()`, "the field was not cleared at once") p.run(waitLong(`window.__posts.length===1 && [...document.querySelectorAll('[data-connecting][data-kind="sign_in"] [equipo-conn-waiting]')].some(w=>w.checkVisibility() && w.textContent.includes('Your runner is finishing the sign-in'))`)) p.check(`(()=>{const post=window.__posts[0];const b=JSON.parse(post.body);return post.url.endsWith('/secret') && !post.body.includes('CANARY') && typeof b.box==='string' && b.attempt===1 && b.provider==='claude' && b.endpoint==='`+wire.EndpointClaudeCode+`' && !document.documentElement.outerHTML.includes('CANARY')})()`, "the request or the page holds the code") shot("signin-waiting") secret := runner.expect(t, wire.FrameSecret).(*wire.SecretCommand) opened := runner.open(t, secret.Sealed) if opened.Secret != canarySignInCode || opened.Endpoint != wire.EndpointClaudeCode || opened.Attempt != 1 || opened.ConnectionID != cmd.Connection || opened.Provider != "claude" || !opened.ExpiresAt.Equal(secret.Sealed.ExpiresAt) { t.Fatal("the opened code 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) } p.run(waitLong(`!document.querySelector('[data-code-form]') && !!document.querySelector('[data-connecting][data-kind="sign_in"] [equipo-conn-waiting]')`)) // Wrong: the CLI started again with a new link; the card says so. runner.send(t, wire.FrameConnection, wire.ConnectionReport{Connection: cmd.Connection, Person: thintest.Owner, Provider: "claude", State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptAuthorize, URL: signInLinks[1], Attempt: 2, WrongCode: true}}) p.run(waitLong(`(()=>{const card=document.querySelector('[data-connecting][data-kind="sign_in"]');const w=card&&card.querySelector('[data-code-wrong]');return !!w && w.checkVisibility() && getComputedStyle(w).color!==getComputedStyle(card.querySelector('[data-token-trust]')).color && w.textContent==='That code did not work. Open Anthropic again and paste the new code.' && card.dataset.attempt==='2' && card.querySelector('[data-open-anthropic]').getAttribute('href')===` + jsonString(signInLinks[1]) + `})()`)) shot("signin-wrong") p.check(`(()=>{window.__posts=[];const f=document.querySelector('[data-code-field]');f.value=`+jsonString(canarySignInCode)+`;f.form.requestSubmit();return f.value===''})()`, "the second code") p.run(waitLong(`window.__posts.length===1 && JSON.parse(window.__posts[0].body).attempt===2`)) if second := runner.expect(t, wire.FrameSecret).(*wire.SecretCommand); second.Sealed.Attempt != 2 || runner.open(t, second.Sealed).Attempt != 2 { t.Fatal("the second code's attempt") } // Connected: the flourish, then the row, a token connection. 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}) p.check(stayed, "the page reloaded or navigated before Claude 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==='Expires about ` + expires.Format("2 Jan 2006") + `')`)) p.check(`!document.documentElement.outerHTML.includes('CANARY')`, "the code is on the page") shot("signin-connected") }) } } // Switching ways: the sign-in card's Paste a token you already have // gives way to the token card, and the token card's Or sign in at // Anthropic instead back to the sign-in; each switch cancels the open // attempt on the runner, unsaid. func TestBrowserConnectionsSignInSwitch(t *testing.T) { inst := thintest.StartInstance(t) runner := dialFake(t, inst) c := inst.Cookie() p := openPage(t, inst.URL, c.Name, c.Value, 390, 900, false) 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;document.querySelector('[data-add="claude"]').click();return true})()`, "Claude") first := runner.expect(t, wire.FrameConnect).(*wire.ConnectCommand) runner.send(t, wire.FrameConnection, wire.ConnectionReport{Connection: first.Connection, 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]')`)) p.check(`(()=>{document.querySelector('[data-connecting] [data-paste-instead]').click();return true})()`, "Paste a token you already have") if v := runner.expect(t, wire.FrameCancelConnect).(*wire.CancelConnectCommand); v.Connection != first.Connection { t.Fatalf("cancel %+v", v) } token := runner.expect(t, wire.FrameConnect).(*wire.ConnectCommand) if token.Kind != wire.KindToken { t.Fatalf("connect %+v", token) } p.run(waitLong(`!!document.querySelector('[data-token-form]') && !document.querySelector('[data-code-steps]') && !document.querySelector('[data-connection-note]')`)) p.check(`(()=>{const b=document.querySelector('[data-connecting] [data-sign-in-instead]');return b.textContent==='Or sign in at Anthropic instead' && (b.click(),true)})()`, "Or sign in at Anthropic instead") runner.expect(t, wire.FrameCancelConnect) if again := runner.expect(t, wire.FrameConnect).(*wire.ConnectCommand); again.Kind != wire.KindSubscription || again.SameMachine { t.Fatalf("connect %+v", again) } p.run(waitLong(`!!document.querySelector('[data-connecting][data-provider="claude"] [data-loading]') && !document.querySelector('[data-token-form]')`)) p.check(stayed, "the page reloaded or navigated") }