Files
loki/.env.example
CatoandClaude Opus 5.5 ff2d7cb6b7 Pictures out of Postgres and off the disk, into a private R2 bucket (#1771)
* feat(media): keep pictures in the private R2 bucket, drain them out of Postgres

The owner's rule: pictures live in Cloudflare R2, not in Postgres or on the
box's disk, and the database gets cleaned up.

- src/lib/media/r2.ts: a small S3 client for R2, SigV4 by hand (node:crypto
  + fetch, no SDK), on the fleet's PHOTOS_S3_* names. Everything is private:
  MEDIA_PRIVATE_S3_BUCKET, or private/loki/ in the photos bucket. Unset means
  behaviour exactly as before.
- Chat pictures and report screenshots are written to the bucket when it is
  configured; the row keeps the key (additive migration 0140: nullable
  object_key and screenshot_keys). Reads try the bucket, then the old column.
  A write the bucket refuses stays in Postgres, so nothing is lost.
- A throttled drain started from instrumentation moves what Postgres still
  holds (chat images, report screenshots, executed commands' attachments):
  small batches under a transaction-scoped advisory lock, upload, HEAD to
  verify length/type/MD5, then key-and-null in one statement; error backoff,
  IMAGE_DRAIN=0 kill switch, progress on /api/health under `media`.
- Commands that have not run keep their base64: runners hold no bucket
  credentials. Retry puts moved bytes back before re-sending.
- Bot shots, private tile shots and preview pictures go to the bucket when
  configured, the temp folder otherwise; bucket caches keep their age limits.
- Deleting a chat or an account deletes its objects by prefix.
- Dropping the emptied columns stays a manual step (apply-schema.sh refuses
  DROP COLUMN): docs/infrastructure/media-storage.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T

* fix(media): private pictures only in MEDIA_PRIVATE_S3_BUCKET, never the photos bucket

The photos bucket (fleet-media) gets a public domain, so a private Loki
picture must never fall back into it. The private store now needs
MEDIA_PRIVATE_S3_BUCKET; unset, or equal to PHOTOS_S3_BUCKET, counts as
unconfigured: pictures stay in Postgres as today, the drain does not run,
and the env check warns in one line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-29 07:21:50 +01:00

326 lines
19 KiB
Bash

# ── Required ────────────────────────────────────────────────────────────────
# PostgreSQL — see docs/infrastructure/postgres-portability.md
#
# Local dev (Docker): direct URL only
DATABASE_URL=postgresql://loki:changeme@localhost:5432/loki
#
# Production (self-hosted Hetzner): set BOTH on the host — not in .env.local
# DATABASE_URL — direct (:5432) for migrations + LISTEN/NOTIFY
# DATABASE_POOL_URL — pooled (:6432 / PgBouncer) for app queries
# ── Agent runs Loki starts on its own (optional) ─────────────────────────────
# Every automatic re-dispatch (a refused feedback run, a refused project run,
# a queued Implement no builder claimed) is OFF unless this is exactly "1".
# Each of those spends the account's provider quota — Claude, Codex, Gemini —
# without anyone tapping a button. Runs a person starts are never affected.
# LOKI_AUTO_DISPATCH=
# ── Smoke / QA (optional, never commit real values) ─────────────────────────
# Authenticated probe suite: npm run test:authenticated-smoke
# LOKI_SESSION_TOKEN= # raw Auth.js session cookie (COCKPIT_SESSION_TOKEN legacy)
# SMOKE_EMAIL= # credentials sign-in for smoke
# SMOKE_PASSWORD=
# SMOKE_PRIVATE_PIN= # unlock private-zone probes; pre-push prod dogfood (auto-read from .env.local)
# DOGFOOD_LOKI_ON_PUSH= # set 1 to force Loki UI dogfood even when no builder is connected
# UI_FLOW_FULL_DISPATCH= # set 0 to skip the G07 harmless full-dispatch smoke prompt
# DOGFOOD_MACHINE_FORCE= # set 1 to fail machine dogfood when no local Fleet Runner
# Login email used by scripts/seed.ts for the default user; keep out of git.
SEED_OWNER_EMAIL=
# Random secret for signing sessions — generate with: openssl rand -base64 32
AUTH_SECRET=
# REQUIRED for every deployment that is not behind Auth.js's own host detection
# — which includes plain `pnpm run dev` on localhost. Without it `src/auth.ts`
# leaves `trustHost` false, and Auth.js answers EVERY /api/auth/session request
# with 500 UntrustedHost: the app renders but no page can read a session, and
# the browser console fills with ClientFetchError. The value is compared as the
# exact string "true" (see src/auth.ts), so `AUTH_TRUST_HOST=1` does NOT work.
# scripts/hetzner/gen-env.sh already writes this on the box; local dev and
# docker-compose did not, which is why a clean checkout looked broken.
AUTH_TRUST_HOST=true
# ── Authentication ───────────────────────────────────────────────────────────
# Local password (quick dev) — leave empty to use the /setup wizard on first run.
# IMPORTANT: setting this alone does NOT enable the "Owner key" sign-in tab —
# you must also set ENABLE_OWNER_KEY=1 below. The hosted production deployment
# keeps LOCAL_AUTH_PASSWORD set for legacy reasons, but the tab stays hidden
# there because ENABLE_OWNER_KEY is unset.
LOCAL_AUTH_PASSWORD=
# Set to 1 only on local installs (loki-app systemd, dev machines). When
# unset, the Owner-key sign-in tab is hidden AND the "local" credentials
# provider rejects every authorize() call — structural defense in depth so a
# stray LOCAL_AUTH_PASSWORD on a public deployment can't be brute-forced.
ENABLE_OWNER_KEY=
# GitHub OAuth (optional — get at github.com/settings/developers)
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
# Optional. Org admin token (repo + workflow) used for every write into the fleet
# organisation: create/seed/wire/delete repos. Without it those writes use the
# person's OAuth token, which an org with OAuth-app restrictions refuses (403).
# GITHUB_ORG_TOKEN=
# ── Optional ─────────────────────────────────────────────────────────────────
# Timezone for cron jobs and schedule display (e.g. America/New_York).
# Reads APP_DEFAULT_TIMEZONE first, then COCKPIT_DEFAULT_TIMEZONE (legacy).
APP_DEFAULT_TIMEZONE=Europe/Zurich
# Locale for date/time formatting. APP_LOCALE preferred, COCKPIT_LOCALE accepted.
APP_LOCALE=de-CH
# The same setting for the browser. Do not set it by hand: next.config.ts
# fills it in from APP_LOCALE when the app is built, so a date is formatted
# the same way on the server and in the browser (src/lib/constants/locale.ts).
# NEXT_PUBLIC_APP_LOCALE=
# Docker only — Postgres password (must match DATABASE_URL above)
POSTGRES_PASSWORD=changeme
# "Power Loki with your own model" (Settings → AI). Seals each user's API key
# at rest (@bitbaum/ai-kit/seal, AES-256-GCM). Without it the feature says it
# is not switched on and chat keeps using the free chain. Generate once with
# `openssl rand -base64 32`; ROTATING it makes every stored key unreadable
# (users are then asked to paste their key again).
BYOK_SEAL_SECRET=
# ── Brand alias scheme ───────────────────────────────────────────────────────
# Every env var below is read as APP_<KEY> first, then COCKPIT_<KEY> as a
# legacy fallback (mirror of scripts/_brand.sh:_brand_env). Set whichever
# prefix matches your environment — both work, APP_* takes precedence.
# ── Daemon ⇄ Cloud bridge ────────────────────────────────────────────────────
# When the local daemon talks to a remote app instance, it authenticates with
# a bearer token. Two paths exist:
#
# 1. Mint a per-user ck_* token from /settings (preferred, multi-tenant safe).
# 2. Use APP_DAEMON_TOKEN as a shared bearer — single-tenant only.
#
# To enable path (2), set BOTH of these on the *server*. The flag is required
# because the token maps to the "default" user and must not be on by accident
# in multi-tenant deployments.
APP_DAEMON_TOKEN=
APP_ALLOW_LEGACY_DAEMON_TOKEN=
# Set to 1 in the local daemon's environment when a local Next.js dev server
# is running alongside a different cloud deployment. Without this, the daemon
# prefers localhost:3000 (the local server's DB) and the cloud control
# panel's runtime state goes stale.
APP_DAEMON_FORCE_REMOTE=
# Override the daemon's remote base URL (defaults to APP_DOMAIN from brand.ts).
APP_BASE_URL=
# ── Web Push (optional — ambient agent-ready notifications) ─────────────────
# Generate keys: npx web-push generate-vapid-keys
# Server-side (host env): VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY, VAPID_SUBJECT (mailto: or https: URL)
# CHROME_PATH= # src/lib/feedback/page-picture.ts (a browser for the picture Loki takes of a live page; else Playwright's own or a system Chromium)
# PW_TEST_SCREENSHOT_NO_FONTS_READY= # src/lib/feedback/page-picture.ts (Playwright's own switch; set by the code itself around a retry when a page's fonts never settle — nothing to configure)
# OPENCLAW_GATEWAY_URL= # src/lib/constants.ts
# Client-side (browser subscribe): NEXT_PUBLIC_VAPID_PUBLIC_KEY must match VAPID_PUBLIC_KEY
VAPID_PUBLIC_KEY=
VAPID_PRIVATE_KEY=
VAPID_SUBJECT=mailto:you@example.com
NEXT_PUBLIC_VAPID_PUBLIC_KEY=
# ── OrangeCat integration (Loop A: mirror subscriptions to the economic layer)
# Mint at https://orangecat.ch/settings/integrations, choose the Loki
# group actor at mint time. Format: ock_<48-hex>. Treat like a password — the
# plaintext is shown once and stored as a sha256 hash on OrangeCat's side.
# When unset, the integration no-ops (subscriptions are still saved locally).
ORANGECAT_API_KEY=
ORANGECAT_API_BASE=https://orangecat.ch
# ── "Login with OrangeCat" (cross-product identity bridge, Part A)
# OIDC relying-party credentials for the orangecat.ch authorization server.
# The client is registered on OrangeCat's side via scripts/oauth/register-client.ts
# (OC repo) with redirect https://loki.orangecat.ch/api/auth/callback/orangecat.
# When unset, the "Continue with OrangeCat" button is not mounted.
ORANGECAT_OAUTH_CLIENT_ID=
ORANGECAT_OAUTH_CLIENT_SECRET=
# Override only for local testing against a non-prod OrangeCat:
# ORANGECAT_OAUTH_ISSUER=https://orangecat.ch
# ── The shared sign-in (Google, Apple, GitHub, X, Facebook in one OIDC service)
# Mounted by AccountKit as `bitbaum-signin`, on the AccountKit runtime only
# (AUTH_RUNTIME=accountkit). All three, or the button stays hidden.
SIGNIN_ISSUER=
SIGNIN_CLIENT_ID=
SIGNIN_CLIENT_SECRET=
# Same 32+ character random value on OrangeCat and Loki. Signs
# ten-minute, one-use entity → build handoffs.
LOKI_BUILD_INTENT_SECRET=
# Same value on both products. Authenticates confirmed-payment activity events.
ORANGECAT_WEBHOOK_SECRET=
# Where a bot's browser keeps its cookies and pictures (src/lib/bot-browser.ts,
# bot-shots.ts). Unset: a folder under the system temp directory.
# LOKI_BOT_BROWSER_DIR=
NEXT_PUBLIC_ORANGECAT_URL=https://www.orangecat.ch
NEXT_PUBLIC_LOKI_URL=https://loki.orangecat.ch
NEXT_PUBLIC_ORANGECAT_PROJECT_ID=cb093f00-8745-4579-98df-050ebfb37181
NEXT_PUBLIC_LOKI_ORANGECAT_PROJECT_ID=8130c927-114a-45b7-8cc2-99efd5224025
# ── Solon (governance pillar, solon.orangecat.ch) ───────────────────────────
# HMAC secret shared with the Solon deployment; verifies decision.finalized
# webhooks at /api/solon/events. Without it that route answers 503.
SOLON_WEBHOOK_SECRET=
# Base URL for Solon API calls (scripts/solon/cast-vote.ts). Public link
# override for nav/footer is NEXT_PUBLIC_SOLON_URL.
SOLON_BASE_URL=https://solon.orangecat.ch
NEXT_PUBLIC_SOLON_URL=https://solon.orangecat.ch
# Loki's Bitcoin signing key for Solon votes. Set ONLY on the box Loki runs
# on — the key never leaves that environment; Solon only ever sees signatures.
LOKI_SOLON_PRIVKEY=
# ── Observability (optional — Sentry error tracking) ────────────────────────
# Leave empty to disable (SDK silently no-ops without a DSN).
# Enable: create a Next.js project at sentry.io and paste its DSN here.
NEXT_PUBLIC_SENTRY_DSN=
# Only needed for sourcemap upload at build time:
# SENTRY_ORG= / SENTRY_PROJECT= / SENTRY_AUTH_TOKEN=
# ── Fleet chat review (optional) ─────────────────────────────────────────────
# One value shared by every app in the loop (heidi, orangecat, substrata, loki):
# the bearer each product's GET /api/chat/review-export demands, and the one
# Loki's nightly review-chats cron presents. Put it in place with the
# share-chat-review-token workflow (never by hand, never in a log):
# `openssl rand -hex 32`. docs/architecture/chat-review.md
CHAT_REVIEW_TOKEN=
# ── Public demo access (optional) ────────────────────────────────────────────
# Set to 1 ONLY on an instance that should host the shared "explore without an
# account" demo. It gates three things at once: the sign-in button appears, the
# sandbox policy in src/config/demo.ts is enforced, and the nightly reset
# (which DELETES the demo user and everything it owns) is allowed to run at all.
# An instance that never sets this cannot be reset even with a valid CRON_SECRET.
#
# After setting it, seed the tenant once:
# DEMO_ACCESS_ENABLED=1 DATABASE_URL=... npx tsx scripts/seed-demo.ts
DEMO_ACCESS_ENABLED=
# Owner for scripts that act on behalf of a person (scripts/provision-widget.ts).
# NOT a secret — an identifier. Without it, provisioning refuses to guess when
# the database holds more than one user, because guessing wrong sends a client's
# site feedback to a stranger.
LOKI_OWNER_EMAIL=you@example.com
# ── Pictures: the private R2 bucket (docs/infrastructure/media-storage.md) ──
# Chat pictures, reports' screenshots, the screenshots a command carried to an
# agent, and the pictures Loki takes (a bot's browser, a private site's tile, a
# preview's before/after) live in Cloudflare R2, not in Postgres or on the
# box's disk. The four PHOTOS_S3_* are the fleet's shared names (Solon and
# Heidi read the same ones): Loki uses their account, all four or none, and
# MEDIA_PRIVATE_S3_BUCKET below. Without all five: everything stays where it
# was before (Postgres, a folder on disk). Read by src/lib/media/r2.ts.
# PHOTOS_S3_ENDPOINT=https://<account>.r2.cloudflarestorage.com
# PHOTOS_S3_BUCKET=
# PHOTOS_S3_ACCESS_KEY_ID=
# PHOTOS_S3_SECRET_ACCESS_KEY=
# PHOTOS_S3_REGION=auto
# Loki's pictures are PRIVATE: never given a public address, always served
# through Loki's own signed-in routes. REQUIRED for the private store: a bucket
# of their own, with no public domain and no r2.dev. The photos bucket has a
# public domain, so it is never used for them: unset, or the same name as
# PHOTOS_S3_BUCKET, means no private store (pictures stay in Postgres and the
# env check warns).
# MEDIA_PRIVATE_S3_BUCKET=
# The drain that moves the pictures still in Postgres into the bucket
# (src/lib/media/drain.ts) runs on its own when the private bucket is set. 0 stops it.
# IMAGE_DRAIN=
# ── Everything else src/ reads (optional — a feature is off until its key is set) ──
# Generated contract, enforced by scripts/test/env-example-covers-src.ts: a
# variable the code reads must be named here, with the file that reads it, so a
# copy of this repo never discovers a switch by grepping. Leave unset to keep
# the feature off; read the named file for what the value means.
# AGENT_PROJECTS_CONF= # src/lib/agent-config.ts
# AGENT_PROMPTS_FILE= # src/lib/agent-config.ts
# APP_SCRIPTS_DIR= # src/app/api/beacon/transcribe/route.ts
# APP_SESSIONS_DIR= # src/lib/session-paths.ts
# APP_URL= # src/lib/email.ts
# COCKPIT_ALLOW_LEGACY_DAEMON_TOKEN= # src/auth.config.ts
# COCKPIT_DAEMON_TOKEN= # src/auth.config.ts
# COCKPIT_SCRIPTS_DIR= # src/app/api/beacon/transcribe/route.ts
# CRON_SECRET= # src/app/api/health/route.ts
# DATABASE_POOL_URL= # src/lib/db-url.ts
# DEPLOY_KEY_PATH= # src/lib/site-cd-local.ts
# DEV_ROOT= # src/lib/site-cd-local.ts
# EMBEDDINGS_API_KEY= # src/lib/rag/embeddings.ts
# EMBEDDINGS_BASE_URL= # src/lib/rag/embeddings.ts
# EMBEDDINGS_DIM= # src/lib/rag/embeddings.ts
# EMBEDDINGS_MODEL= # src/lib/rag/embeddings.ts
# FEEDBACK_WIDGET_TOKEN= # src/app/layout.tsx
# GITHUB_REPO_OWNER= # src/config/github-owner.ts
# GITHUB_TOKEN= # src/lib/agent-execution/box-workspace.ts
# GOG_BIN= # src/lib/actions/calendar-event.ts
# GOOGLE_CLIENT_ID= # src/auth.ts
# GOOGLE_CLIENT_SECRET= # src/auth.ts
# GROQ_API_KEY= # src/lib/actions/calendar-event.ts
# AI_USAGE_DIR= # src/app/api/ai/fleet/route.ts — where every app on the box writes one line per model call (launch.sh.tmpl sets it)
# AI_APP_ID= # src/db/queries/ai-usage.ts — this app's name in the box's AI usage log (default LOKI)
# GROQ_VISION_MODEL= # src/config/vision-models.ts
# HETZNER_STATE_FILE= # src/config/hetzner.ts
# HOSTED_RUNNER_DRAIN_MS= # src/lib/orchestration/settle-background-work.ts
# LOKI_ALLOW_LEGACY_DAEMON_TOKEN= # src/auth.config.ts
# LOKI_BOX_DEV_ROOT= # src/app/api/projects/[id]/route.ts
# LOKI_BUILD_ENGINE_ANTHROPIC_KEY= # src/config/welcome-changes.ts
# LOKI_DAEMON_TOKEN= # src/auth.config.ts
# LOKI_EXECUTOR= # src/lib/agent-execution/index.ts
# LOKI_FLEET_BRIEF_FETCH= # src/lib/fleet-brief/brief.ts
# LOKI_GATEWAY_DEVICE_KEY_B64= # src/lib/openclaw-gateway.ts
# LOKI_MCP_RESOURCE= # src/config/mcp.ts
# LOKI_MODEL= # src/lib/agent/llm.ts
# LOKI_PARALLEL_DISPATCH= # src/lib/orchestration/parallel-run.ts
# LOKI_PERSONAL_SESSION_KEY= # src/app/api/loki/route.ts
# LOKI_PREVIEWS_ROOT= # src/lib/previews/root.ts
# LOKI_PREVIEW_CODE= # src/lib/previews/access.ts
# LOKI_REGISTER_SITE_SCRIPT= # src/lib/site-cd-local.ts
# LOKI_REPO_ROOT= # src/lib/site-cd-local.ts
# LOKI_SANDBOX_DOCKER_ARGS= # src/lib/agent-execution/sandbox.ts
# LOKI_SANDBOX_OCI_RUNTIME= # src/lib/agent-execution/sandbox.ts
# LOKI_SANDBOX_RUNTIME= # src/lib/agent-execution/sandbox.ts
# LOKI_SITES_BASE_DOMAIN= # src/lib/site-cd.ts
# LOKI_SITES_IP= # src/lib/site-domain.ts
# LOKI_SITES_IPV6= # src/lib/site-domain.ts
# LOKI_SITE_CD_AUTO= # src/lib/site-cd-local.ts
# LOKI_TOOL_LOOP= # src/lib/loki-core.ts
# LOKI_WORKFLOW_OWNER= # src/lib/site-cd.ts
# LOKI_WORKTREES_ROOT= # src/lib/agent-execution/worktree-workspace.ts
# LOKI_WORKTREE_DISPATCH= # src/lib/agent-execution/worktree-workspace.ts
# NEXTAUTH_SECRET= # src/lib/actions/action-link.ts
# NEXTAUTH_URL= # src/lib/email.ts
# NEXT_PUBLIC_APP_DOMAIN= # src/config/brand.ts
# NEXT_PUBLIC_BUILD_SHA= # src/components/shell/AppFooter.tsx
# NEXT_PUBLIC_ECOSYSTEM_BITCOIN_ADDRESS= # src/config/ecosystem.ts
# NEXT_PUBLIC_ECOSYSTEM_LIGHTNING_ADDRESS= # src/config/ecosystem.ts
# NEXT_PUBLIC_LOKI_BRIDGE_URL= # src/lib/event-stream.ts
# OPENCLAW_CONTACTS_PATH= # src/app/api/people/sync/openclaw/route.ts
# OPENCLAW_GATEWAY_TOKEN= # src/lib/openclaw-gateway.ts
# OPENCLAW_GATEWAY_URL= # src/lib/constants.ts
# OPENCLAW_KNOWLEDGE_JSON= # src/app/api/people/sync/openclaw/route.ts
# OPENROUTER_API_KEY= # src/lib/loki-core.ts
# ORANGECAT_BASE_URL= # src/lib/register/orangecat.ts
# ORANGECAT_PAY_URL_PERSONAL= # src/lib/oc-pay.ts
# ORANGECAT_PAY_URL_PRO= # src/lib/oc-pay.ts
# ORANGECAT_PAY_URL_TEAM= # src/lib/oc-pay.ts
# Payments are OFF until this is 1, whatever the URLs above say: set it once the
# company is registered and the OrangeCat passes exist. Until then every paid
# plan's button reserves the plan instead (src/lib/oc-pay.ts).
# LOKI_PAYMENTS_OPEN=
# PRIVATE_ZONE_PIN_HASH= # src/lib/private-zone.ts
# RUNTIME_AVAILABLE= # src/instrumentation.ts
# TELEGRAM_BOT_TOKEN= # src/lib/actions/telegram-send.ts
# Loki's notification bot — every account connects its own Telegram to it in
# Settings → Notifications (one tap, no chat ids). Create it with @BotFather;
# the webhook registers itself on the first "Connect Telegram".
# TELEGRAM_NOTIFY_BOT_TOKEN= # src/lib/telegram/notify-bot.ts
# TELEGRAM_NOTIFY_BOT_USERNAME= # e.g. LokiNoticesBot (src/lib/telegram/notify-bot.ts)
# TRANSCRIBE_LOCAL_AVAILABLE= # src/app/api/beacon/transcribe/route.ts
# X1_CONSUMER_KEY= # src/lib/auth-providers.ts
# X1_CONSUMER_SECRET= # src/lib/auth-providers.ts
# Provider inventory probes on the runner ("off" disables the background PONG prompts) — read by src/lib/agents/provider-inventory.ts
# LOKI_PROVIDER_PROBES=
# XDG_RUNTIME_DIR= # src/lib/agent-execution/sandbox.ts (sealed builds: podman rootless state; set by the sealed drop-in)