Link previews: link cards for GitHub issues, pull requests and repositories, Linear issues and Figma files are read through the services' APIs and show a status pill (Open, Merged, In Progress…) and a line of details. Public items need nothing; a workspace's tokens, set by its admins under Workspace settings → Integrations and checked with each service before being sealed, reach private ones and Linear. GET /link-preview takes the workspace; the link card stores kind, status, state and meta. Slack: each workspace connects its own Slack app, made from a manifest the settings page fills in. Docwell posts chosen page and comment events to a channel (edits at most every 30 minutes per page), previews links to Docwell pages posted in Slack, and answers /docwell with a search as the member whose email matches the Slack user, shown only to them. Only pages every member can open are posted or previewed. Requests from Slack are signature-checked; the webhook dispatcher gained listeners so Slack follows the same events. Confluence: a space's HTML export imports with its page tree (from index.html, else breadcrumbs), links between pages, pictures and attachments. Panels become callouts, code macros code blocks with their language, expand macros toggles, task lists to-dos. New collection workspace_integrations (schema snapshot regenerated), OpenAPI and generated Go, TypeScript and Dart types, strings in all five languages, the user guide, and a rebuilt mobile editor bundle. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
299 lines
12 KiB
Go
299 lines
12 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/integrations"
|
|
"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)
|
|
// Workspace integrations (ADR-18): service tokens for link previews, and
|
|
// Slack, which follows the same events as webhooks.
|
|
previews := unfurl.New()
|
|
integrationsSvc := integrations.New(db, dirSvc, previews, integrations.Options{Secret: secret, WebURL: cfg.WebURL, Log: log})
|
|
hooks.Listen(integrationsSvc.Listen)
|
|
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: previews,
|
|
Calendars: calSvc,
|
|
OAuth: oauthRouter,
|
|
OneNote: oneNoteSvc,
|
|
Readwise: readwiseSvc,
|
|
Integrations: integrationsSvc,
|
|
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
|
|
}
|