Add purpose-bound dashboard read tokens and durable replay protection
7 files changed,
+459
−0
connect/dashboard/migrations/0001_dashboard.sql+4 −0connect/dashboard/provider.go+85 −0connect/dashboard/replay.go+51 −0connect/dashboard/token.go+102 −0connect/dashboard/token_test.go+115 −0connect/dashboard/wire.go+68 −0docs/superpowers/specs/2026-10-24-dashboard-design.md+34 −0
CI cancelled — superseded by a newer push — run details
diff --git a/connect/dashboard/migrations/0001_dashboard.sql b/connect/dashboard/migrations/0001_dashboard.sql| new file mode 100644 |
| index 0000000..025a65f |
| --- /dev/null |
| +++ b/connect/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/connect/dashboard/provider.go b/connect/dashboard/provider.go| new file mode 100644 |
| index 0000000..a776f6f |
| --- /dev/null |
| +++ b/connect/dashboard/provider.go |
| @@ -0,0 +1,85 @@ |
| +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, time.Time) (Response, error) |
| +} |
| + |
| +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, 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") |
| + _, _ = w.Write(b) |
| + }), nil |
| +} |
diff --git a/connect/dashboard/replay.go b/connect/dashboard/replay.go| new file mode 100644 |
| index 0000000..e4433f5 |
| --- /dev/null |
| +++ b/connect/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/connect/dashboard/token.go b/connect/dashboard/token.go| new file mode 100644 |
| index 0000000..138703e |
| --- /dev/null |
| +++ b/connect/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/connect/dashboard/token_test.go b/connect/dashboard/token_test.go| new file mode 100644 |
| index 0000000..78ca8af |
| --- /dev/null |
| +++ b/connect/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/connect/dashboard/wire.go b/connect/dashboard/wire.go| new file mode 100644 |
| index 0000000..42855ec |
| --- /dev/null |
| +++ b/connect/dashboard/wire.go |
| @@ -0,0 +1,68 @@ |
| +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 || len(r.Items) > MaxItems || (kind != "documents" && kind != "events") { |
| + return false |
| + } |
| + if kind == "events" { |
| + 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| index 1edf5e6..e214b5c 100644 |
| --- a/docs/superpowers/specs/2026-10-24-dashboard-design.md |
| +++ b/docs/superpowers/specs/2026-10-24-dashboard-design.md |
| @@ -130,3 +130,37 @@ 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. |