feat: update configs

This commit is contained in:
Amiram_se 2026-10-17 13:58:30 +04:00
parent d31903b4c0
commit bbd8789b9b
57 changed files with 547 additions and 277 deletions

39
.dockerignore Normal file
View File

@ -0,0 +1,39 @@
# The build context is the repo root. The build installs node_modules and writes .next itself, so local
# copies would only break the cache.
**/node_modules
**/.next
**/.nx
**/dist
**/coverage
**/*.tsbuildinfo
**/next-env.d.ts
**/*.log
.git
.github
.vscode
.idea
.claude
docs
graft
server-proxy.js
# Deploy files: changing them never rebuilds an image. .deploy/ holds each app's server secrets.
.deploy
.dockerignore
Dockerfile
tools/deploy.sh
tools/rollback.sh
# Generated by the next.config.ts plugins during next build.
apps/*/public/fonts
apps/*/public/icons/symbol-defs.svg
apps/*/public/sw.js
# Keys and certificates (next dev --experimental-https writes apps/<app>/certificates/).
**/*.pem
**/*.key
**/certificates
# Env files: none. tools/deploy.sh hands the app's env to next build as a bind mount, so no env file, a
# developer's local .env included, reaches a layer or the image.
**/.env*

5
.gitignore vendored
View File

@ -41,7 +41,7 @@ test-results
# Env (keep examples committed) # Env (keep examples committed)
.env .env
.env.* .env.*
!.env.example !.env.sample
# Logs # Logs
*.log *.log
@ -64,3 +64,6 @@ Thumbs.db
# Written by the pwa lib's writeServiceWorker on every build or dev start. # Written by the pwa lib's writeServiceWorker on every build or dev start.
apps/*/public/sw.js apps/*/public/sw.js
# Deploy host state: each app's .env.production for docker build (Dockerfile), never committed
.deploy/

72
Dockerfile Normal file
View File

@ -0,0 +1,72 @@
# syntax=docker/dockerfile:1.28
# check=error=true
# One Dockerfile for every Next.js app in apps/. The build context is the repo root and APP names the
# app's folder, so a new app needs no edit here. tools/deploy.sh builds and runs it; a build by hand also
# needs --build-context appenv=<folder holding the app's .env.production>.
# Debian 13 (glibc) in every stage: the runner runs the native binaries (sharp) the build installed.
# Change the tag and the digest together.
ARG NODE_IMAGE=docker.io/library/node:24.22.0-trixie-slim@sha256:7f486cabe892bff8fef04c0f7da8dba84a560be3e4e2740b7a86afc57ebec315
# The workspace install, shared by every app. Only the manifests and the lockfile come in, so a source
# edit never reinstalls dependencies.
FROM ${NODE_IMAGE} AS deps
ENV CI=true \
NEXT_TELEMETRY_DISABLED=1
WORKDIR /repo
# The exact pnpm from the root packageManager field ("pnpm@<version>").
COPY package.json ./
RUN --mount=type=cache,id=npm,target=/root/.npm \
npm install --global --no-audit --no-fund "pnpm@$(node -p "require('./package.json').packageManager.replace(/^pnpm@|\+.*$/g, '')")"
COPY --parents pnpm-lock.yaml pnpm-workspace.yaml .npmrc* patches* **/package.json ./
RUN --mount=type=cache,id=pnpm-store,target=/pnpm-store \
pnpm install --frozen-lockfile --store-dir=/pnpm-store
# next build for one app. The Turbopack cache mount keeps the next build of this app incremental.
FROM deps AS build
COPY . .
ARG APP
ARG NEXT_DEPLOYMENT_ID
WORKDIR /repo/apps/${APP:?}
# The app's env file comes from tools/deploy.sh as a bind mount: it's in no layer, and a changed value
# reruns this step. next build inlines its public values and validates the rest.
RUN --mount=type=cache,id=next-cache-${APP},target=/repo/apps/${APP}/.next/cache \
--mount=type=bind,from=appenv,source=.env.production,target=/repo/apps/${APP}/.env.production <<'SH'
set -eu
# next build type-checks against the declarations (dist/*.d.ts) of the projects the app's tsconfig.json
# references, and no checkout holds them: build them first, as each project's typecheck target does.
pnpm exec tsc --build --emitDeclarationOnly $(node -p "const ts = require('typescript'); ts.readConfigFile('tsconfig.json', ts.sys.readFile).config.references.map((r) => r.path).join(' ')")
pnpm exec next build
# next.config.ts writes these when it loads; a release without them breaks fonts, icons, or worker updates.
# Only apps that ship a service worker write sw.js (the admin panel has none, 0062).
test -d public/fonts && test -f public/icons/symbol-defs.svg \
|| { echo 'next build did not write public/fonts and public/icons/symbol-defs.svg' >&2; exit 1; }
if grep -q writeServiceWorker next.config.ts; then
test -f public/sw.js || { echo 'next build did not write public/sw.js' >&2; exit 1; }
fi
# Standalone copies the env file; the container mounts it at start instead, so the image holds no secret.
rm -f .next/standalone/apps/${APP}/.env*
SH
# The runtime image: the standalone server with its traced node_modules, public/, and .next/static.
FROM ${NODE_IMAGE} AS runner
# KEEP_ALIVE_TIMEOUT outlasts a proxy's usual 60 s upstream keepalive, so it never reuses a socket Node closed.
ENV NODE_ENV=production \
NEXT_TELEMETRY_DISABLED=1 \
HOSTNAME=0.0.0.0 \
PORT=3000 \
KEEP_ALIVE_TIMEOUT=65000
ARG APP
WORKDIR /app/apps/${APP}
COPY --from=build /repo/apps/${APP}/.next/standalone /app
COPY --from=build /repo/apps/${APP}/.next/static .next/static
COPY --from=build /repo/apps/${APP}/public public
# Every file belongs to root, so the app can't change its own code; only the image optimizer's cache is writable.
RUN install -d -o node -g node .next/cache
USER node
EXPOSE 3000
# tools/deploy.sh swaps a release in only after this check passes.
HEALTHCHECK --interval=10s --timeout=3s --start-period=30s --start-interval=2s --retries=3 \
CMD ["node", "-e", "fetch('http://127.0.0.1:' + process.env.PORT + '/healthz').then((r) => process.exit(r.ok ? 0 : 1), () => process.exit(1))"]
CMD ["node", "server.js"]

View File

@ -1,5 +1,13 @@
# Copy to .env.local. Public variables are inlined into the browser bundle: never put a secret in one. # Copy to .env.local. Public variables are inlined into the browser bundle: never put a secret in one.
NEXT_PUBLIC_SITE_URL=http://localhost:7001 NEXT_PUBLIC_SITE_URL=http://localhost:7001
# The API, one end point per side (0066), each an origin with no path. The browser calls
# NEXT_PUBLIC_CLIENT_END_POINT, the gateway's public origin, directly with the session cookies, so
# the gateway must allow this site's origin in CORS; next build inlines it. Server requests go to
# INTERNAL_END_POINT: the gateway's origin from inside the deployment network, server only.
NEXT_PUBLIC_CLIENT_END_POINT=http://localhost:3000
INTERNAL_END_POINT=http://localhost:3000
NEXT_PUBLIC_BALE_HANDLE=lumina_support NEXT_PUBLIC_BALE_HANDLE=lumina_support
NEXT_PUBLIC_TELEGRAM_HANDLE=lumina_support NEXT_PUBLIC_TELEGRAM_HANDLE=lumina_support
NEXT_PUBLIC_SUPPORT_HOURS=شنبه تا پنجشنبه، ۹ تا ۱۸ NEXT_PUBLIC_SUPPORT_HOURS=شنبه تا پنجشنبه، ۹ تا ۱۸
@ -9,10 +17,5 @@ NEXT_PUBLIC_SUPPORT_HOURS=شنبه تا پنجشنبه، ۹ تا ۱۸
# there unregisters the worker for every visitor on their next page load (the kill switch). # there unregisters the worker for every visitor on their next page load (the kill switch).
NEXT_PUBLIC_SERVICE_WORKER_ENABLED=false NEXT_PUBLIC_SERVICE_WORKER_ENABLED=false
# Server only: the gateway's origin from inside the deployment network. Server requests go # Only for steps that run without the real env (lint, type-check).
# there, and so does the browser's /api proxy (next.config rewrite, fixed at build time).
API_INTERNAL_ORIGIN=http://localhost:3000
# Only for steps that run without the real env (lint, type-check). A build still needs
# API_INTERNAL_ORIGIN: the /api rewrite keeps the value it was built with.
SKIP_ENV_VALIDATION=false SKIP_ENV_VALIDATION=false

View File

@ -8,12 +8,8 @@ import {
import type { NextConfig } from 'next'; import type { NextConfig } from 'next';
import path from 'node:path'; import path from 'node:path';
import { // Libs compile from source outside the app, so tracing and Turbopack both start at the workspace root.
API_PROXY_MAX_BODY, const workspaceRoot = path.join(__dirname, '../..');
API_PROXY_PATH,
API_PROXY_TIMEOUT_MS,
} from './src/constants';
import { apiInternalUrl } from './src/env/env.config';
// Fonts and the icon sprite keep fixed names; a changed font gets a new name, and the sprite a new // Fonts and the icon sprite keep fixed names; a changed font gets a new name, and the sprite a new
// ?v= (0011, 0012). Next serves public/ with max-age=0, so without this every visit asks for them again. // ?v= (0011, 0012). Next serves public/ with max-age=0, so without this every visit asks for them again.
@ -30,16 +26,19 @@ const security = [
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' }, { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
]; ];
// The edge nginx (0001) passes a streamed page on as each part renders instead of buffering it whole.
const streaming = [{ key: 'X-Accel-Buffering', value: 'no' }];
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
// The image runs .next/standalone/apps/<app>/server.js with only the traced files; it never loads
// this file at runtime, so the plugins below never run in the container.
output: 'standalone',
outputFileTracingRoot: workspaceRoot,
turbopack: { root: workspaceRoot },
poweredByHeader: false,
// Every visitor gets the metadata in <head>, where Chrome looks for the manifest and Safari for // Every visitor gets the metadata in <head>, where Chrome looks for the manifest and Safari for
// its home-screen tags; Next.js would otherwise stream it to the end of <body> (0054). // its home-screen tags; Next.js would otherwise stream it to the end of <body> (0054).
htmlLimitedBots: /.*/, htmlLimitedBots: /.*/,
// The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default
// and two ID images come close to its 10 MB body limit.
experimental: {
proxyTimeout: API_PROXY_TIMEOUT_MS,
proxyClientMaxBodySize: API_PROXY_MAX_BODY,
},
// Workspace packages export TypeScript source, so Next.js compiles them. // Workspace packages export TypeScript source, so Next.js compiles them.
transpilePackages: [ transpilePackages: [
'@lumina/market', '@lumina/market',
@ -48,23 +47,12 @@ const nextConfig: NextConfig = {
'@lumina/libs', '@lumina/libs',
'@lumina/tools', '@lumina/tools',
], ],
// The browser calls the API on this site's origin (`/api/v1/…`, `/api/files/…`), and the API
// calls are proxied to the gateway, so there is no CORS and the session cookies are this site's
// (0018).
async rewrites() {
return [
{
source: `${API_PROXY_PATH}/:path*`,
destination: `${apiInternalUrl()}/:path*`,
},
];
},
async headers() { async headers() {
// Only Next calls `headers()`, on `next dev` and `next build`, so the worker is written here, as // Only Next calls `headers()`, on `next dev` and `next build`, so the worker is written here, as
// island's plugins write theirs. Next runs from the app's folder, as every Nx target does. // island's plugins write theirs. Next runs from the app's folder, as every Nx target does.
writeServiceWorker({ publicDir: path.join(process.cwd(), 'public') }); writeServiceWorker({ publicDir: path.join(process.cwd(), 'public') });
return [ return [
{ source: '/:path*', headers: security }, { source: '/:path*', headers: [...security, ...streaming] },
{ source: '/fonts/:path*', headers: immutable }, { source: '/fonts/:path*', headers: immutable },
{ source: '/icons/:path*', headers: immutable }, { source: '/icons/:path*', headers: immutable },
// Revalidated on every update check, so a new worker reaches visitors at their next // Revalidated on every update check, so a new worker reaches visitors at their next

View File

@ -54,6 +54,7 @@ export default async function LandingPage() {
siteHost={displayUrl('')} siteHost={displayUrl('')}
labels={labels} labels={labels}
/> />
<p>amiram v2</p>
<Element <Element
tag="script" tag="script"
type="application/ld+json" type="application/ld+json"

View File

@ -0,0 +1,12 @@
import { serverEnv } from '../../env/server';
export const dynamic = 'force-dynamic';
// The image's health check: importing the server env validates it, so a release with missing or invalid
// env answers 500. It calls no back end, so a back-end outage never fails the check.
export function GET(): Response {
void serverEnv;
return new Response('ok', {
headers: { 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' },
});
}

View File

@ -12,25 +12,25 @@ import {
suspendedSessionOf, suspendedSessionOf,
} from '@lumina/market/features/auth'; } from '@lumina/market/features/auth';
import { API_PROXY_PATH, API_VERSION_PATH } from '../constants'; import { API_VERSION_PATH } from '../constants';
import { clientEnv } from '../env'; import { clientEnv } from '../env';
import { ERROR_HANDLER_CONFIG } from './error-reporting'; import { ERROR_HANDLER_CONFIG } from './error-reporting';
// Fills the client module graph with public values only, before client components render (during // Fills the client module graph with public values only, before client components render (during
// SSR and in the browser). Idempotent: safe to run again. // SSR and in the browser). Idempotent: safe to run again.
setMarketEnv({ setMarketEnv({
apiBaseUrl: API_PROXY_PATH, apiBaseUrl: clientEnv.NEXT_PUBLIC_CLIENT_END_POINT,
baleHandle: clientEnv.NEXT_PUBLIC_BALE_HANDLE, baleHandle: clientEnv.NEXT_PUBLIC_BALE_HANDLE,
telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE, telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE,
supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS, supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS,
}); });
// The browser calls the API on this site's origin, proxied to the gateway (0018). The session // The browser calls the gateway directly at its public origin (0066). The session
// lives in HttpOnly cookies the browser sends itself. A 401 runs one refresh for the whole app; // lives in HttpOnly cookies the browser sends itself. A 401 runs one refresh for the whole app;
// when that fails the session is over and the shell signs the user out. A 401 `ACCOUNT_SUSPENDED` // when that fails the session is over and the shell signs the user out. A 401 `ACCOUNT_SUSPENDED`
// never refreshes: the account was suspended mid-session, so the session ends and the page halts // never refreshes: the account was suspended mid-session, so the session ends and the page halts
// (J01-3d), once, whichever request learns it first. // (J01-3d), once, whichever request learns it first.
http.configure({ http.configure({
baseUrl: `${API_PROXY_PATH}${API_VERSION_PATH}`, baseUrl: `${clientEnv.NEXT_PUBLIC_CLIENT_END_POINT}${API_VERSION_PATH}`,
refresh: { refresh: {
endpoint: AUTH_ENDPOINTS.refresh, endpoint: AUTH_ENDPOINTS.refresh,
shouldRefresh: (error) => shouldRefresh: (error) =>

View File

@ -8,11 +8,7 @@ import { setEnv as setMarketEnv } from '@lumina/market/env';
import { SERVER_RESOURCES } from '@lumina/market/server'; import { SERVER_RESOURCES } from '@lumina/market/server';
import { cookies } from 'next/headers'; import { cookies } from 'next/headers';
import { import { API_VERSION_PATH, FORWARDED_COOKIES } from '../constants';
API_PROXY_PATH,
API_VERSION_PATH,
FORWARDED_COOKIES,
} from '../constants';
import { clientEnv } from '../env'; import { clientEnv } from '../env';
import { serverEnv } from '../env/server'; import { serverEnv } from '../env/server';
import { i18n } from '../i18n'; import { i18n } from '../i18n';
@ -20,16 +16,17 @@ import { ERROR_HANDLER_CONFIG } from './error-reporting';
// Fills the server module graph once, before rendering. Idempotent: safe to run again. // Fills the server module graph once, before rendering. Idempotent: safe to run again.
setMarketEnv({ setMarketEnv({
apiBaseUrl: API_PROXY_PATH, apiBaseUrl: clientEnv.NEXT_PUBLIC_CLIENT_END_POINT,
baleHandle: clientEnv.NEXT_PUBLIC_BALE_HANDLE, baleHandle: clientEnv.NEXT_PUBLIC_BALE_HANDLE,
telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE, telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE,
supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS, supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS,
}); });
// Server requests forward only the allowlisted cookies, never the session: the server render is // Server requests go straight to the gateway (`INTERNAL_END_POINT`, 0066) and forward only the
// the same for every visitor, and the browser loads whatever depends on the viewer. Read on each // allowlisted cookies, never the session: the server render is the same for every visitor, and the
// request; nothing per visitor is kept in module state. // browser loads whatever depends on the viewer. Read on each request; nothing per visitor is kept
// in module state.
configureServerHttp({ configureServerHttp({
baseUrl: `${serverEnv.API_INTERNAL_ORIGIN}${API_VERSION_PATH}`, baseUrl: `${serverEnv.INTERNAL_END_POINT}${API_VERSION_PATH}`,
getCookieHeader: async () => getCookieHeader: async () =>
(await cookies()) (await cookies())
.getAll() .getAll()

View File

@ -1,22 +1,2 @@
/** Every gateway route except `/files/*` sits under this prefix. */ /** Every gateway route except `/files/*` sits under this prefix. */
export const API_VERSION_PATH = '/v1'; export const API_VERSION_PATH = '/v1';
/**
* Where the browser reaches the API: this site's own origin, under this path. next.config.ts
* rewrites it to the gateway (`API_INTERNAL_ORIGIN`), so no browser request is cross-origin and
* the session cookies belong to this site (0018). The server render calls the gateway directly.
*/
export const API_PROXY_PATH = '/api';
/**
* How long the `/api` proxy waits for the gateway. Next.js stops at 30 seconds by default; an
* upload (two 5 MB ID images, post media) on a slow connection takes longer, and the HTTP lib
* sets no timeout for uploads.
*/
export const API_PROXY_TIMEOUT_MS = 120_000;
/**
* The largest request body the `/api` proxy passes on (Next.js cuts at 10 MB by default). Creator
* registration and verification send two 5 MB ID images plus the form in one request.
*/
export const API_PROXY_MAX_BODY = '12mb';

View File

@ -1,7 +1,2 @@
export { export { API_VERSION_PATH } from './api';
API_PROXY_MAX_BODY,
API_PROXY_PATH,
API_PROXY_TIMEOUT_MS,
API_VERSION_PATH,
} from './api';
export { FORWARDED_COOKIES } from './cookies'; export { FORWARDED_COOKIES } from './cookies';

View File

@ -1,4 +1,4 @@
import { createClientEnv } from '@lumina/libs/env'; import { createClientEnv, origin } from '@lumina/libs/env';
import * as v from 'valibot'; import * as v from 'valibot';
const required = v.pipe(v.string(), v.nonEmpty()); const required = v.pipe(v.string(), v.nonEmpty());
@ -13,6 +13,11 @@ export const clientEnv = createClientEnv({
prefix: 'NEXT_PUBLIC_', prefix: 'NEXT_PUBLIC_',
schema: { schema: {
NEXT_PUBLIC_SITE_URL: url, NEXT_PUBLIC_SITE_URL: url,
/**
* The gateway's public origin: the browser calls it directly, with the session cookies (0066).
* Media URLs use it too, so the server render writes the same address.
*/
NEXT_PUBLIC_CLIENT_END_POINT: origin,
NEXT_PUBLIC_BALE_HANDLE: required, NEXT_PUBLIC_BALE_HANDLE: required,
NEXT_PUBLIC_TELEGRAM_HANDLE: required, NEXT_PUBLIC_TELEGRAM_HANDLE: required,
NEXT_PUBLIC_SUPPORT_HOURS: required, NEXT_PUBLIC_SUPPORT_HOURS: required,
@ -21,6 +26,7 @@ export const clientEnv = createClientEnv({
}, },
runtimeEnv: { runtimeEnv: {
NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL, NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,
NEXT_PUBLIC_CLIENT_END_POINT: process.env.NEXT_PUBLIC_CLIENT_END_POINT,
NEXT_PUBLIC_BALE_HANDLE: process.env.NEXT_PUBLIC_BALE_HANDLE, NEXT_PUBLIC_BALE_HANDLE: process.env.NEXT_PUBLIC_BALE_HANDLE,
NEXT_PUBLIC_TELEGRAM_HANDLE: process.env.NEXT_PUBLIC_TELEGRAM_HANDLE, NEXT_PUBLIC_TELEGRAM_HANDLE: process.env.NEXT_PUBLIC_TELEGRAM_HANDLE,
NEXT_PUBLIC_SUPPORT_HOURS: process.env.NEXT_PUBLIC_SUPPORT_HOURS, NEXT_PUBLIC_SUPPORT_HOURS: process.env.NEXT_PUBLIC_SUPPORT_HOURS,

View File

@ -1,16 +0,0 @@
import { origin } from '@lumina/libs/env';
import * as v from 'valibot';
/**
* For next.config.ts only: the gateway the `/api` rewrite proxies to. No `server-only` here, as
* the config loads outside React. `next build` writes rewrites into its output, so the value is
* the one at build time (0018) and `SKIP_ENV_VALIDATION` can't skip it: a build without it fails
* here, rather than shipping a proxy to the wrong gateway.
*/
export function apiInternalUrl(): string {
const result = v.safeParse(origin, process.env.API_INTERNAL_ORIGIN);
if (result.success) return result.output;
throw new Error(
`API_INTERNAL_ORIGIN is needed to build: next.config rewrites /api to it and next build keeps the value (0018). ${result.issues[0].message}`,
);
}

View File

@ -7,8 +7,8 @@ import * as v from 'valibot';
/** Server variables; only server code imports them, through `env/server`. */ /** Server variables; only server code imports them, through `env/server`. */
export const serverEnv = createServerEnv({ export const serverEnv = createServerEnv({
schema: { schema: {
/** The gateway from inside the deployment network: server requests and the `/api` proxy. */ /** The gateway from inside the deployment network, for server requests only (0066). */
API_INTERNAL_ORIGIN: origin, INTERNAL_END_POINT: origin,
/** /**
* Set by Next.js itself, never in `.env`: `phase-production-build` while `next build` * Set by Next.js itself, never in `.env`: `phase-production-build` while `next build`
* prerenders pages (the landing, 0026). * prerenders pages (the landing, 0026).

View File

@ -1,5 +1,13 @@
# Copy to .env.local. Public variables are inlined into the browser bundle: never put a secret in one. # Copy to .env.local. Public variables are inlined into the browser bundle: never put a secret in one.
NEXT_PUBLIC_SITE_URL=http://localhost:7000 NEXT_PUBLIC_SITE_URL=http://localhost:7000
# The API, one end point per side (0066), each an origin with no path. The browser calls
# NEXT_PUBLIC_CLIENT_END_POINT, the gateway's public origin, directly with the session cookies, so
# the gateway must allow this site's origin in CORS; next build inlines it. Server requests go to
# INTERNAL_END_POINT: the gateway's origin from inside the deployment network, server only.
NEXT_PUBLIC_CLIENT_END_POINT=http://localhost:3000
INTERNAL_END_POINT=http://localhost:3000
NEXT_PUBLIC_BALE_HANDLE=lumina_support NEXT_PUBLIC_BALE_HANDLE=lumina_support
NEXT_PUBLIC_TELEGRAM_HANDLE=lumina_support NEXT_PUBLIC_TELEGRAM_HANDLE=lumina_support
NEXT_PUBLIC_SUPPORT_HOURS=شنبه تا پنجشنبه، ۹ تا ۱۸ NEXT_PUBLIC_SUPPORT_HOURS=شنبه تا پنجشنبه، ۹ تا ۱۸
@ -9,10 +17,5 @@ NEXT_PUBLIC_SUPPORT_HOURS=شنبه تا پنجشنبه، ۹ تا ۱۸
# there unregisters the worker for every visitor on their next page load (the kill switch). # there unregisters the worker for every visitor on their next page load (the kill switch).
NEXT_PUBLIC_SERVICE_WORKER_ENABLED=false NEXT_PUBLIC_SERVICE_WORKER_ENABLED=false
# Server only: the gateway's origin from inside the deployment network. Server requests go # Only for steps that run without the real env (lint, type-check).
# there, and so does the browser's /api proxy (next.config rewrite, fixed at build time).
API_INTERNAL_ORIGIN=http://localhost:3000
# Only for steps that run without the real env (lint, type-check). A build still needs
# API_INTERNAL_ORIGIN: the /api rewrite keeps the value it was built with.
SKIP_ENV_VALIDATION=false SKIP_ENV_VALIDATION=false

View File

@ -8,12 +8,8 @@ import {
import type { NextConfig } from 'next'; import type { NextConfig } from 'next';
import path from 'node:path'; import path from 'node:path';
import { // Libs compile from source outside the app, so tracing and Turbopack both start at the workspace root.
API_PROXY_MAX_BODY, const workspaceRoot = path.join(__dirname, '../..');
API_PROXY_PATH,
API_PROXY_TIMEOUT_MS,
} from './src/constants';
import { apiInternalUrl } from './src/env/env.config';
// Fonts and the icon sprite keep fixed names; a changed font gets a new name, and the sprite a new // Fonts and the icon sprite keep fixed names; a changed font gets a new name, and the sprite a new
// ?v= (0011, 0012). Next serves public/ with max-age=0, so without this every visit asks for them again. // ?v= (0011, 0012). Next serves public/ with max-age=0, so without this every visit asks for them again.
@ -30,16 +26,19 @@ const security = [
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' }, { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
]; ];
// The edge nginx (0001) passes a streamed page on as each part renders instead of buffering it whole.
const streaming = [{ key: 'X-Accel-Buffering', value: 'no' }];
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
// The image runs .next/standalone/apps/<app>/server.js with only the traced files; it never loads
// this file at runtime, so the plugins below never run in the container.
output: 'standalone',
outputFileTracingRoot: workspaceRoot,
turbopack: { root: workspaceRoot },
poweredByHeader: false,
// Every visitor gets the metadata in <head>, where Chrome looks for the manifest and Safari for // Every visitor gets the metadata in <head>, where Chrome looks for the manifest and Safari for
// its home-screen tags; Next.js would otherwise stream it to the end of <body> (0054). // its home-screen tags; Next.js would otherwise stream it to the end of <body> (0054).
htmlLimitedBots: /.*/, htmlLimitedBots: /.*/,
// The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default
// and two ID images come close to its 10 MB body limit.
experimental: {
proxyTimeout: API_PROXY_TIMEOUT_MS,
proxyClientMaxBodySize: API_PROXY_MAX_BODY,
},
// Workspace packages export TypeScript source, so Next.js compiles them. // Workspace packages export TypeScript source, so Next.js compiles them.
transpilePackages: [ transpilePackages: [
'@lumina/market', '@lumina/market',
@ -48,23 +47,12 @@ const nextConfig: NextConfig = {
'@lumina/libs', '@lumina/libs',
'@lumina/tools', '@lumina/tools',
], ],
// The browser calls the API on this site's origin (`/api/v1/…`, `/api/files/…`), and the API
// calls are proxied to the gateway, so there is no CORS and the session cookies are this site's
// (0018).
async rewrites() {
return [
{
source: `${API_PROXY_PATH}/:path*`,
destination: `${apiInternalUrl()}/:path*`,
},
];
},
async headers() { async headers() {
// Only Next calls `headers()`, on `next dev` and `next build`, so the worker is written here, as // Only Next calls `headers()`, on `next dev` and `next build`, so the worker is written here, as
// island's plugins write theirs. Next runs from the app's folder, as every Nx target does. // island's plugins write theirs. Next runs from the app's folder, as every Nx target does.
writeServiceWorker({ publicDir: path.join(process.cwd(), 'public') }); writeServiceWorker({ publicDir: path.join(process.cwd(), 'public') });
return [ return [
{ source: '/:path*', headers: security }, { source: '/:path*', headers: [...security, ...streaming] },
{ source: '/fonts/:path*', headers: immutable }, { source: '/fonts/:path*', headers: immutable },
{ source: '/icons/:path*', headers: immutable }, { source: '/icons/:path*', headers: immutable },
// Revalidated on every update check, so a new worker reaches visitors at their next // Revalidated on every update check, so a new worker reaches visitors at their next

View File

@ -0,0 +1,12 @@
import { serverEnv } from '../../env/server';
export const dynamic = 'force-dynamic';
// The image's health check: importing the server env validates it, so a release with missing or invalid
// env answers 500. It calls no back end, so a back-end outage never fails the check.
export function GET(): Response {
void serverEnv;
return new Response('ok', {
headers: { 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' },
});
}

View File

@ -12,25 +12,25 @@ import {
suspendedSessionOf, suspendedSessionOf,
} from '@lumina/market/features/auth'; } from '@lumina/market/features/auth';
import { API_PROXY_PATH, API_VERSION_PATH } from '../constants'; import { API_VERSION_PATH } from '../constants';
import { clientEnv } from '../env'; import { clientEnv } from '../env';
import { ERROR_HANDLER_CONFIG } from './error-reporting'; import { ERROR_HANDLER_CONFIG } from './error-reporting';
// Fills the client module graph with public values only, before client components render (during // Fills the client module graph with public values only, before client components render (during
// SSR and in the browser). Idempotent: safe to run again. // SSR and in the browser). Idempotent: safe to run again.
setMarketEnv({ setMarketEnv({
apiBaseUrl: API_PROXY_PATH, apiBaseUrl: clientEnv.NEXT_PUBLIC_CLIENT_END_POINT,
baleHandle: clientEnv.NEXT_PUBLIC_BALE_HANDLE, baleHandle: clientEnv.NEXT_PUBLIC_BALE_HANDLE,
telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE, telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE,
supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS, supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS,
}); });
// The browser calls the API on this site's origin, proxied to the gateway (0018). The session // The browser calls the gateway directly at its public origin (0066). The session
// lives in HttpOnly cookies the browser sends itself. A 401 runs one refresh for the whole app; // lives in HttpOnly cookies the browser sends itself. A 401 runs one refresh for the whole app;
// when that fails the session is over and the shell signs the user out. A 401 `ACCOUNT_SUSPENDED` // when that fails the session is over and the shell signs the user out. A 401 `ACCOUNT_SUSPENDED`
// never refreshes: the account was suspended mid-session, so the session ends and the page halts // never refreshes: the account was suspended mid-session, so the session ends and the page halts
// (J01-3d), once, whichever request learns it first. // (J01-3d), once, whichever request learns it first.
http.configure({ http.configure({
baseUrl: `${API_PROXY_PATH}${API_VERSION_PATH}`, baseUrl: `${clientEnv.NEXT_PUBLIC_CLIENT_END_POINT}${API_VERSION_PATH}`,
refresh: { refresh: {
endpoint: AUTH_ENDPOINTS.refresh, endpoint: AUTH_ENDPOINTS.refresh,
shouldRefresh: (error) => shouldRefresh: (error) =>

View File

@ -8,11 +8,7 @@ import { setEnv as setMarketEnv } from '@lumina/market/env';
import { SERVER_RESOURCES } from '@lumina/market/server'; import { SERVER_RESOURCES } from '@lumina/market/server';
import { cookies } from 'next/headers'; import { cookies } from 'next/headers';
import { import { API_VERSION_PATH, FORWARDED_COOKIES } from '../constants';
API_PROXY_PATH,
API_VERSION_PATH,
FORWARDED_COOKIES,
} from '../constants';
import { clientEnv } from '../env'; import { clientEnv } from '../env';
import { serverEnv } from '../env/server'; import { serverEnv } from '../env/server';
import { i18n } from '../i18n'; import { i18n } from '../i18n';
@ -20,16 +16,17 @@ import { ERROR_HANDLER_CONFIG } from './error-reporting';
// Fills the server module graph once, before rendering. Idempotent: safe to run again. // Fills the server module graph once, before rendering. Idempotent: safe to run again.
setMarketEnv({ setMarketEnv({
apiBaseUrl: API_PROXY_PATH, apiBaseUrl: clientEnv.NEXT_PUBLIC_CLIENT_END_POINT,
baleHandle: clientEnv.NEXT_PUBLIC_BALE_HANDLE, baleHandle: clientEnv.NEXT_PUBLIC_BALE_HANDLE,
telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE, telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE,
supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS, supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS,
}); });
// Server requests forward only the allowlisted cookies, never the session: the server render is // Server requests go straight to the gateway (`INTERNAL_END_POINT`, 0066) and forward only the
// the same for every visitor, and the browser loads whatever depends on the viewer. Read on each // allowlisted cookies, never the session: the server render is the same for every visitor, and the
// request; nothing per visitor is kept in module state. // browser loads whatever depends on the viewer. Read on each request; nothing per visitor is kept
// in module state.
configureServerHttp({ configureServerHttp({
baseUrl: `${serverEnv.API_INTERNAL_ORIGIN}${API_VERSION_PATH}`, baseUrl: `${serverEnv.INTERNAL_END_POINT}${API_VERSION_PATH}`,
getCookieHeader: async () => getCookieHeader: async () =>
(await cookies()) (await cookies())
.getAll() .getAll()

View File

@ -1,22 +1,2 @@
/** Every gateway route except `/files/*` sits under this prefix. */ /** Every gateway route except `/files/*` sits under this prefix. */
export const API_VERSION_PATH = '/v1'; export const API_VERSION_PATH = '/v1';
/**
* Where the browser reaches the API: this site's own origin, under this path. next.config.ts
* rewrites it to the gateway (`API_INTERNAL_ORIGIN`), so no browser request is cross-origin and
* the session cookies belong to this site (0018). The server render calls the gateway directly.
*/
export const API_PROXY_PATH = '/api';
/**
* How long the `/api` proxy waits for the gateway. Next.js stops at 30 seconds by default; an
* upload (two 5 MB ID images, post media) on a slow connection takes longer, and the HTTP lib
* sets no timeout for uploads.
*/
export const API_PROXY_TIMEOUT_MS = 120_000;
/**
* The largest request body the `/api` proxy passes on (Next.js cuts at 10 MB by default). Creator
* registration and verification send two 5 MB ID images plus the form in one request.
*/
export const API_PROXY_MAX_BODY = '12mb';

View File

@ -1,7 +1,2 @@
export { export { API_VERSION_PATH } from './api';
API_PROXY_MAX_BODY,
API_PROXY_PATH,
API_PROXY_TIMEOUT_MS,
API_VERSION_PATH,
} from './api';
export { FORWARDED_COOKIES } from './cookies'; export { FORWARDED_COOKIES } from './cookies';

View File

@ -1,4 +1,4 @@
import { createClientEnv } from '@lumina/libs/env'; import { createClientEnv, origin } from '@lumina/libs/env';
import * as v from 'valibot'; import * as v from 'valibot';
const required = v.pipe(v.string(), v.nonEmpty()); const required = v.pipe(v.string(), v.nonEmpty());
@ -13,6 +13,11 @@ export const clientEnv = createClientEnv({
prefix: 'NEXT_PUBLIC_', prefix: 'NEXT_PUBLIC_',
schema: { schema: {
NEXT_PUBLIC_SITE_URL: url, NEXT_PUBLIC_SITE_URL: url,
/**
* The gateway's public origin: the browser calls it directly, with the session cookies (0066).
* Media URLs use it too, so the server render writes the same address.
*/
NEXT_PUBLIC_CLIENT_END_POINT: origin,
NEXT_PUBLIC_BALE_HANDLE: required, NEXT_PUBLIC_BALE_HANDLE: required,
NEXT_PUBLIC_TELEGRAM_HANDLE: required, NEXT_PUBLIC_TELEGRAM_HANDLE: required,
NEXT_PUBLIC_SUPPORT_HOURS: required, NEXT_PUBLIC_SUPPORT_HOURS: required,
@ -21,6 +26,7 @@ export const clientEnv = createClientEnv({
}, },
runtimeEnv: { runtimeEnv: {
NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL, NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,
NEXT_PUBLIC_CLIENT_END_POINT: process.env.NEXT_PUBLIC_CLIENT_END_POINT,
NEXT_PUBLIC_BALE_HANDLE: process.env.NEXT_PUBLIC_BALE_HANDLE, NEXT_PUBLIC_BALE_HANDLE: process.env.NEXT_PUBLIC_BALE_HANDLE,
NEXT_PUBLIC_TELEGRAM_HANDLE: process.env.NEXT_PUBLIC_TELEGRAM_HANDLE, NEXT_PUBLIC_TELEGRAM_HANDLE: process.env.NEXT_PUBLIC_TELEGRAM_HANDLE,
NEXT_PUBLIC_SUPPORT_HOURS: process.env.NEXT_PUBLIC_SUPPORT_HOURS, NEXT_PUBLIC_SUPPORT_HOURS: process.env.NEXT_PUBLIC_SUPPORT_HOURS,

View File

@ -1,16 +0,0 @@
import { origin } from '@lumina/libs/env';
import * as v from 'valibot';
/**
* For next.config.ts only: the gateway the `/api` rewrite proxies to. No `server-only` here, as
* the config loads outside React. `next build` writes rewrites into its output, so the value is
* the one at build time (0018) and `SKIP_ENV_VALIDATION` can't skip it: a build without it fails
* here, rather than shipping a proxy to the wrong gateway.
*/
export function apiInternalUrl(): string {
const result = v.safeParse(origin, process.env.API_INTERNAL_ORIGIN);
if (result.success) return result.output;
throw new Error(
`API_INTERNAL_ORIGIN is needed to build: next.config rewrites /api to it and next build keeps the value (0018). ${result.issues[0].message}`,
);
}

View File

@ -7,8 +7,8 @@ import * as v from 'valibot';
/** Server variables; only server code imports them, through `env/server`. */ /** Server variables; only server code imports them, through `env/server`. */
export const serverEnv = createServerEnv({ export const serverEnv = createServerEnv({
schema: { schema: {
/** The gateway from inside the deployment network: server requests and the `/api` proxy. */ /** The gateway from inside the deployment network, for server requests only (0066). */
API_INTERNAL_ORIGIN: origin, INTERNAL_END_POINT: origin,
/** /**
* Set by Next.js itself, never in `.env`: `phase-production-build` while `next build` * Set by Next.js itself, never in `.env`: `phase-production-build` while `next build`
* prerenders pages (the landing, 0026). * prerenders pages (the landing, 0026).

View File

@ -1,11 +0,0 @@
# Copy to .env.local. Public variables are inlined into the browser bundle: never put a secret in one.
NEXT_PUBLIC_SITE_URL=http://localhost:7002
# Server only: the admin API's origin from inside the deployment network (0061). The browser's
# /api proxy goes there (next.config rewrite, fixed at build time). The admin app never calls the
# public gateway.
ADMIN_API_INTERNAL_ORIGIN=http://localhost:9010
# Only for steps that run without the real env (lint, type-check). A build still needs
# ADMIN_API_INTERNAL_ORIGIN: the /api rewrite keeps the value it was built with.
SKIP_ENV_VALIDATION=false

View File

@ -0,0 +1,12 @@
# Copy to .env.local. Public variables are inlined into the browser bundle: never put a secret in one.
NEXT_PUBLIC_SITE_URL=http://localhost:7002
# The API, one end point per side (0066), each an origin with no path. The browser calls
# NEXT_PUBLIC_CLIENT_END_POINT, the admin API's public origin, directly with the session cookies, so
# the admin API must allow this site's origin in CORS; next build inlines it. Server requests go to
# INTERNAL_END_POINT: the admin API's origin from inside the deployment network, server only.
NEXT_PUBLIC_CLIENT_END_POINT=http://localhost:9010
INTERNAL_END_POINT=http://localhost:9010
# Only for steps that run without the real env (lint, type-check).
SKIP_ENV_VALIDATION=false

View File

@ -1,13 +1,10 @@
import { withFontCopy } from '@lumina/island/tools/font-copy-plugin'; import { withFontCopy } from '@lumina/island/tools/font-copy-plugin';
import { withIconSprite } from '@lumina/island/tools/icon-sprite-plugin'; import { withIconSprite } from '@lumina/island/tools/icon-sprite-plugin';
import type { NextConfig } from 'next'; import type { NextConfig } from 'next';
import path from 'node:path';
import { // Libs compile from source outside the app, so tracing and Turbopack both start at the workspace root.
API_PROXY_MAX_BODY, const workspaceRoot = path.join(__dirname, '../..');
API_PROXY_PATH,
API_PROXY_TIMEOUT_MS,
} from './src/constants';
import { adminApiInternalUrl } from './src/env/env.config';
// Fonts and the icon sprite keep fixed names (0011, 0012); Next serves public/ with max-age=0. // Fonts and the icon sprite keep fixed names (0011, 0012); Next serves public/ with max-age=0.
const immutable = [ const immutable = [
@ -23,16 +20,21 @@ const security = [
{ key: 'X-Robots-Tag', value: 'noindex, nofollow' }, { key: 'X-Robots-Tag', value: 'noindex, nofollow' },
]; ];
// The edge nginx (0001) passes a streamed page on as each part renders instead of buffering it whole.
const streaming = [{ key: 'X-Accel-Buffering', value: 'no' }];
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
// The image runs .next/standalone/apps/<app>/server.js with only the traced files; it never loads
// this file at runtime, so the plugins below never run in the container.
output: 'standalone',
outputFileTracingRoot: workspaceRoot,
turbopack: { root: workspaceRoot },
poweredByHeader: false,
// Set when the panel shares an origin with the market apps under a path (e.g. `/admin`); empty // Set when the panel shares an origin with the market apps under a path (e.g. `/admin`); empty
// in local dev, where the panel has its own port. // in local dev, where the panel has its own port.
basePath: process.env.NEXT_BASE_PATH ?? '', basePath: process.env.NEXT_BASE_PATH ?? '',
// Metadata always in <head> (0054). // Metadata always in <head> (0054).
htmlLimitedBots: /.*/, htmlLimitedBots: /.*/,
experimental: {
proxyTimeout: API_PROXY_TIMEOUT_MS,
proxyClientMaxBodySize: API_PROXY_MAX_BODY,
},
// Workspace packages export TypeScript source, so Next.js compiles them. // Workspace packages export TypeScript source, so Next.js compiles them.
transpilePackages: [ transpilePackages: [
'@lumina/garden-roof', '@lumina/garden-roof',
@ -41,20 +43,10 @@ const nextConfig: NextConfig = {
'@lumina/libs', '@lumina/libs',
'@lumina/tools', '@lumina/tools',
], ],
// The browser calls the admin API on this site's origin (`/api/v1/admin/…`), proxied to // No service worker or manifest: the panel isn't installable (0062).
// admin-api, so there is no CORS and the session cookies are this site's (0061). No service
// worker or manifest: the panel isn't installable (0062).
async rewrites() {
return [
{
source: `${API_PROXY_PATH}/:path*`,
destination: `${adminApiInternalUrl()}/:path*`,
},
];
},
async headers() { async headers() {
return [ return [
{ source: '/:path*', headers: security }, { source: '/:path*', headers: [...security, ...streaming] },
{ source: '/fonts/:path*', headers: immutable }, { source: '/fonts/:path*', headers: immutable },
{ source: '/icons/:path*', headers: immutable }, { source: '/icons/:path*', headers: immutable },
]; ];

View File

@ -0,0 +1,12 @@
import { serverEnv } from '../../env/server';
export const dynamic = 'force-dynamic';
// The image's health check: importing the server env validates it, so a release with missing or invalid
// env answers 500. It calls no back end, so an admin-api outage never fails the check.
export function GET(): Response {
void serverEnv;
return new Response('ok', {
headers: { 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' },
});
}

View File

@ -5,17 +5,18 @@ import { configureErrorHandler } from '@lumina/libs/error-handler';
import { eventEmitter } from '@lumina/libs/event-emitter'; import { eventEmitter } from '@lumina/libs/event-emitter';
import { http } from '@lumina/libs/http'; import { http } from '@lumina/libs/http';
import { API_PROXY_PATH, API_VERSION_PATH } from '../constants'; import { API_VERSION_PATH } from '../constants';
import { clientEnv } from '../env';
import { ERROR_HANDLER_CONFIG } from './error-reporting'; import { ERROR_HANDLER_CONFIG } from './error-reporting';
// Fills the client module graph with public values only, before client components render (during // Fills the client module graph with public values only, before client components render (during
// SSR and in the browser). Idempotent: safe to run again. // SSR and in the browser). Idempotent: safe to run again.
setGardenRoofEnv({ apiBaseUrl: API_PROXY_PATH }); setGardenRoofEnv({ apiBaseUrl: clientEnv.NEXT_PUBLIC_CLIENT_END_POINT });
// The browser calls the admin API on this site's origin, proxied to admin-api (0061). The session // The browser calls admin-api directly at its public origin (0061, 0066). The session
// lives in HttpOnly cookies the browser sends itself. A 401 runs one refresh for the whole app; // lives in HttpOnly cookies the browser sends itself. A 401 runs one refresh for the whole app;
// when that fails the session is over and the shell signs the admin out. // when that fails the session is over and the shell signs the admin out.
http.configure({ http.configure({
baseUrl: `${API_PROXY_PATH}${API_VERSION_PATH}`, baseUrl: `${clientEnv.NEXT_PUBLIC_CLIENT_END_POINT}${API_VERSION_PATH}`,
refresh: { refresh: {
endpoint: AUTH_ENDPOINTS.refresh, endpoint: AUTH_ENDPOINTS.refresh,
onFailure: () => { onFailure: () => {

View File

@ -3,10 +3,10 @@ import 'server-only';
import { setEnv as setGardenRoofEnv } from '@lumina/garden-roof/env'; import { setEnv as setGardenRoofEnv } from '@lumina/garden-roof/env';
import { configureErrorHandler } from '@lumina/libs/error-handler'; import { configureErrorHandler } from '@lumina/libs/error-handler';
import { API_PROXY_PATH } from '../constants'; import { clientEnv } from '../env';
import { ERROR_HANDLER_CONFIG } from './error-reporting'; import { ERROR_HANDLER_CONFIG } from './error-reporting';
// Fills the server module graph once, before rendering. The server reads nothing from the admin // Fills the server module graph once, before rendering. The server reads nothing from the admin
// API (0062): every panel read runs in the browser, so no server HTTP client is configured. // API (0062): every panel read runs in the browser, so no server HTTP client is configured.
setGardenRoofEnv({ apiBaseUrl: API_PROXY_PATH }); setGardenRoofEnv({ apiBaseUrl: clientEnv.NEXT_PUBLIC_CLIENT_END_POINT });
configureErrorHandler(ERROR_HANDLER_CONFIG); configureErrorHandler(ERROR_HANDLER_CONFIG);

View File

@ -1,15 +1,2 @@
/** Every admin API route sits under this prefix. */ /** Every admin API route sits under this prefix. */
export const API_VERSION_PATH = '/v1'; export const API_VERSION_PATH = '/v1';
/**
* Where the browser reaches the admin API: this site's own origin, under this path.
* next.config.ts rewrites it to `admin-api` (`ADMIN_API_INTERNAL_ORIGIN`), so no browser request
* is cross-origin and the session cookies belong to this site (0061, as 0018).
*/
export const API_PROXY_PATH = '/api';
/** How long the `/api` proxy waits for the admin API; a payout receipt upload outlasts 30 s. */
export const API_PROXY_TIMEOUT_MS = 120_000;
/** The largest request body the `/api` proxy passes on: a payout receipt (5 MB) with its form. */
export const API_PROXY_MAX_BODY = '8mb';

View File

@ -1,6 +1 @@
export { export { API_VERSION_PATH } from './api';
API_PROXY_MAX_BODY,
API_PROXY_PATH,
API_PROXY_TIMEOUT_MS,
API_VERSION_PATH,
} from './api';

View File

@ -1,4 +1,4 @@
import { createClientEnv } from '@lumina/libs/env'; import { createClientEnv, origin } from '@lumina/libs/env';
import * as v from 'valibot'; import * as v from 'valibot';
const url = v.pipe(v.string(), v.url()); const url = v.pipe(v.string(), v.url());
@ -8,8 +8,14 @@ export const clientEnv = createClientEnv({
prefix: 'NEXT_PUBLIC_', prefix: 'NEXT_PUBLIC_',
schema: { schema: {
NEXT_PUBLIC_SITE_URL: url, NEXT_PUBLIC_SITE_URL: url,
/**
* The admin API's public origin: the browser calls it directly, with the session cookies
* (0061, 0066). Upload URLs use it too.
*/
NEXT_PUBLIC_CLIENT_END_POINT: origin,
}, },
runtimeEnv: { runtimeEnv: {
NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL, NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,
NEXT_PUBLIC_CLIENT_END_POINT: process.env.NEXT_PUBLIC_CLIENT_END_POINT,
}, },
}); });

View File

@ -1,15 +0,0 @@
import { origin } from '@lumina/libs/env';
import * as v from 'valibot';
/**
* For next.config.ts only: the admin API the `/api` rewrite proxies to. No `server-only` here, as
* the config loads outside React. `next build` writes rewrites into its output, so the value is
* the one at build time and `SKIP_ENV_VALIDATION` can't skip it.
*/
export function adminApiInternalUrl(): string {
const result = v.safeParse(origin, process.env.ADMIN_API_INTERNAL_ORIGIN);
if (result.success) return result.output;
throw new Error(
`ADMIN_API_INTERNAL_ORIGIN is needed to build: next.config rewrites /api to it and next build keeps the value (0061). ${result.issues[0].message}`,
);
}

View File

@ -6,8 +6,11 @@ import { createServerEnv } from '@lumina/libs/env/server';
/** Server variables; only server code imports them, through `env/server`. */ /** Server variables; only server code imports them, through `env/server`. */
export const serverEnv = createServerEnv({ export const serverEnv = createServerEnv({
schema: { schema: {
/** The admin API from inside the deployment network: the `/api` proxy's destination. */ /**
ADMIN_API_INTERNAL_ORIGIN: origin, * The admin API from inside the deployment network (0061), for server requests only (0066). The
* server reads nothing from it yet (0062).
*/
INTERNAL_END_POINT: origin,
}, },
runtimeEnv: process.env, runtimeEnv: process.env,
skipValidation: process.env.SKIP_ENV_VALIDATION === 'true', skipValidation: process.env.SKIP_ENV_VALIDATION === 'true',

View File

@ -1,6 +1,6 @@
# 0018 The browser calls the API through a Next.js rewrite # 0018 The browser calls the API through a Next.js rewrite
Status: Accepted · Area: architecture · Date: 2026-10-06 · Decided by: user Status: Superseded by 0065 · Area: architecture · Date: 2026-10-06 · Decided by: user
## Context ## Context
The browser called the gateway on its own origin with credentials, so every call was cross-origin: CORS preflights, a CORS allowlist to keep in step, and session cookies that belonged to the API host. The browser called the gateway on its own origin with credentials, so every call was cross-origin: CORS preflights, a CORS allowlist to keep in step, and session cookies that belonged to the API host.

View File

@ -7,7 +7,7 @@ The admin panel (journey J11 in the app design) was out of scope, and admin-only
## Decision ## Decision
- `apps/wall-street-plaza` is the admin app and `platforms/garden-roof` its platform; both are tagged `scope:admin`. `scope:admin` depends only on `scope:admin` and `scope:shared`. `scope:market` never imports `scope:admin`, and the reverse is also not allowed. - `apps/wall-street-plaza` is the admin app and `platforms/garden-roof` its platform; both are tagged `scope:admin`. `scope:admin` depends only on `scope:admin` and `scope:shared`. `scope:market` never imports `scope:admin`, and the reverse is also not allowed.
- The admin app talks only to the back end's admin API (`apps/admin-api` in the Nest monorepo), never to the public gateway. The browser calls it on the app's own origin under `/api`, rewritten to `ADMIN_API_INTERNAL_ORIGIN`, as 0018 does for the gateway. - The admin app talks only to the back end's admin API (`apps/admin-api` in the Nest monorepo), never to the public gateway. The browser calls it directly at its public origin, as 0066 does for the gateway.
- The admin app builds and deploys on its own origin (dev port 7002), so no admin code ships in bull or bear. - The admin app builds and deploys on its own origin (dev port 7002), so no admin code ships in bull or bear.
## Alternatives ## Alternatives

View File

@ -0,0 +1,21 @@
# 0065 One API end point per side
Status: Superseded by 0066 · Area: architecture · Date: 2026-10-16 · Decided by: user · Supersedes: 0018
## Context
The server's API address was an env value (`API_INTERNAL_ORIGIN`, `ADMIN_API_INTERNAL_ORIGIN` in the admin app) and the browser's was a constant (`API_PROXY_PATH = '/api'`). The user wants both as env values with the same keys in every app, set in the bootstraps.
## Decision
- Every app's env has `INTERNAL_END_POINT` (server only) and `NEXT_PUBLIC_CLIENT_END_POINT` (public), with the same names in bull, bear and wall-street-plaza.
- `INTERNAL_END_POINT` is the API's origin from inside the deployment network (the gateway, or admin-api in the admin app). The server bootstrap's HTTP client calls it directly and sends no session cookies.
- `NEXT_PUBLIC_CLIENT_END_POINT` is a path on the app's own origin (`/api`), never another origin. The client bootstrap's HTTP client and the platform's `apiBaseUrl` (media URLs) use it, and each app's `next.config.ts` rewrites `<path>/:path*` to `INTERNAL_END_POINT`.
- The gateway still scopes the refresh cookie to `/api/v1/auth` (`AUTH_COOKIE_PATH_PREFIX=/api`) and keeps the apps' origins in `CORS_ORIGINS`.
## Alternatives
- A constant `/api` for the browser (0018): replaced, the user wants both sides set by env.
- A full URL for the browser end point: not chosen; cross-origin calls bring back CORS and API-host cookies (0018's context). The env lib's `sitePath` rejects an origin.
## Consequences
- `next build` fixes the rewrite, so each environment's build needs both values; `SKIP_ENV_VALIDATION` can't skip them, and a build without them fails.
- Changing `NEXT_PUBLIC_CLIENT_END_POINT` from `/api` also needs the gateway's `AUTH_COOKIE_PATH_PREFIX` changed, or the refresh cookie never reaches the refresh call.
- 0018's proxy consequences still hold: API traffic passes through the Next.js server (`API_PROXY_TIMEOUT_MS`), and the client IP comes from the edge's `X-Forwarded-For`.

View File

@ -0,0 +1,22 @@
# 0066 The browser calls the API directly
Status: Accepted · Area: architecture · Date: 2026-10-16 · Decided by: user · Supersedes: 0065
## Context
Each app's `next.config.ts` rewrote `NEXT_PUBLIC_CLIENT_END_POINT` (`/api`) to `INTERNAL_END_POINT`, so all browser API traffic, uploads included, passed through the Next.js server (0018, 0065). The user removed the rewrite.
## Decision
- Every app's env keeps `INTERNAL_END_POINT` (server only) and `NEXT_PUBLIC_CLIENT_END_POINT` (public), with the same names in bull, bear and wall-street-plaza. Both are origins with no path.
- `NEXT_PUBLIC_CLIENT_END_POINT` is the API's public origin (the gateway, or admin-api in the admin app). The client bootstrap's HTTP client calls it directly with `credentials: 'include'`, and the platform's `apiBaseUrl` (media and upload URLs) uses it.
- `INTERNAL_END_POINT` is the API's origin from inside the deployment network. The server bootstrap's HTTP client calls it and sends no session cookies.
- No `rewrites()` and no proxy settings in `next.config.ts`.
## Alternatives
- The Next.js rewrite (0065): removed by the user.
- The app's nginx proxying `/api` to the API: not chosen; `next dev` has no nginx.
## Consequences
- Back end: CORS must allow each app's origin with credentials (`CORS_ORIGINS`), and the refresh cookie path must drop the `/api` prefix (`AUTH_COOKIE_PATH_PREFIX`), or the session never refreshes.
- Session cookies belong to the API host. The API and the apps must stay on one site (for example `api.example.com` and `example.com`), so `SameSite=Lax` cookies reach the API and its media.
- Browser calls pay a CORS preflight. Upload limits and timeouts are the API's own, not Next.js's.
- The client IP reaches the API without an extra proxy hop.

View File

@ -0,0 +1,19 @@
# 0067 No nginx per app
Status: Accepted · Area: architecture · Date: 2026-10-16 · Decided by: user
## Context
Each app had its own `apps/<app>/nginx.conf` and `<app>-nginx` container in front of its release, so `tools/deploy.sh` could swap releases with no refused request. The user removed it.
## Decision
- No `nginx.conf` in this repo. Each app's container publishes `HTTP_PORT` on the host itself (3000 inside the container).
- `tools/deploy.sh <app>` checks the new release's `/healthz` in a container with no published port, then stops the old release and starts the new one on `HTTP_PORT`. A failed check leaves the old release serving; a failed start brings the old one back.
- The edge that routes phones to bull and desktops to bear (0001) points at each app's `HTTP_PORT`.
## Alternatives
- One nginx per app, reloaded onto the new release: no refused requests during a swap, but one more container and config per app. Removed by the user.
## Consequences
- Each deploy refuses connections for the old release's shutdown (in-flight requests finish, 30 s at most) plus the new one's start, about half a second when idle.
- `/healthz` answers on `HTTP_PORT`; the edge should hide it from visitors.
- The edge must set `Vary: User-Agent` (0001) and must not buffer streamed pages (the apps send `X-Accel-Buffering: no`).

View File

@ -0,0 +1,20 @@
# 0068 Keep the previous release for rollback
Status: Accepted · Area: architecture · Date: 2026-10-16 · Decided by: user
## Context
`tools/deploy.sh` (0067) swapped two fixed containers, `<app>-blue` and `<app>-green`, and removed the old release, so going back meant a full rebuild of an earlier commit. The user asked for a rollback beside the deploy.
## Decision
- Name each deploy's container `<app>-<UTC time of the deploy>`, with its env file in `.deploy/<app>/<container>/`.
- After a swap, keep the old release as a stopped container with its env folder; remove every older one.
- `bash tools/rollback.sh <app>` stops the serving container and starts the previous one, checked against `/healthz`; a failing previous release leaves the serving one in place. Running it again rolls forward.
- Deploy and rollback of one app share `.deploy/<app>/.lock`.
## Alternatives
- Rebuild an earlier commit with `tools/deploy.sh`: still works for older releases, but takes a build, and the env may have changed since.
- Keep more than one previous release: more disk and more env folders with secrets, for a case a checkout and deploy already covers.
## Consequences
- A rollback takes seconds and builds nothing; the previous release keeps the port it was deployed with.
- Containers from the blue/green script (`<app>-blue`, `<app>-green`) are invisible to both scripts: remove them, and `.deploy/<app>/blue` and `green`, before the first deploy with this one.

View File

@ -12,7 +12,6 @@
- 0001 Share one platform, `platforms/market`, between `apps/bull` and `apps/bear`; tag all three `scope:market`. - 0001 Share one platform, `platforms/market`, between `apps/bull` and `apps/bear`; tag all three `scope:market`.
- 0012 Wrap each app's `next.config` in island's `withIconSprite` and `withFontCopy`; they write `symbol-defs.svg` and the fonts into `public/` unhashed, served immutable; link the sprite as `?v=<ICON_SPRITE_VERSION>`. - 0012 Wrap each app's `next.config` in island's `withIconSprite` and `withFontCopy`; they write `symbol-defs.svg` and the fonts into `public/` unhashed, served immutable; link the sprite as `?v=<ICON_SPRITE_VERSION>`.
- 0013 Render every `(auth)` page's steps only in the browser behind `GuestGuard`: the server sends the frame, a same-size skeleton and `noindex`; flow state stays in memory, never in the URL or storage. - 0013 Render every `(auth)` page's steps only in the browser behind `GuestGuard`: the server sends the frame, a same-size skeleton and `noindex`; flow state stays in memory, never in the URL or storage.
- 0018 Call the API from the browser only on the app's own origin under `/api`, rewritten by `next.config.ts` to `API_INTERNAL_ORIGIN`; media URLs use the same path, and the server render calls the gateway directly.
- 0026 Prerender the landing (`/`) with `force-static` and `revalidate = 600`; every other route keeps `force-dynamic` in its route group's layout, never the root's. - 0026 Prerender the landing (`/`) with `force-static` and `revalidate = 600`; every other route keeps `force-dynamic` in its route group's layout, never the root's.
- 0027 Serve خانه at `/feed` and the landing at `/`; send a signed-in visitor of `/` to `homeRoute` in the browser with `LandingRedirect`, never in a proxy. - 0027 Serve خانه at `/feed` and the landing at `/`; send a signed-in visitor of `/` to `homeRoute` in the browser with `LandingRedirect`, never in a proxy.
- 0051 Serve `/_next/static/` JS and CSS cache first in the service worker; `strategy` (default stale-while-revalidate) applies to fonts and the sprite only. - 0051 Serve `/_next/static/` JS and CSS cache first in the service worker; `strategy` (default stale-while-revalidate) applies to fonts and the sprite only.
@ -24,8 +23,11 @@
- 0058 Opening notifications records "seen" and clears the bell; a row stays unread until tapped; creators filter one list by «همه · پیش‌بینی‌ها · مالی · حساب». - 0058 Opening notifications records "seen" and clears the bell; a row stays unread until tapped; creators filter one list by «همه · پیش‌بینی‌ها · مالی · حساب».
- 0059 Checkout and the channel save `?code=` into the per-creator checkout draft on arrival; checkout then strips it from the URL. - 0059 Checkout and the channel save `?code=` into the per-creator checkout draft on arrival; checkout then strips it from the URL.
- 0060 Composers send a creator who can't publish to their own channel with the locked dialog; every publish carries a stable `Idempotency-Key`. - 0060 Composers send a creator who can't publish to their own channel with the locked dialog; every publish carries a stable `Idempotency-Key`.
- 0061 Build the admin panel as `apps/wall-street-plaza` with `platforms/garden-roof`, tagged `scope:admin`; it calls only the back end's `admin-api`, through its own `/api` rewrite. - 0061 Build the admin panel as `apps/wall-street-plaza` with `platforms/garden-roof`, tagged `scope:admin`; it calls only the back end's `admin-api`.
- 0064 Serve a channel at `/channels/username`, built only through `ROUTES`; both apps 308-redirect `/@username/…` there, and no other code reads «@» in a path. - 0064 Serve a channel at `/channels/username`, built only through `ROUTES`; both apps 308-redirect `/@username/…` there, and no other code reads «@» in a path.
- 0066 Give every app `INTERNAL_END_POINT` (server calls) and `NEXT_PUBLIC_CLIENT_END_POINT` (the API's public origin, called directly by the browser with credentials), both set in the bootstraps; no `next.config.ts` rewrite.
- 0067 Run each app as one container publishing `HTTP_PORT`, with no per-app nginx; `tools/deploy.sh` checks the new release's `/healthz` off to the side, then replaces the old release.
- 0068 Keep the previous release as a stopped `<app>-<UTC time>` container with its env folder; `tools/rollback.sh <app>` starts it in place of the serving one.
## Proposed ## Proposed

View File

@ -1,8 +1,8 @@
/** The platform's own settings, named for what they are, not for the variables behind them. */ /** The platform's own settings, named for what they are, not for the variables behind them. */
export type GardenRoofEnv = { export type GardenRoofEnv = {
/** /**
* Where the browser loads the admin API from: a path on this site (`/api`) that the app proxies * Where the browser loads the admin API from: `admin-api`'s public origin (0061, 0066). For what
* to `admin-api` (0061). For what the browser loads itself, such as ID card images. * the browser loads itself, such as ID card images.
*/ */
apiBaseUrl: string; apiBaseUrl: string;
}; };

View File

@ -32,7 +32,7 @@ export type AnalystListItemPayload = {
username: string; username: string;
/** E.164; '' when the account can't be read. */ /** E.164; '' when the account can't be read. */
phone: string; phone: string;
/** Loadable through this site's API proxy. */ /** Loadable from admin-api's public origin. */
avatarUrl: string | null; avatarUrl: string | null;
verificationStatus: VerificationStatus; verificationStatus: VerificationStatus;
accountStatus: AccountStatus; accountStatus: AccountStatus;

View File

@ -93,7 +93,7 @@ export type BetaAnalystPayload = {
/** First and last name, or the username when the account has neither. */ /** First and last name, or the username when the account has neither. */
fullName: string; fullName: string;
username: string; username: string;
/** Loadable through the panel's API proxy (`/api/uploads/…`). */ /** Loadable from admin-api's public origin (`…/uploads/…`). */
avatarUrl: string | null; avatarUrl: string | null;
isActive: boolean; isActive: boolean;
inactiveReason: BetaInactiveReason | null; inactiveReason: BetaInactiveReason | null;

View File

@ -133,7 +133,7 @@ export function toPayoutDetailPayload(
): PayoutDetailPayload { ): PayoutDetailPayload {
return { return {
...toPayoutListItemPayload(dto), ...toPayoutListItemPayload(dto),
// admin-api's route (`/v1/admin/payouts/:id/receipt`), through this site's API proxy. // admin-api's route (`/v1/admin/payouts/:id/receipt`), on admin-api's public origin.
receiptUrl: toApiUrl(dto.receiptUrl), receiptUrl: toApiUrl(dto.receiptUrl),
cancelReason: dto.cancelReason, cancelReason: dto.cancelReason,
lines: dto.lines.map(toLedgerLinePayload), lines: dto.lines.map(toLedgerLinePayload),

View File

@ -67,7 +67,7 @@ export type VerificationDetailPayload = {
submittedAt: string; submittedAt: string;
status: VerificationStatus; status: VerificationStatus;
accountStatus: AccountStatus; accountStatus: AccountStatus;
/** The card's sides as the browser loads them (through the panel's `/api` proxy). */ /** The card's sides as the browser loads them (from admin-api's public origin). */
idImages: { front: string; back: string }; idImages: { front: string; back: string };
rejectionReason: string | null; rejectionReason: string | null;
pastSubmissions: { pastSubmissions: {

View File

@ -21,8 +21,8 @@ function legacyUploadPath(address: string): string | null {
/** /**
* A path the admin API returns (`/v1/admin/verifications/…/id-images/front`, `/uploads/avatars/…`) → the URL the browser * A path the admin API returns (`/v1/admin/verifications/…/id-images/front`, `/uploads/avatars/…`) → the URL the browser
* loads it from, through this site's API proxy (0061), so private files get the session cookie: * loads it from, admin-api's public origin (0061, 0066), so private files get the session cookie:
* `/api/v1/admin/…`. Other absolute addresses (another site's, a CDN's) pass through, as does one * `https://admin-api.example.com/v1/admin/…`. Other absolute addresses (another site's, a CDN's) pass through, as does one
* that isn't a valid URL; empty stays `null`. Reads env inside the call, so bootstrap has always * that isn't a valid URL; empty stays `null`. Reads env inside the call, so bootstrap has always
* run. * run.
*/ */

View File

@ -1,9 +1,9 @@
/** The platform's own settings, named for what they are, not for the variables behind them. */ /** The platform's own settings, named for what they are, not for the variables behind them. */
export type MarketEnv = { export type MarketEnv = {
/** /**
* Where the browser loads the API from: a path on this site (`/api`) that the app proxies to the * Where the browser loads the API from: the gateway's public origin (0066). For what the browser
* gateway (0018). For what the browser loads itself: post media, avatars and uploads (`/files/*` * loads itself: post media, avatars and uploads (`/files/*` sits outside `/v1`). The server
* sits outside `/v1`). A relative URL, so the server render writes the same address. * render writes the same address.
*/ */
apiBaseUrl: string; apiBaseUrl: string;
/** Support chat handles and hours: config values, never hard-coded in a component. */ /** Support chat handles and hours: config values, never hard-coded in a component. */

View File

@ -8,7 +8,7 @@ export type CreatorSummaryPayload = {
/** Without «@». */ /** Without «@». */
username: string; username: string;
displayName: string | null; displayName: string | null;
/** Absolute, through the API proxy; `null` without a photo. */ /** Absolute, on the API's public origin; `null` without a photo. */
avatarUrl: string | null; avatarUrl: string | null;
verified: boolean; verified: boolean;
markets: Market[]; markets: Market[];

View File

@ -22,7 +22,7 @@ export type FeedCreatorPayload = {
username: string; username: string;
/** Shown as the name with @username beside it (R15); `null` shows @username alone. */ /** Shown as the name with @username beside it (R15); `null` shows @username alone. */
displayName: string | null; displayName: string | null;
/** Absolute, through the API proxy; `null` without a photo. */ /** Absolute, on the API's public origin; `null` without a photo. */
avatarUrl: string | null; avatarUrl: string | null;
verified: boolean; verified: boolean;
/** Always `false` on the feed: a suspended creator's posts are left out. */ /** Always `false` on the feed: a suspended creator's posts are left out. */

View File

@ -53,7 +53,7 @@ type LedgerItemBasePayload = {
occurredAt: string; occurredAt: string;
}; };
/** Where a payout's receipt opens and downloads, through this site's API proxy. */ /** Where a payout's receipt opens and downloads, on the API's public origin. */
export type PayoutReceiptPayload = { export type PayoutReceiptPayload = {
url: string; url: string;
downloadUrl: string; downloadUrl: string;

View File

@ -46,7 +46,7 @@ export type FollowedCreatorPayload = {
username: string; username: string;
/** Shown as the name with @username beside it (R15); `null` shows @username alone. */ /** Shown as the name with @username beside it (R15); `null` shows @username alone. */
displayName: string | null; displayName: string | null;
/** Absolute, through the API proxy; `null` without a photo. */ /** Absolute, on the API's public origin; `null` without a photo. */
avatarUrl: string | null; avatarUrl: string | null;
verified: boolean; verified: boolean;
/** The channel is blacked out: the row is dimmed and opens nothing. */ /** The channel is blacked out: the row is dimmed and opens nothing. */

View File

@ -4,7 +4,7 @@ import { getEnv } from '../../env';
export const postHttp = http.extend({}); export const postHttp = http.extend({});
/** `/files/*` sits outside `/v1`: straight under the API's base (`/api/files/…`). Browser only. */ /** `/files/*` sits outside `/v1`: straight under the API's base (`https://api.example.com/files/…`). Browser only. */
export const postFilesHttp = http.extend({ export const postFilesHttp = http.extend({
baseUrl: () => getEnv().apiBaseUrl, baseUrl: () => getEnv().apiBaseUrl,
}); });

View File

@ -21,8 +21,8 @@ function legacyUploadPath(address: string): string | null {
/** /**
* A path the API returns (`/v1/posts/…/media/…`, `/files/…`, `/uploads/…`) → the URL the browser * A path the API returns (`/v1/posts/…/media/…`, `/files/…`, `/uploads/…`) → the URL the browser
* loads it from, through this site's API proxy (0018), so private media gets the session cookie: * loads it from, the gateway's public origin (0066), so private media gets the session cookie:
* `/api/v1/posts/…`. Other absolute addresses (another site's, a CDN's) pass through, as does one * `https://api.example.com/v1/posts/…`. Other absolute addresses (another site's, a CDN's) pass through, as does one
* that isn't a valid URL; empty stays `null`. Reads env inside the call, so bootstrap has always * that isn't a valid URL; empty stays `null`. Reads env inside the call, so bootstrap has always
* run. * run.
*/ */

118
tools/deploy.sh Executable file
View File

@ -0,0 +1,118 @@
#!/usr/bin/env bash
# Deploys one app on this host: builds its image with apps/<app>/.env.production, checks the new release's
# health check (/healthz) in a container off to the side, then swaps the containers: stops the old release
# and starts the new one on HTTP_PORT. The old release stays as a stopped container, the one to roll back
# to; older ones are removed. A failed build or health check leaves the old release serving. The swap
# refuses connections for a few seconds: the old release finishes its in-flight requests (30 s at most),
# then the new one starts. Whatever sits in front (the edge that routes between bull and bear, 0001; this
# repo sets none up, 0067) points at HTTP_PORT.
#
# bash tools/deploy.sh <app> [KEY=VALUE]...
# HTTP_PORT=7001 bash tools/deploy.sh bear
# bash tools/deploy.sh bull NEXT_PUBLIC_SERVICE_WORKER_ENABLED=false
#
# HTTP_PORT ([host:]port) is where the app answers on this host; inside its container it listens on 3000.
# Default: the port the serving release publishes, or 8080 on the first deploy.
#
# apps/<app>/.env.production lives on this host only (git keeps .env.sample) and holds every value, secrets
# included. A KEY=VALUE argument overrides the file's value for this deploy, at build time and at runtime.
#
# Each deploy's container is <app>-<UTC time of the deploy>, such as bull-20261016143005: the one that
# serves and the previous one, stopped, which tools/rollback.sh <app> starts in its place.
# State in .deploy/<app>/, ignored by git and Docker, and readable by this user only: one folder per
# container, named after it, holds its .env.production (the app's file plus the overrides), mounted into it.
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")/.."
app=${1:?Usage: tools/deploy.sh <app> [KEY=VALUE]...}
shift
[ -f "apps/$app/next.config.ts" ] || { echo "apps/$app/next.config.ts is missing" >&2; exit 1; }
[ -f "apps/$app/.env.production" ] \
|| { echo "apps/$app/.env.production is missing: copy apps/$app/.env.sample and fill it in" >&2; exit 1; }
for override in "$@"; do
[[ $override =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] || { echo "Overrides are KEY=VALUE, got: $override" >&2; exit 1; }
done
state="$PWD/.deploy/$app"
mkdir -p "$state"
chmod 700 .deploy
exec 9>"$state/.lock"
flock --nonblock 9 || { echo "A deploy or rollback of $app is running" >&2; exit 1; }
# 1. The release that serves now, the new one's name, and the port. The port is checked before the build,
# unless the serving release already holds it.
containers() { docker ps "$@" --filter "name=^$app-[0-9]{14}\$" --format '{{.Names}}'; }
current=$(containers | head -n 1)
next=$app-$(date -u +%Y%m%d%H%M%S)
published=
if [ -n "$current" ]; then
published=$(docker port "$current" 3000/tcp 2>/dev/null | head -n 1 || true)
published=${published#0.0.0.0:}
published=${published#\[::\]:}
fi
http_port=${HTTP_PORT:-${published:-8080}}
port_host=127.0.0.1
[[ $http_port == *:* ]] && port_host=${http_port%:*}
if [ "$http_port" != "$published" ] && (exec 3<>"/dev/tcp/$port_host/${http_port##*:}") 2>/dev/null; then
echo "Port $http_port is taken; pass a free one: HTTP_PORT=8081 bash tools/deploy.sh $app" >&2
exit 1
fi
# 2. The release's env, in its own folder: the app's file, then the overrides; for a repeated key, the last
# line wins. The container's node user reads it, so it's 644 inside .deploy/, which only this user can
# open. Until the swap, any failure removes the new release and its folder.
mkdir -p "$state/$next"
{ cat "apps/$app/.env.production"; echo; printf '%s\n' "$@"; } > "$state/$next/.env.production"
chmod 644 "$state/$next/.env.production"
trap 'docker rm --force "$next" >/dev/null 2>&1 || true; rm -rf "${state:?}/$next"' EXIT
# 3. Build. The commit names the release and becomes NEXT_DEPLOYMENT_ID; uncommitted changes get their own.
release=$(git rev-parse --short=12 HEAD)
git diff --quiet HEAD || release="$release-dirty-$(date +%s)"
docker build --build-context appenv="$state/$next" \
--build-arg APP="$app" --build-arg NEXT_DEPLOYMENT_ID="$release" --tag "$app:$release" .
start_next() {
docker rm --force "$next" >/dev/null 2>&1 || true
docker run --detach --name "$next" --restart unless-stopped \
--cap-drop ALL --security-opt no-new-privileges --stop-timeout 30 \
--volume "$state/$next/.env.production:/app/apps/$app/.env.production:ro" "$@" "$app:$release" >/dev/null
}
# Docker turns the image's HEALTHCHECK unhealthy when /healthz keeps failing.
wait_healthy() {
local status
while status=$(docker inspect --format '{{.State.Status}} {{.State.Health.Status}}' "$next") \
&& [ "$status" = 'running starting' ]; do
sleep 2
done
[ "$status" = 'running healthy' ] && return 0
docker logs --tail 50 "$next" >&2
echo "$next ($app:$release) is $status" >&2
return 1
}
# 4. Check the new release off to the side, with no published port, while the old one keeps serving.
echo "Checking $app:$release against /healthz"
start_next
wait_healthy || { echo "${current:-No release} keeps serving" >&2; exit 1; }
docker rm --force "$next" >/dev/null
# 5. Swap. Stopping the old release frees the port; SIGTERM lets Next.js finish what it's serving, for up
# to 30 s (--stop-timeout). If the new release fails now, the old one starts again.
trap 'docker rm --force "$next" >/dev/null 2>&1 || true; rm -rf "${state:?}/$next"
if [ -n "$current" ]; then docker start "$current" >/dev/null && echo "$current serves again" >&2; fi' EXIT
if [ -n "$current" ]; then docker stop "$current" >/dev/null; fi
start_next --publish "$http_port:3000"
wait_healthy
trap - EXIT
# 6. Keep one previous release: the old one, stopped, with its env folder. Remove every older container and
# folder, and keep the app's three newest images (Docker never removes an image a container uses).
for old in $(containers --all); do
[ "$old" = "$next" ] || [ "$old" = "$current" ] || docker rm --force "$old" >/dev/null
done
for dir in "$state"/*/; do
dir=${dir%/}
[ "${dir##*/}" = "$next" ] || [ "${dir##*/}" = "$current" ] || rm -rf "$dir"
done
docker image ls "$app" --format '{{.Repository}}:{{.Tag}}' | tail -n +4 | xargs --no-run-if-empty docker image rm >/dev/null 2>&1 || true
echo "$app $release serves at $(docker port "$next" 3000/tcp | head -n 1) as $next${current:+; $current is stopped, kept for a rollback}"

41
tools/rollback.sh Executable file
View File

@ -0,0 +1,41 @@
#!/usr/bin/env bash
# Rolls one app back to its previous release: stops the container that serves and starts the previous one,
# which tools/deploy.sh keeps stopped with its own image and env. The container that served stays stopped as
# the new previous one, so running this again rolls forward. If the previous release fails its health check
# (/healthz), the one that served starts again. The port refuses connections for a few seconds, as in a
# deploy, and the previous release answers on the port it was deployed with.
#
# bash tools/rollback.sh <app>
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")/.."
app=${1:?Usage: tools/rollback.sh <app>}
state="$PWD/.deploy/$app"
[ -d "$state" ] || { echo "$app was never deployed on this host" >&2; exit 1; }
exec 9>"$state/.lock"
flock --nonblock 9 || { echo "A deploy or rollback of $app is running" >&2; exit 1; }
# The container that serves, and the previous one: tools/deploy.sh keeps one, stopped.
containers() { docker ps "$@" --filter "name=^$app-[0-9]{14}\$" --format '{{.Names}}'; }
current=$(containers | head -n 1)
[ -n "$current" ] || { echo "No container of $app serves; deploy it, or start one with docker start" >&2; exit 1; }
previous=$(containers --all | grep -vx "$current" | sort | tail -n 1 || true)
[ -n "$previous" ] || { echo "$app has no previous release to roll back to" >&2; exit 1; }
# Swap. SIGTERM lets Next.js finish what it's serving, for up to 30 s (--stop-timeout). If the previous
# release fails, the one that served starts again.
trap 'docker stop "$previous" >/dev/null 2>&1 || true; docker start "$current" >/dev/null && echo "$current serves again" >&2' EXIT
docker stop "$current" >/dev/null
docker start "$previous" >/dev/null
# Docker turns the image's HEALTHCHECK unhealthy when /healthz keeps failing.
while status=$(docker inspect --format '{{.State.Status}} {{.State.Health.Status}}' "$previous") \
&& [ "$status" = 'running starting' ]; do
sleep 2
done
if [ "$status" != 'running healthy' ]; then
docker logs --tail 50 "$previous" >&2
echo "$previous is $status" >&2
exit 1
fi
trap - EXIT
echo "$app rolled back: $previous serves at $(docker port "$previous" 3000/tcp | head -n 1); $current is stopped, kept to roll forward"