Files
Docwell/Server/internal/settings/settings.go
T
tajniak81andClaude Opus 5.5 342d073460 Add invites and magic-link sign-in
Managers invite people into their organization and workspace admins into
their workspace; the email links to a new /invite page that creates the
account (or attaches an existing one without an organization) and adds the
workspace membership. Invites bypass the signup rules, store only a token
hash, expire after seven days, and return the link so it can be passed on
when mail is not configured. Inviting someone already in the organization
adds them to the workspace directly.

Magic links reuse PocketBase's email OTP: the email now carries a link to
/magic-link next to the code, and the admin settings gain a switch for it.
Managers can also send a user a password-reset email.

The dev proxies read DOCWELL_DEV_API so a dev server can target another
docwell-server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:32:55 +01:00

526 lines
15 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
// Package settings holds the instance settings superadmins edit in the admin
// panel. Signup rules and branding are stored in the instance_settings
// collection (environment variables only seed the defaults); mail and file
// storage are PocketBase's own settings, patched through its settings API.
package settings
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"regexp"
"strings"
"sync"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/mail"
"docwell/server/internal/store/pocketbase"
)
// Signup controls self-service account creation.
type Signup struct {
Enabled bool `json:"enabled"`
// Domains limits signup to these email domains when not empty.
Domains []string `json:"domains"`
}
// Branding is how the instance presents itself in the apps and emails.
type Branding struct {
AppName string `json:"appName"`
// AccentColor is "#rrggbb", or "" for the design system's default.
AccentColor string `json:"accentColor"`
// Logo is a data: URL (PNG, JPEG, WebP or SVG), or "" for the Docwell logo.
Logo string `json:"logo"`
}
// SMTP is the outgoing mail server. Password is write-only: reads leave it
// empty and report PasswordSet instead.
type SMTP struct {
Enabled bool `json:"enabled"`
Host string `json:"host"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password,omitempty"`
PasswordSet bool `json:"passwordSet"`
TLS bool `json:"tls"`
SenderName string `json:"senderName"`
SenderAddress string `json:"senderAddress"`
}
// Storage selects where uploaded files live: PocketBase's local disk, or S3.
// Secret is write-only like SMTP.Password.
type Storage struct {
S3 bool `json:"s3"`
Bucket string `json:"bucket"`
Region string `json:"region"`
Endpoint string `json:"endpoint"`
AccessKey string `json:"accessKey"`
Secret string `json:"secret,omitempty"`
SecretSet bool `json:"secretSet"`
ForcePathStyle bool `json:"forcePathStyle"`
}
// Auth holds the sign-in methods the admin panel switches.
type Auth struct {
// MagicLink emails a one-time sign-in link and code (PocketBase's email OTP).
MagicLink bool `json:"magicLink"`
}
// Instance is every setting, as the admin panel shows it.
type Instance struct {
Signup Signup `json:"signup"`
Auth Auth `json:"auth"`
Branding Branding `json:"branding"`
SMTP SMTP `json:"smtp"`
Storage Storage `json:"storage"`
}
// Update changes the sections that are set. A nil SMTP.Password or
// Storage.Secret keeps the stored one.
type Update struct {
Signup *Signup `json:"signup"`
Auth *Auth `json:"auth"`
Branding *Branding `json:"branding"`
SMTP *struct {
SMTP
Password *string `json:"password"`
} `json:"smtp"`
Storage *struct {
Storage
Secret *string `json:"secret"`
} `json:"storage"`
}
// Public is what signed-out visitors may know (the login page needs it).
type Public struct {
AppName string `json:"appName"`
AccentColor string `json:"accentColor"`
Logo string `json:"logo"`
Signup bool `json:"signup"`
MagicLink bool `json:"magicLink"`
}
const (
keySignup = "signup"
keyBranding = "branding"
cacheTTL = 30 * time.Second
)
type Service struct {
pb *pocketbase.Client
defaults Signup
mail mail.Sender
now func() time.Time
mu sync.Mutex
cache map[string]cached
}
type cached struct {
raw json.RawMessage
expires time.Time
}
// New returns the settings service; defaults apply until a superadmin saves
// signup rules of their own.
func New(pb *pocketbase.Client, defaults Signup, sender mail.Sender) *Service {
return &Service{pb: pb, defaults: defaults, mail: sender, now: time.Now, cache: map[string]cached{}}
}
type kvRecord struct {
ID string `json:"id"`
Key string `json:"key"`
Value json.RawMessage `json:"value"`
}
// load reads one key into out; found is false when it was never saved.
func (s *Service) load(ctx context.Context, key string, out any) (found bool, err error) {
s.mu.Lock()
c, ok := s.cache[key]
s.mu.Unlock()
if !ok || s.now().After(c.expires) {
res, err := pocketbase.List[kvRecord](ctx, s.pb, "instance_settings", pocketbase.ListOptions{
PerPage: 1, Filter: fmt.Sprintf("key = '%s'", key),
})
if err != nil {
return false, err
}
c = cached{expires: s.now().Add(cacheTTL)}
if len(res.Items) > 0 {
c.raw = res.Items[0].Value
}
s.mu.Lock()
s.cache[key] = c
s.mu.Unlock()
}
if len(c.raw) == 0 || string(c.raw) == "null" {
return false, nil
}
return true, json.Unmarshal(c.raw, out)
}
func (s *Service) save(ctx context.Context, key string, v any) error {
raw, err := json.Marshal(v)
if err != nil {
return err
}
res, err := pocketbase.List[kvRecord](ctx, s.pb, "instance_settings", pocketbase.ListOptions{
PerPage: 1, Filter: fmt.Sprintf("key = '%s'", key),
})
if err != nil {
return err
}
body := map[string]any{"key": key, "value": json.RawMessage(raw)}
if len(res.Items) > 0 {
_, err = pocketbase.Update[kvRecord](ctx, s.pb, "instance_settings", res.Items[0].ID, body)
} else {
_, err = pocketbase.Create[kvRecord](ctx, s.pb, "instance_settings", body)
}
if err != nil {
return err
}
s.mu.Lock()
s.cache[key] = cached{raw: raw, expires: s.now().Add(cacheTTL)}
s.mu.Unlock()
return nil
}
// Signup returns the signup rules (the defaults until a superadmin saves some).
func (s *Service) Signup(ctx context.Context) (Signup, error) {
out := s.defaults
if _, err := s.load(ctx, keySignup, &out); err != nil {
return Signup{}, err
}
if out.Domains == nil {
out.Domains = []string{}
}
return out, nil
}
// Branding returns the instance branding; an unset name is "Docwell".
func (s *Service) Branding(ctx context.Context) (Branding, error) {
var out Branding
if _, err := s.load(ctx, keyBranding, &out); err != nil {
return Branding{}, err
}
if out.AppName == "" {
out.AppName = "Docwell"
}
return out, nil
}
// Public returns the settings signed-out visitors may see.
func (s *Service) Public(ctx context.Context) (Public, error) {
b, err := s.Branding(ctx)
if err != nil {
return Public{}, err
}
su, err := s.Signup(ctx)
if err != nil {
return Public{}, err
}
a, err := s.auth(ctx)
if err != nil {
return Public{}, err
}
return Public{AppName: b.AppName, AccentColor: b.AccentColor, Logo: b.Logo, Signup: su.Enabled, MagicLink: a.MagicLink}, nil
}
// auth reads the sign-in switches from the users collection.
func (s *Service) auth(ctx context.Context) (Auth, error) {
var users struct {
OTP struct {
Enabled bool `json:"enabled"`
} `json:"otp"`
}
if err := s.pb.Do(ctx, http.MethodGet, "/api/collections/users", nil, &users); err != nil {
return Auth{}, err
}
return Auth{MagicLink: users.OTP.Enabled}, nil
}
// pbSettings is the part of PocketBase's /api/settings this package uses.
// PocketBase never returns passwords or secrets.
type pbSettings struct {
Meta struct {
AppName string `json:"appName"`
SenderName string `json:"senderName"`
SenderAddress string `json:"senderAddress"`
} `json:"meta"`
SMTP struct {
Enabled bool `json:"enabled"`
Host string `json:"host"`
Port int `json:"port"`
Username string `json:"username"`
TLS bool `json:"tls"`
} `json:"smtp"`
S3 struct {
Enabled bool `json:"enabled"`
Bucket string `json:"bucket"`
Region string `json:"region"`
Endpoint string `json:"endpoint"`
AccessKey string `json:"accessKey"`
ForcePathStyle bool `json:"forcePathStyle"`
} `json:"s3"`
}
func (s *Service) pbSettings(ctx context.Context) (pbSettings, error) {
var out pbSettings
err := s.pb.Do(ctx, http.MethodGet, "/api/settings", nil, &out)
return out, err
}
// Get returns every instance setting (superadmin).
func (s *Service) Get(ctx context.Context, c access.Caller) (Instance, error) {
if err := access.ManageInstance(c); err != nil {
return Instance{}, err
}
return s.get(ctx)
}
func (s *Service) get(ctx context.Context) (Instance, error) {
su, err := s.Signup(ctx)
if err != nil {
return Instance{}, err
}
b, err := s.Branding(ctx)
if err != nil {
return Instance{}, err
}
pb, err := s.pbSettings(ctx)
if err != nil {
return Instance{}, err
}
a, err := s.auth(ctx)
if err != nil {
return Instance{}, err
}
return Instance{
Signup: su,
Auth: a,
Branding: b,
SMTP: SMTP{
Enabled: pb.SMTP.Enabled, Host: pb.SMTP.Host, Port: pb.SMTP.Port, Username: pb.SMTP.Username,
// PocketBase hides the password; with a username set, assume one is stored.
PasswordSet: pb.SMTP.Username != "", TLS: pb.SMTP.TLS,
SenderName: pb.Meta.SenderName, SenderAddress: pb.Meta.SenderAddress,
},
Storage: Storage{
S3: pb.S3.Enabled, Bucket: pb.S3.Bucket, Region: pb.S3.Region, Endpoint: pb.S3.Endpoint,
AccessKey: pb.S3.AccessKey, SecretSet: pb.S3.AccessKey != "", ForcePathStyle: pb.S3.ForcePathStyle,
},
}, nil
}
var (
domainPattern = regexp.MustCompile(`^[a-z0-9-]+(\.[a-z0-9-]+)+$`)
colorPattern = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
logoPattern = regexp.MustCompile(`^data:image/(png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/=]+$`)
)
// maxLogo caps the logo data URL; it is sent with every public settings read.
const maxLogo = 256 << 10
// CleanDomains normalizes an allow-list ("@Example.com " → "example.com").
func CleanDomains(in []string) ([]string, error) {
out := []string{}
seen := map[string]bool{}
for _, d := range in {
d = strings.ToLower(strings.TrimPrefix(strings.TrimSpace(d), "@"))
if d == "" || seen[d] {
continue
}
if !domainPattern.MatchString(d) {
return nil, apperr.InvalidFields(map[string]string{"signup.domains": fmt.Sprintf("%q is not a domain.", d)})
}
seen[d] = true
out = append(out, d)
}
return out, nil
}
func cleanBranding(b Branding) (Branding, error) {
b.AppName = strings.TrimSpace(b.AppName)
b.AccentColor = strings.TrimSpace(b.AccentColor)
fields := map[string]string{}
if b.AppName == "" {
fields["branding.appName"] = "Name is required."
} else if len(b.AppName) > 60 {
fields["branding.appName"] = "Name is too long (max 60)."
}
if b.AccentColor != "" && !colorPattern.MatchString(b.AccentColor) {
fields["branding.accentColor"] = "Colour must look like #2f7d6d."
}
if b.Logo != "" && (len(b.Logo) > maxLogo || !logoPattern.MatchString(b.Logo)) {
fields["branding.logo"] = "Logo must be a PNG, JPEG, WebP or SVG image under 190 KB."
}
if len(fields) > 0 {
return Branding{}, apperr.InvalidFields(fields)
}
return b, nil
}
// Apply saves the sections set in in (superadmin) and returns the result.
func (s *Service) Apply(ctx context.Context, c access.Caller, in Update) (Instance, error) {
if err := access.ManageInstance(c); err != nil {
return Instance{}, err
}
patch := map[string]any{}
meta := map[string]any{}
var branding *Branding
if in.Branding != nil {
b, err := cleanBranding(*in.Branding)
if err != nil {
return Instance{}, err
}
branding = &b
// PocketBase signs its own emails (verification, reset) with this name.
meta["appName"] = b.AppName
meta["senderName"] = b.AppName
if b.AccentColor != "" {
meta["accentColor"] = b.AccentColor
}
}
var signup *Signup
if in.Signup != nil {
domains, err := CleanDomains(in.Signup.Domains)
if err != nil {
return Instance{}, err
}
signup = &Signup{Enabled: in.Signup.Enabled, Domains: domains}
}
if in.SMTP != nil {
m := in.SMTP
m.Host = strings.TrimSpace(m.Host)
m.SenderAddress = strings.TrimSpace(m.SenderAddress)
fields := map[string]string{}
if m.Enabled && m.Host == "" {
fields["smtp.host"] = "Host is required."
}
if m.Enabled && (m.Port < 1 || m.Port > 65535) {
fields["smtp.port"] = "Port must be between 1 and 65535."
}
if !strings.Contains(m.SenderAddress, "@") {
fields["smtp.senderAddress"] = "A valid sender address is required."
}
if len(fields) > 0 {
return Instance{}, apperr.InvalidFields(fields)
}
smtp := map[string]any{
"enabled": m.Enabled, "host": m.Host, "port": m.Port, "username": strings.TrimSpace(m.Username), "tls": m.TLS,
}
if m.Password != nil {
smtp["password"] = *m.Password
}
patch["smtp"] = smtp
meta["senderAddress"] = m.SenderAddress
if name := strings.TrimSpace(m.SenderName); name != "" {
meta["senderName"] = name
}
}
if in.Storage != nil {
st := in.Storage
if st.S3 && (strings.TrimSpace(st.Bucket) == "" || strings.TrimSpace(st.Endpoint) == "") {
return Instance{}, apperr.InvalidFields(map[string]string{"storage.bucket": "Bucket and endpoint are required for S3."})
}
s3 := map[string]any{
"enabled": st.S3, "bucket": strings.TrimSpace(st.Bucket), "region": strings.TrimSpace(st.Region),
"endpoint": strings.TrimSpace(st.Endpoint), "accessKey": strings.TrimSpace(st.AccessKey), "forcePathStyle": st.ForcePathStyle,
}
if st.Secret != nil {
s3["secret"] = *st.Secret
}
patch["s3"] = s3
}
if len(meta) > 0 {
patch["meta"] = meta
}
if len(patch) > 0 {
if err := s.pb.Do(ctx, http.MethodPatch, "/api/settings", patch, nil); err != nil {
return Instance{}, settingsError(err)
}
}
if in.Auth != nil {
body := map[string]any{"otp": map[string]any{"enabled": in.Auth.MagicLink}}
if err := s.pb.Do(ctx, http.MethodPatch, "/api/collections/users", body, nil); err != nil {
return Instance{}, err
}
}
if branding != nil {
if err := s.save(ctx, keyBranding, branding); err != nil {
return Instance{}, err
}
}
if signup != nil {
if err := s.save(ctx, keySignup, signup); err != nil {
return Instance{}, err
}
}
return s.get(ctx)
}
// settingsError reports PocketBase's validation of mail and storage settings
// as field errors ("smtp.host", "s3.bucket", ...).
func settingsError(err error) error {
var pbErr *pocketbase.Error
if !errors.As(err, &pbErr) || pbErr.Status != http.StatusBadRequest {
return err
}
fields := map[string]string{}
for k, v := range pbErr.Data {
fields[k] = v.Message
}
if len(fields) == 0 {
return apperr.Invalid(pbErr.Message)
}
return apperr.InvalidFields(fields)
}
// TestEmail sends a test message to to (superadmin).
func (s *Service) TestEmail(ctx context.Context, c access.Caller, to string) error {
if err := access.ManageInstance(c); err != nil {
return err
}
to = strings.TrimSpace(to)
if !strings.Contains(to, "@") {
return apperr.InvalidFields(map[string]string{"to": "A valid email is required."})
}
b, err := s.Branding(ctx)
if err != nil {
return err
}
m, err := mail.Render(to, "test", map[string]string{"AppName": b.AppName})
if err != nil {
return err
}
if err := s.mail.Send(ctx, m); err != nil {
var pbErr *pocketbase.Error
if errors.As(err, &pbErr) {
return apperr.Invalid("the mail server rejected the message: " + pbErr.Message)
}
return err
}
return nil
}
// TestStorage checks that PocketBase can reach the configured S3 bucket (superadmin).
func (s *Service) TestStorage(ctx context.Context, c access.Caller) error {
if err := access.ManageInstance(c); err != nil {
return err
}
err := s.pb.Do(ctx, http.MethodPost, "/api/settings/test/s3", map[string]string{"filesystem": "storage"}, nil)
var pbErr *pocketbase.Error
if errors.As(err, &pbErr) && pbErr.Status == http.StatusBadRequest {
return apperr.Invalid("storage test failed: " + pbErr.Message)
}
return err
}