oficina / equipo Public

test: verify the foundation sign-in and project flow

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 87879f100be21a5180c348f37a179a657332a7fe parent 94e3c16
11 files changed, +752 −26
  • .gitignore +3 −0
  • README.md +24 −0
  • internal/equipo/budget_test.go +10 −0
  • internal/equipotest/authority_test.go +9 −0
  • internal/equipotest/browser_test.go +181 −26
  • internal/equipotest/budgets_test.go +3 −0
  • internal/equipotest/startup_test.go +98 −0
  • run.sh +28 −0
  • tools/drive/main.go +128 −0
  • tools/drive/main_test.go +96 −0
  • tools/drive/signin.go +172 −0

CI failed — run details

diff --git a/.gitignore b/.gitignore
index cf645f2f..6c3a0a20 100644
--- a/.gitignore
+++ b/.gitignore
@@ -9,3 +9,6 @@
.superpowers/
.claude/
+
+/.env.local
+/.local/
diff --git a/README.md b/README.md
index 81dacbb9..f080f877 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,27 @@
# equipo
An Oficina app: a coordinator and a team of AI specialists for running your own apps. The design is on the `design` branch.
+
+<!-- COPY REVIEW REQUIRED: local startup additions. -->
+
+## Local startup
+
+Create `.env.local` with the values below. Generate the instance key once with
+`openssl rand -hex 32` and keep that value across restarts.
+
+```sh
+EQUIPO_ORIGIN=http://127.0.0.1:8824
+EQUIPO_INSTANCE_KEY=replace-with-your-generated-key
+EQUIPO_OWNERS=you@example.com
+EQUIPO_ALLOW_LOGGED_MAIL=1
+```
+
+Run `./run.sh`. It builds the app and keeps its data in `equipo.db`.
+Owners are seeded only on the first boot. Logged mail prints local sign-in
+links. The environment file, database and `.local` build directory are ignored.
+
+For disposable sample data, run
+`CGO_ENABLED=0 go run ./tools/drive -db "$TMPDIR/equipo-drive.db"`.
+The path must be unused. Open the printed sign-in link and confirm it in your
+browser. The drive listens on `127.0.0.1:8824` and removes its database when you
+stop it with Ctrl-C.
diff --git a/internal/equipo/budget_test.go b/internal/equipo/budget_test.go
new file mode 100644
index 00000000..4a8409d6
--- /dev/null
+++ b/internal/equipo/budget_test.go
@@ -0,0 +1,10 @@
+package equipo
+
+import (
+ "os"
+ "testing"
+
+ "amadan.net/rastrillo/rastrillo/budget"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/internal/equipotest/authority_test.go b/internal/equipotest/authority_test.go
index 5f0b9970..35f63a5d 100644
--- a/internal/equipotest/authority_test.go
+++ b/internal/equipotest/authority_test.go
@@ -57,6 +57,7 @@ func requireRevoked(t *testing.T, auth *equipo.RosterAuthority, req team.Admissi
}
func TestAuthorityUsesLiveRoster(t *testing.T) {
+ t.Parallel()
s, d, p, _, auth, req := authorityFixture(t)
for _, address := range []string{"member@example.com", ownerAddress} {
for _, op := range authorityOps {
@@ -101,6 +102,7 @@ func TestAuthorityUsesLiveRoster(t *testing.T) {
}
func TestAuthorityRejectsMismatchedTarget(t *testing.T) {
+ t.Parallel()
s, _, p, _, auth, req := authorityFixture(t)
other := p
other.ID = 0
@@ -154,6 +156,7 @@ func TestAuthorityRejectsMismatchedTarget(t *testing.T) {
}
func TestAuthorityGrantReferences(t *testing.T) {
+ t.Parallel()
_, _, p, _, auth, req := authorityFixture(t)
ref := equipo.GrantRef(p.ID, " MEMBER@Example.com ")
if ref != req.Grant {
@@ -191,6 +194,7 @@ func TestAuthorityGrantReferences(t *testing.T) {
}
func TestAuthorityFailureIsNotRevocation(t *testing.T) {
+ t.Parallel()
_, d, _, clock, auth, req := authorityFixture(t)
for _, table := range []string{"teams", "projects", "members", "decision_owners"} {
t.Run(table, func(t *testing.T) {
@@ -223,6 +227,7 @@ func TestAuthorityFailureIsNotRevocation(t *testing.T) {
}
func TestAuthoritySnapshotChanges(t *testing.T) {
+ t.Parallel()
s, d, p, clock, auth, req := authorityFixture(t)
beforeAudit := scalar(t, d, "SELECT count(*) FROM audit_events")
first := requireAdmission(t, auth, req)
@@ -247,6 +252,7 @@ func TestAuthoritySnapshotChanges(t *testing.T) {
}
func TestAuthorityReadsOneSnapshot(t *testing.T) {
+ t.Parallel()
s, d, p, _, auth, req := authorityFixture(t)
changed := false
var changedProject equipo.Project
@@ -268,6 +274,7 @@ func TestAuthorityReadsOneSnapshot(t *testing.T) {
}
func TestAuthorityCoreIntegration(t *testing.T) {
+ t.Parallel()
for _, change := range []string{"project revision", "roster epoch", "work reassigned"} {
t.Run(change, func(t *testing.T) {
ctx := context.Background()
@@ -316,6 +323,7 @@ func TestAuthorityCoreIntegration(t *testing.T) {
}
func TestAuthorityProjectOwnershipIsLocal(t *testing.T) {
+ t.Parallel()
s, d, p, _, auth, req := authorityFixture(t)
other := p
other.ID, other.Revision = 0, 0
@@ -336,6 +344,7 @@ func TestAuthorityProjectOwnershipIsLocal(t *testing.T) {
}
func TestAuthorityProjectKinds(t *testing.T) {
+ t.Parallel()
s, _, p, _, auth, req := authorityFixture(t)
for _, kind := range []equipo.ProjectKind{equipo.ProjectRepository, equipo.ProjectWebsite} {
other := p
diff --git a/internal/equipotest/browser_test.go b/internal/equipotest/browser_test.go
index b6502dc8..c0a353ad 100644
--- a/internal/equipotest/browser_test.go
+++ b/internal/equipotest/browser_test.go
@@ -1,60 +1,215 @@
//go:build browser
-// The browser drive: the whole app in a real Chromium, wired exactly
-// as cmd/equipo/main.go wires it — loud on any console error, failed
-// request, 4xx/5xx, or JS value that leaked to the screen unrendered.
-// Not part of the plain suite:
-//
-// go test -tags browser ./...
-//
-// It needs a Chromium: on PATH, via RASTRILLO_CHROME, or in a
-// Playwright cache. A skip is not a pass — with no browser this fails,
-// unless RASTRILLO_BROWSER_OPTIONAL is set, which makes the skip a
-// deliberate visible choice rather than an accident.
package equipotest
import (
+ "context"
+ "fmt"
"io"
"log/slog"
"net/http"
+ "os"
"path/filepath"
+ "strings"
"testing"
+ "time"
+ "amadan.net/oficina/equipo/internal/equipo"
"amadan.net/rastrillo/rastrillo/db"
"amadan.net/rastrillo/rastrillo/harness"
+ "github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
-
- equipo "amadan.net/oficina/equipo/internal/equipo"
+ "github.com/chromedp/chromedp/kb"
)
-// TestBrowserWalk is the minimal loud walk: the home screen arrives
-// with nothing wrong anywhere the rig watches. Grow it with the app —
-// each screen a flow reaches earns a Screen() line, and an expected
-// probe (a signed-out 401, say) earns a rig.Allow.
-func TestBrowserWalk(t *testing.T) {
+func TestFoundationBrowserWalk(t *testing.T) {
mailer := &capturingMailer{}
rig := harness.New(t, func(origin string) http.Handler {
- // The scaffold's own wiring, origin included: the rig hands
- // the app its localhost origin before serving — the same seam
- // main.go fills from EQUIPO_ORIGIN.
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger)
if err != nil {
- t.Fatalf("db.Open: %v", err)
+ t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
mux, err := equipo.App(d, testConfig(origin), mailer, logger)
if err != nil {
- t.Fatalf("App: %v", err)
+ t.Fatal(err)
}
return mux
- })
+ }, harness.WithScrollbars())
+ noJS := os.Getenv("EQUIPO_BROWSER_NO_JS") == "1"
+ // The pinned harness treats Chromium's native cancelled-transition
+ // promise as an app exception, even with scripts disabled. Reduced motion
+ // keeps this walk about navigation and forms; shell focus scripts still run.
+ rig.Run(emulation.SetScriptExecutionDisabled(noJS), emulation.SetEmulatedMedia().WithFeatures([]*emulation.MediaFeature{{Name: "prefers-reduced-motion", Value: "reduce"}}))
+ t.Logf("scripts disabled: %t", noJS)
c := signinClient(t, rig.Origin)
signinEmail(t, c, rig.Origin, rig.Origin, mailer, ownerAddress)
for _, cookie := range c.Jar.Cookies(mustURL(t, rig.Origin)) {
rig.Run(network.SetCookie(cookie.Name, cookie.Value).WithURL(rig.Origin).WithPath("/"))
}
- rig.Run(chromedp.Navigate(rig.Origin + "/conversation"))
- rig.Screen("body", "conversation")
+ check := func(expression, reason string) {
+ t.Helper()
+ var ok bool
+ rig.Run(chromedp.Evaluate(expression, &ok))
+ if !ok {
+ t.Fatal(reason)
+ }
+ }
+ screen := func(note string) {
+ t.Helper()
+ t.Log(note)
+ rig.Screen("body", note)
+ rig.Run(browserWait(`!document.documentElement.matches(":active-view-transition") && document.getAnimations().every(a => a.playState !== "running")`))
+ check(`document.documentElement.scrollWidth <= document.documentElement.clientWidth && document.body.scrollWidth <= document.documentElement.clientWidth`, "horizontal overflow: "+note)
+ }
+ goTo := func(path string) {
+ t.Helper()
+ rig.Run(chromedp.Navigate(rig.Origin + path))
+ screen(path)
+ }
+ clickTo := func(selector, path string) {
+ t.Helper()
+ rig.Run(browserClick(selector), browserWait(fmt.Sprintf(`location.pathname + location.hash === %q`, path)))
+ screen(path)
+ }
+ shot := func(name string) {
+ t.Helper()
+ dir := os.Getenv("EQUIPO_BROWSER_ARTIFACTS")
+ if dir == "" {
+ return
+ }
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ t.Fatal(err)
+ }
+ var png []byte
+ rig.Run(chromedp.CaptureScreenshot(&png))
+ if err := os.WriteFile(filepath.Join(dir, name+".png"), png, 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, width := range []int64{1280, 390} {
+ rig.Run(chromedp.EmulateViewport(width, 900))
+ goTo("/conversation")
+ check(`!!document.querySelector('[data-empty-state]')`, "missing conversation empty state")
+ shot(fmt.Sprintf("empty-%d", width))
+ for i, path := range railPaths {
+ if width == 390 {
+ goTo("/work")
+ }
+ selector := fmt.Sprintf(`[rst-shell-nav] a[href=%q]`, path)
+ clickTo(selector, path)
+ check(fmt.Sprintf(`document.querySelector('[aria-current="page"]').getAttribute('href') === %q`, path), "wrong active destination")
+ if strings.HasPrefix(path, "/specialists/") && width == 390 {
+ key := strings.TrimPrefix(path, "/specialists/")
+ rig.Run(chromedp.Click(`[rel="up"]`, chromedp.ByQuery), browserWait(`location.pathname === '/work'`))
+ selected := "document.activeElement"
+ if noJS {
+ selected = "document.querySelector(':target')"
+ }
+ rig.Run(browserWait(fmt.Sprintf(`%s?.id === %q`, selected, "nav-"+key)))
+ check(fmt.Sprintf(`%s?.id === %q && %s.getBoundingClientRect().bottom <= innerHeight && %s.getBoundingClientRect().top >= 0`, selected, "nav-"+key, selected, selected), "back link missed visible index row")
+ rig.Run(browserWait(`!document.documentElement.matches(":active-view-transition") && document.getAnimations().every(a => a.playState !== "running")`))
+ check(`document.documentElement.scrollWidth <= innerWidth`, "parent index overflow")
+ shot("parent-" + key)
+ // The pinned chromedp can retain stale DOM node IDs after a
+ // back/forward-cache restoration. Assert the restored page
+ // above, then reload before Screen uses its node queries.
+ rig.Run(chromedp.ActionFunc(func(ctx context.Context) error {
+ _, err := chromedp.RunResponse(ctx, chromedp.Reload())
+ return err
+ }))
+ screen("specialist parent reloaded")
+ }
+ if i == 0 {
+ check(`!!document.querySelector('[data-empty-state]')`, "empty destination missing")
+ }
+ }
+ goTo("/work")
+ shot(fmt.Sprintf("index-%d", width))
+ // Content pages start keyboard traversal at the skip link.
+ goTo("/conversation")
+ rig.Run(chromedp.KeyEvent(kb.Tab))
+ check(`document.activeElement.matches('[rst-skip]')`, "skip link not first in keyboard order")
+ shot(fmt.Sprintf("focus-%d", width))
+ rig.Run(chromedp.KeyEvent(kb.Enter))
+ check(`location.hash === '#main'`, "skip link did not reach main")
+
+ goTo("/settings")
+ label := fmt.Sprintf("Browser account %d", width)
+ rig.Run(chromedp.SendKeys(`form[action="/accounts"]:has(input[name="id"][value="0"]) input[name="label"]`, label, chromedp.ByQuery), browserClick(`form[action="/accounts"]:has(input[name="id"][value="0"]) button`), browserWait(fmt.Sprintf(`Array.from(document.querySelectorAll('h2')).some(e => e.textContent === %q)`, label)))
+ screen("account saved")
+ for _, kind := range []string{"app", "website", "repository"} {
+ goTo("/projects/new")
+ name := fmt.Sprintf("%s %d %s", kind, width, strings.Repeat("LongProjectName", 12))
+ rig.Run(
+ chromedp.SetValue(`[name="account_id"]`, fmt.Sprint(map[int64]int{1280: 1, 390: 2}[width]), chromedp.ByQuery),
+ chromedp.SendKeys(`[name="name"]`, name, chromedp.ByQuery),
+ chromedp.SetValue(`[name="kind"]`, kind, chromedp.ByQuery),
+ chromedp.SendKeys(`[name="repository"]`, fmt.Sprintf("amadan.net/browser/%s-%d", kind, width), chromedp.ByQuery),
+ chromedp.SendKeys(`[name="default_branch"]`, "main", chromedp.ByQuery),
+ chromedp.SetValue(`[name="owner_work"]`, ownerAddress, chromedp.ByQuery),
+ chromedp.SetValue(`[name="owner_merge"]`, ownerAddress, chromedp.ByQuery),
+ )
+ if kind != "repository" {
+ rig.Run(chromedp.SendKeys(`[name="app_name"]`, fmt.Sprintf("%s-%d", kind, width), chromedp.ByQuery))
+ }
+ rig.Run(browserClick(`[equipo-form] button[type="submit"]`), browserWait(` /^\/projects\/\d+$/.test(location.pathname)`))
+ screen("created " + kind)
+ check(fmt.Sprintf(`document.querySelector('main h1').textContent === %q && !!document.querySelector('[data-project-kind="%s"]')`, name, kind), "project metadata missing")
+ var path string
+ rig.Run(chromedp.Location(&path))
+ path = strings.TrimPrefix(path, rig.Origin)
+ goTo("/projects")
+ check(fmt.Sprintf(`document.querySelector('h3 a[href=%q]').getClientRects().length > 1`, path), "long project name does not wrap")
+ clickTo(fmt.Sprintf(`h3 a[href=%q]`, path), path)
+ clickTo(fmt.Sprintf(`a[href=%q]`, path+"/edit"), path+"/edit")
+ rig.Run(chromedp.SetValue(`[name="name"]`, name+" edited", chromedp.ByQuery), chromedp.SetValue(`[name="default_branch"]`, "release/browser", chromedp.ByQuery), browserClick(`[equipo-form] button[type="submit"]`), browserWait(fmt.Sprintf(`location.pathname === %q`, path)))
+ screen("edited " + kind)
+ goTo(path)
+ check(fmt.Sprintf(`document.querySelector('main h1').textContent === %q && document.querySelector('[equipo-metadata]').textContent.includes('release/browser')`, name+" edited"), "edit did not persist")
+ }
+ goTo("/projects")
+ check(fmt.Sprintf(`document.querySelectorAll('[data-project-kind]').length === %d`, map[int64]int{1280: 3, 390: 6}[width]), "project count mismatch")
+ shot(fmt.Sprintf("projects-%d", width))
+ goTo("/specialists/engineering")
+ check(`document.querySelectorAll('[data-activity="empty"]').length === 3`, "specialist work is not empty")
+ shot(fmt.Sprintf("specialist-%d", width))
+ }
+ goTo("/work")
+ rig.Run(chromedp.Click(`[rst-shell-profile] summary`, chromedp.ByQuery))
+ clickTo(`form[action="/signout"] button`, "/signin")
+ goTo("/projects")
+ check(`location.pathname === '/signin' && !document.querySelector('[data-project-count]')`, "signout retained project access")
+}
+
+func browserWait(expression string) chromedp.Action {
+ return chromedp.ActionFunc(func(ctx context.Context) error {
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ tick := time.NewTicker(20 * time.Millisecond)
+ defer tick.Stop()
+ for {
+ var ok bool
+ err := chromedp.Evaluate("document.readyState === 'complete' && ("+expression+")", &ok).Do(ctx)
+ if err == nil && ok {
+ return nil
+ }
+ select {
+ case <-ctx.Done():
+ return fmt.Errorf("waiting for %s: %w (last evaluation: %v)", expression, ctx.Err(), err)
+ case <-tick.C:
+ }
+ }
+ })
+}
+
+func browserClick(selector string) chromedp.Action {
+ return chromedp.ActionFunc(func(ctx context.Context) error {
+ ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
+ defer cancel()
+ _, err := chromedp.RunResponse(ctx, chromedp.Click(selector, chromedp.ByQuery))
+ return err
+ })
}
diff --git a/internal/equipotest/budgets_test.go b/internal/equipotest/budgets_test.go
index 7379c533..e2307114 100644
--- a/internal/equipotest/budgets_test.go
+++ b/internal/equipotest/budgets_test.go
@@ -14,6 +14,7 @@ import (
)
func TestBudgetConfiguration(t *testing.T) {
+ t.Parallel()
ctx := context.Background()
s, d, a := projectStore(t)
if _, err := s.Budgets(ctx); !errors.Is(err, equipo.ErrUnavailable) {
@@ -81,6 +82,7 @@ func TestBudgetConfiguration(t *testing.T) {
}
}
func TestBudgetLoweringBelowUsage(t *testing.T) {
+ t.Parallel()
ctx := context.Background()
s, d, a := projectStore(t)
p := saveProject(t, s, projectInput(a), projectOwners(), "p")
@@ -158,6 +160,7 @@ func TestBudgetLoweringBelowUsage(t *testing.T) {
}
func TestBudgetConfigurationFailuresAreAtomic(t *testing.T) {
+ t.Parallel()
ctx := context.Background()
s, d, a := projectStore(t)
p := saveProject(t, s, projectInput(a), projectOwners(), "p")
diff --git a/internal/equipotest/startup_test.go b/internal/equipotest/startup_test.go
new file mode 100644
index 00000000..515c1923
--- /dev/null
+++ b/internal/equipotest/startup_test.go
@@ -0,0 +1,98 @@
+package equipotest
+
+import (
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/rastrillo/rastrillo/mail"
+)
+
+func TestProductionDoesNotUseDriveAuth(t *testing.T) {
+ t.Parallel()
+ for _, name := range []string{"missing key", "blank key", "missing origin", "invalid origin", "public logged mail", "nil mailer", "unconfigured mailer", "missing owners"} {
+ t.Run(name, func(t *testing.T) {
+ t.Parallel()
+ d, logger := foundationDB(t)
+ cfg := testConfig(testOrigin)
+ var sender mail.Sender = &capturingMailer{}
+ switch name {
+ case "missing key":
+ cfg.InstanceKey = ""
+ case "blank key":
+ cfg.InstanceKey = " "
+ case "missing origin":
+ cfg.Origin = ""
+ case "invalid origin":
+ cfg.Origin = "http://public.example.com"
+ case "public logged mail":
+ cfg.Origin = "https://public.example.com"
+ case "nil mailer":
+ sender = nil
+ case "unconfigured mailer":
+ cfg.AllowLoggedMail = false
+ sender = mail.Logged(logger)
+ case "missing owners":
+ cfg.Owners = nil
+ }
+ handler, err := equipo.App(d, cfg, sender, logger)
+ if err == nil || handler != nil {
+ t.Fatal("production constructed a handler without valid auth configuration")
+ }
+ })
+ }
+ t.Run("valid configuration still requires a session", func(t *testing.T) {
+ h := newApp(t)
+ for _, path := range append(append([]string{}, railPaths...), "/work", "/projects/new") {
+ res := get(t, h, path)
+ if res.Code != http.StatusSeeOther || res.Header().Get("Location") != "/signin" {
+ t.Fatalf("%s allowed anonymous access: %d", path, res.Code)
+ }
+ }
+ })
+}
+
+func TestLocalStartupScript(t *testing.T) {
+ script, err := filepath.Abs("../../run.sh")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(script); err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "equipo")
+ if err := os.WriteFile(bin, []byte("#!/bin/sh\nprintf '%s\\n' \"$@\"\n"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ envfile := filepath.Join(dir, "local.env")
+ valid := "EQUIPO_ORIGIN=http://127.0.0.1:8824\nEQUIPO_INSTANCE_KEY=persistent-test-key\nEQUIPO_ALLOW_LOGGED_MAIL=1\n"
+ for _, tc := range []struct {
+ name, config string
+ ok bool
+ }{
+ {"valid", valid, true},
+ {"missing key", "EQUIPO_ORIGIN=http://127.0.0.1:8824\n", false},
+ {"missing origin", "EQUIPO_INSTANCE_KEY=test-key\n", false},
+ {"public origin", valid + "EQUIPO_ORIGIN=https://public.example.com\n", false},
+ {"public listener", valid + "EQUIPO_ADDR=0.0.0.0:8824\n", false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if err := os.WriteFile(envfile, []byte(tc.config), 0600); err != nil {
+ t.Fatal(err)
+ }
+ cmd := exec.Command(script)
+ cmd.Env = []string{"PATH=" + os.Getenv("PATH"), "EQUIPO_ENV_FILE=" + envfile, "EQUIPO_BIN=" + bin, "EQUIPO_DB=" + filepath.Join(dir, "local.db")}
+ output, err := cmd.CombinedOutput()
+ if (err == nil) != tc.ok {
+ t.Fatalf("startup: %v: %s", err, output)
+ }
+ if tc.ok && string(output) != "--db\n"+filepath.Join(dir, "local.db")+"\n--addr\n127.0.0.1:8824\n" {
+ t.Fatalf("arguments: %s", output)
+ }
+ })
+ }
+}
diff --git a/run.sh b/run.sh
new file mode 100755
index 00000000..a18394ae
--- /dev/null
+++ b/run.sh
@@ -0,0 +1,28 @@
+#!/bin/sh
+# COPY REVIEW REQUIRED: local setup diagnostics.
+set -eu
+
+root=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+cd "$root"
+set -a
+. "${EQUIPO_ENV_FILE:-$root/.env.local}"
+set +a
+: "${EQUIPO_ORIGIN:?Set EQUIPO_ORIGIN in .env.local}"
+: "${EQUIPO_INSTANCE_KEY:?Set a persistent EQUIPO_INSTANCE_KEY in .env.local}"
+addr=${EQUIPO_ADDR:-127.0.0.1:8824}
+case "$addr" in
+ 127.0.0.1:*) port=${addr#127.0.0.1:} ;;
+ *) echo 'EQUIPO_ADDR must use 127.0.0.1' >&2; exit 1 ;;
+esac
+case "$port" in ''|*[!0-9]*) exit 1 ;; esac
+[ "$port" -ge 1 ] && [ "$port" -le 65535 ]
+[ "$EQUIPO_ORIGIN" = "http://$addr" ] || {
+ echo 'EQUIPO_ORIGIN must match the local address' >&2
+ exit 1
+}
+if [ -z "${EQUIPO_BIN:-}" ]; then
+ mkdir -p "$root/.local"
+ CGO_ENABLED=0 go build -o "$root/.local/equipo" ./cmd/equipo
+ EQUIPO_BIN=$root/.local/equipo
+fi
+exec "$EQUIPO_BIN" --db "${EQUIPO_DB:-$root/equipo.db}" --addr "$addr"
diff --git a/tools/drive/main.go b/tools/drive/main.go
new file mode 100644
index 00000000..31636875
--- /dev/null
+++ b/tools/drive/main.go
@@ -0,0 +1,128 @@
+// COPY REVIEW REQUIRED: local tool diagnostics and sample labels.
+package main
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "log/slog"
+ "net"
+ "net/http"
+ "os"
+ "os/signal"
+ "strconv"
+ "syscall"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/rastrillo/rastrillo/db"
+)
+
+const owner = "drive@example.com"
+
+func main() {
+ addr := flag.String("addr", "127.0.0.1:8824", "loopback address")
+ path := flag.String("db", "", "new scratch database path")
+ flag.Parse()
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+ if err := run(ctx, *addr, *path, os.Stdout); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
+
+func run(ctx context.Context, addr, path string, out io.Writer) error {
+ host, port, err := net.SplitHostPort(addr)
+ n, portErr := strconv.Atoi(port)
+ if err != nil || host != "127.0.0.1" || portErr != nil || n < 0 || n > 65535 {
+ return errors.New("-addr must use 127.0.0.1 and a valid port")
+ }
+ if path == "" {
+ return errors.New("-db is required")
+ }
+ for _, suffix := range []string{"", "-wal", "-shm"} {
+ if _, err := os.Lstat(path + suffix); !os.IsNotExist(err) {
+ return fmt.Errorf("scratch path must be unused: %s", path+suffix)
+ }
+ }
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ if err != nil {
+ return err
+ }
+ if err := f.Close(); err != nil {
+ os.Remove(path)
+ return err
+ }
+ defer func() {
+ for _, suffix := range []string{"", "-wal", "-shm"} {
+ _ = os.Remove(path + suffix)
+ }
+ }()
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ d, err := db.Open(path, logger)
+ if err != nil {
+ return err
+ }
+ defer d.Close()
+ ln, err := net.Listen("tcp", addr)
+ if err != nil {
+ return err
+ }
+ defer ln.Close()
+ origin := "http://" + ln.Addr().String()
+ key := make([]byte, 32)
+ if _, err := rand.Read(key); err != nil {
+ return err
+ }
+ mailer := &capture{}
+ mux, err := equipo.App(d, equipo.Config{Origin: origin, InstanceKey: hex.EncodeToString(key), Owners: []string{owner}, AllowLoggedMail: true}, mailer, logger)
+ if err != nil {
+ return err
+ }
+ server := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}
+ served := make(chan error, 1)
+ go func() { served <- server.Serve(ln) }()
+ defer func() {
+ shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if server.Shutdown(shutdown) != nil {
+ _ = server.Close()
+ }
+ <-served
+ }()
+ // Both challenges age together. The first session seeds the app; the second
+ // link remains unused so a person can confirm it in their own browser.
+ c := newClient()
+ first, err := prepare(ctx, c, origin)
+ if err != nil {
+ return err
+ }
+ second, err := prepare(ctx, c, origin)
+ if err != nil {
+ return err
+ }
+ link, err := begin(ctx, c, origin, first, mailer)
+ if err != nil {
+ return err
+ }
+ if err := confirm(c, link); err != nil {
+ return err
+ }
+ if err := seed(ctx, c, origin); err != nil {
+ return err
+ }
+ link, err = begin(ctx, c, origin, second, mailer)
+ if err != nil {
+ return err
+ }
+ if _, err := fmt.Fprintf(out, "[%s](%s)\n", link, link); err != nil {
+ return err
+ }
+ <-ctx.Done()
+ return nil
+}
diff --git a/tools/drive/main_test.go b/tools/drive/main_test.go
new file mode 100644
index 00000000..079e3d46
--- /dev/null
+++ b/tools/drive/main_test.go
@@ -0,0 +1,96 @@
+package main
+
+import (
+ "amadan.net/rastrillo/rastrillo/budget"
+ "bufio"
+ "context"
+ "io"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestDriveRefusesUnsafeStartup(t *testing.T) {
+ t.Parallel()
+ for _, addr := range []string{":8824", "0.0.0.0:8824", "localhost:8824", "[::]:8824", "100.119.180.57:8824"} {
+ if err := run(context.Background(), addr, filepath.Join(t.TempDir(), "drive.db"), io.Discard); err == nil {
+ t.Fatalf("accepted %s", addr)
+ }
+ }
+ if err := run(context.Background(), "127.0.0.1:0", "", io.Discard); err == nil {
+ t.Fatal("accepted missing scratch path")
+ }
+ for _, suffix := range []string{"", "-wal", "-shm"} {
+ path := filepath.Join(t.TempDir(), "drive.db")
+ if err := os.WriteFile(path+suffix, []byte("keep"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := run(context.Background(), "127.0.0.1:0", path, io.Discard); err == nil {
+ t.Fatal("accepted existing file")
+ }
+ b, err := os.ReadFile(path + suffix)
+ if err != nil || string(b) != "keep" {
+ t.Fatal("changed existing file")
+ }
+ }
+}
+
+func TestDriveRealSigninAndCleanup(t *testing.T) {
+ t.Parallel()
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ path := filepath.Join(t.TempDir(), "drive.db")
+ r, w := io.Pipe()
+ defer r.Close()
+ done := make(chan error, 1)
+ go func() { err := run(ctx, "127.0.0.1:0", path, w); w.Close(); done <- err }()
+ finished := false
+ t.Cleanup(func() {
+ cancel()
+ r.Close()
+ if !finished {
+ <-done
+ }
+ })
+ scanner := bufio.NewScanner(r)
+ if !scanner.Scan() {
+ t.Fatal("no sign-in link")
+ }
+ line := scanner.Text()
+ link := strings.Split(strings.TrimPrefix(line, "["), "](")[0]
+ c := newClient()
+ if err := confirm(c, link); err != nil {
+ t.Fatal(err)
+ }
+ origin := strings.Split(link, "/auth/")[0]
+ response, err := c.Get(origin + "/projects")
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := io.ReadAll(response.Body)
+ response.Body.Close()
+ if err != nil || response.StatusCode != http.StatusOK {
+ t.Fatalf("projects: %d %v", response.StatusCode, err)
+ }
+ for _, kind := range []string{"app", "website", "repository"} {
+ if !strings.Contains(string(b), `data-project-kind="`+kind+`"`) {
+ t.Fatalf("missing %s", kind)
+ }
+ }
+ cancel()
+ err = <-done
+ finished = true
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, suffix := range []string{"", "-wal", "-shm"} {
+ if _, err := os.Stat(path + suffix); !os.IsNotExist(err) {
+ t.Fatalf("scratch remains: %s: %v", suffix, err)
+ }
+ }
+}
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/tools/drive/signin.go b/tools/drive/signin.go
new file mode 100644
index 00000000..82fca34d
--- /dev/null
+++ b/tools/drive/signin.go
@@ -0,0 +1,172 @@
+package main
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "html"
+ "io"
+ "net/http"
+ "net/http/cookiejar"
+ "net/url"
+ "regexp"
+ "strings"
+ "sync"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/pow"
+)
+
+type capture struct {
+ mu sync.Mutex
+ link string
+}
+
+func (m *capture) Send(_ context.Context, _, _, body string) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ for _, word := range strings.Fields(body) {
+ if strings.Contains(word, "/auth/verify?") {
+ m.link = word
+ return nil
+ }
+ }
+ return errors.New("sign-in email has no link")
+}
+func (m *capture) last() string { m.mu.Lock(); defer m.mu.Unlock(); return m.link }
+func newClient() *http.Client {
+ jar, _ := cookiejar.New(nil)
+ return &http.Client{Jar: jar, Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+}
+
+var forms = regexp.MustCompile(`(?s)<form\b[^>]*>.*?</form>`)
+var inputs = regexp.MustCompile(`<input\b[^>]*>`)
+var attributes = regexp.MustCompile(`([a-z_-]+)="([^"]*)"`)
+
+func fields(c *http.Client, target, action string) (url.Values, error) {
+ res, err := c.Get(target)
+ if err != nil {
+ return nil, err
+ }
+ defer res.Body.Close()
+ body, err := io.ReadAll(res.Body)
+ if err != nil {
+ return nil, err
+ }
+ if res.StatusCode != 200 {
+ return nil, fmt.Errorf("GET %s: %d", res.Request.URL.Path, res.StatusCode)
+ }
+ for _, form := range forms.FindAllString(string(body), -1) {
+ if !strings.Contains(form, `action="`+action+`"`) {
+ continue
+ }
+ values := url.Values{}
+ for _, input := range inputs.FindAllString(form, -1) {
+ attrs := map[string]string{}
+ for _, pair := range attributes.FindAllStringSubmatch(input, -1) {
+ attrs[pair[1]] = html.UnescapeString(pair[2])
+ }
+ if attrs["name"] != "" {
+ values.Set(attrs["name"], attrs["value"])
+ }
+ }
+ return values, nil
+ }
+ return nil, fmt.Errorf("missing form: %s", action)
+}
+func post(ctx context.Context, c *http.Client, origin, path string, values url.Values) (string, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, origin+path, strings.NewReader(values.Encode()))
+ if err != nil {
+ return "", err
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Origin", origin)
+ res, err := c.Do(req)
+ if err != nil {
+ return "", err
+ }
+ defer res.Body.Close()
+ if res.StatusCode != 303 {
+ return "", fmt.Errorf("POST %s: %d", path, res.StatusCode)
+ }
+ return res.Header.Get("Location"), nil
+}
+
+type challenge struct {
+ values url.Values
+ ready time.Time
+}
+
+func prepare(_ context.Context, c *http.Client, origin string) (challenge, error) {
+ values, err := fields(c, origin+"/signin?force=1", "/auth/begin")
+ if err != nil {
+ return challenge{}, err
+ }
+ values.Set("address", owner)
+ return challenge{values, time.Now().Add(pow.DefaultMinAge + 50*time.Millisecond)}, nil
+}
+func begin(ctx context.Context, c *http.Client, origin string, ch challenge, m *capture) (string, error) {
+ timer := time.NewTimer(time.Until(ch.ready))
+ defer timer.Stop()
+ select {
+ case <-ctx.Done():
+ return "", ctx.Err()
+ case <-timer.C:
+ }
+ location, err := post(ctx, c, origin, "/auth/begin", ch.values)
+ if err != nil {
+ return "", err
+ }
+ if !strings.Contains(location, "sent=1") {
+ return "", errors.New("sign-in request refused")
+ }
+ return m.last(), nil
+}
+func confirm(c *http.Client, link string) error {
+ u, err := url.Parse(link)
+ if err != nil {
+ return err
+ }
+ values, err := fields(c, link, "/auth/verify")
+ if err != nil {
+ return err
+ }
+ location, err := post(context.Background(), c, u.Scheme+"://"+u.Host, "/auth/verify", values)
+ if err != nil {
+ return err
+ }
+ if location != "/conversation" {
+ return errors.New("sign-in confirmation refused")
+ }
+ return nil
+}
+func seed(ctx context.Context, c *http.Client, origin string) error {
+ _, err := post(ctx, c, origin, "/accounts", url.Values{"id": {"0"}, "revision": {"0"}, "label": {"Drive account"}})
+ if err != nil {
+ return err
+ }
+ for _, kind := range []string{"app", "website", "repository"} {
+ v, err := fields(c, origin+"/projects/new", "/projects")
+ if err != nil {
+ return err
+ }
+ v.Set("account_id", "1")
+ v.Set("name", "Drive "+kind)
+ v.Set("kind", kind)
+ v.Set("repository", "amadan.net/drive/"+kind)
+ if kind != "repository" {
+ v.Set("app_name", "drive-"+kind)
+ }
+ v.Set("default_branch", "main")
+ v.Set("owner_work", owner)
+ v.Set("owner_merge", owner)
+ location, err := post(ctx, c, origin, "/projects", v)
+ if err != nil {
+ return err
+ }
+ if !strings.HasPrefix(location, "/projects/") {
+ return errors.New("project was not saved")
+ }
+ }
+ return nil
+}