# Self-host OpenGen on Docker or Cloud Run and Vercel

> OpenGen is Apache-2.0 open source and self-hosts with three Node.js 22 processes (web, api, and worker), PostgreSQL 17 with automatic transactional migrations, and private S3 or R2 object storage—with no Redis or Kubernetes required. Configure AES-256-GCM provider vault encryption, OIDC, GitHub OAuth, or Email OTP sign-in, Ed25519 webhook signing keys, and optional Cloud Run plus keyless Vercel Workload Identity Federation deployment.

## Agent Prompt

```text
Help me self-host OpenGen using Docker Compose (local/single-host) or Cloud Run + Vercel (production):
1. Walk me through bootstrapping a 0600 .env file via npm run setup:local and launching PostgreSQL 17, api (:4310), worker, and web (:4320) with deploy/compose.yaml.
2. Verify GET /health reports database readiness and public catalog pages render with zero provider credentials.
3. Guide me through configuring private S3/R2 storage (S3_BUCKET, S3_ENDPOINT, S3_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY), 32-byte hex MR_VAULT_KEY, OIDC/GitHub/Email OTP auth, and Ed25519 OPENGEN_WEBHOOK_SIGNING_KEYS_JSON.
4. For Cloud Run + Vercel, inspect infra/deploy-gcp.sh --plan and infra/update-gcp-image.sh --plan first with distinct API and worker service accounts and keyless Vercel Workload Identity Federation before applying any billable infrastructure.
```

OpenGen is Apache-2.0 open source and self-hosts cleanly with three Node.js 22 processes (`web`, `api`, and `worker`), PostgreSQL 17, and an S3-compatible private bucket. No Redis, Kafka, Temporal, or Kubernetes cluster is required—PostgreSQL handles durable job queues, transactional reservations, ledger accounting, and webhook outbox retries.

## Architecture and multi-stage `Dockerfile`

The root `Dockerfile` builds two production targets from one TypeScript monorepo (`node:22-bookworm-slim`, running as non-root `USER node`):

| Target            | Port   | Command                   | Responsibilities & secret boundary                                                                                                                                                                                                                                         |
| ----------------- | ------ | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `web`             | `4320` | Next.js production server | Public catalog/docs/SEO UI + authenticated Playground/Dashboard BFF proxy. Receives **zero** provider keys, DB credentials, Stripe keys, or storage HMAC keys.                                                                                                             |
| `server` (API)    | `4310` | `npm run dev:api`         | Fastify REST + Streamable HTTP `/mcp` & `/mcp/readonly`, OAuth/OIDC/GitHub/OTP auth, `/.well-known/webhook-jwks.json`, `/media/:token` capability serving.                                                                                                                 |
| `server` (Worker) | none   | `npm run worker`          | Continuous background poll loop executing provider adapters, archiving outputs to private S3, dispatching Ed25519 webhooks, and running bounded asset cleanup. Includes `/usr/bin/ffmpeg` and `/usr/bin/ffprobe`. Isolated from API-only session, IdP, and Stripe secrets. |

## 1. Quick start with Docker Compose and PostgreSQL 17

Generate private local cryptographic material (`POSTGRES_PASSWORD`, `MR_API_TOKEN`, `MR_VAULT_KEY`, and `MR_SESSION_SECRET`) with `0600` file permissions, then launch the full four-service stack (`db`, `api`, `worker`, `web`):

```bash
git clone https://github.com/atomstobits/opengen.git
cd opengen

# Generates private 0600 .env without printing secrets (fails safely if .env already exists)
npm run setup:local

# Build and start PostgreSQL 17, API (:4310), worker, and web (:4320)
docker compose --env-file .env -f deploy/compose.yaml up --build --detach --wait

# Verify API health and public catalog availability (zero provider keys needed)
curl --fail-with-body http://127.0.0.1:4310/health
curl --fail-with-body http://127.0.0.1:4320/v1/models
```

### Automatic PostgreSQL 17 migrations

`deploy/compose.yaml` runs `postgres:17-bookworm`. On startup, `engine.initialize()` acquires a PostgreSQL transaction advisory lock (`pg_advisory_xact_lock(hashtext('media-router-schema'))`), applies contiguous migrations `001.sql` through `044.sql` from `packages/engine/migrations/`, and records each migration's SHA-256 checksum in `mr_migrations`.

> [!WARNING]
> Historical migrations are immutable. Never edit an already-applied `.sql` file—checksum mismatches fail startup intentionally. Before upgrading a production database with new migrations, take a verified PostgreSQL backup and quiesce admissions and workers first.

## 2. Configure private S3 / Cloudflare R2 / GCS HMAC storage

Private uploaded inputs (`inputs/<workspace>/...`) and archived generation outputs (`outputs/<jobId>/...`) require a **private** S3-compatible bucket (AWS S3, Cloudflare R2, or Google Cloud Storage S3-interoperability HMAC). Never expose storage credentials to `web` or `NEXT_PUBLIC_*` variables.

```dotenv
# Shared by API and worker only (never Vercel / web)
S3_BUCKET=your-private-opengen-bucket
S3_ENDPOINT=https://<account-id>.r2.cloudflarestorage.com
S3_REGION=auto
AWS_ACCESS_KEY_ID=your-restricted-access-key
AWS_SECRET_ACCESS_KEY=your-restricted-secret-key

# Ready-input lifetime in milliseconds (604800000 = 7 days; blank disables automatic expiry)
MR_INPUT_RETENTION_MS=604800000
```

Storage requirements:

- **Private ACL / block public access:** every customer input and output stays private; `api` serves temporary first-party `/media/v1.<payload>.<hmac>.<ext>` capability links signed with `OPENGEN_MEDIA_SIGNING_SECRET` (or domain-separated `MR_SESSION_SECRET`, >= 32 characters).
- **Bucket CORS for presigned browser PUTs:** allow `PUT` from your `OPENGEN_PUBLIC_URL` origin with headers `Content-Type`, `If-None-Match` (S3/R2), and `x-goog-if-generation-match` (GCS).
- **No age-only bucket lifecycle deletion on `inputs/`:** OpenGen pins accepted generation inputs in PostgreSQL and performs bounded cleanup in the worker only once pins and active write leases clear.

## 3. Encrypted provider vault and provider credentials

Workspace BYOK provider connections are encrypted at rest with **AES-256-GCM** using `MR_VAULT_KEY` (must be a 64-character / 32-byte hex secret; keep an offline backup separate from database backups).

For operator-managed routes (`billing: "managed"`), configure only the exact provider keys you intend to serve on **both** `api` and `worker`:

```dotenv
MR_VAULT_KEY=<64-hex-char-32-byte-secret>
OPENGEN_EXECUTION_SCOPE=unrestricted
OPENGEN_PROVIDER_EXECUTION_ENABLED=true
METRICS_ORIGIN_REGION=us-central1

# Optional managed provider credentials (add only what you activate)
OPENAI_API_KEY=
BFL_API_KEY=
KLING_API_KEY=
BYTEPLUS_API_KEY=
FAL_KEY=
FAL_BILLING_KEY=
GOOGLE_API_KEY=
XAI_API_KEY=
MINIMAX_API_KEY=
REPLICATE_API_TOKEN=
RUNWAYML_API_SECRET=
PIKA_API_KEY=

# Alibaba Model Studio credentials are bound per exact region:
# ALIBABA_AP_SOUTHEAST_1_API_KEY / ALIBABA_AP_SOUTHEAST_1_ENDPOINT, etc.
ALIBABA_AP_SOUTHEAST_1_API_KEY=
ALIBABA_AP_SOUTHEAST_1_ENDPOINT=
```

Self-hosting does **not** require Stripe. Use the operator bootstrap token `MR_API_TOKEN` (`Authorization: Bearer $MR_API_TOKEN`) to create workspaces (`POST /v1/workspaces`) and grant accounting credit (`POST /v1/workspaces/{id}/credits` with `{ "amountMicros": 5000000, "reference": "unique-funding-ref" }`), or let users connect their own encrypted provider keys for `billing: "byok"`.

## 4. Configure authentication (OIDC, GitHub OAuth, and Email OTP)

All identity and session secrets belong on the **API process only** (never the worker or `web` frontend). Set `OPENGEN_PUBLIC_URL` to your exact public HTTPS origin (no trailing slash) on both `api` and `web`.

```dotenv
OPENGEN_PUBLIC_URL=https://opengen.example.com
MR_SESSION_SECRET=<at-least-32-random-characters>

# Option A: OpenID Connect (Google, Okta, Auth0, Keycloak, etc.)
# Register callback URL: https://opengen.example.com/auth/callback
OIDC_ISSUER=https://accounts.google.com
OIDC_CLIENT_ID=
OIDC_CLIENT_SECRET=
OPENGEN_OIDC_DISPLAY_NAME=Google

# Option B: GitHub OAuth
# Register callback URL: https://opengen.example.com/auth/callback
OPENGEN_GITHUB_CLIENT_ID=
OPENGEN_GITHUB_CLIENT_SECRET=

# Option C: Email OTP (via Resend or an HTTPS relay)
OPENGEN_EMAIL_OTP_ENABLED=true
RESEND_API_KEY=
RESEND_FROM_EMAIL=login@opengen.example.com
# Or use OPENGEN_EMAIL_OTP_RELAY_URL + OPENGEN_EMAIL_OTP_RELAY_AUTH_TOKEN + OPENGEN_EMAIL_OTP_FROM

# Reverse-proxy client-IP attribution (API + web shared >=32 char HMAC secret)
OPENGEN_PROXY_CLIENT_SECRET=<at-least-32-random-characters>
# Optional comma-separated ingress IP/CIDR allowlist for Fastify trustProxy (never "true" or /0)
OPENGEN_TRUSTED_PROXIES=
# Optional single header overwritten by non-Vercel ingress (set on web)
OPENGEN_TRUSTED_CLIENT_IP_HEADER=
```

Notice that both OIDC and GitHub OAuth use the exact redirect callback `${OPENGEN_PUBLIC_URL}/auth/callback`. For external OAuth resource tokens on `/mcp`, optionally set `OIDC_JWKS_URI`, `OIDC_API_AUDIENCE=https://opengen.example.com/mcp`, and `OIDC_ALLOWED_SCOPES="read generate"`.

## 5. Configure Ed25519 webhook signing keys (`OPENGEN_WEBHOOK_SIGNING_KEYS_JSON`)

Both `api` (serving public JWKs at `GET /.well-known/webhook-jwks.json`) and `worker` (signing outbound webhook deliveries) load Ed25519 keys from `OPENGEN_WEBHOOK_SIGNING_KEYS_JSON` (multi-key rotation array) or single-key `OPENGEN_WEBHOOK_SIGNING_PRIVATE_KEY_PEM` / `OPENGEN_WEBHOOK_SIGNING_KEY_JWK`.

Generate a fresh Ed25519 key entry locally with Node.js 22:

```bash
node -e '
  const { generateKeyPairSync } = require("node:crypto");
  const { privateKey } = generateKeyPairSync("ed25519");
  const jwk = privateKey.export({ format: "jwk" });
  console.log(JSON.stringify([{ kid: "og_whk_2026_12", active: true, ...jwk }]));
'
```

To rotate keys with zero downtime, roll out in two phases so recipients never see a signature signed with an unpublished `kid`:

1. **Publish the new public key on `api` first**: add the new key's **public-only** JWK (`kty`, `crv`, `kid`, `x` — without `d` or `"active": true`) alongside the existing active key in `OPENGEN_WEBHOOK_SIGNING_KEYS_JSON` on `api`, roll out `api`, and allow recipient JWKS caches to refresh.
2. **Activate the new private key on `worker` (and `api`)**: switch `"active": true` to the new key (with `d`) while keeping the retired key's **public-only** JWK in the array during your grace window, then remove the retired key after the grace window completes:

```json
[
  {
    "kid": "og_whk_2027_01",
    "active": true,
    "kty": "OKP",
    "crv": "Ed25519",
    "x": "<new-x>",
    "d": "<new-d>"
  },
  { "kid": "og_whk_2026_12", "kty": "OKP", "crv": "Ed25519", "x": "<previous-x>" }
]
```

Verify that `GET https://opengen.example.com/.well-known/webhook-jwks.json` returns **only** public keys (`kty: "OKP"`, `crv: "Ed25519"`, `alg: "EdDSA"`, `use: "sig"`, `kid`, `x`) and never exposes `d`.

## 6. Production deployment on Google Cloud Run and Vercel

OpenGen's reference production topology runs the `web` frontend on **Vercel**, an IAM-private **Cloud Run service** (`opengen-api`), a continuous **Cloud Run worker pool** (`opengen-worker`), **Cloud SQL PostgreSQL 17**, and **Secret Manager** with pinned secret versions.

### Build and deploy immutable Cloud Run images

Copy `infra/opengen.env.example` into git-ignored `infra/.local/opengen.env` (never commit real identifiers or secrets), configure distinct `OPENGEN_API_RUNTIME_SA` and `OPENGEN_WORKER_RUNTIME_SA` service accounts (granting per-secret Secret Manager access rather than project-wide roles), and preview before applying:

```bash
# 1. Offline validation and rollout preview (zero GCP mutations)
bash infra/update-gcp-image.sh --env-file infra/.local/opengen.env --plan

# 2. Build Dockerfile --target server in Cloud Build and pin the exact @sha256 digest
bash infra/update-gcp-image.sh --env-file infra/.local/opengen.env --build

# 3. Roll out the pinned digest to both opengen-api and opengen-worker
OPENGEN_BILLABLE_RUNTIME_APPROVED=yes \
  bash infra/update-gcp-image.sh --env-file infra/.local/opengen.env --skip-build --apply
```

### Connect Vercel to IAM-private Cloud Run via Workload Identity Federation

Keep `opengen-api` IAM-private (no `allUsers` invoker binding) and use `deploy/cloud/vercel-project-settings.json` (`rootDirectory: "apps/web"`, Node `22.x`, root `npm ci`). Set only these **server-only** Vercel environment variables—never put provider keys, database URLs, or service-account JSON on Vercel:

| Vercel env var                   | Purpose                                                                                        |
| -------------------------------- | ---------------------------------------------------------------------------------------------- |
| `OPENGEN_PUBLIC_URL`             | Canonical public website origin (for example `https://opengen.example.com`).                   |
| `MEDIA_ROUTER_API_URL`           | Canonical HTTPS Cloud Run service origin ending in `.run.app` (no path or query).              |
| `GCP_WORKLOAD_IDENTITY_PROVIDER` | `projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID` |
| `GCP_SERVICE_ACCOUNT_EMAIL`      | Dedicated calling service account granted only `roles/run.invoker` on `opengen-api`.           |
| `OPENGEN_PROXY_CLIENT_SECRET`    | Optional >=32-char HMAC secret shared with `opengen-api` for client-IP attribution.            |

At runtime, the Vercel BFF exchanges its short-lived OIDC token via Google STS and IAM Credentials into an `X-Serverless-Authorization: Bearer <GCP-ID-token>` header while keeping the caller's `Authorization` header intact for workspace authentication.

## Next steps

- Wire up inbound webhook verification in your app with [Next.js Webhook Verification](/docs/guides/webhooks-nextjs).
- Connect local coding agents or hosted assistants to your self-hosted `/mcp` endpoint in [Client Setup](/docs/clients) and [Authentication](/docs/authentication).
