airi/server
RainbowBird b3a6d60718
Some checks failed
CI / Detect changes (push) Has been cancelled
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Has been cancelled
Cloudflare Workers / Build - docs (push) Has been cancelled
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Has been cancelled
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Has been cancelled
CI / Build Test (stage-tamagotchi) (push) Has been cancelled
CI / Unit Test (stage-tamagotchi) (push) Has been cancelled
CI / Unit Test (stage-ui-1) (push) Has been cancelled
CI / Lint (push) Has been cancelled
CI / Build Test (stage-web) (push) Has been cancelled
CI / Build Test (ui-playgrounds) (push) Has been cancelled
CI / Build Test (stage-tamagotchi-godot) (push) Has been cancelled
CI / Unit Test (others) (push) Has been cancelled
CI / Unit Test (api-server-1) (push) Has been cancelled
CI / Unit Test (api-server-2) (push) Has been cancelled
CI / Unit Test (stage-ui-2) (push) Has been cancelled
CI / Unit Test (push) Has been cancelled
CI / Type Check (others) (push) Has been cancelled
CI / Type Check (desktop) (push) Has been cancelled
CI / Type Check (web) (push) Has been cancelled
CI / Type Check (push) Has been cancelled
CI / Check Provenance (push) Has been cancelled
Cloudflare Workers / Deploy - stage-web (push) Has been cancelled
feat(api-server): add a script to rotate the LLM router master key (#3545)
## Summary

- Add `server/apps/api/src/scripts/rotate-llm-router-master-key`. It
re-encrypts stored provider keys from `LLM_ROUTER_MASTER_KEY_PREVIOUS`
to `LLM_ROUTER_MASTER_KEY`.
- Document the `LLM_ROUTER_MASTER_KEY` rotation in the API README.
- Document the `BETTER_AUTH_SECRET` rotation in the Auth README. It
needs no code: Better Auth reads `BETTER_AUTH_SECRETS` itself, and
expiring the old JWKS keys makes the jwt plugin create a key under the
new secret.

## Context

The maintainer asked for a script to rotate `LLM_ROUTER_MASTER_KEY` and
`BETTER_AUTH_SECRET`, plus a rotation plan.

Replacing `BETTER_AUTH_SECRET` alone breaks OIDC. The jwt plugin
encrypts the JWKS private keys with the secret, so token signing fails
after the change. Better Auth 1.6.25 supports versioned `secrets` for
this case.

This PR does not change any deployed variable. The rotation itself is a
separate operator step.

## Change map

| Module | Before | After |
| --- | --- | --- |
| API envelope crypto users | AAD helpers were private |
`providerConfigAad` and `STREAM_MODEL_LABEL_FALLBACK` are exported for
the script |
| API rotation script | none | Re-encrypts `config_kv`
`LLM_ROUTER_CONFIG`, `UNSPEECH_UPSTREAM`, and
`user_provider_configs.config` |
| Auth README | no rotation steps | `BETTER_AUTH_SECRETS` plus JWKS key
expiry, no code change |

## Architecture and behavior

```mermaid
sequenceDiagram
  participant Op as Operator
  participant API as API container
  participant PG as Postgres
  participant R as Redis
  Op->>API: rotate-llm-router-master-key --apply
  API->>PG: SELECT config_kv ... FOR UPDATE
  API->>API: decrypt with previous key, encrypt with current key (same AAD)
  API->>PG: UPDATE config_kv
  API->>R: DEL config:<key>, PUBLISH configkv:invalidate
  API->>PG: UPDATE user_provider_configs WHERE id = ? AND config = <old>
  API->>PG: second read-only pass
  API-->>Op: exit 0 / 1 / 2
```

Exit codes of the script: `0` means the old key can be removed. `1`
means some values open with no configured key. `2` means some values
still need the old key.

## Boundaries and risks

| Invariant or boundary | Failure mode | Protection | Evidence or gap |
| --- | --- | --- | --- |
| AAD must match each reader | Re-encrypted key cannot be read | Uses
the model map key, `streaming-tts`, and `providerConfigAad`, the same as
the readers | Unit tests in `rotation.test.ts` |
| Concurrent admin write to ConfigKV | Script overwrites a new config |
Row lock in one transaction | Not run against a real database |
| Concurrent user edit of a provider config | Script overwrites the edit
| Update matches the old ciphertext. A miss counts as a conflict | Not
run against a real database |
| Other ConfigKV fields | Rewrite drops or adds fields | `looseObject`
schemas keep unknown fields and add no defaults | Unit tests check
`headers`, `provider`, and `defaults` |
| Wrong old key | Data is lost | Values that neither key opens stay
unchanged and give exit code 1 | Unit tests |
| JWKS keys after an auth secret rotation | Removing
`BETTER_AUTH_SECRETS` later breaks decryption of new keys | README says
to keep `BETTER_AUTH_SECRETS` | Documented only |

Rotating the auth secret signs out every cookie and bearer session. This
is Better Auth behavior: it signs cookies with the current secret only.
OIDC refresh tokens are stored as SHA-256 hashes and stay valid.

## Verification

Run in an rc Workspace on the first commit of this branch. The second
commit removes the auth script and only changes the Auth README.

- `pnpm -F @proj-airi/api-server typecheck`: pass
- `pnpm -F @proj-airi/api-server exec vitest run`: 995 pass, 5 fail. The
failures are PGlite 5 s timeouts in `mock-db.test.ts` and
`flux-usage-migration.test.ts`. They fail the same way on the merge base
in the same Workspace. `audio-speech-ws/route.test.ts` failed once in
the full run and passed alone.
- `pnpm exec eslint` on the changed files: no errors

Not verified: running the script against a real Postgres and Redis.

## Agent

- Harness: Claude Code
- Model: claude-opus-5-5

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-11-18 13:49:09 +08:00
..
apps feat(api-server): add a script to rotate the LLM router master key (#3545) 2026-11-18 13:49:09 +08:00
dev feat(api,stage-ui): sync Live2D and VRM models to private storage (#2869) 2026-10-14 16:06:15 +08:00
docs/ai/adr feat(analytics): send product events to OpenPanel and PostHog in parallel (#3454) 2026-11-15 03:13:12 +08:00
packages release: v0.15.4 2026-11-13 03:53:10 +07:00
AGENTS.md docs(server): define HTTP response conventions (#3028) 2026-10-19 17:15:33 +08:00
CLAUDE.md docs(AGENTS.md): perform housekeeping on agent-facing docs (#2678) 2026-09-28 01:24:04 +08:00
docker-compose.yaml feat(api,stage-ui): sync Live2D and VRM models to private storage (#2869) 2026-10-14 16:06:15 +08:00
README.md ci(server): deploy a chosen branch to the dev environment (#2918) 2026-10-12 23:13:58 +08:00

AIRI Backend

Project AIRI's hosted backend source lives under this folder. Workspace package names stay stable; the directory groups service source and database ownership while production deployment configuration remains in proj-airi/airi-railway.

Layout

  • apps/api: resource API, business domains, database migrations, and API runtime.
  • apps/auth: standalone Better Auth and OIDC service.
  • packages/auth-shared: Auth-owned database schema and principal contracts.
  • packages/server-sdk-shared: Eventa contracts for the hosted chat WebSocket.
  • dev/caddy: local-only public edge routing for the shared Auth/API origin.
  • docker-compose.yaml: complete local API + Auth + PostgreSQL + Redis + Caddy stack.

Run locally

From the repository root:

pnpm dev:backend

The command uses server/docker-compose.yaml and exposes only Caddy at http://localhost:6112.

Railway deployment

API and Auth are separate long-running Railway services built from the same repository. Keep each service's Root Directory at the repository root. Both Dockerfiles copy workspace manifests and shared packages from that build context. The project-level Railway configuration lives in proj-airi/airi-railway/.railway/railway.ts.

Service Public role Private dependency
Resource API Product and resource API Auth issuer and JWKS
Auth Better Auth and OIDC issuer Resource API deletion endpoint

The Infrastructure as Code file pins each Dockerfile, start command, /readyz healthcheck, and watch patterns. Run the Railway plan from the deployment repository before you apply a change.

Service-to-service contract

Share database, Redis, and observability variables using Railway reference variables rather than copying secret values between services. Configure the two directional private links as follows:

Consumer Variable Value source Purpose
Resource API AUTH_SERVER_URL Auth's canonical public issuer URL JWT issuer, audience, and public JWKS identity
Resource API AUTH_SERVER_INTERNAL_URL Auth's Railway private domain Private JWKS fetch; it does not change issuer validation
Auth PUBLIC_URL Auth's canonical public issuer URL Better Auth and OIDC issuer URL; must equal API AUTH_SERVER_URL
Auth RESOURCE_SERVER_URL API's Railway private domain Private call before deleting a user's business data

Set RATE_LIMIT_TRUSTED_PROXY=railway only for services directly receiving Railway proxy traffic. Keep /internal/* private: Auth calls the API over its private domain, and public routing must not expose the API's internal Auth routes.

The API remains the shared database migration owner. Do not add a Railway pre-deploy migration command to Auth, and do not make Auth startup run shared migrations. After either service deploys, Railway must receive 200 from that service's /readyz; deployment success alone is not sufficient evidence that the service can reach its required dependencies.

Dev environment

The Railway dev environment is one shared slot. It has fixed public URLs, so OAuth callbacks and payment webhooks stay registered when the code changes.

Work on your own branch in this repository. Do not merge into a shared test branch. The server-dev branch is no longer a deploy source.

To test a branch, run the Deploy to server-dev workflow:

gh workflow run deploy-server-dev.yml -f branch=<branch> -f reset_database=true

The workflow does these steps in order:

  1. It resets the dev Neon branch to its parent branch, production. The dev database then holds a copy of the production schema and data.
  2. It sets the source branch of the Railway ts-api and auth-server services and deploys them. The API applies its migrations on startup.
  3. It starts the Cloudflare Workers (server-dev) workflow on the same branch.

Railway deploys each later push to the branch. The frontend does not follow pushes. Run the workflow again with reset_database=false to build it again.

The branch must be in this repository. Railway cannot deploy a branch of a fork.

The reset removes all data that the previous branch wrote. This includes dev accounts that are not in production. Set reset_database=false only when the database already has the migrations of the branch and no others. The Drizzle migrator applies only migrations that are newer than the last applied migration. If the database already has a newer migration from a different branch, the migrator skips the older migrations of the new branch and reports no error.

The reset does not clear Redis. Cached values from the previous branch can stay until they expire.

The workflow needs this repository configuration:

Name Kind Value
RAILWAY_DEV_TOKEN Secret Railway project token for the dev environment
NEON_API_KEY Secret Neon API key for the project that holds the dev database
NEON_PROJECT_ID Variable Neon project ID
NEON_SERVER_DEV_BRANCH Variable Name of the Neon branch that the dev DATABASE_URL points to

The dev Neon branch is serverlize-dev. Its parent is production, so the Neon API key can also read the production branch. Keep the key in the secret only.

Package boundaries

Frontend applications remain under apps/. Hosted-backend packages that define a resource API protocol can live under server/packages/, even when a frontend consumes their generated contract.

Cross-runtime server SDK and protocol packages remain under packages/ because Web, Electron, plugins, and independent services consume them.

Production Caddy routing, OpenTelemetry Collector configuration, observability storage, and Grafana dashboards live in proj-airi/airi-railway so deployment topology is not duplicated in the application repository.