283 lines
8.8 KiB
Go
283 lines
8.8 KiB
Go
package web
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"html"
|
|
"net/http"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"supermarket/internal/users"
|
|
)
|
|
|
|
// Who may reach what. Every route belongs to an area: a module, Settings
|
|
// (admins), anything signed in, or public. One table maps addresses to
|
|
// areas, by their first segments; the app won't start with a route that
|
|
// isn't in it. A GET reads; anything else changes, which a member needs
|
|
// edit on the module for.
|
|
|
|
const (
|
|
areaPublic = "public" // no sign-in: the sign-in pages, static files, MCP (its own key)
|
|
areaSignedIn = "signed-in" // anyone signed in: the Overview, Search, Your account
|
|
areaAdmin = "admin" // admins and the owner: Settings, users, connections
|
|
)
|
|
|
|
// routeAreas maps addresses to areas. An entry matches its path and
|
|
// everything under it (/seo matches /seo/check); one starting with = only
|
|
// itself. The longest match wins, and an exact one over a prefix.
|
|
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, "/signup": areaPublic,
|
|
// Stripe's events: signed with the webhook's secret instead.
|
|
"=/billing/stripe": areaPublic,
|
|
"/teams": areaSignedIn,
|
|
// The JSON API: its own keys, like /mcp.
|
|
"/api": areaPublic,
|
|
|
|
"=/": areaSignedIn, "=/search": areaSignedIn, "/settings/account": areaSignedIn,
|
|
"/users": areaSignedIn, "=/settings": areaSignedIn,
|
|
// Each request is checked against its module (approvals.go).
|
|
"/approvals": areaSignedIn,
|
|
// Old addresses that only redirect.
|
|
"=/profile": areaSignedIn, "=/core": areaSignedIn,
|
|
|
|
"/settings": areaAdmin,
|
|
"/platform": areaPlatform,
|
|
// Signing in to a posting account: admins for the company's, anyone
|
|
// with Content for their own (oauthStart checks which).
|
|
"/auth": areaSignedIn,
|
|
// The Core's sign-in comes back here, before anyone is signed in.
|
|
"/auth/core": areaPublic,
|
|
|
|
"/content": "content", "/posts": "content", "/inbox": "content", "/drafts": "content", "/reddit": "content",
|
|
"/prospects": "prospects", "/signals": "prospects", "/lead-sources": "prospects", "/funnel": "prospects",
|
|
"/outreach": "prospects", "/crm": "prospects",
|
|
"/seo": "seo",
|
|
"/sites": "sites", "/preview": "sites",
|
|
"/metrics": "metrics",
|
|
"/market": "market", "/inventory": "market",
|
|
}
|
|
|
|
// areaOf is the area of a path (or a route's pattern, without its method).
|
|
func areaOf(path string) (string, bool) {
|
|
path = strings.TrimSuffix(path, "{$}")
|
|
if len(path) > 1 {
|
|
path = strings.TrimSuffix(path, "/")
|
|
}
|
|
best, area := -1, ""
|
|
for prefix, a := range routeAreas {
|
|
exact := strings.HasPrefix(prefix, "=")
|
|
p := strings.TrimPrefix(prefix, "=")
|
|
ok := path == p || (!exact && strings.HasPrefix(path, p+"/"))
|
|
score := 2 * len(p) // an exact entry beats a prefix of the same path
|
|
if exact {
|
|
score++
|
|
}
|
|
if ok && score > best {
|
|
best, area = score, a
|
|
}
|
|
}
|
|
return area, best >= 0
|
|
}
|
|
|
|
// publicPath says whether a path is reached without signing in.
|
|
func publicPath(p string) bool {
|
|
a, ok := areaOf(p)
|
|
return ok && a == areaPublic
|
|
}
|
|
|
|
// can says whether the viewer may read (write false) or change things in
|
|
// an area.
|
|
func (v *viewer) can(area string, write bool) bool {
|
|
switch area {
|
|
case areaPublic:
|
|
return true
|
|
case areaSignedIn:
|
|
return v.User != nil || v == localOwner
|
|
case areaAdmin:
|
|
return v.Member.Admin()
|
|
case areaPlatform:
|
|
return v.Platform
|
|
}
|
|
return v.Member.Can(area, write)
|
|
}
|
|
|
|
// canPost says whether the viewer may send a form to a path.
|
|
func (v *viewer) canPost(path string) bool {
|
|
if i := strings.IndexAny(path, "?#"); i >= 0 {
|
|
path = path[:i]
|
|
}
|
|
a, ok := areaOf(path)
|
|
return ok && v.can(a, true)
|
|
}
|
|
|
|
// routes registers handlers, each behind the check for its area.
|
|
type routes struct {
|
|
s *Server
|
|
mux *http.ServeMux
|
|
unmapped []string
|
|
patterns []string // every route, for the tests that walk them all
|
|
}
|
|
|
|
// HandleFunc registers a handler: a method expression such as
|
|
// (*Server).seoPage, run on the Server for the request's team; or a plain
|
|
// handler that needs no team.
|
|
func (rt *routes) HandleFunc(pattern string, fn any) {
|
|
switch f := fn.(type) {
|
|
case func(*Server, http.ResponseWriter, *http.Request):
|
|
rt.Handle(pattern, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
ts, err := rt.s.teamServer(r)
|
|
if err != nil {
|
|
rt.s.serverError(w, err)
|
|
return
|
|
}
|
|
f(ts, w, r)
|
|
}))
|
|
case func(http.ResponseWriter, *http.Request):
|
|
rt.Handle(pattern, http.HandlerFunc(f))
|
|
case http.HandlerFunc:
|
|
rt.Handle(pattern, f)
|
|
default:
|
|
panic(fmt.Sprintf("route %s: a handler of type %T", pattern, fn))
|
|
}
|
|
}
|
|
|
|
func (rt *routes) Handle(pattern string, h http.Handler) {
|
|
path := pattern
|
|
if i := strings.Index(pattern, " "); i >= 0 {
|
|
path = pattern[i+1:]
|
|
}
|
|
area, ok := areaOf(path)
|
|
if !ok {
|
|
rt.unmapped = append(rt.unmapped, pattern)
|
|
return
|
|
}
|
|
rt.patterns = append(rt.patterns, pattern)
|
|
rt.mux.Handle(pattern, rt.s.allow(area, rt.s.guardDomain(pattern, rt.s.audited(pattern, h))))
|
|
}
|
|
|
|
func (rt *routes) err() error {
|
|
if len(rt.unmapped) == 0 {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("routes without an area (add them to routeAreas, in access.go): %s", strings.Join(rt.unmapped, ", "))
|
|
}
|
|
|
|
// allow lets a request through if the viewer may reach its area: reading,
|
|
// or for anything but GET, changing.
|
|
func (s *Server) allow(area string, next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
v := viewerOf(r)
|
|
if area != areaPublic && v.User == nil && v != localOwner {
|
|
s.toSignIn(w, r)
|
|
return
|
|
}
|
|
write := !safeMethod(r.Method)
|
|
// A lapsed team changes nothing, but its billing, people's own
|
|
// accounts, and switching teams.
|
|
if v.ReadOnly && write && !strings.HasPrefix(r.URL.Path, "/settings/billing") &&
|
|
!platformPath(r.URL.Path) && !strings.HasPrefix(r.URL.Path, "/teams/") {
|
|
http.Error(w, sentence(errLapsed.Error())+".", http.StatusForbidden)
|
|
return
|
|
}
|
|
if !v.can(area, write) {
|
|
// A module the team's plan has only to read: say so.
|
|
if write && v.Member.Cap != nil && v.Member.Cap[area] == users.View && v.Member.Can(area, false) {
|
|
if ts, err := s.teamServer(r); err == nil {
|
|
if plan, _ := ts.teamPlan(); plan != nil {
|
|
http.Error(w, fmt.Sprintf("The %s plan doesn't include %s: what's there stays, to read. The team's owner can move up a plan under Settings → Billing.",
|
|
plan.Name, grantName(area)), http.StatusForbidden)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
s.forbidden(w, r)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
// Pages for members who may only view: every form that sends to a module
|
|
// they can't change is shown inside a disabled fieldset, so they see what
|
|
// it holds but can't submit it (and its buttons are hidden, app.css), and
|
|
// htmx buttons that would change something are hidden. The server
|
|
// refuses those requests anyway (allow).
|
|
|
|
var (
|
|
formClose = regexp.MustCompile(`(?i)</form\s*>`)
|
|
hxChange = regexp.MustCompile(`(?is)<[a-z]+\b[^>]*\bhx-(?:post|put|patch|delete)\s*=\s*"([^"]*)"[^>]*>`)
|
|
)
|
|
|
|
// rewriteForms adds the CSRF token to the forms the viewer may send, and
|
|
// disables the others. here is the page's own path, for forms without an
|
|
// action.
|
|
func rewriteForms(page []byte, token, here string, v *viewer) []byte {
|
|
if token == "" && v == nil {
|
|
return page
|
|
}
|
|
var out bytes.Buffer
|
|
out.Grow(len(page) + 1024)
|
|
rest := page
|
|
for {
|
|
loc := formTag.FindIndex(rest)
|
|
if loc == nil {
|
|
out.Write(rest)
|
|
break
|
|
}
|
|
tag := rest[loc[0]:loc[1]]
|
|
out.Write(rest[:loc[0]])
|
|
rest = rest[loc[1]:]
|
|
method, action, _ := formAttrs(tag)
|
|
target := action
|
|
if target == "" {
|
|
target = here
|
|
}
|
|
if method != "post" || !ownAddress(action) || v == nil || v.canPost(target) {
|
|
out.Write(addCSRF(tag, token))
|
|
continue
|
|
}
|
|
// Shown, not sent: the fieldset holds everything up to </form>.
|
|
out.Write(tag)
|
|
out.WriteString(`<fieldset class="readonly" disabled>`)
|
|
end := formClose.FindIndex(rest)
|
|
if end == nil {
|
|
out.Write(rest)
|
|
out.WriteString(`</fieldset>`)
|
|
rest = nil
|
|
continue
|
|
}
|
|
out.Write(rest[:end[0]])
|
|
out.WriteString(`</fieldset>`)
|
|
out.Write(rest[end[0]:end[1]])
|
|
rest = rest[end[1]:]
|
|
}
|
|
if v == nil {
|
|
return out.Bytes()
|
|
}
|
|
return hxChange.ReplaceAllFunc(out.Bytes(), func(tag []byte) []byte {
|
|
m := hxChange.FindSubmatch(tag)
|
|
if v.canPost(html.UnescapeString(string(m[1]))) {
|
|
return tag
|
|
}
|
|
return append(tag[:len(tag)-1:len(tag)-1], []byte(` hidden disabled>`)...)
|
|
})
|
|
}
|
|
|
|
// formAttrs reads a form tag's method (lower case), action and enctype.
|
|
func formAttrs(tag []byte) (method, action, enctype string) {
|
|
for _, m := range attrRe.FindAllSubmatch(tag, -1) {
|
|
switch strings.ToLower(string(m[1])) {
|
|
case "method":
|
|
method = strings.ToLower(string(m[2]))
|
|
case "action":
|
|
action = html.UnescapeString(string(m[2]))
|
|
case "enctype":
|
|
enctype = strings.ToLower(string(m[2]))
|
|
}
|
|
}
|
|
return
|
|
}
|