Your favorite shift management application!
feat(ci): per-PR preview deployments via Komodo (#219)
panteLfd20a61e9f82
diff --git a/.env.example b/.env.exampleindex 45c34d4..01a1137 100644--- a/.env.example+++ b/.env.example@@ -20,6 +20,7 @@# 9. GitHub integration -- version and release check# 10. Rate limiting -- all optional, defaults are sensible# 11. Local development -- dev-server settings, ignored in production+# 12. Telemetry -- opt-in, anonymous usage statistics# ==============================================================================diff --git a/.github/workflows/pr-preview.yml b/.github/workflows/pr-preview.ymlnew file mode 100644index 0000000..c3f349f--- /dev/null+++ b/.github/workflows/pr-preview.yml@@ -0,0 +1,253 @@+name: PR Preview++on:+ pull_request:+ types: [labeled, unlabeled, synchronize, reopened, closed]+ workflow_dispatch:+ inputs:+ pr_number:+ description: "Number of the PR whose preview should be torn down"+ required: true+ type: string++permissions:+ contents: read+ checks: read+ packages: read+ pull-requests: write++env:+ PREVIEW_LABEL: preview+ STACK_COMMENT_MARKER: "<!-- pr-preview -->"++jobs:+ fork-notice:+ name: Fork notice+ if: >-+ github.event.action == 'labeled' &&+ github.event.label.name == 'preview' &&+ github.event.pull_request.head.repo.full_name != github.repository+ runs-on: ubuntu-latest+ steps:+ # A fork PR only gets a read-only token, so `gh pr comment` would 403.+ - name: Print the notice+ run: |+ echo "::notice::Pull requests from a fork get no preview: the workflow has neither the secrets nor an image pushed to ghcr.io there."++ deploy:+ name: Deploy the preview+ if: >-+ github.event.pull_request.head.repo.full_name == github.repository &&+ contains(github.event.pull_request.labels.*.name, 'preview') &&+ (github.event.action == 'synchronize' ||+ github.event.action == 'reopened' ||+ (github.event.action == 'labeled' && github.event.label.name == 'preview'))+ runs-on: ubuntu-latest+ timeout-minutes: 40+ # Job level, not workflow level: a skipped job must not cancel a running+ # teardown. Same group as teardown, so closing the PR cancels a deploy in+ # flight — otherwise it would recreate the stack that was just removed.+ concurrency:+ group: pr-preview-${{ github.event.number || inputs.pr_number }}+ cancel-in-progress: true+ steps:+ - name: Checkout+ uses: actions/checkout@v7++ - name: Check the configuration+ env:+ KOMODO_URL: ${{ vars.KOMODO_URL }}+ KOMODO_SERVER_ID: ${{ vars.KOMODO_SERVER_ID }}+ PREVIEW_DOMAIN: ${{ vars.PREVIEW_DOMAIN }}+ PREVIEW_CADDY_NETWORK: ${{ vars.PREVIEW_CADDY_NETWORK }}+ PREVIEW_ADMIN_EMAIL: ${{ vars.PREVIEW_ADMIN_EMAIL }}+ KOMODO_API_KEY: ${{ secrets.KOMODO_API_KEY }}+ KOMODO_API_SECRET: ${{ secrets.KOMODO_API_SECRET }}+ PREVIEW_BETTER_AUTH_SECRET: ${{ secrets.PREVIEW_BETTER_AUTH_SECRET }}+ PREVIEW_BASIC_AUTH_HASH: ${{ secrets.PREVIEW_BASIC_AUTH_HASH }}+ PREVIEW_BASIC_AUTH_PASSWORD: ${{ secrets.PREVIEW_BASIC_AUTH_PASSWORD }}+ PREVIEW_ADMIN_PASSWORD: ${{ secrets.PREVIEW_ADMIN_PASSWORD }}+ run: |+ missing=""+ for name in KOMODO_URL KOMODO_SERVER_ID PREVIEW_DOMAIN PREVIEW_CADDY_NETWORK \+ PREVIEW_ADMIN_EMAIL KOMODO_API_KEY KOMODO_API_SECRET \+ PREVIEW_BETTER_AUTH_SECRET PREVIEW_BASIC_AUTH_HASH \+ PREVIEW_BASIC_AUTH_PASSWORD PREVIEW_ADMIN_PASSWORD; do+ eval "value=\${$name}"+ [ -z "$value" ] && missing="$missing $name"+ done+ if [ -n "$missing" ]; then+ echo "::error::Missing secrets or variables:$missing"+ exit 1+ fi++ # Only needed for the imagetools fallback in the next step.+ - name: Log in to ghcr.io+ uses: docker/login-action@v4+ with:+ registry: ghcr.io+ username: ${{ github.actor }}+ password: ${{ secrets.GITHUB_TOKEN }}++ - name: Wait for the PR image+ id: image+ env:+ GH_TOKEN: ${{ github.token }}+ SHA: ${{ github.event.pull_request.head.sha }}+ PR: ${{ github.event.number }}+ run: |+ # docker-dev.yml builds the pr-<n> tag; its job is named "build-dev".+ start=$(date +%s)+ deadline=$(( start + 1500 ))+ while [ "$(date +%s)" -lt "$deadline" ]; do+ # Read gh's own exit status: a 403 or a network error must not look+ # like "no run yet", or the fallback below would kick in.+ if ! runs=$(gh api "repos/$GITHUB_REPOSITORY/commits/$SHA/check-runs" \+ --jq '.check_runs[] | select(.name=="build-dev") | "\(.status) \(.conclusion)"' \+ 2>"$RUNNER_TEMP/gh-err.txt"); then+ echo "::error::Could not query the check runs: $(cat "$RUNNER_TEMP/gh-err.txt")"+ exit 1+ fi+ run=$(printf '%s\n' "$runs" | head -1)+ case "$run" in+ "completed success") echo "Image-Build fertig."; exit 0 ;;+ "completed "*) echo "::error::The image build ended as: $run"; exit 1 ;;+ esac+ # docker-dev.yml has paths-ignore for messages/**, docs/** and **/*.md.+ # If no run has appeared after three minutes, this commit has none — then+ # all that counts is whether an earlier push left the tag behind.+ if [ -z "$run" ] && [ "$(( $(date +%s) - start ))" -ge 180 ]; then+ if docker buildx imagetools inspect "ghcr.io/pantelx/bettershift:pr-$PR" >/dev/null 2>&1; then+ echo "::notice::No build for $SHA (paths-ignore); using the existing tag pr-$PR."+ echo "stale=true" >> "$GITHUB_OUTPUT"+ exit 0+ fi+ echo "::error::No build for $SHA and no image pr-$PR. Push a commit that triggers the build first."+ exit 1+ fi+ sleep 20+ done+ echo "::error::Timed out waiting for the image build for $SHA."+ exit 1++ - name: Deploy the stack+ env:+ KOMODO_URL: ${{ vars.KOMODO_URL }}+ KOMODO_API_KEY: ${{ secrets.KOMODO_API_KEY }}+ KOMODO_API_SECRET: ${{ secrets.KOMODO_API_SECRET }}+ KOMODO_SERVER_ID: ${{ vars.KOMODO_SERVER_ID }}+ PR_NUMBER: ${{ github.event.number }}+ PREVIEW_DOMAIN: ${{ vars.PREVIEW_DOMAIN }}+ PREVIEW_CADDY_NETWORK: ${{ vars.PREVIEW_CADDY_NETWORK }}+ PREVIEW_IMAGE: ghcr.io/pantelx/bettershift:pr-${{ github.event.number }}+ PREVIEW_BASIC_AUTH_HASH: ${{ secrets.PREVIEW_BASIC_AUTH_HASH }}+ PREVIEW_BETTER_AUTH_SECRET: ${{ secrets.PREVIEW_BETTER_AUTH_SECRET }}+ run: node scripts/preview-stack.mjs deploy++ - name: Wait for the instance+ env:+ URL: https://pr-${{ github.event.number }}.${{ vars.PREVIEW_DOMAIN }}+ BASIC_PASSWORD: ${{ secrets.PREVIEW_BASIC_AUTH_PASSWORD }}+ run: |+ # Has to cover a registry pull, the migration, the Next.js boot and Caddy's first ACME issuance.+ deadline=$(( $(date +%s) + 300 ))+ while [ "$(date +%s)" -lt "$deadline" ]; do+ if curl -sf -u "preview:$BASIC_PASSWORD" "$URL/api/health" >/dev/null; then+ echo "Instanz ist erreichbar."+ exit 0+ fi+ sleep 5+ done+ echo "::error::$URL/api/health is not answering. The stack is left standing for debugging."+ exit 1++ - name: Seed the demo data+ env:+ PREVIEW_URL: https://pr-${{ github.event.number }}.${{ vars.PREVIEW_DOMAIN }}+ PREVIEW_BASIC_AUTH_PASSWORD: ${{ secrets.PREVIEW_BASIC_AUTH_PASSWORD }}+ PREVIEW_ADMIN_EMAIL: ${{ vars.PREVIEW_ADMIN_EMAIL }}+ PREVIEW_ADMIN_PASSWORD: ${{ secrets.PREVIEW_ADMIN_PASSWORD }}+ run: node scripts/seed-preview.mjs++ - name: Comment on the PR+ env:+ GH_TOKEN: ${{ github.token }}+ PR: ${{ github.event.number }}+ URL: https://pr-${{ github.event.number }}.${{ vars.PREVIEW_DOMAIN }}+ ADMIN_EMAIL: ${{ vars.PREVIEW_ADMIN_EMAIL }}+ ADMIN_PASSWORD: ${{ secrets.PREVIEW_ADMIN_PASSWORD }}+ SHA: ${{ github.event.pull_request.head.sha }}+ STALE_IMAGE: ${{ steps.image.outputs.stale }}+ run: |+ set -o pipefail+ if [ "$STALE_IMAGE" = "true" ]; then+ commit_line="Image: from an earlier commit of this PR — no image was built for \`$SHA\` (paths-ignore)."+ else+ commit_line="Commit: \`$SHA\`"+ fi+ body=$(cat <<EOF+ $STACK_COMMENT_MARKER+ ### Preview ready++ **$URL**++ Sign in with \`$ADMIN_EMAIL\` / \`$ADMIN_PASSWORD\`++ The instance sits behind basic auth (user \`preview\`). Every further push resets+ it and seeds the demo data again.++ $commit_line+ EOF+ )+ existing=$(gh api --paginate "repos/$GITHUB_REPOSITORY/issues/$PR/comments" \+ --jq ".[] | select(.user.login == \"github-actions[bot]\") | select(.body | contains(\"$STACK_COMMENT_MARKER\")) | .id" | tail -n 1)+ if [ -n "$existing" ]; then+ gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$existing" -f body="$body"+ else+ gh api -X POST "repos/$GITHUB_REPOSITORY/issues/$PR/comments" -f body="$body"+ fi++ teardown:+ name: Tear the preview down+ # vars.KOMODO_URL as the switch: secrets are not readable in a job-level `if`,+ # repository variables are. With no configuration there is nothing to tear down.+ if: >-+ vars.KOMODO_URL != '' &&+ (github.event_name == 'workflow_dispatch' ||+ (github.event.pull_request.head.repo.full_name == github.repository &&+ (github.event.action == 'closed' ||+ (github.event.action == 'unlabeled' && github.event.label.name == 'preview'))))+ runs-on: ubuntu-latest+ timeout-minutes: 10+ concurrency:+ group: pr-preview-${{ github.event.number || inputs.pr_number }}+ cancel-in-progress: true+ steps:+ - name: Checkout+ uses: actions/checkout@v7++ - name: Destroy and delete the stack+ env:+ KOMODO_URL: ${{ vars.KOMODO_URL }}+ KOMODO_API_KEY: ${{ secrets.KOMODO_API_KEY }}+ KOMODO_API_SECRET: ${{ secrets.KOMODO_API_SECRET }}+ PR_NUMBER: ${{ github.event.number || inputs.pr_number }}+ run: node scripts/preview-stack.mjs destroy++ - name: Update the comment+ env:+ GH_TOKEN: ${{ github.token }}+ PR: ${{ github.event.number || inputs.pr_number }}+ run: |+ set -o pipefail+ existing=$(gh api --paginate "repos/$GITHUB_REPOSITORY/issues/$PR/comments" \+ --jq ".[] | select(.user.login == \"github-actions[bot]\") | select(.body | contains(\"$STACK_COMMENT_MARKER\")) | .id" | tail -n 1)+ if [ -z "$existing" ]; then+ echo "No preview comment present — nothing to update."+ exit 0+ fi+ gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$existing" \+ -f body="$STACK_COMMENT_MARKER+ ### Preview torn down++ The container and its data have been deleted."diff --git a/CLAUDE.md b/CLAUDE.mdindex 3ec2cb1..2c8864a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -106,7 +106,7 @@ UI strings and log output are product text in the project's locales; code commen## Reference-`docs/AUTH_SETUP.md`, `docs/PERMISSIONS.md`, `docs/ADMIN_PANEL.md`, `docs/ENABLING_AUTH.md`, `docs/UPGRADING.md`; `.env.example` documents every environment variable with its default.+`docs/AUTH_SETUP.md`, `docs/PERMISSIONS.md`, `docs/ADMIN_PANEL.md`, `docs/ENABLING_AUTH.md`, `docs/UPGRADING.md`, `docs/PR_PREVIEWS.md`; `.env.example` documents every environment variable with its default.<!-- BEGIN:nextjs-agent-rules -->diff --git a/docs/PR_PREVIEWS.md b/docs/PR_PREVIEWS.mdnew file mode 100644index 0000000..9e9e75a--- /dev/null+++ b/docs/PR_PREVIEWS.md@@ -0,0 +1,187 @@+# PR Preview Deployments Guide++This guide explains the automated preview environments BetterShift spins up for pull requests, what has to be configured on the server before the first one can deploy, and how to clean one up by hand if the automation doesn't.++## Table of Contents++1. [What It Does](#what-it-does)+2. [Prerequisites on the Server](#prerequisites-on-the-server)+3. [Secrets](#secrets)+4. [Variables](#variables)+5. [How the Pieces Fit Together](#how-the-pieces-fit-together)+6. [What's Different in a Preview](#whats-different-in-a-preview)+7. [Manual Cleanup](#manual-cleanup)+8. [Security Note](#security-note)++---++## What It Does++Adding the `preview` label to a pull request from this repository gets it a running, seeded BetterShift instance at `https://pr-<number>.<PREVIEW_DOMAIN>`. Usually that takes a few minutes; in the worst case it takes considerably longer, because the deploy job first waits for the PR's image to finish building — that wait alone is allowed to run for up to 25 minutes. Every further push to the PR (a `synchronize` event) redeploys it from scratch: the old container and its data are destroyed first, so the instance always reflects the latest commit and starts from a clean, freshly seeded database.++Closing the PR, or removing the `preview` label again, tears the instance down completely — container and data, nothing left behind. Reopening a closed PR that still carries the `preview` label deploys it again, the same way a `synchronize` push does: fresh container, freshly reseeded database.++A pull request from a fork never gets a preview: `.github/workflows/pr-preview.yml` checks `head.repo.full_name` against the target repository and, for a fork PR that gets labeled `preview`, only writes an explanatory `::notice::` into the job log instead of deploying anything. It is a log line rather than a PR comment on purpose: a `pull_request` event from a fork gets a read-only `GITHUB_TOKEN` no matter what the workflow's `permissions:` block says, so posting a comment would simply fail with a 403. Whoever added the label has write access and can read the job. Fork PRs don't get repository secrets or a pushed image, so there would be nothing to deploy against anyway.++## Prerequisites on the Server++Before the first preview can go live, the server that Komodo deploys to needs:++- A wildcard DNS record on `*.<PREVIEW_DOMAIN>` pointing at that server.+- A running `caddy-docker-proxy` instance. It reads Docker labels on containers and reconfigures itself automatically — there's no reload step this feature has to trigger.+- The Docker network named in `PREVIEW_CADDY_NETWORK`, the one Caddy is attached to. If you don't know its name, find it with:++ ```bash+ docker inspect <caddy-container> --format '{{range $k, $v := .NetworkSettings.Networks}}{{$k}} {{end}}'+ ```++- A Komodo instance reachable over HTTPS, with an API key/secret pair (`KOMODO_API_KEY` / `KOMODO_API_SECRET`) that can create, update, deploy, and delete stacks on the target server. Scope that key to the preview server only. Do **not** use an admin key: the same credentials would be able to reach and destroy your production stacks, and they live in a repository that anyone can open a pull request against.+- The GHCR package `ghcr.io/pantelx/bettershift` has to be **public**. The compose file `scripts/preview-stack.mjs` generates carries no registry credentials, so the Komodo host pulls the `pr-<n>` tag anonymously. If you keep the package private, the pull fails with "unauthorized" and you have to attach a Komodo `registry_account` to the stack config instead (and add the corresponding field in `stackConfig()`).++### Image Cleanup Is Your Job++Nothing in this feature prunes images. `docker compose down` — what a teardown runs — removes containers, not images, and every PR pulls a fresh `pr-<n>` image that then sits on the host forever. The first symptom of a full disk is usually an unrelated deploy failing, so treat this as a standing operator duty: run `docker image prune -af --filter "until=168h"` periodically on the preview host (a cron job, or a scheduled prune in Komodo).++The `pr-<n>` tags on ghcr.io are never deleted either, neither by the preview workflow nor by `docker-dev.yml`. That is a deliberate choice — tags cost little and keeping them makes a preview reproducible after the fact — not an oversight.++### One-Time Setup Checks++Four things depend on versions nobody here could verify in advance. Check them once, when setting this up on your server:++**1. Caddy version, for the Basic Auth label.** The compose file `scripts/preview-stack.mjs` generates uses the label `caddy.basic_auth.preview`. Caddy renamed the directive from `basicauth` to `basic_auth` in Caddy 2.8. Check your running version:++```bash+docker exec <caddy-container> caddy version+```++If it's older than 2.8, change the label key in `composeFile()` in `scripts/preview-stack.mjs` from `caddy.basic_auth.preview` to `caddy.basicauth.preview`.++**2. Komodo's `environment` field type.** `scripts/preview-stack.mjs` sends the stack's `environment` as a single newline-separated string (`KEY=value\nKEY=value`). Some Komodo versions instead expect a list of strings. Verify against your instance with a read against any existing stack:++```bash+curl -s -X POST "$KOMODO_URL/read/GetStack" \+ -H "x-api-key: $KOMODO_API_KEY" -H "x-api-secret: $KOMODO_API_SECRET" \+ -H "content-type: application/json" \+ -d '{"stack": "<existing-stack-name>"}' | jq '.config.environment'+```++If that comes back as an array rather than a string, the `environment` value built in `stackConfig()` in `scripts/preview-stack.mjs` needs to become an array of `"KEY=value"` strings instead of the joined string it is today.++**3. Komodo's request shape.** `komodo()` in `scripts/preview-stack.mjs` posts to one endpoint per call with the params as the body — `POST /read/GetStack` with `{"stack": …}`, `POST /execute/DeployStack` with `{"stack": …}`, and so on. Some Komodo versions instead expose a single endpoint per category and expect the call to be named in the body: `POST /read` with `{"type": "GetStack", "params": {"stack": …}}`. The curl above is the test: a `404` or `405` on `/read/GetStack` means your instance wants the other shape, and `komodo()` has to be changed to take a type plus params and post to `/read`, `/write` or `/execute`.++**4. What `/execute/*` returns.** `updateFailure()` in `scripts/preview-stack.mjs` reads the returned Update's `success` field to catch a compose run that failed behind an HTTP 200, but only once `status` says the update is complete — `success` is also `false` while it is still `Queued` or `InProgress`. If your instance returns the initial update under a different `status` spelling, watch the first real deploy: a successful deploy that nevertheless reports `DeployStack fehlgeschlagen.` means the terminal-state check in `updateFailure()` needs your instance's spelling.++## Secrets++Repository secrets the `deploy` job in `.github/workflows/pr-preview.yml` requires. Configure them under **Settings → Secrets and variables → Actions → Secrets** (repository secrets, not environment secrets):++| Secret | Contents |+| --- | --- |+| `KOMODO_API_KEY` | API key of a Komodo (service) user |+| `KOMODO_API_SECRET` | matching API secret |+| `PREVIEW_BETTER_AUTH_SECRET` | `BETTER_AUTH_SECRET` used by every preview instance |+| `PREVIEW_BASIC_AUTH_HASH` | bcrypt hash of the Basic Auth password |+| `PREVIEW_BASIC_AUTH_PASSWORD` | the same password, in plain text |+| `PREVIEW_ADMIN_PASSWORD` | password for the seed admin account |++Generate the hash with:++```bash+docker run --rm caddy caddy hash-password --plaintext '<password>'+```++Store its output in `PREVIEW_BASIC_AUTH_HASH` exactly as printed — plain, unescaped bcrypt hash, `$` characters and all. Do **not** pre-escape any `$` in it by hand: `scripts/preview-stack.mjs` already replaces every `$` with `$$` itself when it writes the value into the `.env` file Komodo hands to Docker Compose, because Compose expands `$`-variables inside `.env` values. Hand-escaping the hash before storing it would double the escaping and produce a broken hash on the other end.++`PREVIEW_BASIC_AUTH_PASSWORD` has to hold the plain-text password, not just the hash, because both the workflow's health check (a plain `curl` request) and `scripts/seed-preview.mjs` need to authenticate through Basic Auth themselves before they can reach the app at all.++`PREVIEW_ADMIN_PASSWORD` has two constraints. It must be **at least 8 characters** long — better-auth enforces that minimum on `/api/auth/sign-up/email`, and a shorter one makes `scripts/seed-preview.mjs` fail with an opaque `400` that says nothing about the length. And it must be a **throwaway used nowhere else**: the deploy job writes it into the sticky PR comment in plain text, on a public repository, so anyone can read it. The member account the seed script creates (`[email protected]`) is registered with the same password.++The Basic Auth username is fixed to `preview` — it's hardcoded into the compose label key (`caddy.basic_auth.preview`) and into the workflow's health-check `curl` call, and it's the default `scripts/seed-preview.mjs` falls back to (`PREVIEW_BASIC_AUTH_USER`, which this workflow never sets). There is no repository variable for it.++## Variables++Repository variables the `deploy` job reads. Same place, one tab over: **Settings → Secrets and variables → Actions → Variables**. `KOMODO_URL` doubles as the feature's on/off switch — while it is unset, the `teardown` job skips itself, so closing a PR on a repository that has no preview server configured doesn't produce a red job.++| Variable | Example |+| --- | --- |+| `KOMODO_URL` | `https://komodo.example.com` |+| `KOMODO_SERVER_ID` | ID of the server the previews are deployed to |+| `PREVIEW_DOMAIN` | `preview.example.com` |+| `PREVIEW_CADDY_NETWORK` | name of the Docker network Caddy is attached to (see [Prerequisites](#prerequisites-on-the-server)) |+| `PREVIEW_ADMIN_EMAIL` | `[email protected]` |++## How the Pieces Fit Together++```text+PR gets the label "preview"+ │+ ▼+.github/workflows/pr-preview.yml (job: deploy)+ │+ ├─ wait (up to 25 min) for the "build-dev" check run (from the+ │ "Docker Dev Build" workflow) on the PR's head SHA+ │ ├─ success → carry on+ │ ├─ failure/cancelled → job fails+ │ └─ still no run after 3 min (docker-dev.yml has paths-ignore+ │ for messages/**, docs/** and **/*.md, so this commit+ │ never triggered a build)+ │ ├─ tag pr-<n> exists from an earlier push → carry on,+ │ │ and mark the deploy as running an older image+ │ └─ no tag at all → job fails+ ├─ node scripts/preview-stack.mjs deploy+ │ ├─ Komodo /read/GetStack, then /write/CreateStack or /write/UpdateStack+ │ └─ Komodo /execute/DeployStack (destroy_before_deploy: true)+ │ └─ server: docker compose up+ │ └─ container carrying the Caddy labels+ │ └─ caddy-docker-proxy picks up the+ │ subdomain live, no reload needed+ ├─ wait up to 5 min for GET /api/health == 200 (through Basic Auth)+ ├─ node scripts/seed-preview.mjs+ └─ sticky PR comment ("### Preview bereit") created or updated,+ naming the head commit — or, on the fallback path above,+ saying that the image comes from an earlier commit++PR is closed / the "preview" label is removed+ / the workflow is started by hand (Run workflow, with a PR number)+ │+ ▼+.github/workflows/pr-preview.yml (job: teardown)+ ├─ node scripts/preview-stack.mjs destroy+ │ ├─ Komodo /execute/DestroyStack+ │ └─ Komodo /write/DeleteStack+ └─ sticky PR comment rewritten to "### Preview abgeräumt"+```++`scripts/preview-stack.mjs` only ever talks to Komodo; it knows nothing about GitHub. `scripts/seed-preview.mjs` only ever talks to the running instance over plain HTTP; it knows nothing about Komodo or GitHub either — that's why it can also be pointed at any instance by hand, for testing, just by setting its environment variables.++## What's Different in a Preview++A few things distinguish a preview container from a normal deployment:++- **No volumes.** The compose file `preview-stack.mjs` generates has no `volumes:` section at all — SQLite and any uploads live in the container's own writable layer. Combined with `destroy_before_deploy: true`, that means every push resets the instance completely and the seed script runs again from an empty database. This is deliberate, not a gap: state is meant to be disposable here.+- **`ALLOW_USER_REGISTRATION=true`** is set on the container so that `scripts/seed-preview.mjs` can register its accounts through the regular `/api/auth/sign-up/email` route, the same way a real user would.+- **The first account the seed script registers becomes superadmin automatically** — that's standard BetterShift behaviour for the first user on any fresh instance (`lib/auth/first-user.ts`), not something specific to previews.+- `AUTH_ENABLED=true`, `TZ=Europe/Berlin` and `DEFAULT_LOCALE=de` are also fixed on the container (overridable only by setting `PREVIEW_TZ` / `PREVIEW_LOCALE` in the workflow's own environment before it calls `scripts/preview-stack.mjs`, since the script falls back to those defaults itself).+- **`TRUSTED_PROXY_HEADER=CF-Connecting-IP`** is set because previews are served through Cloudflare in front of Caddy. With two proxies in the chain, the last `X-Forwarded-For` entry is Cloudflare's address rather than the visitor's, which would make the rate limiter treat every visitor as the same client. If your preview host is not behind Cloudflare, drop this line from `composeFile()` — naming a header the proxy does not set is worse than naming none.+- **`CSP_STRICT_DYNAMIC_BYPASS=true`** relaxes `script-src` to `'self' 'unsafe-inline'`. Cloudflare's Rocket Loader rewrites the page and reconstructs inline scripts without their nonce, which the strict policy then blocks — the app fails to load with no obvious cause. Once Rocket Loader is confirmed off for the preview domain, remove this line so previews exercise the same CSP as production.++## Manual Cleanup++If a teardown run failed, or a stack was left standing on purpose after a broken deploy (see "Note that a health check that times out…" at the end of this section), the easiest fix is the workflow's manual entry point: **Actions → PR Preview → Run workflow**, enter the PR number, start it. That runs the `teardown` job for exactly that PR — destroy the stack, delete it in Komodo, rewrite the sticky comment — without needing any further event on the PR. A closed PR emits no event you could retry, so this is the only in-GitHub way back.++Alternatively, from a checkout with the Komodo credentials at hand:++```bash+KOMODO_URL=… KOMODO_API_KEY=… KOMODO_API_SECRET=… PR_NUMBER=<n> \+ node scripts/preview-stack.mjs destroy+```++This is safe to run even if the stack is already gone — `scripts/preview-stack.mjs` checks for it first and does nothing if it can't find it.++Note that a health check that times out during deploy deliberately leaves the stack running instead of tearing it down: the whole point is to keep the container's logs inspectable in Komodo while you figure out what went wrong. The same is true if the seed step fails. In both cases nothing removes the stack automatically — use the command above once you're done investigating.++## Security Note++This repository is public, and a PR comment is world-readable. The sticky comment the `deploy` job posts therefore includes the seed admin's login (email and password) so anyone can look at the preview, but never the Basic Auth password — that one stays a repository secret and is never written into a comment.++Preview instances only ever contain data `scripts/seed-preview.mjs` generates itself: fictional names, fictional calendars, fictional shifts. Nothing from a real deployment is ever copied into a preview.diff --git a/scripts/preview-stack.mjs b/scripts/preview-stack.mjsnew file mode 100644index 0000000..b5ea0e8--- /dev/null+++ b/scripts/preview-stack.mjs@@ -0,0 +1,256 @@+#!/usr/bin/env node+/**+ * Creates, updates and tears down the per-PR preview stack in Komodo.+ *+ * Plain .mjs without dependencies, like scripts/migrate.mjs: the workflow can+ * run it without `npm ci`.+ *+ * Usage: node scripts/preview-stack.mjs <deploy|destroy> [--dry-run]+ */++const REQUIRED = {+ deploy: [+ "KOMODO_URL",+ "KOMODO_API_KEY",+ "KOMODO_API_SECRET",+ "KOMODO_SERVER_ID",+ "PR_NUMBER",+ "PREVIEW_DOMAIN",+ "PREVIEW_CADDY_NETWORK",+ "PREVIEW_IMAGE",+ "PREVIEW_BASIC_AUTH_HASH",+ "PREVIEW_BETTER_AUTH_SECRET",+ ],+ destroy: [+ "KOMODO_URL",+ "KOMODO_API_KEY",+ "KOMODO_API_SECRET",+ "PR_NUMBER",+ ],+};++function requireEnv(names) {+ const missing = names.filter((name) => !process.env[name]);+ if (missing.length > 0) {+ console.error(`Missing configuration: ${missing.join(", ")}`);+ process.exit(1);+ }+}++/**+ * Actions masks the registered secrets, but escapeEnvValue() doubles every `$`,+ * so an echoed `environment` would no longer match and would print in clear.+ */+function redact(text) {+ const masked = String(text ?? "").replace(+ /((?:BASIC_AUTH_HASH|BETTER_AUTH_SECRET)=)[^\s"',\\]*/g,+ "$1<redacted>"+ );+ return masked.length > 2000 ? `${masked.slice(0, 2000)}… [truncated]` : masked;+}++async function komodo(path, body) {+ const res = await fetch(`${process.env.KOMODO_URL.replace(/\/$/, "")}${path}`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "x-api-key": process.env.KOMODO_API_KEY,+ "x-api-secret": process.env.KOMODO_API_SECRET,+ },+ body: JSON.stringify(body ?? {}),+ });+ const text = await res.text();+ if (!res.ok) {+ const error = new Error(`${path} -> ${res.status}: ${redact(text)}`);+ error.status = res.status;+ error.bodyText = text;+ throw error;+ }+ return text ? JSON.parse(text) : null;+}++/**+ * Komodo answers 200 even when the compose run failed; the outcome sits in the+ * returned Update. Returns a message on a real failure, else null.+ * A response without a `success` field is not a failure, and `success` is also+ * false while an update is still Queued or InProgress — so a `status` that is+ * present but not terminal is not a failure either.+ */+function updateFailure(label, result) {+ const update = result && typeof result === "object" ? (result.update ?? result) : null;+ if (!update || typeof update !== "object" || update.success !== false) return null;+ if (typeof update.status === "string" && !/^complete/i.test(update.status)) return null;++ const logs = Array.isArray(update.logs) ? update.logs : [];+ const failed = logs.filter((log) => log && log.success === false);+ const detail = (failed.length > 0 ? failed : logs)+ .map((log) => [log?.stage, log?.command, log?.stderr, log?.stdout].filter(Boolean).join("\n"))+ .filter(Boolean)+ .join("\n---\n");++ return `${label} failed.${detail ? `\n${redact(detail)}` : " Komodo reported no details."}`;+}++function assertUpdateOk(label, result) {+ const message = updateFailure(label, result);+ if (message) throw new Error(message);+}++/**+ * Only BASIC_AUTH_HASH and BETTER_AUTH_SECRET go through the .env file Komodo+ * writes: a bcrypt hash contains `$`, which compose would read as a variable+ * if it sat in the compose file itself.+ */+function composeFile({ image, host, network, tz, locale }) {+ return [+ "services:",+ " app:",+ ` image: ${image}`,+ " pull_policy: always",+ " restart: unless-stopped",+ " networks: [caddy]",+ " environment:",+ ' AUTH_ENABLED: "true"',+ ' ALLOW_USER_REGISTRATION: "true"',+ ` BETTER_AUTH_URL: "https://${host}"`,+ ' BETTER_AUTH_SECRET: "${BETTER_AUTH_SECRET}"',+ ` TZ: "${tz}"`,+ ` DEFAULT_LOCALE: "${locale}"`,+ // Cloudflare sits in front of Caddy, so the last X-Forwarded-For entry is+ // Cloudflare's address, not the visitor's.+ ' TRUSTED_PROXY_HEADER: "CF-Connecting-IP"',+ // Rocket Loader strips the nonce off the hydration scripts; drop this once+ // it is confirmed off for the preview domain.+ ' CSP_STRICT_DYNAMIC_BYPASS: "true"',+ " labels:",+ ` caddy: ${host}`,+ ' caddy.reverse_proxy: "{{upstreams 3000}}"',+ ' caddy.basic_auth.preview: "${BASIC_AUTH_HASH}"',+ "",+ "networks:",+ " caddy:",+ " external: true",+ ` name: ${network}`,+ "",+ ].join("\n");+}++// Compose expands variables inside .env values, so escape literal $ as $$.+function escapeEnvValue(value) {+ return value.replace(/\$/g, "$$$$");+}++function stackConfig() {+ const pr = process.env.PR_NUMBER;+ const host = `pr-${pr}.${process.env.PREVIEW_DOMAIN}`;+ return {+ server_id: process.env.KOMODO_SERVER_ID,+ project_name: `bettershift-pr-${pr}`,+ file_contents: composeFile({+ image: process.env.PREVIEW_IMAGE,+ host,+ network: process.env.PREVIEW_CADDY_NETWORK,+ tz: process.env.PREVIEW_TZ || "Europe/Berlin",+ locale: process.env.PREVIEW_LOCALE || "de",+ }),+ environment: [+ `BETTER_AUTH_SECRET=${escapeEnvValue(process.env.PREVIEW_BETTER_AUTH_SECRET)}`,+ `BASIC_AUTH_HASH=${escapeEnvValue(process.env.PREVIEW_BASIC_AUTH_HASH)}`,+ ].join("\n"),+ env_file_path: ".env",+ // Each push must start from an empty database, and there are no volumes+ // to carry state over anyway.+ destroy_before_deploy: true,+ auto_update: false,+ poll_for_updates: false,+ webhook_enabled: false,+ };+}++async function findStack(name) {+ try {+ return await komodo("/read/GetStack", { stack: name });+ } catch (error) {+ if (error.status === 404 || /not found|does not exist/i.test(error.bodyText || "")) {+ return null;+ }+ throw error;+ }+}++function stackId(stack, fallbackName) {+ return stack?._id?.$oid || stack?.id || fallbackName;+}++async function deploy({ dryRun }) {+ const name = `bettershift-pr-${process.env.PR_NUMBER}`;+ const config = stackConfig();++ if (dryRun) {+ console.log(`Stack: ${name}`);+ console.log("--- compose ---");+ console.log(config.file_contents);+ console.log("--- config ---");+ console.log(JSON.stringify({ ...config, environment: "<redacted>", file_contents: "<shown above>" }, null, 2));+ return;+ }++ const existing = await findStack(name);+ if (existing) {+ assertUpdateOk(+ "UpdateStack",+ await komodo("/write/UpdateStack", { id: stackId(existing, name), config })+ );+ console.log(`Stack ${name} updated.`);+ } else {+ assertUpdateOk("CreateStack", await komodo("/write/CreateStack", { name, config }));+ console.log(`Stack ${name} created.`);+ }++ assertUpdateOk("DeployStack", await komodo("/execute/DeployStack", { stack: name }));+ console.log(`Stack ${name} deployed.`);+}++async function destroy({ dryRun }) {+ const name = `bettershift-pr-${process.env.PR_NUMBER}`;++ if (dryRun) {+ console.log(`Would destroy and delete stack ${name}.`);+ return;+ }++ const existing = await findStack(name);+ if (!existing) {+ console.log(`Stack ${name} does not exist — nothing to do.`);+ return;+ }++ // Best effort on purpose: a stack whose containers never came up reports a+ // failed destroy, and the row must still go, or nothing ever cleans it up.+ const failure = updateFailure(+ "DestroyStack",+ await komodo("/execute/DestroyStack", { stack: name, services: [], remove_orphans: true })+ );+ if (failure) {+ console.error(`${failure}\nDeleting the stack entry anyway.`);+ }+ await komodo("/write/DeleteStack", { id: stackId(existing, name) });+ console.log(`Stack ${name} destroyed and deleted.`);+}++const command = process.argv[2];+const dryRun = process.argv.includes("--dry-run");++if (command !== "deploy" && command !== "destroy") {+ console.error("Usage: node scripts/preview-stack.mjs <deploy|destroy> [--dry-run]");+ process.exit(1);+}++requireEnv(REQUIRED[command]);++try {+ await (command === "deploy" ? deploy({ dryRun }) : destroy({ dryRun }));+} catch (error) {+ console.error(error.message);+ process.exit(1);+}diff --git a/scripts/seed-preview.mjs b/scripts/seed-preview.mjsnew file mode 100644index 0000000..67f5ea6--- /dev/null+++ b/scripts/seed-preview.mjs@@ -0,0 +1,213 @@+#!/usr/bin/env node+/**+ * Fills a fresh preview instance with demo data over its public HTTP API.+ *+ * Runs on the CI runner, never inside the image: going through the real routes+ * means no duplicate of better-auth's password hashing, and no seed code in the+ * production image.+ */++function requireEnv(name) {+ const value = process.env[name];+ if (!value) {+ console.error(`Missing configuration: ${name}`);+ process.exit(1);+ }+ return value;+}++const BASE = requireEnv("PREVIEW_URL").replace(/\/$/, "");+const ADMIN_EMAIL = requireEnv("PREVIEW_ADMIN_EMAIL");+const ADMIN_PASSWORD = requireEnv("PREVIEW_ADMIN_PASSWORD");+const MEMBER_EMAIL = process.env.PREVIEW_MEMBER_EMAIL || "[email protected]";+const BASIC_USER = process.env.PREVIEW_BASIC_AUTH_USER || "preview";+const BASIC_PASSWORD = process.env.PREVIEW_BASIC_AUTH_PASSWORD || "";++// Empty password means no basic auth in front of the instance (local runs).+const BASIC_HEADER = BASIC_PASSWORD+ ? { authorization: "Basic " + Buffer.from(`${BASIC_USER}:${BASIC_PASSWORD}`).toString("base64") }+ : {};++let cookie = "";++async function api(path, { method = "GET", body } = {}) {+ const res = await fetch(`${BASE}${path}`, {+ method,+ headers: {+ ...BASIC_HEADER,+ "content-type": "application/json",+ // Node's fetch sends `sec-fetch-mode: cors` (unlike a browser it never adds+ // Origin itself), which trips better-auth's CSRF check unless we set it.+ origin: BASE,+ ...(cookie ? { cookie } : {}),+ },+ body: body === undefined ? undefined : JSON.stringify(body),+ });++ const setCookies = res.headers.getSetCookie();+ if (setCookies.length > 0) {+ cookie = setCookies.map((entry) => entry.split(";")[0]).join("; ");+ }++ const text = await res.text();+ if (!res.ok) {+ const error = new Error(`${method} ${path} -> ${res.status}: ${text}`);+ error.status = res.status;+ error.bodyText = text;+ throw error;+ }+ return text ? JSON.parse(text) : null;+}++const pad = (n) => String(n).padStart(2, "0");+/** Local YYYY-MM-DD, never via UTC — same rule as lib/date-utils.ts. */+const iso = (date) => `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;++function daysOfMonth(monthOffset) {+ const today = new Date();+ const first = new Date(today.getFullYear(), today.getMonth() + monthOffset, 1);+ const days = [];+ for (let day = new Date(first); day.getMonth() === first.getMonth(); day.setDate(day.getDate() + 1)) {+ days.push(new Date(day));+ }+ return days;+}++async function signUp({ email, password, name }) {+ return api("/api/auth/sign-up/email", { method: "POST", body: { email, password, name } });+}++async function signIn({ email, password }) {+ cookie = "";+ return api("/api/auth/sign-in/email", { method: "POST", body: { email, password } });+}++async function main() {+ try {+ await signUp({ email: ADMIN_EMAIL, password: ADMIN_PASSWORD, name: "Preview Admin" });+ } catch (error) {+ // Narrow on purpose: better-auth's actual duplicate-user answer only, not any+ // error whose body happens to contain "exist" (e.g. a misrouted 404 page).+ let code;+ try {+ code = JSON.parse(error.bodyText || "").code;+ } catch {+ // not JSON — falls through, code stays undefined, error propagates below+ }+ if (error.status === 422 && code === "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL") {+ console.log("Instance is already seeded — nothing to do.");+ return;+ }+ throw error;+ }+ console.log(`Admin created: ${ADMIN_EMAIL}`);++ await signUp({ email: MEMBER_EMAIL, password: ADMIN_PASSWORD, name: "Max Mitarbeiter" });+ await signIn({ email: ADMIN_EMAIL, password: ADMIN_PASSWORD });++ const team = await api("/api/calendars", {+ method: "POST",+ body: { name: "Dienstplan Team A", color: "#3b82f6" },+ });+ await api("/api/calendars", {+ method: "POST",+ body: { name: "Urlaubsplanung", color: "#f59e0b" },+ });+ console.log("Two calendars created.");++ const bundles = await api(`/api/calendars/${team.id}/bundles`);+ const contribute = bundles.find((bundle) => bundle.name === "Contribute") || bundles[0];+ const found = await api(`/api/users/search?calendarId=${team.id}&q=Max`);+ const member = (Array.isArray(found) ? found : found.users || []).find(+ (candidate) => candidate.email === MEMBER_EMAIL+ );+ if (member) {+ await api(`/api/calendars/${team.id}/shares`, {+ method: "POST",+ body: { userId: member.id, bundleId: contribute.id },+ });+ console.log(`Calendar shared with ${MEMBER_EMAIL} (bundle ${contribute.name}).`);+ } else {+ console.warn(+ `No user ${MEMBER_EMAIL} found — skipping the share and the shift signups.`+ );+ }++ await api(`/api/calendars/${team.id}/custom-fields`, {+ method: "POST",+ body: {+ key: "dienstort",+ label: "Dienstort",+ type: "select",+ options: [+ { id: "zentrale", label: "Zentrale" },+ { id: "aussenstelle", label: "Außenstelle" },+ ],+ required: false,+ showInCalendar: true,+ },+ });++ const presetDefinitions = [+ { title: "Frühdienst", startTime: "06:00", endTime: "14:00", color: "#22c55e" },+ { title: "Spätdienst", startTime: "14:00", endTime: "22:00", color: "#3b82f6" },+ { title: "Nachtdienst", startTime: "22:00", endTime: "06:00", color: "#6366f1" },+ { title: "Urlaub", isAllDay: true, color: "#f97316" },+ ];+ const presets = [];+ for (const definition of presetDefinitions) {+ presets.push(await api("/api/presets", { method: "POST", body: { calendarId: team.id, ...definition } }));+ }+ console.log(`${presets.length} presets created.`);++ const rotation = presets.slice(0, 3);+ let shiftCount = 0;+ for (const monthOffset of [0, 1]) {+ for (const day of daysOfMonth(monthOffset)) {+ if (day.getDay() === 0) continue; // Sundays stay empty so the plan does not look uniformly filled+ const preset = rotation[shiftCount % rotation.length];+ await api("/api/shifts", {+ method: "POST",+ body: {+ calendarId: team.id,+ date: iso(day),+ title: preset.title,+ startTime: preset.startTime,+ endTime: preset.endTime,+ color: preset.color,+ presetId: preset.id,+ customFields: { dienstort: shiftCount % 2 === 0 ? "zentrale" : "aussenstelle" },+ ...(shiftCount % 5 === 0 && member+ ? { signupCapacity: 2, signupUserIds: [member.id] }+ : {}),+ },+ });+ shiftCount += 1;+ }+ }+ console.log(`${shiftCount} shifts created.`);++ const [firstDay] = daysOfMonth(0);+ const notes = [+ { offset: 4, note: "Teambesprechung 10:00", type: "event", color: "#ef4444" },+ { offset: 11, note: "Dienstplan für den Folgemonat abstimmen", type: "note", color: "#3b82f6" },+ { offset: 19, note: "Betriebsausflug", type: "event", color: "#22c55e" },+ ];+ for (const entry of notes) {+ const date = new Date(firstDay);+ date.setDate(date.getDate() + entry.offset);+ await api("/api/notes", {+ method: "POST",+ body: { calendarId: team.id, date: iso(date), note: entry.note, type: entry.type, color: entry.color },+ });+ }+ console.log(`${notes.length} notes created.`);+ console.log("Seed complete.");+}++try {+ await main();+} catch (error) {+ console.error(error.message);+ process.exit(1);+}