oficina / equipo Public

Merge the instance and UI half of Claude token connections

Paul Campbell pushed by claude agent, operated by paul@keymail.dev f4e9b99820fded923ea6e8416fe7b0ec70058617 parent b7bf15cparent e3ea4f9
44 files changed, +3,539 −51
  • docs/mockups/built/2026-11-10/conn-claude-copy-link-1280.png binary
  • docs/mockups/built/2026-11-10/conn-claude-copy-link-390.png binary
  • docs/mockups/built/2026-11-10/conn-codex-copy-link-1280.png binary
  • docs/mockups/built/2026-11-10/conn-codex-copy-link-390.png binary
  • docs/mockups/built/2026-11-10/conn-token-bad-1280.png binary
  • docs/mockups/built/2026-11-10/conn-token-bad-390.png binary
  • docs/mockups/built/2026-11-10/conn-token-card-1280.png binary
  • docs/mockups/built/2026-11-10/conn-token-card-390.png binary
  • docs/mockups/built/2026-11-10/conn-token-chooser-1280.png binary
  • docs/mockups/built/2026-11-10/conn-token-chooser-390.png binary
  • docs/mockups/built/2026-11-10/conn-token-connected-1280.png binary
  • docs/mockups/built/2026-11-10/conn-token-connected-390.png binary
  • docs/mockups/built/2026-11-10/conn-token-rejected-1280.png binary
  • docs/mockups/built/2026-11-10/conn-token-rejected-390.png binary
  • docs/mockups/built/2026-11-10/conn-token-renew-1280.png binary
  • docs/mockups/built/2026-11-10/conn-token-renew-390.png binary
  • docs/mockups/built/2026-11-10/conn-token-waiting-1280.png binary
  • docs/mockups/built/2026-11-10/conn-token-waiting-390.png binary
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +17 −0
  • internal/equipo/app.go +1 −0
  • internal/equipo/chat/connections.go +98 −10
  • internal/equipo/chat/http.go +18 −0
  • internal/equipo/chat/runner.go +5 −0
  • internal/equipo/chat/runners.go +9 −2
  • internal/equipo/chat_connections.go +55 −15
  • internal/equipo/connections_view.go +32 −4
  • internal/equipo/copy.go +17 −0
  • internal/equipo/migrations/0056_thin_token_connections.sql +1 −0
  • internal/equipo/migrations/schema.sql +1 −1
  • internal/equipo/static/connections.js +65 −0
  • internal/equipo/static/equipo.css +17 −0
  • internal/equipo/static/seal.js +127 −0
  • internal/equipo/static/vendor/tweetnacl/LICENSE +24 −0
  • internal/equipo/static/vendor/tweetnacl/nacl-fast.js +2,391 −0
  • internal/equipo/templates/chrome.html +1 −1
  • internal/equipo/templates/models.html +23 −8
  • internal/headless/browser_connections_test.go +12 −4
  • internal/headless/browser_token_test.go +263 −0
  • internal/plan3test/person_api_contract_test.go +1 −1
  • internal/thintest/client.go +5 −0
  • internal/thintest/instance.go +24 −1
  • internal/thintest/token_contract_test.go +321 −0
  • internal/wire/wiretest/testdata/api/event-runner.json +1 −1
  • scripts/runner-reference-allowlist.json +10 −3
diff --git a/docs/mockups/built/2026-11-10/conn-claude-copy-link-1280.png b/docs/mockups/built/2026-11-10/conn-claude-copy-link-1280.png
new file mode 100644
index 00000000..d454014a
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-claude-copy-link-1280.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-claude-copy-link-390.png b/docs/mockups/built/2026-11-10/conn-claude-copy-link-390.png
new file mode 100644
index 00000000..1df77d1d
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-claude-copy-link-390.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-codex-copy-link-1280.png b/docs/mockups/built/2026-11-10/conn-codex-copy-link-1280.png
new file mode 100644
index 00000000..7d11279a
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-codex-copy-link-1280.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-codex-copy-link-390.png b/docs/mockups/built/2026-11-10/conn-codex-copy-link-390.png
new file mode 100644
index 00000000..f56610ac
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-codex-copy-link-390.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-token-bad-1280.png b/docs/mockups/built/2026-11-10/conn-token-bad-1280.png
new file mode 100644
index 00000000..c8af8a28
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-token-bad-1280.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-token-bad-390.png b/docs/mockups/built/2026-11-10/conn-token-bad-390.png
new file mode 100644
index 00000000..e78e41da
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-token-bad-390.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-token-card-1280.png b/docs/mockups/built/2026-11-10/conn-token-card-1280.png
new file mode 100644
index 00000000..be0d09df
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-token-card-1280.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-token-card-390.png b/docs/mockups/built/2026-11-10/conn-token-card-390.png
new file mode 100644
index 00000000..d8e9ef8e
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-token-card-390.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-token-chooser-1280.png b/docs/mockups/built/2026-11-10/conn-token-chooser-1280.png
new file mode 100644
index 00000000..6ecc5de1
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-token-chooser-1280.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-token-chooser-390.png b/docs/mockups/built/2026-11-10/conn-token-chooser-390.png
new file mode 100644
index 00000000..853d2f07
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-token-chooser-390.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-token-connected-1280.png b/docs/mockups/built/2026-11-10/conn-token-connected-1280.png
new file mode 100644
index 00000000..04d1674f
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-token-connected-1280.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-token-connected-390.png b/docs/mockups/built/2026-11-10/conn-token-connected-390.png
new file mode 100644
index 00000000..b203f7f3
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-token-connected-390.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-token-rejected-1280.png b/docs/mockups/built/2026-11-10/conn-token-rejected-1280.png
new file mode 100644
index 00000000..e55a73b4
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-token-rejected-1280.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-token-rejected-390.png b/docs/mockups/built/2026-11-10/conn-token-rejected-390.png
new file mode 100644
index 00000000..8dd022c2
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-token-rejected-390.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-token-renew-1280.png b/docs/mockups/built/2026-11-10/conn-token-renew-1280.png
new file mode 100644
index 00000000..79ea0f09
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-token-renew-1280.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-token-renew-390.png b/docs/mockups/built/2026-11-10/conn-token-renew-390.png
new file mode 100644
index 00000000..14790070
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-token-renew-390.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-token-waiting-1280.png b/docs/mockups/built/2026-11-10/conn-token-waiting-1280.png
new file mode 100644
index 00000000..92af3f71
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-token-waiting-1280.png differ
diff --git a/docs/mockups/built/2026-11-10/conn-token-waiting-390.png b/docs/mockups/built/2026-11-10/conn-token-waiting-390.png
new file mode 100644
index 00000000..f74182ac
Binary files /dev/null and b/docs/mockups/built/2026-11-10/conn-token-waiting-390.png differ
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index 43326e42..c5f07e37 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -5311,6 +5311,23 @@ records remain unchanged.
| `chat.connections.loading_claude_1` | Finding your runner… | Connections slice 1 (Connections page, loading line) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| `chat.connections.loading_claude_2` | Warming up a fresh desk for Claude… | Connections slice 1 (Connections page, loading line) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| `chat.connections.loading_claude_3` | Starting Claude's own sign-in… | Connections slice 1 (Connections page, loading line) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.paste_token` | Paste a token | Claude token connections (Connections page, chooser) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.sign_in_instead` | Or sign in on the runner instead | Claude token connections (Connections page, chooser and token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.token_sub` | Your Claude subscription, with a token from Claude Code. | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.token_run` | On any computer with Claude Code, run | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.token_approve` | Approve in the browser. | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.token_paste` | Paste the token here. | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.token_connect` | Connect | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.token_sealed` | It's sealed to your runner; Equipo's server never sees it. | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.token_bad` | That is not a Claude token. Paste the line that starts sk-ant-oat. | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.token_failed` | That did not go through. Paste the token again. | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.token_no_key` | Your runner needs an update before it can take a token. | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.waiting_token` | Your runner is checking the token… | Claude token connections (Connections page, token card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.token_expires` | Token expires %s | Claude token connections (Connections page, connection row) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.token_renew` | It expires soon. | Claude token connections (Connections page, connection row) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.token_new` | Paste a new token | Claude token connections (Connections page, connection row) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.token_rejected` | This token was rejected. Run claude setup-token again. | Claude token connections (Connections page, connection row) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.connections.copy_link` | Copy link | Claude token connections (Connections page, Connect Codex and Claude sign-in cards) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| `work.merge_now` | Merge | Thin v1 slice 4c review round 2 (task card and page) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| `work.step` | %s, attempt %d: %s | Thin v1 slice 4 review and checks (task card, task and Tasks pages, sidebar) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| `work.steps` | Steps | Thin v1 slice 4 review and checks (task card, task and Tasks pages, sidebar) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index aad779ed..ba1f85cc 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -258,6 +258,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
r.Get("/conversation/connections", a.connectionsView)
r.Post("/conversation/connections", a.connectionsStart)
r.Post("/conversation/connections/{id}/cancel", a.connectionsCancel)
+ r.Post("/conversation/connections/{id}/secret", a.connectionsSecret)
r.Post("/conversation/connections/{id}/sign-out", a.connectionsSignOut)
r.Post("/conversation/connections/{id}/forget", a.connectionsForget)
r.Post("/conversation/connections/prefer", a.connectionsPrefer)
diff --git a/internal/equipo/chat/connections.go b/internal/equipo/chat/connections.go
index d15e45fa..36178583 100644
--- a/internal/equipo/chat/connections.go
+++ b/internal/equipo/chat/connections.go
@@ -2,9 +2,11 @@ package chat
import (
"context"
+ "encoding/base64"
"encoding/json"
"errors"
"slices"
+ "strings"
"time"
"amadan.net/oficina/equipo/internal/wire"
@@ -43,6 +45,8 @@ type connectionRecord struct {
Revision int64
CreatedAt time.Time
UpdatedAt time.Time
+ // ExpiresAt is when a pasted token expires, as the runner reports it.
+ ExpiresAt *time.Time
}
func (connectionRecord) TableName() string { return "chat_connections" }
@@ -75,7 +79,7 @@ type usageRecord struct {
func (usageRecord) TableName() string { return "chat_usage" }
func connectionView(r connectionRecord) wire.Connection {
- v := wire.Connection{ID: r.ID, Revision: r.Revision, RunnerID: r.RunnerID, LocalID: r.LocalID, Provider: r.Provider, Kind: r.Kind, Label: r.Label, State: r.State, Reason: r.Reason, Plan: r.Plan, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt}
+ v := wire.Connection{ID: r.ID, Revision: r.Revision, RunnerID: r.RunnerID, LocalID: r.LocalID, Provider: r.Provider, Kind: r.Kind, Label: r.Label, State: r.State, Reason: r.Reason, Plan: r.Plan, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt, ExpiresAt: r.ExpiresAt}
if r.Headroom != "" {
v.Headroom = &wire.Headroom{}
if json.Unmarshal([]byte(r.Headroom), v.Headroom) != nil {
@@ -111,7 +115,7 @@ func (t *txn) saveConnection(r *connectionRecord, fresh bool) error {
r.CreatedAt = r.UpdatedAt
err = t.db.Create(r).Error
} else {
- err = t.db.Model(&connectionRecord{}).Where("id = ?", r.ID).Select("local_id", "label", "state", "reason", "plan", "headroom", "prompt", "revision", "updated_at").Updates(r).Error
+ err = t.db.Model(&connectionRecord{}).Where("id = ?", r.ID).Select("local_id", "label", "state", "reason", "plan", "headroom", "prompt", "revision", "updated_at", "expires_at").Updates(r).Error
}
if err != nil {
return err
@@ -166,21 +170,21 @@ func (t *txn) helloConnections(l Lease, held []wire.HeldConnection) error {
}) {
continue
}
- r := connectionRecord{ID: newID("cn_"), Person: person, RunnerID: runner, LocalID: h.LocalID, Provider: h.Provider, Kind: h.Kind, Label: h.Label, State: h.State, Plan: h.Plan, Headroom: headroom}
+ r := connectionRecord{ID: newID("cn_"), Person: person, RunnerID: runner, LocalID: h.LocalID, Provider: h.Provider, Kind: h.Kind, Label: h.Label, State: h.State, Plan: h.Plan, Headroom: headroom, ExpiresAt: h.ExpiresAt}
if err := t.saveConnection(&r, true); err != nil {
return err
}
continue
}
r := rows[i]
- changed := r.State != h.State || r.Label != h.Label || r.Plan != h.Plan || r.Reason != ""
+ changed := r.State != h.State || r.Label != h.Label || r.Plan != h.Plan || r.Reason != "" || !sameTime(r.ExpiresAt, h.ExpiresAt)
if !changed && r.Headroom == headroom {
continue
}
if !changed && t.now().Sub(r.UpdatedAt) < headroomEvery {
continue
}
- r.State, r.Label, r.Plan, r.Headroom, r.Reason, r.Prompt = h.State, h.Label, h.Plan, headroom, "", ""
+ r.State, r.Label, r.Plan, r.Headroom, r.Reason, r.Prompt, r.ExpiresAt = h.State, h.Label, h.Plan, headroom, "", "", h.ExpiresAt
if err := t.saveConnection(&r, false); err != nil {
return err
}
@@ -238,6 +242,12 @@ func (t *txn) connectionReport(l Lease, v *wire.ConnectionReport) error {
if v.State != wire.ConnConnecting {
r.Prompt = ""
}
+ if v.State == wire.ConnHealthy && r.Kind == wire.KindToken && r.ExpiresAt == nil {
+ // A setup token lasts a year from when it was pasted; the runner's
+ // hello says exactly when.
+ at := t.now().Add(wire.TokenLifetime)
+ r.ExpiresAt = &at
+ }
if v.LocalID != "" && v.State != wire.ConnError {
// The hello may have recorded the new connection first.
if err := t.db.Where("person = ? AND runner_id = ? AND local_id = ? AND id <> ?", r.Person, r.RunnerID, v.LocalID, r.ID).Delete(&connectionRecord{}).Error; err != nil {
@@ -390,11 +400,13 @@ func (s *Store) Connection(ctx context.Context, person, id string) (out wire.Con
// a Codex account by device code; a Claude account by the CLI's own
// sign-in, finished at the runner's machine (loopback, no paste) or, when
// the person's browser is elsewhere, by `equipo-runner login claude` in
-// a terminal there. Nothing secret passes through the instance either way.
-// A second attempt for the same provider while one is connecting returns
-// that one.
+// a terminal there; or a Claude account from a pasted setup token (kind
+// token), sealed in the app to the runner (SendSecret). Nothing the
+// instance can read passes through it either way. A second attempt for
+// the same provider while one is connecting returns that one.
func (s *Store) StartConnection(ctx context.Context, person string, in wire.Connect) (out wire.Connection, err error) {
- if in.Provider != wire.ProviderClaude && in.Provider != wire.ProviderCodex || in.Kind != "" && in.Kind != wire.KindSubscription {
+ token := in.Kind == wire.KindToken
+ if in.Provider != wire.ProviderClaude && in.Provider != wire.ProviderCodex || in.Kind != "" && in.Kind != wire.KindSubscription && !token || token && (in.Provider != wire.ProviderClaude || in.SameMachine) {
return out, ErrInvalid
}
err = s.tx(ctx, func(t *txn) error {
@@ -422,7 +434,10 @@ func (s *Store) StartConnection(ctx context.Context, person string, in wire.Conn
return ErrRunnerOffline
}
r := connectionRecord{ID: newID("cn_"), Person: person, RunnerID: runner.ID, Provider: in.Provider, Kind: wire.KindSubscription, State: wire.ConnConnecting}
- if in.Provider == wire.ProviderClaude && !in.SameMachine {
+ if token {
+ // The token card: run the command anywhere, approve, paste.
+ r.Kind, r.Prompt = wire.KindToken, asJSON(wire.ConnectPrompt{Kind: wire.PromptToken, Code: "claude setup-token"})
+ } else if in.Provider == wire.ProviderClaude && !in.SameMachine {
// The honest card: Claude's sign-in finishes on the runner's
// machine. The runner watches for the terminal login.
r.Prompt = asJSON(wire.ConnectPrompt{Kind: wire.PromptTerminal, Code: "equipo-runner login claude"})
@@ -456,6 +471,9 @@ func (s *Store) CancelConnection(ctx context.Context, person, id string) (out wi
if err := t.saveConnection(&r, false); err != nil {
return err
}
+ if err := t.dropSecret(r.ID); err != nil {
+ return err
+ }
out = connectionView(r)
return t.command(person, wire.FrameCancelConnect, wire.CancelConnectCommand{Connection: r.ID, Person: person})
})
@@ -489,6 +507,73 @@ func (s *Store) SignOut(ctx context.Context, person, id string) (out wire.Connec
return out, err
}
+// SendSecret queues the sealed secret for one of the person's token
+// attempts (spec §2.4) as a durable secret frame to the attempt's
+// runner. The instance cannot open the box; it checks the clear binding
+// beside it names this attempt (its runner, Claude's endpoint, attempt
+// 1, a short expiry) and that the box is a size a sealed token can be.
+// One box per attempt: the attempt's token prompt goes with it, so the
+// card waits for the runner. The box is in no event, response or log
+// line, and leaves the mailbox once the runner acks it.
+func (s *Store) SendSecret(ctx context.Context, person, id string, in wire.Sealed) (out wire.Connection, err error) {
+ if !sealedShape(in, s.now()) {
+ return out, ErrInvalid
+ }
+ err = s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ var r connectionRecord
+ if err := t.db.Where("id = ? AND person = ?", id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) {
+ return ErrNotFound
+ } else if err != nil {
+ return err
+ }
+ if in.RunnerID != r.RunnerID || in.ConnectionID != r.ID || in.Provider != r.Provider || r.Kind != wire.KindToken {
+ return ErrInvalid
+ }
+ if r.State != wire.ConnConnecting || r.Prompt == "" {
+ return ErrConflict
+ }
+ r.Prompt = ""
+ if err := t.saveConnection(&r, false); err != nil {
+ return err
+ }
+ out = connectionView(r)
+ return t.commandTo(r.RunnerID, person, wire.FrameSecret, wire.SecretCommand{Connection: r.ID, Person: person, Sealed: in})
+ })
+ return out, err
+}
+
+// sealedShape checks what can be checked of a box without opening it.
+func sealedShape(in wire.Sealed, now time.Time) bool {
+ if in.Provider != wire.ProviderClaude || in.Endpoint != wire.EndpointAnthropic || in.Attempt != 1 || len(in.Box) > wire.MaxSealedBytes {
+ return false
+ }
+ // The runner allows a minute of clock skew past the TTL; so does this.
+ if !in.ExpiresAt.After(now) || in.ExpiresAt.Sub(now) > wire.SealedTTL+time.Minute {
+ return false
+ }
+ raw, err := base64.StdEncoding.DecodeString(in.Box)
+ // An ephemeral public key and a MAC at least.
+ return err == nil && len(raw) > 48
+}
+
+// dropSecret takes an ended attempt's box out of the mailbox before its
+// runner took it.
+func (t *txn) dropSecret(connection string) error {
+ like := `{"connection":"` + strings.ReplaceAll(connection, `"`, "") + `",%`
+ return t.db.Model(&commandRecord{}).Where("kind = ? AND body LIKE ?", wire.FrameSecret, like).Updates(map[string]any{"body": "{}", "acked_at": t.now()}).Error
+}
+
+// sameTime reports whether two optional times are the same instant.
+func sameTime(a, b *time.Time) bool {
+ if a == nil || b == nil {
+ return a == b
+ }
+ return a.Equal(*b)
+}
+
// expireAttempts ends attempts that made no progress (a runner that went
// away mid-attempt reports nothing).
func (t *txn) expireAttempts() error {
@@ -501,6 +586,9 @@ func (t *txn) expireAttempts() error {
if err := t.saveConnection(&rows[i], false); err != nil {
return err
}
+ if err := t.dropSecret(rows[i].ID); err != nil {
+ return err
+ }
}
return nil
}
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go
index 57f4d5f1..f40f69d1 100644
--- a/internal/equipo/chat/http.go
+++ b/internal/equipo/chat/http.go
@@ -93,6 +93,7 @@ func (h *HTTP) Mount(r chi.Router) {
r.Post("/connections", h.bearer(h.connect))
r.Get("/connections/{id}", h.thinOr("GET /connections/{id}", thinConnection, h.bearer(h.connection)))
r.Post("/connections/{id}/cancel", h.bearer(h.cancelConnection))
+ r.Post("/connections/{id}/secret", h.bearer(h.secret))
r.Delete("/connections/{id}", h.thinOr("DELETE /connections/{id}", thinConnection, h.bearer(h.signOut)))
r.Post("/connections/{id}/forget", h.bearer(h.forget))
r.Get("/thinking", h.bearer(h.thinking))
@@ -211,6 +212,23 @@ func (h *HTTP) setPreferences(w http.ResponseWriter, r *http.Request, p personap
writeJSON(w, 200, out)
}
+// secret is POST /api/v1/connections/{id}/secret: a token attempt's
+// sealed secret (wire.Sealed), 202 with the attempt waiting for its
+// runner. The box is never echoed.
+func (h *HTTP) secret(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ var in wire.Sealed
+ if err := readJSON(r, &in); err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ out, err := h.Store.SendSecret(r.Context(), p.Address, chi.URLParam(r, "id"), in)
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, http.StatusAccepted, out)
+}
+
func (h *HTTP) cancelConnection(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
out, err := h.Store.CancelConnection(r.Context(), p.Address, chi.URLParam(r, "id"))
if err != nil {
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go
index 4d74f5bd..ea2b06c8 100644
--- a/internal/equipo/chat/runner.go
+++ b/internal/equipo/chat/runner.go
@@ -337,6 +337,11 @@ func (t *txn) ack(l Lease, id string) error {
if c.Kind == wire.FrameBlob {
return t.blobAcked(c.Body)
}
+ if c.Kind == wire.FrameSecret {
+ // The runner holds the secret now: the box leaves the mailbox
+ // (only WAL and backup residue can remain, spec §2.4).
+ return t.db.Model(&commandRecord{}).Where("seq = ?", c.Seq).Update("body", "{}").Error
+ }
if c.Kind != wire.FrameMessage {
return nil
}
diff --git a/internal/equipo/chat/runners.go b/internal/equipo/chat/runners.go
index f5e156c4..3922070c 100644
--- a/internal/equipo/chat/runners.go
+++ b/internal/equipo/chat/runners.go
@@ -2,6 +2,7 @@ package chat
import (
"context"
+ "encoding/base64"
"encoding/json"
"errors"
"slices"
@@ -35,7 +36,8 @@ const orphanedBy = `SELECT id FROM runners WHERE person = ? AND revoked_at IS NO
// attemptKinds are commands that belong to one attempt on one runner: a
// dispatch whose ack was lost may already run there, so they never move.
-var attemptKinds = []string{wire.FrameDispatch, wire.FrameCancelStep, wire.FrameAsk, wire.FrameCancelAsk, wire.FrameBlob, wire.FrameSendPack, wire.FramePublish}
+// A sealed secret opens only with its own runner's key.
+var attemptKinds = []string{wire.FrameDispatch, wire.FrameCancelStep, wire.FrameAsk, wire.FrameCancelAsk, wire.FrameBlob, wire.FrameSendPack, wire.FramePublish, wire.FrameSecret}
// rebind gives the person's primary the conversation's commands no runner
// holds: those written while the person had no primary, and a revoked
@@ -215,6 +217,11 @@ func cleanHello(h wire.Hello) wire.Hello {
default:
h.Sandbox = ""
}
+ // The seal key is published for the apps to seal to: only an X25519
+ // public key (32 bytes, standard base64) is kept.
+ if raw, err := base64.StdEncoding.DecodeString(h.SealKey); err != nil || len(raw) != 32 {
+ h.SealKey = ""
+ }
return h
}
@@ -300,7 +307,7 @@ func (t *txn) runnerOnline(person, id string) (bool, error) {
// runnerView is the Runner resource.
func runnerView(r runnerInfo) wire.Runner {
- v := wire.Runner{ID: r.ID, Revision: r.Revision, Online: r.Online, Label: r.Label, Role: r.Role, Platform: r.Hello.Platform, Capabilities: r.Hello.Capabilities, Removing: r.Removing}
+ v := wire.Runner{ID: r.ID, Revision: r.Revision, Online: r.Online, Label: r.Label, Role: r.Role, Platform: r.Hello.Platform, Capabilities: r.Hello.Capabilities, Removing: r.Removing, SealKey: r.Hello.SealKey}
if !r.SeenAt.IsZero() {
at := r.SeenAt
v.Since = &at
diff --git a/internal/equipo/chat_connections.go b/internal/equipo/chat_connections.go
index 1615e617..075a7b4e 100644
--- a/internal/equipo/chat_connections.go
+++ b/internal/equipo/chat_connections.go
@@ -4,6 +4,8 @@ import (
"context"
"errors"
"fmt"
+ "io"
+ "mime"
"net/http"
"strconv"
"strings"
@@ -25,8 +27,13 @@ import (
// modelLine is a connecting card: an attempt the person started.
type modelLine struct {
ID, Provider, Name string
- Connecting bool
- Prompt *wire.ConnectPrompt
+ // Kind is the attempt's (token: a pasted setup token).
+ Kind string
+ Connecting bool
+ Prompt *wire.ConnectPrompt
+ // A token card seals to RunnerID's SealKey ("" when the runner has
+ // none to give) for Endpoint.
+ RunnerID, SealKey, Endpoint string
// Phrases are the loading line's rotating words while the runner has
// not yet shown the provider's sign-in.
Phrases string
@@ -193,25 +200,34 @@ func (a *application) connectionsView(w http.ResponseWriter, r *http.Request) {
render(w, "models", data)
}
-// connectionsStart is Add Codex, Add Claude and "I am at this machine".
+// connectionsStart is Add Codex, Add Claude (a pasted token, or the
+// sign-in on the runner), "I am at this machine" and a row's Sign in
+// again or Paste a new token.
func (a *application) connectionsStart(w http.ResponseWriter, r *http.Request) {
a.chatActionTo(w, r, "/conversation/connections", func(ctx context.Context, address string) error {
provider, same := r.PostFormValue("provider"), r.PostFormValue("same_machine") == "1"
- if same {
- // The terminal card gives way to the sign-in at this machine.
- conns, err := a.store.Chat().Connections(ctx, address)
- if err != nil {
- return err
- }
- for _, c := range conns {
- if c.State == wire.ConnConnecting && c.Provider == provider {
- if _, err := a.store.Chat().CancelConnection(ctx, address, c.ID); err != nil {
- return err
- }
+ kind := wire.KindSubscription
+ if r.PostFormValue("kind") == wire.KindToken && !same {
+ kind = wire.KindToken
+ }
+ // The card open gives way to the other way of connecting: the
+ // sign-in at this machine, a token, or the sign-in on the runner.
+ conns, err := a.store.Chat().Connections(ctx, address)
+ if err != nil {
+ return err
+ }
+ for _, c := range conns {
+ if c.State == wire.ConnConnecting && c.Provider == provider && (same || c.Kind != kind) {
+ // Switching is not giving up: the ended card goes unsaid.
+ if _, err := a.store.Chat().CancelConnection(ctx, address, c.ID); err != nil {
+ return err
+ }
+ if err := a.store.Chat().Forget(ctx, address, c.ID); err != nil {
+ return err
}
}
}
- _, err := a.store.Chat().StartConnection(ctx, address, wire.Connect{Provider: provider, Kind: wire.KindSubscription, SameMachine: same})
+ _, err = a.store.Chat().StartConnection(ctx, address, wire.Connect{Provider: provider, Kind: kind, SameMachine: same})
if errors.Is(err, chat.ErrRunnerOffline) {
return nil
}
@@ -252,6 +268,30 @@ func (a *application) connectionsForget(w http.ResponseWriter, r *http.Request)
})
}
+// connectionsSecret takes the token card's sealed box (JSON, sealed in
+// the page by connections.js) for one of the person's token attempts.
+// It answers 202 and nothing else: the box is never echoed.
+func (a *application) connectionsSecret(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ ctx, address, ok := sessionContext(r)
+ if !ok {
+ a.failure(w, r, ErrForbidden)
+ return
+ }
+ var in wire.Sealed
+ media, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ raw, err := io.ReadAll(io.LimitReader(r.Body, 2*wire.MaxSealedBytes))
+ if media != "application/json" || err != nil || len(raw) >= 2*wire.MaxSealedBytes || wire.Strict(raw, &in) != nil {
+ a.failure(w, r, chatError(chat.ErrInvalid))
+ return
+ }
+ if _, err := a.store.Chat().SendSecret(ctx, address, chi.URLParam(r, "id"), in); err != nil {
+ a.failure(w, r, chatError(err))
+ return
+ }
+ runnerJSON(w, http.StatusAccepted, struct{}{})
+}
+
func (a *application) connectionsCancel(w http.ResponseWriter, r *http.Request) {
a.chatActionTo(w, r, "/conversation/connections", func(ctx context.Context, address string) error {
_, err := a.store.Chat().CancelConnection(ctx, address, chi.URLParam(r, "id"))
diff --git a/internal/equipo/connections_view.go b/internal/equipo/connections_view.go
index 5e525379..790fb7a3 100644
--- a/internal/equipo/connections_view.go
+++ b/internal/equipo/connections_view.go
@@ -19,6 +19,10 @@ import (
// connRow is one connection the person holds (or held).
type connRow struct {
ID, Provider, Name, Glyph, Label, Plan string
+ // Kind is the connection's (token: a pasted setup token); Expires
+ // says when its token expires, Renew asks for a new one near then.
+ Kind, Expires string
+ Renew bool
// State is the wire state; Words says it.
State, Words string
Meters []connMeter
@@ -85,8 +89,11 @@ func connectionsPage(snap wire.Snapshot, today map[string]int64, prefer wire.Pre
for _, c := range snap.Connections {
switch {
case c.State == wire.ConnConnecting:
- line := modelLine{ID: c.ID, Provider: c.Provider, Name: providerName(c.Provider), Connecting: true, Prompt: c.Prompt, Runner: runner}
- if c.Prompt == nil {
+ line := modelLine{ID: c.ID, Provider: c.Provider, Name: providerName(c.Provider), Kind: c.Kind, Connecting: true, Prompt: c.Prompt, Runner: runner, RunnerID: c.RunnerID, Endpoint: wire.EndpointAnthropic}
+ if c.RunnerID == snap.Runner.ID {
+ line.SealKey = snap.Runner.SealKey
+ }
+ if c.Prompt == nil && c.Kind != wire.KindToken {
line.Phrases = loadingPhrases(c.Provider)
}
v.Attempts = append(v.Attempts, line)
@@ -94,7 +101,11 @@ func connectionsPage(snap wire.Snapshot, today map[string]int64, prefer wire.Pre
case c.State == wire.ConnError && c.LocalID == "":
// An attempt that ended says why once, then the page moves on.
if time.Since(c.UpdatedAt) < 10*time.Minute {
- v.Ended = append(v.Ended, connRow{ID: c.ID, Provider: c.Provider, Name: providerName(c.Provider), Note: copyText("chat.connections.reason." + c.Reason), Forget: true})
+ note := copyText("chat.connections.reason." + c.Reason)
+ if c.Kind == wire.KindToken && c.Reason == "provider_refused" {
+ note = copyText("chat.connections.token_rejected")
+ }
+ v.Ended = append(v.Ended, connRow{ID: c.ID, Provider: c.Provider, Name: providerName(c.Provider), Note: note, Forget: true})
}
default:
held = append(held, c)
@@ -116,11 +127,14 @@ func connectionsPage(snap wire.Snapshot, today map[string]int64, prefer wire.Pre
}
}
for _, c := range held {
- row := connRow{ID: c.ID, Provider: c.Provider, Name: providerName(c.Provider), Glyph: providerGlyph(c.Provider), Label: c.Label, Plan: c.Plan, State: c.State, Words: connectionState(c), Usage: tokensText(today[c.LocalID]), PreferRevision: prefer.Revision}
+ row := connRow{ID: c.ID, Provider: c.Provider, Name: providerName(c.Provider), Glyph: providerGlyph(c.Provider), Label: c.Label, Plan: c.Plan, Kind: c.Kind, State: c.State, Words: connectionState(c), Usage: tokensText(today[c.LocalID]), PreferRevision: prefer.Revision}
_, row.UsageTail, _ = strings.Cut(copyText("chat.connections.usage_today"), "%s")
if c.State == wire.ConnError {
row.State = wire.ConnSignInAgain
}
+ if c.Kind == wire.KindToken {
+ tokenFacts(&row, c, time.Now())
+ }
if c.Headroom != nil && row.State != wire.ConnSignedOut && row.State != wire.ConnSignInAgain {
for _, w := range c.Headroom.Windows {
row.Meters = append(row.Meters, meterOf(w))
@@ -160,6 +174,20 @@ func connectionsPage(snap wire.Snapshot, today map[string]int64, prefer wire.Pre
return v
}
+// tokenFacts says when a pasted token expires, asks for a new one within
+// TokenRenewal of then, and says a rejected one was rejected.
+func tokenFacts(row *connRow, c wire.Connection, now time.Time) {
+ if row.State == wire.ConnSignInAgain {
+ row.Words = copyText("chat.connections.token_rejected")
+ return
+ }
+ if c.ExpiresAt == nil || row.State == wire.ConnSignedOut {
+ return
+ }
+ row.Expires = fmt.Sprintf(copyText("chat.connections.token_expires"), c.ExpiresAt.UTC().Format("2 Jan 2006"))
+ row.Renew = c.ExpiresAt.Sub(now) < wire.TokenRenewal
+}
+
// liveRoles are the roles each connection runs now: a turn of the
// person's running on it, a step running on it.
func liveRoles(snap wire.Snapshot) map[string]bool {
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 75fe6b2d..880ba7b6 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -799,6 +799,23 @@ var pageCopy = map[string]string{
"chat.connections.loading_claude_1": "Finding your runner…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"chat.connections.loading_claude_2": "Warming up a fresh desk for Claude…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"chat.connections.loading_claude_3": "Starting Claude's own sign-in…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.paste_token": "Paste a token", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.sign_in_instead": "Or sign in on the runner instead", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.token_sub": "Your Claude subscription, with a token from Claude Code.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.token_run": "On any computer with Claude Code, run", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.token_approve": "Approve in the browser.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.token_paste": "Paste the token here.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.token_connect": "Connect", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.token_sealed": "It's sealed to your runner; Equipo's server never sees it.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.token_bad": "That is not a Claude token. Paste the line that starts sk-ant-oat.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.token_failed": "That did not go through. Paste the token again.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.token_no_key": "Your runner needs an update before it can take a token.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.waiting_token": "Your runner is checking the token…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.token_expires": "Token expires %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.token_renew": "It expires soon.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.token_new": "Paste a new token", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.token_rejected": "This token was rejected. Run claude setup-token again.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.copy_link": "Copy link", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"chat.switched": "Switched to %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"chat.switched_reset": "Switched to %s; %s resets %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"chat.no_connection": "Nothing can answer right now. %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
diff --git a/internal/equipo/migrations/0056_thin_token_connections.sql b/internal/equipo/migrations/0056_thin_token_connections.sql
new file mode 100644
index 00000000..97dca54a
--- /dev/null
+++ b/internal/equipo/migrations/0056_thin_token_connections.sql
@@ -0,0 +1 @@
+ALTER TABLE chat_connections ADD COLUMN expires_at datetime;
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 47baae33..9590f2a8 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -607,7 +607,7 @@ CREATE TABLE chat_task_distinct (a text, b text, created_at datetime, PRIMARY KE
CREATE TABLE chat_questions (id text PRIMARY KEY, task_id text, asker text, idempotency_key text, step_id text, specialist text, chosen text, text text, state text, reason text, attempt integer, dispatched numeric, answer text, timing text, revision integer, created_at datetime, updated_at datetime);
CREATE INDEX chat_question_task ON chat_questions(task_id);
CREATE UNIQUE INDEX chat_question_key ON chat_questions(task_id, asker, idempotency_key);
-CREATE TABLE chat_connections (id text PRIMARY KEY, person text, runner_id text, local_id text, provider text, kind text, label text, state text, reason text, plan text, headroom text, prompt text, revision integer, created_at datetime, updated_at datetime);
+CREATE TABLE chat_connections (id text PRIMARY KEY, person text, runner_id text, local_id text, provider text, kind text, label text, state text, reason text, plan text, headroom text, prompt text, revision integer, created_at datetime, updated_at datetime, expires_at datetime);
CREATE INDEX chat_connection_person ON chat_connections(person);
CREATE TABLE chat_usage (id integer PRIMARY KEY, person text, connection text, provider text, model text, role text, task_id text, step_id text, turn_id text, attempt integer, outcome text, complete numeric, input_tokens integer, cached_input_tokens integer, cache_write_tokens integer, output_tokens integer, reasoning_output_tokens integer, recorded_at datetime);
CREATE INDEX chat_usage_person ON chat_usage(person, recorded_at);
diff --git a/internal/equipo/static/connections.js b/internal/equipo/static/connections.js
index a047f56d..de6bd159 100644
--- a/internal/equipo/static/connections.js
+++ b/internal/equipo/static/connections.js
@@ -113,7 +113,21 @@
var seen = {};
box.querySelectorAll("[data-connection]").forEach(function (el) { seen[el.dataset.connection] = true; });
next.querySelectorAll("[data-connection]").forEach(function (el) { if (seen[el.dataset.connection]) el.setAttribute("data-settled", ""); });
+ // A token card being typed into stays as it is: the same field,
+ // its value and its focus.
+ var typing = null;
+ box.querySelectorAll("[data-token-form]").forEach(function (form) {
+ var field = form.querySelector("[data-token-field]");
+ var card = form.closest("[data-connecting]");
+ var same = card && next.querySelector('[data-connecting][data-connection="' + CSS.escape(card.dataset.connection) + '"] [data-token-form]');
+ if (same && !form.closest("[data-token-steps]").hidden && (field.value || document.activeElement === field)) {
+ card.setAttribute("data-settled", "");
+ same.closest("[data-connecting]").replaceWith(card);
+ if (document.activeElement === field) typing = field;
+ }
+ });
box.replaceChildren.apply(box, Array.from(next.children));
+ if (typing) typing.focus();
live(box);
Object.keys(connecting).forEach(function (id) {
var row = box.querySelector('[equipo-conn-row][data-connection="' + CSS.escape(id) + '"]');
@@ -148,6 +162,17 @@
sel.removeAllRanges();
sel.addRange(range);
try { document.execCommand("copy"); } catch (e) { /* selected for the person to copy */ }
+ } else {
+ // A link has no code on the page to select: copy it from a
+ // field nobody sees.
+ var field = document.createElement("textarea");
+ field.value = text;
+ field.setAttribute("readonly", "");
+ field.setAttribute("equipo-visually-hidden", "");
+ document.body.append(field);
+ field.select();
+ try { document.execCommand("copy"); } catch (e) { /* nothing more to try */ }
+ field.remove();
}
done();
}
@@ -155,12 +180,52 @@
else select();
});
+ // A Claude token: checked here, sealed here to the runner's seal key
+ // (seal.js) and posted as the box with its clear binding. The field is
+ // cleared at once; the token is never shown, kept or sent in the clear.
+ var TOKEN = /^sk-ant-oat[0-9A-Za-z_-]{8,500}$/;
+ function sealToken(form) {
+ var card = form.closest("[data-connecting]");
+ var field = form.querySelector("[data-token-field]");
+ var note = form.querySelector("[data-token-note]");
+ var token = field.value.trim();
+ field.value = "";
+ function say(key) {
+ note.textContent = note.dataset[key];
+ note.setAttribute("data-tone", "bad");
+ note.hidden = false;
+ field.focus();
+ }
+ if (!TOKEN.test(token)) { token = ""; say("bad"); return; }
+ var d = card.dataset;
+ if (!d.sealKey || !window.EquipoSeal || !window.TextEncoder) { token = ""; say("noKey"); return; }
+ var clear = { runner_id: d.runner, connection_id: d.connection, provider: d.provider, endpoint: d.endpoint, attempt: 1, expires_at: new Date(Date.now() + 10 * 60 * 1000).toISOString() };
+ var message = new TextEncoder().encode(JSON.stringify(Object.assign({ secret: token }, clear)));
+ token = "";
+ var box;
+ try { box = window.EquipoSeal.seal(d.sealKey, message); } catch (e) { box = ""; }
+ message.fill(0);
+ if (!box) { say("noKey"); return; }
+ note.hidden = true;
+ var steps = card.querySelector("[data-token-steps]"), waiting = card.querySelector("[data-token-waiting]");
+ if (steps) steps.hidden = true;
+ if (waiting) waiting.hidden = false;
+ fetch("/conversation/connections/" + encodeURIComponent(d.connection) + "/secret", { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json", "Accept": "application/json" }, body: JSON.stringify(Object.assign({ box: box }, clear)) })
+ .then(function (r) { if (!r.ok) throw new Error("secret"); refreshSoon(); })
+ .catch(function () {
+ if (steps) steps.hidden = false;
+ if (waiting) waiting.hidden = true;
+ say("failed");
+ });
+ }
+
// Forms post in the background; an Add shows its loading card at once,
// in the chooser's place.
root.addEventListener("submit", function (event) {
var form = event.target;
if (!form.matches || !form.matches("form")) return;
event.preventDefault();
+ if (form.matches("[data-token-form]")) { sealToken(form); return; }
if (form.matches("[data-add-form]")) {
var provider = form.querySelector('[name="provider"]').value;
var area = root.querySelector("[data-attempts]");
diff --git a/internal/equipo/static/equipo.css b/internal/equipo/static/equipo.css
index 05f5e657..53683c1b 100644
--- a/internal/equipo/static/equipo.css
+++ b/internal/equipo/static/equipo.css
@@ -858,6 +858,23 @@ a[equipo-source]:hover { color: var(--rst-text); text-decoration: underline; tex
[equipo-conn-empty] [equipo-conn-chooser], [equipo-conn-empty] [equipo-conn-card] { text-align: start; inline-size: 100%; }
[equipo-inline-form] { display: inline; margin: 0; }
[data-copy][data-done] { color: var(--rst-tone-positive-fg); }
+/* Copy link beside an Open button (Paul, 2026-11-09: to open the link in
+ another browser). */
+[equipo-conn-steps] > li > [equipo-conn-link-row] { display: flex; flex-wrap: wrap; align-items: center; gap: var(--rst-sp-2) var(--rst-sp-3); }
+/* A Claude token (Paul, 2026-11-09: "really, really easy"): the Codex
+ card's look, the paste field and Connect on one line where it fits. */
+[equipo-conn-opt-how] { display: inline-block; margin-block-start: .3rem; padding: .05rem .5rem; border-radius: 999px; font-size: var(--rst-fs-xs); color: var(--rst-accent); background: var(--rst-accent-soft); }
+[equipo-conn-alt] { padding: 0 var(--rst-sp-4) var(--rst-sp-3) calc(var(--rst-sp-4) + 2.25rem + var(--rst-sp-3)); font-size: var(--rst-fs-xs); }
+[equipo-conn-alt] [equipo-link], [equipo-conn-card-foot] [data-sign-in-instead] { font-size: var(--rst-fs-xs); }
+[equipo-conn-token] { display: grid; gap: .4rem; margin: 0; }
+[equipo-conn-token] label { color: var(--rst-text); }
+[equipo-conn-token-row] { display: flex; flex-wrap: wrap; gap: var(--rst-sp-2); }
+[equipo-conn-token-row] input { flex: 1 1 14rem; min-inline-size: 0; font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; }
+[equipo-conn-token] [data-token-note] { margin: 0; }
+[equipo-conn-token] [data-token-note][data-tone="bad"] { color: var(--rst-tone-negative-fg); }
+[equipo-conn-expires] { font-size: var(--rst-fs-xs); color: var(--rst-text-muted); white-space: nowrap; }
+[equipo-conn-renew] { font-size: var(--rst-fs-xs); color: var(--rst-tone-warning-fg); }
+[equipo-conn-renew] [equipo-link] { font-size: inherit; }
@container conn (max-width: 600px) {
[equipo-conn-answering] { padding: var(--rst-sp-3); }
[equipo-conn-lead] { font-size: var(--rst-fs-base); }
diff --git a/internal/equipo/static/seal.js b/internal/equipo/static/seal.js
new file mode 100644
index 00000000..d92891d5
--- /dev/null
+++ b/internal/equipo/static/seal.js
@@ -0,0 +1,127 @@
+// Sealing a secret to one runner in the browser (Connections spec §2.4):
+// libsodium's crypto_box_seal, so the runner opens it with its own key
+// and the instance, which only carries it, cannot. The box is
+//
+// ephemeral_pk || crypto_box(message, nonce, recipient_pk, ephemeral_sk)
+// nonce = BLAKE2b-192(ephemeral_pk || recipient_pk)
+//
+// X25519 and XSalsa20-Poly1305 come from the vendored tweetnacl
+// (vendor/tweetnacl/nacl-fast.js, public domain); BLAKE2b is below,
+// adapted from Paul's contra vault (RFC 7693, unkeyed). The Go side is
+// internal/sealbox, and a browser test opens this page's box with
+// x/crypto's box.OpenAnonymous.
+(function () {
+ "use strict";
+
+ var MASK = (1n << 64n) - 1n;
+ var IV = [
+ 0x6a09e667f3bcc908n, 0xbb67ae8584caa73bn, 0x3c6ef372fe94f82bn, 0xa54ff53a5f1d36f1n,
+ 0x510e527fade682d1n, 0x9b05688c2b3e6c1fn, 0x1f83d9abfb41bd6bn, 0x5be0cd19137e2179n
+ ];
+ var SIGMA = [
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
+ [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
+ [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4],
+ [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8],
+ [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13],
+ [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9],
+ [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11],
+ [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10],
+ [6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5],
+ [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
+ [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3]
+ ];
+
+ function rotr(x, n) { return ((x >> n) | (x << (64n - n))) & MASK; }
+
+ function mix(v, a, b, c, d, x, y) {
+ v[a] = (v[a] + v[b] + x) & MASK;
+ v[d] = rotr(v[d] ^ v[a], 32n);
+ v[c] = (v[c] + v[d]) & MASK;
+ v[b] = rotr(v[b] ^ v[c], 24n);
+ v[a] = (v[a] + v[b] + y) & MASK;
+ v[d] = rotr(v[d] ^ v[a], 16n);
+ v[c] = (v[c] + v[d]) & MASK;
+ v[b] = rotr(v[b] ^ v[c], 63n);
+ }
+
+ function compress(h, block, counter, last) {
+ var v = h.concat(IV);
+ v[12] ^= counter & MASK;
+ v[13] ^= (counter >> 64n) & MASK;
+ if (last) v[14] ^= MASK;
+ var m = new Array(16);
+ for (var i = 0; i < 16; i++) {
+ var w = 0n;
+ for (var j = 7; j >= 0; j--) w = (w << 8n) | BigInt(block[i * 8 + j]);
+ m[i] = w;
+ }
+ for (var r = 0; r < 12; r++) {
+ var s = SIGMA[r];
+ mix(v, 0, 4, 8, 12, m[s[0]], m[s[1]]);
+ mix(v, 1, 5, 9, 13, m[s[2]], m[s[3]]);
+ mix(v, 2, 6, 10, 14, m[s[4]], m[s[5]]);
+ mix(v, 3, 7, 11, 15, m[s[6]], m[s[7]]);
+ mix(v, 0, 5, 10, 15, m[s[8]], m[s[9]]);
+ mix(v, 1, 6, 11, 12, m[s[10]], m[s[11]]);
+ mix(v, 2, 7, 8, 13, m[s[12]], m[s[13]]);
+ mix(v, 3, 4, 9, 14, m[s[14]], m[s[15]]);
+ }
+ for (var k = 0; k < 8; k++) h[k] = h[k] ^ v[k] ^ v[k + 8];
+ }
+
+ // blake2b hashes input (a Uint8Array) to outLen bytes (1 to 64),
+ // unkeyed.
+ function blake2b(outLen, input) {
+ if (outLen < 1 || outLen > 64) throw new Error("blake2b output length");
+ var h = IV.slice();
+ h[0] ^= 0x01010000n ^ BigInt(outLen);
+ var counter = 0n, off = 0;
+ while (input.length - off > 128) {
+ counter += 128n;
+ compress(h, input.subarray(off, off + 128), counter, false);
+ off += 128;
+ }
+ var tail = new Uint8Array(128);
+ tail.set(input.subarray(off));
+ counter += BigInt(input.length - off);
+ compress(h, tail, counter, true);
+ var out = new Uint8Array(outLen);
+ for (var i = 0; i < outLen; i++) out[i] = Number((h[i >> 3] >> BigInt(8 * (i & 7))) & 0xffn);
+ return out;
+ }
+
+ function toBase64(bytes) {
+ var s = "";
+ for (var i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
+ return btoa(s);
+ }
+
+ function fromBase64(text) {
+ var s = atob(text), out = new Uint8Array(s.length);
+ for (var i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
+ return out;
+ }
+
+ // seal seals message (a Uint8Array) to the recipient's X25519 public
+ // key (standard base64) and returns the box in standard base64. The
+ // ephemeral secret key is wiped before it returns.
+ function seal(publicKey, message) {
+ var nacl = window.nacl;
+ var pk = fromBase64(publicKey);
+ if (!nacl || pk.length !== nacl.box.publicKeyLength) throw new Error("seal key");
+ var eph = nacl.box.keyPair();
+ var both = new Uint8Array(64);
+ both.set(eph.publicKey);
+ both.set(pk, 32);
+ var boxed = nacl.box(message, blake2b(nacl.box.nonceLength, both), pk, eph.secretKey);
+ eph.secretKey.fill(0);
+ var out = new Uint8Array(32 + boxed.length);
+ out.set(eph.publicKey);
+ out.set(boxed, 32);
+ return toBase64(out);
+ }
+
+ window.EquipoSeal = { seal: seal, blake2b: blake2b };
+})();
diff --git a/internal/equipo/static/vendor/tweetnacl/LICENSE b/internal/equipo/static/vendor/tweetnacl/LICENSE
new file mode 100644
index 00000000..cf1ab25d
--- /dev/null
+++ b/internal/equipo/static/vendor/tweetnacl/LICENSE
@@ -0,0 +1,24 @@
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+For more information, please refer to <http://unlicense.org>
diff --git a/internal/equipo/static/vendor/tweetnacl/nacl-fast.js b/internal/equipo/static/vendor/tweetnacl/nacl-fast.js
new file mode 100644
index 00000000..7ea5fb58
--- /dev/null
+++ b/internal/equipo/static/vendor/tweetnacl/nacl-fast.js
@@ -0,0 +1,2391 @@
+(function(nacl) {
+'use strict';
+
+// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
+// Public domain.
+//
+// Implementation derived from TweetNaCl version 20140427.
+// See for details: http://tweetnacl.cr.yp.to/
+
+var gf = function(init) {
+ var i, r = new Float64Array(16);
+ if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
+ return r;
+};
+
+// Pluggable, initialized in high-level API below.
+var randombytes = function(/* x, n */) { throw new Error('no PRNG'); };
+
+var _0 = new Uint8Array(16);
+var _9 = new Uint8Array(32); _9[0] = 9;
+
+var gf0 = gf(),
+ gf1 = gf([1]),
+ _121665 = gf([0xdb41, 1]),
+ D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),
+ D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),
+ X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),
+ Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),
+ I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
+
+function ts64(x, i, h, l) {
+ x[i] = (h >> 24) & 0xff;
+ x[i+1] = (h >> 16) & 0xff;
+ x[i+2] = (h >> 8) & 0xff;
+ x[i+3] = h & 0xff;
+ x[i+4] = (l >> 24) & 0xff;
+ x[i+5] = (l >> 16) & 0xff;
+ x[i+6] = (l >> 8) & 0xff;
+ x[i+7] = l & 0xff;
+}
+
+function vn(x, xi, y, yi, n) {
+ var i,d = 0;
+ for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];
+ return (1 & ((d - 1) >>> 8)) - 1;
+}
+
+function crypto_verify_16(x, xi, y, yi) {
+ return vn(x,xi,y,yi,16);
+}
+
+function crypto_verify_32(x, xi, y, yi) {
+ return vn(x,xi,y,yi,32);
+}
+
+function core_salsa20(o, p, k, c) {
+ var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,
+ j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,
+ j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,
+ j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,
+ j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,
+ j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,
+ j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,
+ j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,
+ j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,
+ j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,
+ j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,
+ j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,
+ j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,
+ j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,
+ j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,
+ j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;
+
+ var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
+ x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
+ x15 = j15, u;
+
+ for (var i = 0; i < 20; i += 2) {
+ u = x0 + x12 | 0;
+ x4 ^= u<<7 | u>>>(32-7);
+ u = x4 + x0 | 0;
+ x8 ^= u<<9 | u>>>(32-9);
+ u = x8 + x4 | 0;
+ x12 ^= u<<13 | u>>>(32-13);
+ u = x12 + x8 | 0;
+ x0 ^= u<<18 | u>>>(32-18);
+
+ u = x5 + x1 | 0;
+ x9 ^= u<<7 | u>>>(32-7);
+ u = x9 + x5 | 0;
+ x13 ^= u<<9 | u>>>(32-9);
+ u = x13 + x9 | 0;
+ x1 ^= u<<13 | u>>>(32-13);
+ u = x1 + x13 | 0;
+ x5 ^= u<<18 | u>>>(32-18);
+
+ u = x10 + x6 | 0;
+ x14 ^= u<<7 | u>>>(32-7);
+ u = x14 + x10 | 0;
+ x2 ^= u<<9 | u>>>(32-9);
+ u = x2 + x14 | 0;
+ x6 ^= u<<13 | u>>>(32-13);
+ u = x6 + x2 | 0;
+ x10 ^= u<<18 | u>>>(32-18);
+
+ u = x15 + x11 | 0;
+ x3 ^= u<<7 | u>>>(32-7);
+ u = x3 + x15 | 0;
+ x7 ^= u<<9 | u>>>(32-9);
+ u = x7 + x3 | 0;
+ x11 ^= u<<13 | u>>>(32-13);
+ u = x11 + x7 | 0;
+ x15 ^= u<<18 | u>>>(32-18);
+
+ u = x0 + x3 | 0;
+ x1 ^= u<<7 | u>>>(32-7);
+ u = x1 + x0 | 0;
+ x2 ^= u<<9 | u>>>(32-9);
+ u = x2 + x1 | 0;
+ x3 ^= u<<13 | u>>>(32-13);
+ u = x3 + x2 | 0;
+ x0 ^= u<<18 | u>>>(32-18);
+
+ u = x5 + x4 | 0;
+ x6 ^= u<<7 | u>>>(32-7);
+ u = x6 + x5 | 0;
+ x7 ^= u<<9 | u>>>(32-9);
+ u = x7 + x6 | 0;
+ x4 ^= u<<13 | u>>>(32-13);
+ u = x4 + x7 | 0;
+ x5 ^= u<<18 | u>>>(32-18);
+
+ u = x10 + x9 | 0;
+ x11 ^= u<<7 | u>>>(32-7);
+ u = x11 + x10 | 0;
+ x8 ^= u<<9 | u>>>(32-9);
+ u = x8 + x11 | 0;
+ x9 ^= u<<13 | u>>>(32-13);
+ u = x9 + x8 | 0;
+ x10 ^= u<<18 | u>>>(32-18);
+
+ u = x15 + x14 | 0;
+ x12 ^= u<<7 | u>>>(32-7);
+ u = x12 + x15 | 0;
+ x13 ^= u<<9 | u>>>(32-9);
+ u = x13 + x12 | 0;
+ x14 ^= u<<13 | u>>>(32-13);
+ u = x14 + x13 | 0;
+ x15 ^= u<<18 | u>>>(32-18);
+ }
+ x0 = x0 + j0 | 0;
+ x1 = x1 + j1 | 0;
+ x2 = x2 + j2 | 0;
+ x3 = x3 + j3 | 0;
+ x4 = x4 + j4 | 0;
+ x5 = x5 + j5 | 0;
+ x6 = x6 + j6 | 0;
+ x7 = x7 + j7 | 0;
+ x8 = x8 + j8 | 0;
+ x9 = x9 + j9 | 0;
+ x10 = x10 + j10 | 0;
+ x11 = x11 + j11 | 0;
+ x12 = x12 + j12 | 0;
+ x13 = x13 + j13 | 0;
+ x14 = x14 + j14 | 0;
+ x15 = x15 + j15 | 0;
+
+ o[ 0] = x0 >>> 0 & 0xff;
+ o[ 1] = x0 >>> 8 & 0xff;
+ o[ 2] = x0 >>> 16 & 0xff;
+ o[ 3] = x0 >>> 24 & 0xff;
+
+ o[ 4] = x1 >>> 0 & 0xff;
+ o[ 5] = x1 >>> 8 & 0xff;
+ o[ 6] = x1 >>> 16 & 0xff;
+ o[ 7] = x1 >>> 24 & 0xff;
+
+ o[ 8] = x2 >>> 0 & 0xff;
+ o[ 9] = x2 >>> 8 & 0xff;
+ o[10] = x2 >>> 16 & 0xff;
+ o[11] = x2 >>> 24 & 0xff;
+
+ o[12] = x3 >>> 0 & 0xff;
+ o[13] = x3 >>> 8 & 0xff;
+ o[14] = x3 >>> 16 & 0xff;
+ o[15] = x3 >>> 24 & 0xff;
+
+ o[16] = x4 >>> 0 & 0xff;
+ o[17] = x4 >>> 8 & 0xff;
+ o[18] = x4 >>> 16 & 0xff;
+ o[19] = x4 >>> 24 & 0xff;
+
+ o[20] = x5 >>> 0 & 0xff;
+ o[21] = x5 >>> 8 & 0xff;
+ o[22] = x5 >>> 16 & 0xff;
+ o[23] = x5 >>> 24 & 0xff;
+
+ o[24] = x6 >>> 0 & 0xff;
+ o[25] = x6 >>> 8 & 0xff;
+ o[26] = x6 >>> 16 & 0xff;
+ o[27] = x6 >>> 24 & 0xff;
+
+ o[28] = x7 >>> 0 & 0xff;
+ o[29] = x7 >>> 8 & 0xff;
+ o[30] = x7 >>> 16 & 0xff;
+ o[31] = x7 >>> 24 & 0xff;
+
+ o[32] = x8 >>> 0 & 0xff;
+ o[33] = x8 >>> 8 & 0xff;
+ o[34] = x8 >>> 16 & 0xff;
+ o[35] = x8 >>> 24 & 0xff;
+
+ o[36] = x9 >>> 0 & 0xff;
+ o[37] = x9 >>> 8 & 0xff;
+ o[38] = x9 >>> 16 & 0xff;
+ o[39] = x9 >>> 24 & 0xff;
+
+ o[40] = x10 >>> 0 & 0xff;
+ o[41] = x10 >>> 8 & 0xff;
+ o[42] = x10 >>> 16 & 0xff;
+ o[43] = x10 >>> 24 & 0xff;
+
+ o[44] = x11 >>> 0 & 0xff;
+ o[45] = x11 >>> 8 & 0xff;
+ o[46] = x11 >>> 16 & 0xff;
+ o[47] = x11 >>> 24 & 0xff;
+
+ o[48] = x12 >>> 0 & 0xff;
+ o[49] = x12 >>> 8 & 0xff;
+ o[50] = x12 >>> 16 & 0xff;
+ o[51] = x12 >>> 24 & 0xff;
+
+ o[52] = x13 >>> 0 & 0xff;
+ o[53] = x13 >>> 8 & 0xff;
+ o[54] = x13 >>> 16 & 0xff;
+ o[55] = x13 >>> 24 & 0xff;
+
+ o[56] = x14 >>> 0 & 0xff;
+ o[57] = x14 >>> 8 & 0xff;
+ o[58] = x14 >>> 16 & 0xff;
+ o[59] = x14 >>> 24 & 0xff;
+
+ o[60] = x15 >>> 0 & 0xff;
+ o[61] = x15 >>> 8 & 0xff;
+ o[62] = x15 >>> 16 & 0xff;
+ o[63] = x15 >>> 24 & 0xff;
+}
+
+function core_hsalsa20(o,p,k,c) {
+ var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,
+ j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,
+ j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,
+ j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,
+ j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,
+ j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,
+ j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,
+ j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,
+ j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,
+ j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,
+ j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,
+ j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,
+ j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,
+ j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,
+ j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,
+ j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;
+
+ var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
+ x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
+ x15 = j15, u;
+
+ for (var i = 0; i < 20; i += 2) {
+ u = x0 + x12 | 0;
+ x4 ^= u<<7 | u>>>(32-7);
+ u = x4 + x0 | 0;
+ x8 ^= u<<9 | u>>>(32-9);
+ u = x8 + x4 | 0;
+ x12 ^= u<<13 | u>>>(32-13);
+ u = x12 + x8 | 0;
+ x0 ^= u<<18 | u>>>(32-18);
+
+ u = x5 + x1 | 0;
+ x9 ^= u<<7 | u>>>(32-7);
+ u = x9 + x5 | 0;
+ x13 ^= u<<9 | u>>>(32-9);
+ u = x13 + x9 | 0;
+ x1 ^= u<<13 | u>>>(32-13);
+ u = x1 + x13 | 0;
+ x5 ^= u<<18 | u>>>(32-18);
+
+ u = x10 + x6 | 0;
+ x14 ^= u<<7 | u>>>(32-7);
+ u = x14 + x10 | 0;
+ x2 ^= u<<9 | u>>>(32-9);
+ u = x2 + x14 | 0;
+ x6 ^= u<<13 | u>>>(32-13);
+ u = x6 + x2 | 0;
+ x10 ^= u<<18 | u>>>(32-18);
+
+ u = x15 + x11 | 0;
+ x3 ^= u<<7 | u>>>(32-7);
+ u = x3 + x15 | 0;
+ x7 ^= u<<9 | u>>>(32-9);
+ u = x7 + x3 | 0;
+ x11 ^= u<<13 | u>>>(32-13);
+ u = x11 + x7 | 0;
+ x15 ^= u<<18 | u>>>(32-18);
+
+ u = x0 + x3 | 0;
+ x1 ^= u<<7 | u>>>(32-7);
+ u = x1 + x0 | 0;
+ x2 ^= u<<9 | u>>>(32-9);
+ u = x2 + x1 | 0;
+ x3 ^= u<<13 | u>>>(32-13);
+ u = x3 + x2 | 0;
+ x0 ^= u<<18 | u>>>(32-18);
+
+ u = x5 + x4 | 0;
+ x6 ^= u<<7 | u>>>(32-7);
+ u = x6 + x5 | 0;
+ x7 ^= u<<9 | u>>>(32-9);
+ u = x7 + x6 | 0;
+ x4 ^= u<<13 | u>>>(32-13);
+ u = x4 + x7 | 0;
+ x5 ^= u<<18 | u>>>(32-18);
+
+ u = x10 + x9 | 0;
+ x11 ^= u<<7 | u>>>(32-7);
+ u = x11 + x10 | 0;
+ x8 ^= u<<9 | u>>>(32-9);
+ u = x8 + x11 | 0;
+ x9 ^= u<<13 | u>>>(32-13);
+ u = x9 + x8 | 0;
+ x10 ^= u<<18 | u>>>(32-18);
+
+ u = x15 + x14 | 0;
+ x12 ^= u<<7 | u>>>(32-7);
+ u = x12 + x15 | 0;
+ x13 ^= u<<9 | u>>>(32-9);
+ u = x13 + x12 | 0;
+ x14 ^= u<<13 | u>>>(32-13);
+ u = x14 + x13 | 0;
+ x15 ^= u<<18 | u>>>(32-18);
+ }
+
+ o[ 0] = x0 >>> 0 & 0xff;
+ o[ 1] = x0 >>> 8 & 0xff;
+ o[ 2] = x0 >>> 16 & 0xff;
+ o[ 3] = x0 >>> 24 & 0xff;
+
+ o[ 4] = x5 >>> 0 & 0xff;
+ o[ 5] = x5 >>> 8 & 0xff;
+ o[ 6] = x5 >>> 16 & 0xff;
+ o[ 7] = x5 >>> 24 & 0xff;
+
+ o[ 8] = x10 >>> 0 & 0xff;
+ o[ 9] = x10 >>> 8 & 0xff;
+ o[10] = x10 >>> 16 & 0xff;
+ o[11] = x10 >>> 24 & 0xff;
+
+ o[12] = x15 >>> 0 & 0xff;
+ o[13] = x15 >>> 8 & 0xff;
+ o[14] = x15 >>> 16 & 0xff;
+ o[15] = x15 >>> 24 & 0xff;
+
+ o[16] = x6 >>> 0 & 0xff;
+ o[17] = x6 >>> 8 & 0xff;
+ o[18] = x6 >>> 16 & 0xff;
+ o[19] = x6 >>> 24 & 0xff;
+
+ o[20] = x7 >>> 0 & 0xff;
+ o[21] = x7 >>> 8 & 0xff;
+ o[22] = x7 >>> 16 & 0xff;
+ o[23] = x7 >>> 24 & 0xff;
+
+ o[24] = x8 >>> 0 & 0xff;
+ o[25] = x8 >>> 8 & 0xff;
+ o[26] = x8 >>> 16 & 0xff;
+ o[27] = x8 >>> 24 & 0xff;
+
+ o[28] = x9 >>> 0 & 0xff;
+ o[29] = x9 >>> 8 & 0xff;
+ o[30] = x9 >>> 16 & 0xff;
+ o[31] = x9 >>> 24 & 0xff;
+}
+
+function crypto_core_salsa20(out,inp,k,c) {
+ core_salsa20(out,inp,k,c);
+}
+
+function crypto_core_hsalsa20(out,inp,k,c) {
+ core_hsalsa20(out,inp,k,c);
+}
+
+var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]);
+ // "expand 32-byte k"
+
+function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) {
+ var z = new Uint8Array(16), x = new Uint8Array(64);
+ var u, i;
+ for (i = 0; i < 16; i++) z[i] = 0;
+ for (i = 0; i < 8; i++) z[i] = n[i];
+ while (b >= 64) {
+ crypto_core_salsa20(x,z,k,sigma);
+ for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i];
+ u = 1;
+ for (i = 8; i < 16; i++) {
+ u = u + (z[i] & 0xff) | 0;
+ z[i] = u & 0xff;
+ u >>>= 8;
+ }
+ b -= 64;
+ cpos += 64;
+ mpos += 64;
+ }
+ if (b > 0) {
+ crypto_core_salsa20(x,z,k,sigma);
+ for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i];
+ }
+ return 0;
+}
+
+function crypto_stream_salsa20(c,cpos,b,n,k) {
+ var z = new Uint8Array(16), x = new Uint8Array(64);
+ var u, i;
+ for (i = 0; i < 16; i++) z[i] = 0;
+ for (i = 0; i < 8; i++) z[i] = n[i];
+ while (b >= 64) {
+ crypto_core_salsa20(x,z,k,sigma);
+ for (i = 0; i < 64; i++) c[cpos+i] = x[i];
+ u = 1;
+ for (i = 8; i < 16; i++) {
+ u = u + (z[i] & 0xff) | 0;
+ z[i] = u & 0xff;
+ u >>>= 8;
+ }
+ b -= 64;
+ cpos += 64;
+ }
+ if (b > 0) {
+ crypto_core_salsa20(x,z,k,sigma);
+ for (i = 0; i < b; i++) c[cpos+i] = x[i];
+ }
+ return 0;
+}
+
+function crypto_stream(c,cpos,d,n,k) {
+ var s = new Uint8Array(32);
+ crypto_core_hsalsa20(s,n,k,sigma);
+ var sn = new Uint8Array(8);
+ for (var i = 0; i < 8; i++) sn[i] = n[i+16];
+ return crypto_stream_salsa20(c,cpos,d,sn,s);
+}
+
+function crypto_stream_xor(c,cpos,m,mpos,d,n,k) {
+ var s = new Uint8Array(32);
+ crypto_core_hsalsa20(s,n,k,sigma);
+ var sn = new Uint8Array(8);
+ for (var i = 0; i < 8; i++) sn[i] = n[i+16];
+ return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s);
+}
+
+/*
+* Port of Andrew Moon's Poly1305-donna-16. Public domain.
+* https://github.com/floodyberry/poly1305-donna
+*/
+
+var poly1305 = function(key) {
+ this.buffer = new Uint8Array(16);
+ this.r = new Uint16Array(10);
+ this.h = new Uint16Array(10);
+ this.pad = new Uint16Array(8);
+ this.leftover = 0;
+ this.fin = 0;
+
+ var t0, t1, t2, t3, t4, t5, t6, t7;
+
+ t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff;
+ t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
+ t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
+ t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
+ t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
+ this.r[5] = ((t4 >>> 1)) & 0x1ffe;
+ t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
+ t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
+ t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
+ this.r[9] = ((t7 >>> 5)) & 0x007f;
+
+ this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8;
+ this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8;
+ this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8;
+ this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8;
+ this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8;
+ this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8;
+ this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8;
+ this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8;
+};
+
+poly1305.prototype.blocks = function(m, mpos, bytes) {
+ var hibit = this.fin ? 0 : (1 << 11);
+ var t0, t1, t2, t3, t4, t5, t6, t7, c;
+ var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;
+
+ var h0 = this.h[0],
+ h1 = this.h[1],
+ h2 = this.h[2],
+ h3 = this.h[3],
+ h4 = this.h[4],
+ h5 = this.h[5],
+ h6 = this.h[6],
+ h7 = this.h[7],
+ h8 = this.h[8],
+ h9 = this.h[9];
+
+ var r0 = this.r[0],
+ r1 = this.r[1],
+ r2 = this.r[2],
+ r3 = this.r[3],
+ r4 = this.r[4],
+ r5 = this.r[5],
+ r6 = this.r[6],
+ r7 = this.r[7],
+ r8 = this.r[8],
+ r9 = this.r[9];
+
+ while (bytes >= 16) {
+ t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff;
+ t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
+ t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;
+ t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
+ t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;
+ h5 += ((t4 >>> 1)) & 0x1fff;
+ t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
+ t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;
+ t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
+ h9 += ((t7 >>> 5)) | hibit;
+
+ c = 0;
+
+ d0 = c;
+ d0 += h0 * r0;
+ d0 += h1 * (5 * r9);
+ d0 += h2 * (5 * r8);
+ d0 += h3 * (5 * r7);
+ d0 += h4 * (5 * r6);
+ c = (d0 >>> 13); d0 &= 0x1fff;
+ d0 += h5 * (5 * r5);
+ d0 += h6 * (5 * r4);
+ d0 += h7 * (5 * r3);
+ d0 += h8 * (5 * r2);
+ d0 += h9 * (5 * r1);
+ c += (d0 >>> 13); d0 &= 0x1fff;
+
+ d1 = c;
+ d1 += h0 * r1;
+ d1 += h1 * r0;
+ d1 += h2 * (5 * r9);
+ d1 += h3 * (5 * r8);
+ d1 += h4 * (5 * r7);
+ c = (d1 >>> 13); d1 &= 0x1fff;
+ d1 += h5 * (5 * r6);
+ d1 += h6 * (5 * r5);
+ d1 += h7 * (5 * r4);
+ d1 += h8 * (5 * r3);
+ d1 += h9 * (5 * r2);
+ c += (d1 >>> 13); d1 &= 0x1fff;
+
+ d2 = c;
+ d2 += h0 * r2;
+ d2 += h1 * r1;
+ d2 += h2 * r0;
+ d2 += h3 * (5 * r9);
+ d2 += h4 * (5 * r8);
+ c = (d2 >>> 13); d2 &= 0x1fff;
+ d2 += h5 * (5 * r7);
+ d2 += h6 * (5 * r6);
+ d2 += h7 * (5 * r5);
+ d2 += h8 * (5 * r4);
+ d2 += h9 * (5 * r3);
+ c += (d2 >>> 13); d2 &= 0x1fff;
+
+ d3 = c;
+ d3 += h0 * r3;
+ d3 += h1 * r2;
+ d3 += h2 * r1;
+ d3 += h3 * r0;
+ d3 += h4 * (5 * r9);
+ c = (d3 >>> 13); d3 &= 0x1fff;
+ d3 += h5 * (5 * r8);
+ d3 += h6 * (5 * r7);
+ d3 += h7 * (5 * r6);
+ d3 += h8 * (5 * r5);
+ d3 += h9 * (5 * r4);
+ c += (d3 >>> 13); d3 &= 0x1fff;
+
+ d4 = c;
+ d4 += h0 * r4;
+ d4 += h1 * r3;
+ d4 += h2 * r2;
+ d4 += h3 * r1;
+ d4 += h4 * r0;
+ c = (d4 >>> 13); d4 &= 0x1fff;
+ d4 += h5 * (5 * r9);
+ d4 += h6 * (5 * r8);
+ d4 += h7 * (5 * r7);
+ d4 += h8 * (5 * r6);
+ d4 += h9 * (5 * r5);
+ c += (d4 >>> 13); d4 &= 0x1fff;
+
+ d5 = c;
+ d5 += h0 * r5;
+ d5 += h1 * r4;
+ d5 += h2 * r3;
+ d5 += h3 * r2;
+ d5 += h4 * r1;
+ c = (d5 >>> 13); d5 &= 0x1fff;
+ d5 += h5 * r0;
+ d5 += h6 * (5 * r9);
+ d5 += h7 * (5 * r8);
+ d5 += h8 * (5 * r7);
+ d5 += h9 * (5 * r6);
+ c += (d5 >>> 13); d5 &= 0x1fff;
+
+ d6 = c;
+ d6 += h0 * r6;
+ d6 += h1 * r5;
+ d6 += h2 * r4;
+ d6 += h3 * r3;
+ d6 += h4 * r2;
+ c = (d6 >>> 13); d6 &= 0x1fff;
+ d6 += h5 * r1;
+ d6 += h6 * r0;
+ d6 += h7 * (5 * r9);
+ d6 += h8 * (5 * r8);
+ d6 += h9 * (5 * r7);
+ c += (d6 >>> 13); d6 &= 0x1fff;
+
+ d7 = c;
+ d7 += h0 * r7;
+ d7 += h1 * r6;
+ d7 += h2 * r5;
+ d7 += h3 * r4;
+ d7 += h4 * r3;
+ c = (d7 >>> 13); d7 &= 0x1fff;
+ d7 += h5 * r2;
+ d7 += h6 * r1;
+ d7 += h7 * r0;
+ d7 += h8 * (5 * r9);
+ d7 += h9 * (5 * r8);
+ c += (d7 >>> 13); d7 &= 0x1fff;
+
+ d8 = c;
+ d8 += h0 * r8;
+ d8 += h1 * r7;
+ d8 += h2 * r6;
+ d8 += h3 * r5;
+ d8 += h4 * r4;
+ c = (d8 >>> 13); d8 &= 0x1fff;
+ d8 += h5 * r3;
+ d8 += h6 * r2;
+ d8 += h7 * r1;
+ d8 += h8 * r0;
+ d8 += h9 * (5 * r9);
+ c += (d8 >>> 13); d8 &= 0x1fff;
+
+ d9 = c;
+ d9 += h0 * r9;
+ d9 += h1 * r8;
+ d9 += h2 * r7;
+ d9 += h3 * r6;
+ d9 += h4 * r5;
+ c = (d9 >>> 13); d9 &= 0x1fff;
+ d9 += h5 * r4;
+ d9 += h6 * r3;
+ d9 += h7 * r2;
+ d9 += h8 * r1;
+ d9 += h9 * r0;
+ c += (d9 >>> 13); d9 &= 0x1fff;
+
+ c = (((c << 2) + c)) | 0;
+ c = (c + d0) | 0;
+ d0 = c & 0x1fff;
+ c = (c >>> 13);
+ d1 += c;
+
+ h0 = d0;
+ h1 = d1;
+ h2 = d2;
+ h3 = d3;
+ h4 = d4;
+ h5 = d5;
+ h6 = d6;
+ h7 = d7;
+ h8 = d8;
+ h9 = d9;
+
+ mpos += 16;
+ bytes -= 16;
+ }
+ this.h[0] = h0;
+ this.h[1] = h1;
+ this.h[2] = h2;
+ this.h[3] = h3;
+ this.h[4] = h4;
+ this.h[5] = h5;
+ this.h[6] = h6;
+ this.h[7] = h7;
+ this.h[8] = h8;
+ this.h[9] = h9;
+};
+
+poly1305.prototype.finish = function(mac, macpos) {
+ var g = new Uint16Array(10);
+ var c, mask, f, i;
+
+ if (this.leftover) {
+ i = this.leftover;
+ this.buffer[i++] = 1;
+ for (; i < 16; i++) this.buffer[i] = 0;
+ this.fin = 1;
+ this.blocks(this.buffer, 0, 16);
+ }
+
+ c = this.h[1] >>> 13;
+ this.h[1] &= 0x1fff;
+ for (i = 2; i < 10; i++) {
+ this.h[i] += c;
+ c = this.h[i] >>> 13;
+ this.h[i] &= 0x1fff;
+ }
+ this.h[0] += (c * 5);
+ c = this.h[0] >>> 13;
+ this.h[0] &= 0x1fff;
+ this.h[1] += c;
+ c = this.h[1] >>> 13;
+ this.h[1] &= 0x1fff;
+ this.h[2] += c;
+
+ g[0] = this.h[0] + 5;
+ c = g[0] >>> 13;
+ g[0] &= 0x1fff;
+ for (i = 1; i < 10; i++) {
+ g[i] = this.h[i] + c;
+ c = g[i] >>> 13;
+ g[i] &= 0x1fff;
+ }
+ g[9] -= (1 << 13);
+
+ mask = (c ^ 1) - 1;
+ for (i = 0; i < 10; i++) g[i] &= mask;
+ mask = ~mask;
+ for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i];
+
+ this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff;
+ this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff;
+ this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff;
+ this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff;
+ this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff;
+ this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff;
+ this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff;
+ this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff;
+
+ f = this.h[0] + this.pad[0];
+ this.h[0] = f & 0xffff;
+ for (i = 1; i < 8; i++) {
+ f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0;
+ this.h[i] = f & 0xffff;
+ }
+
+ mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff;
+ mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff;
+ mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff;
+ mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff;
+ mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff;
+ mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff;
+ mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff;
+ mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff;
+ mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff;
+ mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff;
+ mac[macpos+10] = (this.h[5] >>> 0) & 0xff;
+ mac[macpos+11] = (this.h[5] >>> 8) & 0xff;
+ mac[macpos+12] = (this.h[6] >>> 0) & 0xff;
+ mac[macpos+13] = (this.h[6] >>> 8) & 0xff;
+ mac[macpos+14] = (this.h[7] >>> 0) & 0xff;
+ mac[macpos+15] = (this.h[7] >>> 8) & 0xff;
+};
+
+poly1305.prototype.update = function(m, mpos, bytes) {
+ var i, want;
+
+ if (this.leftover) {
+ want = (16 - this.leftover);
+ if (want > bytes)
+ want = bytes;
+ for (i = 0; i < want; i++)
+ this.buffer[this.leftover + i] = m[mpos+i];
+ bytes -= want;
+ mpos += want;
+ this.leftover += want;
+ if (this.leftover < 16)
+ return;
+ this.blocks(this.buffer, 0, 16);
+ this.leftover = 0;
+ }
+
+ if (bytes >= 16) {
+ want = bytes - (bytes % 16);
+ this.blocks(m, mpos, want);
+ mpos += want;
+ bytes -= want;
+ }
+
+ if (bytes) {
+ for (i = 0; i < bytes; i++)
+ this.buffer[this.leftover + i] = m[mpos+i];
+ this.leftover += bytes;
+ }
+};
+
+function crypto_onetimeauth(out, outpos, m, mpos, n, k) {
+ var s = new poly1305(k);
+ s.update(m, mpos, n);
+ s.finish(out, outpos);
+ return 0;
+}
+
+function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {
+ var x = new Uint8Array(16);
+ crypto_onetimeauth(x,0,m,mpos,n,k);
+ return crypto_verify_16(h,hpos,x,0);
+}
+
+function crypto_secretbox(c,m,d,n,k) {
+ var i;
+ if (d < 32) return -1;
+ crypto_stream_xor(c,0,m,0,d,n,k);
+ crypto_onetimeauth(c, 16, c, 32, d - 32, c);
+ for (i = 0; i < 16; i++) c[i] = 0;
+ return 0;
+}
+
+function crypto_secretbox_open(m,c,d,n,k) {
+ var i;
+ var x = new Uint8Array(32);
+ if (d < 32) return -1;
+ crypto_stream(x,0,32,n,k);
+ if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1;
+ crypto_stream_xor(m,0,c,0,d,n,k);
+ for (i = 0; i < 32; i++) m[i] = 0;
+ return 0;
+}
+
+function set25519(r, a) {
+ var i;
+ for (i = 0; i < 16; i++) r[i] = a[i]|0;
+}
+
+function car25519(o) {
+ var i, v, c = 1;
+ for (i = 0; i < 16; i++) {
+ v = o[i] + c + 65535;
+ c = Math.floor(v / 65536);
+ o[i] = v - c * 65536;
+ }
+ o[0] += c-1 + 37 * (c-1);
+}
+
+function sel25519(p, q, b) {
+ var t, c = ~(b-1);
+ for (var i = 0; i < 16; i++) {
+ t = c & (p[i] ^ q[i]);
+ p[i] ^= t;
+ q[i] ^= t;
+ }
+}
+
+function pack25519(o, n) {
+ var i, j, b;
+ var m = gf(), t = gf();
+ for (i = 0; i < 16; i++) t[i] = n[i];
+ car25519(t);
+ car25519(t);
+ car25519(t);
+ for (j = 0; j < 2; j++) {
+ m[0] = t[0] - 0xffed;
+ for (i = 1; i < 15; i++) {
+ m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);
+ m[i-1] &= 0xffff;
+ }
+ m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);
+ b = (m[15]>>16) & 1;
+ m[14] &= 0xffff;
+ sel25519(t, m, 1-b);
+ }
+ for (i = 0; i < 16; i++) {
+ o[2*i] = t[i] & 0xff;
+ o[2*i+1] = t[i]>>8;
+ }
+}
+
+function neq25519(a, b) {
+ var c = new Uint8Array(32), d = new Uint8Array(32);
+ pack25519(c, a);
+ pack25519(d, b);
+ return crypto_verify_32(c, 0, d, 0);
+}
+
+function par25519(a) {
+ var d = new Uint8Array(32);
+ pack25519(d, a);
+ return d[0] & 1;
+}
+
+function unpack25519(o, n) {
+ var i;
+ for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);
+ o[15] &= 0x7fff;
+}
+
+function A(o, a, b) {
+ for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];
+}
+
+function Z(o, a, b) {
+ for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];
+}
+
+function M(o, a, b) {
+ var v, c,
+ t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
+ t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
+ t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
+ t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
+ b0 = b[0],
+ b1 = b[1],
+ b2 = b[2],
+ b3 = b[3],
+ b4 = b[4],
+ b5 = b[5],
+ b6 = b[6],
+ b7 = b[7],
+ b8 = b[8],
+ b9 = b[9],
+ b10 = b[10],
+ b11 = b[11],
+ b12 = b[12],
+ b13 = b[13],
+ b14 = b[14],
+ b15 = b[15];
+
+ v = a[0];
+ t0 += v * b0;
+ t1 += v * b1;
+ t2 += v * b2;
+ t3 += v * b3;
+ t4 += v * b4;
+ t5 += v * b5;
+ t6 += v * b6;
+ t7 += v * b7;
+ t8 += v * b8;
+ t9 += v * b9;
+ t10 += v * b10;
+ t11 += v * b11;
+ t12 += v * b12;
+ t13 += v * b13;
+ t14 += v * b14;
+ t15 += v * b15;
+ v = a[1];
+ t1 += v * b0;
+ t2 += v * b1;
+ t3 += v * b2;
+ t4 += v * b3;
+ t5 += v * b4;
+ t6 += v * b5;
+ t7 += v * b6;
+ t8 += v * b7;
+ t9 += v * b8;
+ t10 += v * b9;
+ t11 += v * b10;
+ t12 += v * b11;
+ t13 += v * b12;
+ t14 += v * b13;
+ t15 += v * b14;
+ t16 += v * b15;
+ v = a[2];
+ t2 += v * b0;
+ t3 += v * b1;
+ t4 += v * b2;
+ t5 += v * b3;
+ t6 += v * b4;
+ t7 += v * b5;
+ t8 += v * b6;
+ t9 += v * b7;
+ t10 += v * b8;
+ t11 += v * b9;
+ t12 += v * b10;
+ t13 += v * b11;
+ t14 += v * b12;
+ t15 += v * b13;
+ t16 += v * b14;
+ t17 += v * b15;
+ v = a[3];
+ t3 += v * b0;
+ t4 += v * b1;
+ t5 += v * b2;
+ t6 += v * b3;
+ t7 += v * b4;
+ t8 += v * b5;
+ t9 += v * b6;
+ t10 += v * b7;
+ t11 += v * b8;
+ t12 += v * b9;
+ t13 += v * b10;
+ t14 += v * b11;
+ t15 += v * b12;
+ t16 += v * b13;
+ t17 += v * b14;
+ t18 += v * b15;
+ v = a[4];
+ t4 += v * b0;
+ t5 += v * b1;
+ t6 += v * b2;
+ t7 += v * b3;
+ t8 += v * b4;
+ t9 += v * b5;
+ t10 += v * b6;
+ t11 += v * b7;
+ t12 += v * b8;
+ t13 += v * b9;
+ t14 += v * b10;
+ t15 += v * b11;
+ t16 += v * b12;
+ t17 += v * b13;
+ t18 += v * b14;
+ t19 += v * b15;
+ v = a[5];
+ t5 += v * b0;
+ t6 += v * b1;
+ t7 += v * b2;
+ t8 += v * b3;
+ t9 += v * b4;
+ t10 += v * b5;
+ t11 += v * b6;
+ t12 += v * b7;
+ t13 += v * b8;
+ t14 += v * b9;
+ t15 += v * b10;
+ t16 += v * b11;
+ t17 += v * b12;
+ t18 += v * b13;
+ t19 += v * b14;
+ t20 += v * b15;
+ v = a[6];
+ t6 += v * b0;
+ t7 += v * b1;
+ t8 += v * b2;
+ t9 += v * b3;
+ t10 += v * b4;
+ t11 += v * b5;
+ t12 += v * b6;
+ t13 += v * b7;
+ t14 += v * b8;
+ t15 += v * b9;
+ t16 += v * b10;
+ t17 += v * b11;
+ t18 += v * b12;
+ t19 += v * b13;
+ t20 += v * b14;
+ t21 += v * b15;
+ v = a[7];
+ t7 += v * b0;
+ t8 += v * b1;
+ t9 += v * b2;
+ t10 += v * b3;
+ t11 += v * b4;
+ t12 += v * b5;
+ t13 += v * b6;
+ t14 += v * b7;
+ t15 += v * b8;
+ t16 += v * b9;
+ t17 += v * b10;
+ t18 += v * b11;
+ t19 += v * b12;
+ t20 += v * b13;
+ t21 += v * b14;
+ t22 += v * b15;
+ v = a[8];
+ t8 += v * b0;
+ t9 += v * b1;
+ t10 += v * b2;
+ t11 += v * b3;
+ t12 += v * b4;
+ t13 += v * b5;
+ t14 += v * b6;
+ t15 += v * b7;
+ t16 += v * b8;
+ t17 += v * b9;
+ t18 += v * b10;
+ t19 += v * b11;
+ t20 += v * b12;
+ t21 += v * b13;
+ t22 += v * b14;
+ t23 += v * b15;
+ v = a[9];
+ t9 += v * b0;
+ t10 += v * b1;
+ t11 += v * b2;
+ t12 += v * b3;
+ t13 += v * b4;
+ t14 += v * b5;
+ t15 += v * b6;
+ t16 += v * b7;
+ t17 += v * b8;
+ t18 += v * b9;
+ t19 += v * b10;
+ t20 += v * b11;
+ t21 += v * b12;
+ t22 += v * b13;
+ t23 += v * b14;
+ t24 += v * b15;
+ v = a[10];
+ t10 += v * b0;
+ t11 += v * b1;
+ t12 += v * b2;
+ t13 += v * b3;
+ t14 += v * b4;
+ t15 += v * b5;
+ t16 += v * b6;
+ t17 += v * b7;
+ t18 += v * b8;
+ t19 += v * b9;
+ t20 += v * b10;
+ t21 += v * b11;
+ t22 += v * b12;
+ t23 += v * b13;
+ t24 += v * b14;
+ t25 += v * b15;
+ v = a[11];
+ t11 += v * b0;
+ t12 += v * b1;
+ t13 += v * b2;
+ t14 += v * b3;
+ t15 += v * b4;
+ t16 += v * b5;
+ t17 += v * b6;
+ t18 += v * b7;
+ t19 += v * b8;
+ t20 += v * b9;
+ t21 += v * b10;
+ t22 += v * b11;
+ t23 += v * b12;
+ t24 += v * b13;
+ t25 += v * b14;
+ t26 += v * b15;
+ v = a[12];
+ t12 += v * b0;
+ t13 += v * b1;
+ t14 += v * b2;
+ t15 += v * b3;
+ t16 += v * b4;
+ t17 += v * b5;
+ t18 += v * b6;
+ t19 += v * b7;
+ t20 += v * b8;
+ t21 += v * b9;
+ t22 += v * b10;
+ t23 += v * b11;
+ t24 += v * b12;
+ t25 += v * b13;
+ t26 += v * b14;
+ t27 += v * b15;
+ v = a[13];
+ t13 += v * b0;
+ t14 += v * b1;
+ t15 += v * b2;
+ t16 += v * b3;
+ t17 += v * b4;
+ t18 += v * b5;
+ t19 += v * b6;
+ t20 += v * b7;
+ t21 += v * b8;
+ t22 += v * b9;
+ t23 += v * b10;
+ t24 += v * b11;
+ t25 += v * b12;
+ t26 += v * b13;
+ t27 += v * b14;
+ t28 += v * b15;
+ v = a[14];
+ t14 += v * b0;
+ t15 += v * b1;
+ t16 += v * b2;
+ t17 += v * b3;
+ t18 += v * b4;
+ t19 += v * b5;
+ t20 += v * b6;
+ t21 += v * b7;
+ t22 += v * b8;
+ t23 += v * b9;
+ t24 += v * b10;
+ t25 += v * b11;
+ t26 += v * b12;
+ t27 += v * b13;
+ t28 += v * b14;
+ t29 += v * b15;
+ v = a[15];
+ t15 += v * b0;
+ t16 += v * b1;
+ t17 += v * b2;
+ t18 += v * b3;
+ t19 += v * b4;
+ t20 += v * b5;
+ t21 += v * b6;
+ t22 += v * b7;
+ t23 += v * b8;
+ t24 += v * b9;
+ t25 += v * b10;
+ t26 += v * b11;
+ t27 += v * b12;
+ t28 += v * b13;
+ t29 += v * b14;
+ t30 += v * b15;
+
+ t0 += 38 * t16;
+ t1 += 38 * t17;
+ t2 += 38 * t18;
+ t3 += 38 * t19;
+ t4 += 38 * t20;
+ t5 += 38 * t21;
+ t6 += 38 * t22;
+ t7 += 38 * t23;
+ t8 += 38 * t24;
+ t9 += 38 * t25;
+ t10 += 38 * t26;
+ t11 += 38 * t27;
+ t12 += 38 * t28;
+ t13 += 38 * t29;
+ t14 += 38 * t30;
+ // t15 left as is
+
+ // first car
+ c = 1;
+ v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
+ v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
+ v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
+ v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
+ v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
+ v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
+ v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
+ v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
+ v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
+ v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
+ v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
+ v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
+ v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
+ v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
+ v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
+ v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
+ t0 += c-1 + 37 * (c-1);
+
+ // second car
+ c = 1;
+ v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
+ v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
+ v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
+ v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
+ v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
+ v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
+ v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
+ v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
+ v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
+ v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
+ v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
+ v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
+ v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
+ v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
+ v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
+ v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
+ t0 += c-1 + 37 * (c-1);
+
+ o[ 0] = t0;
+ o[ 1] = t1;
+ o[ 2] = t2;
+ o[ 3] = t3;
+ o[ 4] = t4;
+ o[ 5] = t5;
+ o[ 6] = t6;
+ o[ 7] = t7;
+ o[ 8] = t8;
+ o[ 9] = t9;
+ o[10] = t10;
+ o[11] = t11;
+ o[12] = t12;
+ o[13] = t13;
+ o[14] = t14;
+ o[15] = t15;
+}
+
+function S(o, a) {
+ M(o, a, a);
+}
+
+function inv25519(o, i) {
+ var c = gf();
+ var a;
+ for (a = 0; a < 16; a++) c[a] = i[a];
+ for (a = 253; a >= 0; a--) {
+ S(c, c);
+ if(a !== 2 && a !== 4) M(c, c, i);
+ }
+ for (a = 0; a < 16; a++) o[a] = c[a];
+}
+
+function pow2523(o, i) {
+ var c = gf();
+ var a;
+ for (a = 0; a < 16; a++) c[a] = i[a];
+ for (a = 250; a >= 0; a--) {
+ S(c, c);
+ if(a !== 1) M(c, c, i);
+ }
+ for (a = 0; a < 16; a++) o[a] = c[a];
+}
+
+function crypto_scalarmult(q, n, p) {
+ var z = new Uint8Array(32);
+ var x = new Float64Array(80), r, i;
+ var a = gf(), b = gf(), c = gf(),
+ d = gf(), e = gf(), f = gf();
+ for (i = 0; i < 31; i++) z[i] = n[i];
+ z[31]=(n[31]&127)|64;
+ z[0]&=248;
+ unpack25519(x,p);
+ for (i = 0; i < 16; i++) {
+ b[i]=x[i];
+ d[i]=a[i]=c[i]=0;
+ }
+ a[0]=d[0]=1;
+ for (i=254; i>=0; --i) {
+ r=(z[i>>>3]>>>(i&7))&1;
+ sel25519(a,b,r);
+ sel25519(c,d,r);
+ A(e,a,c);
+ Z(a,a,c);
+ A(c,b,d);
+ Z(b,b,d);
+ S(d,e);
+ S(f,a);
+ M(a,c,a);
+ M(c,b,e);
+ A(e,a,c);
+ Z(a,a,c);
+ S(b,a);
+ Z(c,d,f);
+ M(a,c,_121665);
+ A(a,a,d);
+ M(c,c,a);
+ M(a,d,f);
+ M(d,b,x);
+ S(b,e);
+ sel25519(a,b,r);
+ sel25519(c,d,r);
+ }
+ for (i = 0; i < 16; i++) {
+ x[i+16]=a[i];
+ x[i+32]=c[i];
+ x[i+48]=b[i];
+ x[i+64]=d[i];
+ }
+ var x32 = x.subarray(32);
+ var x16 = x.subarray(16);
+ inv25519(x32,x32);
+ M(x16,x16,x32);
+ pack25519(q,x16);
+ return 0;
+}
+
+function crypto_scalarmult_base(q, n) {
+ return crypto_scalarmult(q, n, _9);
+}
+
+function crypto_box_keypair(y, x) {
+ randombytes(x, 32);
+ return crypto_scalarmult_base(y, x);
+}
+
+function crypto_box_beforenm(k, y, x) {
+ var s = new Uint8Array(32);
+ crypto_scalarmult(s, x, y);
+ return crypto_core_hsalsa20(k, _0, s, sigma);
+}
+
+var crypto_box_afternm = crypto_secretbox;
+var crypto_box_open_afternm = crypto_secretbox_open;
+
+function crypto_box(c, m, d, n, y, x) {
+ var k = new Uint8Array(32);
+ crypto_box_beforenm(k, y, x);
+ return crypto_box_afternm(c, m, d, n, k);
+}
+
+function crypto_box_open(m, c, d, n, y, x) {
+ var k = new Uint8Array(32);
+ crypto_box_beforenm(k, y, x);
+ return crypto_box_open_afternm(m, c, d, n, k);
+}
+
+var K = [
+ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
+ 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
+ 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
+ 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
+ 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
+ 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
+ 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
+ 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
+ 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
+ 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
+ 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
+ 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
+ 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
+ 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
+ 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
+ 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
+ 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
+ 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
+ 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
+ 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
+ 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
+ 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
+ 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
+ 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
+ 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
+ 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
+ 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
+ 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
+ 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
+ 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
+ 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
+ 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
+ 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
+ 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
+ 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
+ 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
+ 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
+ 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
+ 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
+ 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
+];
+
+function crypto_hashblocks_hl(hh, hl, m, n) {
+ var wh = new Int32Array(16), wl = new Int32Array(16),
+ bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,
+ bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,
+ th, tl, i, j, h, l, a, b, c, d;
+
+ var ah0 = hh[0],
+ ah1 = hh[1],
+ ah2 = hh[2],
+ ah3 = hh[3],
+ ah4 = hh[4],
+ ah5 = hh[5],
+ ah6 = hh[6],
+ ah7 = hh[7],
+
+ al0 = hl[0],
+ al1 = hl[1],
+ al2 = hl[2],
+ al3 = hl[3],
+ al4 = hl[4],
+ al5 = hl[5],
+ al6 = hl[6],
+ al7 = hl[7];
+
+ var pos = 0;
+ while (n >= 128) {
+ for (i = 0; i < 16; i++) {
+ j = 8 * i + pos;
+ wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];
+ wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];
+ }
+ for (i = 0; i < 80; i++) {
+ bh0 = ah0;
+ bh1 = ah1;
+ bh2 = ah2;
+ bh3 = ah3;
+ bh4 = ah4;
+ bh5 = ah5;
+ bh6 = ah6;
+ bh7 = ah7;
+
+ bl0 = al0;
+ bl1 = al1;
+ bl2 = al2;
+ bl3 = al3;
+ bl4 = al4;
+ bl5 = al5;
+ bl6 = al6;
+ bl7 = al7;
+
+ // add
+ h = ah7;
+ l = al7;
+
+ a = l & 0xffff; b = l >>> 16;
+ c = h & 0xffff; d = h >>> 16;
+
+ // Sigma1
+ h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));
+ l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ // Ch
+ h = (ah4 & ah5) ^ (~ah4 & ah6);
+ l = (al4 & al5) ^ (~al4 & al6);
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ // K
+ h = K[i*2];
+ l = K[i*2+1];
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ // w
+ h = wh[i%16];
+ l = wl[i%16];
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ b += a >>> 16;
+ c += b >>> 16;
+ d += c >>> 16;
+
+ th = c & 0xffff | d << 16;
+ tl = a & 0xffff | b << 16;
+
+ // add
+ h = th;
+ l = tl;
+
+ a = l & 0xffff; b = l >>> 16;
+ c = h & 0xffff; d = h >>> 16;
+
+ // Sigma0
+ h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));
+ l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ // Maj
+ h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);
+ l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ b += a >>> 16;
+ c += b >>> 16;
+ d += c >>> 16;
+
+ bh7 = (c & 0xffff) | (d << 16);
+ bl7 = (a & 0xffff) | (b << 16);
+
+ // add
+ h = bh3;
+ l = bl3;
+
+ a = l & 0xffff; b = l >>> 16;
+ c = h & 0xffff; d = h >>> 16;
+
+ h = th;
+ l = tl;
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ b += a >>> 16;
+ c += b >>> 16;
+ d += c >>> 16;
+
+ bh3 = (c & 0xffff) | (d << 16);
+ bl3 = (a & 0xffff) | (b << 16);
+
+ ah1 = bh0;
+ ah2 = bh1;
+ ah3 = bh2;
+ ah4 = bh3;
+ ah5 = bh4;
+ ah6 = bh5;
+ ah7 = bh6;
+ ah0 = bh7;
+
+ al1 = bl0;
+ al2 = bl1;
+ al3 = bl2;
+ al4 = bl3;
+ al5 = bl4;
+ al6 = bl5;
+ al7 = bl6;
+ al0 = bl7;
+
+ if (i%16 === 15) {
+ for (j = 0; j < 16; j++) {
+ // add
+ h = wh[j];
+ l = wl[j];
+
+ a = l & 0xffff; b = l >>> 16;
+ c = h & 0xffff; d = h >>> 16;
+
+ h = wh[(j+9)%16];
+ l = wl[(j+9)%16];
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ // sigma0
+ th = wh[(j+1)%16];
+ tl = wl[(j+1)%16];
+ h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);
+ l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ // sigma1
+ th = wh[(j+14)%16];
+ tl = wl[(j+14)%16];
+ h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);
+ l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ b += a >>> 16;
+ c += b >>> 16;
+ d += c >>> 16;
+
+ wh[j] = (c & 0xffff) | (d << 16);
+ wl[j] = (a & 0xffff) | (b << 16);
+ }
+ }
+ }
+
+ // add
+ h = ah0;
+ l = al0;
+
+ a = l & 0xffff; b = l >>> 16;
+ c = h & 0xffff; d = h >>> 16;
+
+ h = hh[0];
+ l = hl[0];
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ b += a >>> 16;
+ c += b >>> 16;
+ d += c >>> 16;
+
+ hh[0] = ah0 = (c & 0xffff) | (d << 16);
+ hl[0] = al0 = (a & 0xffff) | (b << 16);
+
+ h = ah1;
+ l = al1;
+
+ a = l & 0xffff; b = l >>> 16;
+ c = h & 0xffff; d = h >>> 16;
+
+ h = hh[1];
+ l = hl[1];
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ b += a >>> 16;
+ c += b >>> 16;
+ d += c >>> 16;
+
+ hh[1] = ah1 = (c & 0xffff) | (d << 16);
+ hl[1] = al1 = (a & 0xffff) | (b << 16);
+
+ h = ah2;
+ l = al2;
+
+ a = l & 0xffff; b = l >>> 16;
+ c = h & 0xffff; d = h >>> 16;
+
+ h = hh[2];
+ l = hl[2];
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ b += a >>> 16;
+ c += b >>> 16;
+ d += c >>> 16;
+
+ hh[2] = ah2 = (c & 0xffff) | (d << 16);
+ hl[2] = al2 = (a & 0xffff) | (b << 16);
+
+ h = ah3;
+ l = al3;
+
+ a = l & 0xffff; b = l >>> 16;
+ c = h & 0xffff; d = h >>> 16;
+
+ h = hh[3];
+ l = hl[3];
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ b += a >>> 16;
+ c += b >>> 16;
+ d += c >>> 16;
+
+ hh[3] = ah3 = (c & 0xffff) | (d << 16);
+ hl[3] = al3 = (a & 0xffff) | (b << 16);
+
+ h = ah4;
+ l = al4;
+
+ a = l & 0xffff; b = l >>> 16;
+ c = h & 0xffff; d = h >>> 16;
+
+ h = hh[4];
+ l = hl[4];
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ b += a >>> 16;
+ c += b >>> 16;
+ d += c >>> 16;
+
+ hh[4] = ah4 = (c & 0xffff) | (d << 16);
+ hl[4] = al4 = (a & 0xffff) | (b << 16);
+
+ h = ah5;
+ l = al5;
+
+ a = l & 0xffff; b = l >>> 16;
+ c = h & 0xffff; d = h >>> 16;
+
+ h = hh[5];
+ l = hl[5];
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ b += a >>> 16;
+ c += b >>> 16;
+ d += c >>> 16;
+
+ hh[5] = ah5 = (c & 0xffff) | (d << 16);
+ hl[5] = al5 = (a & 0xffff) | (b << 16);
+
+ h = ah6;
+ l = al6;
+
+ a = l & 0xffff; b = l >>> 16;
+ c = h & 0xffff; d = h >>> 16;
+
+ h = hh[6];
+ l = hl[6];
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ b += a >>> 16;
+ c += b >>> 16;
+ d += c >>> 16;
+
+ hh[6] = ah6 = (c & 0xffff) | (d << 16);
+ hl[6] = al6 = (a & 0xffff) | (b << 16);
+
+ h = ah7;
+ l = al7;
+
+ a = l & 0xffff; b = l >>> 16;
+ c = h & 0xffff; d = h >>> 16;
+
+ h = hh[7];
+ l = hl[7];
+
+ a += l & 0xffff; b += l >>> 16;
+ c += h & 0xffff; d += h >>> 16;
+
+ b += a >>> 16;
+ c += b >>> 16;
+ d += c >>> 16;
+
+ hh[7] = ah7 = (c & 0xffff) | (d << 16);
+ hl[7] = al7 = (a & 0xffff) | (b << 16);
+
+ pos += 128;
+ n -= 128;
+ }
+
+ return n;
+}
+
+function crypto_hash(out, m, n) {
+ var hh = new Int32Array(8),
+ hl = new Int32Array(8),
+ x = new Uint8Array(256),
+ i, b = n;
+
+ hh[0] = 0x6a09e667;
+ hh[1] = 0xbb67ae85;
+ hh[2] = 0x3c6ef372;
+ hh[3] = 0xa54ff53a;
+ hh[4] = 0x510e527f;
+ hh[5] = 0x9b05688c;
+ hh[6] = 0x1f83d9ab;
+ hh[7] = 0x5be0cd19;
+
+ hl[0] = 0xf3bcc908;
+ hl[1] = 0x84caa73b;
+ hl[2] = 0xfe94f82b;
+ hl[3] = 0x5f1d36f1;
+ hl[4] = 0xade682d1;
+ hl[5] = 0x2b3e6c1f;
+ hl[6] = 0xfb41bd6b;
+ hl[7] = 0x137e2179;
+
+ crypto_hashblocks_hl(hh, hl, m, n);
+ n %= 128;
+
+ for (i = 0; i < n; i++) x[i] = m[b-n+i];
+ x[n] = 128;
+
+ n = 256-128*(n<112?1:0);
+ x[n-9] = 0;
+ ts64(x, n-8, (b / 0x20000000) | 0, b << 3);
+ crypto_hashblocks_hl(hh, hl, x, n);
+
+ for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);
+
+ return 0;
+}
+
+function add(p, q) {
+ var a = gf(), b = gf(), c = gf(),
+ d = gf(), e = gf(), f = gf(),
+ g = gf(), h = gf(), t = gf();
+
+ Z(a, p[1], p[0]);
+ Z(t, q[1], q[0]);
+ M(a, a, t);
+ A(b, p[0], p[1]);
+ A(t, q[0], q[1]);
+ M(b, b, t);
+ M(c, p[3], q[3]);
+ M(c, c, D2);
+ M(d, p[2], q[2]);
+ A(d, d, d);
+ Z(e, b, a);
+ Z(f, d, c);
+ A(g, d, c);
+ A(h, b, a);
+
+ M(p[0], e, f);
+ M(p[1], h, g);
+ M(p[2], g, f);
+ M(p[3], e, h);
+}
+
+function cswap(p, q, b) {
+ var i;
+ for (i = 0; i < 4; i++) {
+ sel25519(p[i], q[i], b);
+ }
+}
+
+function pack(r, p) {
+ var tx = gf(), ty = gf(), zi = gf();
+ inv25519(zi, p[2]);
+ M(tx, p[0], zi);
+ M(ty, p[1], zi);
+ pack25519(r, ty);
+ r[31] ^= par25519(tx) << 7;
+}
+
+function scalarmult(p, q, s) {
+ var b, i;
+ set25519(p[0], gf0);
+ set25519(p[1], gf1);
+ set25519(p[2], gf1);
+ set25519(p[3], gf0);
+ for (i = 255; i >= 0; --i) {
+ b = (s[(i/8)|0] >> (i&7)) & 1;
+ cswap(p, q, b);
+ add(q, p);
+ add(p, p);
+ cswap(p, q, b);
+ }
+}
+
+function scalarbase(p, s) {
+ var q = [gf(), gf(), gf(), gf()];
+ set25519(q[0], X);
+ set25519(q[1], Y);
+ set25519(q[2], gf1);
+ M(q[3], X, Y);
+ scalarmult(p, q, s);
+}
+
+function crypto_sign_keypair(pk, sk, seeded) {
+ var d = new Uint8Array(64);
+ var p = [gf(), gf(), gf(), gf()];
+ var i;
+
+ if (!seeded) randombytes(sk, 32);
+ crypto_hash(d, sk, 32);
+ d[0] &= 248;
+ d[31] &= 127;
+ d[31] |= 64;
+
+ scalarbase(p, d);
+ pack(pk, p);
+
+ for (i = 0; i < 32; i++) sk[i+32] = pk[i];
+ return 0;
+}
+
+var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);
+
+function modL(r, x) {
+ var carry, i, j, k;
+ for (i = 63; i >= 32; --i) {
+ carry = 0;
+ for (j = i - 32, k = i - 12; j < k; ++j) {
+ x[j] += carry - 16 * x[i] * L[j - (i - 32)];
+ carry = Math.floor((x[j] + 128) / 256);
+ x[j] -= carry * 256;
+ }
+ x[j] += carry;
+ x[i] = 0;
+ }
+ carry = 0;
+ for (j = 0; j < 32; j++) {
+ x[j] += carry - (x[31] >> 4) * L[j];
+ carry = x[j] >> 8;
+ x[j] &= 255;
+ }
+ for (j = 0; j < 32; j++) x[j] -= carry * L[j];
+ for (i = 0; i < 32; i++) {
+ x[i+1] += x[i] >> 8;
+ r[i] = x[i] & 255;
+ }
+}
+
+function reduce(r) {
+ var x = new Float64Array(64), i;
+ for (i = 0; i < 64; i++) x[i] = r[i];
+ for (i = 0; i < 64; i++) r[i] = 0;
+ modL(r, x);
+}
+
+// Note: difference from C - smlen returned, not passed as argument.
+function crypto_sign(sm, m, n, sk) {
+ var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);
+ var i, j, x = new Float64Array(64);
+ var p = [gf(), gf(), gf(), gf()];
+
+ crypto_hash(d, sk, 32);
+ d[0] &= 248;
+ d[31] &= 127;
+ d[31] |= 64;
+
+ var smlen = n + 64;
+ for (i = 0; i < n; i++) sm[64 + i] = m[i];
+ for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
+
+ crypto_hash(r, sm.subarray(32), n+32);
+ reduce(r);
+ scalarbase(p, r);
+ pack(sm, p);
+
+ for (i = 32; i < 64; i++) sm[i] = sk[i];
+ crypto_hash(h, sm, n + 64);
+ reduce(h);
+
+ for (i = 0; i < 64; i++) x[i] = 0;
+ for (i = 0; i < 32; i++) x[i] = r[i];
+ for (i = 0; i < 32; i++) {
+ for (j = 0; j < 32; j++) {
+ x[i+j] += h[i] * d[j];
+ }
+ }
+
+ modL(sm.subarray(32), x);
+ return smlen;
+}
+
+function unpackneg(r, p) {
+ var t = gf(), chk = gf(), num = gf(),
+ den = gf(), den2 = gf(), den4 = gf(),
+ den6 = gf();
+
+ set25519(r[2], gf1);
+ unpack25519(r[1], p);
+ S(num, r[1]);
+ M(den, num, D);
+ Z(num, num, r[2]);
+ A(den, r[2], den);
+
+ S(den2, den);
+ S(den4, den2);
+ M(den6, den4, den2);
+ M(t, den6, num);
+ M(t, t, den);
+
+ pow2523(t, t);
+ M(t, t, num);
+ M(t, t, den);
+ M(t, t, den);
+ M(r[0], t, den);
+
+ S(chk, r[0]);
+ M(chk, chk, den);
+ if (neq25519(chk, num)) M(r[0], r[0], I);
+
+ S(chk, r[0]);
+ M(chk, chk, den);
+ if (neq25519(chk, num)) return -1;
+
+ if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);
+
+ M(r[3], r[0], r[1]);
+ return 0;
+}
+
+function crypto_sign_open(m, sm, n, pk) {
+ var i;
+ var t = new Uint8Array(32), h = new Uint8Array(64);
+ var p = [gf(), gf(), gf(), gf()],
+ q = [gf(), gf(), gf(), gf()];
+
+ if (n < 64) return -1;
+
+ if (unpackneg(q, pk)) return -1;
+
+ for (i = 0; i < n; i++) m[i] = sm[i];
+ for (i = 0; i < 32; i++) m[i+32] = pk[i];
+ crypto_hash(h, m, n);
+ reduce(h);
+ scalarmult(p, q, h);
+
+ scalarbase(q, sm.subarray(32));
+ add(p, q);
+ pack(t, p);
+
+ n -= 64;
+ if (crypto_verify_32(sm, 0, t, 0)) {
+ for (i = 0; i < n; i++) m[i] = 0;
+ return -1;
+ }
+
+ for (i = 0; i < n; i++) m[i] = sm[i + 64];
+ return n;
+}
+
+var crypto_secretbox_KEYBYTES = 32,
+ crypto_secretbox_NONCEBYTES = 24,
+ crypto_secretbox_ZEROBYTES = 32,
+ crypto_secretbox_BOXZEROBYTES = 16,
+ crypto_scalarmult_BYTES = 32,
+ crypto_scalarmult_SCALARBYTES = 32,
+ crypto_box_PUBLICKEYBYTES = 32,
+ crypto_box_SECRETKEYBYTES = 32,
+ crypto_box_BEFORENMBYTES = 32,
+ crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES,
+ crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES,
+ crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES,
+ crypto_sign_BYTES = 64,
+ crypto_sign_PUBLICKEYBYTES = 32,
+ crypto_sign_SECRETKEYBYTES = 64,
+ crypto_sign_SEEDBYTES = 32,
+ crypto_hash_BYTES = 64;
+
+nacl.lowlevel = {
+ crypto_core_hsalsa20: crypto_core_hsalsa20,
+ crypto_stream_xor: crypto_stream_xor,
+ crypto_stream: crypto_stream,
+ crypto_stream_salsa20_xor: crypto_stream_salsa20_xor,
+ crypto_stream_salsa20: crypto_stream_salsa20,
+ crypto_onetimeauth: crypto_onetimeauth,
+ crypto_onetimeauth_verify: crypto_onetimeauth_verify,
+ crypto_verify_16: crypto_verify_16,
+ crypto_verify_32: crypto_verify_32,
+ crypto_secretbox: crypto_secretbox,
+ crypto_secretbox_open: crypto_secretbox_open,
+ crypto_scalarmult: crypto_scalarmult,
+ crypto_scalarmult_base: crypto_scalarmult_base,
+ crypto_box_beforenm: crypto_box_beforenm,
+ crypto_box_afternm: crypto_box_afternm,
+ crypto_box: crypto_box,
+ crypto_box_open: crypto_box_open,
+ crypto_box_keypair: crypto_box_keypair,
+ crypto_hash: crypto_hash,
+ crypto_sign: crypto_sign,
+ crypto_sign_keypair: crypto_sign_keypair,
+ crypto_sign_open: crypto_sign_open,
+
+ crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES,
+ crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES,
+ crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES,
+ crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES,
+ crypto_scalarmult_BYTES: crypto_scalarmult_BYTES,
+ crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES,
+ crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES,
+ crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES,
+ crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES,
+ crypto_box_NONCEBYTES: crypto_box_NONCEBYTES,
+ crypto_box_ZEROBYTES: crypto_box_ZEROBYTES,
+ crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES,
+ crypto_sign_BYTES: crypto_sign_BYTES,
+ crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES,
+ crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES,
+ crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES,
+ crypto_hash_BYTES: crypto_hash_BYTES,
+
+ gf: gf,
+ D: D,
+ L: L,
+ pack25519: pack25519,
+ unpack25519: unpack25519,
+ M: M,
+ A: A,
+ S: S,
+ Z: Z,
+ pow2523: pow2523,
+ add: add,
+ set25519: set25519,
+ modL: modL,
+ scalarmult: scalarmult,
+ scalarbase: scalarbase,
+};
+
+/* High-level API */
+
+function checkLengths(k, n) {
+ if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size');
+ if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size');
+}
+
+function checkBoxLengths(pk, sk) {
+ if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size');
+ if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size');
+}
+
+function checkArrayTypes() {
+ for (var i = 0; i < arguments.length; i++) {
+ if (!(arguments[i] instanceof Uint8Array))
+ throw new TypeError('unexpected type, use Uint8Array');
+ }
+}
+
+function cleanup(arr) {
+ for (var i = 0; i < arr.length; i++) arr[i] = 0;
+}
+
+nacl.randomBytes = function(n) {
+ var b = new Uint8Array(n);
+ randombytes(b, n);
+ return b;
+};
+
+nacl.secretbox = function(msg, nonce, key) {
+ checkArrayTypes(msg, nonce, key);
+ checkLengths(key, nonce);
+ var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);
+ var c = new Uint8Array(m.length);
+ for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i];
+ crypto_secretbox(c, m, m.length, nonce, key);
+ return c.subarray(crypto_secretbox_BOXZEROBYTES);
+};
+
+nacl.secretbox.open = function(box, nonce, key) {
+ checkArrayTypes(box, nonce, key);
+ checkLengths(key, nonce);
+ var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);
+ var m = new Uint8Array(c.length);
+ for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i];
+ if (c.length < 32) return null;
+ if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null;
+ return m.subarray(crypto_secretbox_ZEROBYTES);
+};
+
+nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;
+nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;
+nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;
+
+nacl.scalarMult = function(n, p) {
+ checkArrayTypes(n, p);
+ if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
+ if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');
+ var q = new Uint8Array(crypto_scalarmult_BYTES);
+ crypto_scalarmult(q, n, p);
+ return q;
+};
+
+nacl.scalarMult.base = function(n) {
+ checkArrayTypes(n);
+ if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
+ var q = new Uint8Array(crypto_scalarmult_BYTES);
+ crypto_scalarmult_base(q, n);
+ return q;
+};
+
+nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;
+nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;
+
+nacl.box = function(msg, nonce, publicKey, secretKey) {
+ var k = nacl.box.before(publicKey, secretKey);
+ return nacl.secretbox(msg, nonce, k);
+};
+
+nacl.box.before = function(publicKey, secretKey) {
+ checkArrayTypes(publicKey, secretKey);
+ checkBoxLengths(publicKey, secretKey);
+ var k = new Uint8Array(crypto_box_BEFORENMBYTES);
+ crypto_box_beforenm(k, publicKey, secretKey);
+ return k;
+};
+
+nacl.box.after = nacl.secretbox;
+
+nacl.box.open = function(msg, nonce, publicKey, secretKey) {
+ var k = nacl.box.before(publicKey, secretKey);
+ return nacl.secretbox.open(msg, nonce, k);
+};
+
+nacl.box.open.after = nacl.secretbox.open;
+
+nacl.box.keyPair = function() {
+ var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
+ var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
+ crypto_box_keypair(pk, sk);
+ return {publicKey: pk, secretKey: sk};
+};
+
+nacl.box.keyPair.fromSecretKey = function(secretKey) {
+ checkArrayTypes(secretKey);
+ if (secretKey.length !== crypto_box_SECRETKEYBYTES)
+ throw new Error('bad secret key size');
+ var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
+ crypto_scalarmult_base(pk, secretKey);
+ return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
+};
+
+nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;
+nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;
+nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;
+nacl.box.nonceLength = crypto_box_NONCEBYTES;
+nacl.box.overheadLength = nacl.secretbox.overheadLength;
+
+nacl.sign = function(msg, secretKey) {
+ checkArrayTypes(msg, secretKey);
+ if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
+ throw new Error('bad secret key size');
+ var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);
+ crypto_sign(signedMsg, msg, msg.length, secretKey);
+ return signedMsg;
+};
+
+nacl.sign.open = function(signedMsg, publicKey) {
+ checkArrayTypes(signedMsg, publicKey);
+ if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
+ throw new Error('bad public key size');
+ var tmp = new Uint8Array(signedMsg.length);
+ var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);
+ if (mlen < 0) return null;
+ var m = new Uint8Array(mlen);
+ for (var i = 0; i < m.length; i++) m[i] = tmp[i];
+ return m;
+};
+
+nacl.sign.detached = function(msg, secretKey) {
+ var signedMsg = nacl.sign(msg, secretKey);
+ var sig = new Uint8Array(crypto_sign_BYTES);
+ for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
+ return sig;
+};
+
+nacl.sign.detached.verify = function(msg, sig, publicKey) {
+ checkArrayTypes(msg, sig, publicKey);
+ if (sig.length !== crypto_sign_BYTES)
+ throw new Error('bad signature size');
+ if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
+ throw new Error('bad public key size');
+ var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
+ var m = new Uint8Array(crypto_sign_BYTES + msg.length);
+ var i;
+ for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
+ for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
+ return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
+};
+
+nacl.sign.keyPair = function() {
+ var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
+ var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
+ crypto_sign_keypair(pk, sk);
+ return {publicKey: pk, secretKey: sk};
+};
+
+nacl.sign.keyPair.fromSecretKey = function(secretKey) {
+ checkArrayTypes(secretKey);
+ if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
+ throw new Error('bad secret key size');
+ var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
+ for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];
+ return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
+};
+
+nacl.sign.keyPair.fromSeed = function(seed) {
+ checkArrayTypes(seed);
+ if (seed.length !== crypto_sign_SEEDBYTES)
+ throw new Error('bad seed size');
+ var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
+ var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
+ for (var i = 0; i < 32; i++) sk[i] = seed[i];
+ crypto_sign_keypair(pk, sk, true);
+ return {publicKey: pk, secretKey: sk};
+};
+
+nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;
+nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;
+nacl.sign.seedLength = crypto_sign_SEEDBYTES;
+nacl.sign.signatureLength = crypto_sign_BYTES;
+
+nacl.hash = function(msg) {
+ checkArrayTypes(msg);
+ var h = new Uint8Array(crypto_hash_BYTES);
+ crypto_hash(h, msg, msg.length);
+ return h;
+};
+
+nacl.hash.hashLength = crypto_hash_BYTES;
+
+nacl.verify = function(x, y) {
+ checkArrayTypes(x, y);
+ // Zero length arguments are considered not equal.
+ if (x.length === 0 || y.length === 0) return false;
+ if (x.length !== y.length) return false;
+ return (vn(x, 0, y, 0, x.length) === 0) ? true : false;
+};
+
+nacl.setPRNG = function(fn) {
+ randombytes = fn;
+};
+
+(function() {
+ // Initialize PRNG if environment provides CSPRNG.
+ // If not, methods calling randombytes will throw.
+ var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;
+ if (crypto && crypto.getRandomValues) {
+ // Browsers.
+ var QUOTA = 65536;
+ nacl.setPRNG(function(x, n) {
+ var i, v = new Uint8Array(n);
+ for (i = 0; i < n; i += QUOTA) {
+ crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
+ }
+ for (i = 0; i < n; i++) x[i] = v[i];
+ cleanup(v);
+ });
+ } else if (typeof require !== 'undefined') {
+ // Node.js.
+ crypto = require('crypto');
+ if (crypto && crypto.randomBytes) {
+ nacl.setPRNG(function(x, n) {
+ var i, v = crypto.randomBytes(n);
+ for (i = 0; i < n; i++) x[i] = v[i];
+ cleanup(v);
+ });
+ }
+ }
+})();
+
+})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));
diff --git a/internal/equipo/templates/chrome.html b/internal/equipo/templates/chrome.html
index 70301bf5..e5b731cd 100644
--- a/internal/equipo/templates/chrome.html
+++ b/internal/equipo/templates/chrome.html
@@ -1,6 +1,6 @@
{{define "rail-brand"}}<span hidden></span>{{end}}
{{define "title"}}{{copy .Title}} · {{copy "brand"}}{{end}}
-{{define "head"}}{{.Live.Head (T "rastrillo.ui.live.paused") (T "rastrillo.ui.live.unconfirmed")}}<link rel="stylesheet" href="{{asset "static/equipo.css"}}"><script defer src="{{asset "static/nav-stream.js"}}"></script><script defer src="{{asset "static/work-stream.js"}}"></script>{{if .HousekeepingStream}}<script defer src="{{asset "static/housekeeping.js"}}"></script>{{end}}{{if or (eq .Key "thinking") (eq .Key "settings-hub")}}<script defer src="{{asset "static/stardust.js"}}"></script><script defer src="{{asset "static/thinking-preview.js"}}"></script><script defer src="{{asset "static/settings.js"}}"></script>{{end}}{{if or .ConnectionsStream .ChatStream}}<script defer src="{{asset "static/stardust.js"}}"></script>{{end}}{{if .ConnectionsStream}}<script defer src="{{asset "static/connections.js"}}"></script>{{end}}{{if .ChatStream}}<script defer src="{{asset "static/chat-stream.js"}}"></script><script defer src="{{asset "static/chat-compose.js"}}"></script><script defer src="{{asset "static/ask-target.js"}}"></script>{{if eq .Key "conversation"}}<script defer src="{{asset "static/chat-anchor.js"}}"></script><script defer src="{{asset "static/chat-attach.js"}}"></script>{{end}}{{else if eq .Key "conversation"}}<script defer blocking="render" src="{{asset "static/chat-navigation.js"}}"></script><script defer src="{{asset "static/chat.js"}}"></script><script defer src="{{asset "static/chat-send.js"}}"></script>{{end}}{{end}}
+{{define "head"}}{{.Live.Head (T "rastrillo.ui.live.paused") (T "rastrillo.ui.live.unconfirmed")}}<link rel="stylesheet" href="{{asset "static/equipo.css"}}"><script defer src="{{asset "static/nav-stream.js"}}"></script><script defer src="{{asset "static/work-stream.js"}}"></script>{{if .HousekeepingStream}}<script defer src="{{asset "static/housekeeping.js"}}"></script>{{end}}{{if or (eq .Key "thinking") (eq .Key "settings-hub")}}<script defer src="{{asset "static/stardust.js"}}"></script><script defer src="{{asset "static/thinking-preview.js"}}"></script><script defer src="{{asset "static/settings.js"}}"></script>{{end}}{{if or .ConnectionsStream .ChatStream}}<script defer src="{{asset "static/stardust.js"}}"></script>{{end}}{{if .ConnectionsStream}}<script defer src="{{asset "static/vendor/tweetnacl/nacl-fast.js"}}"></script><script defer src="{{asset "static/seal.js"}}"></script><script defer src="{{asset "static/connections.js"}}"></script>{{end}}{{if .ChatStream}}<script defer src="{{asset "static/chat-stream.js"}}"></script><script defer src="{{asset "static/chat-compose.js"}}"></script><script defer src="{{asset "static/ask-target.js"}}"></script>{{if eq .Key "conversation"}}<script defer src="{{asset "static/chat-anchor.js"}}"></script><script defer src="{{asset "static/chat-attach.js"}}"></script>{{end}}{{else if eq .Key "conversation"}}<script defer blocking="render" src="{{asset "static/chat-navigation.js"}}"></script><script defer src="{{asset "static/chat.js"}}"></script><script defer src="{{asset "static/chat-send.js"}}"></script>{{end}}{{end}}
{{define "up"}}/work{{if .Key}}#nav-{{.Key}}{{end}}{{end}}
{{define "up-label"}}{{.TeamName}}{{end}}
{{define "brand"}}<a rst-shell-brand href="/work">{{icon "users"}}{{.TeamName}}</a>{{end}}
diff --git a/internal/equipo/templates/models.html b/internal/equipo/templates/models.html
index 9f60450c..84a95fb5 100644
--- a/internal/equipo/templates/models.html
+++ b/internal/equipo/templates/models.html
@@ -4,14 +4,19 @@
{{define "conn-star"}}<span equipo-sparkle data-conn-star aria-hidden="true"><svg viewBox="0 0 16 16" focusable="false"><path d="M8 0C8.6 4.6 11.4 7.4 16 8 11.4 8.6 8.6 11.4 8 16 7.4 11.4 4.6 8.6 0 8 4.6 7.4 7.4 4.6 8 0Z"/><circle cx="8" cy="8" r="1.7"/></svg><i data-sat="1"></i><i data-sat="2"></i><i data-sat="3"></i></span>{{end}}
{{define "conn-mark"}}<span equipo-pmark data-provider="{{.}}" aria-hidden="true">{{if eq . "claude"}}Cl{{else if eq . "codex"}}Cx{{else if eq . "mistral"}}Mi{{else if eq . "tensorx"}}Tx{{else}}{{icon "cpu"}}{{end}}</span>{{end}}
{{define "conn-copy"}}<button type="button" rst-btn data-copy="{{.}}" data-copied="{{copy "chat.connections.copied"}}">{{copy "chat.connections.copy"}}</button>{{end}}
+{{define "conn-copy-link"}}<button type="button" rst-btn data-copy="{{.}}" data-copy-link data-copied="{{copy "chat.connections.copied"}}">{{copy "chat.connections.copy_link"}}</button>{{end}}
+{{define "conn-sign-in-instead"}}<form method="post" action="/conversation/connections" data-add-form equipo-inline-form><input type="hidden" name="provider" value="claude"><input type="hidden" name="kind" value="subscription"><button equipo-link type="submit" data-sign-in-instead>{{copy "chat.connections.sign_in_instead"}}</button></form>{{end}}
{{define "conn-waiting"}}<p equipo-conn-waiting aria-live="polite">{{template "conn-star"}}<span>{{.}}</span></p>{{end}}
{{define "conn-cancel"}}<form method="post" action="/conversation/connections/{{.}}/cancel" equipo-inline-form><button rst-btn data-quiet type="submit" data-connection-cancel>{{copy "chat.connections.cancel"}}</button></form>{{end}}
-{{define "conn-attempt"}}<div equipo-conn-card data-connection="{{.ID}}" data-connecting data-provider="{{.Provider}}">
-<div equipo-conn-card-head>{{template "conn-mark" .Provider}}<div><h3>{{if eq .Provider "codex"}}{{copy "chat.connections.title_codex"}}{{else}}{{copy "chat.connections.title_claude"}}{{end}}</h3><p>{{if not .Prompt}}{{copy "chat.connections.loading_sub"}}{{else if eq .Provider "codex"}}{{copy "chat.connections.codex_sub"}}{{else}}{{copy "chat.connections.claude_sub"}}{{end}}</p></div></div>
-{{if not .Prompt}}<div equipo-conn-loading data-loading data-phrases="{{.Phrases}}">{{template "conn-star"}}<p data-phrase>{{index (split .Phrases "|") 0}}</p></div>
+{{define "conn-attempt"}}<div equipo-conn-card data-connection="{{.ID}}" data-connecting data-provider="{{.Provider}}"{{if eq .Kind "token"}} data-kind="token" data-runner="{{.RunnerID}}" data-endpoint="{{.Endpoint}}"{{with .SealKey}} data-seal-key="{{.}}"{{end}}{{end}}>
+<div equipo-conn-card-head>{{template "conn-mark" .Provider}}<div><h3>{{if eq .Provider "codex"}}{{copy "chat.connections.title_codex"}}{{else}}{{copy "chat.connections.title_claude"}}{{end}}</h3><p>{{if eq .Kind "token"}}{{copy "chat.connections.token_sub"}}{{else if not .Prompt}}{{copy "chat.connections.loading_sub"}}{{else if eq .Provider "codex"}}{{copy "chat.connections.codex_sub"}}{{else}}{{copy "chat.connections.claude_sub"}}{{end}}</p></div></div>
+{{if and (not .Prompt) (eq .Kind "token")}}{{template "conn-waiting" (copy "chat.connections.waiting_token")}}
+<p equipo-conn-small>{{copy "chat.connections.token_sealed"}}</p>
+<div equipo-conn-card-foot><span></span>{{template "conn-cancel" .ID}}</div>
+{{else if not .Prompt}}<div equipo-conn-loading data-loading data-phrases="{{.Phrases}}">{{template "conn-star"}}<p data-phrase>{{index (split .Phrases "|") 0}}</p></div>
<div equipo-conn-card-foot><span></span>{{template "conn-cancel" .ID}}</div>
{{else if eq .Prompt.Kind "device_code"}}<ol equipo-conn-steps data-device-code>
-<li><div><a rst-btn="primary" href="{{.Prompt.URL}}" rel="noopener" target="_blank" data-open-provider>{{icon "external-link"}}{{copy "chat.connections.open_openai"}}</a></div></li>
+<li><div equipo-conn-link-row><a rst-btn="primary" href="{{.Prompt.URL}}" rel="noopener" target="_blank" data-open-provider>{{icon "external-link"}}{{copy "chat.connections.open_openai"}}</a>{{template "conn-copy-link" .Prompt.URL}}</div></li>
<li><div><p>{{copy "chat.connections.enter_code"}}</p><div equipo-conn-code-row><code equipo-conn-code data-code>{{.Prompt.Code}}</code>{{template "conn-copy" .Prompt.Code}}<p equipo-conn-once>{{copy "chat.connections.code_once"}}</p></div></div></li>
<li><div><p>{{copy "chat.connections.approve_back"}}</p></div></li>
</ol>
@@ -19,11 +24,19 @@
<p equipo-conn-small>{{copy "chat.connections.device_off"}}</p>
<div equipo-conn-card-foot><span equipo-conn-small>{{copy "chat.connections.codex_fine"}}</span>{{template "conn-cancel" .ID}}</div>
{{else if eq .Prompt.Kind "link"}}<ol equipo-conn-steps data-sign-in-steps>
-<li><div><a rst-btn="primary" href="{{.Prompt.URL}}" rel="noopener" target="_blank" data-sign-in>{{icon "external-link"}}{{copy "chat.connections.open_claude"}}</a></div></li>
+<li><div equipo-conn-link-row><a rst-btn="primary" href="{{.Prompt.URL}}" rel="noopener" target="_blank" data-sign-in>{{icon "external-link"}}{{copy "chat.connections.open_claude"}}</a>{{template "conn-copy-link" .Prompt.URL}}</div></li>
<li><div><p>{{copy "chat.connections.claude_back"}}</p></div></li>
</ol>
{{template "conn-waiting" (copy "chat.connections.waiting_sign_in")}}
<div equipo-conn-card-foot><span equipo-conn-small>{{copy "chat.connections.claude_fine"}}</span>{{template "conn-cancel" .ID}}</div>
+{{else if eq .Prompt.Kind "token"}}<ol equipo-conn-steps data-token-steps>
+<li><div><p>{{copy "chat.connections.token_run"}}</p><div equipo-conn-code-row><code equipo-conn-code data-command>{{.Prompt.Code}}</code>{{template "conn-copy" .Prompt.Code}}</div></div></li>
+<li><div><p>{{copy "chat.connections.token_approve"}}</p></div></li>
+<li><div><form equipo-conn-token data-token-form autocomplete="off"><label for="token-{{.ID}}">{{copy "chat.connections.token_paste"}}</label><span equipo-conn-token-row><input rst-input id="token-{{.ID}}" type="password" data-token-field autocomplete="off" autocapitalize="off" spellcheck="false" required><button rst-btn="primary" type="submit" data-token-connect>{{copy "chat.connections.token_connect"}}</button></span><span equipo-conn-small data-token-note role="status" hidden data-bad="{{copy "chat.connections.token_bad"}}" data-failed="{{copy "chat.connections.token_failed"}}" data-no-key="{{copy "chat.connections.token_no_key"}}"></span></form></div></li>
+</ol>
+<div data-token-waiting hidden>{{template "conn-waiting" (copy "chat.connections.waiting_token")}}</div>
+<p equipo-conn-small>{{copy "chat.connections.token_sealed"}}</p>
+<div equipo-conn-card-foot><span equipo-conn-small>{{template "conn-sign-in-instead"}}</span>{{template "conn-cancel" .ID}}</div>
{{else if eq .Prompt.Kind "terminal"}}<ol equipo-conn-steps data-finish-on>
<li><div><p><strong>{{printf (copy "chat.connections.open_terminal") .Runner}}</strong></p></div></li>
<li><div><p>{{copy "chat.connections.run"}}</p><div equipo-conn-code-row><code equipo-conn-code data-command>{{.Prompt.Code}}</code>{{template "conn-copy" .Prompt.Code}}</div></div></li>
@@ -37,7 +50,8 @@
<summary rst-btn{{if .}}="primary"{{end}} data-add-open>{{icon "plug"}}{{copy "chat.connections.add"}}</summary>
<div equipo-conn-chooser role="group" aria-label="{{copy "chat.connections.add"}}">
<header><h3>{{copy "chat.connections.add"}}</h3><p>{{copy "chat.connections.chooser_lede"}}</p></header>
-<form method="post" action="/conversation/connections" data-add-form><input type="hidden" name="provider" value="claude"><button type="submit" equipo-conn-opt data-add="claude">{{template "conn-mark" "claude"}}<span><span equipo-conn-opt-name>Claude</span><span equipo-conn-opt-desc>{{copy "chat.connections.claude_desc"}}</span></span>{{icon "chevron-right"}}</button></form>
+<form method="post" action="/conversation/connections" data-add-form><input type="hidden" name="provider" value="claude"><input type="hidden" name="kind" value="token"><button type="submit" equipo-conn-opt data-add="claude">{{template "conn-mark" "claude"}}<span><span equipo-conn-opt-name>Claude</span><span equipo-conn-opt-desc>{{copy "chat.connections.claude_desc"}}</span><span equipo-conn-opt-how data-paste-token>{{copy "chat.connections.paste_token"}}</span></span>{{icon "chevron-right"}}</button></form>
+<div equipo-conn-alt>{{template "conn-sign-in-instead"}}</div>
<form method="post" action="/conversation/connections" data-add-form><input type="hidden" name="provider" value="codex"><button type="submit" equipo-conn-opt data-add="codex">{{template "conn-mark" "codex"}}<span><span equipo-conn-opt-name>Codex</span><span equipo-conn-opt-desc>{{copy "chat.connections.codex_desc"}}</span></span>{{icon "chevron-right"}}</button></form>
<p equipo-conn-sep>{{copy "chat.connections.soon"}}</p>
<button type="button" equipo-conn-opt disabled>{{template "conn-mark" "local"}}<span><span equipo-conn-opt-name>{{copy "chat.connections.local"}}</span><span equipo-conn-opt-desc>{{copy "chat.connections.local_desc"}}</span></span><span equipo-conn-soon>{{copy "chat.connections.soon"}}</span></button>
@@ -49,11 +63,12 @@
{{template "conn-mark" .Provider}}
<div equipo-conn-body>
<p equipo-conn-head><span equipo-conn-name>{{.Name}}</span><span equipo-conn-account>{{.Label}}{{with .Plan}}, {{.}}{{end}}</span>{{if .Preferred}}<span equipo-conn-pref>{{icon "star"}}{{copy "chat.connections.preferred"}}</span>{{end}}</p>
-<p equipo-conn-facts><span equipo-conn-state data-connection-state data-s="{{.State}}">{{.Words}}</span>{{range .Meters}}<span equipo-conn-meter data-level="{{.Level}}"><span equipo-conn-bar><i data-w="{{.Used}}"></i></span><span>{{.Name}} <b>{{.Used}}%</b>{{with .Resets}}, {{.}}{{end}}</span></span>{{end}}</p>
+<p equipo-conn-facts><span equipo-conn-state data-connection-state data-s="{{.State}}">{{.Words}}</span>{{with .Expires}}<span equipo-conn-expires data-token-expires>{{.}}</span>{{end}}{{range .Meters}}<span equipo-conn-meter data-level="{{.Level}}"><span equipo-conn-bar><i data-w="{{.Used}}"></i></span><span>{{.Name}} <b>{{.Used}}%</b>{{with .Resets}}, {{.}}{{end}}</span></span>{{end}}</p>
+{{if .Renew}}<div equipo-conn-renew data-token-renew>{{copy "chat.connections.token_renew"}} <form method="post" action="/conversation/connections" data-add-form equipo-inline-form><input type="hidden" name="provider" value="{{.Provider}}"><input type="hidden" name="kind" value="token"><button equipo-link type="submit" data-renew>{{copy "chat.connections.token_new"}}</button></form></div>{{end}}
{{if .Roles}}<p equipo-conn-roles><span equipo-conn-roles-label>{{copy "chat.connections.serving"}}</span>{{range .Roles}}<span equipo-conn-chip{{if .Live}} data-live{{end}}>{{if .Live}}{{template "conn-star"}}{{end}}{{.Name}}</span>{{end}}</p>{{else}}{{with .RolesNote}}<p equipo-conn-roles><span equipo-conn-roles-note>{{.}}</span></p>{{end}}{{end}}
</div>
<div equipo-conn-side>
-<div equipo-conn-actions>{{if .Needs}}<form method="post" action="/conversation/connections" data-add-form equipo-inline-form><input type="hidden" name="provider" value="{{.Provider}}"><button rst-btn type="submit" data-recover="{{.Provider}}">{{.Needs}}</button></form>{{end}}{{if or .MakePreferred .SignOut .Forget}}<span equipo-conn-quiet>{{template "conn-quiet" .}}</span><details equipo-conn-more><summary aria-label="{{copy "chat.connections.more"}}">{{icon "more-horizontal"}}</summary><div>{{template "conn-quiet" .}}</div></details>{{end}}</div>
+<div equipo-conn-actions>{{if .Needs}}<form method="post" action="/conversation/connections" data-add-form equipo-inline-form><input type="hidden" name="provider" value="{{.Provider}}">{{if eq .Kind "token"}}<input type="hidden" name="kind" value="token">{{end}}<button rst-btn type="submit" data-recover="{{.Provider}}">{{.Needs}}</button></form>{{end}}{{if or .MakePreferred .SignOut .Forget}}<span equipo-conn-quiet>{{template "conn-quiet" .}}</span><details equipo-conn-more><summary aria-label="{{copy "chat.connections.more"}}">{{icon "more-horizontal"}}</summary><div>{{template "conn-quiet" .}}</div></details>{{end}}</div>
<p equipo-conn-usage>{{if eq .State "signed_out"}}{{printf (copy "chat.connections.tokens_before") .Usage}}{{else}}<b>{{.Usage}}</b>{{.UsageTail}}{{end}}</p>
</div>
</article>{{end}}
diff --git a/internal/headless/browser_connections_test.go b/internal/headless/browser_connections_test.go
index aeb2588e..330373e4 100644
--- a/internal/headless/browser_connections_test.go
+++ b/internal/headless/browser_connections_test.go
@@ -48,11 +48,17 @@ func connectionsPage(t *testing.T, inst *thintest.Instance) *page {
// connShot writes docs/mockups/built/2026-11-08/conn-<name>-<width>.png
// when EQUIPO_CONN_SHOTS is set.
func connShot(t *testing.T, p *page, name string, width int64) {
+ t.Helper()
+ connShotOn(t, p, "2026-11-08", name, width)
+}
+
+// connShotOn is connShot into docs/mockups/built/<day>/.
+func connShotOn(t *testing.T, p *page, day, name string, width int64) {
t.Helper()
if os.Getenv("EQUIPO_CONN_SHOTS") == "" {
return
}
- dir := filepath.Join("..", "..", "docs", "mockups", "built", "2026-11-08")
+ dir := filepath.Join("..", "..", "docs", "mockups", "built", day)
if err := os.MkdirAll(dir, 0755); err != nil {
t.Fatal(err)
}
@@ -92,8 +98,8 @@ func TestBrowserConnectionsAdd(t *testing.T) {
p.run(browsertest.Wait(`!!document.querySelector('[data-device-code]')`))
p.check(`(()=>{const card=document.querySelector('[data-connecting][data-provider="codex"]');const code=card.querySelector('[data-code]').textContent;const open=card.querySelector('[data-open-provider]');return /^FAKE-/.test(code) && card.textContent.split(code).length===2 && open.getAttribute('href')==='https://auth.openai.com/codex/device' && open.target==='_blank' && !card.textContent.includes('auth.openai.com') && card.querySelectorAll('ol > li').length===3 && card.querySelector('h3').textContent==='Connect Codex'})()`, "the device code card is not the three steps with the code once")
connShot(t, p, "codex-code", width)
- p.check(`(()=>{document.querySelector('[data-device-code] [data-copy]').click();return true})()`, "Copy")
- p.run(browsertest.Wait(`document.querySelector('[data-device-code] [data-copy]').textContent==='Copied'`))
+ p.check(`(()=>{document.querySelector('[data-device-code] [data-copy]:not([data-copy-link])').click();return true})()`, "Copy")
+ p.run(browsertest.Wait(`document.querySelector('[data-device-code] [data-copy]:not([data-copy-link])').textContent==='Copied'`))
// The approval lands with the success card, then the row.
p.check(`(()=>{window.__success=false;new MutationObserver(()=>{if(document.querySelector('[data-success]'))window.__success=true}).observe(document.body,{childList:true,subtree:true});return true})()`, "observer")
writeJSON(t, filepath.Join(r.root, "accounts", ".fake-device.json"), map[string]any{"email": second, "plan": "pro"})
@@ -103,7 +109,9 @@ func TestBrowserConnectionsAdd(t *testing.T) {
// Prefer Codex: pressed at once, and still after the stream's refresh.
p.check(`(()=>{document.querySelector('[data-prefer="codex"]').click();return document.querySelector('[data-prefer="codex"]').getAttribute('aria-pressed')==='true'})()`, "Prefer Codex")
p.run(waitLong(`document.querySelector('[data-prefer="codex"]').getAttribute('aria-pressed')==='true' && !!document.querySelector('[equipo-conn-row][data-provider="codex"] [equipo-conn-pref]')`))
- p.check(`(()=>{document.querySelector('[data-add-open]').click();document.querySelector('[data-add="claude"]').click();return !!document.querySelector('[data-connecting][data-provider="claude"]')})()`, "no card the instant Claude is chosen")
+ // Claude's sign-in on the runner, the chooser's quiet way in
+ // beside Paste a token.
+ p.check(`(()=>{document.querySelector('[data-add-open]').click();document.querySelector('[data-add-area] [data-sign-in-instead]').click();return !!document.querySelector('[data-connecting][data-provider="claude"]')})()`, "no card the instant Claude's sign-in is chosen")
p.run(browsertest.Wait(`!!document.querySelector('[data-finish-on]')`))
p.check(`document.querySelector('[data-finish-on] [data-command]').textContent.includes('equipo-runner login claude') && document.querySelectorAll('[data-finish-on] > li').length===3 && !!document.querySelector('[data-finish-on] [data-copy]') && !!document.querySelector('[data-same-machine]') && !document.querySelector('[data-sign-in]') && !document.querySelector('input[type="password"],input[name="code"]')`, "the finish-on-runner card is not the only way shown, or it asks for a paste")
connShot(t, p, "claude-terminal", width)
diff --git a/internal/headless/browser_token_test.go b/internal/headless/browser_token_test.go
new file mode 100644
index 00000000..c3bd9cf0
--- /dev/null
+++ b/internal/headless/browser_token_test.go
@@ -0,0 +1,263 @@
+//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"
+
+// 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()
+ 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{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/connections"), 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: Claude is Paste a token, with the sign-in on
+ // the runner a quiet link under it.
+ p.check(`(()=>{document.querySelector('[data-add-open]').click();const how=document.querySelector('[data-add="claude"] [data-paste-token]');const alt=document.querySelector('[equipo-conn-chooser] [data-sign-in-instead]');return !!how && how.textContent==='Paste a token' && how.checkVisibility() && !!alt && alt.textContent==='Or sign in on the runner instead' && alt.checkVisibility()})()`, "the chooser does not offer Paste a token with the quiet sign-in link")
+ shot("token-chooser")
+ p.check(`(()=>{document.querySelector('[data-add="claude"]').click();return !!document.querySelector('[data-connecting][data-provider="claude"]')})()`, "no card the instant Claude 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]') && card.textContent.includes("It's sealed to your runner; Equipo's server never sees it.") && !!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.
+ p.check(`(()=>{window.__success=false;new MutationObserver(()=>{if(document.querySelector('[data-success]'))window.__success=true}).observe(document.body,{childList:true,subtree:true});return true})()`, "observer")
+ 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})
+ want := "Token expires " + expires.Format("2 Jan 2006")
+ p.run(waitLong(`window.__success && !document.querySelector('[data-success]') && [...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")
+
+ // Within a month of expiry: a quiet line asks for a new one.
+ soon := time.Now().UTC().Add(10 * 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})
+ 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==='Paste a new token'`))
+ 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})
+ 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. Run claude setup-token again.' && row.querySelector('[data-recover]').textContent==='Sign in again'})()`))
+ shot("token-rejected")
+ // Sign in again is a new token attempt.
+ p.check(`(()=>{document.querySelector('[equipo-conn-row][data-state="sign_in_again"] [data-recover]').click();return true})()`, "Sign in again")
+ p.run(waitLong(`!!document.querySelector('[data-token-form]')`))
+ if cmd := runner.expect(t, wire.FrameConnect).(*wire.ConnectCommand); cmd.Kind != wire.KindToken {
+ t.Fatalf("Sign in again started %+v", cmd)
+ }
+ p.check(stayed, "the page reloaded or navigated")
+ })
+ }
+}
+
+// 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 link
+// 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/connections"), 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 at this machine: the loopback link card.
+ const authorize = "https://claude.ai/oauth/authorize?code=true&state=fake"
+ claude, err := client.Connect(t.Context(), wire.Connect{Provider: "claude", SameMachine: true})
+ 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.PromptLink, URL: authorize}})
+ p.run(waitLong(`!!document.querySelector('[data-sign-in-steps] [data-copy-link]')`))
+ p.check(strings.ReplaceAll(besides, "%[1]s", "[data-sign-in]"), "Copy link is not beside Open Claude")
+ p.check(`(()=>{document.querySelector('[data-sign-in-steps] [data-copy-link]').click();return true})()`, "Copy link")
+ p.run(waitLong(`document.querySelector('[data-sign-in-steps] [data-copy-link]').textContent==='Copied' && window.__copied[1]==='` + authorize + `'`))
+ connShotOn(t, p, tokenDay, "claude-copy-link", width)
+ p.check(stayed, "the page reloaded or navigated")
+ })
+ }
+}
diff --git a/internal/plan3test/person_api_contract_test.go b/internal/plan3test/person_api_contract_test.go
index cb5c5f61..c46b9d6a 100644
--- a/internal/plan3test/person_api_contract_test.go
+++ b/internal/plan3test/person_api_contract_test.go
@@ -56,7 +56,7 @@ func personAPIContractCoverage(t *testing.T) {
f := newFixture(t)
registered := map[string]bool{}
// Thin v1 conversation routes are contracted by internal/wire fixtures.
- thin := map[string]bool{"GET /messages": true, "POST /messages": true, "GET /turns/{id}": true, "POST /turns/{id}/cancel": true, "GET /snapshot": true, "GET /events": true, "DELETE /projects/{id}": true, "POST /cards/{id}/answer": true, "GET /notebook": true, "POST /notebook/reset": true, "POST /tasks/{id}/retry": true, "POST /tasks/{id}/recover": true, "POST /tasks/{id}/merge": true, "POST /tasks/{id}/duplicate": true, "POST /tasks/{id}/uncombine": true, "GET /thinking": true, "PUT /thinking": true, "POST /tasks/{id}/thread": true, "GET /steps/{id}/log": true, "POST /tasks/{id}/questions": true, "POST /questions/{id}/cancel": true, "POST /connections": true, "POST /connections/{id}/cancel": true, "POST /connections/{id}/forget": true, "GET /connections/preference": true, "PUT /connections/preference": true, "GET /housekeeping": true, "PUT /housekeeping": true, "PUT /housekeeping/detectors/{id}": true, "GET /housekeeping/actions": true, "POST /housekeeping/actions/{id}/undo": true, "POST /attachments": true, "GET /attachments/{id}": true, "GET /attachments/{id}/preview": true}
+ thin := map[string]bool{"GET /messages": true, "POST /messages": true, "GET /turns/{id}": true, "POST /turns/{id}/cancel": true, "GET /snapshot": true, "GET /events": true, "DELETE /projects/{id}": true, "POST /cards/{id}/answer": true, "GET /notebook": true, "POST /notebook/reset": true, "POST /tasks/{id}/retry": true, "POST /tasks/{id}/recover": true, "POST /tasks/{id}/merge": true, "POST /tasks/{id}/duplicate": true, "POST /tasks/{id}/uncombine": true, "GET /thinking": true, "PUT /thinking": true, "POST /tasks/{id}/thread": true, "GET /steps/{id}/log": true, "POST /tasks/{id}/questions": true, "POST /questions/{id}/cancel": true, "POST /connections": true, "POST /connections/{id}/cancel": true, "POST /connections/{id}/secret": true, "POST /connections/{id}/forget": true, "GET /connections/preference": true, "PUT /connections/preference": true, "GET /housekeeping": true, "PUT /housekeeping": true, "PUT /housekeeping/detectors/{id}": true, "GET /housekeeping/actions": true, "POST /housekeeping/actions/{id}/undo": true, "POST /attachments": true, "GET /attachments/{id}": true, "GET /attachments/{id}/preview": true}
must(t, chi.Walk(f.Store.PersonAPIHandler().(chi.Routes), func(method, path string, _ http.Handler, _ ...func(http.Handler) http.Handler) error {
if thin[method+" "+path] {
return nil
diff --git a/internal/thintest/client.go b/internal/thintest/client.go
index c1c029f6..2359efc9 100644
--- a/internal/thintest/client.go
+++ b/internal/thintest/client.go
@@ -278,6 +278,11 @@ func (c *Client) CancelConnection(ctx context.Context, id string) (out wire.Conn
return out, c.do(ctx, "POST", "/api/v1/connections/"+id+"/cancel", nil, &out)
}
+// Secret posts a token attempt's sealed secret (202 with the attempt).
+func (c *Client) Secret(ctx context.Context, id string, in wire.Sealed) (out wire.Connection, err error) {
+ return out, c.do(ctx, "POST", "/api/v1/connections/"+id+"/secret", in, &out)
+}
+
// Stream is one open SSE connection.
type Stream struct {
Events <-chan wire.Event
diff --git a/internal/thintest/instance.go b/internal/thintest/instance.go
index 54b9db05..505c6378 100644
--- a/internal/thintest/instance.go
+++ b/internal/thintest/instance.go
@@ -19,6 +19,7 @@ import (
"os"
"path/filepath"
"strings"
+ "sync"
"testing"
"time"
@@ -55,6 +56,27 @@ type Instance struct {
server *http.Server
cookie *http.Cookie
logger *slog.Logger
+ logs *logBuffer
+}
+
+// logBuffer keeps every line the instance logged, so a test can show a
+// secret never reached one.
+type logBuffer struct {
+ mu sync.Mutex
+ buf bytes.Buffer
+}
+
+func (l *logBuffer) Write(p []byte) (int, error) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.buf.Write(p)
+}
+
+// Logs is everything the instance has logged so far, every level.
+func (i *Instance) Logs() string {
+ i.logs.mu.Lock()
+ defer i.logs.mu.Unlock()
+ return i.logs.buf.String()
}
// StartInstance migrates a fresh database and serves it.
@@ -64,7 +86,8 @@ func StartInstance(t testing.TB) *Instance {
if err != nil {
t.Fatal(err)
}
- i := &Instance{addr: l.Addr().String(), Path: schema.Path(t), logger: slog.New(slog.NewTextHandler(io.Discard, nil))}
+ logs := &logBuffer{}
+ i := &Instance{addr: l.Addr().String(), Path: schema.Path(t), logs: logs, logger: slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug}))}
i.URL = "http://" + i.addr
i.serve(t, l)
t.Cleanup(func() { i.Stop() })
diff --git a/internal/thintest/token_contract_test.go b/internal/thintest/token_contract_test.go
new file mode 100644
index 00000000..c779d4ef
--- /dev/null
+++ b/internal/thintest/token_contract_test.go
@@ -0,0 +1,321 @@
+package thintest
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/base64"
+ "io"
+ "net/http"
+ "os"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/sealbox"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// canaryToken is an obviously fake setup token: it is sealed in the test
+// and must never appear on the instance.
+const canaryToken = "sk-ant-oat01-CANARY-not-a-real-token-CANARY"
+
+// recorder keeps every response body the client read.
+type recorder struct {
+ mu sync.Mutex
+ seen bytes.Buffer
+}
+
+func (r *recorder) RoundTrip(req *http.Request) (*http.Response, error) {
+ res, err := http.DefaultTransport.RoundTrip(req)
+ if err != nil {
+ return res, err
+ }
+ raw, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ r.mu.Lock()
+ r.seen.Write(raw)
+ r.mu.Unlock()
+ res.Body = io.NopCloser(bytes.NewReader(raw))
+ return res, err
+}
+
+func (r *recorder) String() string {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.seen.String()
+}
+
+// sealKeys is a runner's seal key pair from a fresh enrolment key.
+func sealKeys(t *testing.T) sealbox.Keys {
+ t.Helper()
+ _, private, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ keys, err := sealbox.FromEd25519(private)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return keys
+}
+
+// rawEvents reads the person's event stream from the start as it is
+// served, for a moment.
+func rawEvents(t *testing.T, r *rig) string {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(r.ctx, 1500*time.Millisecond)
+ defer cancel()
+ req, _ := http.NewRequestWithContext(ctx, "GET", r.inst.URL+"/api/v1/events?after=0", nil)
+ req.Header.Set("Authorization", "Bearer "+r.client.Token)
+ req.Header.Set("Accept", "text/event-stream")
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ raw, _ := io.ReadAll(res.Body)
+ if !bytes.Contains(raw, []byte("event: connection")) {
+ t.Fatalf("the stream served no connection events: %.400s", raw)
+ }
+ return string(raw)
+}
+
+// TestContractTokenConnection (Paul, 2026-11-09; spec §2.4): the runner's
+// seal key is published; a Claude token attempt shows the token card and
+// goes to the runner as connect (kind token); a sealed box whose clear
+// binding is not this attempt's is refused; one that is goes to the
+// runner as a durable secret frame and is blanked once acked. The
+// canary's plaintext appears nowhere on the instance (database and WAL
+// bytes, events, responses, pages, logs) and the box nowhere but the
+// mailbox until the ack.
+func TestContractTokenConnection(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()
+ })
+ if snap, err := r.client.Snapshot(r.ctx); err != nil || snap.Runner.SealKey != keys.PublicString() {
+ t.Fatalf("snapshot runner %+v %v", snap.Runner, err)
+ }
+
+ if _, err := r.client.Connect(r.ctx, wire.Connect{Provider: "codex", Kind: wire.KindToken}); Status(err) != 422 {
+ t.Fatalf("a Codex token attempt: %v", err)
+ }
+ attempt, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude", Kind: wire.KindToken})
+ if err != nil || attempt.State != wire.ConnConnecting || attempt.Kind != wire.KindToken || attempt.Prompt == nil || attempt.Prompt.Kind != wire.PromptToken || attempt.Prompt.Code != "claude setup-token" || attempt.RunnerID != runnerID {
+ t.Fatalf("token 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.Connection != attempt.ID || cmd.Kind != wire.KindToken || cmd.Provider != "claude" {
+ t.Fatalf("connect frame %+v", cmd)
+ }
+ if err = runner.Send(r.ctx, "a-connect", wire.FrameAck, wire.Ack{ID: f.ID}); err != nil {
+ t.Fatal(err)
+ }
+
+ expires := time.Now().UTC().Add(wire.SealedTTL).Truncate(time.Second)
+ sealed, err := sealbox.Seal(keys.PublicString(), wire.SealedPayload{Secret: canaryToken, RunnerID: runnerID, ConnectionID: attempt.ID, Provider: "claude", Endpoint: wire.EndpointAnthropic, Attempt: 1, ExpiresAt: expires})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for name, change := range map[string]func(*wire.Sealed){
+ "another runner": func(s *wire.Sealed) { s.RunnerID = "rn_other" },
+ "another connection": func(s *wire.Sealed) { s.ConnectionID = "cn_other" },
+ "another provider": func(s *wire.Sealed) { s.Provider = "codex" },
+ "another endpoint": func(s *wire.Sealed) { s.Endpoint = "https://api.anthropic.com" },
+ "attempt 2": func(s *wire.Sealed) { s.Attempt = 2 },
+ "expired": func(s *wire.Sealed) { s.ExpiresAt = time.Now().Add(-time.Second) },
+ "too far ahead": func(s *wire.Sealed) { s.ExpiresAt = time.Now().Add(wire.SealedTTL + 2*time.Minute) },
+ "too big": func(s *wire.Sealed) { s.Box = strings.Repeat("A", wire.MaxSealedBytes+4) },
+ "not base64": func(s *wire.Sealed) { s.Box = "not base64!" },
+ "too short to open": func(s *wire.Sealed) { s.Box = base64.StdEncoding.EncodeToString(make([]byte, 40)) },
+ } {
+ bad := sealed
+ change(&bad)
+ if _, err := r.client.Secret(r.ctx, attempt.ID, bad); Status(err) != 422 {
+ t.Fatalf("%s: %v", name, err)
+ }
+ }
+ if _, err := r.client.Secret(r.ctx, "cn_nobody", sealed); Status(err) != 404 {
+ t.Fatalf("an unknown attempt: %v", err)
+ }
+ var queued int
+ if err = r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE kind = ?", wire.FrameSecret).Scan(&queued); err != nil || queued != 0 {
+ t.Fatalf("a refused box was queued: %d %v", queued, err)
+ }
+
+ posted, err := r.client.Secret(r.ctx, attempt.ID, sealed)
+ if err != nil || posted.ID != attempt.ID || posted.State != wire.ConnConnecting || posted.Prompt != nil {
+ t.Fatalf("secret %+v %v", posted, err)
+ }
+ // One box per attempt: the runner would refuse a second anyway.
+ if _, err := r.client.Secret(r.ctx, attempt.ID, sealed); Status(err) != 409 {
+ t.Fatalf("a second box: %v", err)
+ }
+ f, body, err = runner.Expect(r.ctx, wire.FrameSecret)
+ if err != nil {
+ t.Fatal(err)
+ }
+ shape(t, "frames/secret.json", runner.Received[len(runner.Received)-1])
+ cmd := body.(*wire.SecretCommand)
+ if cmd.Connection != attempt.ID || cmd.Person != Owner || cmd.Sealed.Box != sealed.Box || !cmd.Sealed.ExpiresAt.Equal(expires) {
+ t.Fatalf("secret frame %+v", cmd)
+ }
+ if opened, err := keys.Open(cmd.Sealed, time.Now()); err != nil || opened.Secret != canaryToken {
+ t.Fatalf("the runner could not open the box: %v", err)
+ }
+ stored := func() string {
+ var b string
+ if err := r.inst.DB.Writer().QueryRow("SELECT group_concat(body, '|') FROM runner_commands WHERE kind = ?", wire.FrameSecret).Scan(&b); err != nil {
+ t.Fatal(err)
+ }
+ return b
+ }
+ if !strings.Contains(stored(), sealed.Box) {
+ t.Fatal("the box is not in the mailbox before the ack")
+ }
+ if err = runner.Send(r.ctx, "a-secret", wire.FrameAck, wire.Ack{ID: f.ID}); err != nil {
+ t.Fatal(err)
+ }
+ waitFor(t, "the box blanked after the ack", func() bool { return !strings.Contains(stored(), sealed.Box) })
+
+ // The runner's word: healthy, and its hello with the token's expiry.
+ tokenExpires := time.Now().UTC().Add(wire.TokenLifetime).Truncate(time.Second)
+ 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)
+ }
+ hello.Connections = []wire.HeldConnection{{LocalID: "claude-1", Person: Owner, Provider: "claude", Kind: wire.KindToken, Label: Owner, State: wire.ConnHealthy, ExpiresAt: &tokenExpires}}
+ if err = runner.Send(r.ctx, "h2", wire.FrameHello, hello); err != nil {
+ t.Fatal(err)
+ }
+ r.wait("healthy with the token's expiry", func(c *Conversation) bool {
+ v := c.Connections[attempt.ID]
+ return v.State == wire.ConnHealthy && v.ExpiresAt != nil && v.ExpiresAt.Equal(tokenExpires)
+ })
+ if got, err := r.client.Connection(r.ctx, attempt.ID); err != nil || got.ExpiresAt == nil || !got.ExpiresAt.Equal(tokenExpires) || got.Kind != wire.KindToken {
+ t.Fatalf("connection %+v %v", got, err)
+ }
+
+ // The sweep: everything the instance serves, logs or keeps on disk.
+ var sinks []string
+ for _, path := range []string{"/conversation/connections", "/conversation", "/conversation/settings"} {
+ sinks = append(sinks, r.inst.Get(t, path))
+ }
+ if _, err := r.client.Connections(r.ctx); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := r.client.Snapshot(r.ctx); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := r.client.Runners(r.ctx); err != nil {
+ t.Fatal(err)
+ }
+ served := append(sinks, rawEvents(t, r), rec.String(), r.inst.Logs())
+ 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)
+ served = append(served, events, rows)
+ canaries := []string{canaryToken, base64.StdEncoding.EncodeToString([]byte(canaryToken)), "CANARY"}
+ for i, s := range served {
+ for _, c := range canaries {
+ if strings.Contains(s, c) {
+ t.Fatalf("sink %d holds the canary %q", i, c)
+ }
+ }
+ if strings.Contains(s, sealed.Box) || strings.Contains(s, sealed.Box[:24]) {
+ t.Fatalf("sink %d holds the sealed box", i)
+ }
+ }
+ // On disk only the ciphertext may remain (WAL residue), never the
+ // plaintext.
+ 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 canary %q", suffix, c)
+ }
+ }
+ }
+}
+
+// TestContractTokenAttemptEnds: an attempt cancelled before its runner
+// took the box takes the box with it; a seal key that is not an X25519
+// public key is never published.
+func TestContractTokenAttemptEnds(t *testing.T) {
+ r := newRig(t)
+ keys := sealKeys(t)
+ hello := held()
+ hello.SealKey = base64.StdEncoding.EncodeToString([]byte("not a key"))
+ runner, err := DialRunnerHello(r.ctx, r.inst.URL, r.runner, hello)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(runner.Close)
+ r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online })
+ if list, err := r.client.Runners(r.ctx); err != nil || len(list.Items) != 1 || list.Items[0].SealKey != "" {
+ t.Fatalf("a malformed seal key was published: %+v %v", list, err)
+ }
+ attempt, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude", Kind: wire.KindToken})
+ if err != nil {
+ t.Fatal(err)
+ }
+ sealed, err := sealbox.Seal(keys.PublicString(), wire.SealedPayload{Secret: canaryToken, RunnerID: attempt.RunnerID, ConnectionID: attempt.ID, Provider: "claude", Endpoint: wire.EndpointAnthropic, Attempt: 1, ExpiresAt: time.Now().UTC().Add(5 * time.Minute)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = r.client.Secret(r.ctx, attempt.ID, sealed); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = r.client.CancelConnection(r.ctx, attempt.ID); err != nil {
+ t.Fatal(err)
+ }
+ var bodies string
+ if err = r.inst.DB.Writer().QueryRow("SELECT group_concat(body, '|') || group_concat(acked_at IS NOT NULL, '') FROM runner_commands WHERE kind = ?", wire.FrameSecret).Scan(&bodies); err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(bodies, sealed.Box) || !strings.HasSuffix(bodies, "1") {
+ t.Fatalf("the cancelled attempt's box stays in the mailbox: %.120s", bodies)
+ }
+ // A box for an attempt that ended is refused.
+ if _, err = r.client.Secret(r.ctx, attempt.ID, sealed); Status(err) != 409 {
+ t.Fatalf("a box for an ended attempt: %v", err)
+ }
+}
+
+func waitFor(t *testing.T, what string, cond func() bool) {
+ t.Helper()
+ deadline := time.Now().Add(10 * time.Second)
+ for !cond() {
+ if time.Now().After(deadline) {
+ t.Fatalf("timed out waiting for %s", what)
+ }
+ time.Sleep(25 * time.Millisecond)
+ }
+}
diff --git a/internal/wire/wiretest/testdata/api/event-runner.json b/internal/wire/wiretest/testdata/api/event-runner.json
index 052d33de..d0436903 100644
--- a/internal/wire/wiretest/testdata/api/event-runner.json
+++ b/internal/wire/wiretest/testdata/api/event-runner.json
@@ -1 +1 @@
-{"cursor":43,"type":"runner","resource":"runner","id":"RUNNER1","revision":4,"data":{"id":"RUNNER1","revision":4,"online":false,"label":"docs-t1","role":"primary","since":"2026-11-07T10:12:00Z","platform":null,"capabilities":null,"removing":false}}
\ No newline at end of file
+{"cursor":43,"type":"runner","resource":"runner","id":"RUNNER1","revision":4,"data":{"id":"RUNNER1","revision":4,"online":false,"label":"docs-t1","role":"primary","since":"2026-11-07T10:12:00Z","platform":null,"capabilities":null,"removing":false,"seal_key":""}}
\ No newline at end of file
diff --git a/scripts/runner-reference-allowlist.json b/scripts/runner-reference-allowlist.json
index 7ae8b43a..0f479bec 100644
--- a/scripts/runner-reference-allowlist.json
+++ b/scripts/runner-reference-allowlist.json
@@ -10907,14 +10907,14 @@
},
{
"path": "internal/wire/wiretest/testdata/api/runners.json",
- "line_sha256": "76ac979bf9acee38cd7c1d37e5fcd09c675a916d6ed6ac348bab6c4a6685d69d",
+ "line_sha256": "98d1aae0108824520c411adc2112620addcdcd0a2ded757a9ac04b1e4c3c9414",
"match": "node",
"count": 2,
"reason": "Recorded runners fixture: the node toolchain version in a capability report."
},
{
"path": "internal/wire/wiretest/testdata/frames/hello-mac.json",
- "line_sha256": "61d1fbf2209785cb7c52c077a4f76dd59c6902c2a5c9694fe0cbdae50fd9b33b",
+ "line_sha256": "9cdc375d2535217ec19e50fdf1f27d6ab891a8d324424cd31524e43866d096c3",
"match": "node",
"count": 1,
"reason": "Recorded Mac hello fixture: the node toolchain version in its capability report."
@@ -11166,7 +11166,7 @@
},
{
"path": "internal/wire/wiretest/testdata/frames/hello-mac-probes.json",
- "line_sha256": "7c1514f581e43cf001aec9df10a3f08626277be4696fbda524072c6acb073677",
+ "line_sha256": "9b35f3cc57c055aa83964c4d5e26b47bac6650854232bcfd64d3b234f8f3302c",
"match": "node",
"count": 2,
"reason": "Mac runner (darwin worker): the runner executable, its launchd agent, install paths, the pinned srt package and Node it needs, and their tests and docs."
@@ -12759,5 +12759,12 @@
"match": "equipo-runner",
"count": 1,
"reason": "Mac runner (darwin worker): the runner executable, its launchd agent, install paths, the pinned srt package and Node it needs, and their tests and docs."
+ },
+ {
+ "path": "internal/equipo/static/vendor/tweetnacl/nacl-fast.js",
+ "line_sha256": "bfedf17d7072c65f4f424639268a9d6b0bb5291edd92fb998282c19332772b5b",
+ "match": "Node",
+ "count": 1,
+ "reason": "Vendored tweetnacl (public domain): its Node.js crypto fallback comment; the browser uses crypto.getRandomValues."
}
]