diff --git a/PLAN.md b/PLAN.md index 08c657b..8aa9b77 100644 --- a/PLAN.md +++ b/PLAN.md @@ -55,7 +55,7 @@ tools over MCP, approvals, limits and visibility, and the JSON API. Schema 39. **Phase 13 (multi-tenant) is under way** on branch `phase13`, with a -Postgres schema per team (decided 2026-11-26); parts 1–2 are built. +Postgres schema per team (decided 2026-11-26); parts 1–3 are built. **Phase 12 (signing in with the Core, OIDC) is set aside for now** (2026-11-26): before it starts, the user will share the Federated Core's @@ -2825,6 +2825,29 @@ stand. (managed Postgres gives it to the main user). Dropping a team drops its role and what it was granted; tests leave no roles or schemas behind. +**Part 3 built 2026-11-26** on `phase13`. +- `/signup` (multi-tenant only; linked from the sign-in page): name, email, + password, the company's name and its website. It makes the person, the + team (its schema and role), makes them its owner, starts the company + profile with the website, and signs them in. An address that has an + account signs in instead. Five sign-ups per IP in 15 minutes. The trial + comes with Phase 14. +- **One website domain per team**: the website's registered domain (the + public suffix list, `golang.org/x/net/publicsuffix`: `shop.example.co.uk` + is `example.co.uk`), kept on the team. The company profile refuses a + website on another domain, and says to set up another team for it. The + server edition doesn't check this yet (it has no team row); the local + edition keeps its list. +- Several teams per person: a team menu at the top of the sidebar (it + switches as soon as it's changed; a button without JavaScript), and + *New team*. Switching checks the person is in it and that it's active. + Signing in opens the team worked in last. +- Invitations work within the team; inviting an address that has an + account (from another team) adds it to this one with the account it has, + and emails them. +- Not yet: an email address confirmed at sign-up. Domain proof (part 4) + keeps an unconfirmed team from doing anything with a website. + 1. **Teams everywhere.** - Every table that holds a company's data gets `team_id`, and its unique keys include it. The settings table's key becomes diff --git a/internal/web/access.go b/internal/web/access.go index adec16b..bad74c3 100644 --- a/internal/web/access.go +++ b/internal/web/access.go @@ -27,7 +27,8 @@ const ( var routeAreas = map[string]string{ "/static": areaPublic, "=/favicon.ico": areaPublic, "=/healthz": areaPublic, "=/mcp": areaPublic, "/signin": areaPublic, "=/signout": areaPublic, "=/forgot": areaPublic, "/reset": areaPublic, - "/setup": areaPublic, "/invite": areaPublic, + "/setup": areaPublic, "/invite": areaPublic, "/signup": areaPublic, + "/teams": areaSignedIn, // The JSON API: its own keys, like /mcp. "/api": areaPublic, diff --git a/internal/web/activity.go b/internal/web/activity.go index 94a5a41..428d01b 100644 --- a/internal/web/activity.go +++ b/internal/web/activity.go @@ -180,7 +180,7 @@ var actionLabels = map[string]string{ "key-made": "made a new key for", "key-revoked": "revoked a key of", "asked-approval": "asked for approval to", "did-on-its-own": "did on its own:", "approved": "approved", "refused": "refused", "allowed-on-its-own": "let an agent act on its own:", "withdrew-on-its-own": "took back what an agent may do on its own:", - "agent-paused": "paused the agent", "agent-resumed": "resumed the agent", "agent-limits": "changed the limits of", + "team-created": "set up the team", "agent-paused": "paused the agent", "agent-resumed": "resumed the agent", "agent-limits": "changed the limits of", "wrote-draft": "wrote a draft:", "edited-draft": "edited a draft:", "edited-change": "edited a proposed change to", "market-added": "added to the Market", "market-changed": "changed in the Market", } diff --git a/internal/web/auth.go b/internal/web/auth.go index 803a7fc..3fd948f 100644 --- a/internal/web/auth.go +++ b/internal/web/auth.go @@ -154,19 +154,48 @@ func (s *Server) toSignIn(w http.ResponseWriter, r *http.Request) { // startSession signs a user in on this browser. func (s *Server) startSession(w http.ResponseWriter, r *http.Request, u *users.User) error { - token, _, err := users.StartSession(s.DB, u.ID, clientIP(r), r.UserAgent(), time.Now()) + team := s.team() + if s.multi() { + // The team they worked in last, else their first. + list, err := users.TeamsOf(s.platform(), u.ID) + if err != nil { + return err + } + team = 0 + for _, t := range list { + if t.Status == users.TeamActive && (team == 0 || t.ID == lastTeam(s, u.ID)) { + team = t.ID + } + } + if team == 0 { + return errors.New("you aren't in any team that's open") + } + } + token, _, err := users.StartSessionIn(s.platform(), u.ID, team, clientIP(r), r.UserAgent(), time.Now()) if err != nil { return err } - if err := users.SignedIn(s.DB, u.ID, time.Now()); err != nil { + if err := users.SignedIn(s.platform(), u.ID, time.Now()); err != nil { return err } + s.setSessionCookie(w, token) + return nil +} + +// lastTeam is the team a person's latest session worked in. +func lastTeam(s *Server, user int64) int64 { + var t int64 + _ = s.platform().QueryRow(`SELECT team_id FROM sessions WHERE user_id = ? ORDER BY created_at DESC LIMIT 1`, user).Scan(&t) + return t +} + +// setSessionCookie gives the browser its session. +func (s *Server) setSessionCookie(w http.ResponseWriter, token string) { http.SetCookie(w, &http.Cookie{ Name: s.cookieName(sessionCookie), Value: token, Path: "/", MaxAge: int(users.SessionMax / time.Second), Secure: s.secureCookies(), HttpOnly: true, SameSite: http.SameSiteLaxMode, }) - return nil } // endSession signs this browser out. diff --git a/internal/web/profile.go b/internal/web/profile.go index 5d3cb1f..d9c74e3 100644 --- a/internal/web/profile.go +++ b/internal/web/profile.go @@ -107,6 +107,10 @@ func (s *Server) profileSave(w http.ResponseWriter, r *http.Request) { Error: "The company's name and description are required.", Data: withBlankRows(p)}) return } + if msg := s.checkWebsites(p); msg != "" { + s.render(w, r, "profile", page{Title: "Company profile", Nav: "settings/profile", Error: msg, Data: withBlankRows(p)}) + return + } if err := profile.Save(s.DB, p); err != nil { s.serverError(w, err) return diff --git a/internal/web/server.go b/internal/web/server.go index 182e702..3be6570 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -251,6 +251,11 @@ func (s *Server) Handler() (http.Handler, error) { // Signing in (the server edition). mux.HandleFunc("GET /setup/{token}", (*Server).setupPage) mux.HandleFunc("POST /setup/{token}", (*Server).setupSave) + mux.HandleFunc("GET /signup", (*Server).signupPage) + mux.HandleFunc("POST /signup", (*Server).signup) + mux.HandleFunc("POST /teams/switch", (*Server).teamSwitch) + mux.HandleFunc("GET /teams/new", (*Server).teamNewPage) + mux.HandleFunc("POST /teams/new", (*Server).teamNew) mux.HandleFunc("GET /signin", (*Server).signinPage) mux.HandleFunc("POST /signin", (*Server).signin) mux.HandleFunc("POST /signin/code", (*Server).signinCode) @@ -687,10 +692,13 @@ type page struct { NewProspects int // companies and people waiting for review, shown in the menu Drafts int // outreach drafts waiting, shown in the menu - Bare bool // no sidebar: pages before signing in - CSRF string // the form token, for htmx (app.js) - Approvals int // agents' requests waiting for this viewer - Viewer *viewer // who's looking + Bare bool // no sidebar: pages before signing in + CSRF string // the form token, for htmx (app.js) + Approvals int // agents' requests waiting for this viewer + Teams []users.TeamInfo // the viewer\'s teams (multi-tenant), for the switcher + TeamID int64 // the team they\'re working in + Multi bool // the multi-tenant edition + Viewer *viewer // who's looking } // Section is the top bar's first breadcrumb, from Nav. @@ -768,7 +776,9 @@ func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, p p p.Viewer = viewerOf(r) if !p.Bare { p.Approvals = s.waitingFor(p.Viewer) + p.Teams, p.TeamID = s.teamsOf(p.Viewer), s.team() } + p.Multi = s.multi() out, err := withCSRF(r, func(b *bytes.Buffer) error { return t.ExecuteTemplate(b, "layout.html", p) }) if err != nil { s.Log.Error("render", "page", name, "err", err) @@ -823,6 +833,8 @@ var flashes = map[string]string{ "withdrawn-class": "Withdrawn: it asks again from now on.", "agent-paused": "Paused: every call it makes is refused until you resume it.", "agent-resumed": "Resumed.", + "team-created": "Your team is set up. Start with the company's profile.", + "added": "Added: they're told by email, and sign in as they do.", "account-removed": "Signed out: posts scheduled to it are back in Posts.", "own-account-connected": "Connected: you can post as it, and an admin can let others.", "deleted": "Deleted.", diff --git a/internal/web/signin.go b/internal/web/signin.go index cccacac..8aa9dcd 100644 --- a/internal/web/signin.go +++ b/internal/web/signin.go @@ -115,6 +115,12 @@ func (s *Server) cannotSignIn(u *users.User) string { case u.Status != users.Active || u.Kind != users.Person: return badSignIn } + if s.multi() { + if list, err := users.TeamsOf(s.platform(), u.ID); err != nil || len(list) == 0 { + return "This account isn't part of any team any more." + } + return "" + } if _, err := users.MembershipOf(s.DB, s.team(), u.ID); err != nil { return "This account isn't part of the team any more. Ask an admin if you need it again." } diff --git a/internal/web/static/app.css b/internal/web/static/app.css index f1fb950..7532d5e 100644 --- a/internal/web/static/app.css +++ b/internal/web/static/app.css @@ -527,3 +527,6 @@ fieldset.post-as { border: 0; padding: 0; margin: 0.5rem 0; } fieldset.post-as label { display: inline-flex; margin-right: 1rem; } input.tiny { width: 5.5rem; display: inline-block; } .bare-main:has(.api-tool) { max-width: 52rem; } +.team-switch { display: flex; align-items: center; gap: 0.4rem; padding: 0 0.9rem 0.6rem; flex-wrap: wrap; } +.team-switch select { flex: 1; min-width: 0; padding: 0.3rem 0.5rem; font-size: 0.9rem; } +.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); } diff --git a/internal/web/static/app.js b/internal/web/static/app.js index 3ffbba6..41222b3 100644 --- a/internal/web/static/app.js +++ b/internal/web/static/app.js @@ -182,4 +182,8 @@ var meta = document.querySelector('meta[name="csrf-token"]'); if (meta && meta.content) e.detail.headers["X-CSRF-Token"] = meta.content; }); + // A select that submits its form when it changes (the team menu). + document.addEventListener("change", function (e) { + if (e.target.matches("select[data-autosubmit]")) e.target.form.requestSubmit(); + }); })(); diff --git a/internal/web/teams.go b/internal/web/teams.go new file mode 100644 index 0000000..4a52bfa --- /dev/null +++ b/internal/web/teams.go @@ -0,0 +1,291 @@ +package web + +import ( + "errors" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "golang.org/x/net/publicsuffix" + + "supermarket/internal/appmail" + "supermarket/internal/audit" + "supermarket/internal/profile" + "supermarket/internal/users" +) + +// Teams on the multi-tenant edition: signing up makes one, a person can +// belong to several and switch between them, and each team works on one +// website domain (a registered domain, with its subdomains). + +// registeredDomain is a website's registered domain: www.shop.example.co.uk +// is example.co.uk. +func registeredDomain(site string) (string, error) { + site = strings.TrimSpace(site) + if !strings.Contains(site, "://") { + site = "https://" + site + } + u, err := url.Parse(site) + if err != nil || u.Hostname() == "" { + return "", fmt.Errorf("%q isn't a website's address", site) + } + host := strings.ToLower(strings.TrimSuffix(u.Hostname(), ".")) + d, err := publicsuffix.EffectiveTLDPlusOne(host) + if err != nil { + return "", fmt.Errorf("%q isn't a website's address on the internet", host) + } + return d, nil +} + +// onDomain says whether a website is the domain or one of its subdomains. +func onDomain(site, domain string) bool { + d, err := registeredDomain(site) + return err == nil && d == domain +} + +// teamDomain is the team's website domain; "" when it has none (the local +// and server editions). +func (s *Server) teamDomain() string { + if !s.multi() { + return "" + } + t, err := users.GetTeam(s.platform(), s.team()) + if err != nil { + return "" + } + return t.Domain +} + +// checkWebsites says what's wrong with a profile's websites for the team: +// on the multi-tenant edition they must be on its domain. +func (s *Server) checkWebsites(p *profile.Profile) string { + dom := s.teamDomain() + if dom == "" { + return "" + } + for _, w := range p.Websites { + if w.URL != "" && !onDomain(w.URL, dom) { + return fmt.Sprintf("%s isn't on %s, this team's domain. A team works on one domain and its subdomains; for another domain, set up another team.", w.URL, dom) + } + } + return "" +} + +// Signing up. + +type signupForm struct { + Email, Company, Website, Problem string +} + +func (s *Server) signupPage(w http.ResponseWriter, r *http.Request) { + if !s.multi() { + http.NotFound(w, r) + return + } + if v, _ := s.lookupSession(r); v != nil { + http.Redirect(w, r, "/", http.StatusSeeOther) + return + } + s.render(w, r, "signup", page{Title: "Sign up", Bare: true, Data: signupForm{}}) +} + +func (s *Server) signup(w http.ResponseWriter, r *http.Request) { + if !s.multi() { + http.NotFound(w, r) + return + } + now := time.Now() + f := signupForm{Email: strings.TrimSpace(r.PostFormValue("email")), Company: strings.TrimSpace(r.PostFormValue("company")), + Website: strings.TrimSpace(r.PostFormValue("website"))} + fail := func(msg string, code int) { + f.Problem = msg + w.WriteHeader(code) + s.render(w, r, "signup", page{Title: "Sign up", Bare: true, Data: f}) + } + ipKey := "signup:ip:" + clientIP(r) + if s.throttled(ipKey, 5, now) { + fail("Several teams were just set up from here: wait a quarter of an hour.", http.StatusTooManyRequests) + return + } + email, err := users.NormalEmail(f.Email) + if err != nil { + fail("Give your email address: you sign in with it.", http.StatusUnprocessableEntity) + return + } + pw := r.PostFormValue("password") + if err := users.CheckNewPassword(pw, email); err != nil { + fail(sentence(err.Error())+".", http.StatusUnprocessableEntity) + return + } + if f.Company == "" { + fail("Give the company's name.", http.StatusUnprocessableEntity) + return + } + domain, err := registeredDomain(f.Website) + if err != nil { + fail("Give the company's website, such as example.com: "+err.Error()+".", http.StatusUnprocessableEntity) + return + } + site := f.Website + if !strings.Contains(site, "://") { + site = "https://" + site + } + // Someone with an account adds a team from inside, signed in: here, + // the address must be new. + if _, err := users.ByEmail(s.platform(), email); err == nil { + fail("There's an account for that address already: sign in, then add a team from the team menu.", http.StatusConflict) + return + } else if !errors.Is(err, users.ErrNotFound) { + s.serverError(w, err) + return + } + _ = users.Fail(s.DB, ipKey, users.ThrottleWindow, now) + u := &users.User{Email: email, Name: strings.TrimSpace(r.PostFormValue("name")), Status: users.Active} + if err := users.Create(s.platform(), u, now); err != nil { + s.serverError(w, err) + return + } + if err := users.SetPassword(s.platform(), u, pw); err != nil { + s.serverError(w, err) + return + } + team, err := s.newTeam(u, f.Company, domain, site, now) + if err != nil { + s.serverError(w, err) + return + } + token, _, err := users.StartSessionIn(s.platform(), u.ID, team.ID, clientIP(r), r.UserAgent(), now) + if err == nil { + err = users.SignedIn(s.platform(), u.ID, now) + } + if err != nil { + s.serverError(w, err) + return + } + s.setSessionCookie(w, token) + redirect(w, r, "/settings/profile", "team-created") +} + +// newTeam makes a team, its schema and its owner, with the company's +// profile started. +func (s *Server) newTeam(owner *users.User, company, domain, site string, now time.Time) (*users.TeamInfo, error) { + team, err := users.CreateTeam(s.platform(), company, domain, now) + if err != nil { + return nil, err + } + if err := s.Teams.Create(team.ID); err != nil { + return nil, err + } + if err := users.Join(s.platform(), team.ID, owner.ID, users.Owner, nil, now); err != nil { + return nil, err + } + ts, err := s.forTeam(team.ID) + if err != nil { + return nil, err + } + if err := profile.Save(ts.DB, &profile.Profile{Name: company, Websites: []profile.Website{{URL: site}}}); err != nil { + return nil, err + } + ts.record(audit.Entry{UserID: owner.ID, UserName: displayName(owner), Action: "team-created", Target: company, Detail: domain}) + s.Log.Info("teams: created", "team", team.ID, "domain", domain, "owner", owner.Email) + return team, nil +} + +// Several teams. + +// teamsOf are the viewer's teams, for the switcher. +func (s *Server) teamsOf(v *viewer) []users.TeamInfo { + if !s.multi() || v == nil || v.User == nil { + return nil + } + list, _ := users.TeamsOf(s.platform(), v.User.ID) + return list +} + +// teamSwitch moves the session to another of the person's teams. +func (s *Server) teamSwitch(w http.ResponseWriter, r *http.Request) { + v := viewerOf(r) + if !s.multi() || v.Session == nil { + http.NotFound(w, r) + return + } + id, _ := strconv.ParseInt(r.PostFormValue("team"), 10, 64) + if _, err := users.MembershipOf(s.platform(), id, v.User.ID); err != nil { + s.forbidden(w, r) + return + } + if t, err := users.GetTeam(s.platform(), id); err != nil || t.Status != users.TeamActive { + s.forbidden(w, r) + return + } + if err := users.SetSessionTeam(s.platform(), v.Session.ID, id); err != nil { + s.serverError(w, err) + return + } + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +// teamNewPage and teamNew: a signed-in person sets up another team. +func (s *Server) teamNewPage(w http.ResponseWriter, r *http.Request) { + if !s.multi() || viewerOf(r).User == nil { + http.NotFound(w, r) + return + } + s.render(w, r, "team-new", page{Title: "New team", Data: signupForm{}}) +} + +func (s *Server) teamNew(w http.ResponseWriter, r *http.Request) { + v := viewerOf(r) + if !s.multi() || v.User == nil { + http.NotFound(w, r) + return + } + now := time.Now() + f := signupForm{Company: strings.TrimSpace(r.PostFormValue("company")), Website: strings.TrimSpace(r.PostFormValue("website"))} + domain, err := registeredDomain(f.Website) + switch { + case f.Company == "": + f.Problem = "Give the company's name." + case err != nil: + f.Problem = "Give the company's website, such as example.com." + } + if f.Problem != "" { + w.WriteHeader(http.StatusUnprocessableEntity) + s.render(w, r, "team-new", page{Title: "New team", Data: f}) + return + } + site := f.Website + if !strings.Contains(site, "://") { + site = "https://" + site + } + team, err := s.newTeam(v.User, f.Company, domain, site, now) + if err != nil { + s.serverError(w, err) + return + } + if err := users.SetSessionTeam(s.platform(), v.Session.ID, team.ID); err != nil { + s.serverError(w, err) + return + } + redirect(w, r, "/settings/profile", "team-created") +} + +// addExisting adds someone who already has an account to the team (they +// sign in as they do), and tells them. +func (s *Server) addExisting(by *viewer, u *users.User, role users.Role, mods map[string]users.Access, now time.Time) error { + if err := users.Join(s.platform(), s.team(), u.ID, role, mods, now); err != nil { + return err + } + team, _ := users.GetTeam(s.platform(), s.team()) + name := "a team" + if team != nil { + name = team.Name + } + s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: displayName(by.User) + " added you to " + name + " on Supermarket", + Body: "Hello" + nameSuffix(u.Name) + ",\n\n" + displayName(by.User) + " added you to " + name + " on Supermarket.\n\n" + + "Sign in as you do, and choose " + name + " from the team menu:\n" + s.PublicURL + "/signin\n"}) + return nil +} diff --git a/internal/web/teams_test.go b/internal/web/teams_test.go index 13af2fe..25a6ae0 100644 --- a/internal/web/teams_test.go +++ b/internal/web/teams_test.go @@ -3,6 +3,7 @@ package web import ( "net/http" "net/url" + "strconv" "strings" "testing" "time" @@ -133,3 +134,117 @@ func newAgentIn(t *testing.T, ts *Server, name string, scopes map[string]users.A } return u, key } + +func TestRegisteredDomain(t *testing.T) { + for in, want := range map[string]string{"example.com": "example.com", "https://www.Example.com/x": "example.com", + "shop.example.co.uk": "example.co.uk", "http://cloud.acme.io:8080": "acme.io"} { + if got, err := registeredDomain(in); err != nil || got != want { + t.Errorf("%s: %q %v", in, got, err) + } + } + for _, bad := range []string{"", "localhost", "co.uk"} { + if _, err := registeredDomain(bad); err == nil { + t.Errorf("%q accepted", bad) + } + } + if !onDomain("https://enterprise.acme.io", "acme.io") || onDomain("https://acme.io.evil.com", "acme.io") { + t.Error("onDomain") + } +} + +func TestSignUpAndSwitchTeams(t *testing.T) { + s, h := newMultiEdition(t) + form := url.Values{"name": {"Olu"}, "email": {"olu@acme.example"}, "password": {"a long enough one"}, "company": {"Acme"}, "website": {"www.acme.io"}} + if rec := do(h, http.MethodGet, "/signin", nil, nil); !strings.Contains(rec.Body.String(), `href="/signup"`) { + t.Error("no sign-up link") + } + rec := postForm(h, "/signup", form) + if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/settings/profile?msg=team-created" { + t.Fatalf("sign up: %d %s", rec.Code, rec.Body.String()) + } + c := cookieOf(rec, sessionCookie) + u, _ := users.ByEmail(s.platform(), "olu@acme.example") + list, _ := users.TeamsOf(s.platform(), u.ID) + if len(list) != 1 || list[0].Domain != "acme.io" || list[0].Name != "Acme" { + t.Fatalf("teams %+v", list) + } + body := as(h, c, http.MethodGet, "/settings/profile", nil).Body.String() + if !strings.Contains(body, "https://www.acme.io") { + t.Error("profile not started") + } + // Same address again: sign in instead. + if rec := postForm(h, "/signup", form); rec.Code != http.StatusConflict { + t.Errorf("twice: %d", rec.Code) + } + // The profile keeps to the team's domain. + rec = as(h, c, http.MethodPost, "/settings/profile", url.Values{"name": {"Acme"}, "description": {"x"}, "website_url": {"https://other.example"}}) + if !strings.Contains(rec.Body.String(), "isn't on acme.io") { + t.Errorf("another domain accepted: %s", rec.Body.String()) + } + + // A second team, from inside; the menu switches. + rec = as(h, c, http.MethodPost, "/teams/new", url.Values{"company": {"Acme Labs"}, "website": {"acmelabs.dev"}}) + if rec.Code != http.StatusSeeOther { + t.Fatalf("new team: %d %s", rec.Code, rec.Body.String()) + } + list, _ = users.TeamsOf(s.platform(), u.ID) + if len(list) != 2 { + t.Fatalf("teams %+v", list) + } + body = as(h, c, http.MethodGet, "/", nil).Body.String() + if !strings.Contains(body, `