diff --git a/.env.example b/.env.example index 5deb607..8c2de16 100644 --- a/.env.example +++ b/.env.example @@ -1,8 +1,41 @@ +# --------------------------------------------------------------------------- # Server -PORT=20125 +# --------------------------------------------------------------------------- +# Bind address and HTTP port. HOST=0.0.0.0 -# Data directory (sqlite db + secrets) +PORT=20125 +# Pino log level: trace | debug | info | warn | error | fatal. +LOG_LEVEL=info +# Maximum request body in bytes (base64 media payloads need room). +BODY_LIMIT=134217728 + +# --------------------------------------------------------------------------- +# Storage +# --------------------------------------------------------------------------- +# SQLite database and the persisted signing secret live here. DATA_DIR=./data -# Optional: override default dashboard password (hashed at first boot only) + +# --------------------------------------------------------------------------- +# Security +# --------------------------------------------------------------------------- +# Only used when the dashboard password hash is first created. # DASHBOARD_PASSWORD=123456 -LOG_LEVEL=info +# HMAC secret for dashboard session cookies. When empty, a secret is generated +# once and stored in /.secret. When set, the environment value wins on +# every boot and POST /admin/api/settings/rotate-secret returns 409 secret_from_env. +# ROUTER_SECRET= +# Dashboard session lifetime in milliseconds (default 7 days). +SESSION_TTL_MS=604800000 +# Trust X-Forwarded-For/-Proto for request.ip (login brute-force guard + client_ip +# logs). Keep false unless the app runs behind a trusted reverse proxy. +TRUST_PROXY=false +# Allow provider test/sync to reach loopback/link-local/private hosts (SSRF guard). +PROVIDER_ALLOW_PRIVATE_HOSTS=false + +# --------------------------------------------------------------------------- +# Dashboard assets / URLs +# --------------------------------------------------------------------------- +# Directory served as the dashboard build (default: /web/dist). +# WEB_DIST_DIR=./web/dist +# Optional absolute public base URL of this deployment. +# PUBLIC_URL=https://router.example.com diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2e77fc5..2100ea0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,7 @@ jobs: name: Commit messages if: github.event_name == 'pull_request' runs-on: ubuntu-latest + timeout-minutes: 10 steps: - name: Checkout uses: actions/checkout@v4 @@ -44,16 +45,17 @@ jobs: "$PR_TITLE" quality: + # Job name is a required branch-protection status check: do not rename it. name: Lint & test runs-on: ubuntu-latest + timeout-minutes: 20 steps: - name: Checkout uses: actions/checkout@v4 - name: Set up pnpm + # Version comes from package.json `packageManager` (single source of truth). uses: pnpm/action-setup@v4 - with: - version: 10 - name: Set up Node.js uses: actions/setup-node@v4 @@ -73,14 +75,14 @@ jobs: build-and-e2e: name: Build & e2e runs-on: ubuntu-latest + timeout-minutes: 30 steps: - name: Checkout uses: actions/checkout@v4 - name: Set up pnpm + # Version comes from package.json `packageManager` (single source of truth). uses: pnpm/action-setup@v4 - with: - version: 10 - name: Set up Node.js uses: actions/setup-node@v4 diff --git a/.gitignore b/.gitignore index 7ad51dd..b88144c 100644 --- a/.gitignore +++ b/.gitignore @@ -9,7 +9,6 @@ node_modules/ # Build output (generated by `pnpm build`) # --------------------------------------------------------------------------- dist/ -web/dist/ *.tsbuildinfo # --------------------------------------------------------------------------- @@ -19,6 +18,7 @@ data/ *.db *.db-shm *.db-wal +*.db-journal *.sqlite *.sqlite3 .secret @@ -51,11 +51,6 @@ tmp/ .tmp/ *.local -# --------------------------------------------------------------------------- -# Generated dashboard export (scripts/screenshots.ts writes here by default) -# --------------------------------------------------------------------------- -tmp/screenshots/ - # --------------------------------------------------------------------------- # Editors and IDEs # --------------------------------------------------------------------------- diff --git a/AGENTS.md b/AGENTS.md index 09bced4..4e572f1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,7 @@ forwards each request to one of several interchangeable providers using round-ro rotation with failover, so a rate-limited provider never stops traffic. A React dashboard manages providers, models, API keys, logs and settings. -Stack: Node.js ≥ 22.5 (uses `node:sqlite`), Fastify 5, TypeScript ESM, pnpm, Vite + +Stack: Node.js ≥ 22.13 (flag-free `node:sqlite`), Fastify 5, TypeScript ESM, pnpm 10, Vite + React 19 + Tailwind CSS 4. Default port **20125**. ## Golden rules @@ -46,7 +46,7 @@ pnpm test:e2e # full acceptance: real server + deterministic mock u pnpm test:live # smoke test against a real provider (skips on 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 +pnpm exec tsx scripts/screenshots.ts # headless Chrome UI check + screenshots (skips if Chrome absent) ``` Before opening a PR run at least: `pnpm typecheck && pnpm test && pnpm build && pnpm test:e2e`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 55c5956..2401274 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,8 +7,8 @@ coding standards, the commit-message convention enforced by CI, and the pull-req Requirements: -- Node.js **≥ 22.5** (the gateway uses the built-in `node:sqlite` module) -- pnpm 9+ (CI uses pnpm 10) +- Node.js **≥ 22.13** (the gateway uses the built-in `node:sqlite` module without an experimental flag) +- 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) @@ -118,7 +118,7 @@ pull request that passes the required checks. 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 51-check acceptance suite + - **Build & e2e** — production build plus 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 diff --git a/README.md b/README.md index c45f8bf..533f771 100644 --- a/README.md +++ b/README.md @@ -36,8 +36,11 @@ client (OpenAI SDK / Anthropic SDK / curl) ──▶ OpenCode Router :20125 ─ (+ `POST /v1/messages/count_tokens`, `GET /v1/models`) — streaming and non-streaming. - **Full pass-through fidelity**: tool calling, vision/image/video/audio/PDF content parts, and reasoning (`reasoning_effort`, `reasoning.effort`, Anthropic `thinking`) are preserved end-to-end. -- **Provider rotation**: round-robin ordered by priority with automatic failover on `429`/`5xx`/network errors, - per-provider cooldowns, and per-attempt logging. +- **Byte-level pass-through**: request bodies are forwarded unchanged unless reasoning or + `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`). - **Model registry**: synced from any single provider (all providers expose the same catalogue) or added manually. Empty until you configure a provider. @@ -47,8 +50,8 @@ client (OpenAI SDK / Anthropic SDK / curl) ──▶ OpenCode Router :20125 ─ ## Requirements -- Node.js **≥ 22.5** (uses `node:sqlite`; tested on Node 26) -- pnpm 10+ +- Node.js **≥ 22.13** (flag-free `node:sqlite`; tested on Node 26) +- pnpm 10+ (the repo pins `pnpm@10.18.0` through `packageManager`) ## Quick start @@ -66,20 +69,27 @@ Open → you are redirected to the dashboard login. Def (change it in *Settings → Security*). Then: **Providers → Add provider** (id, display name, base URL such as `http://127.0.0.1:20123/v1`, API key) -→ **Test** → **Sync models** → **API Keys → Create key**. The gateway refuses traffic until at least one valid -provider *and* one API key exist. +→ **Test** → **Sync models** → **API Keys → Create key**. The gateway refuses traffic until at least one +enabled provider, one enabled model *and* one API key exist (the dashboard shows `Gateway ready` only then). ## Configuration | Env | Default | Meaning | | --- | --- | --- | -| `PORT` | `20125` | HTTP port | | `HOST` | `0.0.0.0` | Bind address | -| `DATA_DIR` | `./data` | SQLite database + signing secret | -| `LOG_LEVEL` | `info` | Pino level | -| `BODY_LIMIT` | `134217728` | Max request body (base64 media) | +| `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 (base64 media) | | `DASHBOARD_PASSWORD` | `123456` | Only used when the password hash is first created | -| `ROUTER_SECRET` | generated in `DATA_DIR/.secret` | HMAC secret for sessions | +| `ROUTER_SECRET` | generated in `/.secret` | HMAC secret for dashboard sessions; when set, rotation is refused with `409 secret_from_env` | +| `SESSION_TTL_MS` | `604800000` | Dashboard session lifetime (7 days) | +| `TRUST_PROXY` | `false` | Trust `X-Forwarded-*` for `request.ip` (login brute-force guard + `client_ip` logs) — enable only behind a trusted proxy | +| `PROVIDER_ALLOW_PRIVATE_HOSTS` | `false` | Allow provider test/sync to reach loopback/link-local/private hosts (SSRF guard off) | +| `WEB_DIST_DIR` | `/web/dist` | Directory served as the dashboard build | +| `PUBLIC_URL` | unset | Optional absolute public base URL of this deployment | + +[.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**. @@ -133,8 +143,9 @@ curl http://127.0.0.1:20125/v1/messages \ curl http://127.0.0.1:20125/v1/models -H "Authorization: Bearer okr-..." ``` -Every gateway response carries `x-opencode-router-provider`, `x-opencode-router-request-id` and -`x-opencode-router-attempts` headers. +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. 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. @@ -162,10 +173,10 @@ scripts/e2e.ts full end-to-end acceptance run ```bash pnpm typecheck # server + dashboard type checks pnpm test # vitest unit suite (crypto, repos, stats, SSE, normalization) -pnpm test:e2e # boots a real server + mock providers; 51 acceptance checks +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 build # dist/ + web/dist/ -pnpm exec tsx scripts/screenshots.ts # headless Chrome UI check + PNG screenshots +pnpm exec tsx scripts/screenshots.ts # headless Chrome UI check + PNG screenshots (macOS; SKIPs without Chrome) ``` `pnpm test:e2e` is self-contained: it starts two deterministic mock upstreams that mimic the reference @@ -176,7 +187,9 @@ routing, rotation, failover, logging, admin APIs, dashboard routing and the buil provider answers `429` every probe is reported as **SKIP** instead of failing. `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/`. +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. ## Contributing @@ -201,3 +214,6 @@ Agents and automated contributors should read [AGENTS.md](AGENTS.md) first. - Gateway keys are stored as SHA-256 hashes; the plaintext is shown exactly once at creation. - Provider API keys are never returned through the dashboard API (masked only). - Bind to `127.0.0.1` (or place behind a reverse proxy with TLS) when exposing the dashboard. +- Leave `TRUST_PROXY=false` unless you run behind a reverse proxy you control: the login brute-force guard + and logged `client_ip` key on the socket address until it is enabled. +- Keep `PROVIDER_ALLOW_PRIVATE_HOSTS=false` unless providers legitimately live on loopback/private networks. diff --git a/docs/API.md b/docs/API.md index b6fecf2..8402e1f 100644 --- a/docs/API.md +++ b/docs/API.md @@ -9,13 +9,15 @@ Authorization: Bearer okr-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx x-api-key: okr-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` -Responses include: +Response headers: -| Header | Meaning | -| --- | --- | -| `x-opencode-router-provider` | id of the provider that served the request | -| `x-opencode-router-request-id` | gateway request id (same id as in the Logs tab) | -| `x-opencode-router-attempts` | number of upstream attempts (1 = first provider worked) | +| 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) | + +Errors raised before an upstream attempt (auth, routing, validation) carry `x-opencode-router-request-id` only. 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. @@ -32,9 +34,18 @@ for chat/responses, Anthropic style `{"type":"error","error":{"type","message"}} | 429 | `all_providers_rate_limited` | every attempt hit a rate limit | | 502 | `all_providers_failed` | every attempt failed (network/5xx) | -The router retries the next provider for `429`, `5xx`, `408`, `425` 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 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. + +## 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. --- @@ -132,16 +143,25 @@ Lists the enabled models from the registry in OpenAI format, enriched with capab `GET /v1/models/:id` returns a single entry or `404 model_not_found`. +Like every other `/v1/*` request, `GET /v1/models` and `GET /v1/models/:id` write one `request_logs` row per +request (successes and rejections alike). + ## `GET /health` ```json -{"status":"ok","name":"OpenCode Router","version":"1.0.0","startedAt":1765000000000, - "providers":1,"models":12,"apiKeys":true} +{"status":"ok","name":"OpenCode Router","version":"1.0.0","uptimeMs":86400000, + "startedAt":1765000000000,"providers":1,"models":12,"apiKeys":true} ``` +`uptimeMs` is the real process uptime (`now - startedAt`), not a placeholder. + ## Streaming -All three surfaces stream as `text/event-stream` when `stream: true` is set. Bytes are forwarded as they arrive -from the upstream provider (`Cache-Control: no-cache`, `X-Accel-Buffering: no`). The gateway parses frames -in-flight only to extract token usage for logging, and strips provider-internal `x_opencode` metadata. -Client aborts terminate the upstream request and are logged with `client_aborted`. \ No newline at end of file +All three surfaces stream as `text/event-stream` when `stream: true` is set. Bytes are forwarded as they +arrive from the upstream provider (`Cache-Control: no-cache`, `X-Accel-Buffering: no`). Frames are decoded +only to extract token usage and to strip provider-internal `x_opencode` metadata, so invalid UTF-8 and a +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`. diff --git a/docs/SPEC.md b/docs/SPEC.md index f8a5a1d..2756d10 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -22,7 +22,8 @@ message `lead` instead of editing. ```ts // src/core/context.ts interface AppContext { - config: AppConfig; // port, host, dataDir, dbPath, bodyLimit, sessionTtlMs, webDistDir, defaultDashboardPassword + config: AppConfig; // host, port, dataDir, dbPath, logLevel, bodyLimit, sessionTtlMs, webDistDir, + // publicUrl, trustProxy, providerAllowPrivateHosts, defaultDashboardPassword, secret db: { db: DatabaseSync; secret: string }; repo: Repo; // src/db/repos.ts events: EventBus; // src/core/events.ts @@ -43,7 +44,7 @@ incActiveRequests(); decActiveRequests(); getActiveRequests(); 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`), -`log_store_bodies` (`false`), `model_allow_unknown` (`false`). +`model_allow_unknown` (`false`), `upstream_user_agent` (`opencode-router/1.0`). Helpers: `src/util/crypto.ts` (`hashPassword`, `verifyPassword`, `hmacSign`, `generateApiKey`, `uuid`, `randomHex`, `sha256Hex`, `safeEqual`), `src/util/errors.ts` (`ApiError`, `errorTypeForStatus`, `isRetryableStatus`, `upstreamErrorFrom`), @@ -64,6 +65,12 @@ Helpers: `src/util/crypto.ts` (`hashPassword`, `verifyPassword`, `hmacSign`, `ge 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: `. +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 +paired `request:start`/`request:end` event pair. +`request.ip` is the socket address unless `TRUST_PROXY` is configured, so the admin login brute-force guard +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`. @@ -85,34 +92,50 @@ No enabled provider, or zero enabled models → `503` `api_error` code `no_provi | `GET /v1/models/:id` | single model or `404 model_not_found` | ### 2.1 Request pipeline (all three surfaces) -1. Authenticate key. 2. Parse JSON body (invalid JSON → `400 invalid_request_error`). +1. `onRequest` hook: authenticate the key (§ Auth) and emit `request:start`; a rejection here writes one + `request_logs` row and never reads the body. +2. Parse JSON body (invalid JSON → `400 invalid_request_error`). 3. `model` required → else `400` code `model_required`. 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. +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. 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`. -7. Retry with the next provider when the attempt fails with a retryable status (`isRetryableStatus`) - or a network/timeout `ApiError`, up to `max_retries` attempts total. -8. Log the request (§2.6) exactly once per client request; also log every attempt via `insertAttempt`. + 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. +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. +9. Log the request (§2.6) exactly once per client request — `GET /v1/models*` included — and log every + attempt via `insertAttempt`. 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 to always set on success: `x-opencode-router-provider: `, -`x-opencode-router-request-id: `, `x-opencode-router-attempts: `. +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. ### 2.2 Rotation (round-robin + failover) +- `rotation_strategy` selects the order: `round-robin` (default, in-memory cursor advanced per request), + `priority` (stable `priority` asc then `created_at` asc, cursor unused) or `random` (shuffled candidates). - Candidate set: enabled providers, ordered by `priority` asc then `created_at` asc. -- Maintain an in-memory round-robin cursor; each request starts at the next provider. +- Maintain an in-memory round-robin cursor; each request starts at the next provider (round-robin only). - Skip providers whose `cooldown_until > now`. - If every candidate is cooling down, fall back to the candidate with the smallest `cooldown_until` so requests still have a chance (prevents total outage). - Attempts iterate the rotated list; a provider is tried at most once per request. +- Providers skipped because of an active cooldown produce **no** `request_attempts` row, and `attempts` / + `x-opencode-router-attempts` count real upstream calls only. +- Fatal (non-retryable) upstream failures are attributed to the provider that answered, so the log row and + the router headers are populated even though the request failed. - On success: `recordProviderSuccess(id, latencyMs)`. -- On retryable failure: `recordProviderFailure(id, status, message, cooldownMs)` + `events.emitProvider`. +- On retryable failure (incl. `409`): `recordProviderFailure(id, status, message, cooldownMs)` + `events.emitProvider`. - 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), @@ -144,16 +167,25 @@ Disabled models are omitted; empty DB → `{"object":"list","data":[]}`. ### 2.5 Streaming Forward SSE frames as they arrive (flush per frame, `Content-Type: text/event-stream`, -`Cache-Control: no-cache`, `Connection: keep-alive`, `X-Accel-Buffering: no`). +`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. 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) - 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 -(destroy the upstream body, log with `ok=false`, code `client_aborted`). +(destroy the upstream body, log with `ok=false`, code `client_aborted`, status `499`). An idle gap or the +total deadline aborts the upstream: `504` + code `upstream_timeout` while the response is still unsent, or +a `504` status on the already-flushed stream. Retryable failures honour an upstream `retry-after` header +(delta seconds or HTTP-date): the cooldown becomes `max(provider_cooldown_ms, retryAfter)`. ### 2.6 Logging -One `request_logs` row per client request with: `id` (uuid), `ts`, `key_id`, `key_name`, +One `request_logs` row per client request — `GET /v1/models` and `GET /v1/models/:id` included, logged with +the OpenAI (`chat`) surface — with: +`id` (uuid), `ts`, `key_id`, `key_name`, `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. @@ -161,11 +193,16 @@ Emit `ctx.events.emitRequestStart(...)` right after auth and `ctx.events.emitReq ## 3. Admin API (`src/admin/**`, prefix `/admin/api`) ### Auth -- Session cookie `okr_session` = `"."` signed with `ctx.db.secret` via `hmacSign`; store the - session row (`ctx.repo.createSession`), verify both signature and DB row + expiry. +- Session cookie `okr_session` = `".."` where + `hmac = hmacSign(ctx.db.secret, ".")`; store the session row (`ctx.repo.createSession`), + 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` only when the request is https. + `secure` when the request is https (`request.protocol`, a trusted `x-forwarded-proto`, 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, @@ -176,10 +213,13 @@ Emit `ctx.events.emitRequestStart(...)` right after auth and `ctx.events.emitReq ### Endpoints (all JSON; errors use `{error:{message,code}}`) **Bootstrap / stats** - `GET /admin/api/bootstrap` → `{version, uptimeMs, startedAt, gatewayReady, hasProviders, hasApiKeys, hasModels, providerCount, modelCount, keyCount, syncedAt, syncProviderId, activeRequests, settings}`. -- `GET /admin/api/stats?window=1h|6h|24h|7d|30d` → `Repo.statsOverview(...)` output plus +- `GET /admin/api/stats?window=1h|6h|24h|7d|30d` → `Repo.statsOverview(...)` output (including exact + `requestsLast60s`/`errorsLast60s` counts and `activeRequests`) plus `{health:{status,activeRequests,providers:[{id,name,status,enabled,cooldownUntil,lastLatencyMs,successCount,failureCount,lastError,lastCheckedAt}], modelsEnabled, keysActive}, window}`. - `GET /admin/api/events` (SSE) → emits `request:start`, `request:end`, `provider:update`, plus a - `stats` heartbeat every 5s with `{activeRequests, requestsLast60s, errorsLast60s}`. + `stats` heartbeat every 5s with `{activeRequests, requestsLast60s, errorsLast60s}`. Writes apply + per-client backpressure (bounded queue + `drain` resume; the stream is ended after repeated stalls). + `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** @@ -188,8 +228,14 @@ Emit `ctx.events.emitRequestStart(...)` right after auth and `ctx.events.emitReq - `PATCH /admin/api/providers/:id {name?, baseUrl?, apiKey?, enabled?, priority?}` → `{provider}`. - `DELETE /admin/api/providers/:id` → `{ok:true}`. - `POST /admin/api/providers/:id/test` → `{ok, status, latencyMs, models:number, error:null|string}` (GET `{baseUrl}/models`). -- `POST /admin/api/providers/test {baseUrl, apiKey}` → same shape, before saving. + 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). - `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 + `PROVIDER_ALLOW_PRIVATE_HOSTS=true` (SSRF guard). **Models** - `GET /admin/api/models` → `{models:[ModelRow...], syncedAt, syncProviderId, providers:[{id,name}]}`. @@ -201,38 +247,51 @@ Emit `ctx.events.emitRequestStart(...)` right after auth and `ctx.events.emitReq the first enabled one; `400` when no provider exists. Sync semantics: upsert every model reported upstream with `source='sync'`, `providerId`, and delete rows with `source='sync'` from that provider that no longer exist upstream. Manual rows are never deleted. - Record `models_synced_at` + `models_sync_provider_id` in settings. + A `source='sync'` row already owned by a *different* provider is neither re-attributed nor deleted by this + provider's sync (only its owner's sync garbage-collects it). Record `models_synced_at` + + `models_sync_provider_id` in settings. **API keys** - `GET /admin/api/keys` → `{keys:[{id,name,prefix,suffix,enabled,requestCount,lastUsedAt,createdAt,revokedAt}]}`. - `POST /admin/api/keys {name}` → `{key, plaintext}` — plaintext returned **once**. - `PATCH /admin/api/keys/:id {name?, enabled?}` → `{key}`. - `POST /admin/api/keys/:id/revoke` → `{key}` (sets `revokedAt`, disables). -- `DELETE /admin/api/keys/:id` → `{ok:true}`. +- `POST /admin/api/keys/:id/rotate` → `{key, plaintext}` — replaces the stored hash with a new plaintext + (returned exactly once) while keeping the id, name and request counters; `404 key_not_found` for unknown ids. +- `DELETE /admin/api/keys/:id` → `{ok:true}`; `404 key_not_found` for unknown ids. **Logs** - `GET /admin/api/logs?limit&offset&surface&model&providerId&keyId&ok&stream&search&since&until` → `{logs:[...], total, limit, offset}`. - `GET /admin/api/logs/:id` → `{log, attempts:[...]}` (`404` when missing). - `DELETE /admin/api/logs` → `{ok:true, removed}`; `POST /admin/api/logs/prune {days}` → `{removed}`. -- `GET /admin/api/logs/export?format=json|csv` → file download of the current filter. +- `GET /admin/api/logs/export?format=json|csv` → file download of the current filter. Exports are capped at + 500 rows; when the cap truncates the result the response carries `X-Export-Truncated`. CSV cells starting + 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). +- `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`). - `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}` (keep the current session). -- `POST /admin/api/settings/rotate-secret` → `{ok:true, secret}` — rotate `ctx.db.secret`, invalidating - dashboard sessions and all existing gateway keys' hashing scope is unchanged (keys are sha256 of the - plaintext, so they keep working); return the new secret so the operator can store it. - Also persist it to `/.secret`. +- `DELETE /admin/api/settings/sessions` → `{ok:true, revoked}` (revokes **every** other session, not just the + 50 newest; keeps the current session). +- `DELETE /admin/api/settings/sessions/:id` → `{ok:true, revoked:1}` for one session by id; + `400 cannot_revoke_current` for the caller's own session and `404 session_not_found` otherwise. +- `POST /admin/api/settings/rotate-secret` → `{ok:true, secret}` — refuse with `409 secret_from_env` when + `ROUTER_SECRET` is set, because the environment value would win on the next restart. Otherwise generate a + new secret, persist it to `/.secret` **before** swapping the in-memory `ctx.db.secret`, then + 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)`. ### Scheduler (`src/admin/scheduler.ts`) `startScheduler(ctx)` returns a stop function. It: - every `model_sync_interval_ms` (min 30s) syncs models when `auto_sync_models=true` and an enabled provider exists; +- probes providers whose cooldown is active and clears the cooldown when the probe succeeds; - purges expired sessions every 10 minutes; - never throws out of the interval callback (log warnings instead); - does not start timers that keep the process alive (`unref()`). @@ -248,7 +307,7 @@ Files to create: `web/index.html`, `web/vite.config.ts`, `web/tsconfig.json`, `w `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/**`. -Routes: `/` → redirect to `/dashboard/overview` when authenticated else `/login`; +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`. @@ -284,19 +343,18 @@ Routes: `/` → redirect to `/dashboard/overview` when authenticated else `/logi capabilities toggles, reasoning efforts multi-select), sync button with provider picker, shows sync time. - Logs: filter bar (surface/model/provider/status/stream/search/time range), live tail toggle, paginated table, row detail drawer with attempts timeline, export JSON/CSV, clear logs. -- Settings: gateway readiness checklist, rotation + retry + cooldown + timeout, auto sync + interval, - log retention + store bodies, model_allow_unknown, change password, session list with revoke, +- Settings: gateway readiness checklist, rotation strategy + retry + cooldown + timeout, auto sync + interval, + log retention, model_allow_unknown, change password, session list with per-session and revoke-all actions, rotate secret (with confirmation), audit log, system info (version, uptime, db path, counts). - Global: sidebar nav with active indicator, topbar with readiness pill (`Gateway ready` / `Setup needed`), - live active-request counter, theme toggle, logout. All strings in Vietnamese-friendly English labels - (use English UI labels; errors may be in English). + live active-request counter, theme toggle, logout. All UI copy is English. - Everything must degrade gracefully when the gateway has no provider/key/model yet: prominent "Setup needed" banners linking to the right tab. ## 5. Verification requirements - `pnpm typecheck` clean, `pnpm build` produces `dist/` and `web/dist/`. -- `pnpm dev` (or `node dist/src/index.js`) starts on 20125; `GET /health` → `{status:'ok'}`; - `GET /` redirects/serves the dashboard. +- `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. diff --git a/package.json b/package.json index ebf8823..e4b9784 100644 --- a/package.json +++ b/package.json @@ -37,7 +37,7 @@ "url": "https://github.com/dinhdev666/opencode-router/issues" }, "engines": { - "node": ">=22.5.0" + "node": ">=22.13.0" }, "scripts": { "dev": "tsx watch src/index.ts", @@ -80,5 +80,6 @@ "typescript": "^5.9.3", "vite": "^7.1.9", "vitest": "^3.2.4" - } + }, + "packageManager": "pnpm@10.18.0" } diff --git a/scripts/check-commit-messages.mjs b/scripts/check-commit-messages.mjs index dfa18d2..2bd655f 100644 --- a/scripts/check-commit-messages.mjs +++ b/scripts/check-commit-messages.mjs @@ -27,6 +27,8 @@ const ALLOWED_TYPES = [ // ()!: const SUBJECT_PATTERN = new RegExp(`^(${ALLOWED_TYPES.join('|')})(\\([a-z0-9][a-z0-9._/-]*\\))?(!)?: (.+)$`); 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']; @@ -37,19 +39,28 @@ function git(args) { function readCommits(range) { const fieldSeparator = '\u001f'; const recordSeparator = '\u001e'; - const raw = git(['log', `--format=%H${fieldSeparator}%s${recordSeparator}`, range]); + const raw = git(['log', `--format=%H${fieldSeparator}%s${fieldSeparator}%b${recordSeparator}`, range]); if (!raw) return []; return raw .split(recordSeparator) .map((record) => record.trim()) .filter(Boolean) .map((record) => { - const [sha, ...subjectParts] = record.split(fieldSeparator); - return { sha, subject: subjectParts.join(fieldSeparator).trim() }; + const [sha, subject, ...bodyParts] = record.split(fieldSeparator); + return { + sha, + subject: (subject ?? '').trim(), + body: bodyParts.join(fieldSeparator), + }; }); } -function validate(subject) { +/** + * @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. + */ +function validate(subject, body) { if (IGNORED_PREFIXES.some((prefix) => subject.startsWith(prefix))) return []; if (subject.length === 0) return ['empty subject']; @@ -64,11 +75,14 @@ function validate(subject) { return problems; } - const [, , , , description] = match; + 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'); 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'); + } return problems; } @@ -92,10 +106,12 @@ function main() { const failures = []; for (const commit of commits) { - const problems = validate(commit.subject); + const problems = validate(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); if (problems.length > 0) failures.push({ label: 'PR title', subject: prTitle, problems }); } diff --git a/scripts/e2e.ts b/scripts/e2e.ts index 4704271..046d849 100644 --- a/scripts/e2e.ts +++ b/scripts/e2e.ts @@ -1,5 +1,7 @@ import { spawn, type ChildProcess } from 'node:child_process'; import { mkdtempSync, rmSync } from 'node:fs'; +import { request as httpRequest } from 'node:http'; +import { createServer as createNetServer } from 'node:net'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -74,6 +76,151 @@ async function waitFor(url: string, timeoutMs = 30_000): Promise { 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'); + return body.total; +} + +async function waitForLogTotal(expected: number, timeoutMs = 5_000): Promise { + const deadline = Date.now() + timeoutMs; + let last = -1; + while (Date.now() < deadline) { + last = await logTotal(); + if (last >= expected) return last; + await sleep(100); + } + return last; +} + +interface LogRow { + id: string; + status: number; + ok: boolean; + errorCode: string | null; + attempts: number; + providerId: string | null; + providerName: string | null; + surface: string; + userAgent: string | null; +} + +/** Polls the newest log rows until one carries the marker user-agent. */ +async function findLogByUserAgent(marker: string, timeoutMs = 8_000): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const body = await adminJson<{ logs: LogRow[] }>('/logs?limit=10'); + const row = body.logs.find((log) => log.userAgent === marker); + if (row) return row; + 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'); + const originallyDisabled = body.providers.filter((provider) => !provider.enabled).map((provider) => provider.id); + try { + for (const provider of body.providers) { + const want = ids.includes(provider.id); + if (provider.enabled !== want) { + await adminJson(`/providers/${provider.id}`, { method: 'PATCH', body: { enabled: want } }); + } + } + await fn(); + } finally { + for (const provider of body.providers) { + if (originallyDisabled.includes(provider.id)) continue; + await adminJson(`/providers/${provider.id}`, { method: 'PATCH', body: { enabled: true } }); + } + } +} + +/** + * Opens a raw streaming request and destroys the socket as soon as the first byte + * arrives, so the gateway can observe a client abort mid-stream. + */ +async function abortStreamAfterFirstByte(body: unknown, marker: string, key: string): Promise { + await new Promise((resolve) => { + const payload = JSON.stringify(body); + const req = httpRequest( + { + host: '127.0.0.1', + port: PORT, + path: '/v1/chat/completions', + method: 'POST', + headers: { + 'content-type': 'application/json', + 'content-length': Buffer.byteLength(payload), + authorization: `Bearer ${key}`, + 'user-agent': marker, + }, + }, + (res) => { + res.once('data', () => { + req.destroy(); + resolve(); + }); + res.once('error', () => resolve()); + res.once('end', () => resolve()); + }, + ); + req.on('error', () => resolve()); + req.end(payload); + }); +} + +/* --------------------------------------------------------------- events feed */ + +interface SseFeed { + events: Array<{ event: string; data: Record }>; + close: () => void; +} + +/** Subscribes to `/admin/api/events` and collects decoded frames until `close()`. */ +async function openEventFeed(): Promise { + const controller = new AbortController(); + const events: Array<{ event: string; data: Record }> = []; + const response = await fetch(`${BASE}/admin/api/events`, { headers: { cookie }, signal: controller.signal }); + assert(response.ok, `events endpoint returned ${response.status}`); + const reader = response.body!.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + void (async () => { + try { + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + let index = buffer.indexOf('\n\n'); + while (index !== -1) { + const block = buffer.slice(0, index); + buffer = buffer.slice(index + 2); + const lines = block.split('\n'); + const event = lines.find((line) => line.startsWith('event:'))?.slice(6).trim(); + const data = lines.find((line) => line.startsWith('data:'))?.slice(5).trim(); + if (event && data) { + try { + events.push({ event, data: JSON.parse(data) as Record }); + } catch { + /* non-JSON frame */ + } + } + index = buffer.indexOf('\n\n'); + } + } + } catch { + /* aborted */ + } + })(); + return { events, close: () => controller.abort() }; +} + /* ------------------------------------------------------------------ children */ function collect(child: ChildProcess): string[] { @@ -88,10 +235,21 @@ function collect(child: ChildProcess): string[] { return logs; } -function startServer(dataDir: string): ChildProcess { +function startServer(dataDir: string, options: { port?: number; env?: Record } = {}): ChildProcess { return spawn(process.execPath, ['--import', 'tsx', 'src/index.ts'], { cwd: process.cwd(), - env: { ...process.env, PORT: String(PORT), HOST: '127.0.0.1', DATA_DIR: dataDir, LOG_LEVEL: 'warn', NODE_ENV: 'test' }, + env: { + ...process.env, + PORT: String(options.port ?? PORT), + HOST: '127.0.0.1', + DATA_DIR: dataDir, + LOG_LEVEL: 'warn', + NODE_ENV: 'test', + // Test-only: the deterministic mock upstreams are loopback addresses, which + // the provider SSRF guard rejects by default (see src/admin/util.ts). + PROVIDER_ALLOW_PRIVATE_HOSTS: 'true', + ...(options.env ?? {}), + }, stdio: ['ignore', 'pipe', 'pipe'], }); } @@ -127,6 +285,54 @@ async function mockStats(port: number): Promise<{ served: number; total: number return (await response.json()) as { served: number; total: number }; } +/** + * Boots a short-lived server on a free port with `PROVIDER_ALLOW_PRIVATE_HOSTS=false` + * (plus any extra env) and tears it down afterwards. Used for the SSRF guard and the + * `ROUTER_SECRET` rotation refusal, which must not run against the main harness. + */ +async function withAltServer(env: Record, fn: (base: string) => Promise): Promise { + const altDataDir = mkdtempSync(join(tmpdir(), 'okr-e2e-alt-')); + // The port is picked per run: a fixed one can collide with a stray dev server. + const port = Number(process.env.E2E_ALT_PORT ?? (await freePort())); + const base = `http://127.0.0.1:${port}`; + const child = startServer(altDataDir, { + port, + env: { PROVIDER_ALLOW_PRIVATE_HOSTS: 'false', ...env }, + }); + collect(child); + try { + await waitFor(`${base}/health`); + await fn(base); + } finally { + await stop(child); + rmSync(altDataDir, { recursive: true, force: true }); + } +} + +/** Reserves an ephemeral loopback port for an auxiliary server. */ +async function freePort(): Promise { + return new Promise((resolve, reject) => { + const server = createNetServer(); + server.on('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + const port = typeof address === 'object' && address !== null ? address.port : 0; + server.close(() => resolve(port)); + }); + }); +} + +/** 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`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ password: '123456' }), + }); + assert(response.ok, `alt login failed: ${response.status}`); + return extractCookie(response.headers.get('set-cookie')); +} + /* ----------------------------------------------------------------- admin api */ interface ApiOptions { @@ -158,14 +364,31 @@ async function adminJson>(path: string, options: Api interface GatewayOptions { key?: string | null; body: unknown; + /** Send the key as `x-api-key` instead of `Authorization: Bearer`. */ + xApiKey?: boolean; + userAgent?: string; } async function gateway(path: string, options: GatewayOptions): Promise { const headers: Record = { 'content-type': 'application/json' }; - if (options.key !== null) headers.authorization = `Bearer ${options.key ?? gatewayKey}`; + if (options.key !== null) { + const key = options.key ?? gatewayKey; + if (options.xApiKey) headers['x-api-key'] = key; + else headers.authorization = `Bearer ${key}`; + } + if (options.userAgent) headers['user-agent'] = options.userAgent; return fetch(`${BASE}${path}`, { method: 'POST', headers, body: JSON.stringify(options.body) }); } +/** Gateway POST with a raw (not re-serialized) body, for malformed-JSON checks. */ +async function gatewayRaw(path: string, body: string, headers: Record = {}): Promise { + return fetch(`${BASE}${path}`, { + method: 'POST', + headers: { 'content-type': 'application/json', ...headers }, + body, + }); +} + function sseEvents(text: string): Array> { const events: Array> = []; for (const block of text.split('\n\n')) { @@ -213,6 +436,14 @@ async function main(): Promise { return `name=${body.name}`; }); + await check('GET /health reports a live uptimeMs', async () => { + const body = (await (await fetch(`${BASE}/health`)).json()) as { uptimeMs?: number; startedAt?: number }; + assert(typeof body.uptimeMs === 'number' && body.uptimeMs > 0, `uptimeMs=${body.uptimeMs}`); + assert(typeof body.startedAt === 'number', `startedAt=${body.startedAt}`); + assert(body.uptimeMs <= Date.now() - body.startedAt + 1_000, 'uptimeMs is not derived from startedAt'); + return `uptimeMs=${body.uptimeMs}`; + }); + await check('GET / redirects to /dashboard, which redirects to /login when signed out', async () => { const root = await fetch(`${BASE}/`, { redirect: 'manual' }); assert(root.status === 302, `expected 302 from /, got ${root.status}`); @@ -305,6 +536,35 @@ async function main(): Promise { return `ok, ${body.models} models, ${body.latencyMs}ms`; }); + await check('provider draft test accepts an optional id and reuses the stored key', async () => { + const body = await adminJson<{ ok: boolean; models: number }>('/providers/test', { + body: { id: 'primary', baseUrl: MOCK_A }, + }); + assert(body.ok === true, `draft test failed: ${JSON.stringify(body)}`); + assert(body.models === 3, `expected 3 models, got ${body.models}`); + return 'draft baseUrl + stored key accepted'; + }); + + await check('provider test failure is recorded on the provider row', async () => { + await adminJson('/providers', { + body: { id: 'probe-dead', name: 'Probe Dead', baseUrl: DEAD_UPSTREAM, apiKey: MOCK_KEY, enabled: false, priority: 99 }, + }); + try { + const test = await adminJson<{ ok: boolean; error: string | null }>('/providers/probe-dead/test', { method: 'POST' }); + assert(test.ok === false, `expected a failed probe, got ${JSON.stringify(test)}`); + const list = await adminJson<{ providers: Array<{ id: string; failureCount: number; lastError: string | null }> }>( + '/providers', + ); + const row = list.providers.find((provider) => provider.id === 'probe-dead'); + assert(row, 'probe-dead disappeared from /providers'); + assert(row.failureCount >= 1, `failureCount=${row.failureCount}`); + assert(row.lastError !== null && row.lastError.length > 0, 'lastError was not recorded'); + return `ok=false, failureCount=${row.failureCount}`; + } finally { + await adminJson('/providers/probe-dead', { method: 'DELETE' }); + } + }); + await check('sync models from provider', async () => { const body = await adminJson<{ total: number; added: number }>('/models/sync', { body: { providerId: 'primary' } }); assert(body.total === 3, `expected 3 models, got ${body.total}`); @@ -351,14 +611,149 @@ async function main(): Promise { return '404 model_not_found'; }); + await check('gateway rejects a request with no key: 401 missing_api_key', async () => { + const response = await gateway('/v1/chat/completions', { + key: null, + body: { model: MODEL, messages: [{ role: 'user', content: 'hi' }] }, + }); + const body = (await response.json()) as { error?: { code?: string } }; + assert(response.status === 401, `expected 401, got ${response.status}`); + assert(body.error?.code === 'missing_api_key', `unexpected code ${body.error?.code}`); + return '401 missing_api_key'; + }); + + await check('gateway accepts the x-api-key header', async () => { + const response = await gateway('/v1/chat/completions', { + xApiKey: true, + 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 200, got ${response.status}`); + assert( + (body.choices?.[0]?.message?.content ?? '').includes('mock'), + `unexpected body ${JSON.stringify(body).slice(0, 150)}`, + ); + return 'x-api-key accepted'; + }); + + 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. + await sleep(200); + const marker = `e2e-reject-${Date.now()}`; + try { + const before = await logTotal(); + const response = await gatewayRaw('/v1/chat/completions', '{"model":', { 'user-agent': marker }); + 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); + assert(after === before + 1, `expected exactly one new log row, delta=${after - before}`); + const deadline = Date.now() + 3_000; + while (Date.now() < deadline) { + if (feed.events.some((event) => event.event === 'request:end')) break; + await sleep(100); + } + const starts = feed.events.filter((event) => event.event === 'request:start'); + const ends = feed.events.filter((event) => event.event === 'request:end'); + assert(starts.length === 1, `expected 1 request:start, got ${starts.length}`); + assert(ends.length === 1, `expected 1 request:end, got ${ends.length}`); + const startId = String(starts[0]!.data.id); + const endId = String((ends[0]!.data as { log?: { id?: string } }).log?.id ?? ''); + assert(startId === endId, `start/end ids differ: ${startId} vs ${endId || 'none'}`); + return `401 missing_api_key, log delta 1, start/end ${startId.slice(0, 8)}`; + } finally { + feed.close(); + } + }); + + await check('authenticated malformed JSON: 400 invalid_request_error and one log row', async () => { + const before = await logTotal(); + const response = await gatewayRaw('/v1/chat/completions', '{"model":', { + authorization: `Bearer ${gatewayKey}`, + }); + 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); + assert(after === before + 1, `expected exactly one new log row, delta=${after - before}`); + return '400 invalid_request, log delta 1'; + }); + + await check('key rotate issues a new plaintext and invalidates the old one', async () => { + const created = await adminJson<{ key: { id: string; requestCount: number }; plaintext: string }>('/keys', { + body: { name: 'rotate-e2e' }, + }); + const oldKey = created.plaintext; + try { + const rotated = await adminJson<{ key: { id: string; requestCount: number }; plaintext: string }>( + `/keys/${created.key.id}/rotate`, + { method: 'POST' }, + ); + assert(rotated.plaintext.startsWith('okr-'), `unexpected plaintext ${rotated.plaintext}`); + assert(rotated.plaintext !== oldKey, 'rotate returned the same plaintext'); + assert(rotated.key.id === created.key.id, 'rotate changed the key id'); + const oldResponse = await gateway('/v1/chat/completions', { + key: oldKey, + body: { model: MODEL, messages: [{ role: 'user', content: 'hi' }] }, + }); + assert(oldResponse.status === 401, `old key still works (${oldResponse.status})`); + const newResponse = await gateway('/v1/chat/completions', { + key: rotated.plaintext, + body: { model: MODEL, messages: [{ role: 'user', content: 'ping' }], max_tokens: 8 }, + }); + assert(newResponse.ok, `rotated key rejected (${newResponse.status})`); + return `old 401, new 200, id=${rotated.key.id.slice(0, 8)}`; + } finally { + await adminJson(`/keys/${created.key.id}`, { method: 'DELETE' }); + } + }); + + await check('DELETE /admin/api/keys/:id unknown id → 404 key_not_found', async () => { + const response = await admin('/keys/does-not-exist', { method: 'DELETE' }); + const body = (await response.json()) as { error?: { code?: string } }; + assert(response.status === 404, `expected 404, got ${response.status}`); + assert(body.error?.code === 'key_not_found', `unexpected code ${body.error?.code}`); + return '404 key_not_found'; + }); + await check('GET /v1/models returns OpenAI list with metadata', async () => { + const before = await logTotal(); const response = await fetch(`${BASE}/v1/models`, { headers: { authorization: `Bearer ${gatewayKey}` } }); const body = (await response.json()) as { object: string; data: Array> }; assert(response.ok, `status ${response.status}`); assert(body.object === 'list', 'object must be list'); assert(body.data.length === 3, `expected 3 models, got ${body.data.length}`); assert(typeof body.data[0]!.reasoning === 'object', 'expected reasoning metadata'); - return `${body.data.length} models`; + 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); + assert(after === before + 1, `expected one log row for /v1/models, delta=${after - before}`); + return `${body.data.length} models, request-id + 1 log row`; + }); + + await check('GET /v1/models/:id returns the model with a router request id', async () => { + const response = await fetch(`${BASE}/v1/models/${MODEL}`, { + headers: { authorization: `Bearer ${gatewayKey}` }, + }); + const body = (await response.json()) as { id?: string; object?: string }; + assert(response.ok, `status ${response.status}`); + assert(body.id === MODEL, `unexpected id ${body.id}`); + assert(response.headers.get('x-opencode-router-request-id'), 'missing router request id header'); + return `200 ${body.id}`; + }); + + await check('GET /v1/models/:id unknown → 404 model_not_found + log row', async () => { + const before = await logTotal(); + const response = await fetch(`${BASE}/v1/models/opencode/does-not-exist`, { + headers: { authorization: `Bearer ${gatewayKey}` }, + }); + 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); + assert(after === before + 1, `expected one log row, delta=${after - before}`); + return '404 model_not_found + 1 log row'; }); /* ------------------------------------------------ OpenAI chat completions */ @@ -610,6 +1005,64 @@ async function main(): Promise { return 'hint stripped'; }); + /* -------------------------------------------------------- availability gates */ + await check('503 no_provider_configured when every provider is disabled', async () => { + const providers = await adminJson<{ providers: Array<{ id: string }> }>('/providers'); + try { + for (const provider of providers.providers) { + await adminJson(`/providers/${provider.id}`, { method: 'PATCH', body: { enabled: false } }); + } + const response = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'hi' }] }, + }); + const body = (await response.json()) as { error?: { code?: string } }; + assert(response.status === 503, `expected 503, got ${response.status}`); + assert(body.error?.code === 'no_provider_configured', `unexpected code ${body.error?.code}`); + return '503 no_provider_configured'; + } finally { + for (const provider of providers.providers) { + await adminJson(`/providers/${provider.id}`, { method: 'PATCH', body: { enabled: true } }); + } + } + }); + + await check('503 no_models_configured when every model is disabled', async () => { + const models = await adminJson<{ models: Array<{ id: string }> }>('/models'); + const ids = models.models.map((model) => model.id); + try { + const bulk = await adminJson<{ updated: number }>('/models/bulk', { body: { action: 'disable', ids } }); + assert(bulk.updated === ids.length, `expected ${ids.length} disabled, got ${bulk.updated}`); + const response = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'hi' }] }, + }); + const body = (await response.json()) as { error?: { code?: string } }; + assert(response.status === 503, `expected 503, got ${response.status}`); + assert(body.error?.code === 'no_models_configured', `unexpected code ${body.error?.code}`); + return '503 no_models_configured'; + } finally { + const restored = await adminJson<{ updated: number }>('/models/bulk', { body: { action: 'enable', ids } }); + assert(restored.updated === ids.length, `failed to restore ${ids.length} models`); + } + }); + + await check('model_allow_unknown=true lets an unknown model through', async () => { + await adminJson('/settings', { method: 'PATCH', body: { model_allow_unknown: 'true' } }); + try { + const response = await gateway('/v1/chat/completions', { + body: { model: 'opencode/unknown-e2e-model', messages: [{ role: 'user', content: 'ping' }], max_tokens: 8 }, + }); + const body = (await response.json()) as { choices?: Array<{ message?: { content?: string } }>; error?: unknown }; + assert(response.ok, `expected 200, got ${response.status}: ${JSON.stringify(body).slice(0, 150)}`); + assert( + (body.choices?.[0]?.message?.content ?? '').includes('mock'), + 'unknown model was not proxied to the mock upstream', + ); + return 'unknown model served by mock'; + } finally { + await adminJson('/settings', { method: 'PATCH', body: { model_allow_unknown: 'false' } }); + } + }); + /* ------------------------------------------------------------------ rotation */ await check('add second provider (secondary → mockB)', async () => { const body = await adminJson<{ provider: { id: string } }>('/providers', { @@ -639,6 +1092,54 @@ async function main(): Promise { return `A=${a.served} B=${b.served}`; }); + /* ------------------------------------------------------------ stream fidelity */ + await check('streaming forwards invalid UTF-8 and a leading BOM byte-for-byte', async () => { + await mockControl(MOCK_A_PORT, { reset: true }); + await mockControl(MOCK_A_PORT, { fidelityFrames: true }); + try { + await withOnlyProviders(['primary'], async () => { + const response = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'ping' }], stream: true, max_tokens: 8 }, + }); + assert(response.ok, `status ${response.status}`); + const bytes = Buffer.from(await response.arrayBuffer()); + assert( + bytes.subarray(0, 3).equals(Buffer.from([0xef, 0xbb, 0xbf])), + `expected a leading UTF-8 BOM, got ${bytes.subarray(0, 3).toString('hex')}`, + ); + const comment = Buffer.from([0x3a, 0x20, 0x80, 0x0a, 0x0a]); + assert(bytes.includes(comment), 'the lone 0x80 byte was re-encoded (invalid UTF-8 not preserved)'); + assert(bytes.toString('utf8').includes('chat.completion.chunk'), 'SSE frames missing from the forwarded body'); + return `${bytes.length} bytes: BOM + 0x80 preserved`; + }); + } finally { + await mockControl(MOCK_A_PORT, { reset: true }); + } + }); + + await check('client abort mid-stream is logged as 499 client_aborted', async () => { + await mockControl(MOCK_A_PORT, { reset: true }); + await mockControl(MOCK_A_PORT, { frameDelayMs: 400 }); + const marker = `e2e-abort-${Date.now()}`; + try { + await withOnlyProviders(['primary'], async () => { + await abortStreamAfterFirstByte( + { model: MODEL, messages: [{ role: 'user', content: 'Count from 1 to 3.' }], stream: true, max_tokens: 40 }, + marker, + gatewayKey, + ); + }); + const row = await findLogByUserAgent(marker); + if (!row) return 'skipped: 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'); + return `status=499 errorCode=client_aborted`; + } finally { + await mockControl(MOCK_A_PORT, { reset: true }); + } + }); + /* ------------------------------------------------------------------ failover */ await check('dead-provider failover still serves the request', async () => { @@ -705,6 +1206,79 @@ async function main(): Promise { } }); + await check('cooldown-skipped providers add no attempt row and attempts matches the header', async () => { + await mockControl(MOCK_A_PORT, { reset: true }); + await mockControl(MOCK_B_PORT, { reset: true }); + await mockControl(MOCK_A_PORT, { failAfter: 0 }); + await adminJson('/providers', { body: { id: 'cd-flaky', name: 'CD Flaky', baseUrl: MOCK_A, apiKey: MOCK_KEY, priority: 1 } }); + await adminJson('/providers', { body: { id: 'cd-healthy', name: 'CD Healthy', baseUrl: MOCK_B, apiKey: MOCK_KEY, priority: 2 } }); + try { + let detail = ''; + await withOnlyProviders(['cd-flaky', 'cd-healthy'], async () => { + // Request 1 fails over once (cd-flaky 429 → cooldown, cd-healthy serves). + await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'warm the cooldown' }], max_tokens: 8 }, + }); + // Requests 2 and 3 must skip the cooling provider without inventing attempts. + for (let index = 0; index < 2; index += 1) { + const response = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: `cooled ${index}` }], max_tokens: 8 }, + }); + assert(response.ok, `expected success, got ${response.status}`); + const attemptsHeader = Number(response.headers.get('x-opencode-router-attempts')); + const requestId = response.headers.get('x-opencode-router-request-id'); + assert(requestId, 'missing x-opencode-router-request-id'); + assert(attemptsHeader === 1, `expected 1 attempt while cd-flaky cools, got ${attemptsHeader}`); + const row = await adminJson<{ log: { attempts: number }; attempts: Array<{ errorCode: string | null }> }>( + `/logs/${requestId}`, + ); + assert(row.attempts.length === attemptsHeader, `timeline ${row.attempts.length} != header ${attemptsHeader}`); + assert( + row.attempts.every((attempt) => attempt.errorCode !== 'provider_cooldown'), + 'cooldown-skipped provider was written as an attempt row', + ); + assert(row.log.attempts === attemptsHeader, `log attempts ${row.log.attempts} != header ${attemptsHeader}`); + detail = `attempts=1, ${row.attempts.length} timeline row, no provider_cooldown`; + } + }); + return detail; + } finally { + await adminJson('/providers/cd-flaky', { method: 'DELETE' }); + await adminJson('/providers/cd-healthy', { method: 'DELETE' }); + await mockControl(MOCK_A_PORT, { reset: true }); + } + }); + + 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 }); + await adminJson('/settings', { method: 'PATCH', body: { provider_cooldown_ms: '1000' } }); + await adminJson('/providers', { body: { id: 'ra-provider', name: 'RA Provider', baseUrl: MOCK_A, apiKey: MOCK_KEY, priority: 1 } }); + try { + await withOnlyProviders(['ra-provider'], async () => { + const response = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'retry after' }], max_tokens: 8 }, + }); + 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}`); + const list = await adminJson<{ providers: Array<{ id: string; cooldownUntil: number | null }> }>('/providers'); + const row = list.providers.find((provider) => provider.id === 'ra-provider'); + assert(row?.cooldownUntil !== null && row?.cooldownUntil !== undefined, 'no cooldown was recorded'); + const remaining = row.cooldownUntil - Date.now(); + assert( + remaining > 1_200 && remaining < 3_000, + `cooldown=${remaining}ms; expected ~2000ms from retry-after, not the 1000ms setting or the 60s default`, + ); + return `cooldownUntil in ${remaining}ms (retry-after 2s > 1s setting)`; + }); + } finally { + await mockControl(MOCK_A_PORT, { reset: true }); + await adminJson('/providers/ra-provider', { method: 'DELETE' }); + await adminJson('/settings', { method: 'PATCH', body: { provider_cooldown_ms: '60000' } }); + } + }); + await check('all providers dead → 502 all_providers_failed', async () => { await adminJson('/providers/primary', { method: 'PATCH', body: { baseUrl: DEAD_UPSTREAM } }); await adminJson('/providers/secondary', { method: 'PATCH', body: { baseUrl: DEAD_UPSTREAM } }); @@ -743,7 +1317,14 @@ async function main(): Promise { await check('logs captured with tokens, surfaces and attempts', async () => { const body = await adminJson<{ total: number; - logs: Array<{ totalTokens: number; ok: boolean; surface: string; attempts: number; providerName: string | null }>; + logs: Array<{ + totalTokens: number; + ok: boolean; + surface: string; + attempts: number; + providerId: string | null; + providerName: string | null; + }>; }>('/logs?limit=200'); assert(body.total > 20, `expected >20 logs, got ${body.total}`); assert(body.logs.some((log) => log.totalTokens > 0), 'expected token usage on logs'); @@ -751,28 +1332,42 @@ async function main(): Promise { const surfaces = new Set(body.logs.map((log) => log.surface)); assert(surfaces.has('chat') && surfaces.has('responses') && surfaces.has('messages'), 'missing surfaces'); assert( - body.logs.filter((log) => log.ok).every((log) => log.providerName !== null), - 'expected provider attribution on successful rows', + 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}`; + return `total=${body.total} (${modelsRows.length} models rows)`; }); await check('stats overview aggregates traffic', async () => { - const body = await adminJson<{ totals: { requests: number; tokensTotal: number; successRate: number }; series: unknown[] }>( - '/stats?window=24h', - ); + const body = await adminJson<{ + totals: { requests: number; tokensTotal: number; successRate: number }; + requestsLast60s: number; + errorsLast60s: number; + series: unknown[]; + }>('/stats?window=24h'); assert(body.totals.requests > 20, `expected requests > 20, got ${body.totals.requests}`); assert(body.totals.tokensTotal > 0, 'expected token totals'); assert(body.totals.successRate > 0.5, `success rate too low: ${body.totals.successRate}`); - return `requests=${body.totals.requests} tokens=${body.totals.tokensTotal} success=${body.totals.successRate.toFixed(2)}`; + assert(Number.isInteger(body.requestsLast60s) && body.requestsLast60s > 0, `requestsLast60s=${body.requestsLast60s}`); + assert(Number.isInteger(body.errorsLast60s) && body.errorsLast60s >= 0, `errorsLast60s=${body.errorsLast60s}`); + assert(body.errorsLast60s < body.requestsLast60s, 'errorsLast60s cannot exceed requestsLast60s'); + return `requests=${body.totals.requests} tokens=${body.totals.tokensTotal} last60s=${body.requestsLast60s}/${body.errorsLast60s}`; }); await check('request detail exposes attempt timeline', async () => { - const logs = await adminJson<{ logs: Array<{ id: string }> }>('/logs?limit=1'); - const id = logs.logs[0]?.id; - assert(id, 'no log rows'); - const detail = await adminJson<{ attempts: Array<{ providerId: string; ok: boolean }> }>(`/logs/${id}`); + const logs = await adminJson<{ logs: Array<{ id: string; attempts: number }> }>('/logs?limit=50'); + const target = logs.logs.find((log) => log.attempts > 0); + assert(target, 'no proxied log rows with attempts recorded'); + const detail = await adminJson<{ attempts: Array<{ providerId: string; ok: boolean }> }>(`/logs/${target.id}`); assert(detail.attempts.length > 0, 'no attempts recorded'); + assert(detail.attempts.length === target.attempts, `timeline ${detail.attempts.length} != log attempts ${target.attempts}`); return `attempts=${detail.attempts.length}`; }); @@ -818,6 +1413,32 @@ async function main(): Promise { return 'retention=7, hash hidden'; }); + await check('PATCH /settings ignores inherited prototype keys', async () => { + const body = await adminJson<{ ignored: string[]; changed: string[]; settings: Record }>('/settings', { + method: 'PATCH', + body: { constructor: 7, toString: 9, log_store_bodies: true }, + }); + assert(body.ignored.includes('constructor'), `constructor not ignored: ${JSON.stringify(body.ignored)}`); + assert(body.ignored.includes('toString'), `toString not ignored: ${JSON.stringify(body.ignored)}`); + assert(body.ignored.includes('log_store_bodies'), 'the removed log_store_bodies setting must be ignored'); + assert( + !Object.prototype.hasOwnProperty.call(body.settings, 'constructor'), + 'constructor was persisted as a setting', + ); + assert(body.changed.length === 0, `unexpectedly changed ${body.changed.join(',')}`); + return `ignored=${body.ignored.join(',')}`; + }); + + await check('log query validation rejects junk filters', async () => { + const since = await admin('/logs?since=not-a-date'); + const sinceBody = (await since.json()) as { error?: { code?: string } }; + assert(since.status === 400, `expected 400 for since=not-a-date, got ${since.status}`); + assert(sinceBody.error?.code === 'invalid_request', `unexpected code ${sinceBody.error?.code}`); + const limit = await admin('/logs?limit=2.9'); + assert(limit.status === 400, `expected 400 for a fractional limit, got ${limit.status}`); + return '400 invalid_request for since + fractional limit'; + }); + await check('password change → new login → revert', async () => { const change = await admin('/settings/password', { method: 'POST', @@ -845,6 +1466,70 @@ async function main(): Promise { return `json + csv ok (${text.split('\n').length} lines)`; }); + await check('CSV export neutralises formula injection from a user-agent', async () => { + const marker = '=1+1'; + const sent = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'ping' }], max_tokens: 8 }, + userAgent: marker, + }); + assert(sent.ok, `gateway request failed: ${sent.status}`); + const deadline = Date.now() + 3_000; + let logged = false; + while (Date.now() < deadline && !logged) { + const rows = await adminJson<{ logs: Array<{ userAgent: string | null }> }>('/logs?limit=10'); + logged = rows.logs.some((row) => row.userAgent === marker); + if (!logged) await sleep(100); + } + assert(logged, 'the gateway request with the marker user-agent was not logged'); + const csv = await admin('/logs/export?format=csv'); + const text = await csv.text(); + assert(csv.ok, `csv export ${csv.status}`); + const line = text.split('\r\n').find((entry) => entry.includes(marker)); + assert(line, 'marker user-agent missing from the CSV export'); + assert(line.includes(`'${marker}`), `formula cell was not prefixed with a quote: ${line}`); + assert(csv.headers.get('x-export-truncated') === null, 'unexpected truncation header below the 500-row cap'); + const json = await admin('/logs/export?format=json'); + const payload = (await json.json()) as { count: number; total: number; truncated: boolean }; + assert(payload.truncated === false, 'export claims truncation with fewer than 500 rows'); + assert(payload.count === payload.total, `count ${payload.count} != total ${payload.total}`); + return `'${marker} escaped; count=total=${payload.count}, truncated=false`; + }); + + await check('SSRF guard rejects loopback provider URLs without PROVIDER_ALLOW_PRIVATE_HOSTS', async () => { + let detail = ''; + await withAltServer({}, async (base) => { + const altCookie = await altLogin(base); + const response = await fetch(`${base}/admin/api/providers/test`, { + method: 'POST', + headers: { 'content-type': 'application/json', cookie: altCookie }, + body: JSON.stringify({ baseUrl: `http://127.0.0.1:${MOCK_A_PORT}/v1`, apiKey: 'x' }), + }); + const body = (await response.json()) as { error?: { code?: string; message?: string } }; + assert(response.status === 400, `expected 400, got ${response.status}: ${JSON.stringify(body)}`); + assert(body.error?.code === 'invalid_request', `unexpected code ${body.error?.code}`); + detail = '400 invalid_request (loopback provider refused)'; + }); + return detail; + }); + + 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) => { + const altCookie = await altLogin(base); + const rotate = await fetch(`${base}/admin/api/settings/rotate-secret`, { + method: 'POST', + headers: { cookie: altCookie }, + }); + const body = (await rotate.json()) as { error?: { code?: string } }; + assert(rotate.status === 409, `expected 409, got ${rotate.status}: ${JSON.stringify(body)}`); + assert(body.error?.code === 'secret_from_env', `unexpected code ${body.error?.code}`); + const after = await fetch(`${base}/admin/api/bootstrap`, { headers: { cookie: altCookie } }); + assert(after.ok, `the refused rotation deleted sessions (bootstrap ${after.status})`); + detail = '409 secret_from_env, session intact'; + }); + return detail; + }); + await check('logout invalidates session', async () => { const logout = await admin('/logout', { method: 'POST' }); assert(logout.ok, `logout failed: ${logout.status}`); @@ -863,6 +1548,23 @@ async function main(): Promise { assert(actions.has('provider.create'), `expected provider.create in audit, got ${[...actions].slice(0, 5).join(',')}`); return `${body.items.length} entries`; }); + + await check('revoke-all sessions covers more than 50 sessions', async () => { + const cookies: string[] = []; + for (let index = 0; index < 55; index += 1) { + const response = await admin('/login', { body: { password: '123456' }, auth: false }); + assert(response.ok, `login ${index} failed: ${response.status}`); + cookies.push(extractCookie(response.headers.get('set-cookie'))); + } + const revoke = await adminJson<{ ok: boolean; revoked: number }>('/settings/sessions', { method: 'DELETE' }); + assert(revoke.ok === true, 'revoke-all did not report ok'); + assert(revoke.revoked >= 55, `expected >=55 revoked sessions, got ${revoke.revoked}`); + const stale = await fetch(`${BASE}/admin/api/bootstrap`, { headers: { cookie: cookies[0]! } }); + assert(stale.status === 401, `an old session cookie still works (${stale.status})`); + const current = await admin('/bootstrap'); + assert(current.ok, `the current session was revoked (${current.status})`); + return `revoked=${revoke.revoked}, stale cookie 401, current session intact`; + }); } finally { for (const child of children.reverse()) await stop(child); rmSync(dataDir, { recursive: true, force: true }); diff --git a/scripts/mock-upstream.ts b/scripts/mock-upstream.ts index 95b6333..beeb722 100644 --- a/scripts/mock-upstream.ts +++ b/scripts/mock-upstream.ts @@ -49,11 +49,26 @@ interface Control { failAfter: number | null; alwaysStatus: number | null; delayMs: number; + /** When set, every request gets 429 + `retry-after: ` (FEAT-01 e2e). */ + retryAfterSeconds: number | null; + /** Delay between SSE frames in the chat stream (client-abort / slow-consumer e2e). */ + frameDelayMs: number; + /** Prefix the chat stream with raw bytes: a UTF-8 BOM + a comment line holding a lone 0x80. */ + fidelityFrames: boolean; served: number; total: number; } -const control: Control = { failAfter: null, alwaysStatus: null, delayMs: 0, served: 0, total: 0 }; +const control: Control = { + failAfter: null, + alwaysStatus: null, + delayMs: 0, + retryAfterSeconds: null, + frameDelayMs: 0, + fidelityFrames: false, + served: 0, + total: 0, +}; const authFailures: string[] = []; function json(res: ServerResponse, status: number, payload: unknown): void { @@ -175,6 +190,18 @@ function reasoningRequested(body: Record, surface: 'chat' | 're async function gate(res: ServerResponse): Promise { control.total += 1; + if (control.retryAfterSeconds !== null) { + const body = JSON.stringify({ + error: { message: `mock retry-after ${control.retryAfterSeconds}s`, type: 'rate_limit_error', code: 'provider.free-limit' }, + }); + res.writeHead(429, { + 'content-type': 'application/json', + 'content-length': Buffer.byteLength(body), + 'retry-after': String(control.retryAfterSeconds), + }); + res.end(body); + return false; + } if (control.alwaysStatus !== null) { json(res, control.alwaysStatus, { error: { message: `mock forced status ${control.alwaysStatus}`, type: 'rate_limit_error', code: 'provider.free-limit' }, @@ -257,6 +284,13 @@ async function handleChat(req: IncomingMessage, res: ServerResponse): Promise 0) await sleep(control.frameDelayMs); sse(res, null, { id: 'chatcmpl-mock', object: 'chat.completion.chunk', @@ -274,6 +309,7 @@ async function handleChat(req: IncomingMessage, res: ServerResponse): Promise 0) await sleep(control.frameDelayMs); sse(res, null, { id: 'chatcmpl-mock', object: 'chat.completion.chunk', @@ -527,10 +563,16 @@ const server = createServer(async (req, res) => { control.failAfter = null; control.alwaysStatus = null; control.delayMs = 0; + control.retryAfterSeconds = null; + control.frameDelayMs = 0; + control.fidelityFrames = false; } if (body.failAfter !== undefined) control.failAfter = body.failAfter; if (body.alwaysStatus !== undefined) control.alwaysStatus = body.alwaysStatus; if (body.delayMs !== undefined) control.delayMs = body.delayMs; + if (body.retryAfterSeconds !== undefined) control.retryAfterSeconds = body.retryAfterSeconds; + if (body.frameDelayMs !== undefined) control.frameDelayMs = body.frameDelayMs; + if (body.fidelityFrames !== undefined) control.fidelityFrames = body.fidelityFrames; json(res, 200, { ...control, authFailures: authFailures.slice(-5) }); return; } diff --git a/src/admin/auth.ts b/src/admin/auth.ts index d6d4dc4..45a140e 100644 --- a/src/admin/auth.ts +++ b/src/admin/auth.ts @@ -5,7 +5,7 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; import type { AppContext } from '../core/context.js'; import { verifyDashboardPassword } from '../core/seed.js'; -import { ADMIN_VERSION, HttpError, asString, audit, clientIp, jsonBody, userAgent } from './util.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; @@ -92,7 +92,7 @@ export function createAuthGuard(ctx: AppContext) { } export function registerAuthRoutes(scope: FastifyInstance, ctx: AppContext): void { - scope.post('/login', async (request, reply) => { + scope.post('/login', { bodyLimit: ADMIN_CREDENTIAL_BODY_LIMIT }, async (request, reply) => { const ip = clientIp(request) ?? 'unknown'; pruneAttempts(); const limited = checkLoginRateLimit(ip); @@ -104,6 +104,7 @@ export function registerAuthRoutes(scope: FastifyInstance, ctx: AppContext): voi const body = jsonBody(request); const password = asString(body.password); if (!password) throw new HttpError(400, 'invalid_request', 'password is required'); + assertPasswordLength(password, 'password'); if (!verifyDashboardPassword(ctx, password)) { recordLoginFailure(ip); diff --git a/src/admin/index.ts b/src/admin/index.ts index f3f69fb..3add8d4 100644 --- a/src/admin/index.ts +++ b/src/admin/index.ts @@ -29,7 +29,10 @@ export async function registerAdminRoutes(app: FastifyInstance, ctx: AppContext) ? error.code : ((error as { code?: string }).code ?? (status >= 500 ? 'internal_error' : 'invalid_request')); if (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' } }); + return; } const message = error instanceof Error ? error.message : String(error); void reply.status(status).send({ error: { message, code } }); diff --git a/src/admin/keys.ts b/src/admin/keys.ts index 95a7c28..2e089b3 100644 --- a/src/admin/keys.ts +++ b/src/admin/keys.ts @@ -5,6 +5,7 @@ import type { FastifyInstance } from 'fastify'; import type { AppContext } from '../core/context.js'; import type { ApiKeyRow } from '../types.js'; +import { generateApiKey } from '../util/crypto.js'; import { HttpError, asBool, audit, fail, jsonBody, requireString } from './util.js'; export interface ApiKeyView { @@ -77,9 +78,23 @@ export function registerKeyRoutes(scope: FastifyInstance, ctx: AppContext): void return { key: apiKeyView(revoked) }; }); + // FEAT-05: replace the secret material while keeping the row identity, so + // request counts and audit history survive. Disabled keys are rotated too — + // only an unknown id is an error. + scope.post('/keys/:id/rotate', async (request) => { + const id = (request.params as { id: string }).id; + const existing = loadKey(ctx, id); + 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}`); + return { key: apiKeyView(rotated), plaintext }; + }); + scope.delete('/keys/:id', async (request) => { 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}`); return { ok: true }; }); diff --git a/src/admin/logs.ts b/src/admin/logs.ts index 310df2b..7bf5c05 100644 --- a/src/admin/logs.ts +++ b/src/admin/logs.ts @@ -69,8 +69,10 @@ export function registerLogRoutes(scope: FastifyInstance, ctx: AppContext): void query.limit = 500; query.offset = 0; 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}`); + if (truncated) reply.header('x-export-truncated', 'true'); if (format === 'csv') { reply .header('content-type', 'text/csv; charset=utf-8') @@ -80,7 +82,9 @@ export function registerLogRoutes(scope: FastifyInstance, ctx: AppContext): void reply .header('content-type', 'application/json; charset=utf-8') .header('content-disposition', `attachment; filename="opencode-router-logs-${stamp}.json"`); - return reply.send(JSON.stringify({ exportedAt: Date.now(), total, count: rows.length, logs: rows }, null, 2)); + return reply.send( + JSON.stringify({ exportedAt: Date.now(), total, count: rows.length, truncated, logs: rows }, null, 2), + ); }); scope.get('/logs/:id', async (request) => { diff --git a/src/admin/models.ts b/src/admin/models.ts index 9d78752..2a89f83 100644 --- a/src/admin/models.ts +++ b/src/admin/models.ts @@ -147,6 +147,13 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo throw new HttpError(502, 'sync_failed', error instanceof Error ? error.message : String(error)); } ctx.repo.recordProviderSuccess(provider.id, result.latencyMs); + ctx.events.emitProvider({ + providerId: provider.id, + state: 'ok', + status: 200, + message: null, + ts: Date.now(), + }); audit( ctx, 'model.sync', diff --git a/src/admin/providers.ts b/src/admin/providers.ts index 7d7df9f..35346d0 100644 --- a/src/admin/providers.ts +++ b/src/admin/providers.ts @@ -10,6 +10,7 @@ import { asBool, asInt, asString, + assertPublicProviderUrl, audit, fail, httpBaseUrl, @@ -17,7 +18,7 @@ import { maskApiKey, requireString, } from './util.js'; -import { probeProvider, syncProviderModels } from './sync.js'; +import { probeAndRecord, probeProvider, recordProbeSuccess, syncFailureMessage, syncProviderModels } from './sync.js'; export interface ProviderView { id: string; @@ -72,6 +73,17 @@ function loadProvider(ctx: AppContext, id: string): ProviderRow { return provider; } +/** Cooldown applied to a provider that just failed a probe/sync. */ +function cooldownMs(ctx: AppContext): number { + const configured = ctx.repo.getInt('provider_cooldown_ms', 60_000); + return Math.max(0, Number.isFinite(configured) ? configured : 60_000); +} + +/** Detailed probe failures belong in the server log, never in the HTTP response. */ +function logProbeFailure(ctx: AppContext, providerId: string, detail: string, status: number): void { + ctx.logger?.warn?.({ providerId, status, detail }, 'provider probe failed'); +} + export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): void { scope.get('/providers', async () => ({ providers: ctx.repo.listProviders().map(providerView), @@ -81,6 +93,7 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): const body = jsonBody(request); const name = requireString(body.name, 'name'); const baseUrl = httpBaseUrl(body.baseUrl); + assertPublicProviderUrl(baseUrl, ctx.config.providerAllowPrivateHosts); const apiKey = asString(body.apiKey); if (!apiKey) fail(400, 'invalid_request', 'apiKey is required'); const enabled = body.enabled === undefined ? true : asBool(body.enabled); @@ -108,6 +121,7 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): } if (body.baseUrl !== undefined) { patch.baseUrl = httpBaseUrl(body.baseUrl); + assertPublicProviderUrl(patch.baseUrl, ctx.config.providerAllowPrivateHosts); changed.push('baseUrl'); } if (body.apiKey !== undefined) { @@ -141,32 +155,50 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): return { ok: true }; }); - // Test before save — no persisted state required. + // Test before save — no persisted state required. `id` lets the dashboard probe + // a draft `baseUrl` against the stored key when no `apiKey` was retyped (WEB-12). scope.post('/providers/test', async (request) => { const body = jsonBody(request); const baseUrl = httpBaseUrl(body.baseUrl); - const apiKey = asString(body.apiKey); - if (!apiKey) fail(400, 'invalid_request', 'apiKey is required'); + assertPublicProviderUrl(baseUrl, ctx.config.providerAllowPrivateHosts); + let apiKey = asString(body.apiKey); + if (!apiKey) { + const id = asString(body.id); + 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`); + apiKey = asString(stored.apiKey); + if (!apiKey) fail(400, 'invalid_request', 'apiKey is required'); + } const probe = await probeProvider({ baseUrl, apiKey }); + if (probe.detail !== null) ctx.logger?.warn?.({ baseUrl, detail: probe.detail }, 'provider draft test failed'); return { ok: probe.ok, status: probe.status, latencyMs: probe.latencyMs, models: probe.models.length, - error: probe.error, + error: probe.error || null, }; }); scope.post('/providers/:id/test', async (request) => { const id = (request.params as { id: string }).id; const provider = loadProvider(ctx, id); - const probe = await probeProvider({ baseUrl: provider.baseUrl, apiKey: provider.apiKey }); - if (probe.ok) { - ctx.repo.recordProviderSuccess(provider.id, probe.latencyMs); - audit(ctx, 'provider.test', provider.id, `ok models=${probe.models.length} latencyMs=${probe.latencyMs}`); - } else { - audit(ctx, 'provider.test', provider.id, `failed status=${probe.status} error=${probe.error ?? ''}`); - } + // Rows created before the SSRF guard existed are re-checked here. + assertPublicProviderUrl(provider.baseUrl, ctx.config.providerAllowPrivateHosts); + const probe = await probeAndRecord(ctx, provider, { + cooldownMs: cooldownMs(ctx), + log: (detail, failed) => logProbeFailure(ctx, provider.id, detail, failed.status), + }); + if (probe.ok) recordProbeSuccess(ctx, provider.id, probe.latencyMs, probe.status); + audit( + ctx, + 'provider.test', + provider.id, + probe.ok + ? `ok models=${probe.models.length} latencyMs=${probe.latencyMs}` + : `failed status=${probe.status} error=${probe.error ?? ''}`, + ); return { ok: probe.ok, status: probe.status, @@ -183,9 +215,24 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): try { result = await syncProviderModels(ctx, provider); } catch (error) { - throw new HttpError(502, 'sync_failed', error instanceof Error ? error.message : String(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), + ); } ctx.repo.recordProviderSuccess(provider.id, result.latencyMs); + ctx.events.emitProvider({ + providerId: provider.id, + state: 'ok', + status: 200, + message: null, + ts: Date.now(), + }); audit( ctx, 'provider.sync', diff --git a/src/admin/scheduler.ts b/src/admin/scheduler.ts index 44a4271..5e2e15f 100644 --- a/src/admin/scheduler.ts +++ b/src/admin/scheduler.ts @@ -3,22 +3,29 @@ * * - syncs provider models on the `model_sync_interval_ms` cadence when * `auto_sync_models` is enabled and an enabled provider exists; + * - probes providers whose cooldown expired and clears it when they answer again + * (FEAT-02), so a rate-limited provider is not skipped until the next sync; * - purges expired dashboard sessions every 10 minutes. * * All timers are `unref()`ed and every callback is wrapped so nothing throws * out of an interval. The returned function stops the scheduler cleanly. */ import type { AppContext } from '../core/context.js'; -import { syncProviderModels } from './sync.js'; +import { probeAndRecord, syncProviderModels } from './sync.js'; const MIN_SYNC_INTERVAL_MS = 30_000; const TICK_MS = 30_000; const SESSION_PURGE_MS = 10 * 60 * 1000; const INITIAL_SYNC_DELAY_MS = 5_000; +/** Recovery probes are cheap; cap how many run per tick so a big catalog stays calm. */ +const COOLDOWN_PROBES_PER_TICK = 3; +/** A recovery probe only needs to prove the provider answers `GET /models`. */ +const COOLDOWN_PROBE_TIMEOUT_MS = 5_000; export function startScheduler(ctx: AppContext): () => void { let stopped = false; let syncing = false; + let recovering = false; let lastSyncAt = 0; const log = (level: 'info' | 'warn', message: string, extra?: Record): void => { @@ -60,8 +67,58 @@ export function startScheduler(ctx: AppContext): () => void { } }; + /** + * FEAT-02: a provider sitting in `cooldown` with an expired `cooldown_until` is + * unreachable from the gateway. Probe it directly and clear the cooldown on + * success so traffic returns without waiting for a model sync. + */ + const maybeRecoverCooldowns = async (): Promise => { + if (stopped || recovering) return; + try { + const now = Date.now(); + const cooled = ctx.repo + .listProviders() + .filter( + (provider) => + provider.enabled && + provider.status === 'cooldown' && + provider.cooldownUntil !== null && + provider.cooldownUntil <= now, + ) + .slice(0, COOLDOWN_PROBES_PER_TICK); + if (cooled.length === 0) return; + recovering = true; + for (const provider of cooled) { + if (stopped) return; + const probe = await probeAndRecord(ctx, provider, { + cooldownMs: 0, + timeoutMs: COOLDOWN_PROBE_TIMEOUT_MS, + log: (detail) => log('warn', 'cooldown recovery probe failed', { providerId: provider.id, detail }), + }); + if (probe.ok) { + ctx.repo.updateProvider(provider.id, { cooldownUntil: null, status: 'ok' }); + ctx.events.emitProvider({ + providerId: provider.id, + state: 'ok', + status: probe.status, + message: null, + ts: Date.now(), + }); + log('info', 'provider recovered from cooldown', { providerId: provider.id, latencyMs: probe.latencyMs }); + } + } + } catch (error) { + log('warn', 'cooldown recovery sweep failed', { + error: error instanceof Error ? error.message : String(error), + }); + } finally { + recovering = false; + } + }; + const syncTimer = setInterval(() => { void maybeSync(); + void maybeRecoverCooldowns(); }, TICK_MS); syncTimer.unref(); @@ -79,6 +136,7 @@ export function startScheduler(ctx: AppContext): () => void { const initialTimer = setTimeout(() => { void maybeSync(); + void maybeRecoverCooldowns(); }, INITIAL_SYNC_DELAY_MS); initialTimer.unref(); diff --git a/src/admin/session.ts b/src/admin/session.ts index 1fa7d19..2def50f 100644 --- a/src/admin/session.ts +++ b/src/admin/session.ts @@ -58,11 +58,14 @@ export function parseSessionCookie(value: string | undefined | null): SessionCoo return { sid, expiresAt, signature }; } -export function isSecureRequest(request: FastifyRequest): boolean { +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; - return typeof value === 'string' && value.split(',')[0]?.trim().toLowerCase() === 'https'; + 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; } export function sessionCookieOptions(ctx: AppContext, request: FastifyRequest, maxAgeSeconds?: number): AdminCookieOptions { @@ -71,7 +74,7 @@ export function sessionCookieOptions(ctx: AppContext, request: FastifyRequest, m sameSite: 'lax', path: '/', maxAge: maxAgeSeconds ?? Math.floor(ctx.config.sessionTtlMs / 1000), - secure: isSecureRequest(request), + secure: isSecureRequest(request, ctx), }; } @@ -91,7 +94,7 @@ export function clearSessionCookie(ctx: AppContext, request: FastifyRequest, rep httpOnly: true, sameSite: 'lax', path: '/', - secure: isSecureRequest(request), + secure: isSecureRequest(request, ctx), }); } diff --git a/src/admin/settings.ts b/src/admin/settings.ts index 1fd324a..2d1d28d 100644 --- a/src/admin/settings.ts +++ b/src/admin/settings.ts @@ -9,22 +9,23 @@ import type { AppContext } from '../core/context.js'; import { setDashboardPassword, verifyDashboardPassword } from '../core/seed.js'; import { randomHex } from '../util/crypto.js'; import { + ADMIN_CREDENTIAL_BODY_LIMIT, ADMIN_VERSION, HttpError, activeKeyCount, asBool, asInt, asString, + assertPasswordLength, audit, fail, jsonBody, sanitizeSettings, settingTimestamp, } from './util.js'; -import { clearSessionCookie } from './session.js'; import { SETTING_MODELS_SYNC_PROVIDER_ID, SETTING_MODELS_SYNCED_AT } from './sync.js'; -const BOOL_SETTINGS = new Set(['auto_sync_models', 'log_store_bodies', 'model_allow_unknown']); +const BOOL_SETTINGS = new Set(['auto_sync_models', 'model_allow_unknown']); const INT_SETTINGS: Record = { max_retries: { min: 1, max: 10 }, @@ -47,7 +48,9 @@ function applySetting(ctx: AppContext, key: string, value: unknown): string | nu ctx.repo.setSetting(key, parsed ? 'true' : 'false'); return parsed ? 'true' : 'false'; } - const range = INT_SETTINGS[key]; + // Own-property guard: prototype keys ("constructor", "toString", ...) must not + // resolve through the prototype chain and be persisted as settings. + const range = Object.prototype.hasOwnProperty.call(INT_SETTINGS, key) ? INT_SETTINGS[key] : undefined; if (range) { const parsed = asInt(value); if (parsed === null) fail(400, 'invalid_request', `${key} must be an integer`); @@ -122,12 +125,14 @@ export function registerSettingsRoutes(scope: FastifyInstance, ctx: AppContext): return { ...settingsView(ctx), changed, ignored }; }); - scope.post('/settings/password', async (request) => { + scope.post('/settings/password', { bodyLimit: ADMIN_CREDENTIAL_BODY_LIMIT }, async (request) => { const body = jsonBody(request); const currentPassword = asString(body.currentPassword); const newPassword = asString(body.newPassword); if (!currentPassword) fail(400, 'invalid_request', 'currentPassword is required'); if (!newPassword) fail(400, 'invalid_request', 'newPassword is required'); + assertPasswordLength(currentPassword, 'currentPassword'); + assertPasswordLength(newPassword, 'newPassword'); if (newPassword.length < 4) fail(400, 'invalid_request', 'newPassword must be at least 4 characters'); if (!verifyDashboardPassword(ctx, currentPassword)) { throw new HttpError(400, 'invalid_password', 'Current password is incorrect'); @@ -137,35 +142,58 @@ export function registerSettingsRoutes(scope: FastifyInstance, ctx: AppContext): } setDashboardPassword(ctx, newPassword); const currentId = request.adminSession?.id ?? null; - let revoked = 0; - for (const session of ctx.repo.listSessions()) { - if (session.id === currentId) continue; - ctx.repo.deleteSession(session.id); - revoked += 1; - } + const revoked = ctx.repo.deleteOtherSessions(currentId); audit(ctx, 'settings.password.change', null, `revokedSessions=${revoked}`); return { ok: true, revoked }; }); scope.delete('/settings/sessions', async (request) => { const currentId = request.adminSession?.id ?? null; - let revoked = 0; - for (const session of ctx.repo.listSessions()) { - if (session.id === currentId) continue; - ctx.repo.deleteSession(session.id); - revoked += 1; - } + const revoked = ctx.repo.deleteOtherSessions(currentId); audit(ctx, 'settings.sessions.revoke', null, `revoked=${revoked}`); return { ok: true, revoked }; }); + // Per-session revoke (FEAT-03). Deleting your own session would log you out + // mid-action, so that case is a 400 and the UI asks for confirmation instead. + scope.delete('/settings/sessions/:id', async (request) => { + const id = (request.params as { id: string }).id; + const currentId = request.adminSession?.id ?? null; + if (id === currentId) { + throw new HttpError(400, 'cannot_revoke_current', 'Cannot revoke the current session; use logout instead'); + } + if (!ctx.repo.getSession(id)) { + throw new HttpError(404, 'session_not_found', `Session "${id}" not found`); + } + ctx.repo.deleteSession(id); + audit(ctx, 'settings.session.revoke', id, null); + return { ok: true, revoked: 1 }; + }); + scope.post('/settings/rotate-secret', async (request, reply) => { + // An env-provided ROUTER_SECRET always wins over /.secret at boot + // (see openDatabase), so rotating here would be silently reverted on restart: + // refuse instead of deleting every session for nothing. Detected in admin code + // because the config contract does not expose a `secretFromEnv` flag. + if ((process.env.ROUTER_SECRET ?? '').trim().length > 0) { + throw new HttpError( + 409, + 'secret_from_env', + 'ROUTER_SECRET is set; the signing secret is managed by the environment. Unset it and restart to rotate from the dashboard.', + ); + } const secret = randomHex(32); + try { + // Durable first: if the write fails nothing changes and no session is lost. + writeFileSync(resolve(ctx.config.dataDir, '.secret'), secret, { mode: 0o600 }); + } catch (error) { + ctx.logger?.error?.({ err: error }, 'failed to persist rotated signing secret'); + throw new HttpError(500, 'secret_persist_failed', 'Could not persist the new signing secret; nothing was changed'); + } ctx.db.secret = secret; - writeFileSync(resolve(ctx.config.dataDir, '.secret'), secret, { mode: 0o600 }); // Every dashboard cookie is now invalid; gateway keys are sha256(plaintext) and keep working. ctx.repo.deleteAllSessions(); - clearSessionCookie(ctx, request, reply); + reply.header('cache-control', 'no-store'); audit(ctx, 'settings.secret.rotate', null, 'dashboard sessions invalidated; gateway key hashes unchanged'); 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 b5bb6ca..c2d5bd0 100644 --- a/src/admin/stats.ts +++ b/src/admin/stats.ts @@ -5,6 +5,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 { formatSseJson } from '../util/sse.js'; import { ADMIN_VERSION, @@ -30,6 +31,34 @@ export const STATS_WINDOWS: Record = { '30d': { windowMs: 2_592_000_000, bucketMs: 21_600_000 }, }; +/** + * The dashboard polls `/stats` every 5 s while SSE clients get a 5 s heartbeat; + * `statsOverview` sorts every latency row in the window, so a 2 s TTL keeps that + * scan off the hot path without making the KPI cards visibly stale. + */ +const STATS_CACHE_TTL_MS = 2_000; + +const statsCache = new Map(); + +/** Test/ops helper: force the next `/stats` call to hit the database. */ +export function clearStatsCache(): void { + statsCache.clear(); +} + +/** How long to wait for a `drain` before treating the SSE client as stuck. */ +const DRAIN_TIMEOUT_MS = 15_000; +/** Per-client cap on frames buffered while `drain` is pending. */ +const EVENTS_QUEUE_LIMIT = 256; + +function cachedOverview(ctx: AppContext, key: string, config: WindowConfig): StatsOverview { + const now = Date.now(); + const cached = statsCache.get(key); + if (cached && now - cached.at < STATS_CACHE_TTL_MS) return cached.overview; + const overview = ctx.repo.statsOverview(config.windowMs, config.bucketMs, getActiveRequests()); + statsCache.set(key, { at: now, overview }); + return overview; +} + function windowFrom(request: FastifyRequest): { key: string; config: WindowConfig } { const requested = (queryOf(request).window as string | undefined) ?? '1h'; if (Object.prototype.hasOwnProperty.call(STATS_WINDOWS, requested)) { @@ -78,7 +107,8 @@ export function registerStatsRoutes(scope: FastifyInstance, ctx: AppContext): vo scope.get('/stats', async (request) => { const { key, config } = windowFrom(request); - const overview = ctx.repo.statsOverview(config.windowMs, config.bucketMs, getActiveRequests()); + const overview = cachedOverview(ctx, key, config); + // `overview` already carries requestsLast60s/errorsLast60s from statsOverview. return { ...overview, health: buildHealth(ctx), window: key }; }); @@ -161,14 +191,72 @@ export function registerStatsRoutes(scope: FastifyInstance, ctx: AppContext): vo }); raw.flushHeaders?.(); - const send = (event: string, payload: unknown): void => { + // Backpressure: `raw.write()` returning false means the kernel buffer is full + // (slow dashboard tab). Keep a bounded per-client queue and resume on `drain` + // instead of buffering the whole feed in memory. + const queue: string[] = []; + let draining = false; + let drainTimer: ReturnType | null = null; + let failures = 0; + let closed = false; + let cleanup: () => void; + + const flushQueue = (): void => { + draining = false; + while (!closed && queue.length > 0) { + const frame = queue.shift()!; + if (!writeNow(frame)) return; + } + }; + + const onDrain = (): void => { + if (closed) return; + if (drainTimer) { + clearTimeout(drainTimer); + drainTimer = null; + } + failures = 0; + flushQueue(); + }; + + const pauseForDrain = (): void => { + draining = true; + raw.once('drain', onDrain); + if (drainTimer) clearTimeout(drainTimer); + drainTimer = setTimeout(() => { + drainTimer = null; + failures += 1; + if (failures >= 3) { + cleanup(); + return; + } + // The client is not reading: drop what we queued so memory stays bounded. + queue.length = 0; + draining = false; + }, DRAIN_TIMEOUT_MS); + drainTimer.unref?.(); + }; + + const writeNow = (frame: string): boolean => { try { - raw.write(formatSseJson(event, payload)); + return raw.write(frame); } catch { - /* client went away; cleanup runs on close */ + cleanup(); + return false; } }; + const send = (event: string, payload: unknown): void => { + if (closed) return; + const frame = formatSseJson(event, payload); + if (draining) { + if (queue.length >= EVENTS_QUEUE_LIMIT) queue.shift(); + queue.push(frame); + return; + } + if (!writeNow(frame)) pauseForDrain(); + }; + send('stats', statsHeartbeat(ctx)); const offStart = ctx.events.onRequestStart((event) => send('request:start', event)); const offEnd = ctx.events.onRequestEnd((event) => send('request:end', event)); @@ -176,11 +264,12 @@ export function registerStatsRoutes(scope: FastifyInstance, ctx: AppContext): vo const heartbeat = setInterval(() => send('stats', statsHeartbeat(ctx)), 5_000); heartbeat.unref(); - let closed = false; - const cleanup = (): void => { + cleanup = (): void => { if (closed) return; closed = true; clearInterval(heartbeat); + if (drainTimer) clearTimeout(drainTimer); + raw.off('drain', onDrain); offStart(); offEnd(); offProvider(); diff --git a/src/admin/sync.ts b/src/admin/sync.ts index b3552ff..d40fac3 100644 --- a/src/admin/sync.ts +++ b/src/admin/sync.ts @@ -24,7 +24,10 @@ export interface ProviderProbe { status: number; latencyMs: number; models: NormalizedModel[]; - error: string | null; + /** Client-safe failure message ('' on success); never contains the response body. */ + error: string; + /** Server-side detail (upstream body excerpt); never returned to clients. */ + detail: string | null; } export interface SyncResult { @@ -38,9 +41,19 @@ export interface SyncResult { latencyMs: number; } +/** Client-facing probe failure message — deliberately generic (no body echo). */ +export function probeFailureMessage(status: number): string { + return status > 0 ? `Upstream request failed (HTTP ${status})` : 'Upstream request failed'; +} + +/** Client-facing sync failure message — same policy as `probeFailureMessage`. */ +export function syncFailureMessage(providerName: string): string { + return `Upstream request failed while syncing models for provider "${providerName}"`; +} + +/** Detailed upstream error text; kept for logs only, never sent to clients. */ function errorMessageFrom(status: number, body: string, baseUrl: string): string { - const parsed = upstreamErrorFrom(status, body, baseUrl); - return parsed.message; + return upstreamErrorFrom(status, body, baseUrl).message; } /** GETs `{baseUrl}/models` and reports success, latency and parsed models. */ @@ -62,6 +75,7 @@ export async function probeProvider( let body = ''; try { body = await response.response.text(); + response.dispose(); } catch { body = ''; } @@ -70,31 +84,107 @@ export async function probeProvider( status: response.status, latencyMs, models: [], - error: errorMessageFrom(response.status, body, credentials.baseUrl), + error: probeFailureMessage(response.status), + detail: errorMessageFrom(response.status, body, credentials.baseUrl), }; } const payload = await readJsonBody(response.response); - return { ok: true, status: response.status, latencyMs, models: extractModels(payload), error: null }; + response.dispose(); + return { ok: true, status: response.status, latencyMs, models: extractModels(payload), error: '', detail: null }; } catch (error) { return { ok: false, status: 0, latencyMs: Date.now() - started, models: [], - error: error instanceof Error ? error.message : String(error), + error: probeFailureMessage(0), + detail: error instanceof Error ? error.message : String(error), }; } } +/** + * Mirrors `Repo.recordProviderFailure` for the emitted SSE state: retryable / + * rate-limit statuses cool the provider down, everything else is a hard error. + */ +export function failureState(status: number): 'cooldown' | 'error' { + return status === 429 || status === 503 || status === 529 || (status >= 500 && status < 600) + ? 'cooldown' + : 'error'; +} + +/** + * Persists a successful provider probe (`recordProviderSuccess`) and announces it. + * Shared by the provider test/sync routes so every success is visible over SSE. + */ +export function recordProbeSuccess( + ctx: AppContext, + providerId: string, + latencyMs: number, + status: number, +): void { + ctx.repo.recordProviderSuccess(providerId, latencyMs); + ctx.events.emitProvider({ providerId, state: 'ok', status, message: null, ts: Date.now() }); +} + +/** Persists a failed probe (counters + cooldown) and announces the new state. */ +function recordProbeFailure(ctx: AppContext, providerId: string, probe: ProviderProbe, cooldownMs: number): void { + ctx.repo.recordProviderFailure(providerId, probe.status || null, probe.error, cooldownMs); + ctx.events.emitProvider({ + providerId, + state: failureState(probe.status), + status: probe.status || null, + message: probe.error, + ts: Date.now(), + }); +} + +/** + * Probes a stored provider and persists the outcome (status counters, cooldown + * and the `provider:update` SSE event) so the dashboard reflects reality. + * + * `log` receives the detailed failure (upstream body excerpt) server-side only; + * the returned `probe.error` is the client-safe message. + */ +export async function probeAndRecord( + ctx: AppContext, + provider: ProviderRow, + options: { + cooldownMs: number; + log: (detail: string, probe: ProviderProbe) => void; + /** Override the probe deadline (recovery probes are cheap). */ + timeoutMs?: number; + }, +): Promise { + const probe = await probeProvider( + { baseUrl: provider.baseUrl, apiKey: provider.apiKey }, + options.timeoutMs, + ); + if (probe.ok) return probe; + options.log(probe.detail ?? (probe.error || 'unknown error'), probe); + recordProbeFailure(ctx, provider.id, probe, options.cooldownMs); + return probe; +} + /** * Upserts every upstream model with `source='sync'` and removes sync rows that * this provider no longer reports. Manual rows are never modified or deleted. + * + * A row already attributed to another provider is treated as "not mine": it is + * neither re-attributed nor deleted, so two providers reporting the same model id + * cannot steal it from each other (see SPEC §3 sync semantics). */ export async function syncProviderModels(ctx: AppContext, provider: ProviderRow): Promise { const probe = await probeProvider({ baseUrl: provider.baseUrl, apiKey: provider.apiKey }); if (!probe.ok) { - const suffix = probe.status > 0 ? ` (HTTP ${probe.status})` : ''; - throw new Error(`Failed to fetch models from provider "${provider.name}"${suffix}: ${probe.error ?? 'unknown error'}`); + ctx.logger?.warn?.( + { providerId: provider.id, status: probe.status, detail: probe.detail }, + 'provider model sync probe failed', + ); + // Both sync entry points need the failure persisted, so record it here once. + const configured = ctx.repo.getInt('provider_cooldown_ms', 60_000); + recordProbeFailure(ctx, provider.id, probe, Math.max(0, Number.isFinite(configured) ? configured : 60_000)); + throw new Error(syncFailureMessage(provider.name)); } const existing = ctx.repo.listModels(); @@ -107,6 +197,7 @@ export async function syncProviderModels(ctx: AppContext, provider: ProviderRow) 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, diff --git a/src/admin/util.ts b/src/admin/util.ts index 8916168..6b121fa 100644 --- a/src/admin/util.ts +++ b/src/admin/util.ts @@ -83,13 +83,15 @@ export function requireString(value: unknown, field: string): string { return parsed; } -export function requireInt(value: unknown, field: string, min: number, max: number): number { - const parsed = asInt(value); - if (parsed === null) fail(400, 'invalid_request', `${field} must be an integer`); - if (parsed < min || parsed > max) { - fail(400, 'invalid_request', `${field} must be between ${min} and ${max}`); - } - return parsed; +/** + * Route-level `bodyLimit` for credential endpoints. The global limit (128 MB by + * default) exists for media payloads; unauthenticated login must not accept them. + */ +export const ADMIN_CREDENTIAL_BODY_LIMIT = 4096; + +/** Passwords are scrypt-hashed; cap the input so a caller cannot burn CPU for free. */ +export function assertPasswordLength(password: string, field: string): void { + if (password.length > 200) fail(400, 'invalid_request', `${field} must be at most 200 characters`); } export function optionalInt(value: unknown, field: string): number | null { @@ -114,11 +116,156 @@ export function asTimestamp(value: unknown): number | null { return null; } +/** Like `asTimestamp`, but a present-yet-unparsable value is a client error. */ +export function queryTimestamp(value: unknown, field: string): number | null { + if (value === null || value === undefined || value === '') return null; + const parsed = asTimestamp(value); + if (parsed === null) fail(400, 'invalid_request', `${field} must be a unix timestamp or an ISO date`); + return parsed; +} + +/** Like `requireInt`, but rejects fractional values instead of truncating them. */ +export function queryInt(value: unknown, field: string, min: number, max: number): number { + const parsed = + typeof value === 'number' + ? value + : typeof value === 'string' && value.trim().length > 0 + ? Number(value) + : Number.NaN; + if (!Number.isInteger(parsed)) fail(400, 'invalid_request', `${field} must be an integer`); + if (parsed < min || parsed > max) { + fail(400, 'invalid_request', `${field} must be between ${min} and ${max}`); + } + return parsed; +} + +/* ------------------------------------------------------------------- SSRF guard */ + +const PRIVATE_HOSTS = new Set(['localhost', 'localhost.localdomain', 'ip6-localhost', 'ip6-loopback']); + +/** Private / loopback / link-local ranges a provider URL must never point at. */ +const BLOCKED_V4: Array<{ bytes: number[]; bits: number }> = [ + { bytes: [0, 0, 0, 0], bits: 8 }, // unspecified / "this network": routes to localhost on Linux + { bytes: [127, 0, 0, 0], bits: 8 }, // loopback + { bytes: [169, 254, 0, 0], bits: 16 }, // link-local + { bytes: [10, 0, 0, 0], bits: 8 }, + { bytes: [172, 16, 0, 0], bits: 12 }, + { bytes: [192, 168, 0, 0], bits: 16 }, +]; + +const BLOCKED_V6: Array<{ bytes: number[]; bits: number }> = [ + { bytes: v6Bytes('::1'), bits: 128 }, // loopback + { bytes: v6Bytes('fc00::'), bits: 7 }, // unique-local + { bytes: v6Bytes('fe80::'), bits: 10 }, // link-local +]; + +function v6Bytes(address: string): number[] { + const [head, tail] = address.split('::'); + const headParts = head ? head.split(':').filter((part) => part.length > 0) : []; + const tailParts = tail ? tail.split(':').filter((part) => part.length > 0) : []; + const groups = [...headParts, ...Array(Math.max(0, 8 - headParts.length - tailParts.length)).fill('0'), ...tailParts]; + const bytes: number[] = []; + for (const group of groups.slice(0, 8)) { + // Each group is one to four hex digits; a longer group is not a valid address. + const value = /^[0-9a-f]{1,4}$/.test(group) ? Number.parseInt(group, 16) : 0; + bytes.push((value >> 8) & 0xff, value & 0xff); + } + while (bytes.length < 16) bytes.push(0); + return bytes; +} + +function v4Bytes(address: string): number[] | null { + const parts = address.split('.'); + if (parts.length !== 4) return null; + const bytes: number[] = []; + for (const part of parts) { + if (!/^\d{1,3}$/.test(part)) return null; + const value = Number(part); + if (value > 255) return null; + bytes.push(value); + } + return bytes; +} + +function startsWithBits(bytes: number[], prefix: number[], bits: number): boolean { + const whole = Math.floor(bits / 8); + for (let index = 0; index < whole; index += 1) { + if (bytes[index] !== prefix[index]) return false; + } + const rest = bits % 8; + if (rest === 0) return true; + const mask = (0xff << (8 - rest)) & 0xff; + return ((bytes[whole] ?? 0) & mask) === ((prefix[whole] ?? 0) & mask); +} + +function isBlockedAddress(host: string): boolean { + // `URL.hostname` keeps the brackets around an IPv6 literal. + const address = host.replace(/^\[|\]$/g, '').toLowerCase(); + + const v4 = v4Bytes(address); + if (v4) return BLOCKED_V4.some((range) => startsWithBits(v4, range.bytes, range.bits)); + + if (address.includes(':')) { + // An IPv4-mapped/compatible address must be judged by its embedded IPv4 part. + const mapped = /(?:^|:)((?:\d{1,3}\.){3}\d{1,3})$/.exec(address); + if (mapped?.[1]) { + const inner = v4Bytes(mapped[1]); + if (inner) return BLOCKED_V4.some((range) => startsWithBits(inner, range.bytes, range.bits)); + } + const bytes = v6Bytes(address); + if (BLOCKED_V6.some((range) => startsWithBits(bytes, range.bytes, range.bits))) return true; + // IPv4-mapped (`::ffff:7f00:1`) and IPv4-compatible (`::7f00:1`) are rendered + // in hex by WHATWG URL, so decode the embedded IPv4 address and re-check it. + const firstTenZero = bytes.slice(0, 10).every((byte) => byte === 0); + const v4Mapped = bytes[10] === 0xff && bytes[11] === 0xff; + const v4Compatible = bytes[10] === 0 && bytes[11] === 0; + if (firstTenZero && (v4Mapped || v4Compatible)) { + const inner = bytes.slice(12, 16); + if (inner.some((byte) => byte !== 0)) return BLOCKED_V4.some((range) => startsWithBits(inner, range.bytes, range.bits)); + } + return false; + } + + return false; +} + +/** + * Rejects provider URLs that would make the server talk to itself or to the + * private network (SSRF). Hostnames are matched literally; an attacker fully + * controls the provider URL, so DNS resolution is deliberately not attempted. + */ +export function assertPublicProviderUrl(rawUrl: string, allowPrivate: boolean): void { + let host: string; + try { + host = new URL(rawUrl).hostname; + } catch { + fail(400, 'invalid_request', 'baseUrl must be a valid URL'); + return; + } + if (allowPrivate) return; + const normalized = host.toLowerCase(); + if (PRIVATE_HOSTS.has(normalized) || normalized.endsWith('.localhost') || isBlockedAddress(normalized)) { + fail( + 400, + 'invalid_request', + 'baseUrl must not point at a loopback, link-local or private network address (set PROVIDER_ALLOW_PRIVATE_HOSTS=true to allow)', + ); + } +} + export function httpBaseUrl(value: unknown): string { const url = requireString(value, 'baseUrl'); - if (!/^https?:\/\//i.test(url)) { + let parsed: URL; + try { + parsed = new URL(url); + } catch { + fail(400, 'invalid_request', 'baseUrl must be a valid URL'); + return ''; + } + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { fail(400, 'invalid_request', 'baseUrl must start with http:// or https://'); } + if (!parsed.hostname) fail(400, 'invalid_request', 'baseUrl must include a host'); return url.replace(/\/+$/, ''); } @@ -264,8 +411,8 @@ export function parseLogQuery(request: FastifyRequest): LogQuery { if (surfaceRaw === 'chat' || surfaceRaw === 'responses' || surfaceRaw === 'messages') surface = surfaceRaw; else fail(400, 'invalid_request', 'surface must be one of chat, responses, messages'); } - const limit = query.limit === undefined ? 50 : requireInt(query.limit, 'limit', 1, 500); - const offset = query.offset === undefined ? 0 : requireInt(query.offset, 'offset', 0, 1_000_000); + const limit = query.limit === undefined ? 50 : queryInt(query.limit, 'limit', 1, 500); + const offset = query.offset === undefined ? 0 : queryInt(query.offset, 'offset', 0, 1_000_000); const ok = query.ok === undefined ? null : asBool(query.ok); const stream = query.stream === undefined ? null : asBool(query.stream); if (ok === null && query.ok !== undefined) fail(400, 'invalid_request', 'ok must be true or false'); @@ -280,14 +427,23 @@ export function parseLogQuery(request: FastifyRequest): LogQuery { ok, stream, search: asString(query.search), - since: asTimestamp(query.since), - until: asTimestamp(query.until), + since: queryTimestamp(query.since, 'since'), + until: queryTimestamp(query.until, 'until'), }; } +/** Characters that would make a spreadsheet treat the cell as a formula. */ +const CSV_FORMULA_PREFIX = /^[=+\-@\t\r]/; + +/** + * CSV cell escaping: neutralises formula injection (`=`, `+`, `-`, `@`, tab, CR) + * and quotes the RFC 4180 specials. Log fields such as `user_agent` and + * `error_message` are attacker controlled, so both are mandatory. + */ export function csvEscape(value: unknown): string { if (value === null || value === undefined) return ''; - const text = String(value); + let text = String(value); + if (CSV_FORMULA_PREFIX.test(text)) text = `'${text}`; if (/[",\r\n]/.test(text)) return `"${text.replace(/"/g, '""')}"`; return text; } diff --git a/src/config.ts b/src/config.ts index f9beba6..eb1968a 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,6 +1,8 @@ import { mkdirSync } from 'node:fs'; import { resolve } from 'node:path'; +export type TrustProxySetting = boolean | string | string[]; + export interface AppConfig { host: string; port: number; @@ -15,6 +17,34 @@ export interface AppConfig { sessionTtlMs: number; webDistDir: string; publicUrl: string | null; + /** + * Value handed to Fastify's `trustProxy`. Defaults to `false`: without an + * explicit opt-in, `request.ip` (and therefore the login brute-force guard and + * `client_ip` logs) must not be attacker controlled. + */ + trustProxy: TrustProxySetting; + /** Provider probes/sync refuse loopback/link-local/private hosts unless enabled. */ + providerAllowPrivateHosts: boolean; +} + +function envTrustProxy(): TrustProxySetting { + const raw = (process.env.TRUST_PROXY ?? '').trim(); + if (raw.length === 0) return false; + const lower = raw.toLowerCase(); + if (['false', '0', 'no', 'off'].includes(lower)) return false; + if (['true', '1', 'yes', 'on'].includes(lower)) return true; + // A bare number (hop count) is accepted by proxy-addr through the string form. + const list = raw + .split(',') + .map((item) => item.trim()) + .filter((item) => item.length > 0); + return list.length > 0 ? list : false; +} + +function envBool(name: string, fallback: boolean): boolean { + const raw = process.env[name]; + if (raw === undefined || raw.trim().length === 0) return fallback; + return ['true', '1', 'yes', 'on'].includes(raw.trim().toLowerCase()); } function envInt(name: string, fallback: number): number { @@ -45,5 +75,7 @@ export function loadConfig(): AppConfig { ? resolve(process.env.WEB_DIST_DIR) : resolve(process.cwd(), 'web/dist'), publicUrl: process.env.PUBLIC_URL ?? null, + trustProxy: envTrustProxy(), + providerAllowPrivateHosts: envBool('PROVIDER_ALLOW_PRIVATE_HOSTS', false), }; } diff --git a/src/core/events.ts b/src/core/events.ts index 5e6dc59..7052509 100644 --- a/src/core/events.ts +++ b/src/core/events.ts @@ -23,6 +23,13 @@ export interface ProviderEvent { } export class EventBus extends EventEmitter { + constructor() { + super(); + // Every dashboard SSE client attaches three listeners; the default cap of 10 + // would spam MaxListenersExceededWarning on busy dashboards. + this.setMaxListeners(0); + } + emitRequestStart(event: RequestStartEvent): void { this.emit('request:start', event); } diff --git a/src/core/seed.ts b/src/core/seed.ts index a075555..672968b 100644 --- a/src/core/seed.ts +++ b/src/core/seed.ts @@ -20,7 +20,6 @@ export function seedDefaults(ctx: AppContext): void { auto_sync_models: 'true', model_sync_interval_ms: '300000', log_retention_days: '30', - log_store_bodies: 'false', model_allow_unknown: 'false', })) { if (repo.getSetting(key) === null) repo.setSetting(key, value); @@ -28,10 +27,12 @@ export function seedDefaults(ctx: AppContext): void { repo.purgeExpiredSessions(); } -/** Removes old request logs according to the retention setting. */ +/** Removes old request logs and audit entries according to the retention setting. */ export function pruneLogs(ctx: AppContext): number { const days = Math.max(1, ctx.repo.getInt('log_retention_days', 30)); - return ctx.repo.deleteLogsBefore(Date.now() - days * 24 * 60 * 60 * 1000); + const cutoff = Date.now() - days * 24 * 60 * 60 * 1000; + ctx.repo.deleteAuditBefore(cutoff); + return ctx.repo.deleteLogsBefore(cutoff); } export function verifyDashboardPassword(ctx: AppContext, password: string): boolean { diff --git a/src/db/repos.ts b/src/db/repos.ts index e2d1586..8c0346d 100644 --- a/src/db/repos.ts +++ b/src/db/repos.ts @@ -39,7 +39,6 @@ export const DEFAULT_SETTINGS: Record = { auto_sync_models: 'true', model_sync_interval_ms: '300000', log_retention_days: '30', - log_store_bodies: 'false', model_allow_unknown: 'false', upstream_user_agent: 'opencode-router/1.0', }; @@ -77,6 +76,9 @@ export interface StatsOverview { avgTtfbMs: number; }; activeRequests: number; + /** Exact counts for the trailing 60s, independent of the series bucket size. */ + requestsLast60s: number; + errorsLast60s: number; series: Array<{ t: number; requests: number; errors: number; tokens: number }>; byModel: Array<{ model: string; requests: number; tokens: number; errors: number; avgLatencyMs: number }>; byProvider: Array<{ providerId: string; providerName: string; requests: number; errors: number; avgLatencyMs: number }>; @@ -465,6 +467,19 @@ export class Repo { return this.getApiKey(id); } + /** + * Replaces the plaintext hash of an existing key (rotation) while keeping the + * id, name, counters and audit trail. Returns null for unknown ids. + */ + 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 = ?') + .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); return Number(res.changes) > 0; @@ -608,17 +623,20 @@ export class Repo { where.push('stream = ?'); params.push(query.stream ? 1 : 0); } - if (query.since) { + if (query.since !== null && query.since !== undefined) { where.push('ts >= ?'); params.push(query.since); } - if (query.until) { + if (query.until !== null && query.until !== undefined) { where.push('ts <= ?'); params.push(query.until); } if (query.search) { - where.push('(model LIKE ? OR key_name LIKE ? OR provider_name LIKE ? OR error_message LIKE ?)'); - const like = `%${query.search}%`; + // `%`/`_` in the search term must be literals, not wildcards. + where.push( + "(model LIKE ? ESCAPE '\\' OR key_name LIKE ? ESCAPE '\\' OR provider_name LIKE ? ESCAPE '\\' OR error_message LIKE ? ESCAPE '\\')", + ); + const like = `%${query.search.replace(/[\\%_]/g, (match) => `\\${match}`)}%`; params.push(like, like, like, like); } const clause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : ''; @@ -768,6 +786,13 @@ export class Repo { errorMessage: strOrNull(r.error_message), })); + const last60 = this.db + .prepare( + `SELECT COUNT(*) AS requests, COALESCE(SUM(CASE WHEN ok = 0 THEN 1 ELSE 0 END),0) AS errors + FROM request_logs WHERE ts >= ?`, + ) + .get(Date.now() - 60_000) as Row; + const requests = num(totalsRow.requests); return { windowMs, @@ -788,6 +813,8 @@ export class Repo { avgTtfbMs: Math.round(num(totalsRow.avg_ttfb)), }, activeRequests, + requestsLast60s: num(last60.requests), + errorsLast60s: num(last60.errors), series: seriesRows.map((r) => ({ t: num(r.bucket), requests: num(r.requests), @@ -846,6 +873,15 @@ export class Repo { this.db.prepare('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); + return Number(result.changes); + } + purgeExpiredSessions(): void { this.db.prepare('DELETE FROM sessions WHERE expires_at < ?').run(Date.now()); } @@ -864,6 +900,11 @@ export class Repo { /* --------------------------------------------------------------------- audit */ + deleteAuditBefore(ts: number): number { + const result = this.db.prepare('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 (?, ?, ?, ?, ?, ?)') diff --git a/src/db/schema.ts b/src/db/schema.ts index 0411133..563e32e 100644 --- a/src/db/schema.ts +++ b/src/db/schema.ts @@ -91,6 +91,7 @@ CREATE INDEX IF NOT EXISTS idx_request_logs_ts ON request_logs (ts DESC); 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); CREATE TABLE IF NOT EXISTS request_attempts ( id TEXT PRIMARY KEY, @@ -107,6 +108,7 @@ CREATE TABLE IF NOT EXISTS request_attempts ( ); CREATE INDEX IF NOT EXISTS idx_attempts_request ON request_attempts (request_id); +CREATE INDEX IF NOT EXISTS idx_attempts_ts ON request_attempts (ts); CREATE TABLE IF NOT EXISTS sessions ( id TEXT PRIMARY KEY, diff --git a/src/gateway/errors.ts b/src/gateway/errors.ts index 40abf64..1bf3b8b 100644 --- a/src/gateway/errors.ts +++ b/src/gateway/errors.ts @@ -1,6 +1,8 @@ -import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; +import type { FastifyError, FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; +import type { AppContext } from '../core/context.js'; import type { Surface } from '../types.js'; import { ApiError } from '../util/errors.js'; +import { recordRequestLog } from './logging.js'; /** Maps a `/v1/*` URL onto the compatible surface used for error shapes. */ export function surfaceForUrl(url: string): Surface { @@ -9,13 +11,6 @@ export function surfaceForUrl(url: string): Surface { return 'chat'; } -/** Coerces anything thrown into an ApiError without losing the upstream status. */ -export function toApiError(error: unknown, fallbackStatus = 502): ApiError { - if (error instanceof ApiError) return error; - const message = error instanceof Error ? error.message : String(error); - return new ApiError('api_error', message, { status: fallbackStatus }); -} - /** * Sends an error in the shape of the surface that was called. No-ops when the * response was already hijacked / written (streaming headers already flushed). @@ -27,28 +22,52 @@ export function sendApiError(reply: FastifyReply, surface: Surface, error: ApiEr } /** - * Installs a Fastify error handler that renders `/v1/*` failures in the shape of - * the matching surface (invalid JSON, body limit, 404s, ...). Non-`/v1` URLs are - * delegated to the previously installed handler so other layers keep theirs. + * Installs the error handler of the encapsulated gateway scope, so `/v1/*` + * failures are rendered in the shape of the matching surface (invalid JSON, + * body limit, validation, unexpected 500s) without overriding the root handler + * (FIX-02 removes the FSTWRN004 warning this way). */ -export function installGatewayErrorHandler(app: FastifyInstance): void { - const previous = app.errorHandler; - app.setErrorHandler((error: unknown, request: FastifyRequest, reply: FastifyReply) => { - if (!request.url.startsWith('/v1/')) { - return previous.call(app, error, request, reply); - } +export function installGatewayErrorHandler(scope: FastifyInstance, ctx: AppContext): void { + scope.setErrorHandler((error: Error, request: FastifyRequest, reply: FastifyReply) => { const surface = surfaceForUrl(request.url); - const status = - error instanceof ApiError ? error.status : ((error as { statusCode?: number }).statusCode ?? 500); + const errorStatus = (error as FastifyError).statusCode; + const status = error instanceof ApiError ? error.status : typeof errorStatus === 'number' ? errorStatus : 500; const apiError = error instanceof ApiError ? error : new ApiError( status >= 500 ? 'api_error' : 'invalid_request_error', - error instanceof Error ? error.message : String(error), - { status }, + status >= 500 ? 'Internal server error.' : error.message, + { + status, + code: status >= 500 ? 'internal_error' : ((error as FastifyError).code ?? 'invalid_request'), + }, ); - if (status >= 500) app.log.error({ err: error, url: request.url }, 'gateway request failed'); + if (status >= 500) scope.log.error({ err: error, url: request.url }, 'gateway request failed'); + if (reply.raw.headersSent || reply.raw.writableEnded) return; + const state = request.gateway; + // Framework failures (invalid JSON, body limit, validation) never reach a + // route handler, so the single request_logs row is written here instead. + if (state && !state.logged) { + state.logged = true; + recordRequestLog(ctx, { + requestId: state.requestId, + startedAt: state.startedAt, + key: state.key, + model: null, + surface, + stream: false, + status: apiError.status, + ok: false, + errorCode: apiError.code ?? apiError.type, + errorMessage: apiError.message, + ttfbMs: null, + attempts: 0, + clientIp: request.ip ?? null, + userAgent: typeof request.headers['user-agent'] === 'string' ? request.headers['user-agent'] : null, + }); + } + if (state) reply.header('x-opencode-router-request-id', state.requestId); void reply.status(apiError.status).send(apiError.toJSON(surface)); }); -} +} \ No newline at end of file diff --git a/src/gateway/forward-headers.ts b/src/gateway/forward-headers.ts new file mode 100644 index 0000000..21a9147 --- /dev/null +++ b/src/gateway/forward-headers.ts @@ -0,0 +1,51 @@ +import type { IncomingHttpHeaders } from 'node:http'; + +/** + * Client headers the gateway forwards to the provider (FIX-08). + * + * Credentials (`authorization`, `x-api-key`), hop-by-hop headers + * (`host`, `content-length`, `connection`) and `cookie` are never forwarded: + * `upstreamFetch` re-injects the provider key and the fetch implementation + * recomputes the length. + */ +const FORWARDED_HEADERS = [ + 'anthropic-beta', + 'openai-beta', + 'accept', + 'accept-language', + 'x-request-id', + 'traceparent', + 'tracestate', +] as const; + +const FORWARDED_PREFIXES = ['x-stainless-'] as const; + +function firstValue(value: string | string[] | undefined): string | null { + if (typeof value === 'string') return value.length > 0 ? value : null; + if (Array.isArray(value)) { + const first = value.find((item) => typeof item === 'string' && item.length > 0); + return first ?? null; + } + return 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. + */ +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; + } + for (const [name, raw] of Object.entries(headers)) { + const lower = name.toLowerCase(); + if (!FORWARDED_PREFIXES.some((prefix) => lower.startsWith(prefix))) continue; + const value = firstValue(raw); + if (value !== null) out[lower] = value; + } + if (options.acceptJson === true && out.accept === undefined) out.accept = 'application/json'; + return out; +} diff --git a/src/gateway/index.ts b/src/gateway/index.ts index 4e7dd59..cc3aba9 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 { installGatewayHooks } from './preauth.js'; import { registerProxyRoutes } from './proxy.js'; /** @@ -13,12 +14,18 @@ import { registerProxyRoutes } from './proxy.js'; * - `POST /v1/messages/count_tokens` * - `GET /v1/models`, `GET /v1/models/:id` * - * All of them require a gateway API key. Streaming routes hijack the reply and - * forward upstream bytes as they arrive; non-streaming routes forward the JSON - * body with any top-level `x_opencode` key stripped. + * Routes live in their own encapsulated scope so the gateway error handler, + * pre-body API-key authentication hook and raw-body JSON parser own `/v1/*` + * without touching the root scope. All of them require a gateway API key. + * Streaming routes hijack the reply and forward upstream bytes as they arrive; + * non-streaming routes forward the JSON body with any top-level `x_opencode` + * key stripped. */ export async function registerGatewayRoutes(app: FastifyInstance, ctx: AppContext): Promise { - installGatewayErrorHandler(app); - registerProxyRoutes(app, ctx); - registerModelsRoutes(app, ctx); -} \ No newline at end of file + await app.register(async (scope: FastifyInstance): Promise => { + installGatewayErrorHandler(scope, ctx); + installGatewayHooks(scope, ctx); + registerProxyRoutes(scope, ctx); + registerModelsRoutes(scope, ctx); + }); +} diff --git a/src/gateway/logging.ts b/src/gateway/logging.ts index a2d2611..873bc7f 100644 --- a/src/gateway/logging.ts +++ b/src/gateway/logging.ts @@ -1,5 +1,7 @@ +import type { AppContext } from '../core/context.js'; +import type { ApiKeyRow, AttemptRow, ProviderRow, RequestLogRow, Surface, Usage } from '../types.js'; import { uuid } from '../util/crypto.js'; -import type { AttemptRow, RequestLogRow } from '../types.js'; +import { emptyUsage } from './usage.js'; export function newAttempt(input: { requestId: string; @@ -25,4 +27,64 @@ export function newAttempt(input: { errorMessage: input.errorMessage, latencyMs: input.latencyMs, }; +} + +export interface RequestLogInput { + requestId: string; + startedAt: number; + key: ApiKeyRow | null; + provider?: ProviderRow | null; + model: string | null; + surface: Surface; + stream: boolean; + status: number; + ok: boolean; + errorCode: string | null; + errorMessage: string | null; + ttfbMs: number | null; + usage?: Usage | null; + attempts: number; + clientIp: string | null; + userAgent: string | null; +} + +/** + * Writes the single `request_logs` row for a gateway request and emits the + * paired `request:end` event (golden rule 3). Logging failures never break the + * response, so they are reported through the server logger instead. + */ +export function recordRequestLog(ctx: AppContext, input: RequestLogInput): RequestLogRow { + const usage = input.usage ?? emptyUsage(); + const log: RequestLogRow = { + id: input.requestId, + ts: input.startedAt, + keyId: input.key?.id ?? null, + keyName: input.key?.name ?? null, + providerId: input.provider?.id ?? null, + providerName: input.provider?.name ?? null, + model: input.model, + surface: input.surface, + stream: input.stream, + status: input.status, + ok: input.ok, + errorCode: input.errorCode, + errorMessage: input.errorMessage, + latencyMs: Date.now() - input.startedAt, + ttfbMs: input.ttfbMs, + inputTokens: usage.inputTokens, + outputTokens: usage.outputTokens, + totalTokens: usage.totalTokens, + reasoningTokens: usage.reasoningTokens, + cachedTokens: usage.cachedTokens, + attempts: input.attempts, + clientIp: input.clientIp, + userAgent: input.userAgent, + }; + try { + ctx.repo.insertLog(log); + } catch (error) { + ctx.logger.warn({ err: error, requestId: input.requestId }, 'failed to insert gateway request log'); + } + ctx.events.emitRequestEnd({ log }); + return log; } \ No newline at end of file diff --git a/src/gateway/models-route.ts b/src/gateway/models-route.ts index ba8bbd3..8502ad8 100644 --- a/src/gateway/models-route.ts +++ b/src/gateway/models-route.ts @@ -1,13 +1,16 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; import type { AppContext } from '../core/context.js'; -import type { ModelRow, RequestLogRow, Surface } from '../types.js'; -import { uuid } from '../util/crypto.js'; +import type { ModelRow, Surface } from '../types.js'; import { ApiError } from '../util/errors.js'; -import { authenticate } from './auth.js'; import { sendApiError } from './errors.js'; -import { emptyUsage } from './usage.js'; +import { recordRequestLog } from './logging.js'; +import { gatewayState } from './preauth.js'; + +const ROUTER_REQUEST_ID_HEADER = 'x-opencode-router-request-id'; + +/** `/v1/models*` never proxies, so rows use the OpenAI error shape's surface. */ +const MODELS_SURFACE: Surface = 'chat'; -/** `/v1/models` entries are metadata reads: they do not hit a provider and are not logged. */ export function toModelObject(model: ModelRow): Record { return { id: model.id, @@ -33,86 +36,58 @@ export function toModelObject(model: ModelRow): Record { }; } -/** Rejected metadata requests are logged so operators can see key misuse. */ -function logRejectedRequest( +/** + * Writes the single `request_logs` row (golden rule 3) plus the paired + * `request:end` event for a metadata read, then replies. Authentication already + * happened in the gateway pre-auth hook, including its own rejection row. + * Provider/attempts headers describe a proxied call, so they are never set here + * (FIX-15); every `/v1/models*` response carries only the request id. + */ +function finishModelsRequest( ctx: AppContext, request: FastifyRequest, - requestId: string, - startedAt: number, - surface: Surface, - error: ApiError, + reply: FastifyReply, + input: { status: number; ok: boolean; model: string | null; error?: ApiError }, ): void { - const userAgentHeader = request.headers['user-agent']; - const log: RequestLogRow = { - id: requestId, - ts: startedAt, - keyId: null, - keyName: null, - providerId: null, - providerName: null, - model: null, - surface, + const state = gatewayState(request); + recordRequestLog(ctx, { + requestId: state.requestId, + startedAt: state.startedAt, + key: state.key, + model: input.model, + surface: MODELS_SURFACE, stream: false, - status: error.status, - ok: false, - errorCode: error.code ?? error.type, - errorMessage: error.message, - latencyMs: Date.now() - startedAt, + status: input.status, + ok: input.ok, + errorCode: input.error ? (input.error.code ?? input.error.type) : null, + errorMessage: input.error ? input.error.message : null, ttfbMs: null, - ...emptyUsage(), attempts: 0, clientIp: request.ip ?? null, - userAgent: typeof userAgentHeader === 'string' ? userAgentHeader : null, - }; - try { - ctx.repo.insertLog(log); - } catch (error2) { - ctx.logger.warn({ err: error2, requestId }, 'failed to insert gateway request log'); - } - ctx.events.emitRequestEnd({ log }); -} + userAgent: typeof request.headers['user-agent'] === 'string' ? request.headers['user-agent'] : null, + }); + state.logged = true; -function authorize( - ctx: AppContext, - request: FastifyRequest, - reply: FastifyReply, - requestId: string, - startedAt: number, -): boolean { - try { - authenticate(ctx, request.headers); - return true; - } catch (error) { - const apiError = - error instanceof ApiError - ? error - : new ApiError('authentication_error', error instanceof Error ? error.message : String(error), { - code: 'invalid_api_key', - }); - logRejectedRequest(ctx, request, requestId, startedAt, 'chat', apiError); - sendApiError(reply, 'chat', apiError, requestId); - return false; + if (!input.ok && input.error) { + sendApiError(reply, MODELS_SURFACE, input.error, state.requestId); + return; } + reply.header(ROUTER_REQUEST_ID_HEADER, state.requestId); + void reply.status(input.status); } export function registerModelsRoutes(app: FastifyInstance, ctx: AppContext): void { app.get('/v1/models', async (request: FastifyRequest, reply: FastifyReply) => { - const startedAt = Date.now(); - const requestId = uuid(); - if (!authorize(ctx, request, reply, requestId, startedAt)) return; const data = ctx.repo .listModels() .filter((model) => model.enabled) .map((model) => toModelObject(model)); - reply.header('x-opencode-router-request-id', requestId); + finishModelsRequest(ctx, request, reply, { status: 200, ok: true, model: null }); await reply.send({ object: 'list', data }); }); // Model ids contain slashes (`opencode/flint-40b-free`), so a wildcard is required. app.get('/v1/models/*', async (request: FastifyRequest, reply: FastifyReply) => { - const startedAt = Date.now(); - const requestId = uuid(); - if (!authorize(ctx, request, reply, requestId, startedAt)) return; const params = request.params as { '*': string }; const requestedId = (params['*'] ?? '').trim(); const model = requestedId.length > 0 ? ctx.repo.getModel(requestedId) : null; @@ -122,10 +97,10 @@ export function registerModelsRoutes(app: FastifyInstance, ctx: AppContext): voi `The model "${requestedId}" does not exist or is not enabled. Add or enable it in the dashboard (Models tab).`, { code: 'model_not_found', param: 'model' }, ); - sendApiError(reply, 'chat', error, requestId); + finishModelsRequest(ctx, request, reply, { status: error.status, ok: false, model: requestedId, error }); return; } - reply.header('x-opencode-router-request-id', requestId); + finishModelsRequest(ctx, request, reply, { status: 200, ok: true, model: model.id }); await reply.send(toModelObject(model)); }); } \ No newline at end of file diff --git a/src/gateway/preauth.ts b/src/gateway/preauth.ts new file mode 100644 index 0000000..141175b --- /dev/null +++ b/src/gateway/preauth.ts @@ -0,0 +1,162 @@ +import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; +import { decActiveRequests, incActiveRequests, type AppContext } from '../core/context.js'; +import type { ApiKeyRow } from '../types.js'; +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'; + +/** Per-request state produced by the pre-body authentication hook. */ +export interface GatewayRequestState { + requestId: string; + startedAt: number; + /** Authenticated key; only set once the hook has accepted the request. */ + 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; +} + +declare module 'fastify' { + interface FastifyRequest { + /** Gateway id + start timestamp, set before the body is read. */ + gateway?: GatewayRequestState; + } +} + +/** Creates the request state and runs mandatory gateway authentication. */ +export function createPreAuthHook(ctx: AppContext) { + return async function gatewayPreAuth(request: FastifyRequest, reply: FastifyReply): Promise { + const state: GatewayRequestState = { + requestId: uuid(), + startedAt: Date.now(), + key: null, + logged: false, + rawBody: null, + }; + request.gateway = state; + + let key: ApiKeyRow; + try { + key = authenticate(ctx, request.headers); + } catch (error) { + rejectUnauthenticated(ctx, request, reply, state, error); + return; + } + state.key = key; + ctx.events.emitRequestStart({ + id: state.requestId, + ts: state.startedAt, + surface: surfaceForUrl(request.url), + model: null, + stream: false, + keyName: key.name, + }); + }; +} + +/** + * Renders an authentication failure for the called surface and writes the single + * `request_logs` row that golden rule 3 requires. The body is never read. + */ +function rejectUnauthenticated( + ctx: AppContext, + request: FastifyRequest, + reply: FastifyReply, + state: GatewayRequestState, + error: unknown, +): void { + const apiError = + error instanceof ApiError + ? error + : new ApiError('authentication_error', error instanceof Error ? error.message : String(error), { + code: 'invalid_api_key', + }); + const surface = surfaceForUrl(request.url); + const userAgent = request.headers['user-agent']; + + // Rejected calls still occupied an inbound socket; the pair keeps the counter + // accounting symmetric with the route handlers and floors at zero. + incActiveRequests(); + decActiveRequests(); + + // Every log row gets its paired start event, rejections included, so SSE + // consumers never see an orphan `request:end`. + ctx.events.emitRequestStart({ + id: state.requestId, + ts: state.startedAt, + surface, + model: null, + stream: false, + keyName: null, + }); + + recordRequestLog(ctx, { + requestId: state.requestId, + startedAt: state.startedAt, + key: null, + model: null, + surface, + stream: false, + status: apiError.status, + ok: false, + errorCode: apiError.code ?? apiError.type, + errorMessage: apiError.message, + ttfbMs: null, + attempts: 0, + clientIp: request.ip ?? null, + userAgent: typeof userAgent === 'string' ? userAgent : null, + }); + state.logged = true; + sendApiError(reply, surface, apiError, state.requestId); +} + +/** Reads the state attached by `createPreAuthHook`, guarded for runtime safety. */ +export function gatewayState(request: FastifyRequest): GatewayRequestState { + const state = request.gateway; + if (!state) { + throw new ApiError('api_error', 'Gateway request state is missing.', { + status: 500, + code: 'gateway_state_missing', + }); + } + return state; +} + +/** + * 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). + */ +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) { + // The handler reports the missing body with the surface-shaped error. + done(null, undefined); + return; + } + try { + const parsed: unknown = JSON.parse(text); + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + done( + new ApiError('invalid_request_error', 'Request body must be a JSON object.', { + code: 'invalid_request', + }), + ); + return; + } + done(null, parsed); + } catch { + done( + new ApiError('invalid_request_error', 'Request body is not valid JSON.', { code: 'invalid_request' }), + ); + } + }); +} diff --git a/src/gateway/proxy.ts b/src/gateway/proxy.ts index bbbda51..d563526 100644 --- a/src/gateway/proxy.ts +++ b/src/gateway/proxy.ts @@ -1,15 +1,15 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; import { decActiveRequests, incActiveRequests, type AppContext } from '../core/context.js'; -import type { ApiKeyRow, Json, ProviderRow, RequestLogRow, Surface, Usage } from '../types.js'; -import { uuid } from '../util/crypto.js'; +import type { ApiKeyRow, Json, ProviderRow, Surface, Usage } from '../types.js'; import { ApiError, isRetryableStatus, upstreamErrorFrom } from '../util/errors.js'; import { SseParser } from '../util/sse.js'; import { upstreamFetch, type UpstreamResponse } from '../util/upstream.js'; -import { authenticate } from './auth.js'; +import { forwardHeaders } from './forward-headers.js'; import { sendApiError } from './errors.js'; -import { newAttempt } from './logging.js'; +import { newAttempt, recordRequestLog } from './logging.js'; import { normalizeBody } from './normalize.js'; -import { orderProviders } from './rotation.js'; +import { gatewayState } from './preauth.js'; +import { orderProviders, parseRotationStrategy } from './rotation.js'; import { emptyUsage, extractUsageFromFrame, extractUsageFromJson, mergeUsage } from './usage.js'; export interface ProxyRoute { @@ -31,18 +31,33 @@ const PROXY_ROUTES: ProxyRoute[] = [ }, ]; -export function registerProxyRoutes(app: FastifyInstance, ctx: AppContext): void { - for (const route of PROXY_ROUTES) { - app.post(route.url, async (request: FastifyRequest, reply: FastifyReply) => { - await handleProxyRequest(ctx, request, reply, route); - }); - } +/** Decodes `retry-after` (delta seconds or HTTP-date) into milliseconds. */ +export function retryAfterMs(value: string | null, now = Date.now()): number | null { + if (value === null) return null; + const trimmed = value.trim(); + if (trimmed.length === 0) return null; + if (/^\d+$/.test(trimmed)) return Number.parseInt(trimmed, 10) * 1000; + const date = Date.parse(trimmed); + if (!Number.isFinite(date)) return null; + return Math.max(0, date - now); +} + +function isTimeoutReason(reason: string | null): boolean { + if (reason === null) return false; + return reason === 'upstream timeout' || reason.includes('idle timeout'); +} + +/** True when a failed attempt was actually a deadline abort (not e.g. ECONNREFUSED). */ +function isTimeoutFailure(error: ApiError | null | undefined): boolean { + if (!error) return false; + return error.type === 'timeout_error' || error.code === 'upstream_timeout'; } interface SurfaceOutcome { status: number; ok: boolean; aborted: boolean; + timedOut: boolean; ttfbMs: number | null; usage: Usage; errorCode: string | null; @@ -108,12 +123,20 @@ function routerHeaders(provider: ProviderRow, requestId: string, attempts: numbe }; } +function disposeUpstream(upstream: UpstreamResponse): void { + try { + upstream.dispose(); + } catch { + /* already released */ + } +} + /* ------------------------------------------------------------------ upstream */ type AttemptResult = | { kind: 'ok'; response: UpstreamResponse; latencyMs: number } | { kind: 'retry' | 'fatal'; status: number | null; error: ApiError; latencyMs: number } - | { kind: 'abort'; latencyMs: number }; + | { kind: 'abort'; latencyMs: number; timedOut: boolean; error: ApiError | null }; async function readResponseText(response: Response): Promise { try { @@ -123,35 +146,54 @@ async function readResponseText(response: Response): Promise { } } +interface AttemptOptions { + requestId: string; + attempt: number; + /** Total deadline for the whole upstream exchange (headers + body). */ + timeoutMs: number; + cooldownMs: number; + userAgent: string; + signal: AbortSignal; + headers: Record; + /** Raw client body; forwarded verbatim so no bytes are rewritten (FIX-09). */ + rawBody: string | null; + body: Json; + /** Streaming chat needs an SSE accept header when the client did not send one. */ + stream: boolean; +} + async function runAttempt( ctx: AppContext, provider: ProviderRow, route: ProxyRoute, - body: Json, - options: { requestId: string; attempt: number; timeoutMs: number; cooldownMs: number; userAgent: string; signal: AbortSignal }, + options: AttemptOptions, ): Promise { const startedAt = Date.now(); + let upstream: UpstreamResponse | null = null; try { - const response = await upstreamFetch({ + upstream = await upstreamFetch({ baseUrl: provider.baseUrl, apiKey: provider.apiKey, path: route.upstreamPath, method: 'POST', - body, + ...(options.rawBody !== null ? { rawBody: options.rawBody } : { body: options.body }), + headers: options.headers, timeoutMs: options.timeoutMs, userAgent: options.userAgent, signal: options.signal, + // 3xx never followed: the provider key must not cross origins (FIX-08). + redirect: 'manual', }); const latencyMs = Date.now() - startedAt; - if (response.ok) { + if (upstream.ok) { ctx.repo.insertAttempt( newAttempt({ requestId: options.requestId, providerId: provider.id, providerName: provider.name, attempt: options.attempt, - status: response.status, + status: upstream.status, ok: true, errorCode: null, errorMessage: null, @@ -162,22 +204,31 @@ async function runAttempt( ctx.events.emitProvider({ providerId: provider.id, state: 'ok', - status: response.status, + status: upstream.status, message: null, ts: Date.now(), }); - return { kind: 'ok', response, latencyMs }; + return { kind: 'ok', response: upstream, latencyMs }; } - const text = await readResponseText(response.response); - const mapped = upstreamErrorFrom(response.status, text, provider.name); + // The error body is fully read here, so the upstream timeout/abort wiring is + // released before the failover decision (FIX-04 keeps no stray timers). + const text = await readResponseText(upstream.response); + disposeUpstream(upstream); + const mapped = + upstream.status >= 300 && upstream.status < 400 + ? new ApiError('api_error', `Upstream provider "${provider.name}" tried to redirect the request (HTTP ${upstream.status}); redirects are not followed.`, { + status: 502, + code: 'upstream_redirect', + }) + : upstreamErrorFrom(upstream.status, text, provider.name); ctx.repo.insertAttempt( newAttempt({ requestId: options.requestId, providerId: provider.id, providerName: provider.name, attempt: options.attempt, - status: response.status, + status: upstream.status, ok: false, errorCode: mapped.code ?? mapped.type, errorMessage: mapped.message, @@ -185,23 +236,63 @@ async function runAttempt( }), ); - if (isRetryableStatus(response.status)) { - ctx.repo.recordProviderFailure(provider.id, response.status, mapped.message, options.cooldownMs); + if (upstream.status >= 300 && upstream.status < 400) { + // FIX-08: a redirect is a provider misconfiguration, not a rate limit. + // 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({ + providerId: provider.id, + state: 'error', + status: upstream.status, + message: mapped.message, + ts: Date.now(), + }); + return { kind: 'fatal', status: upstream.status, error: mapped, latencyMs }; + } + + if (isRetryableStatus(upstream.status)) { + // FEAT-01: an upstream Retry-After is authoritative when longer than the + // configured cooldown, so the provider is not retried before it recovers. + 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({ providerId: provider.id, state: 'cooldown', - status: response.status, + status: upstream.status, message: mapped.message, ts: Date.now(), }); - return { kind: 'retry', status: response.status, error: mapped, latencyMs }; + return { kind: 'retry', status: upstream.status, error: mapped, latencyMs }; } // 400/401/403/404/422 & friends: the client request is at fault, do not burn other providers. - return { kind: 'fatal', status: response.status, error: mapped, latencyMs }; + return { kind: 'fatal', status: upstream.status, error: mapped, latencyMs }; } catch (error) { const latencyMs = Date.now() - startedAt; - if (options.signal.aborted) return { kind: 'abort', latencyMs }; + const abortReason = upstream?.abortReason ?? null; + if (options.signal.aborted) { + return { + kind: 'abort', + latencyMs, + timedOut: false, + error: new ApiError('connection_error', 'Client aborted the request.', { code: 'client_aborted' }), + }; + } + 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 apiError = error instanceof ApiError ? error @@ -298,73 +389,79 @@ export function rewriteSseFrame(frame: string): string { } } -function writeRaw(reply: FastifyReply, text: string): boolean { +/** + * Forwards one completed frame. The original bytes are written untouched; the + * frame is decoded only to look for `x_opencode` and re-encoded only when the + * rewrite actually changed it (FIX-03: invalid UTF-8 and BOMs stay verbatim). + */ +function writeFrame(reply: FastifyReply, frame: Buffer, delimiter: Buffer): boolean { if (reply.raw.writableEnded || reply.raw.destroyed) return false; + const text = frame.toString('utf8'); + const rewritten = rewriteSseFrame(text); + const bytes = rewritten === text ? frame : Buffer.from(rewritten, 'utf8'); try { - reply.raw.write(Buffer.from(text, 'utf8')); + reply.raw.write(bytes); + reply.raw.write(delimiter); return true; } catch { return false; } } -function nextBoundary(text: string): { index: number; length: number } | null { - const lf = text.indexOf('\n\n'); - const crlf = text.indexOf('\r\n\r\n'); +/** Returns the byte range of the frame terminator, favouring CRLFCRLF when earlier. */ +function nextBoundary(buffer: Buffer): { index: number; length: number } | null { + const lf = buffer.indexOf('\n\n'); + const crlf = buffer.indexOf('\r\n\r\n'); if (lf === -1 && crlf === -1) return null; if (crlf !== -1 && (lf === -1 || crlf < lf)) return { index: crlf, length: 4 }; return { index: lf, length: 2 }; } -async function jsonSurface( - reply: FastifyReply, - surface: Surface, - requestId: string, - provider: ProviderRow, - upstream: UpstreamResponse, - attempts: number, - ttfbMs: number, -): Promise { - void surface; - const buffer = stripTopLevelXOpencode(Buffer.from(await upstream.response.arrayBuffer())); - const usage = mergeUsage(emptyUsage(), extractUsageFromJson(parseJson(buffer.toString('utf8')))); - const headers: Record = { - '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); - reply.raw.end(buffer); - } catch (error) { - return { - status: upstream.status, - ok: false, - aborted: false, - ttfbMs, - usage, - errorCode: 'response_write_failed', - errorMessage: error instanceof Error ? error.message : String(error), +/** + * Waits for the response socket to drain after `write()` returned false, racing + * the client-abort signal and the upstream timeout so a stalled client cannot + * pin a request forever (FIX-05). + */ +function waitForDrain(reply: FastifyReply, guard: RequestGuard, timeoutMs: number): Promise<'drain' | 'abort' | 'timeout'> { + return new Promise((resolve) => { + let settled = false; + const finish = (result: 'drain' | 'abort' | 'timeout'): void => { + if (settled) return; + settled = true; + cleanup(); + resolve(result); }; - } - return { status: upstream.status, ok: true, aborted: false, ttfbMs, usage, errorCode: null, errorMessage: null }; + const onDrain = (): void => finish('drain'); + const onAbort = (): void => finish('abort'); + const timer = setTimeout(() => finish('timeout'), timeoutMs); + const cleanup = (): void => { + clearTimeout(timer); + reply.raw.off('drain', onDrain); + guard.signal.removeEventListener('abort', onAbort); + }; + reply.raw.once('drain', onDrain); + guard.signal.addEventListener('abort', onAbort, { once: true }); + }); } -async function streamSurface( - reply: FastifyReply, - surface: Surface, - requestId: string, - provider: ProviderRow, - upstream: UpstreamResponse, - attempts: number, - requestStartedAt: number, - guard: RequestGuard, -): Promise { - void surface; +interface StreamContext { + reply: FastifyReply; + requestId: string; + provider: ProviderRow; + upstream: UpstreamResponse; + attempts: number; + requestStartedAt: number; + guard: RequestGuard; + /** Idle gap allowed between upstream chunks before the stream is aborted. */ + idleMs: number; +} + +async function streamSurface(input: StreamContext): Promise { + const { reply, requestId, provider, upstream, attempts, requestStartedAt, guard } = input; let usage = emptyUsage(); let ttfbMs: number | null = null; let aborted = false; + let timedOut = false; let ok = true; let errorCode: string | null = null; let errorMessage: string | null = null; @@ -380,10 +477,12 @@ async function streamSurface( }); reply.raw.flushHeaders(); } catch (error) { + disposeUpstream(upstream); return { status: upstream.status, ok: false, aborted: false, + timedOut: false, ttfbMs: null, usage, errorCode: 'response_write_failed', @@ -398,49 +497,99 @@ async function streamSurface( } catch { /* already closed */ } - return { status: upstream.status, ok: true, aborted: false, ttfbMs: null, usage, errorCode: null, errorMessage: null }; + disposeUpstream(upstream); + return { + status: upstream.status, + ok: true, + aborted: false, + timedOut: false, + ttfbMs: null, + usage, + errorCode: null, + errorMessage: null, + }; } const reader = body.getReader(); - const decoder = new TextDecoder('utf-8'); const sse = new SseParser(); - let buffer = ''; + let pending: Buffer = Buffer.alloc(0); + // The idle timer aborts the upstream when the provider stops sending bytes; + // upstreamFetch's own timer stays alive until dispose() as the total deadline. + let idleTimer: NodeJS.Timeout | null = null; + const armIdle = (): void => { + if (idleTimer) clearTimeout(idleTimer); + idleTimer = setTimeout(() => upstream.abort('idle timeout'), input.idleMs); + }; + const clearIdle = (): void => { + if (idleTimer) clearTimeout(idleTimer); + idleTimer = null; + }; + + const onClientAbort = (): void => { + upstream.abort('client aborted'); + }; + guard.signal.addEventListener('abort', onClientAbort, { once: true }); try { + if (guard.aborted) throw new Error('client aborted'); + armIdle(); while (true) { + const chunk = await reader.read(); + if (chunk.done) break; + if (ttfbMs === null) ttfbMs = Date.now() - requestStartedAt; + armIdle(); if (guard.aborted) { aborted = true; break; } - const chunk = await reader.read(); - if (chunk.done) break; - if (ttfbMs === null) ttfbMs = Date.now() - requestStartedAt; - buffer += decoder.decode(chunk.value, { stream: true }); - - let boundary = nextBoundary(buffer); + const value = chunk.value; + if (!value || value.byteLength === 0) continue; + const merged = pending.length === 0 ? Buffer.from(value) : Buffer.concat([pending, Buffer.from(value)]); + let boundary = nextBoundary(merged); + let offset = 0; + let writeFailed = false; while (boundary) { - const frame = buffer.slice(0, boundary.index); - const delimiter = buffer.slice(boundary.index, boundary.index + boundary.length); - buffer = buffer.slice(boundary.index + boundary.length); - for (const message of sse.push(`${frame}\n\n`)) { + const start = offset; + const end = offset + boundary.index; + const frame = merged.subarray(start, end); + const delimiter = merged.subarray(end, end + boundary.length); + for (const message of sse.push(`${frame.toString('utf8')}\n\n`)) { usage = mergeUsage(usage, extractUsageFromFrame(message.data)); } - if (!writeRaw(reply, `${rewriteSseFrame(frame)}${delimiter}`)) { + if (!writeFrame(reply, frame, delimiter)) { + writeFailed = true; + break; + } + offset = end + boundary.length; + boundary = nextBoundary(merged.subarray(offset)); + } + if (writeFailed || guard.aborted || reply.raw.destroyed) { + aborted = true; + break; + } + pending = offset >= merged.length ? Buffer.alloc(0) : merged.subarray(offset); + if (reply.raw.writableNeedDrain) { + const result = await waitForDrain(reply, guard, input.idleMs); + if (result !== 'drain') { aborted = true; break; } - boundary = nextBoundary(buffer); } - if (aborted) break; } if (!aborted) { - buffer += decoder.decode(); - if (buffer.length > 0) { - for (const message of sse.push(`${buffer}\n\n`)) { + if (pending.length > 0) { + const text = pending.toString('utf8'); + for (const message of sse.push(`${text}\n\n`)) { usage = mergeUsage(usage, extractUsageFromFrame(message.data)); } - writeRaw(reply, rewriteSseFrame(buffer)); + const rewritten = rewriteSseFrame(text); + const bytes = rewritten === text ? pending : Buffer.from(rewritten, 'utf8'); + try { + reply.raw.write(bytes); + } catch { + /* peer already gone */ + } } for (const message of sse.flush()) usage = mergeUsage(usage, extractUsageFromFrame(message.data)); try { @@ -452,6 +601,16 @@ async function streamSurface( } catch (error) { if (guard.aborted) { aborted = true; + } else if (isTimeoutReason(upstream.abortReason)) { + timedOut = true; + ok = false; + errorCode = 'upstream_timeout'; + errorMessage = 'Upstream stream idle timeout.'; + try { + reply.raw.end(); + } catch { + /* already closed */ + } } else { ok = false; errorCode = 'stream_error'; @@ -463,6 +622,8 @@ async function streamSurface( } } } finally { + clearIdle(); + guard.signal.removeEventListener('abort', onClientAbort); if (aborted) { try { await reader.cancel(); @@ -475,6 +636,7 @@ async function streamSurface( } catch { /* ignore */ } + disposeUpstream(upstream); } if (aborted) { @@ -484,9 +646,10 @@ async function streamSurface( } return { - status: aborted ? 499 : upstream.status, + status: aborted ? 499 : timedOut ? 504 : upstream.status, ok, aborted, + timedOut, ttfbMs, usage, errorCode, @@ -502,6 +665,78 @@ function parseJson(text: string): unknown { } } +async function jsonSurface( + reply: FastifyReply, + surface: Surface, + requestId: string, + provider: ProviderRow, + upstream: UpstreamResponse, + attempts: number, + ttfbMs: number, +): Promise { + let buffer: Buffer; + try { + buffer = stripTopLevelXOpencode(Buffer.from(await upstream.response.arrayBuffer())); + } catch (error) { + // Nothing has been written to the client yet, so the caller can still return + // 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, + ok: false, + aborted: false, + timedOut, + ttfbMs, + usage: emptyUsage(), + errorCode: timedOut ? 'upstream_timeout' : 'upstream_body_failed', + errorMessage: error instanceof Error ? error.message : String(error), + }; + } finally { + disposeUpstream(upstream); + } + const usage = mergeUsage(emptyUsage(), extractUsageFromJson(parseJson(buffer.toString('utf8')))); + const headers: Record = { + '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); + reply.raw.end(buffer); + } catch (error) { + return { + status: upstream.status, + ok: false, + aborted: false, + timedOut: false, + ttfbMs, + usage, + errorCode: 'response_write_failed', + errorMessage: error instanceof Error ? error.message : String(error), + }; + } + return { + status: upstream.status, + ok: true, + aborted: false, + timedOut: false, + ttfbMs, + usage, + errorCode: null, + errorMessage: null, + }; +} + +/** + * `normalizeBody` returned a shallow copy; the raw bytes can only be reused when + * no logical change happened. The JSON round-trip is the documented comparison + * (FIX-09) and only decides *which* representation is sent, never rewrites it. + */ +function hasLogicalChange(original: Json, normalized: Json): boolean { + return JSON.stringify(normalized) !== JSON.stringify(original); +} + /* -------------------------------------------------------------------- handler */ async function handleProxyRequest( @@ -510,8 +745,9 @@ async function handleProxyRequest( reply: FastifyReply, route: ProxyRoute, ): Promise { - const startedAt = Date.now(); - const requestId = uuid(); + const state = gatewayState(request); + const startedAt = state.startedAt; + const requestId = state.requestId; const surface = route.surface; const clientIp = request.ip ?? null; const userAgentHeader = request.headers['user-agent']; @@ -519,7 +755,7 @@ async function handleProxyRequest( incActiveRequests(); - let key: ApiKeyRow | null = null; + const key: ApiKeyRow | null = state.key; let modelId: string | null = null; let stream = false; let provider: ProviderRow | null = null; @@ -533,16 +769,6 @@ async function handleProxyRequest( let logErrorMessage: string | null = null; try { - key = authenticate(ctx, request.headers); - ctx.events.emitRequestStart({ - id: requestId, - ts: startedAt, - surface, - model: null, - stream: false, - keyName: key.name, - }); - const body = readBody(request); const requestedModel = body.model; if (typeof requestedModel !== 'string' || requestedModel.trim().length === 0) { @@ -581,20 +807,26 @@ async function handleProxyRequest( } const normalized = normalizeBody(surface, body, model, { countTokens: route.countTokens === true }); - const upstreamBody = normalized.body; + const normalizedBody = normalized.body; + const rawBody = state.rawBody; + // Forward the client bytes verbatim whenever normalization changed nothing. + const upstreamBody = rawBody !== null && !hasLogicalChange(body, normalizedBody) ? null : normalizedBody; 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)); 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 }); guard = createRequestGuard(request, reply); - const rotation = orderProviders(providers, Date.now()); + const rotation = orderProviders(providers, Date.now(), strategy); const ordered = rotation.candidates; let lastStatus: number | null = null; let lastError: ApiError | null = null; let fatalError: ApiError | null = null; let everyFailureRateLimited = true; + let everyFailureTimeout = true; let attemptNo = 0; let aborted = false; @@ -606,38 +838,32 @@ async function handleProxyRequest( } const fresh = ctx.repo.getProvider(candidate.id); if (!fresh || !fresh.enabled) continue; - // Re-check the cooldown at attempt time; when every candidate is cooling - // down the request is a best-effort fallback and we try anyway. + // Cooldown-skipped providers are not upstream calls: no attempt row, and no + // increment of the attempts counter (FIX-17 keeps the header/timeline honest). if (!rotation.cooldownFallback && fresh.cooldownUntil !== null && fresh.cooldownUntil > Date.now()) { - attemptNo += 1; - ctx.repo.insertAttempt( - newAttempt({ - requestId, - providerId: fresh.id, - providerName: fresh.name, - attempt: attemptNo, - status: null, - ok: false, - errorCode: 'provider_cooldown', - errorMessage: 'Provider is cooling down; attempt skipped.', - latencyMs: null, - }), - ); continue; } attempts += 1; attemptNo += 1; - const attempt = await runAttempt(ctx, fresh, route, upstreamBody, { + const attempt = await runAttempt(ctx, fresh, route, { requestId, attempt: attemptNo, timeoutMs, cooldownMs, userAgent: upstreamUserAgent, signal: guard.signal, + headers: requestHeaders, + rawBody: upstreamBody === null ? rawBody : null, + body: normalizedBody, + stream, }); 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' }); + } aborted = true; break; } @@ -645,7 +871,16 @@ async function handleProxyRequest( if (attempt.kind === 'ok') { provider = fresh; const outcome = stream - ? await streamSurface(reply, surface, requestId, fresh, attempt.response, attempts, startedAt, guard) + ? await streamSurface({ + reply, + requestId, + provider: fresh, + upstream: attempt.response, + attempts, + requestStartedAt: startedAt, + guard, + idleMs: timeoutMs, + }) : await jsonSurface(reply, surface, requestId, fresh, attempt.response, attempts, attempt.latencyMs); usage = outcome.usage; ttfbMs = outcome.ttfbMs; @@ -654,14 +889,29 @@ async function handleProxyRequest( logErrorCode = outcome.errorCode; logErrorMessage = outcome.errorMessage; if (outcome.aborted) aborted = true; + if (!outcome.ok && !outcome.aborted && !reply.raw.headersSent && !reply.raw.writableEnded) { + // A failure detected before any bytes were written still owes the client + // a surface-shaped error (a response body that timed out mid-read). + throw new ApiError( + outcome.timedOut ? 'timeout_error' : 'api_error', + outcome.errorMessage ?? 'The upstream response could not be forwarded.', + { status: outcome.status, code: outcome.errorCode ?? undefined }, + ); + } break; } lastStatus = attempt.status; lastError = attempt.error; if (attempt.status !== 429) everyFailureRateLimited = false; + // Only a real deadline abort makes the whole request a timeout: a refused + // connection (or any other network error) is still `all_providers_failed`. + if (attempt.status !== null || !isTimeoutFailure(attempt.error)) everyFailureTimeout = false; if (attempt.kind === 'fatal') { fatalError = attempt.error; + // Attribute the log row and `x-opencode-router-provider` to the provider + // that actually answered, even though the error is re-thrown (FIX-18). + provider = fresh; break; } } @@ -680,8 +930,17 @@ async function handleProxyRequest( 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). + throw new ApiError('timeout_error', lastError?.message ?? 'Every provider timed out.', { + status: 504, + code: 'upstream_timeout', + }); } else { - const status = lastStatus ?? 502; + // A 3xx from upstream is never replayed to the client as a redirect + // (FIX-08), so only real error statuses are forwarded. + const status = lastStatus !== null && lastStatus >= 400 ? lastStatus : (lastError?.status ?? 502); throw new ApiError( lastError?.type ?? 'api_error', lastError?.message ?? 'No provider could serve the request; every provider is cooling down.', @@ -689,6 +948,11 @@ async function handleProxyRequest( ); } } + if (fatalError) { + // The provider is already attributed (FIX-18) but the client error must + // still be re-thrown instead of leaving the reply empty. + throw fatalError; + } } catch (error) { if (guard?.aborted) { logStatus = 499; @@ -704,18 +968,24 @@ async function handleProxyRequest( logOk = false; logErrorCode = apiError.code ?? apiError.type; logErrorMessage = apiError.message; + // A fatal upstream error still answered by a provider: keep the router + // attribution headers truthful (FIX-18) alongside the error body. + if (provider !== null && !reply.raw.headersSent && !reply.raw.writableEnded) { + for (const [name, value] of Object.entries(routerHeaders(provider, requestId, attempts))) { + reply.header(name, value); + } + } sendApiError(reply, surface, apiError, requestId); } } finally { guard?.dispose(); decActiveRequests(); - const log: RequestLogRow = { - id: requestId, - ts: startedAt, - keyId: key?.id ?? null, - keyName: key?.name ?? null, - providerId: provider?.id ?? null, - providerName: provider?.name ?? null, + state.logged = true; + recordRequestLog(ctx, { + requestId, + startedAt, + key, + provider, model: modelId, surface, stream, @@ -723,22 +993,19 @@ async function handleProxyRequest( ok: logOk, errorCode: logErrorCode, errorMessage: logErrorMessage, - latencyMs: Date.now() - startedAt, ttfbMs, - inputTokens: usage.inputTokens, - outputTokens: usage.outputTokens, - totalTokens: usage.totalTokens, - reasoningTokens: usage.reasoningTokens, - cachedTokens: usage.cachedTokens, + usage, attempts, clientIp, userAgent: clientUserAgent, - }; - try { - ctx.repo.insertLog(log); - } catch (error) { - ctx.logger.warn({ err: error, requestId }, 'failed to insert gateway request log'); - } - ctx.events.emitRequestEnd({ log }); + }); + } +} + +export function registerProxyRoutes(app: FastifyInstance, ctx: AppContext): void { + for (const route of PROXY_ROUTES) { + app.post(route.url, async (request: FastifyRequest, reply: FastifyReply) => { + await handleProxyRequest(ctx, request, reply, route); + }); } } diff --git a/src/gateway/rotation.ts b/src/gateway/rotation.ts index 95ea75f..4e8697c 100644 --- a/src/gateway/rotation.ts +++ b/src/gateway/rotation.ts @@ -1,8 +1,19 @@ import type { ProviderRow } from '../types.js'; +export type RotationStrategy = 'round-robin' | 'priority' | 'random'; + +const ROTATION_STRATEGIES: readonly RotationStrategy[] = ['round-robin', 'priority', 'random']; + +/** Unknown or missing setting values fall back to the documented default. */ +export function parseRotationStrategy(value: string | null): RotationStrategy { + return value !== null && (ROTATION_STRATEGIES as readonly string[]).includes(value) + ? (value as RotationStrategy) + : 'round-robin'; +} + /** * In-memory round-robin cursor. Requests start at the next enabled provider so - * load is spread across the whole candidate set. + * load is spread across the whole candidate set. Only `round-robin` uses it. */ let cursor = 0; @@ -14,6 +25,38 @@ export function enabledProviders(providers: ProviderRow[]): ProviderRow[] { return providers.filter((provider) => provider.enabled); } +/** Fisher-Yates shuffle on a copy; the cursor is meaningless for `random`. */ +function shuffled(providers: ProviderRow[]): ProviderRow[] { + const items = [...providers]; + for (let index = items.length - 1; index > 0; index -= 1) { + const swap = Math.floor(Math.random() * (index + 1)); + const current = items[index]!; + items[index] = items[swap]!; + items[swap] = current; + } + return items; +} + +/** + * Puts the candidates in attempt order for the configured strategy: + * + * - `round-robin` rotates the list so it starts after the cursor (advancing it). + * - `priority` keeps the repo order (priority asc, created_at asc) and ignores + * the cursor, so the highest-priority provider always goes first. + * - `random` shuffles the candidates. + */ +function orderedProviders( + providers: ProviderRow[], + strategy: RotationStrategy = 'round-robin', +): ProviderRow[] { + if (providers.length === 0) return []; + if (strategy === 'random') return shuffled(providers); + if (strategy === 'priority') return [...providers]; + const start = cursor % providers.length; + cursor = (start + 1) % providers.length; + return [...providers.slice(start), ...providers.slice(0, start)]; +} + export interface ProviderRotation { /** Providers to try, in attempt order. */ candidates: ProviderRow[]; @@ -24,21 +67,21 @@ export interface ProviderRotation { /** * Rotation + failover order for one request. * - * - candidates: enabled providers ordered by `priority` asc then `created_at` asc - * (the repo query already guarantees that order). - * - the list is rotated so the first candidate is the next one after the cursor. + * - enabled providers are ordered by the requested strategy; * - providers whose `cooldown_until` is in the future are skipped; when every * candidate is cooling down the least-cooling one goes first so the gateway * still has a chance instead of failing outright (`cooldownFallback`). */ -export function orderProviders(providers: ProviderRow[], now = Date.now()): ProviderRotation { +export function orderProviders( + providers: ProviderRow[], + now = Date.now(), + strategy: RotationStrategy = 'round-robin', +): ProviderRotation { const enabled = enabledProviders(providers); if (enabled.length === 0) return { candidates: [], cooldownFallback: false }; - const start = cursor % enabled.length; - cursor = (start + 1) % enabled.length; - const rotated = [...enabled.slice(start), ...enabled.slice(0, start)]; - const warm = rotated.filter((provider) => provider.cooldownUntil === null || provider.cooldownUntil <= now); + const ordered = orderedProviders(enabled, strategy); + const warm = ordered.filter((provider) => provider.cooldownUntil === null || provider.cooldownUntil <= now); if (warm.length > 0) return { candidates: warm, cooldownFallback: false }; - const leastCooling = [...rotated].sort((a, b) => (a.cooldownUntil ?? 0) - (b.cooldownUntil ?? 0)); + const leastCooling = [...ordered].sort((a, b) => (a.cooldownUntil ?? 0) - (b.cooldownUntil ?? 0)); return { candidates: leastCooling, cooldownFallback: true }; } diff --git a/src/server.ts b/src/server.ts index 678e70a..c06d9cd 100644 --- a/src/server.ts +++ b/src/server.ts @@ -2,7 +2,7 @@ import Fastify, { type FastifyInstance } from 'fastify'; import fastifyCookie from '@fastify/cookie'; import fastifyStatic from '@fastify/static'; import { existsSync, mkdirSync } from 'node:fs'; -import { join, resolve } from 'node:path'; +import { isAbsolute, join, relative, resolve } from 'node:path'; import type { AppContext } from './core/context.js'; import { ApiError } from './util/errors.js'; import { registerGatewayRoutes } from './gateway/index.js'; @@ -25,8 +25,7 @@ export async function buildServer(ctx: AppContext): Promise { : { target: 'pino-pretty', options: { colorize: true, translateTime: 'HH:MM:ss', ignore: 'pid,hostname' } }, }, bodyLimit: ctx.config.bodyLimit, - trustProxy: true, - disableRequestLogging: true, + trustProxy: ctx.config.trustProxy, routerOptions: { ignoreTrailingSlash: true }, }); ctx.logger = app.log; @@ -49,7 +48,7 @@ export async function buildServer(ctx: AppContext): Promise { status: 'ok', name: 'OpenCode Router', version: '1.0.0', - uptimeMs: Date.now() - Date.now(), + uptimeMs: Date.now() - ctx.startedAt, startedAt: ctx.startedAt, providers: ctx.repo.listProviders().filter((provider) => provider.enabled).length, models: ctx.repo.enabledModelIds().length, @@ -69,7 +68,7 @@ export async function buildServer(ctx: AppContext): Promise { .status(200) .type('text/html; charset=utf-8') .send( - `OpenCode Router

OpenCode Router

Dashboard chưa được build. Chạy pnpm build:web để tạo web/dist.

API endpoints: /v1/chat/completions, /v1/responses, /v1/messages

`, + `OpenCode Router

OpenCode Router

The dashboard has not been built yet. Run pnpm build:web to generate web/dist.

API endpoints: /v1/chat/completions, /v1/responses, /v1/messages

`, ); }; @@ -97,7 +96,10 @@ export async function buildServer(ctx: AppContext): Promise { app.get('/assets/*', async (request, reply) => { const wildcard = (request.params as { '*': string })['*']; const filePath = resolve(webDist, 'assets', wildcard); - if (!filePath.startsWith(resolve(webDist)) || !existsSync(filePath)) { + // Directory containment check: a prefix test would also accept sibling + // directories such as `web/dist-evil`. + const relativePath = relative(webDist, filePath); + if (relativePath.startsWith('..') || isAbsolute(relativePath) || !existsSync(filePath)) { await reply.status(404).send({ error: { message: 'Not found', type: 'not_found_error' } }); return; } @@ -116,6 +118,11 @@ export async function buildServer(ctx: AppContext): Promise { await reply.status(404).send({ error: { message: 'Not found', code: 'not_found' } }); return; } + // The dashboard shell is gated server-side for every path that serves it. + if (!resolveSession(ctx, request)) { + await reply.redirect('/login', 302); + return; + } await sendSpa(request, reply); }); diff --git a/src/util/errors.ts b/src/util/errors.ts index acebf66..56ce087 100644 --- a/src/util/errors.ts +++ b/src/util/errors.ts @@ -40,7 +40,6 @@ export class ApiError extends Error { } toJSON(surface: Surface): Record { - const event = { type: 'error', message: this.message } as Record; if (surface === 'messages') { return { type: 'error', @@ -55,7 +54,6 @@ export class ApiError extends Error { type: this.type === 'not_found_error' ? 'invalid_request_error' : this.type, param: this.param, code: this.code, - ...(event ? {} : {}), }, }; } @@ -96,29 +94,3 @@ export function upstreamErrorFrom(status: number, body: string, provider: string } return new ApiError(type, message, { status, code: code ?? undefined }); } - -export function anthropicErrorType(type: ErrorType): string { - switch (type) { - case 'invalid_request_error': - return 'invalid_request_error'; - case 'authentication_error': - return 'authentication_error'; - case 'permission_error': - return 'permission_error'; - case 'not_found_error': - return 'not_found_error'; - case 'rate_limit_error': - return 'rate_limit_error'; - case 'overloaded_error': - return 'overloaded_error'; - case 'timeout_error': - return 'api_error'; - case 'connection_error': - case 'upstream_error': - return 'api_error'; - default: - return 'api_error'; - } -} - -export const ERROR_STATUS: Record = STATUS_BY_TYPE; \ No newline at end of file diff --git a/src/util/upstream.ts b/src/util/upstream.ts index c4330e3..8832dda 100644 --- a/src/util/upstream.ts +++ b/src/util/upstream.ts @@ -12,11 +12,17 @@ export interface UpstreamRequest { apiKey: string; path: string; method?: string; + /** Structured body: serialized with JSON.stringify unless `rawBody` is set. */ body?: unknown; + /** Client body kept byte-for-byte; takes precedence over `body`. */ + rawBody?: string; + /** Extra request headers (client beta/trace headers); router auth headers win. */ headers?: Record; timeoutMs?: number; signal?: AbortSignal | null; userAgent?: string; + /** `manual` (default) refuses to follow redirects so credentials never leave the origin. */ + redirect?: 'manual' | 'follow'; } export interface UpstreamResponse { @@ -24,6 +30,16 @@ export interface UpstreamResponse { ok: boolean; headers: Headers; response: Response; + /** + * Releases the internal timeout + abort listener. Call it when the body has been + * consumed or cancelled, otherwise the timeout keeps ticking (which is what makes + * `timeoutMs` a real total deadline for streaming responses). + */ + dispose(): void; + /** Aborts the in-flight upstream request/body read (idle timeout, client gone). */ + abort(reason: string): void; + /** Reason passed to the last `abort()` call, or null. */ + readonly abortReason: string | null; } /** @@ -33,13 +49,28 @@ export interface UpstreamResponse { export async function upstreamFetch(req: UpstreamRequest): Promise { const url = joinUrl(req.baseUrl, req.path); const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(new Error('upstream timeout')), req.timeoutMs ?? 600_000); - const onAbort = (): void => controller.abort(new Error('client aborted')); + let abortReason: string | null = null; + const abortWith = (reason: string): void => { + if (abortReason === null) abortReason = reason; + if (!controller.signal.aborted) controller.abort(new Error(reason)); + }; + const onSignalAbort = (): void => abortWith('client aborted'); if (req.signal) { - if (req.signal.aborted) onAbort(); - else req.signal.addEventListener('abort', onAbort, { once: true }); + if (req.signal.aborted) onSignalAbort(); + else req.signal.addEventListener('abort', onSignalAbort, { once: true }); } + // Kept alive until dispose(): a streamed body must stay bounded by the timeout too. + const timeout = + req.timeoutMs === undefined + ? null + : setTimeout(() => abortWith('upstream timeout'), Math.max(1, req.timeoutMs)); + + const detach = (): void => { + if (timeout) clearTimeout(timeout); + if (req.signal) req.signal.removeEventListener('abort', onSignalAbort); + }; + const headers: Record = { 'content-type': 'application/json', accept: 'application/json', @@ -49,24 +80,46 @@ export async function upstreamFetch(req: UpstreamRequest): Promise (session && session.id === id ? session : null), + deleteSession: (id: string) => { + deleted.push(id); + }, + }, + } as unknown as AppContext; + return { ctx, deleted }; +} + +function requestWith(cookie?: string): FastifyRequest { + return { cookies: cookie === undefined ? {} : { [SESSION_COOKIE]: cookie } } as unknown as FastifyRequest; +} + +describe('session cookie format', () => { + it('round-trips sid, expiry and signature', () => { + const expiresAt = Date.now() + 60_000; + const cookie = buildSessionCookie(SECRET, 'sid-1', expiresAt); + const parsed = parseSessionCookie(cookie); + expect(parsed).toEqual({ sid: 'sid-1', expiresAt, signature: signSession(SECRET, 'sid-1', expiresAt) }); + expect(cookie.split('.')).toHaveLength(3); + }); + + it('rejects malformed cookie values', () => { + expect(parseSessionCookie(undefined)).toBeNull(); + expect(parseSessionCookie(null)).toBeNull(); + expect(parseSessionCookie('')).toBeNull(); + expect(parseSessionCookie('sid-only')).toBeNull(); + expect(parseSessionCookie('sid.1.2.3')).toBeNull(); + expect(parseSessionCookie('sid.not-a-number.sig')).toBeNull(); + expect(parseSessionCookie('.123.sig')).toBeNull(); + expect(parseSessionCookie('sid.123.')).toBeNull(); + }); + + it('changes the signature when the payload is tampered with', () => { + const expiresAt = Date.now() + 60_000; + const original = signSession(SECRET, 'sid-1', expiresAt); + expect(signSession(SECRET, 'sid-1', expiresAt + 1)).not.toBe(original); + expect(signSession(SECRET, 'sid-2', expiresAt)).not.toBe(original); + expect(signSession('other-secret', 'sid-1', expiresAt)).not.toBe(original); + }); +}); + +describe('resolveSession', () => { + it('accepts a valid signature + live row', () => { + const session = row('sid-1'); + const { ctx } = contextWith(session); + const cookie = buildSessionCookie(SECRET, session.id, session.expiresAt); + const resolved = resolveSession(ctx, requestWith(cookie)); + expect(resolved?.session.id).toBe('sid-1'); + expect(resolved?.payload.sid).toBe('sid-1'); + }); + + it('rejects a tampered signature', () => { + const session = row('sid-1'); + const { ctx } = contextWith(session); + const payload = parseSessionCookie(buildSessionCookie(SECRET, session.id, session.expiresAt))!; + const tampered = `${payload.sid}.${payload.expiresAt}.${'0'.repeat(payload.signature.length)}`; + expect(resolveSession(ctx, requestWith(tampered))).toBeNull(); + }); + + it('rejects an already-expired cookie without touching the DB', () => { + const session = row('sid-1', Date.now() - 1); + const { ctx, deleted } = contextWith(session); + const cookie = buildSessionCookie(SECRET, session.id, session.expiresAt); + expect(resolveSession(ctx, requestWith(cookie))).toBeNull(); + expect(deleted).toEqual([]); + }); + + it('rejects unknown sessions and drops DB-expired rows', () => { + const unknown = contextWith(null); + const cookie = buildSessionCookie(SECRET, 'missing', Date.now() + 60_000); + expect(resolveSession(unknown.ctx, requestWith(cookie))).toBeNull(); + + const expired = row('sid-2', Date.now() - 1); + const { ctx, deleted } = contextWith(expired); + // The cookie itself is still "live"; the DB row is what has expired. + const liveCookie = buildSessionCookie(SECRET, 'sid-2', Date.now() + 60_000); + expect(resolveSession(ctx, requestWith(liveCookie))).toBeNull(); + expect(deleted).toEqual(['sid-2']); + }); + + it('rejects a request with no cookie at all', () => { + const { ctx } = contextWith(row('sid-1')); + expect(resolveSession(ctx, requestWith())).toBeNull(); + }); +}); diff --git a/tests/admin-util.test.ts b/tests/admin-util.test.ts new file mode 100644 index 0000000..a52a1f7 --- /dev/null +++ b/tests/admin-util.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, it } from 'vitest'; +import { + HttpError, + asTimestamp, + assertPublicProviderUrl, + csvEscape, + maskApiKey, + queryInt, + queryTimestamp, +} from '../src/admin/util.js'; + +describe('csvEscape', () => { + it('prefixes formula triggers with a single quote', () => { + expect(csvEscape('=1+1')).toBe("'=1+1"); + expect(csvEscape('+SUM(A1)')).toBe("'+SUM(A1)"); + expect(csvEscape('-2')).toBe("'-2"); + expect(csvEscape('@x')).toBe("'@x"); + expect(csvEscape('\tcmd')).toBe("'\tcmd"); + expect(csvEscape('\rcmd')).toBe(`"'\rcmd"`); + }); + + it('quotes and doubles RFC 4180 specials', () => { + expect(csvEscape('a,b')).toBe('"a,b"'); + expect(csvEscape('say "hi"')).toBe('"say ""hi"""'); + expect(csvEscape('line1\nline2')).toBe('"line1\nline2"'); + expect(csvEscape('plain text')).toBe('plain text'); + }); + + it('neutralises injection before quoting', () => { + expect(csvEscape('=HYPERLINK("http://evil","x")')).toBe(`"'=HYPERLINK(""http://evil"",""x"")"`); + }); + + it('renders null/undefined as empty and scalars as text', () => { + expect(csvEscape(null)).toBe(''); + expect(csvEscape(undefined)).toBe(''); + expect(csvEscape(0)).toBe('0'); + expect(csvEscape(12)).toBe('12'); + expect(csvEscape(true)).toBe('true'); + }); +}); + +describe('queryTimestamp', () => { + it('passes through absent values', () => { + expect(queryTimestamp(null, 'since')).toBeNull(); + expect(queryTimestamp(undefined, 'since')).toBeNull(); + expect(queryTimestamp('', 'since')).toBeNull(); + }); + + it('parses unix timestamps, numeric strings and ISO dates', () => { + expect(queryTimestamp(1_700_000_000_000, 'since')).toBe(1_700_000_000_000); + expect(queryTimestamp('1700000000', 'since')).toBe(1_700_000_000); + expect(queryTimestamp('2026-01-02T03:04:05Z', 'since')).toBe(Date.parse('2026-01-02T03:04:05Z')); + }); + + it('throws a 400 HttpError for junk instead of silently dropping the filter', () => { + expect(() => queryTimestamp('not-a-date', 'since')).toThrow(HttpError); + try { + queryTimestamp('not-a-date', 'since'); + } catch (error) { + const httpError = error as HttpError; + expect(httpError.statusCode).toBe(400); + expect(httpError.code).toBe('invalid_request'); + expect(httpError.message).toContain('since'); + } + }); +}); + +describe('queryInt', () => { + it('accepts integers inside the range', () => { + expect(queryInt(5, 'limit', 1, 500)).toBe(5); + expect(queryInt('5', 'limit', 1, 500)).toBe(5); + }); + + it('rejects fractional and out-of-range values', () => { + expect(() => queryInt('2.9', 'limit', 1, 500)).toThrow(HttpError); + expect(() => queryInt(0, 'limit', 1, 500)).toThrow(HttpError); + expect(() => queryInt(501, 'limit', 1, 500)).toThrow(HttpError); + expect(() => queryInt(undefined, 'limit', 1, 500)).toThrow(HttpError); + expect(() => queryInt('abc', 'limit', 1, 500)).toThrow(HttpError); + expect(() => queryInt('', 'limit', 1, 500)).toThrow(HttpError); + }); +}); + +describe('asTimestamp', () => { + it('parses the accepted shapes and returns null for junk', () => { + expect(asTimestamp(null)).toBeNull(); + expect(asTimestamp('')).toBeNull(); + expect(asTimestamp(' ')).toBeNull(); + expect(asTimestamp('1700000000')).toBe(1_700_000_000); + expect(asTimestamp(1_700_000_000_000)).toBe(1_700_000_000_000); + expect(asTimestamp(1_700_000_000.9)).toBe(1_700_000_000); + expect(asTimestamp('2026-01-02T03:04:05Z')).toBe(Date.parse('2026-01-02T03:04:05Z')); + expect(asTimestamp('not-a-date')).toBeNull(); + expect(asTimestamp([1])).toBeNull(); + }); +}); + +describe('assertPublicProviderUrl', () => { + const blocked = [ + 'http://127.0.0.1:20125/v1', + 'http://127.1.2.3/v1', + 'http://0.0.0.0:20125/v1', + 'http://[::1]:20125/v1', + 'http://10.0.0.5/v1', + 'http://172.16.5.4/v1', + 'http://172.31.255.1/v1', + 'http://192.168.1.1/v1', + 'http://169.254.169.254/latest/meta-data', + 'http://localhost:20125/v1', + 'http://api.localhost/v1', + 'http://[::ffff:127.0.0.1]/v1', + 'http://[::ffff:7f00:1]/v1', + 'http://[fc00::1]/v1', + 'http://[fe80::1]/v1', + ]; + + it('rejects loopback, link-local and private hosts by default', () => { + for (const url of blocked) { + expect(() => assertPublicProviderUrl(url, false), url).toThrow(HttpError); + } + }); + + it('allows public hosts', () => { + expect(() => assertPublicProviderUrl('https://api.openai.com/v1', false)).not.toThrow(); + expect(() => assertPublicProviderUrl('https://openrouter.ai/api/v1', false)).not.toThrow(); + expect(() => assertPublicProviderUrl('http://8.8.8.8/v1', false)).not.toThrow(); + }); + + it('permits private hosts when allowPrivate=true', () => { + expect(() => assertPublicProviderUrl('http://127.0.0.1:9/v1', true)).not.toThrow(); + expect(() => assertPublicProviderUrl('http://localhost/v1', true)).not.toThrow(); + }); + + it('rejects malformed URLs with a 400', () => { + expect(() => assertPublicProviderUrl('not a url', false)).toThrow(HttpError); + try { + assertPublicProviderUrl('not a url', false); + } catch (error) { + expect((error as HttpError).statusCode).toBe(400); + } + }); +}); + +describe('maskApiKey', () => { + it('never exposes the full key', () => { + expect(maskApiKey(null)).toBe(''); + expect(maskApiKey(undefined)).toBe(''); + expect(maskApiKey('')).toBe(''); + expect(maskApiKey('short')).toBe('****'); + expect(maskApiKey('12345678')).toBe('****'); + expect(maskApiKey('sk-abcdefghijkl')).toBe('sk-a...ijkl'); + expect(maskApiKey('sk-abcdefghijkl')).not.toContain('bcdefgh'); + }); +}); \ No newline at end of file diff --git a/tests/db-repos.test.ts b/tests/db-repos.test.ts new file mode 100644 index 0000000..d389fc2 --- /dev/null +++ b/tests/db-repos.test.ts @@ -0,0 +1,151 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import type { AttemptRow, RequestLogRow } from '../src/types.js'; +import { createTestDb, type TestDb } from './helpers.js'; + +let db: TestDb; + +beforeEach(() => { + db = createTestDb('okr-repo-'); +}); + +afterEach(() => { + db.cleanup(); +}); + +function makeLog(overrides: Partial & { id: string }): RequestLogRow { + return { + ts: Date.now(), + keyId: 'k1', + keyName: 'e2e', + providerId: 'p1', + providerName: 'Primary', + model: 'a/model', + surface: 'chat', + stream: false, + status: 200, + ok: true, + errorCode: null, + errorMessage: null, + latencyMs: 10, + ttfbMs: 5, + inputTokens: 1, + outputTokens: 2, + totalTokens: 3, + reasoningTokens: 0, + cachedTokens: 0, + attempts: 1, + clientIp: '127.0.0.1', + userAgent: 'test', + ...overrides, + }; +} + +function makeAttempt(overrides: Partial & { id: string; requestId: string }): AttemptRow { + return { + ts: Date.now(), + providerId: 'p1', + providerName: 'Primary', + attempt: 1, + status: 200, + ok: true, + errorCode: null, + errorMessage: null, + latencyMs: 5, + ...overrides, + }; +} + +describe('repo: sessions', () => { + it('deleteOtherSessions removes every other session, past the LIMIT 50', () => { + for (let index = 0; index < 60; index += 1) { + db.repo.createSession({ id: `s${index}`, ttlMs: 60_000, clientIp: null, userAgent: null }); + } + expect(db.repo.listSessions()).toHaveLength(50); // the list view is capped on purpose + + expect(db.repo.deleteOtherSessions('s0')).toBe(59); + expect(db.repo.getSession('s0')).not.toBeNull(); + expect(db.repo.listSessions()).toHaveLength(1); + + expect(db.repo.deleteOtherSessions(null)).toBe(1); + expect(db.repo.listSessions()).toHaveLength(0); + }); +}); + +describe('repo: stats', () => { + it('reports exact requestsLast60s/errorsLast60s independent of the bucket size', () => { + const now = Date.now(); + db.repo.insertLog(makeLog({ id: 'recent-ok', ts: now - 1_000, ok: true, status: 200 })); + db.repo.insertLog(makeLog({ id: 'recent-err', ts: now - 2_000, ok: false, status: 500, errorCode: 'boom' })); + db.repo.insertLog(makeLog({ id: 'old-err', ts: now - 120_000, ok: false, status: 500, errorCode: 'boom' })); + + const stats = db.repo.statsOverview(3_600_000, 60_000, 0); + expect(stats.totals.requests).toBe(3); + expect(stats.totals.errors).toBe(2); + expect(stats.requestsLast60s).toBe(2); + expect(stats.errorsLast60s).toBe(1); + }); + + it('computes latency percentiles from the window', () => { + for (const [index, latency] of [10, 20, 30, 40, 50].entries()) { + db.repo.insertLog(makeLog({ id: `l${index}`, latencyMs: latency, ts: Date.now() - 1_000 })); + } + const stats = db.repo.statsOverview(3_600_000, 60_000, 0); + expect(stats.totals.p50LatencyMs).toBe(30); + expect(stats.totals.p95LatencyMs).toBe(50); + }); +}); + +describe('repo: audit retention', () => { + it('deleteAuditBefore prunes by timestamp', () => { + db.repo.audit('dashboard', 'a', null, null); + db.repo.audit('dashboard', 'b', null, null); + expect(db.repo.deleteAuditBefore(Date.now() - 60_000)).toBe(0); + expect(db.repo.deleteAuditBefore(Date.now() + 1_000)).toBe(2); + expect(db.repo.listAudit()).toHaveLength(0); + }); +}); + +describe('repo: log queries', () => { + it('honours since: 0 and treats % / _ in search as literals', () => { + const now = Date.now(); + db.repo.insertLog(makeLog({ id: 'l1', ts: now - 5_000, model: 'a%b' })); + db.repo.insertLog(makeLog({ id: 'l2', ts: now - 4_000, model: 'axb' })); + db.repo.insertLog(makeLog({ id: 'l3', ts: now - 3_000, model: 'plain' })); + + expect(db.repo.listLogs({ since: 0 }).total).toBe(3); + expect(db.repo.listLogs({ search: '%' }).total).toBe(1); + expect(db.repo.listLogs({ search: '%' }).rows[0]?.model).toBe('a%b'); + expect(db.repo.listLogs({ search: '_' }).total).toBe(0); + expect(db.repo.listLogs({ since: 0, until: now - 3_500 }).total).toBe(2); + expect(db.repo.listLogs({ ok: false }).total).toBe(0); + }); + + it('deleteLogsBefore cascades into request_attempts', () => { + const now = Date.now(); + db.repo.insertLog(makeLog({ id: 'x', ts: now })); + db.repo.insertAttempt(makeAttempt({ id: 'a1', requestId: 'x', ts: now })); + expect(db.repo.deleteLogsBefore(now + 1)).toBe(1); + expect(db.repo.listAttempts('x')).toHaveLength(0); + }); +}); + +describe('repo: api key rotation', () => { + it('swaps the plaintext while preserving identity and counters', () => { + const { row, plaintext } = db.repo.createApiKey('laptop'); + db.repo.touchApiKey(row.id); + db.repo.touchApiKey(row.id); + + const replacement = 'okr-ffffffffffffffffffffffffffffffff'; + const rotated = db.repo.rotateApiKey(row.id, replacement); + expect(rotated?.id).toBe(row.id); + expect(rotated?.name).toBe('laptop'); + expect(rotated?.requestCount).toBe(2); + expect(rotated?.keyHash).not.toBe(row.keyHash); + expect(rotated?.keyPrefix).toBe('okr-ffff'); + expect(rotated?.keySuffix).toBe('ffff'); + + expect(db.repo.findApiKeyByPlaintext(plaintext)).toBeNull(); + expect(db.repo.findApiKeyByPlaintext(replacement)?.id).toBe(row.id); + expect(db.repo.rotateApiKey('missing', replacement)).toBeNull(); + }); +}); diff --git a/tests/gateway-normalize.test.ts b/tests/gateway-normalize.test.ts new file mode 100644 index 0000000..862e844 --- /dev/null +++ b/tests/gateway-normalize.test.ts @@ -0,0 +1,149 @@ +import { describe, expect, it } from 'vitest'; +import { effortFromThinking, normalizeBody, requestedEffortFor } from '../src/gateway/normalize.js'; +import type { Json, ModelRow } from '../src/types.js'; + +function model(patch: Partial = {}): ModelRow { + return { + id: 'test/model', + name: 'Test Model', + providerId: 'p1', + contextLength: null, + maxOutputTokens: null, + capabilities: { tools: true, input: ['text'], output: ['text'], temperature: true }, + reasoning: { supported: true, efforts: ['low', 'high'], defaultEffort: 'low' }, + enabled: true, + source: 'sync', + createdAt: 0, + updatedAt: 0, + ...patch, + }; +} + +const reasoningModel = model(); +const plainModel = model({ reasoning: { supported: false, efforts: [], defaultEffort: null } }); + +describe('requestedEffortFor', () => { + it('reads the chat surface reasoning_effort', () => { + expect(requestedEffortFor('chat', { reasoning_effort: ' high ' })).toBe('high'); + expect(requestedEffortFor('chat', { reasoning_effort: '' })).toBeNull(); + expect(requestedEffortFor('chat', {})).toBeNull(); + expect(requestedEffortFor('chat', { reasoning_effort: 42 })).toBeNull(); + }); + + it('reads the responses surface reasoning.effort', () => { + expect(requestedEffortFor('responses', { reasoning: { effort: 'low' } })).toBe('low'); + expect(requestedEffortFor('responses', { reasoning: { effort: 3 } })).toBeNull(); + expect(requestedEffortFor('responses', { reasoning: 'low' })).toBeNull(); + expect(requestedEffortFor('responses', {})).toBeNull(); + }); + + it('maps the messages surface thinking budget', () => { + expect(requestedEffortFor('messages', { thinking: { type: 'enabled', budget_tokens: 1024 } })).toBe('low'); + expect(requestedEffortFor('messages', { thinking: { type: 'enabled', budget_tokens: 16385 } })).toBe('max'); + expect(requestedEffortFor('messages', {})).toBeNull(); + }); +}); + +describe('effortFromThinking', () => { + it('maps budget tokens onto the canonical effort ladder', () => { + expect(effortFromThinking({ type: 'enabled', budget_tokens: 512 })).toBe('low'); + expect(effortFromThinking({ type: 'enabled', budget_tokens: 1024 })).toBe('low'); + expect(effortFromThinking({ type: 'enabled', budget_tokens: 1025 })).toBe('medium'); + expect(effortFromThinking({ type: 'enabled', budget_tokens: 4096 })).toBe('medium'); + expect(effortFromThinking({ type: 'enabled', budget_tokens: 4097 })).toBe('high'); + expect(effortFromThinking({ type: 'enabled', budget_tokens: 16384 })).toBe('high'); + expect(effortFromThinking({ type: 'enabled', budget_tokens: 16385 })).toBe('max'); + }); + + it('accepts numeric strings and enabled-without-budget', () => { + expect(effortFromThinking({ type: 'enabled', budget_tokens: '2048' })).toBe('medium'); + expect(effortFromThinking({ type: 'enabled' })).toBe('medium'); + }); + + it('returns null for disabled or unusable configs', () => { + expect(effortFromThinking({ type: 'disabled', budget_tokens: 5000 })).toBeNull(); + expect(effortFromThinking({ budget_tokens: 'nope' })).toBeNull(); + expect(effortFromThinking(null)).toBeNull(); + expect(effortFromThinking('enabled')).toBeNull(); + expect(effortFromThinking([1, 2])).toBeNull(); + }); +}); + +describe('normalizeBody', () => { + it('strips every reasoning hint for a non-reasoning model', () => { + const body: Json = { + model: 'test/model', + reasoning_effort: 'high', + reasoning: { effort: 'high' }, + thinking: { type: 'enabled', budget_tokens: 2000 }, + stream: true, + }; + const out = normalizeBody('chat', body, plainModel); + expect(out.requestedEffort).toBeNull(); + expect(out.appliedEffort).toBeNull(); + expect('reasoning_effort' in out.body).toBe(false); + expect('reasoning' in out.body).toBe(false); + expect('thinking' in out.body).toBe(false); + // The caller's body is never mutated. + expect(body.reasoning_effort).toBe('high'); + expect(body.thinking).toEqual({ type: 'enabled', budget_tokens: 2000 }); + // Usage injection is independent of the reasoning hints. + expect(out.usageInjected).toBe(true); + expect(out.body.stream_options).toEqual({ include_usage: true }); + }); + + it('maps a requested chat effort onto the supported list', () => { + const out = normalizeBody('chat', { model: 'm', reasoning_effort: 'xhigh' }, reasoningModel); + expect(out.requestedEffort).toBe('xhigh'); + expect(out.appliedEffort).toBe('high'); + expect(out.body.reasoning_effort).toBe('high'); + }); + + it('maps a requested responses effort and keeps sibling reasoning fields', () => { + const out = normalizeBody('responses', { model: 'm', reasoning: { effort: 'xhigh', summary: 'auto' } }, reasoningModel); + expect(out.requestedEffort).toBe('xhigh'); + expect(out.appliedEffort).toBe('high'); + expect(out.body.reasoning).toEqual({ effort: 'high', summary: 'auto' }); + }); + + it('passes an Anthropic thinking block through untouched', () => { + const thinking = { type: 'enabled', budget_tokens: 8000 }; + const out = normalizeBody('messages', { model: 'm', thinking }, reasoningModel); + expect(out.requestedEffort).toBe('high'); + expect(out.appliedEffort).toBeNull(); + expect(out.body.thinking).toEqual(thinking); + }); + + it('does not invent an effort when the client sent none', () => { + const out = normalizeBody('chat', { model: 'm' }, reasoningModel); + expect(out.requestedEffort).toBeNull(); + expect(out.appliedEffort).toBeNull(); + expect('reasoning_effort' in out.body).toBe(false); + }); + + it('injects stream_options.include_usage for chat streaming only', () => { + const injected = normalizeBody('chat', { model: 'm', stream: true }, null); + expect(injected.usageInjected).toBe(true); + expect(injected.body.stream_options).toEqual({ include_usage: true }); + + const preserved = normalizeBody('chat', { model: 'm', stream: true, stream_options: { include_usage: true, foo: 1 } }, null); + expect(preserved.usageInjected).toBe(false); + expect(preserved.body.stream_options).toEqual({ include_usage: true, foo: 1 }); + + const merged = normalizeBody('chat', { model: 'm', stream: true, stream_options: { foo: 1 } }, null); + expect(merged.usageInjected).toBe(true); + expect(merged.body.stream_options).toEqual({ foo: 1, include_usage: true }); + + expect(normalizeBody('chat', { model: 'm' }, null).usageInjected).toBe(false); + expect(normalizeBody('chat', { model: 'm', stream: true }, null, { countTokens: true }).usageInjected).toBe(false); + expect(normalizeBody('responses', { model: 'm', stream: true }, null).usageInjected).toBe(false); + expect(normalizeBody('messages', { model: 'm', stream: true }, null).usageInjected).toBe(false); + }); + + it('returns a copy rather than mutating the caller body', () => { + const body: Json = { model: 'm', stream: true }; + const out = normalizeBody('chat', body, null); + expect(out.body).not.toBe(body); + expect('stream_options' in body).toBe(false); + }); +}); diff --git a/tests/gateway-proxy-helpers.test.ts b/tests/gateway-proxy-helpers.test.ts new file mode 100644 index 0000000..7cd4a8e --- /dev/null +++ b/tests/gateway-proxy-helpers.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from 'vitest'; +import { retryAfterMs, rewriteSseFrame, stripTopLevelXOpencode, stripXOpencode } from '../src/gateway/proxy.js'; + +describe('stripXOpencode', () => { + it('removes a top-level x_opencode key into a new object', () => { + const input = { id: 'x', x_opencode: { session_id: 's' }, choices: [] }; + const out = stripXOpencode(input) as Record; + expect('x_opencode' in out).toBe(false); + expect(out.id).toBe('x'); + expect(out.choices).toEqual([]); + expect(out).not.toBe(input); + expect(input.x_opencode).toEqual({ session_id: 's' }); + }); + + it('removes x_opencode nested in the response/message wrappers', () => { + const input = { + response: { id: 'r', x_opencode: { a: 1 } }, + message: { id: 'm', x_opencode: 1 }, + }; + const out = stripXOpencode(input) as Record>; + expect('x_opencode' in out.response!).toBe(false); + expect('x_opencode' in out.message!).toBe(false); + expect(out.response!.id).toBe('r'); + }); + + it('returns the same reference when there is nothing to strip', () => { + const object = { id: 'x' }; + expect(stripXOpencode(object)).toBe(object); + const array = [1, 2]; + expect(stripXOpencode(array)).toBe(array); + expect(stripXOpencode(null)).toBeNull(); + expect(stripXOpencode('x_opencode')).toBe('x_opencode'); + expect(stripXOpencode(7)).toBe(7); + }); +}); + +describe('stripTopLevelXOpencode', () => { + it('returns the identical Buffer when nothing needs stripping', () => { + const buffer = Buffer.from('{"id":"x","choices":[]}'); + expect(stripTopLevelXOpencode(buffer)).toBe(buffer); + }); + + it('strips x_opencode from a JSON buffer', () => { + const buffer = Buffer.from(JSON.stringify({ id: 'x', x_opencode: { session_id: 's' } })); + const out = stripTopLevelXOpencode(buffer); + expect(out).not.toBe(buffer); + expect(JSON.parse(out.toString('utf8'))).toEqual({ id: 'x' }); + }); + + it('keeps non-JSON bytes that merely mention x_opencode', () => { + const buffer = Buffer.from('data: x_opencode but not json'); + expect(stripTopLevelXOpencode(buffer)).toBe(buffer); + }); +}); + +describe('rewriteSseFrame', () => { + it('returns the frame unchanged when it has no x_opencode', () => { + const frame = 'data: {"id":"x","choices":[]}'; + expect(rewriteSseFrame(frame)).toBe(frame); + }); + + it('rewrites the data line only', () => { + const frame = 'event: message\ndata: {"id":"x","x_opencode":{"session_id":"s"}}'; + const out = rewriteSseFrame(frame); + expect(out).not.toBe(frame); + expect(out.split('\n')[0]).toBe('event: message'); + expect(out).not.toContain('x_opencode'); + const data = out.split('\n').find((line) => line.startsWith('data:'))!; + expect(JSON.parse(data.slice(5).trim())).toEqual({ id: 'x' }); + }); + + it('leaves frames without a JSON data line alone', () => { + const comment = ': x_opencode comment\n\n'; + expect(rewriteSseFrame(comment)).toBe(comment); + const broken = 'data: {"x_opencode":'; + expect(rewriteSseFrame(broken)).toBe(broken); + }); +}); + +describe('retryAfterMs', () => { + it('parses delta seconds', () => { + expect(retryAfterMs('2')).toBe(2000); + expect(retryAfterMs(' 30 ')).toBe(30_000); + expect(retryAfterMs('0')).toBe(0); + }); + + it('parses an HTTP date relative to now', () => { + const now = 1_700_000_000_000; + const at = new Date(now + 5000).toUTCString(); + expect(retryAfterMs(at, now)).toBe(5000); + expect(retryAfterMs(new Date(now - 5000).toUTCString(), now)).toBe(0); + }); + + it('returns null for missing or junk values', () => { + expect(retryAfterMs(null)).toBeNull(); + expect(retryAfterMs('')).toBeNull(); + expect(retryAfterMs('soon')).toBeNull(); + }); +}); diff --git a/tests/gateway-rotation.test.ts b/tests/gateway-rotation.test.ts new file mode 100644 index 0000000..da71c71 --- /dev/null +++ b/tests/gateway-rotation.test.ts @@ -0,0 +1,108 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { orderProviders, parseRotationStrategy, resetRotationCursor } from '../src/gateway/rotation.js'; +import { provider } from './helpers.js'; + +const ids = (providers: Array<{ id: string }>): string[] => providers.map((entry) => entry.id); + +describe('orderProviders round-robin', () => { + beforeEach(() => resetRotationCursor(0)); + + it('rotates the start position and advances the cursor', () => { + const candidates = [provider('a'), provider('b'), provider('c')]; + expect(ids(orderProviders(candidates, 0, 'round-robin').candidates)).toEqual(['a', 'b', 'c']); + expect(ids(orderProviders(candidates, 0, 'round-robin').candidates)).toEqual(['b', 'c', 'a']); + expect(ids(orderProviders(candidates, 0, 'round-robin').candidates)).toEqual(['c', 'a', 'b']); + expect(ids(orderProviders(candidates, 0, 'round-robin').candidates)).toEqual(['a', 'b', 'c']); + }); + + it('honours a manually reset cursor', () => { + const candidates = [provider('a'), provider('b'), provider('c')]; + resetRotationCursor(2); + expect(ids(orderProviders(candidates, 0, 'round-robin').candidates)).toEqual(['c', 'a', 'b']); + }); +}); + +describe('orderProviders priority', () => { + beforeEach(() => resetRotationCursor(0)); + + it('keeps the repo order and ignores the cursor', () => { + resetRotationCursor(2); + const candidates = [provider('a', { priority: 1 }), provider('b', { priority: 2 }), provider('c', { priority: 3 })]; + expect(ids(orderProviders(candidates, 0, 'priority').candidates)).toEqual(['a', 'b', 'c']); + expect(ids(orderProviders(candidates, 0, 'priority').candidates)).toEqual(['a', 'b', 'c']); + }); +}); + +describe('orderProviders random', () => { + it('returns every candidate exactly once', () => { + const candidates = [provider('a'), provider('b'), provider('c'), provider('d')]; + for (let attempt = 0; attempt < 10; attempt += 1) { + const ordered = orderProviders(candidates, 0, 'random').candidates; + expect(ordered).toHaveLength(4); + expect(ids(ordered).sort()).toEqual(['a', 'b', 'c', 'd']); + } + }); +}); + +describe('orderProviders cooldown handling', () => { + const now = 1_000_000; + + it('skips cooling providers while any candidate is warm', () => { + const rotation = orderProviders( + [provider('warm'), provider('cool', { cooldownUntil: now + 5_000 })], + now, + 'priority', + ); + expect(rotation.cooldownFallback).toBe(false); + expect(ids(rotation.candidates)).toEqual(['warm']); + }); + + it('falls back to the least-cooling candidate when every one is cooling', () => { + const rotation = orderProviders( + [ + provider('late', { cooldownUntil: now + 60_000 }), + provider('soon', { cooldownUntil: now + 1_000 }), + provider('mid', { cooldownUntil: now + 5_000 }), + ], + now, + 'priority', + ); + expect(rotation.cooldownFallback).toBe(true); + expect(ids(rotation.candidates)).toEqual(['soon', 'mid', 'late']); + }); + + it('treats an elapsed cooldown as warm', () => { + const rotation = orderProviders([provider('expired', { cooldownUntil: now - 1 })], now, 'priority'); + expect(rotation.cooldownFallback).toBe(false); + expect(ids(rotation.candidates)).toEqual(['expired']); + }); +}); + +describe('orderProviders candidate set', () => { + it('ignores disabled providers', () => { + const rotation = orderProviders([provider('on'), provider('off', { enabled: false })], 0, 'priority'); + expect(ids(rotation.candidates)).toEqual(['on']); + }); + + it('returns an empty rotation when nothing is enabled', () => { + expect(orderProviders([provider('off', { enabled: false })], 0, 'priority')).toEqual({ + candidates: [], + cooldownFallback: false, + }); + expect(orderProviders([], 0, 'priority')).toEqual({ candidates: [], cooldownFallback: false }); + }); +}); + +describe('parseRotationStrategy', () => { + it('accepts the three documented strategies', () => { + expect(parseRotationStrategy('round-robin')).toBe('round-robin'); + expect(parseRotationStrategy('priority')).toBe('priority'); + expect(parseRotationStrategy('random')).toBe('random'); + }); + + it('falls back to round-robin for missing or unknown values', () => { + expect(parseRotationStrategy(null)).toBe('round-robin'); + expect(parseRotationStrategy('')).toBe('round-robin'); + expect(parseRotationStrategy('least-busy')).toBe('round-robin'); + }); +}); diff --git a/tests/gateway-usage.test.ts b/tests/gateway-usage.test.ts new file mode 100644 index 0000000..4a5b692 --- /dev/null +++ b/tests/gateway-usage.test.ts @@ -0,0 +1,139 @@ +import { describe, expect, it } from 'vitest'; +import { + extractUsageFromFrame, + extractUsageFromJson, + mergeUsage, + usageFromPayload, +} from '../src/gateway/usage.js'; +import type { Usage } from '../src/types.js'; + +describe('usageFromPayload', () => { + it('reads an OpenAI chat usage object', () => { + expect( + usageFromPayload({ + prompt_tokens: 10, + completion_tokens: 20, + total_tokens: 30, + completion_tokens_details: { reasoning_tokens: 5 }, + prompt_tokens_details: { cached_tokens: 2 }, + }), + ).toEqual({ inputTokens: 10, outputTokens: 20, totalTokens: 30, reasoningTokens: 5, cachedTokens: 2 }); + }); + + it('reads an Anthropic usage object including cache tokens', () => { + expect( + usageFromPayload({ + input_tokens: 7, + output_tokens: 3, + cache_read_input_tokens: 4, + cache_creation_input_tokens: 6, + }), + ).toEqual({ inputTokens: 7, outputTokens: 3, cachedTokens: 10 }); + }); + + it('reads a Responses usage object', () => { + expect( + usageFromPayload({ + input_tokens: 9, + output_tokens: 8, + total_tokens: 17, + input_tokens_details: { cached_tokens: 2 }, + output_tokens_details: { reasoning_tokens: 12 }, + }), + ).toEqual({ inputTokens: 9, outputTokens: 8, totalTokens: 17, reasoningTokens: 12, cachedTokens: 2 }); + }); + + it('accepts numeric strings', () => { + expect(usageFromPayload({ prompt_tokens: '5', completion_tokens: '6' })).toEqual({ + inputTokens: 5, + outputTokens: 6, + }); + }); + + it('ignores junk payloads and junk fields', () => { + expect(usageFromPayload(null)).toEqual({}); + expect(usageFromPayload(undefined)).toEqual({}); + expect(usageFromPayload('nope')).toEqual({}); + expect(usageFromPayload([1, 2])).toEqual({}); + expect(usageFromPayload({ prompt_tokens: 'abc', completion_tokens: null })).toEqual({}); + }); + + it('prefers explicit cached fields over the Anthropic cache pair', () => { + expect( + usageFromPayload({ prompt_tokens_details: { cached_tokens: 3 }, cache_read_input_tokens: 9 }), + ).toEqual({ cachedTokens: 3 }); + }); +}); + +describe('mergeUsage', () => { + const base: Usage = { inputTokens: 1, outputTokens: 2, totalTokens: 3, reasoningTokens: 4, cachedTokens: 5 }; + + it('keeps base fields the patch does not mention and re-derives the total', () => { + // Patching input/output re-derives totalTokens (1 + 7); the other fields survive. + expect(mergeUsage(base, { outputTokens: 7 })).toEqual({ + inputTokens: 1, + outputTokens: 7, + totalTokens: 8, + reasoningTokens: 4, + cachedTokens: 5, + }); + }); + + it('prefers an explicit total and otherwise derives it', () => { + expect(mergeUsage(base, { outputTokens: 7, totalTokens: 9 }).totalTokens).toBe(9); + const derived = mergeUsage({ ...base, totalTokens: 0 }, { inputTokens: 5, outputTokens: 6 }); + expect(derived.totalTokens).toBe(11); + expect(mergeUsage(base, {}).totalTokens).toBe(3); + }); + + it('leaves the base object untouched', () => { + mergeUsage(base, { inputTokens: 99 }); + expect(base.inputTokens).toBe(1); + }); +}); + +describe('extractUsageFromJson', () => { + it('prefers the top-level usage', () => { + expect(extractUsageFromJson({ usage: { prompt_tokens: 1 }, message: { usage: { input_tokens: 99 } } })).toEqual({ + inputTokens: 1, + }); + }); + + it('reads Anthropic message_start and message_delta payloads', () => { + expect( + extractUsageFromJson({ type: 'message_start', message: { usage: { input_tokens: 9, output_tokens: 0 } } }), + ).toEqual({ inputTokens: 9, outputTokens: 0 }); + expect(extractUsageFromJson({ type: 'message_delta', usage: { output_tokens: 8 } })).toEqual({ + outputTokens: 8, + }); + }); + + it('reads Responses response.completed payloads', () => { + expect( + extractUsageFromJson({ + type: 'response.completed', + response: { usage: { input_tokens: 7, output_tokens: 5, total_tokens: 12 } }, + }), + ).toEqual({ inputTokens: 7, outputTokens: 5, totalTokens: 12 }); + }); + + it('returns an empty patch for junk', () => { + expect(extractUsageFromJson(null)).toEqual({}); + expect(extractUsageFromJson('x')).toEqual({}); + expect(extractUsageFromJson([])).toEqual({}); + expect(extractUsageFromJson({ usage: 'x' })).toEqual({}); + }); +}); + +describe('extractUsageFromFrame', () => { + it('parses a JSON SSE payload', () => { + expect(extractUsageFromFrame('{"usage":{"total_tokens":11}}')).toEqual({ totalTokens: 11 }); + }); + + it('ignores [DONE], empty and non-JSON frames', () => { + expect(extractUsageFromFrame('[DONE]')).toEqual({}); + expect(extractUsageFromFrame('')).toEqual({}); + expect(extractUsageFromFrame(null)).toEqual({}); + expect(extractUsageFromFrame('not json')).toEqual({}); + }); +}); diff --git a/tests/helpers.ts b/tests/helpers.ts new file mode 100644 index 0000000..3874040 --- /dev/null +++ b/tests/helpers.ts @@ -0,0 +1,72 @@ +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { AppConfig } from '../src/config.js'; +import { openDatabase, type DbHandle } from '../src/db/index.js'; +import { Repo } from '../src/db/repos.js'; +import type { ProviderRow } from '../src/types.js'; + +/** Config fixture shared by every unit test: no env, no proxy trust, no private hosts. */ +export function testConfig(dir: string): AppConfig { + return { + host: '127.0.0.1', + port: 0, + dataDir: dir, + dbPath: join(dir, 'test.db'), + logLevel: 'silent', + bodyLimit: 1024, + defaultDashboardPassword: '123456', + secret: '', + sessionTtlMs: 1000 * 60, + webDistDir: join(dir, 'web'), + publicUrl: null, + trustProxy: false, + providerAllowPrivateHosts: false, + }; +} + +export interface TestDb { + dataDir: string; + handle: DbHandle; + repo: Repo; + cleanup(): void; +} + +/** Creates a throw-away data dir + sqlite DB + Repo for one test. */ +export function createTestDb(prefix = 'okr-test-'): TestDb { + const dataDir = mkdtempSync(join(tmpdir(), prefix)); + const handle = openDatabase(testConfig(dataDir)); + const repo = new Repo(handle.db); + return { + dataDir, + handle, + repo, + cleanup(): void { + handle.db.close(); + rmSync(dataDir, { recursive: true, force: true }); + }, + }; +} + +/** Minimal enabled ProviderRow for rotation tests. */ +export function provider(id: string, patch: Partial = {}): ProviderRow { + const now = Date.now(); + return { + id, + name: id, + baseUrl: `https://${id}.example.com/v1`, + apiKey: 'k', + enabled: true, + priority: 100, + status: 'unknown', + cooldownUntil: null, + lastError: null, + lastCheckedAt: null, + lastLatencyMs: null, + successCount: 0, + failureCount: 0, + createdAt: now, + updatedAt: now, + ...patch, + }; +} diff --git a/tests/unit.test.ts b/tests/unit.test.ts index 418dfe9..38ea6f6 100644 --- a/tests/unit.test.ts +++ b/tests/unit.test.ts @@ -2,34 +2,18 @@ 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 type { AppConfig } from '../src/config.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'; import { ApiError, isRetryableStatus, upstreamErrorFrom } from '../src/util/errors.js'; import { extractModels, normalizeProviderModel, resolveEffort } from '../src/util/models.js'; import { SseParser, formatSseJson } from '../src/util/sse.js'; +import { testConfig } from './helpers.js'; let dataDir: string; let handle: DbHandle; let repo: Repo; -function testConfig(dir: string): AppConfig { - return { - host: '127.0.0.1', - port: 0, - dataDir: dir, - dbPath: join(dir, 'test.db'), - logLevel: 'silent', - bodyLimit: 1024, - defaultDashboardPassword: '123456', - secret: '', - sessionTtlMs: 1000 * 60, - webDistDir: join(dir, 'web'), - publicUrl: null, - }; -} - beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'okr-test-')); handle = openDatabase(testConfig(dataDir)); diff --git a/tests/util-upstream.test.ts b/tests/util-upstream.test.ts new file mode 100644 index 0000000..552dc0a --- /dev/null +++ b/tests/util-upstream.test.ts @@ -0,0 +1,228 @@ +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'; + +interface TestServer { + base: string; + server: Server; + close(): Promise; +} + +const servers: TestServer[] = []; + +async function listen(handler: (req: IncomingMessage, res: ServerResponse) => void): Promise { + const server = createServer(handler); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + const port = typeof address === 'object' && address !== null ? address.port : 0; + const testServer: TestServer = { + base: `http://127.0.0.1:${port}/v1`, + server, + close: () => + new Promise((resolve) => { + server.closeAllConnections?.(); + server.close(() => resolve()); + }), + }; + servers.push(testServer); + return testServer; +} + +function bodyOf(req: IncomingMessage): Promise { + return new Promise((resolve, reject) => { + const chunks: Buffer[] = []; + req.on('data', (chunk: Buffer) => chunks.push(chunk)); + req.on('end', () => resolve(Buffer.concat(chunks))); + req.on('error', reject); + }); +} + +afterEach(async () => { + for (const server of servers.splice(0)) await server.close(); +}); + +describe('joinUrl', () => { + it('avoids duplicated slashes and /v1 prefixes', () => { + expect(joinUrl('https://x.example/v1', '/chat/completions')).toBe('https://x.example/v1/chat/completions'); + expect(joinUrl('https://x.example/v1/', 'chat/completions')).toBe('https://x.example/v1/chat/completions'); + expect(joinUrl('https://x.example', '/v1/models')).toBe('https://x.example/v1/models'); + }); +}); + +describe('upstreamFetch redirects', () => { + it("does not follow redirects by default (the target is never hit)", async () => { + const hits: string[] = []; + const target = await listen((req, res) => { + hits.push(req.url ?? ''); + res.writeHead(200, { 'content-type': 'application/json' }); + res.end('{}'); + }); + const origin = await listen((_req, res) => { + res.writeHead(302, { location: `${target.base}/models` }); + res.end(); + }); + + const response = await upstreamFetch({ + baseUrl: origin.base, + apiKey: 'sk-secret', + path: '/chat/completions', + method: 'POST', + body: { model: 'm' }, + timeoutMs: 2_000, + }); + expect(response.status).toBe(302); + expect(response.ok).toBe(false); + expect(hits).toEqual([]); + response.dispose(); + }); + + it('follows redirects only when explicitly asked', async () => { + const hits: string[] = []; + const target = await listen((req, res) => { + hits.push(req.url ?? ''); + res.writeHead(200, { 'content-type': 'application/json' }); + res.end('{"ok":true}'); + }); + const origin = await listen((_req, res) => { + res.writeHead(307, { location: `${target.base}/chat/completions` }); + res.end(); + }); + + const response = await upstreamFetch({ + baseUrl: origin.base, + apiKey: 'sk-secret', + path: '/chat/completions', + method: 'POST', + body: { model: 'm' }, + timeoutMs: 2_000, + redirect: 'follow', + }); + expect(response.status).toBe(200); + expect(hits).toEqual(['/v1/chat/completions']); + response.dispose(); + }); +}); + +describe('upstreamFetch bodies', () => { + it('forwards rawBody byte-for-byte (no JSON round-trip)', 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('{}'); + }); + const raw = '{\n "model": "x", "big": 9007199254740993, "esc": "\\u00e9", "spaced" : [1, 2] }'; + + const response = await upstreamFetch({ + baseUrl: server.base, + apiKey: 'sk-secret', + path: '/chat/completions', + rawBody: raw, + timeoutMs: 2_000, + }); + expect(response.ok).toBe(true); + await response.response.text(); + response.dispose(); + + expect(received).toHaveLength(1); + expect(received[0]!.toString('utf8')).toBe(raw); + }); + + it('sends structured bodies as JSON', 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('{}'); + }); + const response = await upstreamFetch({ + baseUrl: server.base, + apiKey: 'sk-secret', + path: '/chat/completions', + body: { model: 'm', n: 2 }, + timeoutMs: 2_000, + }); + await response.response.text(); + response.dispose(); + expect(JSON.parse(received[0]!.toString('utf8'))).toEqual({ model: 'm', n: 2 }); + }); +}); + +describe('upstreamFetch timeouts', () => { + it('rejects with a 504 upstream_timeout when no headers arrive in time', async () => { + const server = await listen(() => { + /* deliberately never respond */ + }); + const started = Date.now(); + await expect( + upstreamFetch({ baseUrl: server.base, apiKey: 'k', path: '/chat/completions', body: {}, timeoutMs: 300 }), + ).rejects.toMatchObject({ status: 504, code: 'upstream_timeout' }); + expect(Date.now() - started).toBeLessThan(3_000); + }); + + it('keeps the deadline alive for a body that stalls after headers', async () => { + const server = await listen((_req, res) => { + res.writeHead(200, { 'content-type': 'text/event-stream' }); + res.write('data: {"a":1}\n\n'); + // ...and never end the response. + }); + const response = await upstreamFetch({ + baseUrl: server.base, + apiKey: 'k', + path: '/chat/completions', + body: {}, + timeoutMs: 300, + }); + expect(response.status).toBe(200); + + let settledNormally = false; + try { + await response.response.text(); + settledNormally = true; + } catch { + /* expected: the deadline aborts the stalled body */ + } + expect(settledNormally).toBe(false); + expect(response.abortReason).toBe('upstream timeout'); + response.dispose(); + }); + + it('dispose() clears the timeout so a later read is not aborted', async () => { + const server = await listen((_req, res) => { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end('{"ok":true}'); + }); + const response = await upstreamFetch({ + baseUrl: server.base, + apiKey: 'k', + path: '/chat/completions', + body: {}, + timeoutMs: 200, + }); + response.dispose(); + await new Promise((resolve) => setTimeout(resolve, 400)); + expect(response.abortReason).toBeNull(); + expect(await response.response.text()).toBe('{"ok":true}'); + }); + + it('maps a client abort to a client_aborted ApiError', async () => { + const server = await listen(() => { + /* stall */ + }); + const controller = new AbortController(); + const pending = upstreamFetch({ + baseUrl: server.base, + apiKey: 'k', + path: '/chat/completions', + body: {}, + timeoutMs: 5_000, + signal: controller.signal, + }); + setTimeout(() => controller.abort(), 50); + const error = await pending.catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(ApiError); + expect((error as ApiError).code).toBe('client_aborted'); + expect((error as ApiError).status).toBe(502); + }); +}); \ No newline at end of file diff --git a/web/src/components/charts/AreaChart.tsx b/web/src/components/charts/AreaChart.tsx index 30c5b37..f30f242 100644 --- a/web/src/components/charts/AreaChart.tsx +++ b/web/src/components/charts/AreaChart.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from 'react'; +import { useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode } from 'react'; import { formatAxisTime, formatCompact } from '../../lib/format'; export interface AreaPoint { @@ -29,6 +29,37 @@ function useElementWidth(): [React.RefObject, n return [ref, width]; } +/** + * Stats repositories return only non-empty buckets. Without zero-filling those + * samples the chart would compress long idle stretches into a straight segment, so + * interior gaps are padded whenever the samples sit exactly on a known bucket grid. + */ +function fillGaps(points: AreaPoint[], bucketMs?: number): AreaPoint[] { + if (points.length < 2) return [...points]; + const sorted = [...points].sort((a, b) => a.t - b.t); + const t0 = sorted[0]!.t; + const t1 = sorted[sorted.length - 1]!.t; + let step = bucketMs && bucketMs > 0 ? bucketMs : Number.POSITIVE_INFINITY; + if (!Number.isFinite(step)) { + for (let index = 1; index < sorted.length; index += 1) { + step = Math.min(step, sorted[index]!.t - sorted[index - 1]!.t); + } + } + if (!Number.isFinite(step) || step <= 0) return sorted; + // Irregular timestamps would make zero-filling invent data; leave them untouched. + if (sorted.some((point) => (point.t - t0) % step !== 0)) return sorted; + const count = Math.floor((t1 - t0) / step) + 1; + if (count <= sorted.length || count > 2000) return sorted; + const byTime = new Map(sorted.map((point) => [point.t, point])); + const hasSecondary = sorted.some((point) => point.secondary !== undefined); + const dense: AreaPoint[] = []; + for (let index = 0; index < count; index += 1) { + const t = t0 + index * step; + dense.push(byTime.get(t) ?? { t, value: 0, secondary: hasSecondary ? 0 : undefined }); + } + return dense; +} + function smoothPath(points: Array<{ x: number; y: number }>): string { if (points.length === 0) return ''; if (points.length === 1) return `M${points[0]!.x},${points[0]!.y}`; @@ -45,6 +76,11 @@ function smoothPath(points: Array<{ x: number; y: number }>): string { export interface AreaChartProps { points: AreaPoint[]; height?: number; + /** + * Expected spacing between samples (ms). When set, missing buckets between the + * first and last sample are filled with zeros so the x axis stays linear in time. + */ + bucketMs?: number; formatValue?: (value: number) => string; formatLabel?: (t: number) => string; primaryLabel?: string; @@ -66,17 +102,24 @@ export function AreaChart({ secondaryLabel = 'Errors', className = '', emptyHint = 'No traffic in this window yet', + bucketMs, }: AreaChartProps): ReactNode { const [containerRef, width] = useElementWidth(); const gradientId = useId().replace(/:/g, ''); const secondaryGradientId = useId().replace(/:/g, ''); const [hover, setHover] = useState(null); + const series = useMemo(() => fillGaps(points, bucketMs), [points, bucketMs]); + const pad = { top: 14, right: 10, bottom: 22, left: 38 }; const innerWidth = Math.max(10, width - pad.left - pad.right); const innerHeight = Math.max(10, height - pad.top - pad.bottom); - const span = points.length > 1 ? points[points.length - 1]!.t - points[0]!.t : 0; + // Sample positions come from the timestamps, not the array index: sparse buckets + // must keep their real spacing on the time axis. + const t0 = series.length > 0 ? series[0]!.t : 0; + const t1 = series.length > 0 ? series[series.length - 1]!.t : 0; + const span = t1 - t0; const labelFor = useCallback( (t: number) => (formatLabel ? formatLabel(t) : formatAxisTime(t, span)), [formatLabel, span], @@ -84,14 +127,17 @@ export function AreaChart({ const maxValue = Math.max( 1, - ...points.map((point) => Math.max(point.value, point.secondary ?? 0)), + ...series.map((point) => Math.max(point.value, point.secondary ?? 0)), ); - const step = points.length > 1 ? innerWidth / (points.length - 1) : 0; - const xFor = (index: number): number => pad.left + index * step; + const xForTime = (t: number): number => (span > 0 ? pad.left + ((t - t0) / span) * innerWidth : pad.left); + const xFor = (index: number): number => { + const point = series[index]; + return point ? xForTime(point.t) : pad.left; + }; const yFor = (value: number): number => pad.top + innerHeight - (value / maxValue) * innerHeight; - const primary = points.map((point, index) => ({ x: xFor(index), y: yFor(point.value) })); - const secondary = points.map((point, index) => ({ x: xFor(index), y: yFor(point.secondary ?? 0) })); + const primary = series.map((point) => ({ x: xForTime(point.t), y: yFor(point.value) })); + const secondary = series.map((point) => ({ x: xForTime(point.t), y: yFor(point.secondary ?? 0) })); const primaryPath = smoothPath(primary); const areaPath = @@ -104,20 +150,20 @@ export function AreaChart({ y: pad.top + innerHeight - ratio * innerHeight, })); - const tickCount = Math.min(5, Math.max(2, points.length)); + const tickCount = Math.min(5, Math.max(2, series.length)); const xTicks = - points.length > 1 + series.length > 1 ? Array.from({ length: tickCount }).map((_, index) => { - const pointIndex = Math.round((index / (tickCount - 1)) * (points.length - 1)); - return { index: pointIndex, x: xFor(pointIndex), t: points[pointIndex]!.t }; + const pointIndex = Math.round((index / (tickCount - 1)) * (series.length - 1)); + return { index: pointIndex, x: xFor(pointIndex), t: series[pointIndex]!.t }; }) : []; - const hovered = hover !== null ? points[hover] ?? null : null; + const hovered = hover !== null ? series[hover] ?? null : null; return (
- {points.length === 0 ? ( + {series.length === 0 ? (
{emptyHint}
) : ( { const rect = event.currentTarget.getBoundingClientRect(); const relative = event.clientX - rect.left - pad.left; - if (step <= 0) { + if (span <= 0 || series.length === 1) { setHover(0); return; } - const index = Math.max(0, Math.min(points.length - 1, Math.round(relative / step))); - setHover(index); + const target = t0 + (Math.max(0, Math.min(innerWidth, relative)) / innerWidth) * span; + let nearest = 0; + let distance = Number.POSITIVE_INFINITY; + for (let index = 0; index < series.length; index += 1) { + const current = Math.abs(series[index]!.t - target); + if (current < distance) { + distance = current; + nearest = index; + } + } + setHover(nearest); }} > @@ -172,7 +227,7 @@ export function AreaChart({ ) : null} - {points.some((point) => (point.secondary ?? 0) > 0) ? ( + {series.some((point) => (point.secondary ?? 0) > 0) ? ( <> ))} - {hover !== null && points[hover] ? ( + {hover !== null && series[hover] ? ( - - {points[hover]!.secondary !== undefined ? ( - + + {series[hover]!.secondary !== undefined ? ( + ) : null} ) : null} diff --git a/web/src/components/layout/LiveIndicator.tsx b/web/src/components/layout/LiveIndicator.tsx index a7d0d2c..30e2545 100644 --- a/web/src/components/layout/LiveIndicator.tsx +++ b/web/src/components/layout/LiveIndicator.tsx @@ -36,7 +36,7 @@ export function LiveIndicator({ active {showThroughput && typeof requestsLast60s === 'number' ? ( - + {formatNumber(requestsLast60s)}/min ) : null} diff --git a/web/src/components/layout/Sidebar.tsx b/web/src/components/layout/Sidebar.tsx index 0e77b65..0ce60b4 100644 --- a/web/src/components/layout/Sidebar.tsx +++ b/web/src/components/layout/Sidebar.tsx @@ -3,6 +3,7 @@ import { NavLink, Link } from 'react-router-dom'; import { X, Zap } from 'lucide-react'; import { NAV_ITEMS } from './nav'; import { useReadiness } from '../../lib/readiness'; +import { useDialogFocus } from '../../lib/useDialogFocus'; import { ReadinessChecklist } from '../SetupBanner'; import { setupSteps } from '../../lib/readiness'; @@ -31,6 +32,8 @@ export function Sidebar({ mobileOpen, onClose }: { mobileOpen: boolean; onClose: const { bootstrap } = useReadiness(); const steps = setupSteps(bootstrap); const ready = Boolean(bootstrap?.gatewayReady); + // The drawer is the only overlay here: focus trap, Escape and focus restore. + const mobileRef = useDialogFocus({ open: mobileOpen, onClose }); const content = (
@@ -98,6 +101,7 @@ export function Sidebar({ mobileOpen, onClose }: { mobileOpen: boolean; onClose: <>