oficina / home Public

Merge branch 'feat/consolidated-dashboard' into main

Show recent documents and upcoming events for the selected Oficina team
codex agent, operated by paul@keymail.dev 74a30439600f80db4b1ce88603e2c6b9d4ba0ffa parent ff16bf5parent 1c97ecb
26 files changed, +1,744 −5
  • Makefile +6 −2
  • dashboard/go.mod +21 −0
  • dashboard/go.sum +55 −0
  • dashboard/migrations/0001_dashboard.sql +4 −0
  • dashboard/provider.go +92 −0
  • dashboard/provider_test.go +103 −0
  • dashboard/replay.go +51 −0
  • dashboard/token.go +102 −0
  • dashboard/token_test.go +115 −0
  • dashboard/wire.go +71 −0
  • docs/superpowers/specs/2026-10-24-dashboard-design.md +166 −0
  • go.mod +1 −0
  • go.sum +2 −0
  • internal/home/app.go +3 −0
  • internal/home/credits_inventory_test.go +1 −1
  • internal/home/dashboard.go +261 −0
  • internal/home/dashboard_config.go +109 −0
  • internal/home/dashboard_exchange.go +169 −0
  • internal/home/dashboard_preference.go +57 −0
  • internal/home/dashboard_state.go +89 −0
  • internal/home/dashboard_test.go +204 −0
  • internal/home/directory.go +3 −1
  • internal/home/runtime.go +4 −0
  • internal/home/signin_return.go +1 −1
  • internal/home/static/calma.css +19 −0
  • internal/home/templates/dashboard.html +35 −0

CI passed — run details

landed from feat/consolidated-dashboard

diff --git a/Makefile b/Makefile
index 47c04de..bb60285 100644
--- a/Makefile
+++ b/Makefile
@@ -72,7 +72,7 @@ test: test-vet test-fmt test-build test-go test-race
# with HTTP 429 however long the runner waited between runs. What one
# attempt fetched stays cached, so each retry asks for less.
deps:
- @for dir in . handoff roster connect; do \
+ @for dir in . handoff roster connect dashboard; do \
n=0; until (cd $$dir && go mod download); do \
n=$$((n+1)); [ $$n -lt 6 ] || exit 1; \
echo "go mod download in $$dir failed (the hub's git rate limit?); retrying in $$((n*5))s"; \
@@ -85,6 +85,7 @@ test-vet: deps
CGO_ENABLED=0 go vet -tags browser ./internal/home/
cd handoff && CGO_ENABLED=0 go vet ./...
cd roster && CGO_ENABLED=0 go vet ./...
+ cd dashboard && CGO_ENABLED=0 go vet ./...
cd connect && CGO_ENABLED=0 go vet ./...
# Fails on unformatted files rather than rewriting them. CI must never
@@ -102,12 +103,14 @@ test-build:
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build ./cmd/home ./cmd/oficina ./internal/operatorlaunch
cd handoff && CGO_ENABLED=0 go build ./...
cd roster && CGO_ENABLED=0 go build ./...
+ cd dashboard && CGO_ENABLED=0 go build ./...
cd connect && CGO_ENABLED=0 go build ./...
test-go:
CGO_ENABLED=0 go test -count=1 ./...
cd handoff && CGO_ENABLED=0 go test -count=1 ./...
cd roster && CGO_ENABLED=0 go test -count=1 ./...
+ cd dashboard && CGO_ENABLED=0 go test ./...
cd connect && CGO_ENABLED=0 go test -count=1 ./...
# The one concurrency-bearing package. internal/home's link store is
@@ -124,6 +127,7 @@ test-race:
go test -race -count=1 ./internal/home/ ./internal/operator/ ./internal/operatorlaunch/ ./internal/provisioner/ ./internal/home/directorydata/
cd handoff && CGO_ENABLED=1 go test -race -count=1 ./...
cd roster && CGO_ENABLED=1 go test -race -count=1 ./...
+ cd dashboard && CGO_ENABLED=1 go test -race -count=1 ./...
cd connect && CGO_ENABLED=1 go test -race -count=1 ./...
# The browser checks, in a real Chromium (RASTRILLO_CHROME, on PATH, or
@@ -144,6 +148,6 @@ credits:
go build -o "$$notices_tmp/notices" amadan.net/oficina/estilo.git/cmd/oficina-notices; \
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 "$$notices_tmp/notices" \
-package ./cmd/home -lucide -onest \
- -exclude amadan.net/oficina/estilo.git,amadan.net/oficina/home/handoff,amadan.net/oficina/home/roster \
+ -exclude amadan.net/oficina/home/dashboard,amadan.net/oficina/estilo.git,amadan.net/oficina/home/handoff,amadan.net/oficina/home/roster \
> "$$notices_tmp/notices.json"; \
mv "$$notices_tmp/notices.json" internal/home/credits/notices.json
diff --git a/dashboard/go.mod b/dashboard/go.mod
new file mode 100644
index 0000000..ebbe7a2
--- /dev/null
+++ b/dashboard/go.mod
@@ -0,0 +1,21 @@
+module amadan.net/oficina/home/dashboard
+
+go 1.25.0
+
+require (
+ amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd
+ github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2
+ modernc.org/sqlite v1.55.0
+)
+
+require (
+ github.com/dustin/go-humanize v1.0.1 // indirect
+ github.com/google/uuid v1.6.0 // 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
+ modernc.org/libc v1.74.1 // indirect
+ modernc.org/mathutil v1.7.1 // indirect
+ modernc.org/memory v1.11.0 // indirect
+)
diff --git a/dashboard/go.sum b/dashboard/go.sum
new file mode 100644
index 0000000..8bd49e5
--- /dev/null
+++ b/dashboard/go.sum
@@ -0,0 +1,55 @@
+amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd h1:jlFSt95M1ontOg+VePU+kIJpChtWqDQAbnmlxqCnbgc=
+amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd/go.mod h1:RpyHVPD0udcSfHJroY0KZE/FUjgw6Tvfo8SJm2qeZGE=
+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-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/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=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
+github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
+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/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=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
+golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
+golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
+golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
+golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
+golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+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=
+modernc.org/cc/v4 v4.29.0 h1:CXgwL8cvxmyzBQZzbSl/6xFtMCryb6u8IOqDci39cgc=
+modernc.org/cc/v4 v4.29.0/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
+modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU=
+modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk=
+modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
+modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
+modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
+modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
+modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI=
+modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
+modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
+modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
+modernc.org/libc v1.74.1 h1:bdR4VTKFMC4966QSNZ05XLGI/VwzVa2kTUX51Dm0riQ=
+modernc.org/libc v1.74.1/go.mod h1:uH4t5bOx3G3g9Xcmj10YKlTcVISlRDwv8VoQJG9n8Os=
+modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
+modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
+modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
+modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
+modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
+modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
+modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
+modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
+modernc.org/sqlite v1.55.0 h1:hIFh0MCH0rGinQ/4KYb5/UbCkRkb+UP+OkLCVWa5MTM=
+modernc.org/sqlite v1.55.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
+modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
+modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
+modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
+modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
diff --git a/dashboard/migrations/0001_dashboard.sql b/dashboard/migrations/0001_dashboard.sql
new file mode 100644
index 0000000..025a65f
--- /dev/null
+++ b/dashboard/migrations/0001_dashboard.sql
@@ -0,0 +1,4 @@
+CREATE TABLE oficina_dashboard_clock (id INTEGER PRIMARY KEY CHECK(id=1), observed INTEGER NOT NULL);
+INSERT INTO oficina_dashboard_clock VALUES(1,0);
+CREATE TABLE oficina_dashboard_replay (digest BLOB PRIMARY KEY, expires INTEGER NOT NULL);
+CREATE INDEX oficina_dashboard_replay_expiry ON oficina_dashboard_replay(expires);
diff --git a/dashboard/provider.go b/dashboard/provider.go
new file mode 100644
index 0000000..6ebb4d2
--- /dev/null
+++ b/dashboard/provider.go
@@ -0,0 +1,92 @@
+package dashboard
+
+import (
+ "context"
+ "database/sql"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/go-json-experiment/json"
+)
+
+type ProviderConfig struct {
+ DB *sql.DB
+ Issuer, Origin, Directory, Team, Kind string
+ Keys map[string][]byte
+ // Resolve reads an existing explicit link AND current admission. Never creates accounts.
+ Resolve func(context.Context, string) (int64, error)
+ Read func(context.Context, int64, string, time.Time) (Response, error)
+ // Write optionally applies the app's ordinary response-time authorization guard.
+ // It owns writing success or refusal and must never log the body.
+ Write func(http.ResponseWriter, *http.Request, []byte)
+}
+
+func NewProvider(c ProviderConfig) (http.Handler, error) {
+ if c.DB == nil || !ValidOrigin(c.Issuer) || !ValidOrigin(c.Origin) || !ValidOrigin(c.Directory) || !ValidName(c.Team) || len(c.Keys) == 0 || c.Resolve == nil || c.Read == nil || (c.Kind != "documents" && c.Kind != "events") {
+ return nil, ErrRefused
+ }
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "private, no-store")
+ w.Header().Set("Vary", "Authorization")
+ refuse := func(status int) { http.Error(w, "Dashboard unavailable", status) }
+ if r.Method != http.MethodGet || r.URL.Path != Path || r.URL.RawQuery != "" || r.Host != strings.TrimPrefix(c.Origin, "https://") {
+ refuse(404)
+ return
+ }
+ headers := r.Header.Values("Authorization")
+ if len(headers) != 1 || !strings.HasPrefix(headers[0], "Bearer ") {
+ refuse(401)
+ return
+ }
+ now := time.Now()
+ claims, e := Verify(strings.TrimPrefix(headers[0], "Bearer "), c.Issuer, c.Origin, c.Directory, c.Team, c.Keys, now)
+ if e != nil {
+ refuse(401)
+ return
+ }
+ if e = Consume(r.Context(), c.DB, claims, now); e != nil {
+ if e == ErrUnavailable {
+ refuse(503)
+ } else {
+ refuse(401)
+ }
+ return
+ }
+ id, e := c.Resolve(r.Context(), claims.Subject)
+ if e != nil || id <= 0 {
+ if e == ErrUnavailable {
+ refuse(503)
+ } else {
+ refuse(403)
+ }
+ return
+ }
+ result, e := c.Read(r.Context(), id, claims.Subject, now)
+ if e != nil {
+ refuse(503)
+ return
+ }
+ result.Version = 1
+ result.Team = c.Team
+ result.Kind = c.Kind
+ if result.Items == nil {
+ result.Items = []Item{}
+ }
+ if !result.Valid(c.Origin, c.Team, c.Kind) {
+ refuse(503)
+ return
+ }
+ b, e := json.Marshal(result)
+ if e != nil || len(b) > MaxBody {
+ refuse(503)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ if c.Write != nil {
+ c.Write(w, r, b)
+ } else {
+ _, _ = w.Write(b)
+ }
+ }), nil
+}
diff --git a/dashboard/provider_test.go b/dashboard/provider_test.go
new file mode 100644
index 0000000..200f921
--- /dev/null
+++ b/dashboard/provider_test.go
@@ -0,0 +1,103 @@
+package dashboard
+
+import (
+ "context"
+ "database/sql"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestProviderRequiresBoundTokenAndExistingIdentity(t *testing.T) {
+ db, e := sql.Open("sqlite", t.TempDir()+"/provider.db")
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer db.Close()
+ db.SetMaxOpenConns(1)
+ b, _ := Migrations.ReadFile("migrations/0001_dashboard.sql")
+ if _, e = db.Exec(string(b)); e != nil {
+ t.Fatal(e)
+ }
+ k, c := fixture(t)
+ c.Issued = time.Now().Unix()
+ c.Expires = c.Issued + 120
+ resolveCalls, readCalls := 0, 0
+ cfg := ProviderConfig{DB: db, Issuer: c.Issuer, Origin: c.Audience, Directory: c.Directory, Team: c.Team, Kind: "documents", Keys: map[string][]byte{c.KeyID: k.SignPub()}, Resolve: func(_ context.Context, sub string) (int64, error) {
+ resolveCalls++
+ if sub != c.Subject {
+ return 0, ErrRefused
+ }
+ return 1, nil
+ }, Read: func(_ context.Context, id int64, sub string, _ time.Time) (Response, error) {
+ readCalls++
+ return Response{Items: []Item{{ID: "one", Title: "Private canary", URL: c.Audience + "/d/one", Updated: time.Now()}}}, nil
+ }}
+ h, e := NewProvider(cfg)
+ if e != nil {
+ t.Fatal(e)
+ }
+ request := func(token string) *httptest.ResponseRecorder {
+ r := httptest.NewRequest("GET", c.Audience+Path, nil)
+ if token != "" {
+ r.Header.Set("Authorization", "Bearer "+token)
+ }
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, r)
+ return w
+ }
+ if w := request(""); w.Code != 401 {
+ t.Fatal(w.Code)
+ }
+ bad := c
+ bad.Team = "other"
+ token, _ := Sign(k, bad)
+ if w := request(token); w.Code != 401 {
+ t.Fatal(w.Code)
+ }
+ if resolveCalls != 0 || readCalls != 0 {
+ t.Fatal("unverified request reached identity/data")
+ }
+ token, _ = Sign(k, c)
+ w := request(token)
+ if w.Code != 200 || !strings.Contains(w.Body.String(), "Private canary") || w.Header().Get("Cache-Control") != "private, no-store" {
+ t.Fatalf("response %d", w.Code)
+ }
+ if w = request(token); w.Code != 401 {
+ t.Fatal("replay", w.Code)
+ }
+ other := c
+ other.ID, _ = ID()
+ other.Subject = "pr_" + strings.Repeat("b", 26)
+ token, _ = Sign(k, other)
+ if w = request(token); w.Code != 403 || strings.Contains(w.Body.String(), "canary") {
+ t.Fatal("unknown identity", w.Code)
+ }
+ if readCalls != 1 {
+ t.Fatal("read reached more than authorized request", readCalls)
+ }
+}
+func TestMalformedWireIsNotEmptySuccess(t *testing.T) {
+ r := Response{Version: 1, Team: "pilot", Kind: "documents"}
+ if r.Valid("https://docs.example.com", "pilot", "documents") {
+ t.Fatal("nil items accepted")
+ }
+ r.Items = []Item{}
+ if !r.Valid("https://docs.example.com", "pilot", "documents") {
+ t.Fatal("explicit empty refused")
+ }
+ r.Kind = "events"
+ if r.Valid("https://docs.example.com", "pilot", "events") {
+ t.Fatal("missing timezone accepted")
+ }
+ r.Timezone = "Europe/Dublin"
+ if !r.Valid("https://docs.example.com", "pilot", "events") {
+ t.Fatal("valid empty agenda refused")
+ }
+ for _, link := range []string{"https://evil.example.com/d/1", "https://docs.example.com@evil.example.com/d/1", "https://docs.example.com/\\evil"} {
+ if SafeLink(link, "https://docs.example.com") {
+ t.Fatal("unsafe link")
+ }
+ }
+}
diff --git a/dashboard/replay.go b/dashboard/replay.go
new file mode 100644
index 0000000..e4433f5
--- /dev/null
+++ b/dashboard/replay.go
@@ -0,0 +1,51 @@
+package dashboard
+
+import (
+ "context"
+ "crypto/sha256"
+ "database/sql"
+ "embed"
+ "time"
+)
+
+// Migrations contain only replay digests and clock bounds, never pulled content.
+//
+//go:embed migrations/*.sql
+var Migrations embed.FS
+
+// Consume commits replay use before an app resolves identity or reads content.
+// The clock watermark survives restart and rejects backward movement beyond 30s.
+func Consume(ctx context.Context, db *sql.DB, c Claims, now time.Time) error {
+ tx, e := db.BeginTx(ctx, nil)
+ if e != nil {
+ return ErrUnavailable
+ }
+ defer tx.Rollback()
+ var observed int64
+ if e = tx.QueryRowContext(ctx, `UPDATE oficina_dashboard_clock SET observed=MAX(observed,?) WHERE id=1 RETURNING observed`, now.Unix()).Scan(&observed); e != nil {
+ return ErrUnavailable
+ }
+ if now.Unix() < observed-30 || c.Expires <= now.Unix() {
+ return ErrRefused
+ }
+ if _, e = tx.ExecContext(ctx, `DELETE FROM oficina_dashboard_replay WHERE expires < ?`, now.Unix()-30); e != nil {
+ return ErrUnavailable
+ }
+ var count int
+ if e = tx.QueryRowContext(ctx, `SELECT count(*) FROM oficina_dashboard_replay`).Scan(&count); e != nil || count >= 10000 {
+ return ErrUnavailable
+ }
+ h := sha256.Sum256([]byte(c.Issuer + "\x00" + c.ID))
+ res, e := tx.ExecContext(ctx, `INSERT INTO oficina_dashboard_replay(digest,expires) VALUES(?,?) ON CONFLICT(digest) DO NOTHING`, h[:], c.Expires)
+ if e != nil {
+ return ErrUnavailable
+ }
+ n, e := res.RowsAffected()
+ if e != nil || n != 1 {
+ return ErrRefused
+ }
+ if tx.Commit() != nil {
+ return ErrUnavailable
+ }
+ return nil
+}
diff --git a/dashboard/token.go b/dashboard/token.go
new file mode 100644
index 0000000..138703e
--- /dev/null
+++ b/dashboard/token.go
@@ -0,0 +1,102 @@
+// Package dashboard defines read-only, person-bound dashboard requests. Tokens
+// have a distinct signing context and cannot be used for login or account linking.
+package dashboard
+
+import (
+ "encoding/base64"
+ "errors"
+ "net/url"
+ "strings"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/assertion"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+ "github.com/go-json-experiment/json"
+)
+
+const Path = "/api/oficina/dashboard"
+const signingContext = "oficina/dashboard/read/v1"
+const MaxItems = 20
+const MaxBody = 65536
+
+var ErrRefused = errors.New("dashboard: refused")
+var ErrUnavailable = errors.New("dashboard: unavailable")
+
+type Claims struct {
+ Version int `json:"v"`
+ Issuer string `json:"iss"`
+ Audience string `json:"aud"`
+ Directory string `json:"directory"`
+ Subject string `json:"sub"`
+ Team string `json:"team"`
+ Purpose string `json:"purpose"`
+ KeyID string `json:"kid"`
+ ID string `json:"jti"`
+ Nonce string `json:"nonce"`
+ Issued int64 `json:"iat"`
+ Expires int64 `json:"exp"`
+}
+
+func ID() (string, error) { return assertion.RandomID() }
+func ValidID(s string) bool {
+ b, e := base64.RawURLEncoding.Strict().DecodeString(s)
+ return e == nil && len(b) == 16 && base64.RawURLEncoding.EncodeToString(b) == s
+}
+func ValidName(s string) bool {
+ if len(s) == 0 || len(s) > 64 {
+ return false
+ }
+ for _, c := range s {
+ if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_') {
+ return false
+ }
+ }
+ return true
+}
+func ValidOrigin(s string) bool {
+ u, e := url.Parse(s)
+ return e == nil && u.Scheme == "https" && u.Host != "" && u.Host == strings.ToLower(u.Host) && u.User == nil && u.Path == "" && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && u.Opaque == "" && u.Port() == ""
+}
+func valid(c Claims) bool {
+ return c.Version == 1 && c.Purpose == "dashboard-read" && ValidOrigin(c.Issuer) && ValidOrigin(c.Audience) && ValidOrigin(c.Directory) && c.Issuer != c.Audience && c.Issuer != c.Directory && strings.HasPrefix(c.Subject, "pr_") && len(c.Subject) == 29 && ValidName(c.Subject) && ValidName(c.Team) && ValidName(c.KeyID) && ValidID(c.ID) && ValidID(c.Nonce) && c.ID != c.Nonce && c.Issued > 0 && c.Expires > c.Issued && c.Expires-c.Issued <= 120
+}
+func Sign(key *family.Keypair, c Claims) (string, error) {
+ if !valid(c) || key == nil || key.SignPriv == nil {
+ return "", ErrRefused
+ }
+ b, e := json.Marshal(c)
+ if e != nil {
+ return "", ErrUnavailable
+ }
+ sig, e := family.Sign(key, signingContext, b)
+ if e != nil {
+ return "", ErrUnavailable
+ }
+ return base64.RawURLEncoding.EncodeToString(b) + "." + base64.RawURLEncoding.EncodeToString(sig), nil
+}
+func Verify(token, issuer, audience, directory, team string, keys map[string][]byte, now time.Time) (Claims, error) {
+ if len(token) > 4096 {
+ return Claims{}, ErrRefused
+ }
+ p, s, ok := strings.Cut(token, ".")
+ if !ok {
+ return Claims{}, ErrRefused
+ }
+ b, e := base64.RawURLEncoding.Strict().DecodeString(p)
+ if e != nil || base64.RawURLEncoding.EncodeToString(b) != p {
+ return Claims{}, ErrRefused
+ }
+ sig, e := base64.RawURLEncoding.Strict().DecodeString(s)
+ if e != nil || base64.RawURLEncoding.EncodeToString(sig) != s {
+ return Claims{}, ErrRefused
+ }
+ var c Claims
+ if json.Unmarshal(b, &c, json.RejectUnknownMembers(true)) != nil || !valid(c) || c.Issuer != issuer || c.Audience != audience || c.Directory != directory || c.Team != team || c.Issued > now.Unix()+30 || c.Expires <= now.Unix() {
+ return Claims{}, ErrRefused
+ }
+ key := keys[c.KeyID]
+ if len(key) == 0 || !family.Verify(key, signingContext, b, sig) {
+ return Claims{}, ErrRefused
+ }
+ return c, nil
+}
diff --git a/dashboard/token_test.go b/dashboard/token_test.go
new file mode 100644
index 0000000..78ca8af
--- /dev/null
+++ b/dashboard/token_test.go
@@ -0,0 +1,115 @@
+package dashboard
+
+import (
+ "context"
+ "database/sql"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/assertion"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+ _ "modernc.org/sqlite"
+)
+
+func fixture(t *testing.T) (*family.Keypair, Claims) {
+ t.Helper()
+ k, e := family.Generate()
+ if e != nil {
+ t.Fatal(e)
+ }
+ id, _ := ID()
+ nonce, _ := ID()
+ return k, Claims{Version: 1, Issuer: "https://id.example.com", Audience: "https://docs.example.com", Directory: "https://home.example.com", Subject: "pr_" + strings.Repeat("a", 26), Team: "pilot", Purpose: "dashboard-read", KeyID: "key", ID: id, Nonce: nonce, Issued: 1000, Expires: 1120}
+}
+func TestTokensAreBoundAndPurposeSeparated(t *testing.T) {
+ k, c := fixture(t)
+ token, e := Sign(k, c)
+ if e != nil {
+ t.Fatal(e)
+ }
+ verify := func(token string, c Claims, now int64) error {
+ _, e := Verify(token, c.Issuer, c.Audience, c.Directory, c.Team, map[string][]byte{"key": k.SignPub()}, time.Unix(now, 0))
+ return e
+ }
+ if e = verify(token, c, 1000); e != nil {
+ t.Fatal(e)
+ }
+ for _, field := range []string{"issuer", "audience", "directory", "team"} {
+ wrong := c
+ switch field {
+ case "issuer":
+ wrong.Issuer = "https://other.example.com"
+ case "audience":
+ wrong.Audience = "https://other.example.com"
+ case "directory":
+ wrong.Directory = "https://other.example.com"
+ case "team":
+ wrong.Team = "other"
+ }
+ if verify(token, wrong, 1000) == nil {
+ t.Fatal("accepted wrong", field)
+ }
+ }
+ for _, now := range []int64{969, 1120, 1200} {
+ if verify(token, c, now) == nil {
+ t.Fatal("accepted time", now)
+ }
+ }
+ login, e := assertion.Sign(k, assertion.Claims{Version: 1, Issuer: c.Issuer, Audience: c.Audience, Subject: c.Subject, KeyID: c.KeyID, ID: c.ID, Nonce: c.Nonce, IssuedAt: 1000, ExpiresAt: 1120, AuthTime: 1000})
+ if e != nil {
+ t.Fatal(e)
+ }
+ if verify(login, c, 1000) == nil {
+ t.Fatal("login accepted for dashboard")
+ }
+ v, _ := assertion.NewVerifier(c.Issuer, c.Audience, map[string][]byte{"key": k.SignPub()})
+ if _, e = v.Verify(token, time.Unix(1000, 0)); e == nil {
+ t.Fatal("dashboard accepted for login")
+ }
+}
+func TestReplaySurvivesReopenAndClockRollback(t *testing.T) {
+ path := t.TempDir() + "/replay.db"
+ db, e := sql.Open("sqlite", path)
+ if e != nil {
+ t.Fatal(e)
+ }
+ db.SetMaxOpenConns(1)
+ b, _ := Migrations.ReadFile("migrations/0001_dashboard.sql")
+ if _, e = db.Exec(string(b)); e != nil {
+ t.Fatal(e)
+ }
+ _, c := fixture(t)
+ var mu sync.Mutex
+ success := 0
+ var wg sync.WaitGroup
+ for range 8 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if Consume(context.Background(), db, c, time.Unix(1000, 0)) == nil {
+ mu.Lock()
+ success++
+ mu.Unlock()
+ }
+ }()
+ }
+ wg.Wait()
+ if success != 1 {
+ t.Fatalf("consumed %d times", success)
+ }
+ db.Close()
+ db, e = sql.Open("sqlite", path)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer db.Close()
+ if Consume(context.Background(), db, c, time.Unix(1000, 0)) == nil {
+ t.Fatal("replayed after reopen")
+ }
+ c.ID, _ = ID()
+ if Consume(context.Background(), db, c, time.Unix(969, 0)) == nil {
+ t.Fatal("clock rollback accepted")
+ }
+}
diff --git a/dashboard/wire.go b/dashboard/wire.go
new file mode 100644
index 0000000..4d62ee3
--- /dev/null
+++ b/dashboard/wire.go
@@ -0,0 +1,71 @@
+package dashboard
+
+import (
+ "net/url"
+ "strings"
+ "time"
+ "unicode/utf8"
+)
+
+// A document is an object, not an edit log entry. An event is one occurrence.
+type Item struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ URL string `json:"url"`
+ Updated time.Time `json:"updated,omitzero"`
+ Start time.Time `json:"start,omitzero"`
+ End time.Time `json:"end,omitzero"`
+ AllDay bool `json:"all_day,omitempty"`
+ StartDate string `json:"start_date,omitempty"`
+ EndDate string `json:"end_date,omitempty"`
+ Calendar string `json:"calendar,omitempty"`
+}
+type Response struct {
+ Version int `json:"v"`
+ Team string `json:"team"`
+ Kind string `json:"kind"`
+ Items []Item `json:"items"`
+ Truncated bool `json:"truncated"`
+ Timezone string `json:"timezone,omitempty"`
+}
+
+func SafeLink(raw, origin string) bool {
+ u, e := url.Parse(raw)
+ return e == nil && u.Scheme+"://"+u.Host == origin && u.User == nil && u.Opaque == "" && strings.HasPrefix(u.Path, "/") && !strings.ContainsAny(raw, "\r\n\\")
+}
+func (r Response) Valid(origin, team, kind string) bool {
+ if r.Version != 1 || r.Team != team || r.Kind != kind || r.Items == nil || len(r.Items) > MaxItems || (kind != "documents" && kind != "events") {
+ return false
+ }
+ if kind == "events" {
+ if len(r.Timezone) == 0 || len(r.Timezone) > 128 {
+ return false
+ }
+ if _, e := time.LoadLocation(r.Timezone); e != nil {
+ return false
+ }
+ }
+ seen := map[string]bool{}
+ for _, i := range r.Items {
+ if len(i.ID) == 0 || len(i.ID) > 256 || seen[i.ID] || !utf8.ValidString(i.Title) || len(i.Title) > 2048 || len(i.Calendar) > 512 || len(i.URL) > 2048 || !SafeLink(i.URL, origin) {
+ return false
+ }
+ seen[i.ID] = true
+ if kind == "documents" && i.Updated.IsZero() {
+ return false
+ }
+ if kind == "events" {
+ if i.Start.IsZero() || !i.End.After(i.Start) {
+ return false
+ }
+ if i.AllDay {
+ s, e := time.Parse("2006-01-02", i.StartDate)
+ d, f := time.Parse("2006-01-02", i.EndDate)
+ if e != nil || f != nil || !d.After(s) {
+ return false
+ }
+ }
+ }
+ }
+ return true
+}
diff --git a/docs/superpowers/specs/2026-10-24-dashboard-design.md b/docs/superpowers/specs/2026-10-24-dashboard-design.md
new file mode 100644
index 0000000..e214b5c
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-24-dashboard-design.md
@@ -0,0 +1,166 @@
+# Selected-team dashboard
+
+Status: product direction recorded from Paul, 2026-10-24. Implementation proposal;
+not shipped. Independently reviewed and approved as a proposal by GPT-6 (Codex,
+inherited session model; exact variant not exposed), 2026-10-24. Review confirmed
+selected-team scope, omission of todos, and the source assertions below. The
+credential protocol and provider endpoints remain implementation prerequisites
+requiring their own review. Base: Home origin/main at ba81936.
+
+## Product decision
+
+After signing in to oficina.works, show a consolidated dashboard for the selected
+team, including the app launcher and recent work across that team's Oficina apps.
+Paul explicitly chose **only the selected team**, not a combined personal feed
+across teams. Switching teams switches every dashboard section together.
+
+This extends the front-door activity design of 2026-09-05: the app list remains,
+but documents and the calendar become the primary reason to visit Home. Paul
+subsequently clarified that no task support exists today and todos should be left
+out for now; Calendar is a possible future owner, not part of this delivery.
+It does not change the team boundary or move ownership of content into Home.
+
+## Page
+
+Use the existing Oficina chrome and Calma appearance. The heading names the
+selected team and exposes a team switcher. Preserve a compact list of apps near
+the top; recent work occupies most of the page rather than another full tile grid.
+
+- **Recent documents:** one list across Docs, Sheets, Slides, and other participating
+ document apps. Each row has a title, app/type, last-updated time, and a direct
+ link. One row per object, newest updated first; repeated edits do not crowd out
+ other documents. Initially show 20, with links to each app's full list and a
+ clear indication when more items exist. This is recent accessible work, not a
+ claim to record which documents the viewer personally opened.
+- **Calendar:** today's remaining events and the next seven days, in chronological
+ order, with event time, calendar, and a direct link. Preserve all-day dates and
+ use the viewer's chosen timezone for timed events. This is an agenda, not a list
+ sorted by event-edit time.
+
+On narrow screens stack recent documents and the agenda. Navigation,
+team selection, refresh, and item links must work without JavaScript. Use native
+links, headings, lists, and machine-readable time elements.
+
+A successful empty answer says that section has no matching items. An unavailable
+source says which app could not load and offers refresh/open-app navigation.
+Do not claim "no documents" or "nothing scheduled" when a provider
+has not answered. Do not infer support from a 404 or show invented example data
+in the live dashboard. Unsupported sections explain availability without claiming
+an integration exists.
+
+## Implementation evidence and dependencies
+
+The existing signed-in route in `internal/home/directory.go` renders only
+`directoryCatalog`; there is no aggregation handler. `directorydata.Store.Choices`
+provides current member/team/app destinations; it is not a document authorization
+check and is not the personal guest directory described in the older design.
+
+The 2026-09-05 activity spec remains the starting point for response bounds,
+per-person authorization, safe links, partial failures, and memory-only content.
+Its authentication assumptions cannot be copied into code unchanged:
+
+- `internal/home/runtime.go` runs separate credential and directory roles.
+ Directory startup rejects `HOME_ASSERTION_KEY`, and `newDirectory` rejects a
+ signer. The old spec's single-process minting assumption is not the shipped
+ architecture.
+- Current minting uses the assertion library's configured P-256 keypair, not the
+ older spec's stated Ed25519 algorithm.
+- The app sources inspected expose their own document/event lists, but no shipped
+ implementation of the spec's `/activity` endpoint was found in those checkouts.
+ Their latest remote branches must be fetched before implementation work.
+- No Todos repository/task provider was found in the workspace search. The local
+ Calendar importer explicitly skips VTODO. Paul confirmed that no task support
+ exists and explicitly deferred todos. No task provider is required for this
+ delivery, and no empty Todos section should be rendered.
+
+Before wiring live aggregation, specify and independently review a read-only,
+person-bound credential flow compatible with the separated roles. It must bind
+the authenticated person, selected team, destination and read purpose, resist
+replay, and have explicit expiry/revocation behavior. A caller-supplied subject
+plus a service secret is not sufficient. Do not give Directory the credential
+signing key or reuse login assertions without deciding their replay boundary.
+This proposal deliberately does not claim that missing protocol is implemented.
+
+## Data and loading contract
+
+Sources authorize each item for the authenticated viewer in the selected team.
+Home never infers item access from team membership. Guest visibility requires a
+real viewer-specific source directory before it can be advertised as supported.
+Preview origins must have explicit viewer/team mapping before they participate;
+operator configuration alone is not proof of a person's access.
+
+Use separate typed results for recent objects and upcoming event occurrences. The
+existing change-event shape alone cannot describe recurrence, all-day events, or
+stable object deduplication.
+Define a versioned extension and fixtures before provider implementation, with
+stable source-scoped object IDs, safe source-owned URLs, and bounded fields.
+Deduplicate documents by source and object ID; preserve distinct recurrence
+occurrences in the agenda. Keep source truncation visible.
+
+Fan out only to the selected team's viewer-authorized participating sources.
+Bound total render time, response bytes, item counts, and process-wide parallel
+requests. Never follow redirects. Validate source URLs and escape titles. Return
+private no-store responses at the app, Home, and edge. Preserve the prior spec's
+named partial-failure states and bounded per-person/source RAM cache rules.
+Content, titles, event details and deep links must not enter Home's
+database, on-disk caches, logs, metrics or error strings. Revalidate the selected
+team and source access on each request; clear/partition cached results on team or
+person changes and respect the hard maximum age after failed pulls.
+
+## Delivery and acceptance
+
+1. Settle the credential protocol and typed response fixtures. Review amendments
+ to the older activity spec and the suite contract.
+2. Implement authorized source endpoints in document apps and Calendar. Keep
+ capability flags disabled until endpoints and their authorization tests are
+ deployed.
+3. Add the selected-team dashboard renderer, compact app launcher, merger, agenda,
+ source availability states, and bounded client. Select only among the viewer's
+ current teams; preserve the choice through refresh and app navigation. Invalid
+ or removed teams must never fall back to showing another team's content.
+4. Exercise two people and two teams, including unauthorized items, removal of
+ membership, source timeout, 404, malformed/oversized data, redirect, truncation,
+ expired credentials and cache expiry. Verify privacy gates on database/WAL and
+ logs. Exercise timezone, all-day and recurring events and
+ duplicate document edits. Run with JavaScript disabled.
+5. Review the complete change on a deployed canary, check CI, and follow the
+ repository's branch/discussion/review requirements before merging or shipping.
+
+The acceptance case is concrete: signing in with a selected team presents its
+real recent documents, upcoming events, and app links; switching to another team
+replaces all of that data. A failed provider leaves the rest of the dashboard usable and identifies the missing part.
+A launcher with empty placeholder sections does not meet this acceptance case.
+
+## Implementation amendment, 2026-10-25
+
+Paul authorized build, review and deployment. GPT-6 independently reviewed the
+credential protocol and pilot mapping below before implementation.
+
+Directory starts a bounded browser-bound pending request carrying the current
+session digest, actual subject, selected team and pinned source set. Credential
+reads its own session and signs one 120-second, single-use token per source under
+`oficina/dashboard/read/v1`, separate from login assertions. Claims bind issuer,
+source audience, Directory recipient, subject, team, purpose, nonce and jti. A
+fixed-origin form returns the batch; Directory validates it against pending state
+and its current session before consuming the pending request and pulling. Sources
+consume replay IDs durably before resolving existing accounts and item access.
+No signing key moves into Directory, and no service accepts a supplied subject
+as proof of identity. Fresh uncached pulls require a new browser round trip.
+
+The live apex sources are explicitly assigned to one pilot team grouping. This
+is navigation configuration, not roster-established membership: no owner/member
+claim, inferred identity link, provisioning or roster write follows from it. Each
+provider independently resolves an existing Home link, rechecks current local
+admission, and uses its usual item scope. A failed link is not an empty success.
+Each origin belongs to exactly one grouping and verifies that configured team.
+Only the selected grouping is pulled; failure never selects another grouping.
+This pilot exception supersedes the draft's requirement for a preexisting Home
+roster for these sources. The reviewer withdrew that prerequisite after checking
+the actual source authorization boundary; no item access follows from grouping.
+
+The implementation uses a 30-second refresh TTL and 120-second absolute maximum
+for RAM-only results, with bounded entry count and expiry sweeps on each request.
+Every cache key includes session digest, subject, team and source configuration;
+sign-out loses access to that key. Existing short-lived bearer tokens can still
+be spent once until expiry. Source unlink and permission changes are enforced on
+each new pull; displayed cached content has the explicit bounded staleness above.
diff --git a/go.mod b/go.mod
index dab5a0a..d47d8c2 100644
--- a/go.mod
+++ b/go.mod
@@ -6,6 +6,7 @@ toolchain go1.26.5
require (
amadan.net/oficina/estilo.git v0.0.0-20261001084202-0b4d92c3dc16
+ amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489
amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf
amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd
diff --git a/go.sum b/go.sum
index 253b264..e2d6c6b 100644
--- a/go.sum
+++ b/go.sum
@@ -2,6 +2,8 @@ amadan.net/carlos/platform.git/launchctx v0.0.0-20260911135504-fb577f96f7d1 h1:R
amadan.net/carlos/platform.git/launchctx v0.0.0-20260911135504-fb577f96f7d1/go.mod h1:6fBmMWgtESLFXZURzu/HyRXM0vyLuo4+XGGdKuZ+wao=
amadan.net/oficina/estilo.git v0.0.0-20261001084202-0b4d92c3dc16 h1:F5v3x25dEj1rJNnBm71G7shN+fM+T2actUlaGPvoeH8=
amadan.net/oficina/estilo.git v0.0.0-20261001084202-0b4d92c3dc16/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
+amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 h1:AFDuOio0MxNxN9ZWVc3lul1QHkNjNUCO56kXpe/Fw3I=
+amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816/go.mod h1:+7xsX+QyVFrKy5gDAGh+FZ5+75z4CibWTL0wl9DWAw0=
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 h1:RPKtyry/71i06o8L+gjAaUyexbmG56kO1YPs601URAM=
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k=
amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf h1:SRKjCUgtk42WwR7VSn+V0eLNk20mfiY8dQmzdw13Sbo=
diff --git a/internal/home/app.go b/internal/home/app.go
index acf81fb..abd4186 100644
--- a/internal/home/app.go
+++ b/internal/home/app.go
@@ -38,6 +38,7 @@ import (
// is sealed on the way in, and the database handle because that is what
// it is sealed into. Nothing here reaches for a raw key.
type App struct {
+ dash *dashboardState
runtime *Runtime
directory *directoryFeatures
consumer *handoff.Consumer
@@ -198,6 +199,8 @@ func (a *App) Router() http.Handler {
r.Use(csrf.Protect(a.origins.Credential))
if a.runtime != nil && a.runtime.role == "credential" {
r.Get("/authorize", a.handleAuthorize)
+ r.Get("/dashboard/authorize", a.beginDashboard)
+ r.With(a.sessions.Require).Get("/dashboard/resume", a.authorizeDashboard)
r.With(a.sessions.Require).Get("/authorize/resume", a.handleAssertion)
r.Get("/static/assertion.js", serveAsset(staticAsset("assertion.js"), "text/javascript; charset=utf-8"))
}
diff --git a/internal/home/credits_inventory_test.go b/internal/home/credits_inventory_test.go
index fd7352c..dee8559 100644
--- a/internal/home/credits_inventory_test.go
+++ b/internal/home/credits_inventory_test.go
@@ -34,7 +34,7 @@ func TestCreditsMatchProductionDependencies(t *testing.T) {
if err != nil {
t.Fatal("production dependency graph unavailable", err)
}
- inventory, err := catalog.Collect(bytes.NewReader(raw), map[string]bool{"amadan.net/oficina/estilo.git": true, "amadan.net/oficina/home/handoff": true, "amadan.net/oficina/home/roster": true})
+ inventory, err := catalog.Collect(bytes.NewReader(raw), map[string]bool{"amadan.net/oficina/home/dashboard": true, "amadan.net/oficina/estilo.git": true, "amadan.net/oficina/home/handoff": true, "amadan.net/oficina/home/roster": true})
if err != nil {
t.Fatal(err)
}
diff --git a/internal/home/dashboard.go b/internal/home/dashboard.go
new file mode 100644
index 0000000..78cecd8
--- /dev/null
+++ b/internal/home/dashboard.go
@@ -0,0 +1,261 @@
+package home
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "net/url"
+ "sort"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/home/dashboard"
+ "github.com/go-json-experiment/json"
+)
+
+type dashboardRow struct {
+ dashboard.Item
+ App, When, DateTime string
+}
+type dashboardPage struct {
+ Apps []catalogApp
+ Teams []dashboardTeam
+ Team dashboardTeam
+ Documents, Events []dashboardRow
+ Sources []dashboardResult
+ DocumentsComplete, EventsComplete bool
+}
+
+func (a *App) handleDashboard(w http.ResponseWriter, r *http.Request) {
+ if len(a.runtime.dashboard) == 0 {
+ a.render(w, r, 200, "directory.html", map[string]any{"Apps": directoryCatalog(*a.runtime)})
+ return
+ }
+ subject, session, ok := a.dashboardSession(r)
+ if !ok {
+ http.Error(w, "Unable to load your dashboard", 400)
+ return
+ }
+ q, e := url.ParseQuery(r.URL.RawQuery)
+ if e != nil || len(q) > 2 || len(q["team"]) > 1 || len(q["dashboard"]) > 1 || len(q["refresh"]) > 1 || (q.Has("refresh") && (q.Get("refresh") != "1" || q.Has("dashboard"))) {
+ http.NotFound(w, r)
+ return
+ }
+ for k := range q {
+ if k != "team" && k != "dashboard" && k != "refresh" {
+ http.NotFound(w, r)
+ return
+ }
+ }
+ selected := q.Get("team")
+ if selected == "" {
+ var valid bool
+ selected, valid = a.selectedDashboardTeam(r, session)
+ if !valid {
+ http.NotFound(w, r)
+ return
+ }
+ if selected == "" {
+ selected = a.runtime.dashboard[0].ID
+ }
+ }
+ team, ok := a.dashboardTeam(selected)
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ a.rememberDashboardTeam(w, session, team.ID)
+ key := dashboardCacheKey(subject, session, team.ID)
+ now := time.Now()
+ a.dash.mu.Lock()
+ a.dash.sweep(now)
+ cached, found := a.dash.cache[key]
+ if q.Get("dashboard") == "" && !q.Has("refresh") && found && now.Sub(cached.At) < 30*time.Second {
+ a.dash.mu.Unlock()
+ a.renderDashboard(w, r, team, cached.Results)
+ return
+ }
+ nonce := q.Get("dashboard")
+ if nonce != "" {
+ pending, present := a.dash.pending[nonce]
+ if !present || nonce != dashboardNonce(r) || pending.Tokens == nil || pending.Subject != subject || pending.Session != session || pending.Team != team.ID {
+ a.dash.mu.Unlock()
+ http.Error(w, "Dashboard refresh expired. Return to Oficina and try again.", 400)
+ return
+ }
+ delete(a.dash.pending, nonce)
+ a.dash.mu.Unlock()
+ http.SetCookie(w, &http.Cookie{Name: dashboardCookie, Path: "/", Value: "", MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteNoneMode})
+ results := a.pullDashboard(r.Context(), team, pending.Tokens)
+ a.dash.mu.Lock()
+ a.dash.sweep(time.Now())
+ if len(a.dash.cache) >= 256 {
+ for k := range a.dash.cache {
+ delete(a.dash.cache, k)
+ break
+ }
+ }
+ cachedAt := time.Now()
+ a.dash.cache[key] = dashboardCache{Results: results, At: cachedAt}
+ // Drop content even when nobody visits Home again.
+ time.AfterFunc(120*time.Second, func() {
+ a.dash.mu.Lock()
+ defer a.dash.mu.Unlock()
+ if current, ok := a.dash.cache[key]; ok && current.At.Equal(cachedAt) {
+ delete(a.dash.cache, key)
+ }
+ })
+ a.dash.mu.Unlock()
+ // Finish at the ordinary selected-team URL, so refresh never reuses a token.
+ http.Redirect(w, r, "/?team="+url.QueryEscape(team.ID), http.StatusSeeOther)
+ return
+ }
+ if len(a.dash.pending) >= 256 {
+ a.dash.mu.Unlock()
+ http.Error(w, "Dashboard busy. Please try again.", 503)
+ return
+ }
+ nonce, e = dashboard.ID()
+ if e != nil {
+ a.dash.mu.Unlock()
+ http.Error(w, "Dashboard unavailable", 503)
+ return
+ }
+ // A new tab replaces only this browser's pending flow, never another viewer's.
+ if previous := dashboardNonce(r); previous != "" {
+ delete(a.dash.pending, previous)
+ }
+ a.dash.pending[nonce] = dashboardPending{Subject: subject, Session: session, Team: team.ID, Expires: now.Add(5 * time.Minute)}
+ a.dash.mu.Unlock()
+ http.SetCookie(w, &http.Cookie{Name: dashboardCookie, Path: "/", Value: nonce, MaxAge: 300, Secure: true, HttpOnly: true, SameSite: http.SameSiteNoneMode})
+ http.Redirect(w, r, a.origins.Credential+"/dashboard/authorize?"+url.Values{"team": {team.ID}, "nonce": {nonce}}.Encode(), http.StatusSeeOther)
+}
+func (a *App) pullDashboard(parent context.Context, team dashboardTeam, tokens map[string]string) []dashboardResult {
+ ctx, cancel := context.WithTimeout(parent, 3*time.Second)
+ defer cancel()
+ results := make(chan dashboardResult, len(team.Sources))
+ for _, source := range team.Sources {
+ go func(s dashboardSource) {
+ result := dashboardResult{Source: s, Status: "Could not load. Refresh or open the app."}
+ defer func() { results <- result }()
+ select {
+ case a.dash.slots <- struct{}{}:
+ defer func() { <-a.dash.slots }()
+ case <-ctx.Done():
+ result.Status = "Not loaded yet. Refresh to try again."
+ return
+ }
+ req, e := http.NewRequestWithContext(ctx, http.MethodGet, s.Origin+dashboard.Path, nil)
+ if e != nil {
+ return
+ }
+ req.Header.Set("Authorization", "Bearer "+tokens[s.Origin])
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("Cache-Control", "no-store")
+ response, e := a.dash.client.Do(req)
+ if e != nil {
+ return
+ }
+ defer response.Body.Close()
+ if response.StatusCode == 403 {
+ result.Status = "Connect your Oficina account in this app to see your work."
+ return
+ }
+ if response.StatusCode != 200 || !dashboardNoStore(response.Header.Values("Cache-Control")) {
+ return
+ }
+ b, e := io.ReadAll(io.LimitReader(response.Body, dashboard.MaxBody+1))
+ if e != nil || len(b) > dashboard.MaxBody {
+ return
+ }
+ var data dashboard.Response
+ if json.Unmarshal(b, &data, json.RejectUnknownMembers(true)) != nil || !data.Valid(s.Origin, team.ID, s.kind()) {
+ return
+ }
+ result.Response = data
+ result.Status = ""
+ }(source)
+ }
+ out := make([]dashboardResult, 0, len(team.Sources))
+ for range team.Sources {
+ out = append(out, <-results)
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].Source.App < out[j].Source.App })
+ return out
+}
+func (a *App) renderDashboard(w http.ResponseWriter, r *http.Request, team dashboardTeam, results []dashboardResult) {
+ page := dashboardPage{Apps: directoryCatalog(*a.runtime), Teams: a.runtime.dashboard, Team: team, Sources: results, DocumentsComplete: false, EventsComplete: false}
+ // Every launcher belongs to this explicit grouping; no global preview fallback.
+ page.Apps = nil
+ for _, source := range team.launchers() {
+ for _, app := range directoryCatalog(*a.runtime) {
+ if app.Name == source.Name() {
+ app.Href = source.Origin + "/"
+ app.Status = ""
+ page.Apps = append(page.Apps, app)
+ }
+ }
+ }
+ documentProviders, eventProviders, documentFailures, eventFailures := 0, 0, 0, 0
+ for _, result := range results {
+ if result.Source.kind() == "events" {
+ eventProviders++
+ } else {
+ documentProviders++
+ }
+ if result.Status != "" {
+ if result.Source.kind() == "events" {
+ eventFailures++
+ } else {
+ documentFailures++
+ }
+ continue
+ }
+ for _, item := range result.Response.Items {
+ row := dashboardRow{Item: item, App: result.Source.Name()}
+ if result.Source.kind() == "documents" {
+ row.When = item.Updated.UTC().Format("2 Jan 2006, 15:04 UTC")
+ row.DateTime = item.Updated.Format(time.RFC3339)
+ page.Documents = append(page.Documents, row)
+ } else {
+ loc, _ := time.LoadLocation(result.Response.Timezone)
+ row.When = item.Start.In(loc).Format("Mon 2 Jan, 15:04 MST")
+ row.DateTime = item.Start.Format(time.RFC3339)
+ if item.AllDay {
+ row.When = item.StartDate + " · All day"
+ row.DateTime = item.StartDate
+ }
+ page.Events = append(page.Events, row)
+ }
+ }
+ }
+ page.DocumentsComplete = documentProviders > 0 && documentFailures == 0
+ page.EventsComplete = eventProviders > 0 && eventFailures == 0
+ sort.SliceStable(page.Documents, func(i, j int) bool {
+ if page.Documents[i].Updated.Equal(page.Documents[j].Updated) {
+ return page.Documents[i].URL < page.Documents[j].URL
+ }
+ return page.Documents[i].Updated.After(page.Documents[j].Updated)
+ })
+ if len(page.Documents) > 20 {
+ page.Documents = page.Documents[:20]
+ }
+ sort.SliceStable(page.Events, func(i, j int) bool { return page.Events[i].Start.Before(page.Events[j].Start) })
+ a.render(w, r, 200, "dashboard.html", page)
+}
+
+func dashboardNoStore(headers []string) bool {
+ found := false
+ for _, header := range headers {
+ for _, raw := range strings.Split(header, ",") {
+ directive := strings.ToLower(strings.TrimSpace(raw))
+ if directive == "no-store" {
+ found = true
+ }
+ if directive == "public" || strings.HasPrefix(directive, "s-maxage=") || strings.HasPrefix(directive, "max-age=") {
+ return false
+ }
+ }
+ }
+ return found
+}
diff --git a/internal/home/dashboard_config.go b/internal/home/dashboard_config.go
new file mode 100644
index 0000000..4b8a220
--- /dev/null
+++ b/internal/home/dashboard_config.go
@@ -0,0 +1,109 @@
+package home
+
+import (
+ "amadan.net/oficina/home/dashboard"
+ "github.com/go-json-experiment/json"
+)
+
+type dashboardSource struct {
+ App string `json:"app"`
+ Origin string `json:"origin"`
+}
+type dashboardTeam struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Sources []dashboardSource `json:"sources"`
+ Apps []dashboardSource `json:"apps,omitempty"`
+}
+
+func (t dashboardTeam) launchers() []dashboardSource {
+ if len(t.Apps) > 0 {
+ return t.Apps
+ }
+ return t.Sources
+}
+
+func (s dashboardSource) kind() string {
+ if s.App == "calendar" {
+ return "events"
+ }
+ return "documents"
+}
+func (s dashboardSource) Name() string {
+ for _, a := range directoryApps() {
+ if a.slug == s.App {
+ return a.name
+ }
+ }
+ return ""
+}
+func loadDashboardConfig(cfg *Runtime) error {
+ raw, e := exchangeJSON("HOME_DASHBOARD_TEAMS", 16384)
+ if e != nil {
+ return errExchangeConfig
+ }
+ if raw == "" {
+ return nil
+ }
+ if cfg.role != "directory" && cfg.role != "credential" {
+ return errExchangeConfig
+ }
+ if json.Unmarshal([]byte(raw), &cfg.dashboard, json.RejectUnknownMembers(true)) != nil || len(cfg.dashboard) == 0 || len(cfg.dashboard) > 8 {
+ return errExchangeConfig
+ }
+ teams, origins := map[string]bool{}, map[string]string{}
+ for _, t := range cfg.dashboard {
+ if !dashboard.ValidName(t.ID) || teams[t.ID] || len(t.Name) == 0 || len(t.Name) > 128 || len(t.Sources) == 0 || len(t.Sources) > 4 || len(t.Apps) > 6 {
+ return errExchangeConfig
+ }
+ teams[t.ID] = true
+ apps := map[string]bool{}
+ for _, s := range t.Sources {
+ if s.App != "docs" && s.App != "sheets" && s.App != "slides" && s.App != "calendar" {
+ return errExchangeConfig
+ }
+ if !dashboard.ValidOrigin(s.Origin) || s.Origin == cfg.origins.Credential || s.Origin == cfg.origins.Directory || (origins[s.Origin] != "" && origins[s.Origin] != t.ID) || apps[s.App] {
+ return errExchangeConfig
+ }
+ origins[s.Origin] = t.ID
+ apps[s.App] = true
+ if cfg.role == "credential" {
+ found := false
+ for _, v := range cfg.consumers {
+ if v == s.Origin {
+ found = true
+ }
+ }
+ if !found {
+ return errExchangeConfig
+ }
+ }
+ }
+ launchers := map[string]string{}
+ for _, s := range t.launchers() {
+ if s.Name() == "" || launchers[s.App] != "" || !dashboard.ValidOrigin(s.Origin) || s.Origin == cfg.origins.Credential || s.Origin == cfg.origins.Directory || (origins[s.Origin] != "" && origins[s.Origin] != t.ID) {
+ return errExchangeConfig
+ }
+ launchers[s.App] = s.Origin
+ origins[s.Origin] = t.ID
+ }
+ for _, s := range t.Sources {
+ if launchers[s.App] != s.Origin {
+ return errExchangeConfig
+ }
+ }
+
+ }
+ return nil
+}
+func (a *App) dashboardTeam(id string) (dashboardTeam, bool) {
+ if a.runtime == nil {
+ return dashboardTeam{}, false
+ }
+ for _, t := range a.runtime.dashboard {
+ if t.ID == id {
+ return t, true
+ }
+ }
+ return dashboardTeam{}, false
+}
diff --git a/internal/home/dashboard_exchange.go b/internal/home/dashboard_exchange.go
new file mode 100644
index 0000000..8af81ac
--- /dev/null
+++ b/internal/home/dashboard_exchange.go
@@ -0,0 +1,169 @@
+package home
+
+import (
+ "encoding/base64"
+ "io"
+ "mime"
+ "net/http"
+ "net/url"
+ "time"
+
+ "amadan.net/oficina/home/dashboard"
+ "amadan.net/rastrillo/rastrillo/sessions"
+ "github.com/go-json-experiment/json"
+)
+
+const dashboardCallback = "/dashboard/callback"
+
+const dashboardIntentCookie = "__Host-oficina-dashboard-intent"
+
+type dashboardIntent struct {
+ Team, Nonce string
+ Expires int64
+}
+
+func (a *App) beginDashboard(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "private, no-store")
+ q, e := url.ParseQuery(r.URL.RawQuery)
+ if e != nil || len(q) != 2 || len(q["team"]) != 1 || len(q["nonce"]) != 1 || !dashboard.ValidID(q.Get("nonce")) {
+ http.NotFound(w, r)
+ return
+ }
+ if _, ok := a.dashboardTeam(q.Get("team")); !ok {
+ http.NotFound(w, r)
+ return
+ }
+ b, e := json.Marshal(dashboardIntent{q.Get("team"), q.Get("nonce"), time.Now().Unix() + 300})
+ if e != nil {
+ http.Error(w, "Dashboard unavailable", 503)
+ return
+ }
+ sealed, e := a.secrets.Sealer.Seal("dashboard.intent", b)
+ if e != nil {
+ http.Error(w, "Dashboard unavailable", 503)
+ return
+ }
+ http.SetCookie(w, &http.Cookie{Name: dashboardIntentCookie, Value: base64.RawURLEncoding.EncodeToString(sealed), Path: "/", MaxAge: 300, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
+ http.Redirect(w, r, "/dashboard/resume", http.StatusSeeOther)
+}
+func (a *App) authorizeDashboard(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "private, no-store")
+ value := ""
+ count := 0
+ for _, c := range r.Cookies() {
+ if c.Name == dashboardIntentCookie {
+ value = c.Value
+ count++
+ }
+ }
+ if count != 1 || len(value) > 2048 || r.URL.RawQuery != "" {
+ http.NotFound(w, r)
+ return
+ }
+ sealed, e := base64.RawURLEncoding.Strict().DecodeString(value)
+ if e != nil {
+ http.NotFound(w, r)
+ return
+ }
+ b, e := a.secrets.Sealer.Open("dashboard.intent", sealed)
+ if e != nil {
+ http.NotFound(w, r)
+ return
+ }
+ var intent dashboardIntent
+ if json.Unmarshal(b, &intent, json.RejectUnknownMembers(true)) != nil || !dashboard.ValidID(intent.Nonce) || intent.Expires <= time.Now().Unix() || intent.Expires > time.Now().Unix()+300 {
+ http.NotFound(w, r)
+ return
+ }
+ team, ok := a.dashboardTeam(intent.Team)
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+
+ session, ok := sessions.Current(r)
+ if !ok || !ValidPersonRef(session.Subject) {
+ http.Error(w, "Sign in to continue", 401)
+ return
+ }
+ tokens := map[string]string{}
+ now := time.Now()
+ for _, s := range team.Sources {
+ id, e := dashboard.ID()
+ if e != nil {
+ http.Error(w, "Dashboard unavailable", 503)
+ return
+ }
+ token, e := dashboard.Sign(a.runtime.signer, dashboard.Claims{Version: 1, Issuer: a.origins.Credential, Audience: s.Origin, Directory: a.origins.Directory, Subject: session.Subject, Team: team.ID, Purpose: "dashboard-read", KeyID: a.runtime.keyID, ID: id, Nonce: intent.Nonce, Issued: now.Unix(), Expires: now.Unix() + 120})
+ if e != nil {
+ http.Error(w, "Dashboard unavailable", 503)
+ return
+ }
+ tokens[s.Origin] = token
+ }
+ b, e = json.Marshal(tokens)
+ if e != nil {
+ http.Error(w, "Dashboard unavailable", 503)
+ return
+ }
+ w.Header().Set("Referrer-Policy", "strict-origin")
+ a.render(w, r, 200, "assertion.html", map[string]any{"Action": a.origins.Directory + dashboardCallback, "Token": string(b)})
+}
+func (a *App) receiveDashboard(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "private, no-store")
+ fail := func() { http.Error(w, "Unable to load your dashboard. Return to Oficina and try again.", 400) }
+ if a.dash == nil || len(r.Header.Values("Origin")) != 1 || r.Header.Get("Origin") != a.origins.Credential {
+ fail()
+ return
+ }
+ media, _, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ if e != nil || media != "application/x-www-form-urlencoded" {
+ fail()
+ return
+ }
+ b, e := io.ReadAll(http.MaxBytesReader(w, r.Body, 24576))
+ if e != nil {
+ fail()
+ return
+ }
+ form, e := url.ParseQuery(string(b))
+ if e != nil || len(form) != 1 || len(form["assertion"]) != 1 {
+ fail()
+ return
+ }
+ var tokens map[string]string
+ if json.Unmarshal([]byte(form.Get("assertion")), &tokens) != nil {
+ fail()
+ return
+ }
+ nonce := dashboardNonce(r)
+ if nonce == "" {
+ fail()
+ return
+ }
+ now := time.Now()
+ a.dash.mu.Lock()
+ defer a.dash.mu.Unlock()
+ a.dash.sweep(now)
+ pending, ok := a.dash.pending[nonce]
+ if !ok || pending.Tokens != nil {
+ fail()
+ return
+ }
+ team, ok := a.dashboardTeam(pending.Team)
+ if !ok || len(tokens) != len(team.Sources) {
+ fail()
+ return
+ }
+ for _, s := range team.Sources {
+ c, e := dashboard.Verify(tokens[s.Origin], a.origins.Credential, s.Origin, a.origins.Directory, team.ID, a.runtime.keys, now)
+ if e != nil || c.Subject != pending.Subject || c.Nonce != nonce {
+ fail()
+ return
+ }
+ }
+ pending.Tokens = tokens
+ pending.Expires = now.Add(120 * time.Second)
+ a.dash.pending[nonce] = pending
+ http.Redirect(w, r, "/?"+url.Values{"team": {team.ID}, "dashboard": {nonce}}.Encode(), http.StatusSeeOther)
+}
diff --git a/internal/home/dashboard_preference.go b/internal/home/dashboard_preference.go
new file mode 100644
index 0000000..448b42c
--- /dev/null
+++ b/internal/home/dashboard_preference.go
@@ -0,0 +1,57 @@
+package home
+
+import (
+ "encoding/base64"
+ "net/http"
+
+ "amadan.net/oficina/home/dashboard"
+ "github.com/go-json-experiment/json"
+)
+
+const dashboardTeamCookie = "__Host-oficina-dashboard-team"
+
+type dashboardPreference struct{ Session, Team string }
+
+func (a *App) selectedDashboardTeam(r *http.Request, session string) (string, bool) {
+ count := 0
+ value := ""
+ for _, c := range r.Cookies() {
+ if c.Name == dashboardTeamCookie {
+ count++
+ value = c.Value
+ }
+ }
+ if count == 0 {
+ return "", true
+ }
+ if count != 1 || len(value) > 2048 {
+ return "", false
+ }
+ b, e := base64.RawURLEncoding.Strict().DecodeString(value)
+ if e != nil {
+ return "", false
+ }
+ plain, e := a.secrets.Sealer.Open("dashboard.team", b)
+ if e != nil {
+ return "", false
+ }
+ var p dashboardPreference
+ if json.Unmarshal(plain, &p, json.RejectUnknownMembers(true)) != nil || !dashboard.ValidName(p.Team) {
+ return "", false
+ }
+ if p.Session != base64.RawURLEncoding.EncodeToString([]byte(session)) {
+ return "", true
+ }
+ return p.Team, true
+}
+func (a *App) rememberDashboardTeam(w http.ResponseWriter, session, team string) {
+ b, e := json.Marshal(dashboardPreference{base64.RawURLEncoding.EncodeToString([]byte(session)), team})
+ if e != nil {
+ return
+ }
+ sealed, e := a.secrets.Sealer.Seal("dashboard.team", b)
+ if e != nil {
+ return
+ }
+ http.SetCookie(w, &http.Cookie{Name: dashboardTeamCookie, Value: base64.RawURLEncoding.EncodeToString(sealed), Path: "/", MaxAge: 30 * 24 * 3600, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
+}
diff --git a/internal/home/dashboard_state.go b/internal/home/dashboard_state.go
new file mode 100644
index 0000000..af5f74a
--- /dev/null
+++ b/internal/home/dashboard_state.go
@@ -0,0 +1,89 @@
+package home
+
+import (
+ "crypto/sha256"
+ "net/http"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/home/dashboard"
+ "amadan.net/rastrillo/rastrillo/sessions"
+)
+
+const dashboardCookie = "__Host-oficina-dashboard"
+
+type dashboardPending struct {
+ Subject, Team, Session string
+ Expires time.Time
+ Tokens map[string]string
+}
+type dashboardResult struct {
+ Source dashboardSource
+ Response dashboard.Response
+ Status string
+}
+type dashboardCache struct {
+ Results []dashboardResult
+ At time.Time
+}
+type dashboardState struct {
+ mu sync.Mutex
+ pending map[string]dashboardPending
+ cache map[string]dashboardCache
+ slots chan struct{}
+ client *http.Client
+}
+
+func newDashboardState() *dashboardState {
+ return &dashboardState{pending: map[string]dashboardPending{}, cache: map[string]dashboardCache{}, slots: make(chan struct{}, 16), client: &http.Client{Timeout: 3 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
+}
+
+// Sweep every access; hard expiry is independent of whether a source recovers.
+func (d *dashboardState) sweep(now time.Time) {
+ for k, v := range d.pending {
+ if !now.Before(v.Expires) {
+ delete(d.pending, k)
+ }
+ }
+ for k, v := range d.cache {
+ if now.Sub(v.At) >= 120*time.Second {
+ delete(d.cache, k)
+ }
+ }
+}
+func (a *App) dashboardSession(r *http.Request) (string, string, bool) {
+ s, ok := sessions.Current(r)
+ if !ok || !ValidPersonRef(s.Subject) {
+ return "", "", false
+ }
+ count := 0
+ value := ""
+ for _, c := range r.Cookies() {
+ if c.Name == a.sessions.CookieName() {
+ count++
+ value = c.Value
+ }
+ }
+ if count != 1 || value == "" {
+ return "", "", false
+ }
+ h := sha256.Sum256([]byte(value))
+ return s.Subject, string(h[:]), true
+}
+func dashboardCacheKey(subject, session, team string) string {
+ return subject + "\x00" + session + "\x00" + team
+}
+func dashboardNonce(r *http.Request) string {
+ count := 0
+ v := ""
+ for _, c := range r.Cookies() {
+ if c.Name == dashboardCookie {
+ count++
+ v = c.Value
+ }
+ }
+ if count != 1 || !dashboard.ValidID(v) {
+ return ""
+ }
+ return v
+}
diff --git a/internal/home/dashboard_test.go b/internal/home/dashboard_test.go
new file mode 100644
index 0000000..a065598
--- /dev/null
+++ b/internal/home/dashboard_test.go
@@ -0,0 +1,204 @@
+package home
+
+import (
+ "context"
+ "html"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/home/dashboard"
+ "amadan.net/oficina/home/internal/home/sealtest"
+ "github.com/go-json-experiment/json"
+)
+
+type dashboardTransport func(*http.Request) (*http.Response, error)
+
+func (f dashboardTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+func dashboardTestBody(t *testing.T, v any) string {
+ t.Helper()
+ b, e := json.Marshal(v)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return string(b)
+}
+func dashboardTestResponse(body string) *http.Response {
+ return &http.Response{StatusCode: 200, Header: http.Header{"Cache-Control": {"private, no-store"}}, Body: io.NopCloser(strings.NewReader(body))}
+}
+
+func TestDashboardExchangeIsolationAndPrivacy(t *testing.T) {
+ p := newExchangePair(t)
+ credentialSession := signInFully(t, p.credential, sealtest.CanaryAddress)
+ pending, intent := p.start(t)
+ token, _ := p.mint(t, intent, credentialSession)
+ directorySession := p.finish(t, token, pending)
+ teams := []dashboardTeam{{ID: "blue", Name: "Blue", Sources: []dashboardSource{{"docs", "https://blue.docs.oficina.works"}}}, {ID: "red", Name: "Red", Sources: []dashboardSource{{"docs", "https://red.docs.oficina.works"}}}}
+ p.directory.runtime.dashboard = teams
+ p.credential.runtime.dashboard = teams
+ subject := subjectOf(t, p.credential, credentialSession)
+ calls := 0
+ p.directory.dash.client.Transport = dashboardTransport(func(r *http.Request) (*http.Response, error) {
+ calls++
+ if r.URL.Host != "red.docs.oficina.works" {
+ t.Error("crossed selected team")
+ }
+ c, e := dashboard.Verify(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "), Origin, "https://red.docs.oficina.works", directoryOrigin, "red", p.credential.runtime.keys, time.Now())
+ if e != nil || c.Subject != subject {
+ t.Error("invalid source authority")
+ }
+ return dashboardTestResponse(dashboardTestBody(t, dashboard.Response{Version: 1, Team: "red", Kind: "documents", Items: []dashboard.Item{{ID: "one", Title: "Dashboard private title <script>", URL: "https://red.docs.oficina.works/d/private-canary", Updated: time.Now()}}})), nil
+ })
+ start := exchangeRequest(p.directory, "GET", directoryOrigin+"/?team=red", "", nil, directorySession)
+ if start.Code != 303 {
+ t.Fatal("start", start.Code)
+ }
+ nonce := namedCookie(t, start, dashboardCookie)
+ preference := namedCookie(t, start, dashboardTeamCookie)
+ begin := exchangeRequest(p.credential.App, "GET", start.Header().Get("Location"), "", nil)
+ dashboardIntent := namedCookie(t, begin, dashboardIntentCookie)
+ unsigned := exchangeRequest(p.credential.App, "GET", Origin+"/dashboard/resume", "", nil, dashboardIntent)
+ if unsigned.Code != 303 {
+ t.Fatal("missing sign-in gate", unsigned.Code)
+ }
+ signin := exchangeRequest(p.credential.App, "GET", Origin+unsigned.Header().Get("Location"), "", nil, dashboardIntent)
+ if namedCookie(t, signin, returnCookie).Value != "/dashboard/resume" {
+ t.Fatal("lost sign-in return")
+ }
+ minted := exchangeRequest(p.credential.App, "GET", Origin+"/dashboard/resume", "", nil, dashboardIntent, credentialSession)
+ if minted.Code != 200 {
+ t.Fatal("mint", minted.Code)
+ }
+ m := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(minted.Body.String())
+ if len(m) != 2 {
+ t.Fatal("no form")
+ }
+ form := url.Values{"assertion": {html.UnescapeString(m[1])}}
+ for _, origin := range []string{"", "https://evil.invalid"} {
+ if rec := exchangeRequest(p.directory, "POST", directoryOrigin+dashboardCallback, origin, form, nonce); rec.Code != 400 {
+ t.Fatal("accepted wrong origin")
+ }
+ }
+ if rec := exchangeRequest(p.directory, "POST", directoryOrigin+dashboardCallback, Origin, form, nonce, nonce); rec.Code != 400 {
+ t.Fatal("accepted duplicate cookie")
+ }
+ callback := exchangeRequest(p.directory, "POST", directoryOrigin+dashboardCallback, Origin, form, nonce)
+ if callback.Code != 303 {
+ t.Fatal("callback", callback.Code)
+ }
+ if rec := exchangeRequest(p.directory, "POST", directoryOrigin+dashboardCallback, Origin, form, nonce); rec.Code != 400 {
+ t.Fatal("callback replay")
+ }
+ finishURL := directoryOrigin + callback.Header().Get("Location")
+ if rec := exchangeRequest(p.directory, "GET", strings.Replace(finishURL, "team=red", "team=blue", 1), "", nil, nonce, directorySession); rec.Code != 400 {
+ t.Fatal("team substitution", rec.Code)
+ }
+ if rec := exchangeRequest(p.directory, "GET", finishURL, "", nil, nonce, directorySession, directorySession); rec.Code != 400 {
+ t.Fatal("ambiguous session")
+ }
+ finish := exchangeRequest(p.directory, "GET", finishURL, "", nil, nonce, directorySession)
+ if finish.Code != 303 || calls != 1 {
+ t.Fatal("finish", finish.Code, calls)
+ }
+ if rec := exchangeRequest(p.directory, "GET", finishURL, "", nil, nonce, directorySession); rec.Code != 400 {
+ t.Fatal("finish replay")
+ }
+ page := exchangeRequest(p.directory, "GET", directoryOrigin+"/", "", nil, directorySession, preference)
+ if page.Code != 200 || !strings.Contains(page.Body.String(), "Dashboard private title &lt;script&gt;") || strings.Contains(page.Body.String(), "https://blue.docs.oficina.works/") || calls != 1 {
+ t.Fatal("selection, rendering, or cache failed", page.Code)
+ }
+ if refresh := exchangeRequest(p.directory, "GET", directoryOrigin+"/?refresh=1", "", nil, directorySession, preference); refresh.Code != 303 {
+ t.Fatal("refresh reused cached result")
+ }
+ if strings.Contains(page.Body.String(), "Nothing scheduled") {
+ t.Fatal("unconfigured calendar looks empty")
+ }
+ for _, path := range []string{p.credential.dbPath, p.directoryPath} {
+ for _, suffix := range []string{"", "-wal"} {
+ b, e := os.ReadFile(path + suffix)
+ if e != nil {
+ t.Fatal(e)
+ }
+ for _, canary := range []string{"Dashboard private title", "private-canary", form.Get("assertion")} {
+ if strings.Contains(string(b), canary) {
+ t.Fatal("content retained on disk")
+ }
+ }
+ }
+ }
+ if strings.Contains(p.logs.String(), "private title") || strings.Contains(p.logs.String(), "private-canary") {
+ t.Fatal("content logged")
+ }
+ p.directory.dash.mu.Lock()
+ p.directory.dash.sweep(time.Now().Add(121 * time.Second))
+ n := len(p.directory.dash.cache)
+ p.directory.dash.mu.Unlock()
+ if n != 0 {
+ t.Fatal("hard expiry")
+ }
+}
+
+func TestDashboardPullRejectsInvalidSourceData(t *testing.T) {
+ p := newExchangePair(t)
+ source := dashboardSource{"docs", "https://blue.docs.oficina.works"}
+ team := dashboardTeam{ID: "blue", Sources: []dashboardSource{source}}
+ good := dashboardTestBody(t, dashboard.Response{Version: 1, Team: "blue", Kind: "documents", Items: []dashboard.Item{}})
+ cases := []struct {
+ name, body, cache string
+ status int
+ }{
+ {"valid", good, "private, no-store", 200},
+ {"missing items", `{"v":1,"team":"blue","kind":"documents"}`, "no-store", 200},
+ {"wrong team", strings.Replace(good, "blue", "red", 1), "no-store", 200},
+ {"oversized", strings.Repeat("x", dashboard.MaxBody+1), "no-store", 200},
+ {"malformed", "{", "no-store", 200},
+ {"cacheable", good, "public, no-store", 200},
+ {"fake cache directive", good, "x-no-store", 200},
+ {"redirect", good, "no-store", 302},
+ {"disconnected", "", "no-store", 403},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ p.directory.dash.client.Transport = dashboardTransport(func(r *http.Request) (*http.Response, error) {
+ res := dashboardTestResponse(tc.body)
+ res.StatusCode = tc.status
+ res.Header.Set("Cache-Control", tc.cache)
+ res.Header.Set("Location", "https://evil.invalid")
+ return res, nil
+ })
+ got := p.directory.pullDashboard(context.Background(), team, map[string]string{source.Origin: "token"})
+ if len(got) != 1 || (got[0].Status == "") != (tc.name == "valid") {
+ t.Fatal("incorrect provider state")
+ }
+ })
+ }
+}
+
+func TestDashboardCacheDirectives(t *testing.T) {
+ for _, s := range []string{"x-no-store", "public, no-store", "no-store, max-age=1", "no-store, s-maxage=1", "no-store=1"} {
+ if dashboardNoStore([]string{s}) {
+ t.Fatal("accepted", s)
+ }
+ }
+ if !dashboardNoStore([]string{"private", "NO-STORE"}) {
+ t.Fatal("rejected no-store")
+ }
+}
+
+func TestDashboardDuplicateOriginRefused(t *testing.T) {
+ p := newExchangePair(t)
+ r := httptest.NewRequest("POST", directoryOrigin+dashboardCallback, strings.NewReader("assertion=x"))
+ r.Header["Origin"] = []string{Origin, Origin}
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ w := httptest.NewRecorder()
+ p.directory.Router().ServeHTTP(w, r)
+ if w.Code != 400 {
+ t.Fatal(w.Code)
+ }
+}
diff --git a/internal/home/directory.go b/internal/home/directory.go
index 3c06ed7..8be4069 100644
--- a/internal/home/directory.go
+++ b/internal/home/directory.go
@@ -54,6 +54,7 @@ func newDirectory(cfg Runtime, d *db.DB, logger *slog.Logger) (*App, error) {
if err != nil {
return nil, err
}
+ a.dash = newDashboardState()
a.directory, err = a.newDirectoryFeatures()
if err != nil {
return nil, err
@@ -74,6 +75,7 @@ func (a *App) directoryRouter() http.Handler {
// This callback alone accepts a cross-origin POST, with its own exact issuer
// check and browser-bound finish. Every other mutation retains CSRF protection.
r.Post(handoff.CallbackPath, a.consumer.Callback)
+ r.Post(dashboardCallback, a.receiveDashboard)
r.Group(func(r chi.Router) {
r.Use(csrf.Protect(a.origins.Directory))
for _, chooser := range a.directory.choosers {
@@ -108,7 +110,7 @@ func (a *App) directoryRouter() http.Handler {
a.handleIndex(w, r)
return
}
- a.render(w, r, 200, "directory.html", map[string]any{"Apps": directoryCatalog(*a.runtime)})
+ a.handleDashboard(w, r)
})
// The account menu's Appearance (spec §8.3): inside Protect, outside
// any session requirement, so a session that expired mid-page does
diff --git a/internal/home/runtime.go b/internal/home/runtime.go
index 7c0d792..ecd6f39 100644
--- a/internal/home/runtime.go
+++ b/internal/home/runtime.go
@@ -24,6 +24,7 @@ var errExchangeConfig = errors.New("home: invalid assertion configuration")
var directorySchema = migrate.Merge(sessions.Schema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff"), directorydata.Schema, directorydata.RosterSchema)
type Runtime struct {
+ dashboard []dashboardTeam
docsPreviewOrigin string
appPreviewOrigins map[string]string
roster rosterRuntime
@@ -148,6 +149,9 @@ func LoadRuntime(dbPath string, logger *slog.Logger) (Runtime, error) {
default:
return Runtime{}, errExchangeConfig
}
+ if err := loadDashboardConfig(&cfg); err != nil {
+ return Runtime{}, err
+ }
return cfg, nil
}
func consumerName(s string) bool {
diff --git a/internal/home/signin_return.go b/internal/home/signin_return.go
index 8363b65..05e08fc 100644
--- a/internal/home/signin_return.go
+++ b/internal/home/signin_return.go
@@ -11,7 +11,7 @@ const returnTTL = 10 * time.Minute
func credentialReturn(value string) string {
switch value {
- case "/passkey/enrol", "/passkey/codes", "/authorize/resume":
+ case "/passkey/enrol", "/passkey/codes", "/authorize/resume", "/dashboard/resume":
return value
}
return "/"
diff --git a/internal/home/static/calma.css b/internal/home/static/calma.css
index 0e54152..11f2973 100644
--- a/internal/home/static/calma.css
+++ b/internal/home/static/calma.css
@@ -84,3 +84,22 @@ div[home-app] img { filter: saturate(0.6); opacity: 0.8; }
/* The team chooser: one button per team, stacked. */
[home-teams] { display: grid; justify-items: start; gap: var(--rst-sp-2); }
+
+/* The selected team's work takes priority over its compact app launcher. */
+[home-apps-compact] { grid-template-columns: repeat(auto-fit, minmax(95px, 1fr)); gap: 8px; margin-bottom: 32px; }
+[home-apps-compact] [home-app] { padding: 12px 8px; gap: 5px; border-radius: 12px; }
+[home-apps-compact] img { margin: 0; }
+[home-apps-compact] small { font-size: .75rem; }
+[home-dashboard] { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); gap: 40px; }
+[home-dashboard] h2 { margin: 0 0 16px; }
+[home-recent] { margin: 0; padding: 0; list-style: none; }
+[home-recent] li { border-bottom: 1px solid var(--rst-line); }
+[home-recent] a { display: flex; flex-direction: column; gap: 5px; padding: 15px 8px; color: var(--rst-text); text-decoration: none; overflow-wrap: anywhere; border-radius: 8px; }
+[home-recent] a:hover { background: var(--rst-surface); }
+[home-recent] span, [home-recent] time, [home-dashboard-note] { color: var(--rst-text-muted); font-size: .875rem; }
+[home-dashboard-note] { line-height: 1.6; }
+[home-dashboard-sources] { border-top: 1px solid var(--rst-line); margin-top: 32px; padding-top: 16px; font-size: .875rem; }
+[home-team-nav] { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 16px; }
+[home-team-nav] a { padding: 8px 12px; border-radius: 8px; }
+[home-team-nav] [aria-current] { background: var(--rst-surface); font-weight: 650; }
+@media (max-width: 700px) { [home-dashboard] { grid-template-columns: minmax(0, 1fr); gap: 32px; } }
diff --git a/internal/home/templates/dashboard.html b/internal/home/templates/dashboard.html
new file mode 100644
index 0000000..6c8b966
--- /dev/null
+++ b/internal/home/templates/dashboard.html
@@ -0,0 +1,35 @@
+{{define "title"}}{{.Data.Team.Name}} · Oficina{{end}}
+{{define "content"}}
+<header home-hub-head estilo-sky-host>
+{{template "estilo-sky" suiteSky}}
+<h1>{{.Data.Team.Name}}</h1>
+<p home-hub-lede>Your recent work and what’s coming up.</p>
+{{if gt (len .Data.Teams) 1}}<nav home-team-nav aria-label="Teams">{{range .Data.Teams}}<a href="/?team={{.ID}}" {{if eq .ID $.Data.Team.ID}}aria-current="page"{{end}}>{{.Name}}</a>{{end}}</nav>{{end}}
+</header>
+<nav aria-label="Apps"><ul home-apps home-apps-compact>
+{{range .Data.Apps}}<li>{{if .Href}}<a home-app href="{{.Href}}">{{else}}<div home-app>{{end}}
+<img src="{{.Icon}}" alt="" width="28" height="28"><b>{{.Name}}</b>
+{{if not .Href}}<small>{{.Status}}</small>{{end}}
+{{if .Href}}</a>{{else}}</div>{{end}}</li>{{end}}
+</ul></nav>
+<div home-dashboard>
+<section aria-labelledby="recent-heading">
+<h2 id="recent-heading">Recent documents</h2>
+{{if .Data.Documents}}<ul home-recent>{{range .Data.Documents}}
+<li><a href="{{.URL}}"><b><bdi>{{if .Title}}{{.Title}}{{else}}Untitled{{end}}</bdi></b><span>{{.App}} · <time datetime="{{.DateTime}}">{{.When}}</time></span></a></li>
+{{end}}</ul>{{else if .Data.DocumentsComplete}}<p>No recent documents yet. Open an app to get started.</p>{{else}}<p>Your recent documents will appear here when the apps are connected and available.</p>{{end}}
+<p home-dashboard-note>The 20 most recently updated documents across your connected apps. Open an app for its full list.</p>
+</section>
+<section aria-labelledby="agenda-heading">
+<h2 id="agenda-heading">Coming up</h2>
+<p home-dashboard-note>Today and the next seven days.</p>
+{{if .Data.Events}}<ul home-recent>{{range .Data.Events}}
+<li><a href="{{.URL}}"><time datetime="{{.DateTime}}">{{.When}}</time><b><bdi>{{if .Title}}{{.Title}}{{else}}Untitled event{{end}}</bdi></b><span><bdi>{{.Calendar}}</bdi></span></a></li>
+{{end}}</ul>{{else if .Data.EventsComplete}}<p>Nothing scheduled in this window.</p>{{else}}<p>Your agenda is unavailable right now.</p>{{end}}
+</section>
+</div>
+<section home-dashboard-sources aria-label="Connected apps">
+{{range .Data.Sources}}{{if .Status}}<p><b>{{.Source.Name}}</b>: {{.Status}} <a href="{{.Source.Origin}}/">Open {{.Source.Name}}</a></p>{{else if .Response.Truncated}}<p><a href="{{.Source.Origin}}/">More in {{.Source.Name}}</a></p>{{end}}{{end}}
+<p><a href="/?team={{.Data.Team.ID}}&amp;refresh=1">Refresh dashboard</a></p>
+</section>
+{{end}}