| 1 | //go:build browser |
| 2 | |
| 3 | package headless |
| 4 | |
| 5 | import ( |
| 6 | "strconv" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/browsertest" |
| 11 | "amadan.net/oficina/equipo/internal/thintest" |
| 12 | "amadan.net/oficina/equipo/internal/wire" |
| 13 | "github.com/chromedp/chromedp" |
| 14 | ) |
| 15 | |
| 16 | // signInDay is where the sign-in card's screenshots go. |
| 17 | const signInDay = "2026-11-10" |
| 18 | |
| 19 | // canarySignInCode is an obviously fake sign-in code. |
| 20 | const canarySignInCode = "CANARY-sign-in-code-not-real#CANARYSTATE" |
| 21 | |
| 22 | // signInLinks are the authorize links the fake runner's CLI printed. |
| 23 | var signInLinks = []string{ |
| 24 | "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", |
| 25 | "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", |
| 26 | } |
| 27 | |
| 28 | // Paul, 2026-11-10: "Can you not run this on the server and get a link |
| 29 | // to give to the browser?" Claude in the chooser is the sign-in by a |
| 30 | // link, with Paste a token you already have beside it. The card arrives |
| 31 | // at once, then the runner's link: Open Anthropic with Copy link beside |
| 32 | // it (under it when a phone is too narrow), and |
| 33 | // Paste the code Anthropic shows you with a field and Connect. A code is |
| 34 | // checked here, sealed here to the runner's key for the code endpoint |
| 35 | // and the card's attempt, the field cleared at once; the card waits. A |
| 36 | // wrong code's card says so with the next attempt; the right one |
| 37 | // connects, with the flourish, and the row has the token's expiry. |
| 38 | func TestBrowserConnectionsSignIn(t *testing.T) { |
| 39 | for _, width := range []int64{1280, 390} { |
| 40 | t.Run(strconv.FormatInt(width, 10), func(t *testing.T) { |
| 41 | inst := thintest.StartInstance(t) |
| 42 | runner := dialFake(t, inst) |
| 43 | c := inst.Cookie() |
| 44 | p := openPage(t, inst.URL, c.Name, c.Value, width, 900, width > 600) |
| 45 | t.Cleanup(p.stop) |
| 46 | shot := func(name string) { t.Helper(); connShotOn(t, p, signInDay, name, width) } |
| 47 | p.run(chromedp.Navigate(inst.URL+"/conversation/settings/connections/add"), browsertest.Wait(`!!document.querySelector('[data-connections]') && !!window.EquipoSeal && !!window.nacl`)) |
| 48 | p.check(`(()=>{window.__equipoStayed=true;window.__copied=[];navigator.clipboard.writeText=t=>{window.__copied.push(t);return Promise.resolve()};return true})()`, "mark") |
| 49 | p.check(recordPosts, "record posts") |
| 50 | |
| 51 | // The chooser: Claude signs in at Anthropic; the token is the |
| 52 | // quiet second way. |
| 53 | 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") |
| 54 | p.run(waitLong(`document.getAnimations().every(a=>a.playState!=='running'||a.effect&&a.effect.getTiming().iterations===Infinity)`)) |
| 55 | shot("signin-chooser") |
| 56 | 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") |
| 57 | cmd := runner.expect(t, wire.FrameConnect).(*wire.ConnectCommand) |
| 58 | if cmd.Provider != "claude" || cmd.Kind != wire.KindSubscription || cmd.SameMachine { |
| 59 | t.Fatalf("connect frame %+v", cmd) |
| 60 | } |
| 61 | // The server's card: still starting, until the runner's link. |
| 62 | p.run(waitLong(`!!document.querySelector('[data-connecting][data-connection="` + cmd.Connection + `"] [data-loading]')`)) |
| 63 | 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}}) |
| 64 | p.run(waitLong(`!!document.querySelector('[data-code-steps]')`)) |
| 65 | 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") |
| 66 | p.run(waitLong(`document.getAnimations().every(a=>a.playState!=='running'||a.effect&&a.effect.getTiming().iterations===Infinity)`)) |
| 67 | shot("signin-card") |
| 68 | p.check(`(()=>{document.querySelector('[data-code-steps] [data-copy-link]').click();return true})()`, "Copy link") |
| 69 | p.run(waitLong(`document.querySelector('[data-code-steps] [data-copy-link]').textContent==='Copied' && window.__copied[0]===` + jsonString(signInLinks[0]))) |
| 70 | |
| 71 | // Not a code: said here, no request; a token pasted as the code |
| 72 | // is not one either. |
| 73 | for _, bad := range []string{"abc", "sk-ant-oat01-a-token-in-the-code-field"} { |
| 74 | 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) |
| 75 | } |
| 76 | shot("signin-bad") |
| 77 | |
| 78 | // A code: sealed here, posted, the field cleared at once, the |
| 79 | // card waiting. |
| 80 | 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") |
| 81 | 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'))`)) |
| 82 | 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") |
| 83 | shot("signin-waiting") |
| 84 | secret := runner.expect(t, wire.FrameSecret).(*wire.SecretCommand) |
| 85 | opened := runner.open(t, secret.Sealed) |
| 86 | if opened.Secret != canarySignInCode || opened.Endpoint != wire.EndpointClaudeCode || opened.Attempt != 1 || opened.ConnectionID != cmd.Connection || opened.Provider != "claude" || !opened.ExpiresAt.Equal(secret.Sealed.ExpiresAt) { |
| 87 | t.Fatal("the opened code does not match its clear binding") |
| 88 | } |
| 89 | if left := time.Until(opened.ExpiresAt); left < 8*time.Minute || left > wire.SealedTTL { |
| 90 | t.Fatalf("the box expires in %v", left) |
| 91 | } |
| 92 | p.run(waitLong(`!document.querySelector('[data-code-form]') && !!document.querySelector('[data-connecting][data-kind="sign_in"] [equipo-conn-waiting]')`)) |
| 93 | |
| 94 | // Wrong: the CLI started again with a new link; the card says so. |
| 95 | 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}}) |
| 96 | 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]) + `})()`)) |
| 97 | shot("signin-wrong") |
| 98 | p.check(`(()=>{window.__posts=[];const f=document.querySelector('[data-code-field]');f.value=`+jsonString(canarySignInCode)+`;f.form.requestSubmit();return f.value===''})()`, "the second code") |
| 99 | p.run(waitLong(`window.__posts.length===1 && JSON.parse(window.__posts[0].body).attempt===2`)) |
| 100 | if second := runner.expect(t, wire.FrameSecret).(*wire.SecretCommand); second.Sealed.Attempt != 2 || runner.open(t, second.Sealed).Attempt != 2 { |
| 101 | t.Fatal("the second code's attempt") |
| 102 | } |
| 103 | |
| 104 | // Connected: the flourish, then the row, a token connection. |
| 105 | expires := time.Now().UTC().Add(wire.TokenLifetime) |
| 106 | runner.send(t, wire.FrameConnection, wire.ConnectionReport{Connection: cmd.Connection, Person: thintest.Owner, LocalID: "claude-1", Provider: "claude", State: wire.ConnHealthy, Label: second}) |
| 107 | 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}) |
| 108 | p.check(stayed, "the page reloaded or navigated before Claude connected") |
| 109 | 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") + `')`)) |
| 110 | p.check(`!document.documentElement.outerHTML.includes('CANARY')`, "the code is on the page") |
| 111 | shot("signin-connected") |
| 112 | }) |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | // Switching ways: the sign-in card's Paste a token you already have |
| 117 | // gives way to the token card, and the token card's Or sign in at |
| 118 | // Anthropic instead back to the sign-in; each switch cancels the open |
| 119 | // attempt on the runner, unsaid. |
| 120 | func TestBrowserConnectionsSignInSwitch(t *testing.T) { |
| 121 | inst := thintest.StartInstance(t) |
| 122 | runner := dialFake(t, inst) |
| 123 | c := inst.Cookie() |
| 124 | p := openPage(t, inst.URL, c.Name, c.Value, 390, 900, false) |
| 125 | t.Cleanup(p.stop) |
| 126 | p.run(chromedp.Navigate(inst.URL+"/conversation/settings/connections/add"), browsertest.Wait(`!!document.querySelector('[data-connections]')`)) |
| 127 | p.check(`(()=>{window.__equipoStayed=true;document.querySelector('[data-add="claude"]').click();return true})()`, "Claude") |
| 128 | first := runner.expect(t, wire.FrameConnect).(*wire.ConnectCommand) |
| 129 | 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}}) |
| 130 | p.run(waitLong(`!!document.querySelector('[data-code-steps]')`)) |
| 131 | p.check(`(()=>{document.querySelector('[data-connecting] [data-paste-instead]').click();return true})()`, "Paste a token you already have") |
| 132 | if v := runner.expect(t, wire.FrameCancelConnect).(*wire.CancelConnectCommand); v.Connection != first.Connection { |
| 133 | t.Fatalf("cancel %+v", v) |
| 134 | } |
| 135 | token := runner.expect(t, wire.FrameConnect).(*wire.ConnectCommand) |
| 136 | if token.Kind != wire.KindToken { |
| 137 | t.Fatalf("connect %+v", token) |
| 138 | } |
| 139 | p.run(waitLong(`!!document.querySelector('[data-token-form]') && !document.querySelector('[data-code-steps]') && !document.querySelector('[data-connection-note]')`)) |
| 140 | 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") |
| 141 | runner.expect(t, wire.FrameCancelConnect) |
| 142 | if again := runner.expect(t, wire.FrameConnect).(*wire.ConnectCommand); again.Kind != wire.KindSubscription || again.SameMachine { |
| 143 | t.Fatalf("connect %+v", again) |
| 144 | } |
| 145 | p.run(waitLong(`!!document.querySelector('[data-connecting][data-provider="claude"] [data-loading]') && !document.querySelector('[data-token-form]')`)) |
| 146 | p.check(stayed, "the page reloaded or navigated") |
| 147 | } |
| 148 | |