oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3package headless
4
5import (
6 "context"
7 "crypto/rand"
8 "encoding/base64"
9 "strconv"
10 "strings"
11 "testing"
12 "time"
13
14 "amadan.net/oficina/equipo/internal/browsertest"
15 "amadan.net/oficina/equipo/internal/thintest"
16 "amadan.net/oficina/equipo/internal/wire"
17 "github.com/chromedp/chromedp"
18 "golang.org/x/crypto/nacl/box"
19)
20
21// A Claude connection from a pasted setup token (Paul, 2026-11-09:
22// "really, really easy"), in a browser against a fake runner whose seal
23// key the test made, so the test opens what the page sealed.
24
25// canaryToken is an obviously fake setup token.
26const canaryToken = "sk-ant-oat01-CANARY-not-a-real-token-CANARY"
27
28// sealedWords stand beside the token field: what is trusted, and what
29// the server can and cannot do with the token.
30const 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."
31
32// tokenDay is where this feature's screenshots go.
33const tokenDay = "2026-11-10"
34
35type frameIn struct {
36 frame wire.Frame
37 body any
38}
39
40// fakeRunner is a runner the test speaks for: its hello carries the
41// seal key, and every frame it receives arrives on frames.
42type fakeRunner struct {
43 *thintest.FakeRunner
44 frames chan frameIn
45 public *[32]byte
46 private *[32]byte
47 generation int64
48 n int
49}
50
51func dialFake(t *testing.T, inst *thintest.Instance) *fakeRunner {
52 t.Helper()
53 return dialFakeAt(t, inst, 0)
54}
55
56// dialFakeAt is dialFake for a runner that speaks protocol (0: the
57// hello's default).
58func dialFakeAt(t *testing.T, inst *thintest.Instance, protocol int) *fakeRunner {
59 t.Helper()
60 public, private, err := box.GenerateKey(rand.Reader)
61 if err != nil {
62 t.Fatal(err)
63 }
64 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[:])})
65 if err != nil {
66 t.Fatal(err)
67 }
68 t.Cleanup(fr.Close)
69 r := &fakeRunner{FakeRunner: fr, frames: make(chan frameIn, 64), public: public, private: private, generation: fr.Welcome.Generation}
70 // One reader for the life of the connection: a read with a deadline
71 // would close the socket when it passes.
72 go func() {
73 defer close(r.frames)
74 for {
75 _, raw, err := fr.Conn.Read(context.Background())
76 if err != nil {
77 return
78 }
79 f, body, err := wire.ParseFrame(raw)
80 if err != nil {
81 return
82 }
83 r.frames <- frameIn{f, body}
84 }
85 }()
86 return r
87}
88
89// expect waits for a frame of kind and acks it.
90func (r *fakeRunner) expect(t *testing.T, kind string) any {
91 t.Helper()
92 deadline := time.After(15 * time.Second)
93 for {
94 select {
95 case in, ok := <-r.frames:
96 if !ok {
97 t.Fatalf("the runner's connection closed waiting for %s", kind)
98 }
99 if in.frame.Type != kind {
100 continue
101 }
102 r.send(t, wire.FrameAck, wire.Ack{ID: in.frame.ID})
103 return in.body
104 case <-deadline:
105 t.Fatalf("no %s frame", kind)
106 }
107 }
108}
109
110func (r *fakeRunner) send(t *testing.T, kind string, body any) {
111 t.Helper()
112 r.n++
113 if err := r.Send(t.Context(), "f"+strconv.Itoa(r.n), kind, body); err != nil {
114 t.Fatal(err)
115 }
116}
117
118// hello says the runner holds conns, as its heartbeat does.
119func (r *fakeRunner) hello(t *testing.T, conns ...wire.HeldConnection) {
120 t.Helper()
121 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[:])})
122}
123
124// open opens a box sealed to this runner (libsodium crypto_box_seal).
125func (r *fakeRunner) open(t *testing.T, s wire.Sealed) wire.SealedPayload {
126 t.Helper()
127 raw, err := base64.StdEncoding.DecodeString(s.Box)
128 if err != nil {
129 t.Fatal(err)
130 }
131 msg, ok := box.OpenAnonymous(nil, raw, r.public, r.private)
132 if !ok {
133 t.Fatal("the page's box does not open with box.OpenAnonymous")
134 }
135 var p wire.SealedPayload
136 if err := wire.Strict(msg, &p); err != nil {
137 t.Fatalf("the page's payload: %v", err)
138 }
139 return p
140}
141
142// recordPosts keeps every request body the page's scripts send.
143const 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})()`
144
145func TestBrowserConnectionsToken(t *testing.T) {
146 for _, width := range []int64{1280, 390} {
147 t.Run(strconv.FormatInt(width, 10), func(t *testing.T) {
148 inst := thintest.StartInstance(t)
149 runner := dialFake(t, inst)
150 c := inst.Cookie()
151 p := openPage(t, inst.URL, c.Name, c.Value, width, 900, width > 600)
152 t.Cleanup(p.stop)
153 shot := func(name string) { t.Helper(); connShotOn(t, p, tokenDay, name, width) }
154 p.run(chromedp.Navigate(inst.URL+"/conversation/settings/connections/add"), browsertest.Wait(`!!document.querySelector('[data-connections]') && !!window.EquipoSeal && !!window.nacl`))
155 p.check(`(()=>{window.__equipoStayed=true;return true})()`, "mark")
156 p.check(recordPosts, "record posts")
157
158 // The chooser: Paste a token you already have, the quiet link
159 // beside Claude's sign-in by a link (TestBrowserConnectionsSignIn).
160 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")
161 shot("token-chooser")
162 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")
163 p.run(waitLong(`!!document.querySelector('[data-token-form]')`))
164 if cmd := runner.expect(t, wire.FrameConnect).(*wire.ConnectCommand); cmd.Kind != wire.KindToken || cmd.Provider != "claude" {
165 t.Fatalf("connect frame %+v", cmd)
166 }
167 // The card: the Codex card's three steps.
168 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")
169 shot("token-card")
170
171 // A bad format is refused here, quietly, with no request.
172 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")
173 shot("token-bad")
174
175 // A good one: sealed here, posted, the field cleared at once,
176 // then the living waiting line.
177 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")
178 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()`))
179 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")
180 shot("token-waiting")
181 cmd := runner.expect(t, wire.FrameSecret).(*wire.SecretCommand)
182 opened := runner.open(t, cmd.Sealed)
183 s := cmd.Sealed
184 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) {
185 t.Fatal("the opened payload does not match its clear binding")
186 }
187 if left := time.Until(opened.ExpiresAt); left < 8*time.Minute || left > wire.SealedTTL {
188 t.Fatalf("the box expires in %v", left)
189 }
190 // The server's own card waits too (the stream refreshed it).
191 p.run(waitLong(`!document.querySelector('[data-token-form]') && !!document.querySelector('[data-connecting][data-kind="token"] [equipo-conn-waiting]')`))
192
193 // The runner's healthy report: the flourish, then the row with
194 // the account and the token's expiry.
195 // Neither the token nor the CLI says when it expires: the date
196 // is an estimate, and the row says about.
197 expires := time.Now().UTC().Add(wire.TokenLifetime)
198 runner.send(t, wire.FrameConnection, wire.ConnectionReport{Connection: cmd.Connection, Person: thintest.Owner, LocalID: "claude-1", Provider: "claude", State: wire.ConnHealthy, Label: second})
199 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})
200 want := "Expires about " + expires.Format("2 Jan 2006")
201 p.check(stayed, "the page reloaded or navigated before the token connected")
202 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]')`))
203 shot("token-connected")
204 p.check(`(()=>{window.__equipoStayed=true;return true})()`, "mark")
205
206 // Within six weeks of the estimated expiry: a quiet line asks
207 // to sign in again (the sign-in by a link first).
208 soon := time.Now().UTC().Add(40 * 24 * time.Hour)
209 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})
210 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"]')`))
211 shot("token-renew")
212
213 // Rejected: sign in again, said for a token.
214 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})
215 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'})()`))
216 shot("token-rejected")
217 p.check(stayed, "the page reloaded or navigated")
218 // Sign in again is the sign-in by a link, on the Add page, its
219 // card offering the paste second.
220 p.check(`(()=>{document.querySelector('[equipo-conn-row][data-state="sign_in_again"] [data-recover]').click();return true})()`, "Sign in again")
221 again := runner.expect(t, wire.FrameConnect).(*wire.ConnectCommand)
222 if again.Kind != wire.KindSubscription || again.Provider != "claude" {
223 t.Fatalf("Sign in again started %+v", again)
224 }
225 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}})
226 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]')`))
227 })
228 }
229}
230
231// Paul, 2026-11-09: "a 'Copy URL' in addition to open, in case I want to
232// open it in a different browser." The Codex card and the Claude sign-in
233// card each have Copy link beside their Open button; it copies the link
234// and says Copied.
235func TestBrowserConnectionsCopyLink(t *testing.T) {
236 for _, width := range []int64{1280, 390} {
237 t.Run(strconv.FormatInt(width, 10), func(t *testing.T) {
238 inst := thintest.StartInstance(t)
239 runner := dialFake(t, inst)
240 client := thintest.NewClient(inst.URL, inst.DeviceToken(t))
241 c := inst.Cookie()
242 p := openPage(t, inst.URL, c.Name, c.Value, width, 900, width > 600)
243 t.Cleanup(p.stop)
244 p.run(chromedp.Navigate(inst.URL+"/conversation/settings/connections/add"), browsertest.Wait(`!!document.querySelector('[data-connections]')`))
245 p.check(`(()=>{window.__equipoStayed=true;window.__copied=[];navigator.clipboard.writeText=t=>{window.__copied.push(t);return Promise.resolve()};return true})()`, "clipboard")
246 const device = "https://auth.openai.com/codex/device"
247 codex, err := client.Connect(t.Context(), wire.Connect{Provider: "codex"})
248 if err != nil {
249 t.Fatal(err)
250 }
251 runner.expect(t, wire.FrameConnect)
252 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"}})
253 p.run(waitLong(`!!document.querySelector('[data-device-code] [data-copy-link]')`))
254 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'))})()`
255 p.check(strings.ReplaceAll(besides, "%[1]s", "[data-open-provider]"), "Copy link is not beside Open OpenAI")
256 p.check(`(()=>{document.querySelector('[data-device-code] [data-copy-link]').click();return true})()`, "Copy link")
257 p.run(waitLong(`document.querySelector('[data-device-code] [data-copy-link]').textContent==='Copied' && window.__copied[0]==='` + device + `'`))
258 connShotOn(t, p, tokenDay, "codex-copy-link", width)
259 p.run(waitLong(`document.querySelector('[data-device-code] [data-copy-link]').textContent==='Copy link'`))
260 if _, err := client.CancelConnection(t.Context(), codex.ID); err != nil {
261 t.Fatal(err)
262 }
263 runner.expect(t, wire.FrameCancelConnect)
264
265 // Claude: the sign-in card, its link from the runner's own
266 // setup-token. Open Anthropic is wider than Open OpenAI: on a
267 // phone Copy link may sit under it.
268 claude, err := client.Connect(t.Context(), wire.Connect{Provider: "claude"})
269 if err != nil {
270 t.Fatal(err)
271 }
272 runner.expect(t, wire.FrameConnect)
273 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}})
274 p.run(waitLong(`!!document.querySelector('[data-code-steps] [data-copy-link]')`))
275 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")
276 p.check(`(()=>{document.querySelector('[data-code-steps] [data-copy-link]').click();return true})()`, "Copy link")
277 p.run(waitLong(`document.querySelector('[data-code-steps] [data-copy-link]').textContent==='Copied' && window.__copied[1]===` + jsonString(signInLinks[0])))
278 connShotOn(t, p, tokenDay, "claude-copy-link", width)
279 p.check(stayed, "the page reloaded or navigated")
280 })
281 }
282}
283