Sign-in:
- Google, GitHub, Microsoft and any OpenID Connect provider, set up in the
admin panel (secrets are write-only). PocketBase talks to the provider,
and docwell-server keeps the state and PKCE verifier. Accounts a
provider creates follow the sign-up switch and the domain list; refused
ones are removed again.
- Two-step sign-in with an authenticator app (TOTP), set up under "Your
account", with ten single-use recovery codes. After any first factor
(password, email code, provider) the session is held behind a
five-minute challenge: five tries, each code works once. Turning it off
needs a code. Managers can reset it for someone who lost their phone.
Both the web app and the admin panel ask for the code.
Integrations:
- Personal API tokens ("dw_…") that act as their owner, read-only or
read-write, with optional expiry. Only a hash is stored, and the token is
shown once. Tokens cannot manage tokens or two-step sign-in. Admins see
and can revoke their organization's tokens.
- Workspace webhooks for page, comment and space events. Deliveries are
HMAC-SHA256 signed and retried (10 s, 1 min, 5 min), with a 30-day log
and a test button. Loopback and link-local addresses are refused
(DOCWELL_WEBHOOKS_ALLOW_LOCAL is for development).
Audit log: sign-ins (including failures and second steps, filed under the
account's organization) and every successful change request, by route and
path ids, never bodies. Superadmins see everything and org admins their
organization. It is searchable and exportable as CSV in the admin panel's
new Security page, and kept for DOCWELL_AUDIT_RETENTION_DAYS (365).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
435 lines
14 KiB
Go
435 lines
14 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package directory
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
|
|
"docwell/server/internal/access"
|
|
"docwell/server/internal/apperr"
|
|
"docwell/server/internal/store/pocketbase"
|
|
)
|
|
|
|
// ---- Spaces ----------------------------------------------------------------
|
|
|
|
type Space struct {
|
|
ID string `json:"id"`
|
|
Workspace string `json:"workspace"`
|
|
Name string `json:"name"`
|
|
Slug string `json:"slug"`
|
|
Icon string `json:"icon"`
|
|
Description string `json:"description"`
|
|
Visibility string `json:"visibility"`
|
|
DefaultRole string `json:"defaultRole"`
|
|
// Role is the caller's effective space role after the cascade.
|
|
Role string `json:"role"`
|
|
// Limited is true when the caller cannot open the space itself and sees
|
|
// only the pages shared with them (Role is then "").
|
|
Limited bool `json:"limited"`
|
|
Created string `json:"created"`
|
|
}
|
|
|
|
type spaceRecord struct {
|
|
ID string `json:"id"`
|
|
Workspace string `json:"workspace"`
|
|
Name string `json:"name"`
|
|
Slug string `json:"slug"`
|
|
Icon string `json:"icon"`
|
|
Description string `json:"description"`
|
|
Visibility string `json:"visibility"`
|
|
DefaultRole string `json:"default_role"`
|
|
Created string `json:"created"`
|
|
}
|
|
|
|
func (r spaceRecord) view(role string) Space {
|
|
def := r.DefaultRole
|
|
if !access.ValidDefaultRole(def) {
|
|
def = access.SpaceEditor
|
|
}
|
|
return Space{
|
|
ID: r.ID, Workspace: r.Workspace, Name: r.Name, Slug: r.Slug, Icon: r.Icon, Description: r.Description,
|
|
Visibility: r.Visibility, DefaultRole: def, Role: role, Limited: role == "", Created: r.Created,
|
|
}
|
|
}
|
|
|
|
type spaceMemberRecord struct {
|
|
ID string `json:"id"`
|
|
Space string `json:"space"`
|
|
PrincipalID string `json:"principal_id"`
|
|
Role string `json:"role"`
|
|
}
|
|
|
|
// listAll pages through a whole collection query (PocketBase caps a page at 1000 records).
|
|
func listAll[T any](ctx context.Context, s *Service, collection string, opts pocketbase.ListOptions) ([]T, error) {
|
|
opts.PerPage = 1000
|
|
var out []T
|
|
for page := 1; ; page++ {
|
|
opts.Page = page
|
|
res, err := pocketbase.List[T](ctx, s.pb, collection, opts)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, res.Items...)
|
|
if page >= res.TotalPages || len(res.Items) == 0 {
|
|
return out, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
// userSpaceMemberships lists a user's space memberships, in one workspace or ("" ) all.
|
|
func (s *Service) userSpaceMemberships(ctx context.Context, userID, wsID string) ([]spaceMemberRecord, error) {
|
|
filter := fmt.Sprintf("principal_type = 'user' && principal_id = '%s'", userID)
|
|
if wsID != "" {
|
|
filter += fmt.Sprintf(" && space.workspace = '%s'", wsID)
|
|
}
|
|
return listAll[spaceMemberRecord](ctx, s, "space_members", pocketbase.ListOptions{Filter: filter})
|
|
}
|
|
|
|
func (s *Service) spaceMembership(ctx context.Context, spaceID, userID string) (spaceMemberRecord, error) {
|
|
res, err := pocketbase.List[spaceMemberRecord](ctx, s.pb, "space_members", pocketbase.ListOptions{
|
|
PerPage: 1, Filter: fmt.Sprintf("space = '%s' && principal_type = 'user' && principal_id = '%s'", spaceID, userID),
|
|
})
|
|
if err != nil || len(res.Items) == 0 {
|
|
return spaceMemberRecord{}, err
|
|
}
|
|
return res.Items[0], nil
|
|
}
|
|
|
|
// spaceAccess is a space with the caller's workspace and space roles. From
|
|
// pageFor, role is the caller's role on that page (see pageRules) and
|
|
// spaceRole stays the role in the space itself.
|
|
type spaceAccess struct {
|
|
space spaceRecord
|
|
ws workspaceRecord
|
|
wsRole string
|
|
spaceRole string
|
|
role string
|
|
}
|
|
|
|
// loadSpace loads a space with c's roles, without checking that c may open it.
|
|
func (s *Service) loadSpace(ctx context.Context, c access.Caller, id string) (spaceAccess, error) {
|
|
if !validID(id) {
|
|
return spaceAccess{}, apperr.NotFound("space not found")
|
|
}
|
|
sp, err := pocketbase.Get[spaceRecord](ctx, s.pb, "spaces", id)
|
|
if err != nil {
|
|
return spaceAccess{}, mapPB(err, "space not found")
|
|
}
|
|
ws, err := s.getWorkspace(ctx, sp.Workspace)
|
|
if err != nil {
|
|
return spaceAccess{}, err
|
|
}
|
|
wsRole, err := s.effective(ctx, c, ws)
|
|
if err != nil {
|
|
return spaceAccess{}, err
|
|
}
|
|
var explicit string
|
|
if wsRole != "" && !access.AtLeast(wsRole, access.WorkspaceAdmin) {
|
|
if explicit, err = s.explicitSpaceRole(ctx, sp, c.ID); err != nil {
|
|
return spaceAccess{}, err
|
|
}
|
|
}
|
|
role := access.SpaceRole(wsRole, sp.Visibility, sp.DefaultRole, explicit)
|
|
return spaceAccess{space: sp, ws: ws, wsRole: wsRole, spaceRole: role, role: role}, nil
|
|
}
|
|
|
|
// spaceFor loads a space with c's roles. A space c cannot open is reported as
|
|
// not found, like a workspace.
|
|
func (s *Service) spaceFor(ctx context.Context, c access.Caller, id string) (spaceAccess, error) {
|
|
a, err := s.loadSpace(ctx, c, id)
|
|
if err != nil {
|
|
return spaceAccess{}, err
|
|
}
|
|
if err := access.ViewSpace(a.role); err != nil {
|
|
return spaceAccess{}, err
|
|
}
|
|
return a, nil
|
|
}
|
|
|
|
// spaceReach is spaceFor that also lets in a workspace member who cannot
|
|
// open the space but holds page grants in it (a guest a page was shared
|
|
// with). Their role stays "": only pageRules gives them anything.
|
|
func (s *Service) spaceReach(ctx context.Context, c access.Caller, id string) (spaceAccess, error) {
|
|
a, err := s.loadSpace(ctx, c, id)
|
|
if err != nil || a.role != "" {
|
|
return a, err
|
|
}
|
|
if a.wsRole != "" {
|
|
has, err := s.hasPageGrants(ctx, c, a.space)
|
|
if err != nil {
|
|
return spaceAccess{}, err
|
|
}
|
|
if has {
|
|
return a, nil
|
|
}
|
|
}
|
|
return spaceAccess{}, apperr.NotFound("space not found")
|
|
}
|
|
|
|
// ListSpaces lists the spaces of a workspace that c can open.
|
|
func (s *Service) ListSpaces(ctx context.Context, c access.Caller, wsID string) ([]Space, error) {
|
|
ws, wsRole, err := s.workspaceFor(ctx, c, wsID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
spaces, err := listAll[spaceRecord](ctx, s, "spaces", pocketbase.ListOptions{
|
|
Filter: fmt.Sprintf("workspace = '%s'", ws.ID), Sort: "name",
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
explicit := map[string]string{}
|
|
if !access.AtLeast(wsRole, access.WorkspaceAdmin) {
|
|
mine, err := s.userSpaceMemberships(ctx, c.ID, ws.ID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, m := range mine {
|
|
explicit[m.Space] = m.Role
|
|
}
|
|
groups, err := s.userGroups(ctx, c.ID, ws.ID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
grants, err := s.groupGrants(ctx, groups, "")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, g := range grants {
|
|
explicit[g.Space] = access.HigherSpaceRole(explicit[g.Space], g.Role)
|
|
}
|
|
}
|
|
var shared map[string]bool
|
|
if !access.AtLeast(wsRole, access.WorkspaceAdmin) {
|
|
if shared, err = s.grantedSpaces(ctx, c, ws.ID); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
out := []Space{}
|
|
for _, sp := range spaces {
|
|
if role := access.SpaceRole(wsRole, sp.Visibility, sp.DefaultRole, explicit[sp.ID]); role != "" || shared[sp.ID] {
|
|
out = append(out, sp.view(role))
|
|
}
|
|
}
|
|
sort.SliceStable(out, func(i, j int) bool { return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name) })
|
|
return out, nil
|
|
}
|
|
|
|
// GetSpace returns one space with c's role (Limited for someone who sees
|
|
// only pages shared with them).
|
|
func (s *Service) GetSpace(ctx context.Context, c access.Caller, id string) (Space, error) {
|
|
a, err := s.spaceReach(ctx, c, id)
|
|
if err != nil {
|
|
return Space{}, err
|
|
}
|
|
return a.space.view(a.role), nil
|
|
}
|
|
|
|
type CreateSpaceInput struct {
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
Icon string `json:"icon"`
|
|
Visibility string `json:"visibility"`
|
|
}
|
|
|
|
// CreateSpace creates a space in a workspace (workspace admin or above).
|
|
func (s *Service) CreateSpace(ctx context.Context, c access.Caller, wsID string, in CreateSpaceInput) (Space, error) {
|
|
name, err := cleanName(in.Name, "Space")
|
|
if err != nil {
|
|
return Space{}, err
|
|
}
|
|
visibility := in.Visibility
|
|
if visibility == "" {
|
|
visibility = access.SpaceOpen
|
|
}
|
|
if visibility != access.SpaceOpen && visibility != access.SpacePrivate {
|
|
return Space{}, apperr.InvalidFields(map[string]string{"visibility": "Visibility must be open or private."})
|
|
}
|
|
ws, wsRole, err := s.workspaceFor(ctx, c, wsID)
|
|
if err != nil {
|
|
return Space{}, err
|
|
}
|
|
if err := access.CreateSpace(wsRole); err != nil {
|
|
return Space{}, err
|
|
}
|
|
base := slugify(name, "space")
|
|
for i := 1; i <= 50; i++ {
|
|
slug := base
|
|
if i > 1 {
|
|
slug = fmt.Sprintf("%s-%d", base, i)
|
|
}
|
|
rec, err := pocketbase.Create[spaceRecord](ctx, s.pb, "spaces", map[string]any{
|
|
"workspace": ws.ID, "name": name, "slug": slug, "icon": strings.TrimSpace(in.Icon),
|
|
"description": strings.TrimSpace(in.Description), "visibility": visibility, "default_role": access.SpaceEditor,
|
|
})
|
|
var pbErr *pocketbase.Error
|
|
if errors.As(err, &pbErr) && pbErr.Data["slug"].Code == "validation_not_unique" {
|
|
continue
|
|
}
|
|
if err != nil {
|
|
return Space{}, mapPB(err, "space not found")
|
|
}
|
|
s.emitSpace(ctx, "space.created", rec, c.ID)
|
|
return rec.view(access.SpaceAdmin), nil
|
|
}
|
|
return Space{}, apperr.Conflict("could not find a free space address; try another name")
|
|
}
|
|
|
|
// UpdateSpaceInput changes only the fields that are set.
|
|
type UpdateSpaceInput struct {
|
|
Name *string `json:"name"`
|
|
Description *string `json:"description"`
|
|
Icon *string `json:"icon"`
|
|
Visibility *string `json:"visibility"`
|
|
DefaultRole *string `json:"defaultRole"`
|
|
}
|
|
|
|
// UpdateSpace changes a space's settings (space admin).
|
|
func (s *Service) UpdateSpace(ctx context.Context, c access.Caller, id string, in UpdateSpaceInput) (Space, error) {
|
|
a, err := s.spaceFor(ctx, c, id)
|
|
if err != nil {
|
|
return Space{}, err
|
|
}
|
|
if err := access.ManageSpace(a.role); err != nil {
|
|
return Space{}, err
|
|
}
|
|
patch := map[string]any{}
|
|
if in.Name != nil {
|
|
name, err := cleanName(*in.Name, "Space")
|
|
if err != nil {
|
|
return Space{}, err
|
|
}
|
|
patch["name"] = name
|
|
}
|
|
if in.Description != nil {
|
|
patch["description"] = strings.TrimSpace(*in.Description)
|
|
}
|
|
if in.Icon != nil {
|
|
patch["icon"] = strings.TrimSpace(*in.Icon)
|
|
}
|
|
if in.Visibility != nil {
|
|
if *in.Visibility != access.SpaceOpen && *in.Visibility != access.SpacePrivate {
|
|
return Space{}, apperr.InvalidFields(map[string]string{"visibility": "Visibility must be open or private."})
|
|
}
|
|
patch["visibility"] = *in.Visibility
|
|
}
|
|
if in.DefaultRole != nil {
|
|
if !access.ValidDefaultRole(*in.DefaultRole) {
|
|
return Space{}, apperr.InvalidFields(map[string]string{"defaultRole": "Default role must be editor, commenter or viewer."})
|
|
}
|
|
patch["default_role"] = *in.DefaultRole
|
|
}
|
|
if len(patch) == 0 {
|
|
return a.space.view(a.role), nil
|
|
}
|
|
rec, err := pocketbase.Update[spaceRecord](ctx, s.pb, "spaces", a.space.ID, patch)
|
|
if err != nil {
|
|
return Space{}, mapPB(err, "space not found")
|
|
}
|
|
return rec.view(a.role), nil
|
|
}
|
|
|
|
// DeleteSpace deletes a space with all of its pages (workspace admin).
|
|
func (s *Service) DeleteSpace(ctx context.Context, c access.Caller, id string) error {
|
|
a, err := s.spaceFor(ctx, c, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := access.DeleteSpace(a.wsRole); err != nil {
|
|
return err
|
|
}
|
|
if err := s.pb.Delete(ctx, "spaces", a.space.ID); err != nil {
|
|
return mapPB(err, "space not found")
|
|
}
|
|
s.emitSpace(ctx, "space.deleted", a.space, c.ID)
|
|
return nil
|
|
}
|
|
|
|
// ListSpaceMembers lists a space's explicit members (any space role may look).
|
|
// Workspace admins manage every space without being listed.
|
|
func (s *Service) ListSpaceMembers(ctx context.Context, c access.Caller, id string) ([]Member, error) {
|
|
a, err := s.spaceFor(ctx, c, id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
members, err := listAll[spaceMemberRecord](ctx, s, "space_members", pocketbase.ListOptions{
|
|
Filter: fmt.Sprintf("space = '%s' && principal_type = 'user'", a.space.ID),
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]Member, 0, len(members))
|
|
for _, m := range members {
|
|
u, err := s.getUser(ctx, m.PrincipalID)
|
|
if err != nil {
|
|
continue // a deleted user's leftover row
|
|
}
|
|
out = append(out, Member{User: MemberUser{ID: u.ID, Email: u.Email, Name: u.Name}, Role: m.Role})
|
|
}
|
|
sort.Slice(out, func(i, j int) bool { return out[i].User.Email < out[j].User.Email })
|
|
return out, nil
|
|
}
|
|
|
|
// SetSpaceMember adds a workspace member (by email) to a space or changes their role (space admin).
|
|
func (s *Service) SetSpaceMember(ctx context.Context, c access.Caller, id, email, role string) (Member, error) {
|
|
a, err := s.spaceFor(ctx, c, id)
|
|
if err != nil {
|
|
return Member{}, err
|
|
}
|
|
if err := access.ManageSpace(a.role); err != nil {
|
|
return Member{}, err
|
|
}
|
|
u, err := s.findUserByEmail(ctx, email)
|
|
if err != nil {
|
|
return Member{}, err
|
|
}
|
|
targetWsRole, err := s.effective(ctx, u.Caller(), a.ws)
|
|
if err != nil {
|
|
return Member{}, err
|
|
}
|
|
if err := access.SetSpaceMember(a.role, targetWsRole, role); err != nil {
|
|
return Member{}, err
|
|
}
|
|
current, err := s.spaceMembership(ctx, a.space.ID, u.ID)
|
|
if err != nil {
|
|
return Member{}, err
|
|
}
|
|
if current.ID != "" {
|
|
_, err = pocketbase.Update[spaceMemberRecord](ctx, s.pb, "space_members", current.ID, map[string]any{"role": role})
|
|
} else {
|
|
_, err = pocketbase.Create[spaceMemberRecord](ctx, s.pb, "space_members", map[string]any{
|
|
"space": a.space.ID, "principal_type": "user", "principal_id": u.ID, "role": role,
|
|
})
|
|
}
|
|
if err != nil {
|
|
return Member{}, mapPB(err, "space not found")
|
|
}
|
|
return Member{User: MemberUser{ID: u.ID, Email: u.Email, Name: u.Name}, Role: role}, nil
|
|
}
|
|
|
|
// RemoveSpaceMember removes a space membership (idempotent). Anyone may leave;
|
|
// removing others needs space admin.
|
|
func (s *Service) RemoveSpaceMember(ctx context.Context, c access.Caller, id, userID string) error {
|
|
a, err := s.spaceFor(ctx, c, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if userID != c.ID {
|
|
if err := access.ManageSpace(a.role); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if !validID(userID) {
|
|
return apperr.NotFound("member not found")
|
|
}
|
|
current, err := s.spaceMembership(ctx, a.space.ID, userID)
|
|
if err != nil || current.ID == "" {
|
|
return err
|
|
}
|
|
return mapPB(s.pb.Delete(ctx, "space_members", current.ID), "member not found")
|
|
}
|