This is a test email from {{.AppName}}.
+Mail delivery works.
diff --git a/Server/internal/mail/templates/test.txt b/Server/internal/mail/templates/test.txt new file mode 100644 index 0000000..f41294f --- /dev/null +++ b/Server/internal/mail/templates/test.txt @@ -0,0 +1,2 @@ +{{.AppName}} test email +This is a test email from {{.AppName}}. Mail delivery works. diff --git a/Server/internal/settings/settings.go b/Server/internal/settings/settings.go new file mode 100644 index 0000000..dc2e8cf --- /dev/null +++ b/Server/internal/settings/settings.go @@ -0,0 +1,488 @@ +// 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 +} diff --git a/Server/internal/settings/settings_test.go b/Server/internal/settings/settings_test.go new file mode 100644 index 0000000..210e19f --- /dev/null +++ b/Server/internal/settings/settings_test.go @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package settings + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "sync" + "testing" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/mail" + "docwell/server/internal/store/pocketbase" +) + +// fakePB stores instance_settings records and PocketBase settings in memory. +type fakePB struct { + mu sync.Mutex + kv map[string]json.RawMessage + settings map[string]map[string]any +} + +func newFake(t *testing.T) (*fakePB, *pocketbase.Client) { + t.Helper() + f := &fakePB{kv: map[string]json.RawMessage{}, settings: map[string]map[string]any{ + "meta": {"appName": "Docwell", "senderName": "Docwell", "senderAddress": "no-reply@x.test"}, + "smtp": {"enabled": false, "host": "", "port": 587, "username": "", "tls": false}, + "s3": {"enabled": false}, + }} + reply := func(w http.ResponseWriter, v any) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(v) + } + mux := http.NewServeMux() + mux.HandleFunc("POST /api/collections/_superusers/auth-with-password", func(w http.ResponseWriter, r *http.Request) { + reply(w, map[string]string{"token": "su"}) + }) + mux.HandleFunc("GET /api/collections/instance_settings/records", func(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + items := []kvRecord{} + for k, v := range f.kv { + if r.URL.Query().Get("filter") == "key = '"+k+"'" { + items = append(items, kvRecord{ID: "id_" + k, Key: k, Value: v}) + } + } + reply(w, map[string]any{"items": items, "totalItems": len(items), "totalPages": 1}) + }) + save := func(w http.ResponseWriter, r *http.Request) { + var rec kvRecord + _ = json.NewDecoder(r.Body).Decode(&rec) + f.mu.Lock() + f.kv[rec.Key] = rec.Value + f.mu.Unlock() + reply(w, rec) + } + mux.HandleFunc("POST /api/collections/instance_settings/records", save) + mux.HandleFunc("PATCH /api/collections/instance_settings/records/{id}", save) + mux.HandleFunc("GET /api/settings", func(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + reply(w, f.settings) + }) + mux.HandleFunc("PATCH /api/settings", func(w http.ResponseWriter, r *http.Request) { + var patch map[string]map[string]any + _ = json.NewDecoder(r.Body).Decode(&patch) + f.mu.Lock() + defer f.mu.Unlock() + for section, values := range patch { + for k, v := range values { + f.settings[section][k] = v + } + } + reply(w, f.settings) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + return f, pocketbase.New(srv.URL, "su@x.test", "pw") +} + +type sentMail struct{ got []mail.Message } + +func (s *sentMail) Send(_ context.Context, m mail.Message) error { + s.got = append(s.got, m) + return nil +} + +var ( + super = access.Caller{ID: "s", Role: access.RoleSuperadmin} + admin = access.Caller{ID: "a", Role: access.RoleAdmin, OrgID: "o"} +) + +func TestSignupDefaultsUntilSaved(t *testing.T) { + _, pb := newFake(t) + s := New(pb, Signup{Enabled: false, Domains: []string{"env.test"}}, &sentMail{}) + ctx := context.Background() + + got, err := s.Signup(ctx) + if err != nil || got.Enabled || len(got.Domains) != 1 { + t.Fatalf("defaults = %+v, %v", got, err) + } + _, err = s.Apply(ctx, super, Update{Signup: &Signup{Enabled: true, Domains: []string{" @Example.COM", "example.com", "b.test"}}}) + if err != nil { + t.Fatal(err) + } + got, _ = s.Signup(ctx) + if !got.Enabled || len(got.Domains) != 2 || got.Domains[0] != "example.com" { + t.Errorf("saved = %+v", got) + } +} + +func TestOnlySuperadmins(t *testing.T) { + _, pb := newFake(t) + s := New(pb, Signup{}, &sentMail{}) + ctx := context.Background() + for name, err := range map[string]error{ + "get": func() error { _, err := s.Get(ctx, admin); return err }(), + "apply": func() error { _, err := s.Apply(ctx, admin, Update{}); return err }(), + "mail": s.TestEmail(ctx, admin, "x@y.test"), + } { + if e, ok := apperr.As(err); !ok || e.Kind != apperr.KindForbidden { + t.Errorf("%s by an org admin = %v", name, err) + } + } +} + +func TestBrandingAndSMTP(t *testing.T) { + f, pb := newFake(t) + s := New(pb, Signup{}, &sentMail{}) + ctx := context.Background() + + _, err := s.Apply(ctx, super, Update{Branding: &Branding{AppName: "Acme", AccentColor: "red"}}) + if e, ok := apperr.As(err); !ok || e.Fields["branding.accentColor"] == "" { + t.Errorf("bad colour = %v", err) + } + + pw := "secret" + up := Update{Branding: &Branding{AppName: " Acme Wiki ", AccentColor: "#112233"}} + up.SMTP = &struct { + SMTP + Password *string `json:"password"` + }{SMTP: SMTP{Enabled: true, Host: "smtp.x.test", Port: 465, Username: "me", TLS: true, SenderAddress: "wiki@x.test"}, Password: &pw} + got, err := s.Apply(ctx, super, up) + if err != nil { + t.Fatal(err) + } + if got.Branding.AppName != "Acme Wiki" || !got.SMTP.Enabled || got.SMTP.Port != 465 || got.SMTP.Password != "" || !got.SMTP.PasswordSet { + t.Errorf("after apply = %+v", got) + } + if f.settings["meta"]["appName"] != "Acme Wiki" || f.settings["smtp"]["password"] != "secret" { + t.Errorf("pocketbase settings = %v", f.settings) + } + + // Leaving the password out keeps the stored one. + up.SMTP.Password = nil + if _, err := s.Apply(ctx, super, Update{SMTP: up.SMTP}); err != nil { + t.Fatal(err) + } + if f.settings["smtp"]["password"] != "secret" { + t.Error("password must survive an update without one") + } + + pub, err := s.Public(ctx) + if err != nil || pub.AppName != "Acme Wiki" || pub.AccentColor != "#112233" { + t.Errorf("public = %+v, %v", pub, err) + } +} + +func TestTestEmail(t *testing.T) { + _, pb := newFake(t) + sent := &sentMail{} + s := New(pb, Signup{}, sent) + if err := s.TestEmail(context.Background(), super, "nope"); err == nil { + t.Error("invalid address must fail") + } + if err := s.TestEmail(context.Background(), super, "me@x.test"); err != nil { + t.Fatal(err) + } + if len(sent.got) != 1 || sent.got[0].To != "me@x.test" || sent.got[0].Subject != "Docwell test email" { + t.Errorf("sent = %+v", sent.got) + } +} + +func TestCleanDomains(t *testing.T) { + if _, err := CleanDomains([]string{"not a domain"}); err == nil { + t.Error("spaces must be rejected") + } + got, err := CleanDomains([]string{"", "A.b"}) + if err != nil || len(got) != 1 || got[0] != "a.b" { + t.Errorf("got %v, %v", got, err) + } + var e *apperr.Error + _, err = CleanDomains([]string{"x"}) + if !errors.As(err, &e) { + t.Errorf("single label = %v", err) + } +} diff --git a/api/openapi.yaml b/api/openapi.yaml index e7cab38..299be15 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -850,6 +850,81 @@ paths: schema: { $ref: "#/components/schemas/Page" } "403": { $ref: "#/components/responses/Error" } "404": { $ref: "#/components/responses/Error" } + /api/v1/settings/public: + get: + operationId: getPublicSettings + tags: [settings] + summary: Branding and signup availability, for signed-out pages + responses: + "200": + description: OK + content: + application/json: + schema: { $ref: "#/components/schemas/PublicSettings" } + /api/v1/admin/settings: + get: + operationId: getInstanceSettings + tags: [settings] + summary: Every instance setting (superadmin) + security: [{ bearer: [] }] + responses: + "200": + description: OK + content: + application/json: + schema: { $ref: "#/components/schemas/InstanceSettings" } + "403": { $ref: "#/components/responses/Error" } + patch: + operationId: updateInstanceSettings + tags: [settings] + summary: Change the sections that are present (superadmin) + description: >- + Mail and storage settings are PocketBase's own. Passwords and secrets are write-only: + leave them out to keep the stored value. Environment variables such as + DOCWELL_SMTP_HOST are applied again when docwell-db starts. + security: [{ bearer: [] }] + requestBody: + required: true + content: + application/json: + schema: { $ref: "#/components/schemas/InstanceSettingsUpdate" } + responses: + "200": + description: Saved + content: + application/json: + schema: { $ref: "#/components/schemas/InstanceSettings" } + "400": { $ref: "#/components/responses/Error" } + "403": { $ref: "#/components/responses/Error" } + /api/v1/admin/settings/test-email: + post: + operationId: sendTestEmail + tags: [settings] + summary: Send a test email with the saved mail settings (superadmin) + security: [{ bearer: [] }] + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [to] + properties: + to: { type: string, format: email } + responses: + "204": { description: Sent } + "400": { $ref: "#/components/responses/Error" } + "403": { $ref: "#/components/responses/Error" } + /api/v1/admin/settings/test-storage: + post: + operationId: testStorage + tags: [settings] + summary: Check that the configured S3 bucket is reachable (superadmin) + security: [{ bearer: [] }] + responses: + "204": { description: Reachable } + "400": { $ref: "#/components/responses/Error" } + "403": { $ref: "#/components/responses/Error" } components: securitySchemes: bearer: @@ -1110,3 +1185,64 @@ components: properties: name: { type: string } version: { type: string } + PublicSettings: + type: object + required: [appName, accentColor, logo, signup] + properties: + appName: { type: string } + accentColor: { type: string, description: "#rrggbb, or empty for the default" } + logo: { type: string, description: A data URL, or empty for the Docwell logo } + signup: { type: boolean, description: Self-service signup is open } + SignupSettings: + type: object + required: [enabled, domains] + properties: + enabled: { type: boolean } + domains: { type: array, items: { type: string }, description: Allowed email domains; empty allows all } + BrandingSettings: + type: object + required: [appName, accentColor, logo] + properties: + appName: { type: string, maxLength: 60 } + accentColor: { type: string } + logo: { type: string, description: "data:image/(png|jpeg|webp|svg+xml);base64,..., at most 256 KB" } + SmtpSettings: + type: object + required: [enabled, host, port, username, passwordSet, tls, senderName, senderAddress] + properties: + enabled: { type: boolean } + host: { type: string } + port: { type: integer } + username: { type: string } + password: { type: string, writeOnly: true, description: Leave out to keep the stored password } + passwordSet: { type: boolean, readOnly: true } + tls: { type: boolean } + senderName: { type: string } + senderAddress: { type: string } + StorageSettings: + type: object + required: [s3, bucket, region, endpoint, accessKey, secretSet, forcePathStyle] + properties: + s3: { type: boolean, description: false stores files on docwell-db's disk } + bucket: { type: string } + region: { type: string } + endpoint: { type: string } + accessKey: { type: string } + secret: { type: string, writeOnly: true, description: Leave out to keep the stored secret } + secretSet: { type: boolean, readOnly: true } + forcePathStyle: { type: boolean } + InstanceSettings: + type: object + required: [signup, branding, smtp, storage] + properties: + signup: { $ref: "#/components/schemas/SignupSettings" } + branding: { $ref: "#/components/schemas/BrandingSettings" } + smtp: { $ref: "#/components/schemas/SmtpSettings" } + storage: { $ref: "#/components/schemas/StorageSettings" } + InstanceSettingsUpdate: + type: object + properties: + signup: { $ref: "#/components/schemas/SignupSettings" } + branding: { $ref: "#/components/schemas/BrandingSettings" } + smtp: { $ref: "#/components/schemas/SmtpSettings" } + storage: { $ref: "#/components/schemas/StorageSettings" }