Why this matters
Good application code still fails a business if you cannot prove it works on a clean machine, start it without silent misconfiguration, restore it after a disk loss, or stop a runaway bug in minutes. On 2 December 2026, an independent review re-ran this repository from a clean Linux clone and proved two facts: starting the API with NODE_ENV=production and no database URL still opened its port and answered "dataSource":"sample_memory" on /health, while database migrations were applied by nothing outside tests. Shipping silent fallbacks like that puts empty protections in front of real customers. Today the verification gate, fail-fast startup checks, migration CLI, local backup drills and offline smoke checks are built and verified locally. Nothing is deployed yet, no real Meta or Google call has been made, and there are no live customers.
In plain words
The ideas
One manifest, two runners, zero silent skips
In How we build, you met bash tools/verify from the user's seat. Underneath, operations rests on one rule: your computer and continuous integration must run the exact same checks in the exact same order, and a skipped check must never pass quietly.
When a team maintains one list in a local shell script and another hand-typed list in .github/workflows/verify.yml, the two drift apart quickly. If a test runner also skips database tests when PostgreSQL is missing, a broken migration reports green. This repository avoids both traps by storing every step once in a gate manifest, organising steps into eight gate groups, declaring external prerequisites as gate needs, and checking strict two-way agreement with a parity gate.
| Gate group | Steps | What it verifies | Typical needs |
|---|---|---|---|
core | 4 | Typecheck, workspace tests, closed UI tokens, schema DDL | pg18 |
static | 42 | File audits (--self-test plus live), gate parity, learning check | none |
suites | 5 | Contract parity, chaos and races, release journeys, fuzz suites | pg18 (2 of 5) |
postgres | 5 | Live PostgreSQL 18 security matrix, DB/vault suites, collector E2E, pg_dump drills | pg18, pg_dump |
deploy | 6 | Caddy headers, Docker hardening, VPS dry run, offline smoke, restore dry run, dev-stack check | bash, pg18 |
scanners | 3 | Working-tree and git-history secret scans (gitleaks), lockfile CVE scan (osv-scanner) | gitleaks, osv-scanner, network |
build | 1 | Production Next.js web build | none |
browser | 4 | Real Chromium sign-in, connect, event-and-approval and full-stack journeys | pg18, chromium |
Every step in the verification gate finishes as passed, failed, or not run (<reason>). Missing osv-scanner or passing --offline marks that step not run, never passed; passing --require-pg turns missing PostgreSQL 18 into a hard failure. A static gate reads files directly without starting a server or database and ships its own --self-test that injects faults to prove it fails closed.
On GitHub, a fresh Linux CI runner (ubuntu-latest) installs Node 24, pnpm 12, PostgreSQL 18 from PGDG, gitleaks, osv-scanner and Chromium, then executes all 70 steps in manifest order. Under OD-17, the CI trigger fires on every push to main, every pull request into main and manual workflow_dispatch. The common mistake is trusting a headline pass count without reading the not run column, commit SHA and tool versions.
Security gates and the human go/no-go decision
Automated tests prove code invariants, not legal or partner readiness. Operations separates technical verification from human launch approval into two layers.
First, six mandatory security gates (G1 to G6) test the core threat model: cross-tenant FORCE ROW LEVEL SECURITY isolation, encrypted vault denial, expiring SHA-256 preview approvals, hash-on-ingest personal data and consent gating, SSRF-isolated crawling plus zero-tool AI red-teaming, and raw-body HMAC verification plus immutable tax and audit ledgers, paired with gitleaks and osv-scanner. One honest detail to know when reading older docs: docs/THREAT-MODEL.md and AGENTS.md rule 21 order G3 through G6 slightly differently because rule 21 kept an older research list, though both enforce the exact same automated suites. Always read the topic name beside the gate number.
Second, AGENTS.md rule 22 requires an explicit human go/no-go decision. A green CI run never opens live users, real ad accounts or live money automatically. Under OD-05, launch splits into two founder-signed stages:
- Stage 1 (single-player SaaS): requires a locked brand name and domain (
OD-01), written KVKK counsel sign-off (issue 3,C1–C3), clean Turkey-resident PostgreSQL hosting (OD-04), a passing restore drill, fullbash tools/verifyreceipts, external auth review (OD-14, issue 97) and written founder sign-off. - Stage 2 (marketplace safeguarded payments): keeps live checkout in sandbox until fintech counsel and a sworn financial adviser (YMM) sign off on Law 6493, 3/10 VAT withholding (
KDV tevkifatı), 1 percent e-commerce withholding (e-ticaret stopajı) and e-invoicing (issue 3,C4–C10), sandbox rehearsals pass with zero kuruş drift, and both owners approve.
The usual mistake is mistaking green software tests for legal clearance. Software cannot sign a tax opinion or approve a Meta or Shopify app review.
Four environments and clean cutover
An environment is an isolated copy of the system with its own database, secrets and data rules. Only the first two exist live today:
| Environment | Status today | Purpose | Data allowed |
|---|---|---|---|
| Local workstation | Active | Daily development and local tests | Synthetic Sample data only |
Hosted CI (ubuntu-latest) | Active | Clean-machine verification on push and PR | Ephemeral fixtures only |
| Staging | Designed (not provisioned) | Rehearsing containers, migrations, sign-in and backups | Synthetic Sample data only (OD-04) |
| Production | Not built or provisioned | Live shops, live ad accounts and live payments | Real customer data after OD-04, OD-05 and owner sign-off |
Under OD-04, staging can run on a low-cost EU server strictly because it holds zero live Turkish personal data. In private staging, the proxy binds only to server loopback, the firewall opens only SSH (port 22), and owners open the app through an ssh -L tunnel on localhost, which browsers treat as a secure context for passkeys and __Host- cookies without needing a public domain.
Moving to production requires a clean cutover. Under OD-04, you never dump synthetic EU staging rows into production: you build a fresh Turkey-resident PostgreSQL 18 server and separate Turkey-resident backup bucket, run migrations and least-privilege role setup, pass restore-drill.sh --enforce-tr-local, and verify zero non-TR_LOCAL Turkish workspaces before admitting live businesses.
Configuration that fails fast
Think of fail-fast configuration like an aircraft pre-flight checklist that stops takeoff on a missing sensor instead of flying anyway. Software goes one step further: it can also inspect its own database schema automatically before opening a port.
Development allows convenient shortcuts such as sample memory and an ephemeral vault key. Production forbids every one of them. Under NODE_ENV=production, the loader refuses to start if DATABASE_URL is missing or uses a local dev password, if signing secrets are under 32 bytes, if VAULT_MASTER_KEK_BASE64 is missing, malformed or all-zero, if mail or WEB_ORIGIN settings are missing, or if the test-only fake provider switch is set. It also rejects invalid values like NODE_ENV=staging or NODE_ENV=prod.
On any error, the process logs one structured JSON line (api.config_error or dispatch.config_error) with stable codes only — never secret values — and exits 1 before creating a pool or listening. Once running, GET /health reports the data source label (postgres_rls or sample_memory). The usual mistake is generating a random key or falling back to sample memory quietly, which hides broken deployments until a restart destroys every stored token.
Packaging on one origin: Docker Compose, Caddy, migrations and roles
Under AGENTS.md rule 20, deployment stays intentionally simple: Docker Compose and Caddy on one Linux host, with zero Kubernetes or microservices until a measured bottleneck justifies them.
Internet / SSH tunnel
|
v
[ Caddy reverse proxy ] (TLS 1.2/1.3, security headers, scrubbed logs)
|
+--> Web app (Next.js standalone, :3000) ---- zero DB or vault creds
|
+--> Core API (Fastify, :4000) -------------- app_login + vault_login + KEK
|
v
[ internal_zone2 (no internet egress) ]
|
+--> PostgreSQL 18.7 (:5432, loopback only)
| ^-- pnpm db:migrate (migration role, before app boot)
| ^-- dispatch process (app_login + vault_login + KEK, no port)
| ^-- general worker (app_login only, zero vault creds)
|
[ egress_zone3 (isolated crawler network) ]
+--> seo-worker (2 GB RAM cap, zero DB or vault creds)Four rules anchor this layout:
- One origin for host-only cookies. Because
__Host-gd_sessioncarries the__Host-prefix (ADR-0010), browsers send it only to the exact host that issued it. Routing both web pages and/v1/*API paths through one reverse proxy origin lets authenticated browser calls carry the cookie cleanly. - Hardened containers. Application services run as a non-root container with
cap_drop: [ALL],no-new-privileges:true, a read-only root filesystem, a process cap (pids_limit: 256) and a smallnoexec/tmp. - Explicit migrations and split roles. Every new database runs in strict order:
docs/schema.sql, thendeploy/postgres/init-roles.sql, then pnpm db:migrate usingMIGRATION_DATABASE_URL(read only from the environment, never placed in web, API or worker env files). On boot in production, the API, worker and dispatch comparepublic.schema_migrationsagainst shipped files and refuse to start if the schema isbehind,unreadableorunreachable(API exits1; worker and dispatch exit78for behind/unreadable and13for unreachable). - Immediate verification. Right after deployment, a smoke test checks
/health, Caddy headers,404blocks on/metricsand/internal/*, and live PostgreSQL role restrictions.
The mistake people usually make is running web or worker processes as the database superuser, which lets a single query bug bypass every row-level security policy and read vault.*.
Backups, restore drills, RPO and RTO
Two metrics define recovery readiness:
- Recovery point objective (RPO): the oldest unbacked writes you accept losing. Nightly backups alone risk losing up to 24 hours; continuous WAL archiving with
archive_timeout=300targets RPO under 15 minutes (900 s). - Recovery time objective (RTO): total elapsed time to decrypt a backup, restore it cleanly, replay WAL and prove integrity. The target here is RTO under 30 minutes (
1,800 s).
An untested backup is a guess. A restore drill unpacks an encrypted backup into an isolated scratch folder on a non-production port (refusing 5432 and forcing archive_mode=off), times elapsed recovery against the RTO budget, and runs six automated SQL proofs: audit_log SHA-256 hash-chain continuity against vault.audit_chain_head, all base tables and 23 FORCE ROW LEVEL SECURITY tables, {product}_app vault denial, all 7 security triggers plus kuruş balance invariants, zero retained PII on erased contacts, and TR_LOCAL residency when --enforce-tr-local is passed.
One legal rule is easy to forget: KVKK erasure replay. Because encrypted backups stay immutable for 14 days, restoring yesterday's snapshot can resurrect a contact erased under KVKK Article 7 this morning. Before reopening traffic after any point-in-time restore, operators must replay the minimal PII-free erasure tombstone journal (workspace_id, contact_id, erased_at) so deleted people never resurface or fire ad conversions.
Observability, health checks, proxy rate limits and graceful shutdown
Four built-in mechanisms let you observe and control running services safely:
- PII-free structured logging and bounded metrics. Pino emits one JSON line per event with
[REDACTED]scrubbing across headers, cookies, tokens, emails, phones, IBANs, tax IDs and config secrets. Caddy strips secret headers and query keys, masks IPs to/24(IPv4) or/48(IPv6), and useslog_skipso OAuth callback URLs carrying one-time codes never reach access logs. For Prometheus metrics, a closed sanitiser allows only eight low-cardinality labels (service,route_group,status_class,data_source,provider,queue,mode,result) and rejects personal data or UUIDs. - Honest health checks.
GET /healthreturns HTTP200withstatus,service,dataSource,schemaandtimestamp, exposing database mode and migration state immediately. - Proxy-aware rate limits (trust proxy). Production enables fixed-window IP limits on
/v1/auth/*(60per60 s),/v1/audit/preview(30per60 s) and/v1/marketers/apply(10per3600 s), returning429 RATE_LIMITEDwithRetry-After. SettingTRUST_PROXY=loopback(or explicit proxy CIDRs) lets Fastify read the client IP from Caddy instead of collapsing every user into one127.0.0.1bucket; numeric hop counts are rejected so direct clients cannot forgeX-Forwarded-For. - Graceful shutdown. On
SIGTERM,SIGINTor a Windows test IPC shutdown message, the API stops accepting new traffic, drains active work up to a 10-second hard timeout, closes both database pools, callszeroizeBufferon the vault KEK, logsapi.shutdown_completeand exits0.
Load testing and chaos testing
A load test sends bursts and sustained waves of concurrent requests to measure p50, p95 and p99 latency, throughput (RPS) and error rate. Averages hide pain: 99 fast 10 ms replies and 1 stalled 5-second reply average 60 ms while one user waited five seconds. Local loopback benchmarks catch regressions early, yet never prove live wide-area-network SLAs.
A chaos test injects failures and simultaneous conflicting writes — such as racing KVKK erasure against event dispatch or replaying signed webhooks — to prove invariants survive under real concurrency.
Incidents: hard-stops, the kill switch, runbooks and blameless post-mortems
Six non-negotiable failures are SEV-0 hard-stops: cross-tenant leakage, credential or raw PII exposure, unconsented or post-erasure dispatch, unapproved spend mutation, fabricated KPIs or missing-as-zero defects, and kuruş tax drift or trial auto-charges. Either owner may freeze the affected surface immediately (halt under 15 minutes, full lock under 1 hour).
The primary brake is the global kill switch (workspaces.kill_switch_active = true). Enforced in both API code and PostgreSQL trigger trg_approval_requests_guardrails, it blocks budget raises, campaign launches and tracking edits while keeping META_PAUSE_ENTITY, GOOGLE_PAUSE_ENTITY and safeguarded-payment dispute holds open so owners can stop active spend right away.
During an incident, responders follow a written runbook: contain first, preserve audit_log rows and request IDs, revoke compromised marketer grants in one click, rotate exposed KEKs and begin the 72-hour KVKK Article 12 breach-assessment clock if personal data may be affected. Afterwards, you write a blameless post-mortem fixing the systemic gap and adding a negative-control test before reopening the frozen path.
How this repository does it
Every operational safeguard built on this branch maps to verified files:
| Capability | Files on this branch | What breaks if removed | Status |
|---|---|---|---|
| Verification manifest & runner | tools/verify, tools/run-gates.mjs, tools/gates.manifest.json | Local runs drift from CI; missing tools skip silently | Built, verified locally |
| CI workflow & parity gate | .github/workflows/verify.yml, tools/check-gate-parity.mjs | Missing CI steps, unlisted triggers or count ratchets slip in | Built, verified locally |
| Fail-fast runtime config | runtime-config.ts, server.ts, dispatch-main.ts | Production silently serves sample_memory, dev passwords or fake providers | Built, verified locally |
| Migration CLI & schema guard | cli.ts, schema-guard.ts, deploy/postgres/README.md | New code serves against an outdated schema missing triggers | Built, verified locally |
| Pool safety & clean shutdown | db-connection-errors.ts, server-lifecycle.ts, worker-main.ts | DB restarts crash processes; deploys drop work without wiping keys | Built, verified locally |
| Logs, health, rate limits & metrics | logger.ts, app.ts, hardening.ts, rate-limit.ts, metrics-sanitizer.ts | Secrets/PII leak into logs; proxied clients share one rate-limit bucket | Built, verified locally |
| Deploy, proxy & VPS blueprints | docker-compose.staging.yml, Caddyfile, env.staging.example, bootstrap-vps.sh, deploy/systemd | Root containers, exposed DB ports, logged OAuth codes or env-name drift | Built, verified locally (not deployed) |
| Restore drills & smoke test | backup-restore-drill.mjs, restore-drill.sh, staging-smoke.mjs | Corrupt backups, tampered dumps or broken RLS go undetected | Built, verified locally |
| Load, chaos & runbooks | load-bench.mjs, chaos-and-races.test.mjs, RUNBOOK.md, INCIDENT-RESPONSE-AND-KILL-SWITCH-PLAYBOOK.md, DISASTER-RECOVERY-AND-BCP-CHARTER.md, docs/runbooks | Races go untested; responders improvise during SEV-0 outages | Built / drafted |
Process privileges split cleanly across server.ts, dispatch-main.ts and worker-main.ts. Only the API and dispatch process hold VAULT_DATABASE_URL and VAULT_MASTER_KEK_BASE64. The general worker stays vault-less (APP_DATABASE_URL only), purges expired sign-in and OAuth flows hourly, logs worker.heartbeat every 15 seconds, and refuses built-in dry-run adapters in production unless opted into explicitly for synthetic staging. The unit templates under deploy/systemd ({product}-api.service, {product}-dispatch.service, {product}-web.service and {product}-worker.service) isolate each service under its own user and 0600 env file.
// apps/api/src/app.ts — exact /health payload verified by Docker and staging-smoke.mjs
app.get('/health', async () => ({
status: 'ok',
service: 'api',
dataSource,
schema: schemaHealth,
timestamp: now().toISOString(),
}));The manual benchmark tests/perf/load-bench.mjs starts an ephemeral local PostgreSQL 18 cluster and Fastify server to run 6,880 HTTP requests across 86 endpoints (30 x 86 burst plus 50 x 86 sustained at concurrency 25) and sits outside tools/gates.manifest.json so timing runs stay intentional.
Not built yet
Not built yet
What went wrong once
Production quietly served sample data and stub workers (findings P-1 and P-3)
During the 2 December 2026 review (INDEPENDENT-REVIEW-2026-12-02.md), starting NODE_ENV=production node src/server.ts without DATABASE_URL bound its port and answered "dataSource":"sample_memory" on /health, while the worker defaulted to stub adapters returning fake trace IDs. Leaving development fallbacks on the production path caused both defects. Wave 45 (C-REPORT.md) added fail-fast validation in runtime-config.ts and dry-run refusal in worker-main.ts, and Wave 48 (A-REPORT.md) moved real dispatch to dispatch-main.ts. Lesson: a server must refuse to start rather than boot silently wrong.
A PostgreSQL restart crashed the API and the worker (finding P-12)
Wave 45 API suites failed teardown with exit code 1 (57P01) after every test had passed. Reading the pg driver exposed a real production flaw: no error listener was attached to the pool, so a dead idle socket crashed Node.js. Fixing that revealed a second bug: once the worker lost its sockets, nothing kept its event loop alive and it exited 12 ms later. Wave 45 (G-REPORT.md) wired createDbConnectionErrorLogger (db-connection-errors.ts) into every pool, added a keep-alive timer, and pinned both with red-control tests. Lesson: flaky teardown noise often hides a real production outage.
Process signals on Windows broke graceful-shutdown tests
Running bash tools/verify on Windows in Wave 46 (E-REPORT.md) failed seven shutdown tests because child.kill('SIGTERM') hard-kills Windows processes without running cleanup handlers. Adding installIpcShutdownHandler in server-lifecycle.ts let test parents send { type: 'shutdown', signal } over an IPC channel while leaving Linux SIGTERM handlers untouched. Lesson: when owners develop on Windows and deploy on Linux, the gate must pass on both.
A backup round trip caught a CHECK constraint that came back different
In Wave 48 (A-REPORT.md), a new CHECK constraint using BETWEEN ... AND ... AND ... failed pg_dump_drills because PostgreSQL reformatted its parentheses on dump and restore. Rewriting it as a flat >= AND <= AND chain restored exact parity (5/5 drills passing). Lesson: automated restore drills catch subtle schema drift before real data depends on it.
Deploy templates and runtime disagreed on the vault master key's name
In Wave 48 (A-REPORT.md), runtime-config.ts read VAULT_MASTER_KEK_BASE64 while compose and bootstrap templates still set VAULT_KEK_V1. Wave 48 unified every template on VAULT_MASTER_KEK_BASE64 and added deploy-env-runtime-agreement.test.ts to validate every deploy template directly through the production loader. Lesson: test deploy files against the program's own loader so your first deploy is never the test.
Try it yourself
Every step below is read-only or in-memory. None touches your running local dev stack (ports 3000, 4000, 5432), edits repository files or calls external providers. Run from the repository root.
Step 1: print the full verification plan without running anything
Run in Git Bash:
bash tools/verify --listExpected output: all 70 ordered steps across eight groups with their needs, ending in exit code 0.
Step 2: run the gate-parity check and its fail-closed self-test
Run in Windows PowerShell or Git Bash:
node tools/check-gate-parity.mjs --self-test
node tools/check-gate-parity.mjsExpected output: negative-mutation self-tests pass and the live audit confirms tools/gates.manifest.json matches .github/workflows/verify.yml 1:1.
Step 3: dry-run the encrypted backup restore-drill script
Run in Git Bash:
bash deploy/backups/restore-drill.sh --dry-runExpected output: planned scratch folder, non-production port (55432), RPO (900s) and RTO (1800s) budgets, all six SQL checks, and STATUS: dry-run (not executed against a live backup).
Step 4: run the offline staging smoke check and Caddy header tests
Run in Windows PowerShell or Git Bash:
node deploy/staging-smoke.mjs --offline
node --test deploy/caddy/security-headers.test.mjsExpected output: both exit 0, confirming offline deploy blueprints, OpenAPI route parity, Caddy security headers, /metrics blocks and OAuth log_skip rules.
Step 5: test deploy templates against the fail-fast production loader
Run in Windows PowerShell or Git Bash:
pnpm --filter @{product}/api exec vitest run test/deploy-env-runtime-agreement.test.tsExpected output: every test passes, proving deploy/env.staging.example, deploy/docker-compose.staging.yml and deploy/scripts/bootstrap-vps.sh satisfy loadApiRuntimeConfig and loadDispatchRuntimeConfig while keeping vault keys out of the worker template.
Note
Check yourself
0 / 7Why does tools/gates.manifest.json declare explicit needs (such as pg18 or network) on steps?
What happens if you start a newly deployed API in NODE_ENV=production before running pnpm db:migrate?
Why must TRUST_PROXY be set to loopback (or explicit proxy CIDRs) behind Caddy rather than left unset or set to 1?
Why does apps/api/src/dispatch-main.ts run separately from apps/api/src/worker-main.ts?
After restoring a 12-hour-old PostgreSQL backup during a disaster, what mandatory privacy step must finish before reopening traffic?
When kill_switch_active = true is set, why are META_PAUSE_ENTITY and GOOGLE_PAUSE_ENTITY still permitted?
All 70 steps of bash tools/verify pass in GitHub Actions. May you open live Turkish safeguarded payments immediately?
Words to know
34Go deeper
In this repository
- Master operations runbook and
OD-04/OD-05checklists:docs/RUNBOOK.md - Verification gate contract and branch protection:
docs/VERIFICATION.md - Incident playbooks and
SEV-0hard-stops:docs/INCIDENT-RESPONSE-AND-KILL-SWITCH-PLAYBOOK.md - Disaster recovery and business continuity charter:
docs/DISASTER-RECOVERY-AND-BCP-CHARTER.md - Local benchmark honesty policy (TR):
docs/LOCAL-ENGINEERING-BENCHMARKS-AND-VERIFICATION-POLICY-TR.md - Release 1 owner go/no-go evidence pack:
docs/RELEASE-1-GO-NO-GO-EVIDENCE-PACK.md - Wave 49 private staging design brief:
docs/wave49/briefs/WS-A.md - Threat model (
T1–T8,G1–G6) and repository rules:docs/THREAT-MODEL.mdandAGENTS.md - PostgreSQL roles and migration workflow:
deploy/postgres/README.md
Archived lessons replaced by this lesson
Archived lesson 11: load testing, chaos and observabilityArchived lesson 17: hands-on lab workbook and drillsArchived lesson 18: incident postmortems and security audit playbookArchived lesson 29: operational SLA, webhook delivery health and rollout readiness- Archive index:
docs/lessons/archive/README.md
Official external documentation
- Docker Compose overview and profiles
- Docker Engine security and container hardening
- Caddy 2 documentation and log directive
- PostgreSQL 18 backup and continuous archiving (PITR)
- pgBackRest user guide
- Fastify
trustProxyreference - Pino structured logger documentation
- GitHub Actions workflow triggers and hosted runners
- Node.js
EventEmittererror events and process signals - systemd service unit manual