diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2100ea0..e2334f1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,14 +20,15 @@ env: jobs: commit-messages: name: Commit messages - if: github.event_name == 'pull_request' + # Runs on PRs and on pushes to main: a required PR check that is skipped reports + # success without linting anything, so main must be linted too. runs-on: ubuntu-latest timeout-minutes: 10 steps: - name: Checkout uses: actions/checkout@v4 with: - # Full history so every commit of the PR can be inspected. + # Full history so the whole commit range is available. fetch-depth: 0 - name: Set up Node.js @@ -38,11 +39,19 @@ jobs: - name: Lint commit messages and PR title env: PR_TITLE: ${{ github.event.pull_request.title }} + BASE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} + HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} run: | - node scripts/check-commit-messages.mjs \ - "${{ github.event.pull_request.base.sha }}" \ - "${{ github.event.pull_request.head.sha }}" \ - "$PR_TITLE" + # A brand-new branch can push with an all-zero "before" sha; fall back to the + # default range instead of failing the range check. + if [ "$BASE_SHA" = "0000000000000000000000000000000000000000" ]; then + BASE_SHA="" + fi + if [ -z "$BASE_SHA" ] || [ -z "$HEAD_SHA" ]; then + node scripts/check-commit-messages.mjs + else + node scripts/check-commit-messages.mjs "$BASE_SHA" "$HEAD_SHA" "${PR_TITLE:-}" + fi quality: # Job name is a required branch-protection status check: do not rename it. @@ -72,6 +81,10 @@ jobs: - name: Unit tests run: pnpm test + - name: Documentation drift + # Fails while SPEC.md/API.md and the code disagree (env vars, routes, settings). + run: pnpm check:docs + build-and-e2e: name: Build & e2e runs-on: ubuntu-latest @@ -96,14 +109,47 @@ jobs: - name: Build server and dashboard run: pnpm build + - name: Smoke-test the built server + # The e2e suite boots src/index.ts through tsx; this proves dist/ actually runs. + run: | + DATA_DIR="$(mktemp -d)" + PORT=20198 HOST=127.0.0.1 LOG_LEVEL=warn NODE_ENV=production \ + node dist/src/index.js > "$RUNNER_TEMP/smoke.log" 2>&1 & + SERVER_PID=$! + READY=0 + for _ in $(seq 1 100); do + if curl -fsS "http://127.0.0.1:20198/health" -o "$RUNNER_TEMP/health.json"; then READY=1; break; fi + if ! kill -0 "$SERVER_PID" 2>/dev/null; then + echo "server exited during boot"; cat "$RUNNER_TEMP/smoke.log"; exit 1 + fi + sleep 0.2 + done + if [ "$READY" != "1" ]; then echo "server never became healthy"; cat "$RUNNER_TEMP/smoke.log"; exit 1; fi + grep -q '"status":"ok"' "$RUNNER_TEMP/health.json" + DASHBOARD_STATUS="$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:20198/dashboard)" + if [ "$DASHBOARD_STATUS" != "302" ]; then echo "/dashboard → $DASHBOARD_STATUS (expected 302)"; exit 1; fi + DASHBOARD_LOCATION="$(curl -s -o /dev/null -w '%{redirect_url}' http://127.0.0.1:20198/dashboard)" + if [ "$DASHBOARD_LOCATION" != "http://127.0.0.1:20198/login" ]; then + echo "/dashboard redirect → $DASHBOARD_LOCATION (expected /login)"; exit 1 + fi + kill -TERM "$SERVER_PID" + for _ in $(seq 1 50); do kill -0 "$SERVER_PID" 2>/dev/null || break; sleep 0.2; done + if kill -0 "$SERVER_PID" 2>/dev/null; then echo "server did not exit on SIGTERM"; exit 1; fi + wait "$SERVER_PID" || true + echo "dist smoke test passed (health 200, /dashboard 302 → /login, clean SIGTERM)" + cat "$RUNNER_TEMP/smoke.log" + - name: End-to-end acceptance suite run: pnpm test:e2e - name: Upload build artifacts - if: github.event_name == 'push' + # Always upload so a failing e2e run still leaves the built dist/ for debugging; + # a missing artifact is an error instead of a silent no-op. + if: always() uses: actions/upload-artifact@v4 with: name: opencode-router-build + if-no-files-found: error path: | dist/ web/dist/ diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..2bd5a0a --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +22 diff --git a/AGENTS.md b/AGENTS.md index 4e572f1..d780ca8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,19 +37,26 @@ React 19 + Tailwind CSS 4. Default port **20125**. ## Commands ```bash -pnpm install # install dependencies +pnpm install # install dependencies (Node 22+, pnpm 10+; see .nvmrc) pnpm dev # API with watch (port 20125, serves web/dist) pnpm dev:web # dashboard dev server (proxies /admin and /v1) -pnpm typecheck # server + web type checks +pnpm typecheck # server + web + tests/scripts type checks (tsconfig.test.json) pnpm test # vitest unit suite +pnpm check:docs # doc-drift check: env vars, routes, settings vs docs/SPEC.md + docs/API.md pnpm test:e2e # full acceptance: real server + deterministic mock upstreams -pnpm test:live # smoke test against a real provider (skips on 429) +pnpm test:live # smoke test against a real provider (skips on upstream 429) pnpm build # tsc -> dist/ and vite -> web/dist/ pnpm start # run the compiled server (node dist/src/index.js) -pnpm exec tsx scripts/screenshots.ts # headless Chrome UI check + screenshots (skips if Chrome absent) +pnpm exec tsx scripts/screenshots.ts --strict # headless Chrome UI check; fails (not SKIP) without Chrome ``` -Before opening a PR run at least: `pnpm typecheck && pnpm test && pnpm build && pnpm test:e2e`. +Script env knobs: `E2E_PORT`/`E2E_MOCK_A_PORT`/`E2E_MOCK_B_PORT` (e2e, defaults 20197/20196/20195), +`MOCK_PORT`/`MOCK_NAME`/`MOCK_KEY` (mock upstream), `LIVE_PORT`/`LIVE_UPSTREAM`/`LIVE_KEY`/`LIVE_MODEL`/ +`LIVE_VISION_MODEL` (live check), `CHROME_PATH` (screenshots). `pnpm lint:commits` runs the commit-message +linter against `origin/main..HEAD`. + +Before opening a PR run at least: +`pnpm typecheck && pnpm test && pnpm check:docs && pnpm build && pnpm test:e2e`. ## Layout @@ -63,8 +70,8 @@ Before opening a PR run at least: `pnpm typecheck && pnpm test && pnpm build && | `src/gateway/` | `/v1/*` auth, rotation, pass-through proxy, `/v1/models` | | `src/admin/` | `/admin/api/*` (auth, providers, models, keys, logs, settings), scheduler | | `web/` | React 19 + Tailwind dashboard (Vite root, builds to `web/dist`) | -| `scripts/` | e2e, live check, mock upstream, commit-message linter, screenshots | -| `tests/` | vitest unit tests | +| `scripts/` | e2e, live check, mock upstream, commit-message linter, doc-drift checker, screenshots | +| `tests/` | vitest unit tests (incl. `tooling.test.ts` for the repo scripts) | | `docs/` | `SPEC.md` (contract), `API.md` (gateway reference), screenshots | | `.github/workflows/` | CI | @@ -89,8 +96,13 @@ Before opening a PR run at least: `pnpm typecheck && pnpm test && pnpm build && ``` Allowed types: `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`. -Scopes are optional (examples: `gateway`, `admin`, `web`, `db`, `ci`, `docs`, `repo`). -The PR title is linted too because squash merges use it verbatim. +Scopes are optional (examples: `gateway`, `admin`, `web`, `db`, `ci`, `docs`, `repo`) and must match +`[a-z0-9][a-z0-9._/-]*`. The description must start with a lowercase letter (Unicode-aware: `Ä`, `修正` and +emoji-leading descriptions are rejected), must not end with a period and the whole subject is ≤ 100 chars. +Real merge commits are excluded via `git log --no-merges`; `fixup!`/`squash!`/`amend!` and the tooling's own +`Revert "…"`/`Initial commit` subjects are skipped. The PR title is linted too because squash merges use it +verbatim, and CI lints pushes to `main` as well as PRs. An explicitly supplied base/head range that contains +zero commits fails instead of passing an empty check. ## PR workflow @@ -102,5 +114,7 @@ the required checks (`Commit messages`, `Lint & test`, `Build & e2e`), then squa - Editing `dist/`, `web/dist/`, `data/` or `tmp/` (generated, git-ignored). - Committing `.env`, database files, provider keys or dashboard session secrets. - Bypassing the repository layer with ad-hoc SQL outside `src/admin`-level read helpers. +- Weakening the enforcement scripts to make them pass: `pnpm check:docs`, the commit-message linter and the + e2e single-log-row assertions must report real problems. Fix the docs/code, not the checker. - Adding Chinese/Japanese/Vietnamese comments or UI copy to code that is otherwise English. - Force-pushing `main` (blocked by protection) or disabling CI checks to merge. \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2401274..fca8253 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,7 +7,8 @@ coding standards, the commit-message convention enforced by CI, and the pull-req Requirements: -- Node.js **≥ 22.13** (the gateway uses the built-in `node:sqlite` module without an experimental flag) +- Node.js **≥ 22.13** (the gateway uses the built-in `node:sqlite` module without an experimental flag; + `.nvmrc` pins the CI major, so `nvm use` is enough) - pnpm **10+** (the repo pins `pnpm@10.18.0` through `packageManager`; CI uses pnpm 10) - A reachable OpenAI/Anthropic-compatible provider for manual testing (optional — the e2e suite ships deterministic mock upstreams) @@ -62,9 +63,9 @@ on a pull request **and the pull request title** must match: | Part | Rules | | --- | --- | | `type` | one of `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert` | -| `scope` | optional; short noun such as `gateway`, `admin`, `web`, `db`, `ci`, `docs`, `repo` | +| `scope` | optional; matches `[a-z0-9][a-z0-9._/-]*`, short noun such as `gateway`, `admin`, `web`, `db`, `ci`, `docs`, `repo` | | `!` | optional; marks a breaking change (add a `BREAKING CHANGE:` footer) | -| `description` | imperative, lowercase, no trailing period, whole subject ≤ 100 chars | +| `description` | starts with a lowercase letter (Unicode-aware), imperative, no trailing period, whole subject ≤ 100 chars | Valid examples: @@ -82,12 +83,17 @@ Invalid examples (CI will reject): ``` update stuff Fix: Some Thing. +feat: ✨ add sparkles # must start with a lowercase letter +feat: 修正 bug # caseless/uppercase first letters are rejected feat: Add a very long subject ... feature(gateway): unsupported type ``` -Merge commits created by GitHub are skipped by the linter; squash merges use the PR title, -which is why the title must follow the same format. +Real merge commits are excluded via `git log --no-merges`; a normal commit whose subject merely starts with +`Merge ` is still linted. `fixup!`/`squash!`/`amend!` and `Revert "…"`/`Initial commit` subjects are skipped +because tooling generates them. The linter fails when an explicitly supplied base/head range contains zero +commits (an empty check must not pass), and CI lints pushes to `main` in addition to pull requests. Squash +merges use the PR title, which is why the title must follow the same format. Optional local helper: @@ -107,6 +113,7 @@ pull request that passes the required checks. ```bash pnpm typecheck pnpm test + pnpm check:docs pnpm build pnpm test:e2e ``` @@ -116,13 +123,14 @@ pull request that passes the required checks. gh pr create --fill ``` 5. Wait for CI to go green. Required checks: - - **Commit messages** — Conventional Commits validation (commits + PR title) - - **Lint & test** — typecheck and unit tests - - **Build & e2e** — production build plus the end-to-end acceptance suite + - **Commit messages** — Conventional Commits validation (commits + PR title; also linted on pushes to `main`) + - **Lint & test** — typecheck, unit tests and the `pnpm check:docs` drift check + - **Build & e2e** — production build, `dist/` boot smoke test and the end-to-end acceptance suite 6. Squash-merge the PR (the squashed commit message is the PR title). Delete the branch. A PR that changes the gateway contract, the database schema or the admin API must also -update `docs/SPEC.md` and call the change out in the PR description. +update `docs/SPEC.md` and call the change out in the PR description. New env vars, routes or +`DEFAULT_SETTINGS` keys must be documented or `pnpm check:docs` fails — fix the docs, never the checker. ## Reporting bugs / requesting features diff --git a/README.md b/README.md index 533f771..d8ec1a0 100644 --- a/README.md +++ b/README.md @@ -40,12 +40,16 @@ client (OpenAI SDK / Anthropic SDK / curl) ──▶ OpenCode Router :20125 ─ `stream_options` normalization applies, and streamed frames keep the upstream bytes (invalid UTF-8 and a leading BOM included). - **Provider rotation**: round-robin (default), `priority` or `random` ordering with automatic failover on - retryable upstream errors (`408`/`409`/`425`/`429`/`5xx`), per-provider cooldowns, and per-attempt logging. -- **Gateway API keys are mandatory** (`okr-…`, accepted as `Authorization: Bearer` or `x-api-key`). + retryable upstream errors (`408`/`409`/`425`/`429`/`5xx`, network errors and timeouts), per-provider + cooldowns, and per-attempt logging (timed-out attempts included). +- **Gateway API keys are mandatory** (`okr-…`, accepted as `Authorization: Bearer` or `x-api-key`; other + `Authorization` schemes are rejected). Rotate a key without changing its id or counters. - **Model registry**: synced from any single provider (all providers expose the same catalogue) or added manually. Empty until you configure a provider. -- **Dashboard** (login required, default password `123456`): Overview with live traffic, API Keys, Providers, - Models, Logs, Settings. Dark/light, Inter, Lucide, glassmorphism. +- **Dashboard** (login required, default password `123456`): Overview with live traffic, API Keys (create, + enable/disable, rotate, revoke), Providers (test, sync, cooldown state), Models (filters, bulk actions), + Logs (filters, live tail, export), Settings (routing, retention, sessions, secret rotation, audit). + Dark/light, Inter, Lucide, glassmorphism. - **SQLite** storage via Node's built-in `node:sqlite` — no native build step. ## Requirements @@ -91,8 +95,8 @@ enabled provider, one enabled model *and* one API key exist (the dashboard shows [.env.example](.env.example) is the same list as a copy-paste template. -Runtime settings (rotation strategy, retry budget, provider cooldown, request timeout, auto model sync interval, -log retention, …) live in **Dashboard → Settings**. +Runtime settings (rotation strategy, retry budget, provider cooldown, request timeout, SSE idle timeout, +auto model sync interval, log retention, audit retention, …) live in **Dashboard → Settings**. ## Using the gateway @@ -143,9 +147,11 @@ curl http://127.0.0.1:20125/v1/messages \ curl http://127.0.0.1:20125/v1/models -H "Authorization: Bearer okr-..." ``` -Every `/v1/*` response carries `x-opencode-router-request-id`. Responses served by an upstream provider also -carry `x-opencode-router-provider` (winning provider id) and `x-opencode-router-attempts`; errors raised -before an attempt (auth, routing, validation) carry the request id only. +Every `/v1/*` response carries `x-opencode-router-request-id`. Responses served (or failed) by an upstream +provider also carry `x-opencode-router-provider`, `x-opencode-router-name` and `x-opencode-router-attempts`; +errors raised before an attempt (auth, routing, validation) carry the request id only. A `429 +all_providers_rate_limited` answer includes `Retry-After` and `x-opencode-router-cooldown-until`, and relayed +upstream headers (`retry-after`, `x-ratelimit-*`, `openai-*`, `anthropic-*`, `x-stainless-*`) pass through. See [docs/API.md](docs/API.md) for the full gateway reference and [docs/SPEC.md](docs/SPEC.md) for the dashboard/admin API contract. @@ -171,25 +177,29 @@ scripts/e2e.ts full end-to-end acceptance run ## Verification ```bash -pnpm typecheck # server + dashboard type checks -pnpm test # vitest unit suite (crypto, repos, stats, SSE, normalization) +pnpm typecheck # server + dashboard + tests/scripts type checks +pnpm test # vitest unit suite (crypto, repos, stats, SSE, normalization, tooling) +pnpm check:docs # doc-drift checker (env vars, routes, settings vs docs/SPEC.md + docs/API.md) pnpm test:e2e # boots a real server + mock providers; full acceptance suite -pnpm test:live # smoke-tests a real provider (skips when its quota is exhausted) +pnpm test:live # smoke-tests a real provider (skips when it answers 429) pnpm build # dist/ + web/dist/ -pnpm exec tsx scripts/screenshots.ts # headless Chrome UI check + PNG screenshots (macOS; SKIPs without Chrome) +pnpm exec tsx scripts/screenshots.ts --strict # headless Chrome UI check + PNG screenshots ``` -`pnpm test:e2e` is self-contained: it starts two deterministic mock upstreams that mimic the reference -provider (OpenAI + Anthropic surfaces, streaming, tools, vision, reasoning, injectable 429s) and verifies -routing, rotation, failover, logging, admin APIs, dashboard routing and the built dashboard shell. +`pnpm test:e2e` is self-contained: it starts two deterministic mock upstreams (OpenAI + Anthropic surfaces, +streaming, tools, vision, reasoning, injectable 429/5xx/delays) and verifies routing, rotation, failover, +timeouts, byte fidelity, logging (exactly one row per request), auth, cookie flags, the brute-force guard, +admin APIs and the built dashboard shell. It fails fast when a fixed port is occupied or a child exits before +`/health`; the ports are overridable with `E2E_PORT`, `E2E_MOCK_A_PORT` and `E2E_MOCK_B_PORT`. -`pnpm test:live` talks to a real provider (`LIVE_UPSTREAM`, default `http://127.0.0.1:20123/v1`); when the -provider answers `429` every probe is reported as **SKIP** instead of failing. +`pnpm test:live` talks to a real provider (`LIVE_UPSTREAM`, default `http://127.0.0.1:20123/v1`, plus +`LIVE_KEY`, `LIVE_MODEL`, `LIVE_VISION_MODEL`, `LIVE_PORT`); when the provider answers `429` the affected +probe is reported as **SKIP** instead of failing (decided from the upstream status, never from error text). `scripts/screenshots.ts` seeds demo data, drives headless Chrome over CDP, asserts each dashboard page renders its expected content and writes screenshots to `tmp/screenshots/`. It needs a Chrome/Chromium binary -(`CHROME_PATH`, defaulting to the macOS Chrome path); when none is found the script prints `SKIP` and exits -without checking anything. CI does not run this script, so the UI check is a local, macOS-oriented aid. +(`CHROME_PATH`, defaulting to the macOS Chrome path); without one the script prints `SKIP` and exits 0, so +CI-invoked runs use `--strict`, which fails instead of skipping. CI does not run the UI check. ## Contributing @@ -199,6 +209,7 @@ wait for the required checks (`Commit messages`, `Lint & test`, `Build & e2e`) b ```bash pnpm lint:commits # validate your branch's commits locally +pnpm check:docs # env vars / routes / settings vs docs/SPEC.md + docs/API.md node scripts/check-commit-messages.mjs origin/main HEAD "feat(gateway): example" ``` diff --git a/docs/API.md b/docs/API.md index 8402e1f..bae4c51 100644 --- a/docs/API.md +++ b/docs/API.md @@ -9,43 +9,66 @@ Authorization: Bearer okr-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx x-api-key: okr-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` +Only `Bearer` is accepted in `Authorization`; any other scheme (`Basic …`) is treated as no credential +and rejected with `401 missing_api_key`. + Response headers: | Header | Set on | Meaning | | --- | --- | --- | | `x-opencode-router-request-id` | every `/v1/*` response | gateway request id (same id as in the Logs tab) | -| `x-opencode-router-provider` | proxied responses | id of the provider that served the request | -| `x-opencode-router-attempts` | proxied responses | number of upstream attempts (1 = first provider worked) | +| `x-opencode-router-provider` | proxied/failed-attempt responses | id of the provider that served (or failed) the request | +| `x-opencode-router-name` | proxied/failed-attempt responses | display name of that provider | +| `x-opencode-router-attempts` | proxied/failed-attempt responses | number of upstream attempts (1 = first provider worked) | +| `retry-after` | `429 all_providers_rate_limited` | seconds to wait before retrying (min 1) | +| `x-opencode-router-cooldown-until` | `429 all_providers_rate_limited` | epoch milliseconds when the smallest provider cooldown expires | Errors raised before an upstream attempt (auth, routing, validation) carry `x-opencode-router-request-id` only. +Upstream response headers are relayed to the client: `retry-after`, `request-id`, `x-request-id`, +`openai-processing-ms`, `openai-version`, `anthropic-version`, `x-ratelimit-*`, `anthropic-ratelimit-*` +and `x-stainless-*`. Router headers, `content-type` and `content-length` win, and `content-encoding` is +never forwarded. + Error envelope follows the client surface: OpenAI style `{"error":{"message","type","param","code"}}` for chat/responses, Anthropic style `{"type":"error","error":{"type","message"}}` for messages. | HTTP | `code` | Meaning | | --- | --- | --- | -| 401 | `missing_api_key` | no `Authorization`/`x-api-key` header | +| 401 | `missing_api_key` | no `Authorization: Bearer`/`x-api-key` header (non-Bearer schemes count as missing) | | 401 | `no_api_key_configured` | no gateway key exists yet → create one in the dashboard | | 401 | `invalid_api_key` | unknown, disabled or revoked key | | 400 | `model_required` | request body has no `model` | | 404 | `model_not_found` | model missing/disabled in the registry | +| 404 | `unknown_endpoint` | authenticated request to an unknown `/v1/*` path | | 503 | `no_provider_configured` | no enabled provider | | 503 | `no_models_configured` | model registry empty | -| 429 | `all_providers_rate_limited` | every attempt hit a rate limit | +| 429 | `all_providers_rate_limited` | every attempt hit a rate limit (carries `Retry-After`) | | 502 | `all_providers_failed` | every attempt failed (network/5xx) | +| 502 | `upstream_body_failed` | a `2xx` upstream body could not be read (truncated/RST) | +| 502 | `upstream_frame_too_large` | an unterminated SSE frame exceeded the 1 MiB cap | +| 504 | `upstream_timeout` | every candidate timed out (aggregated after exhaustion) | The router retries the next provider for `408`, `409`, `425`, `429`, `5xx` and network/timeout errors, up to -the configured retry budget (Dashboard → Settings → Routing). Client errors (`400/401/403/404/422`) are -returned immediately without burning other providers. +the configured retry budget (Dashboard → Settings → Routing). A timed-out attempt is logged, cools its +provider down and fails over like any other retryable failure; the `504 upstream_timeout` is only returned +after all candidates are exhausted. Client errors (`400/401/403/404/422`) are returned immediately without +burning other providers. + +Unknown `/v1/*` paths (and bare `/v1`) require a valid gateway key, are logged as one `request_logs` row and +answer `404` with code `unknown_endpoint` in the surface-appropriate error envelope. ## Upstream requests -Request bodies are forwarded byte-for-byte; a JSON body is only re-serialized when reasoning normalization or -the `stream_options.include_usage` injection actually changed it. Provider credentials (`Authorization`, -`x-api-key`), `host`, `content-length` and `connection` always come from the router, while the client's -`anthropic-beta`, `openai-beta`, `x-stainless-*`, `accept` and trace headers are forwarded through an -allowlist. Upstream redirects are refused (`redirect: 'manual'`): a `3xx` response is a fatal upstream error -instead of being followed with the provider key. +Request bodies are forwarded byte-for-byte from the raw client bytes (invalid UTF-8 included); a JSON body is +only re-serialized when reasoning normalization, model-id trimming or the `stream_options.include_usage` +injection actually changed it. Provider credentials (`Authorization`, `x-api-key`), `host`, `content-length` +and `connection` always come from the router, while the client's `anthropic-beta`, `anthropic-version`, +`anthropic-dangerous-direct-browser-access`, `openai-beta`, `x-stainless-*`, `accept` and trace headers are +forwarded through an allowlist. `anthropic-version: 2023-06-01` is only defaulted for the +messages/count_tokens surfaces, and a streaming request without an `accept` header is forwarded as +`text/event-stream`. Upstream redirects are refused (`redirect: 'manual'`): a `3xx` response is a fatal +upstream error instead of being followed with the provider key. --- @@ -163,5 +186,7 @@ only to extract token usage and to strip provider-internal `x_opencode` metadata leading BOM reach the client unchanged. `request_timeout_ms` (Dashboard → Settings → Routing) is a total deadline that covers the streamed body, and -a stalled upstream is additionally cut off by an idle timeout between frames. Client aborts terminate the -upstream request and are logged with `client_aborted`. +`stream_idle_timeout_ms` (default 120000, min 1000) cuts off an upstream that goes silent between frames/reads. +An unterminated SSE frame is capped at 1 MiB: the upstream is aborted and the request fails with +`502 upstream_frame_too_large`. Client aborts terminate the upstream request and are logged with +`client_aborted` (status 499). diff --git a/docs/SPEC.md b/docs/SPEC.md index 2756d10..f8c0c0d 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -34,17 +34,37 @@ incActiveRequests(); decActiveRequests(); getActiveRequests(); ``` `Repo` methods (all already implemented): `getSetting/setSetting/getBool/getInt/allSettings`, -`listProviders/getProvider/createProvider/updateProvider/deleteProvider/recordProviderSuccess/recordProviderFailure`, -`listModels/getModel/upsertModel/updateModel/deleteModel/deleteAllModels/enabledModelIds`, -`listApiKeys/hasActiveApiKey/createApiKey/getApiKey/findApiKeyByPlaintext/updateApiKey/deleteApiKey/touchApiKey`, -`insertLog/insertAttempt/listAttempts/listLogs/deleteLogsBefore/clearLogs/statsOverview`, -`createSession/getSession/touchSession/deleteSession/deleteAllSessions/purgeExpiredSessions/listSessions`, -`audit/listAudit/tableCounts`. +`listProviders/getProvider/createProvider/updateProvider/deleteProvider/deleteProviderWithModels/recordProviderSuccess/recordProviderFailure`, +`listModels/getModel/upsertModel/updateModel/deleteModel/deleteAllModels/enabledModelIds/hasEnabledModel/setModelsEnabled/deleteModels/deleteModelsByProvider`, +`listApiKeys/hasActiveApiKey/countActiveApiKeys/createApiKey/getApiKey/findApiKeyByPlaintext/updateApiKey/rotateApiKey/deleteApiKey/touchApiKey`, +`insertLog/insertAttempt/listAttempts/getLog/listLogs/deleteLogsBefore/clearLogs/statsOverview`, +`createSession/getSession/touchSession/deleteSession/deleteAllSessions/deleteOtherSessions/purgeExpiredSessions/listSessions`, +`audit/listAudit/deleteAuditBefore/tableCounts/transaction`. +`upsertModel(input, known?)` accepts the already-loaded row (provider sync is not N+1); +`transaction(fn)` runs `fn` inside one SQLite transaction and is re-entrant (nested calls join it). Settings keys with defaults: `dashboard_password_hash`, `rotation_strategy` (`round-robin`), `max_retries` (`3`), `provider_cooldown_ms` (`60000`), `request_timeout_ms` (`600000`), `auto_sync_models` (`true`), `model_sync_interval_ms` (`300000`), `log_retention_days` (`30`), -`model_allow_unknown` (`false`), `upstream_user_agent` (`opencode-router/1.0`). +`audit_retention_days` (`90`), `model_allow_unknown` (`false`), `upstream_user_agent` (`opencode-router/1.0`), +`stream_idle_timeout_ms` (`120000`). + +Environment variables (`src/config.ts`): + +| Env | Default | Meaning | +| --- | --- | --- | +| `HOST` | `0.0.0.0` | Bind address | +| `PORT` | `20125` | HTTP port | +| `DATA_DIR` | `./data` | SQLite database + persisted signing secret | +| `LOG_LEVEL` | `info` | Pino log level | +| `BODY_LIMIT` | `134217728` | Max request body in bytes | +| `DASHBOARD_PASSWORD` | `123456` | Only used when the password hash is first created | +| `ROUTER_SECRET` | `/.secret` | HMAC secret for dashboard sessions; when set, rotation is refused with `409 secret_from_env` | +| `SESSION_TTL_MS` | `604800000` | Dashboard session lifetime | +| `WEB_DIST_DIR` | `/web/dist` | Directory served as the dashboard build | +| `PUBLIC_URL` | unset | Absolute public base URL; an `https://` value also forces `Secure` session cookies | +| `TRUST_PROXY` | `false` | Trust `X-Forwarded-*` for `request.ip`, `client_ip` logging and the `Secure` cookie decision | +| `PROVIDER_ALLOW_PRIVATE_HOSTS` | `false` | Allow provider test/**sync** to reach loopback/link-local/private hosts (SSRF guard off) | Helpers: `src/util/crypto.ts` (`hashPassword`, `verifyPassword`, `hmacSign`, `generateApiKey`, `uuid`, `randomHex`, `sha256Hex`, `safeEqual`), `src/util/errors.ts` (`ApiError`, `errorTypeForStatus`, `isRetryableStatus`, `upstreamErrorFrom`), @@ -63,7 +83,8 @@ Helpers: `src/util/crypto.ts` (`hashPassword`, `verifyPassword`, `hmacSign`, `ge ### Auth (mandatory) Gateway API key required for every `/v1/*` request except `GET /v1/models`? **No** — every `/v1/*` -request requires a key. Accepted headers: `Authorization: Bearer ` or `x-api-key: `. +request requires a key. Accepted headers: `Authorization: Bearer ` or `x-api-key: `. +Any other `Authorization` scheme (for example `Basic …`) counts as no credential → `401 missing_api_key`. Authentication runs in a gateway `onRequest` hook **before** the body is parsed: unauthenticated requests are rejected without reading or buffering the body and still produce exactly one `request_logs` row plus a @@ -74,9 +95,13 @@ and `client_ip` logs cannot be spoofed with `X-Forwarded-For` by default. - No active API key exists at all → `401` `invalid_api_key`-shaped error, code `no_api_key_configured`, message `No gateway API key configured. Create one in the dashboard (API Keys tab).` - Key present but unknown/disabled/revoked → `401`, code `invalid_api_key`. -- Missing header → `401`, code `missing_api_key`. +- Missing header (or a non-Bearer scheme) → `401`, code `missing_api_key`. On success call `ctx.repo.touchApiKey(key.id)`. +Unknown `/v1/*` paths (and bare `/v1`) are **not** handled by the root not-found handler: an authenticated +catch-all inside the gateway scope requires a key, writes exactly one `request_logs` row/event pair and +answers `404` code `unknown_endpoint` in the surface-appropriate error shape. + ### Provider availability No enabled provider, or zero enabled models → `503` `api_error` code `no_provider_configured` (resp. `no_models_configured`), message explaining what to configure in the dashboard. @@ -90,6 +115,7 @@ No enabled provider, or zero enabled models → `503` `api_error` code `no_provi | `POST /v1/messages/count_tokens` | pass-through | | `GET /v1/models` | OpenAI list built from enabled DB models (see §2.4) | | `GET /v1/models/:id` | single model or `404 model_not_found` | +| `ALL /v1`, `ALL /v1/*` | authenticated catch-all for unknown endpoints (see § Auth) | ### 2.1 Request pipeline (all three surfaces) 1. `onRequest` hook: authenticate the key (§ Auth) and emit `request:start`; a rejection here writes one @@ -99,27 +125,45 @@ No enabled provider, or zero enabled models → `503` `api_error` code `no_provi 4. Model must exist and be enabled in DB unless `model_allow_unknown=true` → else `404` `model_not_found` with message listing how to add it. 5. Normalize reasoning effort (§2.3) and, for chat streaming, ensure usage is reported; keep the raw client - body so it can be forwarded unchanged. + bytes so they can be forwarded unchanged. The normalized/trimmed `model` id is written back into the + forwarded body. 6. Select provider order (§2.2) and attempt the upstream call as a **pass-through to the same surface**: `POST {provider.baseUrl}/chat/completions` / `/responses` / `/messages` / `/messages/count_tokens` - with the provider's API key in both `Authorization: Bearer` and `x-api-key`, plus `anthropic-version: 2023-06-01`. - The body is forwarded byte-for-byte whenever step 5 changed nothing, else as the normalized JSON. Client - headers pass through an allowlist (`anthropic-beta`, `openai-beta`, `x-stainless-*`, `accept`, trace - headers); auth/host/content-length/connection always come from the router. + with the provider's API key in both `Authorization: Bearer` and `x-api-key`. The body is forwarded + byte-for-byte (raw bytes captured with `parseAs: 'buffer'`, so invalid UTF-8 survives) whenever step 5 + changed nothing, else as the normalized JSON. Client headers pass through an allowlist + (`anthropic-beta`, `anthropic-version`, `anthropic-dangerous-direct-browser-access`, `openai-beta`, + `x-stainless-*`, `accept`, trace headers); auth/host/content-length/connection always come from the + router. `anthropic-version: 2023-06-01` is only defaulted for the `messages`/`count_tokens` surfaces; + a streaming request with no/wildcard `accept` is forwarded as `text/event-stream`. 7. Never follow upstream redirects (`redirect: 'manual'`): any `3xx` is a fatal upstream error (`502 upstream_redirect`, single attempt, provider cooled down, the provider key is never replayed). 8. Retry with the next provider when the attempt fails with a retryable status (`isRetryableStatus`: `408`, `409`, `425`, `429`, `5xx`, `529`) or a network/timeout `ApiError`, up to `max_retries` attempts total. + A timed-out provider is logged as a real attempt, put into cooldown and failed over like any other + retryable failure; the aggregated `504 upstream_timeout` is only returned after every candidate is + exhausted, and the log row/attempts are attributed to the provider that timed out. 9. Log the request (§2.6) exactly once per client request — `GET /v1/models*` included — and log every - attempt via `insertAttempt`. + attempt via `insertAttempt` (timed-out attempts included). +10. A `2xx` upstream whose body cannot be read (truncated/RST) is reported as `502 upstream_body_failed` + (the upstream status is kept when it is already ≥ 400; a timeout stays `504 upstream_timeout`). + A streaming body that exceeds the unterminated-frame cap aborts with `502 upstream_frame_too_large`. Strip provider-internal top-level `x_opencode` keys from JSON responses (non-stream body, and each SSE `data:` JSON payload when it parses). Everything else must be forwarded byte-for-byte, including tool calls, images/files/audio/video content parts and Anthropic `thinking` blocks. -Response headers: `x-opencode-router-request-id` on every `/v1/*` response; on proxied responses also -`x-opencode-router-provider: ` and `x-opencode-router-attempts: `. Errors raised before an attempt -(auth, routing, validation) carry the request id only. +Response headers: `x-opencode-router-request-id` on every `/v1/*` response; on proxied/failed-attempt +responses also `x-opencode-router-provider: `, `x-opencode-router-name: ` and +`x-opencode-router-attempts: `. Errors raised before an attempt (auth, routing, validation) carry the +request id only. Provider ids/names are sanitized before they reach a header, and a provider id/name/baseUrl +or `upstream_user_agent` containing control characters is rejected at the admin API (`400`). + +Upstream response headers relayed to the client: `retry-after`, `request-id`, `x-request-id`, +`openai-processing-ms`, `openai-version`, `anthropic-version`, `x-ratelimit-*`, `anthropic-ratelimit-*` +and `x-stainless-*`; router headers, `content-type` and `content-length` win, and `content-encoding` is +never forwarded. `429 all_providers_rate_limited` carries `Retry-After` (whole seconds, min 1) plus +`x-opencode-router-cooldown-until` (epoch ms). ### 2.2 Rotation (round-robin + failover) - `rotation_strategy` selects the order: `round-robin` (default, in-memory cursor advanced per request), @@ -136,10 +180,15 @@ Response headers: `x-opencode-router-request-id` on every `/v1/*` response; on p the router headers are populated even though the request failed. - On success: `recordProviderSuccess(id, latencyMs)`. - On retryable failure (incl. `409`): `recordProviderFailure(id, status, message, cooldownMs)` + `events.emitProvider`. + A cooldown is recorded for a network failure (no status), `408`/`409`/`425`, `429`, `503`, `529`, any other + `5xx`, and any `3xx`; the provider `status` column stays `cooldown` only for `429`/`503`/`529`/`5xx`. +- A timed-out attempt is recorded (log row + `request_attempts`), cools the provider down and fails over, + exactly like any other retryable failure. - On non-retryable failure (400/401/403/404/422): stop immediately and return the upstream error (mapped through `upstreamErrorFrom`) — do not burn other providers on a client error. - All attempts exhausted → response status of the last attempt (or `502` for network errors), - code `all_providers_failed`; if every failure was 429 use `429` + code `all_providers_rate_limited`. + code `all_providers_failed`; if every failure was 429 use `429` + code `all_providers_rate_limited` + (with `Retry-After`); if every failure was a timeout use `504` + code `upstream_timeout`. - Increment/decrement `incActiveRequests()/decActiveRequests()` around the whole request. ### 2.3 Reasoning effort normalization @@ -170,10 +219,13 @@ Forward SSE frames as they arrive (flush per frame, `Content-Type: text/event-st `Cache-Control: no-cache`, `Connection: keep-alive`, `X-Accel-Buffering: no`). Forward the original bytes: a frame is decoded only to detect `x_opencode` / parse usage and re-encoded only when it is actually rewritten, so invalid UTF-8 and a leading BOM reach the client unchanged. `request_timeout_ms` is a real -total deadline that covers the streamed body, plus an idle timeout between reads so a stalled upstream -cannot hang the request. +total deadline that covers the streamed body; `stream_idle_timeout_ms` (default `120000`, min `1000`) is the +idle gap between reads/`drain` waits, so a stalled upstream cannot hang the request. An unterminated SSE +frame is capped at 1 MiB: on breach the upstream is aborted, the log row gets `upstream_frame_too_large` +with status `502`. While forwarding, feed bytes through `SseParser` to extract usage: -- chat: last chunk `usage` (also add `stream_options.include_usage = true` when the client did not set it) +- chat: last chunk `usage` (also add `stream_options.include_usage = true` when the client did not set it; + the gateway never fabricates a usage frame the upstream did not send) - responses: `response.completed` → `response.usage` - messages: `message_delta` → `usage` (`input_tokens`/`output_tokens`, `cache_read_input_tokens`) Record `ttfb_ms` (time to first byte) on the log row. Handle client aborts without crashing @@ -189,6 +241,9 @@ the OpenAI (`chat`) surface — with: `provider_id`/`provider_name` (winning provider), `model`, `surface`, `stream`, `status`, `ok`, `error_code`, `error_message`, `latency_ms`, `ttfb_ms`, token fields, `attempts`, `client_ip`, `user_agent`. Emit `ctx.events.emitRequestStart(...)` right after auth and `ctx.events.emitRequestEnd({log})` at the end. +Event emission is guarded: a throwing dashboard/SSE listener is logged as a warning and can never fail the +request. Upstream error messages redact URL userinfo and query strings, so provider credentials never reach +`request_logs.error_message`, `providers.last_error` or a client-visible error body. ## 3. Admin API (`src/admin/**`, prefix `/admin/api`) @@ -198,17 +253,20 @@ Emit `ctx.events.emitRequestStart(...)` right after auth and `ctx.events.emitReq verify the signature, the in-cookie `expiresAt` (an already-expired cookie is rejected before any DB lookup) and the DB row + expiry. Cookie flags: `httpOnly`, `sameSite: 'lax'`, `path: '/'`, `maxAge` = `sessionTtlMs/1000`, - `secure` when the request is https (`request.protocol`, a trusted `x-forwarded-proto`, or - `PUBLIC_URL` starting with `https://`). + `secure` when the request is https (`request.protocol`, an `x-forwarded-proto: https` that is only + honoured when `TRUST_PROXY` is enabled, or `PUBLIC_URL` starting with `https://`). - Public endpoints: `POST /admin/api/login`, `POST /admin/api/logout`, `GET /admin/api/session`. `/login` and `/settings/password` accept at most 4096 bytes (`413` above it) and reject passwords longer than 200 characters with `400`. - Every other `/admin/api/*` route requires a valid session → else `401 {error:{message,code:'unauthorized'}}`. - `POST /admin/api/login {password}`: verify with `verifyDashboardPassword` (src/core/seed.ts); - brute-force guard: max 10 failed attempts per IP per 5 minutes → `429`; on success create session, - `repo.audit('dashboard','auth.login',...)`, return `{ok:true, expiresAt}`. + brute-force guard: max 10 failed attempts per IP and 50 failed attempts per process per 5 minutes → + `429` with `Retry-After` (seconds) and `{error:{code:'too_many_attempts',retryAfter}}`; on success create + session, `repo.audit(...)`, return `{ok:true, expiresAt}`. - `POST /admin/api/logout` clears the cookie + deletes the session row. - `GET /admin/api/session` → `{authenticated, expiresAt?, version:'1.0.0', uptimeMs, startedAt}` (never 401). +- `HttpError` messages are returned to the client as-is, including `5xx`; only unexpected errors are masked + as `500 internal_error` (with driver/stack detail kept server-side). ### Endpoints (all JSON; errors use `{error:{message,code}}`) **Bootstrap / stats** @@ -219,22 +277,28 @@ Emit `ctx.events.emitRequestStart(...)` right after auth and `ctx.events.emitReq - `GET /admin/api/events` (SSE) → emits `request:start`, `request:end`, `provider:update`, plus a `stats` heartbeat every 5s with `{activeRequests, requestsLast60s, errorsLast60s}`. Writes apply per-client backpressure (bounded queue + `drain` resume; the stream is ended after repeated stalls). + The session row is re-validated on every heartbeat and the stream is closed when the session disappears or + expires; at most 32 concurrent streams are allowed, above that the endpoint answers `503 too_many_streams`. `GET /admin/api/stats` is served from a short (~2s) TTL cache. - `GET /admin/api/activity?limit=20` → merged recent log rows + provider state changes. **Providers** - `GET /admin/api/providers` → `{providers:[{id,name,baseUrl,apiKeyMasked,hasApiKey,enabled,priority,status,cooldownUntil,lastError,lastCheckedAt,lastLatencyMs,successCount,failureCount,createdAt,updatedAt}]}` (never return the raw key). -- `POST /admin/api/providers {id?, name, baseUrl, apiKey, enabled?, priority?}` → `{provider}` (validate: name and baseUrl required, baseUrl must start with http:// or https://, apiKey required). + `apiKeyMasked` reveals at most 4 characters and is `****` for keys shorter than 12 characters. +- `POST /admin/api/providers {id?, name, baseUrl, apiKey, enabled?, priority?}` → `{provider}` (validate: name and baseUrl required, baseUrl must start with http:// or https://, apiKey required; `id`/`name`/`baseUrl` reject control characters, `baseUrl` rejects userinfo). - `PATCH /admin/api/providers/:id {name?, baseUrl?, apiKey?, enabled?, priority?}` → `{provider}`. -- `DELETE /admin/api/providers/:id` → `{ok:true}`. + Changing `baseUrl`, `apiKey` or `enabled` resets `status='unknown'` and `cooldownUntil=null`. +- `DELETE /admin/api/providers/:id` → `{ok:true, modelsRemoved}` — the provider's synced models are removed + in the same transaction. - `POST /admin/api/providers/:id/test` → `{ok, status, latencyMs, models:number, error:null|string}` (GET `{baseUrl}/models`). A failed test updates the provider's status/failure counters/`lastError` and emits `provider:update`, exactly like a gateway failure. - `POST /admin/api/providers/test {baseUrl, apiKey?, id?}` → same shape, before saving. When `apiKey` is - omitted and `id` names a stored provider, the draft `baseUrl` is tested with that provider's stored key - (`404` for an unknown `id`, `400` when neither is given). + omitted and `id` names a stored provider, the stored key is reused **only** when the draft `baseUrl` origin + equals the stored provider's origin (otherwise `400 api_key_required`); `404` for an unknown `id`, `400` + when neither is given. - `POST /admin/api/providers/:id/sync-models` → `{added, updated, removed, total, providerId, syncedAt}`. - Test and sync resolve the URL and refuse loopback/link-local/private hosts unless + Test **and** sync (routes + scheduler) resolve the URL and refuse loopback/link-local/private hosts unless `PROVIDER_ALLOW_PRIVATE_HOSTS=true` (SSRF guard). **Models** @@ -242,7 +306,8 @@ Emit `ctx.events.emitRequestStart(...)` right after auth and `ctx.events.emitReq - `POST /admin/api/models {id, name?, contextLength?, maxOutputTokens?, capabilities?, reasoning?, enabled?}` → `{model}` (source `manual`; `409` when the id exists). - `PATCH /admin/api/models/:id {...}` → `{model}`. - `DELETE /admin/api/models/:id` → `{ok:true}`. -- `POST /admin/api/models/bulk {action:'enable'|'disable'|'delete', ids:[...]}` → `{updated}`. +- `POST /admin/api/models/bulk {action:'enable'|'disable'|'delete', ids:[...]}` → `{updated}`; `ids` is capped + at 1000 entries (`400` above) and the action is applied as one set-based statement inside a transaction. - `POST /admin/api/models/sync {providerId?}` → same shape as provider sync; uses the given provider or the first enabled one; `400` when no provider exists. Sync semantics: upsert every model reported upstream with `source='sync'`, `providerId`, and delete @@ -270,10 +335,14 @@ Emit `ctx.events.emitRequestStart(...)` right after auth and `ctx.events.emitReq with a formula trigger (`=`, `+`, `-`, `@`, tab, CR) are prefixed with `'` before quoting. **Settings** -- `GET /admin/api/settings` → `{settings, sessions:[{id,createdAt,expiresAt,lastSeenAt,clientIp,userAgent,current}], dbPath, dataDir, version, uptimeMs, counts}`. -- `PATCH /admin/api/settings {..known keys..}` → `{settings}` (validate ints/ranges; ignore unknown keys — - inherited object properties such as `constructor` are ignored too; `log_store_bodies` no longer exists and - is reported as `ignored`). +- `GET /admin/api/settings` → `{settings, passwordSet, sessions:[{id,createdAt,expiresAt,lastSeenAt,clientIp,userAgent,current}], dbPath, dataDir, version, uptimeMs, counts}` + (`sessions` lists at most the 50 newest sessions; `passwordSet` reports whether a dashboard password hash exists). +- `PATCH /admin/api/settings {..known keys..}` → `{settings, changed, ignored}`. Every entry is validated + first and valid ones are applied in one transaction, so one bad value changes nothing. Unknown keys — + inherited object properties such as `constructor` included — are reported as `ignored`; + `log_store_bodies` no longer exists and is also reported as `ignored`. Ranges include + `audit_retention_days` 1..3650 and `stream_idle_timeout_ms` 1000..3600000; `upstream_user_agent` rejects + control characters. - `POST /admin/api/settings/password {currentPassword, newPassword}` → `{ok:true}` (`400` wrong current, `400` when shorter than 4 chars); invalidates all other sessions. - `DELETE /admin/api/settings/sessions` → `{ok:true, revoked}` (revokes **every** other session, not just the @@ -286,7 +355,9 @@ Emit `ctx.events.emitRequestStart(...)` right after auth and `ctx.events.emitReq invalidate all dashboard sessions and return the new secret so the operator can store it (response carries `cache-control: no-store`). Gateway key hashes are sha256 of the plaintext, so existing keys keep working. - `GET /admin/api/audit?limit=100` → `{items:[...]}`. -Audit every mutating admin action with `repo.audit('dashboard', action, target, detail)`. +- Audit every mutating admin action with `repo.audit(actor, action, target, detail)`: the actor is + `session:` on session-protected routes (or `dashboard` on public routes) and the client IP is recorded + in the detail. Audit rows are pruned by `audit_retention_days`, not by `log_retention_days`. ### Scheduler (`src/admin/scheduler.ts`) `startScheduler(ctx)` returns a stop function. It: @@ -306,10 +377,13 @@ to `http://127.0.0.1:20125`. Files to create: `web/index.html`, `web/vite.config.ts`, `web/tsconfig.json`, `web/src/main.tsx`, `web/src/App.tsx`, `web/src/styles.css`, `web/src/lib/api.ts`, `web/src/lib/format.ts`, `web/src/lib/theme.ts`, `web/src/components/**`, `web/src/pages/**`. +The built JS/CSS/font bundles are served from `GET /assets/*` (path-contained inside `web/dist`). Routes: `/` → always `302` to `/dashboard`, which redirects to `/login` when there is no valid session; `/login`; `/dashboard/overview`, `/dashboard/keys`, `/dashboard/providers`, `/dashboard/models`, -`/dashboard/logs`, `/dashboard/settings`. +`/dashboard/logs`, `/dashboard/settings`. `/index.html` is never served directly by the static handler: +every shell path (`/`, `/login`, `/dashboard*`, `/index.html`, any unknown path) goes through the +server-side session gate first. ### Visual language (must look premium, not generic) - Palette: pure black/white/neutral only. Accent = white (dark mode) / black (light mode) with subtle @@ -352,9 +426,23 @@ Routes: `/` → always `302` to `/dashboard`, which redirects to `/login` when t "Setup needed" banners linking to the right tab. ## 5. Verification requirements -- `pnpm typecheck` clean, `pnpm build` produces `dist/` and `web/dist/`. +- `pnpm typecheck` clean (server, dashboard, `tests/**` + `scripts/**` via `tsconfig.test.json`), + `pnpm build` produces `dist/` and `web/dist/`. - `pnpm dev` (or `node dist/src/index.js`) starts on 20125; `GET /health` → `{status:'ok'}` with a real - `uptimeMs`; `GET /` always `302`-redirects to `/dashboard`. -- Gateway e2e against the reference provider `http://127.0.0.1:20123/v1` with key `sk-dummy-123`: - models sync, key creation, then streaming + non-streaming chat/responses/messages including a tool call - and a vision request; verify rotation across two providers and 429 failover. + `uptimeMs`; `GET /` always `302`-redirects to `/dashboard`; `/dashboard` without a session `302`s to + `/login`. +- `pnpm test` (vitest unit suite) green. +- `pnpm test:e2e` boots the real server (`src/index.ts`) plus two deterministic mock upstreams on + `E2E_PORT`/`E2E_MOCK_A_PORT`/`E2E_MOCK_B_PORT` (defaults 20197/20196/20195). It fails fast when a fixed + port is occupied or a child exits before `/health`, and covers: all three surfaces (stream + non-stream), + tool calling, vision, reasoning, `include_usage` both directions, `x_opencode` stripping (including an + injected SSE frame), byte-for-byte fidelity, client abort, round-robin (counters reset), 429/503/dead + failover, non-retryable 400 single-attempt, timeout 504, retry-after, single-log-row assertions with a + settle window, revoked/disabled keys, cookie attributes, brute-force 429, admin endpoints and the built + dashboard shell. +- Tooling checks: `pnpm check:docs` diffs the env vars read by `src/config.ts`, the registered routes and + the `DEFAULT_SETTINGS` keys against this file and `docs/API.md` (exits 1 on drift); + `node scripts/check-commit-messages.mjs []` lints Conventional Commits and + fails on an explicitly supplied but empty range; `pnpm exec tsx scripts/screenshots.ts --strict` + runs the headless-Chrome UI check and fails instead of skipping when Chrome is missing + (`CHROME_PATH` overrides the binary). diff --git a/package.json b/package.json index e4b9784..fe10cbc 100644 --- a/package.json +++ b/package.json @@ -37,7 +37,8 @@ "url": "https://github.com/dinhdev666/opencode-router/issues" }, "engines": { - "node": ">=22.13.0" + "node": ">=22.13.0", + "pnpm": ">=10" }, "scripts": { "dev": "tsx watch src/index.ts", @@ -46,18 +47,14 @@ "build:server": "tsc -p tsconfig.json", "build:web": "vite build --config web/vite.config.ts", "start": "node dist/src/index.js", - "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p web/tsconfig.json --noEmit", + "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p web/tsconfig.json --noEmit && tsc -p tsconfig.test.json --noEmit", "test": "vitest run", "test:e2e": "tsx scripts/e2e.ts", "test:live": "tsx scripts/live-check.ts", "mock": "tsx scripts/mock-upstream.ts", + "check:docs": "tsx scripts/check-docs.ts", "lint:commits": "node scripts/check-commit-messages.mjs" }, - "pnpm": { - "onlyBuiltDependencies": [ - "esbuild" - ] - }, "dependencies": { "@fastify/cookie": "^11.0.2", "@fastify/static": "^8.3.0", diff --git a/scripts/check-commit-messages.mjs b/scripts/check-commit-messages.mjs index 2bd655f..73f3f58 100644 --- a/scripts/check-commit-messages.mjs +++ b/scripts/check-commit-messages.mjs @@ -7,10 +7,20 @@ * * Defaults: `origin/main..HEAD` for the range, no PR-title check. * Exits non-zero and prints every offending message when validation fails. + * + * Hardening notes: + * - merge commits are excluded by Git (`--no-merges`) instead of being guessed from + * the subject text, so a hand-written `Merge ...` subject is still linted; + * - the lowercase rule is Unicode-aware: the description must start with a lowercase + * letter (`\p{Ll}`), so `feat: Ädd`, `feat: 修正` and `feat: ✨ sparkle` all fail; + * - an explicitly supplied base+head range that contains zero commits fails instead of + * silently passing a check that validated nothing. */ import { execFileSync } from 'node:child_process'; +import { resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; -const ALLOWED_TYPES = [ +export const ALLOWED_TYPES = [ 'feat', 'fix', 'docs', @@ -26,20 +36,34 @@ const ALLOWED_TYPES = [ // ()!: const SUBJECT_PATTERN = new RegExp(`^(${ALLOWED_TYPES.join('|')})(\\([a-z0-9][a-z0-9._/-]*\\))?(!)?: (.+)$`); -const MAX_SUBJECT_LENGTH = 100; +export const MAX_SUBJECT_LENGTH = 100; /** A `!` subject must document the break in the commit body (Conventional Commits). */ const BREAKING_CHANGE_FOOTER = /^\s*BREAKING[ -]CHANGE:\s*\S/m; -/** Commits generated by tooling (GitHub merge suggestions, fixup chains) are not linted. */ -const IGNORED_PREFIXES = ['Merge ', 'Revert "', 'fixup!', 'squash!', 'amend!', 'Initial commit']; +/** + * Commits generated by tooling (revert commits, fixup!/squash! chains, GitHub's + * "Initial commit") are not linted. Real merge commits are not in this list: Git + * excludes them via `--no-merges`, so a non-merge subject starting with "Merge " is + * still validated. + */ +const IGNORED_PREFIXES = ['Revert "', 'fixup!', 'squash!', 'amend!', 'Initial commit']; +/** Description must begin with a lowercase letter, in any script (Unicode-aware). */ +const LOWERCASE_LETTER = /^\p{Ll}$/u; -function git(args) { +export function git(args) { return execFileSync('git', args, { encoding: 'utf8' }).trim(); } function readCommits(range) { const fieldSeparator = '\u001f'; const recordSeparator = '\u001e'; - const raw = git(['log', `--format=%H${fieldSeparator}%s${fieldSeparator}%b${recordSeparator}`, range]); + // `--no-merges` is the real merge detector: a merge commit is excluded by Git, not + // by matching its subject prefix. + const raw = git([ + 'log', + '--no-merges', + `--format=%H${fieldSeparator}%s${fieldSeparator}%b${recordSeparator}`, + range, + ]); if (!raw) return []; return raw .split(recordSeparator) @@ -55,12 +79,32 @@ function readCommits(range) { }); } +/** + * Build the Git range to lint. + * @param {string | undefined} base + * @param {string | undefined} head + */ +export function commitRange(base, head) { + return base && head ? `${base}..${head}` : 'origin/main..HEAD'; +} + +/** + * A range the caller asked for explicitly must not be empty: passing a check that + * linted nothing is worse than failing it. + * @param {string | undefined} base + * @param {string | undefined} head + */ +export function emptyRangeFails(base, head) { + return Boolean(base && head); +} + /** * @param {string} subject * @param {string} [body] Commit body; `undefined` when the caller only has a title * (the PR title has no body of its own), in which case the footer cannot be checked. + * @returns {string[]} human-readable problems; empty when the subject is acceptable. */ -function validate(subject, body) { +export function validateSubject(subject, body) { if (IGNORED_PREFIXES.some((prefix) => subject.startsWith(prefix))) return []; if (subject.length === 0) return ['empty subject']; @@ -78,7 +122,11 @@ function validate(subject, body) { const [, , , breaking, description] = match; const text = description.trim(); if (text.length === 0) problems.push('empty description'); - if (/^[A-Z]/.test(text)) problems.push('description should start with a lowercase letter'); + // First code point, not first UTF-16 unit: emoji and astral letters must not slip past. + const firstCharacter = Array.from(text)[0] ?? ''; + if (!LOWERCASE_LETTER.test(firstCharacter)) { + problems.push('description should start with a lowercase letter'); + } if (text.endsWith('.')) problems.push('description should not end with a period'); if (breaking === '!' && body !== undefined && !BREAKING_CHANGE_FOOTER.test(body)) { problems.push('breaking change "!" requires a "BREAKING CHANGE:" footer in the commit body'); @@ -88,7 +136,7 @@ function validate(subject, body) { function main() { const [baseArg, headArg, titleArg] = process.argv.slice(2); - const range = baseArg && headArg ? `${baseArg}..${headArg}` : 'origin/main..HEAD'; + const range = commitRange(baseArg, headArg); let commits; try { @@ -99,6 +147,11 @@ function main() { } const prTitle = (titleArg ?? process.env.PR_TITLE ?? '').trim(); + if (commits.length === 0 && emptyRangeFails(baseArg, headArg)) { + console.error(`No commits found in range "${range}" although a base and head were supplied.`); + console.error('Refusing to pass a commit-message check that linted nothing.'); + process.exit(1); + } if (commits.length === 0 && prTitle.length === 0) { console.log(`No commits found in range "${range}"; nothing to validate.`); return; @@ -106,13 +159,13 @@ function main() { const failures = []; for (const commit of commits) { - const problems = validate(commit.subject, commit.body); + const problems = validateSubject(commit.subject, commit.body); if (problems.length > 0) failures.push({ label: commit.sha.slice(0, 8), subject: commit.subject, problems }); } if (prTitle.length > 0) { // A PR title has no body of its own (the squash body is written at merge time), // so only the subject rules apply here. - const problems = validate(prTitle); + const problems = validateSubject(prTitle); if (problems.length > 0) failures.push({ label: 'PR title', subject: prTitle, problems }); } @@ -132,4 +185,8 @@ function main() { process.exit(1); } -main(); +/** True only when this file is the process entry point (so it stays importable by tests). */ +export const isDirectRun = + process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href; + +if (isDirectRun) main(); diff --git a/scripts/check-docs.ts b/scripts/check-docs.ts new file mode 100644 index 0000000..bf35e51 --- /dev/null +++ b/scripts/check-docs.ts @@ -0,0 +1,218 @@ +/** + * Repo-wide documentation drift checker (`pnpm check:docs`). + * + * Derives the machine-checkable contract from the source of truth: + * - environment variables read by `src/config.ts`; + * - Fastify routes registered under `src/**` (`/v1/*` plus the `/admin/api` scope); + * - `DEFAULT_SETTINGS` keys from `src/db/repos.ts`. + * + * ...and diffs them against `docs/SPEC.md` + `docs/API.md`. Both directions are + * checked: something the code exposes but the docs never mention, and a path the docs + * promise that no route implements. + * + * The checker is intentionally strict: it exits 1 on any drift so CI fails while the + * docs are out of date. Fixes belong in the docs (T-10), never in this file. + * + * Usage: pnpm check:docs + */ +import { readFileSync, readdirSync } from 'node:fs'; +import { join, relative, resolve, sep } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ROOT = resolve(process.cwd()); +export const DOC_FILES = ['docs/SPEC.md', 'docs/API.md']; +const CONFIG_FILE = 'src/config.ts'; +const REPO_FILE = 'src/db/repos.ts'; +const SOURCE_DIR = 'src'; +/** Admin routes are registered relatively inside a `/admin/api`-prefixed scope. */ +const ADMIN_PREFIX = '/admin/api'; +/** Doc paths that name a whole area rather than an endpoint. */ +const AREA_PATHS = new Set(['/v1', '/v1/', '/admin/api', '/admin/api/']); + +export interface RouteEntry { + method: string; + path: string; + file: string; +} + +/* ------------------------------------------------------------------ source scan */ + +function listSourceFiles(dir: string): string[] { + const files: string[] = []; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const full = join(dir, entry.name); + if (entry.isDirectory()) files.push(...listSourceFiles(full)); + else if (entry.isFile() && entry.name.endsWith('.ts')) files.push(full); + } + return files; +} + +/** Reads the env var names `src/config.ts` consumes (direct reads plus `envBool`/`envInt`). */ +export function collectEnvVars(root = ROOT): string[] { + const text = readFileSync(join(root, CONFIG_FILE), 'utf8'); + const names = new Set(); + for (const match of text.matchAll(/process\.env\.([A-Z][A-Z0-9_]*)/g)) names.add(match[1]!); + for (const match of text.matchAll(/env(?:Bool|Int)\('([A-Z][A-Z0-9_]*)'/g)) names.add(match[1]!); + return [...names].sort(); +} + +/** Reads the keys of the `DEFAULT_SETTINGS` record in `src/db/repos.ts`. */ +export function collectSettingKeys(root = ROOT): string[] { + const text = readFileSync(join(root, REPO_FILE), 'utf8'); + const start = text.indexOf('export const DEFAULT_SETTINGS'); + if (start < 0) throw new Error(`DEFAULT_SETTINGS not found in ${REPO_FILE}`); + const end = text.indexOf('\n};', start); + if (end < 0) throw new Error(`DEFAULT_SETTINGS block is not terminated in ${REPO_FILE}`); + const block = text.slice(start, end); + const keys = new Set(); + for (const match of block.matchAll(/^\s{2}([a-z][a-z0-9_]*):/gm)) keys.add(match[1]!); + return [...keys].sort(); +} + +/** Every `app/scope.('')` registration plus the passthrough route table. */ +export function collectRoutes(root = ROOT): RouteEntry[] { + const entries = new Map(); + const add = (method: string, path: string, file: string): void => { + if (!path.startsWith('/')) return; + const key = `${method} ${path}`; + if (!entries.has(key)) entries.set(key, { method, path, file }); + }; + + for (const file of listSourceFiles(join(root, SOURCE_DIR))) { + const rel = relative(root, file).split(sep).join('/'); + const prefix = rel.startsWith('src/admin/') ? ADMIN_PREFIX : ''; + const text = readFileSync(file, 'utf8'); + for (const match of text.matchAll(/\.(get|post|put|patch|delete|all|head|options)\(\s*'([^']+)'/g)) { + add(match[1]!.toUpperCase(), prefix + match[2]!, rel); + } + for (const match of text.matchAll(/url:\s*'([^']+)'/g)) add('POST', match[1]!, rel); + } + + return [...entries.values()].sort((left, right) => left.path.localeCompare(right.path)); +} + +/* ---------------------------------------------------------------- doc extraction */ + +/** Normalizes route params and wildcards so `/v1/models/:id` === `/v1/models/*`. */ +export function normalizePath(raw: string): string { + let path = raw.trim(); + path = path.replace(/\?.*$/, ''); + path = path.replace(/\{[^}]*\}/g, ':p'); + path = path.replace(/:[A-Za-z0-9_-]+/g, ':p'); + // `.../models*` and `.../models/*` both name the same param route. + path = path.replace(/\/?\*+/g, '/:p'); + path = path.replace(/\/+$/, ''); + return path.length > 0 ? path : '/'; +} + +/** + * Extracts endpoint-looking paths from markdown code spans. Method-prefixed spans + * (`GET /admin/api/stats`) keep only the path; wildcard/placeholder spans are skipped. + */ +export function collectDocumentedPaths(docs: string[]): string[] { + const paths = new Set(); + for (const doc of docs) { + for (const match of doc.matchAll(/`([^`\n]+)`/g)) { + let token = match[1]!.trim(); + // Spans such as `POST /admin/api/models/bulk {action:'enable'}` keep only the path. + const methodPrefixed = /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|ALL)\s+(\S+)/.exec(token); + const declaredEndpoint = methodPrefixed !== null; + if (methodPrefixed) token = methodPrefixed[2]!; + // A wildcard/elided path is a family, not an endpoint — unless the docs declare it + // with an HTTP method (`ALL /v1/*`), which names a real registered route. + if ((token.includes('*') || token.includes('…') || token.includes('...')) && !declaredEndpoint) continue; + if (!token.startsWith('/') || /\s/.test(token)) continue; + if (AREA_PATHS.has(token)) continue; + paths.add(token); + } + } + return [...paths].sort(); +} + +/** True when `path` or its documented-param/base variant is present in `candidates`. */ +export function pathMatches(path: string, candidates: Set): boolean { + if (candidates.has(path)) return true; + const base = path.replace(/\/:p$/, ''); + if (base !== path && candidates.has(base)) return true; + if (candidates.has(`${path}/:p`)) return true; + return false; +} + +/* ------------------------------------------------------------------------ report */ + +interface Finding { + group: string; + message: string; +} + +function mentions(haystack: string, needle: string): boolean { + const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + return new RegExp(`(? } { + const docs = DOC_FILES.map((file) => readFileSync(join(root, file), 'utf8')); + const docText = docs.join('\n'); + const findings: Finding[] = []; + + const envVars = collectEnvVars(root); + for (const name of envVars) { + if (!mentions(docText, name)) findings.push({ group: 'env vars', message: `${name} is read by src/config.ts but not documented` }); + } + + const settingKeys = collectSettingKeys(root); + for (const key of settingKeys) { + if (!mentions(docText, key)) findings.push({ group: 'settings', message: `${key} is a DEFAULT_SETTINGS key but not documented` }); + } + + const routes = collectRoutes(root); + const documented = collectDocumentedPaths(docs); + const documentedSet = new Set(documented.map(normalizePath)); + const routeSet = new Set(routes.map((route) => normalizePath(route.path))); + + for (const route of routes) { + if (!pathMatches(normalizePath(route.path), documentedSet)) { + findings.push({ + group: 'routes', + message: `${route.method} ${route.path} (${route.file}) is registered but not documented`, + }); + } + } + for (const path of documented) { + const normalized = normalizePath(path); + if (!normalized.startsWith('/v1/') && !normalized.startsWith(`${ADMIN_PREFIX}/`)) continue; + if (!pathMatches(normalized, routeSet)) { + findings.push({ group: 'routes', message: `${path} is documented but no route implements it` }); + } + } + + return { + findings, + checked: { envVars: envVars.length, settingsKeys: settingKeys.length, routes: routes.length, documentedPaths: documented.length }, + }; +} + +function main(): void { + console.log(`Documentation drift check (${DOC_FILES.join(', ')})\n`); + const { findings, checked } = runCheck(ROOT); + console.log( + `Checked ${checked.envVars} env var(s), ${checked.settingsKeys} setting key(s), ${checked.routes} route(s) against ${checked.documentedPaths} documented path(s).\n`, + ); + + if (findings.length === 0) { + console.log('No drift found.'); + return; + } + + const groups = [...new Set(findings.map((finding) => finding.group))]; + for (const group of groups) { + const groupFindings = findings.filter((finding) => finding.group === group); + console.log(`${group} (${groupFindings.length}):`); + for (const finding of groupFindings) console.log(` - ${finding.message}`); + console.log(''); + } + console.error(`${findings.length} documentation drift item(s) found.`); + process.exitCode = 1; +} + +if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main(); diff --git a/scripts/e2e.ts b/scripts/e2e.ts index 046d849..86fc7df 100644 --- a/scripts/e2e.ts +++ b/scripts/e2e.ts @@ -40,6 +40,8 @@ interface CheckResult { const results: CheckResult[] = []; let cookie = ''; let gatewayKey = ''; +/** Mock upstream counters captured right after the round-robin loop (reset inside it). */ +let roundRobinServed = { a: 0, b: 0 }; function record(name: string, ok: boolean, detail: string, ms: number): void { results.push({ name, ok, detail, ms }); @@ -60,10 +62,38 @@ function assert(condition: unknown, message: string): asserts condition { if (!condition) throw new Error(message); } -async function waitFor(url: string, timeoutMs = 30_000): Promise { +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** Fails fast when a fixed e2e port is already taken by a stray process. */ +async function assertPortFree(port: number): Promise { + await new Promise((resolvePort, rejectPort) => { + const probe = createNetServer(); + probe.once('error', (error: NodeJS.ErrnoException) => { + rejectPort( + new Error( + error.code === 'EADDRINUSE' + ? `port ${port} is already in use; stop that process or override the E2E_*_PORT env vars` + : `port ${port}: ${error.message}`, + ), + ); + }); + probe.listen(port, '127.0.0.1', () => probe.close(() => resolvePort())); + }); +} + +/** + * Waits for an HTTP endpoint while watching the child process: a server that dies during + * boot must report why immediately instead of burning the 30 s readiness timeout. + */ +async function waitForReady(url: string, child: ChildProcess, label: string, timeoutMs = 30_000): Promise { const deadline = Date.now() + timeoutMs; let lastError = 'timeout'; while (Date.now() < deadline) { + if (child.exitCode !== null || child.signalCode !== null) { + throw new Error(`${label} exited (code=${child.exitCode}, signal=${child.signalCode}) before ${url} became ready`); + } try { const response = await fetch(url); if (response.ok) return; @@ -71,15 +101,11 @@ async function waitFor(url: string, timeoutMs = 30_000): Promise { } catch (error) { lastError = error instanceof Error ? error.message : String(error); } - await new Promise((resolve) => setTimeout(resolve, 150)); + await sleep(150); } throw new Error(`${url} not ready: ${lastError}`); } -function sleep(ms: number): Promise { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - /** Requests, then waits for the single log row (written in a `finally`) to land. */ async function logTotal(): Promise { const body = await adminJson<{ total: number }>('/logs?limit=1'); @@ -97,6 +123,17 @@ async function waitForLogTotal(expected: number, timeoutMs = 5_000): Promise { + const reached = await waitForLogTotal(expected); + if (reached !== expected) return reached; + await sleep(settleMs); + return logTotal(); +} + interface LogRow { id: string; status: number; @@ -121,6 +158,17 @@ async function findLogByUserAgent(marker: string, timeoutMs = 8_000): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const response = await admin(`/logs/${id}`); + if (response.ok) return ((await response.json()) as { log: LogRow }).log; + await sleep(150); + } + return null; +} + /** Enables only `ids` for the duration of `fn`, restoring the previous flags after. */ async function withOnlyProviders(ids: string[], fn: () => Promise): Promise { const body = await adminJson<{ providers: Array<{ id: string; enabled: boolean }> }>('/providers'); @@ -301,7 +349,7 @@ async function withAltServer(env: Record, fn: (base: string) => }); collect(child); try { - await waitFor(`${base}/health`); + await waitForReady(`${base}/health`, child, `alt server on ${port}`); await fn(base); } finally { await stop(child); @@ -322,13 +370,18 @@ async function freePort(): Promise { }); } -/** Logs into an auxiliary server with the default password and returns its cookie. */ -async function altLogin(base: string): Promise { - const response = await fetch(`${base}/admin/api/login`, { +/** POSTs the default password to an auxiliary server (extra headers allow cookie-flag probes). */ +async function altLoginResponse(base: string, headers: Record = {}): Promise { + return fetch(`${base}/admin/api/login`, { method: 'POST', - headers: { 'content-type': 'application/json' }, + headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify({ password: '123456' }), }); +} + +/** Logs into an auxiliary server with the default password and returns its cookie. */ +async function altLogin(base: string, headers: Record = {}): Promise { + const response = await altLoginResponse(base, headers); assert(response.ok, `alt login failed: ${response.status}`); return extractCookie(response.headers.get('set-cookie')); } @@ -413,12 +466,24 @@ function extractCookie(setCookie: string | null): string { return setCookie.split(';')[0]!; } +/** Reads a `Set-Cookie` attribute (`''` for valueless flags such as `HttpOnly`). */ +function cookieAttribute(setCookie: string | null, name: string): string | null { + assert(setCookie, 'missing set-cookie header'); + for (const part of setCookie.split(';').slice(1)) { + const [key, ...valueParts] = part.trim().split('='); + if (key!.toLowerCase() === name.toLowerCase()) return valueParts.join('='); + } + return null; +} + /* ---------------------------------------------------------------------- main */ async function main(): Promise { const dataDir = mkdtempSync(join(tmpdir(), 'okr-e2e-')); const children: ChildProcess[] = []; try { + // Fail fast (and with a usable message) when a stray process holds a fixed port. + await Promise.all([assertPortFree(PORT), assertPortFree(MOCK_A_PORT), assertPortFree(MOCK_B_PORT)]); const mockA = startMock(MOCK_A_PORT, 'mockA'); const mockB = startMock(MOCK_B_PORT, 'mockB'); const server = startServer(dataDir); @@ -426,7 +491,11 @@ async function main(): Promise { collect(mockA); collect(mockB); collect(server); - await Promise.all([waitFor(`${MOCK_A.replace('/v1', '')}/__stats`), waitFor(`${MOCK_B.replace('/v1', '')}/__stats`), waitFor(`${BASE}/health`)]); + await Promise.all([ + waitForReady(`${MOCK_A.replace('/v1', '')}/__stats`, mockA, 'mockA'), + waitForReady(`${MOCK_B.replace('/v1', '')}/__stats`, mockB, 'mockB'), + waitForReady(`${BASE}/health`, server, 'server'), + ]); console.log(`\nOpenCode Router e2e — server ${BASE}, mocks ${MOCK_A} / ${MOCK_B}, data ${dataDir}\n`); /* ------------------------------------------------------------ routing/health */ @@ -494,6 +563,45 @@ async function main(): Promise { return 'session cookie issued'; }); + await check('session cookie carries HttpOnly, SameSite=Lax, Path=/ and Max-Age', async () => { + const response = await admin('/login', { body: { password: '123456' }, auth: false }); + const setCookie = response.headers.get('set-cookie'); + assert(response.ok, `login failed: ${response.status}`); + assert(cookieAttribute(setCookie, 'HttpOnly') === '', `HttpOnly missing: ${setCookie}`); + assert( + (cookieAttribute(setCookie, 'SameSite') ?? '').toLowerCase() === 'lax', + `SameSite=Lax missing: ${setCookie}`, + ); + assert(cookieAttribute(setCookie, 'Path') === '/', `Path=/ missing: ${setCookie}`); + const maxAge = Number(cookieAttribute(setCookie, 'Max-Age')); + assert(Number.isFinite(maxAge) && maxAge > 600_000, `Max-Age missing/too small: ${setCookie}`); + assert(cookieAttribute(setCookie, 'Secure') === null, `plain-http login must not set Secure: ${setCookie}`); + return `HttpOnly, SameSite=Lax, Max-Age=${maxAge}`; + }); + + await check('Secure cookie requires a trusted x-forwarded-proto', async () => { + let detail = ''; + await withAltServer({ TRUST_PROXY: 'true' }, async (base) => { + const trusted = await altLoginResponse(base, { 'x-forwarded-proto': 'https' }); + assert(trusted.ok, `trusted login failed: ${trusted.status}`); + assert( + cookieAttribute(trusted.headers.get('set-cookie'), 'Secure') === '', + `TRUST_PROXY=true + x-forwarded-proto=https must set Secure: ${trusted.headers.get('set-cookie')}`, + ); + detail = 'trusted proxy → Secure'; + }); + await withAltServer({}, async (base) => { + const untrusted = await altLoginResponse(base, { 'x-forwarded-proto': 'https' }); + assert(untrusted.ok, `untrusted login failed: ${untrusted.status}`); + assert( + cookieAttribute(untrusted.headers.get('set-cookie'), 'Secure') === null, + `untrusted x-forwarded-proto must not set Secure: ${untrusted.headers.get('set-cookie')}`, + ); + detail += ', no TRUST_PROXY → no Secure'; + }); + return detail; + }); + await check('dashboard becomes reachable after login', async () => { const response = await fetch(`${BASE}/dashboard/overview`, { headers: { cookie }, redirect: 'manual' }); const html = await response.text(); @@ -636,6 +744,51 @@ async function main(): Promise { return 'x-api-key accepted'; }); + await check('revoked gateway key → 401 invalid_api_key with exactly one log row', async () => { + const created = await adminJson<{ key: { id: string }; plaintext: string }>('/keys', { body: { name: 'revoked-e2e' } }); + try { + const before = await gateway('/v1/chat/completions', { + key: created.plaintext, + body: { model: MODEL, messages: [{ role: 'user', content: 'ping' }], max_tokens: 8 }, + }); + assert(before.ok, `fresh key was rejected (${before.status})`); + await adminJson(`/keys/${created.key.id}/revoke`, { method: 'POST' }); + const total = await logTotal(); + const response = await gateway('/v1/chat/completions', { + key: created.plaintext, + body: { model: MODEL, messages: [{ role: 'user', content: 'ping' }] }, + }); + const body = (await response.json()) as { error?: { code?: string } }; + assert(response.status === 401, `expected 401, got ${response.status}`); + assert(body.error?.code === 'invalid_api_key', `unexpected code ${body.error?.code}`); + const after = await waitForLogTotalStable(total + 1); + assert(after === total + 1, `expected exactly one new log row, delta=${after - total}`); + return '401 invalid_api_key, log delta 1'; + } finally { + await adminJson(`/keys/${created.key.id}`, { method: 'DELETE' }); + } + }); + + await check('disabled gateway key → 401 invalid_api_key with exactly one log row', async () => { + const created = await adminJson<{ key: { id: string }; plaintext: string }>('/keys', { body: { name: 'disabled-e2e' } }); + try { + await adminJson(`/keys/${created.key.id}`, { method: 'PATCH', body: { enabled: false } }); + const total = await logTotal(); + const response = await gateway('/v1/chat/completions', { + key: created.plaintext, + body: { model: MODEL, messages: [{ role: 'user', content: 'ping' }] }, + }); + const body = (await response.json()) as { error?: { code?: string } }; + assert(response.status === 401, `expected 401, got ${response.status}`); + assert(body.error?.code === 'invalid_api_key', `unexpected code ${body.error?.code}`); + const after = await waitForLogTotalStable(total + 1); + assert(after === total + 1, `expected exactly one new log row, delta=${after - total}`); + return '401 invalid_api_key, log delta 1'; + } finally { + await adminJson(`/keys/${created.key.id}`, { method: 'DELETE' }); + } + }); + await check('unauthenticated malformed JSON: 401 missing_api_key, one log row, one start/end pair', async () => { const feed = await openEventFeed(); // Give the SSE listener a moment to attach before the request fires. @@ -647,7 +800,7 @@ async function main(): Promise { const body = (await response.json()) as { error?: { code?: string } }; assert(response.status === 401, `expected 401 (auth before body parsing), got ${response.status}`); assert(body.error?.code === 'missing_api_key', `unexpected code ${body.error?.code}`); - const after = await waitForLogTotal(before + 1); + const after = await waitForLogTotalStable(before + 1); assert(after === before + 1, `expected exactly one new log row, delta=${after - before}`); const deadline = Date.now() + 3_000; while (Date.now() < deadline) { @@ -675,7 +828,7 @@ async function main(): Promise { const body = (await response.json()) as { error?: { code?: string; type?: string } }; assert(response.status === 400, `expected 400, got ${response.status}`); assert(body.error?.code === 'invalid_request', `unexpected code ${body.error?.code}`); - const after = await waitForLogTotal(before + 1); + const after = await waitForLogTotalStable(before + 1); assert(after === before + 1, `expected exactly one new log row, delta=${after - before}`); return '400 invalid_request, log delta 1'; }); @@ -727,7 +880,7 @@ async function main(): Promise { assert(typeof body.data[0]!.reasoning === 'object', 'expected reasoning metadata'); assert(response.headers.get('x-opencode-router-request-id'), 'missing router request id header'); assert(response.headers.get('x-opencode-router-provider') === null, 'models list must not carry a provider header'); - const after = await waitForLogTotal(before + 1); + const after = await waitForLogTotalStable(before + 1); assert(after === before + 1, `expected one log row for /v1/models, delta=${after - before}`); return `${body.data.length} models, request-id + 1 log row`; }); @@ -751,7 +904,7 @@ async function main(): Promise { const body = (await response.json()) as { error?: { code?: string } }; assert(response.status === 404, `expected 404, got ${response.status}`); assert(body.error?.code === 'model_not_found', `unexpected code ${body.error?.code}`); - const after = await waitForLogTotal(before + 1); + const after = await waitForLogTotalStable(before + 1); assert(after === before + 1, `expected one log row, delta=${after - before}`); return '404 model_not_found + 1 log row'; }); @@ -782,19 +935,74 @@ async function main(): Promise { assert(response.ok, `status ${response.status}`); assert(type.includes('text/event-stream'), `content-type ${type}`); assert(text.includes('chat.completion.chunk'), 'expected chat.completion.chunk frames'); + assert(!text.includes('x_opencode'), 'x_opencode leaked into the chat SSE stream'); const usageFrame = sseEvents(text).find((event) => event.usage) as { usage?: { total_tokens?: number } } | undefined; assert(usageFrame?.usage?.total_tokens, 'expected a usage frame in the stream'); return `${sseEvents(text).length} frames, usage=${usageFrame.usage.total_tokens}`; }); - await check('chat stream injects include_usage when absent', async () => { + await check('chat stream injects include_usage when absent (mock emits usage only when asked)', async () => { const response = await gateway('/v1/chat/completions', { body: { model: MODEL, messages: [{ role: 'user', content: 'hi' }], stream: true, max_tokens: 8 }, }); const text = await response.text(); const usage = (sseEvents(text).find((event) => event.usage) as { usage?: unknown } | undefined)?.usage; assert(usage, 'gateway did not request/forward usage'); - return 'usage forwarded'; + return 'usage forwarded without client stream_options'; + }); + + await check('chat stream keeps an explicit include_usage and never fabricates usage', async () => { + const explicit = await gateway('/v1/chat/completions', { + body: { + model: MODEL, + messages: [{ role: 'user', content: 'hi' }], + stream: true, + stream_options: { include_usage: true }, + max_tokens: 8, + }, + }); + const explicitText = await explicit.text(); + assert(explicit.ok, `status ${explicit.status}`); + assert( + sseEvents(explicitText).some((event) => event.usage), + 'explicit include_usage=true did not reach the upstream', + ); + + // The mock now omits usage entirely: the gateway must forward that absence + // instead of inventing a usage frame. + await mockControl(MOCK_A_PORT, { omitUsage: true }); + try { + const suppressed = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'hi' }], stream: true, max_tokens: 8 }, + }); + const suppressedText = await suppressed.text(); + assert(suppressed.ok, `status ${suppressed.status}`); + assert( + !sseEvents(suppressedText).some((event) => event.usage), + 'gateway fabricated a usage frame the upstream never sent', + ); + return 'explicit include_usage honoured, absent usage not invented'; + } finally { + await mockControl(MOCK_A_PORT, { reset: true }); + } + }); + + await check('chat stream strips an x_opencode key injected into an SSE frame', async () => { + await mockControl(MOCK_A_PORT, { chatStreamXOpencode: true }); + try { + const response = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'ping' }], stream: true, max_tokens: 8 }, + }); + const text = await response.text(); + assert(response.ok, `status ${response.status}`); + assert(!text.includes('x_opencode'), 'x_opencode leaked from a chat SSE frame'); + assert(!text.includes('ses_mock_stream_should_be_stripped'), 'provider session id leaked from an SSE frame'); + assert(sseEvents(text).length >= 3, 'frames were dropped while stripping x_opencode'); + assert(text.includes('chat.completion.chunk'), 'stream lost its chat chunks'); + return `${sseEvents(text).length} frames, injected x_opencode stripped`; + } finally { + await mockControl(MOCK_A_PORT, { reset: true }); + } }); /* ------------------------------------------------------ OpenAI responses */ @@ -804,6 +1012,7 @@ async function main(): Promise { assert(response.ok, `status ${response.status}`); assert(body.object === 'response', `unexpected object ${body.object}`); assert(body.output_text === 'responses', `unexpected text ${body.output_text}`); + assert(!JSON.stringify(body).includes('x_opencode'), 'x_opencode leaked from the responses body'); return `status=${body.status} text=${body.output_text}`; }); @@ -813,6 +1022,7 @@ async function main(): Promise { assert(response.ok, `status ${response.status}`); assert(text.includes('response.created'), 'expected response.created'); assert(text.includes('response.completed'), 'expected response.completed'); + assert(!text.includes('x_opencode'), 'x_opencode leaked into the responses SSE stream'); const completed = sseEvents(text).find((event) => event.type === 'response.completed') as | { response?: { usage?: { total_tokens?: number } } } | undefined; @@ -829,6 +1039,7 @@ async function main(): Promise { assert(response.ok, `status ${response.status}`); assert(body.type === 'message', `unexpected type ${body.type}`); assert(body.content?.[0]?.text === 'messages', `unexpected text ${JSON.stringify(body.content)}`); + assert(!JSON.stringify(body).includes('x_opencode'), 'x_opencode leaked from the messages body'); return `type=message blocks=${body.content.length}`; }); @@ -840,6 +1051,7 @@ async function main(): Promise { assert(response.ok, `status ${response.status}`); assert(text.includes('message_start'), 'expected message_start'); assert(text.includes('message_stop'), 'expected message_stop'); + assert(!text.includes('x_opencode'), 'x_opencode leaked into the messages SSE stream'); const delta = sseEvents(text).find((event) => event.type === 'message_delta') as | { usage?: { output_tokens?: number } } | undefined; @@ -1073,23 +1285,39 @@ async function main(): Promise { }); await check('round-robin distributes across both providers', async () => { + // Reset the mock counters first: without this the previous checks' traffic would + // satisfy the assertions below even if this loop only ever hit one provider. + await mockControl(MOCK_A_PORT, { reset: true }); + await mockControl(MOCK_B_PORT, { reset: true }); for (let index = 0; index < 6; index += 1) { const response = await gateway('/v1/chat/completions', { body: { model: MODEL, messages: [{ role: 'user', content: `ping ${index}` }], max_tokens: 8 }, }); assert(response.ok, `request ${index} failed with ${response.status}`); } + roundRobinServed = { a: (await mockStats(MOCK_A_PORT)).served, b: (await mockStats(MOCK_B_PORT)).served }; + assert( + roundRobinServed.a >= 1 && roundRobinServed.b >= 1, + `expected both providers to serve, got A=${roundRobinServed.a} B=${roundRobinServed.b}`, + ); + assert( + roundRobinServed.a + roundRobinServed.b === 6, + `expected exactly 6 upstream calls, got A=${roundRobinServed.a} B=${roundRobinServed.b}`, + ); const stats = await adminJson<{ byProvider: Array<{ providerId: string }> }>('/stats?window=1h'); const ids = new Set(stats.byProvider.map((entry) => entry.providerId)); assert(ids.has('primary') && ids.has('secondary'), `expected both providers, got ${[...ids].join(',') || 'none'}`); - return `providers used: ${[...ids].sort().join(', ')}`; + return `providers used: ${[...ids].sort().join(', ')} (A=${roundRobinServed.a} B=${roundRobinServed.b})`; }); await check('mock upstreams actually served the traffic', async () => { const a = await mockStats(MOCK_A_PORT); const b = await mockStats(MOCK_B_PORT); - assert(a.served >= 3 && b.served >= 3, `expected both mocks used, got A=${a.served} B=${b.served}`); - return `A=${a.served} B=${b.served}`; + assert( + a.served === roundRobinServed.a && b.served === roundRobinServed.b, + `unexpected extra upstream traffic since the round-robin loop: A=${a.served} B=${b.served}`, + ); + return `A=${a.served} B=${b.served} (6 round-robin calls, no retries)`; }); /* ------------------------------------------------------------ stream fidelity */ @@ -1130,7 +1358,7 @@ async function main(): Promise { ); }); const row = await findLogByUserAgent(marker); - if (!row) return 'skipped: server never logged the aborted request'; + assert(row, 'server never logged the aborted request'); assert(row.status === 499, `expected status 499, got ${row.status} (errorCode=${row.errorCode})`); assert(row.errorCode === 'client_aborted', `expected errorCode client_aborted, got ${row.errorCode}`); assert(row.ok === false, 'aborted request must not be ok'); @@ -1249,6 +1477,99 @@ async function main(): Promise { } }); + await check('non-retryable 400 → single attempt, no other provider burned', async () => { + await mockControl(MOCK_A_PORT, { reset: true }); + await mockControl(MOCK_B_PORT, { reset: true }); + await mockControl(MOCK_A_PORT, { alwaysStatus: 400 }); + // Deterministic order: the round-robin cursor is process state from earlier checks. + await adminJson('/settings', { method: 'PATCH', body: { rotation_strategy: 'priority' } }); + await adminJson('/providers', { body: { id: 'nr-400', name: 'NR 400', baseUrl: MOCK_A, apiKey: MOCK_KEY, priority: 1 } }); + await adminJson('/providers', { body: { id: 'nr-healthy', name: 'NR Healthy', baseUrl: MOCK_B, apiKey: MOCK_KEY, priority: 2 } }); + try { + let detail = ''; + await withOnlyProviders(['nr-400', 'nr-healthy'], async () => { + const response = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'client error' }], max_tokens: 8 }, + }); + const body = (await response.json()) as { error?: { code?: string } }; + assert(response.status === 400, `expected 400, got ${response.status}: ${JSON.stringify(body).slice(0, 150)}`); + assert(body.error?.code === 'provider.free-limit', `unexpected code ${body.error?.code}`); + const attempts = Number(response.headers.get('x-opencode-router-attempts')); + assert(attempts === 1, `expected exactly 1 attempt for a client error, got ${attempts}`); + const healthyTraffic = await mockStats(MOCK_B_PORT); + assert(healthyTraffic.served === 0, `a client error burned another provider (mockB served ${healthyTraffic.served})`); + detail = '400, attempts=1, second provider untouched'; + }); + return detail; + } finally { + await mockControl(MOCK_A_PORT, { reset: true }); + await adminJson('/settings', { method: 'PATCH', body: { rotation_strategy: 'round-robin' } }); + await adminJson('/providers/nr-400', { method: 'DELETE' }); + await adminJson('/providers/nr-healthy', { method: 'DELETE' }); + } + }); + + await check('503 failover: retryable upstream error moves to the next provider', async () => { + await mockControl(MOCK_A_PORT, { reset: true }); + await mockControl(MOCK_B_PORT, { reset: true }); + await mockControl(MOCK_A_PORT, { alwaysStatus: 503 }); + await adminJson('/settings', { method: 'PATCH', body: { rotation_strategy: 'priority' } }); + await adminJson('/providers', { body: { id: 'fo503-a', name: 'FO503 A', baseUrl: MOCK_A, apiKey: MOCK_KEY, priority: 1 } }); + await adminJson('/providers', { body: { id: 'fo503-b', name: 'FO503 B', baseUrl: MOCK_B, apiKey: MOCK_KEY, priority: 2 } }); + try { + let detail = ''; + await withOnlyProviders(['fo503-a', 'fo503-b'], async () => { + const response = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'ping' }], max_tokens: 8 }, + }); + const body = (await response.json()) as { choices?: Array<{ message?: { content?: string } }> }; + assert(response.ok, `expected failover success, got ${response.status}: ${JSON.stringify(body).slice(0, 150)}`); + assert((body.choices?.[0]?.message?.content ?? '').includes('mockB'), 'the healthy provider did not serve the failover'); + const attempts = Number(response.headers.get('x-opencode-router-attempts')); + assert(attempts === 2, `expected 2 attempts, got ${attempts}`); + detail = '503 → next provider, attempts=2'; + }); + return detail; + } finally { + await mockControl(MOCK_A_PORT, { reset: true }); + await adminJson('/settings', { method: 'PATCH', body: { rotation_strategy: 'round-robin' } }); + await adminJson('/providers/fo503-a', { method: 'DELETE' }); + await adminJson('/providers/fo503-b', { method: 'DELETE' }); + } + }); + + await check('short request_timeout_ms → 504 upstream_timeout, logged and attributed', async () => { + await mockControl(MOCK_A_PORT, { reset: true }); + await mockControl(MOCK_A_PORT, { delayMs: 5_000 }); + await adminJson('/settings', { method: 'PATCH', body: { request_timeout_ms: '1500' } }); + await adminJson('/providers', { body: { id: 'slow-a', name: 'Slow A', baseUrl: MOCK_A, apiKey: MOCK_KEY, priority: 1 } }); + try { + let detail = ''; + await withOnlyProviders(['slow-a'], async () => { + const response = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'too slow' }], max_tokens: 8 }, + }); + const body = (await response.json()) as { error?: { code?: string } }; + assert(response.status === 504, `expected 504, got ${response.status}: ${JSON.stringify(body).slice(0, 150)}`); + assert(body.error?.code === 'upstream_timeout', `unexpected code ${body.error?.code}`); + const requestId = response.headers.get('x-opencode-router-request-id'); + assert(requestId, 'missing request id on the timeout response'); + const row = await findLogById(requestId); + assert(row, 'the timed-out request was never logged'); + assert(row.status === 504, `log status=${row.status}`); + assert(row.errorCode === 'upstream_timeout', `log errorCode=${row.errorCode}`); + assert(row.attempts === 1, `log attempts=${row.attempts}, expected 1`); + assert(row.providerId === 'slow-a', `timed-out attempt not attributed: ${row.providerId}`); + detail = '504 upstream_timeout, attempts=1, attributed to slow-a'; + }); + return detail; + } finally { + await mockControl(MOCK_A_PORT, { reset: true }); + await adminJson('/providers/slow-a', { method: 'DELETE' }); + await adminJson('/settings', { method: 'PATCH', body: { request_timeout_ms: '600000' } }); + } + }); + await check('Retry-After longer than the configured cooldown is honoured', async () => { await mockControl(MOCK_A_PORT, { reset: true }); await mockControl(MOCK_A_PORT, { retryAfterSeconds: 2 }); @@ -1306,7 +1627,14 @@ async function main(): Promise { const body = (await response.json()) as { error?: { code?: string } }; assert(response.status === 429, `expected 429, got ${response.status}`); assert(body.error?.code === 'all_providers_rate_limited', `unexpected code ${body.error?.code}`); - return '429 all_providers_rate_limited'; + const retryAfter = Number(response.headers.get('retry-after')); + assert(Number.isInteger(retryAfter) && retryAfter >= 1, `retry-after header=${response.headers.get('retry-after')}`); + const cooldownUntil = Number(response.headers.get('x-opencode-router-cooldown-until')); + assert( + Number.isFinite(cooldownUntil) && cooldownUntil > Date.now(), + `x-opencode-router-cooldown-until=${response.headers.get('x-opencode-router-cooldown-until')}`, + ); + return `429 all_providers_rate_limited, retry-after=${retryAfter}s, cooldown-until set`; } finally { await mockControl(MOCK_A_PORT, { reset: true }); await mockControl(MOCK_B_PORT, { reset: true }); @@ -1335,14 +1663,20 @@ async function main(): Promise { body.logs.filter((log) => log.ok && log.attempts > 0).every((log) => log.providerName !== null), 'expected provider attribution on successful proxied rows', ); - // `/v1/models*` is now logged too (FIX-16): one row per metadata read, no provider. - const modelsRows = body.logs.filter((log) => log.attempts === 0 && log.ok); - assert(modelsRows.length > 0, 'expected /v1/models metadata reads to produce log rows'); - assert( - modelsRows.every((log) => log.providerId === null && log.providerName === null && log.surface === 'chat'), - 'models rows must have attempts=0, no provider attribution and the chat surface', - ); - return `total=${body.total} (${modelsRows.length} models rows)`; + // `/v1/models*` is logged too (FIX-16). Identify the row by the captured router + // request id instead of guessing from `attempts === 0`, which also matches + // rejected/unauthenticated rows. + const modelsResponse = await fetch(`${BASE}/v1/models`, { headers: { authorization: `Bearer ${gatewayKey}` } }); + const modelsRequestId = modelsResponse.headers.get('x-opencode-router-request-id'); + assert(modelsResponse.ok, `models list failed: ${modelsResponse.status}`); + assert(modelsRequestId, 'models response is missing x-opencode-router-request-id'); + await modelsResponse.text(); + const modelsRow = await findLogById(modelsRequestId); + assert(modelsRow, `no log row recorded for the /v1/models request ${modelsRequestId}`); + assert(modelsRow.attempts === 0, `models row attempts=${modelsRow.attempts}, expected 0`); + assert(modelsRow.providerId === null && modelsRow.providerName === null, 'models rows must not carry provider attribution'); + assert(modelsRow.surface === 'chat', `models row surface=${modelsRow.surface}, expected chat`); + return `total=${body.total} (models row ${modelsRequestId.slice(0, 8)}: attempts=0, no provider)`; }); await check('stats overview aggregates traffic', async () => { @@ -1512,6 +1846,57 @@ async function main(): Promise { return detail; }); + await check('login brute-force guard → 429 with Retry-After after 10 failures', async () => { + let detail = ''; + await withAltServer({}, async (base) => { + const statuses: number[] = []; + for (let index = 0; index < 11; index += 1) { + const response = await fetch(`${base}/admin/api/login`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ password: `wrong-${index}` }), + }); + statuses.push(response.status); + if (response.status === 429) { + const body = (await response.json()) as { error?: { code?: string; retryAfter?: number } }; + assert(body.error?.code === 'too_many_attempts', `unexpected code ${body.error?.code}`); + const retryAfter = body.error?.retryAfter; + assert(typeof retryAfter === 'number' && retryAfter >= 1, `body retryAfter=${retryAfter}`); + assert( + response.headers.get('retry-after') === String(retryAfter), + `retry-after header ${response.headers.get('retry-after')} != body retryAfter ${retryAfter}`, + ); + } else { + // Drain the body so the connection can be reused. + await response.text(); + } + } + assert( + statuses.slice(0, 10).every((status) => status === 401), + `expected ten 401s first, got ${statuses.join(',')}`, + ); + assert(statuses[10] === 429, `expected the 11th attempt to be 429, got ${statuses.join(',')}`); + detail = '401×10 then 429 with Retry-After header + body retryAfter'; + }); + return detail; + }); + + await check('no provider key material in any admin response', async () => { + const endpoints = ['/providers', '/bootstrap', '/models', '/keys', '/settings', '/logs?limit=200', '/audit?limit=200', '/stats?window=1h']; + for (const endpoint of endpoints) { + const response = await admin(endpoint); + assert(response.ok, `${endpoint} → ${response.status}`); + const text = await response.text(); + assert(!text.includes(MOCK_KEY), `${endpoint} leaked the provider API key`); + assert(!text.includes('"apiKey"'), `${endpoint} exposes a raw apiKey field`); + } + const exportJson = await admin('/logs/export?format=json'); + assert(exportJson.ok, `log export ${exportJson.status}`); + const exportText = await exportJson.text(); + assert(!exportText.includes(MOCK_KEY), 'log export leaked the provider API key'); + return `${endpoints.length} admin endpoints + log export clean`; + }); + await check('rotate-secret refuses with 409 when ROUTER_SECRET is set and keeps sessions', async () => { let detail = ''; await withAltServer({ ROUTER_SECRET: 'e2e-alt-secret' }, async (base) => { diff --git a/scripts/live-check.ts b/scripts/live-check.ts index 1f5f289..d95d53a 100644 --- a/scripts/live-check.ts +++ b/scripts/live-check.ts @@ -6,9 +6,10 @@ import { join } from 'node:path'; /** * Live smoke test against a real provider endpoint (default: the reference provider). * - * Unlike scripts/e2e.ts (deterministic mocks) this hits the network. When the provider - * answers with a rate-limit/quota error every probe is reported as SKIP instead of FAIL, - * so the command stays useful after a free-tier quota is exhausted. + * Unlike scripts/e2e.ts (deterministic mocks) this hits the network. When the upstream + * answers `429` (rate limit/quota) the affected probe is reported as SKIP instead of + * FAIL, so the command stays useful after a free-tier quota is exhausted. The decision + * comes from the upstream status alone — never from the wording of an error message. * * Usage: pnpm test:live * Env: LIVE_PORT (20194), LIVE_UPSTREAM, LIVE_KEY, LIVE_MODEL, LIVE_VISION_MODEL @@ -25,7 +26,12 @@ type Outcome = 'PASS' | 'FAIL' | 'SKIP'; const outcomes: Array<{ name: string; outcome: Outcome; detail: string }> = []; let cookie = ''; let gatewayKey = ''; -let quotaBlocked = false; + +/** + * Raised when the upstream itself reports a rate limit/quota (`429`). SKIP is derived + * from that status, never from the wording of an error message. + */ +class UpstreamQuotaError extends Error {} function report(name: string, outcome: Outcome, detail: string): void { outcomes.push({ name, outcome, detail }); @@ -41,11 +47,11 @@ async function check(name: string, fn: () => Promise): Promise(path: string, options: { method?: string; body?: unknown } = {}): Promise { const response = await admin(path, options); const text = await response.text(); - if (!response.ok) throw new Error(`${path} → ${response.status}: ${text.slice(0, 300)}`); + if (!response.ok) { + const detail = `${path} → ${response.status}: ${text.slice(0, 300)}`; + // Status-driven SKIP: a quota-limited upstream surfaces as 429 through the admin API. + if (response.status === 429) throw new UpstreamQuotaError(detail); + throw new Error(detail); + } return text ? (JSON.parse(text) as T) : ({} as T); } @@ -121,7 +132,12 @@ async function main(): Promise { const providerTest = await admin('/providers/test', { body: { baseUrl: UPSTREAM, apiKey: UPSTREAM_KEY } }); const probe = (await providerTest.json()) as { ok: boolean; models: number; error: string | null; status: number }; - report('provider reachable', probe.ok ? 'PASS' : 'SKIP', probe.ok ? `${probe.models} models` : `status=${probe.status} ${probe.error}`); + // SKIP only for a real rate limit (429); an unreachable/erroring provider is a FAIL. + report( + 'provider reachable', + probe.ok ? 'PASS' : probe.status === 429 ? 'SKIP' : 'FAIL', + probe.ok ? `${probe.models} models` : `status=${probe.status} ${probe.error}`, + ); await adminJson('/providers', { body: { id: 'live', name: 'Live Provider', baseUrl: UPSTREAM, apiKey: UPSTREAM_KEY, priority: 1 }, @@ -135,7 +151,12 @@ async function main(): Promise { }); } else { await adminJson('/models', { body: { id: MODEL, name: MODEL } }); - report('sync models', 'SKIP', 'provider unreachable, added manual model row instead'); + // Same status-driven decision as the probe itself. + report( + 'sync models', + probe.status === 429 ? 'SKIP' : 'FAIL', + `provider not reachable (status=${probe.status}); added a manual model row instead`, + ); } const key = await adminJson<{ plaintext: string }>('/keys', { body: { name: 'live' } }); @@ -146,10 +167,7 @@ async function main(): Promise { body: { model: MODEL, messages: [{ role: 'user', content: 'Reply with the single word: router' }], max_tokens: 32 }, }); const text = await response.text(); - if (response.status === 429) { - quotaBlocked = true; - throw new Error(text.slice(0, 200)); - } + if (response.status === 429) throw new UpstreamQuotaError(`upstream status 429: ${text.slice(0, 200)}`); assert(response.ok, `status ${response.status}: ${text.slice(0, 200)}`); const body = JSON.parse(text) as { choices?: Array<{ message?: { content?: string } }>; usage?: { total_tokens?: number } }; return `provider=${response.headers.get('x-opencode-router-provider')} tokens=${body.usage?.total_tokens} text="${(body.choices?.[0]?.message?.content ?? '').slice(0, 24)}"`; @@ -160,10 +178,7 @@ async function main(): Promise { body: { model: MODEL, stream: true, max_tokens: 32, messages: [{ role: 'user', content: 'Count 1 to 3.' }] }, }); const text = await response.text(); - if (response.status === 429) { - quotaBlocked = true; - throw new Error(text.slice(0, 200)); - } + if (response.status === 429) throw new UpstreamQuotaError(`upstream status 429: ${text.slice(0, 200)}`); assert(response.ok, `status ${response.status}`); assert(text.includes('chat.completion.chunk'), 'no SSE chunks'); return `${text.split('\n\n').length} frames`; @@ -172,10 +187,7 @@ async function main(): Promise { await check('responses API', async () => { const response = await gateway('/v1/responses', { body: { model: MODEL, input: 'Reply with the single word: responses' } }); const text = await response.text(); - if (response.status === 429) { - quotaBlocked = true; - throw new Error(text.slice(0, 200)); - } + if (response.status === 429) throw new UpstreamQuotaError(`upstream status 429: ${text.slice(0, 200)}`); assert(response.ok, `status ${response.status}: ${text.slice(0, 200)}`); const body = JSON.parse(text) as { object?: string; output_text?: string }; return `${body.object} "${(body.output_text ?? '').slice(0, 24)}"`; @@ -186,10 +198,7 @@ async function main(): Promise { body: { model: MODEL, max_tokens: 32, messages: [{ role: 'user', content: 'Reply with the single word: messages' }] }, }); const text = await response.text(); - if (response.status === 429) { - quotaBlocked = true; - throw new Error(text.slice(0, 200)); - } + if (response.status === 429) throw new UpstreamQuotaError(`upstream status 429: ${text.slice(0, 200)}`); assert(response.ok, `status ${response.status}: ${text.slice(0, 200)}`); const body = JSON.parse(text) as { type?: string; content?: Array<{ text?: string }> }; return `${body.type ?? 'unknown'} "${(body.content?.[0]?.text ?? '').slice(0, 24)}"`; @@ -214,10 +223,7 @@ async function main(): Promise { }, }); const text = await response.text(); - if (response.status === 429) { - quotaBlocked = true; - throw new Error(text.slice(0, 200)); - } + if (response.status === 429) throw new UpstreamQuotaError(`upstream status 429: ${text.slice(0, 200)}`); assert(response.ok, `status ${response.status}: ${text.slice(0, 200)}`); const body = JSON.parse(text) as { choices?: Array<{ message?: { tool_calls?: Array<{ function: { name: string } }> } }> }; const call = body.choices?.[0]?.message?.tool_calls?.[0]; @@ -244,10 +250,7 @@ async function main(): Promise { }, }); const text = await response.text(); - if (response.status === 429) { - quotaBlocked = true; - throw new Error(text.slice(0, 200)); - } + if (response.status === 429) throw new UpstreamQuotaError(`upstream status 429: ${text.slice(0, 200)}`); assert(response.ok, `status ${response.status}: ${text.slice(0, 200)}`); const body = JSON.parse(text) as { choices?: Array<{ message?: { content?: string } }> }; return `"${(body.choices?.[0]?.message?.content ?? '').slice(0, 24)}"`; diff --git a/scripts/mock-upstream.ts b/scripts/mock-upstream.ts index beeb722..80a2be2 100644 --- a/scripts/mock-upstream.ts +++ b/scripts/mock-upstream.ts @@ -55,6 +55,10 @@ interface Control { frameDelayMs: number; /** Prefix the chat stream with raw bytes: a UTF-8 BOM + a comment line holding a lone 0x80. */ fidelityFrames: boolean; + /** Suppress the chat-stream usage frame even when the client asked for usage. */ + omitUsage: boolean; + /** Inject a top-level `x_opencode` key into the first chat SSE data frame. */ + chatStreamXOpencode: boolean; served: number; total: number; } @@ -66,6 +70,8 @@ const control: Control = { retryAfterSeconds: null, frameDelayMs: 0, fidelityFrames: false, + omitUsage: false, + chatStreamXOpencode: false, served: 0, total: 0, }; @@ -94,6 +100,12 @@ function sseStart(res: ServerResponse): void { }); } +/** True when the (already normalized) request asked the provider for stream usage. */ +function includeUsageRequested(body: Record): boolean { + const options = body.stream_options as { include_usage?: boolean } | undefined; + return options?.include_usage === true; +} + function sse(res: ServerResponse, event: string | null, data: unknown): void { const lines: string[] = []; if (event) lines.push(`event: ${event}`); @@ -226,6 +238,7 @@ async function handleChat(req: IncomingMessage, res: ServerResponse): Promise = { id: 'chatcmpl-mock', object: 'chat.completion.chunk', created: Date.now(), model, choices: [{ index: 0, delta: { role: 'assistant', content: '' }, finish_reason: null }], - }); + }; + // e2e: provider-internal metadata injected into a live SSE frame must be stripped. + if (control.chatStreamXOpencode) firstChunk.x_opencode = { session_id: 'ses_mock_stream_should_be_stripped' }; + sse(res, null, firstChunk); if (reasoning) { if (control.frameDelayMs > 0) await sleep(control.frameDelayMs); sse(res, null, { @@ -325,20 +345,22 @@ async function handleChat(req: IncomingMessage, res: ServerResponse): Promise { + // The e2e suite aborts requests (client abort, upstream timeout); writing to a dead + // socket must not crash the deterministic upstream. + res.on('error', () => undefined); try { const url = new URL(req.url ?? '/', `http://127.0.0.1:${PORT}`); const path = url.pathname.replace(/\/+$/, '') || '/'; @@ -566,6 +591,8 @@ const server = createServer(async (req, res) => { control.retryAfterSeconds = null; control.frameDelayMs = 0; control.fidelityFrames = false; + control.omitUsage = false; + control.chatStreamXOpencode = false; } if (body.failAfter !== undefined) control.failAfter = body.failAfter; if (body.alwaysStatus !== undefined) control.alwaysStatus = body.alwaysStatus; @@ -573,6 +600,8 @@ const server = createServer(async (req, res) => { if (body.retryAfterSeconds !== undefined) control.retryAfterSeconds = body.retryAfterSeconds; if (body.frameDelayMs !== undefined) control.frameDelayMs = body.frameDelayMs; if (body.fidelityFrames !== undefined) control.fidelityFrames = body.fidelityFrames; + if (body.omitUsage !== undefined) control.omitUsage = body.omitUsage; + if (body.chatStreamXOpencode !== undefined) control.chatStreamXOpencode = body.chatStreamXOpencode; json(res, 200, { ...control, authFailures: authFailures.slice(-5) }); return; } diff --git a/scripts/screenshots.ts b/scripts/screenshots.ts index fd15ed4..d9c141c 100644 --- a/scripts/screenshots.ts +++ b/scripts/screenshots.ts @@ -1,14 +1,19 @@ import { spawn, type ChildProcess } from 'node:child_process'; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { access } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; /** * Visual verification harness: boots OpenCode Router with seeded demo data (mocked * upstreams), drives headless Chrome over CDP, captures every dashboard tab in dark * and light mode and reports console errors. * - * Usage: pnpm exec tsx scripts/screenshots.ts [--out ./tmp/screenshots] [--port 20193] + * Usage: pnpm exec tsx scripts/screenshots.ts [--out ./tmp/screenshots] [--port 20193] [--strict] + * + * --strict turns an unrunnable check (no Chrome) into a failure instead of a silent + * `SKIP` exit 0; CI runs the harness with it. Env: CHROME_PATH overrides the binary. */ const args = process.argv.slice(2); @@ -16,6 +21,7 @@ function arg(name: string, fallback: string): string { const index = args.indexOf(`--${name}`); return index >= 0 ? (args[index + 1] ?? fallback) : fallback; } +const STRICT = args.includes('--strict'); const OUT_DIR = resolve(arg('out', './tmp/screenshots')); const PORT = Number(arg('port', '20193')); @@ -37,6 +43,23 @@ const SHOTS: Array<{ path: string; name: string; theme: 'dark' | 'light' }> = [ /* --------------------------------------------------------------------- helpers */ +/** + * Verifies a Chrome binary is usable. Without `--strict` a missing browser is a silent + * `SKIP` exit 0; with it (CI) the run fails, so a check that captured nothing cannot + * pass. `CHROME_PATH` is trusted as-is. + */ +export async function ensureChrome(chromePath: string, strict: boolean): Promise<'ok' | 'skip'> { + if (process.env.CHROME_PATH) return 'ok'; + try { + await access(chromePath); + return 'ok'; + } catch { + if (strict) throw new Error(`Chrome not found at ${chromePath}; --strict refuses to skip the UI check`); + console.log(`SKIP Chrome not found at ${chromePath}`); + return 'skip'; + } +} + async function waitFor(url: string, timeoutMs = 30_000): Promise { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { @@ -181,14 +204,7 @@ class Cdp { /* ------------------------------------------------------------------------ main */ async function main(): Promise { - if (!process.env.CHROME_PATH) { - try { - await (await import('node:fs/promises')).access(CHROME); - } catch { - console.log(`SKIP Chrome not found at ${CHROME}`); - return; - } - } + if ((await ensureChrome(CHROME, STRICT)) === 'skip') return; mkdirSync(OUT_DIR, { recursive: true }); const dataDir = mkdtempSync(join(tmpdir(), 'okr-shots-')); const profile = mkdtempSync(join(tmpdir(), 'okr-chrome-')); @@ -207,6 +223,8 @@ async function main(): Promise { DATA_DIR: dataDir, LOG_LEVEL: 'warn', NODE_ENV: 'production', + // The harness seeds loopback providers; without this the SSRF guard rejects them. + PROVIDER_ALLOW_PRIVATE_HOSTS: 'true', }); children.push(mock, server); await waitFor(`http://127.0.0.1:${MOCK_PORT}/__stats`); @@ -388,7 +406,13 @@ async function main(): Promise { } } -main().catch((error) => { - console.error('screenshot run failed:', error); - process.exitCode = 1; -}); \ No newline at end of file +/** True only when this file is the process entry point (keeps the module importable). */ +const isDirectRun = + process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url); + +if (isDirectRun) { + main().catch((error) => { + console.error('screenshot run failed:', error); + process.exitCode = 1; + }); +} \ No newline at end of file diff --git a/src/admin/auth.ts b/src/admin/auth.ts index 45a140e..e66491f 100644 --- a/src/admin/auth.ts +++ b/src/admin/auth.ts @@ -8,8 +8,10 @@ import { verifyDashboardPassword } from '../core/seed.js'; import { ADMIN_CREDENTIAL_BODY_LIMIT, ADMIN_VERSION, HttpError, asString, assertPasswordLength, audit, clientIp, jsonBody, userAgent } from './util.js'; import { clearSessionCookie, createSession, resolveSession, setSessionCookie } from './session.js'; -const LOGIN_WINDOW_MS = 5 * 60 * 1000; -const LOGIN_MAX_ATTEMPTS = 10; +export const LOGIN_WINDOW_MS = 5 * 60 * 1000; +export const LOGIN_MAX_ATTEMPTS = 10; +/** FEAT-08: global failure cap, so one botnet cannot hammer the login from many IPs. */ +export const LOGIN_GLOBAL_MAX_ATTEMPTS = 50; interface AttemptRecord { count: number; @@ -17,6 +19,7 @@ interface AttemptRecord { } const attempts = new Map(); +let globalAttempts: AttemptRecord = { count: 0, firstAt: 0 }; export const PUBLIC_ADMIN_ROUTES = new Set([ 'POST /admin/api/login', @@ -27,6 +30,7 @@ export const PUBLIC_ADMIN_ROUTES = new Set([ /** Test/ops helper: forget every recorded failed login. */ export function resetLoginAttempts(): void { attempts.clear(); + globalAttempts = { count: 0, firstAt: 0 }; } export function normalizeAdminPath(url: string): string { @@ -40,30 +44,47 @@ export function isPublicAdminRoute(method: string, url: string): boolean { return PUBLIC_ADMIN_ROUTES.has(`${method.toUpperCase()} ${normalizeAdminPath(url)}`); } -interface RateLimitHit { +export interface RateLimitHit { retryAfterMs: number; + /** Which bucket tripped: the caller's IP or the process-wide failure cap. */ + scope: 'ip' | 'global'; } -function checkLoginRateLimit(ip: string): RateLimitHit | null { - const record = attempts.get(ip); - if (!record) return null; +function windowHit(record: AttemptRecord | undefined, now: number, max: number): number | null { + if (!record || record.count < max) return null; + const elapsed = now - record.firstAt; + if (elapsed > LOGIN_WINDOW_MS) return null; + return LOGIN_WINDOW_MS - elapsed; +} + +/** Per-IP guard first (dashboards), then the FEAT-08 global cap (distributed bots). */ +export function checkLoginRateLimit(ip: string): RateLimitHit | null { const now = Date.now(); - if (now - record.firstAt > LOGIN_WINDOW_MS) { + const record = attempts.get(ip); + if (record && now - record.firstAt > LOGIN_WINDOW_MS) { attempts.delete(ip); - return null; + } else { + const retryAfterMs = windowHit(record, now, LOGIN_MAX_ATTEMPTS); + if (retryAfterMs !== null) return { retryAfterMs, scope: 'ip' }; } - if (record.count < LOGIN_MAX_ATTEMPTS) return null; - return { retryAfterMs: LOGIN_WINDOW_MS - (now - record.firstAt) }; + const globalRetry = windowHit(globalAttempts, now, LOGIN_GLOBAL_MAX_ATTEMPTS); + if (globalRetry !== null) return { retryAfterMs: globalRetry, scope: 'global' }; + return null; } -function recordLoginFailure(ip: string): void { +export function recordLoginFailure(ip: string): void { const now = Date.now(); const record = attempts.get(ip); if (!record || now - record.firstAt > LOGIN_WINDOW_MS) { attempts.set(ip, { count: 1, firstAt: now }); - return; + } else { + record.count += 1; + } + if (now - globalAttempts.firstAt > LOGIN_WINDOW_MS) { + globalAttempts = { count: 1, firstAt: now }; + } else { + globalAttempts.count += 1; } - record.count += 1; } function pruneAttempts(): void { @@ -71,6 +92,9 @@ function pruneAttempts(): void { for (const [ip, record] of attempts) { if (now - record.firstAt > LOGIN_WINDOW_MS) attempts.delete(ip); } + if (globalAttempts.count > 0 && now - globalAttempts.firstAt > LOGIN_WINDOW_MS) { + globalAttempts = { count: 0, firstAt: 0 }; + } } /** `onRequest` hook: rejects unauthenticated requests with `401 unauthorized`. */ @@ -98,7 +122,17 @@ export function registerAuthRoutes(scope: FastifyInstance, ctx: AppContext): voi const limited = checkLoginRateLimit(ip); if (limited) { const seconds = Math.max(1, Math.ceil(limited.retryAfterMs / 1000)); - throw new HttpError(429, 'too_many_attempts', `Too many failed login attempts. Try again in ${seconds}s.`); + // FEAT-08: standard `Retry-After` plus the same value in the JSON envelope, so + // both HTTP clients and the dashboard can back off correctly. + reply.header('retry-after', String(seconds)); + await reply.status(429).send({ + error: { + message: `Too many failed login attempts. Try again in ${seconds}s.`, + code: 'too_many_attempts', + retryAfter: seconds, + }, + }); + return; } const body = jsonBody(request); @@ -108,14 +142,14 @@ export function registerAuthRoutes(scope: FastifyInstance, ctx: AppContext): voi if (!verifyDashboardPassword(ctx, password)) { recordLoginFailure(ip); - audit(ctx, 'auth.login.failed', ip, `userAgent=${userAgent(request) ?? '-'}`); + audit(ctx, 'auth.login.failed', ip, `userAgent=${userAgent(request) ?? '-'}`, request); throw new HttpError(401, 'invalid_password', 'Invalid password'); } attempts.delete(ip); const session = createSession(ctx, request); setSessionCookie(ctx, request, reply, session.id, session.expiresAt); - audit(ctx, 'auth.login', session.id, `ip=${ip}`); + audit(ctx, 'auth.login', session.id, `ip=${ip}`, request); return { ok: true, expiresAt: session.expiresAt, sessionId: session.id }; }); @@ -123,7 +157,7 @@ export function registerAuthRoutes(scope: FastifyInstance, ctx: AppContext): voi const resolved = resolveSession(ctx, request); if (resolved) { ctx.repo.deleteSession(resolved.session.id); - audit(ctx, 'auth.logout', resolved.session.id, null); + audit(ctx, 'auth.logout', resolved.session.id, null, request); } clearSessionCookie(ctx, request, reply); return { ok: true }; diff --git a/src/admin/index.ts b/src/admin/index.ts index 3add8d4..582a3b0 100644 --- a/src/admin/index.ts +++ b/src/admin/index.ts @@ -3,7 +3,7 @@ * encapsulated Fastify scope so the session guard applies to every route in * this module except the explicit public allowlist (login/logout/session). */ -import type { FastifyInstance } from 'fastify'; +import type { FastifyInstance, FastifyReply } from 'fastify'; import type { AppContext } from '../core/context.js'; import { createAuthGuard, registerAuthRoutes } from './auth.js'; import { registerProviderRoutes } from './providers.js'; @@ -14,28 +14,37 @@ import { registerSettingsRoutes } from './settings.js'; import { registerStatsRoutes } from './stats.js'; import { HttpError } from './util.js'; +/** + * AD-11: `reply.send()` is thenable and rejects when the socket is already gone; + * an unhandled rejection from an error handler can take the process down. + */ +function sendQuietly(reply: FastifyReply, status: number, payload: unknown): void { + void Promise.resolve(reply.status(status).send(payload)).catch(() => {}); +} + export async function registerAdminRoutes(app: FastifyInstance, ctx: AppContext): Promise { await app.register( async (scope: FastifyInstance): Promise => { scope.setErrorHandler((error, request, reply) => { - const status = - error instanceof HttpError - ? error.statusCode - : typeof (error as { statusCode?: number }).statusCode === 'number' - ? (error as { statusCode: number }).statusCode - : 500; - const code = - error instanceof HttpError - ? error.code - : ((error as { code?: string }).code ?? (status >= 500 ? 'internal_error' : 'invalid_request')); - if (status >= 500) { + const isHttpError = error instanceof HttpError; + const status = isHttpError + ? error.statusCode + : typeof (error as { statusCode?: number }).statusCode === 'number' + ? (error as { statusCode: number }).statusCode + : 500; + if (status >= 500) ctx.logger?.error?.({ err: error, url: request.url }, 'admin request failed'); + if (!isHttpError && status >= 500) { // Driver/stack detail stays server-side; clients get a generic message. - ctx.logger?.error?.({ err: error, url: request.url }, 'admin request failed'); - void reply.status(status).send({ error: { message: 'Internal server error', code: 'internal_error' } }); + sendQuietly(reply, status, { error: { message: 'Internal server error', code: 'internal_error' } }); return; } + // HttpError messages are authored for clients (surface-shaped, FEAT-09), so + // they are returned even for 5xx; only unexpected errors are masked above. + const code = isHttpError + ? error.code + : ((error as { code?: string }).code ?? (status >= 500 ? 'internal_error' : 'invalid_request')); const message = error instanceof Error ? error.message : String(error); - void reply.status(status).send({ error: { message, code } }); + sendQuietly(reply, status, { error: { message, code } }); }); // Empty JSON bodies are legitimate for action routes (test, sync, revoke, diff --git a/src/admin/keys.ts b/src/admin/keys.ts index 2e089b3..c8019a6 100644 --- a/src/admin/keys.ts +++ b/src/admin/keys.ts @@ -47,7 +47,7 @@ export function registerKeyRoutes(scope: FastifyInstance, ctx: AppContext): void const body = jsonBody(request); const name = requireString(body.name, 'name'); const { row, plaintext } = ctx.repo.createApiKey(name); - audit(ctx, 'key.create', row.id, `name=${name} prefix=${row.keyPrefix}`); + audit(ctx, 'key.create', row.id, `name=${name} prefix=${row.keyPrefix}`, request); return { key: apiKeyView(row), plaintext }; }); @@ -65,7 +65,7 @@ export function registerKeyRoutes(scope: FastifyInstance, ctx: AppContext): void if (Object.keys(patch).length === 0) fail(400, 'invalid_request', 'No supported fields to update'); const updated = ctx.repo.updateApiKey(id, patch); if (!updated) throw new HttpError(404, 'key_not_found', `API key "${id}" not found`); - audit(ctx, 'key.update', id, `fields=${Object.keys(patch).join(',')}`); + audit(ctx, 'key.update', id, `fields=${Object.keys(patch).join(',')}`, request); return { key: apiKeyView(updated) }; }); @@ -74,7 +74,7 @@ export function registerKeyRoutes(scope: FastifyInstance, ctx: AppContext): void loadKey(ctx, id); const revoked = ctx.repo.updateApiKey(id, { revoked: true, enabled: false }); if (!revoked) throw new HttpError(404, 'key_not_found', `API key "${id}" not found`); - audit(ctx, 'key.revoke', id, `name=${revoked.name}`); + audit(ctx, 'key.revoke', id, `name=${revoked.name}`, request); return { key: apiKeyView(revoked) }; }); @@ -87,7 +87,7 @@ export function registerKeyRoutes(scope: FastifyInstance, ctx: AppContext): void const plaintext = generateApiKey(); const rotated = ctx.repo.rotateApiKey(id, plaintext); if (!rotated) throw new HttpError(404, 'key_not_found', `API key "${id}" not found`); - audit(ctx, 'key.rotate', id, `name=${existing.name} prefix=${rotated.keyPrefix}`); + audit(ctx, 'key.rotate', id, `name=${existing.name} prefix=${rotated.keyPrefix}`, request); return { key: apiKeyView(rotated), plaintext }; }); @@ -95,7 +95,7 @@ export function registerKeyRoutes(scope: FastifyInstance, ctx: AppContext): void const id = (request.params as { id: string }).id; const removed = ctx.repo.deleteApiKey(id); if (!removed) throw new HttpError(404, 'key_not_found', `API key "${id}" not found`); - audit(ctx, 'key.delete', id, `removed=${removed}`); + audit(ctx, 'key.delete', id, `removed=${removed}`, request); return { ok: true }; }); } diff --git a/src/admin/logs.ts b/src/admin/logs.ts index 7bf5c05..ccb71ee 100644 --- a/src/admin/logs.ts +++ b/src/admin/logs.ts @@ -71,7 +71,7 @@ export function registerLogRoutes(scope: FastifyInstance, ctx: AppContext): void const { rows, total } = ctx.repo.listLogs(query); const truncated = total > rows.length; const stamp = new Date().toISOString().replace(/[:.]/g, '-'); - audit(ctx, 'log.export', null, `format=${format} rows=${rows.length} total=${total}`); + audit(ctx, 'log.export', null, `format=${format} rows=${rows.length} total=${total}`, request); if (truncated) reply.header('x-export-truncated', 'true'); if (format === 'csv') { reply @@ -94,9 +94,9 @@ export function registerLogRoutes(scope: FastifyInstance, ctx: AppContext): void return { log: row, attempts: ctx.repo.listAttempts(id) }; }); - scope.delete('/logs', async () => { + scope.delete('/logs', async (request) => { const removed = ctx.repo.clearLogs(); - audit(ctx, 'log.clear', null, `removed=${removed}`); + audit(ctx, 'log.clear', null, `removed=${removed}`, request); return { ok: true, removed }; }); @@ -108,7 +108,7 @@ export function registerLogRoutes(scope: FastifyInstance, ctx: AppContext): void } const cutoff = Date.now() - parsed * 24 * 60 * 60 * 1000; const removed = ctx.repo.deleteLogsBefore(cutoff); - audit(ctx, 'log.prune', null, `days=${parsed} removed=${removed}`); + audit(ctx, 'log.prune', null, `days=${parsed} removed=${removed}`, request); return { removed }; }); } diff --git a/src/admin/models.ts b/src/admin/models.ts index 2a89f83..e066fef 100644 --- a/src/admin/models.ts +++ b/src/admin/models.ts @@ -18,7 +18,15 @@ import { stringList, requireString, } from './util.js'; -import { SETTING_MODELS_SYNC_PROVIDER_ID, SETTING_MODELS_SYNCED_AT, syncProviderModels } from './sync.js'; +import { + SETTING_MODELS_SYNC_PROVIDER_ID, + SETTING_MODELS_SYNCED_AT, + syncFailureMessage, + syncProviderModels, +} from './sync.js'; + +/** AD-05: the global body limit is 128 MB, so the id list needs its own cap. */ +export const MAX_BULK_MODEL_IDS = 1_000; function loadModel(ctx: AppContext, id: string): ModelRow { const model = ctx.repo.getModel(id); @@ -57,7 +65,7 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo enabled, source: 'manual', }); - audit(ctx, 'model.create', id, `source=manual name=${name}`); + audit(ctx, 'model.create', id, `source=manual name=${name}`, request); return { model: created.row }; }); @@ -98,7 +106,7 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo if (changed.length === 0) fail(400, 'invalid_request', 'No supported fields to update'); const updated = ctx.repo.updateModel(id, patch); if (!updated) throw new HttpError(404, 'model_not_found', `Model "${id}" not found`); - audit(ctx, 'model.update', id, `fields=${changed.join(',')}`); + audit(ctx, 'model.update', id, `fields=${changed.join(',')}`, request); return { model: updated }; }); @@ -106,7 +114,7 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo const id = (request.params as { '*': string })['*']; loadModel(ctx, id); ctx.repo.deleteModel(id); - audit(ctx, 'model.delete', id, null); + audit(ctx, 'model.delete', id, null, request); return { ok: true }; }); @@ -118,15 +126,14 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo } const ids = stringList(body.ids); if (!ids || ids.length === 0) fail(400, 'invalid_request', 'ids must be a non-empty array of model ids'); - let updated = 0; - for (const id of ids) { - if (action === 'delete') { - if (ctx.repo.deleteModel(id)) updated += 1; - } else if (ctx.repo.updateModel(id, { enabled: action === 'enable' })) { - updated += 1; - } + if (ids.length > MAX_BULK_MODEL_IDS) { + fail(400, 'invalid_request', `ids must contain at most ${MAX_BULK_MODEL_IDS} entries`); } - audit(ctx, `model.bulk.${action}`, null, `requested=${ids.length} updated=${updated}`); + // AD-05: one set-based statement in a transaction — no per-id event-loop work + // and no partial application if the write fails. + const updated = + action === 'delete' ? ctx.repo.deleteModels(ids) : ctx.repo.setModelsEnabled(ids, action === 'enable'); + audit(ctx, `model.bulk.${action}`, null, `requested=${ids.length} updated=${updated}`, request); return { updated }; }); @@ -144,7 +151,14 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo try { result = await syncProviderModels(ctx, provider); } catch (error) { - throw new HttpError(502, 'sync_failed', error instanceof Error ? error.message : String(error)); + if (error instanceof HttpError) throw error; + // FEAT-09: parity with the provider sync route — log the detail, return the + // client-safe message; never echo driver/upstream internals. + ctx.logger?.warn?.( + { providerId: provider.id, detail: error instanceof Error ? error.message : String(error) }, + 'model sync failed', + ); + throw new HttpError(502, 'sync_failed', syncFailureMessage(provider.name)); } ctx.repo.recordProviderSuccess(provider.id, result.latencyMs); ctx.events.emitProvider({ @@ -159,6 +173,7 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo 'model.sync', provider.id, `added=${result.added} updated=${result.updated} removed=${result.removed} total=${result.total}`, + request, ); return result; }); diff --git a/src/admin/providers.ts b/src/admin/providers.ts index 35346d0..1ecb6ff 100644 --- a/src/admin/providers.ts +++ b/src/admin/providers.ts @@ -10,6 +10,7 @@ import { asBool, asInt, asString, + assertNoControlChars, assertPublicProviderUrl, audit, fail, @@ -60,6 +61,15 @@ export function providerView(provider: ProviderRow): ProviderView { }; } +/** Origin of a provider base URL, or null when it does not parse. */ +function originOf(baseUrl: string): string | null { + try { + return new URL(baseUrl).origin; + } catch { + return null; + } +} + function priorityFrom(value: unknown): number { const parsed = asInt(value); if (parsed === null) fail(400, 'invalid_request', 'priority must be an integer'); @@ -92,6 +102,7 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): scope.post('/providers', async (request) => { const body = jsonBody(request); const name = requireString(body.name, 'name'); + assertNoControlChars(name, 'name'); const baseUrl = httpBaseUrl(body.baseUrl); assertPublicProviderUrl(baseUrl, ctx.config.providerAllowPrivateHosts); const apiKey = asString(body.apiKey); @@ -100,11 +111,12 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): if (enabled === null) fail(400, 'invalid_request', 'enabled must be true or false'); const priority = body.priority === undefined ? 100 : priorityFrom(body.priority); const id = asString(body.id) ?? undefined; + if (id) assertNoControlChars(id, 'id'); if (id && ctx.repo.getProvider(id)) { throw new HttpError(409, 'provider_exists', `Provider "${id}" already exists`); } const provider = ctx.repo.createProvider({ id, name, baseUrl, apiKey, enabled, priority }); - audit(ctx, 'provider.create', provider.id, `${provider.name} ${provider.baseUrl}`); + audit(ctx, 'provider.create', provider.id, `${provider.name} ${provider.baseUrl}`, request); return { provider: providerView(provider) }; }); @@ -117,6 +129,7 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): if (body.name !== undefined) { patch.name = requireString(body.name, 'name'); + assertNoControlChars(patch.name, 'name'); changed.push('name'); } if (body.baseUrl !== undefined) { @@ -141,18 +154,25 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): changed.push('priority'); } if (changed.length === 0) fail(400, 'invalid_request', 'No supported fields to update'); + // AD-07: a replaced URL/key or a re-enabled provider must not stay skipped by + // rotation because of a cooldown recorded against the old configuration. + if (changed.some((field) => field === 'baseUrl' || field === 'apiKey' || field === 'enabled')) { + patch.status = 'unknown'; + patch.cooldownUntil = null; + } const updated = ctx.repo.updateProvider(id, patch); if (!updated) throw new HttpError(404, 'provider_not_found', `Provider "${id}" not found`); - audit(ctx, 'provider.update', id, `fields=${changed.join(',')} previous=${current.name}`); + audit(ctx, 'provider.update', id, `fields=${changed.join(',')} previous=${current.name}`, request); return { provider: providerView(updated) }; }); scope.delete('/providers/:id', async (request) => { const id = (request.params as { id: string }).id; const current = loadProvider(ctx, id); - ctx.repo.deleteProvider(id); - audit(ctx, 'provider.delete', id, current.name); - return { ok: true }; + // AD-02: the provider's synced models go with it (no FK constraints exist). + const { modelsRemoved } = ctx.repo.deleteProviderWithModels(id); + audit(ctx, 'provider.delete', id, `${current.name} modelsRemoved=${modelsRemoved}`, request); + return { ok: true, modelsRemoved }; }); // Test before save — no persisted state required. `id` lets the dashboard probe @@ -167,6 +187,16 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): if (!id) fail(400, 'invalid_request', 'apiKey is required'); const stored = ctx.repo.getProvider(id); if (!stored) throw new HttpError(404, 'provider_not_found', `Provider "${id}" not found`); + // AD-04: reusing the stored key is only safe for the origin it was saved for; + // otherwise this endpoint would exfiltrate a provider credential to any host. + const draftOrigin = originOf(baseUrl); + if (draftOrigin === null || draftOrigin !== originOf(stored.baseUrl)) { + fail( + 400, + 'api_key_required', + 'apiKey is required when the baseUrl origin differs from the stored provider', + ); + } apiKey = asString(stored.apiKey); if (!apiKey) fail(400, 'invalid_request', 'apiKey is required'); } @@ -198,6 +228,7 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): probe.ok ? `ok models=${probe.models.length} latencyMs=${probe.latencyMs}` : `failed status=${probe.status} error=${probe.error ?? ''}`, + request, ); return { ok: probe.ok, @@ -215,15 +246,13 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): try { result = await syncProviderModels(ctx, provider); } catch (error) { + // The SSRF guard fails with a 400; only upstream failures become a 502. + if (error instanceof HttpError) throw error; ctx.logger?.warn?.( { providerId: provider.id, detail: error instanceof Error ? error.message : String(error) }, 'provider model sync failed', ); - throw new HttpError( - 502, - 'sync_failed', - syncFailureMessage(provider.name), - ); + throw new HttpError(502, 'sync_failed', syncFailureMessage(provider.name)); } ctx.repo.recordProviderSuccess(provider.id, result.latencyMs); ctx.events.emitProvider({ @@ -238,6 +267,7 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): 'provider.sync', provider.id, `added=${result.added} updated=${result.updated} removed=${result.removed} total=${result.total}`, + request, ); return result; }); diff --git a/src/admin/session.ts b/src/admin/session.ts index 2def50f..0bf60d1 100644 --- a/src/admin/session.ts +++ b/src/admin/session.ts @@ -58,11 +58,26 @@ export function parseSessionCookie(value: string | undefined | null): SessionCoo return { sid, expiresAt, signature }; } +/** + * AD-09: `x-forwarded-proto` is attacker controlled unless `TRUST_PROXY` says a + * proxy sits in front (and strips/sets it). Without that opt-in the header must + * not influence the `Secure` cookie attribute. + */ +export function trustProxyEnabled(ctx?: AppContext): boolean { + const trust = ctx?.config.trustProxy; + if (trust === true) return true; + if (typeof trust === 'string') return trust.trim().length > 0; + if (Array.isArray(trust)) return trust.length > 0; + return false; +} + export function isSecureRequest(request: FastifyRequest, ctx?: AppContext): boolean { if (request.protocol === 'https') return true; - const forwarded = request.headers['x-forwarded-proto']; - const value = Array.isArray(forwarded) ? forwarded[0] : forwarded; - if (typeof value === 'string' && value.split(',')[0]?.trim().toLowerCase() === 'https') return true; + if (trustProxyEnabled(ctx)) { + const forwarded = request.headers['x-forwarded-proto']; + const value = Array.isArray(forwarded) ? forwarded[0] : forwarded; + if (typeof value === 'string' && value.split(',')[0]?.trim().toLowerCase() === 'https') return true; + } // A deployment that advertises an https PUBLIC_URL is served over TLS even when // the socket is plain http (TLS terminated in front), so never drop `Secure`. return ctx?.config.publicUrl?.startsWith('https://') ?? false; diff --git a/src/admin/settings.ts b/src/admin/settings.ts index 2d1d28d..5347f4e 100644 --- a/src/admin/settings.ts +++ b/src/admin/settings.ts @@ -16,6 +16,7 @@ import { asBool, asInt, asString, + assertNoControlChars, assertPasswordLength, audit, fail, @@ -33,6 +34,9 @@ const INT_SETTINGS: Record = { request_timeout_ms: { min: 1_000, max: 3_600_000 }, model_sync_interval_ms: { min: 30_000, max: 86_400_000 }, log_retention_days: { min: 1, max: 3_650 }, + audit_retention_days: { min: 1, max: 3_650 }, + // GW-05: per-chunk SSE idle deadline, well below the total request timeout. + stream_idle_timeout_ms: { min: 1_000, max: 3_600_000 }, }; const ROTATION_STRATEGIES = new Set(['round-robin', 'priority', 'random']); @@ -41,11 +45,15 @@ function settingsView(ctx: AppContext): { settings: Record range.max) { fail(400, 'invalid_request', `${key} must be between ${range.min} and ${range.max}`); } - ctx.repo.setSetting(key, String(parsed)); return String(parsed); } if (key === 'rotation_strategy') { @@ -65,7 +72,6 @@ function applySetting(ctx: AppContext, key: string, value: unknown): string | nu if (!parsed || !ROTATION_STRATEGIES.has(parsed)) { fail(400, 'invalid_request', `rotation_strategy must be one of ${[...ROTATION_STRATEGIES].join(', ')}`); } - ctx.repo.setSetting(key, parsed); return parsed; } if (key === 'upstream_user_agent') { @@ -73,7 +79,8 @@ function applySetting(ctx: AppContext, key: string, value: unknown): string | nu if (!parsed || parsed.length > 200) { fail(400, 'invalid_request', 'upstream_user_agent must be a string of at most 200 characters'); } - ctx.repo.setSetting(key, parsed); + // GW-10: CR/LF would make every upstream `fetch` throw ERR_INVALID_CHAR. + assertNoControlChars(parsed, 'upstream_user_agent'); return parsed; } return null; @@ -116,12 +123,21 @@ export function registerSettingsRoutes(scope: FastifyInstance, ctx: AppContext): const body = jsonBody(request); const changed: string[] = []; const ignored: string[] = []; + const updates: Array<[string, string]> = []; for (const [key, value] of Object.entries(body)) { - const applied = applySetting(ctx, key, value); - if (applied === null) ignored.push(key); - else changed.push(key); + const validated = validateSetting(key, value); + if (validated === null) ignored.push(key); + else { + changed.push(key); + updates.push([key, validated]); + } + } + if (updates.length > 0) { + ctx.repo.transaction(() => { + for (const [key, value] of updates) ctx.repo.setSetting(key, value); + }); + audit(ctx, 'settings.update', null, `changed=${changed.join(',')}`, request); } - if (changed.length > 0) audit(ctx, 'settings.update', null, `changed=${changed.join(',')}`); return { ...settingsView(ctx), changed, ignored }; }); @@ -143,14 +159,14 @@ export function registerSettingsRoutes(scope: FastifyInstance, ctx: AppContext): setDashboardPassword(ctx, newPassword); const currentId = request.adminSession?.id ?? null; const revoked = ctx.repo.deleteOtherSessions(currentId); - audit(ctx, 'settings.password.change', null, `revokedSessions=${revoked}`); + audit(ctx, 'settings.password.change', null, `revokedSessions=${revoked}`, request); return { ok: true, revoked }; }); scope.delete('/settings/sessions', async (request) => { const currentId = request.adminSession?.id ?? null; const revoked = ctx.repo.deleteOtherSessions(currentId); - audit(ctx, 'settings.sessions.revoke', null, `revoked=${revoked}`); + audit(ctx, 'settings.sessions.revoke', null, `revoked=${revoked}`, request); return { ok: true, revoked }; }); @@ -166,7 +182,7 @@ export function registerSettingsRoutes(scope: FastifyInstance, ctx: AppContext): throw new HttpError(404, 'session_not_found', `Session "${id}" not found`); } ctx.repo.deleteSession(id); - audit(ctx, 'settings.session.revoke', id, null); + audit(ctx, 'settings.session.revoke', id, null, request); return { ok: true, revoked: 1 }; }); @@ -194,7 +210,7 @@ export function registerSettingsRoutes(scope: FastifyInstance, ctx: AppContext): // Every dashboard cookie is now invalid; gateway keys are sha256(plaintext) and keep working. ctx.repo.deleteAllSessions(); reply.header('cache-control', 'no-store'); - audit(ctx, 'settings.secret.rotate', null, 'dashboard sessions invalidated; gateway key hashes unchanged'); + audit(ctx, 'settings.secret.rotate', null, 'dashboard sessions invalidated; gateway key hashes unchanged', request); return { ok: true, secret, sessionsRevoked: true, notes: 'Gateway API keys are unaffected (sha256 of plaintext).' }; }); diff --git a/src/admin/stats.ts b/src/admin/stats.ts index c2d5bd0..205c708 100644 --- a/src/admin/stats.ts +++ b/src/admin/stats.ts @@ -6,6 +6,7 @@ import type { FastifyInstance, FastifyRequest } from 'fastify'; import type { AppContext } from '../core/context.js'; import { getActiveRequests } from '../core/context.js'; import type { StatsOverview } from '../db/repos.js'; +import type { SessionRow } from '../types.js'; import { formatSseJson } from '../util/sse.js'; import { ADMIN_VERSION, @@ -47,6 +48,43 @@ export function clearStatsCache(): void { /** How long to wait for a `drain` before treating the SSE client as stuck. */ const DRAIN_TIMEOUT_MS = 15_000; +/** AD-10: concurrent `/events` streams one process serves before answering 503. */ +export const MAX_EVENTS_STREAMS = 32; +/** AD-10: heartbeat cadence; also the session revalidation cadence. */ +export const EVENTS_HEARTBEAT_MS = 5_000; + +let openEventStreams = 0; + +/** Test/ops helper: forget the concurrent-stream counter. */ +export function resetEventStreams(): void { + openEventStreams = 0; +} + +export function activeEventStreamCount(): number { + return openEventStreams; +} + +/** AD-10: reserve one of the bounded SSE slots; false means the cap is reached. */ +export function acquireEventStream(): boolean { + if (openEventStreams >= MAX_EVENTS_STREAMS) return false; + openEventStreams += 1; + return true; +} + +export function releaseEventStream(): void { + openEventStreams = Math.max(0, openEventStreams - 1); +} + +/** + * AD-10: a stream is authorized at connect time only, so a revoked session or a + * `rotate-secret` (which deletes every session) used to keep streaming. Re-check + * the row + expiry on every heartbeat. + */ +export function eventStreamAuthorized(ctx: AppContext, session: SessionRow | null | undefined): boolean { + if (!session) return false; + if (session.expiresAt <= Date.now()) return false; + return ctx.repo.getSession(session.id) !== null; +} /** Per-client cap on frames buffered while `drain` is pending. */ const EVENTS_QUEUE_LIMIT = 256; @@ -181,8 +219,17 @@ export function registerStatsRoutes(scope: FastifyInstance, ctx: AppContext): vo }); scope.get('/events', async (request, reply) => { + // AD-10: bound the number of concurrent streams before hijacking the reply. + if (!acquireEventStream()) { + await reply.status(503).send({ + error: { message: `Too many concurrent event streams (max ${MAX_EVENTS_STREAMS})`, code: 'too_many_streams' }, + }); + return; + } + reply.hijack(); const raw = reply.raw; + const session = request.adminSession ?? null; raw.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache, no-transform', @@ -199,7 +246,9 @@ export function registerStatsRoutes(scope: FastifyInstance, ctx: AppContext): vo let drainTimer: ReturnType | null = null; let failures = 0; let closed = false; - let cleanup: () => void; + // Declared before the first `send()`: a throwing `raw.write` calls `cleanup`, + // and a `const`/unassigned binding there used to be a TDZ TypeError. + let cleanup: () => void = () => {}; const flushQueue = (): void => { draining = false; @@ -261,7 +310,13 @@ export function registerStatsRoutes(scope: FastifyInstance, ctx: AppContext): vo const offStart = ctx.events.onRequestStart((event) => send('request:start', event)); const offEnd = ctx.events.onRequestEnd((event) => send('request:end', event)); const offProvider = ctx.events.onProvider((event) => send('provider:update', event)); - const heartbeat = setInterval(() => send('stats', statsHeartbeat(ctx)), 5_000); + const heartbeat = setInterval(() => { + if (!eventStreamAuthorized(ctx, session)) { + cleanup(); + return; + } + send('stats', statsHeartbeat(ctx)); + }, EVENTS_HEARTBEAT_MS); heartbeat.unref(); cleanup = (): void => { @@ -273,6 +328,7 @@ export function registerStatsRoutes(scope: FastifyInstance, ctx: AppContext): vo offStart(); offEnd(); offProvider(); + releaseEventStream(); try { raw.end(); } catch { diff --git a/src/admin/sync.ts b/src/admin/sync.ts index d40fac3..214b73d 100644 --- a/src/admin/sync.ts +++ b/src/admin/sync.ts @@ -7,6 +7,7 @@ import type { ProviderRow } from '../types.js'; import { upstreamErrorFrom } from '../util/errors.js'; import { extractModels, type NormalizedModel } from '../util/models.js'; import { readJsonBody, upstreamFetch } from '../util/upstream.js'; +import { assertPublicProviderUrl } from './util.js'; export const SYNC_TIMEOUT_MS = 20_000; @@ -175,6 +176,10 @@ export async function probeAndRecord( * cannot steal it from each other (see SPEC §3 sync semantics). */ export async function syncProviderModels(ctx: AppContext, provider: ProviderRow): Promise { + // AD-03: sync reaches the network exactly like a probe, so the SSRF guard applies + // here too (a legacy row may predate the guard, the scheduler calls this directly). + assertPublicProviderUrl(provider.baseUrl, ctx.config.providerAllowPrivateHosts); + const probe = await probeProvider({ baseUrl: provider.baseUrl, apiKey: provider.apiKey }); if (!probe.ok) { ctx.logger?.warn?.( @@ -187,47 +192,54 @@ export async function syncProviderModels(ctx: AppContext, provider: ProviderRow) throw new Error(syncFailureMessage(provider.name)); } - const existing = ctx.repo.listModels(); - const byId = new Map(existing.map((model) => [model.id, model])); - const upstreamIds = new Set(); - let added = 0; - let updated = 0; - - for (const model of probe.models) { - upstreamIds.add(model.id); - const current = byId.get(model.id); - if (current && current.source === 'manual') continue; - if (current && current.providerId !== null && current.providerId !== provider.id) continue; - const result = ctx.repo.upsertModel({ - id: model.id, - name: model.name, - providerId: provider.id, - contextLength: model.contextLength, - maxOutputTokens: model.maxOutputTokens, - capabilities: model.capabilities, - reasoning: model.reasoning, - source: 'sync', - }); - if (result.created) added += 1; - else updated += 1; - } + const syncedAt = Date.now(); + // OPT-10: the caller already holds the row snapshot, so each upsert skips its own + // `getModel`; the whole write set is one transaction (no partially synced catalog). + const counts = ctx.repo.transaction(() => { + const existing = ctx.repo.listModels(); + const byId = new Map(existing.map((model) => [model.id, model])); + const upstreamIds = new Set(); + let added = 0; + let updated = 0; + let removed = 0; + + for (const model of probe.models) { + upstreamIds.add(model.id); + const current = byId.get(model.id) ?? null; + if (current && current.source === 'manual') continue; + if (current && current.providerId !== null && current.providerId !== provider.id) continue; + const result = ctx.repo.upsertModel( + { + id: model.id, + name: model.name, + providerId: provider.id, + contextLength: model.contextLength, + maxOutputTokens: model.maxOutputTokens, + capabilities: model.capabilities, + reasoning: model.reasoning, + source: 'sync', + }, + current, + ); + byId.set(model.id, result.row); + if (result.created) added += 1; + else updated += 1; + } - let removed = 0; - for (const row of existing) { - if (row.source !== 'sync') continue; - if (row.providerId !== provider.id) continue; - if (upstreamIds.has(row.id)) continue; - if (ctx.repo.deleteModel(row.id)) removed += 1; - } + for (const row of existing) { + if (row.source !== 'sync') continue; + if (row.providerId !== provider.id) continue; + if (upstreamIds.has(row.id)) continue; + if (ctx.repo.deleteModel(row.id)) removed += 1; + } - const syncedAt = Date.now(); - ctx.repo.setSetting(SETTING_MODELS_SYNCED_AT, String(syncedAt)); - ctx.repo.setSetting(SETTING_MODELS_SYNC_PROVIDER_ID, provider.id); + ctx.repo.setSetting(SETTING_MODELS_SYNCED_AT, String(syncedAt)); + ctx.repo.setSetting(SETTING_MODELS_SYNC_PROVIDER_ID, provider.id); + return { added, updated, removed }; + }); return { - added, - updated, - removed, + ...counts, total: probe.models.length, providerId: provider.id, syncedAt, diff --git a/src/admin/util.ts b/src/admin/util.ts index 6b121fa..24382b2 100644 --- a/src/admin/util.ts +++ b/src/admin/util.ts @@ -243,7 +243,9 @@ export function assertPublicProviderUrl(rawUrl: string, allowPrivate: boolean): return; } if (allowPrivate) return; - const normalized = host.toLowerCase(); + // AD-01: `new URL('http://localhost./').hostname` keeps the trailing dot, which + // defeated every literal check (`localhost.`, `127.0.0.1.`, `10.0.0.5.`). + const normalized = host.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.+$/, ''); if (PRIVATE_HOSTS.has(normalized) || normalized.endsWith('.localhost') || isBlockedAddress(normalized)) { fail( 400, @@ -253,8 +255,19 @@ export function assertPublicProviderUrl(rawUrl: string, allowPrivate: boolean): } } +/** + * GW-10: control characters (CR/LF especially) in a header-bound value make Node + * throw `ERR_INVALID_CHAR` at write time, turning every proxied request into a 5xx. + */ +export function assertNoControlChars(value: string, field: string): void { + if (/[\u0000-\u001f\u007f]/.test(value)) { + fail(400, 'invalid_request', `${field} must not contain control characters`); + } +} + export function httpBaseUrl(value: unknown): string { const url = requireString(value, 'baseUrl'); + assertNoControlChars(url, 'baseUrl'); let parsed: URL; try { parsed = new URL(url); @@ -266,14 +279,23 @@ export function httpBaseUrl(value: unknown): string { fail(400, 'invalid_request', 'baseUrl must start with http:// or https://'); } if (!parsed.hostname) fail(400, 'invalid_request', 'baseUrl must include a host'); + // GW-12: credentials in the URL would be echoed back in upstream error messages. + if (parsed.username.length > 0 || parsed.password.length > 0) { + fail(400, 'invalid_request', 'baseUrl must not contain credentials'); + } return url.replace(/\/+$/, ''); } -/** Never expose the stored provider key: prefix + suffix only. */ +/** + * AD-08: never expose the stored provider key. Short keys are fully masked and + * long keys reveal at most 4 characters in total (`sk-123456` used to leak 8 of 9). + */ +export const MASKED_KEY_MIN_LENGTH = 12; + export function maskApiKey(key: string | null | undefined): string { if (!key) return ''; - if (key.length <= 8) return '****'; - return `${key.slice(0, 4)}...${key.slice(-4)}`; + if (key.length < MASKED_KEY_MIN_LENGTH) return '****'; + return `${key.slice(0, 2)}...${key.slice(-2)}`; } export function capabilitiesFrom(value: unknown): ModelCapabilities | undefined { @@ -327,9 +349,28 @@ export function sanitizeSettings(settings: Record): { return { settings: { ...rest, passwordSet }, passwordSet }; } -export function audit(ctx: AppContext, action: string, target: string | null = null, detail: string | null = null): void { +/** + * FEAT-05: the audit trail must say *who* acted. The session id goes into the + * actor column and the client IP is appended to the detail; both stay absent + * (actor `dashboard`) for callers without a request. + */ +export function auditActor(request: FastifyRequest | null | undefined): string { + const sessionId = request?.adminSession?.id; + if (sessionId) return `session:${sessionId}`; + return 'dashboard'; +} + +export function audit( + ctx: AppContext, + action: string, + target: string | null = null, + detail: string | null = null, + request?: FastifyRequest | null, +): void { + const ip = request ? clientIp(request) : null; + const withIp = ip ? (detail ? `${detail} ip=${ip}` : `ip=${ip}`) : detail; try { - ctx.repo.audit('dashboard', action, target, detail); + ctx.repo.audit(auditActor(request), action, target, withIp); } catch (error) { ctx.logger?.warn?.({ err: error, action }, 'failed to write audit entry'); } @@ -357,7 +398,8 @@ export interface HealthSnapshot { } export function activeKeyCount(ctx: AppContext): number { - return ctx.repo.listApiKeys().filter((key) => key.enabled && key.revokedAt === null).length; + // OPT-04: COUNT in SQLite instead of materializing every key row. + return ctx.repo.countActiveApiKeys(); } export function buildHealth(ctx: AppContext): HealthSnapshot { diff --git a/src/core/seed.ts b/src/core/seed.ts index 672968b..11bef9b 100644 --- a/src/core/seed.ts +++ b/src/core/seed.ts @@ -27,12 +27,25 @@ export function seedDefaults(ctx: AppContext): void { repo.purgeExpiredSessions(); } -/** Removes old request logs and audit entries according to the retention setting. */ +const DAY_MS = 24 * 60 * 60 * 1000; + +function retentionDays(ctx: AppContext, key: string, fallback: number): number { + const configured = ctx.repo.getInt(key, fallback); + if (!Number.isFinite(configured)) return fallback; + return Math.min(Math.max(configured, 1), 3_650); +} + +/** + * Removes old request logs and audit entries according to their retention settings. + * FEAT-05: the security trail is pruned by `audit_retention_days` (default 90), so a + * 1-day log retention can no longer wipe the audit history. + */ export function pruneLogs(ctx: AppContext): number { - const days = Math.max(1, ctx.repo.getInt('log_retention_days', 30)); - const cutoff = Date.now() - days * 24 * 60 * 60 * 1000; - ctx.repo.deleteAuditBefore(cutoff); - return ctx.repo.deleteLogsBefore(cutoff); + const now = Date.now(); + const auditDays = retentionDays(ctx, 'audit_retention_days', 90); + const logDays = retentionDays(ctx, 'log_retention_days', 30); + ctx.repo.deleteAuditBefore(now - auditDays * DAY_MS); + return ctx.repo.deleteLogsBefore(now - logDays * DAY_MS); } export function verifyDashboardPassword(ctx: AppContext, password: string): boolean { diff --git a/src/core/shutdown.ts b/src/core/shutdown.ts new file mode 100644 index 0000000..23f730f --- /dev/null +++ b/src/core/shutdown.ts @@ -0,0 +1,86 @@ +/** + * FEAT-07: bounded graceful shutdown. + * + * `app.close()` waits for in-flight requests (a long SSE stream can hold it for + * minutes) while `onClose` hooks flush pending writes (scheduler stop, `db.close()` + * which checkpoints WAL). After `timeoutMs` the remaining sockets are force-closed + * so a stuck client cannot hang the process forever. + */ +import type { FastifyBaseLogger } from 'fastify'; + +export interface ShutdownHost { + close(): Promise; + server?: { closeAllConnections?: () => void }; + log: FastifyBaseLogger; +} + +/** How long to let in-flight requests finish before force-closing their sockets. */ +export const SHUTDOWN_DRAIN_MS = 10_000; + +export interface ShutdownOptions { + timeoutMs?: number; + /** Called once when a shutdown starts (clear intervals, stop schedulers). */ + onShutdownStart?: () => void; + /** Signal source; defaults to `process` (injectable for tests). */ + signals?: Pick; + /** Defaults to `process.exit`; injectable for tests. */ + exit?: (code: number) => void; +} + +export interface ShutdownController { + shutdown(signal: string): Promise; + readonly started: boolean; +} + +export function registerGracefulShutdown(host: ShutdownHost, options: ShutdownOptions = {}): ShutdownController { + const timeoutMs = options.timeoutMs ?? SHUTDOWN_DRAIN_MS; + const signals = options.signals ?? process; + const exit = options.exit ?? ((code: number): void => process.exit(code)); + let started = false; + + const shutdown = async (signal: string): Promise => { + // A second SIGTERM during the drain must not start a competing shutdown. + if (started) return; + started = true; + host.log.info({ signal, timeoutMs }, 'shutting down; draining in-flight requests'); + try { + options.onShutdownStart?.(); + } catch (error) { + host.log.warn({ err: error }, 'shutdown start hook failed'); + } + + const force = setTimeout(() => { + host.log.warn({ timeoutMs }, 'shutdown drain timed out; force-closing connections'); + try { + host.server?.closeAllConnections?.(); + } catch (error) { + host.log.warn({ err: error }, 'force-closing connections failed'); + } + }, timeoutMs); + force.unref?.(); + + let code = 0; + try { + await host.close(); + host.log.info({ signal }, 'shutdown complete'); + } catch (error) { + code = 1; + host.log.error({ err: error, signal }, 'shutdown failed'); + } finally { + clearTimeout(force); + } + exit(code); + }; + + for (const signal of ['SIGINT', 'SIGTERM'] as const) { + signals.on(signal, () => { + void shutdown(signal); + }); + } + return { + shutdown, + get started(): boolean { + return started; + }, + }; +} diff --git a/src/db/repos.ts b/src/db/repos.ts index 8c0346d..6695582 100644 --- a/src/db/repos.ts +++ b/src/db/repos.ts @@ -1,4 +1,4 @@ -import type { DatabaseSync } from 'node:sqlite'; +import type { DatabaseSync, StatementSync } from 'node:sqlite'; import { hashApiKey, generateApiKey, uuid } from '../util/crypto.js'; import type { ApiKeyRow, @@ -39,8 +39,10 @@ export const DEFAULT_SETTINGS: Record = { auto_sync_models: 'true', model_sync_interval_ms: '300000', log_retention_days: '30', + audit_retention_days: '90', model_allow_unknown: 'false', upstream_user_agent: 'opencode-router/1.0', + stream_idle_timeout_ms: '120000', }; export interface LogQuery { @@ -88,13 +90,59 @@ export interface StatsOverview { recentErrors: Array<{ ts: number; model: string | null; providerName: string | null; status: number; errorCode: string | null; errorMessage: string | null }>; } +/** Fallbacks used when a model row is written without explicit capabilities. */ +const DEFAULT_MODEL_CAPABILITIES: ModelCapabilities = { tools: true, input: ['text'], output: ['text'], temperature: true }; +const DEFAULT_MODEL_REASONING: ModelReasoning = { supported: false, efforts: [], defaultEffort: null }; + export class Repo { + /** OPT-01: `node:sqlite` re-prepares on every `prepare()`; the gateway hot path prepares the same SQL per request. */ + private readonly statements = new Map(); + private txDepth = 0; + constructor(private readonly db: DatabaseSync) {} + /** Cached `prepare` — one `StatementSync` per distinct SQL string. */ + private stmt(sql: string): StatementSync { + let statement = this.statements.get(sql); + if (!statement) { + // Filters build SQL dynamically (log queries), so bound the cache: clearing it + // is cheap and keeps a pathological caller from growing it without limit. + if (this.statements.size >= 256) this.statements.clear(); + statement = this.db.prepare(sql); + this.statements.set(sql, statement); + } + return statement; + } + + /** + * Runs `fn` inside one transaction so multi-statement writes are all-or-nothing + * (AD-02/AD-05/AD-06). Re-entrant calls join the outer transaction instead of + * opening a nested `BEGIN` (SQLite rejects that). + */ + transaction(fn: () => T): T { + if (this.txDepth > 0) return fn(); + this.db.exec('BEGIN IMMEDIATE'); + this.txDepth += 1; + try { + const result = fn(); + this.db.exec('COMMIT'); + return result; + } catch (error) { + try { + this.db.exec('ROLLBACK'); + } catch { + /* the transaction was already rolled back by SQLite */ + } + throw error; + } finally { + this.txDepth -= 1; + } + } + /* ------------------------------------------------------------------ settings */ getSetting(key: string): string | null { - const row = this.db.prepare('SELECT value FROM settings WHERE key = ?').get(key) as Row | undefined; + const row = this.stmt('SELECT value FROM settings WHERE key = ?').get(key) as Row | undefined; if (!row) return DEFAULT_SETTINGS[key] ?? null; return String(row.value); } @@ -110,8 +158,7 @@ export class Repo { } setSetting(key: string, value: string): void { - this.db - .prepare( + this.stmt( `INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`, ) @@ -120,7 +167,7 @@ export class Repo { allSettings(): Record { const out: Record = { ...DEFAULT_SETTINGS }; - for (const row of this.db.prepare('SELECT key, value FROM settings').all() as Row[]) { + for (const row of this.stmt('SELECT key, value FROM settings').all() as Row[]) { out[String(row.key)] = String(row.value); } return out; @@ -149,14 +196,14 @@ export class Repo { } listProviders(): ProviderRow[] { - const rows = this.db - .prepare('SELECT * FROM providers ORDER BY priority ASC, created_at ASC') + const rows = this.stmt( + 'SELECT * FROM providers ORDER BY priority ASC, created_at ASC') .all() as Row[]; return rows.map((r) => this.mapProvider(r)); } getProvider(id: string): ProviderRow | null { - const row = this.db.prepare('SELECT * FROM providers WHERE id = ?').get(id) as Row | undefined; + const row = this.stmt('SELECT * FROM providers WHERE id = ?').get(id) as Row | undefined; return row ? this.mapProvider(row) : null; } @@ -170,8 +217,7 @@ export class Repo { }): ProviderRow { const now = Date.now(); const id = input.id?.trim() || uuid(); - this.db - .prepare( + this.stmt( `INSERT INTO providers (id, name, base_url, api_key, enabled, priority, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 'unknown', ?, ?)`, ) @@ -214,8 +260,7 @@ export class Repo { lastError: patch.lastError === undefined ? current.lastError : patch.lastError, updatedAt: Date.now(), }; - this.db - .prepare( + this.stmt( `UPDATE providers SET name=?, base_url=?, api_key=?, enabled=?, priority=?, status=?, cooldown_until=?, last_error=?, updated_at=? WHERE id=?`, ) @@ -235,13 +280,24 @@ export class Repo { } deleteProvider(id: string): boolean { - const res = this.db.prepare('DELETE FROM providers WHERE id = ?').run(id); + const res = this.stmt('DELETE FROM providers WHERE id = ?').run(id); return Number(res.changes) > 0; } + /** + * AD-02: `PRAGMA foreign_keys=ON` has no FK constraints, so deleting a provider + * used to leave its synced models with a dangling `provider_id` forever. + */ + deleteProviderWithModels(id: string): { deleted: boolean; modelsRemoved: number } { + return this.transaction(() => { + const modelsRemoved = this.deleteModelsByProvider(id); + const res = this.stmt('DELETE FROM providers WHERE id = ?').run(id); + return { deleted: Number(res.changes) > 0, modelsRemoved }; + }); + } + recordProviderSuccess(id: string, latencyMs: number): void { - this.db - .prepare( + this.stmt( `UPDATE providers SET status='ok', cooldown_until=NULL, last_error=NULL, last_checked_at=?, last_latency_ms=?, success_count=success_count+1, updated_at=? WHERE id=?`, ) @@ -251,19 +307,23 @@ export class Repo { recordProviderFailure(id: string, status: number | null, error: string, cooldownMs: number): void { const now = Date.now(); const rateLimited = status === 429 || status === 503 || status === 529 || (status !== null && status >= 500); - this.db - .prepare( - `UPDATE providers SET status=?, cooldown_until=?, last_error=?, last_checked_at=?, + // GW-15: a network failure (`status === null`), 408/409/425 or a 3xx is retryable + // too, so the provider backs off instead of being re-hit on the next request. + // The `status` column keeps its previous rate-limit-only semantics. + const coolDown = + status === null || + status === 408 || + status === 409 || + status === 425 || + status === 429 || + status === 503 || + status === 529 || + status >= 500 || + (status >= 300 && status < 400); + this.stmt( + `UPDATE providers SET status=?, cooldown_until=?, last_error=?, last_checked_at=?, failure_count=failure_count+1, updated_at=? WHERE id=?`, - ) - .run( - rateLimited ? 'cooldown' : 'error', - rateLimited ? now + cooldownMs : null, - error.slice(0, 500), - now, - now, - id, - ); + ).run(rateLimited ? 'cooldown' : 'error', coolDown ? now + cooldownMs : null, error.slice(0, 500), now, now, id); } /* -------------------------------------------------------------------- models */ @@ -290,67 +350,98 @@ export class Repo { } listModels(): ModelRow[] { - const rows = this.db.prepare('SELECT * FROM models ORDER BY id ASC').all() as Row[]; + const rows = this.stmt('SELECT * FROM models ORDER BY id ASC').all() as Row[]; return rows.map((r) => this.mapModel(r)); } getModel(id: string): ModelRow | null { - const row = this.db.prepare('SELECT * FROM models WHERE id = ?').get(id) as Row | undefined; + const row = this.stmt('SELECT * FROM models WHERE id = ?').get(id) as Row | undefined; return row ? this.mapModel(row) : null; } - upsertModel(input: { - id: string; - name?: string; - providerId?: string | null; - contextLength?: number | null; - maxOutputTokens?: number | null; - capabilities?: ModelCapabilities; - reasoning?: ModelReasoning; - enabled?: boolean; - source?: 'sync' | 'manual'; - }): { row: ModelRow; created: boolean } { - const existing = this.getModel(input.id); + /** + * OPT-10: `known` lets a bulk caller (provider sync) pass the row it already + * loaded, so the upsert does not re-read every model. The returned row is built + * from the inputs — no trailing `getModel` round-trip either. + */ + upsertModel( + input: { + id: string; + name?: string; + providerId?: string | null; + contextLength?: number | null; + maxOutputTokens?: number | null; + capabilities?: ModelCapabilities; + reasoning?: ModelReasoning; + enabled?: boolean; + source?: 'sync' | 'manual'; + }, + known?: ModelRow | null, + ): { row: ModelRow; created: boolean } { + const existing = known === undefined ? this.getModel(input.id) : known; const now = Date.now(); if (!existing) { - this.db - .prepare( - `INSERT INTO models (id, name, provider_id, context_length, max_output_tokens, capabilities, reasoning, enabled, source, created_at, updated_at) + const capabilities = input.capabilities ?? DEFAULT_MODEL_CAPABILITIES; + const reasoning = input.reasoning ?? DEFAULT_MODEL_REASONING; + const row: ModelRow = { + id: input.id, + name: input.name ?? input.id, + providerId: input.providerId ?? null, + contextLength: input.contextLength ?? null, + maxOutputTokens: input.maxOutputTokens ?? null, + capabilities, + reasoning, + enabled: input.enabled !== false, + source: input.source ?? 'manual', + createdAt: now, + updatedAt: now, + }; + this.stmt( + `INSERT INTO models (id, name, provider_id, context_length, max_output_tokens, capabilities, reasoning, enabled, source, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - ) - .run( - input.id, - input.name ?? input.id, - input.providerId ?? null, - input.contextLength ?? null, - input.maxOutputTokens ?? null, - JSON.stringify(input.capabilities ?? { tools: true, input: ['text'], output: ['text'], temperature: true }), - JSON.stringify(input.reasoning ?? { supported: false, efforts: [], defaultEffort: null }), - input.enabled === false ? 0 : 1, - input.source ?? 'manual', - now, - now, - ); - return { row: this.getModel(input.id)!, created: true }; + ).run( + row.id, + row.name, + row.providerId, + row.contextLength, + row.maxOutputTokens, + JSON.stringify(capabilities), + JSON.stringify(reasoning), + row.enabled ? 1 : 0, + row.source, + row.createdAt, + row.updatedAt, + ); + return { row, created: true }; } - this.db - .prepare( - `UPDATE models SET name=?, provider_id=?, context_length=?, max_output_tokens=?, capabilities=?, reasoning=?, + const row: ModelRow = { + ...existing, + name: input.name ?? existing.name, + providerId: input.providerId === undefined ? existing.providerId : input.providerId, + contextLength: input.contextLength === undefined ? existing.contextLength : input.contextLength, + maxOutputTokens: input.maxOutputTokens === undefined ? existing.maxOutputTokens : input.maxOutputTokens, + capabilities: input.capabilities ?? existing.capabilities, + reasoning: input.reasoning ?? existing.reasoning, + enabled: input.enabled ?? existing.enabled, + source: input.source ?? existing.source, + updatedAt: now, + }; + this.stmt( + `UPDATE models SET name=?, provider_id=?, context_length=?, max_output_tokens=?, capabilities=?, reasoning=?, enabled=?, source=?, updated_at=? WHERE id=?`, - ) - .run( - input.name ?? existing.name, - input.providerId === undefined ? existing.providerId : input.providerId, - input.contextLength === undefined ? existing.contextLength : input.contextLength, - input.maxOutputTokens === undefined ? existing.maxOutputTokens : input.maxOutputTokens, - JSON.stringify(input.capabilities ?? existing.capabilities), - JSON.stringify(input.reasoning ?? existing.reasoning), - (input.enabled ?? existing.enabled) ? 1 : 0, - input.source ?? existing.source, - now, - input.id, - ); - return { row: this.getModel(input.id)!, created: false }; + ).run( + row.name, + row.providerId, + row.contextLength, + row.maxOutputTokens, + JSON.stringify(row.capabilities), + JSON.stringify(row.reasoning), + row.enabled ? 1 : 0, + row.source, + row.updatedAt, + row.id, + ); + return { row, created: false }; } updateModel( @@ -366,8 +457,7 @@ export class Repo { ): ModelRow | null { const existing = this.getModel(id); if (!existing) return null; - this.db - .prepare( + this.stmt( `UPDATE models SET name=?, enabled=?, context_length=?, max_output_tokens=?, capabilities=?, reasoning=?, updated_at=? WHERE id=?`, ) @@ -385,20 +475,54 @@ export class Repo { } deleteModel(id: string): boolean { - const res = this.db.prepare('DELETE FROM models WHERE id = ?').run(id); + const res = this.stmt('DELETE FROM models WHERE id = ?').run(id); return Number(res.changes) > 0; } deleteAllModels(): number { - const res = this.db.prepare('DELETE FROM models').run(); + const res = this.stmt('DELETE FROM models').run(); return Number(res.changes); } enabledModelIds(): string[] { - const rows = this.db.prepare('SELECT id FROM models WHERE enabled = 1').all() as Row[]; + const rows = this.stmt('SELECT id FROM models WHERE enabled = 1').all() as Row[]; return rows.map((r) => String(r.id)); } + /** + * Existence check for the gateway hot path: `enabledModelIds().length === 0` + * materialized every id just to answer a boolean question. + */ + hasEnabledModel(): boolean { + const row = this.stmt('SELECT EXISTS(SELECT 1 FROM models WHERE enabled = 1) AS c').get() as Row; + return num(row.c) > 0; + } + + /** + * AD-05: one set-based statement inside a transaction instead of a + * `getModel` + `UPDATE` per id. Returns the number of existing rows matched. + */ + setModelsEnabled(ids: string[], enabled: boolean): number { + if (ids.length === 0) return 0; + const placeholders = ids.map(() => '?').join(','); + return this.transaction(() => { + const result = this.stmt( + `UPDATE models SET enabled = ?, updated_at = ? WHERE id IN (${placeholders})`, + ).run(enabled ? 1 : 0, Date.now(), ...ids); + return Number(result.changes); + }); + } + + /** AD-05: bulk delete counterpart of `setModelsEnabled`. */ + deleteModels(ids: string[]): number { + if (ids.length === 0) return 0; + const placeholders = ids.map(() => '?').join(','); + return this.transaction(() => { + const result = this.stmt(`DELETE FROM models WHERE id IN (${placeholders})`).run(...ids); + return Number(result.changes); + }); + } + /* ------------------------------------------------------------------ api keys */ private mapApiKey(row: Row): ApiKeyRow { @@ -417,23 +541,33 @@ export class Repo { } listApiKeys(): ApiKeyRow[] { - const rows = this.db.prepare('SELECT * FROM api_keys ORDER BY created_at DESC').all() as Row[]; + const rows = this.stmt('SELECT * FROM api_keys ORDER BY created_at DESC').all() as Row[]; return rows.map((r) => this.mapApiKey(r)); } hasActiveApiKey(): boolean { - const row = this.db - .prepare('SELECT COUNT(*) AS c FROM api_keys WHERE enabled = 1 AND revoked_at IS NULL') + return this.countActiveApiKeys() > 0; + } + + /** Cheaper than `listApiKeys().length` for the gateway hot path. */ + countActiveApiKeys(): number { + const row = this.stmt( + 'SELECT COUNT(*) AS c FROM api_keys WHERE enabled = 1 AND revoked_at IS NULL') .get() as Row; - return num(row.c) > 0; + return num(row.c); + } + + /** Removes a provider's synced models when the provider itself is deleted. */ + deleteModelsByProvider(providerId: string): number { + const res = this.stmt('DELETE FROM models WHERE provider_id = ?').run(providerId); + return Number(res.changes); } createApiKey(name: string): { row: ApiKeyRow; plaintext: string } { const plaintext = generateApiKey(); const id = uuid(); const now = Date.now(); - this.db - .prepare( + this.stmt( `INSERT INTO api_keys (id, name, key_hash, key_prefix, key_suffix, enabled, request_count, created_at) VALUES (?, ?, ?, ?, ?, 1, 0, ?)`, ) @@ -442,12 +576,12 @@ export class Repo { } getApiKey(id: string): ApiKeyRow | null { - const row = this.db.prepare('SELECT * FROM api_keys WHERE id = ?').get(id) as Row | undefined; + const row = this.stmt('SELECT * FROM api_keys WHERE id = ?').get(id) as Row | undefined; return row ? this.mapApiKey(row) : null; } findApiKeyByPlaintext(plaintext: string): ApiKeyRow | null { - const row = this.db.prepare('SELECT * FROM api_keys WHERE key_hash = ?').get(hashApiKey(plaintext)) as + const row = this.stmt('SELECT * FROM api_keys WHERE key_hash = ?').get(hashApiKey(plaintext)) as | Row | undefined; return row ? this.mapApiKey(row) : null; @@ -456,8 +590,8 @@ export class Repo { updateApiKey(id: string, patch: { name?: string; enabled?: boolean; revoked?: boolean }): ApiKeyRow | null { const existing = this.getApiKey(id); if (!existing) return null; - this.db - .prepare('UPDATE api_keys SET name = ?, enabled = ?, revoked_at = ? WHERE id = ?') + this.stmt( + 'UPDATE api_keys SET name = ?, enabled = ?, revoked_at = ? WHERE id = ?') .run( patch.name ?? existing.name, (patch.enabled ?? existing.enabled) ? 1 : 0, @@ -474,20 +608,20 @@ export class Repo { rotateApiKey(id: string, plaintext: string): ApiKeyRow | null { const existing = this.getApiKey(id); if (!existing) return null; - this.db - .prepare('UPDATE api_keys SET key_hash = ?, key_prefix = ?, key_suffix = ? WHERE id = ?') + this.stmt( + 'UPDATE api_keys SET key_hash = ?, key_prefix = ?, key_suffix = ? WHERE id = ?') .run(hashApiKey(plaintext), plaintext.slice(0, 8), plaintext.slice(-4), id); return this.getApiKey(id); } deleteApiKey(id: string): boolean { - const res = this.db.prepare('DELETE FROM api_keys WHERE id = ?').run(id); + const res = this.stmt('DELETE FROM api_keys WHERE id = ?').run(id); return Number(res.changes) > 0; } touchApiKey(id: string): void { - this.db - .prepare('UPDATE api_keys SET last_used_at = ?, request_count = request_count + 1 WHERE id = ?') + this.stmt( + 'UPDATE api_keys SET last_used_at = ?, request_count = request_count + 1 WHERE id = ?') .run(Date.now(), id); } @@ -522,8 +656,7 @@ export class Repo { } insertLog(entry: RequestLogRow): void { - this.db - .prepare( + this.stmt( `INSERT INTO request_logs (id, ts, key_id, key_name, provider_id, provider_name, model, surface, stream, status, ok, error_code, error_message, latency_ms, ttfb_ms, input_tokens, output_tokens, total_tokens, reasoning_tokens, cached_tokens, attempts, client_ip, user_agent) @@ -557,8 +690,7 @@ export class Repo { } insertAttempt(entry: AttemptRow): void { - this.db - .prepare( + this.stmt( `INSERT INTO request_attempts (id, request_id, ts, provider_id, provider_name, attempt, status, ok, error_code, error_message, latency_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ) @@ -578,8 +710,8 @@ export class Repo { } listAttempts(requestId: string): AttemptRow[] { - const rows = this.db - .prepare('SELECT * FROM request_attempts WHERE request_id = ? ORDER BY attempt ASC') + const rows = this.stmt( + 'SELECT * FROM request_attempts WHERE request_id = ? ORDER BY attempt ASC') .all(requestId) as Row[]; return rows.map((r) => ({ id: String(r.id), @@ -640,38 +772,51 @@ export class Repo { params.push(like, like, like, like); } const clause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : ''; - const totalRow = this.db.prepare(`SELECT COUNT(*) AS c FROM request_logs ${clause}`).get(...params) as Row; + const totalRow = this.stmt(`SELECT COUNT(*) AS c FROM request_logs ${clause}`).get(...params) as Row; const limit = Math.min(Math.max(query.limit ?? 50, 1), 500); const offset = Math.max(query.offset ?? 0, 0); - const rows = this.db - .prepare(`SELECT * FROM request_logs ${clause} ORDER BY ts DESC, rowid DESC LIMIT ? OFFSET ?`) + const rows = this.stmt( + `SELECT * FROM request_logs ${clause} ORDER BY ts DESC, rowid DESC LIMIT ? OFFSET ?`) .all(...params, limit, offset) as Row[]; return { rows: rows.map((r) => this.mapLog(r)), total: num(totalRow.c) }; } getLog(id: string): RequestLogRow | null { - const row = this.db.prepare('SELECT * FROM request_logs WHERE id = ?').get(id) as Row | undefined; + const row = this.stmt('SELECT * FROM request_logs WHERE id = ?').get(id) as Row | undefined; return row ? this.mapLog(row) : null; } deleteLogsBefore(ts: number): number { - const res = this.db.prepare('DELETE FROM request_logs WHERE ts < ?').run(ts); - this.db.prepare('DELETE FROM request_attempts WHERE ts < ?').run(ts); + const res = this.stmt('DELETE FROM request_logs WHERE ts < ?').run(ts); + this.stmt('DELETE FROM request_attempts WHERE ts < ?').run(ts); return Number(res.changes); } clearLogs(): number { - const res = this.db.prepare('DELETE FROM request_logs').run(); - this.db.prepare('DELETE FROM request_attempts').run(); + const res = this.stmt('DELETE FROM request_logs').run(); + this.stmt('DELETE FROM request_attempts').run(); return Number(res.changes); } /* --------------------------------------------------------------------- stats */ + /** + * Nearest-rank percentile over the rows `ts >= since` with a non-null latency. + * `count` is the caller's `COUNT(latency_ms)` for the same predicate, so the + * OFFSET stays a single indexed lookup per percentile. + */ + private latencyPercentile(since: number, count: number, p: number): number { + if (count <= 0) return 0; + const index = Math.min(count - 1, Math.floor((p / 100) * count)); + const row = this.stmt( + 'SELECT latency_ms FROM request_logs WHERE ts >= ? AND latency_ms IS NOT NULL ORDER BY latency_ms ASC LIMIT 1 OFFSET ?', + ).get(since, index) as Row | undefined; + return row ? num(row.latency_ms) : 0; + } + statsOverview(windowMs: number, bucketMs: number, activeRequests: number): StatsOverview { const since = Date.now() - windowMs; - const totalsRow = this.db - .prepare( + const totalsRow = this.stmt( `SELECT COUNT(*) AS requests, COALESCE(SUM(ok), 0) AS ok, COALESCE(SUM(CASE WHEN stream = 1 THEN 1 ELSE 0 END), 0) AS streaming, @@ -686,19 +831,13 @@ export class Repo { ) .get(since) as Row; - const latencies = ( - this.db - .prepare('SELECT latency_ms FROM request_logs WHERE ts >= ? AND latency_ms IS NOT NULL ORDER BY latency_ms ASC') - .all(since) as Row[] - ).map((r) => num(r.latency_ms)); - const percentile = (p: number): number => { - if (latencies.length === 0) return 0; - const idx = Math.min(latencies.length - 1, Math.floor((p / 100) * latencies.length)); - return latencies[idx] ?? 0; - }; + const latencies = this.stmt('SELECT COUNT(latency_ms) AS c FROM request_logs WHERE ts >= ?').get(since) as Row; + const latencyCount = num(latencies.c); + // OPT-03: `ORDER BY latency_ms LIMIT 1 OFFSET k` uses the index instead of + // materializing and sorting every latency value of the window in JS. + const percentile = (p: number): number => this.latencyPercentile(since, latencyCount, p); - const seriesRows = this.db - .prepare( + const seriesRows = this.stmt( `SELECT CAST(ts / ? AS INTEGER) * ? AS bucket, COUNT(*) AS requests, COALESCE(SUM(CASE WHEN ok = 0 THEN 1 ELSE 0 END), 0) AS errors, @@ -708,8 +847,7 @@ export class Repo { .all(bucketMs, bucketMs, since) as Row[]; const byModel = ( - this.db - .prepare( + this.stmt( `SELECT COALESCE(model, 'unknown') AS model, COUNT(*) AS requests, COALESCE(SUM(total_tokens),0) AS tokens, COALESCE(SUM(CASE WHEN ok = 0 THEN 1 ELSE 0 END),0) AS errors, COALESCE(AVG(latency_ms),0) AS avg_latency FROM request_logs WHERE ts >= ? GROUP BY model ORDER BY requests DESC LIMIT 12`, @@ -724,8 +862,7 @@ export class Repo { })); const byProvider = ( - this.db - .prepare( + this.stmt( `SELECT COALESCE(provider_id, '') AS provider_id, COALESCE(provider_name, 'unknown') AS provider_name, COUNT(*) AS requests, COALESCE(SUM(CASE WHEN ok = 0 THEN 1 ELSE 0 END),0) AS errors, COALESCE(AVG(latency_ms),0) AS avg_latency @@ -741,8 +878,7 @@ export class Repo { })); const bySurface = ( - this.db - .prepare( + this.stmt( `SELECT surface, COUNT(*) AS requests, COALESCE(SUM(CASE WHEN ok = 0 THEN 1 ELSE 0 END),0) AS errors FROM request_logs WHERE ts >= ? GROUP BY surface`, ) @@ -750,8 +886,7 @@ export class Repo { ).map((r) => ({ surface: String(r.surface), requests: num(r.requests), errors: num(r.errors) })); const byKey = ( - this.db - .prepare( + this.stmt( `SELECT COALESCE(key_id, '') AS key_id, COALESCE(key_name, 'unknown') AS key_name, COUNT(*) AS requests, COALESCE(SUM(total_tokens),0) AS tokens FROM request_logs WHERE ts >= ? GROUP BY key_id ORDER BY requests DESC LIMIT 12`, @@ -765,14 +900,13 @@ export class Repo { })); const byStatus = ( - this.db - .prepare('SELECT status, COUNT(*) AS requests FROM request_logs WHERE ts >= ? GROUP BY status ORDER BY requests DESC LIMIT 12') + this.stmt( + 'SELECT status, COUNT(*) AS requests FROM request_logs WHERE ts >= ? GROUP BY status ORDER BY requests DESC LIMIT 12') .all(since) as Row[] ).map((r) => ({ status: num(r.status), requests: num(r.requests) })); const recentErrors = ( - this.db - .prepare( + this.stmt( `SELECT ts, model, provider_name, status, error_code, error_message FROM request_logs WHERE ts >= ? AND ok = 0 ORDER BY ts DESC LIMIT 10`, ) @@ -786,8 +920,7 @@ export class Repo { errorMessage: strOrNull(r.error_message), })); - const last60 = this.db - .prepare( + const last60 = this.stmt( `SELECT COUNT(*) AS requests, COALESCE(SUM(CASE WHEN ok = 0 THEN 1 ELSE 0 END),0) AS errors FROM request_logs WHERE ts >= ?`, ) @@ -840,8 +973,7 @@ export class Repo { }): SessionRow { const now = Date.now(); const expiresAt = now + input.ttlMs; - this.db - .prepare( + this.stmt( `INSERT INTO sessions (id, created_at, expires_at, last_seen_at, client_ip, user_agent) VALUES (?, ?, ?, ?, ?, ?)`, ) .run(input.id, now, expiresAt, now, input.clientIp, input.userAgent); @@ -849,7 +981,7 @@ export class Repo { } getSession(id: string): SessionRow | null { - const row = this.db.prepare('SELECT * FROM sessions WHERE id = ?').get(id) as Row | undefined; + const row = this.stmt('SELECT * FROM sessions WHERE id = ?').get(id) as Row | undefined; if (!row) return null; return { id: String(row.id), @@ -862,32 +994,32 @@ export class Repo { } touchSession(id: string): void { - this.db.prepare('UPDATE sessions SET last_seen_at = ? WHERE id = ?').run(Date.now(), id); + this.stmt('UPDATE sessions SET last_seen_at = ? WHERE id = ?').run(Date.now(), id); } deleteSession(id: string): void { - this.db.prepare('DELETE FROM sessions WHERE id = ?').run(id); + this.stmt('DELETE FROM sessions WHERE id = ?').run(id); } deleteAllSessions(): void { - this.db.prepare('DELETE FROM sessions').run(); + this.stmt('DELETE FROM sessions').run(); } /** Deletes every session except `keepId` in one statement (no LIMIT 50 pitfall). */ deleteOtherSessions(keepId: string | null): number { const result = keepId === null - ? this.db.prepare('DELETE FROM sessions').run() - : this.db.prepare('DELETE FROM sessions WHERE id <> ?').run(keepId); + ? this.stmt('DELETE FROM sessions').run() + : this.stmt('DELETE FROM sessions WHERE id <> ?').run(keepId); return Number(result.changes); } purgeExpiredSessions(): void { - this.db.prepare('DELETE FROM sessions WHERE expires_at < ?').run(Date.now()); + this.stmt('DELETE FROM sessions WHERE expires_at < ?').run(Date.now()); } listSessions(): SessionRow[] { - const rows = this.db.prepare('SELECT * FROM sessions ORDER BY last_seen_at DESC LIMIT 50').all() as Row[]; + const rows = this.stmt('SELECT * FROM sessions ORDER BY last_seen_at DESC LIMIT 50').all() as Row[]; return rows.map((r) => ({ id: String(r.id), createdAt: num(r.created_at), @@ -901,19 +1033,19 @@ export class Repo { /* --------------------------------------------------------------------- audit */ deleteAuditBefore(ts: number): number { - const result = this.db.prepare('DELETE FROM audit_logs WHERE ts < ?').run(ts); + const result = this.stmt('DELETE FROM audit_logs WHERE ts < ?').run(ts); return Number(result.changes); } audit(actor: string, action: string, target: string | null, detail: string | null): void { - this.db - .prepare('INSERT INTO audit_logs (id, ts, actor, action, target, detail) VALUES (?, ?, ?, ?, ?, ?)') + this.stmt( + 'INSERT INTO audit_logs (id, ts, actor, action, target, detail) VALUES (?, ?, ?, ?, ?, ?)') .run(uuid(), Date.now(), actor, action, target, detail); } listAudit(limit = 100): AuditRow[] { - const rows = this.db - .prepare('SELECT * FROM audit_logs ORDER BY ts DESC LIMIT ?') + const rows = this.stmt( + 'SELECT * FROM audit_logs ORDER BY ts DESC LIMIT ?') .all(Math.min(Math.max(limit, 1), 500)) as Row[]; return rows.map((r) => ({ id: String(r.id), @@ -929,7 +1061,7 @@ export class Repo { const tables = ['providers', 'models', 'api_keys', 'request_logs', 'sessions']; const out: Record = {}; for (const table of tables) { - const row = this.db.prepare(`SELECT COUNT(*) AS c FROM ${table}`).get() as Row; + const row = this.stmt(`SELECT COUNT(*) AS c FROM ${table}`).get() as Row; out[table] = num(row.c); } return out; diff --git a/src/db/schema.ts b/src/db/schema.ts index 563e32e..694a271 100644 --- a/src/db/schema.ts +++ b/src/db/schema.ts @@ -34,6 +34,8 @@ CREATE TABLE IF NOT EXISTS providers ( updated_at INTEGER NOT NULL ); +CREATE INDEX IF NOT EXISTS idx_providers_enabled ON providers (enabled, priority); + CREATE TABLE IF NOT EXISTS models ( id TEXT PRIMARY KEY, name TEXT NOT NULL, @@ -61,6 +63,8 @@ CREATE TABLE IF NOT EXISTS api_keys ( revoked_at INTEGER ); +CREATE INDEX IF NOT EXISTS idx_api_keys_active ON api_keys (enabled, revoked_at); + CREATE TABLE IF NOT EXISTS request_logs ( id TEXT PRIMARY KEY, ts INTEGER NOT NULL, @@ -92,6 +96,11 @@ CREATE INDEX IF NOT EXISTS idx_request_logs_key ON request_logs (key_id, ts DESC CREATE INDEX IF NOT EXISTS idx_request_logs_model ON request_logs (model, ts DESC); CREATE INDEX IF NOT EXISTS idx_request_logs_provider ON request_logs (provider_id, ts DESC); CREATE INDEX IF NOT EXISTS idx_request_logs_latency ON request_logs (ts, latency_ms); +-- OPT-02: indexes for real predicates (idempotent on existing databases). +CREATE INDEX IF NOT EXISTS idx_request_logs_ts_ok ON request_logs (ts, ok); + +CREATE INDEX IF NOT EXISTS idx_models_enabled ON models (enabled); +CREATE INDEX IF NOT EXISTS idx_models_provider ON models (provider_id); CREATE TABLE IF NOT EXISTS request_attempts ( id TEXT PRIMARY KEY, @@ -119,6 +128,8 @@ CREATE TABLE IF NOT EXISTS sessions ( user_agent TEXT ); +CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions (expires_at); + CREATE TABLE IF NOT EXISTS audit_logs ( id TEXT PRIMARY KEY, ts INTEGER NOT NULL, diff --git a/src/gateway/auth.ts b/src/gateway/auth.ts index cbce7ce..f6dcebb 100644 --- a/src/gateway/auth.ts +++ b/src/gateway/auth.ts @@ -6,12 +6,17 @@ import { ApiError } from '../util/errors.js'; export const NO_API_KEY_MESSAGE = 'No gateway API key configured. Create one in the dashboard (API Keys tab).'; -/** Reads the gateway key from `Authorization: Bearer ` or `x-api-key`. */ +/** + * Reads the gateway key from `Authorization: Bearer ` or `x-api-key`. + * GW-13: any other `Authorization` scheme (Basic, Digest, a bare token) is treated + * as absent instead of being used verbatim as the key — SPEC §Auth documents + * `Bearer` or `x-api-key` only. + */ export function extractApiKey(headers: IncomingHttpHeaders): string | null { const authorization = headers.authorization; if (typeof authorization === 'string' && authorization.trim().length > 0) { const match = /^bearer\s+(.+)$/i.exec(authorization.trim()); - const token = (match?.[1] ?? authorization).trim(); + const token = match?.[1]?.trim() ?? ''; if (token.length > 0) return token; } const headerKey = headers['x-api-key']; diff --git a/src/gateway/forward-headers.ts b/src/gateway/forward-headers.ts index 21a9147..fdee0a0 100644 --- a/src/gateway/forward-headers.ts +++ b/src/gateway/forward-headers.ts @@ -10,6 +10,10 @@ import type { IncomingHttpHeaders } from 'node:http'; */ const FORWARDED_HEADERS = [ 'anthropic-beta', + // GW-07: the client's Anthropic API version + browser-access opt-in must reach + // the provider, otherwise newer API versions are unreachable. + 'anthropic-version', + 'anthropic-dangerous-direct-browser-access', 'openai-beta', 'accept', 'accept-language', @@ -31,14 +35,19 @@ function firstValue(value: string | string[] | undefined): string | null { /** * Builds the upstream header allowlist from the client headers. `accept` is only - * defaulted when streaming: a non-streaming client that sent its own `accept` - * keeps it, and the default is required for SSE providers that branch on it. + * defaulted to JSON for non-streaming calls here; a streaming default + * (`text/event-stream`) is applied by `upstreamFetch` (GW-06), so a client that + * did send its own `accept` keeps it on every surface. */ export function forwardHeaders(headers: IncomingHttpHeaders, options: { acceptJson?: boolean } = {}): Record { const out: Record = {}; for (const name of FORWARDED_HEADERS) { const value = firstValue(headers[name]); - if (value !== null) out[name] = value; + if (value === null) continue; + // A bare wildcard means "anything", so it must not shadow the concrete + // surface default (`application/json` / `text/event-stream`, GW-06). + if (name === 'accept' && value.trim() === '*/*') continue; + out[name] = value; } for (const [name, raw] of Object.entries(headers)) { const lower = name.toLowerCase(); diff --git a/src/gateway/index.ts b/src/gateway/index.ts index cc3aba9..816258c 100644 --- a/src/gateway/index.ts +++ b/src/gateway/index.ts @@ -2,6 +2,7 @@ import type { FastifyInstance } from 'fastify'; import type { AppContext } from '../core/context.js'; import { installGatewayErrorHandler } from './errors.js'; import { registerModelsRoutes } from './models-route.js'; +import { registerUnknownGatewayRoutes } from './not-found.js'; import { installGatewayHooks } from './preauth.js'; import { registerProxyRoutes } from './proxy.js'; @@ -27,5 +28,7 @@ export async function registerGatewayRoutes(app: FastifyInstance, ctx: AppContex installGatewayHooks(scope, ctx); registerProxyRoutes(scope, ctx); registerModelsRoutes(scope, ctx); + // Registered last so it only handles paths no real route claimed (GW-04). + registerUnknownGatewayRoutes(scope, ctx); }); } diff --git a/src/gateway/logging.ts b/src/gateway/logging.ts index 873bc7f..386e23c 100644 --- a/src/gateway/logging.ts +++ b/src/gateway/logging.ts @@ -1,8 +1,33 @@ import type { AppContext } from '../core/context.js'; +import type { ProviderEvent, RequestEndEvent, RequestStartEvent } from '../core/events.js'; import type { ApiKeyRow, AttemptRow, ProviderRow, RequestLogRow, Surface, Usage } from '../types.js'; import { uuid } from '../util/crypto.js'; import { emptyUsage } from './usage.js'; +/** + * GW-14: dashboard SSE listeners run synchronously inside the request path, so a + * throwing listener must never take the reply (or the log row) down with it. + */ +function guardedEmit(ctx: AppContext, name: string, emit: () => void): void { + try { + emit(); + } catch (error) { + ctx.logger.warn({ err: error, event: name }, 'gateway event listener threw'); + } +} + +export function emitRequestStart(ctx: AppContext, event: RequestStartEvent): void { + guardedEmit(ctx, 'request:start', () => ctx.events.emitRequestStart(event)); +} + +export function emitRequestEnd(ctx: AppContext, event: RequestEndEvent): void { + guardedEmit(ctx, 'request:end', () => ctx.events.emitRequestEnd(event)); +} + +export function emitProvider(ctx: AppContext, event: ProviderEvent): void { + guardedEmit(ctx, 'provider:update', () => ctx.events.emitProvider(event)); +} + export function newAttempt(input: { requestId: string; providerId: string; @@ -85,6 +110,6 @@ export function recordRequestLog(ctx: AppContext, input: RequestLogInput): Reque } catch (error) { ctx.logger.warn({ err: error, requestId: input.requestId }, 'failed to insert gateway request log'); } - ctx.events.emitRequestEnd({ log }); + emitRequestEnd(ctx, { log }); return log; -} \ No newline at end of file +} diff --git a/src/gateway/normalize.ts b/src/gateway/normalize.ts index d8238eb..3fce890 100644 --- a/src/gateway/normalize.ts +++ b/src/gateway/normalize.ts @@ -64,6 +64,11 @@ export function normalizeBody( options: { countTokens?: boolean } = {}, ): NormalizedBody { const next: Json = { ...body }; + // GW-11: the gateway routes and logs the trimmed model id, so the trimmed id is + // also what the provider must receive (`" x "` would otherwise be rejected). + if (typeof next.model === 'string' && next.model !== next.model.trim() && next.model.trim().length > 0) { + next.model = next.model.trim(); + } let requestedEffort = requestedEffortFor(surface, body); let appliedEffort: string | null = null; diff --git a/src/gateway/not-found.ts b/src/gateway/not-found.ts new file mode 100644 index 0000000..27d6f0a --- /dev/null +++ b/src/gateway/not-found.ts @@ -0,0 +1,48 @@ +import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; +import type { AppContext } from '../core/context.js'; +import { ApiError } from '../util/errors.js'; +import { sendApiError, surfaceForUrl } from './errors.js'; +import { recordRequestLog } from './logging.js'; +import { gatewayState } from './preauth.js'; + +/** + * GW-04: unknown `/v1/*` paths used to fall through to the root not-found handler, + * which runs outside the gateway scope — so the API-key hook never ran (anonymous + * access) and no `request_logs` row was written (SPEC §Auth, golden rule 3). + * + * This catch-all lives inside the authenticated gateway scope and is registered + * last, so real routes always win. It still writes exactly one log row and answers + * with the surface-shaped error envelope. + */ +export function registerUnknownGatewayRoutes(app: FastifyInstance, ctx: AppContext): void { + const handler = async (request: FastifyRequest, reply: FastifyReply): Promise => { + const state = gatewayState(request); + const surface = surfaceForUrl(request.url); + const error = new ApiError('not_found_error', `Unknown endpoint: ${request.method} ${request.url}`, { + code: 'unknown_endpoint', + }); + const userAgent = request.headers['user-agent']; + state.logged = true; + recordRequestLog(ctx, { + requestId: state.requestId, + startedAt: state.startedAt, + key: state.key, + model: null, + surface, + stream: false, + status: error.status, + ok: false, + errorCode: error.code ?? error.type, + errorMessage: error.message, + ttfbMs: null, + attempts: 0, + clientIp: request.ip ?? null, + userAgent: typeof userAgent === 'string' ? userAgent : null, + }); + sendApiError(reply, surface, error, state.requestId); + }; + + app.all('/v1/*', handler); + // `/v1` itself is not covered by the wildcard; it is just as unknown. + app.all('/v1', handler); +} \ No newline at end of file diff --git a/src/gateway/preauth.ts b/src/gateway/preauth.ts index 141175b..d22035b 100644 --- a/src/gateway/preauth.ts +++ b/src/gateway/preauth.ts @@ -5,7 +5,7 @@ import { uuid } from '../util/crypto.js'; import { ApiError } from '../util/errors.js'; import { authenticate } from './auth.js'; import { sendApiError, surfaceForUrl } from './errors.js'; -import { recordRequestLog } from './logging.js'; +import { emitRequestStart, recordRequestLog } from './logging.js'; /** Per-request state produced by the pre-body authentication hook. */ export interface GatewayRequestState { @@ -15,8 +15,12 @@ export interface GatewayRequestState { key: ApiKeyRow | null; /** True once the single request_logs row for this request has been written. */ logged: boolean; - /** Raw body text captured by the gateway JSON parser (FIX-09). */ - rawBody: string | null; + /** + * Raw client bytes captured by the gateway JSON parser (FIX-09/GW-08). Kept as a + * Buffer: decoding to a string would rewrite invalid UTF-8 into U+FFFD and break + * the documented byte-for-byte forwarding. + */ + rawBody: Buffer | null; } declare module 'fastify' { @@ -46,7 +50,7 @@ export function createPreAuthHook(ctx: AppContext) { return; } state.key = key; - ctx.events.emitRequestStart({ + emitRequestStart(ctx, { id: state.requestId, ts: state.startedAt, surface: surfaceForUrl(request.url), @@ -84,7 +88,7 @@ function rejectUnauthenticated( // Every log row gets its paired start event, rejections included, so SSE // consumers never see an orphan `request:end`. - ctx.events.emitRequestStart({ + emitRequestStart(ctx, { id: state.requestId, ts: state.startedAt, surface, @@ -127,23 +131,24 @@ export function gatewayState(request: FastifyRequest): GatewayRequestState { /** * Registers the gateway pre-auth hook plus the raw-body JSON parser on the - * encapsulated gateway scope. The parser keeps the verbatim body text so - * unmodified payloads can be forwarded byte-for-byte (FIX-09). + * encapsulated gateway scope. The parser keeps the verbatim bytes (GW-08: + * `parseAs: 'buffer'`) so unmodified payloads are forwarded byte-for-byte, even + * when the client body is not valid UTF-8. */ export function installGatewayHooks(scope: FastifyInstance, ctx: AppContext): void { scope.addHook('onRequest', createPreAuthHook(ctx)); // Encapsulated to this scope: admin keeps its own lenient parser. - scope.addContentTypeParser('application/json', { parseAs: 'string' }, (request, body, done) => { - const text = typeof body === 'string' ? body : String(body ?? ''); - if (request.gateway) request.gateway.rawBody = text; - if (text.trim().length === 0) { + scope.addContentTypeParser('application/json', { parseAs: 'buffer' }, (request, body, done) => { + const bytes = Buffer.isBuffer(body) ? body : Buffer.from(String(body ?? ''), 'utf8'); + if (request.gateway) request.gateway.rawBody = bytes; + if (bytes.length === 0) { // The handler reports the missing body with the surface-shaped error. done(null, undefined); return; } try { - const parsed: unknown = JSON.parse(text); + const parsed: unknown = JSON.parse(bytes.toString('utf8')); if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { done( new ApiError('invalid_request_error', 'Request body must be a JSON object.', { diff --git a/src/gateway/proxy.ts b/src/gateway/proxy.ts index d563526..7f29140 100644 --- a/src/gateway/proxy.ts +++ b/src/gateway/proxy.ts @@ -6,7 +6,7 @@ import { SseParser } from '../util/sse.js'; import { upstreamFetch, type UpstreamResponse } from '../util/upstream.js'; import { forwardHeaders } from './forward-headers.js'; import { sendApiError } from './errors.js'; -import { newAttempt, recordRequestLog } from './logging.js'; +import { emitProvider, newAttempt, recordRequestLog } from './logging.js'; import { normalizeBody } from './normalize.js'; import { gatewayState } from './preauth.js'; import { orderProviders, parseRotationStrategy } from './rotation.js'; @@ -19,6 +19,23 @@ export interface ProxyRoute { countTokens?: boolean; } +/** Hard cap on one unterminated SSE frame (GW-05); prevents unbounded buffering. */ +export const SSE_MAX_FRAME_BYTES = 1024 * 1024; +/** `stream_idle_timeout_ms` bounds (SPEC §2.5). */ +const MIN_STREAM_IDLE_MS = 1_000; +const DEFAULT_STREAM_IDLE_MS = 120_000; + +/** Upstream response headers that are meaningful to SDK clients (GW-09). */ +const RESPONSE_HEADER_ALLOWLIST = [ + 'retry-after', + 'request-id', + 'x-request-id', + 'openai-processing-ms', + 'openai-version', + 'anthropic-version', +] as const; +const RESPONSE_HEADER_PREFIXES = ['x-ratelimit-', 'anthropic-ratelimit-', 'x-stainless-'] as const; + const PROXY_ROUTES: ProxyRoute[] = [ { url: '/v1/chat/completions', surface: 'chat', upstreamPath: '/chat/completions' }, { url: '/v1/responses', surface: 'responses', upstreamPath: '/responses' }, @@ -53,6 +70,65 @@ function isTimeoutFailure(error: ApiError | null | undefined): boolean { return error.type === 'timeout_error' || error.code === 'upstream_timeout'; } +/** + * HTTP status for a failure that happened while reading an upstream response body + * (GW-03). A truncated body on a `2xx` upstream response is a gateway-side failure + * and must never be answered with that 2xx status, or SDKs parse the error envelope + * as a completion. An upstream status that is already an error is kept as is. + */ +export function bodyReadFailureStatus(upstreamStatus: number, timedOut: boolean): number { + if (timedOut) return 504; + return upstreamStatus >= 400 ? upstreamStatus : 502; +} + +/** Smallest still-active cooldown across enabled providers, or null (FEAT-06). */ +export function smallestCooldownUntil(providers: ProviderRow[], now = Date.now()): number | null { + let smallest: number | null = null; + for (const provider of providers) { + if (!provider.enabled) continue; + const until = provider.cooldownUntil; + if (until === null || until <= now) continue; + if (smallest === null || until < smallest) smallest = until; + } + return smallest; +} + +/** `Retry-After` is whole seconds and never 0 for a rate-limit answer (FEAT-06). */ +export function retryAfterSeconds(cooldownUntil: number | null, now = Date.now()): number { + if (cooldownUntil === null) return 1; + return Math.max(1, Math.ceil((cooldownUntil - now) / 1000)); +} + +/** + * Drops every character Node refuses in a header value (`ERR_INVALID_CHAR`): control + * characters, CR/LF injection attempts and anything outside Latin-1 (GW-10). + */ +export function sanitizeHeaderValue(value: string): string { + return value.replace(/[^\t\x20-\x7E\x80-\xFF]/g, ''); +} + +/** + * Picks the upstream response headers worth forwarding to the SDK client (GW-09): + * retry/backoff and rate-limit signals plus request ids. `overrides` (router + * headers, content-type/length, SSE framing) always win, and `content-encoding` + * never ships because the gateway already decoded the body. + */ +export function forwardedResponseHeaders( + upstream: Headers, + overrides: Record, +): Record { + const out: Record = {}; + upstream.forEach((value, name) => { + const lower = name.toLowerCase(); + const allowed = + (RESPONSE_HEADER_ALLOWLIST as readonly string[]).includes(lower) || + RESPONSE_HEADER_PREFIXES.some((prefix) => lower.startsWith(prefix)); + if (allowed && value.length > 0) out[lower] = value; + }); + for (const [name, value] of Object.entries(overrides)) out[name] = value; + return out; +} + interface SurfaceOutcome { status: number; ok: boolean; @@ -115,10 +191,12 @@ function readBody(request: FastifyRequest): Json { } function routerHeaders(provider: ProviderRow, requestId: string, attempts: number): Record { + // GW-10: provider ids/names are operator supplied; a CR/LF or a non-Latin-1 + // character would make Node throw ERR_INVALID_CHAR for every request. return { - 'x-opencode-router-provider': provider.id, - 'x-opencode-router-name': provider.name, - 'x-opencode-router-request-id': requestId, + 'x-opencode-router-provider': sanitizeHeaderValue(provider.id), + 'x-opencode-router-name': sanitizeHeaderValue(provider.name), + 'x-opencode-router-request-id': sanitizeHeaderValue(requestId), 'x-opencode-router-attempts': String(attempts), }; } @@ -155,8 +233,8 @@ interface AttemptOptions { userAgent: string; signal: AbortSignal; headers: Record; - /** Raw client body; forwarded verbatim so no bytes are rewritten (FIX-09). */ - rawBody: string | null; + /** Raw client bytes; forwarded verbatim so no byte is rewritten (FIX-09/GW-08). */ + rawBody: Buffer | null; body: Json; /** Streaming chat needs an SSE accept header when the client did not send one. */ stream: boolean; @@ -181,6 +259,9 @@ async function runAttempt( timeoutMs: options.timeoutMs, userAgent: options.userAgent, signal: options.signal, + stream: options.stream, + // GW-07: only the Anthropic Messages surface gets an anthropic-version default. + anthropic: route.surface === 'messages', // 3xx never followed: the provider key must not cross origins (FIX-08). redirect: 'manual', }); @@ -201,7 +282,7 @@ async function runAttempt( }), ); ctx.repo.recordProviderSuccess(provider.id, latencyMs); - ctx.events.emitProvider({ + emitProvider(ctx, { providerId: provider.id, state: 'ok', status: upstream.status, @@ -241,7 +322,7 @@ async function runAttempt( // It is fatal for this request (single attempt, logged, cooled down) so the // credentials are never replayed to the redirect target. ctx.repo.recordProviderFailure(provider.id, upstream.status, mapped.message, options.cooldownMs); - ctx.events.emitProvider({ + emitProvider(ctx, { providerId: provider.id, state: 'error', status: upstream.status, @@ -257,7 +338,7 @@ async function runAttempt( const retryAfter = retryAfterMs(upstream.headers.get('retry-after')); const cooldownMs = retryAfter === null ? options.cooldownMs : Math.max(options.cooldownMs, retryAfter); ctx.repo.recordProviderFailure(provider.id, upstream.status, mapped.message, cooldownMs); - ctx.events.emitProvider({ + emitProvider(ctx, { providerId: provider.id, state: 'cooldown', status: upstream.status, @@ -281,17 +362,37 @@ async function runAttempt( }; } if (isTimeoutReason(abortReason)) { - return { - kind: 'abort', - latencyMs, - timedOut: true, - error: - error instanceof ApiError - ? error - : new ApiError('timeout_error', `Upstream provider "${provider.name}" timed out.`, { - code: 'upstream_timeout', - }), - }; + const timeoutError = + error instanceof ApiError + ? error + : new ApiError('timeout_error', `Upstream provider "${provider.name}" timed out.`, { + code: 'upstream_timeout', + }); + // GW-02: a timed-out attempt is an ordinary failed attempt: it gets its + // `request_attempts` row, a provider cooldown and a provider event, so the + // provider is not retried first on the next request. + ctx.repo.insertAttempt( + newAttempt({ + requestId: options.requestId, + providerId: provider.id, + providerName: provider.name, + attempt: options.attempt, + status: null, + ok: false, + errorCode: timeoutError.code ?? timeoutError.type, + errorMessage: timeoutError.message, + latencyMs, + }), + ); + ctx.repo.recordProviderFailure(provider.id, null, timeoutError.message, options.cooldownMs); + emitProvider(ctx, { + providerId: provider.id, + state: 'error', + status: null, + message: timeoutError.message, + ts: Date.now(), + }); + return { kind: 'abort', latencyMs, timedOut: true, error: timeoutError }; } const apiError = error instanceof ApiError @@ -311,7 +412,7 @@ async function runAttempt( }), ); ctx.repo.recordProviderFailure(provider.id, null, apiError.message, options.cooldownMs); - ctx.events.emitProvider({ + emitProvider(ctx, { providerId: provider.id, state: 'error', status: null, @@ -462,19 +563,25 @@ async function streamSurface(input: StreamContext): Promise { let ttfbMs: number | null = null; let aborted = false; let timedOut = false; + let frameTooLarge = false; let ok = true; let errorCode: string | null = null; let errorMessage: string | null = null; try { reply.hijack(); - reply.raw.writeHead(upstream.status, { - 'content-type': 'text/event-stream; charset=utf-8', - 'cache-control': 'no-cache', - connection: 'keep-alive', - 'x-accel-buffering': 'no', - ...routerHeaders(provider, requestId, attempts), - }); + // GW-09: forward the upstream retry/rate-limit/request-id headers alongside the + // SSE framing; content-length is intentionally absent (chunked stream). + reply.raw.writeHead( + upstream.status, + forwardedResponseHeaders(upstream.headers, { + 'content-type': 'text/event-stream; charset=utf-8', + 'cache-control': 'no-cache', + connection: 'keep-alive', + 'x-accel-buffering': 'no', + ...routerHeaders(provider, requestId, attempts), + }), + ); reply.raw.flushHeaders(); } catch (error) { disposeUpstream(upstream); @@ -568,6 +675,13 @@ async function streamSurface(input: StreamContext): Promise { break; } pending = offset >= merged.length ? Buffer.alloc(0) : merged.subarray(offset); + // GW-05: a provider streaming bytes without `\n\n` would otherwise buffer the + // whole response in memory (the request bodyLimit does not apply here). + if (pending.length > SSE_MAX_FRAME_BYTES) { + frameTooLarge = true; + upstream.abort('upstream_frame_too_large'); + break; + } if (reply.raw.writableNeedDrain) { const result = await waitForDrain(reply, guard, input.idleMs); if (result !== 'drain') { @@ -577,7 +691,13 @@ async function streamSurface(input: StreamContext): Promise { } } - if (!aborted) { + if (frameTooLarge) { + try { + reply.raw.end(); + } catch { + /* already closed */ + } + } else if (!aborted) { if (pending.length > 0) { const text = pending.toString('utf8'); for (const message of sse.push(`${text}\n\n`)) { @@ -624,7 +744,7 @@ async function streamSurface(input: StreamContext): Promise { } finally { clearIdle(); guard.signal.removeEventListener('abort', onClientAbort); - if (aborted) { + if (aborted || frameTooLarge) { try { await reader.cancel(); } catch { @@ -639,6 +759,12 @@ async function streamSurface(input: StreamContext): Promise { disposeUpstream(upstream); } + if (frameTooLarge) { + ok = false; + errorCode = 'upstream_frame_too_large'; + errorMessage = `Upstream SSE frame exceeded ${SSE_MAX_FRAME_BYTES} bytes without a frame delimiter.`; + } + if (aborted) { ok = false; errorCode = 'client_aborted'; @@ -646,7 +772,7 @@ async function streamSurface(input: StreamContext): Promise { } return { - status: aborted ? 499 : timedOut ? 504 : upstream.status, + status: aborted ? 499 : timedOut ? 504 : frameTooLarge ? 502 : upstream.status, ok, aborted, timedOut, @@ -682,7 +808,7 @@ async function jsonSurface( // an error response; a timeout must not surface as the upstream's 2xx status. const timedOut = isTimeoutReason(upstream.abortReason); return { - status: timedOut ? 504 : upstream.status, + status: bodyReadFailureStatus(upstream.status, timedOut), ok: false, aborted: false, timedOut, @@ -695,11 +821,13 @@ async function jsonSurface( disposeUpstream(upstream); } const usage = mergeUsage(emptyUsage(), extractUsageFromJson(parseJson(buffer.toString('utf8')))); - const headers: Record = { + // GW-09: forward the upstream retry/rate-limit/request-id headers; the router and + // the rewritten body (content-type/length) always win. + const headers = forwardedResponseHeaders(upstream.headers, { 'content-type': upstream.headers.get('content-type') ?? 'application/json', 'content-length': String(buffer.byteLength), ...routerHeaders(provider, requestId, attempts), - }; + }); try { reply.hijack(); reply.raw.writeHead(upstream.status, headers); @@ -789,7 +917,7 @@ async function handleProxyRequest( { code: 'no_provider_configured', status: 503 }, ); } - if (ctx.repo.enabledModelIds().length === 0 && !allowUnknown) { + if (!ctx.repo.hasEnabledModel() && !allowUnknown) { throw new ApiError( 'api_error', 'No models are enabled. Sync or enable models in the dashboard (Models tab).', @@ -815,6 +943,12 @@ async function handleProxyRequest( const cooldownMs = Math.max(0, ctx.repo.getInt('provider_cooldown_ms', 60_000)); const maxRetries = Math.max(1, ctx.repo.getInt('max_retries', 3)); const timeoutMs = Math.max(1_000, ctx.repo.getInt('request_timeout_ms', 600_000)); + // GW-05: the stream idle gap is its own setting (min 1s); `timeoutMs` stays the + // total deadline enforced by upstreamFetch. + const streamIdleMs = Math.max( + MIN_STREAM_IDLE_MS, + ctx.repo.getInt('stream_idle_timeout_ms', DEFAULT_STREAM_IDLE_MS), + ); const upstreamUserAgent = ctx.repo.getSetting('upstream_user_agent') ?? 'opencode-router/1.0'; const strategy = parseRotationStrategy(ctx.repo.getSetting('rotation_strategy')); const requestHeaders = forwardHeaders(request.headers, { acceptJson: !stream || route.countTokens === true }); @@ -825,6 +959,7 @@ async function handleProxyRequest( let lastStatus: number | null = null; let lastError: ApiError | null = null; let fatalError: ApiError | null = null; + let lastAttemptProvider: ProviderRow | null = null; let everyFailureRateLimited = true; let everyFailureTimeout = true; let attemptNo = 0; @@ -846,6 +981,7 @@ async function handleProxyRequest( attempts += 1; attemptNo += 1; + lastAttemptProvider = fresh; const attempt = await runAttempt(ctx, fresh, route, { requestId, attempt: attemptNo, @@ -861,8 +997,13 @@ async function handleProxyRequest( if (attempt.kind === 'abort') { if (attempt.timedOut) { - // A timeout before any headers reached the client becomes a 504. - throw attempt.error ?? new ApiError('timeout_error', 'Upstream provider timed out.', { code: 'upstream_timeout' }); + // GW-01: a timed-out attempt is already logged and cooled down by + // `runAttempt`; fail over to the next candidate and answer the aggregated + // 504 only after every candidate is exhausted. + lastStatus = null; + lastError = attempt.error; + everyFailureRateLimited = false; + continue; } aborted = true; break; @@ -879,7 +1020,7 @@ async function handleProxyRequest( attempts, requestStartedAt: startedAt, guard, - idleMs: timeoutMs, + idleMs: streamIdleMs, }) : await jsonSurface(reply, surface, requestId, fresh, attempt.response, attempts, attempt.latencyMs); usage = outcome.usage; @@ -926,13 +1067,20 @@ async function handleProxyRequest( // Client error: surface the upstream error untouched, no failover. throw fatalError; } else if (attempts > 0 && everyFailureRateLimited && lastStatus === 429) { + // FEAT-06: hand SDK clients a concrete backoff instead of a hot retry loop. + const cooldownUntil = smallestCooldownUntil(ctx.repo.listProviders()); + const retryAfter = retryAfterSeconds(cooldownUntil); + reply.header('retry-after', String(retryAfter)); + reply.header('x-opencode-router-cooldown-until', String(cooldownUntil ?? Date.now() + retryAfter * 1000)); throw new ApiError('rate_limit_error', 'All providers are rate limited (HTTP 429). Try again shortly.', { code: 'all_providers_rate_limited', status: 429, }); } else if (attempts > 0 && everyFailureTimeout) { // Every provider failed on a network/timeout path: the deadline, not the - // provider, is what the client hit (FIX-04). + // provider, is what the client hit (FIX-04). GW-02: attribute the log row to + // the provider that actually timed out. + provider = lastAttemptProvider; throw new ApiError('timeout_error', lastError?.message ?? 'Every provider timed out.', { status: 504, code: 'upstream_timeout', diff --git a/src/index.ts b/src/index.ts index 791c872..1c0ed63 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,6 +3,7 @@ import { openDatabase } from './db/index.js'; import { Repo } from './db/repos.js'; import { EventBus } from './core/events.js'; import { seedDefaults, pruneLogs } from './core/seed.js'; +import { registerGracefulShutdown } from './core/shutdown.js'; import { buildServer } from './server.js'; import { startScheduler } from './admin/scheduler.js'; @@ -55,14 +56,12 @@ async function main(): Promise { }, 6 * 60 * 60 * 1000); pruneTimer.unref(); - const shutdown = async (signal: string): Promise => { - app.log.info({ signal }, 'shutting down'); - clearInterval(pruneTimer); - await app.close(); - process.exit(0); - }; - process.on('SIGINT', () => void shutdown('SIGINT')); - process.on('SIGTERM', () => void shutdown('SIGTERM')); + // FEAT-07: bound the drain; `app.close()` also runs the `onClose` hook that stops + // the scheduler and closes the database (flushing the WAL). + registerGracefulShutdown(app, { + timeoutMs: 10_000, + onShutdownStart: () => clearInterval(pruneTimer), + }); } -void main(); \ No newline at end of file +void main(); diff --git a/src/server.ts b/src/server.ts index c06d9cd..8a3ec8d 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,7 +1,7 @@ import Fastify, { type FastifyInstance } from 'fastify'; import fastifyCookie from '@fastify/cookie'; import fastifyStatic from '@fastify/static'; -import { existsSync, mkdirSync } from 'node:fs'; +import { existsSync, mkdirSync, readFileSync, statSync } from 'node:fs'; import { isAbsolute, join, relative, resolve } from 'node:path'; import type { AppContext } from './core/context.js'; import { ApiError } from './util/errors.js'; @@ -42,6 +42,11 @@ export async function buildServer(ctx: AppContext): Promise { wildcard: false, decorateReply: true, index: false, + // The dashboard shell is gated server-side for every path that serves it, so + // `/index.html` must never be answered by the static handler (which has no + // session check). Unknown shell paths fall through to the gated not-found + // handler; `sendSpa` below reads the file after the gate instead. + allowedPath: (pathname: string): boolean => pathname !== '/index.html' && pathname !== '/', }); app.get('/health', async () => ({ @@ -59,9 +64,23 @@ export async function buildServer(ctx: AppContext): Promise { await registerAdminRoutes(app, ctx); const indexHtml = join(webDist, 'index.html'); + // Shell content cache: read once, re-read only when the build changes on disk. + let shellCache: { mtimeMs: number; html: string } | null = null; + const readShell = (): string | null => { + try { + const { mtimeMs } = statSync(indexHtml); + if (!shellCache || shellCache.mtimeMs !== mtimeMs) { + shellCache = { mtimeMs, html: readFileSync(indexHtml, 'utf8') }; + } + return shellCache.html; + } catch { + return null; + } + }; const sendSpa = async (_request: unknown, reply: import('fastify').FastifyReply): Promise => { - if (existsSync(indexHtml)) { - await reply.sendFile('index.html'); + const html = existsSync(indexHtml) ? readShell() : null; + if (html !== null) { + await reply.status(200).type('text/html; charset=utf-8').send(html); return; } await reply diff --git a/src/util/upstream.ts b/src/util/upstream.ts index 8832dda..1c3e785 100644 --- a/src/util/upstream.ts +++ b/src/util/upstream.ts @@ -15,16 +15,38 @@ export interface UpstreamRequest { /** Structured body: serialized with JSON.stringify unless `rawBody` is set. */ body?: unknown; /** Client body kept byte-for-byte; takes precedence over `body`. */ - rawBody?: string; + rawBody?: Buffer; /** Extra request headers (client beta/trace headers); router auth headers win. */ headers?: Record; timeoutMs?: number; signal?: AbortSignal | null; userAgent?: string; + /** True for a streaming request: `accept` defaults to `text/event-stream`. */ + stream?: boolean; + /** True for the Anthropic Messages surface: `anthropic-version` gets a default. */ + anthropic?: boolean; /** `manual` (default) refuses to follow redirects so credentials never leave the origin. */ redirect?: 'manual' | 'follow'; } +/** + * Removes userinfo and query from a URL before it is embedded in an error message + * that reaches `request_logs.error_message`, `providers.last_error` or the client + * (GW-12: `https://user:pass@host/v1` must never leak the credentials). + */ +export function redactUrl(raw: string): string { + try { + const url = new URL(raw); + url.username = ''; + url.password = ''; + url.search = ''; + url.hash = ''; + return url.toString(); + } catch { + return raw; + } +} + export interface UpstreamResponse { status: number; ok: boolean; @@ -42,6 +64,21 @@ export interface UpstreamResponse { readonly abortReason: string | null; } +/** + * Scrubs credentials a runtime error may quote verbatim. `fetch` itself rejects a + * credentialed URL with the full URL in its message, so redacting only the URL the + * gateway composes is not enough (GW-12). + */ +export function redactMessage(message: string, url: string): string { + let out = message.split(url).join(redactUrl(url)); + out = out.replace(/(\/\/)[^/@\s]+@/g, '$1'); + out = out.replace( + /([?&](?:api[_-]?key|key|token|access[_-]?token|password)=)[^&\s]*/gi, + '$1REDACTED', + ); + return out; +} + /** * Performs a request against an OpenAI/Anthropic compatible provider endpoint. * Network level failures are converted into ApiError instances. @@ -73,11 +110,15 @@ export async function upstreamFetch(req: UpstreamRequest): Promise = { 'content-type': 'application/json', - accept: 'application/json', + // GW-06: a streaming client that sent no `Accept` must still advertise SSE, + // otherwise providers that branch on the header answer with a JSON body. + accept: req.stream === true ? 'text/event-stream' : 'application/json', authorization: `Bearer ${req.apiKey}`, 'x-api-key': req.apiKey, - 'anthropic-version': '2023-06-01', 'user-agent': req.userAgent ?? 'opencode-router/1.0', + // GW-07: the Anthropic API version is only a default for the Messages surface; + // a client-supplied value (forwarded via `headers`) wins over it. + ...(req.anthropic === true ? { 'anthropic-version': '2023-06-01' } : {}), ...(req.headers ?? {}), }; // Router-supplied credentials always win over caller-supplied header echoes. @@ -108,16 +149,20 @@ export async function upstreamFetch(req: UpstreamRequest): Promise ({ + status: 200, + payload: { object: 'list', data: [{ id: 'm1' }, { id: 'm2' }] } as unknown, + calls: [] as Array<{ baseUrl: string; apiKey: string; path: string }>, +})); + +vi.mock('../src/util/upstream.js', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + upstreamFetch: async (request: { baseUrl: string; apiKey: string; path: string }) => { + upstream.calls.push({ baseUrl: request.baseUrl, apiKey: request.apiKey, path: request.path }); + const body = typeof upstream.payload === 'string' ? upstream.payload : JSON.stringify(upstream.payload); + return { + status: upstream.status, + ok: upstream.status >= 200 && upstream.status < 300, + headers: new Headers({ 'content-type': 'application/json' }), + response: new Response(body, { status: upstream.status, headers: { 'content-type': 'application/json' } }), + dispose: () => {}, + abort: () => {}, + abortReason: null, + }; + }, + }; +}); + +/* ----------------------------------------------------------------------- harness */ + +interface TestApp { + app: FastifyInstance; + ctx: AppContext; + repo: Repo; + handle: DbHandle; + dataDir: string; + /** A valid signed session cookie for direct route calls. */ + cookie(): string; + /** Real `/login` round-trip; returns the cookie header value. */ + login(password?: string): Promise; + request(method: string, url: string, payload?: unknown, cookie?: string): Promise; + json(method: string, url: string, payload?: unknown, cookie?: string): Promise; + close(): Promise; +} + +async function buildAdminApp(configOverrides: Partial = {}): Promise { + const dataDir = mkdtempSync(join(tmpdir(), 'okr-admin-')); + const config: AppConfig = { ...testConfig(dataDir), ...configOverrides }; + const handle = openDatabase(config); + const repo = new Repo(handle.db); + const ctx: AppContext = { + config, + db: handle, + repo, + events: new EventBus(), + logger: null as never, + startedAt: Date.now(), + }; + const app = Fastify({ logger: false, bodyLimit: config.bodyLimit, trustProxy: config.trustProxy }); + ctx.logger = app.log; + await app.register(fastifyCookie); + await registerAdminRoutes(app, ctx); + + const request = async ( + method: string, + url: string, + payload?: unknown, + cookie?: string, + ): Promise => + app.inject({ + method: method as 'GET', + url, + ...(payload === undefined ? {} : { payload: payload as object }), + ...(cookie === undefined ? {} : { headers: { cookie } }), + }); + + return { + app, + ctx, + repo, + handle, + dataDir, + cookie(): string { + const session = repo.createSession({ + id: randomUUID(), + ttlMs: config.sessionTtlMs, + clientIp: '127.0.0.1', + userAgent: 'vitest', + }); + return `${SESSION_COOKIE}=${buildSessionCookie(ctx.db.secret, session.id, session.expiresAt)}`; + }, + async login(password = '123456'): Promise { + const response = await request('POST', '/admin/api/login', { password }); + const cookie = response.cookies.find((item) => item.name === SESSION_COOKIE); + if (!cookie) throw new Error(`login failed: ${response.statusCode} ${response.body}`); + return `${SESSION_COOKIE}=${cookie.value}`; + }, + request, + async json(method: string, url: string, payload?: unknown, cookie?: string): Promise { + const response = await request(method, url, payload, cookie); + return JSON.parse(response.body) as T; + }, + async close(): Promise { + await app.close(); + handle.db.close(); + rmSync(dataDir, { recursive: true, force: true }); + }, + }; +} + +let app: TestApp; + +beforeEach(async () => { + resetLoginAttempts(); + resetEventStreams(); + upstream.status = 200; + upstream.payload = { object: 'list', data: [{ id: 'm1' }, { id: 'm2' }] }; + upstream.calls = []; + app = await buildAdminApp(); +}); + +afterEach(async () => { + await app.close(); +}); + +/* ------------------------------------------------------------------------ login */ + +describe('login brute-force guard (FEAT-08)', () => { + it('limits per IP after LOGIN_MAX_ATTEMPTS failures', () => { + for (let index = 0; index < LOGIN_MAX_ATTEMPTS; index += 1) recordLoginFailure('10.0.0.1'); + const hit = checkLoginRateLimit('10.0.0.1'); + expect(hit?.scope).toBe('ip'); + expect(hit?.retryAfterMs).toBeGreaterThan(0); + expect(checkLoginRateLimit('10.0.0.2')).toBeNull(); + }); + + it('limits globally across many IPs', () => { + for (let index = 0; index < LOGIN_GLOBAL_MAX_ATTEMPTS; index += 1) { + recordLoginFailure(`10.0.${Math.floor(index / 250)}.${index % 250}`); + } + const hit = checkLoginRateLimit('198.51.100.7'); + expect(hit?.scope).toBe('global'); + expect(hit?.retryAfterMs).toBeGreaterThan(0); + }); + + it('returns 429 + retry-after from the route and blocks even a correct password', async () => { + for (let index = 0; index < LOGIN_MAX_ATTEMPTS; index += 1) { + const failed = await app.request('POST', '/admin/api/login', { password: 'wrong' }); + expect(failed.statusCode).toBe(401); + } + const limited = await app.request('POST', '/admin/api/login', { password: '123456' }); + expect(limited.statusCode).toBe(429); + expect(limited.headers['retry-after']).toBeDefined(); + const body = JSON.parse(limited.body) as { error: { code: string; retryAfter: number } }; + expect(body.error.code).toBe('too_many_attempts'); + expect(body.error.retryAfter).toBeGreaterThanOrEqual(1); + expect(Number(limited.headers['retry-after'])).toBe(body.error.retryAfter); + }); + + it('clears the per-IP counter after a successful login', async () => { + for (let index = 0; index < 3; index += 1) { + await app.request('POST', '/admin/api/login', { password: 'wrong' }); + } + expect(checkLoginRateLimit('127.0.0.1')).toBeNull(); + const ok = await app.request('POST', '/admin/api/login', { password: '123456' }); + expect(ok.statusCode).toBe(200); + expect(checkLoginRateLimit('127.0.0.1')).toBeNull(); + }); +}); + +/* --------------------------------------------------------------------- settings */ + +describe('PATCH /settings (AD-06, audit_retention_days, stream_idle_timeout_ms)', () => { + it('rejects the whole patch when one value is invalid', async () => { + const cookie = app.cookie(); + const response = await app.request('PATCH', '/admin/api/settings', { max_retries: '5', request_timeout_ms: 999 }, cookie); + expect(response.statusCode).toBe(400); + expect(app.repo.getSetting('max_retries')).toBe('3'); + expect(app.repo.getSetting('request_timeout_ms')).toBe('600000'); + }); + + it('applies every valid entry in one transaction and reports ignored keys', async () => { + const cookie = app.cookie(); + const body = await app.json<{ changed: string[]; ignored: string[]; settings: Record }>( + 'PATCH', + '/admin/api/settings', + { max_retries: '5', audit_retention_days: '30', stream_idle_timeout_ms: '60000', nope: '1' }, + cookie, + ); + expect(body.changed.sort()).toEqual(['audit_retention_days', 'max_retries', 'stream_idle_timeout_ms']); + expect(body.ignored).toEqual(['nope']); + expect(app.repo.getSetting('max_retries')).toBe('5'); + expect(app.repo.getSetting('audit_retention_days')).toBe('30'); + expect(app.repo.getSetting('stream_idle_timeout_ms')).toBe('60000'); + expect(body.settings.stream_idle_timeout_ms).toBe('60000'); + }); + + it('validates both new ranges', async () => { + const cookie = app.cookie(); + for (const payload of [ + { audit_retention_days: '0' }, + { audit_retention_days: '3651' }, + { stream_idle_timeout_ms: '999' }, + { stream_idle_timeout_ms: '3600001' }, + ]) { + const response = await app.request('PATCH', '/admin/api/settings', payload, cookie); + expect(response.statusCode, JSON.stringify(payload)).toBe(400); + } + const ok = await app.request('PATCH', '/admin/api/settings', { stream_idle_timeout_ms: '1000' }, cookie); + expect(ok.statusCode).toBe(200); + expect(app.repo.getSetting('stream_idle_timeout_ms')).toBe('1000'); + expect(app.repo.getSetting('audit_retention_days')).toBe('90'); + }); + + it('rejects control characters in upstream_user_agent', async () => { + const cookie = app.cookie(); + const response = await app.request('PATCH', '/admin/api/settings', { upstream_user_agent: 'ok\r\nX-Evil: 1' }, cookie); + expect(response.statusCode).toBe(400); + expect(app.repo.getSetting('upstream_user_agent')).toBe('opencode-router/1.0'); + }); +}); + +describe('audit attribution (FEAT-05)', () => { + it('records the session id as actor and the client IP in the detail', async () => { + const cookie = await app.login(); + const patched = await app.request('PATCH', '/admin/api/settings', { max_retries: '4' }, cookie); + expect(patched.statusCode).toBe(200); + const body = await app.json<{ items: Array<{ action: string; actor: string; detail: string | null }> }>( + 'GET', + '/admin/api/audit?limit=20', + undefined, + cookie, + ); + const entry = body.items.find((item) => item.action === 'settings.update'); + expect(entry, 'settings.update audit entry missing').toBeDefined(); + expect(entry!.actor).toMatch(/^session:/); + expect(entry!.detail).toContain('ip=127.0.0.1'); + expect(entry!.detail).toContain('changed=max_retries'); + const login = body.items.find((item) => item.action === 'auth.login'); + expect(login?.actor).toBe('dashboard'); + }); +}); + +/* -------------------------------------------------------------------- providers */ + +describe('providers', () => { + function seedProvider(id = 'p1', baseUrl = 'https://api.example.com/v1'): void { + app.repo.createProvider({ id, name: 'Primary', baseUrl, apiKey: 'stored-secret-key' }); + } + + it('resets a stale cooldown when baseUrl, apiKey or enabled changes (AD-07)', async () => { + seedProvider(); + const cookie = app.cookie(); + + app.repo.recordProviderFailure('p1', 429, 'rate limited', 60_000); + expect(app.repo.getProvider('p1')?.status).toBe('cooldown'); + const patched = await app.request('PATCH', '/admin/api/providers/p1', { apiKey: 'rotated-key' }, cookie); + expect(patched.statusCode).toBe(200); + expect(app.repo.getProvider('p1')?.status).toBe('unknown'); + expect(app.repo.getProvider('p1')?.cooldownUntil).toBeNull(); + + app.repo.recordProviderFailure('p1', 429, 'rate limited', 60_000); + const priority = await app.request('PATCH', '/admin/api/providers/p1', { priority: 5 }, cookie); + expect(priority.statusCode).toBe(200); + expect(app.repo.getProvider('p1')?.status).toBe('cooldown'); + expect(app.repo.getProvider('p1')?.cooldownUntil).toBeGreaterThan(Date.now()); + }); + + it('rejects control characters in name and id (GW-10)', async () => { + const cookie = app.cookie(); + for (const payload of [ + { name: 'bad\r\nname', baseUrl: 'https://api.example.com/v1', apiKey: 'k' }, + { name: 'ok', id: 'bad\nid', baseUrl: 'https://api.example.com/v1', apiKey: 'k' }, + ]) { + const response = await app.request('POST', '/admin/api/providers', payload, cookie); + expect(response.statusCode, JSON.stringify(payload)).toBe(400); + } + seedProvider(); + const patch = await app.request('PATCH', '/admin/api/providers/p1', { name: 'x\ry' }, cookie); + expect(patch.statusCode).toBe(400); + }); + + it('never returns the raw provider key (AD-08)', async () => { + seedProvider(); + const body = await app.json<{ providers: Array<{ apiKeyMasked: string }> }>('GET', '/admin/api/providers', undefined, app.cookie()); + expect(JSON.stringify(body)).not.toContain('stored-secret-key'); + expect(body.providers[0]?.apiKeyMasked).toBe('st...ey'); + }); + + it('deletes a provider together with its synced models (AD-02)', async () => { + seedProvider(); + app.repo.upsertModel({ id: 'sync-1', providerId: 'p1', source: 'sync' }); + app.repo.upsertModel({ id: 'sync-2', providerId: 'p1', source: 'sync' }); + app.repo.upsertModel({ id: 'manual' }); + const body = await app.json<{ ok: boolean; modelsRemoved: number }>('DELETE', '/admin/api/providers/p1', undefined, app.cookie()); + expect(body).toEqual({ ok: true, modelsRemoved: 2 }); + expect(app.repo.getProvider('p1')).toBeNull(); + expect(app.repo.listModels().map((model) => model.id)).toEqual(['manual']); + }); + + it('reuses a stored key only for the stored origin (AD-04)', async () => { + seedProvider(); + const cookie = app.cookie(); + + const sameOrigin = await app.json<{ ok: boolean; models: number }>( + 'POST', + '/admin/api/providers/test', + { id: 'p1', baseUrl: 'https://api.example.com/v2' }, + cookie, + ); + expect(sameOrigin.ok).toBe(true); + expect(upstream.calls[0]?.apiKey).toBe('stored-secret-key'); + + upstream.calls = []; + const crossOrigin = await app.request( + 'POST', + '/admin/api/providers/test', + { id: 'p1', baseUrl: 'https://evil.example.com/v1' }, + cookie, + ); + expect(crossOrigin.statusCode).toBe(400); + expect((JSON.parse(crossOrigin.body) as { error: { code: string } }).error.code).toBe('api_key_required'); + expect(upstream.calls).toHaveLength(0); + + const explicit = await app.request( + 'POST', + '/admin/api/providers/test', + { id: 'p1', baseUrl: 'https://evil.example.com/v1', apiKey: 'explicit' }, + cookie, + ); + expect(explicit.statusCode).toBe(200); + expect(upstream.calls[0]?.apiKey).toBe('explicit'); + }); + + it('rejects a stored provider whose URL points at a private host (AD-01/GW-12)', async () => { + app.repo.createProvider({ id: 'legacy', name: 'Legacy', baseUrl: 'http://127.0.0.1:9/v1', apiKey: 'k' }); + const cookie = app.cookie(); + const test = await app.request('POST', '/admin/api/providers/legacy/test', undefined, cookie); + expect(test.statusCode).toBe(400); + const res = await app.request('POST', '/admin/api/providers', { name: 'x', baseUrl: 'https://user:pass@api.example.com/v1', apiKey: 'k' }, cookie); + expect(res.statusCode).toBe(400); + }); +}); + +/* ----------------------------------------------------------------------- models */ + +describe('models', () => { + function seedModels(count: number): string[] { + const ids = Array.from({ length: count }, (_, index) => `m-${index}`); + for (const id of ids) app.repo.upsertModel({ id }); + return ids; + } + + it('applies a bulk action atomically with one statement (AD-05)', async () => { + seedModels(3); + const cookie = app.cookie(); + const disabled = await app.json<{ updated: number }>( + 'POST', + '/admin/api/models/bulk', + { action: 'disable', ids: ['m-0', 'm-1', 'missing'] }, + cookie, + ); + expect(disabled.updated).toBe(2); + expect(app.repo.enabledModelIds()).toEqual(['m-2']); + + const deleted = await app.json<{ updated: number }>( + 'POST', + '/admin/api/models/bulk', + { action: 'delete', ids: ['m-0', 'm-2'] }, + cookie, + ); + expect(deleted.updated).toBe(2); + expect(app.repo.listModels().map((model) => model.id)).toEqual(['m-1']); + }); + + it('rejects more than MAX ids without touching the database', async () => { + // The shared fixture uses a tiny bodyLimit; the cap test needs a realistic one. + const large = await buildAdminApp({ bodyLimit: 4 * 1024 * 1024 }); + try { + for (const id of ['m-0', 'm-1']) large.repo.upsertModel({ id }); + const ids = Array.from({ length: 1_001 }, (_, index) => `m-${index}`); + const response = await large.request('POST', '/admin/api/models/bulk', { action: 'delete', ids }, large.cookie()); + expect(response.statusCode).toBe(400); + expect((JSON.parse(response.body) as { error: { message: string } }).error.message).toContain('at most 1000'); + expect(large.repo.listModels()).toHaveLength(2); + } finally { + await large.close(); + } + }); +}); + +/* ------------------------------------------------------------------ sync guards */ + +describe('model sync (AD-03, FEAT-09)', () => { + it('refuses a private provider URL from both sync entry points', async () => { + app.repo.createProvider({ id: 'private', name: 'Private', baseUrl: 'http://10.0.0.5/v1', apiKey: 'k' }); + const cookie = app.cookie(); + const direct = await app.request('POST', '/admin/api/providers/private/sync-models', undefined, cookie); + expect(direct.statusCode).toBe(400); + expect((JSON.parse(direct.body) as { error: { code: string } }).error.code).toBe('invalid_request'); + const global = await app.request('POST', '/admin/api/models/sync', { providerId: 'private' }, cookie); + expect(global.statusCode).toBe(400); + expect(upstream.calls).toHaveLength(0); + }); + + it('returns a client-safe 502 message instead of upstream internals (FEAT-09)', async () => { + app.repo.createProvider({ id: 'p1', name: 'Primary', baseUrl: 'https://api.example.com/v1', apiKey: 'k' }); + const cookie = app.cookie(); + upstream.status = 500; + upstream.payload = 'boom: sqlite detail'; + const response = await app.request('POST', '/admin/api/models/sync', { providerId: 'p1' }, cookie); + expect(response.statusCode).toBe(502); + const body = JSON.parse(response.body) as { error: { code: string; message: string } }; + expect(body.error.code).toBe('sync_failed'); + expect(body.error.message).toBe('Upstream request failed while syncing models for provider "Primary"'); + expect(body.error.message).not.toContain('boom'); + expect(body.error.message).not.toContain('api.example.com'); + }); + + it('syncs upstream models and stores the sync timestamp', async () => { + app.repo.createProvider({ id: 'p1', name: 'Primary', baseUrl: 'https://api.example.com/v1', apiKey: 'k' }); + const body = await app.json<{ added: number; updated: number; removed: number; total: number }>( + 'POST', + '/admin/api/models/sync', + { providerId: 'p1' }, + app.cookie(), + ); + expect(body).toEqual({ added: 2, updated: 0, removed: 0, total: 2, providerId: 'p1', syncedAt: expect.any(Number), latencyMs: expect.any(Number) }); + expect(app.repo.listModels().map((model) => model.id).sort()).toEqual(['m1', 'm2']); + }); +}); + +/* ------------------------------------------------------------------------- SSE */ + +describe('SSE stream guards (AD-10)', () => { + it('bounds concurrent streams and releases the slot', () => { + resetEventStreams(); + for (let index = 0; index < MAX_EVENTS_STREAMS; index += 1) { + expect(acquireEventStream()).toBe(true); + } + expect(acquireEventStream()).toBe(false); + expect(activeEventStreamCount()).toBe(MAX_EVENTS_STREAMS); + releaseEventStream(); + expect(acquireEventStream()).toBe(true); + resetEventStreams(); + expect(activeEventStreamCount()).toBe(0); + }); + + it('survives a throwing socket write before cleanup is assigned (AD-10 TDZ guard)', async () => { + const handlers = new Map Promise>(); + const scope = { + get: (path: string, handler: (request: unknown, reply: unknown) => Promise) => handlers.set(path, handler), + } as unknown as FastifyInstance; + const noop = (): void => {}; + const ctx = { + repo: { listLogs: () => ({ total: 0, rows: [] }) }, + events: { onRequestStart: () => noop, onRequestEnd: () => noop, onProvider: () => noop }, + } as unknown as AppContext; + registerStatsRoutes(scope, ctx); + const handler = handlers.get('/events'); + expect(handler).toBeDefined(); + + let onClose: (() => void) | undefined; + const raw = { + writeHead: () => {}, + flushHeaders: () => {}, + write: () => { + throw new Error('socket gone'); + }, + once: () => {}, + off: () => {}, + end: () => {}, + }; + const request = { + adminSession: null, + raw: { + on: (event: string, listener: () => void) => { + if (event === 'close') onClose = listener; + }, + }, + }; + const reply = { hijack: () => {}, raw }; + + resetEventStreams(); + // Before the fix this rejected with `TypeError: cleanup is not a function`. + await expect(handler!(request, reply)).resolves.toBeUndefined(); + expect(activeEventStreamCount()).toBe(1); + onClose?.(); + expect(activeEventStreamCount()).toBe(0); + }); + + it('drops authorization when the session row disappears or expires', () => { + const now = Date.now(); + const session: SessionRow = { + id: 's1', + createdAt: now, + expiresAt: now + 60_000, + lastSeenAt: now, + clientIp: null, + userAgent: null, + }; + const live = { repo: { getSession: (id: string) => (id === 's1' ? session : null) } } as unknown as AppContext; + expect(eventStreamAuthorized(live, session)).toBe(true); + expect(eventStreamAuthorized(live, null)).toBe(false); + expect(eventStreamAuthorized(live, { ...session, expiresAt: now - 1 })).toBe(false); + + const revoked = { repo: { getSession: () => null } } as unknown as AppContext; + expect(eventStreamAuthorized(revoked, session)).toBe(false); + }); + + it('answers 503 past the cap and frees the slot on disconnect', async () => { + await app.app.listen({ host: '127.0.0.1', port: 0 }); + const address = app.app.server.address(); + const port = typeof address === 'object' && address ? address.port : 0; + const cookie = app.cookie(); + resetEventStreams(); + for (let index = 0; index < MAX_EVENTS_STREAMS - 1; index += 1) acquireEventStream(); + + const first = http.get({ host: '127.0.0.1', port, path: '/admin/api/events', headers: { cookie } }); + const [firstResponse] = (await once(first, 'response')) as [http.IncomingMessage]; + expect(firstResponse.statusCode).toBe(200); + firstResponse.resume(); + expect(activeEventStreamCount()).toBe(MAX_EVENTS_STREAMS); + + const second = await new Promise<{ status: number; body: string }>((resolve, reject) => { + const request = http.get({ host: '127.0.0.1', port, path: '/admin/api/events', headers: { cookie } }, (response) => { + let body = ''; + response.setEncoding('utf8'); + response.on('data', (chunk: string) => { + body += chunk; + }); + response.on('end', () => resolve({ status: response.statusCode ?? 0, body })); + }); + request.on('error', reject); + }); + expect(second.status).toBe(503); + expect((JSON.parse(second.body) as { error: { code: string } }).error.code).toBe('too_many_streams'); + + first.destroy(); + const deadline = Date.now() + 2_000; + while (activeEventStreamCount() > MAX_EVENTS_STREAMS - 1 && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 10)); + } + expect(activeEventStreamCount()).toBe(MAX_EVENTS_STREAMS - 1); + resetEventStreams(); + }); +}); + +/* ------------------------------------------------------------- server shell gate */ + +describe('server dashboard shell gate', () => { + let dataDir: string; + let ctx: AppContext; + let server: FastifyInstance; + + beforeEach(async () => { + dataDir = mkdtempSync(join(tmpdir(), 'okr-shell-')); + const webDist = join(dataDir, 'web'); + mkdirSync(join(webDist, 'assets'), { recursive: true }); + writeFileSync(join(webDist, 'index.html'), 'shell'); + writeFileSync(join(webDist, 'assets', 'app.js'), 'console.log("app")'); + const config = { ...testConfig(dataDir), webDistDir: webDist }; + const handle = openDatabase(config); + ctx = { + config, + db: handle, + repo: new Repo(handle.db), + events: new EventBus(), + logger: null as never, + startedAt: Date.now(), + }; + server = await buildServer(ctx); + }); + + afterEach(async () => { + await server.close(); + ctx.db.db.close(); + rmSync(dataDir, { recursive: true, force: true }); + }); + + it('never serves the shell without a session', async () => { + const direct = await server.inject({ method: 'GET', url: '/index.html' }); + expect(direct.statusCode).toBe(302); + expect(direct.headers.location).toBe('/login'); + + const dashboard = await server.inject({ method: 'GET', url: '/dashboard' }); + expect(dashboard.statusCode).toBe(302); + expect(dashboard.headers.location).toBe('/login'); + + const root = await server.inject({ method: 'GET', url: '/' }); + expect(root.statusCode).toBe(302); + expect(root.headers.location).toBe('/dashboard'); + + // The login shell and its assets stay reachable without a session. + const login = await server.inject({ method: 'GET', url: '/login' }); + expect(login.statusCode).toBe(200); + expect(login.body).toContain('id="shell"'); + expect(login.headers['content-type']).toContain('text/html'); + const asset = await server.inject({ method: 'GET', url: '/assets/app.js' }); + expect(asset.statusCode).toBe(200); + }); + + it('serves the shell for a valid session', async () => { + const session = ctx.repo.createSession({ id: randomUUID(), ttlMs: 60_000, clientIp: null, userAgent: null }); + const cookie = `${SESSION_COOKIE}=${buildSessionCookie(ctx.db.secret, session.id, session.expiresAt)}`; + const index = await server.inject({ method: 'GET', url: '/index.html', headers: { cookie } }); + expect(index.statusCode).toBe(200); + expect(index.body).toContain('id="shell"'); + const dashboard = await server.inject({ method: 'GET', url: '/dashboard/overview', headers: { cookie } }); + expect(dashboard.statusCode).toBe(200); + expect(dashboard.body).toContain('id="shell"'); + }); +}); diff --git a/tests/admin-session.test.ts b/tests/admin-session.test.ts index 8fe6dbc..1e530ea 100644 --- a/tests/admin-session.test.ts +++ b/tests/admin-session.test.ts @@ -3,9 +3,12 @@ import { describe, expect, it } from 'vitest'; import { SESSION_COOKIE, buildSessionCookie, + isSecureRequest, parseSessionCookie, resolveSession, + sessionCookieOptions, signSession, + trustProxyEnabled, } from '../src/admin/session.js'; import type { AppContext } from '../src/core/context.js'; import type { SessionRow } from '../src/types.js'; @@ -110,3 +113,52 @@ describe('resolveSession', () => { expect(resolveSession(ctx, requestWith())).toBeNull(); }); }); + +describe('isSecureRequest (AD-09) and trustProxy', () => { + function request(protocol: string, headers: Record = {}): FastifyRequest { + return { protocol, headers } as unknown as FastifyRequest; + } + + function ctxWith(patch: { trustProxy?: boolean | string | string[]; publicUrl?: string | null }): AppContext { + return { config: { ...testConfig('/tmp/okr-session-secure'), ...patch } } as unknown as AppContext; + } + + it('trusts the socket protocol unconditionally', () => { + expect(isSecureRequest(request('https'))).toBe(true); + expect(isSecureRequest(request('http'))).toBe(false); + }); + + it('ignores x-forwarded-proto unless TRUST_PROXY is enabled', () => { + const untrusted = ctxWith({ trustProxy: false }); + expect(isSecureRequest(request('http', { 'x-forwarded-proto': 'https' }), untrusted)).toBe(false); + expect(isSecureRequest(request('http', { 'x-forwarded-proto': 'https' }))).toBe(false); + + const trusted = ctxWith({ trustProxy: true }); + expect(isSecureRequest(request('http', { 'x-forwarded-proto': 'https' }), trusted)).toBe(true); + expect(isSecureRequest(request('http', { 'x-forwarded-proto': 'https, http' }), trusted)).toBe(true); + expect(isSecureRequest(request('http', { 'x-forwarded-proto': 'http' }), trusted)).toBe(false); + }); + + it('honours an https PUBLIC_URL as a TLS-terminating deployment', () => { + expect(isSecureRequest(request('http'), ctxWith({ publicUrl: 'https://router.example.com' }))).toBe(true); + expect(isSecureRequest(request('http'), ctxWith({ publicUrl: 'http://router.example.com' }))).toBe(false); + }); + + it('treats only a configured trustProxy value as enabled', () => { + expect(trustProxyEnabled(undefined)).toBe(false); + expect(trustProxyEnabled(ctxWith({ trustProxy: false }))).toBe(false); + expect(trustProxyEnabled(ctxWith({ trustProxy: true }))).toBe(true); + expect(trustProxyEnabled(ctxWith({ trustProxy: '1' }))).toBe(true); + expect(trustProxyEnabled(ctxWith({ trustProxy: '' }))).toBe(false); + expect(trustProxyEnabled(ctxWith({ trustProxy: [] }))).toBe(false); + expect(trustProxyEnabled(ctxWith({ trustProxy: ['10.0.0.1'] }))).toBe(true); + }); + + it('sets the Secure cookie attribute from the same check', () => { + const trusted = ctxWith({ trustProxy: true }); + expect(sessionCookieOptions(trusted, request('http', { 'x-forwarded-proto': 'https' })).secure).toBe(true); + const untrusted = ctxWith({ trustProxy: false }); + expect(sessionCookieOptions(untrusted, request('http', { 'x-forwarded-proto': 'https' })).secure).toBe(false); + expect(sessionCookieOptions(untrusted, request('https')).secure).toBe(true); + }); +}); diff --git a/tests/admin-util.test.ts b/tests/admin-util.test.ts index a52a1f7..0b1ab49 100644 --- a/tests/admin-util.test.ts +++ b/tests/admin-util.test.ts @@ -2,8 +2,10 @@ import { describe, expect, it } from 'vitest'; import { HttpError, asTimestamp, + assertNoControlChars, assertPublicProviderUrl, csvEscape, + httpBaseUrl, maskApiKey, queryInt, queryTimestamp, @@ -108,6 +110,13 @@ describe('assertPublicProviderUrl', () => { 'http://169.254.169.254/latest/meta-data', 'http://localhost:20125/v1', 'http://api.localhost/v1', + // AD-01: a trailing dot used to defeat every literal check. + 'http://localhost./v1', + 'http://api.localhost./v1', + 'http://127.0.0.1./v1', + 'http://10.0.0.5./v1', + 'http://192.168.1.1./v1', + 'http://169.254.169.254./latest/meta-data', 'http://[::ffff:127.0.0.1]/v1', 'http://[::ffff:7f00:1]/v1', 'http://[fc00::1]/v1', @@ -148,7 +157,46 @@ describe('maskApiKey', () => { expect(maskApiKey('')).toBe(''); expect(maskApiKey('short')).toBe('****'); expect(maskApiKey('12345678')).toBe('****'); - expect(maskApiKey('sk-abcdefghijkl')).toBe('sk-a...ijkl'); + expect(maskApiKey('sk-abcdefghijkl')).toBe('sk...kl'); expect(maskApiKey('sk-abcdefghijkl')).not.toContain('bcdefgh'); }); + + // AD-08: `sk-123456` (9 chars) used to reveal 8 of its 9 characters. + it('reveals at most 4 characters and fully masks anything below 12', () => { + expect(maskApiKey('sk-123456')).toBe('****'); + expect(maskApiKey('a'.repeat(11))).toBe('****'); + expect(maskApiKey('a'.repeat(12))).toBe('aa...aa'); + const masked = maskApiKey('sk-abcdefghijkl'); + expect(masked.replace(/[^a-z0-9]/gi, '')).toHaveLength(4); + expect(masked).toBe('sk...kl'); + }); +}); + +describe('httpBaseUrl', () => { + it('accepts http(s) URLs without credentials and strips trailing slashes', () => { + expect(httpBaseUrl('https://api.openai.com/v1/')).toBe('https://api.openai.com/v1'); + expect(httpBaseUrl('http://8.8.8.8:8080/v1')).toBe('http://8.8.8.8:8080/v1'); + }); + + it('rejects non-http schemes, junk and control characters', () => { + expect(() => httpBaseUrl('ftp://api.openai.com/v1')).toThrow(HttpError); + expect(() => httpBaseUrl('not a url')).toThrow(HttpError); + expect(() => httpBaseUrl('https://api.openai.com/v1\r\nX-Evil: 1')).toThrow(HttpError); + expect(() => httpBaseUrl(123)).toThrow(HttpError); + }); + + // GW-12: credentials in the URL would be echoed back in upstream error messages. + it('rejects userinfo in the URL', () => { + expect(() => httpBaseUrl('https://user:pass@api.openai.com/v1')).toThrow(HttpError); + expect(() => httpBaseUrl('https://user@api.openai.com/v1')).toThrow(HttpError); + }); +}); + +describe('assertNoControlChars', () => { + it('accepts printable values and rejects CR/LF and NUL', () => { + expect(() => assertNoControlChars('openrouter/1.0 (linux)', 'upstream_user_agent')).not.toThrow(); + for (const value of ['a\r', 'a\n', 'a\r\nb', 'a\u0000b', 'a\u007fb']) { + expect(() => assertNoControlChars(value, 'name'), JSON.stringify(value)).toThrow(HttpError); + } + }); }); \ No newline at end of file diff --git a/tests/db-repos.test.ts b/tests/db-repos.test.ts index d389fc2..1e02eae 100644 --- a/tests/db-repos.test.ts +++ b/tests/db-repos.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import type { AttemptRow, RequestLogRow } from '../src/types.js'; +import { Repo } from '../src/db/repos.js'; import { createTestDb, type TestDb } from './helpers.js'; let db: TestDb; @@ -149,3 +150,223 @@ describe('repo: api key rotation', () => { expect(db.repo.rotateApiKey('missing', replacement)).toBeNull(); }); }); + +describe('repo: prepared-statement cache (OPT-01)', () => { + it('prepares each distinct SQL string once', () => { + const db2 = createTestDb('okr-cache-'); + try { + const original = db2.handle.db.prepare.bind(db2.handle.db); + let prepares = 0; + (db2.handle.db as unknown as { prepare: (sql: string) => unknown }).prepare = (sql: string) => { + prepares += 1; + return original(sql); + }; + const repo = new Repo(db2.handle.db); + repo.insertLog(makeLog({ id: 'c1' })); + repo.insertLog(makeLog({ id: 'c2' })); + expect(prepares).toBe(1); + repo.insertLog(makeLog({ id: 'c3' })); + expect(prepares).toBe(1); + // A different statement still gets prepared (and cached) on first use. + repo.getLog('c1'); + expect(prepares).toBe(2); + repo.getLog('c2'); + expect(prepares).toBe(2); + } finally { + db2.cleanup(); + } + }); +}); + +describe('repo: transactions', () => { + it('rolls back every statement when the body throws', () => { + expect(() => + db.repo.transaction(() => { + db.repo.createProvider({ id: 'p1', name: 'P1', baseUrl: 'http://x/v1', apiKey: 'k' }); + db.repo.upsertModel({ id: 'm1' }); + throw new Error('boom'); + }), + ).toThrow('boom'); + expect(db.repo.listProviders()).toHaveLength(0); + expect(db.repo.listModels()).toHaveLength(0); + }); + + it('joins an outer transaction instead of opening a nested one', () => { + const result = db.repo.transaction(() => { + db.repo.upsertModel({ id: 'outer' }); + return db.repo.transaction(() => { + db.repo.upsertModel({ id: 'inner' }); + return 'done'; + }); + }); + expect(result).toBe('done'); + expect(db.repo.listModels().map((model) => model.id).sort()).toEqual(['inner', 'outer']); + }); +}); + +describe('repo: bulk model writes (AD-05)', () => { + it('updates and deletes in one set-based statement', () => { + db.repo.upsertModel({ id: 'a' }); + db.repo.upsertModel({ id: 'b' }); + db.repo.upsertModel({ id: 'c' }); + + expect(db.repo.setModelsEnabled(['a', 'b', 'missing'], false)).toBe(2); + expect(db.repo.enabledModelIds()).toEqual(['c']); + expect(db.repo.setModelsEnabled(['a', 'c'], true)).toBe(2); + expect(db.repo.enabledModelIds().sort()).toEqual(['a', 'c']); + + expect(db.repo.deleteModels(['a', 'nope'])).toBe(1); + expect(db.repo.setModelsEnabled([], false)).toBe(0); + expect(db.repo.deleteModels([])).toBe(0); + }); +}); + +describe('repo: provider delete cascade (AD-02)', () => { + it('removes the provider and its models together', () => { + db.repo.createProvider({ id: 'p1', name: 'P1', baseUrl: 'http://x/v1', apiKey: 'k' }); + db.repo.createProvider({ id: 'p2', name: 'P2', baseUrl: 'http://y/v1', apiKey: 'k' }); + db.repo.upsertModel({ id: 'owned-1', providerId: 'p1', source: 'sync' }); + db.repo.upsertModel({ id: 'owned-2', providerId: 'p1', source: 'sync' }); + db.repo.upsertModel({ id: 'other', providerId: 'p2', source: 'sync' }); + db.repo.upsertModel({ id: 'manual' }); + + expect(db.repo.deleteProviderWithModels('p1')).toEqual({ deleted: true, modelsRemoved: 2 }); + expect(db.repo.getProvider('p1')).toBeNull(); + expect(db.repo.listModels().map((model) => model.id).sort()).toEqual(['manual', 'other']); + expect(db.repo.deleteModelsByProvider('p1')).toBe(0); + }); +}); + +describe('repo: provider failure cooldown (GW-15)', () => { + const cooled = [null, 302, 408, 409, 425, 429, 500, 503, 529]; + const notCooled = [400, 401, 403, 404, 422]; + + it('cools down retryable failures, including network errors and redirects', () => { + for (const [index, status] of cooled.entries()) { + const id = `cool-${index}`; + db.repo.createProvider({ id, name: id, baseUrl: 'http://x/v1', apiKey: 'k' }); + db.repo.recordProviderFailure(id, status, 'nope', 60_000); + const row = db.repo.getProvider(id)!; + expect(row.cooldownUntil, `status=${status}`).toBeGreaterThan(Date.now()); + expect(row.failureCount).toBe(1); + } + }); + + it('leaves client errors without a cooldown', () => { + for (const [index, status] of notCooled.entries()) { + const id = `hard-${index}`; + db.repo.createProvider({ id, name: id, baseUrl: 'http://x/v1', apiKey: 'k' }); + db.repo.recordProviderFailure(id, status, 'nope', 60_000); + const row = db.repo.getProvider(id)!; + expect(row.cooldownUntil, `status=${status}`).toBeNull(); + expect(row.status).toBe('error'); + } + }); + + it('keeps the cooldown status only for rate-limit style failures', () => { + db.repo.createProvider({ id: 'rl', name: 'rl', baseUrl: 'http://x/v1', apiKey: 'k' }); + db.repo.recordProviderFailure('rl', 429, 'slow down', 60_000); + expect(db.repo.getProvider('rl')?.status).toBe('cooldown'); + + db.repo.createProvider({ id: 'net', name: 'net', baseUrl: 'http://x/v1', apiKey: 'k' }); + db.repo.recordProviderFailure('net', null, 'unreachable', 60_000); + expect(db.repo.getProvider('net')?.status).toBe('error'); + expect(db.repo.getProvider('net')?.cooldownUntil).toBeGreaterThan(Date.now()); + }); +}); + +describe('repo: upsert with a known row (OPT-10)', () => { + it('does not re-read the row and reports the same shape as before', () => { + const created = db.repo.upsertModel({ id: 'a/model', name: 'A', capabilities: undefined }); + expect(created.created).toBe(true); + expect(created.row.name).toBe('A'); + expect(created.row.enabled).toBe(true); + expect(db.repo.getModel('a/model')).toEqual(created.row); + + const known = db.repo.getModel('a/model'); + const updated = db.repo.upsertModel({ id: 'a/model', name: 'A v2', enabled: false }, known); + expect(updated.created).toBe(false); + expect(updated.row.name).toBe('A v2'); + expect(updated.row.enabled).toBe(false); + expect(db.repo.getModel('a/model')).toEqual(updated.row); + + // `known: null` claims "does not exist yet" and must not fall back to a read. + const missing = db.repo.upsertModel({ id: 'b/model', name: 'B' }, null); + expect(missing.created).toBe(true); + expect(db.repo.getModel('b/model')?.name).toBe('B'); + }); +}); + +describe('repo: stats percentiles (OPT-03)', () => { + const reference = (values: number[], p: number): number => { + if (values.length === 0) return 0; + const sorted = [...values].sort((a, b) => a - b); + return sorted[Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length))] ?? 0; + }; + + it('matches the nearest-rank definition and ignores null latencies', () => { + const empty = db.repo.statsOverview(3_600_000, 60_000, 0); + expect(empty.totals.p50LatencyMs).toBe(0); + expect(empty.totals.p95LatencyMs).toBe(0); + + const latencies: Array = [1, 7, 3, null, 99, 42, 5, 13, 8, 21]; + latencies.forEach((latency, index) => { + db.repo.insertLog(makeLog({ id: `p${index}`, latencyMs: latency, ts: Date.now() - 1_000 })); + }); + const present = latencies.filter((value): value is number => value !== null); + const stats = db.repo.statsOverview(3_600_000, 60_000, 0); + expect(stats.totals.p50LatencyMs).toBe(reference(present, 50)); + expect(stats.totals.p95LatencyMs).toBe(reference(present, 95)); + expect(stats.totals.p50LatencyMs).toBe(8); + expect(stats.totals.p95LatencyMs).toBe(99); + }); + + it('is stable for single-row and off-window data', () => { + db.repo.insertLog(makeLog({ id: 'only', latencyMs: 250, ts: Date.now() - 1_000 })); + db.repo.insertLog(makeLog({ id: 'old', latencyMs: 9_000, ts: Date.now() - 90 * 24 * 60 * 60 * 1000 })); + const stats = db.repo.statsOverview(3_600_000, 60_000, 0); + expect(stats.totals.p50LatencyMs).toBe(250); + expect(stats.totals.p95LatencyMs).toBe(250); + expect(stats.totals.requests).toBe(1); + }); +}); + +describe('repo: schema indexes (OPT-02)', () => { + it('creates an index for every hot predicate', () => { + const names = new Set( + (db.handle.db.prepare("SELECT name FROM sqlite_master WHERE type = 'index'").all() as Array<{ name: string }>).map( + (row) => row.name, + ), + ); + for (const index of [ + 'idx_sessions_expires', + 'idx_models_enabled', + 'idx_models_provider', + 'idx_api_keys_active', + 'idx_providers_enabled', + 'idx_request_logs_ts_ok', + ]) { + expect(names.has(index), index).toBe(true); + } + }); +}); + +describe('repo: hot-path existence helpers (OPT-04)', () => { + it('keeps hasEnabledModel/countActiveApiKeys consistent with the row lists', () => { + expect(db.repo.hasEnabledModel()).toBe(false); + expect(db.repo.countActiveApiKeys()).toBe(0); + db.repo.upsertModel({ id: 'm1' }); + const { row } = db.repo.createApiKey('laptop'); + expect(db.repo.hasEnabledModel()).toBe(true); + expect(db.repo.hasEnabledModel()).toBe(db.repo.enabledModelIds().length > 0); + expect(db.repo.countActiveApiKeys()).toBe(1); + expect(db.repo.hasActiveApiKey()).toBe(true); + + db.repo.updateApiKey(row.id, { revoked: true, enabled: false }); + expect(db.repo.countActiveApiKeys()).toBe(0); + expect(db.repo.hasActiveApiKey()).toBe(false); + + db.repo.updateModel('m1', { enabled: false }); + expect(db.repo.hasEnabledModel()).toBe(false); + }); +}); diff --git a/tests/gateway-auth.test.ts b/tests/gateway-auth.test.ts new file mode 100644 index 0000000..f387b02 --- /dev/null +++ b/tests/gateway-auth.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from 'vitest'; +import { extractApiKey } from '../src/gateway/auth.js'; +import { forwardHeaders } from '../src/gateway/forward-headers.js'; + +describe('extractApiKey (GW-13)', () => { + it('accepts Bearer tokens', () => { + expect(extractApiKey({ authorization: 'Bearer okr-abc' })).toBe('okr-abc'); + expect(extractApiKey({ authorization: 'bearer okr-abc ' })).toBe('okr-abc'); + expect(extractApiKey({ authorization: 'BEARER okr-abc' })).toBe('okr-abc'); + }); + + it('rejects every non-Bearer Authorization scheme', () => { + expect(extractApiKey({ authorization: 'Basic b2tyLWF respons' })).toBeNull(); + expect(extractApiKey({ authorization: 'Digest username="x"' })).toBeNull(); + expect(extractApiKey({ authorization: 'okr-abc' })).toBeNull(); + expect(extractApiKey({ authorization: 'Bearer' })).toBeNull(); + expect(extractApiKey({ authorization: 'Bearer ' })).toBeNull(); + }); + + it('still falls back to x-api-key', () => { + expect(extractApiKey({ 'x-api-key': ' okr-xyz ' })).toBe('okr-xyz'); + expect(extractApiKey({ 'x-api-key': ['okr-first', 'okr-second'] })).toBe('okr-first'); + // A non-Bearer Authorization must not hide a valid x-api-key. + expect(extractApiKey({ authorization: 'Basic b2ty', 'x-api-key': 'okr-xyz' })).toBe('okr-xyz'); + }); + + it('returns null when nothing is present', () => { + expect(extractApiKey({})).toBeNull(); + expect(extractApiKey({ authorization: ' ', 'x-api-key': '' })).toBeNull(); + }); +}); + +describe('forwardHeaders (GW-07)', () => { + it('forwards the Anthropic version and browser-access opt-in', () => { + const out = forwardHeaders({ + 'anthropic-version': '2025-01-01', + 'anthropic-dangerous-direct-browser-access': 'true', + 'anthropic-beta': 'prompt-caching-2024-07-31', + }); + expect(out['anthropic-version']).toBe('2025-01-01'); + expect(out['anthropic-dangerous-direct-browser-access']).toBe('true'); + expect(out['anthropic-beta']).toBe('prompt-caching-2024-07-31'); + }); + + it('never forwards credentials or hop-by-hop headers', () => { + const out = forwardHeaders({ + authorization: 'Bearer okr-secret', + 'x-api-key': 'okr-secret', + cookie: 'session=abc', + host: 'router.example', + 'content-length': '12', + connection: 'keep-alive', + accept: 'text/event-stream', + 'x-stainless-lang': 'js', + }); + expect(out.authorization).toBeUndefined(); + expect(out['x-api-key']).toBeUndefined(); + expect(out.cookie).toBeUndefined(); + expect(out.host).toBeUndefined(); + expect(out['content-length']).toBeUndefined(); + expect(out.connection).toBeUndefined(); + expect(out.accept).toBe('text/event-stream'); + expect(out['x-stainless-lang']).toBe('js'); + }); + + it('only defaults accept for non-streaming calls', () => { + expect(forwardHeaders({}, { acceptJson: true }).accept).toBe('application/json'); + // Streaming leaves `accept` to `upstreamFetch` (GW-06) so the SSE default applies. + expect(forwardHeaders({}, { acceptJson: false }).accept).toBeUndefined(); + expect(forwardHeaders({ accept: 'application/x-custom' }, { acceptJson: true }).accept).toBe( + 'application/x-custom', + ); + }); + + it('does not let a bare wildcard accept shadow the surface default (GW-06)', () => { + expect(forwardHeaders({ accept: '*/*' }, { acceptJson: false }).accept).toBeUndefined(); + expect(forwardHeaders({ accept: '*/*' }, { acceptJson: true }).accept).toBe('application/json'); + expect(forwardHeaders({ accept: 'text/event-stream' }, { acceptJson: true }).accept).toBe( + 'text/event-stream', + ); + }); +}); diff --git a/tests/gateway-normalize.test.ts b/tests/gateway-normalize.test.ts index 862e844..860e29a 100644 --- a/tests/gateway-normalize.test.ts +++ b/tests/gateway-normalize.test.ts @@ -147,3 +147,26 @@ describe('normalizeBody', () => { expect('stream_options' in body).toBe(false); }); }); + +describe('model id normalization (GW-11)', () => { + it('forwards the trimmed model id', () => { + const out = normalizeBody('chat', { model: ' opencode/flint ' }, null); + expect(out.body.model).toBe('opencode/flint'); + }); + + it('leaves an already trimmed id untouched', () => { + const body: Json = { model: 'opencode/flint', stream: false }; + const out = normalizeBody('chat', body, null); + expect(out.body.model).toBe('opencode/flint'); + expect(out.body).not.toBe(body); + }); + + it('does not mutate the caller body and keeps a non-string model alone', () => { + const body: Json = { model: ' x ' }; + normalizeBody('chat', body, null); + expect(body.model).toBe(' x '); + + const numeric: Json = { model: 7 }; + expect(normalizeBody('chat', numeric, null).body.model).toBe(7); + }); +}); diff --git a/tests/gateway-proxy-helpers.test.ts b/tests/gateway-proxy-helpers.test.ts index 7cd4a8e..73394f0 100644 --- a/tests/gateway-proxy-helpers.test.ts +++ b/tests/gateway-proxy-helpers.test.ts @@ -1,5 +1,16 @@ import { describe, expect, it } from 'vitest'; -import { retryAfterMs, rewriteSseFrame, stripTopLevelXOpencode, stripXOpencode } from '../src/gateway/proxy.js'; +import { + bodyReadFailureStatus, + forwardedResponseHeaders, + retryAfterMs, + retryAfterSeconds, + rewriteSseFrame, + sanitizeHeaderValue, + smallestCooldownUntil, + stripTopLevelXOpencode, + stripXOpencode, +} from '../src/gateway/proxy.js'; +import { provider } from './helpers.js'; describe('stripXOpencode', () => { it('removes a top-level x_opencode key into a new object', () => { @@ -97,3 +108,92 @@ describe('retryAfterMs', () => { expect(retryAfterMs('soon')).toBeNull(); }); }); + +describe('bodyReadFailureStatus (GW-03)', () => { + it('maps a failed body read on a 2xx upstream answer to 502', () => { + expect(bodyReadFailureStatus(200, false)).toBe(502); + expect(bodyReadFailureStatus(204, false)).toBe(502); + expect(bodyReadFailureStatus(301, false)).toBe(502); + }); + + it('keeps an upstream error status', () => { + expect(bodyReadFailureStatus(400, false)).toBe(400); + expect(bodyReadFailureStatus(502, false)).toBe(502); + }); + + it('keeps 504 for a timeout', () => { + expect(bodyReadFailureStatus(200, true)).toBe(504); + expect(bodyReadFailureStatus(500, true)).toBe(504); + }); +}); + +describe('sanitizeHeaderValue (GW-10)', () => { + it('strips control characters and CRLF injection', () => { + expect(sanitizeHeaderValue('provider\r\nx-injected: 1')).toBe('providerx-injected: 1'); + expect(sanitizeHeaderValue('a\u0000b\u0007c')).toBe('abc'); + expect(sanitizeHeaderValue('plain name-1')).toBe('plain name-1'); + }); + + it('drops characters Node rejects outside Latin-1', () => { + expect(sanitizeHeaderValue('日本語 provider')).toBe(' provider'); + }); +}); + +describe('forwardedResponseHeaders (GW-09)', () => { + it('forwards backoff / rate-limit / request-id headers', () => { + const upstream = new Headers({ + 'retry-after': '2', + 'x-ratelimit-remaining': '0', + 'anthropic-ratelimit-tokens-remaining': '7', + 'x-request-id': 'req_1', + 'openai-processing-ms': '12', + 'content-type': 'application/json', + 'content-encoding': 'gzip', + 'set-cookie': 'a=b', + }); + const out = forwardedResponseHeaders(upstream, { 'content-type': 'application/json' }); + expect(out['retry-after']).toBe('2'); + expect(out['x-ratelimit-remaining']).toBe('0'); + expect(out['anthropic-ratelimit-tokens-remaining']).toBe('7'); + expect(out['x-request-id']).toBe('req_1'); + expect(out['openai-processing-ms']).toBe('12'); + expect(out['content-encoding']).toBeUndefined(); + expect(out['set-cookie']).toBeUndefined(); + }); + + it('lets router overrides win', () => { + const upstream = new Headers({ 'x-request-id': 'upstream', 'content-type': 'text/plain' }); + const out = forwardedResponseHeaders(upstream, { + 'x-request-id': 'router', + 'content-type': 'application/json', + 'content-length': '5', + }); + expect(out['x-request-id']).toBe('router'); + expect(out['content-type']).toBe('application/json'); + expect(out['content-length']).toBe('5'); + }); +}); + +describe('FEAT-06 cooldown helpers', () => { + it('finds the smallest active cooldown among enabled providers', () => { + const now = 1_000_000; + const providers = [ + provider('a', { cooldownUntil: now + 5_000 }), + provider('b', { cooldownUntil: now + 2_000 }), + provider('c', { cooldownUntil: now - 1_000 }), + provider('d', { cooldownUntil: null }), + provider('e', { cooldownUntil: now + 1_000, enabled: false }), + ]; + expect(smallestCooldownUntil(providers, now)).toBe(now + 2_000); + expect(smallestCooldownUntil(providers.slice(2), now)).toBeNull(); + expect(smallestCooldownUntil([], now)).toBeNull(); + }); + + it('converts a cooldown deadline to whole Retry-After seconds', () => { + const now = 1_000_000; + expect(retryAfterSeconds(now + 2_400, now)).toBe(3); + expect(retryAfterSeconds(now + 1, now)).toBe(1); + expect(retryAfterSeconds(now - 500, now)).toBe(1); + expect(retryAfterSeconds(null, now)).toBe(1); + }); +}); diff --git a/tests/gateway-stream.test.ts b/tests/gateway-stream.test.ts new file mode 100644 index 0000000..45e85cd --- /dev/null +++ b/tests/gateway-stream.test.ts @@ -0,0 +1,476 @@ +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import Fastify, { type FastifyInstance } from 'fastify'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import type { AppContext } from '../src/core/context.js'; +import { EventBus } from '../src/core/events.js'; +import { registerGatewayRoutes } from '../src/gateway/index.js'; +import { SSE_MAX_FRAME_BYTES } from '../src/gateway/proxy.js'; +import type { AppConfig } from '../src/config.js'; +import { createTestDb, testConfig, type TestDb } from './helpers.js'; + +interface MockRequest { + url: string; + headers: IncomingMessage['headers']; + body: Buffer; +} + +interface MockUpstream { + baseUrl: string; + requests: MockRequest[]; + close(): Promise; +} + +const upstreams: MockUpstream[] = []; + +type MockHandler = (req: IncomingMessage, res: ServerResponse, body: Buffer) => void; + +/** Loopback mock provider on an ephemeral port (never a fixed port). */ +async function startUpstream(handler: MockHandler): Promise { + const requests: MockRequest[] = []; + const server: Server = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on('data', (chunk: Buffer) => chunks.push(chunk)); + req.on('end', () => { + const body = Buffer.concat(chunks); + requests.push({ url: req.url ?? '', headers: req.headers, body }); + handler(req, res, body); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as AddressInfo; + const upstream: MockUpstream = { + baseUrl: `http://127.0.0.1:${port}/v1`, + requests, + close: () => + new Promise((resolve) => { + server.closeAllConnections?.(); + server.close(() => resolve()); + }), + }; + upstreams.push(upstream); + return upstream; +} + +export function jsonResponse(res: ServerResponse, status: number, payload: unknown, headers: Record = {}): void { + const body = Buffer.from(JSON.stringify(payload)); + res.writeHead(status, { 'content-type': 'application/json', 'content-length': String(body.length), ...headers }); + res.end(body); +} + +async function waitFor(fn: () => T | null | undefined | false, label: string, timeoutMs = 5_000): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + const value = fn(); + if (value) return value as T; + if (Date.now() > deadline) throw new Error(`timed out waiting for ${label}`); + await new Promise((resolve) => setTimeout(resolve, 20)); + } +} + +function logsFor(db: TestDb, requestId: string) { + return db.repo.listLogs({ limit: 50 }).rows.filter((row) => row.id === requestId); +} + +let db: TestDb; +let app: FastifyInstance; +let ctx: AppContext; +let origin: string; +let apiKey: string; + +function config(): AppConfig { + return testConfig(db.dataDir); +} + +async function buildApp(events = new EventBus()): Promise { + app = Fastify({ logger: false }); + ctx = { + config: config(), + db: db.handle, + repo: db.repo, + events, + logger: app.log, + startedAt: Date.now(), + }; + await registerGatewayRoutes(app, ctx); + await app.listen({ port: 0, host: '127.0.0.1' }); + const { port } = app.server.address() as AddressInfo; + origin = `http://127.0.0.1:${port}`; +} + +function addProvider(id: string, baseUrl: string, priority: number): void { + db.repo.createProvider({ id, name: id, baseUrl, apiKey: 'sk-provider', priority }); +} + +function gatewayFetch(path: string, init: RequestInit = {}): Promise { + const headers = new Headers(init.headers); + if (!headers.has('authorization')) headers.set('authorization', `Bearer ${apiKey}`); + if (init.body !== undefined && !headers.has('content-type')) headers.set('content-type', 'application/json'); + return fetch(`${origin}${path}`, { ...init, headers }); +} + +const chatBody = (model = 'test/model'): string => + JSON.stringify({ model, messages: [{ role: 'user', content: 'ping' }] }); + +const CHAT = '/v1/chat/completions'; + +beforeEach(async () => { + db = createTestDb('okr-gateway-'); + db.repo.upsertModel({ id: 'test/model', name: 'Test Model' }); + apiKey = db.repo.createApiKey('tests').plaintext; + db.repo.setSetting('rotation_strategy', 'priority'); + await buildApp(); +}); + +afterEach(async () => { + await app.close(); + db.cleanup(); + for (const upstream of upstreams.splice(0)) await upstream.close(); +}); + +/* --------------------------------------------------------------- GW-04 auth */ + +describe('unknown /v1/* paths (GW-04)', () => { + it('requires a gateway API key and logs the rejection', async () => { + const response = await fetch(`${origin}/v1/nope`, { method: 'POST' }); + expect(response.status).toBe(401); + const body = (await response.json()) as { error?: { code?: string } }; + expect(body.error?.code).toBe('missing_api_key'); + expect(db.repo.listLogs({}).total).toBe(1); + }); + + it('answers an authenticated unknown path with the surface-shaped 404 and exactly one row', async () => { + const response = await gatewayFetch('/v1/nope', { method: 'POST', body: chatBody() }); + expect(response.status).toBe(404); + expect(response.headers.get('x-opencode-router-request-id')).toBeTruthy(); + const body = (await response.json()) as { error?: { code?: string } }; + expect(body.error?.code).toBe('unknown_endpoint'); + + const logs = db.repo.listLogs({}); + expect(logs.total).toBe(1); + expect(logs.rows[0]!.errorCode).toBe('unknown_endpoint'); + expect(logs.rows[0]!.status).toBe(404); + expect(logs.rows[0]!.keyId).not.toBeNull(); + }); + + it('shapes the anthropic 404 for unknown /v1/messages paths', async () => { + const response = await gatewayFetch('/v1/messages/nope', { method: 'POST', body: chatBody() }); + expect(response.status).toBe(404); + const body = (await response.json()) as { type?: string }; + expect(body.type).toBe('error'); + expect(db.repo.listLogs({}).total).toBe(1); + }); + + it('rejects a non-Bearer Authorization scheme (GW-13)', async () => { + const response = await fetch(`${origin}/v1/nope`, { + method: 'POST', + headers: { authorization: 'Basic b2tyLXNlY3JldA==' }, + }); + expect(response.status).toBe(401); + const body = (await response.json()) as { error?: { code?: string } }; + expect(body.error?.code).toBe('missing_api_key'); + + // x-api-key keeps working. + const ok = await fetch(`${origin}/v1/nope`, { method: 'POST', headers: { 'x-api-key': apiKey } }); + expect(ok.status).toBe(404); + }); + + it('keeps the real routes ahead of the catch-all', async () => { + const response = await gatewayFetch('/v1/models'); + expect(response.status).toBe(200); + const body = (await response.json()) as { object?: string; data?: unknown[] }; + expect(body.object).toBe('list'); + expect(Array.isArray(body.data)).toBe(true); + expect(db.repo.listLogs({}).total).toBe(1); + }); +}); + +/* ------------------------------------------------------- GW-01 / GW-02 failover */ + +describe('timeout failover (GW-01/GW-02)', () => { + it('fails over to a healthy provider, logs the attempt and cools the slow one down', async () => { + const slow = await startUpstream(() => { + /* never responds */ + }); + const fast = await startUpstream((_req, res) => jsonResponse(res, 200, { provider: 'fast' })); + addProvider('slow', slow.baseUrl, 1); + addProvider('fast', fast.baseUrl, 2); + db.repo.setSetting('request_timeout_ms', '1000'); + db.repo.setSetting('provider_cooldown_ms', '60000'); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(200); + expect(response.headers.get('x-opencode-router-provider')).toBe('fast'); + expect(response.headers.get('x-opencode-router-attempts')).toBe('2'); + expect(await response.json()).toEqual({ provider: 'fast' }); + + const requestId = response.headers.get('x-opencode-router-request-id')!; + const attempts = db.repo.listAttempts(requestId); + expect(attempts).toHaveLength(2); + expect(attempts[0]).toMatchObject({ providerId: 'slow', ok: false, status: null, errorCode: 'upstream_timeout' }); + expect(attempts[1]).toMatchObject({ providerId: 'fast', ok: true, status: 200 }); + + const slowRow = db.repo.getProvider('slow')!; + expect(slowRow.cooldownUntil).not.toBeNull(); + expect(slowRow.cooldownUntil!).toBeGreaterThan(Date.now()); + expect(slowRow.failureCount).toBe(1); + + const logs = logsFor(db, requestId); + expect(logs).toHaveLength(1); + expect(logs[0]).toMatchObject({ providerId: 'fast', ok: true, status: 200, attempts: 2 }); + }); + + it('aggregates a 504 with provider attribution when every provider times out', async () => { + const slow = await startUpstream(() => { + /* never responds */ + }); + addProvider('slow', slow.baseUrl, 1); + db.repo.setSetting('request_timeout_ms', '1000'); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(504); + expect(response.headers.get('x-opencode-router-provider')).toBe('slow'); + const body = (await response.json()) as { error?: { code?: string } }; + expect(body.error?.code).toBe('upstream_timeout'); + + const requestId = response.headers.get('x-opencode-router-request-id')!; + const logs = logsFor(db, requestId); + expect(logs).toHaveLength(1); + expect(logs[0]).toMatchObject({ providerId: 'slow', ok: false, status: 504, errorCode: 'upstream_timeout' }); + }); +}); + +/* ------------------------------------------------------------------- GW-03 */ + +describe('2xx body-read failure (GW-03)', () => { + it('answers 502 instead of echoing the upstream 200', async () => { + const broken = await startUpstream((_req, res) => { + res.writeHead(200, { 'content-type': 'application/json', 'content-length': '200' }); + res.write('{"partial":'); + // Destroy only after the headers/partial body reached the gateway, so this + // exercises the body-read path and not a connection-level failure. + setTimeout(() => res.socket?.destroy(), 50); + }); + addProvider('broken', broken.baseUrl, 1); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(502); + const body = (await response.json()) as { error?: { code?: string } }; + expect(body.error?.code).toBe('upstream_body_failed'); + + const requestId = response.headers.get('x-opencode-router-request-id')!; + expect(logsFor(db, requestId)[0]).toMatchObject({ status: 502, errorCode: 'upstream_body_failed' }); + }); +}); + +/* ----------------------------------------------------------- GW-05 SSE limits */ + +describe('SSE frame cap and idle timeout (GW-05)', () => { + it('aborts and logs upstream_frame_too_large when a partial frame grows past the cap', async () => { + const noisy = await startUpstream((_req, res) => { + res.writeHead(200, { 'content-type': 'text/event-stream' }); + res.write('data: {"a":1}\n\n'); + res.write('x'.repeat(SSE_MAX_FRAME_BYTES + 4_096)); + // never terminates the frame + }); + addProvider('noisy', noisy.baseUrl, 1); + + const response = await gatewayFetch(CHAT, { + method: 'POST', + body: JSON.stringify({ model: 'test/model', stream: true, messages: [{ role: 'user', content: 'x' }] }), + }); + expect(response.status).toBe(200); + const requestId = response.headers.get('x-opencode-router-request-id')!; + await response.text(); + + const row = await waitFor(() => logsFor(db, requestId)[0], 'the frame-cap log row'); + expect(row.errorCode).toBe('upstream_frame_too_large'); + expect(row.ok).toBe(false); + expect(row.status).toBe(502); + }); + + it('honours stream_idle_timeout_ms instead of the total request deadline', async () => { + const stalled = await startUpstream((_req, res) => { + res.writeHead(200, { 'content-type': 'text/event-stream' }); + res.write('data: {"a":1}\n\n'); + // never sends anything else and never ends + }); + addProvider('stalled', stalled.baseUrl, 1); + db.repo.setSetting('stream_idle_timeout_ms', '1000'); + db.repo.setSetting('request_timeout_ms', '600000'); + + const started = Date.now(); + const response = await gatewayFetch(CHAT, { + method: 'POST', + body: JSON.stringify({ model: 'test/model', stream: true, messages: [{ role: 'user', content: 'x' }] }), + }); + const requestId = response.headers.get('x-opencode-router-request-id')!; + await response.text(); + expect(Date.now() - started).toBeLessThan(5_000); + + const row = await waitFor(() => logsFor(db, requestId)[0], 'the idle-timeout log row'); + expect(row.errorCode).toBe('upstream_timeout'); + expect(row.status).toBe(504); + expect(row.ok).toBe(false); + }); +}); + +/* --------------------------------------- GW-06/07/09/11 headers and model id */ + +describe('headers, model id and response headers (GW-06/GW-07/GW-09/GW-11)', () => { + it('forwards accept, anthropic-version and the trimmed model, and relays upstream headers', async () => { + const upstream = await startUpstream((_req, res) => + jsonResponse(res, 200, { ok: true }, { 'x-ratelimit-remaining': '5', 'retry-after': '3' }), + ); + addProvider('up', upstream.baseUrl, 1); + + const response = await gatewayFetch(CHAT, { + method: 'POST', + body: JSON.stringify({ model: ' test/model ', messages: [{ role: 'user', content: 'hi' }] }), + }); + expect(response.status).toBe(200); + expect(response.headers.get('x-ratelimit-remaining')).toBe('5'); + expect(response.headers.get('retry-after')).toBe('3'); + expect(response.headers.get('x-opencode-router-provider')).toBe('up'); + + const sent = upstream.requests.at(-1)!; + expect(sent.headers.accept).toBe('application/json'); + expect(sent.headers['anthropic-version']).toBeUndefined(); + expect(JSON.parse(sent.body.toString('utf8'))).toEqual({ + model: 'test/model', + messages: [{ role: 'user', content: 'hi' }], + }); + }); + + it('defaults and forwards anthropic-version on the messages surface only', async () => { + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, { ok: true })); + addProvider('up', upstream.baseUrl, 1); + + await gatewayFetch('/v1/messages', { + method: 'POST', + body: JSON.stringify({ model: 'test/model', max_tokens: 16, messages: [{ role: 'user', content: 'hi' }] }), + }); + expect(upstream.requests.at(-1)!.headers['anthropic-version']).toBe('2023-06-01'); + + await gatewayFetch('/v1/messages', { + method: 'POST', + headers: { 'anthropic-version': '2025-01-01' }, + body: JSON.stringify({ model: 'test/model', max_tokens: 16, messages: [{ role: 'user', content: 'hi' }] }), + }); + expect(upstream.requests.at(-1)!.headers['anthropic-version']).toBe('2025-01-01'); + }); + + it('defaults accept to text/event-stream for a streaming call with no accept', async () => { + const upstream = await startUpstream((_req, res) => { + res.writeHead(200, { 'content-type': 'text/event-stream' }); + res.write('data: {"a":1}\n\n'); + res.end(); + }); + addProvider('up', upstream.baseUrl, 1); + + const response = await gatewayFetch(CHAT, { + method: 'POST', + body: JSON.stringify({ model: 'test/model', stream: true, messages: [{ role: 'user', content: 'hi' }] }), + }); + await response.text(); + expect(upstream.requests.at(-1)!.headers.accept).toBe('text/event-stream'); + }); +}); + +/* ------------------------------------------------------------------- GW-08 */ + +describe('byte-faithful request bodies (GW-08)', () => { + it('forwards the client bytes untouched, including invalid UTF-8', async () => { + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, { ok: true })); + addProvider('up', upstream.baseUrl, 1); + + const raw = Buffer.concat([ + Buffer.from('{\n "model": "test/model", "big": 9007199254740993, "messages": [{"role":"user","content":"'), + Buffer.from([0xff, 0xfe]), + Buffer.from('"}]}'), + ]); + await gatewayFetch(CHAT, { method: 'POST', body: raw }); + + const sent = upstream.requests.at(-1)!; + expect(sent.body.equals(raw)).toBe(true); + }); +}); + +/* ------------------------------------------------------------------ FEAT-06 */ + +describe('client-facing backoff signal (FEAT-06)', () => { + it('adds Retry-After and the cooldown deadline header to all_providers_rate_limited', async () => { + const first = await startUpstream((_req, res) => + jsonResponse(res, 429, { error: { message: 'rate limited' } }, { 'retry-after': '2' }), + ); + const second = await startUpstream((_req, res) => jsonResponse(res, 429, { error: { message: 'rate limited' } })); + addProvider('first', first.baseUrl, 1); + addProvider('second', second.baseUrl, 2); + db.repo.setSetting('provider_cooldown_ms', '4000'); + + const before = Date.now(); + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(429); + const body = (await response.json()) as { error?: { code?: string } }; + expect(body.error?.code).toBe('all_providers_rate_limited'); + + const retryAfter = Number(response.headers.get('retry-after')); + expect(Number.isInteger(retryAfter)).toBe(true); + expect(retryAfter).toBeGreaterThanOrEqual(1); + expect(retryAfter).toBeLessThanOrEqual(5); + + const until = Number(response.headers.get('x-opencode-router-cooldown-until')); + expect(Number.isFinite(until)).toBe(true); + expect(until).toBeGreaterThan(before); + expect(until).toBeLessThanOrEqual(Date.now() + 5_000); + }); +}); + +/* ------------------------------------------------------------------- GW-10 */ + +describe('router header sanitization (GW-10)', () => { + it('does not 500 when a provider name contains control characters', async () => { + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, { ok: true })); + // Bypasses the admin validation on purpose: the proxy must defend itself too. + db.repo.createProvider({ + id: 'evil', + name: 'bad\r\nx-injected: 1', + baseUrl: upstream.baseUrl, + apiKey: 'sk-provider', + priority: 1, + }); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(200); + expect(response.headers.get('x-opencode-router-name')).toBe('badx-injected: 1'); + expect(response.headers.get('x-injected')).toBeNull(); + }); +}); + +/* ------------------------------------------------------------------- GW-14 */ + +describe('guarded event emission (GW-14)', () => { + it('keeps serving when dashboard listeners throw', async () => { + const events = new EventBus(); + events.on('request:start', () => { + throw new Error('start listener boom'); + }); + events.on('request:end', () => { + throw new Error('end listener boom'); + }); + events.on('provider:update', () => { + throw new Error('provider listener boom'); + }); + await app.close(); + await buildApp(events); + apiKey = db.repo.createApiKey('second').plaintext; + + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, { ok: true })); + addProvider('up', upstream.baseUrl, 1); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true }); + expect(db.repo.listLogs({}).total).toBe(1); + }); +}); diff --git a/tests/tooling.test.ts b/tests/tooling.test.ts new file mode 100644 index 0000000..256ea40 --- /dev/null +++ b/tests/tooling.test.ts @@ -0,0 +1,111 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + MAX_SUBJECT_LENGTH, + commitRange, + emptyRangeFails, + validateSubject, +} from '../scripts/check-commit-messages.mjs'; +import { normalizePath } from '../scripts/check-docs.js'; +import { ensureChrome } from '../scripts/screenshots.js'; + +describe('commit-message validator', () => { + const accepted: Array<[subject: string, body?: string, why?: string]> = [ + ['feat: add provider rotation', undefined, 'plain feat'], + ['fix(gateway): fail over on timeout', undefined, 'scoped fix'], + ['chore(repo): drop duplicated config'], + ['docs(spec.md): document env vars', undefined, 'scope may contain dots'], + ['feat(ci): cache pnpm store'], + ['feat: änderung der routen', undefined, 'Unicode lowercase letter is accepted'], + ['feat!: remove legacy endpoint', 'BREAKING CHANGE: the legacy endpoint is gone'], + ['fixup! feat: add provider rotation', undefined, 'fixup chain'], + ['squash! feat: add provider rotation', undefined, 'squash chain'], + ['amend! feat: add provider rotation', undefined, 'amend chain'], + ['Revert "feat: add provider rotation"', undefined, 'git revert output'], + ['Initial commit'], + ]; + + it.each(accepted)('accepts %j', (subject, body) => { + expect(validateSubject(subject, body)).toEqual([]); + }); + + const rejected: Array<[subject: string, body: string | undefined, expected: string]> = [ + ['feat: Add provider rotation', undefined, 'description should start with a lowercase letter'], + ['feat: Änderung der routen', undefined, 'description should start with a lowercase letter'], + ['feat: 修正 bug', undefined, 'description should start with a lowercase letter'], + ['feat: ✨ add sparkle', undefined, 'description should start with a lowercase letter'], + ['feat: add provider rotation.', undefined, 'description should not end with a period'], + ['feature: add provider rotation', undefined, 'does not match'], + ['feat(Gateway): add provider rotation', undefined, 'does not match'], + ['feat: ', undefined, 'does not match'], + ['Merge branch \'main\' into feat/rotation', undefined, 'does not match'], + ['feat!: remove legacy endpoint', 'no footer here', 'breaking change "!" requires a "BREAKING CHANGE:" footer'], + [ + `feat: ${'a'.repeat(MAX_SUBJECT_LENGTH)}`, + undefined, + `subject is ${MAX_SUBJECT_LENGTH + 6} chars (max ${MAX_SUBJECT_LENGTH})`, + ], + ]; + + it.each(rejected)('rejects %j', (subject, body, expected) => { + const problems = validateSubject(subject, body); + expect(problems.join('\n')).toContain(expected); + }); + + it('does not require a footer when only a PR title is validated (no body available)', () => { + expect(validateSubject('feat!: remove legacy endpoint')).toEqual([]); + }); + + it('treats an empty subject as invalid', () => { + expect(validateSubject('')).toEqual(['empty subject']); + }); +}); + +describe('commit-message range handling', () => { + it('builds the explicit base..head range', () => { + expect(commitRange('origin/main', 'HEAD')).toBe('origin/main..HEAD'); + }); + + it('falls back to origin/main..HEAD when no range was supplied', () => { + expect(commitRange(undefined, undefined)).toBe('origin/main..HEAD'); + expect(commitRange('origin/main', undefined)).toBe('origin/main..HEAD'); + }); + + it('refuses to pass an explicitly supplied but empty range', () => { + expect(emptyRangeFails('origin/main', 'HEAD')).toBe(true); + expect(emptyRangeFails(undefined, undefined)).toBe(false); + expect(emptyRangeFails('origin/main', '')).toBe(false); + }); +}); + +describe('doc checker path normalization', () => { + it('normalizes params and wildcards so code and docs compare equal', () => { + expect(normalizePath('/v1/models/:id')).toBe('/v1/models/:p'); + expect(normalizePath('/v1/models/*')).toBe('/v1/models/:p'); + expect(normalizePath('/v1/models*')).toBe('/v1/models/:p'); + expect(normalizePath('/admin/api/providers/:id/test')).toBe('/admin/api/providers/:p/test'); + expect(normalizePath('/admin/api/logs?limit=10')).toBe('/admin/api/logs'); + expect(normalizePath('/')).toBe('/'); + expect(normalizePath('/dashboard/')).toBe('/dashboard'); + }); +}); + +describe('screenshots harness Chrome guard', () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it('skips a missing Chrome without --strict (exit 0 stays possible)', async () => { + vi.stubEnv('CHROME_PATH', ''); + await expect(ensureChrome('/nonexistent/chrome-binary', false)).resolves.toBe('skip'); + }); + + it('fails a missing Chrome with --strict', async () => { + vi.stubEnv('CHROME_PATH', ''); + await expect(ensureChrome('/nonexistent/chrome-binary', true)).rejects.toThrow(/--strict/); + }); + + it('accepts an existing binary', async () => { + vi.stubEnv('CHROME_PATH', ''); + await expect(ensureChrome(process.execPath, false)).resolves.toBe('ok'); + }); +}); \ No newline at end of file diff --git a/tests/unit.test.ts b/tests/unit.test.ts index 38ea6f6..0350890 100644 --- a/tests/unit.test.ts +++ b/tests/unit.test.ts @@ -1,7 +1,11 @@ +import { EventEmitter } from 'node:events'; import { existsSync, mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { pruneLogs } from '../src/core/seed.js'; +import { registerGracefulShutdown, type ShutdownHost } from '../src/core/shutdown.js'; +import type { AppContext } from '../src/core/context.js'; import { openDatabase, type DbHandle } from '../src/db/index.js'; import { Repo } from '../src/db/repos.js'; import { generateApiKey, hashApiKey, hashPassword, hmacSign, verifyPassword } from '../src/util/crypto.js'; @@ -334,3 +338,143 @@ describe('errors', () => { expect(error.toJSON('messages')).toMatchObject({ type: 'error', error: { type: 'invalid_request_error', message: 'bad' } }); }); }); + +describe('pruneLogs retention (FEAT-05)', () => { + const DAY = 24 * 60 * 60 * 1000; + + function auditRow(id: string, ts: number): void { + handle.db.prepare('INSERT INTO audit_logs (id, ts, actor, action, target, detail) VALUES (?, ?, ?, ?, ?, ?)').run( + id, + ts, + 'dashboard', + 'test.action', + null, + null, + ); + } + + function ctx(): AppContext { + return { repo } as unknown as AppContext; + } + + it('keeps audit rows on their own retention window', () => { + repo.setSetting('log_retention_days', '1'); + auditRow('old-2d', Date.now() - 2 * DAY); + auditRow('fresh', Date.now()); + const removed = pruneLogs(ctx()); + expect(removed).toBe(0); + expect(repo.listAudit(10).map((item) => item.id).sort()).toEqual(['fresh', 'old-2d']); + }); + + it('prunes audit rows past audit_retention_days and request logs past log_retention_days', () => { + repo.setSetting('log_retention_days', '1'); + repo.setSetting('audit_retention_days', '1'); + auditRow('stale-audit', Date.now() - 2 * DAY); + auditRow('fresh-audit', Date.now()); + repo.insertLog({ + id: 'stale-log', + ts: Date.now() - 2 * DAY, + keyId: null, + keyName: null, + providerId: null, + providerName: null, + model: 'a/model', + surface: 'chat', + stream: false, + status: 200, + ok: true, + errorCode: null, + errorMessage: null, + latencyMs: 1, + ttfbMs: 1, + inputTokens: 0, + outputTokens: 0, + totalTokens: 0, + reasoningTokens: 0, + cachedTokens: 0, + attempts: 1, + clientIp: null, + userAgent: null, + }); + + expect(pruneLogs(ctx())).toBe(1); + expect(repo.listAudit(10).map((item) => item.id)).toEqual(['fresh-audit']); + expect(repo.listLogs({ limit: 10 }).total).toBe(0); + }); +}); + +describe('graceful shutdown (FEAT-07)', () => { + function makeHost(close: () => Promise): { host: ShutdownHost; forced: number[] } { + const forced: number[] = []; + const host = { + close, + server: { closeAllConnections: () => forced.push(Date.now()) }, + log: { info: () => {}, warn: () => {}, error: () => {} }, + } as unknown as ShutdownHost; + return { host, forced }; + } + + it('drains in-flight requests and exits 0', async () => { + let closed = 0; + const { host } = makeHost(async () => { + closed += 1; + }); + const exits: number[] = []; + const started: string[] = []; + const controller = registerGracefulShutdown(host, { + signals: new EventEmitter(), + exit: (code) => exits.push(code), + onShutdownStart: () => started.push('start'), + }); + await controller.shutdown('SIGTERM'); + expect(closed).toBe(1); + expect(started).toEqual(['start']); + expect(exits).toEqual([0]); + expect(controller.started).toBe(true); + }); + + it('force-closes connections after the drain timeout, then closes', async () => { + vi.useFakeTimers(); + try { + let release!: () => void; + const pending = new Promise((resolve) => { + release = resolve; + }); + const { host, forced } = makeHost(() => pending); + const exits: number[] = []; + const controller = registerGracefulShutdown(host, { + timeoutMs: 1_000, + signals: new EventEmitter(), + exit: (code) => exits.push(code), + }); + + const running = controller.shutdown('SIGINT'); + await vi.advanceTimersByTimeAsync(1_000); + expect(forced).toHaveLength(1); + expect(exits).toEqual([]); + + release(); + await running; + expect(exits).toEqual([0]); + } finally { + vi.useRealTimers(); + } + }); + + it('reports a failed close and runs only once per process', async () => { + const signals = new EventEmitter(); + let closes = 0; + const { host } = makeHost(async () => { + closes += 1; + throw new Error('close failed'); + }); + const exits: number[] = []; + registerGracefulShutdown(host, { signals, exit: (code) => exits.push(code) }); + + signals.emit('SIGINT'); + signals.emit('SIGTERM'); + await new Promise((resolve) => setImmediate(resolve)); + expect(closes).toBe(1); + expect(exits).toEqual([1]); + }); +}); diff --git a/tests/util-upstream.test.ts b/tests/util-upstream.test.ts index 552dc0a..ee18f41 100644 --- a/tests/util-upstream.test.ts +++ b/tests/util-upstream.test.ts @@ -1,7 +1,7 @@ import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'; import { afterEach, describe, expect, it } from 'vitest'; import { ApiError } from '../src/util/errors.js'; -import { joinUrl, upstreamFetch } from '../src/util/upstream.js'; +import { joinUrl, redactUrl, upstreamFetch } from '../src/util/upstream.js'; interface TestServer { base: string; @@ -112,7 +112,7 @@ describe('upstreamFetch bodies', () => { res.writeHead(200, { 'content-type': 'application/json' }); res.end('{}'); }); - const raw = '{\n "model": "x", "big": 9007199254740993, "esc": "\\u00e9", "spaced" : [1, 2] }'; + const raw = Buffer.from('{\n "model": "x", "big": 9007199254740993, "esc": "\\u00e9", "spaced" : [1, 2] }'); const response = await upstreamFetch({ baseUrl: server.base, @@ -126,7 +126,35 @@ describe('upstreamFetch bodies', () => { response.dispose(); expect(received).toHaveLength(1); - expect(received[0]!.toString('utf8')).toBe(raw); + expect(received[0]!.equals(raw)).toBe(true); + }); + + it('keeps invalid UTF-8 bytes intact when forwarding a Buffer body (GW-08)', async () => { + const received: Buffer[] = []; + const server = await listen(async (req, res) => { + received.push(await bodyOf(req)); + res.writeHead(200, { 'content-type': 'application/json' }); + res.end('{}'); + }); + // `\xff` is not valid UTF-8: a string round-trip would turn it into U+FFFD. + const raw = Buffer.concat([ + Buffer.from('{"model":"m","messages":[{"role":"user","content":"'), + Buffer.from([0xff, 0xfe]), + Buffer.from('"}]}'), + ]); + + const response = await upstreamFetch({ + baseUrl: server.base, + apiKey: 'sk-secret', + path: '/chat/completions', + rawBody: raw, + timeoutMs: 2_000, + }); + await response.response.text(); + response.dispose(); + + expect(received[0]!.equals(raw)).toBe(true); + expect(received[0]!.includes(0xef)).toBe(false); // no U+FFFD replacement bytes }); it('sends structured bodies as JSON', async () => { @@ -225,4 +253,128 @@ describe('upstreamFetch timeouts', () => { expect((error as ApiError).code).toBe('client_aborted'); expect((error as ApiError).status).toBe(502); }); -}); \ No newline at end of file +}); +describe('upstreamFetch request headers (GW-06/GW-07)', () => { + interface Captured { + base: string; + headers: () => IncomingMessage['headers'] | null; + } + + const headerServers: Array<{ close(): Promise }> = []; + afterEach(async () => { + for (const server of headerServers.splice(0)) await server.close(); + }); + + async function capture(): Promise { + let headers: IncomingMessage['headers'] | null = null; + const server = await listen((req, res) => { + headers = req.headers; + res.writeHead(200, { 'content-type': 'application/json' }); + res.end('{}'); + }); + headerServers.push(server); + return { base: server.base, headers: () => headers }; + } + + it('defaults accept to application/json for a non-streaming call', async () => { + const server = await capture(); + const response = await upstreamFetch({ baseUrl: server.base, apiKey: 'k', path: '/chat/completions', body: {} }); + await response.response.text(); + response.dispose(); + expect(server.headers()?.accept).toBe('application/json'); + }); + + it('defaults accept to text/event-stream for a streaming call', async () => { + const server = await capture(); + const response = await upstreamFetch({ + baseUrl: server.base, + apiKey: 'k', + path: '/chat/completions', + body: { stream: true }, + stream: true, + }); + await response.response.text(); + response.dispose(); + expect(server.headers()?.accept).toBe('text/event-stream'); + }); + + it('keeps a client-supplied accept header', async () => { + const server = await capture(); + const response = await upstreamFetch({ + baseUrl: server.base, + apiKey: 'k', + path: '/chat/completions', + body: {}, + stream: true, + headers: { accept: 'application/x-custom' }, + }); + await response.response.text(); + response.dispose(); + expect(server.headers()?.accept).toBe('application/x-custom'); + }); + + it('only defaults anthropic-version on the Anthropic surface', async () => { + const openai = await capture(); + const first = await upstreamFetch({ baseUrl: openai.base, apiKey: 'k', path: '/chat/completions', body: {} }); + await first.response.text(); + first.dispose(); + expect(openai.headers()?.['anthropic-version']).toBeUndefined(); + + const anthropic = await capture(); + const second = await upstreamFetch({ + baseUrl: anthropic.base, + apiKey: 'k', + path: '/messages', + body: {}, + anthropic: true, + }); + await second.response.text(); + second.dispose(); + expect(anthropic.headers()?.['anthropic-version']).toBe('2023-06-01'); + }); + + it('lets a client-supplied anthropic-version win over the default', async () => { + const server = await capture(); + const response = await upstreamFetch({ + baseUrl: server.base, + apiKey: 'k', + path: '/messages', + body: {}, + anthropic: true, + headers: { 'anthropic-version': '2025-01-01' }, + }); + await response.response.text(); + response.dispose(); + expect(server.headers()?.['anthropic-version']).toBe('2025-01-01'); + }); +}); + +describe('redactUrl (GW-12)', () => { + it('drops userinfo and query string', () => { + expect(redactUrl('https://user:pass@host.example/v1/chat/completions?key=secret')).toBe( + 'https://host.example/v1/chat/completions', + ); + expect(redactUrl('https://user@host.example/v1')).toBe('https://host.example/v1'); + expect(redactUrl('https://host.example/v1?api_key=abc')).toBe('https://host.example/v1'); + }); + + it('returns unparsable input unchanged', () => { + expect(redactUrl('not a url')).toBe('not a url'); + }); + + it('never exposes credentials in the unreachable-provider error message', async () => { + // Port 1 on loopback is refused immediately, so the error composes promptly. + const error = await upstreamFetch({ + baseUrl: 'http://user:pass@127.0.0.1:1/v1?token=secret', + apiKey: 'k', + path: '/chat/completions', + body: {}, + timeoutMs: 1_000, + }).catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(ApiError); + const message = (error as ApiError).message; + expect(message).not.toContain('user:pass'); + expect(message).not.toContain('secret'); + expect(message).toContain('127.0.0.1:1'); + }); +}); diff --git a/tsconfig.test.json b/tsconfig.test.json new file mode 100644 index 0000000..1d0f607 --- /dev/null +++ b/tsconfig.test.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "ES2023", + "lib": ["ES2023"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "noUncheckedIndexedAccess": false, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "allowJs": true, + "checkJs": false, + "noEmit": true, + "types": ["node"] + }, + "include": [ + "src/server.ts", + "tests/**/*.ts", + "scripts/**/*.ts", + "scripts/**/*.mjs", + "vitest.config.ts", + "web/vite.config.ts" + ], + "exclude": ["node_modules", "dist"] +} diff --git a/vitest.config.ts b/vitest.config.ts index 0fd0c48..bdbff92 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -4,9 +4,13 @@ export default defineConfig({ test: { include: ['tests/**/*.test.ts'], environment: 'node', + // Forks (not worker threads) keep native modules such as `node:sqlite` isolated + // per test file. + pool: 'forks', testTimeout: 20_000, + hookTimeout: 20_000, }, resolve: { extensions: ['.ts', '.js', '.json'], }, -}); \ No newline at end of file +}); diff --git a/web/index.html b/web/index.html index 78e93cd..ecc0b72 100644 --- a/web/index.html +++ b/web/index.html @@ -9,14 +9,22 @@ OpenCode Router diff --git a/web/src/components/SetupBanner.tsx b/web/src/components/SetupBanner.tsx index 2a9775b..80b5ae3 100644 --- a/web/src/components/SetupBanner.tsx +++ b/web/src/components/SetupBanner.tsx @@ -1,4 +1,4 @@ -import type { ReactNode } from 'react'; +import { memo, type ReactNode } from 'react'; import { Link } from 'react-router-dom'; import { ArrowUpRight, Check, ShieldCheck, Sparkles, TriangleAlert } from 'lucide-react'; import { setupSteps, useReadiness, type SetupStep } from '../lib/readiness'; @@ -83,7 +83,7 @@ export function ReadinessChecklist({ } /** Prominent "Setup needed" banner shown on every dashboard page until the gateway is ready. */ -export function SetupBanner({ onNavigate }: { onNavigate?: () => void }): ReactNode { +function SetupBannerBase({ onNavigate }: { onNavigate?: () => void }): ReactNode { const { bootstrap, loading } = useReadiness(); if (loading || !bootstrap || bootstrap.gatewayReady) return null; @@ -124,6 +124,9 @@ export function SetupBanner({ onNavigate }: { onNavigate?: () => void }): ReactN ); } +/** Renders on every page: memo so it only re-renders when readiness actually changes. */ +export const SetupBanner = memo(SetupBannerBase); + /** Small ready-state counterpart used at the top of the Overview page. */ export function ReadyBanner(): ReactNode { const { bootstrap } = useReadiness(); diff --git a/web/src/components/layout/Sidebar.tsx b/web/src/components/layout/Sidebar.tsx index 0ce60b4..81b15fb 100644 --- a/web/src/components/layout/Sidebar.tsx +++ b/web/src/components/layout/Sidebar.tsx @@ -1,4 +1,4 @@ -import type { ReactNode } from 'react'; +import { memo, type ReactNode } from 'react'; import { NavLink, Link } from 'react-router-dom'; import { X, Zap } from 'lucide-react'; import { NAV_ITEMS } from './nav'; @@ -28,7 +28,7 @@ function BrandMark(): ReactNode { ); } -export function Sidebar({ mobileOpen, onClose }: { mobileOpen: boolean; onClose: () => void }): ReactNode { +function SidebarBase({ mobileOpen, onClose }: { mobileOpen: boolean; onClose: () => void }): ReactNode { const { bootstrap } = useReadiness(); const steps = setupSteps(bootstrap); const ready = Boolean(bootstrap?.gatewayReady); @@ -114,4 +114,6 @@ export function Sidebar({ mobileOpen, onClose }: { mobileOpen: boolean; onClose: ) : null} ); -} \ No newline at end of file +} +/** Always-mounted navigation: memo keeps it out of page-level re-render cascades. */ +export const Sidebar = memo(SidebarBase); diff --git a/web/src/components/layout/Topbar.tsx b/web/src/components/layout/Topbar.tsx index 5d286c3..07fc7ff 100644 --- a/web/src/components/layout/Topbar.tsx +++ b/web/src/components/layout/Topbar.tsx @@ -1,20 +1,22 @@ -import type { ReactNode } from 'react'; +import { memo, type ReactNode } from 'react'; import { Link, useLocation, useNavigate } from 'react-router-dom'; import { LogOut, Menu, ShieldCheck } from 'lucide-react'; import { navItemForPath } from './nav'; import { ThemeToggle } from './ThemeToggle'; import { LiveIndicator } from './LiveIndicator'; import { IconButton } from '../ui/Button'; -import { useReadiness } from '../../lib/readiness'; +import { useReadiness, useRealtimeState } from '../../lib/readiness'; import { useAuth } from '../../lib/auth'; import { useToast } from '../ui/Toast'; +import { extractErrorMessage } from '../../lib/api'; -export function Topbar({ onOpenMobile }: { onOpenMobile: () => void }): ReactNode { +function TopbarBase({ onOpenMobile }: { onOpenMobile: () => void }): ReactNode { const location = useLocation(); const navigate = useNavigate(); const toast = useToast(); const { logout } = useAuth(); - const { bootstrap, realtime } = useReadiness(); + const { bootstrap } = useReadiness(); + const realtime = useRealtimeState(); const item = navItemForPath(location.pathname); const ready = Boolean(bootstrap?.gatewayReady); @@ -65,13 +67,20 @@ export function Topbar({ onOpenMobile }: { onOpenMobile: () => void }): ReactNod label="Sign out" icon={} onClick={() => { - void logout().then(() => { - toast.info('Signed out', 'Your dashboard session was cleared.'); - navigate('/login', { replace: true }); - }); + // A failed /logout must not trap the operator in the dashboard: the local + // session state is cleared in the auth layer regardless, so navigate anyway. + void logout() + .then(() => toast.info('Signed out', 'Your dashboard session was cleared.')) + .catch((cause: unknown) => { + toast.error('Sign out failed', extractErrorMessage(cause)); + }) + .finally(() => navigate('/login', { replace: true })); }} /> ); -} \ No newline at end of file +} + +/** Always-mounted shell chrome: memo keeps it out of page-level re-render cascades. */ +export const Topbar = memo(TopbarBase); \ No newline at end of file diff --git a/web/src/components/ui/Button.tsx b/web/src/components/ui/Button.tsx index 8fbf27a..e8679a5 100644 --- a/web/src/components/ui/Button.tsx +++ b/web/src/components/ui/Button.tsx @@ -35,7 +35,7 @@ export function Button({ -