Run docwell-db as a stock PocketBase and let the server set it up
CI / go (Server) (push) Failing after 22m50s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 8m47s
CI / desktop (ubuntu-latest) (push) Successful in 2h56m50s
CI / mobile (push) Failing after 5m33s
CI / docker (push) Successful in 1h43m8s
Docs / build (push) Successful in 16m2s
Docs / deploy (push) Skipped
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s

docwell-db no longer needs a Docwell image: the stack runs
tajniak81/pocketbase-docker-root as it is, and docwell-server does what
the migrations and pb_hooks used to do inside PocketBase.

On start, docwell-server now:
- waits for PocketBase and imports Docwell's collections from an
  embedded snapshot (internal/pbschema). Existing collections and
  fields are matched by name, so their data is kept; the admin-managed
  users options (OAuth2 providers, magic link) are left untouched.
- writes the DOCWELL_APP_NAME, DOCWELL_WEB_URL, DOCWELL_MAIL_FROM,
  DOCWELL_SMTP_* and DOCWELL_S3_* settings into PocketBase, as the
  boot hook did.

It also replaces the hook's two routes: token checks use PocketBase's
auth-refresh (the organization name is read as the superuser), and
Docwell's own emails go out over SMTP from the server. PocketBase never
returns the SMTP password, so the server keeps a copy in the
superuser-only instance_settings collection; a password saved before
this change has to be entered once more in the admin panel.

Database/ keeps pb_migrations as the source of the schema;
export-schema.sh regenerates the snapshot from them. Database/Dockerfile
and pb_hooks are removed, the release no longer builds docwell-db, the
AIO image runs PocketBase without migrations or hooks, and the compose
files default DB_IMAGE to the stock image and pass the settings to the
server instead of the database.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-11-13 20:09:38 +01:00
1 parent 24a2d275a0
commit b9be8be156
43 files changed
+5265 -372

No files matched your search

+4 -8
View File
@@ -1,7 +1,6 @@
# Publishes a release on Gitea: push a tag like v1.0.0.
# Images go to the registry of the Gitea that runs this workflow,
# <host>/<repository owner>/<name>, for linux/amd64 and linux/arm64 (docwell-db:
# amd64 only, like its PocketBase base image), tagged
# <host>/<repository owner>/<name>, for linux/amd64 and linux/arm64, tagged
# with the version (1.0.0, 1.0) and latest. Desktop installers (Windows NSIS,
# Linux deb, rpm and AppImage) are attached to the Gitea release for the tag,
# which is made once every build has passed. Gitea has no hosted Mac runners,
@@ -42,12 +41,9 @@ jobs:
fail-fast: false
matrix:
include:
# FROM tajniak81/pocketbase-docker-root, published for amd64
# only. Add linux/arm64 back once that image has it.
- name: docwell-db
context: Database
dockerfile: Database/Dockerfile
platforms: linux/amd64
# No docwell-db image: the stack runs a stock PocketBase
# (tajniak81/pocketbase-docker-root) and docwell-server applies
# Docwell's schema to it.
- name: docwell-server
context: .
dockerfile: Server/Dockerfile
-23
View File
@@ -1,23 +0,0 @@
# docwell-db: PocketBase from tajniak81/pocketbase-docker-root (the root
# variant of https://github.com/freefall-dev/PocketBase-docker) plus Docwell's
# migrations and hooks.
#
# The base image downloads a pinned PocketBase release, checks it against the
# published checksums, and its entrypoint creates the superuser from
# PB_ADMIN_EMAIL / PB_ADMIN_PASSWORD when it does not exist yet, then runs
# `pocketbase serve`. Serve applies pending migrations on start. PocketBase
# finds pb_migrations and pb_hooks next to pb_data, so they go under /pb.
#
# Note: the base image is published for linux/amd64 only.
ARG PB_IMAGE=tajniak81/pocketbase-docker-root:0.40.6
FROM ${PB_IMAGE}
COPY pb_migrations /pb/pb_migrations
COPY pb_hooks /pb/pb_hooks
# docwell-server expects PocketBase on 8070 (DOCWELL_PB_URL=http://db:8070).
# The base image's entrypoint and HEALTHCHECK both read PB_PORT.
ENV PB_PORT=8070
EXPOSE 8070
# Inherited: VOLUME /pb/pb_data, HEALTHCHECK on /api/health, ENTRYPOINT.
+35 -17
View File
@@ -1,29 +1,47 @@
# docwell-db
# Database schema
[PocketBase](https://pocketbase.io) with Docwell's schema migrations. The image is built `FROM`
docwell-db is a stock [PocketBase](https://pocketbase.io): the stack runs
[`tajniak81/pocketbase-docker-root`](https://hub.docker.com/r/tajniak81/pocketbase-docker-root)
([source](https://github.com/freefall-dev/PocketBase-docker)); its tag, set by `PB_IMAGE` in `Dockerfile`, pins the
PocketBase version. Data is in `/pb/pb_data`; migrations and hooks are copied to `/pb/pb_migrations` and
`/pb/pb_hooks`, where PocketBase finds them next to the data directory. The base image is linux/amd64 only.
([source](https://github.com/freefall-dev/PocketBase-docker)) as it is. There is no Docwell image for it any more.
docwell-server brings PocketBase up to Docwell's schema itself, every time it starts
([`Server/internal/pbschema`](../Server/internal/pbschema/pbschema.go)): missing collections and fields are created,
existing ones keep their data. It also writes the `DOCWELL_*` settings (app name and URL, mail, file storage) and
sends Docwell's own emails, so PocketBase needs no hooks either.
- `pb_migrations/` holds JS migrations, applied in filename order at startup.
- `pb_hooks/` holds optional JS hooks (keep these minimal).
- All collection API rules are `null`, so only superusers have access. Never expose this service publicly; only docwell-server talks to it.
This folder is where that schema is written:
- `pb_migrations/` holds the JS migrations, the source of truth for the schema.
- `export-schema.sh` turns them into `Server/internal/pbschema/schema.json`, the snapshot docwell-server embeds and
applies.
- All collection API rules are `null`, so only superusers have access. Never expose PocketBase publicly; only
docwell-server talks to it.
## Changing the schema
1. Add a migration to `pb_migrations/` (`pocketbase migrate create "add_comments" --migrationsDir ./pb_migrations`,
or copy an existing file). Leave earlier migrations alone.
2. Regenerate the snapshot (needs Docker and Go):
```bash
sh Database/export-schema.sh
```
3. Commit the migration and the new `schema.json` together. `go test ./internal/pbschema` checks the snapshot.
Removing a collection or a field is not done by the snapshot: it only adds and updates. Do that by hand, once, in
the PocketBase dashboard of each install, after the release that stops using it.
The admin panel manages two parts of the `users` collection itself, the OAuth2 providers and the magic link switch
(`otp.enabled`), so the snapshot leaves them out and they keep whatever is set.
## Run locally
Download PocketBase v0.40.6 for your OS into `Database/bin/`, then:
```bash
./bin/pocketbase migrate up --dir ./pb_data --migrationsDir ./pb_migrations
./bin/pocketbase superuser upsert admin@docwell.test devpassword123 --dir ./pb_data
./bin/pocketbase serve --dir ./pb_data --migrationsDir ./pb_migrations --hooksDir ./pb_hooks
./bin/pocketbase serve --dir ./pb_data --http 127.0.0.1:8070
```
The PocketBase dashboard is at http://127.0.0.1:8070/_/.
## New migration
```bash
./bin/pocketbase migrate create "add_comments" --dir ./pb_data --migrationsDir ./pb_migrations
```
Start docwell-server against it (`DOCWELL_PB_EMAIL` and `DOCWELL_PB_PASSWORD` set to that superuser) and it creates
the collections. The PocketBase dashboard is at http://127.0.0.1:8070/_/.
+46
View File
@@ -0,0 +1,46 @@
#!/bin/sh
# Regenerates Server/internal/pbschema/schema.json from pb_migrations.
#
# docwell-server applies that snapshot to PocketBase on every start, so after
# adding or changing a migration here, run this and commit the new JSON:
#
# sh Database/export-schema.sh
#
# Needs Docker and Go. Starts a throwaway PocketBase (the same base image the
# stack runs), lets it apply the migrations to an empty database, exports the
# collections, and removes the container.
set -eu
cd "$(dirname "$0")/.."
ROOT=$(pwd)
# Docker Desktop on Windows wants E:/..., not Git Bash's /e/...
MOUNT_ROOT=$(pwd -W 2>/dev/null || pwd)
IMAGE="${PB_IMAGE:-tajniak81/pocketbase-docker-root:0.40.6}"
NAME=docwell-schema-export
PORT=18070
EMAIL=export@docwell.localhost
PASSWORD=export-only-password
docker rm -f "$NAME" >/dev/null 2>&1 || true
trap 'docker rm -f "$NAME" >/dev/null 2>&1 || true' EXIT
# Git Bash on Windows rewrites /pb/... paths unless told not to.
MSYS_NO_PATHCONV=1 docker run -d --name "$NAME" -p "127.0.0.1:$PORT:8070" \
-e PB_ADMIN_EMAIL="$EMAIL" -e PB_ADMIN_PASSWORD="$PASSWORD" \
-v "$MOUNT_ROOT/Database/pb_migrations:/pb/pb_migrations:ro" \
"$IMAGE" >/dev/null
i=0
until docker exec "$NAME" wget -qO- http://127.0.0.1:8070/api/health >/dev/null 2>&1; do
i=$((i + 1))
if [ "$i" -gt 60 ]; then
docker logs "$NAME"
echo "PocketBase did not start" >&2
exit 1
fi
sleep 1
done
cd "$ROOT/Server"
go run ./cmd/pbschema-export -url "http://127.0.0.1:$PORT" -email "$EMAIL" -password "$PASSWORD" \
-out internal/pbschema/schema.json
-96
View File
@@ -1,96 +0,0 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
/// <reference path="../pb_data/types.d.ts" />
// Token check used by docwell-server: returns the "users" record that owns the
// bearer token (with its organization expanded), or 401. Unlike auth-refresh,
// it does not issue a new token.
routerAdd(
"GET",
"/api/docwell/auth/verify",
(e) => {
e.auth.ignoreEmailVisibility(true);
e.app.expandRecord(e.auth, ["organization"], null);
return e.json(200, e.auth);
},
$apis.requireAuth("users"),
);
// Sends one email through PocketBase's SMTP settings, so docwell-server's own
// emails (invites, test mails) use the same mail configuration as the auth
// emails PocketBase sends itself.
routerAdd(
"POST",
"/api/docwell/mail",
(e) => {
const body = e.requestInfo().body;
const to = String(body.to || "").trim();
const subject = String(body.subject || "").trim();
if (!to || !subject) {
throw new BadRequestError("to and subject are required");
}
const meta = e.app.settings().meta;
const message = new MailerMessage({
from: { address: meta.senderAddress, name: meta.senderName },
to: [{ address: to }],
subject: subject,
html: String(body.html || ""),
text: String(body.text || ""),
});
e.app.newMailClient().send(message);
return e.noContent(204);
},
$apis.requireSuperuserAuth(),
);
// Settings that come from the environment are applied on every start, so
// changing an env var and restarting is enough. Settings without an env var
// are left alone: the admin panel manages them.
onBootstrap((e) => {
e.next();
const env = (key) => $os.getenv(key) || "";
const settings = e.app.settings();
if (env("DOCWELL_APP_NAME")) {
settings.meta.appName = env("DOCWELL_APP_NAME");
} else if (settings.meta.appName === "Acme") {
// PocketBase's placeholder name on a fresh database.
settings.meta.appName = "Docwell";
}
settings.meta.appURL = env("DOCWELL_WEB_URL") || "http://localhost:3000";
settings.meta.senderName = settings.meta.appName;
if (env("DOCWELL_MAIL_FROM")) {
settings.meta.senderAddress = env("DOCWELL_MAIL_FROM");
} else if (settings.meta.senderAddress === "support@example.com") {
settings.meta.senderAddress = "no-reply@docwell.localhost";
}
const smtpHost = env("DOCWELL_SMTP_HOST");
if (smtpHost) {
settings.smtp.enabled = true;
settings.smtp.host = smtpHost;
settings.smtp.port = parseInt(env("DOCWELL_SMTP_PORT") || "587", 10);
settings.smtp.username = env("DOCWELL_SMTP_USERNAME");
settings.smtp.password = env("DOCWELL_SMTP_PASSWORD");
settings.smtp.tls = env("DOCWELL_SMTP_TLS") === "true";
}
// File storage. Only when DOCWELL_S3_ENABLED is set: "true" moves uploads to
// the bucket, "false" back to local disk. Unset leaves the admin panel's
// Storage screen in charge.
const s3Enabled = env("DOCWELL_S3_ENABLED");
if (s3Enabled === "true") {
settings.s3.enabled = true;
settings.s3.bucket = env("DOCWELL_S3_BUCKET") || "docwell";
settings.s3.endpoint = env("DOCWELL_S3_ENDPOINT");
settings.s3.region = env("DOCWELL_S3_REGION") || "us-east-1";
settings.s3.accessKey = env("DOCWELL_S3_ACCESS_KEY");
settings.s3.secret = env("DOCWELL_S3_SECRET");
settings.s3.forcePathStyle = env("DOCWELL_S3_FORCE_PATH_STYLE") !== "false";
} else if (s3Enabled === "false") {
settings.s3.enabled = false;
}
e.app.save(settings);
});
@@ -43,7 +43,7 @@ migrate(
users.fields.add(new DateField({ name: "last_seen" }));
// Email links open docwell-web pages ({APP_URL} = DOCWELL_WEB_URL, set by
// pb_hooks/docwell.pb.js), never the private PocketBase dashboard.
// docwell-server on start), never the private PocketBase dashboard.
users.verificationTemplate.subject = "Verify your {APP_NAME} email";
users.verificationTemplate.body =
"<p>Hello,</p><p>Confirm your email address for {APP_NAME}:</p>" +
+2 -2
View File
@@ -43,8 +43,8 @@ RUN apk add --no-cache ca-certificates unzip wget \
&& wget -q "https://github.com/pocketbase/pocketbase/releases/download/v${PB_VERSION}/pocketbase_${PB_VERSION}_linux_${TARGETARCH:-amd64}.zip" -O /tmp/pb.zip \
&& unzip /tmp/pb.zip pocketbase -d /usr/local/bin && rm /tmp/pb.zip && apk del unzip
COPY --from=build /out/ /usr/local/bin/
COPY Database/pb_migrations /pb_migrations
COPY Database/pb_hooks /pb_hooks
# No migrations or hooks: docwell-server applies Docwell's schema and the
# DOCWELL_* settings to PocketBase when it starts.
COPY Docker-AIO/start.sh /start.sh
RUN chmod +x /start.sh && mkdir /data
+1 -1
View File
@@ -39,7 +39,7 @@ before the first start and keep a copy.
## File storage
The `DOCWELL_S3_*` variables are written into PocketBase by its boot hook on every start, and while they are set they
The `DOCWELL_S3_*` variables are written into PocketBase by docwell-server on every start, and while they are set they
win over the admin panel's **Storage** screen. Only uploaded files move to the bucket; the database and PocketBase's
backups stay in `pb_data`. The details of each storage option, and how to copy the files of an existing install into
a bucket (PocketBase does **not** move them for you), are in
+5 -4
View File
@@ -28,9 +28,10 @@ name: docwell-aio
# /api, /collab and /admin to docwell-server inside the container; PocketBase
# listens on the container's loopback only.
#
# On every boot the container applies pending migrations, creates or updates
# the PocketBase superuser from PB_ADMIN_* (a changed password is applied) and
# writes the env-driven settings (mail, app URL). All idempotent, so restarts
# On every boot the container creates or updates the PocketBase superuser
# from PB_ADMIN_* (a changed password is applied); docwell-server then brings
# the collections up to Docwell's schema and writes the env-driven settings
# (mail, app URL, file storage). All idempotent, so restarts
# and upgrades are safe.
services:
@@ -69,7 +70,7 @@ services:
DOCWELL_SMTP_PASSWORD: "${DOCWELL_SMTP_PASSWORD:-}"
DOCWELL_SMTP_TLS: "${DOCWELL_SMTP_TLS:-false}"
# --- File storage: external S3 --------------------------------------
# Applied by the PocketBase boot hook on every start, so these win over the
# Applied by docwell-server on every start, so these win over the
# admin panel's Storage screen. Only uploaded files move to the bucket;
# the database and PocketBase's backups stay on PB_DATA. The bucket must
# already exist: nothing here creates it.
@@ -40,9 +40,10 @@ name: docwell-aio
# /api, /collab and /admin to docwell-server inside the container; PocketBase
# listens on the container's loopback only.
#
# On every boot the container applies pending migrations, creates or updates
# the PocketBase superuser from PB_ADMIN_* (a changed password is applied) and
# writes the env-driven settings (mail, app URL). All idempotent, so restarts
# On every boot the container creates or updates the PocketBase superuser
# from PB_ADMIN_* (a changed password is applied); docwell-server then brings
# the collections up to Docwell's schema and writes the env-driven settings
# (mail, app URL, file storage). All idempotent, so restarts
# and upgrades are safe.
services:
@@ -241,7 +242,7 @@ services:
DOCWELL_SMTP_PASSWORD: "${DOCWELL_SMTP_PASSWORD:-}"
DOCWELL_SMTP_TLS: "${DOCWELL_SMTP_TLS:-false}"
# --- File storage: the SeaweedFS in this stack ------------------------
# Applied by the PocketBase boot hook on every start, so these win over
# Applied by docwell-server on every start, so these win over
# the admin panel's Storage screen. Only uploaded files move to the
# bucket; the database and PocketBase's backups stay on PB_DATA.
DOCWELL_S3_ENABLED: "true"
+5 -4
View File
@@ -33,9 +33,10 @@ name: docwell-aio
# /api, /collab and /admin to docwell-server inside the container; PocketBase
# listens on the container's loopback only.
#
# On every boot the container applies pending migrations, creates or updates
# the PocketBase superuser from PB_ADMIN_* (a changed password is applied) and
# writes the env-driven settings (mail, app URL). All idempotent, so restarts
# On every boot the container creates or updates the PocketBase superuser
# from PB_ADMIN_* (a changed password is applied); docwell-server then brings
# the collections up to Docwell's schema and writes the env-driven settings
# (mail, app URL, file storage). All idempotent, so restarts
# and upgrades are safe.
services:
@@ -117,7 +118,7 @@ services:
DOCWELL_SMTP_PASSWORD: "${DOCWELL_SMTP_PASSWORD:-}"
DOCWELL_SMTP_TLS: "${DOCWELL_SMTP_TLS:-false}"
# --- File storage: the SeaweedFS in this stack ------------------------
# Applied by the PocketBase boot hook on every start, so these win over
# Applied by docwell-server on every start, so these win over
# the admin panel's Storage screen. Only uploaded files move to the
# bucket; the database and PocketBase's backups stay on PB_DATA.
DOCWELL_S3_ENABLED: "true"
+4 -3
View File
@@ -19,9 +19,10 @@ name: docwell-aio
# bucket use docker-compose.prod.s3.yml (bucket elsewhere) or
# docker-compose.prod.seaweedfs.yml (SeaweedFS next to this container).
#
# On every boot the container applies pending migrations, creates or updates
# the PocketBase superuser from PB_ADMIN_* (a changed password is applied) and
# writes the env-driven settings (mail, app URL). All idempotent, so restarts
# On every boot the container creates or updates the PocketBase superuser
# from PB_ADMIN_* (a changed password is applied); docwell-server then brings
# the collections up to Docwell's schema and writes the env-driven settings
# (mail, app URL, file storage). All idempotent, so restarts
# and upgrades are safe.
services:
+3 -4
View File
@@ -16,14 +16,13 @@ if [ -n "${PB_ENCRYPTION_KEY:-}" ]; then
ENC="--encryptionEnv=PB_ENCRYPTION_KEY"
fi
# PocketBase runs stock: docwell-server applies Docwell's collections and the
# DOCWELL_* settings to it when it starts.
# shellcheck disable=SC2086 # $ENC is empty or one flag
pocketbase migrate up --dir /pb_data --migrationsDir /pb_migrations $ENC
# shellcheck disable=SC2086
pocketbase superuser upsert "$PB_ADMIN_EMAIL" "$PB_ADMIN_PASSWORD" --dir /pb_data $ENC
# shellcheck disable=SC2086
pocketbase serve --http 127.0.0.1:8070 --dir /pb_data \
--migrationsDir /pb_migrations --hooksDir /pb_hooks --automigrate=false $ENC &
pocketbase serve --http 127.0.0.1:8070 --dir /pb_data $ENC &
PB_PID=$!
i=0
+2 -1
View File
@@ -2,7 +2,8 @@
DOCWELL_REGISTRY=ghcr.io/docwell
DOCWELL_VERSION=latest
# PocketBase superuser, used by docwell-db and docwell-server. Change these.
# PocketBase superuser: docwell-db creates it, docwell-server signs in with it.
# Change these.
PB_ADMIN_EMAIL=admin@docwell.test
PB_ADMIN_PASSWORD=change-me-please
+12 -6
View File
@@ -4,12 +4,16 @@
# docker compose -f docker-compose.prod.yml up -d
# --- Images ------------------------------------------------------------------
# Registry and tag for all three images. For images released on a Gitea server,
# DOCWELL_REGISTRY=<gitea host>/<owner>. Pin a version in production.
# Registry and tag for docwell-server and docwell-web. For images released on a
# Gitea server, DOCWELL_REGISTRY=<gitea host>/<owner>. Pin a version in
# production.
DOCWELL_REGISTRY=ghcr.io/docwell
DOCWELL_VERSION=latest
# Or override one image at a time (a mirror, a hotfix tag):
# DB_IMAGE=ghcr.io/docwell/docwell-db:1.0.0
# docwell-db is a stock PocketBase; docwell-server applies Docwell's schema to
# it on start. The default, tajniak81/pocketbase-docker-root:0.40.6, creates
# the superuser below. Another PocketBase image works if it does the same.
# DB_IMAGE=tajniak81/pocketbase-docker-root:0.40.6
# Or override the Docwell images one at a time (a mirror, a hotfix tag):
# SERVER_IMAGE=ghcr.io/docwell/docwell-server:1.0.0
# WEB_IMAGE=ghcr.io/docwell/docwell-web:1.0.0
@@ -54,8 +58,10 @@ DOCWELL_MAX_UPLOAD_MB=50
DOCWELL_AUDIT_RETENTION_DAYS=
# --- Email -------------------------------------------------------------------
# Verification, password reset and sign-in codes, sent by PocketBase. Blank
# host = email off (and the admin panel's Mail screen stays in charge).
# One mail server for everything: PocketBase sends verification, password reset
# and sign-in emails, docwell-server sends invites and notifications.
# docwell-server writes these into PocketBase on every start. Blank host = the
# admin panel's Email screen stays in charge.
DOCWELL_SMTP_HOST=
DOCWELL_SMTP_PORT=587
DOCWELL_SMTP_USERNAME=
+12 -6
View File
@@ -4,12 +4,16 @@
# docker compose -f docker-compose.prod.s3.yml up -d
# --- Images ------------------------------------------------------------------
# Registry and tag for all three images. For images released on a Gitea server,
# DOCWELL_REGISTRY=<gitea host>/<owner>. Pin a version in production.
# Registry and tag for docwell-server and docwell-web. For images released on a
# Gitea server, DOCWELL_REGISTRY=<gitea host>/<owner>. Pin a version in
# production.
DOCWELL_REGISTRY=ghcr.io/docwell
DOCWELL_VERSION=latest
# Or override one image at a time (a mirror, a hotfix tag):
# DB_IMAGE=ghcr.io/docwell/docwell-db:1.0.0
# docwell-db is a stock PocketBase; docwell-server applies Docwell's schema to
# it on start. The default, tajniak81/pocketbase-docker-root:0.40.6, creates
# the superuser below. Another PocketBase image works if it does the same.
# DB_IMAGE=tajniak81/pocketbase-docker-root:0.40.6
# Or override the Docwell images one at a time (a mirror, a hotfix tag):
# SERVER_IMAGE=ghcr.io/docwell/docwell-server:1.0.0
# WEB_IMAGE=ghcr.io/docwell/docwell-web:1.0.0
@@ -54,8 +58,10 @@ DOCWELL_MAX_UPLOAD_MB=50
DOCWELL_AUDIT_RETENTION_DAYS=
# --- Email -------------------------------------------------------------------
# Verification, password reset and sign-in codes, sent by PocketBase. Blank
# host = email off (and the admin panel's Mail screen stays in charge).
# One mail server for everything: PocketBase sends verification, password reset
# and sign-in emails, docwell-server sends invites and notifications.
# docwell-server writes these into PocketBase on every start. Blank host = the
# admin panel's Email screen stays in charge.
DOCWELL_SMTP_HOST=
DOCWELL_SMTP_PORT=587
DOCWELL_SMTP_USERNAME=
+12 -6
View File
@@ -4,12 +4,16 @@
# docker compose -f docker-compose.prod.seaweedfs.yml up -d
# --- Images ------------------------------------------------------------------
# Registry and tag for all three images. For images released on a Gitea server,
# DOCWELL_REGISTRY=<gitea host>/<owner>. Pin a version in production.
# Registry and tag for docwell-server and docwell-web. For images released on a
# Gitea server, DOCWELL_REGISTRY=<gitea host>/<owner>. Pin a version in
# production.
DOCWELL_REGISTRY=ghcr.io/docwell
DOCWELL_VERSION=latest
# Or override one image at a time (a mirror, a hotfix tag):
# DB_IMAGE=ghcr.io/docwell/docwell-db:1.0.0
# docwell-db is a stock PocketBase; docwell-server applies Docwell's schema to
# it on start. The default, tajniak81/pocketbase-docker-root:0.40.6, creates
# the superuser below. Another PocketBase image works if it does the same.
# DB_IMAGE=tajniak81/pocketbase-docker-root:0.40.6
# Or override the Docwell images one at a time (a mirror, a hotfix tag):
# SERVER_IMAGE=ghcr.io/docwell/docwell-server:1.0.0
# WEB_IMAGE=ghcr.io/docwell/docwell-web:1.0.0
@@ -54,8 +58,10 @@ DOCWELL_MAX_UPLOAD_MB=50
DOCWELL_AUDIT_RETENTION_DAYS=
# --- Email -------------------------------------------------------------------
# Verification, password reset and sign-in codes, sent by PocketBase. Blank
# host = email off (and the admin panel's Mail screen stays in charge).
# One mail server for everything: PocketBase sends verification, password reset
# and sign-in emails, docwell-server sends invites and notifications.
# docwell-server writes these into PocketBase on every start. Blank host = the
# admin panel's Email screen stays in charge.
DOCWELL_SMTP_HOST=
DOCWELL_SMTP_PORT=587
DOCWELL_SMTP_USERNAME=
+12 -6
View File
@@ -4,12 +4,16 @@
# docker compose -f docker-compose.prod.seaweedfs.split.yml up -d
# --- Images ------------------------------------------------------------------
# Registry and tag for all three images. For images released on a Gitea server,
# DOCWELL_REGISTRY=<gitea host>/<owner>. Pin a version in production.
# Registry and tag for docwell-server and docwell-web. For images released on a
# Gitea server, DOCWELL_REGISTRY=<gitea host>/<owner>. Pin a version in
# production.
DOCWELL_REGISTRY=ghcr.io/docwell
DOCWELL_VERSION=latest
# Or override one image at a time (a mirror, a hotfix tag):
# DB_IMAGE=ghcr.io/docwell/docwell-db:1.0.0
# docwell-db is a stock PocketBase; docwell-server applies Docwell's schema to
# it on start. The default, tajniak81/pocketbase-docker-root:0.40.6, creates
# the superuser below. Another PocketBase image works if it does the same.
# DB_IMAGE=tajniak81/pocketbase-docker-root:0.40.6
# Or override the Docwell images one at a time (a mirror, a hotfix tag):
# SERVER_IMAGE=ghcr.io/docwell/docwell-server:1.0.0
# WEB_IMAGE=ghcr.io/docwell/docwell-web:1.0.0
@@ -54,8 +58,10 @@ DOCWELL_MAX_UPLOAD_MB=50
DOCWELL_AUDIT_RETENTION_DAYS=
# --- Email -------------------------------------------------------------------
# Verification, password reset and sign-in codes, sent by PocketBase. Blank
# host = email off (and the admin panel's Mail screen stays in charge).
# One mail server for everything: PocketBase sends verification, password reset
# and sign-in emails, docwell-server sends invites and notifications.
# docwell-server writes these into PocketBase on every start. Blank host = the
# admin panel's Email screen stays in charge.
DOCWELL_SMTP_HOST=
DOCWELL_SMTP_PORT=587
DOCWELL_SMTP_USERNAME=
+16 -11
View File
@@ -26,16 +26,21 @@ up becomes the instance admin.**
## The PocketBase image
docwell-db is built `FROM tajniak81/pocketbase-docker-root` (source:
[freefall-dev/PocketBase-docker](https://github.com/freefall-dev/PocketBase-docker), root variant), with Docwell's
`pb_migrations` and `pb_hooks` copied into `/pb`. That image downloads a pinned PocketBase release and checks it
against the published checksums. On every start its entrypoint creates the superuser from `PB_ADMIN_EMAIL` and
`PB_ADMIN_PASSWORD` if it does not exist yet, then starts `pocketbase serve`, which applies pending migrations.
docwell-db runs [`tajniak81/pocketbase-docker-root`](https://hub.docker.com/r/tajniak81/pocketbase-docker-root)
(source: [freefall-dev/PocketBase-docker](https://github.com/freefall-dev/PocketBase-docker), root variant) as it is,
with no Docwell files in it. That image downloads a pinned PocketBase release and checks it against the published
checksums. On every start its entrypoint creates the superuser from `PB_ADMIN_EMAIL` and `PB_ADMIN_PASSWORD` if it
does not exist yet, then starts `pocketbase serve` on port 8070.
docwell-server does the rest when it starts: it signs in as that superuser, brings PocketBase's collections up to
Docwell's schema (creating what is missing, keeping existing data), and writes the settings that come from the
environment (`DOCWELL_APP_NAME`, `DOCWELL_WEB_URL`, `DOCWELL_MAIL_FROM`, `DOCWELL_SMTP_*`, `DOCWELL_S3_*`). Upgrading
Docwell is therefore just a newer docwell-server; docwell-db changes only when you move to a newer PocketBase.
- Data lives in `/pb/pb_data` in the container.
- The PocketBase version follows the base image tag, set by `PB_IMAGE` in [`Database/Dockerfile`](../Database/Dockerfile)
(`docker build --build-arg PB_IMAGE=tajniak81/pocketbase-docker-root:0.40.6 Database`).
- The base image is published for **linux/amd64 only**, so docwell-db is amd64-only for now.
- The PocketBase version is the image tag. Override it with `DB_IMAGE` in `.env`; any PocketBase image that creates
the superuser from `PB_ADMIN_*` and serves on port 8070 works.
- The base image is published for **linux/amd64 only**.
- `PB_ENCRYPTION_KEY` (exactly 32 characters, `openssl rand -hex 16`) turns on PocketBase's settings
encryption, which keeps the stored SMTP password and S3 secret encrypted. Set it before the first start and keep
a copy.
@@ -61,8 +66,8 @@ By default uploaded files sit in `pb_data/storage`, next to the database. The S3
bucket instead; the database and PocketBase's own backups stay in `pb_data` either way. Clients never see the bucket:
every file goes through docwell-server.
The storage settings come from the `DOCWELL_S3_*` variables, which docwell-db's boot hook writes into PocketBase on
every start. While `DOCWELL_S3_ENABLED` is set they win over the admin panel's **Storage** screen; with the plain
The storage settings come from the `DOCWELL_S3_*` variables, which docwell-server writes into PocketBase on every
start. While `DOCWELL_S3_ENABLED` is set they win over the admin panel's **Storage** screen; with the plain
`docker-compose.prod.yml` (no `DOCWELL_S3_*`) the admin panel is in charge. "Test the saved bucket" in that screen
checks the connection either way.
@@ -103,5 +108,5 @@ docker compose -f docker-compose.prod.yml pull
docker compose -f docker-compose.prod.yml up -d
```
Migrations run when docwell-db starts. Pin `DOCWELL_VERSION` in production, and take a backup first
docwell-server updates PocketBase's collections when it starts. Pin `DOCWELL_VERSION` in production, and take a backup first
(admin panel → Backups, or a copy of the `pb_data` volume).
+35 -27
View File
@@ -28,15 +28,19 @@ name: docwell
# docwell-server is the only client of docwell-db (PocketBase).
#
# On every boot:
# • docwell-db creates the PocketBase superuser from PB_ADMIN_* if it does not
# exist yet (an existing one is left alone, password included), applies
# pending migrations and writes the env-driven settings (mail, app URL).
# • docwell-server signs in to PocketBase with the same PB_ADMIN_* pair.
# • docwell-db, a stock PocketBase (tajniak81/pocketbase-docker-root), creates
# the superuser from PB_ADMIN_* if it does not exist yet (an existing one is
# left alone, password included).
# • docwell-server signs in with the same PB_ADMIN_* pair, brings PocketBase's
# collections up to Docwell's schema and writes the env-driven settings
# (app name and URL, mail, file storage).
# Both are idempotent, so restarts and upgrades are safe.
services:
db:
image: "${DB_IMAGE:-${DOCWELL_REGISTRY:-ghcr.io/docwell}/docwell-db:${DOCWELL_VERSION:-latest}}"
# A stock PocketBase: docwell-server applies Docwell's schema to it on
# start, so the image needs no migrations or hooks of its own.
image: "${DB_IMAGE:-tajniak81/pocketbase-docker-root:0.40.6}"
container_name: docwell-db
restart: unless-stopped
extra_hosts:
@@ -53,28 +57,6 @@ services:
# Exactly 32 characters; blank = off. Set it before the first boot and
# never lose it: the settings cannot be read without it.
PB_ENCRYPTION_KEY: "${PB_ENCRYPTION_KEY:-}"
# PocketBase sends the auth emails; the links in them open docwell-web.
DOCWELL_APP_NAME: "${DOCWELL_APP_NAME:-}"
DOCWELL_WEB_URL: "${DOCWELL_WEB_URL:-http://localhost:3000}"
DOCWELL_MAIL_FROM: "${DOCWELL_MAIL_FROM:-}"
DOCWELL_SMTP_HOST: "${DOCWELL_SMTP_HOST:-}"
DOCWELL_SMTP_PORT: "${DOCWELL_SMTP_PORT:-587}"
DOCWELL_SMTP_USERNAME: "${DOCWELL_SMTP_USERNAME:-}"
DOCWELL_SMTP_PASSWORD: "${DOCWELL_SMTP_PASSWORD:-}"
DOCWELL_SMTP_TLS: "${DOCWELL_SMTP_TLS:-false}"
# --- File storage: external S3 --------------------------------------
# Applied by the PocketBase boot hook on every start, so these win over the
# admin panel's Storage screen. Only uploaded files move to the bucket;
# the database and PocketBase's backups stay on PB_DATA. The bucket must
# already exist: nothing here creates it.
DOCWELL_S3_ENABLED: "true"
DOCWELL_S3_ENDPOINT: "${DOCWELL_S3_ENDPOINT:?set DOCWELL_S3_ENDPOINT in .env}"
DOCWELL_S3_BUCKET: "${DOCWELL_S3_BUCKET:-docwell}"
DOCWELL_S3_REGION: "${DOCWELL_S3_REGION:-us-east-1}"
DOCWELL_S3_ACCESS_KEY: "${DOCWELL_S3_ACCESS_KEY:?set DOCWELL_S3_ACCESS_KEY in .env}"
DOCWELL_S3_SECRET: "${DOCWELL_S3_SECRET:?set DOCWELL_S3_SECRET in .env}"
# true for SeaweedFS and MinIO, false for AWS S3 proper.
DOCWELL_S3_FORCE_PATH_STYLE: "${DOCWELL_S3_FORCE_PATH_STYLE:-true}"
volumes:
# Named volume by default; set PB_DATA to a host path in .env for a bind
# mount. Database, uploads, PocketBase backups: back this one up.
@@ -116,6 +98,32 @@ services:
DOCWELL_SIGNUP_DOMAINS: "${DOCWELL_SIGNUP_DOMAINS:-}"
DOCWELL_MAX_UPLOAD_MB: "${DOCWELL_MAX_UPLOAD_MB:-50}"
DOCWELL_AUDIT_RETENTION_DAYS: "${DOCWELL_AUDIT_RETENTION_DAYS:-}"
# --- PocketBase settings ----------------------------------------------
# Written into PocketBase by docwell-server on every start, so they win
# over the admin panel. PocketBase sends the auth emails (verification,
# reset, sign-in links), docwell-server its own (invites, notifications),
# both through this mail server. Blank SMTP host = the admin panel's
# Email screen is in charge.
DOCWELL_APP_NAME: "${DOCWELL_APP_NAME:-}"
DOCWELL_MAIL_FROM: "${DOCWELL_MAIL_FROM:-}"
DOCWELL_SMTP_HOST: "${DOCWELL_SMTP_HOST:-}"
DOCWELL_SMTP_PORT: "${DOCWELL_SMTP_PORT:-587}"
DOCWELL_SMTP_USERNAME: "${DOCWELL_SMTP_USERNAME:-}"
DOCWELL_SMTP_PASSWORD: "${DOCWELL_SMTP_PASSWORD:-}"
DOCWELL_SMTP_TLS: "${DOCWELL_SMTP_TLS:-false}"
# --- File storage: external S3 --------------------------------------
# Applied by docwell-server on every start, so these win over the
# admin panel's Storage screen. Only uploaded files move to the bucket;
# the database and PocketBase's backups stay on PB_DATA. The bucket must
# already exist: nothing here creates it.
DOCWELL_S3_ENABLED: "true"
DOCWELL_S3_ENDPOINT: "${DOCWELL_S3_ENDPOINT:?set DOCWELL_S3_ENDPOINT in .env}"
DOCWELL_S3_BUCKET: "${DOCWELL_S3_BUCKET:-docwell}"
DOCWELL_S3_REGION: "${DOCWELL_S3_REGION:-us-east-1}"
DOCWELL_S3_ACCESS_KEY: "${DOCWELL_S3_ACCESS_KEY:?set DOCWELL_S3_ACCESS_KEY in .env}"
DOCWELL_S3_SECRET: "${DOCWELL_S3_SECRET:?set DOCWELL_S3_SECRET in .env}"
# true for SeaweedFS and MinIO, false for AWS S3 proper.
DOCWELL_S3_FORCE_PATH_STYLE: "${DOCWELL_S3_FORCE_PATH_STYLE:-true}"
volumes:
# The search index only; rebuilt from the database when missing, so it
# needs no backup.
+36 -28
View File
@@ -36,10 +36,12 @@ name: docwell
# docwell-server is the only client of docwell-db (PocketBase).
#
# On every boot:
# • docwell-db creates the PocketBase superuser from PB_ADMIN_* if it does not
# exist yet (an existing one is left alone, password included), applies
# pending migrations and writes the env-driven settings (mail, app URL).
# • docwell-server signs in to PocketBase with the same PB_ADMIN_* pair.
# • docwell-db, a stock PocketBase (tajniak81/pocketbase-docker-root), creates
# the superuser from PB_ADMIN_* if it does not exist yet (an existing one is
# left alone, password included).
# • docwell-server signs in with the same PB_ADMIN_* pair, brings PocketBase's
# collections up to Docwell's schema and writes the env-driven settings
# (app name and URL, mail, file storage).
# Both are idempotent, so restarts and upgrades are safe.
services:
@@ -204,7 +206,9 @@ services:
start_period: 15s
db:
image: "${DB_IMAGE:-${DOCWELL_REGISTRY:-ghcr.io/docwell}/docwell-db:${DOCWELL_VERSION:-latest}}"
# A stock PocketBase: docwell-server applies Docwell's schema to it on
# start, so the image needs no migrations or hooks of its own.
image: "${DB_IMAGE:-tajniak81/pocketbase-docker-root:0.40.6}"
container_name: docwell-db
restart: unless-stopped
depends_on:
@@ -221,29 +225,6 @@ services:
# Exactly 32 characters; blank = off. Set it before the first boot and
# never lose it: the settings cannot be read without it.
PB_ENCRYPTION_KEY: "${PB_ENCRYPTION_KEY:-}"
# PocketBase sends the auth emails; the links in them open docwell-web.
DOCWELL_APP_NAME: "${DOCWELL_APP_NAME:-}"
DOCWELL_WEB_URL: "${DOCWELL_WEB_URL:-http://localhost:3000}"
DOCWELL_MAIL_FROM: "${DOCWELL_MAIL_FROM:-}"
DOCWELL_SMTP_HOST: "${DOCWELL_SMTP_HOST:-}"
DOCWELL_SMTP_PORT: "${DOCWELL_SMTP_PORT:-587}"
DOCWELL_SMTP_USERNAME: "${DOCWELL_SMTP_USERNAME:-}"
DOCWELL_SMTP_PASSWORD: "${DOCWELL_SMTP_PASSWORD:-}"
DOCWELL_SMTP_TLS: "${DOCWELL_SMTP_TLS:-false}"
# --- File storage: the SeaweedFS in this stack ------------------------
# Applied by the PocketBase boot hook on every start, so these win over
# the admin panel's Storage screen. Only uploaded files move to the
# bucket; the database and PocketBase's backups stay on PB_DATA.
DOCWELL_S3_ENABLED: "true"
# The service name: a container-to-container call on the compose network.
DOCWELL_S3_ENDPOINT: "http://seaweedfs-s3:8333"
DOCWELL_S3_BUCKET: "${DOCWELL_S3_BUCKET:-docwell}"
# SeaweedFS ignores the region; PocketBase insists on having one.
DOCWELL_S3_REGION: "${DOCWELL_S3_REGION:-us-east-1}"
DOCWELL_S3_ACCESS_KEY: "${DOCWELL_S3_ACCESS_KEY:?set DOCWELL_S3_ACCESS_KEY in .env}"
DOCWELL_S3_SECRET: "${DOCWELL_S3_SECRET:?set DOCWELL_S3_SECRET in .env}"
# Path style: a self-hosted gateway has no per-bucket DNS names.
DOCWELL_S3_FORCE_PATH_STYLE: "true"
volumes:
# Named volume by default; set PB_DATA to a host path in .env for a bind
# mount. Database, uploads, PocketBase backups: back this one up.
@@ -285,6 +266,33 @@ services:
DOCWELL_SIGNUP_DOMAINS: "${DOCWELL_SIGNUP_DOMAINS:-}"
DOCWELL_MAX_UPLOAD_MB: "${DOCWELL_MAX_UPLOAD_MB:-50}"
DOCWELL_AUDIT_RETENTION_DAYS: "${DOCWELL_AUDIT_RETENTION_DAYS:-}"
# --- PocketBase settings ----------------------------------------------
# Written into PocketBase by docwell-server on every start, so they win
# over the admin panel. PocketBase sends the auth emails (verification,
# reset, sign-in links), docwell-server its own (invites, notifications),
# both through this mail server. Blank SMTP host = the admin panel's
# Email screen is in charge.
DOCWELL_APP_NAME: "${DOCWELL_APP_NAME:-}"
DOCWELL_MAIL_FROM: "${DOCWELL_MAIL_FROM:-}"
DOCWELL_SMTP_HOST: "${DOCWELL_SMTP_HOST:-}"
DOCWELL_SMTP_PORT: "${DOCWELL_SMTP_PORT:-587}"
DOCWELL_SMTP_USERNAME: "${DOCWELL_SMTP_USERNAME:-}"
DOCWELL_SMTP_PASSWORD: "${DOCWELL_SMTP_PASSWORD:-}"
DOCWELL_SMTP_TLS: "${DOCWELL_SMTP_TLS:-false}"
# --- File storage: the SeaweedFS in this stack ------------------------
# Applied by docwell-server on every start, so these win over
# the admin panel's Storage screen. Only uploaded files move to the
# bucket; the database and PocketBase's backups stay on PB_DATA.
DOCWELL_S3_ENABLED: "true"
# The service name: a container-to-container call on the compose network.
DOCWELL_S3_ENDPOINT: "http://seaweedfs-s3:8333"
DOCWELL_S3_BUCKET: "${DOCWELL_S3_BUCKET:-docwell}"
# SeaweedFS ignores the region; PocketBase insists on having one.
DOCWELL_S3_REGION: "${DOCWELL_S3_REGION:-us-east-1}"
DOCWELL_S3_ACCESS_KEY: "${DOCWELL_S3_ACCESS_KEY:?set DOCWELL_S3_ACCESS_KEY in .env}"
DOCWELL_S3_SECRET: "${DOCWELL_S3_SECRET:?set DOCWELL_S3_SECRET in .env}"
# Path style: a self-hosted gateway has no per-bucket DNS names.
DOCWELL_S3_FORCE_PATH_STYLE: "true"
volumes:
# The search index only; rebuilt from the database when missing, so it
# needs no backup.
+36 -28
View File
@@ -29,10 +29,12 @@ name: docwell
# docwell-server is the only client of docwell-db (PocketBase).
#
# On every boot:
# • docwell-db creates the PocketBase superuser from PB_ADMIN_* if it does not
# exist yet (an existing one is left alone, password included), applies
# pending migrations and writes the env-driven settings (mail, app URL).
# • docwell-server signs in to PocketBase with the same PB_ADMIN_* pair.
# • docwell-db, a stock PocketBase (tajniak81/pocketbase-docker-root), creates
# the superuser from PB_ADMIN_* if it does not exist yet (an existing one is
# left alone, password included).
# • docwell-server signs in with the same PB_ADMIN_* pair, brings PocketBase's
# collections up to Docwell's schema and writes the env-driven settings
# (app name and URL, mail, file storage).
# Both are idempotent, so restarts and upgrades are safe.
services:
@@ -80,7 +82,9 @@ services:
- 'echo "s3.bucket.create -name $$DOCWELL_S3_BUCKET" | weed shell -master=seaweedfs:9333 || true'
db:
image: "${DB_IMAGE:-${DOCWELL_REGISTRY:-ghcr.io/docwell}/docwell-db:${DOCWELL_VERSION:-latest}}"
# A stock PocketBase: docwell-server applies Docwell's schema to it on
# start, so the image needs no migrations or hooks of its own.
image: "${DB_IMAGE:-tajniak81/pocketbase-docker-root:0.40.6}"
container_name: docwell-db
restart: unless-stopped
depends_on:
@@ -97,29 +101,6 @@ services:
# Exactly 32 characters; blank = off. Set it before the first boot and
# never lose it: the settings cannot be read without it.
PB_ENCRYPTION_KEY: "${PB_ENCRYPTION_KEY:-}"
# PocketBase sends the auth emails; the links in them open docwell-web.
DOCWELL_APP_NAME: "${DOCWELL_APP_NAME:-}"
DOCWELL_WEB_URL: "${DOCWELL_WEB_URL:-http://localhost:3000}"
DOCWELL_MAIL_FROM: "${DOCWELL_MAIL_FROM:-}"
DOCWELL_SMTP_HOST: "${DOCWELL_SMTP_HOST:-}"
DOCWELL_SMTP_PORT: "${DOCWELL_SMTP_PORT:-587}"
DOCWELL_SMTP_USERNAME: "${DOCWELL_SMTP_USERNAME:-}"
DOCWELL_SMTP_PASSWORD: "${DOCWELL_SMTP_PASSWORD:-}"
DOCWELL_SMTP_TLS: "${DOCWELL_SMTP_TLS:-false}"
# --- File storage: the SeaweedFS in this stack ------------------------
# Applied by the PocketBase boot hook on every start, so these win over
# the admin panel's Storage screen. Only uploaded files move to the
# bucket; the database and PocketBase's backups stay on PB_DATA.
DOCWELL_S3_ENABLED: "true"
# The service name: a container-to-container call on the compose network.
DOCWELL_S3_ENDPOINT: "http://seaweedfs:8333"
DOCWELL_S3_BUCKET: "${DOCWELL_S3_BUCKET:-docwell}"
# SeaweedFS ignores the region; PocketBase insists on having one.
DOCWELL_S3_REGION: "${DOCWELL_S3_REGION:-us-east-1}"
DOCWELL_S3_ACCESS_KEY: "${DOCWELL_S3_ACCESS_KEY:?set DOCWELL_S3_ACCESS_KEY in .env}"
DOCWELL_S3_SECRET: "${DOCWELL_S3_SECRET:?set DOCWELL_S3_SECRET in .env}"
# Path style: a self-hosted gateway has no per-bucket DNS names.
DOCWELL_S3_FORCE_PATH_STYLE: "true"
volumes:
# Named volume by default; set PB_DATA to a host path in .env for a bind
# mount. Database, uploads, PocketBase backups: back this one up.
@@ -161,6 +142,33 @@ services:
DOCWELL_SIGNUP_DOMAINS: "${DOCWELL_SIGNUP_DOMAINS:-}"
DOCWELL_MAX_UPLOAD_MB: "${DOCWELL_MAX_UPLOAD_MB:-50}"
DOCWELL_AUDIT_RETENTION_DAYS: "${DOCWELL_AUDIT_RETENTION_DAYS:-}"
# --- PocketBase settings ----------------------------------------------
# Written into PocketBase by docwell-server on every start, so they win
# over the admin panel. PocketBase sends the auth emails (verification,
# reset, sign-in links), docwell-server its own (invites, notifications),
# both through this mail server. Blank SMTP host = the admin panel's
# Email screen is in charge.
DOCWELL_APP_NAME: "${DOCWELL_APP_NAME:-}"
DOCWELL_MAIL_FROM: "${DOCWELL_MAIL_FROM:-}"
DOCWELL_SMTP_HOST: "${DOCWELL_SMTP_HOST:-}"
DOCWELL_SMTP_PORT: "${DOCWELL_SMTP_PORT:-587}"
DOCWELL_SMTP_USERNAME: "${DOCWELL_SMTP_USERNAME:-}"
DOCWELL_SMTP_PASSWORD: "${DOCWELL_SMTP_PASSWORD:-}"
DOCWELL_SMTP_TLS: "${DOCWELL_SMTP_TLS:-false}"
# --- File storage: the SeaweedFS in this stack ------------------------
# Applied by docwell-server on every start, so these win over
# the admin panel's Storage screen. Only uploaded files move to the
# bucket; the database and PocketBase's backups stay on PB_DATA.
DOCWELL_S3_ENABLED: "true"
# The service name: a container-to-container call on the compose network.
DOCWELL_S3_ENDPOINT: "http://seaweedfs:8333"
DOCWELL_S3_BUCKET: "${DOCWELL_S3_BUCKET:-docwell}"
# SeaweedFS ignores the region; PocketBase insists on having one.
DOCWELL_S3_REGION: "${DOCWELL_S3_REGION:-us-east-1}"
DOCWELL_S3_ACCESS_KEY: "${DOCWELL_S3_ACCESS_KEY:?set DOCWELL_S3_ACCESS_KEY in .env}"
DOCWELL_S3_SECRET: "${DOCWELL_S3_SECRET:?set DOCWELL_S3_SECRET in .env}"
# Path style: a self-hosted gateway has no per-bucket DNS names.
DOCWELL_S3_FORCE_PATH_STYLE: "true"
volumes:
# The search index only; rebuilt from the database when missing, so it
# needs no backup.
+22 -14
View File
@@ -19,15 +19,19 @@ name: docwell
# docker-compose.prod.seaweedfs.yml (SeaweedFS in this stack).
#
# On every boot:
# • docwell-db creates the PocketBase superuser from PB_ADMIN_* if it does not
# exist yet (an existing one is left alone, password included), applies
# pending migrations and writes the env-driven settings (mail, app URL).
# • docwell-server signs in to PocketBase with the same PB_ADMIN_* pair.
# • docwell-db, a stock PocketBase (tajniak81/pocketbase-docker-root), creates
# the superuser from PB_ADMIN_* if it does not exist yet (an existing one is
# left alone, password included).
# • docwell-server signs in with the same PB_ADMIN_* pair, brings PocketBase's
# collections up to Docwell's schema and writes the env-driven settings
# (app name and URL, mail, file storage).
# Both are idempotent, so restarts and upgrades are safe.
services:
db:
image: "${DB_IMAGE:-${DOCWELL_REGISTRY:-ghcr.io/docwell}/docwell-db:${DOCWELL_VERSION:-latest}}"
# A stock PocketBase: docwell-server applies Docwell's schema to it on
# start, so the image needs no migrations or hooks of its own.
image: "${DB_IMAGE:-tajniak81/pocketbase-docker-root:0.40.6}"
container_name: docwell-db
restart: unless-stopped
environment:
@@ -40,15 +44,6 @@ services:
# Exactly 32 characters; blank = off. Set it before the first boot and
# never lose it: the settings cannot be read without it.
PB_ENCRYPTION_KEY: "${PB_ENCRYPTION_KEY:-}"
# PocketBase sends the auth emails; the links in them open docwell-web.
DOCWELL_APP_NAME: "${DOCWELL_APP_NAME:-}"
DOCWELL_WEB_URL: "${DOCWELL_WEB_URL:-http://localhost:3000}"
DOCWELL_MAIL_FROM: "${DOCWELL_MAIL_FROM:-}"
DOCWELL_SMTP_HOST: "${DOCWELL_SMTP_HOST:-}"
DOCWELL_SMTP_PORT: "${DOCWELL_SMTP_PORT:-587}"
DOCWELL_SMTP_USERNAME: "${DOCWELL_SMTP_USERNAME:-}"
DOCWELL_SMTP_PASSWORD: "${DOCWELL_SMTP_PASSWORD:-}"
DOCWELL_SMTP_TLS: "${DOCWELL_SMTP_TLS:-false}"
volumes:
# Named volume by default; set PB_DATA to a host path in .env for a bind
# mount. Database, uploads, PocketBase backups: back this one up.
@@ -90,6 +85,19 @@ services:
DOCWELL_SIGNUP_DOMAINS: "${DOCWELL_SIGNUP_DOMAINS:-}"
DOCWELL_MAX_UPLOAD_MB: "${DOCWELL_MAX_UPLOAD_MB:-50}"
DOCWELL_AUDIT_RETENTION_DAYS: "${DOCWELL_AUDIT_RETENTION_DAYS:-}"
# --- PocketBase settings ----------------------------------------------
# Written into PocketBase by docwell-server on every start, so they win
# over the admin panel. PocketBase sends the auth emails (verification,
# reset, sign-in links), docwell-server its own (invites, notifications),
# both through this mail server. Blank SMTP host = the admin panel's
# Email screen is in charge.
DOCWELL_APP_NAME: "${DOCWELL_APP_NAME:-}"
DOCWELL_MAIL_FROM: "${DOCWELL_MAIL_FROM:-}"
DOCWELL_SMTP_HOST: "${DOCWELL_SMTP_HOST:-}"
DOCWELL_SMTP_PORT: "${DOCWELL_SMTP_PORT:-587}"
DOCWELL_SMTP_USERNAME: "${DOCWELL_SMTP_USERNAME:-}"
DOCWELL_SMTP_PASSWORD: "${DOCWELL_SMTP_PASSWORD:-}"
DOCWELL_SMTP_TLS: "${DOCWELL_SMTP_TLS:-false}"
volumes:
# The search index only; rebuilt from the database when missing, so it
# needs no backup.
+10 -10
View File
@@ -8,20 +8,12 @@ name: docwell
services:
db:
image: ${DOCWELL_REGISTRY:-ghcr.io/docwell}/docwell-db:${DOCWELL_VERSION:-latest}
build: ../Database
# A stock PocketBase: docwell-server applies Docwell's schema to it on start.
image: ${DB_IMAGE:-tajniak81/pocketbase-docker-root:0.40.6}
restart: unless-stopped
environment:
PB_ADMIN_EMAIL: ${PB_ADMIN_EMAIL}
PB_ADMIN_PASSWORD: ${PB_ADMIN_PASSWORD}
# PocketBase sends the auth emails; links in them open docwell-web.
DOCWELL_WEB_URL: ${DOCWELL_WEB_URL:-http://localhost:3000}
DOCWELL_MAIL_FROM: ${DOCWELL_MAIL_FROM:-no-reply@docwell.localhost}
DOCWELL_SMTP_HOST: ${DOCWELL_SMTP_HOST:-}
DOCWELL_SMTP_PORT: ${DOCWELL_SMTP_PORT:-587}
DOCWELL_SMTP_USERNAME: ${DOCWELL_SMTP_USERNAME:-}
DOCWELL_SMTP_PASSWORD: ${DOCWELL_SMTP_PASSWORD:-}
DOCWELL_SMTP_TLS: ${DOCWELL_SMTP_TLS:-false}
# Optional: encrypts PocketBase's stored settings (exactly 32 characters).
PB_ENCRYPTION_KEY: ${PB_ENCRYPTION_KEY:-}
volumes:
@@ -50,6 +42,14 @@ services:
DOCWELL_SIGNUP_ENABLED: ${DOCWELL_SIGNUP_ENABLED:-true}
DOCWELL_SIGNUP_DOMAINS: ${DOCWELL_SIGNUP_DOMAINS:-}
DOCWELL_MAX_UPLOAD_MB: ${DOCWELL_MAX_UPLOAD_MB:-50}
# Written into PocketBase on every start. PocketBase sends the auth
# emails, docwell-server its own, both through this mail server.
DOCWELL_MAIL_FROM: ${DOCWELL_MAIL_FROM:-no-reply@docwell.localhost}
DOCWELL_SMTP_HOST: ${DOCWELL_SMTP_HOST:-}
DOCWELL_SMTP_PORT: ${DOCWELL_SMTP_PORT:-587}
DOCWELL_SMTP_USERNAME: ${DOCWELL_SMTP_USERNAME:-}
DOCWELL_SMTP_PASSWORD: ${DOCWELL_SMTP_PASSWORD:-}
DOCWELL_SMTP_TLS: ${DOCWELL_SMTP_TLS:-false}
volumes:
# The search index (rebuilt from the database when missing).
- server_data:/data
+1 -1
View File
@@ -36,5 +36,5 @@ curl -fsS -X POST https://wiki.example.com/api/v1/admin/backups -H "Authorizatio
Pin a version with `DOCWELL_VERSION=0.1.0` in `.env` instead of following `latest`.
Database changes (migrations) run on their own when docwell-db starts. Going back to an older version after a
Database changes run on their own: docwell-server updates PocketBase's collections when it starts. Going back to an older version after a
migration is not supported; restore the backup instead.
+29 -20
View File
@@ -6,15 +6,42 @@ Docwell is configured with environment variables, set in `.env` (separate servic
## Database (docwell-db)
docwell-db is a stock PocketBase image (`tajniak81/pocketbase-docker-root`); docwell-server creates and updates
Docwell's collections in it when it starts. Change the image with `DB_IMAGE`.
| Variable | Default | What it does |
| --- | --- | --- |
| `PB_ADMIN_EMAIL` | `admin@docwell.test` | The internal PocketBase superuser. docwell-server signs in with it. |
| `PB_ADMIN_PASSWORD` | *(required)* | Its password. Also the key file links are signed with: changing it ends open file links (they renew on reload). docwell-db only uses it to *create* the superuser; to change it later, see *Changing the PocketBase password* in `Docker/README.md`. The all-in-one image applies a new value at every start. |
| `PB_ENCRYPTION_KEY` | | Exactly 32 characters. Encrypts PocketBase's stored settings (SMTP password, S3 secret). Set it before the first start and keep a copy. |
| `DOCWELL_WEB_URL` | `http://localhost:3000` | The web app's address. Links in emails open it. |
## API server (docwell-server)
| Variable | Default | What it does |
| --- | --- | --- |
| `DOCWELL_ADDR` | `:8080` | Listen address. |
| `DOCWELL_PB_URL` | `http://127.0.0.1:8070` | Where docwell-db is. Keep it on a private network. |
| `DOCWELL_PB_EMAIL`, `DOCWELL_PB_PASSWORD` | *(required)* | The PocketBase superuser (`PB_ADMIN_EMAIL`, `PB_ADMIN_PASSWORD`). |
| `DOCWELL_PUBLIC_URL` | `http://localhost:8080` | The API's public address. Exported pages link attachments here. |
| `DOCWELL_WEB_URL` | `http://localhost:3000` | The web app's address, for invite and share links, and for the links in PocketBase's emails. |
| `DOCWELL_CORS_ORIGINS` | `http://localhost:5173,http://localhost:3000` | Comma-separated origins allowed to call the API from a browser: the web app's address. |
| `DOCWELL_SIGNUP_ENABLED` | `true` | Self-service sign-up, until a superadmin saves *Authentication* in the admin panel. |
| `DOCWELL_SIGNUP_DOMAINS` | | Comma-separated email domains allowed to sign up (empty: any), with the same rule. |
| `DOCWELL_MAX_UPLOAD_MB` | `50` | Largest attachment, 1 to 100. |
| `DOCWELL_DATA_DIR` | `./data` (`/data` in the image) | The search index. It is rebuilt from the database when missing, so a volume is optional but makes restarts faster. |
| `DOCWELL_SHUTDOWN_TIMEOUT` | `15s` | How long to wait for requests and open pages to finish saving on shutdown. |
| `DOCWELL_AUDIT_RETENTION_DAYS` | `365` | How long the audit log keeps entries. `0` keeps them forever. |
| `DOCWELL_WEBHOOKS_ALLOW_LOCAL` | `false` | Let webhooks call loopback and link-local addresses. For development only. |
### PocketBase settings
docwell-server writes these into PocketBase every time it starts.
| Variable | Default | What it does |
| --- | --- | --- |
| `DOCWELL_APP_NAME` | | The name in emails. When set it is applied at every start and overrides *Branding*. |
| `DOCWELL_MAIL_FROM` | `no-reply@docwell.localhost` | Sender address. When set it overrides *Email → Sender address* at every start. |
| `DOCWELL_SMTP_HOST` | | Mail server. When set, all `DOCWELL_SMTP_*` values are applied at every start and override *Admin panel → Email*. Leave it empty to manage mail in the admin panel. |
| `DOCWELL_SMTP_HOST` | | Mail server, for PocketBase's emails (verification, password reset, sign-in links) and docwell-server's own (invites, notifications). When set, all `DOCWELL_SMTP_*` values are applied at every start and override *Admin panel → Email*. Leave it empty to manage mail in the admin panel. |
| `DOCWELL_SMTP_PORT` | `587` | |
| `DOCWELL_SMTP_USERNAME` | | |
| `DOCWELL_SMTP_PASSWORD` | | |
@@ -26,24 +53,6 @@ Docwell is configured with environment variables, set in `.env` (separate servic
| `DOCWELL_S3_ACCESS_KEY`, `DOCWELL_S3_SECRET` | | Credentials. |
| `DOCWELL_S3_FORCE_PATH_STYLE` | `true` | `false` for AWS S3; `true` for MinIO and SeaweedFS. |
## API server (docwell-server)
| Variable | Default | What it does |
| --- | --- | --- |
| `DOCWELL_ADDR` | `:8080` | Listen address. |
| `DOCWELL_PB_URL` | `http://127.0.0.1:8070` | Where docwell-db is. Keep it on a private network. |
| `DOCWELL_PB_EMAIL`, `DOCWELL_PB_PASSWORD` | *(required)* | The PocketBase superuser (`PB_ADMIN_EMAIL`, `PB_ADMIN_PASSWORD`). |
| `DOCWELL_PUBLIC_URL` | `http://localhost:8080` | The API's public address. Exported pages link attachments here. |
| `DOCWELL_WEB_URL` | `http://localhost:3000` | The web app's address, for invite and share links. |
| `DOCWELL_CORS_ORIGINS` | `http://localhost:5173,http://localhost:3000` | Comma-separated origins allowed to call the API from a browser: the web app's address. |
| `DOCWELL_SIGNUP_ENABLED` | `true` | Self-service sign-up, until a superadmin saves *Authentication* in the admin panel. |
| `DOCWELL_SIGNUP_DOMAINS` | | Comma-separated email domains allowed to sign up (empty: any), with the same rule. |
| `DOCWELL_MAX_UPLOAD_MB` | `50` | Largest attachment, 1 to 100. |
| `DOCWELL_DATA_DIR` | `./data` (`/data` in the image) | The search index. It is rebuilt from the database when missing, so a volume is optional but makes restarts faster. |
| `DOCWELL_SHUTDOWN_TIMEOUT` | `15s` | How long to wait for requests and open pages to finish saving on shutdown. |
| `DOCWELL_AUDIT_RETENTION_DAYS` | `365` | How long the audit log keeps entries. `0` keeps them forever. |
| `DOCWELL_WEBHOOKS_ALLOW_LOCAL` | `false` | Let webhooks call loopback and link-local addresses. For development only. |
## Web app (docwell-web)
| Variable | Default | What it does |
+1 -1
View File
@@ -1022,7 +1022,7 @@ export interface paths {
head?: never;
/**
* 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.
* @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-server starts.
*/
patch: operations["updateInstanceSettings"];
trace?: never;
+5 -4
View File
@@ -20,7 +20,7 @@ User and operator documentation lives in [Docs-Site](Docs-Site) (a VitePress sit
| Folder | What | Stack |
|---|---|---|
| `Database/` | **docwell-db**: storage, private service | PocketBase v0.40.6 + JS migrations |
| `Database/` | Schema for **docwell-db** (storage, private service), a stock PocketBase that docwell-server sets up | PocketBase v0.40.6, JS migrations |
| `Server/` | **docwell-server**: the only public API, plus the admin panel at `/admin/` | Go 1.26, Vue 3, Tailwind CSS 4 |
| `Web-App/` | **docwell-web**: serves the end-user web app | Go 1.26, Vue 3, Tailwind CSS 4, Tiptap |
| `Desktop-App/` | Desktop app; reuses the web app UI | Wails v3 |
@@ -94,8 +94,9 @@ npm install
Run each piece in its own terminal:
```bash
# 1. Database (from Database/)
./bin/pocketbase serve --dir ./pb_data --migrationsDir ./pb_migrations
# 1. Database (from Database/). docwell-server creates the collections on start.
./bin/pocketbase superuser upsert admin@docwell.test devpassword123 --dir ./pb_data # once
./bin/pocketbase serve --dir ./pb_data --http 127.0.0.1:8070
# 2. API server (from Server/). Build yrs.wasm once, and again after changing Server/ycrdt-wasm:
# rustup target add wasm32-wasip1 && go generate ./internal/ycrdt
@@ -137,7 +138,7 @@ The documentation site: `npm run dev:docs` (http://localhost:5173) and `npm run
### Releases
Push a tag like `v1.0.0` to the Gitea repository. The Release workflow builds `docwell-db`, `docwell-server`, `docwell-web` and the all-in-one `docwell` image for `linux/amd64` and `linux/arm64` and pushes them to that Gitea's container registry, `<gitea host>/<repository owner>/`. It also builds the Windows and Linux desktop installers and attaches them to a Gitea release for the tag. The macOS DMG is built by hand on a Mac (`wails3 task darwin:package:dmg` in `Desktop-App`) and attached afterwards. The runners, secret and variables it needs are listed at the top of [.github/workflows/release.yml](.github/workflows/release.yml).
Push a tag like `v1.0.0` to the Gitea repository. The Release workflow builds `docwell-server`, `docwell-web` and the all-in-one `docwell` image for `linux/amd64` and `linux/arm64` and pushes them to that Gitea's container registry, `<gitea host>/<repository owner>/`. It also builds the Windows and Linux desktop installers and attaches them to a Gitea release for the tag. The macOS DMG is built by hand on a Mac (`wails3 task darwin:package:dmg` in `Desktop-App`) and attached afterwards. The runners, secret and variables it needs are listed at the top of [.github/workflows/release.yml](.github/workflows/release.yml).
The compose files pull from `DOCWELL_REGISTRY` (default `ghcr.io/docwell`) at `DOCWELL_VERSION` (default `latest`). For images from a Gitea registry, set `DOCWELL_REGISTRY=<gitea host>/<repository owner>`.
+1 -1
View File
@@ -51,7 +51,7 @@ async function sendTest() {
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
<DwCallout v-if="saved" tone="success" size="ui" class="mt-4">Saved.</DwCallout>
<DwCallout size="ui" class="mt-4 max-w-xl">
If DOCWELL_SMTP_HOST is set for docwell-db, those environment values are applied again whenever it starts.
If DOCWELL_SMTP_HOST is set for docwell-server, those environment values are applied again whenever it starts.
</DwCallout>
<form v-if="settings" class="mt-6 grid max-w-xl gap-4 dw-card sm:grid-cols-2" @submit.prevent="submit">
+49 -2
View File
@@ -26,6 +26,7 @@ import (
"docwell/server/internal/instance"
"docwell/server/internal/jobs"
"docwell/server/internal/mail"
"docwell/server/internal/pbschema"
"docwell/server/internal/push"
"docwell/server/internal/search"
"docwell/server/internal/settings"
@@ -53,8 +54,29 @@ func run(log *slog.Logger) error {
}
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)
// 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)
@@ -181,3 +203,28 @@ func run(log *slog.Logger) error {
}
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
}
+75
View File
@@ -0,0 +1,75 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Command pbschema-export writes internal/pbschema/schema.json from a running
// PocketBase that has applied Database/pb_migrations. Database/export-schema.sh
// starts that PocketBase and runs this; there is no need to call it directly.
//
// pbschema-export -url http://127.0.0.1:18070 -email ... -password ... -out internal/pbschema/schema.json
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"strings"
"docwell/server/internal/store/pocketbase"
)
func main() {
url := flag.String("url", "http://127.0.0.1:18070", "PocketBase URL")
email := flag.String("email", "", "superuser email")
password := flag.String("password", "", "superuser password")
out := flag.String("out", "internal/pbschema/schema.json", "output file")
flag.Parse()
if err := run(*url, *email, *password, *out); err != nil {
fmt.Fprintln(os.Stderr, "pbschema-export:", err)
os.Exit(1)
}
}
func run(url, email, password, out string) error {
pb := pocketbase.New(url, email, password)
var res struct {
Items []map[string]any `json:"items"`
}
if err := pb.Do(context.Background(), http.MethodGet, "/api/collections?perPage=1000&skipTotal=1&sort=created", nil, &res); err != nil {
return err
}
var cols []map[string]any
for _, c := range res.Items {
name, _ := c["name"].(string)
// PocketBase's own system collections (_superusers, _otps, ...).
if strings.HasPrefix(name, "_") {
continue
}
delete(c, "created")
delete(c, "updated")
if name == "users" {
// Managed in the admin panel; the import keeps whatever is set.
delete(c, "oauth2")
if otp, ok := c["otp"].(map[string]any); ok {
delete(otp, "enabled")
}
}
cols = append(cols, c)
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false) // keep the email templates readable in diffs
enc.SetIndent("", " ")
if err := enc.Encode(cols); err != nil {
return err
}
if err := os.WriteFile(out, buf.Bytes(), 0o644); err != nil {
return err
}
fmt.Printf("wrote %d collections to %s\n", len(cols), out)
return nil
}
+20 -3
View File
@@ -385,11 +385,28 @@ func (s *Service) Verify(ctx context.Context, token string) (User, error) {
}
s.mu.Unlock()
var rec UserRecord
if err := s.pb.DoAs(ctx, http.MethodGet, "/api/docwell/auth/verify", token, nil, &rec); err != nil {
// auth-refresh is PocketBase's built-in token check: it rejects invalid and
// expired tokens and returns the owner (whose own email is always visible
// to them). It also issues a fresh token, which is not used here: the
// caller's token stays valid until it expires.
var res struct {
Record UserRecord `json:"record"`
}
if err := s.pb.DoAs(ctx, http.MethodPost, usersPath+"/auth-refresh", token, nil, &res); err != nil {
return User{}, tokenError(err)
}
u := rec.User()
u := res.Record.User()
// organizations is superuser-only, so the user's own token cannot expand
// it: read the name with the server's superuser session instead.
if u.Organization != "" {
org, err := pocketbase.Get[struct {
Name string `json:"name"`
}](ctx, s.pb, "organizations", u.Organization)
if err != nil && !pocketbase.IsNotFound(err) {
return User{}, err
}
u.OrganizationName = org.Name
}
if u.Status == "disabled" {
return User{}, ErrAccountDisabled
}
+7 -10
View File
@@ -79,6 +79,9 @@ func newFakePB(t *testing.T) (*fakePB, *pocketbase.Client) {
}
return nil
}
mux.HandleFunc("GET /api/collections/organizations/records/{id}", func(w http.ResponseWriter, r *http.Request) {
reply(w, 200, map[string]any{"id": r.PathValue("id"), "name": "Org " + r.PathValue("id")})
})
mux.HandleFunc("GET /api/collections/users/records/{id}", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
@@ -122,21 +125,15 @@ func newFakePB(t *testing.T) (*fakePB, *pocketbase.Client) {
}
reply(w, 200, map[string]any{"token": "tok:" + email, "record": rec})
})
mux.HandleFunc("GET /api/docwell/auth/verify", func(w http.ResponseWriter, r *http.Request) {
mux.HandleFunc("POST /api/collections/users/auth-refresh", func(w http.ResponseWriter, r *http.Request) {
f.verifyCalls.Add(1)
f.mu.Lock()
defer f.mu.Unlock()
for email, rec := range f.users {
if r.Header.Get("Authorization") == "tok:"+email {
// Like the real hook, the verify route expands the organization.
out := map[string]any{}
for k, v := range rec {
out[k] = v
}
if org, _ := rec["organization"].(string); org != "" {
out["expand"] = map[string]any{"organization": map[string]any{"name": "Org " + org}}
}
reply(w, 200, out)
// No expand: organizations is superuser-only, so PocketBase would
// not expand it for the user's own token.
reply(w, 200, map[string]any{"token": "tok:" + email, "record": rec})
return
}
}
+56
View File
@@ -42,6 +42,34 @@ type Config struct {
// WebhooksAllowLocal lets webhooks call loopback and link-local
// addresses (for development; off in production).
WebhooksAllowLocal bool
// PocketBase settings written on every start (settings.ApplyEnv). Empty
// values leave the admin panel in charge.
AppName string
MailFrom string
SMTP SMTP
S3 S3
}
// SMTP is the mail server from DOCWELL_SMTP_*; Host empty means not set.
type SMTP struct {
Host string
Port int
Username string
Password string
TLS bool
}
// S3 is file storage from DOCWELL_S3_*. Enabled is "true", "false" or ""
// (not set).
type S3 struct {
Enabled string
Bucket string
Endpoint string
Region string
AccessKey string
Secret string
ForcePathStyle bool
}
// Load reads the configuration from the environment and validates it.
@@ -72,6 +100,34 @@ func fromLookup(lookup func(string) (string, bool)) (Config, error) {
WebhooksAllowLocal: get("DOCWELL_WEBHOOKS_ALLOW_LOCAL", "false") == "true",
}
cfg.AppName = get("DOCWELL_APP_NAME", "")
cfg.MailFrom = get("DOCWELL_MAIL_FROM", "")
cfg.SMTP = SMTP{
Host: get("DOCWELL_SMTP_HOST", ""),
Username: get("DOCWELL_SMTP_USERNAME", ""),
Password: get("DOCWELL_SMTP_PASSWORD", ""),
TLS: get("DOCWELL_SMTP_TLS", "false") == "true",
}
if v := get("DOCWELL_SMTP_PORT", ""); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 1 || n > 65535 {
return Config{}, errors.New("DOCWELL_SMTP_PORT must be between 1 and 65535")
}
cfg.SMTP.Port = n
}
cfg.S3 = S3{
Enabled: get("DOCWELL_S3_ENABLED", ""),
Bucket: get("DOCWELL_S3_BUCKET", ""),
Endpoint: get("DOCWELL_S3_ENDPOINT", ""),
Region: get("DOCWELL_S3_REGION", ""),
AccessKey: get("DOCWELL_S3_ACCESS_KEY", ""),
Secret: get("DOCWELL_S3_SECRET", ""),
ForcePathStyle: get("DOCWELL_S3_FORCE_PATH_STYLE", "true") != "false",
}
if e := cfg.S3.Enabled; e != "" && e != "true" && e != "false" {
return Config{}, errors.New(`DOCWELL_S3_ENABLED must be "true", "false" or empty`)
}
cfg.AuditRetentionDays = 365
if v := get("DOCWELL_AUDIT_RETENTION_DAYS", ""); v != "" {
n, err := strconv.Atoi(v)
+3 -13
View File
@@ -1,8 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package mail sends Docwell's own emails (invites, test mails). Delivery goes
// through PocketBase (pb_hooks/docwell.pb.js), so every email uses the one SMTP
// configuration the admin panel edits.
// Package mail sends Docwell's own emails (invites, notifications, test
// mails). They go out over SMTP with the same mail server configuration
// PocketBase uses for its auth emails (see SMTPSender).
package mail
import (
@@ -11,11 +11,8 @@ import (
"embed"
"fmt"
"html/template"
"net/http"
"strings"
texttemplate "text/template"
"docwell/server/internal/store/pocketbase"
)
// Message is one email. HTML and Text are alternative bodies.
@@ -31,13 +28,6 @@ type Sender interface {
Send(ctx context.Context, m Message) error
}
// PBSender sends through PocketBase's mail hook.
type PBSender struct{ PB *pocketbase.Client }
func (s PBSender) Send(ctx context.Context, m Message) error {
return s.PB.Do(ctx, http.MethodPost, "/api/docwell/mail", m, nil)
}
//go:embed templates
var files embed.FS
+206
View File
@@ -0,0 +1,206 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package mail
import (
"bytes"
"context"
"crypto/rand"
"crypto/tls"
"encoding/hex"
"errors"
"fmt"
"mime"
"mime/multipart"
"mime/quotedprintable"
"net"
"net/mail"
"net/smtp"
"net/textproto"
"strconv"
"strings"
"time"
)
// Config is the mail server and sender. PocketBase holds the same values for
// its own auth emails; settings.Service.MailConfig reads them from there.
type Config struct {
Enabled bool
Host string
Port int
Username string
Password string
// TLS connects with implicit TLS (usually port 465). Without it the
// connection is upgraded with STARTTLS when the server offers it, as
// PocketBase does.
TLS bool
SenderName string
SenderAddress string
}
// ErrNotConfigured is returned when no mail server is set up.
var ErrNotConfigured = errors.New("mail: no mail server is configured")
// DeliveryError is the mail server refusing the message or the connection.
type DeliveryError struct{ Err error }
func (e *DeliveryError) Error() string { return "mail: " + e.Err.Error() }
func (e *DeliveryError) Unwrap() error { return e.Err }
// SMTPSender delivers messages to the mail server Config returns, read on
// every send so admin panel changes apply at once.
type SMTPSender struct {
Config func(ctx context.Context) (Config, error)
// Timeout bounds one delivery; zero means 30 seconds.
Timeout time.Duration
}
func (s *SMTPSender) Send(ctx context.Context, m Message) error {
cfg, err := s.Config(ctx)
if err != nil {
return err
}
if !cfg.Enabled || cfg.Host == "" {
return ErrNotConfigured
}
from, err := mail.ParseAddress(cfg.SenderAddress)
if err != nil {
return &DeliveryError{Err: fmt.Errorf("sender address %q: %w", cfg.SenderAddress, err)}
}
from.Name = cfg.SenderName
to, err := mail.ParseAddress(m.To)
if err != nil {
return &DeliveryError{Err: fmt.Errorf("recipient %q: %w", m.To, err)}
}
body, err := build(from, to, m)
if err != nil {
return err
}
timeout := s.Timeout
if timeout == 0 {
timeout = 30 * time.Second
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
if err := deliver(ctx, cfg, from.Address, to.Address, body); err != nil {
return &DeliveryError{Err: err}
}
return nil
}
func deliver(ctx context.Context, cfg Config, from, to string, body []byte) error {
port := cfg.Port
if port == 0 {
port = 587
}
addr := net.JoinHostPort(cfg.Host, strconv.Itoa(port))
tlsConfig := &tls.Config{ServerName: cfg.Host, MinVersion: tls.VersionTLS12}
var dialer net.Dialer
conn, err := dialer.DialContext(ctx, "tcp", addr)
if err != nil {
return err
}
if deadline, ok := ctx.Deadline(); ok {
_ = conn.SetDeadline(deadline)
}
if cfg.TLS {
tlsConn := tls.Client(conn, tlsConfig)
if err := tlsConn.HandshakeContext(ctx); err != nil {
conn.Close()
return err
}
conn = tlsConn
}
c, err := smtp.NewClient(conn, cfg.Host)
if err != nil {
conn.Close()
return err
}
defer c.Close()
if !cfg.TLS {
if ok, _ := c.Extension("STARTTLS"); ok {
if err := c.StartTLS(tlsConfig); err != nil {
return err
}
}
}
if cfg.Username != "" {
if ok, _ := c.Extension("AUTH"); !ok {
return errors.New("the server does not accept a login (no AUTH)")
}
if err := c.Auth(smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host)); err != nil {
return err
}
}
if err := c.Mail(from); err != nil {
return err
}
if err := c.Rcpt(to); err != nil {
return err
}
w, err := c.Data()
if err != nil {
return err
}
if _, err := w.Write(body); err != nil {
w.Close()
return err
}
if err := w.Close(); err != nil {
return err
}
return c.Quit()
}
// build renders m as a multipart/alternative message.
func build(from, to *mail.Address, m Message) ([]byte, error) {
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
domain := "docwell.localhost"
if at := strings.LastIndexByte(from.Address, '@'); at >= 0 {
domain = from.Address[at+1:]
}
id := make([]byte, 16)
_, _ = rand.Read(id)
header := []string{
"From: " + from.String(),
"To: " + to.String(),
"Subject: " + mime.QEncoding.Encode("utf-8", m.Subject),
"Date: " + time.Now().UTC().Format(time.RFC1123Z),
"Message-ID: <" + hex.EncodeToString(id) + "@" + domain + ">",
"MIME-Version: 1.0",
"Content-Type: multipart/alternative; boundary=" + mw.Boundary(),
}
var out bytes.Buffer
out.WriteString(strings.Join(header, "\r\n") + "\r\n\r\n")
for _, part := range []struct{ kind, body string }{{"text/plain", m.Text}, {"text/html", m.HTML}} {
if part.body == "" {
continue
}
pw, err := mw.CreatePart(textproto.MIMEHeader{
"Content-Type": {part.kind + "; charset=utf-8"},
"Content-Transfer-Encoding": {"quoted-printable"},
})
if err != nil {
return nil, err
}
qp := quotedprintable.NewWriter(pw)
if _, err := qp.Write([]byte(part.body)); err != nil {
return nil, err
}
if err := qp.Close(); err != nil {
return nil, err
}
}
if err := mw.Close(); err != nil {
return nil, err
}
out.Write(buf.Bytes())
return out.Bytes(), nil
}
+113
View File
@@ -0,0 +1,113 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package mail
import (
"bufio"
"context"
"errors"
"net"
"strconv"
"strings"
"testing"
)
// fakeSMTP accepts one message without TLS or auth and returns what it got.
func fakeSMTP(t *testing.T) (host string, port int, got chan string) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { ln.Close() })
got = make(chan string, 1)
go func() {
conn, err := ln.Accept()
if err != nil {
return
}
defer conn.Close()
r := bufio.NewReader(conn)
say := func(s string) { _, _ = conn.Write([]byte(s + "\r\n")) }
say("220 fake ESMTP")
var log strings.Builder
for {
line, err := r.ReadString('\n')
if err != nil {
return
}
cmd := strings.ToUpper(strings.TrimSpace(line))
log.WriteString(line)
switch {
case strings.HasPrefix(cmd, "EHLO"), strings.HasPrefix(cmd, "HELO"):
say("250 fake")
case strings.HasPrefix(cmd, "DATA"):
say("354 go ahead")
for {
l, err := r.ReadString('\n')
if err != nil {
return
}
if l == ".\r\n" {
break
}
log.WriteString(l)
}
say("250 queued")
case strings.HasPrefix(cmd, "QUIT"):
say("221 bye")
got <- log.String()
return
default:
say("250 ok")
}
}
}()
h, p, _ := net.SplitHostPort(ln.Addr().String())
n, _ := strconv.Atoi(p)
return h, n, got
}
func TestSMTPSender(t *testing.T) {
host, port, got := fakeSMTP(t)
s := &SMTPSender{Config: func(context.Context) (Config, error) {
return Config{Enabled: true, Host: host, Port: port, SenderName: "Docwell", SenderAddress: "no-reply@example.com"}, nil
}}
err := s.Send(context.Background(), Message{To: "ada@example.com", Subject: "Zaproszenie – Docwell", Text: "hello", HTML: "<p>hello</p>"})
if err != nil {
t.Fatal(err)
}
session := <-got
for _, want := range []string{
"MAIL FROM:<no-reply@example.com>",
"RCPT TO:<ada@example.com>",
`From: "Docwell" <no-reply@example.com>`,
"Subject: =?utf-8?q?",
"Content-Type: text/plain; charset=utf-8",
"Content-Type: text/html; charset=utf-8",
} {
if !strings.Contains(session, want) {
t.Errorf("session is missing %q:\n%s", want, session)
}
}
}
func TestSMTPSenderNotConfigured(t *testing.T) {
s := &SMTPSender{Config: func(context.Context) (Config, error) { return Config{Host: "smtp.example.com"}, nil }}
if err := s.Send(context.Background(), Message{To: "a@example.com"}); !errors.Is(err, ErrNotConfigured) {
t.Fatalf("err = %v, want ErrNotConfigured", err)
}
}
func TestSMTPSenderRefused(t *testing.T) {
ln, _ := net.Listen("tcp", "127.0.0.1:0")
addr := ln.Addr().(*net.TCPAddr)
ln.Close() // nothing listens there now
s := &SMTPSender{Config: func(context.Context) (Config, error) {
return Config{Enabled: true, Host: "127.0.0.1", Port: addr.Port, SenderAddress: "a@example.com"}, nil
}}
var de *DeliveryError
if err := s.Send(context.Background(), Message{To: "b@example.com", Text: "x"}); !errors.As(err, &de) {
t.Fatalf("err = %v, want a DeliveryError", err)
}
}
+121
View File
@@ -0,0 +1,121 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package pbschema brings PocketBase's collections to the schema docwell-server
// expects, so docwell-db can be a stock PocketBase image with no migrations or
// hooks of its own.
//
// schema.json is the target state: every Docwell collection, plus the changes
// Docwell makes to the built-in "users" auth collection. It is generated from
// Database/pb_migrations by Database/export-schema.sh; edit the migrations,
// not the JSON.
//
// Apply imports it through PocketBase's collections import, which runs in one
// transaction. Collections and fields that already exist keep their ids
// (matched by name), so their data stays; missing ones are created. Settings
// the admin panel changes on "users" (OAuth2 providers, magic link) are left
// out of the snapshot, and the import keeps their current values.
package pbschema
import (
"context"
_ "embed"
"encoding/json"
"fmt"
"net/http"
"docwell/server/internal/store/pocketbase"
)
//go:embed schema.json
var snapshot []byte
// Collections returns the target collections, decoded fresh on every call.
func Collections() ([]map[string]any, error) {
var cols []map[string]any
if err := json.Unmarshal(snapshot, &cols); err != nil {
return nil, fmt.Errorf("pbschema: schema.json: %w", err)
}
return cols, nil
}
type existingCollection struct {
ID string `json:"id"`
Name string `json:"name"`
Fields []struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"fields"`
}
// Apply imports the snapshot into PocketBase. Running it again is harmless.
func Apply(ctx context.Context, pb *pocketbase.Client) error {
want, err := Collections()
if err != nil {
return err
}
var have struct {
Items []existingCollection `json:"items"`
}
if err := pb.Do(ctx, http.MethodGet, "/api/collections?perPage=1000&skipTotal=1&fields=id,name,fields", nil, &have); err != nil {
return fmt.Errorf("pbschema: list collections: %w", err)
}
if err := remap(want, have.Items); err != nil {
return err
}
body := map[string]any{"collections": want, "deleteMissing": false}
if err := pb.Do(ctx, http.MethodPut, "/api/collections/import", body, nil); err != nil {
return fmt.Errorf("pbschema: import collections: %w", err)
}
return nil
}
// remap rewrites the snapshot's collection and field ids to the ids of the
// collections and fields PocketBase already has with the same names, and
// points relation fields at the remapped collection ids.
func remap(want []map[string]any, have []existingCollection) error {
byName := make(map[string]existingCollection, len(have))
for _, c := range have {
byName[c.Name] = c
}
ids := map[string]string{} // snapshot collection id -> live id
for _, c := range want {
id, _ := c["id"].(string)
name, _ := c["name"].(string)
if id == "" || name == "" {
return fmt.Errorf("pbschema: schema.json: collection without id or name")
}
if live, ok := byName[name]; ok {
ids[id] = live.ID
} else {
ids[id] = id
}
}
for _, c := range want {
name := c["name"].(string)
c["id"] = ids[c["id"].(string)]
liveFields := map[string]string{}
for _, f := range byName[name].Fields {
liveFields[f.Name] = f.ID
}
fields, _ := c["fields"].([]any)
for _, raw := range fields {
f, ok := raw.(map[string]any)
if !ok {
return fmt.Errorf("pbschema: schema.json: %s: malformed field", name)
}
if fieldName, _ := f["name"].(string); liveFields[fieldName] != "" {
f["id"] = liveFields[fieldName]
}
if target, ok := f["collectionId"].(string); ok && target != "" {
live, known := ids[target]
if !known {
return fmt.Errorf("pbschema: schema.json: %s.%v points at unknown collection %s", name, f["name"], target)
}
f["collectionId"] = live
}
}
}
return nil
}
+87
View File
@@ -0,0 +1,87 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package pbschema
import (
"encoding/json"
"testing"
)
func TestSnapshot(t *testing.T) {
cols, err := Collections()
if err != nil {
t.Fatal(err)
}
names := map[string]bool{}
for _, c := range cols {
name := c["name"].(string)
if name[0] == '_' {
t.Errorf("system collection %s in the snapshot", name)
}
names[name] = true
if name == "users" {
if _, ok := c["oauth2"]; ok {
t.Error("users.oauth2 is admin-managed and must not be in the snapshot")
}
if _, ok := c["otp"].(map[string]any)["enabled"]; ok {
t.Error("users.otp.enabled is admin-managed and must not be in the snapshot")
}
}
}
for _, want := range []string{"users", "organizations", "pages", "instance_settings"} {
if !names[want] {
t.Errorf("snapshot has no %s collection", want)
}
}
// Every relation must point at a collection in the snapshot.
if err := remap(cols, nil); err != nil {
t.Fatal(err)
}
}
func TestRemap(t *testing.T) {
var want []map[string]any
_ = json.Unmarshal([]byte(`[
{"id": "snap_orgs", "name": "organizations", "fields": [
{"id": "f_name", "name": "name", "type": "text"},
{"id": "f_new", "name": "slug", "type": "text"}]},
{"id": "snap_pages", "name": "pages", "fields": [
{"id": "f_org", "name": "organization", "type": "relation", "collectionId": "snap_orgs"}]}
]`), &want)
have := []existingCollection{{ID: "live_orgs", Name: "organizations"}}
have[0].Fields = append(have[0].Fields, struct {
ID string `json:"id"`
Name string `json:"name"`
}{ID: "live_name", Name: "name"})
if err := remap(want, have); err != nil {
t.Fatal(err)
}
orgs, pages := want[0], want[1]
if orgs["id"] != "live_orgs" {
t.Errorf("existing collection id = %v, want live_orgs", orgs["id"])
}
fields := orgs["fields"].([]any)
if id := fields[0].(map[string]any)["id"]; id != "live_name" {
t.Errorf("existing field id = %v, want live_name", id)
}
if id := fields[1].(map[string]any)["id"]; id != "f_new" {
t.Errorf("new field id = %v, want f_new", id)
}
if pages["id"] != "snap_pages" {
t.Errorf("new collection id = %v, want snap_pages", pages["id"])
}
rel := pages["fields"].([]any)[0].(map[string]any)
if rel["collectionId"] != "live_orgs" {
t.Errorf("relation target = %v, want live_orgs", rel["collectionId"])
}
}
func TestRemapUnknownRelation(t *testing.T) {
var want []map[string]any
_ = json.Unmarshal([]byte(`[{"id": "a", "name": "a", "fields": [
{"id": "r", "name": "r", "type": "relation", "collectionId": "missing"}]}]`), &want)
if err := remap(want, nil); err == nil {
t.Fatal("expected an error for a relation to an unknown collection")
}
}
File diff suppressed because it is too large. Load diff
+115
View File
@@ -0,0 +1,115 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package settings
import (
"context"
"fmt"
"net/http"
)
// Env holds the PocketBase settings that come from environment variables.
// ApplyEnv writes them on every start, so changing an env var and restarting
// is enough. Settings without an env var are left alone: the admin panel
// manages them.
type Env struct {
AppName string // DOCWELL_APP_NAME
WebURL string // DOCWELL_WEB_URL: {APP_URL} in PocketBase's auth emails
MailFrom string // DOCWELL_MAIL_FROM
// SMTP is applied only when SMTPHost is set.
SMTPHost string
SMTPPort int
SMTPUsername string
SMTPPassword string
SMTPTLS bool
// S3 is "true" (uploads go to the bucket), "false" (back to local disk)
// or "" (the admin panel's Storage screen is in charge).
S3 string
S3Bucket string
S3Endpoint string
S3Region string
S3AccessKey string
S3Secret string
S3ForcePathStyle bool
}
// PocketBase's placeholders on a fresh database.
const (
pbPlaceholderName = "Acme"
pbPlaceholderSender = "support@example.com"
)
// ApplyEnv writes the environment's settings to PocketBase.
func (s *Service) ApplyEnv(ctx context.Context, env Env) error {
var cur struct {
Meta struct {
AppName string `json:"appName"`
SenderAddress string `json:"senderAddress"`
} `json:"meta"`
}
if err := s.pb.Do(ctx, http.MethodGet, "/api/settings", nil, &cur); err != nil {
return fmt.Errorf("settings: read: %w", err)
}
appName := cur.Meta.AppName
if env.AppName != "" {
appName = env.AppName
} else if appName == pbPlaceholderName || appName == "" {
appName = "Docwell"
}
sender := cur.Meta.SenderAddress
if env.MailFrom != "" {
sender = env.MailFrom
} else if sender == pbPlaceholderSender || sender == "" {
sender = "no-reply@docwell.localhost"
}
webURL := env.WebURL
if webURL == "" {
webURL = "http://localhost:3000"
}
patch := map[string]any{
"meta": map[string]any{
"appName": appName, "appURL": webURL, "senderName": appName, "senderAddress": sender,
},
}
if env.SMTPHost != "" {
port := env.SMTPPort
if port == 0 {
port = 587
}
patch["smtp"] = map[string]any{
"enabled": true, "host": env.SMTPHost, "port": port,
"username": env.SMTPUsername, "password": env.SMTPPassword, "tls": env.SMTPTLS,
}
}
switch env.S3 {
case "true":
bucket, region := env.S3Bucket, env.S3Region
if bucket == "" {
bucket = "docwell"
}
if region == "" {
region = "us-east-1"
}
patch["s3"] = map[string]any{
"enabled": true, "bucket": bucket, "endpoint": env.S3Endpoint, "region": region,
"accessKey": env.S3AccessKey, "secret": env.S3Secret, "forcePathStyle": env.S3ForcePathStyle,
}
case "false":
patch["s3"] = map[string]any{"enabled": false}
}
if err := s.pb.Do(ctx, http.MethodPatch, "/api/settings", patch, nil); err != nil {
return fmt.Errorf("settings: apply environment: %w", settingsError(err))
}
if env.SMTPHost != "" {
if err := s.save(ctx, keySMTPPassword, env.SMTPPassword); err != nil {
return fmt.Errorf("settings: store smtp password: %w", err)
}
}
return nil
}
+42 -6
View File
@@ -131,7 +131,11 @@ type Public struct {
const (
keySignup = "signup"
keyBranding = "branding"
cacheTTL = 30 * time.Second
// keySMTPPassword is docwell-server's copy of the mail server password.
// PocketBase never returns it, and the server needs it to send its own
// emails. instance_settings is superuser-only, like PocketBase's settings.
keySMTPPassword = "smtp_password"
cacheTTL = 30 * time.Second
)
type Service struct {
@@ -394,14 +398,20 @@ func (s *Service) get(ctx context.Context) (Instance, error) {
if err != nil {
return Instance{}, err
}
var smtpPassword string
if _, err := s.load(ctx, keySMTPPassword, &smtpPassword); err != nil {
return Instance{}, err
}
return Instance{
Signup: su,
Auth: a,
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,
// PocketBase hides the password, so this reports the server's own copy:
// a password saved before the server kept one shows as unset and has
// to be entered again before Docwell's own emails can be sent.
PasswordSet: smtpPassword != "", TLS: pb.SMTP.TLS,
SenderName: pb.Meta.SenderName, SenderAddress: pb.Meta.SenderAddress,
},
Storage: Storage{
@@ -550,6 +560,11 @@ func (s *Service) Apply(ctx context.Context, c access.Caller, in Update) (Instan
return Instance{}, settingsError(err)
}
}
if in.SMTP != nil && in.SMTP.Password != nil {
if err := s.save(ctx, keySMTPPassword, *in.SMTP.Password); err != nil {
return Instance{}, err
}
}
if in.Auth != nil {
body := map[string]any{"otp": map[string]any{"enabled": in.Auth.MagicLink}}
if oauth != nil {
@@ -607,15 +622,36 @@ func (s *Service) TestEmail(ctx context.Context, c access.Caller, to string) err
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)
if errors.Is(err, mail.ErrNotConfigured) {
return apperr.Invalid("No mail server is configured.")
}
var delivery *mail.DeliveryError
if errors.As(err, &delivery) {
return apperr.Invalid("the mail server rejected the message: " + delivery.Err.Error())
}
return err
}
return nil
}
// MailConfig is the mail server docwell-server sends its own emails through:
// PocketBase's SMTP settings, with the password from the server's own copy.
func (s *Service) MailConfig(ctx context.Context) (mail.Config, error) {
pb, err := s.pbSettings(ctx)
if err != nil {
return mail.Config{}, err
}
var password string
if _, err := s.load(ctx, keySMTPPassword, &password); err != nil {
return mail.Config{}, err
}
return mail.Config{
Enabled: pb.SMTP.Enabled, Host: pb.SMTP.Host, Port: pb.SMTP.Port,
Username: pb.SMTP.Username, Password: password, TLS: pb.SMTP.TLS,
SenderName: pb.Meta.SenderName, SenderAddress: pb.Meta.SenderAddress,
}, 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 {
+1 -1
View File
@@ -1243,7 +1243,7 @@ paths:
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.
DOCWELL_SMTP_HOST are applied again when docwell-server starts.
security: [{ bearer: [] }]
requestBody:
required: true