|
Some checks are pending
CI / Detect changes (push) Waiting to run
CI / Lint (push) Blocked by required conditions
CI / Build Test (stage-web) (push) Blocked by required conditions
CI / Build Test (stage-tamagotchi) (push) Blocked by required conditions
CI / Build Test (ui-playgrounds) (push) Blocked by required conditions
CI / Build Test (stage-tamagotchi-godot) (push) Blocked by required conditions
CI / Unit Test (others) (push) Blocked by required conditions
CI / Unit Test (api-server-1) (push) Blocked by required conditions
CI / Unit Test (api-server-2) (push) Blocked by required conditions
CI / Unit Test (stage-tamagotchi) (push) Blocked by required conditions
CI / Unit Test (stage-ui-1) (push) Blocked by required conditions
CI / Unit Test (stage-ui-2) (push) Blocked by required conditions
CI / Unit Test (push) Blocked by required conditions
CI / Type Check (others) (push) Blocked by required conditions
CI / Type Check (desktop) (push) Blocked by required conditions
CI / Type Check (web) (push) Blocked by required conditions
CI / Type Check (push) Blocked by required conditions
CI / Check Provenance (push) Blocked by required conditions
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Build - docs (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
Release Tamagotchi / Plan Updates (push) Waiting to run
Release Tamagotchi / Build (push) Blocked by required conditions
Release Tamagotchi / Build-1 (push) Blocked by required conditions
Release Tamagotchi / Build-2 (push) Blocked by required conditions
Release Tamagotchi / Build-3 (push) Blocked by required conditions
Release Tamagotchi / Build-4 (push) Blocked by required conditions
Release Tamagotchi / Publish Bundle (push) Blocked by required conditions
Release Tamagotchi / Promote Canary to Stable (push) Blocked by required conditions
Release Tamagotchi / Publish GitCode Release Mirror (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-1 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-2 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-3 (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
## Summary
This is **PR 1 of 4** for migrating Web authentication to a same-origin
BFF with Better Auth `HttpOnly` session cookies and moving Electron
token management to the main process.
This PR adds two strictly additive backend boundaries without changing
any existing Bearer JWT or OIDC flows:
1. **`server/apps/auth`**:
- Adds private `GET /internal/auth/session` (outside `/api/auth/*` rate
limiting and blocked at the public edge by `/internal/* -> 404`) so
`server/apps/api` can resolve Better Auth session cookies over
`AUTH_SERVER_INTERNAL_URL` without importing Better Auth or holding
`BETTER_AUTH_SECRET`.
- Adds cookie-only `POST /api/auth/session-jwt` to mint a 5-minute
stateless JWT (using Better Auth's `auth.api.signJWT` and existing JWKS
key set, matching `iss`, `aud`, `sub`, and `sid`) for Bearer-only
upstreams such as `cloud.airi.build`.
2. **`server/apps/api`**:
- Extends `resolveRequestAuth` to resolve `better-auth.session_token`
(and `__Secure-better-auth.session_token`) cookies via
`AUTH_SERVER_INTERNAL_URL/internal/auth/session` when no `Authorization:
Bearer` header is present.
- Enforces CSRF origin checks on cookie-authenticated mutations and
CSWSH trusted-origin checks on cookie-authenticated WebSocket upgrades
(`/ws/chat`, `/ws/v2/chat`, `/api/v1/audio/speech/ws`).
- Supports pre-authenticated `/ws/v2/chat` upgrades on open while
preserving anonymous upgrade + `chat:authenticate` for native clients.
3. **ADR**: Adds
`server/docs/ai/adr/2026-12-02-cookie-session-and-session-jwt-boundary.md`.
This PR is independent and based on `origin/main` (`4554c786a`).
## Change map
| Module | Before | After | Description |
| --- | --- | --- | --- |
| Auth routes (`server/apps/auth/src/routes.ts`, `auth.ts`) | Only
public `/api/auth/*` routes and OIDC token exchange exist. | Adds
private `GET /internal/auth/session` and cookie-only `POST
/api/auth/session-jwt` backed by `auth.api.signJWT`. | Keeps Better Auth
and its secret inside `server/apps/auth` while enabling same-origin
cookie BFFs. |
| API request auth (`server/apps/api/src/libs/request-auth.ts`,
`middlewares/auth.ts`, `audio-transcription-stream/route.ts`) | Accepts
`Authorization: Bearer` JWTs only. | Keeps Bearer priority, adds
internal cookie session resolution with CSRF/CSWSH origin validation and
ban re-checks. | Enables cookie-authenticated HTTP and streaming ASR
requests without duplicating Better Auth in `api-server`. |
| API WebSocket auth (`server/apps/api/src/app.ts`, `libs/ws-auth.ts`,
`routes/chat-ws/v2/index.ts`) | `/ws/chat` and `/api/v1/audio/speech/ws`
require `?token=`. `/ws/v2/chat` always requires `chat:authenticate`. |
Accepts trusted-origin session cookies on upgrade and pre-authenticates
`/ws/v2/chat` on open while keeping `?token=` and `chat:authenticate`
unchanged. | Removes browser URL query tokens when Web moves behind a
same-origin BFF. |
## Architecture and behavior
```mermaid
sequenceDiagram
participant B as Browser / Web BFF
participant API as server/apps/api
participant AUTH as server/apps/auth
participant DB as PostgreSQL
B->>API: HTTP / WS upgrade with Cookie + trusted Origin
API->>API: Validate CSRF / CSWSH origin rules
API->>AUTH: GET /internal/auth/session (Cookie only)
AUTH->>DB: Verify active session and ban state
AUTH-->>API: 200 { userId, sessionId, expiresAt, ... }
API->>DB: Load user row and re-check ban state
API-->>B: Authenticated response or pre-authenticated WS peer
```
## Boundaries and risks
| Invariant or boundary | Failure mode | Protection | Evidence or gap |
| --- | --- | --- | --- |
| Better Auth isolation | `api-server` leaks `BETTER_AUTH_SECRET` or
imports Better Auth | Cookie validation stays in `auth-server` behind
private `GET /internal/auth/session` | Covered by
`routes-cookie-session.test.ts` and `request-auth.test.ts` |
| Public edge isolation for `/internal/auth/session` | Public caller
reaches internal route | Edge proxy blocks `/internal/*` with `404`
(same contract as `api-server`'s `/internal/auth/*`) | Existing Caddy
edge rule in `server/dev/caddy/Caddyfile`; Railway edge config not
modified in this PR |
| Cookie-only isolation on `/session-jwt` and `/internal/auth/session` |
Bearer JWT tries to mint new JWTs or resolve internal session |
`copyCookieHeaderOnly` strips `Authorization` before calling
`auth.api.getSession` | Covered by `routes-cookie-session.test.ts` |
| CSRF on cookie mutations and `/session-jwt` | Cross-site form or
script triggers state-changing call | Rejects `Sec-Fetch-Site:
cross-site` and untrusted `Origin` / `Referer` headers | Covered by
`routes-cookie-session.test.ts` and `request-auth.test.ts` |
| CSWSH on cookie WebSocket upgrades | Cross-site page opens WS using
browser cookie | `requireTrustedOriginForCookie: true` requires a
present, trusted `Origin` header | Covered by `request-auth.test.ts` |
| Transient internal auth failure on WS upgrade | Temporary 5xx closes
WS as permanent 4001 | `resolveCookieSession` throws on non-401
failures; WS upgrades close with retryable `1011`
(`createRetryableWsEvents`) | Covered by `request-auth.test.ts` |
| Existing Bearer / OIDC clients | Regression on Electron, Capacitor, or
current Web | Bearer path runs first and never invokes cookie lookup |
Covered by existing `request-auth.test.ts` and
`routes-oidc-token-auth.test.ts` |
## Verification
### Static checks
```text
pnpm exec eslint server/docs/ai/adr/2026-12-02-cookie-session-and-session-jwt-boundary.md server/apps/auth/src/auth.ts server/apps/auth/src/routes.ts server/apps/auth/src/tests/routes-cookie-session.test.ts server/apps/api/src/app.ts server/apps/api/src/middlewares/auth.ts server/apps/api/src/libs/request-auth.ts server/apps/api/src/libs/ws-auth.ts server/apps/api/src/libs/tests/request-auth.test.ts server/apps/api/src/routes/audio-transcription-stream/route.ts server/apps/api/src/routes/chat-ws/v2/index.ts server/apps/api/src/routes/chat-ws/v2/index.test.ts
# Passed (0 errors)
pnpm -F @proj-airi/auth-server typecheck
pnpm -F @proj-airi/api-server typecheck
# Passed (0 errors)
```
### Focused tests
```text
pnpm -F @proj-airi/auth-server exec vitest run src/tests/routes-cookie-session.test.ts src/tests/routes-oidc-token-auth.test.ts
# Passed: 2 files, 13 tests (plus 196 existing auth-server tests passed on the preceding full run)
pnpm -F @proj-airi/api-server exec vitest run src/libs/tests/request-auth.test.ts src/libs/tests/ws-auth.test.ts src/routes/chat-ws/v2/ src/routes/audio-transcription-stream/route.test.ts
# Passed: 7 files, 33 tests
```
### Not verified locally
- Full monorepo `pnpm typecheck` and `pnpm test:run` (left for GitHub
Actions CI).
- Live Railway private-network (`AUTH_SERVER_INTERNAL_URL`) deployment
verification (verified after merge).
|
||
|---|---|---|
| .. | ||
| apps | ||
| dev | ||
| docs/ai/adr | ||
| packages | ||
| AGENTS.md | ||
| CLAUDE.md | ||
| docker-compose.yaml | ||
| README.md | ||
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:
- It resets the dev Neon branch to its parent branch,
production. The dev database then holds a copy of the production schema and data. - It sets the source branch of the Railway
ts-apiandauth-serverservices and deploys them. The API applies its migrations on startup. - 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.