Compare commits

..

1 Commits

Author SHA1 Message Date
Julien Gautier b25d4fb944 ci(gitlab): land .gitlab-ci.yml alongside gitea workflow (ADR-0028 phase 2)
CI / scan (pull_request) Successful in 2m39s
CI / commits (pull_request) Successful in 2m38s
CI / check (pull_request) Successful in 2m51s
CI / a11y (pull_request) Successful in 2m28s
CI / perf (pull_request) Successful in 6m37s
Port .gitea/workflows/ci.yml job-by-job to GitLab CI per ADR-0028
section Migration sequence Phase 2. Architectural principles from
ADR-0015 preserved verbatim (thin YAML, gates as package.json
scripts, defense-in-depth on conventional commits).

Job parity:
- check / commits / perf / a11y -> 1:1 port; Gitea variable names
  rewritten to GitLab equivalents.
- scan -> sast + secret_detection (built-in GitLab includes) + audit
  (pnpm audit kept for npm-advisory defense in depth). The manual
  Trivy + gitleaks install plus the two paywalled-action workarounds
  documented in the Gitea workflow go away per ADR-0028 section
  What changes.

Notable adaptations: explicit cache block keyed on pnpm-lock.yaml,
no default:image (would override analyzer images), Playwright image
for perf to dovetail with the upcoming ADR-0016 axe-core e2e.

Phase 2 keeps both pipelines green for ~1 calendar week per
ADR-0028 section Confirmation. Phase 3 deletes .gitea/workflows
and tightens the push rule to main only.
2026-05-27 17:50:56 +02:00
25 changed files with 1484 additions and 3466 deletions
-5
View File
@@ -35,11 +35,6 @@ pnpm-debug.log*
infra/*-tenant.entra.json infra/*-tenant.entra.json
!infra/*-tenant.entra.example.json !infra/*-tenant.entra.example.json
# Tenant-private Entra per-persona oids consumed by prisma/seed.ts
# (ADR-0026 §"Seed personas"). Same pattern — commit only the example.
infra/*-tenant.personas.json
!infra/*-tenant.personas.example.json
# OS / editor scrap # OS / editor scrap
.DS_Store .DS_Store
Thumbs.db Thumbs.db
+5 -15
View File
@@ -105,21 +105,11 @@ commits:
perf: perf:
extends: .node-job extends: .node-job
stage: perf stage: perf
# Lighthouse CI drives a real Chrome via chrome-launcher, which # Lighthouse CI drives a real Chrome instance. Playwright's image is
# probes the PATH / CHROME_PATH for a standard Chrome/Chromium # the canonical "Node + browsers" CI image and is already on our
# binary. The Playwright image bundles Chromium under /ms-playwright # roadmap for the ADR-0016 axe-core e2e — single image covers both
# with a non-standard name chrome-launcher cannot discover, so we # uses once the a11y suite lands.
# stay on the base Node image and apt-install Debian's `chromium` image: mcr.microsoft.com/playwright:v1.55.0-jammy
# (lands at /usr/bin/chromium). The future ADR-0016 axe-core e2e job
# — which drives Playwright directly — will use the Playwright image
# instead: the two tools want different things, so they get
# different images rather than one image that serves both poorly.
image: node:24-bookworm
variables:
CHROME_PATH: /usr/bin/chromium
before_script:
- !reference [.node-job, before_script]
- apt-get update -qq && apt-get install -y -qq --no-install-recommends chromium
# Skip on Renovate MRs (same rationale as commits + the perf signal # Skip on Renovate MRs (same rationale as commits + the perf signal
# on a dep bump is essentially zero). Push events on `main` still # on a dep bump is essentially zero). Push events on `main` still
# run perf — we catch regressions immediately post-merge, not # run perf — we catch regressions immediately post-merge, not
+2 -3
View File
@@ -57,13 +57,12 @@ The structural, security, observability, and quality choices are recorded as ADR
- **Portal-side identity model:** `Person` golden record (stable identity, can exist without a portal account — workforce pre-provisioning, dossier bénéficiaires, alumni) + `User` overlay (one-to-zero-or-one with Person, lazy-created on first OIDC callback in v1; carries portal-only state like `lastSignInAt`). `UserScope` backs the ADR-0025 scope axis with opaque `value` strings referencing ADR-0027's `Structure.code` / `Delegation.code` / `Region.code` — no FK at the DB level so historical rows survive structure decommissioning; admin-UI write path validates. v1 dedup uses `entraOid` only; `Person.email` is an indexed attribute, not a unique key, because two distinct humans genuinely share emails (shared aliases, generic `info@`, upstream-feed errors). Facets (Salarié / Élu / Adhérent / Bénéficiaire) + Pléiades / Acteurs+ sync + operator-confirmed Person-merge flow deferred to ADR-0029 — see [ADR-0026](docs/decisions/0026-person-user-portal-data-model.md). - **Portal-side identity model:** `Person` golden record (stable identity, can exist without a portal account — workforce pre-provisioning, dossier bénéficiaires, alumni) + `User` overlay (one-to-zero-or-one with Person, lazy-created on first OIDC callback in v1; carries portal-only state like `lastSignInAt`). `UserScope` backs the ADR-0025 scope axis with opaque `value` strings referencing ADR-0027's `Structure.code` / `Delegation.code` / `Region.code` — no FK at the DB level so historical rows survive structure decommissioning; admin-UI write path validates. v1 dedup uses `entraOid` only; `Person.email` is an indexed attribute, not a unique key, because two distinct humans genuinely share emails (shared aliases, generic `info@`, upstream-feed errors). Facets (Salarié / Élu / Adhérent / Bénéficiaire) + Pléiades / Acteurs+ sync + operator-confirmed Person-merge flow deferred to ADR-0029 — see [ADR-0026](docs/decisions/0026-person-user-portal-data-model.md).
- **Portal-side organisational hierarchy:** `Region` (INSEE 2-digit) → `Delegation` (department 23-char) → `Structure` with `kind` discriminator (`medico_social` / `antenne` / `dispositif` / `entreprise_adaptee` / `mouvement` / `administratif` / `siege`, aligned with cascade's `Structure.type`). `Structure.code` is the portal-internal string PK, externally meaningful: for medico-social rows it equals the FINESS (9 digits) and round-trips cleanly through scope literals (`etablissement:0330800013`) and URLs; for non-FINESS rows it is an APF-internal slug (`siege`, `apf-bdx-merignac`, `ea-toulouse`, …). `finess` / `siret` / `codePaie` are nullable, unique-when-present attributes — populated where the upstream registry has the structure on file. v1 ships a small inline-migration seed (test-tenant scope: Région Nouvelle-Aquitaine, Délégation 33, a handful of médico-social + siège); the full cascade-driven inventory sync, plus `Pole` / `Service` / arbitrary nesting / per-source enrichment, land additively with ADR-0029 — see [ADR-0027](docs/decisions/0027-portal-side-organisational-hierarchy.md). - **Portal-side organisational hierarchy:** `Region` (INSEE 2-digit) → `Delegation` (department 23-char) → `Structure` with `kind` discriminator (`medico_social` / `antenne` / `dispositif` / `entreprise_adaptee` / `mouvement` / `administratif` / `siege`, aligned with cascade's `Structure.type`). `Structure.code` is the portal-internal string PK, externally meaningful: for medico-social rows it equals the FINESS (9 digits) and round-trips cleanly through scope literals (`etablissement:0330800013`) and URLs; for non-FINESS rows it is an APF-internal slug (`siege`, `apf-bdx-merignac`, `ea-toulouse`, …). `finess` / `siret` / `codePaie` are nullable, unique-when-present attributes — populated where the upstream registry has the structure on file. v1 ships a small inline-migration seed (test-tenant scope: Région Nouvelle-Aquitaine, Délégation 33, a handful of médico-social + siège); the full cascade-driven inventory sync, plus `Pole` / `Service` / arbitrary nesting / per-source enrichment, land additively with ADR-0029 — see [ADR-0027](docs/decisions/0027-portal-side-organisational-hierarchy.md).
- **Runtime:** Node.js latest LTS major. - **Runtime:** Node.js latest LTS major.
- **Local dev environment:** three coexisting run modes — native `pnpm nx serve`, the VSCode devcontainer, and a Docker Compose `apps` profile that boots all three Nx dev servers without a native Node/pnpm toolchain (`./infra/local/dev.sh up apps`). Dev-only (production images deferred to the ADR-0028 Container Registry work); shared `Dockerfile.dev`, repo bind-mounted for hot reload, `node_modules`/Nx cache in named volumes, BFF entrypoint runs `prisma generate` + `migrate deploy` — see [ADR-0030](docs/decisions/0030-dockerised-dev-mode.md).
## Repository status ## Repository status
The Nx workspace is **scaffolded and operational**. The three apps (`portal-shell`, `portal-admin`, `portal-bff`) and the seven lib roots (`libs/feature/auth`, `libs/shared/auth`, `libs/shared/charts`, `libs/shared/state`, `libs/shared/tokens`, `libs/shared/ui`, `libs/shared/util`) are in place; CI runs `format:check / lint / test / build` plus the ADR-0025 catalogue-drift gate on every PR. The Nx workspace is **scaffolded and operational**. The three apps (`portal-shell`, `portal-admin`, `portal-bff`) and the seven lib roots (`libs/feature/auth`, `libs/shared/auth`, `libs/shared/charts`, `libs/shared/state`, `libs/shared/tokens`, `libs/shared/ui`, `libs/shared/util`) are in place; CI runs `format:check / lint / test / build` plus the ADR-0025 catalogue-drift gate on every PR.
ADRs 0001 → 0028 plus ADR-0030 are accepted and cover the structural, security, observability, quality, i18n, admin-app, docs-site, charts, AI-relay, authorization, portal-side identity + organisational hierarchy, CI/CD platform migration, and dockerised local-dev mode choices. ADR-0028 supersedes only ADR-0015's "Gitea Actions" platform choice — the rest of ADR-0015's architectural principles carry over unchanged; the 4-phase migration (mirror → parallel pipelines → cutover → cleanup) ships in follow-up PRs. ADR-0029 (cascade / Pléiades / Acteurs+ syncs + facet schemas) is the next proposed addition — its number is reserved ahead of ADR-0030, which was written first. Until ADR-0026 + ADR-0027 implementation PRs ship, ADR-0025's stubs (`Principal.user.{id, personId}` placeholders, `StubScopeResolver`'s `unrestricted` blanket return) remain in place. **Shipped on `main`:** ADRs 0001 → 0028 are accepted and cover the structural, security, observability, quality, i18n, admin-app, docs-site, charts, AI-relay, authorization, portal-side identity + organisational hierarchy, and CI/CD platform migration choices. ADR-0028 supersedes only ADR-0015's "Gitea Actions" platform choice — the rest of ADR-0015's architectural principles carry over unchanged; the 4-phase migration (mirror → parallel pipelines → cutover → cleanup) ships in follow-up PRs. ADR-0029 (cascade / Pléiades / Acteurs+ syncs + facet schemas) is the next proposed addition. Until ADR-0026 + ADR-0027 implementation PRs ship, ADR-0025's stubs (`Principal.user.{id, personId}` placeholders, `StubScopeResolver`'s `unrestricted` blanket return) remain in place. **Shipped on `main`:**
- **Phase-1 foundation** — Nx workspace, Angular `portal-shell`, NestJS `portal-bff`, Prisma + Postgres, Pino + OpenTelemetry, Husky/lint-staged/commitlint, Gitea Actions CI. - **Phase-1 foundation** — Nx workspace, Angular `portal-shell`, NestJS `portal-bff`, Prisma + Postgres, Pino + OpenTelemetry, Husky/lint-staged/commitlint, Gitea Actions CI.
- **Phase-2 auth + audit + security** — OIDC Auth Code + PKCE via MSAL Node, Redis sessions with AES-256-GCM at rest, idle 30 min sliding + absolute 12 h hard ceiling, RP-initiated logout, double-submit CSRF, `audit.events` append-only schema with role-based grants, helmet + env-driven CORS allowlist + rate limiting + structured error envelope (see [ADR-0021](docs/decisions/0021-phase-2-security-baseline.md)). - **Phase-2 auth + audit + security** — OIDC Auth Code + PKCE via MSAL Node, Redis sessions with AES-256-GCM at rest, idle 30 min sliding + absolute 12 h hard ceiling, RP-initiated logout, double-submit CSRF, `audit.events` append-only schema with role-based grants, helmet + env-driven CORS allowlist + rate limiting + structured error envelope (see [ADR-0021](docs/decisions/0021-phase-2-security-baseline.md)).
@@ -110,7 +109,7 @@ pnpm nx format:check
## Environment conventions ## Environment conventions
- **Two development environments.** `local` (Windows-WSL or native macOS / Linux on the workstation) and `development` (Debian 13 VM at `10.100.201.21` — the default for new devs, replaces WSL). A `hybrid` sub-mode runs the IDE + Nx servers on the workstation while reaching the infra services (postgres / redis / otel) on the dev VM through SSH tunnels. Full procedure: [docs/setup/01-dev-debian-vm-setup.md](docs/setup/01-dev-debian-vm-setup.md). The legacy WSL flow remains documented in [docs/setup/02-wsl-terminal-setup.md](docs/setup/02-wsl-terminal-setup.md). - **Two development environments.** `local` (Windows-WSL or native macOS / Linux on the workstation) and `development` (Debian 13 VM at `10.100.201.21` — the default for new devs, replaces WSL). A `hybrid` sub-mode runs the IDE + Nx servers on the workstation while reaching the infra services (postgres / redis / otel) on the dev VM through SSH tunnels. Full procedure: [docs/setup/01-dev-debian-vm-setup.md](docs/setup/01-dev-debian-vm-setup.md). The legacy WSL flow remains documented in [docs/setup/02-wsl-terminal-setup.md](docs/setup/02-wsl-terminal-setup.md).
- **Two IDE flows on the dev VM** — VSCode Remote-SSH (default; transparent equivalent of the WSL flow) and Devcontainer (`.devcontainer/devcontainer.json` shipped, Node + pnpm pinned in the image, mounts the docker socket so the host's `apf-portal-dev` Compose network is reachable from inside). Independently of the IDE flow, the apps can run **natively** (`pnpm nx serve`) or as **Docker Compose services** (`./infra/local/dev.sh up apps`, no native toolchain — ADR-0030); the "which mode when" table is in [docs/setup/01-dev-debian-vm-setup.md](docs/setup/01-dev-debian-vm-setup.md). - **Two IDE flows on the dev VM** — VSCode Remote-SSH (default; transparent equivalent of the WSL flow) and Devcontainer (`.devcontainer/devcontainer.json` shipped, Node + pnpm pinned in the image, mounts the docker socket so the host's `apf-portal-dev` Compose network is reachable from inside).
- **Never install Angular globally.** Use `pnpm dlx` for one-off CLI invocations and project-local `pnpm nx ...` for everything else — versions stay pinned per project. - **Never install Angular globally.** Use `pnpm dlx` for one-off CLI invocations and project-local `pnpm nx ...` for everything else — versions stay pinned per project.
- **On WSL: work inside the WSL filesystem** (`~/Works/...`), never under `/mnt/c` — the latter has severe I/O penalties that break Nx caching and dev-server reload times. On the dev VM the analogous rule is "stay on the VM disk, do not work over SSHFS / network mounts". - **On WSL: work inside the WSL filesystem** (`~/Works/...`), never under `/mnt/c` — the latter has severe I/O penalties that break Nx caching and dev-server reload times. On the dev VM the analogous rule is "stay on the VM disk, do not work over SSHFS / network mounts".
- **pnpm is mandatory** (activated via `corepack enable`); do not introduce npm or yarn lockfiles. - **pnpm is mandatory** (activated via `corepack enable`); do not introduce npm or yarn lockfiles.
+1 -8
View File
@@ -84,8 +84,7 @@
"continuous": true, "continuous": true,
"executor": "@angular/build:dev-server", "executor": "@angular/build:dev-server",
"options": { "options": {
"port": 4300, "port": 4300
"proxyConfig": "apps/portal-admin/proxy.conf.js"
}, },
"configurations": { "configurations": {
"production": { "production": {
@@ -93,12 +92,6 @@
}, },
"development": { "development": {
"buildTarget": "portal-admin:build:development" "buildTarget": "portal-admin:build:development"
},
"https": {
"buildTarget": "portal-admin:build:development",
"ssl": true,
"sslKey": ".secrets/dev-tls.key",
"sslCert": ".secrets/dev-tls.pem"
} }
}, },
"defaultConfiguration": "development" "defaultConfiguration": "development"
-21
View File
@@ -1,21 +0,0 @@
// Angular dev-server proxy for portal-admin.
//
// Mirrors apps/portal-shell/proxy.conf.js — same rationale, same
// `/api → ${BFF_TARGET:-http://localhost:3000}` rule. The admin app
// talks to the same BFF (ADR-0020 §"Where does the admin app live"),
// just at admin-specific paths under `/api/admin/...`; the proxy
// match on `/api` covers both surfaces.
//
// JS form deliberate — only this form can read `process.env` so the
// Docker / native target swap (BFF_TARGET in dev.compose.yml) works
// without a rebuild.
const target = process.env['BFF_TARGET'] ?? 'http://localhost:3000';
module.exports = {
'/api': {
target,
secure: false,
changeOrigin: true,
},
};
@@ -13,17 +13,13 @@
*/ */
export const environment = { export const environment = {
/** /**
* Prefix of the BFF HTTP API. Same value as portal-shell — both * Origin + prefix of the BFF HTTP API. Same value as portal-shell
* SPAs talk to the same BFF (per ADR-0020 §"Where does the admin * — both SPAs talk to the same BFF (per ADR-0020 §"Where does
* app live"). The admin-specific routing happens via the * the admin app live"). The admin-specific routing happens via
* `AUTH_PATH_PREFIX` token (`/admin/auth`) provided in * the `AUTH_PATH_PREFIX` token (`/admin/auth`) provided in
* `app.config.ts`, not by talking to a different host. * `app.config.ts`, not by talking to a different host.
*
* Relative path: see portal-shell `environment.ts` for the full
* rationale. Both SPAs use `proxy.conf.js` to proxy `/api/*` to
* the BFF, keeping every call same-origin in the browser.
*/ */
bffApiBaseUrl: '/api', bffApiBaseUrl: 'http://localhost:3000/api',
/** /**
* Name of the BFF's CSRF cookie. v1 reuses `portal_csrf` * Name of the BFF's CSRF cookie. v1 reuses `portal_csrf`
-17
View File
@@ -60,23 +60,6 @@ ENTRA_CLIENT_SECRET=replace_with_real_value
# User portal — `/api/auth/callback` is the OIDC return URL; the # User portal — `/api/auth/callback` is the OIDC return URL; the
# post-logout URL is where Entra sends the browser after RP-initiated # post-logout URL is where Entra sends the browser after RP-initiated
# logout (typically the SPA landing page). # logout (typically the SPA landing page).
#
# The four `localhost` values below are the **WSL-native default** —
# browser and BFF on the same host, `http://localhost:*` redirect
# URIs (which Entra accepts as the only exception to its HTTPS rule).
# Leave them here in this file regardless of how the docker `apps`
# profile is being run.
#
# For the ADR-0030 dockerised `apps` profile accessed via a
# hostname (e.g. `https://apf-portal.dev-jg.local:4200/`), do NOT
# edit these values — instead override them at the compose level
# from `infra/local/.env`. Compose's `environment:` block on the
# `portal-bff` service interpolates each of these four vars at
# parse time and wins over `env_file:`, so the BFF in the container
# sees the hostname URIs while native `nx serve` keeps reading
# this file's localhost defaults. See
# `infra/README.md` → "Switching between dev modes" for the
# two-mode toggle.
ENTRA_REDIRECT_URI=http://localhost:3000/api/auth/callback ENTRA_REDIRECT_URI=http://localhost:3000/api/auth/callback
ENTRA_POST_LOGOUT_REDIRECT_URI=http://localhost:4200/ ENTRA_POST_LOGOUT_REDIRECT_URI=http://localhost:4200/
# Admin portal — distinct callback per ADR-0020 §"Sessions — distinct # Admin portal — distinct callback per ADR-0020 §"Sessions — distinct
@@ -153,32 +153,6 @@ describe('createRateLimitMiddleware', () => {
await mw(makeReq({ ip: '10.0.0.11', path: '/api/x' }), res, next); await mw(makeReq({ ip: '10.0.0.11', path: '/api/x' }), res, next);
expect(res.status).not.toHaveBeenCalledWith(429); expect(res.status).not.toHaveBeenCalledWith(429);
}); });
it('keys IPv6 addresses by their /56 prefix so per-host rotation cannot bypass the bucket', async () => {
const mw = createRateLimitMiddleware({ perMinute: 1, authPerMinute: 99 });
const next = jest.fn() as unknown as NextFunction;
// Two addresses inside `2001:db8:abcd:0000::/56` must share a
// bucket — otherwise an attacker swaps the host suffix on every
// retry and the per-IP limit never bites. This is the bypass the
// lib's `ERR_ERL_KEY_GEN_IPV6` boot-time validation refuses to
// ship. (The lib v8 default mask is `/56`, a typical residential
// ISP customer allocation.)
let res = makeRes();
await mw(makeReq({ ip: '2001:db8:abcd::1', path: '/api/x' }), res, next);
expect(res.status).not.toHaveBeenCalledWith(429);
res = makeRes();
await mw(makeReq({ ip: '2001:db8:abcd::ffff', path: '/api/x' }), res, next);
expect(res.status).toHaveBeenCalledWith(429);
// Different `/56` (`2001:db8:abce::/56`) — independent bucket.
// Confirms the truncation does not collapse all IPv6 traffic into
// one global bucket.
res = makeRes();
await mw(makeReq({ ip: '2001:db8:abce::1', path: '/api/x' }), res, next);
expect(res.status).not.toHaveBeenCalledWith(429);
});
}); });
function restore(name: string, value: string | undefined): void { function restore(name: string, value: string | undefined): void {
@@ -1,5 +1,5 @@
import type { NextFunction, Request, RequestHandler, Response } from 'express'; import type { NextFunction, Request, RequestHandler, Response } from 'express';
import rateLimit, { ipKeyGenerator, type Options } from 'express-rate-limit'; import rateLimit, { type Options } from 'express-rate-limit';
import { errorResponse } from './structured-error.filter'; import { errorResponse } from './structured-error.filter';
/** /**
@@ -79,14 +79,7 @@ export function createRateLimitMiddleware(config: RateLimitConfig): RequestHandl
if (hasSession && sessionId) { if (hasSession && sessionId) {
return `s:${sessionId}`; return `s:${sessionId}`;
} }
// `ipKeyGenerator` normalises the address before keying — most return `ip:${req.ip ?? 'unknown'}`;
// importantly, it truncates IPv6 to its `/56` prefix (the lib v8
// default — a typical residential ISP customer allocation) so an
// attacker can't rotate through the trailing bits of their own
// subnet to escape the per-IP bucket. The lib raises
// `ERR_ERL_KEY_GEN_IPV6` at boot if a custom keyGenerator returns
// `req.ip` verbatim, exactly to prevent that bypass.
return `ip:${ipKeyGenerator(req.ip ?? 'unknown')}`;
}, },
handler: (_req: Request, res: Response, _next: NextFunction, _optionsUsed: Options) => { handler: (_req: Request, res: Response, _next: NextFunction, _optionsUsed: Options) => {
res.status(429).json(errorResponse('rate_limited', 'Too many requests')); res.status(429).json(errorResponse('rate_limited', 'Too many requests'));
-9
View File
@@ -83,21 +83,12 @@
"serve": { "serve": {
"continuous": true, "continuous": true,
"executor": "@angular/build:dev-server", "executor": "@angular/build:dev-server",
"options": {
"proxyConfig": "apps/portal-shell/proxy.conf.js"
},
"configurations": { "configurations": {
"production": { "production": {
"buildTarget": "portal-shell:build:production" "buildTarget": "portal-shell:build:production"
}, },
"development": { "development": {
"buildTarget": "portal-shell:build:development" "buildTarget": "portal-shell:build:development"
},
"https": {
"buildTarget": "portal-shell:build:development",
"ssl": true,
"sslKey": ".secrets/dev-tls.key",
"sslCert": ".secrets/dev-tls.pem"
} }
}, },
"defaultConfiguration": "development" "defaultConfiguration": "development"
-32
View File
@@ -1,32 +0,0 @@
// Angular dev-server proxy for portal-shell.
//
// Lets the SPA call `/api/...` as a SAME-ORIGIN request — the dev
// server intercepts it and proxies to the BFF. Two wins:
// - the browser no longer pins the BFF to `localhost:3000`, so the
// SPA works when accessed from a different host (e.g. `http://
// <vm-ip>:4200/` in the ADR-0030 dockerised dev mode, where the
// browser may not be on the same machine as the BFF);
// - CORS is bypassed entirely in dev (same origin), so the BFF's
// `CORS_ALLOWED_ORIGINS` allowlist no longer has to enumerate the
// workstation/VM hostnames a developer might use.
//
// Target resolution:
// - native `nx serve` → defaults to http://localhost:3000
// (the BFF on the same machine).
// - Compose `apps` profile → BFF_TARGET=http://portal-bff:3000 is
// set in dev.compose.yml so the proxy
// hits the BFF container by name.
//
// JS form (not JSON) is deliberate: it is the only Angular-supported
// proxy-config form that can read `process.env` at dev-server startup,
// which is what makes the Docker / native swap work without rebuilds.
const target = process.env['BFF_TARGET'] ?? 'http://localhost:3000';
module.exports = {
'/api': {
target,
secure: false,
changeOrigin: true,
},
};
@@ -18,24 +18,12 @@
*/ */
export const environment = { export const environment = {
/** /**
* Prefix of the BFF HTTP API. The SPA prepends this to every * Origin + prefix of the BFF HTTP API. The SPA prepends this to
* backend call (`${bffApiBaseUrl}/health`, etc.) and derives the * every backend call (`${bffApiBaseUrl}/health`, etc.) and derives
* OTel trace-header propagation pattern from its resolved origin * the OTel trace-header propagation pattern from its origin (see
* (see `observability/tracing.ts`). * `observability/tracing.ts`).
*
* Relative path: the Angular dev-server proxies `/api/*` to the
* BFF (see `proxy.conf.js`, BFF target overridable via the
* `BFF_TARGET` env var — set by the ADR-0030 `apps` Compose
* profile to `http://portal-bff:3000`). This keeps every BFF call
* same-origin in the browser, so the SPA works whether it is
* accessed via `localhost:4200`, the VM IP, or any other host —
* and the BFF's `CORS_ALLOWED_ORIGINS` no longer has to enumerate
* every developer-side hostname. Production siblings
* (`environment.prod.ts`, etc.) may set an absolute origin when
* the SPA and BFF live on different hosts; `tracing.ts` resolves
* either form against `window.location.origin`.
*/ */
bffApiBaseUrl: '/api', bffApiBaseUrl: 'http://localhost:3000/api',
/** /**
* Name of the BFF's CSRF cookie. Mirrors the BFF's * Name of the BFF's CSRF cookie. Mirrors the BFF's
@@ -55,13 +55,7 @@ const SERVICE_VERSION = 'dev';
// so a deploy-time change to `bffApiBaseUrl` automatically propagates // so a deploy-time change to `bffApiBaseUrl` automatically propagates
// `traceparent` to the right origin. RegExp special chars are escaped // `traceparent` to the right origin. RegExp special chars are escaped
// before going into the source. // before going into the source.
// const bffOrigin = new URL(environment.bffApiBaseUrl).origin;
// Resolved against `window.location.origin` so a relative
// `bffApiBaseUrl` (e.g. `/api` for the dev-server proxy in
// `proxy.conf.js`) yields the current origin; an absolute
// `bffApiBaseUrl` (e.g. cross-origin production) keeps its own origin
// (the second `URL` arg is ignored when the first is absolute).
const bffOrigin = new URL(environment.bffApiBaseUrl, window.location.origin).origin;
const bffOriginRegex = new RegExp(`^${bffOrigin.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/.*`); const bffOriginRegex = new RegExp(`^${bffOrigin.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/.*`);
const provider = new WebTracerProvider({ const provider = new WebTracerProvider({
-112
View File
@@ -1,112 +0,0 @@
---
status: accepted
date: 2026-05-28
decision-makers: R&D Lead
tags: [infrastructure, process]
---
# Dockerised full-stack dev mode — `compose up` runs the Nx apps alongside infra
## Context and Problem Statement
Today the local **infrastructure** (PostgreSQL / Redis / OTel Collector) runs in Docker via [`infra/local/dev.compose.yml`](../../infra/local/dev.compose.yml), but the **Nx applications** (`portal-bff`, `portal-shell`, `portal-admin`) run **natively** — requiring Node + pnpm installed on the host (workstation or `vm-dev`). Two frictions follow:
1. **Onboarding requires the native toolchain.** nvm + corepack + the pinned pnpm is a setup step that fails in non-obvious ways — a fresh-VM install just hit exactly this (the nvm init never reached the zsh session, so `node` / `pnpm` were "command not found").
2. **A developer asked to run the whole stack with a single `docker compose up`** — no native toolchain, no IDE attach. The use case is real for frontend-focused work, quick demos, and onboarding.
How do we offer a "just run everything in Docker" dev mode **without regressing** the two flows that work today (native `nx serve`; the [ADR-0020](0020-portal-admin-app.md)-era VSCode devcontainer)?
## Decision Drivers
- **Onboarding friction.** The native toolchain (nvm / corepack / pnpm pin) is the step most likely to break for a new dev; the recent `.zshrc` nvm gap is evidence.
- **A concrete developer request.** `docker compose up` → all servers, zero native Node/pnpm.
- **Consistency with the all-in-Docker posture.** Infra is already containerised; the apps are the gap.
- **No regression.** The native `nx serve` flow and the devcontainer flow serve IDE-integrated development + debugging; both must keep working unchanged.
- **Hot reload is non-negotiable.** Angular/Vite HMR and NestJS watch mode must work inside the containers, or the mode is useless for actual development.
- **Stable, recognised tooling only** (CLAUDE.md bar) — Docker Compose + the official `node` image, no exotic dev-orchestration layer.
- **Dev-only scope.** Production images are a separate concern, already earmarked for the GitLab Container Registry after the [ADR-0028](0028-migrate-cicd-and-git-hosting-to-gitlab.md) cutover. This ADR must not entangle dev DX with deployment artefacts.
## Considered Options
- **Option A — Status quo.** Native apps + the optional devcontainer; no compose-run apps.
- **Option B — Extend `dev.compose.yml` with an `apps` profile** running the three Nx dev servers from one shared `Dockerfile.dev` (chosen).
- **Option C — Per-app Dockerfiles + a separate apps compose file**, layered over the infra compose.
- **Option D — Lean on the devcontainer alone** — tell the developer to use "Reopen in Container".
## Decision Outcome
Chosen option: **B — an `apps` Compose profile backed by a single `Dockerfile.dev`**, because it satisfies the `docker compose up` request, removes the native-toolchain dependency for that audience, and — being **profile-gated** — leaves the infra-only mode (and therefore the native and devcontainer flows) untouched.
### Shape of the implementation (specified here, built in the follow-up PR)
- **One `Dockerfile.dev`** at `infra/local/` (or repo root): `node:24-bookworm` + corepack activating the pinned pnpm. The monorepo means **one image, one install** serves all three apps.
- **Three Compose services** — `portal-bff`, `portal-shell`, `portal-admin` — all from that image, differing only by command (`pnpm exec nx serve <app> --host 0.0.0.0`) and published port (`3000` / `4200` / `4300`, matching the devcontainer's `forwardPorts`).
- **Repo bind-mounted** into each service for hot reload; **`node_modules` (and the Nx cache) held in named volumes**, NOT bind-mounted — this is the load-bearing detail: native modules (`esbuild`, `@swc/core`, Prisma engines, `lmdb`, `@parcel/watcher`) must be the ones installed _inside_ the container, never shadowed by the host's `node_modules`.
- **`depends_on` the infra services with `condition: service_healthy`** (the compose already defines healthchecks for postgres/redis).
- **BFF entrypoint**: install-if-cold → `prisma generate``prisma migrate deploy` → serve. (`migrate deploy`, not `migrate dev` — apply committed migrations only; never auto-author in a container.)
- **Env** points at Compose service names: `postgres:5432`, `redis:6379`, `otel-collector:4317` — same `apf-portal-dev` network the devcontainer already joins.
- **Profile-gated**: the services carry `profiles: [apps]`, so `./infra/local/dev.sh up` stays infra-only (native devs unaffected) and `./infra/local/dev.sh up apps` brings up the full stack.
### Three coexisting modes — "which when"
The follow-up PR documents this table in `docs/setup/`:
| Mode | Toolchain on host | Best for |
| -------------------------- | ------------------ | ------------------------------------------------------------------------------------------ |
| **Native** (`nx serve`) | Node + pnpm native | Day-to-day dev with the fastest iteration + simplest debugger attach. |
| **Devcontainer** | none (Docker) | IDE-integrated dev without a native toolchain; VSCode attaches, you run `nx serve` inside. |
| **Compose `apps` profile** | none (Docker) | "Run everything with one command" — onboarding, frontend-only work, demos, no IDE attach. |
### Consequences
- **Good**, because `docker compose --profile apps up` yields the full stack with zero native toolchain — and an onboarding path that structurally cannot hit the nvm/`.zshrc` class of failure.
- **Good**, because it is consistent with the already-containerised infra and is purely opt-in (profile-gated) — native and devcontainer flows are byte-for-byte unchanged.
- **Good**, because a single image + single install keeps the monorepo's dev container cheap to build and reason about.
- **Bad**, because it adds a **third** run mode to document and keep working as the apps evolve — mitigated by the explicit "which when" table and by sharing the infra network/healthchecks already in place.
- **Bad**, because iteration is marginally slower than native (Nx daemon/cache across the container lifecycle; Vite rebuilds) and **debugger attach needs extra wiring** (inspector port + source-map paths) — acceptable because the target audience for this mode is precisely the one that does not need a step-debugger.
- **Bad**, because `node_modules` in a named volume means a lockfile bump needs a re-install pass (the entrypoint handles it; first run after a bump is slower) and the image + volumes consume host disk.
- **Neutral**, because this is **dev-only**: it deliberately produces no deployment artefact. Production images land later with the [ADR-0028](0028-migrate-cicd-and-git-hosting-to-gitlab.md) Container Registry work; if a `Dockerfile.dev` stage can be reused there, that is a bonus, not a goal here.
### Confirmation
- On a host with **no native Node/pnpm**, a fresh checkout runs `./infra/local/dev.sh up apps` (or the raw `docker compose … --profile apps up`) and reaches: BFF healthy on `:3000`, `portal-shell` on `:4200`, `portal-admin` on `:4300`, all connected to postgres/redis/otel.
- Editing a source file triggers HMR / watch-reload in the relevant container within a few seconds (validated for at least one app of each type — Angular and NestJS).
- The infra-only invocation (`dev.sh up`, no `apps`) is unchanged — native devs see no difference.
- The "which mode when" table lands in `docs/setup/`.
## Pros and Cons of the Options
### Option A — Status quo (native apps + optional devcontainer)
- Good, because zero new surface to maintain.
- Good, because native iteration is the fastest and debugging is simplest.
- Bad, because it does not answer the `docker compose up` request.
- Bad, because every new dev still pays the native-toolchain setup cost (the friction that motivated this ADR).
### Option B — `apps` profile + shared `Dockerfile.dev` (chosen)
- Good, because one command brings up the full stack with no native toolchain.
- Good, because profile-gating makes it purely additive — no regression to native/devcontainer.
- Good, because one image/one install fits the monorepo and is cheap.
- Neutral, because it reuses the existing `apf-portal-dev` network + healthchecks rather than inventing new infra.
- Bad, because it is a third documented mode and adds the node_modules-volume + debugger-attach caveats above.
### Option C — Per-app Dockerfiles + separate apps compose
- Good, because per-app images map cleanly onto eventual production images.
- Bad, because three Dockerfiles + a second compose file is more surface for a monorepo where one install serves all apps — premature for a dev-only mode.
- Bad, because a separate compose file fragments the "up" experience (two files to coordinate) vs a profile in the existing one.
### Option D — Devcontainer only
- Good, because it already exists and already removes the native toolchain.
- Bad, because it is **interactive / IDE-bound** — you reopen in the container and run `nx serve` by hand. It does not deliver the "one `docker compose up` runs every server" experience the request is about.
- Bad, because it ties the no-toolchain path to VSCode specifically.
## More Information
- Complements [ADR-0020](0020-portal-admin-app.md) (the VSCode devcontainer) — this ADR adds a non-interactive, services-oriented sibling, not a replacement.
- The BFF entrypoint's `prisma generate` + `migrate deploy` follows [ADR-0006](0006-persistence-postgresql-prisma.md); migrations are applied, never authored, inside the container.
- Production images are **out of scope** and tracked against the [ADR-0028](0028-migrate-cicd-and-git-hosting-to-gitlab.md) Container Registry follow-up (post-cutover).
- Builds on the existing [`infra/local/dev.compose.yml`](../../infra/local/dev.compose.yml) profiles pattern (`dbtools`, `observability`, `serve-static`) — `apps` is one more profile in the same idiom.
- Accepted; the implementation PR carries the `Dockerfile.dev`, the `apps` Compose profile, the BFF entrypoint, the CLAUDE.md architecture roll-up entry, and the "which mode when" guidance in `docs/setup/`.
-1
View File
@@ -72,4 +72,3 @@ ADRs are listed in numerical order. To slice by topic, filter on the `Tags` colu
| [0026](0026-person-user-portal-data-model.md) | `Person` golden record + `User` portal-account — portal-side identity model | accepted | `data`, `backend`, `security` | 2026-05-24 | | [0026](0026-person-user-portal-data-model.md) | `Person` golden record + `User` portal-account — portal-side identity model | accepted | `data`, `backend`, `security` | 2026-05-24 |
| [0027](0027-portal-side-organisational-hierarchy.md) | Portal-side organisational hierarchy — `Structure` with kind discriminator and nullable FINESS / SIRET | accepted | `data`, `backend` | 2026-05-24 | | [0027](0027-portal-side-organisational-hierarchy.md) | Portal-side organisational hierarchy — `Structure` with kind discriminator and nullable FINESS / SIRET | accepted | `data`, `backend` | 2026-05-24 |
| [0028](0028-migrate-cicd-and-git-hosting-to-gitlab.md) | Migrate CI/CD + git hosting from Gitea to GitLab self-hosted | accepted | `infrastructure`, `process` | 2026-05-26 | | [0028](0028-migrate-cicd-and-git-hosting-to-gitlab.md) | Migrate CI/CD + git hosting from Gitea to GitLab self-hosted | accepted | `infrastructure`, `process` | 2026-05-26 |
| [0030](0030-dockerised-dev-mode.md) | Dockerised full-stack dev mode — `compose up` runs the Nx apps alongside infra | accepted | `infrastructure`, `process` | 2026-05-28 |
+10 -28
View File
@@ -160,16 +160,16 @@ The `bootstrap.sh` script runs every numbered script (`10-…` → `80-…`) in
What each script does: What each script does:
| Script | Effect | Idempotent? | | Script | Effect | Idempotent? |
| ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
| [`10-base-packages.sh`](scripts/10-base-packages.sh) | `apt update` + install the minimal set every other script depends on: `curl wget git ca-certificates gnupg build-essential pkg-config`. | ✅ | | [`10-base-packages.sh`](scripts/10-base-packages.sh) | `apt update` + install the minimal set every other script depends on: `curl wget git ca-certificates gnupg build-essential pkg-config`. | ✅ |
| [`20-zsh.sh`](scripts/20-zsh.sh) | Install zsh + Oh My Zsh + Powerlevel10k + plugins (autosuggestions, syntax-highlighting). Patch `~/.zshrc` (theme + plugins + fzf hook) and `~/.bashrc` (exec zsh on interactive shells — `chsh` is blocked on the corp VM). | ✅ | | [`20-zsh.sh`](scripts/20-zsh.sh) | Install zsh + Oh My Zsh + Powerlevel10k + plugins (autosuggestions, syntax-highlighting). Patch `~/.zshrc` (theme + plugins + fzf hook) and `~/.bashrc` (exec zsh on interactive shells — `chsh` is blocked on the corp VM). | ✅ |
| [`30-cli-tools.sh`](scripts/30-cli-tools.sh) | Install `bat eza fd-find ripgrep fzf zoxide ncdu keychain` + `jq yq httpie make tree htop tmux direnv dnsutils unzip`. Aliases for the Debian-renamed binaries (`batcat``bat`, `fdfind``fd`). | ✅ | | [`30-cli-tools.sh`](scripts/30-cli-tools.sh) | Install `bat eza fd-find ripgrep fzf zoxide ncdu keychain` + `jq yq httpie make tree htop tmux direnv dnsutils unzip`. Aliases for the Debian-renamed binaries (`batcat``bat`, `fdfind``fd`). | ✅ |
| [`40-node.sh`](scripts/40-node.sh) | Install nvm. Install Node from the repo's `.nvmrc` (currently `24`). Enable corepack, pin pnpm to `package.json`'s `packageManager`. Mirror the nvm init into `~/.zshrc` (the installer only patches `~/.bashrc`, which the zsh hand-off execs past — without this, zsh has no node/pnpm on PATH). | ✅ | | [`40-node.sh`](scripts/40-node.sh) | Install nvm. Install Node from the repo's `.nvmrc` (currently `24`). Enable corepack, pin pnpm to `package.json`'s `packageManager`. | ✅ |
| [`50-docker.sh`](scripts/50-docker.sh) | Install Docker CE + compose plugin from the Docker apt repo. Add the current user to the `docker` group. Enable `docker.service`. | ✅ | | [`50-docker.sh`](scripts/50-docker.sh) | Install Docker CE + compose plugin from the Docker apt repo. Add the current user to the `docker` group. Enable `docker.service`. | ✅ |
| [`60-tuning.sh`](scripts/60-tuning.sh) | `fs.inotify.max_user_watches=524288` (Vite / Nx watch). Prompt for hostname (only if generic). Add a 4 GB swapfile if none. | ✅ | | [`60-tuning.sh`](scripts/60-tuning.sh) | `fs.inotify.max_user_watches=524288` (Vite / Nx watch). Prompt for hostname (only if generic). Add a 4 GB swapfile if none. | ✅ |
| [`70-hardening.sh`](scripts/70-hardening.sh) | Best-effort UFW (allow SSH only, prompts before enabling), `unattended-upgrades` on security channel, `fail2ban` (opt-in — prompts before installing), sshd hardening (no root, no password — prompts before applying). **Probes before applying** — skips what's already done. | ✅ | | [`70-hardening.sh`](scripts/70-hardening.sh) | Best-effort UFW (allow SSH only, prompts before enabling), `unattended-upgrades` on security channel, `fail2ban` (opt-in — prompts before installing), sshd hardening (no root, no password — prompts before applying). **Probes before applying** — skips what's already done. | ✅ |
| [`80-dotfiles.sh`](scripts/80-dotfiles.sh) | Symlink `docs/setup/dotfiles/aliases.zsh``~/.oh-my-zsh/custom/aliases.zsh`. Generate `~/.gitconfig` from `docs/setup/dotfiles/gitconfig.txt`, prompt for identity (name + email). | ✅ | | [`80-dotfiles.sh`](scripts/80-dotfiles.sh) | Symlink `docs/setup/dotfiles/aliases.zsh``~/.oh-my-zsh/custom/aliases.zsh`. Generate `~/.gitconfig` from `docs/setup/dotfiles/gitconfig.txt`, prompt for identity (name + email). | ✅ |
After bootstrap, reload your shell to pick up the new PATH + zsh: After bootstrap, reload your shell to pick up the new PATH + zsh:
@@ -203,24 +203,6 @@ pnpm exec nx run-many -t lint test --parallel=3 # smoke test
## Step 5 — Choose your IDE flow ## Step 5 — Choose your IDE flow
### Running the apps — three modes (which when)
There are three ways to run the apps locally. They coexist; pick by need.
| Mode | Toolchain on host | Best for |
| --------------------------------- | ------------------ | ----------------------------------------------------------------------------------------- |
| **Native** (`pnpm nx serve`) | Node + pnpm native | Day-to-day dev — fastest iteration, simplest debugger attach. |
| **Devcontainer** (Option B below) | none (Docker) | IDE-integrated dev with no native toolchain; VSCode attaches, you run `nx serve` inside. |
| **Compose `apps` profile** | none (Docker) | "Run everything with one command" — onboarding, frontend-only work, demos. No IDE attach. |
The Compose `apps` profile (per [ADR-0030](../decisions/0030-dockerised-dev-mode.md)) is the lightest way to boot the full stack without a native toolchain:
```bash
./infra/local/dev.sh up apps # infra + portal-bff:3000 + portal-shell:4200 + portal-admin:4300
```
Usage, prerequisites (the BFF still needs its `apps/portal-bff/.env` secrets) and the port caveat are documented in [infra/README.md](../../infra/README.md) → "Dockerised app dev mode". The IDE-flow options below (Remote-SSH / Devcontainer / Hybrid) are orthogonal — they decide where your editor + terminals run, not how the apps boot.
### Option A — VSCode Remote-SSH (default) ### Option A — VSCode Remote-SSH (default)
From your workstation: From your workstation:
-23
View File
@@ -53,27 +53,4 @@ if [[ -f "$REPO_ROOT/package.json" ]]; then
popd >/dev/null popd >/dev/null
fi fi
# The nvm installer appends its init to ~/.bashrc only. But the
# interactive shell on this VM is zsh: 20-zsh.sh hands off via
# `exec zsh -l` (chsh is blocked on the corp VM). That hand-off execs
# zsh *before* the nvm block in ~/.bashrc runs, and the nvm installer
# leaves ~/.zshrc untouched — so without this, zsh sessions have
# neither node nor pnpm on PATH. Mirror the nvm init into ~/.zshrc
# (idempotent via marker, same pattern as 20-zsh.sh's .bashrc patch).
ZSHRC="$HOME/.zshrc"
[[ -f "$ZSHRC" ]] || touch "$ZSHRC"
NVM_MARKER='# Managed by docs/setup/scripts/40-node.sh — nvm init for zsh.'
if grep -qF "$NVM_MARKER" "$ZSHRC"; then
skip "nvm init already in $ZSHRC."
else
cat >> "$ZSHRC" <<'EOF'
# Managed by docs/setup/scripts/40-node.sh — nvm init for zsh.
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
EOF
ok "Patched $ZSHRC with nvm init."
fi
log "Reload your shell (exec zsh -l) so nvm + node + pnpm are on PATH." log "Reload your shell (exec zsh -l) so nvm + node + pnpm are on PATH."
+30 -240
View File
@@ -2,16 +2,15 @@
Infrastructure-as-code artefacts for the project. Separate from application code and from documentation: this folder contains the recipes and configs that the team and ops use to stand up running infrastructure (CI runners, future local-dev databases, future on-prem deploy assets). Infrastructure-as-code artefacts for the project. Separate from application code and from documentation: this folder contains the recipes and configs that the team and ops use to stand up running infrastructure (CI runners, future local-dev databases, future on-prem deploy assets).
| Subject | File / Folder | ADR / Reference | | Subject | File / Folder | ADR / Reference |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | -------------------------------------- | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Self-hosted CI runners (Gitea Actions) | [`ci-runners.compose.yml`](ci-runners.compose.yml) | [ADR-0015 §"Runners"](../docs/decisions/0015-cicd-gitea-actions.md) | | Self-hosted CI runners (Gitea Actions) | [`ci-runners.compose.yml`](ci-runners.compose.yml) | [ADR-0015 §"Runners"](../docs/decisions/0015-cicd-gitea-actions.md) |
| Shared `act_runner` configuration | [`runner-config.yaml`](runner-config.yaml) | [ADR-0015 §"Runners"](../docs/decisions/0015-cicd-gitea-actions.md) | | Shared `act_runner` configuration | [`runner-config.yaml`](runner-config.yaml) | [ADR-0015 §"Runners"](../docs/decisions/0015-cicd-gitea-actions.md) |
| CI runners convenience script | [`ci-runners.sh`](ci-runners.sh) | See "Convenience script" below | | CI runners convenience script | [`ci-runners.sh`](ci-runners.sh) | See "Convenience script" below |
| Runtime state of the runners | `data/` (git-ignored after `.gitignore`) | — | | Runtime state of the runners | `data/` (git-ignored after `.gitignore`) | — |
| Env-vars template for the runners | `.env.example` (`.env` is git-ignored) | — | | Env-vars template for the runners | `.env.example` (`.env` is git-ignored) | — |
| Local-dev runtime stack | [`local/`](local/) | [ADR-0006](../docs/decisions/0006-persistence-postgresql-prisma.md), [ADR-0010](../docs/decisions/0010-session-management-redis.md), [ADR-0012](../docs/decisions/0012-observability-pino-opentelemetry.md), [ADR-0013](../docs/decisions/0013-audit-trail-separated-postgres-append-only.md) | | Local-dev runtime stack | [`local/`](local/) | [ADR-0006](../docs/decisions/0006-persistence-postgresql-prisma.md), [ADR-0010](../docs/decisions/0010-session-management-redis.md), [ADR-0012](../docs/decisions/0012-observability-pino-opentelemetry.md), [ADR-0013](../docs/decisions/0013-audit-trail-separated-postgres-append-only.md) |
| Entra group GUID → role slug map | [`test-tenant.entra.example.json`](test-tenant.entra.example.json) (`*-tenant.entra.json` is git-ignored) | [ADR-0025 §"Sources of truth — Entra-side configuration"](../docs/decisions/0025-authorization-model-privileges-roles-scopes.md) | | Entra group GUID → role slug map | [`test-tenant.entra.example.json`](test-tenant.entra.example.json) (`*-tenant.entra.json` is git-ignored) | [ADR-0025 §"Sources of truth — Entra-side configuration"](../docs/decisions/0025-authorization-model-privileges-roles-scopes.md) |
| Per-persona Entra `oid` map | [`test-tenant.personas.example.json`](test-tenant.personas.example.json) (`*-tenant.personas.json` is git-ignored) | [ADR-0026 §"Seed personas"](../docs/decisions/0026-person-user-portal-data-model.md) — consumed by `apps/portal-bff/prisma/seed.ts` |
Future folders / files that will land here as the corresponding ADRs ship: Future folders / files that will land here as the corresponding ADRs ship:
@@ -144,16 +143,14 @@ Old, no-longer-referenced images can be reaped during the periodic `docker syste
A Docker Compose recipe spinning up the runtime services the BFF and ADRs assume — Postgres, Redis, OpenTelemetry Collector — plus optional viewers / tooling (pgweb, Jaeger UI, Caddy serve-static) gated behind Compose profiles. Designed to start in a single command on a contributor's WSL2 / Linux / macOS host. A Docker Compose recipe spinning up the runtime services the BFF and ADRs assume — Postgres, Redis, OpenTelemetry Collector — plus optional viewers / tooling (pgweb, Jaeger UI, Caddy serve-static) gated behind Compose profiles. Designed to start in a single command on a contributor's WSL2 / Linux / macOS host.
| File | Role | | File | Role |
| -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| [`local/dev.sh`](local/dev.sh) | Convenience wrapper around `docker compose` — see "Convenience script" below | | [`local/dev.sh`](local/dev.sh) | Convenience wrapper around `docker compose` — see "Convenience script" below |
| [`local/dev.compose.yml`](local/dev.compose.yml) | Service definitions: postgres, redis, otel-collector, plus pgweb / jaeger / caddy / the `apps` dev servers behind profiles | | [`local/dev.compose.yml`](local/dev.compose.yml) | Service definitions: postgres, redis, otel-collector, plus pgweb / jaeger / caddy behind profiles |
| [`local/Dockerfile.dev`](local/Dockerfile.dev) | Dev-only image (Node 24 + corepack) shared by the three `apps`-profile dev servers (ADR-0030) | | [`local/.env.example`](local/.env.example) | Credentials + ports template (copy to `.env`, which is git-ignored) |
| [`local/dev-entrypoint.sh`](local/dev-entrypoint.sh) | Entrypoint for the `apps` services: BFF runs `prisma generate` + `migrate deploy`, then each runs `nx serve` | | [`local/init/postgres/01-init.sql`](local/init/postgres/01-init.sql) | Bootstrap SQL for ADR-0013: audit roles + schema, applied on first boot only |
| [`local/.env.example`](local/.env.example) | Credentials + ports template (copy to `.env`, which is git-ignored) | | [`local/otel-collector.yaml`](local/otel-collector.yaml) | Collector pipeline: OTLP receivers → batch → debug exporter (always) + forward to Jaeger when active |
| [`local/init/postgres/01-init.sql`](local/init/postgres/01-init.sql) | Bootstrap SQL for ADR-0013: audit roles + schema, applied on first boot only | | [`local/Caddyfile`](local/Caddyfile) | Reverse-proxy config for the `serve-static` profile — per-locale SPA fallback + smart `/` redirect (ADR-0019) |
| [`local/otel-collector.yaml`](local/otel-collector.yaml) | Collector pipeline: OTLP receivers → batch → debug exporter (always) + forward to Jaeger when active |
| [`local/Caddyfile`](local/Caddyfile) | Reverse-proxy config for the `serve-static` profile — per-locale SPA fallback + smart `/` redirect (ADR-0019) |
### First-time setup ### First-time setup
@@ -187,231 +184,24 @@ $EDITOR infra/local/.env
Run `./infra/local/dev.sh help` for the full reference. Cheat-sheet: Run `./infra/local/dev.sh help` for the full reference. Cheat-sheet:
| Command | Effect | | Command | Effect |
| ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | ------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| `./infra/local/dev.sh up` | Core only (postgres + redis + otel-collector) | | `./infra/local/dev.sh up` | Core only (postgres + redis + otel-collector) |
| `./infra/local/dev.sh up all` | Core + dbtools + observability + apps (full dev stack). serve-static is excluded — it would collide with apps on port 4200 | | `./infra/local/dev.sh up all` | Core + every profile |
| `./infra/local/dev.sh up dbtools` | Core + pgweb | | `./infra/local/dev.sh up dbtools` | Core + pgweb |
| `./infra/local/dev.sh up observability` | Core + Jaeger | | `./infra/local/dev.sh up observability` | Core + Jaeger |
| `./infra/local/dev.sh up serve-static` | Core + Caddy serving `dist/.../browser/` per ADR-0019 | | `./infra/local/dev.sh up serve-static` | Core + Caddy serving `dist/.../browser/` per ADR-0019 |
| `./infra/local/dev.sh up apps` | Core + the three Nx dev servers in Docker (ADR-0030) | | `./infra/local/dev.sh down` | Tear down the whole stack (every profile in scope) |
| `./infra/local/dev.sh down` | Tear down the whole stack (every profile in scope) | | `./infra/local/dev.sh down -v` | Tear down + wipe named volumes (incl. audit-roles bootstrap) |
| `./infra/local/dev.sh down -v` | Tear down + wipe named volumes (incl. audit-roles bootstrap) | | `./infra/local/dev.sh stop pgweb` | Stop one service (containers stay around) |
| `./infra/local/dev.sh stop pgweb` | Stop one service (containers stay around) | | `./infra/local/dev.sh status` | `docker compose ps`, with every profile visible |
| `./infra/local/dev.sh status` | `docker compose ps`, with every profile visible | | `./infra/local/dev.sh logs otel-collector` | Follow logs |
| `./infra/local/dev.sh logs otel-collector` | Follow logs | | `./infra/local/dev.sh exec postgres psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"` | Run a command inside a service |
| `./infra/local/dev.sh exec postgres psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"` | Run a command inside a service |
Anything not matching one of the named verbs is passed through to `docker compose -f dev.compose.yml ...` (with every profile flagged in), so you keep the full Compose surface available — `./dev.sh config`, `./dev.sh top`, `./dev.sh inspect …`, etc. Anything not matching one of the named verbs is passed through to `docker compose -f dev.compose.yml ...` (with every profile flagged in), so you keep the full Compose surface available — `./dev.sh config`, `./dev.sh top`, `./dev.sh inspect …`, etc.
If you prefer to call `docker compose` directly, every example below shows the raw command alongside the script form. If you prefer to call `docker compose` directly, every example below shows the raw command alongside the script form.
### Dockerised app dev mode — `apps` profile (ADR-0030)
The `apps` profile runs the three Nx dev servers **in Docker**, so a contributor can bring up the whole stack without installing Node / pnpm natively:
```bash
./infra/local/dev.sh up apps # infra + portal-bff:3000 + portal-shell:4200 + portal-admin:4300
```
How it works (see [ADR-0030](../docs/decisions/0030-dockerised-dev-mode.md)):
- A single [`Dockerfile.dev`](local/Dockerfile.dev) (Node 24 + corepack) backs all three services — one image, one install for the monorepo.
- The repo is bind-mounted for hot reload; `node_modules` and the Nx cache live in named volumes (`apf-portal-app-node-modules`, `apf-portal-app-nx-cache`) so the container's native modules are never shadowed by the host's.
- A one-shot `apps-deps` service runs `pnpm install` once into the shared volume; the three servers gate on its completion, avoiding a three-way install race.
- The BFF entrypoint runs `prisma generate` + `prisma migrate deploy` before serving.
**Prerequisite — the BFF still needs its secrets.** No native toolchain is required, but `apps/portal-bff/.env` (Entra / session / jwks config) must exist, same as native dev (`cp apps/portal-bff/.env.example apps/portal-bff/.env` then fill it). The host-specific URLs (`DATABASE_URL` / `REDIS_URL` / OTel endpoint) are overridden automatically to the Compose service names — you don't edit those for the container. SPA-only work (`up portal-shell`) doesn't need the BFF env.
**Port note.** The SPA dev servers default to 4200 / 4300 — 4200 is the same port the `serve-static` profile uses. Don't run `apps` and `serve-static` together, or set `SHELL_PORT` in `infra/local/.env`.
The three dev modes (native `nx serve`, devcontainer, this `apps` profile) and when to use each are summarised in [docs/setup/01-dev-debian-vm-setup.md](../docs/setup/01-dev-debian-vm-setup.md).
### Switching between dev modes — `localhost` vs hostname
Within the `apps` profile, there are **two access modes** for the SPA. They differ only in how the browser reaches the dev-servers — the BFF and the rest of the stack are unchanged. The toggle is a single file: [`infra/local/.env`](local/.env.example).
| Mode | When to use | What flips |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| **A — `localhost` (default)** | Solo dev, browser on the same workstation as the VSCode Remote-SSH client. No cert plumbing, no `hosts` file change. The fastest path to a working stack. | Nothing — `infra/local/.env` is the default. |
| **B — HTTPS hostname** | A teammate (or PM / QA) needs to browse YOUR VM from THEIR machine, or you have a shared VM. Requires the team mkcert CA already installed (see "Team mkcert CA on `vm-gitlab`" below) and `apf-portal.dev-XX.local` in their `hosts` file. | `NX_SERVE_CONFIGURATION=https` plus the four `ENTRA_*_REDIRECT_URI` lines in `infra/local/.env` (commented template in `.env.example`). |
The toggle works because Compose's `environment:` block on the `portal-bff` service interpolates each `ENTRA_*_REDIRECT_URI` from `infra/local/.env` with a `localhost` fallback, and wins over `env_file:`. As a result `apps/portal-bff/.env` keeps its native-friendly `localhost` defaults regardless of mode — native `nx serve` (no Docker) and Mode A both read the same `.env` cleanly, while Mode B sees the override only inside the container.
#### Mode A — `localhost` via VSCode port forwarding
1. Make sure `infra/local/.env` does NOT set `NX_SERVE_CONFIGURATION` (or sets it to `development`) and leaves the four `ENTRA_*_REDIRECT_URI` lines commented (this is the `.env.example` default).
2. `./infra/local/dev.sh up apps`.
3. VSCode Remote-SSH auto-discovers the published ports (panel **PORTS** at the bottom of VSCode) and forwards them to your workstation. If a port doesn't show up, "Forward a Port" manually (4200, 4300, 3000).
4. Open `http://localhost:4200/` on the workstation. The SPA loads, fetches `/api/...` (proxied to the BFF inside Compose), and the OIDC callback at `http://localhost:3000/api/auth/callback` (already registered in Entra) is reachable through the same VSCode tunnel.
Nothing else to configure. No mkcert. No `hosts` file. No cert warning.
#### Mode B — HTTPS hostname (`apf-portal.dev-XX.local`)
Detailed setup in the next two subsections ("HTTPS dev-server setup" + "Team mkcert CA on `vm-gitlab`"). Once the workstation has the team CA installed and the host file knows the hostname, switching is:
1. In `infra/local/.env`, uncomment the five Mode B lines (and replace `dev-jg` with the right hostname).
2. `./infra/local/dev.sh down && ./infra/local/dev.sh up apps`.
3. Browse `https://apf-portal.dev-XX.local:4200/`.
To switch back to Mode A: comment those five lines, `down && up apps`. No other file touched.
### HTTPS dev-server setup — remote-browser access via a hostname
By default the dev-servers serve plain HTTP — fine when the browser is on the same host as the BFF (`http://localhost:4200/`), which is also the only HTTP origin Entra accepts as a redirect URI. The moment you access the SPA over a **hostname** (e.g. `apf-portal.dev.local`, useful when the browser sits on a workstation and the stack runs on a shared / per-dev VM), Entra refuses the `http:` redirect URI and the dev-servers must terminate TLS.
The setup is one-time per dev:
1. **Install [mkcert](https://github.com/FiloSottile/mkcert)** on your workstation (the machine where the browser runs) and bootstrap its local CA:
```bash
# Debian / WSL Ubuntu:
sudo apt install -y libnss3-tools
# macOS:
# brew install mkcert nss
# Windows (PowerShell, choco):
# choco install mkcert
mkcert -install
```
2. **Generate the cert** for the hostname you registered in your `/etc/hosts` and in Entra. From the repo root on your workstation:
```bash
mkdir -p .secrets
mkcert -key-file .secrets/dev-tls.key -cert-file .secrets/dev-tls.pem \
apf-portal.dev-jg.local # ← replace with YOUR hostname
```
`.secrets/` is git-ignored; the bind-mount in the `apps` profile (the repo at `/workspace`) makes the files visible inside the containers at the path the `https` configuration expects.
3. **Update `apps/portal-bff/.env`** so the BFF tells Entra the matching HTTPS URIs — see the redirect-URI block in [`apps/portal-bff/.env.example`](../apps/portal-bff/.env.example) for the override pattern. The same URIs must be registered in your Entra app registration's "Redirect URIs" list (the BFF only sends one of them per auth request; Entra validates it is on the list).
4. **Enable the `https` Nx serve configuration** for the compose dev-servers by adding to `infra/local/.env`:
```env
NX_SERVE_CONFIGURATION=https
```
The compose command resolves `--configuration=${NX_SERVE_CONFIGURATION:-development}` at parse time, so the SPAs pick up the `https` config defined in `apps/portal-shell/project.json` and `apps/portal-admin/project.json`. The BFF stays HTTP behind the proxy — only the public origin is HTTPS.
5. `./infra/local/dev.sh up apps` → browser opens `https://apf-portal.dev-jg.local:4200/`. No cert warning (mkcert's CA is trusted by the workstation after step 1).
Native `nx serve` (WSL / localhost) is **unaffected** — it keeps using the `development` configuration by default, no SSL required, and the `localhost` URIs registered in Entra still work.
When real DNS + corp-CA-signed certs arrive, the hostname can be reused as-is (Entra registrations are literal strings — they don't care who signs the cert). Drop the cert files back into `.secrets/` and remove the mkcert step.
### Team mkcert CA on `vm-gitlab` — sharing the trust root
The previous section is the **solo flow** (one dev mints their own CA, certs only trusted by their own workstation). It does not let a teammate browse another dev's VM without a certificate warning — every dev has their own private CA, none of which the others trust.
For a multi-dev team the canonical pattern is one shared CA held on `vm-gitlab`. The CA private key (`rootCA-key.pem`) stays on `vm-gitlab` — never copied to any workstation; only the public `rootCA.pem` is distributed to each developer's Windows trust store, and the R&D Lead mints per-VM certs on `vm-gitlab` when a new VM (or new developer) joins. Browsing any dev VM from any workstation then "just works" — green padlock, no warning.
This subsection assumes the per-dev workstation procedure of "HTTPS dev-server setup" above is what every developer will do **once**, with the rootCA.pem they receive from this shared CA.
#### Initial setup on `vm-gitlab` (one-time, by the R&D Lead)
```bash
# 1. Install mkcert on vm-gitlab (no service to run — mkcert is one-shot).
sudo curl -fsSL https://dl.filippo.io/mkcert/latest?for=linux/amd64 \
-o /usr/local/bin/mkcert
sudo chmod +x /usr/local/bin/mkcert
# 2. Create the shared CAROOT, root-only.
sudo mkdir -p /srv/apf-portal/mkcert-ca
sudo chown root:root /srv/apf-portal/mkcert-ca
sudo chmod 700 /srv/apf-portal/mkcert-ca
# 3. Generate the CA into that CAROOT. (`-install` here just touches
# the local trust store of vm-gitlab — cosmetic for an infra VM,
# no harm.)
sudo CAROOT=/srv/apf-portal/mkcert-ca mkcert -install
# 4. Verify.
sudo ls -la /srv/apf-portal/mkcert-ca/
# → rootCA.pem (-rw-r--r--), rootCA-key.pem (-rw-------, root only)
```
After this, the CA exists and is owned by `root` on `vm-gitlab`. Developers never touch it directly.
#### Minting a cert for a dev VM (R&D Lead, on `vm-gitlab`)
Repeat once per VM hostname (`apf-portal.dev-jg.local`, `apf-portal.dev-vc.local`, `apf-portal.dev.local`, …). Replace `<host>` and the SSH/scp target accordingly:
```bash
sudo CAROOT=/srv/apf-portal/mkcert-ca mkcert \
-key-file /tmp/<host>-tls.key \
-cert-file /tmp/<host>-tls.pem \
apf-portal.<host>.local
# Sanity check.
sudo openssl x509 -in /tmp/<host>-tls.pem -noout -subject -issuer
# subject CN must be apf-portal.<host>.local; issuer the mkcert CA name.
# Ship to the target VM, renaming to the path the `https` Nx serve
# configuration expects (.secrets/dev-tls.{key,pem}).
sudo scp /tmp/<host>-tls.key <vm>:~/Works/apf_portal/.secrets/dev-tls.key
sudo scp /tmp/<host>-tls.pem <vm>:~/Works/apf_portal/.secrets/dev-tls.pem
# Wipe the staging copies.
sudo rm /tmp/<host>-tls.*
```
The certificate is good for ~2 years (mkcert default). When it nears expiry, regenerate with the same command and re-`scp` — the dev-server picks up the new files on next restart.
#### Onboarding a new developer
A new teammate needs **three things**: a copy of `rootCA.pem` (public, low-sensitivity), a per-VM cert minted by the R&D Lead, and the same hosts-file + `.env` configuration every dev follows.
**R&D Lead side** — on `vm-gitlab`:
```bash
# Hand off the public CA cert to the new dev via a secure channel
# (1Password shared vault, Bitwarden, direct scp). Never plain e-mail.
sudo cat /srv/apf-portal/mkcert-ca/rootCA.pem
```
Then mint that dev's per-VM cert (see "Minting a cert for a dev VM" above) and ship it to their VM's `~/Works/apf_portal/.secrets/`.
**New developer side** — on their Windows workstation:
```powershell
# 1. Install mkcert (only to get the `-install` command — no need to
# generate certs on the workstation).
choco install mkcert -y
# 2. Drop the rootCA.pem they received into the local CAROOT path.
$caroot = mkcert -CAROOT
Copy-Item "C:\path\to\rootCA.pem" "$caroot\rootCA.pem"
# NB: only rootCA.pem — they do NOT receive rootCA-key.pem.
# 3. Register the team CA in their Windows trust store.
mkcert -install
# Confirm the Windows security dialog. Their machine now trusts every
# cert minted by the team CA on vm-gitlab.
```
Then they:
- Edit `C:\Windows\System32\drivers\etc\hosts` (admin) and add the entries for every VM they want to reach (their own + the others as needed):
```
10.100.201.20 apf-portal.dev-vc.local
10.100.201.21 apf-portal.dev-jg.local
10.100.201.22 apf-portal.dev.local
```
- Edit `apps/portal-bff/.env` on their VM so the four `ENTRA_*_REDIRECT_URI` values point at `https://apf-portal.<their-host>:{4200,4300}/...` (the matching URIs are already registered Entra-side — no action there).
- Set `NX_SERVE_CONFIGURATION=https` in `infra/local/.env` on their VM.
- `./infra/local/dev.sh down && ./infra/local/dev.sh up apps`.
Total onboarding budget: ~5 min of R&D Lead time on `vm-gitlab` (mint + transfer) + ~10 min of work on the new dev's workstation + VM. No SSH access to `vm-gitlab` is granted to developers — only the R&D Lead operates the CA.
#### Operational notes
- **Departures.** mkcert has no CRL; revoking trust on a former dev's machine isn't actionable from the CA side. The risk surface is what that dev could have signed before leaving — and they only ever had the public `rootCA.pem`, never the private key, so they cannot have signed anything in your trust circle. No action required when a dev leaves.
- **CA rotation.** Rare (audit, suspected compromise, annual hygiene). Regenerate the CA on `vm-gitlab`, re-mint every VM's cert, redistribute the new `rootCA.pem` to each dev. Each dev re-imports + re-`mkcert -install`. No `.env` or Entra change.
- **Per-VM cert rotation.** Same pattern as initial mint — regenerate, scp, `dev.sh restart portal-shell portal-admin`. No client-side action.
- **Migration to a corp-signed CA.** When the infra team issues an internal-CA-signed cert (already trusted by every domain-joined workstation, no mkcert step), drop those files into `.secrets/dev-tls.{key,pem}` and remove the team mkcert CA from each dev's trust store. Entra registrations are unchanged — they reference hostname + port, not the issuer.
### Service endpoints (defaults) ### Service endpoints (defaults)
| Service | Host port | Purpose | | Service | Host port | Purpose |
-26
View File
@@ -35,29 +35,3 @@ OTEL_HTTP_PORT=4318
PGWEB_PORT=8081 PGWEB_PORT=8081
JAEGER_UI_PORT=16686 JAEGER_UI_PORT=16686
SERVE_STATIC_PORT=4200 SERVE_STATIC_PORT=4200
# ---------------------------------------------------------------- Apps (`--profile apps`)
# Two access modes for the SPA dev-servers — pick one. The switch
# happens entirely in this file (compose interpolates the SPA's nx
# serve --configuration AND the BFF's ENTRA_*_REDIRECT_URI from here);
# `apps/portal-bff/.env` stays at its localhost defaults regardless.
# See infra/README.md → "Switching between dev modes".
# === Mode A — Localhost / VSCode port-forwarding (DEFAULT) ===
# Leave the entire Mode B block below commented. The SPA dev-servers
# stay on plain HTTP, the BFF receives the `http://localhost:*`
# redirect URIs already registered in Entra. Browse `http://
# localhost:4200/` from the workstation — VSCode Remote-SSH auto-
# forwards 4200 / 4300 / 3000 from the VM.
# === Mode B — HTTPS via hostname (apf-portal.dev-XX.local) ===
# Required when the SPA is accessed via a hostname (Entra refuses
# `http:` for non-`localhost` redirect URIs — see the team mkcert CA
# setup in infra/README.md). Replace `dev-jg` with YOUR hostname and
# uncomment the five lines.
#
# NX_SERVE_CONFIGURATION=https
# ENTRA_REDIRECT_URI=https://apf-portal.dev-jg.local:4200/api/auth/callback
# ENTRA_POST_LOGOUT_REDIRECT_URI=https://apf-portal.dev-jg.local:4200/
# ENTRA_ADMIN_REDIRECT_URI=https://apf-portal.dev-jg.local:4300/api/admin/auth/callback
# ENTRA_ADMIN_POST_LOGOUT_REDIRECT_URI=https://apf-portal.dev-jg.local:4300/
-35
View File
@@ -1,35 +0,0 @@
# Dev-only image for the dockerised full-stack dev mode (ADR-0030).
#
# One image serves all three Nx apps (portal-bff / portal-shell /
# portal-admin) — the monorepo means a single install. The image is
# intentionally minimal: Node + corepack, nothing copied in. The repo
# is bind-mounted at runtime and dependencies install into a named
# volume (see dev.compose.yml `apps` profile), so node_modules — with
# its native modules built for THIS image — is never shadowed by the
# host's.
#
# NOT a production image. Production artefacts are out of scope per
# ADR-0030 and tracked against the ADR-0028 Container Registry work.
FROM node:24-bookworm
# corepack ships with Node 24. Enabling it lets pnpm resolve from the
# `packageManager` field in package.json at runtime — no version pinned
# here, so this image never drifts from the repo's pinned pnpm.
RUN corepack enable
# Nx + Angular CLI memory ceiling — matches the devcontainer (.devcontainer/
# devcontainer.json). 4 GB avoids OOM on large `nx` graph work.
ENV NODE_OPTIONS=--max-old-space-size=4096
# Nx daemon is per-container and would contend across the three app
# containers sharing one workspace bind-mount — disable it. Slight
# task-graph cost, robust behaviour.
ENV NX_DAEMON=false
WORKDIR /workspace
# No COPY / no install at build time: the repo is bind-mounted and the
# `apps-deps` one-shot service installs into the node_modules volume on
# first boot. Build context stays tiny (just infra/local/) — nothing is
# copied. Invoked via `bash` so it does not depend on the bind-mounted
# script keeping its executable bit.
ENTRYPOINT ["bash", "/workspace/infra/local/dev-entrypoint.sh"]
-26
View File
@@ -1,26 +0,0 @@
#!/usr/bin/env bash
# Shared entrypoint for the ADR-0030 `apps` Compose profile services.
#
# Behaviour is driven by env + the passed command:
# - The `apps-deps` one-shot service runs `pnpm install` as its
# command; this entrypoint just execs it (APF_ROLE unset → no
# prisma). It populates the shared node_modules volume once, so
# the app services don't race three concurrent installs.
# - The BFF service sets APF_ROLE=bff → this entrypoint runs
# `prisma generate` + `prisma migrate deploy` (client + committed
# migrations) before serving. `migrate deploy`, never `migrate
# dev` — a container never authors migrations.
# - The SPA services (portal-shell / portal-admin) leave APF_ROLE
# unset → straight to `exec "$@"` (nx serve).
set -euo pipefail
cd /workspace
if [[ "${APF_ROLE:-}" == "bff" ]]; then
echo "[dev-entrypoint] BFF: prisma generate"
pnpm exec prisma generate
echo "[dev-entrypoint] BFF: prisma migrate deploy"
pnpm exec prisma migrate deploy
fi
echo "[dev-entrypoint] exec: $*"
exec "$@"
-149
View File
@@ -34,23 +34,6 @@
name: apf-portal-dev name: apf-portal-dev
# Shared base for the ADR-0030 `apps` profile — dev servers for the three
# Nx apps. The repo is bind-mounted for hot reload; node_modules and the
# Nx cache live in named volumes so the container's install (native
# modules built for THIS image) is never shadowed by the host's.
x-app-base: &app-base
build:
context: .
dockerfile: Dockerfile.dev
profiles: [apps]
working_dir: /workspace
volumes:
- ../../:/workspace
- app-node-modules:/workspace/node_modules
- app-nx-cache:/workspace/.nx
networks:
- apf-portal-dev
services: services:
postgres: postgres:
image: postgres:17.2-alpine image: postgres:17.2-alpine
@@ -206,143 +189,11 @@ services:
networks: networks:
- apf-portal-dev - apf-portal-dev
# ------------------------------------------------------------------
# ADR-0030 dockerised full-stack dev mode (`--profile apps`).
#
# ./infra/local/dev.sh up apps → infra + the three dev servers,
# no native Node/pnpm on the host.
#
# Hot reload via the repo bind-mount. See docs/setup/ for the
# "which mode when" guidance (native / devcontainer / compose apps).
# NOTE: the SPA dev servers default to 4200/4300 — the same 4200 the
# `serve-static` profile uses; don't run `apps` and `serve-static`
# together, or override SHELL_PORT.
# ------------------------------------------------------------------
# One-shot: populate the shared node_modules volume once so the three
# app services don't race three concurrent installs on it. Exits when
# done; the apps gate on its successful completion.
apps-deps:
<<: *app-base
container_name: apf-portal-apps-deps
command: ['pnpm', 'install', '--frozen-lockfile']
portal-bff:
<<: *app-base
container_name: apf-portal-bff-dev
environment:
APF_ROLE: bff
NODE_ENV: development
PORT: '3000'
# Host-specific URLs rebuilt from infra/local/.env creds → Compose
# service names. Compose `environment` wins over `env_file`, so
# these override the localhost values in the BFF's own .env.
DATABASE_URL: 'postgresql://${POSTGRES_USER:-portal}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-portal_dev}?schema=public'
REDIS_URL: 'redis://default:${REDIS_PASSWORD}@redis:6379/0'
OTEL_EXPORTER_OTLP_ENDPOINT: 'http://otel-collector:4318/v1/traces'
# OIDC redirect URIs. Driven by infra/local/.env so switching
# between the two access modes — `localhost` (default; VSCode
# Remote-SSH port-forwarding) and `https` hostname (the
# ADR-0030 mkcert path) — is a single-file change. Unset →
# localhost defaults; set in infra/local/.env to override with
# an `https://apf-portal.dev-XX.local:…` hostname. See the
# "Switching between dev modes" subsection of infra/README.md.
# Compose `environment` overrides `env_file`, so the BFF's
# own .env stays at localhost (so native `nx serve` works
# untouched) and only `infra/local/.env` carries the
# docker-apps-mode override.
ENTRA_REDIRECT_URI: ${ENTRA_REDIRECT_URI:-http://localhost:3000/api/auth/callback}
ENTRA_POST_LOGOUT_REDIRECT_URI: ${ENTRA_POST_LOGOUT_REDIRECT_URI:-http://localhost:4200/}
ENTRA_ADMIN_REDIRECT_URI: ${ENTRA_ADMIN_REDIRECT_URI:-http://localhost:3000/api/admin/auth/callback}
ENTRA_ADMIN_POST_LOGOUT_REDIRECT_URI: ${ENTRA_ADMIN_POST_LOGOUT_REDIRECT_URI:-http://localhost:4300/}
# Secrets (Entra / session / jwks) come from the BFF's own dev env.
# `required: false` so SPA-only devs can `up` without it — the BFF
# then fails its own boot-time config validators with a clear message
# rather than Compose erroring on a missing file.
env_file:
- path: ../../apps/portal-bff/.env
required: false
command: ['pnpm', 'exec', 'nx', 'serve', 'portal-bff']
ports:
- '${BFF_PORT:-3000}:3000'
depends_on:
apps-deps:
condition: service_completed_successfully
postgres:
condition: service_healthy
redis:
condition: service_healthy
portal-shell:
<<: *app-base
container_name: apf-portal-shell-dev
environment:
# Read by apps/portal-shell/proxy.conf.js — points the dev-server
# /api proxy at the BFF container by name (Compose DNS). Native
# `nx serve` leaves BFF_TARGET unset and falls back to localhost.
BFF_TARGET: http://portal-bff:3000
# `--configuration=${NX_SERVE_CONFIGURATION:-development}` is
# interpolated by Compose at YAML parse time from
# `infra/local/.env`. Set `NX_SERVE_CONFIGURATION=https` there to
# serve over TLS — required when accessing via a hostname (Entra
# rejects `http:` for non-`localhost` redirect URIs). See the
# `https` configuration in apps/portal-shell/project.json + the
# "HTTPS dev-server setup" section in infra/README.md for the
# mkcert procedure.
command:
[
'pnpm',
'exec',
'nx',
'serve',
'portal-shell',
'--host',
'0.0.0.0',
'--port',
'4200',
'--configuration=${NX_SERVE_CONFIGURATION:-development}',
]
ports:
- '${SHELL_PORT:-4200}:4200'
depends_on:
apps-deps:
condition: service_completed_successfully
portal-admin:
<<: *app-base
container_name: apf-portal-admin-dev
environment:
# See portal-shell — same proxy target for the admin SPA.
BFF_TARGET: http://portal-bff:3000
# See portal-shell for the NX_SERVE_CONFIGURATION rationale.
command:
[
'pnpm',
'exec',
'nx',
'serve',
'portal-admin',
'--host',
'0.0.0.0',
'--port',
'4300',
'--configuration=${NX_SERVE_CONFIGURATION:-development}',
]
ports:
- '${ADMIN_PORT:-4300}:4300'
depends_on:
apps-deps:
condition: service_completed_successfully
volumes: volumes:
postgres-data: postgres-data:
name: apf-portal-postgres-data name: apf-portal-postgres-data
redis-data: redis-data:
name: apf-portal-redis-data name: apf-portal-redis-data
app-node-modules:
name: apf-portal-app-node-modules
app-nx-cache:
name: apf-portal-app-nx-cache
networks: networks:
apf-portal-dev: apf-portal-dev:
+5 -27
View File
@@ -14,22 +14,9 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
COMPOSE_FILE="${SCRIPT_DIR}/dev.compose.yml" COMPOSE_FILE="${SCRIPT_DIR}/dev.compose.yml"
# Every profile defined in dev.compose.yml, used as the teardown / # Profiles defined in dev.compose.yml. Keep in sync if a new profile
# status / logs scope so a profile started under a custom flag is # is added.
# always reachable later. Keep in sync if a new profile is added. ALL_PROFILES=(dbtools observability serve-static)
ALL_PROFILES=(dbtools observability serve-static apps)
# What `up all` expands to — everything you want running for a full
# dev session. `serve-static` is deliberately excluded:
# - it would collide with `apps` on host port 4200 (both publish the
# SPA there by default — Caddy serves the production build, the
# `apps` profile runs the Angular dev-server);
# - without a prior `nx build --configuration=production`, Caddy
# just 404s every request, so it adds nothing to a comprehensive
# `up all` invocation. Users who actually need it run
# `./infra/local/dev.sh up serve-static` (and `down` still tears
# it down because it's in ALL_PROFILES above).
UP_ALL_PROFILES=(dbtools observability apps)
# Build "--profile p1 --profile p2 …" as separate arguments. # Build "--profile p1 --profile p2 …" as separate arguments.
build_all_profile_flags() { build_all_profile_flags() {
@@ -69,18 +56,10 @@ Commands:
up [target...] Bring up the stack. up [target...] Bring up the stack.
Targets: Targets:
(none) core only (postgres + redis + otel-collector) (none) core only (postgres + redis + otel-collector)
all core + dbtools + observability + apps — all core + all profiles
the full dev stack. serve-static is
EXCLUDED because it collides with apps
on port 4200; run it explicitly when
you actually want to serve a prod build.
dbtools core + pgweb dbtools core + pgweb
observability core + jaeger observability core + jaeger
serve-static core + caddy (production-build reverse proxy) serve-static core + caddy (production-build reverse proxy)
apps core + the three Nx dev servers in
Docker — no native Node/pnpm needed
(ADR-0030). portal-bff:3000,
portal-shell:4200, portal-admin:4300.
Multiple targets allowed (e.g. `up dbtools observability`). Multiple targets allowed (e.g. `up dbtools observability`).
down [-v] Tear the stack down. Always runs with every down [-v] Tear the stack down. Always runs with every
@@ -108,7 +87,6 @@ Commands:
Examples: Examples:
./infra/local/dev.sh up ./infra/local/dev.sh up
./infra/local/dev.sh up all ./infra/local/dev.sh up all
./infra/local/dev.sh up apps
./infra/local/dev.sh up observability ./infra/local/dev.sh up observability
./infra/local/dev.sh down -v ./infra/local/dev.sh down -v
./infra/local/dev.sh stop pgweb ./infra/local/dev.sh stop pgweb
@@ -136,7 +114,7 @@ case "$cmd" in
if [[ $# -eq 0 ]]; then if [[ $# -eq 0 ]]; then
dc_core up -d dc_core up -d
elif [[ "$1" == "all" ]]; then elif [[ "$1" == "all" ]]; then
up_with_profiles "${UP_ALL_PROFILES[@]}" dc_all up -d
else else
up_with_profiles "$@" up_with_profiles "$@"
fi fi
+12 -13
View File
@@ -2,7 +2,7 @@
"name": "apf-portal", "name": "apf-portal",
"version": "0.0.0", "version": "0.0.0",
"license": "MIT", "license": "MIT",
"packageManager": "pnpm@10.34.1", "packageManager": "pnpm@10.33.4",
"scripts": { "scripts": {
"prepare": "husky", "prepare": "husky",
"ci:check": "pnpm exec nx affected -t format:check lint test build", "ci:check": "pnpm exec nx affected -t format:check lint test build",
@@ -45,7 +45,6 @@
"axios@<1.15.2": ">=1.15.2", "axios@<1.15.2": ">=1.15.2",
"@angular-devkit/core>ajv@<8.18.0": ">=8.18.0", "@angular-devkit/core>ajv@<8.18.0": ">=8.18.0",
"brace-expansion@<5.0.6": ">=5.0.6", "brace-expansion@<5.0.6": ">=5.0.6",
"dompurify@<3.4.5": ">=3.4.5",
"esbuild@<0.25.0": ">=0.25.0", "esbuild@<0.25.0": ">=0.25.0",
"follow-redirects@<1.16.0": ">=1.16.0", "follow-redirects@<1.16.0": ">=1.16.0",
"ip-address@<10.1.1": ">=10.1.1", "ip-address@<10.1.1": ">=10.1.1",
@@ -79,19 +78,19 @@
"@nestjs/schematics": "^11.0.0", "@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.0", "@nestjs/testing": "^11.0.0",
"@nx/angular": "^22.7.1", "@nx/angular": "^22.7.1",
"@nx/devkit": "22.7.5", "@nx/devkit": "22.7.2",
"@nx/eslint": "^22.7.1", "@nx/eslint": "^22.7.1",
"@nx/eslint-plugin": "22.7.5", "@nx/eslint-plugin": "22.7.2",
"@nx/jest": "22.7.5", "@nx/jest": "22.7.2",
"@nx/js": "22.7.5", "@nx/js": "22.7.2",
"@nx/nest": "^22.7.1", "@nx/nest": "^22.7.1",
"@nx/node": "22.7.5", "@nx/node": "22.7.2",
"@nx/playwright": "22.7.5", "@nx/playwright": "22.7.2",
"@nx/vite": "^22.7.1", "@nx/vite": "^22.7.1",
"@nx/vitest": "22.7.5", "@nx/vitest": "22.7.2",
"@nx/web": "22.7.5", "@nx/web": "22.7.2",
"@nx/webpack": "22.7.5", "@nx/webpack": "22.7.2",
"@oxc-project/runtime": "^0.133.0", "@oxc-project/runtime": "^0.131.0",
"@playwright/test": "^1.36.0", "@playwright/test": "^1.36.0",
"@schematics/angular": "~21.2.0", "@schematics/angular": "~21.2.0",
"@swc-node/register": "1.11.1", "@swc-node/register": "1.11.1",
@@ -125,7 +124,7 @@
"jsonc-eslint-parser": "^2.1.0", "jsonc-eslint-parser": "^2.1.0",
"lint-staged": "^17.0.0", "lint-staged": "^17.0.0",
"mermaid": "^11.15.0", "mermaid": "^11.15.0",
"nx": "22.7.5", "nx": "22.7.2",
"pino-pretty": "^13.1.3", "pino-pretty": "^13.1.3",
"postcss": "^8.5.12", "postcss": "^8.5.12",
"prettier": "^3.8.1", "prettier": "^3.8.1",
+1406 -2608
View File
File diff suppressed because it is too large Load Diff