Files
Docwell/Server/internal/settings/settings.go
T
tajniak81andClaude Opus 5.5 e33a99241e Add instance settings and mail delivery through PocketBase
Superadmins can now change signup rules (on/off and the domain allow-list)
and branding at runtime; the environment variables only seed the defaults.
Mail and S3 storage settings pass through to PocketBase's own settings, and
docwell-server sends its own emails through a PocketBase hook so there is a
single SMTP configuration. The boot hook no longer wipes SMTP settings that
were not set from the environment.

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

489 lines
14 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"`
}
// Instance is every setting, as the admin panel shows it.
type Instance struct {
Signup Signup `json:"signup"`
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"`
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"`
}
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
}
return Public{AppName: b.AppName, AccentColor: b.AccentColor, Logo: b.Logo, Signup: su.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
}
return Instance{
Signup: su,
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 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
}