6.6 KiB
9router admin consumption adapter
Wiring (integration owner)
Import RouterUsageModule from backend/src/router-usage/router-usage.module into the root application's imports. This branch deliberately does not edit app.module.ts. Existing AuthModule/JWT strategy must be registered by the application. Route requires a JWT bearer user with admin/superadmin role; API-key authentication is deliberately not enabled for this sensitive endpoint.
Set backend-only ROUTER_USAGE_CLI_TOKEN using the existing router CLI auth token from the operator secret store. Optional ROUTER_USAGE_BASE_URL must be exactly https://nr.parsaaghayi.ir (an origin slash is accepted). Do not ship this token to the frontend. No environment/configuration was changed during implementation. No push/deploy performed; integration follows CI/CD and production needs separate Gate2.
Exact API
GET /admin/router-usage?period=7d (plus the existing application global prefix, if any).
Allowed periods: today, 24h, 7d, 30d, 60d, all; default 7d. Unknown query properties/custom from/to ranges and invalid periods return 400. Missing/invalid JWT is rejected by Passport; authenticated non-admin gets 403. Response is private/no-store.
Response fields:
source: "9router",periodstatus: "available" | "unavailable"reason: null | "not_configured" | "invalid_configuration" | "busy" | "upstream_unavailable"attribution: {scope:"9router_total", hermes:null, additive:false}freshness: {retrievedAt: ISO8601|null, sourceUpdatedAt:null, stale:null}. Retrieval time is NOT a guarantee of provider freshness. The source exposes no authoritative updated-at for aggregates. No last-good cache is served.capabilities: {errors:false, reasoningTokens:false, cacheWriteTokens:false, quota:false, customTimeRange:false}data: null | {totals, providers:[], models:[], accounts:[]}
Every metrics object contains requests, inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, reasoningTokens, errors (number|null). Zero is retained only if upstream reported zero; absent/invalid counters remain null. Input/output/cache map to promptTokens/completionTokens/cachedTokens; cache-read is a subset of input, never add it again. Cache-write/reasoning/errors are always null because the stats contract does not expose these aggregates.
Provider rows: {provider,...metrics}. Model rows: {model,provider,...metrics}. Account rows: {accountId,model,provider,...metrics,quota:{status:"unknown",remaining:null,resetAt:null,reason:"upstream_quota_get_mutates_credentials"}}. Account rows are upstream account/model summaries, NOT unique account inventory; accounts without usage are absent. IDs are validated, nullable if unsafe; account names/emails are never returned. No raw upstream maps, logs, prompts, provider data or credentials are returned. Dimensions are different views of the same consumption: do NOT sum totals+models+accounts. Hermes attribution remains unknown; do NOT add Hermes telemetry to router totals.
Deployed-source inspection and real probe
Read-only inspected running 9router image decolua/9router:vpn: compiled /app/.next/server/app/api/usage/stats/route.js, /app/.next/server/chunks/9100.js, /app/.next/server/middleware.js, /app/.next/server/chunks/7211.js, providers routes and /app/open-sse/services/usage.js. No credential tables or router DB contents were dumped/modified.
Verified stats route accepts the periods above. today uses router-local midnight, 24h rolling history; 7/30/60d use router-local daily buckets, all all retained daily aggregates. This is not arbitrary UTC timestamp filtering; retention/completeness is upstream-owned.
Authenticated internal GET probe returned HTTP 200, 5 provider summaries, 21 model summaries, 21 account/model summaries. Verified model fields: requests, promptTokens, completionTokens, cachedTokens, cost, rawModel, provider, lastUsed. Account fields additionally include connectionId/accountName. Only schema/counts printed; no keys or account values printed. Public HTTPS reverse proxy path was not live-authenticated, so its separate proxy authentication/network reachability remains an operator verification step.
Dashboard routes authenticate using x-9r-cli-token or valid auth_token session cookie. Normal inference API Bearer keys do NOT authenticate these dashboard routes. CLI token is NOT the contents of cli-secret: deployed middleware computes first 16 hex characters of SHA256(machine-id + "9r-cli-auth" + cli-secret). Probe derived it only inside the router process command and never emitted it; no new token or configuration was created.
Security finding: stats byApiKey map keys contain raw inference keys, even when row fields are masked. Adapter discards this map entirely and never logs response bodies/errors.
Quota blocker: GET /api/usage/[connectionId] calls refreshAndUpdateCredentials, including updateProviderConnection; OAuth refresh/retry can persist credentials. It is NOT read-only despite being GET. Therefore adapter does NOT call it. Provider quota handlers can return quotas (used/total/remaining/resetAt), messages or synthesized unlimited defaults; these cannot safely be treated as verified provider truth here. Quota reset grants exist in provider helpers but must never be consumed by this adapter. No safe deployed cache-only provider quota route was established. A separately reviewed router-side non-mutating, provenance/timestamp-bearing quota snapshot API is required before exposing live remaining/reset. Quota is unknown, never zero/unlimited fabricated. Connection inventory/status refresh is also not represented as quota truth.
Bounds and verification
Only fixed-origin authenticated GET /api/usage/stats is invoked; redirect:error, abort after 5 seconds, streaming cap 1 MiB, <=2000 rows per dimension, <=4 concurrent requests per backend process. No retries or stale cache. Schema/transport/auth/rate-limit/oversize failures produce unavailable + null data without raw errors. No SQL, POST or token refresh.
Strict test-first slices observed missing contract, adapter, module failures before implementation. Disposable containers used existing backend image dependencies, read-only source mounts, network disabled and copied source into ephemeral /work; no host dependencies/build output or running containers changed. npm run build passed. Focused: 3 suites/24 tests passed. Full backend regression: 92 suites/781 tests passed (existing negative-path tests log expected payment/SSL errors). HTTP guard tests replace JWT authentication only and exercise real RolesGuard; deployed JWT strategy remains application-owned.