Files
Docwell/Server/cmd/docwell-server/main.go
T
tajniak81andClaude Opus 5.5 631b929433 Add OAuth and OIDC sign-in, two-step codes, audit log, API tokens and webhooks
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>
2026-11-01 09:31:45 +01:00

174 lines
6.0 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
// Command docwell-server runs the Docwell API, collaboration relay and admin panel.
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"path/filepath"
"runtime"
"syscall"
"time"
"docwell/server/internal/admin"
"docwell/server/internal/audit"
"docwell/server/internal/auth"
"docwell/server/internal/collab"
"docwell/server/internal/config"
"docwell/server/internal/directory"
"docwell/server/internal/httpapi"
"docwell/server/internal/instance"
"docwell/server/internal/jobs"
"docwell/server/internal/mail"
"docwell/server/internal/search"
"docwell/server/internal/settings"
"docwell/server/internal/store/pocketbase"
"docwell/server/internal/webhooks"
"docwell/server/internal/ycrdt"
)
// Version is set at build time with -ldflags "-X main.Version=...".
var Version = "dev"
func main() {
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
if err := run(log); err != nil {
log.Error("fatal", "err", err)
os.Exit(1)
}
}
func run(log *slog.Logger) error {
cfg, err := config.Load()
if err != nil {
return err
}
db := pocketbase.New(cfg.PocketBaseURL, cfg.PocketBaseEmail, cfg.PocketBasePassword)
mailer := mail.PBSender{PB: db}
settingsSvc := settings.New(db, settings.Signup{Enabled: cfg.SignupEnabled, Domains: cfg.SignupDomains}, mailer)
authSvc := auth.NewService(db, auth.Options{
Rules: func(ctx context.Context) (bool, []string, error) {
rules, err := settingsSvc.Signup(ctx)
return rules.Enabled, rules.Domains, err
},
// Providers send people back to the web app, or to the desktop app's link.
OAuthRedirects: []string{cfg.WebURL + "/oauth/callback", "docwell://oauth/callback"},
})
settingsSvc.SetOAuthCallback(cfg.WebURL + "/oauth/callback")
auditLog := audit.New(db, log)
defer auditLog.Close()
hooks := webhooks.New(db, log, webhooks.Options{AllowLocal: cfg.WebhooksAllowLocal})
// yrs.wasm compiles once; the cache makes later starts fast (ADR-3).
cacheDir, _ := os.UserCacheDir()
if cacheDir != "" {
cacheDir = filepath.Join(cacheDir, "docwell", "wazero")
}
yrs, err := ycrdt.New(context.Background(), cacheDir)
if err != nil {
return err
}
hub := collab.NewHub(collab.Options{
Store: collab.NewPBStore(db), Docs: ycrdt.NewPool(yrs, max(2, runtime.GOMAXPROCS(0))), Log: log,
})
dirSvc := directory.New(db, authSvc.Forget, hub)
hub.OnSaved(func(page, editor string, doc []byte) {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
dirSvc.PageSaved(ctx, page, editor, doc)
})
// The search index follows PocketBase and can be rebuilt from it at any time.
index, err := search.Open(cfg.DataDir, db, log)
if err != nil {
return err
}
defer index.Close()
reg := jobs.New()
reg.Register("search.index", "Adds changed pages to the search index", 3*time.Second, nil)
reg.Register("search.sweep", "Removes deleted pages from the search index", 10*time.Minute, index.Sweep)
reg.Register("search.rebuild", "Rebuilds the whole search index from the database", 0, index.Rebuild)
reg.Register("notify.digest", "Emails people their unread notifications", 5*time.Minute, dirSvc.SendDigests)
reg.Register("notify.prune", "Deletes read notifications older than 90 days", 24*time.Hour, dirSvc.PruneNotifications)
reg.Register("links.backfill", "Works out page links for pages saved before backlinks existed", 0, dirSvc.BackfillLinks)
index.Track(reg.Track)
indexCtx, stopIndex := context.WithCancel(context.Background())
defer stopIndex()
go index.Run(indexCtx, 3*time.Second, 10*time.Minute)
go reg.Every(indexCtx, "notify.digest", 5*time.Minute)
go reg.Every(indexCtx, "notify.prune", 24*time.Hour)
_ = reg.Run("links.backfill")
dirSvc.UseSearch(index)
dirSvc.UseWebhooks(hooks)
go hooks.Run(indexCtx)
reg.Register("webhooks.prune", "Deletes webhook deliveries older than 30 days", 24*time.Hour, hooks.Prune)
go reg.Every(indexCtx, "webhooks.prune", 24*time.Hour)
if days := cfg.AuditRetentionDays; days > 0 {
reg.Register("audit.prune", fmt.Sprintf("Deletes audit log entries older than %d days", days), 24*time.Hour,
func(ctx context.Context) error { return auditLog.Prune(ctx, time.Duration(days)*24*time.Hour) })
go reg.Every(indexCtx, "audit.prune", 24*time.Hour)
}
dirSvc.SetPublicURL(cfg.PublicURL)
dirSvc.SetMaxUpload(int64(cfg.MaxUploadMB) << 20)
dirSvc.UseMail(directory.Mailer{Sender: mailer, WebURL: cfg.WebURL, AppName: func(ctx context.Context) string {
b, _ := settingsSvc.Branding(ctx)
return b.AppName
}})
srv := &http.Server{
Addr: cfg.Addr,
Handler: httpapi.NewRouter(httpapi.Deps{
Version: Version,
CORSOrigins: cfg.CORSOrigins,
DB: db,
Auth: authSvc,
Directory: dirSvc,
Settings: settingsSvc,
// Derived from the PocketBase password, so links survive restarts
// without another secret to configure.
FileTokens: auth.NewFileTokens(cfg.PocketBasePassword, time.Hour),
MaxUpload: int64(cfg.MaxUploadMB) << 20,
Instance: instance.New(db, Version, hub, index, reg),
Collab: hub,
Audit: auditLog,
Admin: admin.Handler("/admin"),
Log: log,
}),
ReadHeaderTimeout: 10 * time.Second,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
errCh := make(chan error, 1)
go func() {
log.Info("docwell-server listening", "addr", cfg.Addr, "version", Version, "pocketbase", cfg.PocketBaseURL)
errCh <- srv.ListenAndServe()
}()
select {
case err := <-errCh:
if !errors.Is(err, http.ErrServerClosed) {
return err
}
case <-ctx.Done():
log.Info("shutting down")
}
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
defer cancel()
// Open WebSockets are hijacked and not tracked by Shutdown; closing the hub
// saves every open page, and the process exit then drops the sockets.
err = srv.Shutdown(shutdownCtx)
if herr := hub.Close(shutdownCtx); herr != nil {
log.Error("collab: saving open pages", "err", herr)
}
return err
}