Files
Docwell/Server/cmd/docwell-server/main.go
T
tajniak81andClaude Opus 5.5 9d674e9699
CI / go (Media) (push) Successful in 14m33s
CI / go (Server) (push) Failing after 23m30s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 9m30s
CI / desktop (ubuntu-latest) (push) Successful in 1h21m24s
CI / mobile (push) Failing after 4m16s
CI / docker (push) Successful in 1h1m25s
Docs / build (push) Successful in 14m59s
Docs / deploy (push) Skipped
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
Add invite links with approval, sharing switches, page views and unused-file cleanup
Phase G of docs/AFFINE.md (ADR-17):

- Invite links: one per workspace (member or guest, optional end date,
  optional admin approval) on a new /join page. Requests are approved
  (optionally as another role) or declined from workspace settings;
  join_request, join_approved and join_declined notifications reach the
  inbox, phones and the email digest. Workspace admins decide, else the
  organization's admins, else superadmins. Signup honours ?redirect=.
- Workspace switches: allowSharing (off makes every share link answer 404
  until it is back on) and urlPreview (chat apps may show private pages'
  titles). docwell-web writes title and Open Graph tags for known
  link-preview bots, asking docwell-server via DOCWELL_PREVIEW_API_URL;
  search engines are left out.
- Page analytics: page_views counts opens per page, person and day from
  the existing visit call and share-link reads; editors see totals, a
  daily chart and recent viewers in the Info panel. analytics.prune
  drops rows after 400 days.
- Unused files: attachments whose id appears in no page's Yjs state,
  page icon or comment (older than a day) are listed and deleted from
  workspace settings.
- Migration, schema snapshot, OpenAPI, generated clients, translations
  in five languages, phone inbox, compose files and user docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:59:55 +01:00

292 lines
11 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/ai"
"docwell/server/internal/audit"
"docwell/server/internal/auth"
"docwell/server/internal/calendar"
"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/oauth"
"docwell/server/internal/onenote"
"docwell/server/internal/pbschema"
"docwell/server/internal/push"
"docwell/server/internal/readwise"
"docwell/server/internal/search"
"docwell/server/internal/settings"
"docwell/server/internal/store/pocketbase"
"docwell/server/internal/unfurl"
"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)
// docwell-db is a stock PocketBase: the server brings its schema up to date
// before anything else touches it.
if err := preparePocketBase(db, log); err != nil {
return err
}
// Docwell's own emails go out over SMTP with PocketBase's mail settings.
var settingsSvc *settings.Service
mailer := &mail.SMTPSender{Config: func(ctx context.Context) (mail.Config, error) {
return settingsSvc.MailConfig(ctx)
}}
settingsSvc = settings.New(db, settings.Signup{Enabled: cfg.SignupEnabled, Domains: cfg.SignupDomains}, mailer)
envCtx, cancelEnv := context.WithTimeout(context.Background(), time.Minute)
err = settingsSvc.ApplyEnv(envCtx, settings.Env{
AppName: cfg.AppName, WebURL: cfg.WebURL, MailFrom: cfg.MailFrom,
SMTPHost: cfg.SMTP.Host, SMTPPort: cfg.SMTP.Port, SMTPUsername: cfg.SMTP.Username,
SMTPPassword: cfg.SMTP.Password, SMTPTLS: cfg.SMTP.TLS,
S3: cfg.S3.Enabled, S3Bucket: cfg.S3.Bucket, S3Endpoint: cfg.S3.Endpoint, S3Region: cfg.S3.Region,
S3AccessKey: cfg.S3.AccessKey, S3Secret: cfg.S3.Secret, S3ForcePathStyle: cfg.S3.ForcePathStyle,
})
cancelEnv()
if err != nil {
return err
}
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")
if cfg.AdminEmail != "" {
adminCtx, cancelAdmin := context.WithTimeout(context.Background(), time.Minute)
created, err := authSvc.EnsureSuperadmin(adminCtx, cfg.AdminEmail, cfg.AdminPassword, cfg.AdminName)
cancelAdmin()
switch {
case err != nil:
return fmt.Errorf("create superadmin from DOCWELL_ADMIN_EMAIL: %w", err)
case created:
log.Info("created superadmin from DOCWELL_ADMIN_EMAIL", "email", cfg.AdminEmail)
default:
log.Info("accounts already exist; DOCWELL_ADMIN_EMAIL left unused")
}
}
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 and sent reminders older than 90 days", 24*time.Hour, dirSvc.PruneNotifications)
reg.Register("analytics.prune", "Deletes page view counts older than 400 days", 24*time.Hour, dirSvc.PruneViews)
reg.Register("notify.reminders", "Sends reminders for dates in pages that are due", time.Minute, dirSvc.SendReminders)
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)
go reg.Every(indexCtx, "notify.reminders", time.Minute)
_ = reg.Run("links.backfill")
dirSvc.UseSearch(index)
dirSvc.UseWebhooks(hooks)
go hooks.Run(indexCtx)
// Phones get pushes through UnifiedPush; endpoints follow the webhook address rules.
pushSvc := push.New(db, log, push.Options{AllowLocal: cfg.WebhooksAllowLocal})
dirSvc.UsePush(pushSvc)
go pushSvc.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)
}
// AI (ADR-15): provider keys are sealed with DOCWELL_SECRET_KEY, or with a
// key derived from the PocketBase password when it is not set.
secret := cfg.SecretKey
if secret == "" {
secret = "pb:" + cfg.PocketBasePassword
}
aiSvc, err := ai.New(db, dirSvc, log, ai.Options{Secret: secret, DataDir: cfg.DataDir, AllowLocal: cfg.WebhooksAllowLocal,
MediaURL: cfg.MediaURL, MediaToken: cfg.MediaToken})
if err != nil {
return err
}
defer aiSvc.Close()
aiSvc.Track(reg.Track)
reg.Register("ai.index", "Embeds changed pages of workspaces with AI indexing on", 30*time.Second,
func(ctx context.Context) error { return aiSvc.IndexPass(ctx, true) })
go aiSvc.Run(indexCtx, 30*time.Second, 10*time.Minute)
// Integrations (ADR-16): calendar passwords, Google tokens and Readwise
// tokens are sealed with the same secret as AI keys; sources follow the
// webhook address rules. Google and Microsoft sign-ins come back to one
// callback, routed by their signed state.
states := oauth.NewStates(secret)
oauthRouter := oauth.NewRouter(states, cfg.WebURL)
calSvc := calendar.New(db, calendar.Options{
Secret: secret, AllowLocal: cfg.WebhooksAllowLocal, States: states, PublicURL: cfg.PublicURL, WebURL: cfg.WebURL,
Google: oauth.Google(cfg.Google.ClientID, cfg.Google.ClientSecret),
})
oauthRouter.Handle(calendar.PurposeGoogle, calSvc.GoogleCallback)
reg.Register("calendars.sync", "Copies the events of people's calendars for their journals", 5*time.Minute, calSvc.SyncDue)
go reg.Every(indexCtx, "calendars.sync", 5*time.Minute)
oneNoteSvc := onenote.New(dirSvc, onenote.Options{
Provider: oauth.Microsoft(cfg.Microsoft.ClientID, cfg.Microsoft.ClientSecret, cfg.Microsoft.Tenant),
States: states, PublicURL: cfg.PublicURL, WebURL: cfg.WebURL, AllowLocal: cfg.WebhooksAllowLocal,
})
oauthRouter.Handle(onenote.Purpose, oneNoteSvc.Callback)
readwiseSvc := readwise.New(db, dirSvc, readwise.Options{Secret: secret, AllowLocal: cfg.WebhooksAllowLocal})
reg.Register("readwise.sync", "Adds new Readwise highlights to people's pages", 10*time.Minute, readwiseSvc.SyncDue)
go reg.Every(indexCtx, "readwise.sync", 10*time.Minute)
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,
Previews: unfurl.New(),
Calendars: calSvc,
OAuth: oauthRouter,
OneNote: oneNoteSvc,
Readwise: readwiseSvc,
Push: pushSvc,
AI: aiSvc,
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
}
// preparePocketBase waits for PocketBase to answer, then applies Docwell's
// collections to it (pbschema).
func preparePocketBase(db *pocketbase.Client, log *slog.Logger) error {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
for {
err := db.Health(ctx)
if err == nil {
break
}
log.Info("waiting for PocketBase", "err", err)
select {
case <-ctx.Done():
return fmt.Errorf("pocketbase did not answer: %w", err)
case <-time.After(2 * time.Second):
}
}
start := time.Now()
if err := pbschema.Apply(ctx, db); err != nil {
return err
}
log.Info("pocketbase schema applied", "dur", time.Since(start).String())
return nil
}