diff --git a/.dockerignore b/.dockerignore index 780a6c1..c8cbf69 100644 --- a/.dockerignore +++ b/.dockerignore @@ -9,6 +9,11 @@ node_modules !.env.example *.log coverage +test-results +*.tsbuildinfo .next out build +.agent +.pi +.superpowers diff --git a/.env.example b/.env.example index da116d8..10c019d 100644 --- a/.env.example +++ b/.env.example @@ -4,9 +4,24 @@ # All secrets are server-only — never prefix with NEXT_PUBLIC_. # --------------------------------------------------------------------------- -# Database (Postgres). docker-compose sets this for the app container. +# Database (Postgres). The compose app/migrate services build their own URL from +# POSTGRES_*; this value is for host-side CLI commands (`pnpm db:*`, psql). DATABASE_URL=postgres://media:media@localhost:5433/media +# Compose database credentials. Applied only when the pgdata volume is first +# initialized; changing them later does not change the role inside Postgres. +# For production use a URL-safe password (openssl rand -hex 24) and update +# DATABASE_URL to match. +POSTGRES_USER=media +POSTGRES_PASSWORD=media +POSTGRES_DB=media +POSTGRES_PORT=5433 +POSTGRES_BIND=127.0.0.1 + +# Host publishing. Set APP_BIND=127.0.0.1 when a reverse proxy is in front. +APP_PORT=3000 +APP_BIND=0.0.0.0 + # Auth (magic-link). Generate a secret with: openssl rand -base64 32 # This value also encrypts the admin-entered Gmail app password: rotating it # makes stored SMTP credentials undecryptable (they are then treated as unset). @@ -59,7 +74,10 @@ UPLOAD_DIR=/tmp/uploads # The app always writes to /archive inside the container; admins can change the # archive subfolder in Settings → Photo archive (NFS). ARCHIVE_DIR=/archive +ARCHIVE_FOLDER=Glenloch Media NFS_SHARE= +# Host path bind-mounted at /archive. Leave empty to use the archive-data volume. +MEDIA_ARCHIVE_DIR= # Observability (declared; no Sentry integration is wired yet) SENTRY_DSN= diff --git a/README.md b/README.md index 56c10a5..dd761b1 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Built with Next.js 15, React 19, TypeScript, PostgreSQL 16, and Drizzle ORM. It - [Backup and restore](#backup-and-restore) - [Roles and permissions](#roles-and-permissions) - [Testing](#testing) -- [Deployment notes](#deployment-notes) +- [Production deployment on Ubuntu](#production-deployment-on-ubuntu) - [Project structure](#project-structure) - [Documentation](#documentation) - [Known gaps](#known-gaps) @@ -108,7 +108,7 @@ docker compose --profile tools run --rm migrate # migrations + seed docker compose up -d --build app ``` -Open . The app publishes on host port `3000`; Postgres is exposed on `5433` to avoid clashing with a local `5432`. +Open . The app publishes on host port `3000`; Postgres is published on `5433` but bound to `127.0.0.1` by default (set `POSTGRES_BIND=0.0.0.0` only if another host must reach it). With the default local configuration (`MAGIC_LINK_DEV_TRANSPORT=true`), requesting a sign-in link shows it in the browser and prints it in the app log: @@ -155,7 +155,10 @@ Copy `.env.example` to `.env`; never commit real secrets (`.env*` is ignored, `. | Variable | Purpose | | --- | --- | -| `DATABASE_URL` | Postgres connection string. Compose uses `db:5432`; local dev uses `localhost:5433`. | +| `DATABASE_URL` | Postgres connection string for host-side CLI commands. Compose builds the app/migrate URL from `POSTGRES_*` and uses `db:5432`; local dev uses `localhost:5433`. | +| `POSTGRES_USER`, `POSTGRES_PASSWORD`, `POSTGRES_DB` | Compose database credentials. Applied only when the `pgdata` volume is first initialized; use a URL-safe password (hex is simplest). | +| `POSTGRES_PORT`, `POSTGRES_BIND` | Host publishing for Postgres. Defaults: `5433` on `127.0.0.1`. | +| `APP_PORT`, `APP_BIND` | Host publishing for the app. Default: `3000` on all interfaces; set `APP_BIND=127.0.0.1` behind a reverse proxy. | | `NEXTAUTH_SECRET` | Auth.js signing secret **and** the at-rest encryption key for the stored Gmail app password. Rotating it invalidates sessions and makes the stored SMTP password undecryptable. | | `NEXTAUTH_URL` | Base URL for Auth.js. Keep it HTTP locally; an HTTPS value marks the session cookie `Secure`, which breaks plain-HTTP LAN access. | | `PUBLIC_ORIGIN` | Canonical origin used in emailed links. **Set this in any off-LAN deployment**; if empty, links use the request origin/Host header. | @@ -168,7 +171,7 @@ Copy `.env.example` to `.env`; never commit real secrets (`.env*` is ignored, `. | `POSTMARK_SERVER_TOKEN`, `POSTMARK_FROM` | Optional Postmark fallback and default sender. Admin email settings take precedence. | | `OUTBOX_DIR` | Console email transport directory (`/tmp/outbox` in compose). | | `UPLOAD_DIR` | Training attachments and event photo/video bytes (`/tmp/uploads` in compose). | -| `ARCHIVE_DIR`, `NFS_SHARE` | Archive mount path inside the container and the reported NFS share. | +| `ARCHIVE_DIR`, `NFS_SHARE`, `ARCHIVE_FOLDER` | Archive mount path inside the container, the reported NFS share, and the default archive subfolder. | | `MEDIA_ARCHIVE_DIR` | **Compose-only host path** mounted at `/archive` for the NFS export. | | `SENTRY_DSN` | Declared but not wired to any integration. | @@ -245,14 +248,301 @@ If a server is already listening on port 3000, Playwright reuses it; stop the de The unit suite covers pure domain rules, auth/permissions/tokens, uploads, rate limiting, event access, photo/video helpers, and backup/export logic. `.github/workflows/ci.yml` defines the full check sequence: migration drift, typecheck, lint, unit tests, migrations, E2E, and build. -## Deployment notes +## Production deployment on Ubuntu -- Run the app behind a TLS-terminating reverse proxy. Application responses already set `X-Content-Type-Options`, `Referrer-Policy`, `Permissions-Policy`, and `X-Frame-Options` on API routes; `/embed/*` is intentionally frameable. -- Set `PUBLIC_ORIGIN` to the public HTTPS origin, `AUTO_ACTIVATE_NEW_USERS=false`, `ALLOW_DEV_RESET=false`, and `MAGIC_LINK_DEV_TRANSPORT=false` once real mail is configured. -- Schedule the four cron routes externally (host cron/systemd timer/scheduler container) with `CRON_SECRET`. -- Mount the NFS export on the Docker host and start Compose with `MEDIA_ARCHIVE_DIR=/path/to/export`; configure the archive subfolder in Settings → Media archive (NFS). -- Persist the Postgres, outbox, uploads, and archive volumes. Keep `NEXTAUTH_SECRET` stable and backed up. -- The `/api/dev/*` prefix is historical: these are the production admin/cron APIs. The guards, not the URL, are the security boundary. +This is the full path for a fresh Ubuntu 22.04/24.04 host using Docker. The result is the app on `127.0.0.1:3000`, Postgres on `127.0.0.1:5433`, Caddy terminating TLS on ports 80/443, and cron driving the background jobs. + +**Host requirements** + +- Ubuntu 22.04 LTS or 24.04 LTS with sudo access. +- 2 vCPU and 2 GB RAM minimum (4 GB for heavy video processing), 20 GB free disk plus space for media. +- A DNS `A` record (and `AAAA` if using IPv6) for the hostname, pointing at the server. +- Inbound TCP 22, 80, and 443 allowed. Do **not** expose 3000 or 5433. +- Optional: an NFS export for the media archive. + +### 1. Install Docker Engine and Compose + +```bash +sudo apt-get update +sudo apt-get install -y ca-certificates curl gnupg +sudo install -m 0755 -d /etc/apt/keyrings +curl -fsSL https://download.docker.com/linux/ubuntu/gpg \ + | sudo gpg --dearmor --yes -o /etc/apt/keyrings/docker.gpg +sudo chmod a+r /etc/apt/keyrings/docker.gpg +echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" \ + | sudo tee /etc/apt/sources.list.d/docker.list >/dev/null +sudo apt-get update +sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin +sudo usermod -aG docker "$USER" +newgrp docker +docker compose version +``` + +### 2. Put the code on the server + +```bash +sudo mkdir -p /opt/glenloch-media +sudo chown "$USER":"$USER" /opt/glenloch-media +git clone https://git.maple-street.net/bhursey/glenloch-media.git /opt/glenloch-media +cd /opt/glenloch-media +``` + +For a private repository, configure a read-only deploy key or access token in your Git host instead of embedding a password in the clone URL. Keep the checkout on `main`. + +### 3. Create the environment file + +```bash +cp .env.example .env +chmod 600 .env +openssl rand -base64 32 # NEXTAUTH_SECRET +openssl rand -hex 32 # CRON_SECRET +openssl rand -hex 24 # POSTGRES_PASSWORD (hex avoids URL encoding) +``` + +Edit `.env`. Minimum production values: + +```dotenv +NEXTAUTH_URL=https://media.example.org +NEXTAUTH_SECRET= +PUBLIC_ORIGIN=https://media.example.org +APP_ORIGIN=https://media.example.org + +APP_BIND=127.0.0.1 +POSTGRES_BIND=127.0.0.1 +POSTGRES_USER=media +POSTGRES_PASSWORD= +POSTGRES_DB=media +DATABASE_URL=postgres://media:@localhost:5433/media + +CHURCH_TIMEZONE=America/New_York +AUTO_ACTIVATE_NEW_USERS=false +ALLOW_DEV_RESET=false + +# Bootstrap only. Set to false before exposing the app (step 5). +MAGIC_LINK_DEV_TRANSPORT=true + +CRON_SECRET= +POSTMARK_FROM=media@example.org +# POSTMARK_SERVER_TOKEN=... # optional; Gmail can be configured in Admin instead +``` + +Notes: + +- `NEXTAUTH_URL` and `PUBLIC_ORIGIN` must be the public HTTPS origin. An HTTPS `NEXTAUTH_URL` makes the session cookie `Secure`, so do not sign in over plain HTTP once it is set. +- `POSTGRES_*` is applied when the `pgdata` volume is first initialized. Changing it later does **not** change the existing role; rotate with SQL (`ALTER ROLE`) or recreate the volume. +- `DATABASE_URL` is for host-side CLI commands. Compose builds the app's internal URL from `POSTGRES_*`. +- Back up `NEXTAUTH_SECRET` with the database: it encrypts the stored Gmail app password. + +Validate the rendered Compose configuration before starting: + +```bash +docker compose config --quiet +``` + +### 4. Build, migrate, and start + +```bash +docker compose up -d db +docker compose --profile tools run --rm migrate +docker compose up -d --build app +docker compose ps +curl -fsS http://127.0.0.1:3000/api/health +``` + +`migrate` runs migrations **and the demo seed** (seeded services, sample volunteers, and `admin@glenloch.local`). The seed is idempotent. For a clean production dataset, sign in with the seeded admin, then edit the services and people in Admin; do not re-run the seed after customizing. + +### 5. First sign-in and admin bootstrap + +Keep the app on loopback and use an SSH tunnel for this step: + +```bash +ssh -L 3000:127.0.0.1:3000 you@media.example.org +``` + +Open `http://localhost:3000/login`, request a link for `admin@glenloch.local`, and read it from the page or from `docker compose logs app`. Then: + +1. Admin → People: change the admin name and email to the real person, and create real accounts. +2. Admin → Services: set real service times, roles, and headcounts. +3. Remove or deactivate the seeded demo people. +4. Configure the real sender in Admin → Email delivery (Gmail app password) or set `POSTMARK_SERVER_TOKEN`. + +Only after that, set `MAGIC_LINK_DEV_TRANSPORT=false` in `.env` and restart: + +```bash +docker compose up -d app +``` + +**Do not expose the app publicly while the dev transport is on:** it displays sign-in links in the browser. Keep `APP_BIND=127.0.0.1` until bootstrap is finished. + +### 6. Reverse proxy and TLS with Caddy + +Install Caddy from its official repository: + +```bash +sudo apt-get install -y debian-keyring debian-archive-keyring apt-transport-https curl +curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' \ + | sudo gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg +curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' \ + | sudo tee /etc/apt/sources.list.d/caddy-stable.list >/dev/null +sudo apt-get update +sudo apt-get install -y caddy +``` + +Write `/etc/caddy/Caddyfile` (replace the hostname): + +```caddyfile +media.example.org { + encode zstd gzip + reverse_proxy 127.0.0.1:3000 +} +``` + +```bash +sudo caddy validate --config /etc/caddy/Caddyfile +sudo systemctl reload caddy +sudo systemctl status caddy --no-pager +``` + +Caddy obtains and renews the certificate automatically once DNS and ports 80/443 are correct. Nginx also works: proxy to `http://127.0.0.1:3000` and set a body limit large enough for video uploads. + +### 7. Firewall + +```bash +sudo ufw allow OpenSSH +sudo ufw allow 80/tcp +sudo ufw allow 443/tcp +sudo ufw enable +sudo ufw status +``` + +`APP_BIND=127.0.0.1` and `POSTGRES_BIND=127.0.0.1` keep the app and database off the public interface. + +### 8. Background jobs (cron) + +Create `/usr/local/bin/media-hub-cron`: + +```bash +sudo tee /usr/local/bin/media-hub-cron >/dev/null <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +cd /opt/glenloch-media +secret="$(sed -n 's/^CRON_SECRET=//p' .env | head -1)" +base="http://127.0.0.1:3000" +case "${1:-}" in + notifications) endpoints=(notifications) ;; + daily) endpoints=(instances slots complete) ;; + *) echo "usage: $0 notifications|daily" >&2; exit 2 ;; +esac +for endpoint in "${endpoints[@]}"; do + curl -fsS -H "Authorization: Bearer $secret" "$base/api/dev/cron/$endpoint" >/dev/null +done +EOF +sudo chmod 700 /usr/local/bin/media-hub-cron +``` + +Schedule it in root's crontab (`sudo crontab -e`): + +```cron +*/5 * * * * /usr/local/bin/media-hub-cron notifications +15 3 * * * /usr/local/bin/media-hub-cron daily +``` + +The daily job runs instances → slots → complete in that order. Run the script manually once and check its exit status after changing `.env`. + +### 9. Media archive on NFS (optional) + +Without NFS the app uses the `archive-data` Docker volume, which is included in the admin backup. To store originals and photo archives on a NAS: + +```bash +sudo apt-get install -y nfs-common +sudo mkdir -p /mnt/glenloch-media +sudo mount -t nfs nas.example.org:/export /mnt/glenloch-media +``` + +Persist it in `/etc/fstab`: + +```fstab +nas.example.org:/export /mnt/glenloch-media nfs defaults,_netdev,nofail 0 0 +``` + +Set the host path in `.env`, recreate the app, and verify write access as the container user (UID 100): + +```dotenv +MEDIA_ARCHIVE_DIR=/mnt/glenloch-media +``` + +```bash +docker compose up -d app +docker compose exec app sh -c 'test -w /archive && echo "archive writable"' +``` + +Adjust NFS export ownership or ID mapping so UID 100 can write. Set the archive subfolder in Settings → Media archive (NFS). + +### 10. Email delivery + +Configure one transport in Admin → Email delivery: + +- **Gmail SMTP** — the sending Gmail address plus a Google app password (requires 2FA on that account). The password is stored encrypted with `NEXTAUTH_SECRET`. +- **Postmark** — set `POSTMARK_SERVER_TOKEN` and `POSTMARK_FROM` in `.env`, then `docker compose up -d app`. + +Without either, mail goes to the console transport under `OUTBOX_DIR` and is visible with `docker compose logs app`. Use Admin → Notifications → **Send test** to confirm delivery. + +### 11. Backups + +Use Admin → Backup & restore to download a ZIP of the database dump, uploads, archive, and manifest. Keep copies off the server, and store `.env` (especially `NEXTAUTH_SECRET`) separately with the backup. Restore on a fresh stack through the same admin panel; the database load is one transaction. + +At minimum, back up after every schedule/training/media milestone and before every upgrade. The database, uploads, and archive volumes live under Docker's volume directory; the application-level ZIP is the supported portable backup. + +### 12. Updating the deployment + +Take a backup, then: + +```bash +cd /opt/glenloch-media +git pull --ff-only +docker compose --profile tools run --rm migrate +docker compose up -d --build app +docker compose ps +curl -fsS http://127.0.0.1:3000/api/health +``` + +`migrate` is idempotent and also runs the seed, which does not duplicate authored lessons or existing rows. If a release is bad, rebuild the previous commit: + +```bash +git log --oneline -5 +git checkout +docker compose up -d --build app +# after fixing: +git switch main +``` + +### 13. Health and troubleshooting + +| Symptom | Check | +| --- | --- | +| 502 from Caddy | `docker compose ps` (app should be `healthy`), then `docker compose logs --tail=100 app`. | +| Login link not delivered | `MAGIC_LINK_DEV_TRANSPORT`, Gmail/Postmark configuration, `docker compose logs app`, and the console outbox. | +| `password authentication failed` | `POSTGRES_PASSWORD` changed after the volume was initialized. Use the original role password or rotate it with SQL. Changing the env alone does not update Postgres. | +| Secure-cookie/login loop | `NEXTAUTH_URL` and `PUBLIC_ORIGIN` must exactly match the HTTPS origin in the browser. | +| Wrong links in email | Set `PUBLIC_ORIGIN`; otherwise links derive from the request Host header. | +| Video upload/encode fails | Free disk space, `UPLOAD_DIR` writability, and `docker compose logs app` for FFmpeg errors. | +| Archive unavailable | NFS mount exists on the host, `MEDIA_ARCHIVE_DIR` is set, and UID 100 can write to `/archive`. | +| Cron returns 401 | `CRON_SECRET` is set in `.env` and matches the value read by `/usr/local/bin/media-hub-cron`. | +| Disk filling up | Docker log rotation is capped at 10 MB × 3 per service; remove old backups, exports, and unused media. | + +### 14. Production checklist + +- [ ] `NEXTAUTH_SECRET` generated, backed up, and not reused from development. +- [ ] `PUBLIC_ORIGIN` and `NEXTAUTH_URL` set to the public HTTPS URL. +- [ ] `APP_BIND=127.0.0.1`, `POSTGRES_BIND=127.0.0.1`, and Postgres is not reachable from the internet. +- [ ] `AUTO_ACTIVATE_NEW_USERS=false`, `ALLOW_DEV_RESET=false`, `MAGIC_LINK_DEV_TRANSPORT=false`. +- [ ] Strong, URL-safe `POSTGRES_PASSWORD`; `.env` is mode `600`. +- [ ] TLS certificate issued; HTTP redirects to HTTPS. +- [ ] Gmail/Postmark configured and a test email received. +- [ ] Cron jobs installed and returning success. +- [ ] Backup downloaded, stored off-host, and restore tested once. +- [ ] NFS archive writable (if used). +- [ ] The `/api/dev/*` prefix is historical: the guards, not the URL, are the security boundary. ## Project structure diff --git a/docker-compose.yml b/docker-compose.yml index 9a914b1..584e6c8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -14,7 +14,9 @@ services: dockerfile: Dockerfile environment: NODE_ENV: production - DATABASE_URL: postgres://media:media@db:5432/media + # Built from the POSTGRES_* values in .env. Use a URL-safe password + # (hex is simplest); reserved URL characters must be percent-encoded. + DATABASE_URL: postgres://${POSTGRES_USER:-media}:${POSTGRES_PASSWORD:-media}@db:5432/${POSTGRES_DB:-media} # Fallback base URL only. Generated links (magic link, invite, publish # emails) use the origin of the request that created them, so access via # http://:3000 and https:// both produce working @@ -23,7 +25,9 @@ services: # Secure cookie is rejected by browsers on plain-http LAN access. NEXTAUTH_URL: ${NEXTAUTH_URL:-http://localhost:3000} NEXTAUTH_SECRET: ${NEXTAUTH_SECRET:-dev-only-secret-change-me} - POSTMARK_FROM: media@localhost + POSTMARK_FROM: ${POSTMARK_FROM:-media@localhost} + POSTMARK_SERVER_TOKEN: ${POSTMARK_SERVER_TOKEN:-} + ARCHIVE_FOLDER: ${ARCHIVE_FOLDER:-Glenloch Media} APP_ORIGIN: ${APP_ORIGIN:-http://localhost:3000} # Canonical origin for emailed links. Set this to the public URL when the # app is reachable from outside the LAN; empty means "use the request @@ -56,26 +60,39 @@ services: - uploads-data:/tmp/uploads - ${MEDIA_ARCHIVE_DIR:-archive-data}:/archive ports: - - "${APP_PORT:-3000}:3000" + # Default keeps LAN access working. A proxied host should set + # APP_BIND=127.0.0.1 so only Caddy/Nginx can reach the app. + - "${APP_BIND:-0.0.0.0}:${APP_PORT:-3000}:3000" depends_on: db: condition: service_healthy + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:3000/api/health >/dev/null 2>&1 || exit 1"] + interval: 30s + timeout: 5s + retries: 3 + start_period: 30s + logging: + options: + max-size: "10m" + max-file: "3" restart: unless-stopped db: image: postgres:16-alpine environment: - POSTGRES_USER: media - POSTGRES_PASSWORD: media - POSTGRES_DB: media + POSTGRES_USER: ${POSTGRES_USER:-media} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-media} + POSTGRES_DB: ${POSTGRES_DB:-media} # Host 5433 -> container 5432 (local postgres already holds 5432). # Override POSTGRES_PORT if 5433 is taken by another stack. ports: - - "${POSTGRES_PORT:-5433}:5432" + # Loopback by default: the app reaches Postgres over the Compose network. + - "${POSTGRES_BIND:-127.0.0.1}:${POSTGRES_PORT:-5433}:5432" volumes: - pgdata:/var/lib/postgresql/data healthcheck: - test: ["CMD-SHELL", "pg_isready -U media"] + test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-media} -d ${POSTGRES_DB:-media}"] interval: 5s timeout: 5s retries: 10 @@ -90,7 +107,7 @@ services: target: tools command: ["sh", "-c", "pnpm db:migrate && pnpm db:seed"] environment: - DATABASE_URL: postgres://media:media@db:5432/media + DATABASE_URL: postgres://${POSTGRES_USER:-media}:${POSTGRES_PASSWORD:-media}@db:5432/${POSTGRES_DB:-media} depends_on: db: condition: service_healthy