oficina / alta Public

web: Alta's pages, Home sign-in and the operator-only gate

Home sign-in only, through the shared handoff consumer (ALTA_HOME_* read
by home/connect): any Home identity gets a session, and every page but
the operator's (ALTA_OPERATOR_SUBJECT) answers the unknown page's 404.
Sessions end after 30 idle minutes or 12 hours. Posts are same-origin
(rastrillo csrf) except the assertion callback.

§11's pages, estilo's chrome and Calma, scriptless but for estilo's
busy.js: teams, new team, initialize (Paul types the pre-flight
sentence), the run page with both Home confirm links and the plan id's
first 8 hex to match on each, per-app steps in words, resume and a new
plan when a window closes, the team page with add apps, audit, the
owner retype after step 13 and the audit log, and retire with the typed
label and what survives. No live updates: refresh to see progress; live
runs also advance in the background every 20 s.

cmd/alta serves through rastrillo's activation contract; 'alta keygen'
prints fresh operator material and both roles' HOME_OPERATOR_HTTP.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 5587cdb4b0acafda7ba9362f2b47032b8f93d466 parent 44e93d7
17 files changed, +1,571 −0
  • cmd/alta/main.go +200 −0
  • go.mod +10 −0
  • go.sum +28 −0
  • internal/web/app.go +605 −0
  • internal/web/render.go +143 −0
  • internal/web/static/alta.css +21 −0
  • internal/web/templates/index.html +23 −0
  • internal/web/templates/initialize.html +9 −0
  • internal/web/templates/layout.html +33 −0
  • internal/web/templates/notfound.html +4 −0
  • internal/web/templates/retire.html +13 −0
  • internal/web/templates/run.html +41 −0
  • internal/web/templates/signedout.html +4 −0
  • internal/web/templates/team.html +48 −0
  • internal/web/templates/team_new.html +14 −0
  • internal/web/web_test.go +271 −0
  • internal/web/words.go +104 −0
diff --git a/cmd/alta/main.go b/cmd/alta/main.go
new file mode 100644
index 0000000..df2a455
--- /dev/null
+++ b/cmd/alta/main.go
@@ -0,0 +1,200 @@
+// Command alta is Alta, Paul's team-provisioning app
+// (home implementation/team-provisioning-app.md).
+//
+// alta serve (the CARLOS activation contract, or -addr)
+// alta keygen print fresh operator material and Home's pins
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "os"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/alta/console"
+ "amadan.net/oficina/alta/homeop"
+ "amadan.net/oficina/alta/internal/web"
+ "amadan.net/oficina/alta/provision"
+ "amadan.net/oficina/home/connect"
+ "amadan.net/rastrillo/rastrillo"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+)
+
+func main() {
+ logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
+ if len(os.Args) > 1 && os.Args[1] == "keygen" {
+ if err := keygen(os.Stdout); err != nil {
+ logger.Error("alta keygen", "err", err)
+ os.Exit(1)
+ }
+ return
+ }
+ if err := run(logger); err != nil {
+ logger.Error("alta: exiting", "err", err)
+ os.Exit(1)
+ }
+}
+
+func env(name string) string { return strings.TrimSpace(os.Getenv(name)) }
+
+func required(names ...string) error {
+ var missing []string
+ for _, n := range names {
+ if env(n) == "" {
+ missing = append(missing, n)
+ }
+ }
+ if len(missing) > 0 {
+ return fmt.Errorf("alta: missing %s", strings.Join(missing, ", "))
+ }
+ return nil
+}
+
+// config is everything run reads from the environment. Values are never
+// logged; errors name variables, not contents.
+func run(logger *slog.Logger) error {
+ if err := required("ALTA_ORIGIN", "ALTA_DEK", "ALTA_OPERATOR_SUBJECT", "ALTA_OPERATOR_KEY", "ALTA_OPERATOR_PREFILTER",
+ "ALTA_OPERATOR_INSTALLATION", "ALTA_OPERATOR_REGISTRY", "ALTA_OPERATOR_DEVICE", "ALTA_DIRECTORY_PROVISIONING_PUBLIC_KEY", "HOME_DIRECTORY_ORIGIN"); err != nil {
+ return err
+ }
+ origin := env("ALTA_ORIGIN")
+ if !homeop.Origin(origin) {
+ return errors.New("alta: ALTA_ORIGIN must be a bare https origin")
+ }
+ home, err := connect.LoadEnv("ALTA", origin)
+ if err != nil || home == nil {
+ return errors.New("alta: ALTA_HOME_* must configure Home sign-in (Alta has no other)")
+ }
+ if home.Directory == "" || !homeop.Origin(home.Directory) || !homeop.Origin(home.Issuer) {
+ return errors.New("alta: HOME_DIRECTORY_ORIGIN and ALTA_HOME_ISSUER must be bare https origins")
+ }
+ dek, err := base64.StdEncoding.Strict().DecodeString(env("ALTA_DEK"))
+ if err != nil || len(dek) != 32 {
+ return errors.New("alta: ALTA_DEK must be 32 bytes, standard base64")
+ }
+ keyRaw, err := base64.StdEncoding.Strict().DecodeString(env("ALTA_OPERATOR_KEY"))
+ if err != nil {
+ return errors.New("alta: ALTA_OPERATOR_KEY is not standard base64")
+ }
+ key, err := family.UnmarshalKeypair(keyRaw)
+ if err != nil {
+ return errors.New("alta: ALTA_OPERATOR_KEY is not a keypair")
+ }
+ prefilter := env("ALTA_OPERATOR_PREFILTER")
+ pins := []string{env("ALTA_OPERATOR_INSTALLATION"), env("ALTA_OPERATOR_REGISTRY"), env("ALTA_OPERATOR_DEVICE"), prefilter}
+ for _, p := range pins {
+ if !homeop.CanonicalToken(p) {
+ return errors.New("alta: the operator installation, registry, device and prefilter are 32 bytes, base64url")
+ }
+ }
+ provisioner := env("ALTA_DIRECTORY_PROVISIONING_PUBLIC_KEY")
+ if b, err := base64.RawURLEncoding.Strict().DecodeString(provisioner); err != nil || len(b) != 65 {
+ return errors.New("alta: ALTA_DIRECTORY_PROVISIONING_PUBLIC_KEY is a P-256 point, base64url")
+ }
+ account := env("ALTA_CARLOS_ACCOUNT")
+ if account == "" {
+ account = "bds"
+ }
+ consoleBase := env("ALTA_CARLOS_CONSOLE")
+ if consoleBase == "" {
+ consoleBase = "https://console.carloku.com"
+ }
+ tokens := map[string]string{}
+ for _, a := range provision.Apps {
+ if t := env("ALTA_CARLOS_" + a.Prefix); t != "" {
+ tokens[a.Slug] = t
+ }
+ }
+
+ opts, err := rastrillo.Resolve(rastrillo.Options{DBPath: "alta.db", Logger: logger})
+ if err != nil {
+ return fmt.Errorf("alta: resolve activation: %w", err)
+ }
+ db, err := provision.OpenDB(opts.DBPath)
+ if err != nil {
+ return fmt.Errorf("alta: open database: %w", err)
+ }
+ defer db.Close()
+ store, err := provision.NewStore(context.Background(), db, dek, time.Now, web.Extra...)
+ if err != nil {
+ return err
+ }
+ httpc := &http.Client{Timeout: 30 * time.Second}
+ roles := map[string]homeop.Role{}
+ for name, o := range map[string]string{homeop.Credential: home.Issuer, homeop.Directory: home.Directory} {
+ roles[name] = homeop.Role{Name: name, Origin: o, Installation: pins[0], Registry: pins[1], Device: pins[2]}
+ }
+ engine := provision.New(provision.Config{
+ Store: store,
+ Home: &homeop.Client{HTTP: httpc, Key: key, Prefilter: prefilter, Roles: roles},
+ Console: &console.Client{HTTP: httpc, Base: consoleBase, Account: account, Tokens: tokens, Guard: provision.Guard{Store: store, Account: account}},
+ Public: &http.Client{Timeout: 15 * time.Second},
+ HomeCfg: provision.HomeConfig{Issuer: home.Issuer, Directory: home.Directory, KeysBase64: env("ALTA_HOME_KEYS_BASE64"), Provisioner: provisioner},
+ Account: account, CallsZone: env("ALTA_CALLS_ZONE"), Logger: logger,
+ })
+ app, err := web.New(web.Config{Origin: origin, OperatorSubject: env("ALTA_OPERATOR_SUBJECT"), Home: home, Engine: engine, Store: store,
+ HomeDirectory: home.Directory, HomeCredential: home.Issuer, Account: account, Logger: logger, Tick: 20 * time.Second})
+ if err != nil {
+ return err
+ }
+ defer app.Close()
+ mux := http.NewServeMux()
+ mux.Handle("/", app)
+ opts.DBPath = ""
+ opts.Mux = mux
+ // Alta has no schedule of its own: a run that waits on a domain or a
+ // walk resumes when Paul next opens a page or presses Resume.
+ return rastrillo.Serve(opts)
+}
+
+// keygen prints fresh operator material for Alta, and the pins Home's
+// HOME_OPERATOR_HTTP needs on each role. The private key goes to
+// `carlos secrets set --app alta`; the rest is public.
+func keygen(w *os.File) error {
+ k, err := family.Generate()
+ if err != nil {
+ return err
+ }
+ raw, err := family.MarshalKeypair(k)
+ if err != nil {
+ return err
+ }
+ prefilter := homeop.Token()
+ pre, _ := base64.RawURLEncoding.DecodeString(prefilter)
+ sum := sha256.Sum256(pre)
+ pub := base64.RawURLEncoding.EncodeToString(k.SignPub())
+ inst, reg, dev := homeop.Token(), homeop.Token(), homeop.Token()
+ fmt.Fprintln(w, "# Alta's secrets (carlos secrets set --app alta):")
+ fmt.Fprintf(w, "ALTA_OPERATOR_KEY=%s\nALTA_OPERATOR_PREFILTER=%s\nALTA_DEK=%s\n", base64.StdEncoding.EncodeToString(raw), prefilter, base64.StdEncoding.EncodeToString(randomBytes()))
+ fmt.Fprintln(w, "# Alta's pins (carlos env set --app alta):")
+ fmt.Fprintf(w, "ALTA_OPERATOR_INSTALLATION=%s\nALTA_OPERATOR_REGISTRY=%s\nALTA_OPERATOR_DEVICE=%s\n", inst, reg, dev)
+ for _, role := range []struct{ name, origin string }{{"directory", "https://oficina.works"}, {"credential", "https://id.oficina.works"}} {
+ actions := []string{"directory.inspect", "directory.initialize", "directory.seed-team", "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer", "directory.disable-consumer"}
+ if role.name == "credential" {
+ actions = []string{"credential.inspect", "credential.owner-seed", "credential.register-consumer", "credential.retire-consumer"}
+ }
+ cfg := map[string]any{"version": 1, "role": role.name, "origin": role.origin, "installation": inst, "registry": reg, "device": dev,
+ "public_key": pub, "key_id": homeop.KeyID(k.SignPub()), "actions": actions, "operator_subject": "<Paul's person ref>",
+ "prefilter_token_sha256": hex.EncodeToString(sum[:])}
+ if role.name == "credential" {
+ cfg["directory_provisioning_public_key"] = "<the directory's provisioning public key>"
+ }
+ b, _ := json.Marshal(cfg)
+ fmt.Fprintf(w, "# HOME_OPERATOR_HTTP for the %s role:\n%s\n", role.name, b)
+ }
+ return nil
+}
+
+func randomBytes() []byte {
+ t := homeop.Token()
+ b, _ := base64.RawURLEncoding.DecodeString(t)
+ return b
+}
diff --git a/go.mod b/go.mod
index 7676bf3..184c9d9 100644
--- a/go.mod
+++ b/go.mod
@@ -5,20 +5,30 @@ go 1.26
toolchain go1.26.5
require (
+ amadan.net/oficina/estilo.git v0.0.0-20261026221328-cca97df85b67
+ amadan.net/oficina/home/connect v0.0.0-20261028092646-82d938882ed3
amadan.net/oficina/home/handoff v0.0.0-20261028092646-82d938882ed3
amadan.net/oficina/home/roster v0.0.0-20261028092646-82d938882ed3
amadan.net/rastrillo/rastrillo v0.29.1-0.20261028004840-5bb38c0ab31b
+ github.com/go-chi/chi/v5 v5.3.2
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2
modernc.org/sqlite v1.55.0
)
require (
+ amadan.net/rastrillo/rastrillo/money v0.1.0 // indirect
+ github.com/carlosframework/rastrillo v0.23.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/google/uuid v1.6.0 // indirect
+ github.com/jinzhu/inflection v1.0.0 // indirect
+ github.com/jinzhu/now v1.1.5 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/sys v0.46.0 // indirect
+ golang.org/x/text v0.39.0 // indirect
+ gorm.io/gorm v1.31.2 // indirect
+ gorm.io/plugin/dbresolver v1.6.2 // indirect
modernc.org/libc v1.74.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
diff --git a/go.sum b/go.sum
index 53fb821..995fa6d 100644
--- a/go.sum
+++ b/go.sum
@@ -1,3 +1,7 @@
+amadan.net/oficina/estilo.git v0.0.0-20261026221328-cca97df85b67 h1:B0mReCGiVImozUwSVHhsvSYycEd8hxxAX8cU6nlEDWE=
+amadan.net/oficina/estilo.git v0.0.0-20261026221328-cca97df85b67/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
+amadan.net/oficina/home/connect v0.0.0-20261028092646-82d938882ed3 h1:ErD9M+ESc00+x8d8p3621bh4Ykoz9QWHvYiDtFPxGsQ=
+amadan.net/oficina/home/connect v0.0.0-20261028092646-82d938882ed3/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk=
amadan.net/oficina/home/handoff v0.0.0-20261028092646-82d938882ed3 h1:KQ3zM7eJp/JRQuPI2090jVcV5fJSVmOvonVAfSWzwUY=
amadan.net/oficina/home/handoff v0.0.0-20261028092646-82d938882ed3/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k=
amadan.net/oficina/home/roster v0.0.0-20261028092646-82d938882ed3 h1:AjimnZNNK8kIlaba371a4TgO7Z04DgLLBhjv25k2fPo=
@@ -6,10 +10,28 @@ amadan.net/rastrillo/rastrillo v0.29.1-0.20261028004840-5bb38c0ab31b h1:7rApPVcE
amadan.net/rastrillo/rastrillo v0.29.1-0.20261028004840-5bb38c0ab31b/go.mod h1:jSSeydqEvlm/fU3hhWoXFnyEaDgroR8LPRZSo9ZhhIM=
amadan.net/rastrillo/rastrillo/money v0.1.0 h1:MxU4oqNrW8abxRTkgZBv24OYNpFnvonajNqeLIzmmaM=
amadan.net/rastrillo/rastrillo/money v0.1.0/go.mod h1:cmgkjBEIQh1pFSYvQk0UU6oPYS8kSDypdT9+t4Flx0U=
+github.com/carlosframework/rastrillo v0.23.0 h1:tKAAlwPt4Pg/rkqk7o6jvV12bbZ0r34oEVpuOlKfX7w=
+github.com/carlosframework/rastrillo v0.23.0/go.mod h1:pZlrE5F5OhspvZFzef0DrfjHAjA8FXycb9J5/8vc8Tw=
+github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 h1:UQ4AU+BGti3Sy/aLU8KVseYKNALcX9UXY6DfpwQ6J8E=
+github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327/go.mod h1:NItd7aLkcfOA/dcMXvl8p1u+lQqioRMq/SqDp71Pb/k=
+github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZSzM=
+github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo=
+github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
+github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
+github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
+github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 h1:iizUGZ9pEquQS5jTGkh4AqeeHCMbfbjeb0zMt0aEFzs=
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2/go.mod h1:TiCD2a1pcmjd7YnhGH0f/zKNcCD06B029pHhzV23c2M=
+github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
+github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
+github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
+github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
+github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
+github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
+github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
+github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -24,6 +46,8 @@ github.com/keymaildev/signin v0.1.1 h1:gO+1IAM99sqUkBtCezkgGxab+/DOrqwDxd5H32N1s
github.com/keymaildev/signin v0.1.1/go.mod h1:Eb/sCmEel1jlcdkgPOrNeMn5jvxzoFvJrdjDUxOBHls=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
+github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
@@ -41,6 +65,10 @@ golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
+gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
+gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
+gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
+gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
gorm.io/plugin/dbresolver v1.6.2 h1:F4b85TenghUeITqe3+epPSUtHH7RIk3fXr5l83DF8Pc=
diff --git a/internal/web/app.go b/internal/web/app.go
new file mode 100644
index 0000000..aee83c2
--- /dev/null
+++ b/internal/web/app.go
@@ -0,0 +1,605 @@
+// Package web is Alta's pages (team-provisioning-app.md §11): plain GETs
+// and form POSTs, no live updates, estilo's chrome, scriptless except
+// estilo's busy.js. Only one person ref, ALTA_OPERATOR_SUBJECT, sees any
+// page; any other signed-in identity gets the 404 an unknown page gets.
+package web
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "net/http"
+ "net/mail"
+ "net/url"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/alta/homeop"
+ "amadan.net/oficina/alta/provision"
+ "amadan.net/oficina/home/connect"
+ "amadan.net/oficina/home/handoff"
+ "amadan.net/oficina/home/handoff/seal"
+ "amadan.net/rastrillo/rastrillo/assertion"
+ "amadan.net/rastrillo/rastrillo/csrf"
+ "amadan.net/rastrillo/rastrillo/migrate"
+ "amadan.net/rastrillo/rastrillo/sessions"
+ "github.com/go-chi/chi/v5"
+)
+
+// Session lifetimes (§2): idle 30 minutes, absolute 12 hours.
+const (
+ IdleLifetime = 30 * time.Minute
+ AbsoluteLifetime = 12 * time.Hour
+)
+
+// Extra is the migration sets Alta's database carries beside its own:
+// sessions and the Home hand-off.
+var Extra = []*migrate.Set{sessions.Schema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff")}
+
+// Config is the app's wiring.
+type Config struct {
+ Origin string
+ OperatorSubject string
+ Home *connect.DecodedCredentials
+ Engine *provision.Engine
+ Store *provision.Store
+ // HomeDirectory and HomeCredential are the two confirm origins.
+ HomeDirectory, HomeCredential string
+ Account string
+ Logger *slog.Logger
+ Now func() time.Time
+ // Tick is how often live runs are advanced in the background; zero
+ // disables (tests drive the engine themselves).
+ Tick time.Duration
+}
+
+// App is Alta's HTTP handler.
+type App struct {
+ cfg Config
+ sess *sessions.Sessions
+ consumer *handoff.Consumer
+ mux http.Handler
+
+ mu sync.Mutex
+ running map[int64]bool
+ done chan struct{}
+ stopOnce sync.Once
+}
+
+// New builds the app. Home sign-in is required: Alta has no other.
+func New(cfg Config) (*App, error) {
+ if cfg.Home == nil || cfg.OperatorSubject == "" || cfg.Engine == nil || cfg.Store == nil || cfg.Origin == "" {
+ return nil, errors.New("web: Home sign-in, the operator subject, the engine and the origin are required")
+ }
+ if !homeop.PersonRef(cfg.OperatorSubject) {
+ return nil, errors.New("web: ALTA_OPERATOR_SUBJECT is not a person ref")
+ }
+ if cfg.Logger == nil {
+ cfg.Logger = slog.Default()
+ }
+ if cfg.Now == nil {
+ cfg.Now = time.Now
+ }
+ db := cfg.Store.DB()
+ sess, err := sessions.New(sessions.Config{DB: db, Origin: cfg.Origin, TTL: AbsoluteLifetime, SigninPath: handoff.StartPath, Logger: cfg.Logger, Now: cfg.Now})
+ if err != nil {
+ return nil, err
+ }
+ sealer, err := seal.New(cfg.Home.DEK, "oficina/alta/handoff")
+ if err != nil {
+ return nil, err
+ }
+ store, err := handoff.NewStore(db, sealer, cfg.Home.Issuer, cfg.Origin, cfg.Home.Keys)
+ if err != nil {
+ return nil, err
+ }
+ a := &App{cfg: cfg, sess: sess, running: map[int64]bool{}, done: make(chan struct{})}
+ a.consumer, err = handoff.NewConsumer(handoff.ConsumerConfig{Store: store, ConsumerID: cfg.Home.ConsumerID, Now: cfg.Now,
+ CurrentSubject: func(r *http.Request) string {
+ if s, ok := sess.From(r); ok {
+ return s.Subject
+ }
+ return ""
+ },
+ Complete: func(w http.ResponseWriter, r *http.Request, c assertion.Claims) error {
+ // Any Home identity gets a session; only the operator gets a
+ // page. Refusing the session instead would loop the sign-in.
+ return sess.SignIn(w, r, sessions.Session{Subject: c.Subject, Method: "home", AuthTime: time.Unix(c.AuthTime, 0)})
+ },
+ Fail: func(w http.ResponseWriter, r *http.Request, status int) {
+ a.plain(w, status, "Unable to sign in. Start again.")
+ }})
+ if err != nil {
+ return nil, err
+ }
+ a.mux = a.routes()
+ if cfg.Tick > 0 {
+ go a.tick(cfg.Tick)
+ }
+ return a, nil
+}
+
+// Close stops the background ticker.
+func (a *App) Close() { a.stopOnce.Do(func() { close(a.done) }) }
+
+func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) { a.mux.ServeHTTP(w, r) }
+
+func (a *App) routes() http.Handler {
+ r := chi.NewRouter()
+ r.Handle(assetPrefix+"*", assetHandler())
+ // The assertion callback is the one route outside CSRF: Home's page
+ // posts it cross-origin with its exact Origin.
+ r.Post(handoff.CallbackPath, a.consumer.Callback)
+ r.Group(func(r chi.Router) {
+ r.Use(csrf.Protect(a.cfg.Origin))
+ r.Use(a.sess.Middleware)
+ r.Get(handoff.StartPath, a.consumer.Start)
+ r.Get(handoff.FinishPath, a.consumer.Finish)
+ r.Post("/signout", a.signout)
+ r.Group(func(r chi.Router) {
+ r.Use(a.operatorOnly)
+ r.Get("/", a.index)
+ r.Get("/initialize", a.initializeForm)
+ r.Post("/initialize", a.initialize)
+ r.Get("/teams/new", a.newTeamForm)
+ r.Post("/teams", a.createTeam)
+ r.Get("/teams/{label}", a.team)
+ r.Post("/teams/{label}/apps", a.addApps)
+ r.Post("/teams/{label}/owner", a.retypeOwner)
+ r.Post("/teams/{label}/audit", a.audit)
+ r.Get("/teams/{label}/retire", a.retireForm)
+ r.Post("/teams/{label}/retire", a.retire)
+ r.Get("/runs/{id}", a.run)
+ r.Post("/runs/{id}/advance", a.advance)
+ r.Post("/runs/{id}/plan", a.resubmit)
+ })
+ })
+ r.NotFound(func(w http.ResponseWriter, r *http.Request) { a.notFound(w, r) })
+ return r
+}
+
+// operatorOnly sends a signed-out browser to Home's sign-in and answers
+// any identity but the operator's with the unknown page's 404. It also
+// keeps the idle clock.
+func (a *App) operatorOnly(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ s, ok := sessions.Current(r)
+ if !ok {
+ if r.Method == http.MethodGet || r.Method == http.MethodHead {
+ http.Redirect(w, r, handoff.StartPath+"?return_to="+url.QueryEscape(r.URL.RequestURI()), http.StatusSeeOther)
+ return
+ }
+ a.notFound(w, r)
+ return
+ }
+ if c, err := r.Cookie(a.sess.CookieName()); err == nil {
+ expired, err := a.cfg.Store.Seen(r.Context(), sessions.HashToken(c.Value), IdleLifetime)
+ if err != nil {
+ a.plain(w, http.StatusServiceUnavailable, "Try again.")
+ return
+ }
+ if expired {
+ a.sess.SignOut(w, r)
+ http.Redirect(w, r, handoff.StartPath+"?return_to="+url.QueryEscape(returnPath(r)), http.StatusSeeOther)
+ return
+ }
+ }
+ if s.Subject != a.cfg.OperatorSubject {
+ a.notFound(w, r)
+ return
+ }
+ w.Header().Set("Cache-Control", "no-store")
+ next.ServeHTTP(w, r)
+ })
+}
+
+func returnPath(r *http.Request) string {
+ if r.Method == http.MethodGet {
+ return r.URL.RequestURI()
+ }
+ return "/"
+}
+
+func (a *App) signout(w http.ResponseWriter, r *http.Request) {
+ a.sess.SignOut(w, r)
+ a.render(w, r, http.StatusOK, "signedout", page{Title: "Signed out", Bare: true})
+}
+
+// ---- background advancing ----
+
+// kick advances run in the background, once at a time per run.
+func (a *App) kick(id int64) {
+ a.mu.Lock()
+ if a.running[id] {
+ a.mu.Unlock()
+ return
+ }
+ a.running[id] = true
+ a.mu.Unlock()
+ go func() {
+ defer func() {
+ a.mu.Lock()
+ delete(a.running, id)
+ a.mu.Unlock()
+ }()
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ defer cancel()
+ _ = a.cfg.Engine.Advance(ctx, id)
+ }()
+}
+
+func (a *App) tick(every time.Duration) {
+ t := time.NewTicker(every)
+ defer t.Stop()
+ for {
+ select {
+ case <-a.done:
+ return
+ case <-t.C:
+ runs, err := a.cfg.Store.LiveRuns(context.Background())
+ if err != nil {
+ continue
+ }
+ for _, r := range runs {
+ a.kick(r.ID)
+ }
+ a.cfg.Store.SweepSeen(context.Background(), AbsoluteLifetime)
+ }
+ }
+}
+
+// ---- forms ----
+
+func errorCode(err error) string {
+ var fl *provision.Fail
+ var pk *provision.Park
+ switch {
+ case errors.As(err, &fl):
+ return fl.Code
+ case errors.As(err, &pk):
+ return pk.Code
+ }
+ return "transient"
+}
+
+func (a *App) index(w http.ResponseWriter, r *http.Request) {
+ ctx := r.Context()
+ teams, err := a.cfg.Store.Teams(ctx)
+ if err != nil {
+ a.plain(w, http.StatusServiceUnavailable, "Try again.")
+ return
+ }
+ var rows []teamRow
+ for _, t := range teams {
+ rows = append(rows, a.teamRow(ctx, t))
+ }
+ _, initialized, _ := a.cfg.Store.Done(ctx, "", "", "initialize")
+ inits, _ := a.cfg.Store.Runs(ctx, "")
+ a.render(w, r, http.StatusOK, "index", page{Title: "Teams", Data: map[string]any{"Teams": rows, "Initialized": initialized, "InitRuns": inits}})
+}
+
+type teamRow struct {
+ Label, Name string
+ Apps, Live int
+ Pending int
+ Retired int
+ RunID int64
+ RunState string
+ RunWords string
+}
+
+func (a *App) teamRow(ctx context.Context, t provision.Team) teamRow {
+ row := teamRow{Label: t.Label, Name: t.Name}
+ for app, st := range t.Apps {
+ if st == "retired" {
+ row.Retired++
+ continue
+ }
+ row.Apps++
+ if _, ok, _ := a.cfg.Store.Done(ctx, t.Label, app, provision.StepAudit); ok {
+ if spec, _ := provision.AppBySlug(app); spec.Roster {
+ row.Live++
+ continue
+ }
+ }
+ row.Pending++
+ }
+ if runs, _ := a.cfg.Store.Runs(ctx, t.Label); len(runs) > 0 {
+ row.RunID, row.RunState, row.RunWords = runs[0].ID, runs[0].State, describe(runs[0].Code)
+ }
+ return row
+}
+
+func (a *App) newTeamForm(w http.ResponseWriter, r *http.Request) {
+ a.render(w, r, http.StatusOK, "team_new", page{Title: "New team", Data: map[string]any{"Apps": provision.Apps, "Checked": map[string]bool{}, "Form": map[string]string{}}})
+}
+
+func (a *App) createTeam(w http.ResponseWriter, r *http.Request) {
+ if err := r.ParseForm(); err != nil {
+ a.plain(w, http.StatusBadRequest, "Bad form.")
+ return
+ }
+ in := provision.NewTeam{Label: strings.TrimSpace(r.PostForm.Get("label")), Name: strings.TrimSpace(r.PostForm.Get("name")), Owner: strings.TrimSpace(r.PostForm.Get("owner")), Apps: r.PostForm["app"], Forked: r.PostForm.Get("forked") == "1"}
+ if addr, err := mail.ParseAddress(in.Owner); err == nil && addr.Name == "" {
+ in.Owner = addr.Address
+ }
+ id, err := a.cfg.Engine.CreateTeam(r.Context(), in)
+ if err != nil {
+ checked := map[string]bool{}
+ for _, s := range in.Apps {
+ checked[s] = true
+ }
+ // The owner's address is echoed back into the form it came from,
+ // never logged or stored on a refusal.
+ a.render(w, r, http.StatusUnprocessableEntity, "team_new", page{Title: "New team", Error: describe(errorCode(err)),
+ Data: map[string]any{"Apps": provision.Apps, "Checked": checked, "Form": map[string]string{"label": in.Label, "name": in.Name, "owner": in.Owner}, "Forked": in.Forked}})
+ return
+ }
+ http.Redirect(w, r, "/runs/"+strconv.FormatInt(id, 10), http.StatusSeeOther)
+}
+
+func (a *App) initializeForm(w http.ResponseWriter, r *http.Request) {
+ a.render(w, r, http.StatusOK, "initialize", page{Title: "Initialize Home's directory", Data: map[string]any{"Sentence": provision.InitializeAttestation}})
+}
+
+func (a *App) initialize(w http.ResponseWriter, r *http.Request) {
+ _ = r.ParseForm()
+ id, err := a.cfg.Engine.StartInitialize(r.Context(), r.PostForm.Get("attestation"))
+ if err != nil {
+ a.render(w, r, http.StatusUnprocessableEntity, "initialize", page{Title: "Initialize Home's directory", Error: describe(errorCode(err)), Data: map[string]any{"Sentence": provision.InitializeAttestation}})
+ return
+ }
+ http.Redirect(w, r, "/runs/"+strconv.FormatInt(id, 10), http.StatusSeeOther)
+}
+
+func (a *App) teamFor(w http.ResponseWriter, r *http.Request) (provision.Team, bool) {
+ t, err := a.cfg.Store.Team(r.Context(), chi.URLParam(r, "label"))
+ if err != nil {
+ a.notFound(w, r)
+ return t, false
+ }
+ return t, true
+}
+
+// appView is one app's row on the team and run pages.
+type appView struct {
+ Slug, Name, Host, State string
+ Steps []stepView
+ Pending bool
+}
+
+type stepView struct {
+ Name, State, Words string
+}
+
+func (a *App) appViews(ctx context.Context, t provision.Team, apps []string) []appView {
+ steps, _ := a.cfg.Store.Steps(ctx, t.Label)
+ by := map[string]provision.Step{}
+ for _, s := range steps {
+ by[s.App+"/"+s.Name] = s
+ }
+ var out []appView
+ for _, slug := range provision.SortApps(apps) {
+ spec, _ := provision.AppBySlug(slug)
+ v := appView{Slug: slug, Name: spec.Name, Host: provision.PublicHost(t.Label, slug), State: t.Apps[slug], Pending: !spec.Roster}
+ names := provision.AppSteps(spec)
+ if t.Apps[slug] == "retired" {
+ names = provision.RetireSteps
+ }
+ for _, n := range names {
+ s, ok := by[slug+"/"+n]
+ sv := stepView{Name: n, State: "todo"}
+ if ok {
+ sv.State, sv.Words = s.State, describe(s.Code)
+ }
+ v.Steps = append(v.Steps, sv)
+ }
+ out = append(out, v)
+ }
+ return out
+}
+
+func (a *App) team(w http.ResponseWriter, r *http.Request) {
+ t, ok := a.teamFor(w, r)
+ if !ok {
+ return
+ }
+ ctx := r.Context()
+ var apps, addable []string
+ for _, s := range provision.Slugs() {
+ if _, in := t.Apps[s]; in {
+ apps = append(apps, s)
+ } else {
+ addable = append(addable, s)
+ }
+ }
+ runs, _ := a.cfg.Store.Runs(ctx, t.Label)
+ audit, _ := a.cfg.Store.AuditLog(ctx, t.Label, 40)
+ _, holdsOwner, _ := a.cfg.Store.Owner(ctx, t.Label)
+ a.render(w, r, http.StatusOK, "team", page{Title: t.Name, Context: t.Label, Notice: describe(r.URL.Query().Get("audit")),
+ Data: map[string]any{"Team": t, "Apps": a.appViews(ctx, t, apps), "Addable": addable, "Runs": runs, "Audit": audit, "HoldsOwner": holdsOwner, "Seeded": t.TeamSQID != ""}})
+}
+
+func (a *App) addApps(w http.ResponseWriter, r *http.Request) {
+ t, ok := a.teamFor(w, r)
+ if !ok {
+ return
+ }
+ _ = r.ParseForm()
+ apps := r.PostForm["app"]
+ if len(apps) == 0 {
+ // "Continue": every active app, under a new plan.
+ for app, st := range t.Apps {
+ if st == "active" {
+ apps = append(apps, app)
+ }
+ }
+ }
+ id, err := a.cfg.Engine.AddApps(r.Context(), t.Label, apps)
+ if err != nil {
+ http.Redirect(w, r, "/teams/"+t.Label+"?audit="+url.QueryEscape(errorCode(err)), http.StatusSeeOther)
+ return
+ }
+ http.Redirect(w, r, "/runs/"+strconv.FormatInt(id, 10), http.StatusSeeOther)
+}
+
+func (a *App) retypeOwner(w http.ResponseWriter, r *http.Request) {
+ t, ok := a.teamFor(w, r)
+ if !ok {
+ return
+ }
+ _ = r.ParseForm()
+ addr := strings.TrimSpace(r.PostForm.Get("owner"))
+ if !homeop.OwnerAddress(addr) {
+ http.Redirect(w, r, "/teams/"+t.Label+"?audit=owner-shape", http.StatusSeeOther)
+ return
+ }
+ if err := a.cfg.Store.SetOwner(r.Context(), t.Label, addr); err != nil {
+ a.plain(w, http.StatusServiceUnavailable, "Try again.")
+ return
+ }
+ a.cfg.Store.Audit(r.Context(), 0, t.Label, "", "owner-retyped", "")
+ http.Redirect(w, r, "/teams/"+t.Label, http.StatusSeeOther)
+}
+
+func (a *App) audit(w http.ResponseWriter, r *http.Request) {
+ t, ok := a.teamFor(w, r)
+ if !ok {
+ return
+ }
+ code := "audit-ok"
+ for app, st := range t.Apps {
+ if st != "active" {
+ continue
+ }
+ spec, _ := provision.AppBySlug(app)
+ if err := a.cfg.Engine.AuditEnvironment(r.Context(), t.Label, spec); err != nil {
+ code = errorCode(err) + "-" + app
+ break
+ }
+ }
+ a.cfg.Store.Audit(r.Context(), 0, t.Label, "", "audit", code)
+ http.Redirect(w, r, "/teams/"+t.Label+"?audit="+url.QueryEscape(code), http.StatusSeeOther)
+}
+
+func (a *App) retireForm(w http.ResponseWriter, r *http.Request) {
+ t, ok := a.teamFor(w, r)
+ if !ok {
+ return
+ }
+ var active []string
+ for _, s := range provision.Slugs() {
+ if t.Apps[s] == "active" {
+ active = append(active, s)
+ }
+ }
+ a.render(w, r, http.StatusOK, "retire", page{Title: "Retire apps", Context: t.Label, Data: map[string]any{"Team": t, "Apps": a.appViews(r.Context(), t, active)}})
+}
+
+func (a *App) retire(w http.ResponseWriter, r *http.Request) {
+ t, ok := a.teamFor(w, r)
+ if !ok {
+ return
+ }
+ _ = r.ParseForm()
+ id, err := a.cfg.Engine.RetireApps(r.Context(), t.Label, r.PostForm["app"], strings.TrimSpace(r.PostForm.Get("label")))
+ if err != nil {
+ var active []string
+ for _, s := range provision.Slugs() {
+ if t.Apps[s] == "active" {
+ active = append(active, s)
+ }
+ }
+ a.render(w, r, http.StatusUnprocessableEntity, "retire", page{Title: "Retire apps", Context: t.Label, Error: describe(errorCode(err)), Data: map[string]any{"Team": t, "Apps": a.appViews(r.Context(), t, active)}})
+ return
+ }
+ http.Redirect(w, r, "/runs/"+strconv.FormatInt(id, 10), http.StatusSeeOther)
+}
+
+func (a *App) runFor(w http.ResponseWriter, r *http.Request) (provision.Run, bool) {
+ id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
+ if err != nil {
+ a.notFound(w, r)
+ return provision.Run{}, false
+ }
+ run, err := a.cfg.Store.Run(r.Context(), id)
+ if err != nil {
+ a.notFound(w, r)
+ return provision.Run{}, false
+ }
+ return run, true
+}
+
+// roleView is one role's line in the plan section.
+type roleView struct {
+ Role, Confirm, Words, State string
+ Until time.Time
+}
+
+func (a *App) run(w http.ResponseWriter, r *http.Request) {
+ run, ok := a.runFor(w, r)
+ if !ok {
+ return
+ }
+ ctx := r.Context()
+ plans, _ := a.cfg.Store.Plans(ctx, run.PlanID)
+ var roles []roleView
+ for _, role := range []string{homeop.Directory, homeop.Credential} {
+ p, ok := plans[role]
+ if !ok {
+ continue
+ }
+ v := roleView{Role: role, State: p.State}
+ switch role {
+ case homeop.Directory:
+ v.Confirm, v.Words = a.cfg.HomeDirectory+"/operator/confirm", "Check the label, name and apps"
+ case homeop.Credential:
+ v.Confirm, v.Words = a.cfg.HomeCredential+"/operator/confirm", "Retype the owner's address"
+ if run.Kind != homeop.KindCreateTeam {
+ v.Words = "Check the apps"
+ }
+ }
+ if p.Window > 0 {
+ v.Until = time.Unix(p.Window, 0)
+ }
+ roles = append(roles, v)
+ }
+ data := map[string]any{"Run": run, "Roles": roles, "Prefix": homeop.PlanPrefix(run.PlanID), "Words": describe(run.Code),
+ "PlanExpires": time.Unix(run.PlanExpires, 0), "Live": run.State == "planned" || run.State == "running" || run.State == "parked"}
+ title := "Initialize"
+ if run.Label != "" {
+ t, err := a.cfg.Store.Team(ctx, run.Label)
+ if err == nil {
+ data["Team"] = t
+ data["Apps"] = a.appViews(ctx, t, run.Apps)
+ title = t.Name
+ }
+ }
+ a.render(w, r, http.StatusOK, "run", page{Title: title, Context: run.Label, Data: data})
+}
+
+func (a *App) advance(w http.ResponseWriter, r *http.Request) {
+ run, ok := a.runFor(w, r)
+ if !ok {
+ return
+ }
+ a.kick(run.ID)
+ http.Redirect(w, r, "/runs/"+strconv.FormatInt(run.ID, 10), http.StatusSeeOther)
+}
+
+func (a *App) resubmit(w http.ResponseWriter, r *http.Request) {
+ run, ok := a.runFor(w, r)
+ if !ok {
+ return
+ }
+ if err := a.cfg.Engine.Resubmit(r.Context(), run.ID); err != nil {
+ var fl *provision.Fail
+ if errors.As(err, &fl) && fl.Code == "use-add-apps" && run.Label != "" {
+ http.Redirect(w, r, "/teams/"+run.Label, http.StatusSeeOther)
+ return
+ }
+ }
+ http.Redirect(w, r, "/runs/"+strconv.FormatInt(run.ID, 10), http.StatusSeeOther)
+}
diff --git a/internal/web/render.go b/internal/web/render.go
new file mode 100644
index 0000000..3fe5465
--- /dev/null
+++ b/internal/web/render.go
@@ -0,0 +1,143 @@
+package web
+
+import (
+ "bytes"
+ "embed"
+ "html/template"
+ "io/fs"
+ "net/http"
+ "testing/fstest"
+ "time"
+
+ "amadan.net/oficina/estilo.git/base"
+ "amadan.net/oficina/estilo.git/brand"
+ "amadan.net/oficina/estilo.git/busy"
+ "amadan.net/oficina/estilo.git/chrome"
+ estilomenu "amadan.net/oficina/estilo.git/menu"
+ "amadan.net/oficina/estilo.git/theme"
+ "amadan.net/rastrillo/rastrillo"
+ "amadan.net/rastrillo/rastrillo/sessions"
+ "amadan.net/rastrillo/rastrillo/ui"
+)
+
+//go:embed templates static
+var appFS embed.FS
+
+const assetPrefix = "/static/"
+
+// The stylesheets in the suite's order: rastrillo's tokens, estilo's
+// theme (Calma), then estilo's base, menu and chrome, then Alta's own.
+// The brand mark is estilo's Oficina mark: Alta is not an app in the
+// switcher and has no mark of its own.
+var assets = rastrillo.NewAssets(func() fs.FS {
+ files := fstest.MapFS{
+ "static/tokens.css": {Data: ui.TokensCSS()},
+ "static/theme.css": {Data: theme.CSS()},
+ "static/estilo/base.css": {Data: base.CSS()},
+ "static/estilo/menu.css": {Data: estilomenu.CSS()},
+ "static/estilo/chrome.css": {Data: chrome.CSS()},
+ "static/oficina.svg": {Data: brand.SVG("oficina")},
+ }
+ b, err := appFS.ReadFile("static/alta.css")
+ if err != nil {
+ panic(err)
+ }
+ files["static/alta.css"] = &fstest.MapFile{Data: b}
+ return files
+}())
+
+func assetHandler() http.Handler {
+ busyH, files := busy.Handler(), assets.Handler()
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if len(r.URL.Path) > len(busy.Prefix) && r.URL.Path[:len(busy.Prefix)] == busy.Prefix {
+ busyH.ServeHTTP(w, r)
+ return
+ }
+ files.ServeHTTP(w, r)
+ })
+}
+
+var pageNames = []string{"index", "team_new", "team", "run", "retire", "initialize", "notfound", "signedout"}
+
+var pages = map[string]*template.Template{}
+
+func init() {
+ for _, name := range pageNames {
+ t := template.New("layout").Funcs(ui.Funcs()).Funcs(template.FuncMap{
+ "asset": assets.Path,
+ "busyJS": func() string { return busy.Prefix + "busy.js" },
+ "busyCSS": func() string { return busy.Prefix + "busy.css" },
+ "when": func(t time.Time) string { return t.UTC().Format("2 Jan 15:04 UTC") },
+ "unix": func(n int64) string { return time.Unix(n, 0).UTC().Format("2 Jan 15:04 UTC") },
+ "describe": describe,
+ })
+ t = template.Must(t.ParseFS(ui.Templates(), "*.html"))
+ t = template.Must(t.ParseFS(chrome.Templates(), "templates/*.html"))
+ t = template.Must(t.ParseFS(estilomenu.Templates(), "templates/*.html"))
+ pages[name] = template.Must(t.ParseFS(appFS, "templates/layout.html", "templates/"+name+".html"))
+ }
+}
+
+// page is every template's data.
+type page struct {
+ Title, Context string
+ Error, Notice string
+ Bare bool
+ Data map[string]any
+ Frame frame
+}
+
+type frame struct {
+ Chrome chrome.Bar
+ Theme string
+}
+
+func (a *App) frame(r *http.Request, p page) frame {
+ bar := chrome.Bar{
+ App: chrome.App{Name: "Alta", Slug: "alta", Home: "/", Icon: assets.Path("static/oficina.svg")},
+ Context: p.Context,
+ Labels: chrome.BarLabels{Skip: "Skip to content", Menu: "Menu"},
+ }
+ if s, ok := sessions.Current(r); ok && s.Subject == a.cfg.OperatorSubject && !p.Bare {
+ bar.Nav = []chrome.Link{{Href: "/", Label: "Teams", Current: r.URL.Path == "/"}, {Href: "/teams/new", Label: "New team", Current: r.URL.Path == "/teams/new"}}
+ bar.NavLabel = "Alta"
+ bar.Account = &chrome.Account{
+ TriggerLabel: "Account",
+ Initials: "P",
+ Address: "Paul",
+ Labels: chrome.AccountLabels{SignedInAs: "Signed in as", Appearance: "Appearance", Help: "Help"},
+ SignOut: chrome.SignOut{Action: "/signout", Label: "Sign out"},
+ }
+ } else {
+ bar.App.Home = ""
+ }
+ return frame{Chrome: bar, Theme: chrome.ThemeAttr(chrome.Appearance(r))}
+}
+
+func (a *App) render(w http.ResponseWriter, r *http.Request, status int, name string, p page) {
+ p.Frame = a.frame(r, p)
+ if p.Data == nil {
+ p.Data = map[string]any{}
+ }
+ var buf bytes.Buffer
+ if err := pages[name].ExecuteTemplate(&buf, "layout", p); err != nil {
+ a.cfg.Logger.Error("alta render", "page", name, "err", err)
+ a.plain(w, http.StatusInternalServerError, "Something went wrong.")
+ return
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.Header().Set("Cache-Control", "no-store")
+ w.WriteHeader(status)
+ _, _ = buf.WriteTo(w)
+}
+
+func (a *App) notFound(w http.ResponseWriter, r *http.Request) {
+ a.render(w, r, http.StatusNotFound, "notfound", page{Title: "Not found", Bare: true})
+}
+
+func (a *App) plain(w http.ResponseWriter, status int, msg string) {
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+ w.Header().Set("Cache-Control", "no-store")
+ w.WriteHeader(status)
+ _, _ = w.Write([]byte(msg + "\n"))
+}
diff --git a/internal/web/static/alta.css b/internal/web/static/alta.css
new file mode 100644
index 0000000..6c20745
--- /dev/null
+++ b/internal/web/static/alta.css
@@ -0,0 +1,21 @@
+/* alta.css: Alta's own rules under estilo's bar (chrome.css is estilo's). */
+body { background: var(--rst-bg); }
+[rst-page] { max-inline-size: 72rem; margin-inline: auto; }
+section { margin-block: var(--rst-sp-5); }
+.alta-box { border: 1px solid var(--rst-border); border-radius: var(--rst-radius, 8px); padding: var(--rst-sp-4); }
+.alta-quiet { color: var(--rst-text-muted); }
+.alta-label { font-family: var(--rst-font-mono, ui-monospace, monospace); }
+.alta-sentence { font-weight: 600; }
+.alta-apps { display: flex; flex-wrap: wrap; gap: var(--rst-sp-3); border: 0; padding: 0; }
+.alta-apps legend { font-weight: 600; margin-block-end: var(--rst-sp-2); }
+.alta-check { display: block; margin-block: var(--rst-sp-3); }
+.alta-actions { display: flex; flex-wrap: wrap; gap: var(--rst-sp-2); align-items: center; }
+.alta-grid { inline-size: 100%; border-collapse: collapse; }
+.alta-grid th, .alta-grid td { text-align: start; vertical-align: top; padding: var(--rst-sp-2); border-block-end: 1px solid var(--rst-border); }
+.alta-steps { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: var(--rst-sp-1) var(--rst-sp-3); }
+.alta-step[data-state="todo"] { color: var(--rst-text-muted); }
+.alta-step[data-state="failed"] { color: var(--rst-negative, #b42318); font-weight: 600; }
+.alta-step small { display: block; color: var(--rst-text-muted); }
+.alta-roles li { margin-block: var(--rst-sp-2); }
+.alta-roles a, .alta-grid small { overflow-wrap: anywhere; }
+.alta-audit { list-style: none; padding: 0; font-size: var(--rst-fs-sm); }
diff --git a/internal/web/templates/index.html b/internal/web/templates/index.html
new file mode 100644
index 0000000..74ec6db
--- /dev/null
+++ b/internal/web/templates/index.html
@@ -0,0 +1,23 @@
+{{define "content"}}
+{{template "page-header" dict "Title" "Teams" "ActionHref" "/teams/new" "ActionLabel" "New team"}}
+{{if not .Data.Initialized}}
+<section class="alta-box">
+ <h2>Home's directory</h2>
+ <p>Alta's first production run initializes Home's directory, after your pre-flight confirmation (amendment §12). No team can be created before it.</p>
+ <p><a rst-btn href="/initialize">Initialize…</a></p>
+ {{range .Data.InitRuns}}<p class="alta-quiet"><a href="/runs/{{.ID}}">Initialize run {{.ID}}</a> · {{.State}}{{with .Code}} · {{describe .}}{{end}}</p>{{end}}
+</section>
+{{end}}
+{{if .Data.Teams}}
+<div rst-list>
+{{range .Data.Teams}}
+<div rst-row>
+ <span rst-row-main><a href="/teams/{{.Label}}"><span class="alta-label">{{.Label}}</span> {{.Name}}</a>
+ <small rst-row-sub>{{.Apps}} apps · live {{.Live}} · pending {{.Pending}}{{if .Retired}} · retired {{.Retired}}{{end}}{{if .RunID}} · <a href="/runs/{{.RunID}}">last run {{.RunState}}</a>{{with .RunWords}}: {{.}}{{end}}{{end}}</small></span>
+</div>
+{{end}}
+</div>
+{{else}}
+{{template "empty-state" dict "Body" "No teams yet. A team is one instance of each app at <label>.<app>.oficina.works, registered with Home, with its first owner." "ActionHref" "/teams/new" "ActionLabel" "New team"}}
+{{end}}
+{{end}}
diff --git a/internal/web/templates/initialize.html b/internal/web/templates/initialize.html
new file mode 100644
index 0000000..06271cf
--- /dev/null
+++ b/internal/web/templates/initialize.html
@@ -0,0 +1,9 @@
+{{define "content"}}
+{{template "page-header" dict "Title" "Initialize Home's directory" "Sub" "Once, before the first team. Then confirm on oficina.works/operator/confirm."}}
+<form rst-form method="post" action="/initialize">
+ <p>The production directory had no teams, memberships, team instances, roster generation, consumers, tokens or operator rows on 2026-10-27 (amendment §12). Home cannot prove that it has never issued a roster generation or consumer record. Only you can: type the sentence below to say so. Alta then signs Home's baseline attestation.</p>
+ <p class="alta-sentence">{{.Data.Sentence}}</p>
+ {{template "field" dict "ID" "attestation" "Name" "attestation" "Label" "Type the sentence" "Required" true "Autocomplete" "off"}}
+ <div rst-form-foot><button type="submit" rst-btn="primary">Submit the initialize plan</button></div>
+</form>
+{{end}}
diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html
new file mode 100644
index 0000000..c5c3bc5
--- /dev/null
+++ b/internal/web/templates/layout.html
@@ -0,0 +1,33 @@
+{{define "layout"}}<!doctype html>
+{{/* layout — every page: estilo's bar and <main>. data-theme comes from
+ the Appearance cookie, read server-side, so nothing flashes. The
+ only script is estilo's busy.js (the 650 ms submit rule). */}}
+<html lang="en" dir="ltr"{{with .Frame.Theme}} data-theme="{{.}}"{{end}}>
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<meta name="robots" content="noindex, nofollow">
+<title>{{with .Title}}{{.}} · {{end}}Alta</title>
+<link rel="icon" type="image/svg+xml" href="{{asset "static/oficina.svg"}}">
+<link rel="stylesheet" href="{{asset "static/tokens.css"}}">
+<link rel="stylesheet" href="{{busyCSS}}">
+<link rel="stylesheet" href="{{asset "static/theme.css"}}">
+<link rel="stylesheet" href="{{asset "static/estilo/base.css"}}">
+<link rel="stylesheet" href="{{asset "static/estilo/menu.css"}}">
+<link rel="stylesheet" href="{{asset "static/estilo/chrome.css"}}">
+<link rel="stylesheet" href="{{asset "static/alta.css"}}">
+<script defer src="{{busyJS}}"></script>
+</head>
+<body>
+<div estilo-shell>
+<a rst-skip href="#main">{{.Frame.Chrome.Labels.Skip}}</a>
+{{template "estilo-bar" .Frame.Chrome}}
+<main rst-page id="main">
+{{with .Error}}<p rst-callout="negative" role="alert">{{.}}</p>{{end}}
+{{with .Notice}}<p rst-callout role="status">{{.}}</p>{{end}}
+{{template "content" .}}
+</main>
+</div>
+</body>
+</html>
+{{end}}
diff --git a/internal/web/templates/notfound.html b/internal/web/templates/notfound.html
new file mode 100644
index 0000000..4bcc44e
--- /dev/null
+++ b/internal/web/templates/notfound.html
@@ -0,0 +1,4 @@
+{{define "content"}}
+{{template "page-header" dict "Title" "Not found"}}
+<p>There is nothing here.</p>
+{{end}}
diff --git a/internal/web/templates/retire.html b/internal/web/templates/retire.html
new file mode 100644
index 0000000..04b880e
--- /dev/null
+++ b/internal/web/templates/retire.html
@@ -0,0 +1,13 @@
+{{define "content"}}
+{{$t := .Data.Team}}
+{{template "page-header" dict "Title" (printf "Retire apps from %s" $t.Name) "Sub" "Disable at the directory, retire at the credential origin, detach the hostname, delete the instance."}}
+<form rst-form method="post" action="/teams/{{$t.Label}}/retire">
+ <fieldset class="alta-apps"><legend>Apps to retire</legend>
+ {{range .Data.Apps}}<label><input type="checkbox" name="app" value="{{.Slug}}"> {{.Name}} — {{.Host}}</label>{{end}}
+ </fieldset>
+ <p><strong>What survives:</strong> each instance's parked database replica (only a CARLOS operator purges it, and the host cannot be re-created until then), the owned environment (there is no delete verb), and the Home team, its roster and label.</p>
+ <p><strong>Never again:</strong> the label and every retired hostname are never reused; a retired app cannot be re-added to this team.</p>
+ {{template "field" dict "ID" "label" "Name" "label" "Label" (printf "Type %s to confirm" $t.Label) "Required" true "Autocomplete" "off"}}
+ <div rst-form-foot><button type="submit" rst-btn="danger">Submit the retire plan to Home</button> <a rst-btn href="/teams/{{$t.Label}}">Cancel</a></div>
+</form>
+{{end}}
diff --git a/internal/web/templates/run.html b/internal/web/templates/run.html
new file mode 100644
index 0000000..c740c7d
--- /dev/null
+++ b/internal/web/templates/run.html
@@ -0,0 +1,41 @@
+{{define "content"}}
+{{$run := .Data.Run}}
+{{template "page-header" dict "Title" (printf "Run %d · %s" $run.ID $run.Kind) "Sub" (printf "%s%s" $run.State (or (and .Data.Words (printf " · %s" .Data.Words)) ""))}}
+{{if .Data.Roles}}
+<section class="alta-box">
+ <h2>Plan {{.Data.Prefix}} — confirm on Home</h2>
+ <p>Open each page in order, sign in afresh, and check that both show plan <strong class="alta-label">{{.Data.Prefix}}</strong>. Home shows its own copy of the plan; confirm only what Home shows.</p>
+ <ol class="alta-roles">
+ {{range .Data.Roles}}
+ <li><a href="{{.Confirm}}" rel="noreferrer">{{.Confirm}}</a> — {{.Words}}
+ {{if eq .State "open"}}{{template "status-pill" dict "Label" (printf "open until %s" (when .Until)) "Tone" "positive"}}{{else if eq .State "pending"}}{{template "status-pill" dict "Label" "waiting" "Tone" "warning"}}{{else if eq .State "closed"}}{{template "status-pill" dict "Label" "closed"}}{{else}}{{template "status-pill" dict "Label" "not yet with Home" "Tone" "warning"}}{{end}}</li>
+ {{end}}
+ </ol>
+ <p class="alta-quiet">The plan expires {{when .Data.PlanExpires}} unless confirmed; a window lasts 15 minutes and is never extended.</p>
+</section>
+{{end}}
+{{with .Data.Apps}}
+<section>
+ <h2>Apps</h2>
+ <table class="alta-grid">
+ <thead><tr><th scope="col">App</th><th scope="col">Steps</th></tr></thead>
+ <tbody>
+ {{range .}}
+ <tr><th scope="row">{{.Name}}<br><small class="alta-quiet">{{.Host}}</small></th>
+ <td><ul class="alta-steps">{{range .Steps}}<li class="alta-step" data-state="{{.State}}"><span>{{if eq .State "done"}}✓{{else if eq .State "parked"}}◷{{else if eq .State "failed"}}✕{{else}}·{{end}} {{.Name}}</span>{{with .Words}} <small>{{.}}</small>{{end}}</li>{{end}}</ul>
+ {{if .Pending}}<small class="alta-quiet">No roster mode yet: stays pending in Home's chooser.</small>{{end}}</td></tr>
+ {{end}}
+ </tbody>
+ </table>
+</section>
+{{end}}
+<section class="alta-actions">
+ {{if .Data.Live}}
+ <form method="post" action="/runs/{{$run.ID}}/advance"><button type="submit" rst-btn="primary">Resume</button></form>
+ {{if or (eq $run.Code "plan-expired") (eq $run.Code "plan-refused-credential")}}<form method="post" action="/runs/{{$run.ID}}/plan"><button type="submit" rst-btn>Submit a new plan</button></form>{{end}}
+ {{if and .Data.Team (or (eq $run.Code "window-expired") (eq $run.Code "window-closed"))}}<form method="post" action="/teams/{{$run.Label}}/apps"><button type="submit" rst-btn>Continue under a new plan</button></form>{{end}}
+ {{end}}
+ {{with .Data.Team}}<a rst-btn href="/teams/{{.Label}}">Team</a>{{end}}
+ <p class="alta-quiet">Refresh to see progress.</p>
+</section>
+{{end}}
diff --git a/internal/web/templates/signedout.html b/internal/web/templates/signedout.html
new file mode 100644
index 0000000..f78a76a
--- /dev/null
+++ b/internal/web/templates/signedout.html
@@ -0,0 +1,4 @@
+{{define "content"}}
+{{template "page-header" dict "Title" "You’re signed out"}}
+<p><a rst-btn href="/">Sign in</a></p>
+{{end}}
diff --git a/internal/web/templates/team.html b/internal/web/templates/team.html
new file mode 100644
index 0000000..3439004
--- /dev/null
+++ b/internal/web/templates/team.html
@@ -0,0 +1,48 @@
+{{define "content"}}
+{{$t := .Data.Team}}
+{{template "page-header" dict "Title" $t.Name "Sub" (printf "%s · environment %s%s" $t.Label $t.Environment (or (and $t.TeamSQID (printf " · Home team %s" $t.TeamSQID)) " · not yet at Home"))}}
+<section>
+ <h2>Apps</h2>
+ <table class="alta-grid">
+ <thead><tr><th scope="col">App</th><th scope="col">Steps</th></tr></thead>
+ <tbody>
+ {{range .Data.Apps}}
+ <tr><th scope="row">{{.Name}}{{if eq .State "retired"}} (retired){{end}}<br><small class="alta-quiet">{{.Host}}</small></th>
+ <td><ul class="alta-steps">{{range .Steps}}<li class="alta-step" data-state="{{.State}}"><span>{{if eq .State "done"}}✓{{else if eq .State "parked"}}◷{{else if eq .State "failed"}}✕{{else}}·{{end}} {{.Name}}</span>{{with .Words}} <small>{{.}}</small>{{end}}</li>{{end}}</ul></td></tr>
+ {{end}}
+ </tbody>
+ </table>
+</section>
+<section class="alta-actions">
+ <form method="post" action="/teams/{{$t.Label}}/apps"><button type="submit" rst-btn="primary">Continue under a new plan</button></form>
+ <form method="post" action="/teams/{{$t.Label}}/audit"><button type="submit" rst-btn>Audit</button></form>
+ {{if .Data.Seeded}}<a rst-btn="danger" href="/teams/{{$t.Label}}/retire">Retire apps…</a>{{end}}
+</section>
+{{if and .Data.Seeded .Data.Addable}}
+<section class="alta-box">
+ <h2>Add apps</h2>
+ <form method="post" action="/teams/{{$t.Label}}/apps">
+ <fieldset class="alta-apps"><legend>Apps</legend>{{range .Data.Addable}}<label><input type="checkbox" name="app" value="{{.}}"> {{.}}</label>{{end}}</fieldset>
+ <button type="submit" rst-btn>Submit plan to Home</button>
+ </form>
+</section>
+{{end}}
+{{if not .Data.HoldsOwner}}
+<section class="alta-box">
+ <h2>Owner's address</h2>
+ <p>Alta deleted the owner's address once every allowlist was written. An app that needs it again (a stopgap allowlist edit) asks for it here; Alta deletes it again once written.</p>
+ <form method="post" action="/teams/{{$t.Label}}/owner">
+ {{template "field" dict "ID" "owner" "Name" "owner" "Label" "Owner email" "Type" "email" "Required" true "Autocomplete" "off"}}
+ <button type="submit" rst-btn>Hold it until written</button>
+ </form>
+</section>
+{{end}}
+<section>
+ <h2>Runs</h2>
+ {{if .Data.Runs}}<ul>{{range .Data.Runs}}<li><a href="/runs/{{.ID}}">Run {{.ID}}</a> · {{.Kind}} · {{.State}}{{with .Code}} · {{describe .}}{{end}}</li>{{end}}</ul>{{else}}<p>None.</p>{{end}}
+</section>
+<section>
+ <h2>Audit</h2>
+ {{if .Data.Audit}}<ul class="alta-audit">{{range .Data.Audit}}<li><time>{{when .At}}</time> {{.Event}}{{with .App}} · {{.}}{{end}}{{with .Detail}} · {{.}}{{end}}</li>{{end}}</ul>{{else}}<p>Nothing yet.</p>{{end}}
+</section>
+{{end}}
diff --git a/internal/web/templates/team_new.html b/internal/web/templates/team_new.html
new file mode 100644
index 0000000..c88eeb2
--- /dev/null
+++ b/internal/web/templates/team_new.html
@@ -0,0 +1,14 @@
+{{define "content"}}
+{{template "page-header" dict "Title" "New team" "Sub" "Alta checks everything it can first, then submits a plan you confirm on Home."}}
+<form rst-form method="post" action="/teams">
+ {{template "field" dict "ID" "label" "Name" "label" "Label" "Label" "Value" (index .Data.Form "label") "Required" true "Autofocus" true "Autocomplete" "off" "Pattern" "[a-z][a-z0-9-]{1,30}[a-z0-9]" "Help" "Lower-case letters, digits and hyphens. The team's hosts are <label>.<app>.oficina.works. A label is never reused, even after its apps are retired."}}
+ {{template "field" dict "ID" "name" "Name" "name" "Label" "Name" "Value" (index .Data.Form "name") "Required" true "Help" "What the team is called in Home."}}
+ {{template "field" dict "ID" "owner" "Name" "owner" "Label" "Owner email" "Type" "email" "Value" (index .Data.Form "owner") "Required" true "Autocomplete" "off" "Help" "They must already have signed in at oficina.works once."}}
+ <fieldset class="alta-apps">
+ <legend>Apps</legend>
+ {{range .Data.Apps}}<label><input type="checkbox" name="app" value="{{.Slug}}"{{if or (index $.Data.Checked .Slug) (not $.Data.Checked)}} checked{{end}}> {{.Name}}</label>{{end}}
+ </fieldset>
+ <label class="alta-check"><input type="checkbox" name="forked" value="1"{{if .Data.Forked}} checked{{end}}> Moving a stopgap: use the environments you forked to <span class="alta-label">&lt;label&gt;-team</span></label>
+ <div rst-form-foot><button type="submit" rst-btn="primary">Submit plan to Home</button></div>
+</form>
+{{end}}
diff --git a/internal/web/web_test.go b/internal/web/web_test.go
new file mode 100644
index 0000000..6a19bea
--- /dev/null
+++ b/internal/web/web_test.go
@@ -0,0 +1,271 @@
+package web
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/alta/console"
+ "amadan.net/oficina/alta/console/fakeconsole"
+ "amadan.net/oficina/alta/homeop"
+ "amadan.net/oficina/alta/homeop/fakehome"
+ "amadan.net/oficina/alta/provision"
+ "amadan.net/oficina/home/connect"
+ "amadan.net/rastrillo/rastrillo/assertion"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+)
+
+const (
+ origin = "https://alta.example.test"
+ issuer = "https://id.oficina.works"
+ dirO = "https://oficina.works"
+ operator = "pr_" + "bbbbbbbbbbbbbbbbbbbbbbbbbb"
+ stranger = "pr_" + "cccccccccccccccccccccccccc"
+ owner = "owner-canary@lagged.test"
+)
+
+type fixture struct {
+ t *testing.T
+ now time.Time
+ app *App
+ signer *family.Keypair
+ home *fakehome.Home
+ engine *provision.Engine
+ store *provision.Store
+ jar map[string]*http.Cookie
+}
+
+func newFixture(t *testing.T) *fixture {
+ f := &fixture{t: t, now: time.Unix(2_000_000_000, 0), jar: map[string]*http.Cookie{}}
+ clock := func() time.Time { return f.now }
+ key, _ := family.Generate()
+ pre := homeop.Token()
+ f.home = fakehome.New(key.SignPub(), pre, issuer, dirO, clock)
+ f.home.AddPerson(owner)
+ dir := httptest.NewServer(f.home.Handler(homeop.Directory))
+ cred := httptest.NewServer(f.home.Handler(homeop.Credential))
+ t.Cleanup(dir.Close)
+ t.Cleanup(cred.Close)
+ con := fakeconsole.New("bds", "alta")
+ t.Cleanup(con.Close)
+ tokens := map[string]string{}
+ for _, a := range provision.Apps {
+ tokens[a.Slug] = con.Mint(a.Slug)
+ }
+ db, err := provision.OpenDB(filepath.Join(t.TempDir(), "alta.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { db.Close() })
+ f.store, err = provision.NewStore(context.Background(), db, bytes.Repeat([]byte{3}, 32), clock, Extra...)
+ if err != nil {
+ t.Fatal(err)
+ }
+ roles := map[string]homeop.Role{}
+ for name, url := range map[string]string{homeop.Credential: cred.URL, homeop.Directory: dir.URL} {
+ p := f.home.Pins(name)
+ o := issuer
+ if name == homeop.Directory {
+ o = dirO
+ }
+ roles[name] = homeop.Role{Name: name, Origin: o, URL: url, Installation: p.Installation, Registry: p.Registry, Device: p.Device}
+ }
+ f.engine = provision.New(provision.Config{Store: f.store, Home: &homeop.Client{Key: key, Prefilter: pre, Roles: roles, Now: clock},
+ Console: &console.Client{Base: con.URL(), Account: "bds", Tokens: tokens, Guard: provision.Guard{Store: f.store, Account: "bds"}},
+ HomeCfg: provision.HomeConfig{Issuer: issuer, Directory: dirO, Provisioner: f.home.ProvisioningPublic()}, Account: "bds", Now: clock, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))})
+ f.signer, _ = family.Generate()
+ app, err := New(Config{Origin: origin, OperatorSubject: operator, Engine: f.engine, Store: f.store, HomeDirectory: dirO, HomeCredential: issuer, Account: "bds", Now: clock,
+ Home: &connect.DecodedCredentials{Issuer: issuer, ConsumerID: "alta", Keys: map[string][]byte{"k1": f.signer.SignPub()}, DEK: bytes.Repeat([]byte{5}, 32), Directory: dirO}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.app = app
+ return f
+}
+
+func (f *fixture) do(method, path string, form url.Values, headers map[string]string) *httptest.ResponseRecorder {
+ f.t.Helper()
+ var body io.Reader
+ if form != nil {
+ body = strings.NewReader(form.Encode())
+ }
+ r := httptest.NewRequest(method, origin+path, body)
+ if form != nil {
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ }
+ for k, v := range headers {
+ r.Header.Set(k, v)
+ }
+ for _, c := range f.jar {
+ r.AddCookie(c)
+ }
+ w := httptest.NewRecorder()
+ f.app.ServeHTTP(w, r)
+ for _, c := range w.Result().Cookies() {
+ if c.MaxAge < 0 {
+ delete(f.jar, c.Name)
+ } else {
+ f.jar[c.Name] = c
+ }
+ }
+ return w
+}
+
+var sameOrigin = map[string]string{"Origin": origin, "Sec-Fetch-Site": "same-origin"}
+
+// signIn is the Home hand-off, with Home's assertion minted here.
+func (f *fixture) signIn(subject string) {
+ f.t.Helper()
+ start := f.do("GET", "/auth/start?return_to=%2F", nil, nil)
+ if start.Code != 303 {
+ f.t.Fatalf("start %d", start.Code)
+ }
+ target, _ := url.Parse(start.Header().Get("Location"))
+ if target.Host != "id.oficina.works" || target.Query().Get("consumer") != "alta" {
+ f.t.Fatalf("issuer target %s", target)
+ }
+ id, _ := assertion.RandomID()
+ token, err := assertion.Sign(f.signer, assertion.Claims{Version: 1, Issuer: issuer, Audience: origin, Subject: subject, KeyID: "k1", ID: id, Nonce: target.Query().Get("nonce"), IssuedAt: f.now.Unix(), ExpiresAt: f.now.Unix() + 120, AuthTime: f.now.Unix()})
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ cb := f.do("POST", "/auth/assertion", url.Values{"assertion": {token}}, map[string]string{"Origin": issuer})
+ if cb.Code != 303 {
+ f.t.Fatalf("callback %d", cb.Code)
+ }
+ fin := f.do("GET", "/auth/finish", nil, nil)
+ if fin.Code != 303 || fin.Header().Get("Location") != "/" {
+ f.t.Fatalf("finish %d %s", fin.Code, fin.Header().Get("Location"))
+ }
+}
+
+func TestSignInIsHomeOnlyAndOperatorOnly(t *testing.T) {
+ f := newFixture(t)
+ if w := f.do("GET", "/", nil, nil); w.Code != 303 || !strings.HasPrefix(w.Header().Get("Location"), "/auth/start?return_to=") {
+ t.Fatalf("anonymous: %d %s", w.Code, w.Header().Get("Location"))
+ }
+ f.signIn(stranger)
+ for _, p := range []string{"/", "/teams/new", "/runs/1", "/initialize"} {
+ if w := f.do("GET", p, nil, nil); w.Code != 404 {
+ t.Fatalf("stranger %s: %d", p, w.Code)
+ }
+ }
+ unknown := f.do("GET", "/no-such-page", nil, nil)
+ stranger := f.do("GET", "/teams/new", nil, nil)
+ if unknown.Body.String() != stranger.Body.String() {
+ t.Fatal("a stranger's 404 differs from an unknown page's")
+ }
+ f.jar = map[string]*http.Cookie{}
+ f.signIn(operator)
+ w := f.do("GET", "/", nil, nil)
+ if w.Code != 200 || !strings.Contains(w.Body.String(), "Initialize") {
+ t.Fatalf("operator: %d", w.Code)
+ }
+ scriptless(t, w.Body.String())
+}
+
+func scriptless(t *testing.T, html string) {
+ t.Helper()
+ scripts := regexp.MustCompile(`<script[^>]*>`).FindAllString(html, -1)
+ if len(scripts) != 1 || !strings.Contains(scripts[0], "busy.js") {
+ t.Fatalf("scripts %v: Alta is scriptless but for estilo's busy.js", scripts)
+ }
+ if strings.Contains(html, " style=") || strings.Contains(html, "<style") || strings.Contains(html, " onclick") {
+ t.Fatal("inline style or handler")
+ }
+}
+
+func TestIdleSessionEnds(t *testing.T) {
+ f := newFixture(t)
+ f.signIn(operator)
+ if w := f.do("GET", "/", nil, nil); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ f.now = f.now.Add(IdleLifetime + time.Minute)
+ if w := f.do("GET", "/", nil, nil); w.Code != 303 {
+ t.Fatalf("idle session still served: %d", w.Code)
+ }
+}
+
+func TestCrossOriginPostRefused(t *testing.T) {
+ f := newFixture(t)
+ f.signIn(operator)
+ w := f.do("POST", "/teams", url.Values{"label": {"alpha"}}, map[string]string{"Origin": "https://evil.example"})
+ if w.Code != 403 {
+ t.Fatalf("cross-origin POST: %d", w.Code)
+ }
+}
+
+func TestInitializeThenNewTeamShowsTheConfirmCeremony(t *testing.T) {
+ f := newFixture(t)
+ f.signIn(operator)
+ if w := f.do("POST", "/initialize", url.Values{"attestation": {"yes"}}, sameOrigin); w.Code != 422 || !strings.Contains(w.Body.String(), "Type the sentence exactly") {
+ t.Fatalf("bad attestation: %d", w.Code)
+ }
+ w := f.do("POST", "/initialize", url.Values{"attestation": {provision.InitializeAttestation}}, sameOrigin)
+ if w.Code != 303 {
+ t.Fatalf("initialize: %d %s", w.Code, w.Body.String())
+ }
+ if err := f.home.Confirm(homeop.Directory, ""); err != nil {
+ t.Fatal(err)
+ }
+ id := strings.TrimPrefix(w.Header().Get("Location"), "/runs/")
+ runID := mustInt(t, id)
+ if err := f.engine.Advance(context.Background(), runID); err != nil {
+ t.Fatal(err)
+ }
+ f.now = f.now.Add(homeop.WindowLifetime * time.Second)
+ page := f.do("GET", "/teams/new", nil, nil)
+ if page.Code != 200 {
+ t.Fatal(page.Code)
+ }
+ scriptless(t, page.Body.String())
+ // A label used before is refused on the form, and the address is
+ // echoed into the form only.
+ w = f.do("POST", "/teams", url.Values{"label": {"Bad Label"}, "name": {"Lagged"}, "owner": {owner}, "app": {"docs", "calls"}}, sameOrigin)
+ if w.Code != 422 || !strings.Contains(w.Body.String(), "lower-case") {
+ t.Fatalf("bad label: %d", w.Code)
+ }
+ w = f.do("POST", "/teams", url.Values{"label": {"lagged"}, "name": {"Lagged"}, "owner": {owner}, "app": {"docs", "calls"}}, sameOrigin)
+ if w.Code != 303 {
+ t.Fatalf("create: %d %s", w.Code, w.Body.String())
+ }
+ run := f.do("GET", w.Header().Get("Location"), nil, nil)
+ body := run.Body.String()
+ r, _ := f.store.Run(context.Background(), mustInt(t, strings.TrimPrefix(w.Header().Get("Location"), "/runs/")))
+ for _, want := range []string{"https://oficina.works/operator/confirm", "https://id.oficina.works/operator/confirm", homeop.PlanPrefix(r.PlanID), "lagged.docs.oficina.works", "Resume"} {
+ if !strings.Contains(body, want) {
+ t.Fatalf("run page lacks %q", want)
+ }
+ }
+ if strings.Contains(body, owner) {
+ t.Fatal("the run page shows the owner's address")
+ }
+ scriptless(t, body)
+ team := f.do("GET", "/teams/lagged", nil, nil)
+ if team.Code != 200 || strings.Contains(team.Body.String(), owner) {
+ t.Fatalf("team page: %d", team.Code)
+ }
+ retire := f.do("GET", "/teams/lagged/retire", nil, nil)
+ if retire.Code != 200 || !strings.Contains(retire.Body.String(), "Type lagged to confirm") {
+ t.Fatalf("retire page: %d", retire.Code)
+ }
+}
+
+func mustInt(t *testing.T, s string) int64 {
+ var n int64
+ if err := json.Unmarshal([]byte(s), &n); err != nil {
+ t.Fatalf("not a run id: %q", s)
+ }
+ return n
+}
diff --git a/internal/web/words.go b/internal/web/words.go
new file mode 100644
index 0000000..e1847e0
--- /dev/null
+++ b/internal/web/words.go
@@ -0,0 +1,104 @@
+package web
+
+import "strings"
+
+// Every state the engine records is a fixed code; this is the one place
+// they become words. An unknown code is shown as itself, which is honest
+// and greppable.
+var words = map[string]string{
+ "awaiting-confirm": "Waiting for you to confirm on Home",
+ "awaiting-confirm-directory": "Waiting for you to confirm on oficina.works",
+ "awaiting-confirm-credential": "Waiting for you to confirm on id.oficina.works",
+ "window-expired": "The confirmed window closed. Continue under a new plan.",
+ "window-closed": "No window is open. Continue under a new plan.",
+ "plan-expired": "The plan expired before it was confirmed. Submit a new one.",
+ "home-busy": "Home already has a plan pending or a window open on that role",
+ "home-unavailable": "Home did not answer. Alta will try again.",
+ "home-not-initialized": "Home's directory is not initialized yet",
+ "receipt-stale": "The owner receipt aged out; a new one is taken next",
+ "owner-needed": "Retype the owner's address to continue",
+ "owner-retype-needed": "Retype the owner's address: Alta no longer holds it",
+ "owner-refused": "Home refused the owner. Have they signed in at oficina.works?",
+ "seed-refused": "Home refused the team: the label may be taken at Home",
+ "provision-refused": "Home refused the directory consumer",
+ "register-refused": "Home refused the credential consumer",
+ "record-unverified": "Home's provisioning record did not verify",
+ "awaiting-platform-keys": "Waiting for the platform to deliver mail (and relay) credentials",
+ "environment-absent": "The environment is not there yet",
+ "extra-key": "The environment holds a key the recipe does not name",
+ "host-held": "The host is held outside Alta's scope",
+ "instance-bound-elsewhere": "The instance is bound to another environment",
+ "domain-checking": "Hostname attached; the platform is checking it",
+ "domain-pending-dns": "Hostname waits for DNS",
+ "domain-issuing-cert": "Issuing the certificate",
+ "domain-unverified": "The hostname needs its ownership proved",
+ "domain-misdirected": "DNS points somewhere else",
+ "domain-failed": "The certificate is failing",
+ "domain-route": "The hostname points at another route",
+ "restarting": "Restarting after a config change",
+ "version-unreachable": "/api/version does not answer yet",
+ "version-unstamped": "The build reports no version",
+ "awaiting-box-report": "Waiting for the box to report what it serves",
+ "serving-disagrees": "The box and /api/version disagree",
+ "version-not-commit": "The app's version is not a commit, so it cannot be activated",
+ "no-readiness-probe": "The app has no /api/team yet",
+ "not-team-mode": "The app is not in team mode",
+ "awaiting-roster": "Waiting for the app's roster",
+ "attempt-expired": "The verification attempt lapsed; verifying again",
+ "console-unavailable": "The console did not answer. Alta will try again.",
+ "console-write": "The console refused a write",
+ "transient": "Something went wrong. Alta will try again.",
+ "guard": "Alta's own guard refused a request",
+ "label-used": "That label has been used before. Labels are never reused.",
+ "label-shape": "A label is 3–32 lower-case letters, digits and hyphens, starting with a letter",
+ "name-shape": "Give the team a name",
+ "owner-shape": "That is not a plain email address",
+ "no-apps": "Choose at least one app",
+ "environment-shape": "That label is too long for a forked environment name",
+ "label-mismatch": "Type the team's label exactly to confirm",
+ "app-retired": "That app was retired from this team and is never re-added",
+ "attestation-mismatch": "Type the sentence exactly to confirm",
+ "already-initialized": "Home's directory is already initialized",
+ "initialized-elsewhere": "Home's directory was initialized by something other than Alta",
+ "plan-refused-credential": "Home refused the plan. Has the owner signed in at oficina.works?",
+ "plan-refused-directory": "Home's directory refused the plan",
+ "stream-diverged": "Home's operator stream moved without Alta",
+ "use-add-apps": "The team exists: continue with a new plan instead",
+ "audit-extra-key": "The environment holds a key the recipe does not name",
+ "audit-missing-key": "The environment is missing a recipe key",
+ "audit-value": "A value differs from the recipe",
+ "audit-kind": "A key has the wrong kind",
+ "audit-allowlist-empty": "The allowlist is empty",
+ "team-not-seeded": "The team was never created at Home",
+ "no-team": "No such team",
+ "app-not-active": "That app is not active in this team",
+ "run-finished": "That run has finished",
+ "bearer-unrecoverable": "Home's roster bearer could not be recovered",
+ "no-secrets-pubkey": "The console gave no key to seal secrets to",
+}
+
+func describe(code string) string {
+ if code == "" {
+ return ""
+ }
+ if w, ok := words[code]; ok {
+ return w
+ }
+ for prefix, w := range map[string]string{
+ "mail-prefix-": "Mail is declared under a prefix this app does not read: ",
+ "no-credential-": "No team credential for ",
+ "environment-exists-": "An environment of that name already exists for ",
+ "fork-missing-": "No forked environment for ",
+ "instance-bound-elsewhere-": "The instance is bound to another environment: ",
+ "console-": "The console did not answer for ",
+ "home-": "Home: ",
+ "domain-slow-": "Over 30 minutes and still ",
+ "roster-": "The app's roster says ",
+ "plan-": "Plan: ",
+ } {
+ if strings.HasPrefix(code, prefix) {
+ return w + strings.TrimPrefix(code, prefix)
+ }
+ }
+ return code
+}