# crvouga/personal — CLOUD app infrastructure guide > **Scope: cloud-hosted application infrastructure only.** Use this guide for the OpenTofu-managed resources that apps use: Vault (OpenBao) secrets, PostgreSQL, the Cloudflare R2 object store, Railway hosting with prebuilt GHCR images, DNS/TLS on `*.chrisvouga.dev`, GitHub OIDC for CI, and Google sign-in through the auth relay. Values are generated from `packages/infra/tofu/modules/inventory/inventory.tf.json`, `.github/workflows/publish.yml`, `.github/workflows/deploy.yml` and the Vault secret registry; CI fails whenever this file drifts from them. **This guide never covers developer machines.** Toolchains (mise), workstation config, Docker engine setup, the Ubuntu developer fleet (homelab), T3, the private fleet AI proxy (CLIProxyAPI), Beszel, Turborepo caching and disposable test databases are **local development infrastructure** → https://www.chrisvouga.dev/llms-local.txt. If your task is about any of those, stop and use that guide instead. Do not mix the two. Canonical deployed URL: https://www.chrisvouga.dev/llms-cloud.txt · Index of both guides: https://www.chrisvouga.dev/llms-infra.txt · Source snapshot (current `main`): https://raw.githubusercontent.com/crvouga/personal/main/llms-cloud.txt ## Cloud vs local: the boundary | Question | Cloud (this guide) | Local (the other guide) | | --- | --- | --- | | Where does it run? | Railway (apps and Vault), Cloudflare (DNS, R2), managed PostgreSQL, GHCR, GitHub Actions | A developer's computer or a fleet node | | Who owns it? | OpenTofu in `crvouga/personal`, changed only by a reviewed PR from a GitHub issue | mise (`mise.toml`), `packages/workstation`, homelab | | How is it changed? | Never by you directly: open a GitHub issue | The documented local commands | Traps: - **`dev` does not mean local.** The Vault `dev` config, the `dev` R2 bucket, the `dev` `DATABASE_URL` and the nonproduction auth relay are **cloud** resources. They are the non-production cloud environment. A process on your laptop reaching them is still using cloud infrastructure, and everything in this guide applies. - **"Local" commands in this guide are clients of the cloud.** `personal infra-vault run`, `psql "$DATABASE_URL"` and `docker run` for an image smoke test run on your machine, but they only read cloud secrets or test a container bound for the cloud. They never set up or change your machine. - **A fleet machine is not a hosting target.** Never deploy an app to a developer machine or fleet node, and never configure a machine through OpenTofu. ## Communicating with `crvouga/personal`: GitHub issues **GitHub issues are the only channel between other projects and this one.** If your project wants `crvouga/personal` to manage infrastructure for it — hosting, a secret key, a database or schema, an object-store prefix, an auth-relay grant, a policy or access change, or a fix to something here — open an issue on `crvouga/personal`. Do not message the owner out of band, edit another repo's files, or work around the platform with a dashboard, an admin API or your own provisioning. The agent working in `crvouga/personal` reads the issue, makes the OpenTofu change in a PR that closes it, and reports back **in the same issue**. | Need | Issue title prefix | Guide | | --- | --- | --- | | Host a service and/or list it on the portfolio | `[hosting] — ` | §4 Step 1 (full body template) | | New Vault key or CI read access for a new namespace | `[secrets] — ` | §1 | | Database / schema allocation, extension, `dev`+`prd` scope | `[database] — ` | §2 | | Object-store bucket, prefix or credential change | `[storage] — ` | §3 | | Auth-relay agent grant or operator onboarding | `[auth] — ` | §5 | | Anything else, or a bug / stale statement in this guide | `[infra] — ` | below | Rules for every issue: 1. **Search first**: `gh issue list -R crvouga/personal --state all --search "[] in:title"`. Comment on or update the existing issue instead of opening a duplicate. 2. **One issue per request**, titled with the prefix above. State the requesting repo (`owner/name`), the app id, which of `dev` / `prd` you need, and the exact end state you expect. Write `none` / `n/a` rather than leaving a field out. For a request without its own template, include: Context, Request, Why, Acceptance (how you will verify it), and Links. 3. **Never put secret values in an issue** — it is public. List secret _names_ and where the human will write the values (Vault), and ask the human to rotate anything that leaks. 4. **Open it with `gh`**: `gh issue create -R crvouga/personal --label enhancement --title "[] — " --body-file /tmp/request.md` (use `--label bug` for something broken). If `gh` is unauthenticated or the human lacks access, hand the human the filled-in body and the command. 5. **Give the human the issue URL**, then keep going with unrelated work. The infra agent answers in issue comments (questions, the live URL, the Vault path to fill in, the PR number). Re-read the issue (`gh issue view -R crvouga/personal --comments`) before you continue the dependent work, and only treat the request as done when the issue is closed or the infra agent says so. 6. **Answer questions in the issue**, not elsewhere, so the history stays attached to the request. 7. **In the other direction**, when `crvouga/personal` needs something from your project (a failing publish workflow, a bad health path, a deprecated contract), it opens an issue on _your_ repo. Watch for those and answer them in the same issue. ## Ground rules - **Never invent, print, log, or commit secret values.** If an optional secret is missing or invalid, report its key and source, skip only its dependent integration or skill check, and continue unrelated work. Required credentials for an active deployment fail that deployment; never claim a skipped check passed. - **This guide never installs tools or configures a machine.** A missing CLI (`vault`, `docker`, `gh`, `psql`) is a local-development concern: report it and point to https://www.chrisvouga.dev/llms-local.txt. - **Shared infrastructure changes belong in `crvouga/personal` through OpenTofu** (deployments, secrets, policies, hosting, databases and buckets). **To get one, raise a GitHub issue on `crvouga/personal`** (see the section above) — never apply it yourself. A scoped auth-relay registration is an authorized runtime operation: agents may use §5 to manage their own application clients without an infrastructure deployment. Never use provider dashboards or administration APIs. - `@pkgs/*` packages in `crvouga/personal` are **private workspace packages** — they cannot be installed elsewhere. Use the plain HTTP / S3 / env-var contracts below. - Keep the app **twelve-factor**: configuration and secrets come from env vars at runtime, never from files baked into the image or the repo. ## Integration checklist 1. Needs secrets (API keys, database URLs)? → [1. Vault](#1-vault-secrets). Every other section depends on it. 2. Needs relational data? → [2. PostgreSQL](#2-postgresql). Use only the `DATABASE_URL` contract; the platform database credentials are not an app interface. 3. Stores files / blobs? → [3. Object store](#3-object-store-cloudflare-r2-s3-compatible). 4. Should be publicly hosted at `*.chrisvouga.dev` (and listed on the portfolio)? → [4. Hosting](#4-hosting-on-the-managed-services). The project must be Dockerized and publish prebuilt images; you request hosting by opening a `[hosting]` GitHub issue on `crvouga/personal` (§4 Step 1) that carries everything needed to deploy it and list it on the portfolio. 5. Needs Google sign-in? → [5. Auth relay](#5-auth-relay-google-sign-in). Use public OIDC settings; register with a scoped Vault credential, never Google or relay administrator credentials. 6. Needs logs, traces or metrics? → [6. Observability](#6-observability-logs-traces-metrics). Send standard OpenTelemetry to the shared stack; agents query it with a read-only token. ## Resources at a glance | Resource | Endpoint | Auth | | --- | --- | --- | | Vault (OpenBao) | `https://vault.chrisvouga.dev` | `vault login` locally; GitHub OIDC (role `github-actions`) in CI; read token at runtime | | PostgreSQL | via `DATABASE_URL` (opaque connection URL) | connection URL from Vault; an app-specific allocation is required | | Object store | Cloudflare R2 (S3 API) via `S3_ENDPOINT` | SigV4 with `S3_ACCESS_KEY_ID` / `S3_SECRET_ACCESS_KEY` | | Google sign-in | `https://auth.chrisvouga.dev/realms/projects` / `https://auth-dev.chrisvouga.dev/realms/projects-dev` | Public OIDC code + S256 PKCE; agent registration uses a scoped Vault credential (§6) | | Observability | Grafana Cloud via standard `OTEL_EXPORTER_OTLP_*` | Write-only OTLP header and read-only `GRAFANA_SERVICE_ACCOUNT_TOKEN` from Vault (§6) | | Hosting | Railway project `personal` at `*.chrisvouga.dev` | Prebuilt GHCR image published by the shared workflow (§5) | All consumer credentials live in Vault. Auth agent credentials use isolated `secret/auth-relay-agents//` documents, outside the shared personal document and shared CI read policy. Vault supplies application secrets; application users authenticate through the shared Google-to-OIDC relay, never through Vault. This is a consumer guide, not an inventory dump. State backends, provider credentials, the OpenBao storage database, administrative tunnels, and control-plane tokens are intentionally excluded from consumer instructions. They remain OpenTofu-owned and must never be reused by an application. All 14 domain registrations remain at Squarespace; registrar/DNS consolidation is cancelled. Existing Cloudflare DNS for `chrisvouga.dev`, `gamezilla.app`, `moviefinder.app` and `normalizer.app` is preserved. `bun domains inventory` and `bun domains discover` are read-only. Consumers must not transfer registrations or change shared nameservers. Cancellation evidence and the accepted disabled DNSSEC setting for unused `emulates.dev` are documented in [`packages/infra/docs/domain-migration.md`](https://github.com/crvouga/personal/blob/main/packages/infra/docs/domain-migration.md). --- ## 1. Vault (secrets) **Coordinates** | Thing | Value | | ------- | ---------------------------------------------------------------------------------------- | | Address | `https://vault.chrisvouga.dev` (OpenBao; Vault-compatible API + CLI) | | Engine | KV v2 mounted at `secret/` | | Path | `secret//` (HTTP API: `secret/data//`) | | Project | `personal` — shared by all personal apps; use it unless told otherwise | | Configs | `dev`, `prd` — `dev` = non-production cloud environment (local processes, CI tests, previews), `prd` = production (same key names in both) | Each KV field becomes one env var. Every config must carry the **same key names** (values may differ). CI read access covers only `secret/data/personal/+` and `secret/metadata/personal/+` and `auth/token/lookup-self` — a new project namespace needs a policy change in `crvouga/personal`, so add your app's keys under `personal`. To get a new key or access, open a `[secrets]` issue on `crvouga/personal` listing the key names, which configs need them and which app uses them (names only, never values). ### Keys that already exist Reuse these instead of creating duplicates. Adding a key means a human updates the OpenTofu vault root secrets input **and** adds its name to `vault.kv_keys` in the OpenTofu inventory. | Key | Configs | Used by | Required | | --- | --- | --- | --- | | `BESZEL_FLEET_AUTH` | prd | fleet-monitoring | yes | | `FLEET_CONTROLLER_ADMIN_TOKEN` | prd | fleet-api | yes | | `ZOOMIES_ENCRYPTION_KEY` | prd | zoomies | yes | | `ZOOMIES_BOOTSTRAP_TOKEN` | prd | zoomies, zoomies-setup | yes | | `ZOOMIES_BACKUP_PASSPHRASE` | prd | zoomies | yes | | `ZOOMIES_GITHUB_APP_ID` | prd | zoomies-setup | | | `ZOOMIES_GITHUB_APP_INSTALLATION_ID` | prd | zoomies-setup | | | `ZOOMIES_GITHUB_APP_PRIVATE_KEY` | prd | zoomies-setup | | | `ZOOMIES_GITHUB_APP_WEBHOOK_SECRET` | prd | zoomies-setup | | | `GOOGLE_OAUTH_CLIENT_ID` | dev, prd | auth-relay, auth-relay-dev | yes | | `GOOGLE_OAUTH_CLIENT_SECRET` | dev, prd | auth-relay, auth-relay-dev | yes | | `TURBO_CACHE` | dev, prd | ci | | | `TURBO_LOG_ORDER` | dev, prd | ci | | | `TURBO_TELEMETRY_DISABLED` | dev, prd | ci | | | `S3_ENDPOINT` | dev, prd | ci, 9router, fleet-api, zoomies, mockingbird-fleet | yes | | `S3_REGION` | dev, prd | ci, 9router, fleet-api, zoomies, mockingbird-fleet | yes | | `S3_ACCESS_KEY_ID` | dev, prd | ci, 9router, fleet-api, zoomies, mockingbird-fleet | yes | | `S3_SECRET_ACCESS_KEY` | dev, prd | ci, 9router, fleet-api, zoomies, mockingbird-fleet | yes | | `S3_BUCKET` | dev, prd | ci, 9router, fleet-api, zoomies, mockingbird-fleet | yes | | `S3_ACCESS_KEY` | dev, prd | ci | | | `S3_SECRET_KEY` | dev, prd | ci | | | `VAULT_TOKEN` | dev, prd | railway | yes | | `DATABASE_URL` | dev, prd | moviefinder, llm-proxy, ci, 9router, pickflix, mockingbird-fleet | | | `TMDB_API_READ_ACCESS_TOKEN` | dev, prd | moviefinder, pickflix | | | `TWILIO_ACCOUNT_SID` | dev, prd | moviefinder | | | `TWILIO_AUTH_TOKEN` | dev, prd | moviefinder | | | `TWILIO_SERVICE_SID` | dev, prd | moviefinder | | | `CLOUDFLARE_API_TOKEN` | dev, prd | ci, infra | | | `CLOUDFLARE_ACCOUNT_ID` | dev, prd | ci, infra | | | `RAILWAY_TOKEN` | dev, prd | ci, infra | | | `GRAFANA_CLOUD_ACCESS_POLICY_TOKEN` | prd | infra | | | `OTEL_EXPORTER_OTLP_ENDPOINT` | dev, prd | railway, ci, agents | | | `OTEL_EXPORTER_OTLP_HEADERS` | dev, prd | railway, ci, agents | | | `OTEL_RESOURCE_ATTRIBUTES` | dev, prd | railway, ci, agents | | | `GRAFANA_URL` | dev, prd | agents | | | `GRAFANA_SERVICE_ACCOUNT_TOKEN` | dev, prd | agents | | | `PORTFOLIO_GITHUB_TOKEN` | dev, prd | ci, portfolio | yes | | `DOCKER_USERNAME` | prd | github-actions | yes | | `DOCKER_PASSWORD` | prd | github-actions | yes | | `MOCKINGBIRD_JUNCTION_API_KEY` | prd | github-actions, mockingbird | yes | | `MOCKINGBIRD_STRIPE_SECRET_KEY` | prd | github-actions, mockingbird | yes | | `OPENAI_API_KEY` | dev, prd | ci, opencode | | | `9ROUTER_PASSWORD` | prd | 9router | yes | | `9ROUTER_JWT_SECRET` | prd | 9router | yes | | `9ROUTER_API_KEY_SECRET` | prd | 9router | yes | | `9ROUTER_MACHINE_ID_SALT` | prd | 9router | yes | | `9ROUTER_TUNNEL_TOKEN` | prd | | | | `INITIAL_PASSWORD` | prd | 9router | yes | | `JWT_SECRET` | prd | 9router | yes | | `API_KEY_SECRET` | prd | 9router | yes | | `MACHINE_ID_SALT` | prd | 9router | yes | | `YOUTUBE_API_KEY` | prd | pickflix | yes | | `PICKFLIX_SECRET` | prd | pickflix | yes | | `PICKFLIX_SESSION_SECRET` | prd | pickflix | yes | | `RESEND_API_KEY` | prd | pickflix | yes | | `AUTH_RELAY_SETUP_TOKEN_PRODUCTION` | prd | auth-relay | yes | | `AUTH_RELAY_SETUP_TOKEN_NONPRODUCTION` | dev | auth-relay-dev | yes | | `AUTH_RELAY_DATABASE_URL` | dev, prd | auth-relay, auth-relay-dev | | | `AUTH_CONSOLE_CLIENT_ID` | dev, prd | auth-relay, auth-relay-dev | | | `AUTH_CONSOLE_CLIENT_SECRET` | dev, prd | auth-relay, auth-relay-dev | | | `AUTH_MANAGER_CLIENT_ID` | dev, prd | auth-relay, auth-relay-dev | | | `AUTH_MANAGER_CLIENT_SECRET` | dev, prd | auth-relay, auth-relay-dev | | | `MOVIEFINDER_AUTH_SECRET` | dev, prd | moviefinder | yes | | `LANES_SESSION_SECRET` | dev, prd | lanes | yes | | `LANES_GITHUB_WEBHOOK_SECRET` | dev, prd | lanes | yes | | `LANES_TOKEN_ENCRYPTION_KEY` | dev, prd | lanes | yes | | `LANES_ZERO_API_KEY` | dev, prd | lanes, lanes-zero | yes | | `LANES_ZERO_ADMIN_PASSWORD` | dev, prd | lanes-zero | yes | | `LANES_GITHUB_CLIENT_ID` | dev, prd | lanes | | | `LANES_GITHUB_CLIENT_SECRET` | dev, prd | lanes | | | `LANES_GITHUB_PUBLIC_TOKEN` | dev, prd | lanes | | | `ZERO_UPSTREAM_DB` | dev, prd | lanes-zero | | | `MOCKINGBIRD_FLEET_OPERATOR_TOKEN` | prd | mockingbird-fleet | yes | | `CLIPROXY_FLEET_CLIENT_API_KEY` | prd | cliproxy-fleet, fleet-agents | yes | | `CLIPROXY_FLEET_MANAGEMENT_KEY` | prd | cliproxy-fleet | yes | | `CLIPROXY_FLEET_RESTIC_PASSWORD` | prd | cliproxy-fleet | yes | | `TAILSCALE_API_TOKEN` | prd | cliproxy-fleet | yes | ### From a developer machine — `personal infra-vault run` (reads cloud Vault) This reads the **cloud** Vault from a laptop; it does not create anything local. The `personal` CLI and the `vault`/`bao` and `jq` CLIs come from local machine setup (https://www.chrisvouga.dev/llms-local.txt). The human logs in once per machine: ```bash vault login --method=userpass username=crvouga ``` In your project, commit a `.vault.yaml` (coordinates only, no secrets — safe to commit). `personal infra-vault setup --project personal --config dev` writes it: ```yaml addr: https://vault.chrisvouga.dev mount: secret project: personal config: dev ``` Then wrap commands: ```bash personal infra-vault run -- bun run dev # injects every field as env vars personal infra-vault run --config prd -- # override config personal infra-vault run --dry-run -- # list injected var names only vault kv get secret/personal/dev # inspect (human only) bun run infra:vault plan # update the OpenTofu secrets input, then review/apply ``` Put `personal infra-vault run -- …` inside `package.json` scripts rather than asking developers to export variables. List the needed env var **names** (never values) in `.env.example`, and gitignore `.env*` except `.env.example`. ### CI (GitHub Actions) — OIDC, no stored token Repos under `crvouga/*` mint a short-lived Vault token via GitHub OIDC. Never add a `VAULT_TOKEN` repository secret for CI. ```yaml permissions: id-token: write contents: read steps: - uses: hashicorp/vault-action@v4 with: url: https://vault.chrisvouga.dev method: jwt path: jwt role: github-actions jwtGithubAudience: https://vault.chrisvouga.dev secrets: | secret/data/personal/prd DATABASE_URL | DATABASE_URL ; secret/data/personal/prd SOME_KEY | SOME_KEY ``` - JWT auth at `jwt/`, role `github-actions` → policy `ci-read`, TTL 15m. - Repository claims restrict access to `crvouga/*`. The existing role permits branch and pull-request jobs in these repositories. Never substitute a stored `VAULT_TOKEN` for OIDC. - Vault restarts **sealed** and auto-unseals on deploy. If calls return 503, poll `GET https://vault.chrisvouga.dev/v1/sys/health?standbyok=true` until 200 before failing — [`.github/actions/vault-secrets/action.yml`](https://github.com/crvouga/personal/blob/main/.github/actions/vault-secrets/action.yml) is a wait + retry pattern to copy. - A repo outside `crvouga/*` or a project outside `personal` needs [`packages/infra/tofu/vault/main.tf`](https://github.com/crvouga/personal/blob/main/packages/infra/tofu/vault/main.tf) / a policy change — tell the human. ### App runtime — read token + HTTP Processes that cannot be wrapped in `personal infra-vault run` (servers loading secrets at boot, Workers) use a long-lived read-only token supplied as the platform secret `VAULT_TOKEN` (policy `personal-read`, period 768h; the human mints it). Pass `VAULT_ADDR=https://vault.chrisvouga.dev`, `VAULT_PROJECT=personal`, `VAULT_CONFIG=prd` as plain env. ```ts const res = await fetch( `${VAULT_ADDR}/v1/secret/data/${VAULT_PROJECT}/${VAULT_CONFIG}`, { headers: { 'X-Vault-Token': VAULT_TOKEN } } ); if (!res.ok) throw new Error(`vault ${res.status}`); // 503 = sealed → retry with backoff const secrets = (await res.json()).data.data as Record; ``` Honor `Retry-After` on 429 and cache the result for the process lifetime. **Apps hosted on the services do not need this** — declare `secrets:` in `OpenTofu inventory` (§4) and they arrive as plain env vars. --- ## 2. PostgreSQL The application database contract is the secret env var `DATABASE_URL` in Vault `secret/personal/{dev,prd}`. Treat the entire connection string as opaque: pass it unchanged to a PostgreSQL driver, do not parse or reconstruct it, and never print it. The URL selects the environment; do not hardcode a hostname, database, role, password, TLS mode, or provider. ### Boundaries - `DATABASE_URL` is the only application-facing PostgreSQL credential. `DB_CONNECTION_URI`, `PLANETSCALE_SERVICE_TOKEN_ID`, `PLANETSCALE_SERVICE_TOKEN`, and the `secret_store` schema belong to the OpenBao control plane. Never read, request, inject, migrate, inspect, or reuse them from an application. - Do not create a database, branch, role, extension, replica, or provider project from another repo. Those are infrastructure resources and must be declared in `crvouga/personal` with OpenTofu. Application repositories own their allocated schemas and table migrations; the platform does not reconcile their application DDL. - A new app needs an explicitly allocated database/schema before it runs DDL or writes data. Include the requested app id, schema name, extensions, migration command, and whether both `dev` and `prd` are required in the hosting request (§4), or in a `[database]` issue on `crvouga/personal` if the app is already hosted. Record an allocated schema in the service inventory as `database_schema`; its application migrations may create and evolve only that schema. If no allocation is recorded in the approved infrastructure change, stop; possession of the shared credential is not authorization to use another app's tables. - Keep dev and production separate by loading the matching Vault config. Never copy production data into dev or point a local process at `prd` unless the human explicitly requests it. - Use parameterized queries. Put schema changes in deterministic, committed migrations and make the deploy strategy explicit. Never perform destructive or irreversible migrations automatically; use expand/migrate/contract changes and a reviewed backup/rollback plan. - Configure a small bounded connection pool, release clients in `finally`, set query/statement timeouts, retry only transient connection failures with bounded backoff, and make write retries idempotent. Do not retry constraint errors or arbitrary transactions. ### Connecting from a developer machine (cloud `dev` database) The `dev` `DATABASE_URL` points at the **cloud** non-production database, not a database on your machine. Load it through the same `.vault.yaml` contract as §1: ```bash personal infra-vault run -- sh -c 'psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -c "select 1"' personal infra-vault run -- bun run dev personal infra-vault run -- bun run db:migrate # only after the app's schema is allocated ``` The quoting in the `psql` example is intentional: the child shell expands `DATABASE_URL` after `personal infra-vault run` injects it. A command such as `personal infra-vault run -- psql "$DATABASE_URL"` expands too early and usually passes an empty value. Minimal Node/Bun shape (use the project's existing PostgreSQL library if it has one): ```ts import { Pool } from 'pg'; const connectionString = process.env.DATABASE_URL; if (!connectionString) throw new Error('DATABASE_URL is required'); export const db = new Pool({ connectionString, // preserve provider-required TLS/query parameters max: 5, connectionTimeoutMillis: 10_000, statement_timeout: 30_000, }); ``` Do not add an unconditional custom `ssl` object: many clients let it override TLS parameters already encoded in the managed URL. ### CI and hosted runtime - **CI:** request `DATABASE_URL` with the GitHub OIDC Vault step from §1. Expose it only to the migration/test step that needs it; do not write it to `$GITHUB_ENV`, artifacts, caches, summaries, or logs. - **Hosted runtime:** list `{ "name": "DATABASE_URL", "source": "vault" }` in the service's OpenTofu inventory `secrets`. The services copies the `prd` value into Railway. The app does not fetch Vault directly. - **Tests:** must not mutate the shared cloud `dev` database unless the human explicitly requests an integration test and the app has an isolated schema. Unit and repository tests use a disposable PostgreSQL container on the developer machine or CI runner; that is local infrastructure (https://www.chrisvouga.dev/llms-local.txt), never a cloud resource. - **Health checks:** do not make the public liveness path depend on a database query. Check database readiness separately at boot or through a diagnostic endpoint; transient database trouble must not create a restart loop. Verify without exposing connection details: ```bash personal infra-vault run -- sh -c 'psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -Atqc "select 1" | grep -qx 1' ``` --- ## 3. Object store (Cloudflare R2, S3-compatible) Shared buckets, one per Vault config; apps partition them by key prefix. | Vault config | Bucket | | --- | --- | | `dev` | `crvouga-development` | | `prd` | `crvouga-production` | **Env vars** (Vault `secret/personal/{dev,prd}`): | Var | Meaning | | --- | --- | | `S3_ENDPOINT` | Cloudflare R2 S3 API endpoint (https://.r2.cloudflarestorage.com) | | `S3_REGION` | R2 SigV4 region (always "auto") | | `S3_ACCESS_KEY_ID` | R2 API token Access Key ID (Object Read & Write on the shared bucket) | | `S3_SECRET_ACCESS_KEY` | R2 API token Secret Access Key (shown once at creation) | | `S3_BUCKET` | Shared R2 bucket (dev→crvouga-development, prd→crvouga-production) | **Rules** - **Prefix every key with your app id**: `/…` (e.g. `moviefinder/posters/123.webp`). Never write, list, or delete outside your prefix — other apps share the bucket. Make the prefix a single constant at the composition root. - The current credentials can reach a shared bucket; the prefix is an isolation contract, not an IAM boundary. Validate every caller-supplied key after normalization, reject `..`, leading `/`, empty segments and backslashes, and never accept a complete object key directly from an HTTP request. - Read the bucket from `S3_BUCKET`; never hardcode bucket names. dev vs prd is selected purely by the Vault config you run with. - Use path-style addressing: `${S3_ENDPOINT}/${S3_BUCKET}/${key}`. - Buckets are private. Serve objects through your app (or presigned URLs), never public bucket URLs. - Store the authoritative MIME type and size as object metadata; do not trust a download filename or user-provided `Content-Type`. Stream large bodies instead of buffering them, place explicit size limits on uploads, and use multipart upload only when the chosen SDK can abort failed uploads. - Treat `PUT` of the same key as replacement. Generate immutable/versioned keys when overwrites would break caches, and delete only keys that your app recorded as owned. R2 listing is paginated; follow continuation tokens until complete. - Do not create buckets or R2 tokens; provisioning lives in `crvouga/personal` (`bun run infra apply`). **Clients** ```ts // Workers / Bun / Node — tiny, fetch-based (what crvouga/personal uses) import { AwsClient } from 'aws4fetch'; const s3 = new AwsClient({ accessKeyId: env.S3_ACCESS_KEY_ID, secretAccessKey: env.S3_SECRET_ACCESS_KEY, region: env.S3_REGION, // "auto" service: 's3', }); const base = `${env.S3_ENDPOINT.replace(/\/$/, '')}/${env.S3_BUCKET}`; const key = `myapp/${id}`; const objectUrl = `${base}/${key.split('/').map(encodeURIComponent).join('/')}`; await s3.fetch(objectUrl, { method: 'PUT', body: bytes, headers: { 'content-type': type }, }); const res = await s3.fetch(objectUrl); // 404 → missing ``` ```ts // @aws-sdk/client-s3 new S3Client({ endpoint: process.env.S3_ENDPOINT, region: process.env.S3_REGION, forcePathStyle: true, credentials: { accessKeyId: process.env.S3_ACCESS_KEY_ID!, secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!, }, }); ``` Any other S3 SDK works with the same five values + path-style. AWS CLI: `aws s3 ls s3://$S3_BUCKET/myapp/ --endpoint-url $S3_ENDPOINT` (with `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` set from the `S3_*` vars). Recommended shape: hide the SDK behind a small interface — `get(key) → {body, contentType, size} | null`, `put(key, bytes, contentType)` (idempotent), `head(key) → boolean`, `delete(key)` (no-op if missing), `withPrefix(prefix)` — plus an in-memory implementation for tests. --- ## 4. Hosting on the managed services `crvouga/personal` hosts apps on Railway (project `personal`, region `us-west2`) behind `*.chrisvouga.dev` hostnames with TLS and DNS managed by OpenTofu. **Railway never builds your code.** Every hosted project is Dockerized, CI publishes a **prebuilt image** to GHCR, and the services deploys that exact image. ### Contract your project must meet - **Dockerized.** A `Dockerfile` (multi-stage; build tools in the build stage, minimal runtime stage) that builds with plain `docker build -f ` — no build args or secrets required. The build must run in CI for `linux/amd64`. - **Prebuilt image.** Built and pushed only by the shared publish workflow below, as `ghcr.io/crvouga/chrisvouga-:` and `:latest`. Never enable Railway's GitHub/Nixpacks builds, never run `railway up`, never push images by hand. Railway pulls the GHCR image selected by OpenTofu. All images must be public and allow anonymous pulls. The inventory rejects private registry credentials; `bun run health --only images` checks anonymous GHCR pulls. - **One port.** The container listens on `0.0.0.0:` and that port equals `port` in `OpenTofu inventory`. Read `PORT` from env (the services sets it via `env:`) with the same default in code. - **Health check.** `GET ` (default `/`) returns 2xx within seconds of boot, without auth and without depending on third-party services. Deploys that fail it are marked failed. - **Config from env only.** Runtime secrets are injected by the services from Vault as env vars (`secrets:` in `OpenTofu inventory`). Nothing secret in the image, repo, or Dockerfile; no `.env` files read in production. Fail fast at boot with a clear message naming any missing var. - **Stateless.** Containers can be replaced at any time: no local disk state (use Postgres via `DATABASE_URL` or the object store), logs to stdout/stderr, handle `SIGTERM` gracefully. - **Small and reproducible.** Pin base images (e.g. `node:22-bookworm-slim`, `oven/bun:1.3`, `nginx:alpine`), commit a lockfile and install with it frozen, and add a `.dockerignore` (`node_modules`, `.git`, `.env*`, build output). Minimal Dockerfiles to start from: ```dockerfile # Static site (Vite/Astro/etc.) served by nginx on port 80 FROM node:22-bookworm-slim AS build WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci COPY . . RUN npm run build FROM nginx:alpine COPY --from=build /app/dist /usr/share/nginx/html EXPOSE 80 ``` ```dockerfile # Bun HTTP server on $PORT (default 8080) FROM oven/bun:1.3 AS build WORKDIR /app COPY package.json bun.lock ./ RUN bun install --frozen-lockfile --production COPY . . FROM oven/bun:1.3-slim WORKDIR /app ENV NODE_ENV=production PORT=8080 COPY --from=build /app /app USER bun EXPOSE 8080 CMD ["bun", "run", "src/server.ts"] ``` Smoke-test the image on your machine before wiring CI (this tests the container bound for the cloud; it is not local hosting): `docker build -t app . && docker run --rm -p 8080:8080 -e PORT=8080 app`, then `curl -fsS localhost:8080`. ### Step 1 — open a hosting request issue (on `crvouga/personal`) You cannot add a service from another repo — the services only runs what `packages/infra/tofu/modules/inventory/inventory.tf.json` in `crvouga/personal` declares, and an agent working there adds it. Your job is to hand that agent **everything** it needs in one GitHub issue, so it never has to open your repo to guess: where the image lives, how to run it, which secrets it needs, and how the project should appear on the portfolio at `https://www.chrisvouga.dev`. 1. Meet the contract above and verify the image locally (`docker build` + `docker run` + `curl` the health path). Do not open the issue until that works. 2. Commit the publish workflow (Step 3) in the same change, so the image already exists on GHCR when the infra agent deploys it. Until the service entry lands, the deploy step in `crvouga/personal` fails with "service id not found" — that is expected. 3. Check for an existing request first: `gh issue list -R crvouga/personal --state all --search "[hosting] in:title"`. Update that issue instead of opening a duplicate. 4. Fill in **every** field of the body below (write `none` / `n/a` rather than deleting a field), save it to a scratch file outside the repo, and open the issue: ```bash gh issue create -R crvouga/personal --label enhancement \ --title "[hosting] — " \ --body-file /tmp/hosting-request.md ``` If `gh` is not authenticated or the human lacks access to `crvouga/personal`, give the human the filled-in body and the command instead. 5. Tell the human the issue URL. When the infra agent comments with the live URL, confirm `curl -fsS https://` succeeds. **Never put secret values in the issue** (it is public). List secret _names_ only; the human writes values into Vault. Issue body — copy it verbatim and replace every `<…>`: ```md ## Service | Field | Value | | -------------------- | --------------------------------------------------------------------------------------- | | Service id | `` — kebab-case, unique in `OpenTofu inventory`; becomes the Railway name and GHCR name | | Summary | | | Source repo | `/` (), default branch `
` | | Source code URL | | | Requested hostname | `.chrisvouga.dev` (or "any") | | Kind | | | Stack | | ## Authentication (if needed) - Shared Google/OIDC relay: ; production/nonproduction: <...> - Project / instance names: <...>; exact owned callback URLs/origins: <...> - Loopback development / preview lifecycle / expiry needs: <...> - Registration credential id(s), Vault config(s), repository and exact CI OIDC subject(s): - Ownership evidence: ## Image | Field | Value | | ------------------- | ------------------------------------------------------------------------------------------- | | Image source | ` / external image: ``> | | Image reference | `:latest>` | | Already published? | `, run / not yet> | | Dockerfile | `` | | Build context | `` | | Platform | `linux/amd64` builds in CI: | | Publish workflow | / not yet / n/a (external)> | | Image size | | ## Runtime | Field | Value | | --------------------- | ---------------------------------------------------------------------------- | | Port | `` (reads `PORT` from env: , default ``) | | Health path | `` → , no auth, no third-party calls | | Boot time | | | Start command | `` | | Plain env vars | <`NAME=value`, one per line — non-secret only — or none> | | Websockets / SSE | | | Background work | | | Persistent disk | none (required — containers are stateless; use Postgres or the object store) | | Memory / CPU needs | | | Graceful `SIGTERM` | | ## Secrets and shared infra Names only — never values. | Env var | Already in Vault `personal`? | Configs | Purpose / where the human gets the value | | -------- | --------------------------------- | ------------ | ---------------------------------------- | | `` | | | | - Postgres (`DATABASE_URL`): ; migrations run - Object store (R2): ; key prefix `/` - Vault access from CI (OIDC): ## Image smoke test (run on a developer machine) docker build -f -t docker run --rm -p : -e PORT= curl -fsS -o /dev/null -w '%{http_code}\n' localhost: ## Portfolio entry | Field | Value | | ----------- | ------------------------------------------------------------------------ | | List it? | (the portfolio shows only a few hand-picked projects) | | Name | | | Description | | | Live URL | <`https://` / none> | | Code URL | | ## Anything else ``` ### Step 2 — the service entry (added in `crvouga/personal` from your issue) Application repositories own publisher workflows and validation. Set `managed_publisher = false` and list `required_status_checks` in the repository inventory entry to retain that ownership while using the shared image build/deploy workflow. Set repository `publish_dispatch = true` when the publisher needs its OpenTofu-managed `DEPLOY_DISPATCH_TOKEN` before hosting is activated. This supports publishing and verifying an image before adding the live service; repository settings are adopted through the foundation root's import blocks. The infra agent turns your issue into an entry like this in `packages/infra/tofu/modules/inventory/inventory.tf.json` (when you are working inside `crvouga/personal` yourself, add it and run `bun run infra:services plan` to review the plan). Use it to check that your issue answers every field: ```json { "id": "my-app", "kind": "railway", "hostname": "my-app.chrisvouga.dev", "github_repo": "crvouga/my-app", "source_code_url": "https://github.com/crvouga/my-app", "dockerfile": "./Dockerfile", "build_context": ".", "port": 8080, "health_check": true, "health_path": "/health", "env": { "PORT": "8080" }, "secrets": [ { "name": "DATABASE_URL", "source": "vault" } ] } ``` | Field | Meaning | | ----------------- | ----------------------------------------------------------------------------------------------- | | `id` | Service id: Railway service name, GHCR package `chrisvouga-`, and publish `service_id` | | `state_key` | Optional Terraform resource generation key; defaults to `id`. Public service ids and image names do not change. | | `hostname` | Public hostname on `chrisvouga.dev`; DNS and TLS are provisioned automatically | | `github_repo` | `owner/name` of the repo that publishes the image | | `source_code_url` | Link shown on the portfolio | | `dockerfile` | Dockerfile path, relative to the repo root | | `build_context` | Docker build context, relative to the repo root | | `port` | Port the container listens on | | `health_check` | Probe the service after deploys | | `health_path` | Path probed (default `/`); must return 2xx | | `env` | Plain, non-secret env vars | | `secrets` | `name` + `source: vault` → value copied from Vault `personal/prd` into the service's env | | `image` | Optional external image, used verbatim (skips GHCR publishing entirely) | | `internal` | `true` for a service reached only on Railway's private network (`.railway.internal:`): no `hostname`, custom domain or DNS record | | `initial_image_tag` | Reviewed commit tag for a service's first activation; later dispatches select new revisions | A Vault secret binding may specify `vault_key` when the source key differs from the runtime `name`, for example `{ "name": "AWS_ACCESS_KEY_ID", "source": "vault", "vault_key": "S3_ACCESS_KEY_ID" }`. Do not create duplicate Vault values for aliases. A new deployment generation can use a distinct `state_key` when reusing a retired public service id, preserving the old retirement records. Do not rekey an existing live service without a reviewed state migration/import plan; that would propose replacement resources. For single-writer SQLite services, `railway.volume` declares a provider-managed `{ "name": "working", "mount_path": "/var/lib/app" }` volume. Railway prevents concurrent deployments mounting that volume; use exactly one replica. Set `railway.draining_seconds` for graceful shutdown and `railway.health_timeout_seconds` to cover restore plus initial sync. A Railway volume is mounted with root ownership; supply a compatible runtime UID or an application-owned privilege-dropping entrypoint. R2 replication and recovery checks remain necessary; HTTP readiness alone does not prove replica freshness. ### Step 3 — add the publish workflow (in your repo) Commit exactly this as `.github/workflows/publish.yml` (from `crvouga/personal`, `bun run infra apply` generates and pushes it for every service of that repo). If the repo's default branch is not `main`, change the trigger branch: ```yaml # Managed by OpenTofu github_repository_file. name: Publish image on: push: branches: - main permissions: contents: read packages: write # Queue publishes per branch instead of running them in parallel; never cancel # an in-flight publish so a deploy dispatch is not cut off halfway. concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: false jobs: my_app: uses: crvouga/personal/.github/workflows/publish.yml@main secrets: DEPLOY_DISPATCH_TOKEN: ${{ secrets.DEPLOY_DISPATCH_TOKEN }} CALLER_GITHUB_TOKEN: ${{ github.token }} with: service_id: my-app dockerfile: ./Dockerfile context: . image_owner: crvouga image_prefix: chrisvouga infra_github_repo: crvouga/personal ``` It calls `crvouga/personal`'s `ci.yml` as a reusable workflow. Inputs: | Input | Required | Default | Meaning | | --- | --- | --- | --- | | `service_id` | yes | | Service id matching OpenTofu inventory (e.g. portfolio, todo-app). | | `dockerfile` | | `./Dockerfile` | Path to Dockerfile relative to context. | | `context` | | `.` | Docker build context. | | `image_owner` | | `crvouga` | ghcr.io owner. | | `image_prefix` | | `chrisvouga` | GHCR package prefix (from OpenTofu inventory image_prefix). | | `infra_github_repo` | | `crvouga/personal` | Infra repo owner/name for deploy dispatch. | | `notify_deploy` | | `true` | POST repository_dispatch to infra after push. Set false when chaining deploy. | Caller secrets: `DEPLOY_DISPATCH_TOKEN` (the OpenTofu-managed platform PAT, used to publish existing GHCR packages and dispatch deployment; requires repository/workflow access and `write:packages`) and `CALLER_GITHUB_TOKEN` (pass `github.token`; publishing fallback when the platform token is absent). Update missing or rotated credentials through the OpenTofu foundation root. ### What happens on every push to `main` 1. Your repo's publish job builds the Dockerfile and pushes `ghcr.io/crvouga/chrisvouga-:` + `:latest`. 2. It sends `repository_dispatch` `deploy-service` with `{"id": "", "image_tag": ""}` to `crvouga/personal`. 3. `crvouga/personal` CI applies OpenTofu DNS / Railway resources from `OpenTofu inventory`, syncs the declared Vault secrets into the service, deploys the image at that SHA, and health-checks `https://`. Check it: `gh run list -R crvouga/personal --workflow ci.yml --limit 3`, then `curl -fsS https://`. Never redeploy from the Railway dashboard; a human can redeploy with `gh workflow run deploy.yml -R crvouga/personal -f action=deploy -f service_id= -f image_tag=`. ### Current services Working examples to copy from — each links to its source repo: | Service id | Public URL | Repo | Dockerfile (context) | Port | Health | | --- | --- | --- | --- | --- | --- | | `portfolio` | https://www.chrisvouga.dev | [crvouga/personal](https://github.com/crvouga/personal/tree/main/packages/portfolio) | `packages/portfolio/Dockerfile` (`.`) | 80 | `/` | | `moviefinder-app-rust` | https://moviefinder-app-rust.chrisvouga.dev | [crvouga/moviefinder.app-rust](https://github.com/crvouga/moviefinder.app-rust) | `./Dockerfile` (`.`) | 3000 | `/` | | `moviefinder-app-react` | https://moviefinder-app-react.chrisvouga.dev | [crvouga/moviefinder.app-react](https://github.com/crvouga/moviefinder.app-react) | `./Dockerfile` (`.`) | 3000 | `/` | | `moviefinder-app-clojurescript` | https://moviefinder-app-clojurescript.chrisvouga.dev | [crvouga/moviefinder.app-clojurescript](https://github.com/crvouga/moviefinder.app-clojurescript) | `./Dockerfile` (`.`) | 9630 | `/` | | `headless-combobox-svelte-example` | https://svelte-headlesscombobox.chrisvouga.dev | [crvouga/headless-combobox](https://github.com/crvouga/headless-combobox) | `example/svelte/Dockerfile` (`example/svelte`) | 80 | `/` | | `headless-combobox-docs` | https://headlesscombobox.chrisvouga.dev | [crvouga/headless-combobox](https://github.com/crvouga/headless-combobox) | `./Dockerfile` (`.`) | 80 | `/` | | `todo-app` | https://todo.chrisvouga.dev | [crvouga/todo-v1](https://github.com/crvouga/todo-v1) | `./Dockerfile` (`.`) | 8080 | `/` | | `image-service` | https://imageservice.chrisvouga.dev | [crvouga/image-service](https://github.com/crvouga/image-service) | `./Dockerfile` (`.`) | 80 | `/login/send_link` | | `connect-four` | https://connectfour.chrisvouga.dev | [crvouga/connect-four](https://github.com/crvouga/connect-four) | `./Dockerfile` (`.`) | 8080 | `/` | | `anime-blog` | https://anime.chrisvouga.dev | [crvouga/anime](https://github.com/crvouga/anime) | `./Dockerfile` (`.`) | 80 | `/` | | `snake-game` | https://snake.chrisvouga.dev | [crvouga/snake](https://github.com/crvouga/snake) | `./Dockerfile` (`.`) | 80 | `/` | | `match-three` | https://matchthree.chrisvouga.dev | [crvouga/match-three](https://github.com/crvouga/match-three) | `./Dockerfile` (`.`) | 80 | `/` | | `simon-says` | https://simonsays.chrisvouga.dev | [crvouga/simon-says](https://github.com/crvouga/simon-says) | `./Dockerfile` (`.`) | 80 | `/` | | `violets-garden` | https://violetsgarden.chrisvouga.dev | [crvouga/violets-garden](https://github.com/crvouga/violets-garden) | `./Dockerfile` (`.`) | 80 | `/` | | `mockingbird-docs` | https://mockingbird.chrisvouga.dev | [crvouga/mockingbird](https://github.com/crvouga/mockingbird/tree/main/sites/docs) | `sites/docs/Dockerfile` (`.`) | 80 | `/` | | `mockingbird-fleet` | https://mockingbird-fleet.chrisvouga.dev | [crvouga/mockingbird](https://github.com/crvouga/mockingbird/tree/main/sites/fleet) | `sites/fleet/Dockerfile` (`.`) | 8080 | `/health` | | `gitty-storybook` | https://gitty-storybook.chrisvouga.dev | [crvouga/gitty](https://github.com/crvouga/gitty) | `Dockerfile.storybook` (`.`) | 80 | `/` | | `lanes` | https://lanes.chrisvouga.dev | [crvouga/gitty](https://github.com/crvouga/gitty) | `./Dockerfile` (`.`) | 8787 | `/health` | | `llm-proxy` | https://llm-proxy.chrisvouga.dev | [crvouga/llm-server](https://github.com/crvouga/llm-server) | `proxy/Dockerfile` (`proxy`) | 8080 | `/ui` | | `9router` | https://9router.chrisvouga.dev | [crvouga/personal](https://github.com/crvouga/personal/tree/main/packages/9router) | `packages/9router/Dockerfile` (`packages/9router`) | 20128 | `/api/health` | | `pickflix` | https://pickflix.chrisvouga.dev | [crvouga/pickflix-v1](https://github.com/crvouga/pickflix-v1) | `./Dockerfile` (`.`) | 9000 | `/health` | | `moviefinder` | https://moviefinder.chrisvouga.dev | [crvouga/moviefinder](https://github.com/crvouga/moviefinder) | `./Dockerfile` (`.`) | 8080 | `/health` | | `fleet-api` | https://fleet.chrisvouga.dev | [crvouga/fleet](https://github.com/crvouga/fleet) | `./Dockerfile` (`.`) | 8080 | `/health` | | `zoomies` | https://zoomies.chrisvouga.dev | [crvouga/personal](https://github.com/crvouga/personal/tree/main/packages/zoomies) | `packages/zoomies/Dockerfile` (`packages/zoomies`) | 8080 | `/healthz` | --- ## 5. Auth relay (Google sign-in) **Status: `preproduction`; live Google, reliability and browser acceptance remain incomplete.** Configured endpoints below do not establish readiness. Check discovery and the [acceptance record](https://github.com/crvouga/personal/blob/main/packages/auth-relay/acceptance.md) before relying on the relay. Missing deployment, credentials or approval are blockers; never substitute mock authentication or disable verification. | Use | Console / agent API origin | OIDC issuer | | --- | --- | --- | | Production HTTPS apps | `https://auth.chrisvouga.dev` | `https://auth.chrisvouga.dev/realms/projects` | | Localhost, development, CI, staging, previews | `https://auth-dev.chrisvouga.dev` | `https://auth-dev.chrisvouga.dev/realms/projects-dev` | ### Information and credentials to collect | Item | Source | Secret? | | --- | --- | --- | | Project, environment, instance, exact callbacks, registration expiry | Your app and the operator-approved grant | No | | Relay origin and issuer | Table above; discovery at `/.well-known/openid-configuration` | No | | Client ID, callback, scopes | Successful registration response / console connection settings | No; safe as runtime configuration | | `AUTH_RELAY_AGENT_TOKEN` | **Isolated** Vault `secret/auth-relay-agents//`; obtain the exact credential id/path from platform onboarding | Yes; use only in registration tooling | | Vault CI role | `auth-relay-agent-`; exact repository + OIDC subject binding | Role name is public; use GitHub OIDC, no static Vault token | | Session encryption/signing secret, if your framework requires one | A separate application secret in Vault | Yes; never use the registration token as a session secret | Applications are **public PKCE clients**: there is no consuming OIDC client secret. Never request or copy `GOOGLE_OAUTH_*`, `AUTH_MANAGER_*`, `AUTH_CONSOLE_*`, `AUTH_RELAY_DATABASE_URL`, setup tokens, or platform database/provider credentials. A registration credential does not grant application users access, and a Google sign-in does not make someone a relay operator. ### One-time onboarding (platform operator) 1. Request a credential id, repo and exact GitHub OIDC subject, relay environment, project, approved HTTPS origins, whether changing loopback ports are needed, and expiry. Include this in the hosting request when applicable. Verify repository/deployment/domain ownership; a hostname or Google email alone is not evidence. No wildcard or shared hosting suffix approvals. 2. In `crvouga/personal`, add an entry to the **complete** `auth_agent_credentials` input map of the Vault OpenTofu root. Persist it in the existing OpenTofu-owned `TOFU_VAULT_INPUTS` input, preserving all other fields. Example metadata (no credential values): ```json { "my-app-dev": { "config": "dev", "repository": "owner/my-app", "subject": "repo:owner/my-app:ref:refs/heads/main", "generation": 1 } } ``` Use a separate id and `config: "prd"` for production. Protected GitHub environments can use an exact `repo:owner/my-app:environment:production` subject instead. An untrusted PR must never receive a production credential. This input controls credential delivery only; application registrations and callback scopes are never OpenTofu inventory entries. 3. Review and apply a saved Vault-root plan through the existing deployment workflow. OpenTofu generates the random credential, writes only its isolated Vault document, and creates a read-only policy/JWT role restricted to that document. Shared `personal/*` CI/runtime tokens cannot read it. If a resource already exists, import it before applying; never replace it to adopt it. 4. Read the **nonsecret** `auth_agent_credentials` OpenTofu output for path, role and SHA-256 fingerprint. In the correct relay console, sign in as an authorized operator, open **Agent access**, and approve that fingerprint with one project, allowed environments, exact owned HTTPS origins, optional nonproduction loopback access and expiry. Paste only the fingerprint, never the token. Application data goes into the relay's isolated PostgreSQL schema. The singleton first-operator setup and Google configuration remain platform-only operations. 5. Supply the integrating agent the credential id/path/role, approved project/scopes/expiry and relay origin. All of these are public metadata. Local agents use an existing authorized Vault login; grant narrowly scoped Vault read access through OpenTofu if needed, never a root/operator token. Runtime app containers never receive the registration credential. Grant leases last at most seven days outside production and 366 days in production. Registrations cannot outlive the grant. Operators renew grants explicitly. Rotate by incrementing `generation` in the credential input, applying the reviewed plan, and replacing the fingerprint on the **existing** grant. Its id and application ownership remain stable; the old token then fails immediately. Revoke **Agent access** to stop registration operations; revoke application clients separately to stop their new sign-ins. Existing app sessions follow the app's own policy. ### Register from another project The dependency-free [Bun agent client](https://github.com/crvouga/personal/blob/main/packages/auth-relay/agent.ts) can be copied into your project, inspected and pinned to a reviewed commit. No private `@pkgs/*` imports or platform checkout is needed: ```bash # Download source for review; replace main with a reviewed commit for reproducibility. curl -fsS https://raw.githubusercontent.com/crvouga/personal/main/packages/auth-relay/agent.ts -o auth-relay-agent.ts # List only the fields that would be injected; no values. personal infra-vault run --path secret/auth-relay-agents/my-app-dev/dev --dry-run -- bun auth-relay-agent.ts --help # A fingerprint is public; it can be supplied to the operator without revealing the token. personal infra-vault run --path secret/auth-relay-agents/my-app-dev/dev -- bun auth-relay-agent.ts fingerprint personal infra-vault run --path secret/auth-relay-agents/my-app-dev/dev -- bun auth-relay-agent.ts list --origin https://auth-dev.chrisvouga.dev ``` Commit a **public** `auth-registration.json`. The helper defaults to a one-hour lease capped at the grant expiry; optionally set an explicit future `expiresAt` or `--ttl-seconds` within the grant and environment limits: ```json { "name": "My app local", "project": "my-app", "environment": "localhost", "instance": "dev-server-one", "callbacks": ["http://localhost:5173/auth/callback"] } ``` ```bash personal infra-vault run --path secret/auth-relay-agents/my-app-dev/dev -- bun auth-relay-agent.ts register --origin https://auth-dev.chrisvouga.dev --file auth-registration.json # Teardown: use the public client id from the registration result. personal infra-vault run --path secret/auth-relay-agents/my-app-dev/dev -- bun auth-relay-agent.ts revoke --origin https://auth-dev.chrisvouga.dev --id app- ``` For changing ports, supply `--callback http://localhost:/auth/callback` after the server binds; this overrides the single callback without editing the file. `--ttl-seconds 3600` requests a fresh one-hour lease capped at grant expiry. The helper looks up the immutable `(project, environment, instance)`, reuses its client id and supplies its current revision. Re-running updates/renews that client, including an exact port change, without a Google change or deployment. Give each simultaneous server/preview a different instance. Choose the actual bound port before registering; do not advertise readiness until registration succeeds. Preview teardown revokes its client; expiry remains a fallback when teardown fails. A separately approved loopback grant permits changing explicit ports, never wildcard redirect URIs. Only clients created under this grant can be listed, updated or revoked by its credential. An operator-created client or another grant's client cannot be adopted by guessing its id/project. For an identity collision, ask an operator to resolve ownership; do not generate new ids repeatedly. Writes use revision checks. On a timeout or conflict, list again and reconcile the saved state before retrying; no request is automatically retried. New-client provider failures retain a pending identity for recovery. ### CI registration without a static Vault token Use the credential's dedicated role, **not** the shared application role from §1. Adapt the subject-bound job/ref/environment to the approved onboarding metadata: ```yaml permissions: contents: read id-token: write steps: # Checkout and install the project's pinned Bun runtime first. - uses: hashicorp/vault-action@v4 id: relay-credential with: url: https://vault.chrisvouga.dev method: jwt path: jwt role: auth-relay-agent-my-app-dev jwtGithubAudience: https://vault.chrisvouga.dev exportEnv: false secrets: | secret/data/auth-relay-agents/my-app-dev/dev AUTH_RELAY_AGENT_TOKEN | AUTH_RELAY_AGENT_TOKEN - run: bun auth-relay-agent.ts register --origin https://auth-dev.chrisvouga.dev --file auth-registration.json env: AUTH_RELAY_AGENT_TOKEN: ${{ steps.relay-credential.outputs.AUTH_RELAY_AGENT_TOKEN }} ``` Do not echo credentials, enable shell tracing, write them to `.env`, arguments, `$GITHUB_ENV`, job summaries, artifacts or caches. Inject them only into the registration step. Keep the production credential out of fork/PR jobs and browser code. ### Plain HTTP contract (any language) Use HTTPS with `Authorization: Bearer ` and `Content-Type: application/json`. No cookies, browser Origin, redirect following or CORS. Keep the credential in process memory; never send it in the URL. Paths are relative to the selected relay origin: | Method / path | Contract | | --- | --- | | `GET /agent/v1/clients` | Returns `issuer`, approved `grant`, and this grant's `clients` including `id`, `revision`, `config`, `desired`, `revoked`. Pending records have null `config`; use `desired` to reconcile identity. | | `PUT /agent/v1/clients/app-` | Registration JSON above plus explicit `expiresAt` (ISO-8601 timestamp) and `revision` (0 for a new UUID; returned revision for updates). Returns `id`, `issuer`, next `revision`, and public `settings`. Identity is immutable; 1–8 exact callbacks. | | `DELETE /agent/v1/clients/app-` | Revokes only this grant's client; returns `ok`. Repeating revocation is safe. | `401`: missing/unknown/expired/revoked credential; check Vault path, selected environment and fingerprint. `403`: browser-origin/cookie request denied. `400`: invalid registration, delegated scope, ownership or stale revision; inspect local metadata and re-list. `429`: honor `Retry-After`. `503`: dependency failure; reconcile before retrying a write. Errors contain no credential values. Agent credentials cannot access `/api/*` console/operator/setup operations. ### Configure and verify the consuming app Use returned public `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_REDIRECT_URI` and `OIDC_SCOPES=openid email profile`. Discover endpoints at `/.well-known/openid-configuration`. Use a maintained library supporting public clients, authorization code, mandatory S256 PKCE, `token_endpoint_auth_method=none`, random state and nonce. Optional `kc_idp_hint=google` skips the provider choice. Confidential client, implicit, password, refresh and iframe silent-renew flows are outside the supported profile. Bind each ten-minute, single-use transaction to the exact client/callback, browser, state, nonce and verifier; separate concurrent tabs. Never retry a one-time code exchange after an error/timeout. Validate signature, exact issuer, audience, nonce and expiry; cache JWKS with bounded freshness and refresh once on an unknown key. Identify people by `(iss, sub)`, never automatically link accounts by email. A verified email alone grants no app permissions. Each app owns its authorization and sessions. SSR sessions use host-only HttpOnly/Secure/SameSite=Lax cookies over HTTPS. Namespace local session/transaction cookies per project **and instance**: localhost ports do not isolate cookies. Browser-only clients keep transactions per tab and avoid persistent token storage. Use top-level redirects. Existing app sessions follow local policy during a relay outage; new authentication fails closed. Before reporting success, verify discovery, registration readback, fresh login and callback/token validation, denied state/replay, concurrent tabs, and a second local instance. Confirm no registration credential enters the app bundle or runtime env. A missing deployment, Vault permission or operator approval is a precise blocker, not a passed check. Framework integration details and rollout evidence: [`packages/auth-relay/README.md`](https://github.com/crvouga/personal/blob/main/packages/auth-relay/README.md), [`packages/auth-relay/operations.md`](https://github.com/crvouga/personal/blob/main/packages/auth-relay/operations.md), [`packages/auth-relay/acceptance.md`](https://github.com/crvouga/personal/blob/main/packages/auth-relay/acceptance.md). --- ## 6. Observability (logs, traces, metrics) Every project shares **one** observability backend: a Grafana Cloud stack (free plan; data is kept 14 days) that receives **OpenTelemetry (OTLP)**. Projects never see Grafana-specific settings. They send OTLP using the standard `OTEL_*` environment variables, so the backend can be swapped (self-hosted Grafana stack, ClickHouse, any OTLP vendor) by changing Vault values, not application code. The stack, its write-only ingest token and the agents' read-only token are all OpenTofu resources ([`packages/infra/tofu/foundation/observability.tf`](https://github.com/crvouga/personal/blob/main/packages/infra/tofu/foundation/observability.tf)); their values are written into Vault by the vault root. Nothing is created by hand. Current state: inventory `observability.live` = `false`. While it is `false` the keys below are absent and every exporter stays off. Integrate anyway: the same code starts exporting once the stack is live. ### Vault keys (both `dev` and `prd`) | Key | Purpose | | --- | --- | | `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP/HTTP base URL. Signals go to `/v1/logs`, `/v1/traces`, `/v1/metrics` | | `OTEL_EXPORTER_OTLP_HEADERS` | `Authorization=Basic%20…`, the write-only ingest credential. Treat it as a secret | | `OTEL_RESOURCE_ATTRIBUTES` | `deployment.environment.name=production` in `prd`, `development` in `dev` | | `GRAFANA_URL` | Grafana instance URL, for querying | | `GRAFANA_SERVICE_ACCOUNT_TOKEN` | Read-only (`Viewer`) token for agents and the Grafana MCP server | The ingest credential cannot read data and the agent token cannot write it. Never mint other tokens in the Grafana UI; open an `[observability]` issue on `crvouga/personal` instead. ### Send telemetry from your project - **Hosted on the managed services (§4):** nothing to request. The services root injects `OTEL_SERVICE_NAME=`, `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf` and `OTEL_RESOURCE_ATTRIBUTES` into every Railway service. A service opts out with `"observability": false` in its inventory entry. - **Any language:** use the official OpenTelemetry SDK or auto-instrumentation for your runtime with its default env-var configuration (Node `@opentelemetry/auto-instrumentations-node`, Python `opentelemetry-instrument`, Go/Java/.NET SDKs). Do not hardcode endpoints or credentials. With no `OTEL_EXPORTER_OTLP_ENDPOINT` the SDK must stay a no-op so tests and offline runs work. - **Inside `crvouga/personal`:** `@pkgs/logger` already exports every record as OTLP logs (redacted first; `traceId` correlates with `X-Request-ID`). Call `await flushLogs()` during graceful shutdown. See [`packages/logger/README.md`](https://github.com/crvouga/personal/blob/main/packages/logger/README.md). - **Locally / in CI:** `personal infra-vault run -- ` (dev config) or the OIDC Vault step (§1) supplies the same keys, tagged `development`. Set `OTEL_SDK_DISABLED=true` to turn export off for a run. - **Hosted elsewhere** (Vercel, Workers, another host): copy the `prd` OTLP keys into that platform's secrets from Vault at deploy time and set `OTEL_SERVICE_NAME`. Never commit them. Rules: set `service.name` to your project or service id; log structured events, never request bodies, tokens, SQL parameters or personal data; keep labels low-cardinality (no user IDs or URLs as metric labels or Loki labels). ### Query it (agents) Read `GRAFANA_URL` and `GRAFANA_SERVICE_ACCOUNT_TOKEN` from Vault (`personal infra-vault run --config prd -- …`). Then use either option: - **Grafana MCP server** (preferred). Configure the official `mcp-grafana` server with env `GRAFANA_URL` and `GRAFANA_SERVICE_ACCOUNT_TOKEN`. It exposes LogQL, PromQL and TraceQL queries, data-source listing and dashboards as tools. Installing the binary is local machine setup (https://www.chrisvouga.dev/llms-local.txt). - **HTTP API.** List data sources, then query through the data-source proxy: ```bash curl -sH "Authorization: Bearer $GRAFANA_SERVICE_ACCOUNT_TOKEN" "$GRAFANA_URL/api/datasources" | jq '.[] | {uid, type}' curl -sG -H "Authorization: Bearer $GRAFANA_SERVICE_ACCOUNT_TOKEN" \ "$GRAFANA_URL/api/datasources/proxy/uid//loki/api/v1/query_range" \ --data-urlencode 'query={service_name=""} | json | level="error"' \ --data-urlencode "start=$(date -u -d '-1 hour' +%s)000000000" ``` Useful LogQL: `{service_name=""} |= ""` finds one request across services; `{deployment_environment_name="production"} | json | level="error"` lists recent errors everywhere. Traces are in the Tempo data source (`{resource.service.name=""}` in TraceQL). `bun run health --only observability` verifies the whole path read-only. ### Uptime and alerts (synthetic monitoring) When `observability.synthetic_monitoring.enabled` is on, the foundation root installs Grafana Synthetic Monitoring and creates one HTTP check per public service: the same health URL `bun run health-check --all-public` probes (`https://`), from the probes listed in inventory, every 15 minutes (about 70k executions a month, inside the free plan). Each check alerts after repeated failures and when its TLS certificate is close to expiry, through the stack's default notification policy (the Grafana Cloud account owner's email). A new public service gets its check on the next Deploy; nothing is added by hand. Results are in the Synthetic Monitoring app and its data source (`probe_success{job=""}`). ### Operator setup (one time, inside `crvouga/personal`) The only manual step is one credential that cannot be created as code: 1. Sign up for Grafana Cloud (free). In the portal, open **Administration → Cloud access policies**, create a policy for the **organization** realm with scopes `stacks:read`, `stacks:write`, `accesspolicies:read`, `accesspolicies:write`, `accesspolicies:delete` and `stack-service-accounts:write`, and create a token for it. 2. Run `bun run observability:bootstrap` (hidden prompt, `GRAFANA_CLOUD_ACCESS_POLICY_TOKEN` or `--token-file`; `--yes` applies without asking, `--dry-run` previews). It checks the token's scopes, records the stack to adopt (the sign-up stack, or the inventory slug when the organization has none, which OpenTofu then creates) with its real region in inventory `observability.stack`, stores the token in Vault `prd` and the `GRAFANA_CLOUD_ACCESS_POLICY_TOKEN` Actions secret through reviewed OpenTofu plans, sets `observability.live` and regenerates these guides. 3. Open a PR with that change. On merge, Deploy applies foundation (stack, ingest and agent tokens, synthetic monitoring), then vault (writes the keys above), then services (injects them). Verify with `bun run health --only observability`. --- ## Troubleshooting | Symptom | Meaning / fix | | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `personal infra-vault run`: `No value found at secret/…` | KV empty, or wrong project/config in `.vault.yaml` — tell the human | | `personal infra-vault run`: permission denied / 403 | Token expired — the human runs `vault login …` | | Vault HTTP 503 | Sealed (restart in progress) — wait and retry; the human can run `gh workflow run deploy.yml -R crvouga/personal -f action=unseal` | | OIDC: audience error | Missing `jwtGithubAudience: https://vault.chrisvouga.dev` | | OIDC: role / bound claim error | Repository or optional ref claim does not match the declared role — see §1 CI | | R2: `SignatureDoesNotMatch` | Wrong secret key, region ≠ `auto`, or virtual-host addressing — use path-style | | R2: `NoSuchBucket` | `S3_BUCKET` does not match the config's bucket | | Publish: `id-token` / permissions error | The caller workflow must grant `contents: read`, `packages: write`, `id-token: write` (Step 3 does) | | Publish: `DEPLOY_DISPATCH_TOKEN is not set` | Org secret missing — see Step 3 | | Deploy: service id not found | No `OpenTofu inventory` entry for that `service_id` yet — open the Step 1 `[hosting]` issue | | Deploy: health check fails | Container not listening on `port`, or `health_path` is not 2xx — reproduce with `docker run` locally | --- ## Handling requests (agents working inside `crvouga/personal`) Every request from another project arrives as a GitHub issue (see _Communicating with `crvouga/personal`_). List them with `gh issue list -R crvouga/personal --state open` and triage by title prefix (`[hosting]`, `[secrets]`, `[database]`, `[storage]`, `[auth]`, `[infra]`). For each: validate it, ask for anything missing **in an issue comment** and stop (never guess), make the change through OpenTofu in one branch and PR with `Closes #`, then comment the outcome (live URL, Vault path to populate, PR link) on the issue. Never close a request that was not delivered; if you decline it, say why in a comment first. When this repo needs something from another project, open an issue on that project's repo rather than editing it. The steps below cover `[hosting]` requests in detail. ### Hosting requests Hosting requests are issues titled `[hosting] — …` (`gh issue list -R crvouga/personal --search "[hosting] in:title" --state open`). Work one issue per branch and PR: 1. **Validate the request.** Every field is filled; the id and hostname are unused in [`packages/infra/tofu/modules/inventory/inventory.tf.json`](https://github.com/crvouga/personal/blob/main/packages/infra/tofu/modules/inventory/inventory.tf.json); the image reference exists (`docker manifest inspect ` or the GHCR package page); no secret values appear anywhere in the issue (if one does, tell the human to rotate it and edit the issue). Ask for anything missing in an issue comment and stop — never guess a port, health path or secret. 2. **Declare the service.** Add the entry to `locals.inventory.services` in the OpenTofu JSON definition (fields as in Step 2; `image:` only for an external image). For each new secret, add it to `vault.kv_keys` with `configs` and `used_by: []`, then tell the human the required OpenTofu vault secrets input changes — never write values yourself. 3. **Plan.** `bun run infra:services plan` (dry run) and check the plan only adds this service, its DNS record and its variable bindings. 4. **Publish workflow.** If the issue says it is not committed yet, `bun run infra apply` generates it (ask the human before pushing to another repo). 5. **Portfolio.** When the issue asks for a listing, add an entry to `PROJECTS` in [`packages/portfolio/src/content.ts`](https://github.com/crvouga/personal/blob/main/packages/portfolio/src/content.ts) (`name`, `description`, `live`, `code`). The homepage is deliberately short, so keep it to the strongest four or five projects. 6. **Regenerate and check.** `bun run llms:sync` (the services table changes), then `bun run check`. 7. **Ship.** Open the PR with `Closes #` in the body. After merge, watch CI (`gh run list -R crvouga/personal --workflow ci.yml --limit 3`), confirm `curl -fsS https://`, and comment the live URL on the issue. If the deploy failed only because the entry was missing, redeploy with `gh workflow run deploy.yml -R crvouga/personal -f action=deploy -f service_id= -f image_tag=`. --- ## Maintaining this file (agents working inside `crvouga/personal`) `llms-cloud.txt` is generated — never edit it by hand. Prose lives in [`scripts/llms-cloud.template.md`](https://github.com/crvouga/personal/blob/main/scripts/llms-cloud.template.md); the generator rejects local-development content here (see `BOUNDARY` in [`scripts/llms-txt.ts`](https://github.com/crvouga/personal/blob/main/scripts/llms-txt.ts)); values, tables and the publish workflow come from [`packages/infra/tofu/modules/inventory/inventory.tf.json`](https://github.com/crvouga/personal/blob/main/packages/infra/tofu/modules/inventory/inventory.tf.json), [`.github/workflows/publish.yml`](https://github.com/crvouga/personal/blob/main/.github/workflows/publish.yml) and [`.github/workflows/deploy.yml`](https://github.com/crvouga/personal/blob/main/.github/workflows/deploy.yml), [`scripts/secret-integrations.ts`](https://github.com/crvouga/personal/blob/main/scripts/secret-integrations.ts) and [`packages/infra/lib/publish-workflow.ts`](https://github.com/crvouga/personal/blob/main/packages/infra/lib/publish-workflow.ts) via [`scripts/llms-txt.ts`](https://github.com/crvouga/personal/blob/main/scripts/llms-txt.ts). Run `bun run llms:sync` after changing any of them; `bun run check:llms` (part of `bun run check`) fails CI on drift, on a dangling file reference, or on an unknown `bun run` script.