diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..e093493 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,54 @@ +# Multi-stage Dockerfile for Immich Redaktionsportal +# Node.js 24 Alpine standalone build + +FROM node:24-alpine AS base +RUN corepack enable && corepack prepare pnpm@10.34.5 --activate + +FROM base AS dependencies +WORKDIR /app +COPY package.json pnpm-lock.yaml ./ +RUN pnpm install --frozen-lockfile + +FROM base AS builder +WORKDIR /app +COPY --from=dependencies /app/node_modules ./node_modules +COPY . . + +# Set build-time dummy env vars required for static layout evaluation during next build +ENV NODE_ENV=production +ENV NEXT_TELEMETRY_DISABLED=1 +ENV DATABASE_URL=postgres://portal:portal@localhost:5432/portal +ENV BETTER_AUTH_SECRET=00000000000000000000000000000000 +ENV BETTER_AUTH_URL=http://localhost:3000 +ENV IMMICH_BASE_URL=http://localhost:2283 +ENV IMMICH_API_KEY=build-time-dummy-key +ENV SMTP_HOST=localhost +ENV SMTP_PORT=587 +ENV SMTP_USER=portal@localhost +ENV SMTP_PASSWORD=dummy-password +ENV SMTP_FROM=portal@localhost +ENV LEGAL_IMPRINT_URL=https://example.com/impressum +ENV LEGAL_PRIVACY_URL=https://example.com/datenschutz +ENV LEGAL_TERMS_URL=https://example.com/nutzungsbedingungen + +RUN pnpm build + +FROM node:24-alpine AS runner +WORKDIR /app + +ENV NODE_ENV=production +ENV PORT=3000 +ENV HOSTNAME="0.0.0.0" + +RUN addgroup --system --gid 1001 nodejs && \ + adduser --system --uid 1001 nextjs + +COPY --from=builder /app/public ./public +COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ +COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static + +USER nextjs + +EXPOSE 3000 + +CMD ["node", "server.js"] diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..9e31033 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,56 @@ +services: + portal-db: + image: postgres:17-alpine + container_name: portal-db + restart: unless-stopped + environment: + POSTGRES_DB: ${POSTGRES_DB:-portal} + POSTGRES_USER: ${POSTGRES_USER:-portal} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-change-me} + volumes: + - portal-db-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER:-portal} -d $${POSTGRES_DB:-portal}"] + interval: 5s + timeout: 5s + retries: 5 + networks: + - portal-internal + + portal-app: + build: + context: . + dockerfile: Dockerfile + container_name: portal-app + restart: unless-stopped + ports: + - "3000:3000" + environment: + DATABASE_URL: ${DATABASE_URL:-postgres://portal:change-me@portal-db:5432/portal} + BETTER_AUTH_SECRET: ${BETTER_AUTH_SECRET} + BETTER_AUTH_URL: ${BETTER_AUTH_URL:-http://localhost:3000} + IMMICH_BASE_URL: ${IMMICH_BASE_URL} + IMMICH_API_KEY: ${IMMICH_API_KEY} + SMTP_HOST: ${SMTP_HOST} + SMTP_PORT: ${SMTP_PORT:-587} + SMTP_USER: ${SMTP_USER} + SMTP_PASSWORD: ${SMTP_PASSWORD} + SMTP_FROM: ${SMTP_FROM} + LEGAL_IMPRINT_URL: ${LEGAL_IMPRINT_URL} + LEGAL_PRIVACY_URL: ${LEGAL_PRIVACY_URL} + LEGAL_TERMS_URL: ${LEGAL_TERMS_URL} + depends_on: + portal-db: + condition: service_healthy + networks: + - portal-internal + - immich-net + +volumes: + portal-db-data: + +networks: + portal-internal: + internal: true + immich-net: + external: true diff --git a/docs/operations.md b/docs/operations.md new file mode 100644 index 0000000..35c1739 --- /dev/null +++ b/docs/operations.md @@ -0,0 +1,114 @@ +# Operations Runbook: Immich Redaktionsportal + +This guide documents production deployment, operations, security practices, backup/restore procedures, and maintenance for the Immich Redaktionsportal. + +--- + +## 1. Production Architecture Overview + +The portal runs as a self-hosted Next.js standalone container alongside a dedicated PostgreSQL 17 database. + +- **App Server**: Next.js 16 (Node.js 24 LTS, standalone output). +- **Database**: PostgreSQL 17 (isolated database, separate from Immich). +- **Immich Integration**: Isolated via server-only Immich API adapter using an administrator API key. +- **Mail**: Nodemailer via SMTP (TLS / STARTTLS). + +--- + +## 2. Environment Configuration + +All production configuration is provided via environment variables (e.g. `.env` or Docker secrets). + +| Variable | Description | Example / Notes | +| :--- | :--- | :--- | +| `DATABASE_URL` | PostgreSQL connection string | `postgres://portal:pass@portal-db:5432/portal` | +| `BETTER_AUTH_SECRET` | 32+ character random secret | `openssl rand -hex 32` | +| `BETTER_AUTH_URL` | Public base URL of the portal | `https://presse.example.de` | +| `IMMICH_BASE_URL` | Internal URL to Immich server | `http://immich-server:2283` | +| `IMMICH_API_KEY` | Restricted Immich API key | API key of dedicated Immich service user | +| `SMTP_HOST` | Outbound mail server hostname | `smtp.infomaniak.com` | +| `SMTP_PORT` | Outbound mail server port | `587` (STARTTLS) or `465` (SSL) | +| `SMTP_USER` | SMTP username | `portal@example.de` | +| `SMTP_PASSWORD` | SMTP password | Confidential | +| `SMTP_FROM` | Default From email address | `Leon Tonhäuser Presse ` | +| `LEGAL_IMPRINT_URL` | Public Impressum link | `https://example.de/impressum` | +| `LEGAL_PRIVACY_URL` | Public Datenschutz link | `https://example.de/datenschutz` | +| `LEGAL_TERMS_URL` | Public Nutzungsbedingungen link | `https://example.de/terms` | + +--- + +## 3. Reverse Proxy & Streaming Configuration + +When placing Nginx or Traefik in front of the portal: + +1. **Proxy Buffering**: Disable response buffering for the download stream endpoint (`/api/downloads/[downloadId]/file`) to support direct streaming of original high-resolution photo files: + ```nginx + location /api/downloads/ { + proxy_pass http://localhost:3000; + proxy_buffering off; + proxy_read_timeout 600s; + proxy_send_timeout 600s; + } + ``` +2. **Body Size Limits**: Unused (portal handles photo downloads only, not uploads). +3. **Security Headers**: Managed by Next.js (`next.config.ts`), including restrictive CSP, frame denial (`DENY`), and strict Referrer-Policy. + +--- + +## 4. Immich Service-User Permissions & API Key Setup + +1. Create a dedicated service user in Immich (e.g. `redaktion-service@example.de`). +2. Share **only** administrator-approved editorial albums read-only with this user. +3. Generate an API Key for the user with only the following scopes: + - `album.read` + - `asset.read` + - `asset.view` + - `asset.download` +4. Test API access against Immich endpoints before deploying. + +--- + +## 5. Database Migrations + +Database schema migrations are managed via Drizzle Kit. + +- **Apply Migrations**: + ```bash + pnpm drizzle-kit migrate + ``` +- Migrations must be executed prior to starting a new app container version. + +--- + +## 6. Backup & Restore Procedures + +### Nightly Backup Drill + +Use `scripts/backup-db.sh` in a daily cron job: +```bash +0 2 * * * /path/to/portal/scripts/backup-db.sh /var/backups/immich-portal >> /var/log/portal-backup.log 2>&1 +``` + +### Restore Procedure + +To restore from a `.dump` file created by `backup-db.sh`: +```bash +# 1. Stop the application container to prevent writes +docker compose stop portal-app + +# 2. Restore database from dump file +docker exec -i portal-db pg_restore -U portal -d portal --clean --if-exists < /path/to/backup.dump + +# 3. Restart application container +docker compose start portal-app +``` + +--- + +## 7. Operational Maintenance Tasks + +- **API Key Rotation**: Generate a new key in Immich, update `IMMICH_API_KEY` in environment/secrets, and restart `portal-app`. +- **Health Verification**: + - `GET /api/health/live` -> 200 OK (Process liveness). + - `GET /api/health/ready` -> 200 OK (Database & Immich connectivity). +- **Audit Log Inspection**: Accessible in portal UI under `/admin/audit` (Admin role required). diff --git a/scripts/backup-db.sh b/scripts/backup-db.sh new file mode 100755 index 0000000..97503c8 --- /dev/null +++ b/scripts/backup-db.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +set -euo pipefail + +# ----------------------------------------------------------------------------- +# Database Backup Script for Immich Redaktionsportal +# Usage: ./scripts/backup-db.sh /path/to/backup/directory +# ----------------------------------------------------------------------------- + +OUT_DIR="${1:-}" + +if [[ -z "${OUT_DIR}" ]]; then + echo "Error: Backup output directory argument is required." >&2 + echo "Usage: $0 /path/to/backup-dir" >&2 + exit 1 +fi + +# Normalize path +OUT_DIR="$(cd "${OUT_DIR}" 2>/dev/null && pwd || echo "${OUT_DIR}")" + +# Safety checks: reject root, HOME directory, or empty path +if [[ "${OUT_DIR}" == "/" ]]; then + echo "Error: Refusing to write backup directly to root directory '/'." >&2 + exit 1 +fi + +if [[ -n "${HOME:-}" && "${OUT_DIR}" == "${HOME}" ]]; then + echo "Error: Refusing to write backup directly to home directory '${HOME}'." >&2 + exit 1 +fi + +mkdir -p "${OUT_DIR}" + +TIMESTAMP="$(date -u +"%Y%m%d_%H%M%SZ")" +BACKUP_FILE="${OUT_DIR}/portal_backup_${TIMESTAMP}.dump" + +echo "Starting database backup to ${BACKUP_FILE}..." + +if command -v docker >/dev/null 2>&1 && docker ps --format '{{.Names}}' | grep -q '^portal-db$'; then + echo "Backing up via portal-db Docker container..." + docker exec -t portal-db pg_dump -U "${POSTGRES_USER:-portal}" -d "${POSTGRES_DB:-portal}" --format=custom > "${BACKUP_FILE}" +elif [[ -n "${DATABASE_URL:-}" ]]; then + echo "Backing up via local pg_dump using DATABASE_URL..." + pg_dump --format=custom --dbname="${DATABASE_URL}" > "${BACKUP_FILE}" +else + echo "Error: Neither portal-db docker container nor DATABASE_URL environment variable is available." >&2 + exit 1 +fi + +echo "Backup complete: ${BACKUP_FILE} ($(du -h "${BACKUP_FILE}" | cut -f1))" diff --git a/src/app/api/health/ready/readiness-handler.ts b/src/app/api/health/ready/readiness-handler.ts new file mode 100644 index 0000000..7f5b0e1 --- /dev/null +++ b/src/app/api/health/ready/readiness-handler.ts @@ -0,0 +1,56 @@ +import "server-only"; + +import { sql } from "drizzle-orm"; +import { NextResponse } from "next/server"; + +import { db } from "@/db/client"; +import { immichClient } from "@/modules/immich/client"; + +export type ReadinessCheckers = { + checkDb: () => Promise; + checkImmich: () => Promise; +}; + +export function createReadinessRoute(checkers?: Partial) { + return async function GET() { + let dbOk = false; + let immichOk = false; + + try { + dbOk = checkers?.checkDb + ? await checkers.checkDb() + : await (async () => { + await db.execute(sql`SELECT 1`); + return true; + })(); + } catch { + dbOk = false; + } + + try { + immichOk = checkers?.checkImmich + ? await checkers.checkImmich() + : await (async () => { + await immichClient.listAlbums(); + return true; + })(); + } catch { + immichOk = false; + } + + const allReady = dbOk && immichOk; + const status = allReady ? "ok" : "not_ready"; + const httpStatus = allReady ? 200 : 503; + + return NextResponse.json( + { + status, + checks: { + database: dbOk ? "ok" : "failed", + immich: immichOk ? "ok" : "failed", + }, + }, + { status: httpStatus }, + ); + }; +} diff --git a/src/app/api/health/ready/route.test.ts b/src/app/api/health/ready/route.test.ts new file mode 100644 index 0000000..f02d56b --- /dev/null +++ b/src/app/api/health/ready/route.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, test } from "vitest"; +import { createReadinessRoute } from "./readiness-handler"; + +describe("GET /api/health/ready", () => { + test("returns 200 ok when database and Immich are healthy", async () => { + const route = createReadinessRoute({ + checkDb: async () => true, + checkImmich: async () => true, + }); + const response = await route(); + expect(response.status).toBe(200); + await expect(response.json()).resolves.toEqual({ + status: "ok", + checks: { database: "ok", immich: "ok" }, + }); + }); + + test("returns 503 when database is unreachable", async () => { + const route = createReadinessRoute({ + checkDb: async () => false, + checkImmich: async () => true, + }); + const response = await route(); + expect(response.status).toBe(503); + await expect(response.json()).resolves.toEqual({ + status: "not_ready", + checks: { database: "failed", immich: "ok" }, + }); + }); + + test("returns 503 when Immich is unavailable", async () => { + const route = createReadinessRoute({ + checkDb: async () => true, + checkImmich: async () => false, + }); + const response = await route(); + expect(response.status).toBe(503); + await expect(response.json()).resolves.toEqual({ + status: "not_ready", + checks: { database: "ok", immich: "failed" }, + }); + }); +}); diff --git a/src/app/api/health/ready/route.ts b/src/app/api/health/ready/route.ts new file mode 100644 index 0000000..4705a44 --- /dev/null +++ b/src/app/api/health/ready/route.ts @@ -0,0 +1,3 @@ +import { createReadinessRoute } from "./readiness-handler"; + +export const GET = createReadinessRoute();