Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(docker): one-command self-host — WP1 complete (Docker + compose) (#79)
Ashiq Hussain Mire931b2bf588a
diff --git a/.dockerignore b/.dockerignorenew file mode 100644index 0000000..cf3b7dd--- /dev/null+++ b/.dockerignore@@ -0,0 +1,57 @@+# .dockerignore — keep the build context (and the builder stage's+# COPY . .) to what the build actually reads. Mirrors .gitignore's+# artifacts plus Docker's own outputs.++# build outputs & caches+.next+.open-next+dev.log+server.log+test-results+playwright-report+coverage++# the database config / runtime files never belong in an image+.env+.env.*+!.env.example++# git & CI+.git+.gitignore+.github++# node tooling local state+node_modules+npm-debug.log*++# local editor / OS noise+.DS_Store+*.swp+.idea+.vscode++# docs & research not read by the build (keeps context small)+docs+research+*.md+!README.md++# the docker files themselves (never COPY'd, avoids cache churn)+Dockerfile+docker-compose.yml+.dockerignore++# playwright / test rigs+tests+playwright*.config.ts+playwright.plugins.config.ts+playwright.stockvideo.config.ts++# scripts not needed inside the image (patch-prisma-wasm.mjs and+# build.mjs ARE needed — they run in deps/builder stages; the+# entrypoint is COPY'd explicitly)+scripts/verify-*+scripts/*-e2e.sh+scripts/debug-*+scripts/qa-*diff --git a/.env.docker.example b/.env.docker.examplenew file mode 100644index 0000000..c54ccbe--- /dev/null+++ b/.env.docker.example@@ -0,0 +1,54 @@+# Canvix Docker self-host — environment file+#+# cp .env.docker.example .env (next to docker-compose.yml)+# edit POSTGRES_PASSWORD, then: docker compose up -d+#+# App → http://localhost:3000 (migrations run automatically on+# boot; the 366-template library syncs itself from code — there is+# no seed step).++# ── Required ─────────────────────────────────────────────────────+# Password for the compose Postgres. Generate one:+# openssl rand -hex 24+# (Used only inside the compose network; the app connects with it.)+POSTGRES_PASSWORD=change-me-to-a-long-random-secret++# ── Database override (rarely needed) ────────────────────────────+# By default the app talks to the compose "db" service:+# postgresql://canvix:${POSTGRES_PASSWORD}@db:5432/canvix?sslmode=disable+# To use your OWN Postgres (Supabase/Neon/RDS/external), set+# DATABASE_URL here and comment out the db service in+# docker-compose.yml (plus the app's depends_on). Hosted URLs work+# as-is — Canvix auto-applies TLS/pooler flags (src/lib/db-url.ts).+# DATABASE_URL=postgresql://user:pass@host:5432/canvix++# Host port for the app (default 3000). Change if 3000 is taken:+# CANVIX_PORT=3000++# ── Optional integrations (all default off; the app degrades+# honestly without them — see .env.example for the full+# reference of every variable and what it unlocks) ────────────+# AI provider (Magic Layers, Assistant, Magic Write, image gen…):+# ZAI_BASE_URL=https://your-provider.example/v1+# ZAI_API_KEY=your-key++# Stock video (Pexels/Pixabay) + sound (Freesound) search:+# PEXELS_API_KEY=+# PIXABAY_API_KEY=+# FREESOUND_API_KEY=++# AI agents / MCP endpoint (POST /api/mcp):+# CANVIX_MCP_TOKEN=change-me-to-a-long-random-secret++# Plugins (third-party sandboxed iframe apps):+# CANVIX_PLUGINS=1++# Admin bootstrap (comma-separated usernames promoted on first+# login — see docs/ADMIN.md):+# CANVIX_ADMIN_USERS=your-username++# Rate limits / observability / template-sync opt-out:+# CANVIX_RATE_LIMITS=off+# CANVIX_LOG=requests+# CANVIX_ERROR_WEBHOOK_URL=+# CANVIX_TEMPLATE_SYNC=0diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9a40a3f..599e8dc 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -174,3 +174,93 @@ jobs:path: test-results/if-no-files-found: ignoreretention-days: 7++ # ── Docker self-host smoke: every PR + main ─────────────────────+ # WP1 (deployment & API trust). Proves the operator story end to+ # end on every PR: `docker compose up` from a clean checkout must+ # produce a migrated, seeded, serving Canvix — the exact promise+ # docs/DOCKER.md makes. Builds the production image (multi-stage,+ # standalone) and drives the real containers:+ #+ # pg17 + app → migrate-on-boot → /api/health ok:true (which+ # asserts reachable + migrated + seeded, incl. the boot-time+ # template sync) → register an account through the real route+ # (scrypt + session + cookies, the full auth rail) → landing+ # page serves → compose down.+ #+ # Kept separate from lint-unit/e2e: no Node setup, no npm ci —+ # everything inside the image. Runs on ubuntu-latest's own Docker.+ docker:+ name: docker+ runs-on: ubuntu-latest+ timeout-minutes: 25+ steps:+ - name: Checkout+ uses: actions/checkout@v7++ # POSTGRES_PASSWORD is the only required variable. Compose's+ # ${VAR:?msg} interpolation fires on EVERY compose command —+ # `build` included — so the .env must exist before any of them+ # (the first CI run failed exactly here: build before .env).+ - name: Write the compose .env+ run: echo "POSTGRES_PASSWORD=ci-smoke-password" > .env++ - name: Build the app image (multi-stage, standalone)+ run: docker compose build app++ - name: Bring the stack up (pg17 + app, migrate-on-boot)+ run: |+ docker compose up -d --wait+ # --wait: blocks until both containers are healthy, i.e.+ # the entrypoint already ran migrate deploy + the server+ # answered /api/health inside the container healthcheck.++ - name: Assert /api/health is fully green (migrated + seeded)+ run: |+ for i in $(seq 1 30); do+ BODY=$(curl -fsS http://localhost:3000/api/health 2>/dev/null) && break+ sleep 2+ done+ echo "health: $BODY"+ # heredoc-fed python: no shell interpolation headaches. The+ # compose db hostname "db" classifies as remote (only+ # localhost is local) — expected inside the compose network.+ BODY="$BODY" python3 - <<'PY'+ import json, os+ body = json.loads(os.environ["BODY"])+ assert body.get("ok") is True, f"health not ok: {body}"+ db = body.get("database", {})+ assert db.get("kind") == "remote" and db.get("host") == "db", f"unexpected db: {db}"+ templates = body.get("templates", 0)+ assert templates >= 300, f"template library did not sync on boot: {templates}"+ print(f"health green: {templates} templates, db host {db.get('host')}")+ PY++ - name: Register an account through the real route+ run: |+ RESP=$(curl -sS -o /tmp/reg.json -c /tmp/reg-cookies.txt -w '%{http_code}' \+ -H 'Content-Type: application/json' \+ -d '{"username":"docker-smoke","password":"ci-smoke-passphrase-1"}' \+ http://localhost:3000/api/auth/register)+ echo "register: $RESP $(cat /tmp/reg.json)"+ [ "$RESP" = "201" ] || { echo "register failed"; exit 1; }+ # and the session cookie it issued actually authenticates+ AUTH=$(curl -sS -o /tmp/me.json -b /tmp/reg-cookies.txt -w '%{http_code}' \+ http://localhost:3000/api/auth/me)+ echo "me (with session): $AUTH $(cat /tmp/me.json)"+ [ "$AUTH" = "200" ] || { echo "session did not authenticate"; exit 1; }++ - name: Landing page serves+ run: |+ CODE=$(curl -sS -o /dev/null -w '%{http_code}' http://localhost:3000/)+ echo "landing: $CODE"+ [ "$CODE" = "200" ]++ - name: Assert the stack is clean after down+ if: always()+ run: |+ # .env must exist for ANY compose command (the required-+ # variable interpolation above) — re-create it in case an+ # earlier step failed before the Write step ran+ [ -f .env ] || echo "POSTGRES_PASSWORD=ci-smoke-password" > .env+ docker compose down -v --remove-orphansdiff --git a/.gitignore b/.gitignoreindex 0e59727..a936c21 100644--- a/.gitignore+++ b/.gitignore@@ -33,6 +33,7 @@ yarn-error.log*# env files (can opt-in for committing if needed).env*!.env.example+!.env.docker.example# vercel.verceldiff --git a/CHANGELOG.md b/CHANGELOG.mdindex ef69968..14a0596 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,39 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).### Added+- **Docker self-hosting (WP1: deployment & API trust)** — the+ one-command self-host the roadmap promised: `cp+ .env.docker.example .env`, set `POSTGRES_PASSWORD`, `docker+ compose up -d` → Canvix + Postgres 17, app on :3000, migrations+ applied automatically on boot, the 366-template library syncing+ itself from code on first boot (no seed step, no Node toolchain,+ no host build). The image is a three-stage build+ (`deps → builder → runner`) around the same `.next/standalone`+ artifact every self-hosted Node deploy already uses — Docker is+ just another consumer of it. The runner stays non-root (uid 1001)+ with dumb-init PID 1 (`docker stop` drains in-flight requests) and+ carries exactly one native binary: the Prisma schema-engine, in an+ isolated `/opt/migrate` toolchain the entrypoint uses for+ migrate-on-boot (the app itself is rust-free — engineType="client"+ compiles queries to WASM at runtime). Two Docker-specific traps+ handled and documented: `HOSTNAME` injection (the standalone+ server binds `process.env.HOSTNAME || 0.0.0.0` — the container id+ would kill it) and db-url.ts's TLS-forcing for non-localhost+ hosts (the compose URL pins `?sslmode=disable` for the in-network+ `db` hostname). The migrate toolchain carries the same `effect`+ override as the app (Dependabot #9) with an install-time assertion+ — a vulnerable effect in the image is a build error, not a silent+ regression. Pre-migration databases (tables, no history)+ auto-baseline against `0001_init`, ported from db-setup.sh's+ documented recovery. `CANVIX_RUN_MIGRATIONS=0` opts out for+ multi-replica deploys where a separate job owns migrations. CI+ gains a **docker job on every PR**: build the image, compose up,+ assert `/api/health` fully green (migrated + seeded — proving+ migrate-on-boot and the template sync), register an account+ through the real route (scrypt + session round-trip), landing+ 200, down. Local daemon-free verification:+ `scripts/test-migrate-toolchain.sh`. Full operator guide:+ `docs/DOCKER.md`.- **REST API + scoped API keys (Wave 6 core)** — the `/api/v1` RESTrail. Users create `cvx_…` bearer keys in Settings → Profile & AIkeys → API keys: pick a label and scopes (`designs:read`,diff --git a/Dockerfile b/Dockerfilenew file mode 100644index 0000000..7fe0154--- /dev/null+++ b/Dockerfile@@ -0,0 +1,150 @@+# syntax=docker/dockerfile:1+# ─────────────────────────────────────────────────────────────────+# Canvix — Docker image (WP1: deployment & API trust)+#+# WHAT YOU GET+# A single-image, two-container self-host: this app image plus any+# Postgres 17 (docker-compose.yml wires both). One command, no+# Node toolchain on the host, no build step for the operator.+#+# docker compose up -d → app on http://localhost:3000,+# migrations applied automatically on+# boot, template library syncing itself+# from code (no seed step)+#+# SHAPE (multi-stage, three stages)+#+# deps — npm ci (the lockfile is the contract). postinstall+# runs `prisma generate` + scripts/patch-prisma-wasm.mjs+# exactly like a contributor machine, so the generated+# client and the patched runtime land here.+#+# builder — `npm run build` (next build + the standalone copy+# steps in scripts/build.mjs, which already place+# .next/static and public/ inside .next/standalone).+# Docker is just another consumer of the artifact+# every self-hosted Node deploy already uses.+#+# runner — node:22-slim (bookworm) + only what the server needs:+# the standalone tree (server.js, traced node_modules —+# sharp, pg, @prisma/client + wasm), the prisma/ dir+# (schema + migrations) and a small /opt/migrate+# toolchain for `prisma migrate deploy` at boot. No+# build toolchain, no devDependencies, no bundler.+#+# WHY THE PRISMA SPLIT WORKS+# The app is rust-free (engineType="client": the generated client+# compiles queries to WASM at runtime — prisma/schema.prisma).+# Only `prisma migrate deploy` runs a native binary (the+# schema-engine, ~40 MB, prebuilt for debian-openssl-3.0.x on+# x64 and aarch64), and only at boot. So the runner carries+# exactly one native piece: the migration engine.+#+# BASE IMAGE+# node:22-slim bookworm: Prisma ships the schema-engine for+# debian-openssl-3.0.x; slim keeps the glibc + openssl 3 the+# binary needs. The CI wall (lint-unit, e2e) runs Node 22 — the+# runner matches the tested version.+# ─────────────────────────────────────────────────────────────────++# ── 1. deps ───────────────────────────────────────────────────────+FROM node:22-slim AS deps+WORKDIR /app++# postinstall needs these: `prisma generate` reads prisma/schema.+# prisma, patch-prisma-wasm.mjs patches what it generates. Anything+# else in the context would just bust the layer cache.+COPY package.json package-lock.json ./+COPY prisma/schema.prisma prisma/schema.prisma+COPY scripts/patch-prisma-wasm.mjs scripts/patch-prisma-wasm.mjs+RUN npm ci --no-audit --no-fund \+ # fail LOUDLY if the generated client / wasm patch did not land —+ # a silently skipped postinstall must be a build error here, not a+ # runtime 500 on every DB route+ && test -f src/generated/prisma/internal/class.ts \+ && grep -q "WebAssembly.compile" src/generated/prisma/internal/class.ts \+ || (echo "✗ prisma generate / wasm patch did not run — is postinstall intact?" && exit 1)++# ── 2. builder ────────────────────────────────────────────────────+FROM node:22-slim AS builder+WORKDIR /app++# scripts/build.mjs branches on WORKERS_CI (Cloudflare Workers+# Builds) — Docker is the plain standalone path, so pin it off.+COPY --from=deps /app/node_modules ./node_modules+COPY --from=deps /app/src/generated ./src/generated+COPY . .+ENV WORKERS_CI=+RUN npm run build \+ && test -f .next/standalone/server.js \+ || (echo "✗ next build did not emit .next/standalone" && exit 1)++# ── 3. runner ─────────────────────────────────────────────────────+FROM node:22-slim AS runner+WORKDIR /app++# dumb-init: PID 1 signal handling (SIGTERM reaches node, so+# `docker stop` drains in-flight requests instead of the 10 s kill).+# curl: the container healthcheck. From the slim image's own+# bookworm apt — no extra repos.+RUN apt-get update \+ && apt-get install -y --no-install-recommends dumb-init curl ca-certificates \+ && rm -rf /var/lib/apt/lists/*++# Non-root. The app persists everything to Postgres (media included:+# bytea columns, not files), so /app needs no writable subvolume.+RUN groupadd --system --gid 1001 canvix \+ && useradd --system --uid 1001 --gid canvix canvix++# The standalone server Next's tracer assembled — server.js, the+# traced node_modules (sharp, pg, @prisma/client + wasm) AND (from+# scripts/build.mjs) .next/static + public/ inside it. One copy.+COPY --from=builder --chown=canvix:canvix /app/.next/standalone ./++# /opt/migrate: the prisma CLI toolchain for migrate-on-boot+# (docker-entrypoint.sh). Installed from its own minimal+# package.json so it CANNOT pull the app's dependency tree, pinned+# to the exact CLI version package-lock.json carries, and carrying+# the same effect override as the app — the @prisma/config→effect+# pin is why Dependabot #9 needed an override in the first place;+# without it the image would boot a known-vulnerable effect on+# every start. The trailing node check makes a regression loud.+RUN mkdir -p /opt/migrate \+ && cd /opt/migrate \+ && printf '%s\n' \+ '{' \+ ' "name": "canvix-migrate",' \+ ' "private": true,' \+ ' "description": "isolated prisma migrate-deploy toolchain (see Dockerfile)",' \+ ' "overrides": { "@prisma/config": { "effect": "^3.22.1" } }' \+ '}' > package.json \+ && npm install --no-audit --no-fund [email protected] \+ # the app never uses the library engine (engineType="client"), so+ # the CLI's downloaded query-engine .so is dead weight in the image+ && rm -f node_modules/@prisma/engines/libquery_engine-*.so.node \+ && node -e "const v=require('effect/package.json').version;const p=v.split('.').map(Number);if(p[0]!==3||p[1]<22){console.error('effect '+v+' — override did not apply (Dependabot #9 regression)');process.exit(1)}console.log('effect override ok: '+v)" \+ && test -x node_modules/@prisma/engines/schema-engine-debian-openssl-3.0.x \+ || (echo "✗ migrate toolchain install failed" && exit 1)++# schema + migrations for migrate deploy; the entrypoint runs the+# CLI from /opt/migrate/node_modules/.bin/prisma+COPY --chown=canvix:canvix prisma ./prisma+COPY --chown=canvix:canvix docker-entrypoint.sh ./docker-entrypoint.sh+RUN chmod +x docker-entrypoint.sh++# The standalone server binds process.env.HOSTNAME || 0.0.0.0 — but+# Docker sets HOSTNAME to the container id, which server.js would try+# (and fail) to bind. The entrypoint re-asserts it; the ENV is the+# default for anyone exec-ing a shell in the image.+ENV NODE_ENV=production \+ HOSTNAME=0.0.0.0 \+ PORT=3000++USER canvix+EXPOSE 3000++HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \+ CMD curl -fsS "http://127.0.0.1:${PORT}/api/health" || exit 1++ENTRYPOINT ["dumb-init", "--"]+CMD ["/app/docker-entrypoint.sh"]diff --git a/README.md b/README.mdindex 9f75574..18404ba 100644--- a/README.md+++ b/README.md@@ -518,6 +518,11 @@ Canvix runs on **any Node host** and — since v0.9.3 — on **CloudflareWorkers** too, and — since v0.9.4 — on **Netlify**. Same codebase, samedatabase, zero config divergence.+**Fastest self-host (Docker)?** `cp .env.docker.example .env`, set+`POSTGRES_PASSWORD`, `docker compose up -d` → app + Postgres 17 with+migrations applied on boot — the full story in+[`docs/DOCKER.md`](docs/DOCKER.md).+**Running it long-term?** Two operations guides shipped with v0.12.4:[`docs/BACKUP-AND-RESTORE.md`](docs/BACKUP-AND-RESTORE.md) — theone-command `pg_dump` backup, a restore drill executed and verifieddiff --git a/ROADMAP.md b/ROADMAP.mdindex e1744ac..2b54313 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -102,6 +102,7 @@ Not in the original plan, forced by operating canvix.app in production:| — | v0.23.1 patch: admin video-slot save fix (the `SLOT_ORDER` omission), BYOK failure hints on all five AI surfaces, the missing `/test` route shipped (a `.gitignore` casualty) | ✅ | v0.23.1 || — | v0.23.2 patch: the admin "Test video generation" button answered `Unknown slot` (v0.16-era slot lists never learned the v0.19 video slot) — fixed + 9 regression tests | ✅ | v0.23.2 || — | **WebP export** — the fourth raster format (Wave 5 remainder): browser-native encoder, feature-detected card (hidden where the canvas lies — Safari's silent PNG fallback), honest-degradation guard on the captured bytes, 1×/2×/3× + all-pages parity with PNG/JPG | ✅ | Unreleased (Wave 5 slice) |+| — | **Docker/compose self-hosting (WP1 completion)** — the one-command self-host: three-stage image around the standalone artifact, migrate-on-boot entrypoint (P3005 auto-baseline), boot-time template sync, compose pg17 + app, CI docker job on every PR (health + register + landing through the real containers) | ✅ | Unreleased (WP1) |### 2.3 Where that leaves the numbers@@ -129,13 +130,13 @@ Not in the original plan, forced by operating canvix.app in production:| WP | Scope | Absorbs | Effort | v1.0 unblocks ||---|---|---|---|---|-| **WP1 — Deployment & API trust** | Docker image + compose file (Postgres + app, single `docker compose up`) · scoped API keys for self-hosters (read-only/read-write per key, revocable) | Wave 6 core (Docker), Wave 6 (scoped keys via the MCP-rail model) | M (~100 h) | Docker/compose is the single most-asked self-hoster item; the M-block and every deployment story after it get cheaper |+| **WP1 — Deployment & API trust** ✅ | ~~Docker image + compose file (Postgres + app, single `docker compose up`)~~ · ~~scoped API keys for self-hosters (read-only/read-write per key, revocable)~~ — **complete**: API keys shipped as PR #77 (v0.24); Docker/compose shipped with the three-stage standalone image, migrate-on-boot entrypoint, CI docker job (`docs/DOCKER.md`) | Wave 6 core (Docker), Wave 6 (scoped keys via the MCP-rail model) | M (~100 h) — done | Docker/compose was the single most-asked self-hoster item; every deployment story after this is cheaper || **WP2 — Real-time collaboration at scale** | Postgres `LISTEN/NOTIFY` → in-process hub → SSE fan-out (kills the per-connection poll loop) · **op-level undo broadcast** that preserves concurrent remote edits rather than clobbering them (undo syncs as ops, not `pages:replace`) — building on the HLC last-write-wins merge + deletion tombstones shipped in v0.10.0 | M4 + M6 | M/L (~120 h) | The scaling wall (~0.31–1.25 q/s per client); live-session correctness for shared editing || **WP3 — Accessible mobile & touch editing** | Touch-first editing with accessible pointer/touch semantics — large handles, 1-finger drag vs 2-finger pan, double-tap zoom, long-press menu, handle/target sizing to WCAG pointer-target minimums · bottom-sheet properties on mobile · responsive layout verification across breakpoints; pairs with WP5's S2 audit. Deep gesture polish (pinch-rotate, momentum pan, edge-pinch) stays on the project's own cadence, outside the funded scope | M1 + M2 + M3 — **the last unchecked README promise** | M (~60 h) | Closes the displaced v0.16 mobile block; parity with Canva mobile web, on accessible terms || **WP4 — Sharing roles & portability** | Share links with view/comment/edit roles (+ optional password & expiry) · `.canvix` portable project file — a **documented, open archive format** (design JSON + embedded media, single-file backup/transfer). Vector-text PDF (v0.15.3) and native editable PPTX (v0.21.0) already shipped — they are the export track record this WP extends, not its scope | Wave 5 remainder (share roles, `.canvix`) | M (~80 h) | The feature the competitive matrix scores hardest against Canva; the backup story self-hosters ask for || **WP5 — v1.0 quality gate** | S1–S4 stabilization only: performance budgets in CI (S1) · **WCAG keyboard/screen-reader accessibility audit** (S2) · self-hoster handbook (S3) · the 1.0 definition pass + tag (S4). **Funded scope contains zero AI code of any kind** — both the `z-ai-web-dev-sdk` removal and the provider-neutral adapter sit outside the grant: removing the SDK means writing the direct OpenAI-compatible client, which is AI connector work, and NLnet's FAQ is explicit that connectors stay out of funded scope. Both proceed as unfunded project work on their own cadence | §4.5 (S1–S4) | M (~60 h: S1 25 + S2 20 + S3 10 + S4 5) | The gate itself: the audited, budgeted, documented core — then tag v1.0.0 |-**Sequencing:** WP1 → WP2 → WP3 → WP4 → WP5 — deployment trust first (every later WP ships to a reproducible environment), the scaling wall before the traffic that mobile brings, sharing after the sessions it serves are correct, and the stabilization gate last, wrapping v1.0. Each WP lands as minor releases with the full CI wall + docs + export-parity checks per the standing acceptance bar. **Funding boundary:** the funded scope is WP1–WP4 plus WP5's S1–S4 — **420 h ≈ €12,600 at €30/h cost-recovery (~21 weeks at 20 h/week)**, labour-only: no hardware line (NLnet's external-spending policy excludes regular workstation upgrades as basic operational IT cost), no AI subscriptions (non-reimbursable). The entire AI-provider track — SDK removal and adapter together, ~65 h — is deliberately unfunded and proceeds on the project's own cadence.+**Sequencing:** WP1 ✅ → WP2 → WP3 → WP4 → WP5 — deployment trust first (**done**: every later WP ships to a reproducible environment), the scaling wall before the traffic that mobile brings, sharing after the sessions it serves are correct, and the stabilization gate last, wrapping v1.0. Each WP lands as minor releases with the full CI wall + docs + export-parity checks per the standing acceptance bar. **Funding boundary:** the funded scope is WP1–WP4 plus WP5's S1–S4 — **420 h ≈ €12,600 at €30/h cost-recovery (~21 weeks at 20 h/week)**, labour-only: no hardware line (NLnet's external-spending policy excludes regular workstation upgrades as basic operational IT cost), no AI subscriptions (non-reimbursable). The entire AI-provider track — SDK removal and adapter together, ~65 h — is deliberately unfunded and proceeds on the project's own cadence.**Recently landed (context for the WPs):**@@ -186,7 +187,7 @@ Only the PPTX slice shipped. Remaining scope, in recommended order:This is the largest *new* surface, and the audit's biggest measured deficit (Accounts & platform, Collaboration). Suggested cuts:-- **Core (do these):** email + password reset · comment @mentions (overlaps M5) · per-user undo in shared sessions (overlaps M6) · object edit locks · Docker/compose self-hosting (the single most-asked self-hoster item) · ~~REST API + scoped API keys~~ **✅ shipped v0.24** — `cvx_…` bearer keys (sha256-stored, shown once, revocable; scopes `designs:read`/`designs:write`), `GET /api/v1/designs` (+`/[id]`) keyset-paginated and owner-scoped, profile-page management UI, `docs/API.md`. The MCP rail proved the model; this is it for people.+- **Core (do these):** email + password reset · comment @mentions (overlaps M5) · per-user undo in shared sessions (overlaps M6) · object edit locks · ~~Docker/compose self-hosting (the single most-asked self-hoster item)~~ **✅ shipped (WP1)** — three-stage standalone image, compose pg17 + app, migrate-on-boot entrypoint, CI docker job on every PR (`docs/DOCKER.md`) · ~~REST API + scoped API keys~~ **✅ shipped v0.24** — `cvx_…` bearer keys (sha256-stored, shown once, revocable; scopes `designs:read`/`designs:write`), `GET /api/v1/designs` (+`/[id]`) keyset-paginated and owner-scoped, profile-page management UI, `docs/API.md`. The MCP rail proved the model; this is it for people.- **Choose deliberately:** OAuth + OIDC SSO (enterprise ask; the original roadmap's discipline list said "no OAuth" — the audit reopened it; decide once, document it) · i18n framework · light/dark theme toggle · PWA install.- **Stretch (post-1.0):** teams/workspaces, shared brand kits (the `Organization`/`Membership` models from the original §7).- **2FA** — mentioned in the enterprise-wall cluster; TOTP is small and self-contained.@@ -223,7 +224,7 @@ This is the largest *new* surface, and the audit's biggest measured deficit (Acc**The NLnet grant track (§3) is the funded expression of this order — WP1–WP5 in sequence.** Without funding, the same three moves stand, in order:-1. **Wave 6 core slice — Docker/compose + scoped API keys.** The enterprise wall is the biggest measured deficit and Docker is the highest-frequency self-hoster ask. (M-sized each, independent.) *(= WP1)*+1. **Wave 6 core slice — Docker/compose + scoped API keys.** ✅ **done (= WP1, complete)** — API keys shipped v0.24 (PR #77); Docker/compose shipped as the three-stage standalone image + compose + CI docker job (`docs/DOCKER.md`). The next move in this order is #2 below.2. **The M-block, led by M4 (collab fan-out) with M6 (op-level undo).** LISTEN/NOTIFY removes the scaling wall while staying Postgres-only; M1–M3 close the last README promise; M5/M6 double as Wave-6 items. *(= WP2 + WP3)*3. **Wave 5 remainder (share roles first, then `.canvix`).** Roles+password+expiry sharing is the feature the competitive matrix scores hardest against Canva. *(= WP4)*diff --git a/docker-compose.yml b/docker-compose.ymlnew file mode 100644index 0000000..a16475e--- /dev/null+++ b/docker-compose.yml@@ -0,0 +1,67 @@+# docker-compose.yml — the one-command self-host (WP1: deployment+# & API trust).+#+# docker compose up -d+# → http://localhost:3000 (migrations apply automatically on+# boot; the 366-template library syncs itself from code)+#+# Two containers:+# db — Postgres 17 (the only state; Canvix stores media as+# bytea columns, so there is NO app volume — losing the+# app container loses nothing)+# app — the image built from ./Dockerfile+#+# Bringing your own database? Comment the db service out, point+# DATABASE_URL at it and remove depends_on. Supabase / Neon / RDS+# URLs work as-is (src/lib/db-url.ts auto-applies TLS + pooler+# flags). For the compose-internal db the URL pins sslmode=disable+# because db-url.ts would otherwise treat the non-localhost+# hostname "db" as remote and force TLS — which plain Postgres+# does not speak inside the compose network.++services:+ db:+ image: postgres:17+ restart: unless-stopped+ environment:+ POSTGRES_USER: canvix+ POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env — see .env.docker.example}+ POSTGRES_DB: canvix+ volumes:+ - canvix-db:/var/lib/postgresql/data+ healthcheck:+ test: ["CMD-SHELL", "pg_isready -U canvix -d canvix"]+ interval: 5s+ timeout: 5s+ retries: 12++ app:+ build: .+ restart: unless-stopped+ depends_on:+ db:+ condition: service_healthy+ environment:+ # sslmode=disable: the in-network "db" hostname is not+ # localhost, so db-url.ts would force TLS on it — pinned off+ # because compose-internal Postgres is plaintext by design.+ DATABASE_URL: ${DATABASE_URL:-postgresql://canvix:${POSTGRES_PASSWORD}@db:5432/canvix?sslmode=disable}+ # ── optional: copy any of these from .env.docker.example ──+ ZAI_BASE_URL: ${ZAI_BASE_URL:-}+ ZAI_API_KEY: ${ZAI_API_KEY:-}+ PEXELS_API_KEY: ${PEXELS_API_KEY:-}+ PIXABAY_API_KEY: ${PIXABAY_API_KEY:-}+ FREESOUND_API_KEY: ${FREESOUND_API_KEY:-}+ CANVIX_MCP_TOKEN: ${CANVIX_MCP_TOKEN:-}+ CANVIX_PLUGINS: ${CANVIX_PLUGINS:-}+ CANVIX_RATE_LIMITS: ${CANVIX_RATE_LIMITS:-}+ CANVIX_SSE_MAX_PER_IP: ${CANVIX_SSE_MAX_PER_IP:-}+ CANVIX_LOG: ${CANVIX_LOG:-}+ CANVIX_ERROR_WEBHOOK_URL: ${CANVIX_ERROR_WEBHOOK_URL:-}+ CANVIX_TEMPLATE_SYNC: ${CANVIX_TEMPLATE_SYNC:-}+ CANVIX_ADMIN_USERS: ${CANVIX_ADMIN_USERS:-}+ ports:+ - "${CANVIX_PORT:-3000}:3000"++volumes:+ canvix-db:diff --git a/docker-entrypoint.sh b/docker-entrypoint.shnew file mode 100644index 0000000..c77df30--- /dev/null+++ b/docker-entrypoint.sh@@ -0,0 +1,94 @@+#!/bin/sh+# docker-entrypoint.sh — the container's boot sequence (WP1).+#+# 1. wait for the database to accept connections+# 2. prisma migrate deploy (migrations from the image; the P3005+# baseline recovery from scripts/db-setup.sh is ported: a+# database with tables but no migration history gets baselined+# against 0001_init, then migrated the rest of the way)+# 3. exec the standalone Next server as PID 1 (dumb-init's child)+# — its instrumentation hook (src/instrumentation.ts) syncs the+# template library from code on boot, so there is NO seed step+# here: templates appear on first request, idempotent forever.+#+# Design notes:+# - POSIX sh (dash): the runner is slim; no bash assumption.+# - The app itself never needs the prisma CLI — only this script+# does, which is why the CLI lives in /opt/migrate, not /app.+# - HOSTNAME is re-asserted because docker injects HOSTNAME=<cid>+# into every container, and .next/standalone/server.js binds+# process.env.HOSTNAME || '0.0.0.0' — un-overridden, the server+# would try to bind the container id as a hostname and die.+# - CANVIX_RUN_MIGRATIONS=0 skips step 1–2 entirely (operators who+# run migrations as a separate job, e.g. multi-replica deploys+# where replicas must not race `migrate deploy`).++set -u++HOSTNAME=0.0.0.0+export HOSTNAME++MIGRATE_DIR=/opt/migrate+PRISMA="$MIGRATE_DIR/node_modules/.bin/prisma"+SCHEMA=/app/prisma/schema.prisma+# first migration ever — what a pre-migration database is baselined+# against (same value scripts/db-setup.sh defaults to)+BASELINE_MIGRATION="${CANVIX_BASELINE_MIGRATION:-0001_init}"++log() { echo "[entrypoint] $*"; }++# ── migrations ────────────────────────────────────────────────────+if [ "${CANVIX_RUN_MIGRATIONS:-1}" = "0" ]; then+ log "CANVIX_RUN_MIGRATIONS=0 — skipping migrate-on-boot (operator-managed schema)"+else+ # 1. wait for the database: migrate deploy against a not-yet-ready+ # Postgres produces P1001 noise. Up to ~60 s (30 × 2 s), then+ # let migrate deploy fail with its real error instead.+ if [ -n "${DATABASE_URL:-}" ]; then+ i=0+ while [ "$i" -lt 30 ]; do+ if "$PRISMA" db execute --schema "$SCHEMA" \+ --stdin <<'SQL' >/dev/null 2>&1+SELECT 1;+SQL+ then+ break+ fi+ i=$((i + 1))+ sleep 2+ done+ [ "$i" -lt 30 ] || log "WARNING: database still not accepting connections after 60 s — handing off to migrate deploy for the real error"+ fi++ # 2. apply migrations (idempotent: "No pending migrations" on+ # up-to-date databases). P3005 (schema not empty, no history —+ # a pre-migration database) is recovered by baselining, the+ # documented Prisma path scripts/db-setup.sh has used since+ # v0.8.+ log "applying database migrations…"+ if "$PRISMA" migrate deploy --schema "$SCHEMA"; then+ log "migrations: ok"+ else+ rc=$?+ # prisma migrate deploy exits 5 on P3005-shaped failures (and 1+ # on older CLIs) — same recovery envelope as scripts/db-setup.sh+ if [ "$rc" -eq 5 ] || [ "$rc" -eq 1 ]; then+ log "existing schema without migration history detected — baselining $BASELINE_MIGRATION"+ if "$PRISMA" migrate resolve --applied "$BASELINE_MIGRATION" --schema "$SCHEMA" \+ && "$PRISMA" migrate deploy --schema "$SCHEMA"; then+ log "migrations: ok (baselined)"+ else+ log "ERROR: migrate deploy failed and baselining did not apply. If this is a fresh database, check DATABASE_URL. Full diagnosis: start the app anyway (below) and open /api/health"+ # do NOT exit: the server may still serve against a partially+ # migrated database, and /api/health tells the operator what+ # is missing — same philosophy as db-setup.sh's messaging.+ fi+ else+ log "ERROR: migrate deploy failed (exit $rc). Starting anyway — /api/health reports the exact state."+ fi+ fi+fi++# ── the server ────────────────────────────────────────────────────+log "starting canvix on ${HOSTNAME}:${PORT:-3000}"+exec node server.jsdiff --git a/docs/DOCKER.md b/docs/DOCKER.mdnew file mode 100644index 0000000..784ba16--- /dev/null+++ b/docs/DOCKER.md@@ -0,0 +1,176 @@+# Docker self-hosting (WP1: deployment & API trust)++> **TL;DR** — `cp .env.docker.example .env`, set `POSTGRES_PASSWORD`,+> `docker compose up -d` → **http://localhost:3000**. Migrations apply+> automatically on boot; the 366-template library syncs itself from+> code. There is no seed step, no Node toolchain, no build on the host.+>+> ```bash+> git clone https://github.com/mir-ashiq/canvix.git+> cd canvix+> cp .env.docker.example .env+> # edit .env: POSTGRES_PASSWORD=$(openssl rand -hex 24)+> docker compose up -d+> curl http://localhost:3000/api/health # {"ok":true,...}+> ```++This is the single most-requested self-hoster path made one command:+a multi-stage image built from the same standalone artifact every+self-hosted Node deploy already uses, wired to a Postgres 17+container. The CI wall includes a **docker job on every PR** that+builds the image, brings the stack up, and asserts health ++registration through the real routes — the promise in this document+is enforced, not aspirational.++## What the two containers do++| Container | Image | Role |+|---|---|---|+| `db` | `postgres:17` | The only state — designs, versions, accounts, sessions, media (bytea columns; Canvix stores no files, so there is **no app volume**) |+| `app` | built from `./Dockerfile` | The Next.js standalone server + the migrate-on-boot entrypoint |++Only `db` has a volume (`canvix-db`). Losing and recreating the `app`+container loses nothing; upgrade = `git pull && docker compose up -d+--build`, and the entrypoint applies pending migrations before the+server starts (idempotent — "No pending migrations" on an up-to-date+database).++## The boot sequence (what you'll see in `docker compose logs app`)++```+[entrypoint] applying database migrations…+[entrypoint] migrations: ok+[entrypoint] starting canvix on 0.0.0.0:3000+▲ Next.js 16.4.6 …+```++1. **Wait for the database** (up to 60 s; `docker compose up --wait`+ normally makes this a no-op via the `db` healthcheck).+2. **`prisma migrate deploy`** — migrations baked into the image. A+ database with tables but no migration history (pre-migration+ databases) is auto-baselined against `0001_init`, the same+ recovery `npm run db:setup` has used since v0.8.+3. **The standalone server** starts as the entrypoint's exec'd child+ (PID 1 via dumb-init, so `docker stop` drains in-flight requests).+ Its instrumentation hook syncs the built-in template library from+ code — new templates appear on every version upgrade, idempotent+ forever, nothing is ever deleted.++`/api/health` reports the whole story with exact fixes when something+is wrong: env → connect → migrate → seed, each step with its own+error and remedy. Point a browser there first whenever anything+misbehaves.++## Configuration++Everything is environment-driven; compose reads `.env` next to it+(`.env.docker.example` documents every variable). The app **degrades+honestly** without optional keys — no AI keys means the AI features+hide, no stock keys means those rails hide, everything else works.++| Variable | Required | What it does |+|---|---|---|+| `POSTGRES_PASSWORD` | **yes** (compose refuses without it) | Password for the compose Postgres |+| `DATABASE_URL` | no | Override to point at your own Postgres/Supabase/Neon — comment out the `db` service and the app's `depends_on` in `docker-compose.yml`. Hosted URLs work as-is (TLS/pooler flags auto-applied by `src/lib/db-url.ts`) |+| `CANVIX_PORT` | no (3000) | Host port for the app |+| `ZAI_BASE_URL` / `ZAI_API_KEY` | no | AI provider — Magic Layers, Assistant, image gen… |+| `PEXELS_API_KEY` / `PIXABAY_API_KEY` | no | Stock-video search |+| `FREESOUND_API_KEY` | no | Freesound search |+| `CANVIX_MCP_TOKEN` | no | Enables the `/api/mcp` AI-agent endpoint |+| `CANVIX_PLUGINS` | no (`1` to enable) | Third-party sandboxed plugins |+| `CANVIX_ADMIN_USERS` | no | Bootstrap admins (see [`docs/ADMIN.md`](ADMIN.md)) |+| `CANVIX_RATE_LIMITS` | no | `off` when a proxy in front already throttles |+| `CANVIX_RUN_MIGRATIONS` | no (`0` to skip) | Multi-replica deploys where a separate job owns migrations |+| `CANVIX_TEMPLATE_SYNC` | no (`0` to skip) | Operators who curate the template library by hand |++Full variable reference with defaults and interplay:+[`.env.example`](../.env.example) (the non-Docker path's annotated+reference — same variables).++### Using your own database++Compose-internal Postgres is the default; bring your own in three+edits:++```yaml+# docker-compose.yml+# 1. delete/comment the db: service+# 2. delete the app's depends_on: block+# 3. set DATABASE_URL in .env:+# DATABASE_URL=postgresql://user:pass@host:5432/canvix+```++Supabase **transaction pooler** URLs (port 6543) work for the app,+but `migrate deploy` needs the session pooler — `scripts/db-setup.sh`+rewrites the URL for migrations on the Node path. Inside Docker, set+`DATABASE_URL` to the **session/direct** URL (port 5432 style) so both+the migrations and the app run against the same database; Supabase's+IPv4-friendly pooler on 5432 is the practical choice.++### Behind a reverse proxy++Set `PORT`/`CANVIX_PORT` as needed and terminate TLS in your proxy.+The security headers (CSP, HSTS, X-Frame-Options…) ship from+`next.config.ts` on every route. HSTS only starts counting once the+host is served over TLS. Nothing Canvix-side needs changing.++## Operations++- **Backup / restore** — the one-command `pg_dump` story, restore+ drill, and media GC: [`docs/BACKUP-AND-RESTORE.md`](BACKUP-AND-RESTORE.md).+ Docker equivalent: `docker compose exec db pg_dump -U canvix canvix > backup.sql`+- **Upgrades** — `git pull && docker compose up -d --build`. The+ entrypoint's migrate-on-boot makes every upgrade a rolling one; the+ honest rollback caveat (forward-only migrations) is in+ [`docs/UPGRADING.md`](UPGRADING.md).+- **Logs** — `docker compose logs -f app`. `CANVIX_LOG=requests`+ adds one JSON line per API request; everything is off by default+ (a design tool's logs are the self-hoster's to read).+- **Health** — `curl http://localhost:3000/api/health` (liveness) or+ `?v=2` (aggregate counts + DB latency probe). The container+ healthcheck uses the same route.++## Image architecture (for contributors)++Three stages, no build toolchain in the final image (~350 MB):++```+deps npm ci → prisma generate + patch-prisma-wasm (postinstall,+ exactly like a contributor machine); fails LOUDLY if the+ generated client or the wasm patch did not land+builder `npm run build` → .next/standalone (the same artifact every+ self-hosted Node deploy uses — build.mjs already places+ .next/static + public/ inside it)+runner node:22-slim + the standalone tree + prisma/ (schema ++ migrations) + /opt/migrate (the prisma CLI for the+ entrypoint) — non-root (uid 1001), dumb-init PID 1+```++The Prisma split is the interesting part. The app is rust-free+(`engineType="client"`: the generated client compiles queries to WASM+at runtime — see `prisma/schema.prisma`), so the request path carries+no native binaries at all. Only `prisma migrate deploy` runs one (the+schema-engine, ~40 MB, prebuilt for debian-openssl-3.0.x), and only+at boot — which is why it lives in `/opt/migrate`, isolated from the+app's traced `node_modules`.++The migrate toolchain carries the same `effect` override as the app+(`^3.22.1`, Dependabot #9 / GHSA-7589-6fvf-x4pw): `@prisma/config`+pins `effect` exactly, and the image's install-time assertion makes a+regression a **build error**, not a silently vulnerable container.++Two Docker-specific traps the entrypoint handles, for the record:++- **`HOSTNAME`**: Docker injects `HOSTNAME=<container-id>` into every+ container, and the standalone `server.js` binds+ `process.env.HOSTNAME || '0.0.0.0'` — un-overridden, the server+ would try to bind the container id as a hostname and die. The+ entrypoint (and the image `ENV`) pin it to `0.0.0.0`.+- **TLS-forcing**: `src/lib/db-url.ts` forces `sslmode=require` for+ any non-localhost host — including the compose-internal `db`+ hostname, which speaks plaintext. The compose default URL pins+ `?sslmode=disable` (user-pinned values pass through untouched).++**Local verification without a daemon** (the sandbox has no Docker):+`scripts/test-migrate-toolchain.sh` replays the `/opt/migrate` install+and its assertions; the full container proof is the CI `docker` job.diff --git a/scripts/test-migrate-toolchain.sh b/scripts/test-migrate-toolchain.shnew file mode 100644index 0000000..5044d9a--- /dev/null+++ b/scripts/test-migrate-toolchain.sh@@ -0,0 +1,49 @@+#!/usr/bin/env bash+# test-migrate-toolchain.sh — replicate the Dockerfile's /opt/migrate+# stage locally to prove the prisma migrate-deploy toolchain installs+# and works WITHOUT a Docker daemon:+# 1. the isolated package.json + effect override + [email protected]+# install (exact Dockerfile RUN sequence, incl. the .so removal+# and the version assertions)+# 2. the CLI answers `prisma -v` from that install+# 3. `prisma migrate deploy --schema prisma/schema.prisma` runs+# against a scratch Postgres… which this sandbox doesn't have,+# so step 3's proof rides the CI docker job (documented there).+set -euo pipefail+cd "$(dirname "$0")/.."++SCRATCH=$(mktemp -d /tmp/canvix-migrate-test.XXXXXX)+trap 'rm -rf "$SCRATCH"' EXIT++echo "── installing /opt/migrate toolchain into $SCRATCH (Dockerfile mirror) ──"+cd "$SCRATCH"+printf '%s\n' \+ '{' \+ ' "name": "canvix-migrate",' \+ ' "private": true,' \+ ' "description": "isolated prisma migrate-deploy toolchain (see Dockerfile)",' \+ ' "overrides": { "@prisma/config": { "effect": "^3.22.1" } }' \+ '}' > package.json++npm install --no-audit --no-fund [email protected] > /dev/null 2>&1++# the app never uses the library engine (engineType="client") — same+# dead-weight removal as the Dockerfile+rm -f node_modules/@prisma/engines/libquery_engine-*.so.node++echo "── assertions (the Dockerfile's own, verbatim) ──"+node -e "const v=require('effect/package.json').version;const p=v.split('.').map(Number);if(p[0]!==3||p[1]<22){console.error('effect '+v+' — override did not apply (Dependabot #9 regression)');process.exit(1)}console.log('✓ effect override ok: '+v)"+test -x node_modules/@prisma/engines/schema-engine-debian-openssl-3.0.x \+ && echo "✓ schema-engine binary present + executable" \+ || { echo "✗ schema-engine missing"; exit 1; }++echo "── CLI smoke from the isolated install ──"+DATABASE_URL=postgresql://x:x@localhost:5432/x \+ node_modules/.bin/prisma -v 2>/dev/null | head -3++echo "── migrate deploy against a throwaway URL: must fail with the REAL error (P1001), not a module/engine error ──"+set +e+DATABASE_URL=postgresql://x:[email protected]:54399/x \+ node_modules/.bin/prisma migrate deploy --schema /home/z/my-project/canvix-main/prisma/schema.prisma 2>&1 | tail -3+set -e+echo "(P1001 = correct: CLI + schema + engine all loaded, connection refused as expected)"