oficina / equipo Public

feat: add the Teams directory and web navigation hierarchy

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev f6df0cf4c1035a4422b0923562a69139da40ccde parent 334dd73
31 files changed, +1,147 −104
  • .rastrillo/budgets.txt +1 −1
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +53 −0
  • internal/equipo/app.go +5 −4
  • internal/equipo/auth.go +22 −77
  • internal/equipo/conversation_handlers.go +1 −1
  • internal/equipo/copy.go +27 −0
  • internal/equipo/handlers.go +1 −0
  • internal/equipo/library/navigation.go +16 −0
  • internal/equipo/library_handlers.go +4 −1
  • internal/equipo/migrations/0029_team_links.sql +9 −0
  • internal/equipo/migrations/schema.sql +10 −0
  • internal/equipo/preferences.go +1 −1
  • internal/equipo/render.go +1 −1
  • internal/equipo/setup/invites.go +4 −1
  • internal/equipo/setup/session_handlers.go +172 −0
  • internal/equipo/setup/team_link_handlers.go +97 −0
  • internal/equipo/setup/team_links.go +237 −0
  • internal/equipo/static/equipo.css +19 −0
  • internal/equipo/task_page_handlers.go +2 −4
  • internal/equipo/team_links.go +28 −0
  • internal/equipo/templates/chrome.html +4 −1
  • internal/equipo/templates/index.html +3 −1
  • internal/equipo/templates/layout.html +4 −3
  • internal/equipo/templates/playbooks.html +1 −1
  • internal/equipo/templates/task.html +2 −0
  • internal/equipo/templates/teams.html +27 −0
  • internal/equipo/templates/thread.html +1 −0
  • internal/equipotest/pages_test.go +7 −7
  • internal/plan3test/teams_migration_test.go +51 −0
  • internal/plan3test/teams_navigation_browser_test.go +79 −0
  • internal/plan3test/teams_navigation_test.go +258 −0

CI failed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 0e445204..ecc769b8 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -28,4 +28,4 @@ time internal/runner/provider/codex 15s Task 11a full branch gate measured 11.65
time internal/directlive 360s Task 5 adds both coordinator policy cases to the fake certification matrix. The targeted 19-case fixture measured 287.275s; 360s leaves 25 percent headroom for namespaces, both adapters, journal, MCP probes and package siblings. Full-package timing is deferred by the targeted-only dispatch.
time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops.
-size internal/plan3test - 8600 Task 17 adds account setup authority, secret projection, migration and onboarding regressions beside the shared fixture harness. Measured 8331 test lines; source remains within the default. The existing 300s integration time ceiling is unchanged.
+size internal/plan3test - 9000 Task 18 adds private Teams directory, sign-in, migration and scriptless browser navigation regressions in the mandated integration package. Measured 8774 test lines and 741 source lines; the existing 300s time ceiling is unchanged.
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index 491f4a30..0f3c6f53 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -4426,3 +4426,56 @@ All new or renamed runtime entries below are individually marked `COPY REVIEW RE
- `internal/runnerproto/account_setup.go`
- `docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md` (this appended fix-round report).
- `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-17-report.md` (full local report, ignored by git).
+
+## Task 18
+
+Implemented the private Teams link directory, verified local sign-in remembering, and Teams → team → page → task/thread navigation. The existing Task 8 landing setting is reused; sign-in defaults pass through it and explicit deep links retain their destination. Remote links grant no authority, trigger no server fetch and expose no remote counts.
+
+### TDD and verification
+
+- RED: `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestTeams' -count=1`, exit 1 before implementation: `f.Store.RememberTeam undefined` and `undefined: equipo.TeamLink`. The browser-tagged version also failed on the missing interfaces.
+- Additional RED: `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestTeamsInvitedSignIn$' -count=1`, exit 1: `accepted verified invite did not remember current team []`. Invitation acceptance now remembers the current instance in the same transaction after joining.
+- Intermediate failures were resolved: Preferences used the Settings parent; Playbooks lost its navigation key; the old rail test expected 12 links; the browser clicked during a CSS page transition. The browser test disables page scripts and uses reduced motion, with a 10-second limit for each drive step. Chromium was present, so no browser coverage was skipped.
+- The size check initially failed at 10,943 root source lines and 8,774 integration test lines. Session/auth composition moved into `setup`, and count projection moved into its feature packages. The root now has 10,797 source lines under its unchanged 10,800 cap. The integration exception is 9,000 test lines for 8,774 measured lines; its 300s time allowance is unchanged. Setup has 2,459 source/318 test lines; library has 2,525 source/10 test lines; plan3test has 741 source lines.
+- Staticcheck initially found ST1005 on two existing reviewed auth errors after extraction. Restored the existing copy-specific lint exception; the final run is clean.
+
+| Final command | Exit | Result |
+| --- | --- | --- |
+| `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestTeams' -count=1` | 0 | ok amadan.net/oficina/equipo/internal/plan3test 3.078s |
+| `CGO_ENABLED=0 go test -tags browser ./internal/plan3test -run '^(TestTeamsHierarchyBrowser\|TestConversationLayout)$' -count=1` | 0 | ok amadan.net/oficina/equipo/internal/plan3test 4.665s |
+| `CGO_ENABLED=0 go test ./internal/equipotest -run '^(TestRailRoutes\|TestTaskLayoutRules\|TestVendoredAssetsMatchTheLibrary\|TestTaskPagesUnknownCounts\|TestSigninAdmission\|TestSigninCSRF\|TestAuthProductionConfig\|TestSigninNoProof)$' -count=1` | 0 | ok amadan.net/oficina/equipo/internal/equipotest 11.258s |
+| `make migration-check && CGO_ENABLED=0 go test ./internal/equipo -run '^TestConversationMigrationSnapshot$' -count=1` | 0 | CGO_ENABLED=0 go test ./internal/equipo -run '^TestMigrationModels$' -count=1; ok amadan.net/oficina/equipo/internal/equipo 0.602s; ok amadan.net/oficina/equipo/internal/equipo 3.146s |
+| `CGO_ENABLED=0 go vet ./internal/equipo ./internal/equipo/setup ./internal/equipo/library ./internal/equipotest ./internal/plan3test && CGO_ENABLED=0 go vet -tags browser ./internal/plan3test` | 0 | No diagnostics |
+| `CGO_ENABLED=0 go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./internal/equipo ./internal/equipo/setup ./internal/equipo/library ./internal/equipotest ./internal/plan3test && CGO_ENABLED=0 go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 -tags browser ./internal/plan3test` | 0 | Final rerun after restoring the existing ST1005 copy exception: exit 0, no diagnostics. |
+| `make budget && gofmt -l internal/equipo/*.go internal/equipo/setup/*.go internal/equipo/library/*.go internal/plan3test/*.go internal/equipotest/*.go && git diff --check` | 0 | go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size; budget size: 34 directories within budget |
+
+Additional regression: `CGO_ENABLED=0 go test ./internal/plan3test -run '^(TestTeams|TestInvite|TestPreferences|TestConversationScriptless)' -count=1`, exit 0 (11.718s) after session extraction. No full suite, `make ci`, provider run, provider sign-in, enrolment, merge, push or deployment ran.
+
+### Guard mutations
+
+Each mutation ran separately against the named targeted command, failed an assertion with exit 1, and was restored immediately. All 12 were repeated after the session/count extraction. The final Teams and browser commands above passed with every mutation restored.
+
+| Guard broken | Command | Failure observed | Restored |
+| --- | --- | --- | --- |
+| HTTPS remote origins | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestTeamsDirectoryPrivacy$ -count=1` | teams_navigation_test.go:46: unsafe origin "http://remote.example": <nil>; teams_navigation_test.go:46: unsafe origin "//remote.example": <nil> | Yes |
+| userinfo forbidden | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestTeamsDirectoryPrivacy$ -count=1` | teams_navigation_test.go:46: unsafe origin "https://user:password@remote.example": <nil> | Yes |
+| private directory | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestTeamsDirectoryPrivacy$ -count=1` | teams_navigation_test.go:68: private directory leaked [{6QAUMVIK5WYGUWW2QRHUFSZ5AZ https://remote.example Private team <nil> 1}] | Yes |
+| untrusted timestamp | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestTeamsDirectoryPrivacy$ -count=1` | teams_navigation_test.go:51: trusted submitted sign-in time <nil> | Yes |
+| current membership | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestTeamsDirectoryPrivacy$ -count=1` | teams_navigation_test.go:91: got <nil>, want You do not have access to this page. Ask an owner for access. | Yes |
+| update revision | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestTeamsDirectoryPrivacy$ -count=1` | teams_navigation_test.go:79: got <nil>, want This record changed. Reload the page and try again. | Yes |
+| transaction audit | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestTeamsTransactionGuards$ -count=1` | teams_navigation_test.go:211: write ignored audit failure | Yes |
+| phone task parent | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestTeamsHierarchy$ -count=1` | teams_navigation_test.go:27: /tasks/FONUZDR3QUGO4QNBZJNM5UYF76 missing parent /journey | Yes |
+| unknown current count | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestTeamsUnavailableCounts$ -count=1` | teams_navigation_test.go:139: missing unknown state "Counts unavailable"; teams_navigation_test.go:143: unknown count rendered as zero | Yes |
+| landing after sign-in | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestTeamsLandingPreference$ -count=1` | teams_navigation_test.go:152: sign-in bypasses landing preference /conversation | Yes |
+| verified current instance | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestTeamsLandingPreference$ -count=1` | teams_navigation_test.go:160: verified instance not remembered [] | Yes |
+| origin timestamp binding | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestTeamsTransactionGuards$ -count=1` | teams_navigation_test.go:228: new origin inherited verified timestamp | Yes |
+
+### Self-review and remaining limits
+
+All link operations scope records to the verified person and recheck the current roster inside the transaction, including retries. A failed audit rolls back the link and request record. Origins reject userinfo, query strings, fragments, paths, script schemes and non-HTTPS remote addresses. The configured loopback instance is the sole HTTP exception. Submitted sign-in times are rejected, and changing an origin clears its verified time. Browser responses use no-store and remote links suppress referrers.
+
+Migration 0029 adds only the app-owned team_links table and its unique person/origin index. Model/schema parity, upgrade preservation of Task 8 settings and idempotent reapplication passed. Vendored static assets remain byte-identical. README prose is unchanged.
+
+Remote membership and sign-in cannot be verified across independent origins; manually added links retain an unknown last sign-in and unavailable remote status. The directory is local to this instance and person. Automatic cross-origin discovery and aggregate remote Needs you remain outside Task 18. All 13 new copy entries are individually marked COPY REVIEW REQUIRED in copy.go; approval remains for the controller’s copy pass.
+
+Full report: `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-18-report.md`.
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index 3b4377bf..88f15db9 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -162,11 +162,11 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
a.Post("/api/enrolments", a.beginEnrolment)
a.Post("/api/enrolments/token", a.exchangeEnrolment)
a.Mount("/api/runner/v2", runner)
- a.Get("/signin", func(w http.ResponseWriter, r *http.Request) { renderSignin(a.auth, w, r) })
+ a.Get("/signin", a.store.sessionHandler(a.auth).Signin)
a.Post("/auth/begin", a.auth.Begin)
- a.Get("/auth/callback", a.auth.Callback)
- a.Get("/auth/verify", a.auth.Verify)
- a.Post("/auth/verify", a.auth.Verify)
+ a.Get("/auth/callback", a.rememberSignIn(a.auth.Callback))
+ a.Get("/auth/verify", a.rememberSignIn(a.auth.Verify))
+ a.Post("/auth/verify", a.rememberSignIn(a.auth.Verify))
a.Post("/auth/forget", a.auth.Forget)
a.Post("/signout", a.auth.Signout)
ih := a.invitationHandler()
@@ -190,6 +190,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
r.Post("/settings/recovery/release", a.releaseRecovery)
r.Get("/", a.preferenceHandler().Landing)
a.preferenceHandler().Routes(r)
+ a.teamLinkHandler().Routes(r)
a.onboardingHandler().Routes(r)
a.conversationHandler().Routes(r)
a.planHandler().Routes(r)
diff --git a/internal/equipo/auth.go b/internal/equipo/auth.go
index d86d85f3..603a7ada 100644
--- a/internal/equipo/auth.go
+++ b/internal/equipo/auth.go
@@ -1,15 +1,15 @@
package equipo
import (
+ "amadan.net/oficina/equipo/internal/equipo/setup"
+ "amadan.net/rastrillo/rastrillo/auth"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/mail"
"context"
"errors"
+ "gorm.io/gorm"
"log/slog"
"net/http"
-
- "amadan.net/rastrillo/rastrillo/auth"
- "amadan.net/rastrillo/rastrillo/db"
- "amadan.net/rastrillo/rastrillo/mail"
- "amadan.net/rastrillo/rastrillo/pow"
)
func NewAuth(d *db.DB, cfg Config, mailer mail.Sender, store *Store, logger *slog.Logger) (*auth.Auth, error) {
@@ -19,90 +19,35 @@ func NewAuth(d *db.DB, cfg Config, mailer mail.Sender, store *Store, logger *slo
if d == nil || store == nil || store.db != d {
return nil, ErrUnavailable
}
- if mailer == nil {
+ store.invitationKey, store.personOrigin = cfg.InstanceKey, cfg.Origin
+ return setup.NewAuth(d, setup.AuthOptions{Origin: cfg.Origin, Key: cfg.InstanceKey, AllowLoggedMail: cfg.AllowLoggedMail,
//lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go.
- return nil, errors.New(copyMissingMailer)
- }
- if !mail.IsConfigured(mailer) && !cfg.AllowLoggedMail {
- //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go.
- return nil, errors.New(copyUnconfiguredMailer)
- }
- guard, err := pow.New(pow.Config{
- InstanceKey: cfg.InstanceKey, Nonces: pow.SQLNonces(d.Writer()),
- Difficulty: pow.NoProof, MinAge: pow.DefaultMinAge,
- })
- if err != nil {
- return nil, err
- }
- store.invitationKey = cfg.InstanceKey
- store.personOrigin = cfg.Origin
- var a *auth.Auth
- a, err = auth.New(auth.Config{
- DB: d.Writer(), Origin: cfg.Origin, InstanceKey: cfg.InstanceKey, Mailer: mailer, Logger: logger,
- Proof: guard, KeymailServers: []string{"keymail.dev"}, SigninScreen: true,
- BeginPath: "/auth/begin", ForgetPath: "/auth/forget", SignedInPath: "/conversation",
- Authorize: func(address string) bool {
- member, err := store.Member(context.Background(), address)
- if err == nil && member.Active {
- return true
- }
- if err != nil && !errors.Is(err, ErrNotFound) {
- return false
- }
- pending, err := store.MayVerifyInvitation(context.Background(), address)
- return err == nil && pending
- },
- SubjectFor: func(address string) (string, error) { return normalizeAddress(address), nil },
- RenderConfirm: func(w http.ResponseWriter, r *http.Request, _ auth.ConfirmPageData) { renderSignin(a, w, r) },
- })
- return a, err
+ MissingMailer: errors.New(copyMissingMailer), UnconfiguredMailer: errors.New(copyUnconfiguredMailer),
+ Normalize: normalizeAddress, MayVerify: store.MayVerifyInvitation, Handler: store.sessionHandler(nil)}, mailer, logger)
}
-
-func renderSignin(a *auth.Auth, w http.ResponseWriter, r *http.Request) {
- if a == nil {
- privateUnavailable(w, r)
- return
+func (s *Store) sessionHandler(authentication *auth.Auth) *setup.SessionHandler {
+ return &setup.SessionHandler{Auth: authentication, Member: s.Member, NotFound: ErrNotFound,
+ Remember: func(ctx context.Context, a Actor) error {
+ return s.write(ctx, func(tx *gorm.DB) error { return s.invitationsAt(tx).RememberSignedIn(a) })
+ },
+ Render: func(w http.ResponseWriter, state auth.SigninState) {
+ render(w, "signin_page", map[string]any{"State": state, "Brand": map[string]string{"Name": copyBrand}})
+ },
+ Failure: func(w http.ResponseWriter, r *http.Request, status int) { ErrorPage(w, r, status, "") },
}
- state := a.SigninState(r)
- a.PrepareSigninResponse(w, state)
- render(w, "signin_page", map[string]any{"State": state, "Brand": map[string]string{"Name": copyBrand}})
}
// RequireMember lets composed routes use the same admission as the app.
func (a *application) RequireMember(next http.Handler) http.Handler { return a.requireMember(next) }
-
func (a *application) requireMember(next http.Handler) http.Handler {
if a == nil || a.auth == nil || a.store == nil {
return http.HandlerFunc(privateUnavailable)
}
- browser := a.auth.RequireSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Cache-Control", "no-store")
- id, ok := auth.From(r)
- if !ok {
- ErrorPage(w, r, http.StatusForbidden, "")
- return
- }
- member, err := a.store.Member(r.Context(), id.Address)
- if err != nil && !errors.Is(err, ErrNotFound) {
- privateUnavailable(w, r)
- return
- }
- if err != nil || !member.Active || id.At.IsZero() || id.At.Unix() < member.SessionEpoch {
- ErrorPage(w, r, http.StatusForbidden, "")
- return
- }
- next.ServeHTTP(w, r)
- }))
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if len(r.Header.Values("Authorization")) != 0 {
- w.Header().Set("Cache-Control", "no-store")
- ErrorPage(w, r, http.StatusForbidden, "")
- return
- }
- browser.ServeHTTP(w, r)
- })
+ return a.store.sessionHandler(a.auth).RequireMember(next)
+}
+func (a *application) rememberSignIn(next http.HandlerFunc) http.HandlerFunc {
+ return a.store.sessionHandler(a.auth).RememberSignIn(next)
}
-
func privateUnavailable(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
ErrorPage(w, r, http.StatusServiceUnavailable, "")
diff --git a/internal/equipo/conversation_handlers.go b/internal/equipo/conversation_handlers.go
index 4595b80d..b98ebb0b 100644
--- a/internal/equipo/conversation_handlers.go
+++ b/internal/equipo/conversation_handlers.go
@@ -29,7 +29,7 @@ func (a *application) conversationHandler() *conversation.Handler {
}
a.renderLive(w, r, name, data)
}, RenderSettings: func(w http.ResponseWriter, r *http.Request, v conversation.CoordinatorPage) {
- data, err := a.page(r, "settings")
+ data, err := a.page(r, "coordinator")
if err != nil {
a.failure(w, r, err)
return
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index af735be0..f074920f 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -48,6 +48,33 @@ const BootLog = "Equipo could not start."
// COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules).
var pageCopy = map[string]string{
+ // COPY REVIEW REQUIRED: teams.title
+ "teams.title": "Teams",
+ // COPY REVIEW REQUIRED: teams.add
+ "teams.add": "Remember a team",
+ // COPY REVIEW REQUIRED: teams.forget
+ "teams.forget": "Forget this link",
+ // COPY REVIEW REQUIRED: teams.remembered
+ "teams.remembered": "Your remembered teams",
+ // COPY REVIEW REQUIRED: teams.directory_help
+ "teams.directory_help": "Add links to other Equipo instances you have signed in to. Only you can see this directory. Each instance has its own sign-in and membership. Links do not give access or share accounts.",
+ // COPY REVIEW REQUIRED: teams.last_signin_unknown
+ "teams.last_signin_unknown": "Last sign-in unknown",
+ // COPY REVIEW REQUIRED: teams.last_signin
+ "teams.last_signin": "Last signed in",
+ // COPY REVIEW REQUIRED: teams.remote_unavailable
+ "teams.remote_unavailable": "Remote status unavailable",
+ // COPY REVIEW REQUIRED: teams.counts_unknown
+ "teams.counts_unknown": "Counts unavailable",
+ // COPY REVIEW REQUIRED: teams.origin
+ "teams.origin": "Instance address",
+ // COPY REVIEW REQUIRED: teams.name
+ "teams.name": "Team name",
+ // COPY REVIEW REQUIRED: teams.current
+ "teams.current": "Current team",
+ // COPY REVIEW REQUIRED: teams.parent_task
+ "teams.parent_task": "Task",
+
// COPY REVIEW REQUIRED: account_setup.title
"account_setup.title": "Connect a model account",
// COPY REVIEW REQUIRED: account_setup.label
diff --git a/internal/equipo/handlers.go b/internal/equipo/handlers.go
index db558706..2433b58d 100644
--- a/internal/equipo/handlers.go
+++ b/internal/equipo/handlers.go
@@ -28,6 +28,7 @@ type budgetForm struct {
Fields []budgetField
}
type pageData struct {
+ Teams setup.TeamLinkView
Onboarding setup.OnboardingView
Invite setup.InviteView
Invitations []Invitation
diff --git a/internal/equipo/library/navigation.go b/internal/equipo/library/navigation.go
index dbf353a0..d22862f1 100644
--- a/internal/equipo/library/navigation.go
+++ b/internal/equipo/library/navigation.go
@@ -1,9 +1,12 @@
package library
+import "amadan.net/oficina/equipo/internal/equipo/planning"
+
type NavItem struct{ Key, Group, Href, CopyKey, Icon string }
func Navigation() []NavItem {
return []NavItem{
+ {"teams", "", "/teams", "teams.title", "users"},
{"conversation", "", "/conversation", "nav.conversation", "message-circle"},
{"needs-you", "", "/needs-you", "nav.needs-you", "inbox"},
{"journey", "", "/journey", "nav.journey", "route"},
@@ -15,6 +18,8 @@ func Navigation() []NavItem {
{"review", "specialists", "/specialists/review", "nav.review", "check-circle"},
{"playbooks", "", "/playbooks", "playbooks.title", "route"},
{"templates", "specialists", "/templates", "templates.title", "plus"},
+ {"preferences", "team", "/preferences", "preferences.title", "sliders"},
+ {"coordinator", "team", "/settings/coordinator", "coordinator.settings", "message-circle"},
{"connections", "team", "/connections", "nav.connections", "plug"},
{"people", "team", "/people", "nav.people", "users"},
{"settings", "team", "/settings", "nav.settings", "sliders"},
@@ -50,3 +55,14 @@ func WithSpecialists(rows []Specialist) ([]NavItem, map[string]string) {
}
return nav, names
}
+
+func NavigationCounts(counts map[string]planning.SpecialistWorkView, rows []Specialist, err error) map[string]planning.SpecialistWorkView {
+ if err == nil {
+ return counts
+ }
+ unknown := make(map[string]planning.SpecialistWorkView, len(rows))
+ for _, row := range rows {
+ unknown[row.Key] = planning.SpecialistWorkView{}
+ }
+ return unknown
+}
diff --git a/internal/equipo/library_handlers.go b/internal/equipo/library_handlers.go
index faf316e8..e1103c76 100644
--- a/internal/equipo/library_handlers.go
+++ b/internal/equipo/library_handlers.go
@@ -15,7 +15,10 @@ func (a *application) libraryHandler() *library.Handler {
return
}
data.Title = library.PageTitle(name, v)
- data.Key, data.Specialist = v.Specialist.Key, v.Specialist
+ data.Specialist = v.Specialist
+ if v.Specialist.Key != "" {
+ data.Key = v.Specialist.Key
+ }
data.Owner = data.Owner || v.Specialist.Creator == data.Address
data.Work, data.Tasks = v.Work, v.Work.Tasks
data.Library = v
diff --git a/internal/equipo/migrations/0029_team_links.sql b/internal/equipo/migrations/0029_team_links.sql
new file mode 100644
index 00000000..3c723431
--- /dev/null
+++ b/internal/equipo/migrations/0029_team_links.sql
@@ -0,0 +1,9 @@
+CREATE TABLE team_links (
+ id text PRIMARY KEY,
+ person text,
+ origin text,
+ name text,
+ last_signed_in_at datetime,
+ revision integer
+);
+CREATE UNIQUE INDEX team_link_person_origin ON team_links(person, origin);
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 857ee3af..7f3624df 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -444,3 +444,13 @@ CREATE TABLE account_setups (
challenge text
);
CREATE INDEX account_setup_person ON account_setups(person);
+
+CREATE TABLE team_links (
+ id text PRIMARY KEY,
+ person text,
+ origin text,
+ name text,
+ last_signed_in_at datetime,
+ revision integer
+);
+CREATE UNIQUE INDEX team_link_person_origin ON team_links(person, origin);
diff --git a/internal/equipo/preferences.go b/internal/equipo/preferences.go
index e300e94e..eb9b795c 100644
--- a/internal/equipo/preferences.go
+++ b/internal/equipo/preferences.go
@@ -29,7 +29,7 @@ func (s *Store) SavePersonalSettings(ctx context.Context, a Actor, in PersonalSe
}
func (a *application) preferenceHandler() *conversation.PreferenceHandler {
return &conversation.PreferenceHandler{App: a.store.coordinatorApplication(), Failure: a.failure, Render: func(w http.ResponseWriter, r *http.Request, v conversation.PreferencePage) {
- data, err := a.page(r, "settings")
+ data, err := a.page(r, "preferences")
if err != nil {
a.failure(w, r, err)
return
diff --git a/internal/equipo/render.go b/internal/equipo/render.go
index 32edfe99..1fcc0f79 100644
--- a/internal/equipo/render.go
+++ b/internal/equipo/render.go
@@ -27,7 +27,7 @@ var assets = rastrillo.NewAssets(appFS)
var pages = map[string]*template.Template{}
func init() {
- for _, name := range []string{"onboarding", "invite", "playbooks", "playbook_form", "playbook_diff", "specialist_form", "template_library", "template_diff", "conversation", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval"} {
+ for _, name := range []string{"teams", "onboarding", "invite", "playbooks", "playbook_form", "playbook_diff", "specialist_form", "template_library", "template_diff", "conversation", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval"} {
page := template.Must(template.New("layout").
Funcs(ui.Funcs(ui.WithIcons(icons.Icon, icons.Assets))).
Funcs(template.FuncMap{"projectAllows": library.ProjectAllowed, "asset": assets.Path, "copy": copyText, "taskGroups": func() []string { return []string{"needs-person", "running", "queued", "finished"} },
diff --git a/internal/equipo/setup/invites.go b/internal/equipo/setup/invites.go
index a20b4632..213c4ebc 100644
--- a/internal/equipo/setup/invites.go
+++ b/internal/equipo/setup/invites.go
@@ -41,7 +41,7 @@ type inviteRequest struct {
func (inviteRequest) TableName() string { return "invitation_requests" }
-var Models = []any{&InvitationRecord{}, &inviteRequest{}, &OnboardingRecord{}, &AccountSetupRecord{}}
+var Models = []any{&InvitationRecord{}, &inviteRequest{}, &OnboardingRecord{}, &AccountSetupRecord{}, &TeamLinkRecord{}}
type Dependencies struct {
RunnerCurrent func(*gorm.DB, runnerproto.RunnerPrincipal) error
@@ -264,6 +264,9 @@ func (s *Store) Accept(a kernel.Actor, id, secret string, m kernel.Mutation) (ke
if err = s.initializeOnboarding(a); err != nil {
return out, err
}
+ if err = s.RememberSignedIn(a); err != nil {
+ return out, err
+ }
r.State = "accepted"
r.Revision++
now := s.deps.Now
diff --git a/internal/equipo/setup/session_handlers.go b/internal/equipo/setup/session_handlers.go
new file mode 100644
index 00000000..515bace4
--- /dev/null
+++ b/internal/equipo/setup/session_handlers.go
@@ -0,0 +1,172 @@
+package setup
+
+import (
+ "amadan.net/rastrillo/rastrillo/auth"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/mail"
+ "amadan.net/rastrillo/rastrillo/pow"
+ "bytes"
+ "context"
+ "errors"
+ "log/slog"
+ "net/http"
+)
+
+type SessionHandler struct {
+ Auth *auth.Auth
+ Member func(context.Context, string) (Member, error)
+ Remember func(context.Context, Actor) error
+ Render func(http.ResponseWriter, auth.SigninState)
+ Failure func(http.ResponseWriter, *http.Request, int)
+ NotFound error
+}
+type AuthOptions struct {
+ Origin, Key string
+ AllowLoggedMail bool
+ MissingMailer, UnconfiguredMailer error
+ Normalize func(string) string
+ MayVerify func(context.Context, string) (bool, error)
+ Handler *SessionHandler
+}
+
+func NewAuth(d *db.DB, o AuthOptions, mailer mail.Sender, logger *slog.Logger) (*auth.Auth, error) {
+ if mailer == nil {
+ return nil, o.MissingMailer
+ }
+ if !mail.IsConfigured(mailer) && !o.AllowLoggedMail {
+ return nil, o.UnconfiguredMailer
+ }
+ guard, err := pow.New(pow.Config{InstanceKey: o.Key, Nonces: pow.SQLNonces(d.Writer()), Difficulty: pow.NoProof, MinAge: pow.DefaultMinAge})
+ if err != nil {
+ return nil, err
+ }
+ h := o.Handler
+ h.Auth, err = auth.New(auth.Config{
+ DB: d.Writer(), Origin: o.Origin, InstanceKey: o.Key, Mailer: mailer, Logger: logger,
+ Proof: guard, KeymailServers: []string{"keymail.dev"}, SigninScreen: true,
+ BeginPath: "/auth/begin", ForgetPath: "/auth/forget", SignedInPath: "/",
+ Authorize: func(address string) bool {
+ member, err := h.Member(context.Background(), address)
+ if err == nil && member.Active {
+ return true
+ }
+ if err != nil && !errors.Is(err, h.NotFound) {
+ return false
+ }
+ pending, err := o.MayVerify(context.Background(), address)
+ return err == nil && pending
+ },
+ SubjectFor: func(address string) (string, error) { return o.Normalize(address), nil },
+ RenderConfirm: func(w http.ResponseWriter, r *http.Request, _ auth.ConfirmPageData) { h.Signin(w, r) },
+ })
+ return h.Auth, err
+}
+func (h *SessionHandler) fail(w http.ResponseWriter, r *http.Request, status int) {
+ w.Header().Set("Cache-Control", "no-store")
+ h.Failure(w, r, status)
+}
+func (h *SessionHandler) Signin(w http.ResponseWriter, r *http.Request) {
+ if h.Auth == nil {
+ h.fail(w, r, http.StatusServiceUnavailable)
+ return
+ }
+ state := h.Auth.SigninState(r)
+ h.Auth.PrepareSigninResponse(w, state)
+ h.Render(w, state)
+}
+
+func (h *SessionHandler) RequireMember(next http.Handler) http.Handler {
+ if h.Auth == nil || h.Member == nil {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h.fail(w, r, http.StatusServiceUnavailable) })
+ }
+ browser := h.Auth.RequireSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ id, ok := auth.From(r)
+ if !ok {
+ h.fail(w, r, http.StatusForbidden)
+ return
+ }
+ member, err := h.Member(r.Context(), id.Address)
+ if err != nil && !errors.Is(err, h.NotFound) {
+ h.fail(w, r, http.StatusServiceUnavailable)
+ return
+ }
+ if err != nil || !member.Active || id.At.IsZero() || id.At.Unix() < member.SessionEpoch {
+ h.fail(w, r, http.StatusForbidden)
+ return
+ }
+ next.ServeHTTP(w, r)
+ }))
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if len(r.Header.Values("Authorization")) != 0 {
+ w.Header().Set("Cache-Control", "no-store")
+ h.fail(w, r, http.StatusForbidden)
+ return
+ }
+ browser.ServeHTTP(w, r)
+ })
+}
+
+// Buffer the auth response until its newly minted session has been checked.
+// This preserves the framework's return_to handling, including task deep links.
+func (h *SessionHandler) RememberSignIn(next http.HandlerFunc) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ out := &signInResponse{header: make(http.Header)}
+ next(out, r)
+ response := http.Response{Header: out.header}
+ for _, cookie := range response.Cookies() {
+ if cookie.Name != h.Auth.SessionCookie() || cookie.Value == "" || cookie.MaxAge < 0 {
+ continue
+ }
+ request := r.Clone(r.Context())
+ request.Header = r.Header.Clone()
+ request.Header.Del("Cookie")
+ request.AddCookie(cookie)
+ id, ok := h.Auth.SessionFrom(request)
+ if !ok {
+ h.fail(w, r, http.StatusServiceUnavailable)
+ return
+ }
+ member, err := h.Member(r.Context(), id.Address)
+ // Invite recipients have verified an identity but have not joined yet.
+ if errors.Is(err, h.NotFound) || (err == nil && !member.Active) {
+ continue
+ }
+ if err == nil {
+ err = h.Remember(r.Context(), Actor{Address: id.Address})
+ }
+ if err != nil {
+ h.fail(w, r, http.StatusServiceUnavailable)
+ return
+ }
+ }
+ for key, values := range out.header {
+ w.Header()[key] = values
+ }
+ status := out.status
+ if status == 0 {
+ status = http.StatusOK
+ }
+ w.WriteHeader(status)
+ _, _ = w.Write(out.body.Bytes())
+ }
+}
+
+type signInResponse struct {
+ header http.Header
+ status int
+ body bytes.Buffer
+}
+
+func (w *signInResponse) Header() http.Header { return w.header }
+func (w *signInResponse) WriteHeader(status int) {
+ if w.status == 0 {
+ w.status = status
+ }
+}
+func (w *signInResponse) Write(b []byte) (int, error) {
+ if w.status == 0 {
+ w.status = http.StatusOK
+ }
+ return w.body.Write(b)
+}
diff --git a/internal/equipo/setup/team_link_handlers.go b/internal/equipo/setup/team_link_handlers.go
new file mode 100644
index 00000000..c307ea2c
--- /dev/null
+++ b/internal/equipo/setup/team_link_handlers.go
@@ -0,0 +1,97 @@
+package setup
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/planning"
+ "context"
+ "crypto/rand"
+ "github.com/go-chi/chi/v5"
+ "net/http"
+)
+
+type TeamLinkOperations interface {
+ TeamLinks(context.Context, Actor) ([]TeamLink, error)
+ RememberTeam(context.Context, Actor, TeamLink, Mutation) (TeamLink, error)
+ ForgetTeam(context.Context, Actor, string, Mutation) error
+}
+type TeamLinkView struct {
+ Links []TeamLink
+ RequestID string
+ CurrentNeeds *int
+}
+type TeamLinkHandler struct {
+ Store TeamLinkOperations
+ Actor func(*http.Request) (Actor, error)
+ Render func(http.ResponseWriter, *http.Request, TeamLinkView)
+ Failure func(http.ResponseWriter, *http.Request, error)
+ Invalid error
+}
+
+func (h *TeamLinkHandler) Routes(r chi.Router) {
+ r.Get("/teams", h.Page)
+ r.Post("/teams/links", h.Remember)
+ r.Post("/teams/links/{id}/forget", h.Forget)
+}
+func (h *TeamLinkHandler) Page(w http.ResponseWriter, r *http.Request) {
+ privacy(w)
+ a, err := h.Actor(r)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ links, err := h.Store.TeamLinks(r.Context(), a)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ h.Render(w, r, TeamLinkView{Links: links, RequestID: rand.Text()})
+}
+func (h *TeamLinkHandler) Remember(w http.ResponseWriter, r *http.Request) { h.change(w, r, false) }
+func (h *TeamLinkHandler) Forget(w http.ResponseWriter, r *http.Request) { h.change(w, r, true) }
+func (h *TeamLinkHandler) change(w http.ResponseWriter, r *http.Request, forget bool) {
+ privacy(w)
+ a, err := h.Actor(r)
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ m, err := planning.ReadMutation(w, r, h.Invalid)
+ if err == nil {
+ allowed := map[string]bool{"request_id": true, "revision": true}
+ if !forget {
+ allowed["origin"] = true
+ allowed["name"] = true
+ }
+ for key := range r.PostForm {
+ if !allowed[key] {
+ err = h.Invalid
+ break
+ }
+ }
+ }
+ if err == nil {
+ if forget {
+ err = h.Store.ForgetTeam(r.Context(), a, chi.URLParam(r, "id"), m)
+ } else {
+ _, err = h.Store.RememberTeam(r.Context(), a, TeamLink{Origin: r.PostForm.Get("origin"), Name: r.PostForm.Get("name")}, m)
+ }
+ }
+ if err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ http.Redirect(w, r, "/teams", http.StatusSeeOther)
+}
+
+func (v *TeamLinkView) SetCurrentTasks(tasks []planning.TaskViewData, err error) {
+ v.CurrentNeeds = nil
+ if err != nil {
+ return
+ }
+ n := 0
+ for _, task := range tasks {
+ if task.NeedsYou {
+ n++
+ }
+ }
+ v.CurrentNeeds = &n
+}
diff --git a/internal/equipo/setup/team_links.go b/internal/equipo/setup/team_links.go
new file mode 100644
index 00000000..9d81ed33
--- /dev/null
+++ b/internal/equipo/setup/team_links.go
@@ -0,0 +1,237 @@
+package setup
+
+import (
+ "context"
+ "crypto/rand"
+ "errors"
+ "net"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+ "unicode"
+
+ "gorm.io/gorm"
+)
+
+type TeamLink struct {
+ ID, Origin, Name string
+ LastSignedInAt *time.Time
+ Revision int64
+}
+
+type TeamLinkRecord struct {
+ ID string `gorm:"primaryKey"`
+ Person string `gorm:"uniqueIndex:team_link_person_origin"`
+ Origin string `gorm:"uniqueIndex:team_link_person_origin"`
+ Name string
+ LastSignedInAt *time.Time
+ Revision int64
+}
+
+func (TeamLinkRecord) TableName() string { return "team_links" }
+func (r TeamLinkRecord) view() TeamLink {
+ return TeamLink{r.ID, r.Origin, r.Name, r.LastSignedInAt, r.Revision}
+}
+
+func (s *Store) linkMember(a Actor) error {
+ m, err := s.deps.Member(s.tx, a.Address)
+ if errors.Is(err, s.deps.NotFound) {
+ return s.deps.Forbidden
+ }
+ if err != nil {
+ return err
+ }
+ if !m.Active {
+ return s.deps.Forbidden
+ }
+ return nil
+}
+func (s *Store) linkOrigin(raw string) (string, error) {
+ u, err := url.Parse(raw)
+ if err != nil || u.Hostname() == "" || u.Opaque != "" || u.User != nil || strings.ContainsAny(raw, "?#\\") || (u.Path != "" && u.Path != "/") || u.RawPath != "" {
+ return "", s.deps.Invalid
+ }
+ if u.Scheme != "https" {
+ if u.Scheme != "http" || strings.TrimSuffix(raw, "/") != s.deps.Origin {
+ return "", s.deps.Invalid
+ }
+ ip := net.ParseIP(u.Hostname())
+ if u.Hostname() != "localhost" && (ip == nil || !ip.IsLoopback()) {
+ return "", s.deps.Invalid
+ }
+ }
+ if strings.HasSuffix(u.Host, ":") {
+ return "", s.deps.Invalid
+ }
+ if port := u.Port(); port != "" {
+ n, e := strconv.Atoi(port)
+ if e != nil || n < 1 || n > 65535 {
+ return "", s.deps.Invalid
+ }
+ }
+ u.Scheme = strings.ToLower(u.Scheme)
+ u.Host = strings.ToLower(u.Host)
+ u.Path = ""
+ if u.Scheme == "https" && u.Port() == "443" {
+ u.Host = strings.TrimSuffix(u.Host, ":443")
+ }
+ return u.String(), nil
+}
+func (s *Store) teamLinks(a Actor) ([]TeamLink, error) {
+ if err := s.linkMember(a); err != nil {
+ return nil, err
+ }
+ var rows []TeamLinkRecord
+ if err := s.tx.Where("person=?", a.Address).Order("name, id").Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ out := make([]TeamLink, 0, len(rows))
+ for _, r := range rows {
+ out = append(out, r.view())
+ }
+ return out, nil
+}
+func (s *Store) rememberTeam(a Actor, in TeamLink, m Mutation) (TeamLink, error) {
+ var out TeamLink
+ if err := s.linkMember(a); err != nil {
+ return out, err
+ }
+ origin, err := s.linkOrigin(in.Origin)
+ if err != nil {
+ return out, err
+ }
+ name := strings.TrimSpace(in.Name)
+ if in.LastSignedInAt != nil || name == "" || len(name) > 160 || strings.IndexFunc(name, unicode.IsControl) >= 0 {
+ return out, s.deps.Invalid
+ }
+ input := struct {
+ ID, Origin, Name string
+ Revision int64
+ }{in.ID, origin, name, m.Revision}
+ if ok, err := s.replay(a, "team.remember", in.ID, m, input, &out); ok || err != nil {
+ return out, err
+ }
+ var row TeamLinkRecord
+ if in.ID == "" {
+ if m.Revision != 0 {
+ return out, s.deps.Conflict
+ }
+ var n int64
+ if err = s.tx.Model(&TeamLinkRecord{}).Where("person=? AND origin=?", a.Address, origin).Count(&n).Error; err != nil {
+ return out, err
+ }
+ if n != 0 {
+ return out, s.deps.Conflict
+ }
+ row = TeamLinkRecord{ID: rand.Text(), Person: a.Address, Origin: origin, Name: name, Revision: 1}
+ if err = s.tx.Create(&row).Error; err != nil {
+ return out, err
+ }
+ } else {
+ if err = s.tx.Where("id=? AND person=?", in.ID, a.Address).First(&row).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ err = s.deps.NotFound
+ }
+ return out, err
+ }
+ if row.Revision != m.Revision {
+ return out, s.deps.Conflict
+ }
+ // A verified timestamp belongs to its origin. Editing an origin loses it.
+ if row.Origin != origin {
+ row.LastSignedInAt = nil
+ }
+ row.Origin, row.Name, row.Revision = origin, name, row.Revision+1
+ var n int64
+ if err = s.tx.Model(&TeamLinkRecord{}).Where("person=? AND origin=? AND id<>?", a.Address, origin, row.ID).Count(&n).Error; err != nil {
+ return out, err
+ }
+ if n != 0 {
+ return out, s.deps.Conflict
+ }
+ if err = s.tx.Model(&TeamLinkRecord{}).Where("id=? AND person=?", row.ID, a.Address).Select("origin", "name", "revision", "last_signed_in_at").Updates(&row).Error; err != nil {
+ return out, err
+ }
+ }
+ if err = s.deps.Audit(s.tx, a, "team_link.remember", row.ID); err != nil {
+ return out, err
+ }
+ out = row.view()
+ return out, s.save(a, "team.remember", in.ID, m, input, out)
+}
+func (s *Store) forgetTeam(a Actor, id string, m Mutation) error {
+ if err := s.linkMember(a); err != nil {
+ return err
+ }
+ var saved bool
+ if ok, err := s.replay(a, "team.forget", id, m, m, &saved); ok || err != nil {
+ return err
+ }
+ var row TeamLinkRecord
+ if err := s.tx.Where("id=? AND person=?", id, a.Address).First(&row).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return s.deps.NotFound
+ }
+ return err
+ }
+ if row.Revision != m.Revision {
+ return s.deps.Conflict
+ }
+ if err := s.tx.Where("id=? AND person=?", id, a.Address).Delete(&TeamLinkRecord{}).Error; err != nil {
+ return err
+ }
+ if err := s.deps.Audit(s.tx, a, "team_link.forget", id); err != nil {
+ return err
+ }
+ return s.save(a, "team.forget", id, m, m, true)
+}
+
+func (s *Application) TeamLinks(ctx context.Context, a Actor) (out []TeamLink, err error) {
+ a.Address = s.Normalize(a.Address)
+ err = s.Read(ctx, func(tx *gorm.DB) error { out, err = s.At(tx).teamLinks(a); return err })
+ return
+}
+func (s *Application) RememberTeam(ctx context.Context, a Actor, in TeamLink, m Mutation) (out TeamLink, err error) {
+ a.Address = s.Normalize(a.Address)
+ err = s.Write(ctx, func(tx *gorm.DB) error { out, err = s.At(tx).rememberTeam(a, in, m); return err })
+ if err != nil {
+ out = TeamLink{}
+ }
+ return
+}
+func (s *Application) ForgetTeam(ctx context.Context, a Actor, id string, m Mutation) error {
+ a.Address = s.Normalize(a.Address)
+ return s.Write(ctx, func(tx *gorm.DB) error { return s.At(tx).forgetTeam(a, id, m) })
+}
+
+// RememberSignedIn is called only with the newly verified local session identity.
+// Its origin, team name and timestamp come from the instance, never the form.
+func (s *Store) RememberSignedIn(a Actor) error {
+ if err := s.linkMember(a); err != nil {
+ return err
+ }
+ origin, err := s.linkOrigin(s.deps.Origin)
+ if err != nil {
+ return err
+ }
+ var team struct{ Name string }
+ if err = s.tx.Table("teams").Take(&team).Error; err != nil {
+ return err
+ }
+ var row TeamLinkRecord
+ err = s.tx.Where("person=? AND origin=?", a.Address, origin).First(&row).Error
+ now := s.deps.Now
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ row = TeamLinkRecord{ID: rand.Text(), Person: a.Address, Origin: origin, Name: team.Name, LastSignedInAt: &now, Revision: 1}
+ err = s.tx.Create(&row).Error
+ } else if err == nil {
+ row.LastSignedInAt = &now
+ row.Revision++
+ err = s.tx.Model(&TeamLinkRecord{}).Where("id=? AND person=?", row.ID, a.Address).Select("last_signed_in_at", "revision").Updates(&row).Error
+ }
+ if err != nil {
+ return err
+ }
+ return s.deps.Audit(s.tx, a, "team_link.signin", row.ID)
+}
diff --git a/internal/equipo/static/equipo.css b/internal/equipo/static/equipo.css
index ffa5f87a..5f6518a8 100644
--- a/internal/equipo/static/equipo.css
+++ b/internal/equipo/static/equipo.css
@@ -41,3 +41,22 @@
[equipo-form] [equipo-checkbox] { display: flex; align-items: center; }
[equipo-form] [equipo-checkbox] input { width: auto; }
#composer { margin-block: var(--rst-sp-5); }
+
+[equipo-current-team], [equipo-team-link] > a {
+ display: flex;
+ align-items: center;
+ gap: var(--rst-sp-2);
+ min-inline-size: 0;
+}
+[rst-shell-sidebar~="teams"] > [rst-shell-back] { display: none; }
+@media (max-width: 799.98px) {
+ [equipo-team-heading] { display: none; }
+ [equipo-team-index] > [rst-shell-back] {
+ display: flex;
+ align-items: center;
+ min-block-size: var(--rst-shell-strip);
+ background: var(--rst-surface);
+ border-block-end: 1px solid var(--rst-line);
+ padding-inline: var(--rst-sp-1);
+ }
+}
diff --git a/internal/equipo/task_page_handlers.go b/internal/equipo/task_page_handlers.go
index 53c65f83..4834c8a8 100644
--- a/internal/equipo/task_page_handlers.go
+++ b/internal/equipo/task_page_handlers.go
@@ -6,6 +6,7 @@ import (
"strconv"
"strings"
+ "amadan.net/oficina/equipo/internal/equipo/library"
"amadan.net/rastrillo/rastrillo/live"
"github.com/go-chi/chi/v5"
)
@@ -20,10 +21,7 @@ func (a *application) fillCounts(r *http.Request, data *pageData) error {
return nil
}
counts, err := a.store.SpecialistCounts(r.Context(), Actor{Address: data.Address})
- if err != nil {
- return err
- }
- data.Counts = counts
+ data.Counts = library.NavigationCounts(counts, data.Specialists, err)
return nil
}
func (a *application) taskList(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/equipo/team_links.go b/internal/equipo/team_links.go
new file mode 100644
index 00000000..72f68c69
--- /dev/null
+++ b/internal/equipo/team_links.go
@@ -0,0 +1,28 @@
+package equipo
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/library"
+ "amadan.net/oficina/equipo/internal/equipo/setup"
+ "net/http"
+)
+
+type TeamLink = setup.TeamLink
+
+func (a *application) teamLinkHandler() *setup.TeamLinkHandler {
+ return &setup.TeamLinkHandler{Store: a.store, Invalid: ErrInvalid, Failure: a.failure,
+ Actor: library.SessionActor(ErrForbidden),
+ Render: func(w http.ResponseWriter, r *http.Request, v setup.TeamLinkView) {
+ data, err := a.page(r, "teams")
+ if err != nil {
+ a.failure(w, r, err)
+ return
+ }
+ data.Title = "teams.title"
+ data.Origin = a.origin
+ tasks, err := a.store.Journey(r.Context(), Actor{Address: data.Address})
+ v.SetCurrentTasks(tasks, err)
+ data.Teams = v
+ render(w, "teams", data)
+ },
+ }
+}
diff --git a/internal/equipo/templates/chrome.html b/internal/equipo/templates/chrome.html
index 8c6a3180..504d2076 100644
--- a/internal/equipo/templates/chrome.html
+++ b/internal/equipo/templates/chrome.html
@@ -1,7 +1,9 @@
+{{define "rail-brand"}}{{end}}
{{define "title"}}{{copy .Title}} · {{copy "brand"}}{{end}}
{{define "head"}}{{.Live.Head (T "rastrillo.ui.live.paused") (T "rastrillo.ui.live.unconfirmed")}}<link rel="stylesheet" href="{{asset "static/equipo.css"}}">{{end}}
{{define "up"}}/work{{if .Key}}#nav-{{.Key}}{{end}}{{end}}
-{{define "brand"}}<a rst-shell-brand href="/people">{{icon "users"}}{{.TeamName}}</a>{{end}}
+{{define "up-label"}}{{.TeamName}}{{end}}
+{{define "brand"}}<a rst-shell-brand href="/work">{{icon "users"}}{{.TeamName}}</a>{{end}}
{{define "nav"}}
{{template "region:rail" .}}{{end}}
{{define "region:rail"}}<nav rst-shell-nav id="rail" {{.Live.Attrs .CollectionTopic}}>
@@ -9,6 +11,7 @@
{{range .Nav}}
{{if ne .Group $group}}{{if .Group}}<p equipo-nav-group>{{copy (printf "nav.%s" .Group)}}</p>{{end}}{{$group = .Group}}{{end}}
<a id="nav-{{.Key}}" href="{{.Href}}"{{if eq .Key $key}} aria-current="page"{{end}}>{{icon .Icon}}<span>{{if index $names .Key}}{{index $names .Key}}{{else}}{{copy .CopyKey}}{{end}}{{if eq .Group "specialists"}}{{with index $counts .Key}}{{if .CountsKnown}}<small equipo-count>{{.Working}} · {{.Queued}} {{copy "activity.queued"}} · {{.Waiting}} {{copy "task.state.waiting"}}</small>{{else}}<small equipo-count>{{copy "counts.unavailable"}}</small>{{end}}{{end}}{{end}}</span></a>
+{{if eq .Key "teams"}}<div equipo-team-heading>{{template "brand" $}}</div>{{end}}
{{end}}
</nav>{{end}}
{{define "region:notice"}}<div id="notice" role="status"></div>{{end}}
diff --git a/internal/equipo/templates/index.html b/internal/equipo/templates/index.html
index c946e8af..0513e103 100644
--- a/internal/equipo/templates/index.html
+++ b/internal/equipo/templates/index.html
@@ -1,2 +1,4 @@
+{{define "up"}}/teams{{end}}
+{{define "up-label"}}{{copy "teams.title"}}{{end}}
{{define "view"}}index{{end}}
-{{define "content"}}<h1>{{copy "nav.work"}}</h1><a rst-btn href="/tasks/new">{{copy "task.new"}}</a>{{end}}
+{{define "content"}}<h1>{{.TeamName}}</h1><a rst-btn href="/tasks/new">{{copy "task.new"}}</a>{{end}}
diff --git a/internal/equipo/templates/layout.html b/internal/equipo/templates/layout.html
index f641e041..e4d8b1d9 100644
--- a/internal/equipo/templates/layout.html
+++ b/internal/equipo/templates/layout.html
@@ -1,3 +1,4 @@
+{{define "brand"}}<a rst-shell-brand href="/">{{T "rastrillo.ui.shell_home"}}</a>{{end}}
{{define "layout"}}<!doctype html>
<html lang="{{block "lang" .}}en{{end}}" dir="{{block "dir" .}}ltr{{end}}">
<head>
@@ -45,14 +46,14 @@
An app with its own template called view renames it: the name is
generic, and this one is now the shell's. At 800px and up both views
are the rail beside the page. */}}
-<div rst-shell-sidebar="{{block "view" .}}page{{end}}">
+<div rst-shell-sidebar="{{block "view" .}}page{{end}}"{{if eq .Key "work"}} equipo-team-index{{end}}>
<a rst-skip href="#main">{{T "rastrillo.ui.shell_skip"}}</a>
{{/* The back control: first after the skip link, so focus order is what
is seen; a link, not a script; its visible word inside its
accessible name (WCAG 2.5.3); rel="up" for tools that read it. An
app that wants its name on it ("‹ Ledger") edits this line, which is
the app's own from the moment it is scaffolded. */}}
-<div rst-shell-back><a href="{{block "up" .}}/{{end}}" rel="up" aria-label="{{copy "nav.back"}}">{{copy "nav.work"}}</a></div>
+<div rst-shell-back><a href="{{block "up" .}}/{{end}}" rel="up" aria-label="{{template "up-label" .}}">{{block "up-label" .}}{{copy "nav.work"}}{{end}}</a></div>
<aside rst-shell-rail>
{{/* The index's heading is the app's name: the brand, in a span of its
own, then the page's title for an app whose brand renders nothing
@@ -63,7 +64,7 @@
inside the brand would appear twice. tokens.css shows the heading
only on the phone index, so no page ever exposes two h1s. */}}
<h1 rst-shell-title><span>{{template "brand" .}}</span><span>{{template "title" .}}</span></h1>
-{{block "brand" .}}<a rst-shell-brand href="/">{{T "rastrillo.ui.shell_home"}}</a>{{end}}
+{{block "rail-brand" .}}{{template "brand" .}}{{end}}
{{block "nav" .}}<nav rst-shell-nav></nav>{{end}}
{{/* The rail's foot: one profile menu, an avatar that opens a card with
the person's name, the language switcher and the account's links.
diff --git a/internal/equipo/templates/playbooks.html b/internal/equipo/templates/playbooks.html
index 9443d5f0..53c8900c 100644
--- a/internal/equipo/templates/playbooks.html
+++ b/internal/equipo/templates/playbooks.html
@@ -1,5 +1,5 @@
{{define "title"}}{{copy "playbooks.title"}}{{end}}
-{{define "up"}}/work{{end}}
+{{define "up"}}/work#nav-playbooks{{end}}
{{define "content"}}
<h1>{{copy "playbooks.title"}}</h1><a rst-btn href="/playbooks/new">{{copy "playbooks.new"}}</a>
{{range .Library.Playbooks}}<section equipo-card><h2><a href="/playbooks/{{.ID}}/edit">{{.Name}}</a></h2><span equipo-badge>{{copy (printf "task.kind.%s" .Kind)}}</span><p>{{copy "playbooks.used"}}: <span equipo-value>{{.Used}}</span></p>{{if .Template.ID}}<a href="/playbooks/{{.ID}}/template-diff">{{copy "playbooks.update_available"}}</a>{{end}}</section>{{end}}
diff --git a/internal/equipo/templates/task.html b/internal/equipo/templates/task.html
index 41ea15ea..185bb9f7 100644
--- a/internal/equipo/templates/task.html
+++ b/internal/equipo/templates/task.html
@@ -1,3 +1,5 @@
+{{define "up"}}/journey{{end}}
+{{define "up-label"}}{{copy "nav.journey"}}{{end}}
{{define "content"}}<h1>{{copy "task.plan"}}</h1>{{template "region:activity" .}}{{end}}
{{define "region:activity"}}<div id="activity" {{.Live.Attrs .Topic}}>{{with .TaskView}}
{{template "task-card" .}}
diff --git a/internal/equipo/templates/teams.html b/internal/equipo/templates/teams.html
new file mode 100644
index 00000000..a212fdc7
--- /dev/null
+++ b/internal/equipo/templates/teams.html
@@ -0,0 +1,27 @@
+{{define "view"}}page teams{{end}}
+{{define "content"}}
+<h1>{{copy "teams.title"}}</h1>
+<section equipo-card>
+<h2>{{copy "teams.current"}}</h2>
+<a equipo-current-team href="/work">{{icon "users"}}<span equipo-secondary>{{.TeamName}}</span></a>
+<p>{{copy "nav.needs-you"}}: {{if ne .Teams.CurrentNeeds nil}}<span equipo-value>{{.Teams.CurrentNeeds}}</span>{{else}}<span equipo-value>{{copy "teams.counts_unknown"}}</span>{{end}}</p>
+</section>
+<h2>{{copy "teams.remembered"}}</h2>
+<p>{{copy "teams.directory_help"}}</p>
+{{$request := .Teams.RequestID}}{{$origin := .Origin}}
+{{range .Teams.Links}}
+<section equipo-card equipo-team-link>
+<a href="{{if eq .Origin $origin}}/work{{else}}{{.Origin}}{{end}}" rel="noreferrer">{{icon "users"}}<span equipo-secondary>{{.Name}}</span></a>
+<p equipo-secondary>{{.Origin}}</p>
+<p>{{if .LastSignedInAt}}{{copy "teams.last_signin"}}: <time equipo-value datetime="{{.LastSignedInAt.Format "2006-01-02T15:04:05Z07:00"}}">{{.LastSignedInAt.Format "2006-01-02 15:04 UTC"}}</time>{{else}}{{copy "teams.last_signin_unknown"}}{{end}}</p>
+{{if ne .Origin $origin}}<p>{{copy "teams.remote_unavailable"}}</p>{{end}}
+<form method="post" action="/teams/links/{{.ID}}/forget"><input type="hidden" name="request_id" value="{{$request}}-{{.ID}}"><input type="hidden" name="revision" value="{{.Revision}}"><button rst-btn type="submit">{{copy "teams.forget"}}</button></form>
+</section>
+{{end}}
+<form equipo-form method="post" action="/teams/links">
+<input type="hidden" name="request_id" value="{{.Teams.RequestID}}"><input type="hidden" name="revision" value="0">
+<label>{{copy "teams.name"}}<input rst-input name="name" maxlength="160" required></label>
+<label>{{copy "teams.origin"}}<input rst-input type="url" name="origin" required></label>
+<button rst-btn type="submit">{{copy "teams.add"}}</button>
+</form>
+{{end}}
diff --git a/internal/equipo/templates/thread.html b/internal/equipo/templates/thread.html
index 87fc7150..37fc17b8 100644
--- a/internal/equipo/templates/thread.html
+++ b/internal/equipo/templates/thread.html
@@ -1,3 +1,4 @@
+{{define "up-label"}}{{copy "teams.parent_task"}}{{end}}
{{define "title"}}{{copy "conversation.thread_link"}}{{end}}
{{define "up"}}/tasks/{{.Conversation.ThreadID}}{{end}}
{{define "content"}}
diff --git a/internal/equipotest/pages_test.go b/internal/equipotest/pages_test.go
index f7ffedbb..000f0e15 100644
--- a/internal/equipotest/pages_test.go
+++ b/internal/equipotest/pages_test.go
@@ -19,8 +19,8 @@ import (
const memberAddress = "reader@example.com"
-var railPaths = []string{"/conversation", "/needs-you", "/journey", "/projects", "/specialists/product", "/specialists/design", "/specialists/copy", "/specialists/engineering", "/specialists/review", "/connections", "/people", "/settings"}
-var railNames = []string{"Conversation", "Needs you", "Journey", "Projects", "Product", "Design", "Copy", "Engineering", "Review", "Connections", "People", "Settings"}
+var railPaths = []string{"/teams", "/conversation", "/needs-you", "/journey", "/projects", "/specialists/product", "/specialists/design", "/specialists/copy", "/specialists/engineering", "/specialists/review", "/playbooks", "/templates", "/preferences", "/settings/coordinator", "/connections", "/people", "/settings"}
+var railNames = []string{"Teams", "Conversation", "Needs you", "Journey", "Projects", "Product", "Design", "Copy", "Engineering", "Review", "Playbooks", "Template library", "Preferences", "Your coordinator", "Connections", "People", "Settings"}
func newPageFixture(t *testing.T) authFixture {
t.Helper()
@@ -90,8 +90,8 @@ func TestRailRoutes(t *testing.T) {
for _, path := range append(append([]string{}, railPaths...), "/work") {
body := pageBody(t, c, f.server.URL, path)
nav := regexp.MustCompile(`(?s)<nav rst-shell-nav[^>]*>.*?</nav>`).FindString(body)
- links := regexp.MustCompile(`(?s)<a\b[^>]*>.*?</a>`).FindAllString(nav, -1)
- if len(links) != 12 {
+ links := regexp.MustCompile(`(?s)<a id="nav-[^>]*>.*?</a>`).FindAllString(nav, -1)
+ if len(links) != len(railPaths) {
t.Fatalf("%s: %d rail destinations", path, len(links))
}
for i, link := range links {
@@ -110,14 +110,14 @@ func TestRailRoutes(t *testing.T) {
if currentCount != want {
t.Fatalf("ambiguous navigation position: %s: %d", path, currentCount)
}
- if !strings.Contains(body, `rst-shell-brand href="/people"`) {
+ if !strings.Contains(body, `rst-shell-brand href="/work"`) {
t.Fatal("missing team link")
}
if strings.Contains(nav, ">Apps<") || strings.Contains(nav, ">Billing<") {
t.Fatal("console navigation leaked")
}
- if path != "/work" && !strings.Contains(body, `href="/work#nav-`) {
- t.Fatal("missing phone parent")
+ if path != "/work" && path != "/teams" && !strings.Contains(body, `href="/work#nav-`) {
+ t.Fatal("missing phone parent", path)
}
for _, asset := range []string{"theme.", "shell.", "tokens.", "equipo."} {
if !strings.Contains(body, "/static/"+asset) {
diff --git a/internal/plan3test/teams_migration_test.go b/internal/plan3test/teams_migration_test.go
new file mode 100644
index 00000000..d77e165d
--- /dev/null
+++ b/internal/plan3test/teams_migration_test.go
@@ -0,0 +1,51 @@
+package plan3test
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/migrate"
+ "io"
+ "log/slog"
+ "path/filepath"
+ "testing"
+)
+
+func TestTeamsMigration(t *testing.T) {
+ d, err := db.Open(filepath.Join(t.TempDir(), "teams.db"), slog.New(slog.NewTextHandler(io.Discard, nil)))
+ must(t, err)
+ t.Cleanup(func() { must(t, d.Close()) })
+ old := &migrate.Set{}
+ for _, m := range equipo.BootSchema.All() {
+ if m.ID != "equipo/0029_team_links" {
+ old.Add(m)
+ }
+ }
+ _, err = migrate.Apply(ctx, d, old)
+ must(t, err)
+ _, err = d.Writer().Exec("INSERT INTO personal_settings(team_id,person,landing,revision) VALUES('saved','saved@example.com','work',7)")
+ must(t, err)
+ result, err := migrate.Apply(ctx, d, equipo.BootSchema)
+ must(t, err)
+ if len(result.Applied) != 1 || result.Applied[0] != "equipo/0029_team_links" {
+ t.Fatal(result.Applied)
+ }
+ var landing string
+ var revision int
+ must(t, d.Writer().QueryRow("SELECT landing,revision FROM personal_settings WHERE person='saved@example.com'").Scan(&landing, &revision))
+ if landing != "work" || revision != 7 {
+ t.Fatal("lost existing landing setting")
+ }
+ fresh := newFixture(t)
+ up, err := migrate.Read(ctx, d.Writer())
+ must(t, err)
+ clean, err := migrate.Read(ctx, fresh.DB.Writer())
+ must(t, err)
+ if !up.Equal(clean) {
+ t.Fatal(up.Diff(clean))
+ }
+ result, err = migrate.Apply(ctx, d, equipo.BootSchema)
+ must(t, err)
+ if len(result.Applied) != 0 {
+ t.Fatal("migration repeated")
+ }
+}
diff --git a/internal/plan3test/teams_navigation_browser_test.go b/internal/plan3test/teams_navigation_browser_test.go
new file mode 100644
index 00000000..24580ff0
--- /dev/null
+++ b/internal/plan3test/teams_navigation_browser_test.go
@@ -0,0 +1,79 @@
+//go:build browser
+
+package plan3test
+
+import (
+ "amadan.net/rastrillo/rastrillo/harness"
+ "context"
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/emulation"
+ "github.com/chromedp/cdproto/network"
+ "github.com/chromedp/chromedp"
+ "net/http"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestTeamsHierarchyBrowser(t *testing.T) {
+ found := false
+ for _, name := range []string{"chromium", "chromium-browser", "google-chrome", "google-chrome-stable"} {
+ if _, err := exec.LookPath(name); err == nil {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Skip("Chrome/Chromium binary unavailable; scriptless Teams hierarchy needs the chromedp fixture")
+ }
+ f := newFixture(t)
+ task := f.createTask(t)
+ if body := f.get(t, owner, "/journey").Body.String(); !strings.Contains(body, `href="/tasks/`+task.ID+`"`) {
+ t.Fatal("fixture task missing from journey", body)
+ }
+ rig := harness.New(t, func(string) http.Handler { return f.Handler }, harness.WithScrollbars())
+ run := func(label string, steps ...chromedp.Action[chromedp.Void]) {
+ t.Helper()
+ t.Log(label)
+ drive, cancel := context.WithTimeout(rig.Context(), 10*time.Second)
+ defer cancel()
+ if err := chromedp.Do(drive, steps...); err != nil {
+ t.Fatalf("%s: %v; page: %s", label, err, harness.Evaluate[string](rig, `location.href+"\n"+document.querySelector("main").outerHTML`))
+ }
+ }
+ cookie := f.Cookies[owner.Address]
+ run("set session and disable scripts", chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
+ if _, err := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: cookie.Name, Value: cookie.Value, URL: rig.Origin, Path: "/"}); err != nil {
+ return err
+ }
+ if _, err := cdp.Call(ctx, target, emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{Features: []*emulation.MediaFeature{{Name: "prefers-reduced-motion", Value: "reduce"}}}); err != nil {
+ return err
+ }
+ _, err := cdp.Call(ctx, target, emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true})
+ return err
+ }))
+ run("desktop sidebar", chromedp.EmulateViewport(1280, 900), chromedp.Navigate(rig.Origin+"/conversation"))
+ if !harness.Evaluate[bool](rig, `document.querySelector('#nav-teams').getBoundingClientRect().width>0 && document.querySelector('#nav-teams').getBoundingClientRect().bottom<=document.querySelector('[equipo-team-heading]').getBoundingClientRect().top`) {
+ t.Fatal("desktop Teams link hidden")
+ }
+ run("phone directory", chromedp.EmulateViewport(390, 844), chromedp.Navigate(rig.Origin+"/teams"))
+ if !harness.Evaluate[bool](rig, `document.querySelector('[equipo-current-team]').getBoundingClientRect().width>0 && document.documentElement.scrollWidth<=innerWidth`) {
+ t.Fatal("phone directory hidden or overflowing")
+ }
+ run("open current team", chromedp.Click(chromedp.CSS(`[equipo-current-team]`)), chromedp.WaitVisible(chromedp.CSS(`#nav-journey`)))
+ if !harness.Evaluate[bool](rig, `document.querySelector('[rst-shell-back] a').getAttribute('href')==='/teams' && document.querySelector('[rst-shell-back]').getBoundingClientRect().height>0`) {
+ t.Fatal("team index lacks visible Teams parent")
+ }
+ run("open Journey", chromedp.Click(chromedp.CSS(`#nav-journey`)), chromedp.WaitVisible(chromedp.CSS(`main a[href="/tasks/`+task.ID+`"]`)))
+ if !harness.Evaluate[bool](rig, `document.querySelector('[rst-shell-back] a').getAttribute('href')==='/work#nav-journey'`) {
+ t.Fatal("page parent is not team")
+ }
+ run("open task", chromedp.Click(chromedp.CSS(`main a[href="/tasks/`+task.ID+`"]`)), chromedp.WaitVisible(chromedp.CSS(`main a[href="/tasks/`+task.ID+`/thread"]`)))
+ if !harness.Evaluate[bool](rig, `document.querySelector('[rst-shell-back] a').getAttribute('href')==='/journey'`) {
+ t.Fatal("task parent is not page")
+ }
+ run("open thread", chromedp.Click(chromedp.CSS(`main a[href="/tasks/`+task.ID+`/thread"]`)))
+ run("thread parent", chromedp.WaitVisible(chromedp.CSS(`[rst-shell-back] a[href="/tasks/`+task.ID+`"]`)))
+ run("back to task", chromedp.Click(chromedp.CSS(`[rst-shell-back] a`)), chromedp.WaitVisible(chromedp.CSS(`[rst-shell-back] a[href="/journey"]`)))
+}
diff --git a/internal/plan3test/teams_navigation_test.go b/internal/plan3test/teams_navigation_test.go
new file mode 100644
index 00000000..8f99f73c
--- /dev/null
+++ b/internal/plan3test/teams_navigation_test.go
@@ -0,0 +1,258 @@
+package plan3test
+
+import (
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+)
+
+func TestTeamsHierarchy(t *testing.T) {
+ f := newFixture(t)
+ task := f.createTask(t)
+ custom, err := f.Store.CreateSpecialist(ctx, owner, specialistInput("Custom QA"), equipo.Mutation{RequestID: "nav-specialist"})
+ must(t, err)
+ body := f.get(t, owner, "/work").Body.String()
+ if !strings.Contains(body, `href="/specialists/`+custom.Key+`"`) || !strings.Contains(body, "Custom QA") {
+ t.Fatal("custom specialist missing from navigation")
+ }
+ for path, up := range map[string]string{"/work": "/teams", "/conversation": "/work#nav-conversation", "/preferences": "/work#nav-preferences", "/playbooks": "/work#nav-playbooks", "/settings/coordinator": "/work#nav-coordinator", "/tasks/" + task.ID: "/journey", "/tasks/" + task.ID + "/thread": "/tasks/" + task.ID} {
+ w := f.get(t, owner, path)
+ expectHTTP(t, w, 200)
+ if !strings.Contains(w.Body.String(), `href="`+up+`" rel="up"`) {
+ t.Errorf("%s missing parent %s", path, up)
+ }
+ if !strings.Contains(w.Body.String(), `href="/teams"`) {
+ t.Errorf("%s missing Teams link", path)
+ }
+ }
+ w := f.get(t, owner, "/work")
+ for _, href := range []string{"/preferences", "/playbooks", "/settings/coordinator"} {
+ if !strings.Contains(w.Body.String(), `href="`+href+`"`) {
+ t.Errorf("missing navigation %s", href)
+ }
+ }
+ expectHTTP(t, f.get(t, owner, "/teams"), 200)
+}
+
+func TestTeamsDirectoryPrivacy(t *testing.T) {
+ f := newFixture(t)
+ for _, origin := range []string{"javascript:alert(1)", "http://remote.example", "https://user:password@remote.example", "https://remote.example#secret", "https://remote.example#", "https://remote.example?token=secret", "https://remote.example?", "https://remote.example/path", "//remote.example", "https://", "https://remote.example:bad", "https://remote.example\\@evil.example"} {
+ if _, err := f.Store.RememberTeam(ctx, owner, equipo.TeamLink{Origin: origin, Name: "Remote"}, equipo.Mutation{RequestID: origin}); !errors.Is(err, equipo.ErrInvalid) {
+ t.Errorf("unsafe origin %q: %v", origin, err)
+ }
+ }
+ now := time.Now()
+ if _, err := f.Store.RememberTeam(ctx, owner, equipo.TeamLink{Origin: "https://remote.example", Name: "Remote", LastSignedInAt: &now}, equipo.Mutation{RequestID: "forged-time"}); !errors.Is(err, equipo.ErrInvalid) {
+ t.Fatal("trusted submitted sign-in time", err)
+ }
+ row, err := f.Store.RememberTeam(ctx, owner, equipo.TeamLink{Origin: "https://remote.example/", Name: "Private team"}, equipo.Mutation{RequestID: "add"})
+ must(t, err)
+ if row.LastSignedInAt != nil || row.Revision != 1 || row.Origin != "https://remote.example" {
+ t.Fatal(row)
+ }
+ again, err := f.Store.RememberTeam(ctx, owner, equipo.TeamLink{Origin: "https://remote.example/", Name: "Private team"}, equipo.Mutation{RequestID: "add"})
+ must(t, err)
+ if again.ID != row.ID {
+ t.Fatal("duplicate replay")
+ }
+ _, err = f.Store.RememberTeam(ctx, owner, equipo.TeamLink{Origin: row.Origin, Name: "Changed"}, equipo.Mutation{RequestID: "add"})
+ wantInviteError(t, err, equipo.ErrConflict)
+ links, err := f.Store.TeamLinks(ctx, peer)
+ must(t, err)
+ if len(links) != 0 {
+ t.Fatal("private directory leaked", links)
+ }
+ expectHTTP(t, f.get(t, peer, "/teams"), 200)
+ if strings.Contains(f.get(t, peer, "/teams").Body.String(), row.Origin) {
+ t.Fatal("HTML leaked private directory")
+ }
+ wantInviteError(t, f.Store.ForgetTeam(ctx, peer, row.ID, equipo.Mutation{RequestID: "foreign", Revision: 1}), equipo.ErrNotFound)
+ row.Name = "Renamed"
+ _, err = f.Store.RememberTeam(ctx, peer, row, equipo.Mutation{RequestID: "foreign-update", Revision: 1})
+ wantInviteError(t, err, equipo.ErrNotFound)
+ _, err = f.Store.RememberTeam(ctx, owner, row, equipo.Mutation{RequestID: "stale", Revision: 2})
+ wantInviteError(t, err, equipo.ErrConflict)
+ updated, err := f.Store.RememberTeam(ctx, owner, row, equipo.Mutation{RequestID: "rename", Revision: 1})
+ must(t, err)
+ if updated.Revision != 2 {
+ t.Fatal(updated)
+ }
+ wantInviteError(t, f.Store.ForgetTeam(ctx, owner, row.ID, equipo.Mutation{RequestID: "stale-delete", Revision: 1}), equipo.ErrConflict)
+ for range 2 {
+ must(t, f.Store.ForgetTeam(ctx, owner, row.ID, equipo.Mutation{RequestID: "forget", Revision: 2}))
+ }
+ must(t, f.Store.SetMember(ctx, peer, owner.Address, equipo.RoleMember, false, 1))
+ _, err = f.Store.RememberTeam(ctx, owner, equipo.TeamLink{Origin: "https://remote.example/", Name: "Private team"}, equipo.Mutation{RequestID: "add"})
+ wantInviteError(t, err, equipo.ErrForbidden)
+ wantInviteError(t, f.Store.ForgetTeam(ctx, owner, row.ID, equipo.Mutation{RequestID: "forget", Revision: 2}), equipo.ErrForbidden)
+}
+
+func TestTeamsNoFederatedAuthority(t *testing.T) {
+ f := newFixture(t)
+ before := f.count(t, "SELECT count(*) FROM members")
+ transport := http.DefaultTransport
+ http.DefaultTransport = teamsNoNetwork{t}
+ t.Cleanup(func() { http.DefaultTransport = transport })
+ form := actionForm("form-add", 0)
+ form.Set("origin", "https://remote.example")
+ form.Set("name", "Remote")
+ inviteCSRF(t, f, owner, "/teams/links", form, nil)
+ expectHTTP(t, formPost(t, f, owner, "/teams/links", form), 303)
+ rows, err := f.Store.TeamLinks(ctx, owner)
+ must(t, err)
+ if len(rows) != 1 {
+ t.Fatal(rows)
+ }
+ if f.count(t, "SELECT count(*) FROM members") != before || f.count(t, "SELECT count(*) FROM connections") != 0 {
+ t.Fatal("remembering link granted authority")
+ }
+ w := f.get(t, owner, "/teams")
+ expectHTTP(t, w, 200)
+ if !strings.Contains(w.Body.String(), `href="https://remote.example" rel="noreferrer"`) {
+ t.Fatal("remote link leaks referrer or credentials")
+ }
+ form = actionForm("form-forget", rows[0].Revision)
+ expectHTTP(t, formPost(t, f, owner, "/teams/links/"+rows[0].ID+"/forget", form), 303)
+}
+
+type teamsNoNetwork struct{ t *testing.T }
+
+func (s teamsNoNetwork) RoundTrip(*http.Request) (*http.Response, error) {
+ s.t.Error("remembered directory attempted server fetch")
+ return nil, errors.New("network forbidden")
+}
+
+func TestTeamsUnavailableCounts(t *testing.T) {
+ f := newFixture(t)
+ _, err := f.Store.RememberTeam(ctx, owner, equipo.TeamLink{Origin: "https://remote.invalid", Name: "Offline team"}, equipo.Mutation{RequestID: "offline"})
+ must(t, err)
+ f.exec(t, "ALTER TABLE tasks RENAME TO unavailable_tasks")
+ w := f.get(t, owner, "/teams")
+ expectHTTP(t, w, 200)
+ for _, text := range []string{"Counts unavailable", "Last sign-in unknown", "Remote status unavailable"} {
+ if !strings.Contains(w.Body.String(), text) {
+ t.Errorf("missing unknown state %q", text)
+ }
+ }
+ if strings.Contains(w.Body.String(), `equipo-value>0<`) {
+ t.Fatal("unknown count rendered as zero")
+ }
+}
+
+func TestTeamsLandingPreference(t *testing.T) {
+ f := newFixture(t)
+ w := verifyInviteIdentity(t, f, owner.Address)
+ expectHTTP(t, w, 303)
+ if w.Header().Get("Location") != "/" {
+ t.Fatal("sign-in bypasses landing preference", w.Header().Get("Location"))
+ }
+ if f.get(t, owner, "/").Header().Get("Location") != "/conversation" {
+ t.Fatal("wrong default landing")
+ }
+ links, err := f.Store.TeamLinks(ctx, owner)
+ must(t, err)
+ if len(links) != 1 || links[0].Origin != origin || links[0].LastSignedInAt == nil {
+ t.Fatal("verified instance not remembered", links)
+ }
+ form := actionForm("landing", 1)
+ form.Set("action", "landing")
+ form.Set("landing", "work")
+ expectHTTP(t, formPost(t, f, owner, "/settings/coordinator", form), 303)
+ if f.get(t, owner, "/").Header().Get("Location") != "/work" {
+ t.Fatal("override ignored")
+ }
+ task := f.createTask(t)
+ deep := "/tasks/" + task.ID + "/thread"
+ r := httptest.NewRequest("GET", deep, nil)
+ out := httptest.NewRecorder()
+ f.Handler.ServeHTTP(out, r)
+ if !strings.Contains(out.Header().Get("Location"), "return_to=") {
+ t.Fatal("lost signed-out deep link")
+ }
+ w = verifyInviteIdentity(t, f, owner.Address, deep)
+ expectHTTP(t, w, 303)
+ if w.Header().Get("Location") != deep {
+ t.Fatal("sign-in replaced deep link", w.Header())
+ }
+ expectHTTP(t, f.get(t, owner, deep), 200)
+ links, err = f.Store.TeamLinks(ctx, owner)
+ must(t, err)
+ if len(links) != 1 {
+ t.Fatal("sign-in duplicated current instance")
+ }
+ if f.get(t, peer, "/").Header().Get("Location") != "/conversation" {
+ t.Fatal("landing setting shared")
+ }
+}
+
+func TestTeamsTransactionGuards(t *testing.T) {
+ t.Run("roster failure", func(t *testing.T) {
+ f := newFixture(t)
+ f.exec(t, "ALTER TABLE members RENAME TO unavailable_members")
+ if _, err := f.Store.TeamLinks(ctx, owner); err == nil {
+ t.Fatal("roster lookup failed open")
+ }
+ if _, err := f.Store.RememberTeam(ctx, owner, equipo.TeamLink{Origin: "https://remote.example", Name: "Remote"}, equipo.Mutation{RequestID: "roster-failure"}); err == nil {
+ t.Fatal("write ignored roster failure")
+ }
+ if f.count(t, "SELECT count(*) FROM team_links") != 0 {
+ t.Fatal("failed roster wrote a link")
+ }
+ })
+ t.Run("audit rollback", func(t *testing.T) {
+ f := newFixture(t)
+ f.exec(t, "CREATE TRIGGER no_link_audit BEFORE INSERT ON audit_events WHEN NEW.kind LIKE 'team_link.%' BEGIN SELECT RAISE(ABORT,'audit failed'); END")
+ if _, err := f.Store.RememberTeam(ctx, owner, equipo.TeamLink{Origin: "https://remote.example", Name: "Remote"}, equipo.Mutation{RequestID: "audit-failure"}); err == nil {
+ t.Fatal("write ignored audit failure")
+ }
+ if f.count(t, "SELECT count(*) FROM team_links") != 0 || f.count(t, "SELECT count(*) FROM invitation_requests WHERE operation='team.remember'") != 0 {
+ t.Fatal("link or replay survived failed audit")
+ }
+ })
+ t.Run("verified timestamp follows origin", func(t *testing.T) {
+ f := newFixture(t)
+ expectHTTP(t, verifyInviteIdentity(t, f, owner.Address), 303)
+ rows, err := f.Store.TeamLinks(ctx, owner)
+ must(t, err)
+ row := rows[0]
+ row.Origin = "https://changed.example"
+ row.LastSignedInAt = nil
+ result, err := f.Store.RememberTeam(ctx, owner, row, equipo.Mutation{RequestID: "change-origin", Revision: row.Revision})
+ must(t, err)
+ if result.LastSignedInAt != nil {
+ t.Fatal("new origin inherited verified timestamp")
+ }
+ })
+ t.Run("forged form identity", func(t *testing.T) {
+ f := newFixture(t)
+ v := actionForm("forged", 0)
+ v.Set("name", "Remote")
+ v.Set("origin", "https://remote.example")
+ v.Set("person", peer.Address)
+ expectHTTP(t, formPost(t, f, owner, "/teams/links", v), 422)
+ v.Del("person")
+ v.Set("last_signed_in_at", time.Now().Format(time.RFC3339))
+ expectHTTP(t, formPost(t, f, owner, "/teams/links", v), 422)
+ })
+}
+
+func TestTeamsInvitedSignIn(t *testing.T) {
+ f := newFixture(t)
+ in, secret := issueInvite(t, f, invitee.Address)
+ expectHTTP(t, verifyInviteIdentity(t, f, invitee.Address, "/invites/"+in.ID), 303)
+ if f.count(t, "SELECT count(*) FROM team_links WHERE person=?", invitee.Address) != 0 {
+ t.Fatal("pending invite acquired a directory before joining")
+ }
+ _, err := f.Store.AcceptInvitation(ctx, invitee, in.ID, secret, equipo.Mutation{RequestID: "accept-team", Revision: 1})
+ must(t, err)
+ rows, err := f.Store.TeamLinks(ctx, invitee)
+ must(t, err)
+ if len(rows) != 1 || rows[0].Origin != origin || rows[0].LastSignedInAt == nil {
+ t.Fatal("accepted verified invite did not remember current team", rows)
+ }
+}