⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat: publish release images to GHCR and run deploys from them (#220)
Crofffad6d0f8750c
diff --git a/.env.example b/.env.exampleindex 47db935d..c3327940 100644--- a/.env.example+++ b/.env.example@@ -15,15 +15,15 @@ POSTGRES_PORT=5432DATABASE_URL=postgres://itsaplan:itsaplan@localhost:5432/itsaplan# ── Public origins (each set once; every service derives from these) ──-# API_URL — api origin: auth handler, email links, and the web browser bundle.+# API_URL — api origin: auth handler, email links, and the origin the browser calls.# APP_URL — web origin: CORS/auth trusted origins, passkey, email links.API_URL=http://localhost:3000APP_URL=http://localhost:3001-# ── Legal document URLs (web build args) ──+# ── Legal document URLs ──# Shown on the logged-out screens; Google OAuth sign-in requires the privacy policy# to be reachable. Point them at this instance's own documents. Leave empty to hide-# the legal notice. Inlined into the web bundle at build time (rebuild web to change).+# the legal notice. Read by web at startup, so a change needs a restart, not a build.# PRIVACY_URL=https://example.com/privacy# TERMS_URL=https://example.com/terms@@ -103,7 +103,12 @@ WORKER_INTERNAL_TOKEN=change-me-please-generate-a-real-secret# TELEMETRY_DEBUG=1 # log the exact body before each send# ── Web (Next.js) ──-# The browser bundle needs NEXT_PUBLIC_API_URL (= API_URL above) and the optional-# NEXT_PUBLIC_PRIVACY_URL / NEXT_PUBLIC_TERMS_URL (= PRIVACY_URL / TERMS_URL above),-# set in the separate apps/web/.env locally, or as Docker build args.+# web reads API_URL, PRIVACY_URL and TERMS_URL from its environment at startup, so+# one image serves any instance. Local dev reads them from the separate apps/web/.env,+# which Next loads on its own.# WEB_PORT=3001 # host port for the web app; change if 3001 is taken++# ── Published images ──+# The release the four services run. Unset means the newest one; pin it to stay on a+# known version. `docker compose up -d --build` ignores this and builds the checkout.+# VERSION=0.10.1diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 472066fd..ea2e2af5 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -64,12 +64,8 @@ jobs:- run: bun install --frozen-lockfile- # NEXT_PUBLIC_API_URL is inlined into the web bundle at build time. It only has- # to be a syntactically valid URL for the build to succeed.- name: Buildrun: bun run build- env:- NEXT_PUBLIC_API_URL: http://localhost:3000test:name: Test suitediff --git a/.github/workflows/publish-images.yml b/.github/workflows/publish-images.ymlnew file mode 100644index 00000000..cb8171eb--- /dev/null+++ b/.github/workflows/publish-images.yml@@ -0,0 +1,120 @@+name: Publish images++# Builds the four service images and pushes them to GHCR, one manifest per service+# covering amd64 and arm64. Called by release.yml once a release is tagged; the+# manual trigger republishes an existing tag.+#+# Each architecture is built on a runner of that architecture (no QEMU) and pushed+# by digest; a second job joins the two digests into one tagged manifest.+on:+ workflow_call:+ inputs:+ tag:+ description: The release tag to build, e.g. v0.10.1+ required: true+ type: string+ workflow_dispatch:+ inputs:+ tag:+ description: The release tag to build, e.g. v0.10.1+ required: true+ type: string++env:+ REGISTRY: ghcr.io++jobs:+ build:+ name: ${{ matrix.service }} ${{ matrix.platform.arch }}+ runs-on: ${{ matrix.platform.runner }}+ permissions:+ contents: read+ packages: write+ strategy:+ fail-fast: false+ matrix:+ service: [api, worker, bot, web]+ platform:+ - arch: amd64+ runner: ubuntu-24.04+ - arch: arm64+ runner: ubuntu-24.04-arm+ steps:+ - uses: actions/checkout@v7+ with:+ ref: ${{ inputs.tag }}++ - uses: docker/setup-buildx-action@v4++ - uses: docker/login-action@v4+ with:+ registry: ${{ env.REGISTRY }}+ username: ${{ github.actor }}+ password: ${{ secrets.GITHUB_TOKEN }}++ # push-by-digest publishes the layers without a tag: the image is only+ # reachable by digest until the manifest job names it.+ - id: build+ uses: docker/build-push-action@v7+ with:+ context: .+ file: apps/${{ matrix.service }}/Dockerfile+ platforms: linux/${{ matrix.platform.arch }}+ cache-from: type=gha,scope=${{ matrix.service }}-${{ matrix.platform.arch }}+ cache-to: type=gha,mode=max,scope=${{ matrix.service }}-${{ matrix.platform.arch }}+ outputs: type=image,name=${{ env.REGISTRY }}/${{ github.repository }}-${{ matrix.service }},push-by-digest=true,name-canonical=true,push=true++ - name: Keep the digest for the manifest+ run: |+ mkdir -p /tmp/digests+ echo -n "${{ steps.build.outputs.digest }}" > "/tmp/digests/${{ matrix.platform.arch }}"++ - uses: actions/upload-artifact@v7+ with:+ name: digest-${{ matrix.service }}-${{ matrix.platform.arch }}+ path: /tmp/digests/*+ retention-days: 1++ manifest:+ name: ${{ matrix.service }} manifest+ needs: build+ runs-on: ubuntu-24.04+ permissions:+ contents: read+ packages: write+ strategy:+ fail-fast: false+ matrix:+ service: [api, worker, bot, web]+ steps:+ - uses: actions/download-artifact@v8+ with:+ pattern: digest-${{ matrix.service }}-*+ merge-multiple: true+ path: /tmp/digests++ - uses: docker/login-action@v4+ with:+ registry: ${{ env.REGISTRY }}+ username: ${{ github.actor }}+ password: ${{ secrets.GITHUB_TOKEN }}++ # A prerelease carries a suffix (v1.2.3-rc.1) and must not move `latest`.+ - name: Tag the manifest+ env:+ IMAGE: ${{ env.REGISTRY }}/${{ github.repository }}-${{ matrix.service }}+ TAG: ${{ inputs.tag }}+ run: |+ set -euo pipefail+ version=${TAG#v}+ tags=(-t "$IMAGE:$version")+ case "$version" in+ *-*) ;;+ *) tags+=(-t "$IMAGE:latest") ;;+ esac+ sources=()+ for digest in /tmp/digests/*; do+ sources+=("$IMAGE@$(cat "$digest")")+ done+ docker buildx imagetools create "${tags[@]}" "${sources[@]}"+ docker buildx imagetools inspect "$IMAGE:$version"diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex a2c4da03..324e7d6d 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -41,6 +41,9 @@ jobs:runs-on: ubuntu-latestpermissions:contents: write+ # Empty on a push that cut no release; the image job keys off it.+ outputs:+ tag: ${{ steps.move.outputs.tag }}steps:# `fetch-depth: 0` fetches the tags read below, and the object for the# current `release` head — without it git cannot prove the push is a@@ -55,11 +58,27 @@ jobs:# because git resolves a bare `release` against the remote, which fails# while the branch does not exist yet.- name: Move the release branch to the released commit+ id: moverun: |tag=$(git tag --points-at HEAD --list 'v*')+ echo "tag=$tag" >> "$GITHUB_OUTPUT"if [ -z "$tag" ]; thenecho "No release tag on $(git rev-parse --short HEAD), nothing to move."exit 0fiecho "Moving the release branch to $tag."git push origin HEAD:refs/heads/release++ # Prebuilt images for self-hosters: `docker compose pull` instead of a build.+ # Chained here for the same reason as the job above — a `release: published`+ # event raised by GITHUB_TOKEN starts no workflow run.+ publish-images:+ name: Publish images+ needs: move-release-branch+ if: ${{ needs.move-release-branch.outputs.tag != '' }}+ permissions:+ contents: read+ packages: write+ uses: ./.github/workflows/publish-images.yml+ with:+ tag: ${{ needs.move-release-branch.outputs.tag }}diff --git a/AGENTS.md b/AGENTS.mdindex 33b94bb2..27e9a1b7 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -114,8 +114,9 @@ bun run dev # api :3000 + web :3001- Root `.env` (copy from `.env.example`) feeds api, drizzle, and docker-compose.Bun apps load it via `--env-file=../../.env`; drizzle via `dotenv` in `drizzle.config.ts`.- `apps/web/.env` is **separate** — Next reads env only from its own folder. It holds- `NEXT_PUBLIC_API_URL` (same value as the root `API_URL`); in the Docker build it comes- from a build arg. `NEXT_PUBLIC_*` are inlined at **build time**.+ `API_URL` (same value as the root one) and the legal document URLs. web reads them from+ its process at **startup**, never through `NEXT_PUBLIC_*`, which `next build` would inline+ into the bundle and pin the image to one instance.- Local dev DB: `docker compose -f docker-compose.dev.yml up -d` (the deploy composes doNOT publish the DB port). **Host 5432 is often taken** → use `POSTGRES_PORT=5433` and set`DATABASE_URL=...localhost:5433...` in `.env`.@@ -127,12 +128,13 @@ bun run dev # api :3000 + web :3001| File | Purpose || ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- || `docker-compose.dev.yml` | local backing services only: Postgres + MinIO. The apps run on the host. |-| `docker-compose.yml` | self-hosting stack. Builds every service from source (`docker compose up -d --build`), reads a plain `.env`, requires the secrets via `${VAR:?}`. |-| `docker-compose.coolify.yml` | the same stack for Coolify: reads its generated `SERVICE_*` variables and builds the images from source. |+| `docker-compose.yml` | self-hosting stack. Runs the published images (`docker compose pull && up -d`) or builds them from source (`up -d --build`); reads a plain `.env`, requires the secrets via `${VAR:?}`. |+| `docker-compose.coolify.yml` | the same stack for Coolify: reads its generated `SERVICE_*` variables and builds from source. No `image:` here — with both fields Coolify still builds, and stops creating rollback images. |+| `docker-compose.coolify-images.yml` | the same stack as a Coolify service (New Resource → Docker Compose Empty): the published images, no `build:`, no `ports:`, and the two domains declared with `SERVICE_URL_API_3000` / `SERVICE_URL_WEB_3001`. || `docker-compose.test.yml` | test gate against a throwaway Postgres. |-A change to the deploy stack usually has to land in **both** `docker-compose.yml` and-`docker-compose.coolify.yml`. The **api applies migrations on startup** (`migrate.ts` in+A change to the deploy stack usually has to land in **all three** of `docker-compose.yml`,+`docker-compose.coolify.yml`, and `docker-compose.coolify-images.yml`. The **api applies migrations on startup** (`migrate.ts` inits Dockerfile CMD). `bot` runs Telegram long polling and must stay at one replica.## Test gate (Docker)@@ -163,8 +165,11 @@ same commands.`typecheck`, an app build, and the compose test gate. `codeql.yml` scans for securityissues. Do not add a workflow that duplicates a job an existing one already runs.-Images are not published to a registry: every deploy builds from source-(`docker compose up -d --build`).+`publish-images.yml` pushes the four service images to GHCR+(`ghcr.io/croffasia/itsaplan-<service>`), one manifest per service covering amd64 and+arm64, each architecture built on a runner of its own. `release.yml` calls it once a+release is tagged: a `release: published` event raised by GITHUB_TOKEN starts no workflow+run, so the trigger has to be chained to the job that cut the release.## Commits and releasesdiff --git a/README.md b/README.mdindex 2a03bff2..931a7cbd 100644--- a/README.md+++ b/README.md@@ -111,11 +111,12 @@ Requirements: Docker and a domain behind a TLS-terminating reverse proxy.git clone https://github.com/croffasia/itsaplan.gitcd itsaplancp .env.example .env # set API_URL, APP_URL, and the secrets-docker compose up -d --build+docker compose up -d```-One command brings up the whole stack: Postgres, MinIO, api, worker, bot, and web. The-first account registered becomes the instance admin.+One command brings up the whole stack: Postgres, MinIO, api, worker, bot, and web, the four+services from the images published on each release. `docker compose up -d --build` builds+them from the checkout instead. The first account registered becomes the instance admin.- [Deploy on Railway](docs/railway.md) — one-click hosted deploy from the template- [Self-hosting](docs/self-hosting.md) — the full production setup, secrets, and updatesdiff --git a/apps/web/.env.example b/apps/web/.env.exampleindex 457b0401..d5fd73bd 100644--- a/apps/web/.env.example+++ b/apps/web/.env.example@@ -1,11 +1,12 @@# Next.js reads .env only from its own folder (apps/web/.env). Copy: cp .env.example .env-# NEXT_PUBLIC_* is inlined into the bundle at build time.+# These are read by the server at startup and handed to the browser on every render,+# so a deployment sets them on the container instead (see the root .env.example).# Public API origin the browser reaches (same value as API_URL in the root .env):-NEXT_PUBLIC_API_URL=http://localhost:3000+API_URL=http://localhost:3000# Legal document URLs shown on the logged-out screens. Point them at this instance's# own privacy policy and terms; Google OAuth sign-in requires the privacy policy to# be reachable. Leave empty to hide the legal notice.-NEXT_PUBLIC_PRIVACY_URL=-NEXT_PUBLIC_TERMS_URL=+PRIVACY_URL=+TERMS_URL=diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 536b2556..ee3c1ce5 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -85,8 +85,15 @@ next-intl, language from the `NEXT_LOCALE` cookie — no `[locale]` route segmen- A screen that has to stay live calls `useLiveRefresh({ scope, targets })` with a scope from`@/utils/revScopes` — never its own polling. `SyncProvider` polls every registered scope in onerequest and invalidates the targets of the ones that moved.-- Call the backend over HTTP at the API origin. `lib/api.ts` reads `NEXT_PUBLIC_API_URL`- from `apps/web/.env` (same value as the root `API_URL`), inlined at build time.+- Call the backend over HTTP at the API origin. `lib/api.ts` takes it from+ `utils/runtimeEnv`, which reads `API_URL` in the server process and hands it to the+ browser through the inline script in `components/runtime-env-script.tsx`. A per-instance+ value goes through there — never `process.env.NEXT_PUBLIC_*` in a component, which+ `next build` inlines and which pins the image to one instance.+- Avatars and attachments render from `/media/...` on the web origin (`app/media`, which+ streams them from the api), not from an absolute api url. That keeps them local images+ for `next/image`: `images.remotePatterns` is frozen into the standalone build, so an+ api origin listed there would only be valid for the instance that built the image.- Add shadcn components with `bunx shadcn@latest add <name>` (config in `components.json`).- **Don't edit `src/components/ui/`** — those files are generated and re-adding a componentoverwrites them. Style them from the outside instead: every primitive carries a `data-slot`@@ -99,8 +106,8 @@ next-intl, language from the `NEXT_LOCALE` cookie — no `[locale]` route segmen`chart.tsx` passes `debounce` to recharts' `ResponsiveContainer`, without which a chart in acontainer that resizes itself loops until React reports "Maximum update depth exceeded".- Tailwind v4: no `tailwind.config`; tokens live in `src/app/globals.css` (`@theme`, CSS vars).-- `NEXT_PUBLIC_*` are build-time — set them in `apps/web/.env` before `next build`, or as- web Dockerfile build args.+- Nothing per-instance may reach the bundle: the image is published once and serves every+ instance. New config of that kind belongs in `utils/runtimeEnv`.- Don't remove `output: "standalone"` + `outputFileTracingRoot` from `next.config` — the Dockerimage depends on them.- When touching `localStorage`/`window` in a render path (e.g. a `useState` initializer), guarddiff --git a/apps/web/Dockerfile b/apps/web/Dockerfileindex 219e17bb..d63b3398 100644--- a/apps/web/Dockerfile+++ b/apps/web/Dockerfile@@ -28,18 +28,18 @@ RUN bun install --frozen-lockfileFROM base AS buildCOPY --from=install /app ./COPY . .-# NEXT_PUBLIC_* are inlined into the bundle at build time — pass them as build args.-ARG NEXT_PUBLIC_API_URL-ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL-ARG NEXT_PUBLIC_PRIVACY_URL-ENV NEXT_PUBLIC_PRIVACY_URL=$NEXT_PUBLIC_PRIVACY_URL-ARG NEXT_PUBLIC_TERMS_URL-ENV NEXT_PUBLIC_TERMS_URL=$NEXT_PUBLIC_TERMS_URL+# No per-instance value is baked in: the origins are read from the environment at+# startup (apps/web/src/utils/runtimeEnv.ts), so one image serves any instance.ENV NEXT_TELEMETRY_DISABLED=1RUN cd apps/web && bun run build-# 3) Minimal final image (standalone output).-FROM base AS release+# 3) Minimal final image (standalone output). Node, not Bun: turbopack imports a+# serverExternalPackage under an internal alias that Next resolves through a Node+# module hook, and Bun does not honour it — every page rendering markdown then fails+# with "Failed to load external module isomorphic-dompurify-<hash>". Alpine keeps the+# musl build of the traced native modules (sharp) valid.+FROM node:22-alpine AS release+WORKDIR /appENV NODE_ENV=productionENV NEXT_TELEMETRY_DISABLED=1ENV PORT=3001@@ -50,4 +50,4 @@ COPY --from=build /app/apps/web/.next/static ./apps/web/.next/staticCOPY --from=build /app/apps/web/public ./apps/web/publicEXPOSE 3001-CMD ["bun", "apps/web/server.js"]+CMD ["node", "apps/web/server.js"]diff --git a/apps/web/next.config.ts b/apps/web/next.config.tsindex 5667f45a..e38a8efc 100644--- a/apps/web/next.config.ts+++ b/apps/web/next.config.ts@@ -2,8 +2,6 @@ import path from 'node:path';import type { NextConfig } from 'next';import createNextIntlPlugin from 'next-intl/plugin';-const apiUrl = new URL(process.env.NEXT_PUBLIC_API_URL as string);-const nextConfig: NextConfig = {// standalone build for a lean docker image.output: 'standalone',@@ -13,24 +11,6 @@ const nextConfig: NextConfig = {// files (default-stylesheet.css) by a path relative to its module. Bundling it// breaks that path, so it is required from node_modules at runtime instead.serverExternalPackages: ['isomorphic-dompurify'],- // Avatars and attachments are served by the api on its own origin, and the- // image optimizer only fetches from allowed origins. NEXT_PUBLIC_API_URL is- // the value the client uses too (src/lib/api.ts) and is set at build time.- // Spelled out rather than built from a URL, because a URL pattern also pins- // the query string to the empty one it carries, and a replaced attachment is- // requested with a cache-busting `?v=`.- images: {- // The optimizer refuses local IPs, and in dev the api is on localhost.- dangerouslyAllowLocalIP: process.env.NODE_ENV === 'development',- remotePatterns: [- {- protocol: apiUrl.protocol === 'https:' ? 'https' : 'http',- hostname: apiUrl.hostname,- port: apiUrl.port,- pathname: '/**',- },- ],- },};export default createNextIntlPlugin('./src/i18n/request.ts')(nextConfig);diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsxindex 9c15de12..281ddaaa 100644--- a/apps/web/src/app/layout.tsx+++ b/apps/web/src/app/layout.tsx@@ -3,6 +3,7 @@ import { ThemeProvider } from 'next-themes';import { NextIntlClientProvider } from 'next-intl';import { getLocale, getTranslations } from 'next-intl/server';import { Providers } from '@/components/providers';+import RuntimeEnvScript from '@/components/runtime-env-script';import { localeDirection, type Locale } from '@/i18n/locales';import './globals.css';@@ -21,6 +22,7 @@ export default async function RootLayout({return (<html lang={locale} dir={localeDirection(locale as Locale)} suppressHydrationWarning><body className="antialiased">+ <RuntimeEnvScript /><ThemeProviderattribute="class"defaultTheme="system"diff --git a/apps/web/src/app/media/[...path]/route.ts b/apps/web/src/app/media/[...path]/route.tsnew file mode 100644index 00000000..ba8ddeef--- /dev/null+++ b/apps/web/src/app/media/[...path]/route.ts@@ -0,0 +1,52 @@+import { serverRuntimeEnv } from '@/utils/runtimeEnv';++// Avatars and attachments live on the api, on another origin. Serving them through+// the web origin makes them local images for next/image: `images.remotePatterns` is+// frozen into the build, so an absolute api url cannot be optimized by an image that+// has to serve any instance.+//+// Only the api's two public, unauthenticated media routes are reachable here, and no+// request header is forwarded — this must never become a way to reach the rest of the+// api through the web server.+const MEDIA_ROOTS = ['avatars', 'attachments'];++// Copied from the api's response, including the headers that keep attacker-controlled+// bytes inert (nosniff, the disposition that forces a download, the sandbox CSP).+const PASSTHROUGH_HEADERS = [+ 'content-type',+ 'content-length',+ 'content-disposition',+ 'cache-control',+ 'etag',+ 'x-content-type-options',+ 'content-security-policy',+];++export async function GET(request: Request, { params }: { params: Promise<{ path: string[] }> }) {+ const { path } = await params;+ if (!MEDIA_ROOTS.includes(path[0]) || path.some((segment) => segment === '..')) {+ return new Response(null, { status: 404 });+ }++ // The public origin is what the browser uses; inside a compose network the api is+ // reached by service name, which is what SERVICE_URL_API carries (as for the worker).+ const origin = process.env.SERVICE_URL_API || serverRuntimeEnv().apiUrl;+ const { search } = new URL(request.url);+ const upstream = await fetch(`${origin}/${path.join('/')}${search}`, {+ // The api answers 304 to it, and passing it on keeps a cached avatar cached.+ headers: forwardedHeaders(request),+ cache: 'no-store',+ });++ const headers = new Headers();+ for (const name of PASSTHROUGH_HEADERS) {+ const value = upstream.headers.get(name);+ if (value) headers.set(name, value);+ }+ return new Response(upstream.body, { status: upstream.status, headers });+}++function forwardedHeaders(request: Request): HeadersInit {+ const ifNoneMatch = request.headers.get('if-none-match');+ return ifNoneMatch ? { 'if-none-match': ifNoneMatch } : {};+}diff --git a/apps/web/src/components/common/Avatar.tsx b/apps/web/src/components/common/Avatar.tsxindex a329791a..a2b58948 100644--- a/apps/web/src/components/common/Avatar.tsx+++ b/apps/web/src/components/common/Avatar.tsx@@ -3,7 +3,7 @@import { forwardRef, useState, type ComponentProps } from 'react';import Image from 'next/image';import { avatarColor, initials } from '@/utils/avatar';-import { resolveApiUrl } from '@/lib/api';+import { mediaUrl } from '@/lib/api';import { cn } from '@/lib/utils';// A person's avatar. With an uploaded `image` it shows that picture; otherwise@@ -38,7 +38,7 @@ const Avatar = forwardRef<>{showImage ? (<Image- src={resolveApiUrl(image!)}+ src={mediaUrl(image!)}alt={name}fill// The largest avatar in the app is size-16 (64px); everything else isdiff --git a/apps/web/src/components/runtime-env-script.tsx b/apps/web/src/components/runtime-env-script.tsxnew file mode 100644index 00000000..3489e9a5--- /dev/null+++ b/apps/web/src/components/runtime-env-script.tsx@@ -0,0 +1,14 @@+import { connection } from 'next/server';+import { serverRuntimeEnv } from '@/utils/runtimeEnv';++// Publishes the per-instance origins to the browser. It renders before any bundle+// script, so a client module reading runtimeEnv() at import time already sees them.+// `connection()` keeps the values out of a prerender: a page rendered at build time+// would carry the building machine's environment into the HTML.+// `<` is escaped because the JSON is written into an inline script, where a+// `</script>` inside a value would end the element.+export default async function RuntimeEnvScript() {+ await connection();+ const json = JSON.stringify(serverRuntimeEnv()).replace(/</g, '\\u003c');+ return <script dangerouslySetInnerHTML={{ __html: `window.__ITSAPLAN_ENV__=${json}` }} />;+}diff --git a/apps/web/src/features/api-docs/components/ScalarReference.tsx b/apps/web/src/features/api-docs/components/ScalarReference.tsxindex 682a9ea1..29354c0e 100644--- a/apps/web/src/features/api-docs/components/ScalarReference.tsx+++ b/apps/web/src/features/api-docs/components/ScalarReference.tsx@@ -3,10 +3,11 @@import { ApiReferenceReact } from '@scalar/api-reference-react';import '@scalar/api-reference-react/style.css';import './scalar-theme.css';+import { API_URL } from '@/lib/api';// The API mounts /docs/json outside the session guard, so the browser fetches it// directly.-const SPEC_URL = `${process.env.NEXT_PUBLIC_API_URL}/docs/json`;+const SPEC_URL = `${API_URL}/docs/json`;// The app owns the light/dark switch (next-themes), so Scalar's mode is forced to// match and its own toggle is hidden. Theming: scalar-theme.css.diff --git a/apps/web/src/features/mcp/utils/clients.ts b/apps/web/src/features/mcp/utils/clients.tsindex c8df8aab..f993d130 100644--- a/apps/web/src/features/mcp/utils/clients.ts+++ b/apps/web/src/features/mcp/utils/clients.ts@@ -1,6 +1,7 @@-// The MCP endpoint clients connect to. NEXT_PUBLIC_API_URL is the API origin-// (mandatory build-time config); the transport is Streamable HTTP at /mcp.-export const MCP_URL = `${process.env.NEXT_PUBLIC_API_URL}/mcp`;+import { API_URL } from '@/lib/api';++// The MCP endpoint clients connect to; the transport is Streamable HTTP at /mcp.+export const MCP_URL = `${API_URL}/mcp`;interface McpClient {// Product names stay as they are written by their makers; only the generic entrydiff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex d4737703..73e98d1f 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -1,22 +1,25 @@// Typed client for the planner API (apps/api/src/planner). Row shapes mirror the-// store DTOs. The API is a separate service; the browser reaches it at-// NEXT_PUBLIC_API_URL. The planner routes require a better-auth session, so every+// store DTOs. The API is a separate service; the browser reaches it at the API+// origin below. The planner routes require a better-auth session, so every// request sends credentials (the session cookie).import type { Locale } from '@/i18n/locales';import type { FilterSet } from '@/utils/filters';import type { SavedViewDisplay } from '@/utils/viewSettings';import type { DashboardLayout, BreakdownBy } from '@/utils/dashboardWidgets';+import { runtimeEnv } from '@/utils/runtimeEnv';-// NEXT_PUBLIC_* is inlined at build time, so a build without it ships a client-// that cannot reach the API. Fail at import instead of pointing at a wrong origin.-export const API_URL = process.env.NEXT_PUBLIC_API_URL as string;-if (!API_URL) throw new Error('NEXT_PUBLIC_API_URL is not set');+// The API origin, read from the running server rather than from the build (see+// utils/runtimeEnv). A deployment without it ships a client that cannot reach the+// API. Fail at import instead of pointing at a wrong origin.+export const API_URL = runtimeEnv().apiUrl;+if (!API_URL) throw new Error('API_URL is not set on the web service');-// Resolves a possibly-relative API path (e.g. a stored avatar/attachment URL) to-// an absolute one against the API origin. Leaves absolute URLs untouched.-export function resolveApiUrl(url: string): string {- return url.startsWith('http') ? url : `${API_URL}${url}`;+// Points a relative media path (a stored avatar or attachment URL) at the web+// origin's media route (app/media), which streams it from the API. Leaves an+// absolute URL — an embed stored before this, or an external image — untouched.+export function mediaUrl(url: string): string {+ return url.startsWith('http') ? url : `/media${url}`;}// An error carrying the HTTP status so callers can tell apart 401 (no session),@@ -2342,10 +2345,10 @@ export interface InviteView {hasAccount: boolean;}-// The attachment DTO's url is relative to the API origin; make it absolute so it-// works in <img>/<video> and markdown rendered on the web origin.-function absolutizeAttachment(a: Attachment): Attachment {- return { ...a, url: a.url.startsWith('http') ? a.url : `${API_URL}${a.url}` };+// The attachment DTO's url is relative to the API origin; point it at the web+// origin's media route so it works in <img>/<video> and markdown rendered there.+function withMediaUrl(a: Attachment): Attachment {+ return { ...a, url: mediaUrl(a.url) };}// Multipart upload — cannot use request(), which forces a JSON Content-Type; the@@ -2359,7 +2362,7 @@ async function sendAttachmentFile(form.append('file', file);const res = await fetch(`${API_URL}${path}`, { method, credentials: 'include', body: form });if (!res.ok) throw await apiFailure(res);- return absolutizeAttachment(await res.json());+ return withMediaUrl(await res.json());}// Inbox notifications. Each row is enriched with the issue and project it points at@@ -2721,9 +2724,7 @@ export const api = {request<void>(`/worklogs/${worklogId}`, { method: 'DELETE' }),listAttachments: (issueId: number) =>- request<Attachment[]>(`/issues/${issueId}/attachments`).then((rows) =>- rows.map(absolutizeAttachment),- ),+ request<Attachment[]>(`/issues/${issueId}/attachments`).then((rows) => rows.map(withMediaUrl)),uploadAttachment: (issueId: number, file: File) =>sendAttachmentFile(`/issues/${issueId}/attachments`, 'POST', file),// Keeps the attachment's id and URL, so an embed of it in a description showsdiff --git a/apps/web/src/proxy.ts b/apps/web/src/proxy.tsindex 6c09aa98..81e9f5ee 100644--- a/apps/web/src/proxy.ts+++ b/apps/web/src/proxy.ts@@ -11,7 +11,9 @@ const PUBLIC_PATHS = ['/login', '/register'];// reason: a reset link opened in a browser that still holds a session must show the// form, not bounce to the app. The public read-only share pages (/share/*) open for// anyone with the link, signed in or not.-const OPEN_PATHS = ['/invite', '/forgot-password', '/reset-password', '/share'];+// `/media` streams avatars and attachments from the api, which serves them without+// a session — a share page opened by a logged-out visitor shows them too.+const OPEN_PATHS = ['/invite', '/forgot-password', '/reset-password', '/share', '/media'];// Gate the whole app behind a session. This is an optimistic check: it only looks// for the presence of the better-auth session cookie, not its validity — the APIdiff --git a/apps/web/src/utils/app.ts b/apps/web/src/utils/app.tsindex 104f8946..0108ff8d 100644--- a/apps/web/src/utils/app.ts+++ b/apps/web/src/utils/app.ts@@ -1,3 +1,5 @@+import { runtimeEnv } from './runtimeEnv';+// The product name shown to users: the login panel, the passkey label in the OS// picker, and the account page. It is defined once, so a rebrand is one edit.export const APP_NAME = "It's a Plan";@@ -5,10 +7,9 @@ export const APP_NAME = "It's a Plan";// The product site. The product mark on the public share pages links to it.export const APP_SITE_URL = 'https://itsaplan.dev/';-// The legal document URLs, linked from the logged-out screens. Google requires the-// privacy policy and the terms registered for the OAuth client to be reachable-// before a user gives consent. Each instance points these at its own documents-// through apps/web/.env (build-time, inlined into the bundle). When they are unset,-// the legal notice is hidden.-export const PRIVACY_POLICY_URL = process.env.NEXT_PUBLIC_PRIVACY_URL ?? '';-export const TERMS_URL = process.env.NEXT_PUBLIC_TERMS_URL ?? '';+// The legal document URLs, linked from the logged-out screens: Google requires the+// privacy policy and terms registered for the OAuth client to be reachable before+// consent is given. Each instance points these at its own documents through its+// environment (see runtimeEnv); when unset, the legal notice is hidden.+export const PRIVACY_POLICY_URL = runtimeEnv().privacyUrl;+export const TERMS_URL = runtimeEnv().termsUrl;diff --git a/apps/web/src/utils/runtimeEnv.ts b/apps/web/src/utils/runtimeEnv.tsnew file mode 100644index 00000000..76eb624c--- /dev/null+++ b/apps/web/src/utils/runtimeEnv.ts@@ -0,0 +1,37 @@+// The per-instance origins the browser needs. A NEXT_PUBLIC_* value is inlined into+// the bundle by `next build`, which pins one build to one instance; these are read+// from the server process on every render and handed to the browser by+// RuntimeEnvScript, so the same build serves any instance.++export interface RuntimeEnv {+ apiUrl: string;+ privacyUrl: string;+ termsUrl: string;+}++declare global {+ interface Window {+ __ITSAPLAN_ENV__?: RuntimeEnv;+ }+}++// The NEXT_PUBLIC_ prefixed name is still accepted, for a deployment that sets it on+// the container. Both names are read through a computed key: Next inlines a literal+// `process.env.NEXT_PUBLIC_X` at build time, server code included, and only a dynamic+// lookup reaches the running process.+function readOrigin(name: string): string {+ return process.env[name] || process.env[`NEXT_PUBLIC_${name}`] || '';+}++export function serverRuntimeEnv(): RuntimeEnv {+ return {+ apiUrl: readOrigin('API_URL'),+ privacyUrl: readOrigin('PRIVACY_URL'),+ termsUrl: readOrigin('TERMS_URL'),+ };+}++export function runtimeEnv(): RuntimeEnv {+ if (typeof window === 'undefined') return serverRuntimeEnv();+ return window.__ITSAPLAN_ENV__ ?? { apiUrl: '', privacyUrl: '', termsUrl: '' };+}diff --git a/docker-compose.coolify-images.yml b/docker-compose.coolify-images.ymlnew file mode 100644index 00000000..719fe4be--- /dev/null+++ b/docker-compose.coolify-images.yml@@ -0,0 +1,199 @@+# ─────────────────────────────────────────────────────────────+# Coolify stack on the published images: postgres + minio + api + worker + bot + web.+# In Coolify: New Resource → Docker Compose Empty → paste this file. Nothing is built;+# the four services run the images published to GHCR on each release, and VERSION picks+# one (unset means the newest).+#+# For a Coolify resource that builds from source, use docker-compose.coolify.yml.+#+# SERVICE_PASSWORD_* / SERVICE_URL_* are Coolify magic variables: generated and+# persisted on first deploy, stable across deploys. api and web each declare their own+# domain by listing SERVICE_URL_API_3000 / SERVICE_URL_WEB_3001 without a value; everything+# else reads them back. A SERVICE_URL_* key in any other service declares a domain there+# too, which is why worker and bot address the api through API_URL instead.+#+# No host port is published: Coolify's proxy reaches the containers over the internal+# network, and a `ports:` entry here turns into a second, malformed domain.+#+# Coolify reports the worst container health as the resource status, so a service+# without a healthcheck holds the whole stack at "running (unknown)". Services that+# answer no requests are taken out of that aggregate with `exclude_from_hc: true`+# (a Coolify key, stripped before compose runs) or, for one-shot containers, by+# `restart: 'no'`, which it treats the same way.+# ─────────────────────────────────────────────────────────────+services:+ postgres:+ image: postgres:17-alpine+ restart: unless-stopped+ environment:+ POSTGRES_USER: ${POSTGRES_USER:-itsaplan}+ POSTGRES_PASSWORD: ${SERVICE_PASSWORD_POSTGRES}+ POSTGRES_DB: ${POSTGRES_DB:-itsaplan}+ volumes:+ - postgres-data:/var/lib/postgresql/data+ healthcheck:+ test: ['CMD-SHELL', 'pg_isready -U ${POSTGRES_USER:-itsaplan} -d ${POSTGRES_DB:-itsaplan}']+ interval: 5s+ timeout: 5s+ retries: 10++ # S3-compatible object store for issue attachments (MinIO).+ # Both the S3 API (:9000) and the console (:9001) are internal only — the api+ # streams attachment bytes over the internal network, so no port is published.+ # Administer through mc from inside the network or an SSH tunnel.+ minio:+ image: minio/minio:latest+ restart: unless-stopped+ command: server /data --console-address ":9001"+ environment:+ MINIO_ROOT_USER: ${SERVICE_USER_MINIO}+ MINIO_ROOT_PASSWORD: ${SERVICE_PASSWORD_MINIO}+ volumes:+ - minio-data:/data+ healthcheck:+ test: ['CMD', 'mc', 'ready', 'local']+ interval: 15s+ timeout: 5s+ retries: 5+ start_period: 20s++ # One-shot: waits for MinIO, creates the attachments bucket, then exits.+ # restart "no" is explicit: it exits 0 by design, and platforms that inject+ # restart: unless-stopped (e.g. Coolify) would otherwise loop it forever and+ # trip their restart-count limit, tearing the whole stack down.+ minio-init:+ image: minio/mc:latest+ restart: 'no'+ depends_on:+ - minio+ environment:+ MINIO_ROOT_USER: ${SERVICE_USER_MINIO}+ MINIO_ROOT_PASSWORD: ${SERVICE_PASSWORD_MINIO}+ S3_BUCKET: ${S3_BUCKET:-planner-attachments}+ entrypoint: >+ /bin/sh -c "+ until mc alias set local http://minio:9000 \"$$MINIO_ROOT_USER\" \"$$MINIO_ROOT_PASSWORD\"; do echo 'waiting for minio...'; sleep 2; done;+ mc mb --ignore-existing local/\"$$S3_BUCKET\";+ echo 'bucket ready: '\"$$S3_BUCKET\";+ "++ api:+ image: ghcr.io/croffasia/itsaplan-api:${VERSION:-latest}+ restart: unless-stopped+ depends_on:+ postgres:+ condition: service_healthy+ minio:+ condition: service_started+ # Applies migrations on startup, then starts the server (see api Dockerfile CMD).+ environment:+ # Listed without a value, this asks Coolify for the public domain of this+ # service on port 3000. The port belongs to the declaration only — the value read+ # back below is SERVICE_URL_API, which Coolify derives from it without the port.+ - SERVICE_URL_API_3000+ - NODE_ENV=production+ - API_PORT=3000+ - DATABASE_URL=postgres://${POSTGRES_USER:-itsaplan}:${SERVICE_PASSWORD_POSTGRES}@postgres:5432/${POSTGRES_DB:-itsaplan}+ - BETTER_AUTH_SECRET=${SERVICE_PASSWORD_64_BETTERAUTH}+ # Encrypts stored AI provider API keys at rest (AES-256-GCM). Changing it makes+ # existing stored credentials undecryptable.+ - APP_ENCRYPTION_KEY=${SERVICE_PASSWORD_64_ENCRYPTION}+ # The worker and the bot authenticate to /internal/* with this same token.+ - WORKER_INTERNAL_TOKEN=${SERVICE_PASSWORD_64_WORKER}+ # API_URL is the api origin; APP_URL is the web origin.+ - API_URL=${SERVICE_URL_API}+ - APP_URL=${SERVICE_URL_WEB}+ # To override the cookie parent domain (multi-label TLDs / deep subdomains),+ # add a COOKIE_DOMAIN env in Coolify — the code reads it if present.+ - S3_ENDPOINT=http://minio:9000+ - S3_BUCKET=${S3_BUCKET:-planner-attachments}+ - S3_ACCESS_KEY_ID=${SERVICE_USER_MINIO}+ - S3_SECRET_ACCESS_KEY=${SERVICE_PASSWORD_MINIO}+ - S3_REGION=${S3_REGION:-us-east-1}+ - S3_FORCE_PATH_STYLE=${S3_FORCE_PATH_STYLE:-}+ # start_period covers the migrations the container applies before it listens.+ healthcheck:+ test: ['CMD', 'wget', '-q', '-O', '/dev/null', 'http://127.0.0.1:3000/']+ interval: 15s+ timeout: 5s+ retries: 5+ start_period: 90s++ # Background worker for webhook delivery, agent schedules, and autonomous agent+ # runs. Shares the database with the api. No public ports, so nothing to probe.+ worker:+ image: ghcr.io/croffasia/itsaplan-worker:${VERSION:-latest}+ restart: unless-stopped+ exclude_from_hc: true+ depends_on:+ postgres:+ condition: service_healthy+ api:+ condition: service_started+ environment:+ NODE_ENV: production+ DATABASE_URL: postgres://${POSTGRES_USER:-itsaplan}:${SERVICE_PASSWORD_POSTGRES}@postgres:5432/${POSTGRES_DB:-itsaplan}+ API_URL: http://api:3000+ WORKER_INTERNAL_TOKEN: ${SERVICE_PASSWORD_64_WORKER}+ # Anonymous telemetry (TELEMETRY.md). Either variable, set to anything but 0,+ # turns it off.+ TELEMETRY_DISABLED: ${TELEMETRY_DISABLED:-}+ DO_NOT_TRACK: ${DO_NOT_TRACK:-}+ TELEMETRY_DEBUG: ${TELEMETRY_DEBUG:-}+ # Optional tuning — defaults live in apps/worker/src/config.ts:+ # WEBHOOK_POLL_INTERVAL_MS, WEBHOOK_BATCH_SIZE, WEBHOOK_TIMEOUT_MS,+ # WEBHOOK_MAX_ATTEMPTS, WEBHOOK_DISABLE_THRESHOLD, WEBHOOK_LEASE_SECONDS,+ # WEBHOOK_CLEANUP_DAYS, WEBHOOK_CLEANUP_EVERY_TICKS.+ # Agent runs: AGENT_RUN_BATCH_SIZE, AGENT_RUN_TIMEOUT_MS,+ # AGENT_RUN_MAX_ATTEMPTS, AGENT_RUN_LEASE_SECONDS.++ # Telegram bot: long polling for the instance bot, completing the account links+ # users start from their profile. No database and no public ports — it reaches the+ # api's internal routes with the same shared token the worker uses.+ #+ # Must stay at one replica: Telegram hands each getUpdates call to a single caller,+ # so a second instance would take updates away from the first.+ bot:+ image: ghcr.io/croffasia/itsaplan-bot:${VERSION:-latest}+ restart: unless-stopped+ exclude_from_hc: true+ depends_on:+ api:+ condition: service_started+ environment:+ NODE_ENV: production+ API_URL: http://api:3000+ WORKER_INTERNAL_TOKEN: ${SERVICE_PASSWORD_64_WORKER}+ # The bot token itself is not set here: it is stored in the database and edited+ # in god mode, so the service picks up a change without a redeploy.+ # Optional tuning — defaults live in apps/bot/src/config.ts:+ # BOT_CONFIG_POLL_INTERVAL_MS, BOT_API_TIMEOUT_MS.++ web:+ image: ghcr.io/croffasia/itsaplan-web:${VERSION:-latest}+ restart: unless-stopped+ depends_on:+ - api+ environment:+ # Declares this service's public domain on port 3001; see the api service.+ - SERVICE_URL_WEB_3001+ - NODE_ENV=production+ - PORT=3001+ - HOSTNAME=0.0.0.0+ # The api origin the browser uses. web streams avatars and attachments from the+ # same origin (/media), so they are served from the web origin.+ - API_URL=${SERVICE_URL_API}+ # Legal document URLs shown on the logged-out screens; empty hides the notice.+ - PRIVACY_URL=${PRIVACY_URL:-}+ - TERMS_URL=${TERMS_URL:-}+ # /login renders without a session, and without reaching the api.+ healthcheck:+ test: ['CMD', 'wget', '-q', '-O', '/dev/null', 'http://127.0.0.1:3001/login']+ interval: 15s+ timeout: 5s+ retries: 5+ start_period: 20s++volumes:+ postgres-data:+ minio-data:diff --git a/docker-compose.coolify.yml b/docker-compose.coolify.ymlindex 05536d01..e3421cc5 100644--- a/docker-compose.coolify.yml+++ b/docker-compose.coolify.yml@@ -1,7 +1,11 @@# ─────────────────────────────────────────────────────────────# Coolify stack: postgres + minio + api + worker + bot + web.# In Coolify: New Resource → Docker Compose → point to this file, then set the-# environment variables (see .env.example) in the UI. Builds from source.+# environment variables (see .env.example) in the UI.+#+# Every service is built from the checkout Coolify clones. To run the images published+# on each release instead, use docker-compose.coolify-images.yml.+## For self-hosting anywhere else, use docker-compose.yml.## SERVICE_PASSWORD_* / SERVICE_URL_* are Coolify magic variables: generated and@@ -171,13 +175,6 @@ services:build:context: .dockerfile: apps/web/Dockerfile- args:- # The api origin, inlined into the web bundle at build time. Sourced from- # Coolify's Domain for the api service.- NEXT_PUBLIC_API_URL: ${SERVICE_URL_API:-http://localhost:3000}- # Legal document URLs shown on the logged-out screens; empty hides the notice.- NEXT_PUBLIC_PRIVACY_URL: ${PRIVACY_URL:-}- NEXT_PUBLIC_TERMS_URL: ${TERMS_URL:-}restart: unless-stoppeddepends_on:- api@@ -185,6 +182,14 @@ services:NODE_ENV: productionPORT: 3001HOSTNAME: 0.0.0.0+ # The api origin the browser uses, from Coolify's Domain for the api service.+ # web reaches the api at the same address to stream avatars and attachments+ # (/media), so they are served from the web origin.+ API_URL: ${SERVICE_URL_API:-http://localhost:3000}+ SERVICE_URL_API: ${SERVICE_URL_API:-http://api:3000}+ # Legal document URLs shown on the logged-out screens; empty hides the notice.+ PRIVACY_URL: ${PRIVACY_URL:-}+ TERMS_URL: ${TERMS_URL:-}# /login renders without a session, and without reaching the api.healthcheck:test: ['CMD', 'wget', '-q', '-O', '/dev/null', 'http://127.0.0.1:3001/login']diff --git a/docker-compose.yml b/docker-compose.ymlindex 77a92349..17d47933 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -4,17 +4,18 @@# (backing services only).## cp .env.example .env # fill in the required values below-# docker compose up -d --build+# docker compose up -d## Required in .env (the stack refuses to start without them):# POSTGRES_PASSWORD, BETTER_AUTH_SECRET, APP_ENCRYPTION_KEY, WORKER_INTERNAL_TOKEN,# S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, API_URL, APP_URL# Generate each secret with: openssl rand -base64 32#-# Every service is built from this checkout. Bring the stack up with a build:+# The four services run from images published on each release; update with+# docker compose pull && docker compose up -d+# VERSION in .env pins a release (defaults to the latest one). To run this+# checkout instead of the published images, build them:# docker compose up -d --build-# web bakes API_URL into its bundle at build time, so rebuild it after changing-# API_URL: docker compose up -d --build web# ─────────────────────────────────────────────────────────────name: itsaplan@@ -73,6 +74,7 @@ services:# Applies database migrations on startup, then serves the API.api:+ image: ghcr.io/croffasia/itsaplan-api:${VERSION:-latest}build:context: .dockerfile: apps/api/Dockerfile@@ -118,6 +120,7 @@ services:# Webhook delivery, notification delivery, agent schedules, and agent runs.# Shares the database with the api. No public ports.worker:+ image: ghcr.io/croffasia/itsaplan-worker:${VERSION:-latest}build:context: .dockerfile: apps/worker/Dockerfile@@ -146,6 +149,7 @@ services:# Must stay at one replica: Telegram hands each getUpdates call to a single# caller, so a second instance would take updates away from the first.bot:+ image: ghcr.io/croffasia/itsaplan-bot:${VERSION:-latest}build:context: .dockerfile: apps/bot/Dockerfile@@ -158,18 +162,13 @@ services:SERVICE_URL_API: http://api:3000WORKER_INTERNAL_TOKEN: ${WORKER_INTERNAL_TOKEN}- # The api origin is inlined into the bundle at build time, so the image is bound- # to the origin it was built with. Sourced from the shared API_URL so the root- # .env keeps it in one place; rebuild web after changing API_URL.+ # The origins are read at startup and handed to the browser by the server render,+ # so the image carries none of them and a changed API_URL only needs a restart.web:+ image: ghcr.io/croffasia/itsaplan-web:${VERSION:-latest}build:context: .dockerfile: apps/web/Dockerfile- args:- NEXT_PUBLIC_API_URL: ${API_URL:?public origin of the api, e.g. https://api.example.com}- # Legal document URLs shown on the logged-out screens; empty hides the notice.- NEXT_PUBLIC_PRIVACY_URL: ${PRIVACY_URL:-}- NEXT_PUBLIC_TERMS_URL: ${TERMS_URL:-}restart: unless-stoppeddepends_on:- api@@ -177,6 +176,14 @@ services:NODE_ENV: productionPORT: 3001HOSTNAME: 0.0.0.0+ # The api origin the browser uses.+ API_URL: ${API_URL:?public origin of the api, e.g. https://api.example.com}+ # Where web itself reaches the api: it streams avatars and attachments from+ # there (/media) so they are served from the web origin.+ SERVICE_URL_API: http://api:3000+ # Legal document URLs shown on the logged-out screens; empty hides the notice.+ PRIVACY_URL: ${PRIVACY_URL:-}+ TERMS_URL: ${TERMS_URL:-}# /login renders without a session, and without reaching the api.healthcheck:test: ['CMD', 'wget', '-q', '-O', '/dev/null', 'http://127.0.0.1:3001/login']diff --git a/docs/coolify.md b/docs/coolify.mdindex 2a8c8b58..ae4e3ce8 100644--- a/docs/coolify.md+++ b/docs/coolify.md@@ -43,10 +43,10 @@ the host:| Domains for web | `https://plan.example.com:3001` |Coolify turns those into `SERVICE_URL_API` and `SERVICE_URL_WEB`, which the compose file-reads as the api's `API_URL` / `APP_URL` and as the api origin baked into the web bundle.+reads as the api's `API_URL` / `APP_URL` and as the api origin web hands to the browser.-Set both **before the first deploy**. Next.js inlines the api origin at build time, so-changing the api domain later needs a redeploy.+Changing a domain later takes a redeploy, which is how Coolify applies an environment+change.## 4. Deploy@@ -58,5 +58,21 @@ are generated on the first deploy and stay stable across later ones — nothinghand. Optional variables from `.env.example` — legal document URLs, telemetry opt-out,worker tuning — go in **Configuration → Environment Variables**.+## 5. Deploy the published images++A Public Repository resource always builds from source. To run the images published to GHCR on+each release, create the stack as a service instead:++1. **New Resource → Docker Compose Empty**, then pick the server.+2. Paste the whole of `docker-compose.coolify-images.yml` into **Docker Compose file** and+ press **Save**. It carries no `build:` sections — nothing is built.+3. In **Environment Variables**, set `VERSION` to a release (e.g. `0.10.1`); leave it out for+ the newest.+4. Press **Deploy**. Coolify generates a domain for api and one for web on the first+ deploy; rename them under the service if you want your own.++To keep an existing Public Repository resource and pull instead of build, set **Custom build+command** in **Configuration → General** to `docker compose pull` and redeploy.+To run the same stack outside Coolify, see [self-hosting.md](self-hosting.md) or[railway.md](railway.md).diff --git a/docs/railway.md b/docs/railway.mdindex 3bd197a3..5bbc0d0f 100644--- a/docs/railway.md+++ b/docs/railway.md@@ -27,8 +27,8 @@ Press the button and fill in the two fields on the **web** service:| `API_URL` | `https://api.example.com` || `APP_URL` | `https://app.example.com` |-Full origins, including `https://`. The api reads both by reference, and web bakes the api-origin into its bundle at build time.+Full origins, including `https://`. The api reads both by reference, and web reads `API_URL`+at startup and hands it to the browser on every render.## 3. Attach the hostnames@@ -49,9 +49,8 @@ variables.## Changing a hostname later-Edit `API_URL` or `APP_URL` **on the web service**. Web rebuilds, which is what has to-happen: Next.js inlines the api origin at build time, so a restart alone would keep serving-the old address. The api picks the new value up by reference and only restarts.+Edit `API_URL` or `APP_URL` **on the web service**. Both services restart and serve the new+address; no rebuild is involved.## Notesdiff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex dbd4dda8..0b8bb42f 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -11,13 +11,13 @@ cp .env.example .env# POSTGRES_PASSWORD, BETTER_AUTH_SECRET, APP_ENCRYPTION_KEY,# WORKER_INTERNAL_TOKEN, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY-docker compose up -d --build+docker compose up -d```-One command brings up the whole stack: Postgres, MinIO, api, worker, bot, and web. Every-service is built from this checkout; web bakes `API_URL` into its bundle because Next.js-inlines `NEXT_PUBLIC_*` at build time. The API applies migrations on startup, and the first-account registered becomes the instance admin.+One command brings up the whole stack: Postgres, MinIO, api, worker, bot, and web. The four+services run from the images published on each release; `VERSION` in `.env` pins one instead+of the newest. The API applies migrations on startup, and the first account registered+becomes the instance admin.`.env.example` documents every variable, including the optional ones: legal document URLs,passkey and cookie settings, telemetry opt-out, and worker tuning.@@ -26,10 +26,21 @@ passkey and cookie settings, telemetry opt-out, and worker tuning.```bashgit pull+docker compose pull+docker compose up -d+```++`git pull` is for the compose file itself; the services come from the registry. Changing+`API_URL` or `APP_URL` afterwards only needs `docker compose up -d`.++## Building from source instead++```bashdocker compose up -d --build```-Changing `API_URL` needs a rebuild too, for the same build-time inlining reason.+Builds every service from this checkout and runs those images. Nothing else changes, and+the same command picks up local edits.For a Coolify instance, see [coolify.md](coolify.md). For a hosted deploy without aserver of your own, see [railway.md](railway.md).diff --git a/turbo.json b/turbo.jsonindex 86d845e9..6ffe0e12 100644--- a/turbo.json+++ b/turbo.json@@ -1,14 +1,6 @@{"$schema": "https://turbo.build/schema.json",- "globalEnv": [- "NODE_ENV",- "DATABASE_URL",- "BETTER_AUTH_SECRET",- "API_URL",- "APP_URL",- "API_PORT",- "NEXT_PUBLIC_API_URL"- ],+ "globalEnv": ["NODE_ENV", "DATABASE_URL", "BETTER_AUTH_SECRET", "API_URL", "APP_URL", "API_PORT"],"tasks": {"dev": {"cache": false,