Dough Git

commit

dockerhub

commit
4e820f4996f5039fcef054ff8f23dfa4dc557dcb
author
Clove Twilight <[email protected]>
date
2026-09-05 15:39

diff --git a/.env.example b/.env.example
index 4ad3add..5a03791 100644
--- a/.env.example
+++ b/.env.example
@@ -69,3 +69,14 @@ BETA_ALLOWED_DISCORD_IDS=
 # 32+ random bytes, base64. Rotate by generating a new one; sessions are
 # server-side, so rotation invalidates them rather than corrupting them.
 SESSION_SECRET=
+
+# --- published images ----------------------------------------------------
+# Only needed when running with docker-compose.prod.yml, which pulls prebuilt
+# images instead of compiling on the server. IMAGE_BASE is the Docker Hub
+# account and name WITHOUT the `-api` / `-web` suffix the overlay appends; no
+# registry host is needed, since Docker Hub is the default.
+IMAGE_BASE=
+# `latest` moves on every push to main. Pin an immutable tag in production --
+# `sha-abc1234`, a released `1.2.3`, or `1.2.3@sha256:...` -- so a restart
+# cannot quietly change what is running.
+IMAGE_TAG=latest
diff --git a/.github/workflows/images.yml b/.github/workflows/images.yml
new file mode 100644
index 0000000..d68ae47
--- /dev/null
+++ b/.github/workflows/images.yml
@@ -0,0 +1,89 @@
+name: Publish images
+
+# Builds both images and pushes them to Docker Hub, so a server pulls rather
+# than compiles. Building on the box costs about seventy seconds of CPU it does
+# not have spare, and means the running code was compiled somewhere unversioned.
+#
+# Images are built for amd64 and arm64: most VPS hosts are amd64, Apple Silicon
+# is arm64, and one manifest serves both.
+#
+# Requires two repository secrets:
+#   DOCKERHUB_USERNAME  the account the images live under
+#   DOCKERHUB_TOKEN     an access token from Docker Hub → Account settings →
+#                       Personal access tokens, with Read & Write scope.
+#                       An access token, never the account password.
+
+on:
+  push:
+    branches: [main]
+    tags: ["v*"]
+  workflow_dispatch:
+
+env:
+  # Docker Hub image names are `account/name`, so the repository name cannot be
+  # used directly — it already contains a slash.
+  IMAGE_NAME: pkviewer
+
+jobs:
+  build:
+    runs-on: ubuntu-latest
+    permissions:
+      contents: read
+
+    strategy:
+      fail-fast: false
+      matrix:
+        include:
+          - name: api
+            dockerfile: docker/api.Dockerfile
+          - name: web
+            dockerfile: docker/web.Dockerfile
+
+    steps:
+      - uses: actions/checkout@v4
+
+      - uses: docker/setup-qemu-action@v3
+      - uses: docker/setup-buildx-action@v3
+
+      - name: Sign in to Docker Hub
+        uses: docker/login-action@v3
+        with:
+          username: ${{ secrets.DOCKERHUB_USERNAME }}
+          password: ${{ secrets.DOCKERHUB_TOKEN }}
+
+      - name: Work out tags
+        id: meta
+        uses: docker/metadata-action@v5
+        with:
+          images: ${{ secrets.DOCKERHUB_USERNAME }}/${{ env.IMAGE_NAME }}-${{ matrix.name }}
+          tags: |
+            # A moving pointer for convenience, and immutable tags to pin to.
+            type=raw,value=latest,enable={{is_default_branch}}
+            type=semver,pattern={{version}}
+            type=semver,pattern={{major}}.{{minor}}
+            type=sha,format=short
+
+      - name: Build and push
+        uses: docker/build-push-action@v6
+        with:
+          # The repository root: both images depend on the shared workspace.
+          context: .
+          file: ${{ matrix.dockerfile }}
+          platforms: linux/amd64,linux/arm64
+          push: true
+          tags: ${{ steps.meta.outputs.tags }}
+          labels: ${{ steps.meta.outputs.labels }}
+          # Layer cache, so a source-only change does not reinstall dependencies
+          # on every run.
+          cache-from: type=gha
+          cache-to: type=gha,mode=max
+          # Docker Hub renders a plain manifest list more predictably than one
+          # carrying provenance attestations.
+          provenance: false
+
+      - name: Report what was published
+        run: |
+          echo "### Published" >> "$GITHUB_STEP_SUMMARY"
+          echo '```' >> "$GITHUB_STEP_SUMMARY"
+          echo "${{ steps.meta.outputs.tags }}" >> "$GITHUB_STEP_SUMMARY"
+          echo '```' >> "$GITHUB_STEP_SUMMARY"
diff --git a/apps/api/src/config/index.ts b/apps/api/src/config/index.ts
index 7f0c82a..074ee99 100644
--- a/apps/api/src/config/index.ts
+++ b/apps/api/src/config/index.ts
@@ -189,22 +189,38 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
       ["PUBLIC_ASSET_ORIGIN", e.PUBLIC_ASSET_ORIGIN ?? e.PUBLIC_ORIGIN],
     ] as const) {
       if (!value.startsWith("https://")) {
-        throw new ConfigError(`${key} must be https in production (got ${value})`);
+        // Session cookies are Secure and __Host- prefixed, so sign-in cannot
+        // work over http. TLS terminates at the proxy in front; this is the
+        // public URL people visit, not the address the container listens on.
+        throw new ConfigError(
+          `${key} must be https in production (got ${value}). ` +
+            "It is the public URL visitors use — TLS terminates at your reverse " +
+            "proxy, and the container itself still speaks http behind it.",
+        );
       }
     }
-    if (e.DISCORD_REDIRECT_URIS.length === 0) {
-      throw new ConfigError("DISCORD_REDIRECT_URIS must list at least one URI in production");
-    }
+
     if (e.SESSION_SECRET.length < 32) {
       throw new ConfigError(
         "SESSION_SECRET must be at least 32 characters in production. " +
           "Generate one with: openssl rand -base64 32",
       );
     }
-    if (!e.DISCORD_CLIENT_ID || !e.DISCORD_CLIENT_SECRET) {
-      throw new ConfigError(
-        "DISCORD_CLIENT_ID and DISCORD_CLIENT_SECRET are required in production; " +
-          "without them nobody can sign in.",
+    /**
+     * Incomplete Discord configuration warns; it does not stop the server.
+     *
+     * Every public page works without it — only sign-in is unavailable, and
+     * that endpoint already answers 503. Refusing to boot made a read-only
+     * deployment impossible and blocked bringing a stack up before the OAuth
+     * application exists, which is the normal order of doing things.
+     */
+    const discordReady =
+      e.DISCORD_CLIENT_ID && e.DISCORD_CLIENT_SECRET && e.DISCORD_REDIRECT_URIS.length > 0;
+    if (!discordReady) {
+      console.warn(
+        "[config] Discord sign-in is not configured, so nobody can sign in. " +
+          "Public pages work normally. Set DISCORD_CLIENT_ID, DISCORD_CLIENT_SECRET " +
+          "and DISCORD_REDIRECT_URIS to enable it.",
       );
     }
   }
diff --git a/apps/api/test/config.test.ts b/apps/api/test/config.test.ts
index eb24dd6..7de1780 100644
--- a/apps/api/test/config.test.ts
+++ b/apps/api/test/config.test.ts
@@ -151,9 +151,21 @@ describe("beta readiness", () => {
     expect(() => loadConfig(withoutSecret)).toThrow(/SESSION_SECRET/);
   });
 
-  test("production refuses to start without Discord credentials", () => {
-    const { DISCORD_CLIENT_SECRET: _omitted, ...withoutDiscord } = prodBase;
-    expect(() => loadConfig(withoutDiscord)).toThrow(/DISCORD_CLIENT/);
+  // Every public page works without Discord; only sign-in is unavailable, and
+  // that endpoint answers 503. Refusing to boot made a read-only deployment
+  // impossible and blocked bringing a stack up before the OAuth app exists.
+  test("production starts without Discord credentials, for a read-only deployment", () => {
+    const { DISCORD_CLIENT_SECRET: _s, DISCORD_CLIENT_ID: _i, DISCORD_REDIRECT_URIS: _r, ...readOnly } =
+      prodBase;
+    const cfg = loadConfig(readOnly);
+    expect(cfg.discord.clientId).toBe("");
+    expect(cfg.discord.redirectUris).toEqual([]);
+  });
+
+  test("an http origin in production explains where TLS belongs", () => {
+    expect(() => loadConfig({ ...prodBase, PUBLIC_ORIGIN: "http://system.example" })).toThrow(
+      /reverse\s+proxy/,
+    );
   });
 
   test("the error names the missing variable so it can be fixed", () => {
diff --git a/apps/web/test/docker.test.ts b/apps/web/test/docker.test.ts
index d5605c5..018dabe 100644
--- a/apps/web/test/docker.test.ts
+++ b/apps/web/test/docker.test.ts
@@ -61,3 +61,41 @@ describe("container toolchain", () => {
     expect(compose).toContain('"127.0.0.1:3000:3000"');
   });
 });
+
+/**
+ * The publish workflow and the production overlay have to agree on image names,
+ * and nothing else connects them: CI pushes `USER/pkviewer-api`, the server
+ * pulls whatever the overlay spells. Rename one and the other keeps working
+ * right up until a deploy pulls a tag that was never published.
+ */
+describe("published images", () => {
+  const workflow = readFileSync(join(root, ".github/workflows/images.yml"), "utf8");
+  const overlay = readFileSync(join(root, "docker-compose.prod.yml"), "utf8");
+
+  // Just the build matrix: `- name:` also introduces every workflow step.
+  const matrix = workflow.slice(workflow.indexOf("include:")).split(/^ {4}\w/m)[0]!;
+  const built = [...matrix.matchAll(/- name: ([\w-]+)$/gm)].map((m) => m[1]!);
+  const pulled = [...overlay.matchAll(/image: \$\{IMAGE_BASE[^}]*\}-([\w-]+):/g)].map((m) => m[1]!);
+
+  test("CI builds an image for every service the overlay pulls", () => {
+    // Both sides come from regexes, so an empty match on both would otherwise
+    // agree vacuously.
+    expect(built.length).toBeGreaterThan(0);
+    expect(new Set(built)).toEqual(new Set(pulled));
+  });
+
+  test("the overlay pulls an image for every service compose defines", () => {
+    const compose = readFileSync(join(root, "docker-compose.yml"), "utf8");
+    // Only the services block: top-level `volumes:` also holds two-space keys.
+    const block = compose.slice(compose.indexOf("services:") + 9).split(/^\S/m)[0]!;
+    const services = [...block.matchAll(/^ {2}([\w-]+):$/gm)].map((m) => m[1]!);
+    expect(new Set(pulled)).toEqual(new Set(services));
+  });
+
+  // A password would work and would be wrong: a token is scoped and can be
+  // revoked on its own.
+  test("the registry credential is a secret, never a literal", () => {
+    expect(workflow).toContain("${{ secrets.DOCKERHUB_TOKEN }}");
+    expect(workflow).not.toMatch(/password:\s*(?!\$\{\{)\S/);
+  });
+});
diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml
new file mode 100644
index 0000000..5498072
--- /dev/null
+++ b/docker-compose.prod.yml
@@ -0,0 +1,33 @@
+# Running from published images instead of building on the server.
+#
+#   docker compose -f docker-compose.yml -f docker-compose.prod.yml pull
+#   docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
+#
+# This overlay replaces the `build:` in docker-compose.yml with an `image:`, so
+# the server pulls what CI already built and tested rather than compiling. Every
+# other setting — the unpublished API port, the loopback web binding, the data
+# volume — comes from the base file unchanged.
+#
+# Set IMAGE_BASE and IMAGE_TAG in .env, for example:
+#   IMAGE_BASE=yourdockerhubuser/pkviewer
+#   IMAGE_TAG=latest
+#
+# IMAGE_BASE is the Docker Hub account and name without the `-api` / `-web`
+# suffix, which this file appends. No registry host is needed: Docker Hub is the
+# default, so `user/pkviewer` and `docker.io/user/pkviewer` mean the same thing.
+#
+# Pin IMAGE_TAG to a released version rather than `latest` once there is one, so
+# a restart cannot quietly change what is running. The publish workflow tags
+# every build with a short commit sha as well as semver, so there is always
+# something immutable to pin to.
+
+services:
+  api:
+    image: ${IMAGE_BASE:?set IMAGE_BASE in .env}-api:${IMAGE_TAG:-latest}
+    build: !reset null
+    pull_policy: always
+
+  web:
+    image: ${IMAGE_BASE:?set IMAGE_BASE in .env}-web:${IMAGE_TAG:-latest}
+    build: !reset null
+    pull_policy: always
diff --git a/docker-compose.yml b/docker-compose.yml
index c773738..0aa75cf 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -43,7 +43,13 @@ services:
       # lives in this file: accounts, claims, addresses, themes, links.
       - pkviewer-data:/data
     healthcheck:
-      test: ["CMD", "wget", "-qO-", "http://127.0.0.1:3001/health"]
+      # Uses Bun rather than wget or curl: this is a Bun image, so the runtime
+      # is certain to be there while a fetch tool is not.
+      test:
+        - CMD
+        - bun
+        - -e
+        - fetch("http://127.0.0.1:3001/health").then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))
       interval: 30s
       timeout: 5s
       retries: 3
diff --git a/docs/decisions.md b/docs/decisions.md
index 3dbde95..9ec6953 100644
--- a/docs/decisions.md
+++ b/docs/decisions.md
@@ -511,6 +511,45 @@ is correct and discloses nothing — a system that does not exist and one that
 belongs to someone else are indistinguishable — and every management page is
 `noindex`. Worth revisiting if it ever matters for monitoring.
 
+## Deployment
+
+**D1. Two containers, mirroring the two processes.** The API is the only SQLite
+writer, so it is the only container with the data volume. It is `expose`d to the
+compose network and never `ports:`-published: the browser reaches it only
+through the web tier's proxy, so publishing 3001 would put the management API on
+the host network. The web tier binds `127.0.0.1:3000` and a TLS-terminating
+reverse proxy sits in front. Guarded by `apps/web/test/docker.test.ts`.
+
+**D2. Images are built in CI, not on the server.** `.github/workflows/images.yml`
+publishes `USER/pkviewer-api` and `USER/pkviewer-web` to **Docker Hub** for
+amd64 and arm64; `docker-compose.prod.yml` swaps `build:` for `image:` and
+changes nothing else. Docker Hub over GHCR was the owner's preference — both
+registries pin identically, so this was not a technical constraint. CI
+authenticates with a scoped access token in `DOCKERHUB_TOKEN`, never a password.
+
+**D3. Every build gets an immutable tag.** `latest` moves; `sha-<short>` and
+semver tags do not. Production pins one of the immutable ones so a restart, or
+`pull_policy: always`, cannot silently change what is running. A test asserts
+the workflow's build matrix and the overlay's image names cannot drift apart,
+because nothing else connects them and the failure only surfaces at deploy time.
+
+**D4. Origins are configuration, never baked into an image.** The web image
+builds with `http://build.invalid` placeholders precisely so that a value
+leaking into the bundle would be obvious. Every page embedding an origin is
+force-dynamic and reads config at request time, which is what keeps the eventual
+domain move a config change rather than a rebuild.
+
+**D5. The container Bun must match the lockfile's Bun.** A stale pin (1.2 against
+a 1.4 lockfile) built locally and failed on the server, since `--frozen-lockfile`
+cannot satisfy a newer lockfile. `--frozen-lockfile` stays — it was correctly
+reporting a real mismatch — and a test asserts the pinned tag tracks the Bun the
+suite runs under.
+
+**D6. Missing Discord credentials warn, they do not abort.** Production once
+hard-failed without them, which contradicted the documented read-only
+deployment and showed up only as an unhealthy container. Public pages work
+without sign-in; the warning names the three variables that enable it.
+
 ## Guardrails
 
 No user JavaScript, ever. No arbitrary HTML. No custom CSS in MVP. No
diff --git a/docs/deployment.md b/docs/deployment.md
index 47f58af..da4a585 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -67,7 +67,13 @@ is `force-dynamic` specifically to keep that true.
 | `DISCORD_REDIRECT_URIS` | **production** | Comma-separated. **Register the beta and production URIs together** so the domain move is a cutover, not a flag day. Each must be `<public origin>/auth/discord/callback` and registered identically in Discord. |
 
 Without Discord credentials the app still runs and every public page works —
-nobody can sign in. That is a legitimate read-only deployment.
+nobody can sign in, and `/auth/discord/start` answers 503. That is a legitimate
+read-only deployment, and startup says so rather than refusing to boot.
+
+`PUBLIC_ORIGIN` must still be https in production even before a certificate
+exists: it is the public URL visitors will use, TLS terminates at the proxy in
+front, and the container itself speaks http behind it. Session cookies are
+`Secure`, so sign-in cannot work over http.
 
 ### Database
 
@@ -186,6 +192,71 @@ docker compose exec api sh -c \
 or more simply, stop the stack and copy the volume. Never `cp` a live WAL
 database.
 
+## Running from published images
+
+Building on the server costs CPU it usually has none of, and means the running
+code was compiled somewhere unversioned. `.github/workflows/images.yml` builds
+both images for amd64 and arm64 on every push to `main` and publishes them to
+Docker Hub, so the server pulls instead.
+
+The workflow needs two repository secrets, under Settings → Secrets and
+variables → Actions:
+
+| Secret | Value |
+| --- | --- |
+| `DOCKERHUB_USERNAME` | the Docker Hub account the images live under |
+| `DOCKERHUB_TOKEN` | a personal access token with Read & Write scope, from Docker Hub → Account settings → Personal access tokens |
+
+Use an access token, never the account password: a token is scoped, listed, and
+revocable on its own without changing the password everywhere else it is used.
+
+The two repositories — `USER/pkviewer-api` and `USER/pkviewer-web` — are created
+by the first successful push. They are public by default; make them private in
+Docker Hub if that is wanted, and then `docker login` on the server before
+pulling.
+
+Add to `.env`:
+
+```
+IMAGE_BASE=USER/pkviewer
+IMAGE_TAG=latest
+```
+
+`IMAGE_BASE` omits the `-api` and `-web` suffix, which the overlay appends, and
+needs no registry host — Docker Hub is the default, so `USER/pkviewer` and
+`docker.io/USER/pkviewer` mean the same thing.
+
+Then:
+
+```bash
+docker compose -f docker-compose.yml -f docker-compose.prod.yml pull
+docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
+```
+
+The overlay swaps `build:` for `image:` and changes nothing else — the
+unpublished API port, the loopback web binding and the data volume all still
+come from the base file.
+
+### Pinning
+
+Every build is published under several tags:
+
+| Tag | Moves | Use |
+| --- | --- | --- |
+| `latest` | yes, on every push to `main` | convenience only |
+| `sha-abc1234` | never | pin to an exact commit |
+| `1.2.3` | never | pin to a release, from a `v1.2.3` git tag |
+| `1.2` | yes, within a minor series | patch updates without a version bump |
+
+Pin `IMAGE_TAG` to one of the immutable tags in production. `latest` means a
+`docker compose pull` — or an automatic restart with `pull_policy: always` —
+can silently change what is running, and there is then no record of what was
+running when something broke.
+
+For an exact, unfakeable pin, use a digest instead of a tag: `docker buildx
+imagetools inspect USER/pkviewer-api:1.2.3` prints one, and
+`IMAGE_TAG=1.2.3@sha256:…` works in the overlay.
+
 ## Deploying a change
 
 ```bash