--- name: letmepost-selfhost-dev description: Use when editing letmepost self-host. Worktree, test DB. version: 1.0.0 author: HamaratLabs license: MIT --- # letmepost self-host development Repo `/letmepost-selfhost`, a local branch (upstream letmepost + local patches). Work in a worktree under `.worktrees/`; never touch the running instance (dashboard ``, API ``, worker), its `apps/api/.env` or its DATABASE_URL. ## Worktree setup - `node_modules`: APFS-clone from the main checkout: `cp -cR ../../node_modules ./node_modules` and the same for every `apps/*/node_modules`, `packages/*/node_modules` (pnpm symlinks are relative, so clones resolve inside the worktree). No `pnpm install` needed. - The worktree has no `apps/api/.env`; keep it that way (vitest + server load `.env` via dotenv). - Tests need built `@letmepost/schemas` and `apps/api/src/routes/openapi.json` → run via `pnpm turbo run test --filter=@letmepost/api` (or `node scripts/copy-openapi.mjs` once, then `npx vitest run`). ## Throwaway infra (never the real DB) - Postgres: `initdb -D /pgdata -U lmp --auth=trust`, start with `LC_ALL=en_US.UTF-8` (else "postmaster became multithreaded"), unusual port (e.g. 58432), `createdb lmp_..._test`. - Redis: `redis-server --port 56379 --save '' --appendonly no --daemonize yes`. - Test env: `DATABASE_URL` + `TEST_DATABASE_URL` = scratch DB, `REDIS_URL`, `BETTER_AUTH_SECRET`, `KEK_MASTER` (CI values work). Many test files import `app.ts`, which needs DATABASE_URL at import. - Running the API in the worktree: also `CORS_ORIGINS=` (allowlist is only the local dashboard origin + CORS_ORIGINS) and `PUBLIC_API_BASE_URL` (OAuth redirect URIs use it, not BETTER_AUTH_URL). - Browser QA without typing a password: sign up via curl into the scratch DB, inject `better-auth.session_token` with CDP `Network.setCookie`. framer-motion pages stay blurred until `Page.bringToFront`. ## Adding a platform: everything that must change `index.ts` registration is NOT enough. Touch: schemas `Platform`, `PLATFORM_STATE`, `TargetOptions`; `_shared/scopes.ts`, `_shared/dispatch.ts` (preflight + publish), `_shared/api-versions.ts`, `_shared/target-options.ts` (options mapping for route + worker), `routes/accounts.ts` publicView, `routes/posts.ts` + `queue/publish-processor.ts` if async (`ASYNC_STATUS_PLATFORMS`), `queue/tiktok-poll-processor.ts` (platform-dispatching poller), dashboard `lib/accounts.ts` + `platform-icons.tsx` + `globals.css --brand-*`, sdk-ts types, hand-maintained `docs/api-reference/openapi.json`, docs page + `docs.json` nav + platform-credentials + environment, `.env.example`. DB `platform` enum already lists youtube/tiktok. ## Running instance ops (config-only changes) - Private-network mode: if you expose API and dashboard beyond localhost, keep them on a private network only (never public), with the user's approval. Point the public URL variables (PUBLIC_API_BASE_URL/BETTER_AUTH_URL, DASHBOARD_URL, TRUSTED_ORIGINS/CORS_ORIGINS) at the new origins; dashboard `NEXT_PUBLIC_API_URL` is baked at `next build` → rebuild after changing it. Auth cookies follow the configured base URL, so the old localhost panel stops working for auth after the switch. - Restart without `lmp.sh down`: down runs `redis-cli shutdown nosave` and Redis has no persistence → delayed BullMQ jobs (refresh-token, billing) are lost. Stop only dashboard/worker/api via their pid files (pkill -P + kill), then `lmp.sh up` (background) skips the live infra. - Changes to the running instance's `.env` are made only with the user's approval; if your agent runtime asks for approval, wait for it and do not look for another way around it. Never patch/read .env with tools that echo context lines. - Client API key files: validate shape with `jq '.apiKey|test("^lmp_")'`, never print the key. A key file can silently hold a literal placeholder (`***`) after a bad copy. ## Cloud VM deployment (tried, then retired in favour of local + object storage) - Build on your own machine and ship artifacts; on a small VM with an egress quota only run `pnpm install --prod`. Keep env in `/etc//api.env` and symlink it into each release. - Close public signup via `DISABLE_SIGNUP=true` (auth.ts) plus a reverse-proxy 403. - Destructive commands on the remote server (recursive delete, `sudo`, `systemctl stop|restart|disable`) need the user's approval, including when run through `gcloud compute ssh --command` or a copied script. - `caddy validate` as root creates log files root-owned → chown /var/log/caddy afterwards or reload fails. Global options block must be the first non-comment line (no blank line before `{`). - Headless screenshot: framer-motion pages can come out blank with Chrome `--screenshot`; use raw CDP via Node (`--remote-debugging-port`, wait ~7 s real time, Page.captureScreenshot). - Cost watch: check the provider's current network pricing; an in-use external IPv4 may only be free for a few hours per month. ## R2 media store - Point S3 at an R2 bucket (`AWS_REGION=auto`, path-style automatic via `S3_ENDPOINT`), public base = an R2 custom domain. SDK default CRC32 checksums + lib-storage multipart work on R2 unchanged; letmepost never presigns. - Credentials: the user provides R2 keys; keep them in the OS keychain or a 0600 file and use them only inside scripts; never echo or print them. - Range requests (206) work against R2 through a custom domain, so media can be read in parts. - Upload brakes: brake flag in Redis, guard = a maintenance-queue job. Route tests that sum the `media` table must measure a baseline (table is bucket-wide; scratch DBs keep e2e rows). - Keep `.env.bak*` in `.gitignore` (also `.git/info/exclude`). - Redis is persistence-less: maintenance schedules live in `queue/maintenance-schedules.ts` and are re-registered on every reconnect; a marker key tells a wipe from a blip. Empty-but-reachable Redis + guard configured → uploads 503 `media.guard_pending` until the guard has measured once; log a distinct error after 3 guard failures in a row. - Upload route S3 tests without a bucket: `tests/support/fake-s3.ts` (real `S3Client` with an in-memory requestHandler) + test setters for the client and max upload size. Feed the request body in small chunks with `setImmediate` between them (Readable.toWeb + `duplex: "half"`); one big Buffer trips busboy's limit before the S3 upload starts and the abort path never runs. - Live worker runs as `node --import ./instrument.mjs dist/queue/worker.js` from the main checkout; a worktree smoke worker is `node dist/queue/worker.js` — kill only by your own pid file. ## Pitfalls - Scratch Postgres may fail "could not bind ... Address already in use" on any port when passed via `pg_ctl -o`; put `port`, `listen_addresses` and `unix_socket_directories=` in `postgresql.conf` instead. - Bash helpers with `set -euo pipefail`: `grep` for an absent key exits 1 and kills the script silently; wrap as `{ grep … || true; }`. - Google resumable upload answers 308 "Resume Incomplete"; fetch with `redirect: "manual"`. - `guardedFetch` blocks private IPs and has a 30 s total timeout — read own media-store URLs directly (Range) instead. - `drizzle-kit generate --name x` works offline; drizzle.config does not load `.env`, so `db:migrate` needs DATABASE_URL exported; `pnpm --filter @letmepost/api migrate` (dist/db/migrate.js) does load `.env`. - Docs check: `python3 docs/.scripts/validate.py`.