feat: onboard personal accounts and a safe first task
32 files changed,
+2,171
−20
.rastrillo/budgets.txt+2 −0cmd/equipo-runner/account_environment.go+51 −0cmd/equipo-runner/account_login.go+29 −0cmd/equipo-runner/account_login_test.go+121 −0cmd/equipo-runner/main.go+3 −0docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+86 −0docs/superpowers/plans/LIVE-GATE-plan-3.md+35 −0internal/equipo/account_setup.go+14 −0internal/equipo/copy.go+39 −0internal/equipo/invitations.go+5 −1internal/equipo/migrations/0028_setup_accounts.sql+17 −0internal/equipo/migrations/schema.sql+17 −0internal/equipo/runner_api.go+1 −1internal/equipo/setup/account_connection.go+22 −0internal/equipo/setup/account_handlers.go+93 −0internal/equipo/setup/accounts.go+315 −0internal/equipo/setup/invites.go+4 −1internal/equipo/setup/onboarding_handlers.go+38 −0internal/equipo/templates/connections.html+1 −1internal/equipo/templates/onboarding.html+16 −2internal/plan3test/onboarding_accounts_migration_test.go+50 −0internal/plan3test/onboarding_accounts_test.go+283 −0internal/runner/account_login.go+41 −0internal/runner/connections.go+3 −13internal/runner/provider/login.go+56 −0internal/runner/runtime_direct.go+1 −1internal/runner/setup/account_bindings.go+103 −0internal/runner/setup/account_login.go+199 −0internal/runner/setup/account_login_test.go+187 −0internal/runner/setup/account_terminal_test.go+261 −0internal/runnerproto/account_setup.go+76 −0internal/runnerproto/handler.go+2 −0
CI failed — run details
Intent
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 39a44646..9b66b530 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -27,3 +27,5 @@ time internal/runner/provider/codex 15s Task 11a full branch gate measured 11.65 |
| time internal/directlive 360s Task 5 adds both coordinator policy cases to the fake certification matrix. The targeted 19-case fixture measured 287.275s; 360s leaves 25 percent headroom for namespaces, both adapters, journal, MCP probes and package siblings. Full-package timing is deferred by the targeted-only dispatch. |
| time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops. |
| + |
| +size internal/plan3test - 8600 Task 17 adds account setup authority, secret projection, migration and onboarding regressions beside the shared fixture harness. Measured 8331 test lines; source remains within the default. The existing 300s integration time ceiling is unchanged. |
diff --git a/cmd/equipo-runner/account_environment.go b/cmd/equipo-runner/account_environment.go| new file mode 100644 |
| index 00000000..c8bc222d |
| --- /dev/null |
| +++ b/cmd/equipo-runner/account_environment.go |
| @@ -0,0 +1,51 @@ |
| +package main |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| +) |
| + |
| +func accountEnvironment(getenv func(string) string) (func(string) string, error) { |
| + if getenv("EQUIPO_ORIGIN") != "" { |
| + return getenv, nil |
| + } |
| + home := getenv("HOME") |
| + if !filepath.IsAbs(home) { |
| + return nil, provider.ErrContract |
| + } |
| + path := filepath.Join(home, ".local/share/equipo-runner/runner.env") |
| + real, e := filepath.EvalSymlinks(path) |
| + if e != nil || real != path { |
| + return nil, provider.ErrPolicy |
| + } |
| + st, e := os.Lstat(path) |
| + if e != nil || !st.Mode().IsRegular() || st.Mode().Perm() != 0600 || st.Size() > 65536 { |
| + return nil, provider.ErrPolicy |
| + } |
| + raw, e := os.ReadFile(path) |
| + if e != nil { |
| + return nil, provider.ErrPolicy |
| + } |
| + values := map[string]string{} |
| + for _, line := range strings.Split(string(raw), "\n") { |
| + if line == "" || strings.HasPrefix(line, "#") { |
| + continue |
| + } |
| + key, value, ok := strings.Cut(line, "=") |
| + if !ok || !strings.HasPrefix(key, "EQUIPO_") { |
| + return nil, provider.ErrContract |
| + } |
| + if _, ok = values[key]; ok { |
| + return nil, provider.ErrContract |
| + } |
| + v, e := strconv.Unquote(value) |
| + if e != nil { |
| + return nil, provider.ErrContract |
| + } |
| + values[key] = v |
| + } |
| + return func(k string) string { return values[k] }, nil |
| +} |
diff --git a/cmd/equipo-runner/account_login.go b/cmd/equipo-runner/account_login.go| new file mode 100644 |
| index 00000000..268fe16d |
| --- /dev/null |
| +++ b/cmd/equipo-runner/account_login.go |
| @@ -0,0 +1,29 @@ |
| +package main |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "context" |
| + "fmt" |
| + "io" |
| +) |
| + |
| +func accountLogin(ctx context.Context, args []string, output io.Writer, getenv func(string) string) int { |
| + if len(args) != 3 || args[0] != "login" || args[1] != "--setup" || args[2] == "" { |
| + return 1 |
| + } |
| + env, err := accountEnvironment(getenv) |
| + if err != nil { |
| + _, _ = fmt.Fprintln(output, equipo.RunnerText("account_setup.unavailable")) |
| + return 1 |
| + } |
| + cfg, err := runner.LoadConfig(env) |
| + if err == nil { |
| + err = runner.LoginAccount(ctx, cfg, args[2]) |
| + } |
| + if err != nil { |
| + _, _ = fmt.Fprintln(output, equipo.RunnerText("account_setup.unavailable")) |
| + return 1 |
| + } |
| + return 0 |
| +} |
diff --git a/cmd/equipo-runner/account_login_test.go b/cmd/equipo-runner/account_login_test.go| new file mode 100644 |
| index 00000000..bf5fc74d |
| --- /dev/null |
| +++ b/cmd/equipo-runner/account_login_test.go |
| @@ -0,0 +1,121 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +type accountTransport func(*http.Request) (*http.Response, error) |
| + |
| +func (f accountTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| +func TestOnboardingClaudeHeadlessBrowserLogin(t *testing.T) { |
| + root := t.TempDir() |
| + fake := filepath.Join(root, "fake") |
| + if e := os.WriteFile(fake, []byte("#!/bin/sh\nexit 99\n"), 0700); e != nil { |
| + t.Fatal(e) |
| + } |
| + state := filepath.Join(root, "state") |
| + if e := os.Mkdir(state, 0700); e != nil { |
| + t.Fatal(e) |
| + } |
| + cred := runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Token: "fixture-bearer", RunnerID: "runner", Person: "person", ExpiresAt: time.Now().Add(time.Hour)}} |
| + raw, _ := json.Marshal(cred) |
| + if e := os.WriteFile(filepath.Join(state, "credentials.json"), raw, 0600); e != nil { |
| + t.Fatal(e) |
| + } |
| + values := map[string]string{"HOME": root, "EQUIPO_ORIGIN": "https://fixture.test", "EQUIPO_INSTANCE_ID": "team", "EQUIPO_RUNNER_STATE_DIR": state, "EQUIPO_WORKSPACE_ROOT": filepath.Join(root, "work"), "EQUIPO_SCRATCH_ROOT": filepath.Join(root, "scratch")} |
| + for _, key := range []string{"EQUIPO_CLAUDE_PATH", "EQUIPO_CODEX_PATH", "EQUIPO_AMADAN_PATH", "EQUIPO_BWRAP_PATH", "EQUIPO_CODEX_CODE_MODE_HOST_PATH", "EQUIPO_ACCOUNT_BINDINGS_PATH", "EQUIPO_AMADAN_CREDENTIAL_PATH", "EQUIPO_GO_ROOT", "EQUIPO_GO_BINARY", "EQUIPO_GIT_PATH"} { |
| + values[key] = fake |
| + } |
| + prior := http.DefaultTransport |
| + t.Cleanup(func() { http.DefaultTransport = prior }) |
| + calls := 0 |
| + http.DefaultTransport = accountTransport(func(r *http.Request) (*http.Response, error) { |
| + calls++ |
| + if r.URL.Path != "/api/runner/v2/account-setups" || r.Header.Get("Authorization") != "Bearer fixture-bearer" { |
| + t.Fatal("wrong authenticated channel", r.URL) |
| + } |
| + var q runnerproto.AccountSetupRequest |
| + if e := runnerproto.Decode(r.Body, &q); e != nil { |
| + t.Fatal(e) |
| + } |
| + if q.ID != "pending-setup" { |
| + t.Fatal("wrong setup ID") |
| + } |
| + s := runnerproto.AccountSetup{ID: q.ID, RunnerID: "runner", Provider: "claude", State: "pending", Mode: "browser", Revision: 1} |
| + if calls == 2 { |
| + if q.Result == nil || q.Result.State != "unavailable" || q.Result.Challenge != nil { |
| + t.Fatal("unconfirmed contract accepted", q) |
| + } |
| + s.State = "unavailable" |
| + s.Revision = 2 |
| + } |
| + raw, _ := runnerproto.Marshal(runnerproto.WorkResponse{Version: 2, Result: s}) |
| + return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(raw)), Header: make(http.Header)}, nil |
| + }) |
| + var out, logs bytes.Buffer |
| + code := run(context.Background(), []string{"account", "login", "--setup", "pending-setup"}, strings.NewReader("TERMINAL-RETURN-SECRET\n"), &out, &logs, func(k string) string { return values[k] }) |
| + if code != 1 || calls != 2 || strings.Contains(logs.String(), "SECRET") || strings.Contains(logs.String(), "fixture-bearer") || strings.Contains(logs.String(), root) { |
| + t.Fatal("unsafe terminal command", code, calls, logs.String()) |
| + } |
| + if _, e := os.Stat(filepath.Join(state, "accounts")); !os.IsNotExist(e) { |
| + t.Fatal("unavailable flow allocated a credential home") |
| + } |
| + calls = 0 |
| + for _, args := range [][]string{{"account", "login"}, {"account", "login", "--setup", "id", "--code", "SECRET"}, {"account", "login", "--setup", ""}} { |
| + if run(context.Background(), args, strings.NewReader(""), &out, &logs, func(k string) string { return values[k] }) != 1 { |
| + t.Fatal("invalid login argv accepted") |
| + } |
| + } |
| + if calls != 0 { |
| + t.Fatal("invalid argv reached instance") |
| + } |
| +} |
| + |
| +func TestOnboardingAccountEnvironment(t *testing.T) { |
| + root := t.TempDir() |
| + dir := filepath.Join(root, ".local/share/equipo-runner") |
| + if e := os.MkdirAll(dir, 0700); e != nil { |
| + t.Fatal(e) |
| + } |
| + path := filepath.Join(dir, "runner.env") |
| + data := "EQUIPO_ORIGIN=\"https://fixture.test\"\nEQUIPO_INSTANCE_ID=\"fixture\"\n" |
| + if e := os.WriteFile(path, []byte(data), 0600); e != nil { |
| + t.Fatal(e) |
| + } |
| + getenv := func(k string) string { |
| + if k == "HOME" { |
| + return root |
| + } |
| + return "" |
| + } |
| + env, e := accountEnvironment(getenv) |
| + if e != nil || env("EQUIPO_ORIGIN") != "https://fixture.test" { |
| + t.Fatal("installed configuration not read", e) |
| + } |
| + if e = os.Chmod(path, 0644); e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = accountEnvironment(getenv); e == nil { |
| + t.Fatal("shared configuration accepted") |
| + } |
| + if e = os.Chmod(path, 0600); e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = os.WriteFile(path, []byte(data+"EQUIPO_INSTANCE_ID=\"changed\"\n"), 0600); e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = accountEnvironment(getenv); e == nil { |
| + t.Fatal("duplicate environment accepted") |
| + } |
| +} |
diff --git a/cmd/equipo-runner/main.go b/cmd/equipo-runner/main.go| index 287948cb..e6573249 100644 |
| --- a/cmd/equipo-runner/main.go |
| +++ b/cmd/equipo-runner/main.go |
| @@ -29,6 +29,9 @@ func run(ctx context.Context, args []string, input io.Reader, output, errorOutpu |
| } |
| return 0 |
| } |
| + if len(args) > 0 && args[0] == "account" { |
| + return accountLogin(ctx, args[1:], errorOutput, getenv) |
| + } |
| if len(args) > 0 && args[0] == "install" { |
| return installRunner(ctx, args[1:], input, output, errorOutput, getenv) |
| } |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index 75906801..b60190db 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -4206,3 +4206,89 @@ The full task report is also appended at .superpowers/sdd/2026-11-04-equipo-plan |
| ### Session |
| All verification processes have exited. No server, watcher or real user service was started. No sign-in, provider session, machine enrolment, lingering, sysctl, AppArmor or real user config operation occurred. Go caches remained at their defaults. The task's TMPDIR scratch is removed before handoff. Source and controller-report changes are committed locally; the ignored task report is saved in place. Safe to close. |
| + |
| +## Task 17: personal accounts and safe first task |
| + |
| +Status: DONE_WITH_CONCERNS. Production login is unavailable pending the 3b offline-contract gaps recorded in LIVE-GATE-plan-3.md. No real provider run, sign-in or enrolment occurred. The implementation adds private setup records, runner-authenticated result correlation, dedicated-home and identity guards, terminal-command dispatch, safe metadata projections, cancellation, onboarding forms, Task 12 library links and a sourced recommendation first task. Synthetic terminal fixtures do not certify real provider login. |
| + |
| +Implementation subject: `feat: onboard personal accounts and a safe first task`. Author: `codex <codex~paul@keymail.dev>`. Local commit only. |
| + |
| +### Tests first |
| + |
| +The mandated first command was: |
| + |
| +`CGO_ENABLED=0 go test ./internal/runner/... ./internal/plan3test -run '^TestOnboarding(Account|Device|Claude|NoDevice|Safe|Specialists)' -count=1` |
| + |
| +It exited 1 before implementation: RequestAccountSetup, AccountSetup, CancelAccountSetup, StartOnboardingTask and AccountSetupResult were undefined. The new runner test initially used the wrong package name; after correcting it to runnersetup, `CGO_ENABLED=0 go test ./internal/runner/setup -run '^TestOnboarding(Account|Device|NoDevice)' -count=1` exited 1 because LoginChallenge, LoginResult and AccountLogin did not exist. Both packages then passed the original named tests after implementation. |
| + |
| +The specialist-stage rendering test was tightened to inspect the stage's own list, rather than matching sidebar links. `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestOnboardingSpecialists$' -count=1` exited 1 with `specialist-stage choices missing`, then passed after the list was rendered (0.541s). Test-fixture fixes during iteration corrected the person-step key to the existing required `merge` key, used a private subdirectory for homes, and used snake-case runner wire encoding in the command transport fixture. |
| + |
| +### Verification |
| + |
| +All final commands below exited 0. No full suite or `make ci` ran. |
| + |
| +- `CGO_ENABLED=0 go test ./internal/runner/... ./internal/plan3test -run '^TestOnboarding(Account|Device|Claude|NoDevice|Safe|Specialists)' -count=1` passed after implementation. The final expanded command below includes command and setup regressions too. |
| +- `CGO_ENABLED=0 go test ./internal/runner/... ./internal/plan3test ./cmd/equipo-runner ./internal/equipo/setup -run '^TestOnboarding(Account|Device|Claude|NoDevice|Safe|Specialists|InstallPrerequisites)' -count=1`. Final timings: runner/setup 0.609s, plan3test 2.067s, command 0.141s, equipo/setup 0.701s. Other runner packages compiled and reported no matching tests. |
| +- `CGO_ENABLED=0 go test ./internal/equipotest -run '^Test(ConnectionsBelongToPersonAndMachine|ConnectionsHTTPAuthority|ConnectionsAtomicWrites|ConnectionSelectionModelAndAllowance|ReviewWaitsForOtherFamily|EnrolmentAudience|RunnerRemovalRevokes|SpecialistsSeedOnce|SpecialistSettingsCurrentOwner|RunnerAppCSRF)$' -count=1`: 6.389s. |
| +- `CGO_ENABLED=0 go test ./internal/runner ./internal/runner/provider ./internal/runnerproto -run '^Test(AccountHomeBinding|AccountHomeConfigured|AccountHomeRefresh|RunnerConfig|RunnerServiceLifecycle|OnboardingServiceWithoutAccounts|DirectBinding|Wire|Decode)' -count=1`: runner 0.282s and provider 0.080s; runnerproto compiled with no matching tests. |
| +- After excluding display labels from the binding policy hash: `CGO_ENABLED=0 go test ./internal/runner -run '^Test(AccountHomeConfigured|RunnerConfig|OnboardingServiceWithoutAccounts)' -count=1`: 0.199s. |
| +- `make migration-check`: TestMigrationModels passed, 0.152s. |
| +- `CGO_ENABLED=0 go test ./internal/equipo -run '^Test(TemplateCopyKeys|MigrationModels|ConversationMigrationSnapshot)$' -count=1`: 2.409s. |
| +- `CGO_ENABLED=0 go vet ./internal/equipo ./internal/equipo/setup ./internal/runner ./internal/runner/setup ./internal/runner/provider ./internal/runnerproto ./internal/plan3test ./cmd/equipo-runner`. |
| +- `CGO_ENABLED=0 go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./internal/equipo ./internal/equipo/setup ./internal/runner ./internal/runner/setup ./internal/runner/provider ./internal/runnerproto ./internal/plan3test ./cmd/equipo-runner`. Its first run exited 1 for three numeric HTTP 303 literals; those now use http.StatusSeeOther and the final run passed. |
| +- `make budget`: 34 directories within budget. `gofmt -l` over all changed/new Go files and `git diff --check`: no output. |
| + |
| +### Guard mutations |
| + |
| +Each mutation below was applied alone, produced a behavioral test failure (exit 1), and was restored immediately. The final expanded test command ran after all restorations. An initial generation mutation produced an unused-variable compilation failure; it was discarded and rerun as a compiling conditional bypass. Only that corrected behavioral result is counted here. |
| + |
| +- **dedicated homes**: `CGO_ENABLED=0 go test ./internal/runner/setup -run ^TestOnboardingAccountDedicatedHome$ -count=1`. Exit 1. `account_login_test.go:98: interactive home accepted` Restored. |
| + |
| +- **identity readback**: `CGO_ENABLED=0 go test ./internal/runner/setup -run ^TestOnboardingAccountIdentityReadback$ -count=1`. Exit 1. `account_terminal_test.go:215: identity readback bypassed` Restored. |
| + |
| +- **secret projection**: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestOnboardingAccountRunnerGuards$ -count=1`. Exit 1. `onboarding_accounts_test.go:179: browser challenge stored <nil>` Restored. |
| + |
| +- **roster**: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestOnboardingClaudeHeadlessBrowserLogin$ -count=1`. Exit 1. `onboarding_accounts_test.go:63: removed member replay <nil>` Restored. |
| + |
| +- **runner generation**: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestOnboardingAccountLifecycle$ -count=1`. Exit 1. `onboarding_accounts_test.go:86: stale generation pending` Restored. |
| + |
| +- **expiry**: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestOnboardingAccountLifecycle$ -count=1`. Exit 1. `onboarding_accounts_test.go:80: expired setup pending` Restored. |
| + |
| +- **read permissions**: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestOnboardingSafeFirstTask$ -count=1`. Exit 1. `plan_workflow_test.go:25: research gained write authority: {RequestKey:task/plan/1 Project:1 Account:team Parent:0 Requester:owner@example.com GrantRef:eyJ2ZXJzaW9uIjoxLCJwcm9qZWN0X2lkIjoxLCJhZGRyZXNzIjoib3duZXJAZXhhbXBsZS5jb20ifQ Target:{Kind:projec…` Restored. |
| + |
| +- **review family**: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestOnboardingSafeFirstTask$ -count=1`. Exit 1. `plan_model_choice_test.go:109: The information is unavailable. Try again in a minute.` Restored. |
| + |
| +- **terminal cancellation**: `CGO_ENABLED=0 go test ./internal/runner/setup -run ^TestOnboardingAccountTerminalCancellation$ -count=1`. Exit 1. `account_terminal_test.go:235: terminal child survived cancellation` Restored. |
| + |
| +- **new account preserves old binding**: `CGO_ENABLED=0 go test ./internal/runner/setup -run ^TestOnboardingAccountBindings$ -count=1`. Exit 1. `account_login_test.go:166: new setup replaced existing home` Restored. |
| + |
| +### Schema, budget and self-review |
| + |
| +The new additive full migration ID is equipo/0028_setup_accounts, ordered after 0028_onboarding and before the reserved 0029 team-links task. Models, fresh/upgrade comparison and schema snapshot checks pass. No old migration was changed. Root source remains at 10,780/10,800 lines and runner at 9,399/9,400. plan3test has 8,331 test lines with an 8,600-line exception; its 300s time allowance is unchanged. Source and test checks pass across 34 directories. |
| + |
| +Authority and audit share the write transaction. Result replay rechecks current credentials and roster before canonical input comparison. Initial connection metadata leaves containment, availability and allowance unclaimed. Existing AccountLease refresh rules are preserved. New binding saves refuse replacement, and uncertain restart cannot claim connected. The production driver, identity-probe/binding wiring and real full onboarding exercise remain explicit live-gate work. No copy review, subagent, .claude/HANDOFF.md or README change occurred. |
| + |
| +### Pending copy (COPY REVIEW REQUIRED) |
| + |
| +| Key | Draft text | |
| +| --- | --- | |
| +| account_setup.title | Connect a model account | |
| +| account_setup.label | Account label | |
| +| account_setup.runner | Paired machine | |
| +| account_setup.add | Connect account | |
| +| account_setup.dedicated | Each account uses a new private home on your runner. | |
| +| account_setup.browser | Run this command on the paired machine. Open the official sign-in link there and paste the returned code only into that terminal. | |
| +| account_setup.command | equipo-runner account login --setup %s | |
| +| account_setup.cancel | Cancel sign-in | |
| +| account_setup.pending | Waiting for sign-in on your runner. | |
| +| account_setup.waiting_runner | Waiting for the runner to report this account. | |
| +| account_setup.connected | Account connected. | |
| +| account_setup.expired | Sign-in expired. Start again. | |
| +| account_setup.denied | Sign-in was denied. | |
| +| account_setup.cancelled | Sign-in cancelled. | |
| +| account_setup.unavailable | This login flow is not available for the installed provider version. | |
| +| onboarding.library | Add specialists from the library | |
| +| onboarding.start_task | Read and recommend | |
| +| onboarding.first_instructions | Read the project material and recommend what to work on next. Cite the sources for each recommendation. Do not edit files, create a branch or publish changes. | |
| + |
| +Full report: `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-17-report.md` (local, ignored). |
diff --git a/docs/superpowers/plans/LIVE-GATE-plan-3.md b/docs/superpowers/plans/LIVE-GATE-plan-3.md| index 3ee562dc..9e18eda0 100644 |
| --- a/docs/superpowers/plans/LIVE-GATE-plan-3.md |
| +++ b/docs/superpowers/plans/LIVE-GATE-plan-3.md |
| @@ -140,3 +140,38 @@ question and cancellation outcomes, and Paul's merge reference in the controller |
| report. Stop the disposable instance and runner, verify that their children have |
| exited, and remove only scratch created for this run. Preserve the private evidence |
| bundle and the dedicated homes. Do not publish secrets or sign-in links. |
| + |
| +## 3b: account login contracts |
| + |
| +Task 17 keeps production account login unavailable. The offline Plan 2b guide, |
| +`docs/live-gate.md`, records `claude auth login` and `codex login` with dedicated |
| +homes. The provider fixtures record session and account readback protocols, but |
| +contain no device-login transcript or headless browser return-code transcript. |
| +They do not confirm `codex login --device-auth` for 0.165.0, the device display |
| +format, cancellation and expiry signals, or Claude 2.1.312's headless exchange |
| +and callback listener behavior. No provider was invoked to fill these gaps. |
| + |
| +Before enabling either production driver, Paul must explicitly authorize a |
| +separate exercise with new dedicated accounts. Record the pinned binary's |
| +supported login commands and the complete terminal flow, then sanitize the |
| +recording. Confirm that Codex supports the official device flow and that Claude |
| +supports opening its official link on another device with the returned code |
| +entered only at the runner terminal. Any callback listener must bind loopback, |
| +belong to the setup process and close on success, cancellation and expiry. |
| +Do not infer a verification address or use private OAuth endpoints. |
| + |
| +Implement the driver against those recordings, including identity readback, |
| +terminal process cancellation and expiry. Wire its verified binding into the |
| +runner's account file and ordinary connection reports. The current production |
| +constructor deliberately cannot launch either CLI; the terminal and device |
| +fixtures test the local boundary only and are not provider certification. |
| +Exercise the complete command, instance correlation and restarted runner with |
| +two labeled accounts from one provider. Verify that a repeated result does not |
| +create another connection, unknown allowance stays unknown, and a new login |
| +never replaces an existing home. Retain the existing same-identity refresh |
| +rules. Confirm that credentials, polling secrets and browser return codes are |
| +absent from instance traffic, browser forms, logs, journals and audit records. |
| + |
| +The synthetic terminal fixture uses a pseudo-terminal and fake binaries under |
| +TMPDIR. It establishes no claim about a real provider's browser exchange. |
| +App copy added for these states remains marked COPY REVIEW REQUIRED in copy.go. |
diff --git a/internal/equipo/account_setup.go b/internal/equipo/account_setup.go| new file mode 100644 |
| index 00000000..261ba031 |
| --- /dev/null |
| +++ b/internal/equipo/account_setup.go |
| @@ -0,0 +1,14 @@ |
| +package equipo |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/setup" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| + "context" |
| +) |
| + |
| +type AccountSetup = setup.AccountSetup |
| +type LoginDisplay = setup.LoginDisplay |
| + |
| +func (s *Store) StartOnboardingTask(ctx context.Context, a Actor, projectID int64, m Mutation) (taskplan.Plan, error) { |
| + return s.ProposePlan(ctx, a, taskplan.Plan{ProjectID: projectID, Kind: taskplan.Recommendation, Steps: []taskplan.Step{{Key: "research", Specialist: "product", Action: "recommend", Instructions: copyOnboardingFirstInstructions}, {Key: "merge", Action: "person"}}}, m) |
| +} |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 5ecc7c86..109215b2 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -48,6 +48,42 @@ const BootLog = "Equipo could not start." |
| // COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules). |
| var pageCopy = map[string]string{ |
| + // COPY REVIEW REQUIRED: account_setup.title |
| + "account_setup.title": "Connect a model account", |
| + // COPY REVIEW REQUIRED: account_setup.label |
| + "account_setup.label": "Account label", |
| + // COPY REVIEW REQUIRED: account_setup.runner |
| + "account_setup.runner": "Paired machine", |
| + // COPY REVIEW REQUIRED: account_setup.add |
| + "account_setup.add": "Connect account", |
| + // COPY REVIEW REQUIRED: account_setup.dedicated |
| + "account_setup.dedicated": "Each account uses a new private home on your runner.", |
| + // COPY REVIEW REQUIRED: account_setup.browser |
| + "account_setup.browser": "Run this command on the paired machine. Open the official sign-in link there and paste the returned code only into that terminal.", |
| + // COPY REVIEW REQUIRED: account_setup.command |
| + "account_setup.command": "equipo-runner account login --setup %s", |
| + // COPY REVIEW REQUIRED: account_setup.cancel |
| + "account_setup.cancel": "Cancel sign-in", |
| + // COPY REVIEW REQUIRED: account_setup.pending |
| + "account_setup.pending": "Waiting for sign-in on your runner.", |
| + // COPY REVIEW REQUIRED: account_setup.waiting_runner |
| + "account_setup.waiting_runner": "Waiting for the runner to report this account.", |
| + // COPY REVIEW REQUIRED: account_setup.connected |
| + "account_setup.connected": "Account connected.", |
| + // COPY REVIEW REQUIRED: account_setup.expired |
| + "account_setup.expired": "Sign-in expired. Start again.", |
| + // COPY REVIEW REQUIRED: account_setup.denied |
| + "account_setup.denied": "Sign-in was denied.", |
| + // COPY REVIEW REQUIRED: account_setup.cancelled |
| + "account_setup.cancelled": "Sign-in cancelled.", |
| + // COPY REVIEW REQUIRED: account_setup.unavailable |
| + "account_setup.unavailable": "This login flow is not available for the installed provider version.", |
| + // COPY REVIEW REQUIRED: onboarding.library |
| + "onboarding.library": "Add specialists from the library", |
| + // COPY REVIEW REQUIRED: onboarding.start_task |
| + "onboarding.start_task": "Read and recommend", |
| + // COPY REVIEW REQUIRED: onboarding.first_instructions |
| + "onboarding.first_instructions": "Read the project material and recommend what to work on next. Cite the sources for each recommendation. Do not edit files, create a branch or publish changes.", |
| // COPY REVIEW REQUIRED: onboarding.title |
| "onboarding.title": "Set up Equipo", |
| // COPY REVIEW REQUIRED: onboarding.welcome |
| @@ -1021,3 +1057,6 @@ func CoordinatorToolCopy() runnerproto.CoordinatorToolCopy { |
| const copyInviteExpired = "This invitation is no longer valid. Ask a team owner for a new one." |
| func RunnerSetupCopy(key string) string { return copyText(key) } |
| + |
| +// COPY REVIEW REQUIRED: onboarding.first_instructions |
| +var copyOnboardingFirstInstructions = pageCopy["onboarding.first_instructions"] |
diff --git a/internal/equipo/invitations.go b/internal/equipo/invitations.go| index 75d4dd3d..f33b284e 100644 |
| --- a/internal/equipo/invitations.go |
| +++ b/internal/equipo/invitations.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "amadan.net/oficina/equipo/internal/equipo/setup" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| "gorm.io/gorm" |
| ) |
| @@ -12,7 +13,10 @@ type Invitation = setup.Invitation |
| var ErrInvitationExpired = &refusal{copyInviteExpired, ErrConflict} |
| func (s *Store) invitationsAt(tx *gorm.DB) *setup.Store { |
| - return setup.New(tx, setup.Dependencies{Key: s.invitationKey, Origin: s.personOrigin, Now: s.runnerClock.Now().UTC(), Owner: requireOwner, Member: memberAt, Audit: appendAudit, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict, Unavailable: ErrUnavailable, Expired: ErrInvitationExpired, |
| + return setup.New(tx, setup.Dependencies{RunnerCurrent: func(tx *gorm.DB, p runnerproto.RunnerPrincipal) error { |
| + _, err := runnerPrincipalAt(tx, p, s.runnerClock.Now()) |
| + return err |
| + }, ConnectAccount: setup.ConnectAccount, Key: s.invitationKey, Origin: s.personOrigin, Now: s.runnerClock.Now().UTC(), Owner: requireOwner, Member: memberAt, Audit: appendAudit, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict, Unavailable: ErrUnavailable, Expired: ErrInvitationExpired, |
| Normalize: normalizeAddress, ValidAddress: validAddress, Seed: seedSpecialists, TeamName: copyBrand, BootstrapOwners: ErrBootstrapOwners, LastOwner: ErrLastOwner, DecisionOwnerAssigned: ErrDecisionOwnerAssigned, |
| LapseOwner: func(tx *gorm.DB, address string) error { |
| return lapseOwnerAcknowledgements(tx, address, s.runnerClock.Now().UTC()) |
diff --git a/internal/equipo/migrations/0028_setup_accounts.sql b/internal/equipo/migrations/0028_setup_accounts.sql| new file mode 100644 |
| index 00000000..67c2ae59 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0028_setup_accounts.sql |
| @@ -0,0 +1,17 @@ |
| +CREATE TABLE account_setups ( |
| + id text PRIMARY KEY, |
| + person text, |
| + runner_id text, |
| + provider text, |
| + label text, |
| + state text, |
| + mode text, |
| + connection_id text, |
| + revision integer, |
| + runner_revision integer, |
| + member_revision integer, |
| + created_at datetime, |
| + expires_at datetime, |
| + challenge text |
| +); |
| +CREATE INDEX account_setup_person ON account_setups(person); |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index d8cc42ae..857ee3af 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -427,3 +427,20 @@ CREATE TABLE onboarding_states ( |
| completed text |
| ); |
| ALTER TABLE runner_enrolments ADD COLUMN created_at datetime; |
| +CREATE TABLE account_setups ( |
| + id text PRIMARY KEY, |
| + person text, |
| + runner_id text, |
| + provider text, |
| + label text, |
| + state text, |
| + mode text, |
| + connection_id text, |
| + revision integer, |
| + runner_revision integer, |
| + member_revision integer, |
| + created_at datetime, |
| + expires_at datetime, |
| + challenge text |
| +); |
| +CREATE INDEX account_setup_person ON account_setups(person); |
diff --git a/internal/equipo/runner_api.go b/internal/equipo/runner_api.go| index 9496ecf0..8a130f53 100644 |
| --- a/internal/equipo/runner_api.go |
| +++ b/internal/equipo/runner_api.go |
| @@ -7,7 +7,7 @@ import ( |
| ) |
| func (s *Store) runnerProtocol() *runnerproto.Handler { |
| - return &runnerproto.Handler{Execution: func() runnerproto.ExecutionAPI { |
| + return &runnerproto.Handler{AccountSetups: s, Execution: func() runnerproto.ExecutionAPI { |
| if s.execution == nil { |
| return nil |
| } |
diff --git a/internal/equipo/setup/account_connection.go b/internal/equipo/setup/account_connection.go| new file mode 100644 |
| index 00000000..1d95a953 |
| --- /dev/null |
| +++ b/internal/equipo/setup/account_connection.go |
| @@ -0,0 +1,22 @@ |
| +package setup |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "encoding/json" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func ConnectAccount(tx *gorm.DB, p runnerproto.RunnerPrincipal, a AccountSetup, q runnerproto.AccountSetupResult) (string, error) { |
| + // Sign-in alone grants no model availability or containment certification. |
| + report := runnerproto.ConnectionReport{LocalID: a.ID, Provider: a.Provider, ProviderVersion: q.ProviderVersion, Family: map[string]string{"codex": "gpt", "claude": "claude"}[a.Provider], Model: "pending", AccountLabel: a.Label, Kind: "subscription", UnavailableReason: "account_setup.waiting_runner", Routing: runnerproto.ConnectionRouting{BindingID: a.ID, AccountID: q.AccountID}} |
| + raw, err := json.Marshal([]runnerproto.ConnectionReport{report}) |
| + if err != nil { |
| + return "", err |
| + } |
| + row := planning.ConnectionRecord{Connection: planning.Connection{ID: a.ID, LocalID: a.ID, RunnerID: p.RunnerID, Person: p.Person, Revision: 1}, ReportsJSON: string(raw)} |
| + if err = tx.Create(&row).Error; err != nil { |
| + return "", err |
| + } |
| + return row.ID, nil |
| +} |
diff --git a/internal/equipo/setup/account_handlers.go b/internal/equipo/setup/account_handlers.go| new file mode 100644 |
| index 00000000..e0427661 |
| --- /dev/null |
| +++ b/internal/equipo/setup/account_handlers.go |
| @@ -0,0 +1,93 @@ |
| +package setup |
| + |
| +import ( |
| + "context" |
| + "gorm.io/gorm" |
| + "net/http" |
| + "slices" |
| + "strconv" |
| +) |
| + |
| +type OnboardingProject struct { |
| + ID int64 |
| + Name string |
| +} |
| + |
| +func (s *Application) OnboardingProjects(ctx context.Context, a Actor) (out []OnboardingProject, err error) { |
| + err = s.Read(ctx, func(tx *gorm.DB) error { |
| + if e := s.At(tx).onboardingMember(a); e != nil { |
| + return e |
| + } |
| + return tx.Table("projects").Select("id", "name").Order("name, id").Scan(&out).Error |
| + }) |
| + if err != nil { |
| + out = nil |
| + } |
| + return |
| +} |
| +func (h *OnboardingHandler) accountForm(w http.ResponseWriter, r *http.Request, fields ...string) (Actor, bool) { |
| + privacy(w) |
| + a, e := h.Actor(r) |
| + if e != nil { |
| + h.Failure(w, r, e) |
| + return a, false |
| + } |
| + r.Body = http.MaxBytesReader(w, r.Body, 4096) |
| + if r.ParseForm() != nil { |
| + h.Failure(w, r, h.Invalid) |
| + return a, false |
| + } |
| + for k, v := range r.PostForm { |
| + if len(v) != 1 || !slices.Contains(fields, k) { |
| + h.Failure(w, r, h.Invalid) |
| + return a, false |
| + } |
| + } |
| + return a, true |
| +} |
| +func (h *OnboardingHandler) Account(w http.ResponseWriter, r *http.Request) { |
| + a, ok := h.accountForm(w, r, "runner_id", "provider", "label", "request_id") |
| + if !ok { |
| + return |
| + } |
| + _, e := h.Store.RequestAccountSetup(r.Context(), a, r.PostForm.Get("runner_id"), r.PostForm.Get("provider"), r.PostForm.Get("label"), Mutation{RequestID: r.PostForm.Get("request_id")}) |
| + if e != nil { |
| + h.Failure(w, r, e) |
| + return |
| + } |
| + http.Redirect(w, r, "/onboarding", http.StatusSeeOther) |
| +} |
| +func (h *OnboardingHandler) CancelAccount(w http.ResponseWriter, r *http.Request) { |
| + a, ok := h.accountForm(w, r, "id", "revision", "request_id") |
| + if !ok { |
| + return |
| + } |
| + rev, e := strconv.ParseInt(r.PostForm.Get("revision"), 10, 64) |
| + if e != nil { |
| + h.Failure(w, r, h.Invalid) |
| + return |
| + } |
| + e = h.Store.CancelAccountSetup(r.Context(), a, r.PostForm.Get("id"), Mutation{Revision: rev, RequestID: r.PostForm.Get("request_id")}) |
| + if e != nil { |
| + h.Failure(w, r, e) |
| + return |
| + } |
| + http.Redirect(w, r, "/onboarding", http.StatusSeeOther) |
| +} |
| +func (h *OnboardingHandler) FirstTask(w http.ResponseWriter, r *http.Request) { |
| + a, ok := h.accountForm(w, r, "project_id", "request_id") |
| + if !ok { |
| + return |
| + } |
| + id, e := strconv.ParseInt(r.PostForm.Get("project_id"), 10, 64) |
| + if e != nil { |
| + h.Failure(w, r, h.Invalid) |
| + return |
| + } |
| + p, e := h.Store.StartOnboardingTask(r.Context(), a, id, Mutation{RequestID: r.PostForm.Get("request_id")}) |
| + if e != nil { |
| + h.Failure(w, r, e) |
| + return |
| + } |
| + http.Redirect(w, r, "/tasks/"+p.TaskID, http.StatusSeeOther) |
| +} |
diff --git a/internal/equipo/setup/accounts.go b/internal/equipo/setup/accounts.go| new file mode 100644 |
| index 00000000..e5451ce4 |
| --- /dev/null |
| +++ b/internal/equipo/setup/accounts.go |
| @@ -0,0 +1,315 @@ |
| +package setup |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "errors" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type AccountSetup = runnerproto.AccountSetup |
| +type LoginDisplay = runnerproto.LoginDisplay |
| +type AccountSetupRecord struct { |
| + ID string `gorm:"primaryKey"` |
| + Person string `gorm:"index:account_setup_person"` |
| + RunnerID, Provider, Label, State, Mode, ConnectionID string |
| + Revision, RunnerRevision, MemberRevision int64 |
| + CreatedAt, ExpiresAt time.Time |
| + Challenge *LoginDisplay `gorm:"serializer:json"` |
| +} |
| + |
| +func (AccountSetupRecord) TableName() string { return "account_setups" } |
| +func (r AccountSetupRecord) view() AccountSetup { |
| + return AccountSetup{ID: r.ID, RunnerID: r.RunnerID, Provider: r.Provider, Label: r.Label, State: r.State, Mode: r.Mode, Challenge: r.Challenge, ConnectionID: r.ConnectionID, Revision: r.Revision} |
| +} |
| +func (s *Store) accountRunner(a Actor, id string) (RunnerRecord, error) { |
| + var r RunnerRecord |
| + if err := s.onboardingMember(a); err != nil { |
| + return r, err |
| + } |
| + err := s.tx.Where("id=? AND person=? AND revoked_at IS NULL", id, a.Address).First(&r).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return r, s.deps.NotFound |
| + } |
| + if err != nil { |
| + return r, err |
| + } |
| + var count int64 |
| + if err = s.tx.Model(&EnrolmentRecord{}).Where("runner_id=? AND person=? AND consumed_at IS NOT NULL AND revoked_at IS NULL", id, a.Address).Count(&count).Error; err != nil { |
| + return r, err |
| + } |
| + if count != 1 { |
| + return r, s.deps.Conflict |
| + } |
| + return r, nil |
| +} |
| +func (s *Store) account(a Actor, id string) (AccountSetupRecord, error) { |
| + var row AccountSetupRecord |
| + if err := s.onboardingMember(a); err != nil { |
| + return row, err |
| + } |
| + err := s.tx.Where("id=? AND person=?", id, a.Address).First(&row).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return row, s.deps.NotFound |
| + } |
| + if err != nil { |
| + return row, err |
| + } |
| + if row.State == "pending" || row.State == "waiting_runner" { |
| + if !s.deps.Now.Before(row.ExpiresAt) { |
| + row.State = "expired" |
| + row.Challenge = nil |
| + return row, nil |
| + } |
| + r, e := s.accountRunner(a, row.RunnerID) |
| + if e != nil && !errors.Is(e, s.deps.NotFound) && !errors.Is(e, s.deps.Conflict) { |
| + return row, e |
| + } |
| + m, e2 := s.deps.Member(s.tx, a.Address) |
| + if e2 != nil { |
| + return row, e2 |
| + } |
| + if e != nil || r.Revision != row.RunnerRevision || m.Revision != row.MemberRevision { |
| + row.State = "unavailable" |
| + row.Challenge = nil |
| + } |
| + } |
| + return row, nil |
| +} |
| +func (s *Application) RequestAccountSetup(ctx context.Context, a Actor, runnerID, providerName, label string, m Mutation) (out AccountSetup, err error) { |
| + a.Address = s.Normalize(a.Address) |
| + err = s.Write(ctx, func(tx *gorm.DB) error { |
| + var e error |
| + out, e = s.At(tx).requestAccount(a, runnerID, providerName, label, m) |
| + return e |
| + }) |
| + if err != nil { |
| + out = AccountSetup{} |
| + } |
| + return |
| +} |
| +func (s *Store) requestAccount(a Actor, runnerID, name, label string, m Mutation) (AccountSetup, error) { |
| + r, err := s.accountRunner(a, runnerID) |
| + if err != nil { |
| + return AccountSetup{}, err |
| + } |
| + if (name != "codex" && name != "claude") || strings.TrimSpace(label) == "" || len(label) > 80 || strings.ContainsAny(label, "\x00\r\n") || m.Revision != 0 { |
| + return AccountSetup{}, s.deps.Invalid |
| + } |
| + input := struct{ Runner, Provider, Label string }{runnerID, name, label} |
| + var out AccountSetup |
| + if ok, err := s.replay(a, "account_setup.request", runnerID, m, input, &out); ok || err != nil { |
| + return out, err |
| + } |
| + member, err := s.deps.Member(s.tx, a.Address) |
| + if err != nil { |
| + return out, err |
| + } |
| + row := AccountSetupRecord{ID: rand.Text(), Person: a.Address, RunnerID: runnerID, Provider: name, Label: label, State: "pending", Mode: map[string]string{"codex": "device", "claude": "browser"}[name], Revision: 1, RunnerRevision: r.Revision, MemberRevision: member.Revision, CreatedAt: s.deps.Now, ExpiresAt: s.deps.Now.Add(10 * time.Minute)} |
| + if err = s.tx.Create(&row).Error; err != nil { |
| + return out, err |
| + } |
| + if err = s.initializeOnboarding(a); err != nil { |
| + return out, err |
| + } |
| + if err = s.tx.Model(&OnboardingRecord{}).Where("person=?", a.Address).Updates(map[string]any{"account_setup_id": row.ID, "runner_id": runnerID, "revision": gorm.Expr("revision+1")}).Error; err != nil { |
| + return out, err |
| + } |
| + if err = s.deps.Audit(s.tx, a, "account_setup.request", row.ID); err != nil { |
| + return out, err |
| + } |
| + out = row.view() |
| + return out, s.save(a, "account_setup.request", runnerID, m, input, out) |
| +} |
| +func (s *Application) AccountSetup(ctx context.Context, a Actor, id string) (out AccountSetup, err error) { |
| + a.Address = s.Normalize(a.Address) |
| + err = s.Read(ctx, func(tx *gorm.DB) error { r, e := s.At(tx).account(a, id); out = r.view(); return e }) |
| + if err != nil { |
| + out = AccountSetup{} |
| + } |
| + return |
| +} |
| +func (s *Application) AccountSetups(ctx context.Context, a Actor) (out []AccountSetup, err error) { |
| + a.Address = s.Normalize(a.Address) |
| + err = s.Read(ctx, func(tx *gorm.DB) error { |
| + st := s.At(tx) |
| + if e := st.onboardingMember(a); e != nil { |
| + return e |
| + } |
| + var rows []AccountSetupRecord |
| + if e := tx.Where("person=?", a.Address).Order("created_at DESC, id").Limit(100).Find(&rows).Error; e != nil { |
| + return e |
| + } |
| + for _, r := range rows { |
| + row, e := st.account(a, r.ID) |
| + if e != nil { |
| + return e |
| + } |
| + out = append(out, row.view()) |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + out = nil |
| + } |
| + return |
| +} |
| +func (s *Application) AccountRunners(ctx context.Context, a Actor) (out []Runner, err error) { |
| + a.Address = s.Normalize(a.Address) |
| + err = s.Read(ctx, func(tx *gorm.DB) error { |
| + st := s.At(tx) |
| + if e := st.onboardingMember(a); e != nil { |
| + return e |
| + } |
| + var rows []RunnerRecord |
| + if e := tx.Where("person=? AND revoked_at IS NULL", a.Address).Order("label, id").Find(&rows).Error; e != nil { |
| + return e |
| + } |
| + for _, r := range rows { |
| + if _, e := st.accountRunner(a, r.ID); e == nil { |
| + out = append(out, r.Runner) |
| + } else if !errors.Is(e, st.deps.Conflict) { |
| + return e |
| + } |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + out = nil |
| + } |
| + return |
| +} |
| +func (s *Application) CancelAccountSetup(ctx context.Context, a Actor, id string, m Mutation) error { |
| + a.Address = s.Normalize(a.Address) |
| + return s.Write(ctx, func(tx *gorm.DB) error { |
| + st := s.At(tx) |
| + row, e := st.account(a, id) |
| + if e != nil { |
| + return e |
| + } |
| + var out AccountSetup |
| + if ok, e := st.replay(a, "account_setup.cancel", id, m, m, &out); ok || e != nil { |
| + return e |
| + } |
| + if row.Revision != m.Revision || row.State == "connected" { |
| + return st.deps.Conflict |
| + } |
| + row.State = "cancelled" |
| + row.Challenge = nil |
| + row.Revision++ |
| + if e = st.updateAccount(row); e != nil { |
| + return e |
| + } |
| + if e = st.deps.Audit(tx, a, "account_setup.cancel", id); e != nil { |
| + return e |
| + } |
| + return st.save(a, "account_setup.cancel", id, m, m, row.view()) |
| + }) |
| +} |
| +func (s *Store) updateAccount(row AccountSetupRecord) error { |
| + q := s.tx.Model(&AccountSetupRecord{}).Where("id=? AND revision=?", row.ID, row.Revision-1).Select("State", "Challenge", "ConnectionID", "Revision").Updates(&row) |
| + if q.Error != nil { |
| + return q.Error |
| + } |
| + if q.RowsAffected != 1 { |
| + return s.deps.Conflict |
| + } |
| + return nil |
| +} |
| +func (s *Application) RunnerAccountSetup(ctx context.Context, p runnerproto.RunnerPrincipal, id string) (out AccountSetup, err error) { |
| + err = s.Read(ctx, func(tx *gorm.DB) error { |
| + st := s.At(tx) |
| + if e := st.deps.RunnerCurrent(tx, p); e != nil { |
| + return e |
| + } |
| + r, e := st.account(Actor{Address: p.Person}, id) |
| + if e != nil { |
| + return e |
| + } |
| + if r.RunnerID != p.RunnerID || r.State != "pending" { |
| + return st.deps.Conflict |
| + } |
| + out = r.view() |
| + return nil |
| + }) |
| + if err != nil { |
| + out = AccountSetup{} |
| + } |
| + return |
| +} |
| +func (s *Application) ReportAccountSetup(ctx context.Context, p runnerproto.RunnerPrincipal, q runnerproto.AccountSetupResult) (out AccountSetup, err error) { |
| + err = s.Write(ctx, func(tx *gorm.DB) error { |
| + st := s.At(tx) |
| + if e := st.deps.RunnerCurrent(tx, p); e != nil { |
| + return e |
| + } |
| + a := Actor{Address: p.Person} |
| + row, e := st.account(a, q.ID) |
| + if e != nil { |
| + return e |
| + } |
| + runner, e := st.accountRunner(a, p.RunnerID) |
| + if e != nil { |
| + return e |
| + } |
| + member, e := st.deps.Member(tx, a.Address) |
| + if e != nil { |
| + return e |
| + } |
| + if row.RunnerID != p.RunnerID || row.RunnerRevision != runner.Revision || row.MemberRevision != member.Revision || (row.State != "pending" && row.State != q.State) { |
| + return st.deps.Conflict |
| + } |
| + m := Mutation{RequestID: strconv.FormatInt(q.Revision, 10), Revision: q.Revision} |
| + if ok, e := st.replay(a, "account_setup.report", row.ID, m, q, &out); ok || e != nil { |
| + return e |
| + } |
| + if row.State != "pending" || row.Revision != q.Revision { |
| + return st.deps.Conflict |
| + } |
| + if q.State != "pending" && q.Challenge != nil { |
| + return st.deps.Invalid |
| + } |
| + if !runnerproto.ValidLoginDisplay(row.Provider, row.Mode, q.Challenge, st.deps.Now) { |
| + return st.deps.Invalid |
| + } |
| + switch q.State { |
| + case "pending", "expired", "denied", "cancelled", "unavailable": |
| + if q.AccountID != "" || q.ProviderVersion != "" { |
| + return st.deps.Invalid |
| + } |
| + case "connected": |
| + if q.Challenge != nil || q.AccountID == "" || len(q.AccountID) > 256 || strings.ContainsAny(q.AccountID, "\x00\r\n/") || q.ProviderVersion != map[string]string{"claude": "2.1.312", "codex": "0.165.0"}[row.Provider] { |
| + return st.deps.Invalid |
| + } |
| + row.ConnectionID, e = st.deps.ConnectAccount(tx, p, row.view(), q) |
| + if e != nil { |
| + return e |
| + } |
| + default: |
| + return st.deps.Invalid |
| + } |
| + row.State = q.State |
| + row.Challenge = q.Challenge |
| + if q.State != "pending" { |
| + row.Challenge = nil |
| + } |
| + row.Revision++ |
| + if e = st.updateAccount(row); e != nil { |
| + return e |
| + } |
| + if e = st.deps.Audit(tx, a, "account_setup."+q.State, row.ID); e != nil { |
| + return e |
| + } |
| + out = row.view() |
| + return st.save(a, "account_setup.report", row.ID, m, q, out) |
| + }) |
| + if err != nil { |
| + out = AccountSetup{} |
| + } |
| + return |
| +} |
diff --git a/internal/equipo/setup/invites.go b/internal/equipo/setup/invites.go| index 43aac92e..a20b4632 100644 |
| --- a/internal/equipo/setup/invites.go |
| +++ b/internal/equipo/setup/invites.go |
| @@ -11,6 +11,7 @@ import ( |
| "time" |
| "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| "gorm.io/gorm" |
| ) |
| @@ -40,9 +41,11 @@ type inviteRequest struct { |
| func (inviteRequest) TableName() string { return "invitation_requests" } |
| -var Models = []any{&InvitationRecord{}, &inviteRequest{}, &OnboardingRecord{}} |
| +var Models = []any{&InvitationRecord{}, &inviteRequest{}, &OnboardingRecord{}, &AccountSetupRecord{}} |
| type Dependencies struct { |
| + RunnerCurrent func(*gorm.DB, runnerproto.RunnerPrincipal) error |
| + ConnectAccount func(*gorm.DB, runnerproto.RunnerPrincipal, AccountSetup, runnerproto.AccountSetupResult) (string, error) |
| Normalize func(string) string |
| ValidAddress func(string) bool |
| Seed func(*gorm.DB) (int64, error) |
diff --git a/internal/equipo/setup/onboarding_handlers.go b/internal/equipo/setup/onboarding_handlers.go| index e6f84e77..9d6ff470 100644 |
| --- a/internal/equipo/setup/onboarding_handlers.go |
| +++ b/internal/equipo/setup/onboarding_handlers.go |
| @@ -6,16 +6,29 @@ import ( |
| "net/http" |
| "strconv" |
| + "amadan.net/oficina/equipo/internal/equipo/library" |
| "amadan.net/oficina/equipo/internal/release" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| "github.com/go-chi/chi/v5" |
| ) |
| type OnboardingOperations interface { |
| + ListSpecialists(context.Context, Actor) ([]library.Specialist, error) |
| + RequestAccountSetup(context.Context, Actor, string, string, string, Mutation) (AccountSetup, error) |
| + AccountSetups(context.Context, Actor) ([]AccountSetup, error) |
| + AccountRunners(context.Context, Actor) ([]Runner, error) |
| + CancelAccountSetup(context.Context, Actor, string, Mutation) error |
| + StartOnboardingTask(context.Context, Actor, int64, Mutation) (taskplan.Plan, error) |
| + OnboardingProjects(context.Context, Actor) ([]OnboardingProject, error) |
| Onboarding(context.Context, Actor) (OnboardingState, error) |
| AdvanceOnboarding(context.Context, Actor, string, Mutation) (OnboardingState, error) |
| ChooseOnboardingProvider(context.Context, Actor, string, Mutation) (OnboardingState, error) |
| } |
| type OnboardingView struct { |
| + Specialists []library.Specialist |
| + Accounts []AccountSetup |
| + Runners []Runner |
| + Projects []OnboardingProject |
| State OnboardingState |
| RequestID, InstallCommand string |
| } |
| @@ -32,6 +45,9 @@ type OnboardingHandler struct { |
| func (h *OnboardingHandler) Routes(r chi.Router) { |
| r.Get("/onboarding", h.Page) |
| + r.Post("/onboarding/accounts", h.Account) |
| + r.Post("/onboarding/accounts/cancel", h.CancelAccount) |
| + r.Post("/onboarding/first-task", h.FirstTask) |
| r.Post("/onboarding/advance", h.Advance) |
| r.Post("/onboarding/provider", h.Provider) |
| } |
| @@ -48,6 +64,28 @@ func (h *OnboardingHandler) Page(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| v := OnboardingView{State: state, RequestID: rand.Text()} |
| + if state.CurrentStep == "specialists" { |
| + v.Specialists, e = h.Store.ListSpecialists(r.Context(), a) |
| + if e != nil { |
| + h.Failure(w, r, e) |
| + return |
| + } |
| + } |
| + v.Accounts, e = h.Store.AccountSetups(r.Context(), a) |
| + if e != nil { |
| + h.Failure(w, r, e) |
| + return |
| + } |
| + v.Runners, e = h.Store.AccountRunners(r.Context(), a) |
| + if e != nil { |
| + h.Failure(w, r, e) |
| + return |
| + } |
| + v.Projects, e = h.Store.OnboardingProjects(r.Context(), a) |
| + if e != nil { |
| + h.Failure(w, r, e) |
| + return |
| + } |
| if h.Manifest.InstallCertified() && h.InstallAvailable != nil && h.InstallAvailable() { |
| v.InstallCommand, _ = release.InstallCommand(h.Origin, h.Version, h.InstanceID) |
| } |
diff --git a/internal/equipo/templates/connections.html b/internal/equipo/templates/connections.html| index 5150c370..74eacdb2 100644 |
| --- a/internal/equipo/templates/connections.html |
| +++ b/internal/equipo/templates/connections.html |
| @@ -1,3 +1,3 @@ |
| {{define "content"}}<h1>{{copy "nav.connections"}}</h1><a rst-btn href="/runners/enrol">{{copy "connections.enrol"}}</a>{{template "region:activity" .}} |
| -<h2>{{copy "connections.personal"}}</h2>{{range .Choices}}<form equipo-form method="post" action="/projects/{{.Project.ID}}/connections"><h3>{{.Project.Name}}</h3><input type="hidden" name="revision" value="{{.Revision}}">{{range .Options}}<label><input type="checkbox" name="connection_id" value="{{.ID}}"{{if .Enabled}} checked{{end}}>{{copy "connections.enable"}}: {{.Label}}</label>{{end}}<label>{{copy "connections.reason"}}<select rst-input name="mode"><option value="best_fit"{{if eq .Mode "best_fit"}} selected{{end}}>{{copy "connections.best_fit"}}</option><option value="pinned"{{if eq .Mode "pinned"}} selected{{end}}>{{copy "connections.pinned"}}</option><option value="ask"{{if eq .Mode "ask"}} selected{{end}}>{{copy "connections.ask"}}</option></select></label><label>{{copy "connections.pin"}}<select rst-input name="pinned_id"><option value="">{{copy "value.none"}}</option>{{$pinned:=.PinnedID}}{{range .Options}}<option value="{{.ID}}"{{if eq .ID $pinned}} selected{{end}}>{{.Label}}</option>{{end}}</select></label><button rst-btn>{{copy "form.save"}}</button></form>{{end}}{{end}} |
| +<a rst-btn href="/onboarding">{{copy "account_setup.add"}}</a><h2>{{copy "connections.personal"}}</h2>{{range .Choices}}<form equipo-form method="post" action="/projects/{{.Project.ID}}/connections"><h3>{{.Project.Name}}</h3><input type="hidden" name="revision" value="{{.Revision}}">{{range .Options}}<label><input type="checkbox" name="connection_id" value="{{.ID}}"{{if .Enabled}} checked{{end}}>{{copy "connections.enable"}}: {{.Label}}</label>{{end}}<label>{{copy "connections.reason"}}<select rst-input name="mode"><option value="best_fit"{{if eq .Mode "best_fit"}} selected{{end}}>{{copy "connections.best_fit"}}</option><option value="pinned"{{if eq .Mode "pinned"}} selected{{end}}>{{copy "connections.pinned"}}</option><option value="ask"{{if eq .Mode "ask"}} selected{{end}}>{{copy "connections.ask"}}</option></select></label><label>{{copy "connections.pin"}}<select rst-input name="pinned_id"><option value="">{{copy "value.none"}}</option>{{$pinned:=.PinnedID}}{{range .Options}}<option value="{{.ID}}"{{if eq .ID $pinned}} selected{{end}}>{{.Label}}</option>{{end}}</select></label><button rst-btn>{{copy "form.save"}}</button></form>{{end}}{{end}} |
| {{define "region:activity"}}<div id="activity" {{.Live.Attrs .Topic}}>{{range .Connections}}<section equipo-card><h2>{{.Report.AccountLabel}}</h2><p>{{.Person}}</p><p>{{copy "connections.counted_usage"}}</p>{{if .Report.AllowanceKnown}}<span equipo-value>{{.Report.AllowanceRemaining}}</span>{{else}}<p>{{copy "connections.remaining_unknown"}}</p>{{end}}{{if not .Available}}<p>{{copy "runner.preflight.unavailable"}}</p>{{end}}{{template "trial-label" .Isolation}}<p>{{copy "connections.versions"}}: {{.Report.Provider}} {{.Report.ProviderVersion}} / {{.Report.LauncherVersion}} / {{.Report.BwrapVersion}}</p>{{if .Unverified}}<p>{{copy "isolation.unverified"}}</p>{{else}}<p>{{copy "isolation.confined"}}</p>{{end}}</section>{{else}}<p data-empty-state="connections.empty">{{copy "connections.empty"}}</p>{{end}}</div>{{end}} |
diff --git a/internal/equipo/templates/onboarding.html b/internal/equipo/templates/onboarding.html| index eed0abc2..181c4b0f 100644 |
| --- a/internal/equipo/templates/onboarding.html |
| +++ b/internal/equipo/templates/onboarding.html |
| @@ -17,8 +17,12 @@ |
| <p>{{copy "onboarding.pair"}}</p><a href="/runners/enrol">{{copy "runner.title"}}</a> |
| <p>{{copy "onboarding.account_pending"}}</p> |
| {{end}} |
| -{{if eq .Onboarding.State.CurrentStep "specialists"}}<a href="/work">{{copy "onboarding.specialists"}}</a>{{end}} |
| -{{if eq .Onboarding.State.CurrentStep "first_task"}}<p>{{copy "onboarding.safe_first_task"}}</p><a href="/conversation">{{copy "conversation.title"}}</a>{{end}} |
| +{{if eq .Onboarding.State.CurrentStep "specialists"}}<ul data-onboarding-specialists>{{range .Onboarding.Specialists}}<li><a href="/specialists/{{.Key}}">{{.Name}}</a>{{if .Required}} <span equipo-value>{{copy "specialists.required"}}</span>{{end}}</li>{{end}}</ul>{{end}} |
| +<a href="/templates">{{copy "onboarding.library"}}</a> |
| +{{if eq .Onboarding.State.CurrentStep "first_task"}}<p>{{copy "onboarding.safe_first_task"}}</p> |
| +<form method="post" action="/onboarding/first-task" equipo-form><input type="hidden" name="request_id" value="{{.Onboarding.RequestID}}-task"> |
| +<label>{{copy "plan.project"}}<select name="project_id" rst-select>{{range .Onboarding.Projects}}<option value="{{.ID}}">{{.Name}}</option>{{end}}</select></label> |
| +<button rst-btn type="submit">{{copy "onboarding.start_task"}}</button></form>{{end}} |
| {{if ne .Onboarding.State.CurrentStep "complete"}} |
| <form method="post" action="/onboarding/advance" equipo-form> |
| <input type="hidden" name="step" value="{{.Onboarding.State.CurrentStep}}"> |
| @@ -28,6 +32,16 @@ |
| </form> |
| {{else}}<a href="/conversation">{{copy "conversation.title"}}</a>{{end}} |
| </section> |
| +<section equipo-card><h2>{{copy "account_setup.title"}}</h2><p>{{copy "account_setup.dedicated"}}</p> |
| +{{if .Onboarding.Runners}}<form method="post" action="/onboarding/accounts" equipo-form> |
| +<input type="hidden" name="request_id" value="{{.Onboarding.RequestID}}-account"> |
| +<label>{{copy "account_setup.runner"}}<select name="runner_id" rst-select>{{range .Onboarding.Runners}}<option value="{{.ID}}">{{.Label}}</option>{{end}}</select></label> |
| +<label>{{copy "onboarding.account"}}<select name="provider" rst-select><option value="codex">{{copy "onboarding.codex"}}</option><option value="claude">{{copy "onboarding.claude"}}</option></select></label> |
| +<label>{{copy "account_setup.label"}}<input name="label" maxlength="80" required rst-input></label><button rst-btn type="submit">{{copy "account_setup.add"}}</button></form>{{end}} |
| +{{$request:=.Onboarding.RequestID}}{{range .Onboarding.Accounts}}<section equipo-card><h3>{{.Label}}</h3><p>{{copy (printf "account_setup.%s" .State)}}</p><code>{{.ID}}</code> |
| +{{if eq .State "pending"}}<p>{{copy "account_setup.browser"}}</p><pre>{{printf (copy "account_setup.command") .ID}}</pre> |
| +{{with .Challenge}}<a href="{{.VerificationURI}}" rel="noreferrer">{{.VerificationURI}}</a><code>{{.UserCode}}</code>{{end}} |
| +<form method="post" action="/onboarding/accounts/cancel"><input type="hidden" name="id" value="{{.ID}}"><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="request_id" value="{{$request}}-{{.ID}}"><button rst-btn type="submit">{{copy "account_setup.cancel"}}</button></form>{{end}}</section>{{end}}</section> |
| <section equipo-card><h2>{{copy "onboarding.hosted"}}</h2><p>{{copy "onboarding.later"}}</p></section> |
| <section equipo-card><h2>{{copy "onboarding.mac"}}</h2><p>{{copy "onboarding.mac_later"}}</p></section> |
| {{end}} |
diff --git a/internal/plan3test/onboarding_accounts_migration_test.go b/internal/plan3test/onboarding_accounts_migration_test.go| new file mode 100644 |
| index 00000000..85d047e0 |
| --- /dev/null |
| +++ b/internal/plan3test/onboarding_accounts_migration_test.go |
| @@ -0,0 +1,50 @@ |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "io" |
| + "log/slog" |
| + "path/filepath" |
| + "testing" |
| +) |
| + |
| +func TestOnboardingAccountMigration(t *testing.T) { |
| + d, e := db.Open(filepath.Join(t.TempDir(), "accounts.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + must(t, e) |
| + t.Cleanup(func() { must(t, d.Close()) }) |
| + old := &migrate.Set{} |
| + for _, m := range equipo.BootSchema.All() { |
| + if m.ID != "equipo/0028_setup_accounts" { |
| + old.Add(m) |
| + } |
| + } |
| + _, e = migrate.Apply(ctx, d, old) |
| + must(t, e) |
| + _, e = d.Writer().Exec("INSERT INTO onboarding_states(person,revision,provider_choice,completed) VALUES('saved',7,'claude','{\"welcome\":true}')") |
| + must(t, e) |
| + result, e := migrate.Apply(ctx, d, equipo.BootSchema) |
| + must(t, e) |
| + if len(result.Applied) != 1 || result.Applied[0] != "equipo/0028_setup_accounts" { |
| + t.Fatal(result.Applied) |
| + } |
| + var rev int |
| + must(t, d.Writer().QueryRow("SELECT revision FROM onboarding_states WHERE person='saved'").Scan(&rev)) |
| + if rev != 7 { |
| + t.Fatal("setup migration lost progress") |
| + } |
| + fresh := newFixture(t) |
| + up, e := migrate.Read(ctx, d.Writer()) |
| + must(t, e) |
| + clean, e := migrate.Read(ctx, fresh.DB.Writer()) |
| + must(t, e) |
| + if !up.Equal(clean) { |
| + t.Fatal(up.Diff(clean)) |
| + } |
| + result, e = migrate.Apply(ctx, d, equipo.BootSchema) |
| + must(t, e) |
| + if len(result.Applied) != 0 { |
| + t.Fatal("migration repeated") |
| + } |
| +} |
diff --git a/internal/plan3test/onboarding_accounts_test.go b/internal/plan3test/onboarding_accounts_test.go| new file mode 100644 |
| index 00000000..c6f7641b |
| --- /dev/null |
| +++ b/internal/plan3test/onboarding_accounts_test.go |
| @@ -0,0 +1,283 @@ |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func accountRunner(t *testing.T, f *fixture) { |
| + t.Helper() |
| + var instance string |
| + must(t, f.DB.Writer().QueryRow("SELECT id FROM teams").Scan(&instance)) |
| + f.exec(t, "INSERT INTO runners(id,instance_id,person,label,revision,machine_key_hash) VALUES('account-runner',?,?,?,1,'machine')", instance, owner.Address, "Desk") |
| + f.exec(t, "INSERT INTO runner_enrolments(id,runner_id,person,consumed_at) VALUES('account-enrol','account-runner',?,?)", owner.Address, time.Now()) |
| +} |
| +func TestOnboardingClaudeHeadlessBrowserLogin(t *testing.T) { |
| + f := newFixture(t) |
| + accountRunner(t, f) |
| + m := equipo.Mutation{RequestID: "setup"} |
| + s, e := f.Store.RequestAccountSetup(ctx, owner, "account-runner", "claude", "Personal", m) |
| + must(t, e) |
| + if s.ID == "" || s.State != "pending" || s.Mode != "browser" || s.Challenge != nil { |
| + t.Fatal("unsafe pending projection", s) |
| + } |
| + again, e := f.Store.RequestAccountSetup(ctx, owner, "account-runner", "claude", "Personal", m) |
| + must(t, e) |
| + if again.ID != s.ID { |
| + t.Fatal("request duplicated") |
| + } |
| + w := f.get(t, owner, "/onboarding") |
| + expectHTTP(t, w, 200) |
| + if !strings.Contains(w.Body.String(), "equipo-runner account login --setup "+s.ID) { |
| + t.Fatal("pending setup command missing") |
| + } |
| + _, e = f.Store.AccountSetup(ctx, peer, s.ID) |
| + if !errors.Is(e, equipo.ErrNotFound) { |
| + t.Fatal("private setup exposed", e) |
| + } |
| + _, e = f.Store.AccountSetup(ctx, owner, "missing") |
| + if !errors.Is(e, equipo.ErrNotFound) { |
| + t.Fatal("missing setup accepted", e) |
| + } |
| + must(t, f.Store.CancelAccountSetup(ctx, owner, s.ID, equipo.Mutation{RequestID: "cancel", Revision: s.Revision})) |
| + s, e = f.Store.AccountSetup(ctx, owner, s.ID) |
| + must(t, e) |
| + if s.State != "cancelled" { |
| + t.Fatal("cancel not persisted") |
| + } |
| + f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) |
| + _, e = f.Store.RequestAccountSetup(ctx, owner, "account-runner", "claude", "Personal", m) |
| + if !errors.Is(e, equipo.ErrForbidden) { |
| + t.Fatal("removed member replay", e) |
| + } |
| +} |
| +func TestOnboardingAccountLifecycle(t *testing.T) { |
| + f := newFixture(t) |
| + accountRunner(t, f) |
| + s, e := f.Store.RequestAccountSetup(ctx, owner, "account-runner", "codex", "One", equipo.Mutation{RequestID: "one"}) |
| + must(t, e) |
| + other, e := f.Store.RequestAccountSetup(ctx, owner, "account-runner", "codex", "Two", equipo.Mutation{RequestID: "two"}) |
| + must(t, e) |
| + if s.ID == other.ID { |
| + t.Fatal("account replaced") |
| + } |
| + f.exec(t, "UPDATE account_setups SET expires_at=? WHERE id=?", time.Now().Add(-time.Second), s.ID) |
| + s, e = f.Store.AccountSetup(ctx, owner, s.ID) |
| + must(t, e) |
| + if s.State != "expired" { |
| + t.Fatal("expired setup pending") |
| + } |
| + f.exec(t, "UPDATE runners SET revision=revision+1 WHERE id='account-runner'") |
| + s, e = f.Store.AccountSetup(ctx, owner, other.ID) |
| + must(t, e) |
| + if s.State != "unavailable" { |
| + t.Fatal("stale generation pending") |
| + } |
| + _ = runnerproto.AccountSetupResult{ID: s.ID} |
| +} |
| +func TestOnboardingSafeFirstTask(t *testing.T) { |
| + f := newFixture(t) |
| + task := f.createTask(t) |
| + p, e := f.Store.StartOnboardingTask(ctx, owner, task.ProjectID, equipo.Mutation{RequestID: "safe"}) |
| + must(t, e) |
| + if string(p.Kind) != "recommendation" || len(p.Steps) != 2 || p.Steps[0].Action != "recommend" { |
| + t.Fatal("unsafe first task", p) |
| + } |
| + for _, step := range p.Steps { |
| + if step.Action == "implement" || step.Action == "publish" || step.Action == "review" { |
| + t.Fatal("change path in first task") |
| + } |
| + } |
| + TestPlanWorkflowRecommendation(t) |
| + TestPlanWorkflowRecommendationDelivery(t) |
| + TestPlanModelChoiceReviewFamily(t) |
| + |
| +} |
| +func TestOnboardingSpecialists(t *testing.T) { |
| + f := newFixture(t) |
| + rows, e := f.Store.ListSpecialists(ctx, owner) |
| + must(t, e) |
| + if len(rows) != 5 { |
| + t.Fatal("defaults missing", len(rows)) |
| + } |
| + for _, key := range []string{"engineering", "review"} { |
| + row, e := f.Store.Specialist(ctx, owner, key) |
| + must(t, e) |
| + if !row.Required { |
| + t.Fatal("required specialist optional") |
| + } |
| + if e = f.Store.DeleteSpecialist(ctx, owner, key, equipo.Mutation{RequestID: key, Revision: row.Revision}); !errors.Is(e, equipo.ErrForbidden) { |
| + t.Fatal("required specialist deleted", e) |
| + } |
| + } |
| + s, e := f.Store.InstallSpecialistTemplate(ctx, owner, equipo.TemplateRef{ID: "qa", Version: 1}, equipo.Mutation{RequestID: "install"}) |
| + must(t, e) |
| + if s.TemplateID != "qa" || s.Creator != owner.Address { |
| + t.Fatal("library copy missing") |
| + } |
| + w := f.get(t, owner, "/onboarding") |
| + expectHTTP(t, w, 200) |
| + if !strings.Contains(w.Body.String(), "/templates") { |
| + t.Fatal("onboarding library link missing") |
| + } |
| + f.exec(t, `INSERT INTO onboarding_states(person,revision,completed) VALUES(?,1,'{"welcome":true,"account":true,"runner":true}')`, owner.Address) |
| + w = f.get(t, owner, "/onboarding") |
| + expectHTTP(t, w, 200) |
| + _, list, ok := strings.Cut(w.Body.String(), "<ul data-onboarding-specialists>") |
| + if !ok { |
| + t.Fatal("specialist-stage choices missing") |
| + } |
| + list, _, _ = strings.Cut(list, "</ul>") |
| + for _, key := range []string{"product", "design", "copy", "engineering", "review"} { |
| + if !strings.Contains(list, "/specialists/"+key) { |
| + t.Fatal("onboarding specialist missing", key) |
| + } |
| + } |
| +} |
| + |
| +func TestOnboardingAccountRunnerGuards(t *testing.T) { |
| + f := newFixture(t) |
| + accountRunner(t, f) |
| + token := base64.RawURLEncoding.EncodeToString(make([]byte, 32)) |
| + sum := sha256.Sum256([]byte(runnerproto.RunnerAudience + "\x00" + token)) |
| + f.exec(t, "INSERT INTO runner_credentials(id,runner_id,instance_id,audience,person,machine_key_hash,token_hash,expires_at) VALUES('account-cred','account-runner',?,?,?,'machine',?,?)", f.TeamID, runnerproto.RunnerAudience, owner.Address, hex.EncodeToString(sum[:]), time.Now().Add(time.Hour)) |
| + p, e := f.Store.AuthenticateRunner(ctx, token) |
| + must(t, e) |
| + makeSetup := func(name string) equipo.AccountSetup { |
| + t.Helper() |
| + s, e := f.Store.RequestAccountSetup(ctx, owner, "account-runner", name, name, equipo.Mutation{RequestID: rand.Text()}) |
| + must(t, e) |
| + return s |
| + } |
| + s := makeSetup("claude") |
| + for _, wrong := range []equipo.RunnerPrincipal{{RunnerID: "other", Person: p.Person, CredentialID: p.CredentialID}, {RunnerID: p.RunnerID, Person: peer.Address, CredentialID: p.CredentialID}, {RunnerID: p.RunnerID, Person: p.Person, CredentialID: "missing"}} { |
| + if _, e = f.Store.RunnerAccountSetup(ctx, wrong, s.ID); e == nil { |
| + t.Fatal("wrong runner accepted") |
| + } |
| + } |
| + if _, e = f.Store.RunnerAccountSetup(ctx, p, "missing"); e == nil { |
| + t.Fatal("missing setup accepted") |
| + } |
| + request := func(body string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + r := httptest.NewRequest("POST", "/account-setups", strings.NewReader(body)) |
| + r.Header.Set("Authorization", "Bearer "+token) |
| + r.Header.Set("Content-Type", "application/json") |
| + w := httptest.NewRecorder() |
| + f.Store.RunnerHandler().ServeHTTP(w, r) |
| + return w |
| + } |
| + for _, field := range []string{"credential_home", "return_code", "challenge_id"} { |
| + body := fmt.Sprintf(`{"version":2,"id":%q,"result":{"id":%q,"revision":1,"state":"pending",%q:"SECRET-MUST-NOT-ESCAPE"}}`, s.ID, s.ID, field) |
| + w := request(body) |
| + expectHTTP(t, w, 422) |
| + if strings.Contains(w.Body.String(), "SECRET-MUST-NOT-ESCAPE") { |
| + t.Fatal("secret reflected") |
| + } |
| + } |
| + display := &runnerproto.LoginDisplay{VerificationURI: "https://auth.openai.com/codex/device", UserCode: "ABCD-EFGH", ExpiresAt: time.Now().Add(time.Minute)} |
| + if _, e = f.Store.ReportAccountSetup(ctx, p, runnerproto.AccountSetupResult{ID: s.ID, Revision: 1, State: "pending", Challenge: display}); !errors.Is(e, equipo.ErrInvalid) { |
| + t.Fatal("browser challenge stored", e) |
| + } |
| + s = makeSetup("codex") |
| + q := runnerproto.AccountSetupResult{ID: s.ID, Revision: 1, State: "pending", Challenge: display} |
| + for _, uri := range []string{"https://attacker.test/code", "https://auth.openai.com/codex/device?secret=hidden", "http://auth.openai.com/codex/device"} { |
| + bad := *display |
| + bad.VerificationURI = uri |
| + q.Challenge = &bad |
| + if _, e = f.Store.ReportAccountSetup(ctx, p, q); !errors.Is(e, equipo.ErrInvalid) { |
| + t.Fatal("unsafe device link accepted", e) |
| + } |
| + } |
| + q.Challenge = display |
| + s, e = f.Store.ReportAccountSetup(ctx, p, q) |
| + must(t, e) |
| + if s.Challenge == nil { |
| + t.Fatal("safe device display dropped") |
| + } |
| + q = runnerproto.AccountSetupResult{ID: s.ID, Revision: s.Revision, State: "connected", AccountID: "observed-account", ProviderVersion: "0.165.0"} |
| + f.exec(t, "CREATE TRIGGER setup_audit_failure BEFORE INSERT ON audit_events WHEN NEW.kind='account_setup.connected' BEGIN SELECT RAISE(ABORT,'fixture'); END") |
| + if _, e = f.Store.ReportAccountSetup(ctx, p, q); e == nil { |
| + t.Fatal("audit failure ignored") |
| + } |
| + if f.count(t, "SELECT count(*) FROM connections WHERE local_id=?", s.ID) != 0 { |
| + t.Fatal("connection escaped rollback") |
| + } |
| + f.exec(t, "DROP TRIGGER setup_audit_failure") |
| + s, e = f.Store.ReportAccountSetup(ctx, p, q) |
| + must(t, e) |
| + again, e := f.Store.ReportAccountSetup(ctx, p, q) |
| + must(t, e) |
| + if again.Revision != s.Revision || again.ConnectionID != s.ConnectionID { |
| + t.Fatal("lost result duplicated connection") |
| + } |
| + if s.State != "connected" || s.ConnectionID == "" || s.Challenge != nil { |
| + t.Fatal("connection result", s) |
| + } |
| + var reports string |
| + must(t, f.DB.Writer().QueryRow("SELECT reports_json FROM connections WHERE id=?", s.ConnectionID).Scan(&reports)) |
| + var rows []runnerproto.ConnectionReport |
| + must(t, json.Unmarshal([]byte(reports), &rows)) |
| + if len(rows) != 1 || rows[0].Available || rows[0].AllowanceKnown || rows[0].AccountLabel != "codex" { |
| + t.Fatal("sign-in fabricated availability or allowance", reports) |
| + } |
| + for _, state := range []string{"expired", "cancelled", "revision", "roster", "role"} { |
| + t.Run(state, func(t *testing.T) { |
| + s := makeSetup("claude") |
| + switch state { |
| + case "expired": |
| + f.exec(t, "UPDATE account_setups SET expires_at=? WHERE id=?", time.Now().Add(-time.Second), s.ID) |
| + case "cancelled": |
| + must(t, f.Store.CancelAccountSetup(ctx, owner, s.ID, equipo.Mutation{RequestID: "cancel", Revision: s.Revision})) |
| + case "revision": |
| + f.exec(t, "UPDATE runners SET revision=revision+1 WHERE id=?", p.RunnerID) |
| + case "roster": |
| + f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) |
| + case "role": |
| + f.exec(t, "UPDATE members SET role='member',revision=revision+1 WHERE address=?", owner.Address) |
| + } |
| + if _, e = f.Store.RunnerAccountSetup(ctx, p, s.ID); e == nil { |
| + t.Fatal("invalid setup exposed") |
| + } |
| + if _, e = f.Store.ReportAccountSetup(ctx, p, runnerproto.AccountSetupResult{ID: s.ID, Revision: s.Revision, State: "connected", AccountID: "observed", ProviderVersion: "2.1.312"}); e == nil { |
| + t.Fatal("invalid setup accepted result") |
| + } |
| + f.exec(t, "UPDATE members SET active=1,role='owner' WHERE address=?", owner.Address) |
| + }) |
| + } |
| +} |
| + |
| +func TestOnboardingAccountForms(t *testing.T) { |
| + f := newFixture(t) |
| + accountRunner(t, f) |
| + values := url.Values{"runner_id": {"account-runner"}, "provider": {"claude"}, "label": {"Personal"}, "request_id": {"form"}} |
| + w := inviteRequest(t, f, owner, "POST", "/onboarding/accounts", values, nil) |
| + expectHTTP(t, w, 303) |
| + values.Set("return_code", "SECRET-MUST-NOT-ESCAPE") |
| + w = inviteRequest(t, f, owner, "POST", "/onboarding/accounts", values, nil) |
| + expectHTTP(t, w, 422) |
| + values.Del("return_code") |
| + values.Set("request_id", "csrf") |
| + expectHTTP(t, inviteRequest(t, f, owner, "POST", "/onboarding/accounts", values, nil, "https://foreign.test"), 403) |
| + body := f.get(t, owner, "/onboarding").Body.String() |
| + if strings.Contains(body, "return_code") || strings.Contains(body, "SECRET-MUST-NOT-ESCAPE") { |
| + t.Fatal("browser collected provider code") |
| + } |
| + var audits string |
| + must(t, f.DB.Writer().QueryRow("SELECT group_concat(record_id) FROM audit_events").Scan(&audits)) |
| + if strings.Contains(audits, "SECRET-MUST-NOT-ESCAPE") { |
| + t.Fatal("secret audited") |
| + } |
| +} |
diff --git a/internal/runner/account_login.go b/internal/runner/account_login.go| new file mode 100644 |
| index 00000000..d47e1ec2 |
| --- /dev/null |
| +++ b/internal/runner/account_login.go |
| @@ -0,0 +1,41 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "path/filepath" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + runnersetup "amadan.net/oficina/equipo/internal/runner/setup" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +func (c *HTTPInstance) AccountSetup(ctx context.Context, id string) (out runnerproto.AccountSetup, err error) { |
| + token, e := c.token("", false) |
| + if e != nil { |
| + return out, e |
| + } |
| + err = c.post(ctx, "account-setups", runnerproto.AccountSetupRequest{Version: 2, ID: id}, token, &out) |
| + return |
| +} |
| +func (c *HTTPInstance) ReportAccountSetup(ctx context.Context, q runnerproto.AccountSetupResult) (out runnerproto.AccountSetup, err error) { |
| + token, e := c.token("", false) |
| + if e != nil { |
| + return out, e |
| + } |
| + err = c.post(ctx, "account-setups", runnerproto.AccountSetupRequest{Version: 2, ID: q.ID, Result: &q}, token, &out) |
| + return |
| +} |
| +func LoginAccount(ctx context.Context, c Config, id string) error { |
| + if id == "" || len(id) > 128 { |
| + return provider.ErrContract |
| + } |
| + cred, err := readCredentials(filepath.Join(c.StateDir, "credentials.json")) |
| + if err != nil { |
| + return provider.ErrIdentity |
| + } |
| + instance := &HTTPInstance{origin: c.Origin + "/api/runner/v2", client: outboundClient(), bearer: cred.Bearer} |
| + login := runnersetup.AccountLogin{Root: filepath.Join(c.StateDir, "accounts"), RunnerID: cred.Bearer.RunnerID, Instance: instance, Driver: provider.NewLoginDriver()} |
| + // No terminal process or credential home is created while contracts are gated. |
| + _, err = login.Begin(ctx, id) |
| + return err |
| +} |
diff --git a/internal/runner/connections.go b/internal/runner/connections.go| index 27be1dce..c608614d 100644 |
| --- a/internal/runner/connections.go |
| +++ b/internal/runner/connections.go |
| @@ -11,22 +11,11 @@ import ( |
| "sort" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| + runnersetup "amadan.net/oficina/equipo/internal/runner/setup" |
| "amadan.net/oficina/equipo/internal/runner/workspace" |
| ) |
| -type AccountBinding struct { |
| - PersonID string `json:"person_id,omitempty"` |
| - ProviderHome string `json:"provider_home,omitempty"` |
| - ExpectedIdentity provider.Identity `json:"expected_identity,omitempty"` |
| - ID string `json:"id"` |
| - LocalID string `json:"local_id"` |
| - Provider string `json:"provider"` |
| - Family string `json:"family"` |
| - Model string `json:"model"` |
| - AccountID string `json:"account_id"` |
| - CredentialHome string `json:"credential_home"` |
| - Kind string `json:"kind"` |
| -} |
| +type AccountBinding = runnersetup.AccountBinding |
| func (c Config) securityPaths(bs []AccountBinding) workspace.SecurityPaths { |
| home, _ := os.UserHomeDir() |
| @@ -75,6 +64,7 @@ func bindingPolicy(c Config, bs []AccountBinding, b AccountBinding) (provider.Re |
| } |
| } |
| b.Model = "" |
| + b.Label = "" |
| raw, _ := json.Marshal(struct { |
| Binding AccountBinding |
| Mode string |
diff --git a/internal/runner/provider/login.go b/internal/runner/provider/login.go| new file mode 100644 |
| index 00000000..d6475642 |
| --- /dev/null |
| +++ b/internal/runner/provider/login.go |
| @@ -0,0 +1,56 @@ |
| +package provider |
| + |
| +import ( |
| + "context" |
| + "os" |
| + "time" |
| +) |
| + |
| +type LoginDriver interface { |
| + Begin(ctx context.Context, providerName, credentialHome string) (LoginChallenge, error) |
| + Poll(ctx context.Context, challengeID string) (LoginResult, error) |
| + Cancel(ctx context.Context, challengeID string) error |
| +} |
| +type LoginChallenge struct { |
| + ID, VerificationURI, UserCode, Mode string |
| + ExpiresAt time.Time |
| +} |
| +type LoginResult struct { |
| + State string |
| + Identity Identity |
| +} |
| + |
| +const ErrLoginUnavailable Error = "account_setup.unavailable" |
| + |
| +// The recorded Plan 2b material establishes ordinary login commands only. It |
| +// does not establish device output, headless exchange or callback ownership. |
| +// Keep production disabled until those contracts have recorded evidence. |
| +type unavailableLogin struct{} |
| + |
| +func NewLoginDriver() LoginDriver { return unavailableLogin{} } |
| +func (unavailableLogin) Supported(string) bool { return false } |
| +func (unavailableLogin) Begin(context.Context, string, string) (LoginChallenge, error) { |
| + return LoginChallenge{}, ErrLoginUnavailable |
| +} |
| +func (unavailableLogin) Poll(context.Context, string) (LoginResult, error) { |
| + return LoginResult{State: "unavailable"}, ErrLoginUnavailable |
| +} |
| +func (unavailableLogin) Cancel(context.Context, string) error { return nil } |
| + |
| +// NewLoginHome allocates an empty private home. Existing accounts are never |
| +// adopted, refreshed or overwritten by the new-account path. |
| +func NewLoginHome(root string) (string, error) { |
| + rules := DefaultHomeRules() |
| + if rules.RefusesPath(root) || refusedMountAlias(root, rules) { |
| + return "", ErrPolicy |
| + } |
| + dir, err := makePrivateRoot(root) |
| + if err != nil { |
| + return "", ErrPolicy |
| + } |
| + defer dir.Close() |
| + if !privateDirectory(dir) { |
| + return "", ErrPolicy |
| + } |
| + return os.MkdirTemp(root, "account-") |
| +} |
diff --git a/internal/runner/runtime_direct.go b/internal/runner/runtime_direct.go| index 60875d18..19ac30b4 100644 |
| --- a/internal/runner/runtime_direct.go |
| +++ b/internal/runner/runtime_direct.go |
| @@ -112,7 +112,7 @@ func (r *Runtime) discoverNamespaces(ctx context.Context) ([]runnerproto.Connect |
| reports := make([]runnerproto.ConnectionReport, 0, len(bs)) |
| for _, b := range bs { |
| hash := sha256.Sum256([]byte(b.ProviderHome)) |
| - report := runnerproto.ConnectionReport{LocalID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, Kind: b.Kind, ProviderVersion: b.ExpectedIdentity.ProviderVersion, LauncherVersion: directLauncherVersion(), BwrapVersion: "0.11.0", PolicyVersion: provider.PolicyVersion, ProviderVersionSource: "direct-cli", UnavailableReason: "capability_unverified", IsolationConfigHash: runnerproto.EventHash(b), Routing: runnerproto.ConnectionRouting{BindingID: b.ID, AccountID: b.AccountID, CredentialHomeHash: hex.EncodeToString(hash[:])}} |
| + report := runnerproto.ConnectionReport{AccountLabel: b.Label, LocalID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, Kind: b.Kind, ProviderVersion: b.ExpectedIdentity.ProviderVersion, LauncherVersion: directLauncherVersion(), BwrapVersion: "0.11.0", PolicyVersion: provider.PolicyVersion, ProviderVersionSource: "direct-cli", UnavailableReason: "capability_unverified", IsolationConfigHash: runnerproto.EventHash(b), Routing: runnerproto.ConnectionRouting{BindingID: b.ID, AccountID: b.AccountID, CredentialHomeHash: hex.EncodeToString(hash[:])}} |
| work, err := os.MkdirTemp(r.cfg.WorkspaceRoot, "preflight-") |
| if err != nil { |
| return nil, err |
diff --git a/internal/runner/setup/account_bindings.go b/internal/runner/setup/account_bindings.go| new file mode 100644 |
| index 00000000..3be1a052 |
| --- /dev/null |
| +++ b/internal/runner/setup/account_bindings.go |
| @@ -0,0 +1,103 @@ |
| +package runnersetup |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +type AccountBinding struct { |
| + Label string `json:"label,omitempty"` |
| + PersonID string `json:"person_id,omitempty"` |
| + ProviderHome string `json:"provider_home,omitempty"` |
| + ExpectedIdentity provider.Identity `json:"expected_identity,omitempty"` |
| + ID string `json:"id"` |
| + LocalID string `json:"local_id"` |
| + Provider string `json:"provider"` |
| + Family string `json:"family"` |
| + Model string `json:"model"` |
| + AccountID string `json:"account_id"` |
| + CredentialHome string `json:"credential_home"` |
| + Kind string `json:"kind"` |
| +} |
| + |
| +// SaveAccountBinding appends a verified account atomically. Refresh belongs to |
| +// AccountLease, so this path refuses any existing account identity or home. |
| +func SaveAccountBinding(ctx context.Context, path, person, model string, s runnerproto.AccountSetup, b provider.Binding) error { |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| + if person == "" || model == "" || s.ID == "" || s.ID != b.ID || s.Provider != b.Provider || b.AccountID == "" || b.Expected.AccountID != b.AccountID || b.Expected.HomeID == "" || b.Expected.ProviderVersion == "" || provider.DefaultHomeRules().RefusesPath(b.Home) { |
| + return provider.ErrIdentity |
| + } |
| + dir := filepath.Dir(path) |
| + real, err := filepath.EvalSymlinks(dir) |
| + if err != nil || real != dir { |
| + return provider.ErrPolicy |
| + } |
| + f, err := os.Open(dir) |
| + if err != nil { |
| + return provider.ErrPolicy |
| + } |
| + defer f.Close() |
| + st, err := f.Stat() |
| + if err != nil || st.Mode().Perm() != 0700 { |
| + return provider.ErrPolicy |
| + } |
| + if err = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { |
| + return provider.ErrAccountBusy |
| + } |
| + defer unix.Flock(int(f.Fd()), unix.LOCK_UN) |
| + var rows []AccountBinding |
| + st, err = os.Lstat(path) |
| + if err == nil { |
| + if !st.Mode().IsRegular() || st.Mode().Perm() != 0600 || st.Size() > 1<<20 { |
| + return provider.ErrPolicy |
| + } |
| + in, err := os.Open(path) |
| + if err != nil { |
| + return provider.ErrPolicy |
| + } |
| + err = runnerproto.DecodeLimit(io.LimitReader(in, 1<<20), &rows, 1<<20) |
| + in.Close() |
| + if err != nil { |
| + return provider.ErrIdentity |
| + } |
| + } else if !os.IsNotExist(err) { |
| + return provider.ErrPolicy |
| + } |
| + if len(rows) >= 256 { |
| + return provider.ErrIdentity |
| + } |
| + for _, row := range rows { |
| + if row.ID == b.ID || row.LocalID == s.ID || row.ProviderHome == b.Home || row.ExpectedIdentity.HomeID == b.Expected.HomeID || row.Provider == b.Provider && row.AccountID == b.AccountID { |
| + return provider.ErrIdentity |
| + } |
| + } |
| + rows = append(rows, AccountBinding{ID: b.ID, LocalID: s.ID, Label: s.Label, PersonID: person, ProviderHome: b.Home, ExpectedIdentity: b.Expected, Provider: b.Provider, Family: map[string]string{"codex": "gpt", "claude": "claude"}[b.Provider], Model: model, AccountID: b.AccountID, Kind: "subscription"}) |
| + out, err := os.CreateTemp(dir, ".accounts-") |
| + if err != nil { |
| + return provider.ErrAccountMaintenance |
| + } |
| + defer os.Remove(out.Name()) |
| + defer out.Close() |
| + if err = json.NewEncoder(out).Encode(rows); err != nil { |
| + return provider.ErrAccountMaintenance |
| + } |
| + if err = out.Sync(); err != nil { |
| + return provider.ErrAccountMaintenance |
| + } |
| + if err = out.Close(); err != nil { |
| + return provider.ErrAccountMaintenance |
| + } |
| + if err = os.Rename(out.Name(), path); err != nil { |
| + return provider.ErrAccountMaintenance |
| + } |
| + return f.Sync() |
| +} |
diff --git a/internal/runner/setup/account_login.go b/internal/runner/setup/account_login.go| new file mode 100644 |
| index 00000000..4149db48 |
| --- /dev/null |
| +++ b/internal/runner/setup/account_login.go |
| @@ -0,0 +1,199 @@ |
| +package runnersetup |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +type AccountInstance interface { |
| + AccountSetup(context.Context, string) (runnerproto.AccountSetup, error) |
| + ReportAccountSetup(context.Context, runnerproto.AccountSetupResult) (runnerproto.AccountSetup, error) |
| +} |
| +type accountLogin struct { |
| + setup runnerproto.AccountSetup |
| + challenge provider.LoginChallenge |
| + home string |
| +} |
| +type AccountLogin struct { |
| + Root, RunnerID string |
| + Instance AccountInstance |
| + Driver provider.LoginDriver |
| + Probe func(context.Context, provider.Binding) (provider.Identity, error) |
| + Save func(context.Context, runnerproto.AccountSetup, provider.Binding) error |
| + active *accountLogin |
| +} |
| + |
| +func (l *AccountLogin) Begin(ctx context.Context, id string) (provider.LoginChallenge, error) { |
| + if l.active != nil { |
| + return provider.LoginChallenge{}, provider.ErrAccountBusy |
| + } |
| + s, err := l.Instance.AccountSetup(ctx, id) |
| + if err != nil || s.ID != id || s.RunnerID != l.RunnerID || s.State != "pending" || s.Revision < 1 { |
| + return provider.LoginChallenge{}, provider.ErrIdentity |
| + } |
| + if capability, ok := l.Driver.(interface{ Supported(string) bool }); ok && !capability.Supported(s.Provider) { |
| + _, err = l.Instance.ReportAccountSetup(ctx, runnerproto.AccountSetupResult{ID: s.ID, Revision: s.Revision, State: "unavailable"}) |
| + if err != nil { |
| + return provider.LoginChallenge{}, err |
| + } |
| + return provider.LoginChallenge{}, provider.ErrLoginUnavailable |
| + } |
| + home, err := provider.NewLoginHome(l.Root) |
| + if err != nil { |
| + return provider.LoginChallenge{}, err |
| + } |
| + // An exclusive marker records allocation only. Restart never resumes a |
| + // provider poll or claims that an uncertain terminal exchange succeeded. |
| + sum := sha256.Sum256([]byte(id)) |
| + marker := filepath.Join(l.Root, "setup-"+hex.EncodeToString(sum[:])+".json") |
| + f, err := os.OpenFile(marker, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) |
| + if err != nil { |
| + os.Remove(home) |
| + return provider.LoginChallenge{}, provider.ErrUncertain |
| + } |
| + raw, _ := json.Marshal(struct{ ID, Home string }{id, home}) |
| + _, err = f.Write(raw) |
| + if err == nil { |
| + err = f.Sync() |
| + } |
| + closeErr := f.Close() |
| + if err != nil || closeErr != nil { |
| + return provider.LoginChallenge{}, provider.ErrUncertain |
| + } |
| + c, err := l.Driver.Begin(ctx, s.Provider, home) |
| + if err != nil { |
| + _, _ = l.Instance.ReportAccountSetup(ctx, runnerproto.AccountSetupResult{ID: s.ID, Revision: s.Revision, State: "unavailable"}) |
| + return provider.LoginChallenge{}, provider.ErrLoginUnavailable |
| + } |
| + l.active = &accountLogin{setup: s, challenge: c, home: home} |
| + if c.ID == "" || !time.Now().Before(c.ExpiresAt) || c.Mode != s.Mode { |
| + _ = l.Driver.Cancel(ctx, c.ID) |
| + l.active = nil |
| + return provider.LoginChallenge{}, provider.ErrContract |
| + } |
| + var display *runnerproto.LoginDisplay |
| + if c.Mode == "device" { |
| + display = &runnerproto.LoginDisplay{VerificationURI: c.VerificationURI, UserCode: c.UserCode, ExpiresAt: c.ExpiresAt} |
| + } |
| + if !runnerproto.ValidLoginDisplay(s.Provider, s.Mode, display, time.Now()) { |
| + _ = l.Driver.Cancel(ctx, c.ID) |
| + l.active = nil |
| + return provider.LoginChallenge{}, provider.ErrContract |
| + } |
| + s, err = l.Instance.ReportAccountSetup(ctx, runnerproto.AccountSetupResult{ID: s.ID, Revision: s.Revision, State: "pending", Challenge: display}) |
| + if err != nil { |
| + _ = l.Driver.Cancel(ctx, c.ID) |
| + l.active = nil |
| + return provider.LoginChallenge{}, err |
| + } |
| + l.active.setup = s |
| + return c, nil |
| +} |
| +func (l *AccountLogin) current(ctx context.Context) error { |
| + if l.active == nil { |
| + return provider.ErrUncertain |
| + } |
| + s, e := l.Instance.AccountSetup(ctx, l.active.setup.ID) |
| + if e != nil || s.State != "pending" || s.RunnerID != l.RunnerID || s.Revision != l.active.setup.Revision { |
| + _ = l.Driver.Cancel(ctx, l.active.challenge.ID) |
| + return provider.ErrIdentity |
| + } |
| + return nil |
| +} |
| +func (l *AccountLogin) Poll(ctx context.Context) (runnerproto.AccountSetup, error) { |
| + if err := l.current(ctx); err != nil { |
| + return runnerproto.AccountSetup{}, err |
| + } |
| + a := l.active |
| + r := provider.LoginResult{State: "expired"} |
| + var err error |
| + if time.Now().Before(a.challenge.ExpiresAt) { |
| + r, err = l.Driver.Poll(ctx, a.challenge.ID) |
| + } else { |
| + _ = l.Driver.Cancel(ctx, a.challenge.ID) |
| + } |
| + if err != nil { |
| + return runnerproto.AccountSetup{}, provider.ErrLoginUnavailable |
| + } |
| + if r.State == "pending" { |
| + return a.setup, nil |
| + } |
| + switch r.State { |
| + case "connected", "expired", "denied", "cancelled", "unavailable": |
| + default: |
| + return runnerproto.AccountSetup{}, provider.ErrContract |
| + } |
| + q := runnerproto.AccountSetupResult{ID: a.setup.ID, Revision: a.setup.Revision, State: r.State} |
| + if r.State == "connected" { |
| + b, err := l.verify(ctx, r.Identity) |
| + if err != nil { |
| + _ = l.Driver.Cancel(ctx, a.challenge.ID) |
| + return runnerproto.AccountSetup{}, err |
| + } |
| + if err = l.current(ctx); err != nil { |
| + return runnerproto.AccountSetup{}, err |
| + } |
| + if l.Save == nil { |
| + return runnerproto.AccountSetup{}, provider.ErrContract |
| + } |
| + if err = l.Save(ctx, a.setup, b); err != nil { |
| + return runnerproto.AccountSetup{}, provider.ErrAccountMaintenance |
| + } |
| + q.AccountID = r.Identity.AccountID |
| + q.ProviderVersion = r.Identity.ProviderVersion |
| + } |
| + out, err := l.Instance.ReportAccountSetup(ctx, q) |
| + if err == nil { |
| + l.active = nil |
| + } |
| + return out, err |
| +} |
| +func (l *AccountLogin) verify(ctx context.Context, id provider.Identity) (provider.Binding, error) { |
| + a := l.active |
| + b := provider.Binding{ID: a.setup.ID, Home: a.home, AccountID: id.AccountID, Provider: a.setup.Provider, Expected: id, RuntimeRoot: filepath.Join(l.Root, "runtime")} |
| + if id.AccountID == "" || id.HomeID == "" || id.ProviderVersion == "" || l.Probe == nil { |
| + return b, provider.ErrIdentity |
| + } |
| + f, err := os.OpenFile(filepath.Join(a.home, provider.IdentityFile), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) |
| + if err != nil { |
| + return b, provider.ErrIdentity |
| + } |
| + raw, _ := json.Marshal(id) |
| + _, err = f.Write(raw) |
| + if err == nil { |
| + err = f.Sync() |
| + } |
| + ce := f.Close() |
| + if err != nil || ce != nil { |
| + return b, provider.ErrIdentity |
| + } |
| + lease, err := provider.OpenAccount(ctx, b) |
| + if err != nil { |
| + return b, err |
| + } |
| + defer lease.Close() |
| + if err = lease.Preflight(ctx, l.Probe); err != nil { |
| + return b, provider.ErrIdentity |
| + } |
| + return b, nil |
| +} |
| +func (l *AccountLogin) Cancel(ctx context.Context) error { |
| + if l.active == nil { |
| + return provider.ErrUncertain |
| + } |
| + a := l.active |
| + if err := l.Driver.Cancel(ctx, a.challenge.ID); err != nil { |
| + return provider.ErrAccountMaintenance |
| + } |
| + _, err := l.Instance.ReportAccountSetup(ctx, runnerproto.AccountSetupResult{ID: a.setup.ID, Revision: a.setup.Revision, State: "cancelled"}) |
| + l.active = nil |
| + return err |
| +} |
diff --git a/internal/runner/setup/account_login_test.go b/internal/runner/setup/account_login_test.go| new file mode 100644 |
| index 00000000..2f62b612 |
| --- /dev/null |
| +++ b/internal/runner/setup/account_login_test.go |
| @@ -0,0 +1,187 @@ |
| +package runnersetup |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +type loginFixture struct { |
| + home string |
| + state string |
| + cancelled bool |
| + identity provider.Identity |
| +} |
| + |
| +func (d *loginFixture) Begin(_ context.Context, name, home string) (provider.LoginChallenge, error) { |
| + d.home = home |
| + return provider.LoginChallenge{ID: "provider-secret", Mode: map[string]string{"claude": "browser", "codex": "device"}[name], VerificationURI: "https://auth.openai.com/codex/device", UserCode: "ABCD-EFGH", ExpiresAt: time.Now().Add(time.Minute)}, nil |
| +} |
| +func (d *loginFixture) Poll(context.Context, string) (provider.LoginResult, error) { |
| + return provider.LoginResult{State: d.state, Identity: d.identity}, nil |
| +} |
| +func (d *loginFixture) Cancel(context.Context, string) error { d.cancelled = true; return nil } |
| + |
| +type loginInstance struct { |
| + setup runnerproto.AccountSetup |
| + result runnerproto.AccountSetupResult |
| + err error |
| +} |
| + |
| +func (i *loginInstance) AccountSetup(_ context.Context, id string) (runnerproto.AccountSetup, error) { |
| + if id != i.setup.ID || i.err != nil { |
| + return runnerproto.AccountSetup{}, provider.ErrIdentity |
| + } |
| + return i.setup, nil |
| +} |
| +func (i *loginInstance) ReportAccountSetup(_ context.Context, r runnerproto.AccountSetupResult) (runnerproto.AccountSetup, error) { |
| + i.result = r |
| + if i.err != nil { |
| + return runnerproto.AccountSetup{}, i.err |
| + } |
| + i.setup.State = r.State |
| + i.setup.Revision++ |
| + return i.setup, nil |
| +} |
| +func loginHarness(t *testing.T, name string) (*AccountLogin, *loginFixture, *loginInstance) { |
| + t.Helper() |
| + root := filepath.Join(t.TempDir(), "private") |
| + d := &loginFixture{state: "pending", identity: provider.Identity{AccountID: "account", HomeID: "home", ProviderVersion: "fixture"}} |
| + i := &loginInstance{setup: runnerproto.AccountSetup{ID: "setup-one", RunnerID: "runner", Provider: name, State: "pending", Mode: map[string]string{"claude": "browser", "codex": "device"}[name], Revision: 1}} |
| + l := &AccountLogin{Root: root, RunnerID: "runner", Instance: i, Driver: d, Probe: func(context.Context, provider.Binding) (provider.Identity, error) { return d.identity, nil }, Save: func(context.Context, runnerproto.AccountSetup, provider.Binding) error { return nil }} |
| + return l, d, i |
| +} |
| +func TestOnboardingAccountDedicatedHome(t *testing.T) { |
| + ctx := context.Background() |
| + l, d, i := loginHarness(t, "codex") |
| + c, e := l.Begin(ctx, "setup-one") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + first := d.home |
| + st, e := os.Stat(first) |
| + if e != nil || st.Mode().Perm() != 0700 { |
| + t.Fatal("home not private", e) |
| + } |
| + if e = l.Cancel(ctx); e != nil { |
| + t.Fatal(e) |
| + } |
| + i.setup.State = "pending" |
| + i.setup.ID = "setup-two" |
| + _, e = l.Begin(ctx, "setup-two") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if first == d.home { |
| + t.Fatal("same-provider homes shared") |
| + } |
| + raw, _ := json.Marshal(i.result) |
| + if strings.Contains(string(raw), "provider-secret") || strings.Contains(string(raw), l.Root) { |
| + t.Fatal("secret left runner") |
| + } |
| + if c.ID != "provider-secret" { |
| + t.Fatal("local challenge lost") |
| + } |
| + bad, _, bi := loginHarness(t, "codex") |
| + bi.setup.ID = "fresh" |
| + bad.Root = filepath.Join(l.Root, ".codex") |
| + t.Setenv("CODEX_HOME", bad.Root) |
| + if _, e = bad.Begin(ctx, "fresh"); e == nil { |
| + t.Fatal("interactive home accepted") |
| + } |
| +} |
| +func TestOnboardingDeviceFlow(t *testing.T) { |
| + for _, state := range []string{"pending", "connected", "expired", "denied", "cancelled"} { |
| + t.Run(state, func(t *testing.T) { |
| + l, d, i := loginHarness(t, "codex") |
| + ctx := context.Background() |
| + _, e := l.Begin(ctx, i.setup.ID) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + d.state = state |
| + r, e := l.Poll(ctx) |
| + if state == "connected" { |
| + if e == nil || r.State == "connected" { |
| + t.Fatal("login succeeded without credential readback") |
| + } |
| + } else if e != nil || r.State != state { |
| + t.Fatal(state, r, e) |
| + } |
| + }) |
| + } |
| + l, d, i := loginHarness(t, "codex") |
| + _, e := l.Begin(context.Background(), i.setup.ID) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = l.Cancel(context.Background()); e != nil || !d.cancelled || i.result.State != "cancelled" { |
| + t.Fatal("cancel not contained", e) |
| + } |
| + restart := *l |
| + restart.active = nil |
| + if _, e = restart.Poll(context.Background()); e == nil { |
| + t.Fatal("restart invented success") |
| + } |
| +} |
| +func TestOnboardingNoDeviceCapability(t *testing.T) { |
| + for _, name := range []string{"claude", "codex"} { |
| + d := provider.NewLoginDriver() |
| + _, e := d.Begin(context.Background(), name, filepath.Join(t.TempDir(), "never-created")) |
| + if !errors.Is(e, provider.ErrLoginUnavailable) { |
| + t.Fatal("unrecorded login contract enabled", name, e) |
| + } |
| + } |
| + l, _, i := loginHarness(t, "claude") |
| + c, e := l.Begin(context.Background(), i.setup.ID) |
| + if e != nil || c.Mode != "browser" || i.result.Challenge != nil { |
| + t.Fatal("browser fallback exposed challenge", e) |
| + } |
| +} |
| + |
| +func TestOnboardingAccountBindings(t *testing.T) { |
| + root := filepath.Join(t.TempDir(), "state") |
| + if e := os.Mkdir(root, 0700); e != nil { |
| + t.Fatal(e) |
| + } |
| + path := filepath.Join(root, "accounts.json") |
| + s := runnerproto.AccountSetup{ID: "one", Provider: "codex", Label: "Personal"} |
| + b := provider.Binding{ID: "one", Provider: "codex", Home: filepath.Join(root, "one"), AccountID: "account-one", Expected: provider.Identity{AccountID: "account-one", HomeID: "home-one", ProviderVersion: "0.165.0"}} |
| + if e := SaveAccountBinding(context.Background(), path, "person", "model", s, b); e != nil { |
| + t.Fatal(e) |
| + } |
| + original, e := os.ReadFile(path) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = SaveAccountBinding(context.Background(), path, "person", "model", s, b); e == nil { |
| + t.Fatal("new setup replaced existing home") |
| + } |
| + after, _ := os.ReadFile(path) |
| + if string(after) != string(original) { |
| + t.Fatal("rejected save changed bindings") |
| + } |
| + s.ID = "two" |
| + s.Label = "Work" |
| + b.ID = "two" |
| + b.Home = filepath.Join(root, "two") |
| + b.AccountID = "account-two" |
| + b.Expected.AccountID = b.AccountID |
| + b.Expected.HomeID = "home-two" |
| + if e = SaveAccountBinding(context.Background(), path, "person", "model", s, b); e != nil { |
| + t.Fatal(e) |
| + } |
| + raw, _ := os.ReadFile(path) |
| + var rows []AccountBinding |
| + if e = json.Unmarshal(raw, &rows); e != nil || len(rows) != 2 || rows[0].Label != "Personal" || rows[1].Label != "Work" { |
| + t.Fatal("labeled accounts lost", e) |
| + } |
| +} |
diff --git a/internal/runner/setup/account_terminal_test.go b/internal/runner/setup/account_terminal_test.go| new file mode 100644 |
| index 00000000..32b2f334 |
| --- /dev/null |
| +++ b/internal/runner/setup/account_terminal_test.go |
| @@ -0,0 +1,261 @@ |
| +package runnersetup |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// This is a terminal boundary fixture, not a recording of a supported provider |
| +// exchange. Production remains unavailable until the live gate records it. |
| +type terminalLogin struct { |
| + loginFixture |
| + input string |
| + terminal *os.File |
| + done chan error |
| + cancel context.CancelFunc |
| +} |
| + |
| +func (d *terminalLogin) Begin(ctx context.Context, name, home string) (provider.LoginChallenge, error) { |
| + c, err := d.loginFixture.Begin(ctx, name, home) |
| + if err != nil { |
| + return c, err |
| + } |
| + fd, err := unix.Open("/dev/ptmx", unix.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0) |
| + if err != nil { |
| + return c, err |
| + } |
| + master := os.NewFile(uintptr(fd), "fixture-terminal") |
| + d.terminal = master |
| + if err = unix.IoctlSetPointerInt(fd, unix.TIOCSPTLCK, 0); err != nil { |
| + master.Close() |
| + return c, err |
| + } |
| + n, err := unix.IoctlGetInt(fd, unix.TIOCGPTN) |
| + if err != nil { |
| + master.Close() |
| + return c, err |
| + } |
| + slave, err := os.OpenFile(fmt.Sprintf("/dev/pts/%d", n), os.O_RDWR, 0) |
| + if err != nil { |
| + master.Close() |
| + return c, err |
| + } |
| + term, err := unix.IoctlGetTermios(int(slave.Fd()), unix.TCGETS) |
| + if err != nil { |
| + slave.Close() |
| + master.Close() |
| + return c, err |
| + } |
| + term.Lflag &^= unix.ECHO |
| + _ = unix.IoctlSetTermios(int(slave.Fd()), unix.TCSETS, term) |
| + child, cancel := context.WithCancel(ctx) |
| + d.cancel = cancel |
| + args := []string{"auth", "login"} |
| + if name == "codex" { |
| + args = []string{"login", "--device-auth"} |
| + } |
| + cmd := exec.CommandContext(child, name, args...) |
| + cmd.Env = []string{"HOME=" + home, "CLAUDE_CONFIG_DIR=" + home, "CLAUDE_SECURESTORAGE_CONFIG_DIR=" + home, "CODEX_HOME=" + home} |
| + cmd.Stdin = slave |
| + cmd.Stdout = slave |
| + cmd.Stderr = slave |
| + if err = cmd.Start(); err != nil { |
| + cancel() |
| + slave.Close() |
| + master.Close() |
| + return c, err |
| + } |
| + slave.Close() |
| + d.done = make(chan error, 1) |
| + go func() { d.done <- cmd.Wait() }() |
| + if d.input != "" { |
| + _, err = master.Write([]byte(d.input + "\n")) |
| + } |
| + return c, err |
| +} |
| +func (d *terminalLogin) Poll(context.Context, string) (provider.LoginResult, error) { |
| + select { |
| + case err := <-d.done: |
| + if err != nil { |
| + return provider.LoginResult{State: "denied"}, nil |
| + } |
| + return provider.LoginResult{State: "connected", Identity: d.identity}, nil |
| + default: |
| + return provider.LoginResult{State: "pending"}, nil |
| + } |
| +} |
| +func (d *terminalLogin) Cancel(context.Context, string) error { |
| + d.cancelled = true |
| + if d.cancel != nil { |
| + d.cancel() |
| + } |
| + if d.terminal != nil { |
| + d.terminal.Close() |
| + } |
| + return nil |
| +} |
| +func terminalFixture(t *testing.T, name, code string) (*AccountLogin, *terminalLogin, *loginInstance) { |
| + t.Helper() |
| + l, base, i := loginHarness(t, name) |
| + bin := t.TempDir() |
| + script := `#!/bin/sh |
| +set -eu |
| +umask 077 |
| +test -t 0 |
| +case "$1" in |
| + auth) test "$2" = login; home="$CLAUDE_CONFIG_DIR"; file=.credentials.json ;; |
| + login) test "$2" = --device-auth; home="$CODEX_HOME"; file=auth.json ;; |
| + *) exit 2 ;; |
| +esac |
| +printf '%s\n' 'Open the fixture browser link and return the code at this terminal.' |
| +IFS= read -r code |
| +test "$code" = 'TERMINAL-RETURN-SECRET' |
| +printf '%s' '{"token":"NATIVE-CREDENTIAL-SECRET"}' > "$home/$file" |
| +printf '%s' '{"account_id":"account","home_id":"home","provider_version":"fixture"}' > "$home/readback.json" |
| +` |
| + if err := os.WriteFile(filepath.Join(bin, name), []byte(script), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Setenv("PATH", bin) |
| + d := &terminalLogin{loginFixture: *base, input: code} |
| + l.Driver = d |
| + l.Probe = func(_ context.Context, b provider.Binding) (provider.Identity, error) { |
| + data, err := os.ReadFile(filepath.Join(d.home, "readback.json")) |
| + if err != nil { |
| + return provider.Identity{}, err |
| + } |
| + var id provider.Identity |
| + err = json.Unmarshal(data, &id) |
| + return id, err |
| + } |
| + t.Cleanup(func() { _ = d.Cancel(context.Background(), "") }) |
| + return l, d, i |
| +} |
| +func TestOnboardingClaudeHeadlessBrowserLogin(t *testing.T) { |
| + for _, name := range []string{"claude", "codex"} { |
| + t.Run(name, func(t *testing.T) { |
| + l, d, i := terminalFixture(t, name, "TERMINAL-RETURN-SECRET") |
| + saved := false |
| + l.Save = func(_ context.Context, s runnerproto.AccountSetup, b provider.Binding) error { |
| + saved = true |
| + if s.ID != i.setup.ID || b.Home != d.home { |
| + t.Fatal("wrong setup saved") |
| + } |
| + return nil |
| + } |
| + c, err := l.Begin(context.Background(), i.setup.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if name == "claude" && i.result.Challenge != nil { |
| + t.Fatal("browser challenge forwarded") |
| + } |
| + if c.ID != "provider-secret" { |
| + t.Fatal("local polling identity lost") |
| + } |
| + deadline := time.Now().Add(2 * time.Second) |
| + var out runnerproto.AccountSetup |
| + for time.Now().Before(deadline) { |
| + out, err = l.Poll(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if out.State != "pending" { |
| + break |
| + } |
| + time.Sleep(time.Millisecond) |
| + } |
| + if out.State != "connected" || !saved { |
| + t.Fatal("terminal login lacked verified identity", out) |
| + } |
| + raw, _ := json.Marshal(i.result) |
| + for _, secret := range []string{"TERMINAL-RETURN-SECRET", "NATIVE-CREDENTIAL-SECRET", "provider-secret", l.Root} { |
| + if strings.Contains(string(raw), secret) { |
| + t.Fatal("terminal secret left runner") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| +func TestOnboardingAccountIdentityReadback(t *testing.T) { |
| + for _, mismatch := range []bool{false, true} { |
| + t.Run(fmt.Sprint(mismatch), func(t *testing.T) { |
| + l, d, i := loginHarness(t, "codex") |
| + _, err := l.Begin(context.Background(), i.setup.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = os.WriteFile(filepath.Join(d.home, "auth.json"), []byte(`{"token":"FAKE"}`), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + d.state = "connected" |
| + saved := false |
| + l.Save = func(context.Context, runnerproto.AccountSetup, provider.Binding) error { saved = true; return nil } |
| + l.Probe = func(context.Context, provider.Binding) (provider.Identity, error) { |
| + id := d.identity |
| + if mismatch { |
| + id.AccountID = "changed" |
| + } |
| + return id, nil |
| + } |
| + out, err := l.Poll(context.Background()) |
| + if mismatch { |
| + if err == nil || saved || out.State == "connected" { |
| + t.Fatal("identity readback bypassed") |
| + } |
| + } else if err != nil || !saved || out.State != "connected" { |
| + t.Fatal("verified account failed", out, err) |
| + } |
| + }) |
| + } |
| +} |
| +func TestOnboardingAccountTerminalCancellation(t *testing.T) { |
| + l, d, i := terminalFixture(t, "claude", "") |
| + _, err := l.Begin(context.Background(), i.setup.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = l.Cancel(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + select { |
| + case <-d.done: |
| + case <-time.After(time.Second): |
| + t.Fatal("terminal child survived cancellation") |
| + } |
| + if i.result.State != "cancelled" { |
| + t.Fatal("cancelled terminal became connected") |
| + } |
| +} |
| +func TestOnboardingAccountRestart(t *testing.T) { |
| + l, _, i := loginHarness(t, "codex") |
| + _, err := l.Begin(context.Background(), i.setup.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + restarted := *l |
| + restarted.active = nil |
| + if _, err = restarted.Begin(context.Background(), i.setup.ID); err == nil { |
| + t.Fatal("restart reused uncertain home") |
| + } |
| + if _, err = restarted.Poll(context.Background()); err == nil { |
| + t.Fatal("restart invented connected state") |
| + } |
| + for _, state := range []string{"cancelled", "expired", "unavailable"} { |
| + i.setup.State = state |
| + if _, err = restarted.Begin(context.Background(), i.setup.ID); err == nil { |
| + t.Fatal("terminal state restarted", state) |
| + } |
| + } |
| +} |
diff --git a/internal/runnerproto/account_setup.go b/internal/runnerproto/account_setup.go| new file mode 100644 |
| index 00000000..00cbc09c |
| --- /dev/null |
| +++ b/internal/runnerproto/account_setup.go |
| @@ -0,0 +1,76 @@ |
| +package runnerproto |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "regexp" |
| + "time" |
| +) |
| + |
| +type LoginDisplay struct { |
| + VerificationURI, UserCode string |
| + ExpiresAt time.Time |
| +} |
| +type AccountSetup struct { |
| + ID, RunnerID, Provider, Label, State, Mode string |
| + Challenge *LoginDisplay |
| + ConnectionID string |
| + Revision int64 |
| +} |
| + |
| +// AccountSetupResult deliberately has no provider challenge ID, home or return code. |
| +type AccountSetupResult struct { |
| + ID, State, AccountID, ProviderVersion string |
| + Revision int64 |
| + Challenge *LoginDisplay |
| +} |
| +type AccountSetupRequest struct { |
| + Version int `json:"version"` |
| + ID string `json:"id"` |
| + Result *AccountSetupResult `json:"result,omitempty"` |
| +} |
| + |
| +var displayCode = regexp.MustCompile(`^[A-Z0-9]{4}-[A-Z0-9]{4}$`) |
| + |
| +func ValidLoginDisplay(provider, mode string, d *LoginDisplay, now time.Time) bool { |
| + if d == nil { |
| + return true |
| + } |
| + return provider == "codex" && mode == "device" && d.VerificationURI == "https://auth.openai.com/codex/device" && displayCode.MatchString(d.UserCode) && now.Before(d.ExpiresAt) && !d.ExpiresAt.After(now.Add(15*time.Minute)) |
| +} |
| + |
| +type AccountSetupAPI interface { |
| + RunnerAccountSetup(context.Context, RunnerPrincipal, string) (AccountSetup, error) |
| + ReportAccountSetup(context.Context, RunnerPrincipal, AccountSetupResult) (AccountSetup, error) |
| +} |
| + |
| +func (s *Handler) runnerAccountSetup(w http.ResponseWriter, r *http.Request) { |
| + p, _, ok := s.Bearer(w, r) |
| + if !ok { |
| + return |
| + } |
| + var q AccountSetupRequest |
| + if !s.Body(w, r, &q, 4096) { |
| + return |
| + } |
| + if q.Version != 2 || q.ID == "" || len(q.ID) > 128 || q.Result != nil && q.Result.ID != q.ID { |
| + s.Failure(w, s.Invalid) |
| + return |
| + } |
| + if s.AccountSetups == nil { |
| + s.Failure(w, s.Unavailable) |
| + return |
| + } |
| + var out AccountSetup |
| + var err error |
| + if q.Result == nil { |
| + out, err = s.AccountSetups.RunnerAccountSetup(r.Context(), p, q.ID) |
| + } else { |
| + out, err = s.AccountSetups.ReportAccountSetup(r.Context(), p, *q.Result) |
| + } |
| + if err != nil { |
| + s.Failure(w, err) |
| + return |
| + } |
| + s.JSON(w, 200, WorkResponse{Version: 2, Result: out}) |
| +} |
diff --git a/internal/runnerproto/handler.go b/internal/runnerproto/handler.go| index a94243df..4baa378a 100644 |
| --- a/internal/runnerproto/handler.go |
| +++ b/internal/runnerproto/handler.go |
| @@ -31,6 +31,7 @@ type ExecutionAPI interface { |
| ReadArtifact(context.Context, RunnerPrincipal, RunnerRequest, team.ArtifactID) (team.Artifact, error) |
| } |
| type Handler struct { |
| + AccountSetups AccountSetupAPI |
| Execution func() ExecutionAPI |
| AuthenticateRunner func(context.Context, string) (RunnerPrincipal, error) |
| ReportConnections func(context.Context, RunnerPrincipal, []ConnectionReport) error |
| @@ -44,6 +45,7 @@ type Handler struct { |
| func (s *Handler) Router() chi.Router { |
| r := chi.NewRouter() |
| + r.Post("/account-setups", s.runnerAccountSetup) |
| for _, op := range []string{"poll", "claim", "recover", "renew", "event", "containment", "tool", "tool_result"} { |
| r.Post("/coordinator/"+op, s.coordinatorRunnerOperation(op)) |
| } |