@warlock.js/devtools 5.60.0 → 5.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/cjs/{extract-8kaX_cUV.cjs → ai-source-CeHZDYG1.cjs} +449 -408
- package/cjs/ai-source-CeHZDYG1.cjs.map +1 -0
- package/cjs/{attach-D5aMqUnA.cjs → attach-D9gWc6lU.cjs} +19 -19
- package/cjs/attach-D9gWc6lU.cjs.map +1 -0
- package/cjs/{boot-Dg5YZGGR.cjs → boot-Guumt-du.cjs} +13 -10
- package/cjs/boot-Guumt-du.cjs.map +1 -0
- package/cjs/{capture-CBgONYhk.cjs → capture-D2k0GnBN.cjs} +21 -420
- package/cjs/capture-D2k0GnBN.cjs.map +1 -0
- package/cjs/{collector-CJbQbzzK.cjs → collector-BfC4v87v.cjs} +4 -46
- package/cjs/collector-BfC4v87v.cjs.map +1 -0
- package/cjs/errors-DNQ-g49I.cjs.map +1 -1
- package/cjs/{http-DCVCf44M.cjs → http-CPbhLN61.cjs} +13 -7
- package/cjs/http-CPbhLN61.cjs.map +1 -0
- package/cjs/index.cjs +1 -1
- package/cjs/{insights-CFof59kF.cjs → insights-COA3u37q.cjs} +53 -21
- package/cjs/insights-COA3u37q.cjs.map +1 -0
- package/cjs/{process-panel-D3D9Y_dc.cjs → process-panel-Dev6eg_f.cjs} +2 -2
- package/cjs/{process-panel-D3D9Y_dc.cjs.map → process-panel-Dev6eg_f.cjs.map} +1 -1
- package/cjs/query-shape-DShKQa0x.cjs +45 -0
- package/cjs/query-shape-DShKQa0x.cjs.map +1 -0
- package/cjs/redact-DQ28mDzr.cjs +533 -0
- package/cjs/redact-DQ28mDzr.cjs.map +1 -0
- package/cjs/{runs-DECWPGnq.cjs → runs-DXTf_o5P.cjs} +10 -11
- package/cjs/runs-DXTf_o5P.cjs.map +1 -0
- package/cjs/{server-CC5DpObz.cjs → server-Dc0YdP6Y.cjs} +6 -6
- package/cjs/{server-CC5DpObz.cjs.map → server-Dc0YdP6Y.cjs.map} +1 -1
- package/cjs/{src-VyOjEEAo.cjs → src-Ca1gNdZj.cjs} +21 -18
- package/cjs/src-Ca1gNdZj.cjs.map +1 -0
- package/cjs/{stream-route-DFHuIWgg.cjs → stream-route-qEHoPVth.cjs} +25 -22
- package/cjs/stream-route-qEHoPVth.cjs.map +1 -0
- package/esm/ai/reports/runs.mjs +5 -6
- package/esm/ai/reports/runs.mjs.map +1 -1
- package/esm/ai/rollup/extract.mjs +21 -4
- package/esm/ai/rollup/extract.mjs.map +1 -1
- package/esm/devtools-connector.d.mts.map +1 -1
- package/esm/devtools-connector.mjs +4 -1
- package/esm/devtools-connector.mjs.map +1 -1
- package/esm/index.d.mts +2 -2
- package/esm/panels.mjs +14 -1
- package/esm/panels.mjs.map +1 -1
- package/esm/production/boot.mjs +5 -2
- package/esm/production/boot.mjs.map +1 -1
- package/esm/production/contracts.d.mts +17 -4
- package/esm/production/contracts.d.mts.map +1 -1
- package/esm/production/contracts.mjs.map +1 -1
- package/esm/production/http/mount.mjs +8 -2
- package/esm/production/http/mount.mjs.map +1 -1
- package/esm/production/http/share.mjs.map +1 -1
- package/esm/production/index.d.mts +2 -2
- package/esm/production/insights/jobs.mjs +45 -11
- package/esm/production/insights/jobs.mjs.map +1 -1
- package/esm/production/options.d.mts +5 -0
- package/esm/production/options.d.mts.map +1 -1
- package/esm/production/options.mjs.map +1 -1
- package/esm/server/ai-routes.mjs +11 -5
- package/esm/server/ai-routes.mjs.map +1 -1
- package/esm/server/panel-routes.mjs.map +1 -1
- package/esm/server/ui-assets.mjs +4 -7
- package/esm/server/ui-assets.mjs.map +1 -1
- package/esm/sources/ai-source.d.mts.map +1 -1
- package/esm/sources/ai-source.mjs +3 -3
- package/esm/sources/ai-source.mjs.map +1 -1
- package/esm/types.d.mts +7 -4
- package/esm/types.d.mts.map +1 -1
- package/llms-full.txt +27 -24
- package/package.json +8 -8
- package/skills/SKILL.md +27 -24
- package/ui/dashboard/assets/app.css +1 -1
- package/ui/dashboard/assets/app.js +2 -2
- package/ui/dashboard/build-info.json +7 -7
- package/cjs/attach-D5aMqUnA.cjs.map +0 -1
- package/cjs/boot-Dg5YZGGR.cjs.map +0 -1
- package/cjs/capture-CBgONYhk.cjs.map +0 -1
- package/cjs/collector-CJbQbzzK.cjs.map +0 -1
- package/cjs/extract-8kaX_cUV.cjs.map +0 -1
- package/cjs/histogram-CkoVizdf.cjs +0 -102
- package/cjs/histogram-CkoVizdf.cjs.map +0 -1
- package/cjs/http-DCVCf44M.cjs.map +0 -1
- package/cjs/insights-CFof59kF.cjs.map +0 -1
- package/cjs/runs-DECWPGnq.cjs.map +0 -1
- package/cjs/src-VyOjEEAo.cjs.map +0 -1
- package/cjs/stream-route-DFHuIWgg.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contracts.mjs","names":[],"sources":["../../../../../../../../packages/devtools/src/production/contracts.ts"],"sourcesContent":["/**\n * The contracts of the devtools production monitor: the shapes the server\n * stores, the JSON its API returns, and the few constants both sides share.\n *\n * This file has NO imports, so the dashboard (`ui-src/`) can import its types\n * too. Every timestamp is epoch milliseconds, every duration milliseconds,\n * every size bytes. Absent values are `null`, never missing.\n */\n\n// ---------------------------------------------------------------------------\n// Modes, roles and stages\n// ---------------------------------------------------------------------------\n\n/** Where the dashboard runs: the loopback development dashboard or the signed-in production monitor. */\nexport type DevtoolsMode = \"development\" | \"production\";\n\n/** What an account may do: `admin` manages users and the dashboard, `viewer` reads. */\nexport type DevtoolsRole = \"admin\" | \"viewer\";\n\n/**\n * Where a browser session stands. Only `active` reaches the data routes;\n * every other stage reaches only the sign-in steps it needs next.\n */\nexport type DevtoolsSessionStage =\n | \"signed-out\"\n | \"password-change\"\n | \"mfa-enrol\"\n | \"mfa-verify\"\n | \"active\";\n\n/** How an account's current password was set. `env` and `reset` passwords must be changed at the next sign-in. */\nexport type DevtoolsPasswordSource = \"env\" | \"setup\" | \"invite\" | \"user\" | \"reset\";\n\n// ---------------------------------------------------------------------------\n// Instances\n// ---------------------------------------------------------------------------\n\n/** One process that runs the monitor (a pm2 or cluster worker, a container). */\nexport type DevtoolsInstanceInfo = {\n /** Stable for the life of the process: `<host>:<pid>:<start time base36>`. */\n id: string;\n /** What the dashboard shows: `<host> #<worker>` or `<host> pid <pid>`. */\n label: string;\n host: string;\n pid: number;\n /** pm2's `NODE_APP_INSTANCE` / `pm_id`, or the cluster worker id; `null` when neither is set. */\n worker: string | null;\n startedAt: number;\n /** When the instance last wrote its report (the current time for the instance answering). */\n seenAt: number;\n nodeVersion: string;\n};\n\n// ---------------------------------------------------------------------------\n// Histograms (mergeable across instances)\n// ---------------------------------------------------------------------------\n\n/**\n * Upper bounds (inclusive, ms) of the latency buckets every histogram uses.\n * A histogram's `counts` has one more entry than this list: the last entry\n * counts everything above the highest bound. Fixed bounds make histograms\n * from several instances merge exactly.\n */\nexport const DEVTOOLS_LATENCY_BUCKETS_MS = [\n 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000,\n] as const;\n\n/** A latency histogram over `DEVTOOLS_LATENCY_BUCKETS_MS`. */\nexport type DevtoolsHistogram = {\n /** `DEVTOOLS_LATENCY_BUCKETS_MS.length + 1` entries. */\n counts: number[];\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n// ---------------------------------------------------------------------------\n// Query, route and error statistics\n// ---------------------------------------------------------------------------\n\n/** Statistics for one normalized query shape (literals and bindings replaced by `?`). */\nexport type DevtoolsQueryShapeStats = {\n /** First 16 hex characters of the SHA-256 of `shape`; the id the API and EXPLAIN use. */\n id: string;\n /** The normalized query, at most 2000 characters. Never holds a value. */\n shape: string;\n driver: \"postgres\" | \"mongodb\";\n connection: string;\n count: number;\n errors: number;\n histogram: DevtoolsHistogram;\n /** Sampled requests in which this shape reached the N+1 threshold, and the highest count in one request. */\n nPlusOne: { requests: number; maxPerRequest: number };\n /** The slowest run seen; its values stay in the process that ran it (see EXPLAIN). */\n slowest: {\n durationMs: number;\n at: number;\n route: string | null;\n requestId: string | null;\n instance: string;\n } | null;\n firstSeen: number;\n lastSeen: number;\n /** Whether EXPLAIN can run for this shape (a Postgres `SELECT`/`WITH`, or a MongoDB `find`/`aggregate`/`count`). */\n explainable: boolean;\n};\n\n/** Time spent in one named request phase (middleware, validation, handler, …) on one route. */\nexport type DevtoolsRoutePhaseStats = {\n name: string;\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n/** Statistics for one route pattern and method. */\nexport type DevtoolsRouteStats = {\n /** `\"<METHOD> <route pattern>\"`, e.g. `\"GET /posts/:slug\"`. */\n key: string;\n method: string;\n route: string;\n count: number;\n /** Responses with a 5xx status or a thrown error. */\n errors: number;\n histogram: DevtoolsHistogram;\n /** At most 30 phases, slowest total first. */\n phases: DevtoolsRoutePhaseStats[];\n slowest: { durationMs: number; at: number; requestId: string | null; instance: string } | null;\n};\n\n/** Errors grouped by fingerprint (normalized message + route + source). */\nexport type DevtoolsErrorGroup = {\n /** First 16 hex characters of the SHA-256 of the fingerprint. */\n id: string;\n /** The latest message as raised, at most 500 characters. */\n message: string;\n /** The error class name when known (`TypeError`). */\n name: string | null;\n source: \"request\" | \"log\";\n route: string | null;\n status: number | null;\n count: number;\n firstSeen: number;\n lastSeen: number;\n lastRequestId: string | null;\n /** The latest stack, at most 4000 characters; `null` when none was available. */\n stack: string | null;\n};\n\n/** A warn/error log entry kept for the Logs panel in production (no context: it may hold values). */\nexport type DevtoolsReportLogEntry = {\n level: \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\";\n module: string;\n action: string;\n /** At most 1000 characters. */\n message: string;\n at: number;\n requestId: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Resources, health, jobs\n// ---------------------------------------------------------------------------\n\n/** One resource reading of a process. */\nexport type DevtoolsResourcePoint = {\n at: number;\n rssBytes: number;\n heapUsedBytes: number;\n heapTotalBytes: number;\n externalBytes: number;\n /** Process CPU time over wall time since the previous point, 0–100 per core (can exceed 100). */\n cpuPercent: number;\n eventLoopDelayP50Ms: number;\n eventLoopDelayP99Ms: number;\n eventLoopDelayMaxMs: number;\n /** `performance.eventLoopUtilization()` since the previous point, 0–1. */\n eventLoopUtilization: number;\n /** Garbage collections since the previous point. */\n gcCount: number;\n /** Total GC pause since the previous point. */\n gcPauseMs: number;\n};\n\n/** The latest resource reading plus values that change rarely. */\nexport type DevtoolsResourceSnapshot = DevtoolsResourcePoint & {\n heapLimitBytes: number;\n uptimeSeconds: number;\n /** Totals since the monitor started, by GC kind. */\n gcByKind: Record<\n \"minor\" | \"major\" | \"incremental\" | \"weakcb\",\n { count: number; pauseMs: number }\n >;\n};\n\n/** Readiness checks (core's `health` registry) of one process, with a short history. */\nexport type DevtoolsHealthReport = {\n status: \"ok\" | \"error\" | \"unknown\";\n checkedAt: number | null;\n checks: Record<string, boolean>;\n /** Newest last, at most 60 entries. */\n history: { at: number; status: \"ok\" | \"error\"; failed: string[] }[];\n};\n\n/** One scheduled job (`@warlock.js/scheduler`). */\nexport type DevtoolsScheduleInfo = {\n name: string;\n /** The cron expression, or `null` for an interval schedule. */\n cron: string | null;\n /** A readable interval such as `\"every 5 minutes\"`, or `null`. */\n interval: string | null;\n isRunning: boolean;\n lastRunAt: number | null;\n nextRunAt: number | null;\n lastDurationMs: number | null;\n lastError: string | null;\n runs: number;\n failures: number;\n};\n\n/** Background work of one process: schedules and queue counts, each `available: false` when its package is not installed. */\nexport type DevtoolsJobsReport = {\n available: { scheduler: boolean; queue: boolean };\n schedules: DevtoolsScheduleInfo[];\n /** Job counts per queue and state (`waiting`, `active`, `delayed`, `failed`, `completed`). */\n queues: { name: string; counts: Record<string, number> }[];\n};\n\n/** What the capture did since the process started. */\nexport type DevtoolsCaptureCounters = {\n sampleRate: number;\n requests: number;\n sampled: number;\n /** Unsampled requests kept as a summary because they were slow or failed. */\n keptUnsampled: number;\n /** Samples written to the database. */\n stored: number;\n /** Samples not written because the per-minute budget was spent. */\n droppedStored: number;\n /** Query shapes, routes and error groups evicted to keep memory bounded. */\n evictedShapes: number;\n evictedRoutes: number;\n evictedErrors: number;\n /** Queries not kept inside a sampled request because it reached its per-request limit. */\n droppedQueries: number;\n};\n\n/**\n * Everything one process reports, written to the database every\n * `reportIntervalMs` (one row per instance) and merged by the dashboard.\n * Serialized it stays under 256 KB: lists are trimmed from the end.\n */\nexport type DevtoolsInstanceReport = {\n instance: DevtoolsInstanceInfo;\n at: number;\n resources: { snapshot: DevtoolsResourceSnapshot; history: DevtoolsResourcePoint[] };\n /** At most 200, highest total time first. */\n queries: DevtoolsQueryShapeStats[];\n /** At most 200, highest total time first. */\n routes: DevtoolsRouteStats[];\n /** At most 50, newest first. */\n errors: DevtoolsErrorGroup[];\n /** At most 50, newest first. */\n logs: DevtoolsReportLogEntry[];\n health: DevtoolsHealthReport;\n jobs: DevtoolsJobsReport;\n capture: DevtoolsCaptureCounters;\n};\n\n// ---------------------------------------------------------------------------\n// Requests (stored samples)\n// ---------------------------------------------------------------------------\n\n/**\n * A request row. Matches the development `DevtoolsRequestSummary` field for\n * field, plus where it was captured.\n */\nexport type DevtoolsSampleSummary = {\n id: string;\n method: string;\n path: string;\n route?: string;\n status?: number;\n startedAt: number;\n durationMs?: number;\n queryCount: number;\n warningCount: number;\n /** Read from the persisted request log only. */\n persisted?: true;\n /** The instance that served the request. */\n instance?: string;\n /** Kept because it was slow or failed, without a timeline (the request was not sampled). */\n partial?: true;\n};\n\n/** A query inside a stored sample: the shape only, never the SQL text with values or the bindings. */\nexport type DevtoolsSampleQuery = {\n id: string;\n connection: string;\n driver: \"postgres\" | \"mongodb\";\n /** Same as `shape`: kept under this name so the request view renders it like a development query. */\n sql?: string;\n collection?: string;\n command?: string;\n shape: string;\n shapeId: string;\n startedAt: number;\n durationMs: number;\n rowCount?: number;\n error?: string;\n};\n\n/** The timeline of a sampled request, with every value removed (see the redaction rules). */\nexport type DevtoolsSampleDetail = DevtoolsSampleSummary & {\n error?: string;\n phases: { name: string; startedAt: number; durationMs: number }[];\n queries: DevtoolsSampleQuery[];\n /** Cache operation counts only; keys are not kept. */\n cache: { hits: number; misses: number; writes: number };\n /** Log entries without context. */\n logs: { level: string; module: string; action: string; message: string; at: number }[];\n warnings: { type: \"n+1\"; message: string; shape: string; count: number }[];\n /** Queries left out because the request reached `maxQueriesPerRequest`. */\n droppedQueries: number;\n};\n\n// ---------------------------------------------------------------------------\n// API views (what the dashboard reads)\n// ---------------------------------------------------------------------------\n\n/** `GET api/instances`. */\nexport type DevtoolsInstancesView = {\n /** The instance that answered this request. */\n current: string;\n /** Instances seen in the last 5 minutes (the answering one included), newest first. */\n instances: DevtoolsInstanceInfo[];\n};\n\n/** `GET api/resources?instance=<id|all>`. */\nexport type DevtoolsResourcesView = {\n instances: {\n instance: DevtoolsInstanceInfo;\n snapshot: DevtoolsResourceSnapshot;\n history: DevtoolsResourcePoint[];\n }[];\n};\n\n/** A shape row with figures computed from its histogram. */\nexport type DevtoolsQueryShapeRow = DevtoolsQueryShapeStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n /** Ids of the instances that reported this shape. */\n instances: string[];\n};\n\n/** `GET api/queries/stats?instance=&sort=total|p95|count|n+1&limit=`. */\nexport type DevtoolsQueryStatsView = {\n shapes: DevtoolsQueryShapeRow[];\n /** The sample rate the counts come from; counts are of sampled requests only. */\n sampleRate: number;\n instanceCount: number;\n evicted: number;\n};\n\n/** A route row with figures computed from its histogram. */\nexport type DevtoolsRouteStatsRow = DevtoolsRouteStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n instances: string[];\n};\n\n/** `GET api/routes/stats?instance=&sort=total|p95|count|errors&limit=`. */\nexport type DevtoolsRouteStatsView = {\n routes: DevtoolsRouteStatsRow[];\n sampleRate: number;\n instanceCount: number;\n};\n\n/** `GET api/health?instance=`. */\nexport type DevtoolsHealthView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsHealthReport }[];\n};\n\n/** `GET api/errors?instance=&limit=`. */\nexport type DevtoolsErrorsView = {\n groups: (DevtoolsErrorGroup & { instances: string[] })[];\n};\n\n/**\n * One row of `GET api/logs?level=&module=&instance=` (newest first), in both\n * modes. Development rows carry `context` and no `instance`; production rows\n * carry `instance` and never `context`.\n */\nexport type DevtoolsLogRow = DevtoolsReportLogEntry & {\n instance: string | null;\n context?: unknown;\n};\n\n/** `GET api/logs`: the rows, newest first (a plain array, as in 5.55). */\nexport type DevtoolsLogsView = DevtoolsLogRow[];\n\n/** `GET api/jobs?instance=`. */\nexport type DevtoolsJobsView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsJobsReport }[];\n};\n\n/** `POST api/queries/:shapeId/explain`. */\nexport type DevtoolsExplainResult = {\n shapeId: string;\n driver: \"postgres\" | \"mongodb\";\n /** `true` only when the project allows executing plans (`explain.executing`). */\n executing: boolean;\n plan: unknown;\n /** The instance whose example ran the EXPLAIN. */\n instance: string;\n};\n\n/** One dashboard tab, as `GET api/panels` lists it (enabled tabs only, in display order). */\nexport type DevtoolsPanelInfo = {\n id: string;\n title: string;\n /** `built-in` tabs are React views in the bundle; `package` tabs load `panels/<id>/view.js`. */\n type: \"built-in\" | \"package\";\n /** Whether the panel declares a shared view (`DevtoolsPanel.share`); always `false` for built-in tabs. */\n shareable: boolean;\n};\n\n/**\n * The built-in tabs, in display order, with whether production shows them\n * when the project says nothing (`production.panels` overrides per id).\n *\n * The AI section (`ai-reports`, `ai`, `agents`, `ai-models`, `ai-errors`,\n * `ai-evaluate`) sits under \"AI\" in the sidebar. `ai` keeps its id (it is the\n * Runs page) so existing links and `production.panels.ai` keep working. In\n * production the three report tabs show only when the AI feed is available\n * (Panoptic loads), unless `production.panels` turns one on explicitly.\n */\nexport const DEVTOOLS_BUILT_IN_PANELS = [\n { id: \"requests\", title: \"Requests\", production: true },\n { id: \"queries\", title: \"Queries\", production: true },\n { id: \"routes\", title: \"Routes\", production: true },\n { id: \"resources\", title: \"Resources\", production: true },\n { id: \"health\", title: \"Health\", production: true },\n { id: \"errors\", title: \"Errors\", production: true },\n { id: \"logs\", title: \"Logs\", production: true },\n { id: \"jobs\", title: \"Jobs\", production: true },\n { id: \"mail\", title: \"Mail\", production: false },\n { id: \"ai-reports\", title: \"Reports\", production: true },\n { id: \"ai\", title: \"Runs\", production: false },\n { id: \"agents\", title: \"Agents\", production: false },\n { id: \"ai-models\", title: \"Models\", production: true },\n { id: \"ai-errors\", title: \"Errors\", production: true },\n { id: \"ai-evaluate\", title: \"Evaluate\", production: false },\n { id: \"api\", title: \"API\", production: false },\n] as const;\n\n/** The id of a built-in tab. */\nexport type DevtoolsBuiltInPanelId = (typeof DEVTOOLS_BUILT_IN_PANELS)[number][\"id\"];\n\n// ---------------------------------------------------------------------------\n// Accounts, sessions, invites\n// ---------------------------------------------------------------------------\n\n/** An account as the API shows it (never a hash or a secret). */\nexport type DevtoolsAccountView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n twoFactor: {\n totp: boolean;\n passkeys: { id: string; name: string; createdAt: number; lastUsedAt: number | null }[];\n recoveryCodesLeft: number;\n };\n mustChangePassword: boolean;\n createdAt: number;\n lastLoginAt: number | null;\n};\n\n/** `GET api/auth/session`: who is signed in and what comes next. */\nexport type DevtoolsSessionView = {\n mode: DevtoolsMode;\n stage: DevtoolsSessionStage;\n /** `null` when signed out, and in development (no accounts there). */\n account: DevtoolsAccountView | null;\n /** `admin` in development; `null` when signed out. */\n role: DevtoolsRole | null;\n /** The token to send as `X-Devtools-Csrf` on every POST/PUT/PATCH/DELETE; `null` when signed out and in development. */\n csrf: string | null;\n /** When the session ends at the latest; `null` when signed out and in development. */\n expiresAt: number | null;\n /** The instance that answered; `null` when signed out. */\n instance: DevtoolsInstanceInfo | null;\n /** Sign-in methods the server offers; `null` when signed out. */\n methods: { totp: true; passkeys: boolean } | null;\n /** Read-only share links: `enabled` mirrors `production.share.enabled`; `null` when signed out and in development. */\n share: { enabled: boolean } | null;\n /** The installed `@warlock.js/core` version; `null` when signed out or not found. */\n warlockVersion: string | null;\n /** The app's own `package.json` name and version (nothing else is read); `null` when signed out or not found. */\n app: { name: string; version: string } | null;\n};\n\n/** `POST api/auth/login` body. */\nexport type DevtoolsLoginInput = { email: string; password: string };\n\n/** Answer of every sign-in step: the next stage, and the new CSRF token when the session changed. */\nexport type DevtoolsAuthStepResult = { stage: DevtoolsSessionStage; csrf: string | null };\n\n/** `POST api/auth/totp/start` (and `api/account/totp/start`). */\nexport type DevtoolsTotpEnrolment = {\n /** Base32, for manual entry. */\n secret: string;\n /** `otpauth://totp/...`, rendered as a QR code by the dashboard. */\n uri: string;\n issuer: string;\n account: string;\n};\n\n/** Recovery codes, shown once. */\nexport type DevtoolsRecoveryCodes = { codes: string[] };\n\n/** A pending or used invite. */\nexport type DevtoolsInviteView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n createdAt: number;\n expiresAt: number;\n createdBy: string | null;\n usedAt: number | null;\n};\n\n/** `POST api/admin/invites`: the token appears only in this answer. */\nexport type DevtoolsCreatedInvite = { invite: DevtoolsInviteView; token: string };\n\n/** `GET api/admin/users`. */\nexport type DevtoolsUserListView = {\n accounts: DevtoolsAccountView[];\n invites: DevtoolsInviteView[];\n};\n\n/** A session as its owner sees it (`GET api/account/sessions`). */\nexport type DevtoolsSessionInfo = {\n id: string;\n current: boolean;\n createdAt: number;\n lastSeenAt: number;\n expiresAt: number;\n ip: string | null;\n userAgent: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Share links\n// ---------------------------------------------------------------------------\n\n/** Where a share link stands. `revoked` wins over `expired`. */\nexport type DevtoolsShareStatus = \"active\" | \"expired\" | \"revoked\";\n\n/** A share link as the admin screen shows it (never the token or its hash). */\nexport type DevtoolsShareView = {\n id: string;\n /** The id of the panel the link opens. */\n panel: string;\n /** What the admin called it, 1-80 characters. */\n label: string;\n /** The email of the admin who made it; `null` when that account is gone. */\n createdBy: string | null;\n createdAt: number;\n expiresAt: number;\n revokedAt: number | null;\n lastUsedAt: number | null;\n /** How many times the link was used, counted at most once a minute. */\n uses: number;\n status: DevtoolsShareStatus;\n};\n\n/** `GET api/admin/shares`. */\nexport type DevtoolsShareList = {\n enabled: boolean;\n /** The longest life a link may have, in days. */\n maxDays: number;\n /** The panels that declare a shared view. */\n panels: { id: string; title: string }[];\n /** Newest first. */\n shares: DevtoolsShareView[];\n};\n\n/** `POST api/admin/shares` body. `label` is 1-80 characters, `days` a whole number from 1 to `maxDays`. */\nexport type DevtoolsShareCreateInput = { panel: string; label: string; days: number };\n\n/** `POST api/admin/shares`: the URL (with the token in its fragment) appears only in this answer. */\nexport type DevtoolsCreatedShare = { share: DevtoolsShareView; url: string };\n\n/**\n * What a share link opens, answered by `POST api/share/open` and\n * `GET api/share/info`: the panel and the names the shared view may load.\n */\nexport type DevtoolsShareOpenAnswer = {\n panel: string;\n /** The panel's title. */\n title: string;\n label: string;\n expiresAt: number;\n /** Served names from the panel's `assets` the shared page may load. */\n assets: string[];\n /** Whether the shared page may load images from the panel's `files`. */\n files: boolean;\n};\n\n/** The longest label of a share link. */\nexport const DEVTOOLS_SHARE_LABEL_MAX = 80;\n\n// ---------------------------------------------------------------------------\n// Audit log\n// ---------------------------------------------------------------------------\n\n/** Every audited event. `login.failed` and `mfa.failed` are the ones rate limits count. */\nexport type DevtoolsAuditType =\n | \"admin.seeded\"\n | \"admin.reset\"\n | \"setup.completed\"\n | \"login.succeeded\"\n | \"login.failed\"\n | \"login.blocked\"\n | \"mfa.succeeded\"\n | \"mfa.failed\"\n | \"mfa.enrolled\"\n | \"mfa.removed\"\n | \"recovery-code.used\"\n | \"recovery-codes.regenerated\"\n | \"passkey.added\"\n | \"passkey.removed\"\n | \"password.changed\"\n | \"logout\"\n | \"session.revoked\"\n | \"invite.created\"\n | \"invite.revoked\"\n | \"invite.accepted\"\n | \"account.role-changed\"\n | \"account.removed\"\n | \"account.mfa-reset\"\n | \"account.signed-out\"\n | \"dashboard.disabled\"\n | \"dashboard.enabled\"\n | \"dashboard.locked\"\n | \"explain.run\"\n | \"requests.cleared\"\n | \"panel.action\"\n | \"share.created\"\n | \"share.revoked\"\n | \"share.failed\";\n\n/** The audit types that count toward the account, IP and global failure limits. */\nexport const DEVTOOLS_FAILURE_AUDIT_TYPES: readonly DevtoolsAuditType[] = [\n \"login.failed\",\n \"mfa.failed\",\n \"share.failed\",\n];\n\n/** One audit log entry. */\nexport type DevtoolsAuditEntry = {\n id: string;\n at: number;\n type: DevtoolsAuditType;\n /** The account acting or targeted; `null` for an unknown email or the CLI. */\n accountId: string | null;\n /** The email as typed or as stored, lower-cased; `null` when there was none. */\n email: string | null;\n /** `\"cli\"` for a command, else the client IP after trusted-proxy resolution. */\n ip: string | null;\n /** At most 200 characters. */\n userAgent: string | null;\n /** Small flat facts: target account, role, shape id, panel route. Never a secret. */\n detail: Record<string, string | number | boolean | null>;\n /** Short reference shown to users in error messages (8 characters). */\n ref: string;\n};\n\n// ---------------------------------------------------------------------------\n// Errors the API returns\n// ---------------------------------------------------------------------------\n\n/**\n * Error codes in API answers. Each has a fixed message (see\n * `DEVTOOLS_ERROR_MESSAGES` in `errors.ts`) that says what failed and what to\n * do next.\n */\nexport type DevtoolsErrorCode =\n | \"auth.invalid-credentials\"\n | \"auth.invalid-code\"\n | \"auth.invalid-setup-token\"\n | \"auth.password-too-short\"\n | \"auth.password-too-long\"\n | \"auth.password-common\"\n | \"auth.password-same-as-email\"\n | \"auth.password-unchanged\"\n | \"auth.wrong-current-password\"\n | \"auth.busy\"\n | \"invite.invalid\"\n | \"invite.email-taken\"\n | \"account.not-found\"\n | \"account.last-admin\"\n | \"account.self\"\n | \"account.last-factor\"\n | \"role.forbidden\"\n | \"csrf.invalid\"\n | \"passkey.unavailable\"\n | \"passkey.failed\"\n | \"explain.not-allowed\"\n | \"explain.unsupported\"\n | \"explain.elsewhere\"\n | \"explain.failed\"\n | \"request.not-found\"\n | \"request.invalid-filter\"\n | \"share.not-found\"\n | \"stream.too-many\"\n | \"ai.range-invalid\"\n | \"ai.evaluate-unavailable\"\n | \"ai.prompt-not-found\"\n | \"ai.evaluate-failed\"\n | \"input.invalid\"\n | \"server.error\";\n\n/** The JSON body of every failed API call. */\nexport type DevtoolsApiErrorBody = {\n /** What failed and what to do next. */\n error: string;\n code: DevtoolsErrorCode;\n /** Short reference to quote to an admin; also written to the audit log or server log. */\n ref?: string;\n /** The instance that answered, when it matters (`explain.elsewhere`). */\n instance?: string;\n};\n\n// ---------------------------------------------------------------------------\n// AI section: reports, runs, models, errors, evaluate\n// ---------------------------------------------------------------------------\n\n/**\n * Upper bounds (inclusive, ms) of the latency buckets of the AI rollups.\n * Model calls take seconds, so these differ from `DEVTOOLS_LATENCY_BUCKETS_MS`.\n * A histogram has one more count than this list: the last counts everything\n * above five minutes. Fixed bounds make rollups from several processes add up\n * exactly. Changing them is a breaking change of the stored rollups.\n */\nexport const DEVTOOLS_AI_LATENCY_BUCKETS_MS = [\n 250, 500, 1000, 2000, 3000, 5000, 7500, 10000, 15000, 20000, 30000, 45000, 60000, 120000, 300000,\n] as const;\n\n/** The date-range presets of the Reports, Models and Errors pages. */\nexport type DevtoolsAiRangePreset = \"24h\" | \"7d\" | \"30d\";\n\n/** The range a report covers, after the server aligned it to its buckets. */\nexport type DevtoolsAiResolvedRange = {\n preset: DevtoolsAiRangePreset | \"custom\";\n /** Inclusive start, on an hour boundary. */\n from: number;\n /** Exclusive end, on an hour boundary. */\n to: number;\n /** Bucket width of the charts: 1 hour, 6 hours or 1 day. */\n stepMs: number;\n /** The browser's offset from UTC (minutes east), used to align day buckets. */\n utcOffsetMinutes: number;\n};\n\n/** Why an AI page has nothing to show; `title`, `message` and `command` are written for the page. */\nexport type DevtoolsAiUnavailableReasonView =\n | \"ai-missing\"\n | \"panoptic-missing\"\n | \"panoptic-failed\"\n | \"observation-off\"\n | \"not-collected\"\n | \"table-missing\"\n | \"reports-off\";\n\n/** The answer of any AI route that cannot serve its data. */\nexport type DevtoolsAiUnavailableView = {\n available: false;\n reason: DevtoolsAiUnavailableReasonView;\n title: string;\n message: string;\n /** A command or config line to copy; `null` when there is none. */\n command: string | null;\n /** The load error and versions for `panoptic-failed`; otherwise `null`. */\n detail: string | null;\n};\n\n/** Token counts. `input` is the whole prompt (cache reads and writes included) on every provider. */\nexport type DevtoolsAiTokenTotals = {\n input: number;\n output: number;\n /** Prompt tokens read from the provider's cache (part of `input`). */\n cached: number;\n /** Prompt tokens written to the provider's cache (part of `input`). */\n cacheWrite: number;\n /** Reasoning tokens (part of `output`). */\n reasoning: number;\n};\n\n/**\n * Estimated cost. `estimatedUsd` sums only runs whose model has pricing; runs\n * that used tokens on a model without pricing are counted in `unpricedRuns`\n * and `unpricedTokens`, never as zero cost.\n */\nexport type DevtoolsAiCostTotals = {\n estimatedUsd: number;\n pricedRuns: number;\n unpricedRuns: number;\n unpricedTokens: number;\n};\n\n/** Latency from the bucketed histogram: each figure is a bucket's upper bound (`null` with no runs). */\nexport type DevtoolsAiLatencyTotals = {\n p50Ms: number | null;\n p95Ms: number | null;\n meanMs: number | null;\n};\n\n/** Totals over a range (or one row of a breakdown). */\nexport type DevtoolsAiTotals = {\n runs: number;\n completed: number;\n failed: number;\n /** Runs that stopped early: `incomplete` and `max-iterations`. */\n incomplete: number;\n cancelled: number;\n /** `(failed + incomplete) / runs`, from 0 to 1; 0 with no runs. Cancelled runs are not errors. */\n errorRate: number;\n tokens: DevtoolsAiTokenTotals;\n cost: DevtoolsAiCostTotals;\n latency: DevtoolsAiLatencyTotals;\n /** Runs where a `fallbackModel()` chain answered from a later model at least once. */\n fallbackRuns: number;\n /** Runs where the provider refused at least once (finish reason `refusal` or a content filter). */\n refusals: number;\n};\n\n/**\n * Time series for a stacked chart: `values[i]` belongs to `buckets[i]`. At\n * most five named series; the rest are summed into one `other` series.\n */\nexport type DevtoolsAiSeriesSet = {\n /** Bucket starts, oldest first. */\n buckets: number[];\n series: {\n /** Stable identity (`provider/model`, an agent name, a category); the UI keys colours on it. */\n key: string;\n label: string;\n values: number[];\n /** `true` for the summed \"Other\" series. */\n other: boolean;\n }[];\n};\n\n/** One bucket of the error-rate line. */\nexport type DevtoolsAiRatePoint = {\n at: number;\n runs: number;\n /** Failed plus incomplete runs. */\n errors: number;\n /** `errors / runs`; `null` for a bucket without runs (the line has a gap there). */\n rate: number | null;\n};\n\n/** A row of the top agents or top models table. */\nexport type DevtoolsAiBreakdownRow = {\n /** The agent name, or `provider/model`. */\n key: string;\n label: string;\n /** The provider for a model row; `null` for an agent row. */\n provider: string | null;\n totals: DevtoolsAiTotals;\n /** Share of the range's estimated cost, 0 to 1 (share of runs when nothing was priced). */\n share: number;\n};\n\n/** The filter values present in a range, for the filter row. */\nexport type DevtoolsAiFilterOptions = {\n agents: string[];\n /** `provider/model` keys. */\n models: string[];\n providers: string[];\n};\n\n/** `GET api/ai/reports`. */\nexport type DevtoolsAiReportView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n /** The period of the same length just before `range`. */\n previousRange: { from: number; to: number };\n /** `false` when part of the previous period is older than the kept history: its totals are partial. */\n previousComplete: boolean;\n totals: DevtoolsAiTotals;\n previous: DevtoolsAiTotals;\n /** Estimated USD per bucket, by model (top five plus Other). */\n costByModel: DevtoolsAiSeriesSet;\n /** Tokens per bucket: series `uncached`, `cached`, `output`. */\n tokens: DevtoolsAiSeriesSet;\n errorRate: DevtoolsAiRatePoint[];\n /** Up to 10 rows, highest estimated cost first (most runs when nothing was priced). */\n topAgents: DevtoolsAiBreakdownRow[];\n topModels: DevtoolsAiBreakdownRow[];\n /** `provider/model` keys that used tokens without pricing in the range. */\n unpricedModels: string[];\n filters: DevtoolsAiFilterOptions;\n /** `true` when `@warlock.js/ai` observes nothing, so new runs are not counted. */\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** Whether a model's runs carried pricing in the range; `no-tokens` when no run used tokens. */\nexport type DevtoolsAiPricingState = \"set\" | \"missing\" | \"partial\" | \"no-tokens\";\n\n/** One row of the Models page. */\nexport type DevtoolsAiModelRow = {\n /** `provider/model`. */\n key: string;\n model: string;\n provider: string;\n totals: DevtoolsAiTotals;\n pricing: DevtoolsAiPricingState;\n /** Estimated USD per priced run; `null` when no run was priced. */\n costPerRunUsd: number | null;\n /** `fallbackRuns / runs`, 0 to 1. */\n fallbackRate: number;\n /** Agents that used the model, most runs first (at most 5). */\n agents: string[];\n /** Start of the last hour with a run. */\n lastSeenAt: number;\n};\n\n/** `GET api/ai/models`. */\nexport type DevtoolsAiModelsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n totals: DevtoolsAiTotals;\n /** Most runs first. */\n models: DevtoolsAiModelRow[];\n /** Runs per bucket by model (top five plus Other). */\n runsByModel: DevtoolsAiSeriesSet;\n filters: DevtoolsAiFilterOptions;\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** How failed runs are grouped on the Errors page. */\nexport type DevtoolsAiErrorCategory =\n | \"rate-limit\"\n | \"timeout\"\n | \"refusal\"\n | \"provider\"\n | \"budget\"\n | \"tool\"\n | \"schema\"\n | \"incomplete\"\n | \"other\";\n\n/** Every category, in the order the Errors page lists them. */\nexport const DEVTOOLS_AI_ERROR_CATEGORIES = [\n \"rate-limit\",\n \"timeout\",\n \"refusal\",\n \"provider\",\n \"budget\",\n \"tool\",\n \"schema\",\n \"incomplete\",\n \"other\",\n] as const satisfies readonly DevtoolsAiErrorCategory[];\n\n/** One category of failed runs. */\nexport type DevtoolsAiErrorGroup = {\n category: DevtoolsAiErrorCategory;\n /** \"Rate limit\", \"Timeout\", \"Refusal\", \"Provider error\", \"Budget\", \"Tool failed\", \"Invalid output\", \"Incomplete\", \"Other\". */\n label: string;\n count: number;\n /** Share of all failed runs in the range, 0 to 1. */\n share: number;\n previousCount: number;\n /** At most 5 each, most first. */\n byModel: { key: string; count: number }[];\n byAgent: { key: string; count: number }[];\n};\n\n/** A recent failed run (development only: production keeps no run details). */\nexport type DevtoolsAiFailedRun = {\n traceId: string;\n /** The agent span that failed. */\n agent: string;\n /** `provider/model`, or `null` when unreported. */\n model: string | null;\n status: string;\n category: DevtoolsAiErrorCategory;\n /** The error code (`PROVIDER_RATE_LIMIT`) or error name. */\n code: string | null;\n /** The error message, secrets scrubbed, at most 300 characters. */\n message: string | null;\n endedAt: number;\n requestId: string | null;\n};\n\n/** `GET api/ai/errors`. */\nexport type DevtoolsAiErrorsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n totals: DevtoolsAiTotals;\n previous: DevtoolsAiTotals;\n /** `false` when part of the previous period is older than the kept history: its totals are partial. */\n previousComplete: boolean;\n /** Categories with at least one failed run, most first. */\n groups: DevtoolsAiErrorGroup[];\n /** Failed runs per bucket by category (top five plus Other). */\n overTime: DevtoolsAiSeriesSet;\n /** Newest first, at most 50; `null` in production. */\n recent: DevtoolsAiFailedRun[] | null;\n filters: DevtoolsAiFilterOptions;\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** Usage of one run as the Runs page shows it. */\nexport type DevtoolsAiUsageView = {\n input: number;\n output: number;\n total: number;\n cachedTokens: number | null;\n cacheWriteTokens: number | null;\n /** `false` when `input` excludes cache tokens (the provider reports them on top). */\n inputIncludesCache: boolean | null;\n};\n\n/** One row of the Runs page (a Panoptic trace, content-free). */\nexport type DevtoolsAiRunRow = {\n traceId: string;\n requestId: string | null;\n sessionId: string | null;\n name: string;\n /** The root span type: `agent`, `workflow`, `supervisor`, … */\n type: string;\n status: string;\n startedAt: string;\n duration: number;\n usage: DevtoolsAiUsageView;\n /** Estimated USD; `null` when the run carried no pricing. */\n cost: number | null;\n models: string[];\n /** `promptName@promptVersion` of the root agent, or `null`. */\n promptKey: string | null;\n toolCalls: number;\n retries: number;\n incomplete: boolean;\n};\n\n/** A group of the Runs page (`groupBy=session|prompt|type`). */\nexport type DevtoolsAiRunGroup = {\n key: string;\n label: string;\n runs: number;\n failed: number;\n estimatedCostUsd: number;\n p95Ms: number | null;\n /** Trace ids of the group, newest first (at most 50). */\n traceIds: string[];\n};\n\n/** `GET api/ai/runs`. */\nexport type DevtoolsAiRunsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n /** Newest first, at most `limit` (default 200). */\n runs: DevtoolsAiRunRow[];\n /** `null` unless `groupBy` was given. */\n groups: DevtoolsAiRunGroup[] | null;\n stats: {\n /** Runs matching the filter (before `limit`). */\n count: number;\n failed: number;\n /** Priced runs only. */\n estimatedCostUsd: number;\n /** Runs that used tokens on a model without pricing (not in `estimatedCostUsd`). */\n unpricedRuns: number;\n p50Ms: number | null;\n p95Ms: number | null;\n };\n /** How many traces the dashboard keeps (`maxRequests`). */\n capacity: number;\n };\n\n/** A distinct system prompt seen in recent agent runs (the Evaluate picker). */\nexport type DevtoolsAiEvaluatePrompt = {\n /** The prompt's hash from the agent trace. */\n hash: string;\n /** Agents that used it, most recent first. */\n agents: string[];\n /** The newest run that carried its text. */\n runId: string;\n lastSeenAt: string;\n /** The first 200 characters. */\n preview: string;\n length: number;\n};\n\n/** `GET api/ai/evaluate`. */\nexport type DevtoolsAiEvaluateView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n /** Whether `panoptic.evaluate` (or `panoptic.dashboard.evaluate`) has a judge model. */\n configured: boolean;\n /** The judge model as `provider/name`; `null` when not configured. */\n judge: string | null;\n /** The configured default grading instructions; `\"\"` when none. */\n instructions: string;\n /** Newest first, at most 50. */\n prompts: DevtoolsAiEvaluatePrompt[];\n };\n\n/** `POST api/ai/evaluate` body: exactly one of `runId` and `systemPrompt`. */\nexport type DevtoolsAiEvaluateRequest = {\n /** An agent run whose system prompt text is kept. */\n runId?: string;\n /** A pasted prompt, 1 to 100,000 characters. */\n systemPrompt?: string;\n /** Overrides the configured instructions for this run; at most 4,000 characters. */\n instructions?: string;\n};\n\n/** `POST api/ai/evaluate` answer. */\nexport type DevtoolsAiEvaluateResult = {\n /** 0 to 1; `null` when the judge returned no score. */\n score: number | null;\n issues: string[];\n /** The judge model as `provider/name`. */\n judge: string;\n durationMs: number;\n};\n"],"mappings":";;;;;;;AA+DA,MAA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ages/devtools/src/production/contracts.ts"],"sourcesContent":["/**\n * The contracts of the devtools production monitor: the shapes the server\n * stores, the JSON its API returns, and the few constants both sides share.\n *\n * This file has NO imports, so the dashboard (`ui-src/`) can import its types\n * too. Every timestamp is epoch milliseconds, every duration milliseconds,\n * every size bytes. Absent values are `null`, never missing.\n */\n\n// ---------------------------------------------------------------------------\n// Modes, roles and stages\n// ---------------------------------------------------------------------------\n\n/** Where the dashboard runs: the loopback development dashboard or the signed-in production monitor. */\nexport type DevtoolsMode = \"development\" | \"production\";\n\n/** What an account may do: `admin` manages users and the dashboard, `viewer` reads. */\nexport type DevtoolsRole = \"admin\" | \"viewer\";\n\n/**\n * Where a browser session stands. Only `active` reaches the data routes;\n * every other stage reaches only the sign-in steps it needs next.\n */\nexport type DevtoolsSessionStage =\n | \"signed-out\"\n | \"password-change\"\n | \"mfa-enrol\"\n | \"mfa-verify\"\n | \"active\";\n\n/** How an account's current password was set. `env` and `reset` passwords must be changed at the next sign-in. */\nexport type DevtoolsPasswordSource = \"env\" | \"setup\" | \"invite\" | \"user\" | \"reset\";\n\n// ---------------------------------------------------------------------------\n// Instances\n// ---------------------------------------------------------------------------\n\n/** One process that runs the monitor (a pm2 or cluster worker, a container). */\nexport type DevtoolsInstanceInfo = {\n /** Stable for the life of the process: `<host>:<pid>:<start time base36>`. */\n id: string;\n /** What the dashboard shows: `<host> #<worker>` or `<host> pid <pid>`. */\n label: string;\n host: string;\n pid: number;\n /** pm2's `NODE_APP_INSTANCE` / `pm_id`, or the cluster worker id; `null` when neither is set. */\n worker: string | null;\n startedAt: number;\n /** When the instance last wrote its report (the current time for the instance answering). */\n seenAt: number;\n nodeVersion: string;\n};\n\n// ---------------------------------------------------------------------------\n// Histograms (mergeable across instances)\n// ---------------------------------------------------------------------------\n\n/**\n * Upper bounds (inclusive, ms) of the latency buckets every histogram uses.\n * A histogram's `counts` has one more entry than this list: the last entry\n * counts everything above the highest bound. Fixed bounds make histograms\n * from several instances merge exactly.\n */\nexport const DEVTOOLS_LATENCY_BUCKETS_MS = [\n 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000,\n] as const;\n\n/** A latency histogram over `DEVTOOLS_LATENCY_BUCKETS_MS`. */\nexport type DevtoolsHistogram = {\n /** `DEVTOOLS_LATENCY_BUCKETS_MS.length + 1` entries. */\n counts: number[];\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n// ---------------------------------------------------------------------------\n// Query, route and error statistics\n// ---------------------------------------------------------------------------\n\n/** Statistics for one normalized query shape (literals and bindings replaced by `?`). */\nexport type DevtoolsQueryShapeStats = {\n /** First 16 hex characters of the SHA-256 of `shape`; the id the API and EXPLAIN use. */\n id: string;\n /** The normalized query, at most 2000 characters. Never holds a value. */\n shape: string;\n driver: \"postgres\" | \"mongodb\";\n connection: string;\n count: number;\n errors: number;\n histogram: DevtoolsHistogram;\n /** Sampled requests in which this shape reached the N+1 threshold, and the highest count in one request. */\n nPlusOne: { requests: number; maxPerRequest: number };\n /** The slowest run seen; its values stay in the process that ran it (see EXPLAIN). */\n slowest: {\n durationMs: number;\n at: number;\n route: string | null;\n requestId: string | null;\n instance: string;\n } | null;\n firstSeen: number;\n lastSeen: number;\n /** Whether EXPLAIN can run for this shape (a Postgres `SELECT`/`WITH`, or a MongoDB `find`/`aggregate`/`count`). */\n explainable: boolean;\n};\n\n/** Time spent in one named request phase (middleware, validation, handler, …) on one route. */\nexport type DevtoolsRoutePhaseStats = {\n name: string;\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n/** Statistics for one route pattern and method. */\nexport type DevtoolsRouteStats = {\n /** `\"<METHOD> <route pattern>\"`, e.g. `\"GET /posts/:slug\"`. */\n key: string;\n method: string;\n route: string;\n count: number;\n /** Responses with a 5xx status or a thrown error. */\n errors: number;\n histogram: DevtoolsHistogram;\n /** At most 30 phases, slowest total first. */\n phases: DevtoolsRoutePhaseStats[];\n slowest: { durationMs: number; at: number; requestId: string | null; instance: string } | null;\n};\n\n/** Errors grouped by fingerprint (normalized message + route + source). */\nexport type DevtoolsErrorGroup = {\n /** First 16 hex characters of the SHA-256 of the fingerprint. */\n id: string;\n /** The latest message as raised, at most 500 characters. */\n message: string;\n /** The error class name when known (`TypeError`). */\n name: string | null;\n source: \"request\" | \"log\";\n route: string | null;\n status: number | null;\n count: number;\n firstSeen: number;\n lastSeen: number;\n lastRequestId: string | null;\n /** The latest stack, at most 4000 characters; `null` when none was available. */\n stack: string | null;\n};\n\n/** A warn/error log entry kept for the Logs panel in production (no context: it may hold values). */\nexport type DevtoolsReportLogEntry = {\n level: \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\";\n module: string;\n action: string;\n /** At most 1000 characters. */\n message: string;\n at: number;\n requestId: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Resources, health, jobs\n// ---------------------------------------------------------------------------\n\n/** One resource reading of a process. */\nexport type DevtoolsResourcePoint = {\n at: number;\n rssBytes: number;\n heapUsedBytes: number;\n heapTotalBytes: number;\n externalBytes: number;\n /** Process CPU time over wall time since the previous point, 0–100 per core (can exceed 100). */\n cpuPercent: number;\n eventLoopDelayP50Ms: number;\n eventLoopDelayP99Ms: number;\n eventLoopDelayMaxMs: number;\n /** `performance.eventLoopUtilization()` since the previous point, 0–1. */\n eventLoopUtilization: number;\n /** Garbage collections since the previous point. */\n gcCount: number;\n /** Total GC pause since the previous point. */\n gcPauseMs: number;\n};\n\n/** The latest resource reading plus values that change rarely. */\nexport type DevtoolsResourceSnapshot = DevtoolsResourcePoint & {\n heapLimitBytes: number;\n uptimeSeconds: number;\n /** Totals since the monitor started, by GC kind. */\n gcByKind: Record<\n \"minor\" | \"major\" | \"incremental\" | \"weakcb\",\n { count: number; pauseMs: number }\n >;\n};\n\n/** Readiness checks (core's `health` registry) of one process, with a short history. */\nexport type DevtoolsHealthReport = {\n status: \"ok\" | \"error\" | \"unknown\";\n checkedAt: number | null;\n checks: Record<string, boolean>;\n /** Newest last, at most 60 entries. */\n history: { at: number; status: \"ok\" | \"error\"; failed: string[] }[];\n};\n\n/** One scheduled job (`@warlock.js/scheduler`). */\nexport type DevtoolsScheduleInfo = {\n name: string;\n /** The cron expression, or `null` for an interval schedule. */\n cron: string | null;\n /** A readable interval such as `\"every 5 minutes\"`, or `null`. */\n interval: string | null;\n isRunning: boolean;\n lastRunAt: number | null;\n nextRunAt: number | null;\n lastDurationMs: number | null;\n lastError: string | null;\n runs: number;\n failures: number;\n /** The latest runs, newest first (at most 10). Absent when the scheduler keeps no history. */\n recentRuns?: DevtoolsScheduleRun[];\n};\n\n/** One recorded run of a scheduled job; the error is a message, never a stack. */\nexport type DevtoolsScheduleRun = {\n startedAt: number;\n durationMs: number;\n outcome: \"success\" | \"failed\" | \"skipped\";\n error?: string;\n skipReason?: string;\n};\n\n/** Background work of one process: schedules and queue counts, each `available: false` when its package is not installed. */\nexport type DevtoolsJobsReport = {\n available: { scheduler: boolean; queue: boolean };\n schedules: DevtoolsScheduleInfo[];\n /** Job counts per queue and state (`waiting`, `active`, `delayed`, `failed`, `completed`). */\n queues: DevtoolsQueueInfo[];\n};\n\n/** One queue's job counts. `countsAvailable: false` when the active driver cannot count. */\nexport type DevtoolsQueueInfo = {\n name: string;\n counts: Record<string, number>;\n countsAvailable?: boolean;\n};\n\n/** What the capture did since the process started. */\nexport type DevtoolsCaptureCounters = {\n sampleRate: number;\n requests: number;\n sampled: number;\n /** Unsampled requests kept as a summary because they were slow or failed. */\n keptUnsampled: number;\n /** Samples written to the database. */\n stored: number;\n /** Samples not written because the per-minute budget was spent. */\n droppedStored: number;\n /** Query shapes, routes and error groups evicted to keep memory bounded. */\n evictedShapes: number;\n evictedRoutes: number;\n evictedErrors: number;\n /** Queries not kept inside a sampled request because it reached its per-request limit. */\n droppedQueries: number;\n};\n\n/**\n * Everything one process reports, written to the database every\n * `reportIntervalMs` (one row per instance) and merged by the dashboard.\n * Serialized it stays under 256 KB: lists are trimmed from the end.\n */\nexport type DevtoolsInstanceReport = {\n instance: DevtoolsInstanceInfo;\n at: number;\n resources: { snapshot: DevtoolsResourceSnapshot; history: DevtoolsResourcePoint[] };\n /** At most 200, highest total time first. */\n queries: DevtoolsQueryShapeStats[];\n /** At most 200, highest total time first. */\n routes: DevtoolsRouteStats[];\n /** At most 50, newest first. */\n errors: DevtoolsErrorGroup[];\n /** At most 50, newest first. */\n logs: DevtoolsReportLogEntry[];\n health: DevtoolsHealthReport;\n jobs: DevtoolsJobsReport;\n capture: DevtoolsCaptureCounters;\n};\n\n// ---------------------------------------------------------------------------\n// Requests (stored samples)\n// ---------------------------------------------------------------------------\n\n/**\n * A request row. Matches the development `DevtoolsRequestSummary` field for\n * field, plus where it was captured.\n */\nexport type DevtoolsSampleSummary = {\n id: string;\n method: string;\n path: string;\n route?: string;\n status?: number;\n startedAt: number;\n durationMs?: number;\n queryCount: number;\n warningCount: number;\n /** Read from the persisted request log only. */\n persisted?: true;\n /** The instance that served the request. */\n instance?: string;\n /** Kept because it was slow or failed, without a timeline (the request was not sampled). */\n partial?: true;\n};\n\n/** A query inside a stored sample: the shape only, never the SQL text with values or the bindings. */\nexport type DevtoolsSampleQuery = {\n id: string;\n connection: string;\n driver: \"postgres\" | \"mongodb\";\n /** Same as `shape`: kept under this name so the request view renders it like a development query. */\n sql?: string;\n collection?: string;\n command?: string;\n shape: string;\n shapeId: string;\n startedAt: number;\n durationMs: number;\n rowCount?: number;\n error?: string;\n};\n\n/** The timeline of a sampled request, with every value removed (see the redaction rules). */\nexport type DevtoolsSampleDetail = DevtoolsSampleSummary & {\n error?: string;\n phases: { name: string; startedAt: number; durationMs: number }[];\n queries: DevtoolsSampleQuery[];\n /** Cache operation counts only; keys are not kept. */\n cache: { hits: number; misses: number; writes: number };\n /** Log entries without context. */\n logs: { level: string; module: string; action: string; message: string; at: number }[];\n warnings: { type: \"n+1\"; message: string; shape: string; count: number }[];\n /** Queries left out because the request reached `maxQueriesPerRequest`. */\n droppedQueries: number;\n};\n\n// ---------------------------------------------------------------------------\n// API views (what the dashboard reads)\n// ---------------------------------------------------------------------------\n\n/** `GET api/instances`. */\nexport type DevtoolsInstancesView = {\n /** The instance that answered this request. */\n current: string;\n /** Instances seen in the last 5 minutes (the answering one included), newest first. */\n instances: DevtoolsInstanceInfo[];\n};\n\n/** `GET api/resources?instance=<id|all>`. */\nexport type DevtoolsResourcesView = {\n instances: {\n instance: DevtoolsInstanceInfo;\n snapshot: DevtoolsResourceSnapshot;\n history: DevtoolsResourcePoint[];\n }[];\n};\n\n/** A shape row with figures computed from its histogram. */\nexport type DevtoolsQueryShapeRow = DevtoolsQueryShapeStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n /** Ids of the instances that reported this shape. */\n instances: string[];\n};\n\n/** `GET api/queries/stats?instance=&sort=total|p95|count|n+1&limit=`. */\nexport type DevtoolsQueryStatsView = {\n shapes: DevtoolsQueryShapeRow[];\n /** The sample rate the counts come from; counts are of sampled requests only. */\n sampleRate: number;\n instanceCount: number;\n evicted: number;\n};\n\n/** A route row with figures computed from its histogram. */\nexport type DevtoolsRouteStatsRow = DevtoolsRouteStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n instances: string[];\n};\n\n/** `GET api/routes/stats?instance=&sort=total|p95|count|errors&limit=`. */\nexport type DevtoolsRouteStatsView = {\n routes: DevtoolsRouteStatsRow[];\n sampleRate: number;\n instanceCount: number;\n};\n\n/** `GET api/health?instance=`. */\nexport type DevtoolsHealthView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsHealthReport }[];\n};\n\n/** `GET api/errors?instance=&limit=`. */\nexport type DevtoolsErrorsView = {\n groups: (DevtoolsErrorGroup & { instances: string[] })[];\n};\n\n/**\n * One row of `GET api/logs?level=&module=&instance=` (newest first), in both\n * modes. Development rows carry `context` and no `instance`; production rows\n * carry `instance` and never `context`.\n */\nexport type DevtoolsLogRow = DevtoolsReportLogEntry & {\n instance: string | null;\n context?: unknown;\n};\n\n/** `GET api/logs`: the rows, newest first (a plain array, as in 5.55). */\nexport type DevtoolsLogsView = DevtoolsLogRow[];\n\n/** `GET api/jobs?instance=`. */\nexport type DevtoolsJobsView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsJobsReport }[];\n};\n\n/** `POST api/queries/:shapeId/explain`. */\nexport type DevtoolsExplainResult = {\n shapeId: string;\n driver: \"postgres\" | \"mongodb\";\n /** `true` only when the project allows executing plans (`explain.executing`). */\n executing: boolean;\n plan: unknown;\n /** The instance whose example ran the EXPLAIN. */\n instance: string;\n};\n\n/** One dashboard tab, as `GET api/panels` lists it (enabled tabs only, in display order). */\nexport type DevtoolsPanelInfo = {\n id: string;\n title: string;\n /** `built-in` tabs are React views in the bundle; `package` tabs load `panels/<id>/view.js`. */\n type: \"built-in\" | \"package\";\n /** Whether the panel declares a shared view (`DevtoolsPanel.share`); always `false` for built-in tabs. */\n shareable: boolean;\n};\n\n/**\n * The built-in tabs, in display order, with whether production shows them\n * when the project says nothing (`production.panels` overrides per id).\n *\n * The AI section (`ai-reports`, `ai`, `agents`, `ai-models`, `ai-errors`,\n * `ai-evaluate`) sits under \"AI\" in the sidebar. `ai` keeps its id (it is the\n * Runs page) so existing links and `production.panels.ai` keep working. In\n * production the three report tabs show only when the AI feed is available\n * (Panoptic loads), unless `production.panels` turns one on explicitly.\n */\nexport const DEVTOOLS_BUILT_IN_PANELS = [\n { id: \"requests\", title: \"Requests\", production: true },\n { id: \"queries\", title: \"Queries\", production: true },\n { id: \"routes\", title: \"Routes\", production: true },\n { id: \"resources\", title: \"Resources\", production: true },\n { id: \"health\", title: \"Health\", production: true },\n { id: \"errors\", title: \"Errors\", production: true },\n { id: \"logs\", title: \"Logs\", production: true },\n { id: \"jobs\", title: \"Jobs\", production: true },\n { id: \"mail\", title: \"Mail\", production: false },\n { id: \"ai-reports\", title: \"Reports\", production: true },\n { id: \"ai\", title: \"Runs\", production: false },\n { id: \"agents\", title: \"Agents\", production: false },\n { id: \"ai-models\", title: \"Models\", production: true },\n { id: \"ai-errors\", title: \"Errors\", production: true },\n { id: \"ai-evaluate\", title: \"Evaluate\", production: false },\n { id: \"api\", title: \"API\", production: false },\n] as const;\n\n/** The id of a built-in tab. */\nexport type DevtoolsBuiltInPanelId = (typeof DEVTOOLS_BUILT_IN_PANELS)[number][\"id\"];\n\n// ---------------------------------------------------------------------------\n// Accounts, sessions, invites\n// ---------------------------------------------------------------------------\n\n/** An account as the API shows it (never a hash or a secret). */\nexport type DevtoolsAccountView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n twoFactor: {\n totp: boolean;\n passkeys: { id: string; name: string; createdAt: number; lastUsedAt: number | null }[];\n recoveryCodesLeft: number;\n };\n mustChangePassword: boolean;\n createdAt: number;\n lastLoginAt: number | null;\n};\n\n/** `GET api/auth/session`: who is signed in and what comes next. */\nexport type DevtoolsSessionView = {\n mode: DevtoolsMode;\n stage: DevtoolsSessionStage;\n /** `null` when signed out, and in development (no accounts there). */\n account: DevtoolsAccountView | null;\n /** `admin` in development; `null` when signed out. */\n role: DevtoolsRole | null;\n /** The token to send as `X-Devtools-Csrf` on every POST/PUT/PATCH/DELETE; `null` when signed out and in development. */\n csrf: string | null;\n /** When the session ends at the latest; `null` when signed out and in development. */\n expiresAt: number | null;\n /** The instance that answered; `null` when signed out. */\n instance: DevtoolsInstanceInfo | null;\n /** Sign-in methods the server offers; `null` when signed out. */\n methods: { totp: true; passkeys: boolean } | null;\n /** Read-only share links: `enabled` mirrors `production.share.enabled`; `null` when signed out and in development. */\n share: { enabled: boolean } | null;\n /** The installed `@warlock.js/core` version; `null` when signed out or not found. */\n warlockVersion: string | null;\n /** The app's own `package.json` name and version (nothing else is read); `null` when signed out or not found. */\n app: { name: string; version: string } | null;\n};\n\n/** `POST api/auth/login` body. */\nexport type DevtoolsLoginInput = { email: string; password: string };\n\n/** Answer of every sign-in step: the next stage, and the new CSRF token when the session changed. */\nexport type DevtoolsAuthStepResult = { stage: DevtoolsSessionStage; csrf: string | null };\n\n/** `POST api/auth/totp/start` (and `api/account/totp/start`). */\nexport type DevtoolsTotpEnrolment = {\n /** Base32, for manual entry. */\n secret: string;\n /** `otpauth://totp/...`, rendered as a QR code by the dashboard. */\n uri: string;\n issuer: string;\n account: string;\n};\n\n/** Recovery codes, shown once. */\nexport type DevtoolsRecoveryCodes = { codes: string[] };\n\n/** A pending or used invite. */\nexport type DevtoolsInviteView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n createdAt: number;\n expiresAt: number;\n createdBy: string | null;\n usedAt: number | null;\n};\n\n/** `POST api/admin/invites`: the token appears only in this answer. */\nexport type DevtoolsCreatedInvite = { invite: DevtoolsInviteView; token: string };\n\n/** `GET api/admin/users`. */\nexport type DevtoolsUserListView = {\n accounts: DevtoolsAccountView[];\n invites: DevtoolsInviteView[];\n};\n\n/** A session as its owner sees it (`GET api/account/sessions`). */\nexport type DevtoolsSessionInfo = {\n id: string;\n current: boolean;\n createdAt: number;\n lastSeenAt: number;\n expiresAt: number;\n ip: string | null;\n userAgent: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Share links\n// ---------------------------------------------------------------------------\n\n/** Where a share link stands. `revoked` wins over `expired`. */\nexport type DevtoolsShareStatus = \"active\" | \"expired\" | \"revoked\";\n\n/** A share link as the admin screen shows it (never the token or its hash). */\nexport type DevtoolsShareView = {\n id: string;\n /** The id of the panel the link opens. */\n panel: string;\n /** What the admin called it, 1-80 characters. */\n label: string;\n /** The email of the admin who made it; `null` when that account is gone. */\n createdBy: string | null;\n createdAt: number;\n expiresAt: number;\n revokedAt: number | null;\n lastUsedAt: number | null;\n /** How many times the link was used, counted at most once a minute. */\n uses: number;\n status: DevtoolsShareStatus;\n};\n\n/** `GET api/admin/shares`. */\nexport type DevtoolsShareList = {\n enabled: boolean;\n /** The longest life a link may have, in days. */\n maxDays: number;\n /** The panels that declare a shared view. */\n panels: { id: string; title: string }[];\n /** Newest first. */\n shares: DevtoolsShareView[];\n};\n\n/** `POST api/admin/shares` body. `label` is 1-80 characters, `days` a whole number from 1 to `maxDays`. */\nexport type DevtoolsShareCreateInput = { panel: string; label: string; days: number };\n\n/** `POST api/admin/shares`: the URL (with the token in its fragment) appears only in this answer. */\nexport type DevtoolsCreatedShare = { share: DevtoolsShareView; url: string };\n\n/**\n * What a share link opens, answered by `POST api/share/open` and\n * `GET api/share/info`: the panel and the names the shared view may load.\n */\nexport type DevtoolsShareOpenAnswer = {\n panel: string;\n /** The panel's title. */\n title: string;\n label: string;\n expiresAt: number;\n /** Served names from the panel's `assets` the shared page may load. */\n assets: string[];\n /** Whether the shared page may load images from the panel's `files`. */\n files: boolean;\n};\n\n/** The longest label of a share link. */\nexport const DEVTOOLS_SHARE_LABEL_MAX = 80;\n\n// ---------------------------------------------------------------------------\n// Audit log\n// ---------------------------------------------------------------------------\n\n/** Every audited event. `login.failed` and `mfa.failed` are the ones rate limits count. */\nexport type DevtoolsAuditType =\n | \"admin.seeded\"\n | \"admin.reset\"\n | \"setup.completed\"\n | \"login.succeeded\"\n | \"login.failed\"\n | \"login.blocked\"\n | \"mfa.succeeded\"\n | \"mfa.failed\"\n | \"mfa.enrolled\"\n | \"mfa.removed\"\n | \"recovery-code.used\"\n | \"recovery-codes.regenerated\"\n | \"passkey.added\"\n | \"passkey.removed\"\n | \"password.changed\"\n | \"logout\"\n | \"session.revoked\"\n | \"invite.created\"\n | \"invite.revoked\"\n | \"invite.accepted\"\n | \"account.role-changed\"\n | \"account.removed\"\n | \"account.mfa-reset\"\n | \"account.signed-out\"\n | \"dashboard.disabled\"\n | \"dashboard.enabled\"\n | \"dashboard.locked\"\n | \"explain.run\"\n | \"requests.cleared\"\n | \"panel.action\"\n | \"share.created\"\n | \"share.revoked\"\n | \"share.failed\";\n\n/** The audit types that count toward the account, IP and global failure limits. */\nexport const DEVTOOLS_FAILURE_AUDIT_TYPES: readonly DevtoolsAuditType[] = [\n \"login.failed\",\n \"mfa.failed\",\n \"share.failed\",\n];\n\n/** One audit log entry. */\nexport type DevtoolsAuditEntry = {\n id: string;\n at: number;\n type: DevtoolsAuditType;\n /** The account acting or targeted; `null` for an unknown email or the CLI. */\n accountId: string | null;\n /** The email as typed or as stored, lower-cased; `null` when there was none. */\n email: string | null;\n /** `\"cli\"` for a command, else the client IP after trusted-proxy resolution. */\n ip: string | null;\n /** At most 200 characters. */\n userAgent: string | null;\n /** Small flat facts: target account, role, shape id, panel route. Never a secret. */\n detail: Record<string, string | number | boolean | null>;\n /** Short reference shown to users in error messages (8 characters). */\n ref: string;\n};\n\n// ---------------------------------------------------------------------------\n// Errors the API returns\n// ---------------------------------------------------------------------------\n\n/**\n * Error codes in API answers. Each has a fixed message (see\n * `DEVTOOLS_ERROR_MESSAGES` in `errors.ts`) that says what failed and what to\n * do next.\n */\nexport type DevtoolsErrorCode =\n | \"auth.invalid-credentials\"\n | \"auth.invalid-code\"\n | \"auth.invalid-setup-token\"\n | \"auth.password-too-short\"\n | \"auth.password-too-long\"\n | \"auth.password-common\"\n | \"auth.password-same-as-email\"\n | \"auth.password-unchanged\"\n | \"auth.wrong-current-password\"\n | \"auth.busy\"\n | \"invite.invalid\"\n | \"invite.email-taken\"\n | \"account.not-found\"\n | \"account.last-admin\"\n | \"account.self\"\n | \"account.last-factor\"\n | \"role.forbidden\"\n | \"csrf.invalid\"\n | \"passkey.unavailable\"\n | \"passkey.failed\"\n | \"explain.not-allowed\"\n | \"explain.unsupported\"\n | \"explain.elsewhere\"\n | \"explain.failed\"\n | \"request.not-found\"\n | \"request.invalid-filter\"\n | \"share.not-found\"\n | \"stream.too-many\"\n | \"ai.range-invalid\"\n | \"ai.evaluate-unavailable\"\n | \"ai.prompt-not-found\"\n | \"ai.evaluate-failed\"\n | \"input.invalid\"\n | \"server.error\";\n\n/** The JSON body of every failed API call. */\nexport type DevtoolsApiErrorBody = {\n /** What failed and what to do next. */\n error: string;\n code: DevtoolsErrorCode;\n /** Short reference to quote to an admin; also written to the audit log or server log. */\n ref?: string;\n /** The instance that answered, when it matters (`explain.elsewhere`). */\n instance?: string;\n};\n\n// ---------------------------------------------------------------------------\n// AI section: reports, runs, models, errors, evaluate\n// ---------------------------------------------------------------------------\n\n/**\n * Upper bounds (inclusive, ms) of the latency buckets of the AI rollups.\n * Model calls take seconds, so these differ from `DEVTOOLS_LATENCY_BUCKETS_MS`.\n * A histogram has one more count than this list: the last counts everything\n * above five minutes. Fixed bounds make rollups from several processes add up\n * exactly. Changing them is a breaking change of the stored rollups.\n */\nexport const DEVTOOLS_AI_LATENCY_BUCKETS_MS = [\n 250, 500, 1000, 2000, 3000, 5000, 7500, 10000, 15000, 20000, 30000, 45000, 60000, 120000, 300000,\n] as const;\n\n/** The date-range presets of the Reports, Models and Errors pages. */\nexport type DevtoolsAiRangePreset = \"24h\" | \"7d\" | \"30d\";\n\n/** The range a report covers, after the server aligned it to its buckets. */\nexport type DevtoolsAiResolvedRange = {\n preset: DevtoolsAiRangePreset | \"custom\";\n /** Inclusive start, on an hour boundary. */\n from: number;\n /** Exclusive end, on an hour boundary. */\n to: number;\n /** Bucket width of the charts: 1 hour, 6 hours or 1 day. */\n stepMs: number;\n /** The browser's offset from UTC (minutes east), used to align day buckets. */\n utcOffsetMinutes: number;\n};\n\n/** Why an AI page has nothing to show; `title`, `message` and `command` are written for the page. */\nexport type DevtoolsAiUnavailableReasonView =\n | \"ai-missing\"\n | \"panoptic-missing\"\n | \"panoptic-failed\"\n | \"observation-off\"\n | \"not-collected\"\n | \"table-missing\"\n | \"reports-off\";\n\n/** The answer of any AI route that cannot serve its data. */\nexport type DevtoolsAiUnavailableView = {\n available: false;\n reason: DevtoolsAiUnavailableReasonView;\n title: string;\n message: string;\n /** A command or config line to copy; `null` when there is none. */\n command: string | null;\n /** The load error and versions for `panoptic-failed`; otherwise `null`. */\n detail: string | null;\n};\n\n/** Token counts. `input` is the whole prompt (cache reads and writes included) on every provider. */\nexport type DevtoolsAiTokenTotals = {\n input: number;\n output: number;\n /** Prompt tokens read from the provider's cache (part of `input`). */\n cached: number;\n /** Prompt tokens written to the provider's cache (part of `input`). */\n cacheWrite: number;\n /** Reasoning tokens (part of `output`). */\n reasoning: number;\n};\n\n/**\n * Estimated cost. `estimatedUsd` sums only runs whose model has pricing; runs\n * that used tokens on a model without pricing are counted in `unpricedRuns`\n * and `unpricedTokens`, never as zero cost.\n */\nexport type DevtoolsAiCostTotals = {\n estimatedUsd: number;\n pricedRuns: number;\n unpricedRuns: number;\n unpricedTokens: number;\n};\n\n/** Latency from the bucketed histogram: each figure is a bucket's upper bound (`null` with no runs). */\nexport type DevtoolsAiLatencyTotals = {\n p50Ms: number | null;\n p95Ms: number | null;\n meanMs: number | null;\n};\n\n/** Totals over a range (or one row of a breakdown). */\nexport type DevtoolsAiTotals = {\n runs: number;\n completed: number;\n failed: number;\n /** Runs that stopped early: `incomplete` and `max-iterations`. */\n incomplete: number;\n cancelled: number;\n /** `(failed + incomplete) / runs`, from 0 to 1; 0 with no runs. Cancelled runs are not errors. */\n errorRate: number;\n tokens: DevtoolsAiTokenTotals;\n cost: DevtoolsAiCostTotals;\n latency: DevtoolsAiLatencyTotals;\n /** Runs where a `fallbackModel()` chain answered from a later model at least once. */\n fallbackRuns: number;\n /** Runs where the provider refused at least once (finish reason `refusal` or a content filter). */\n refusals: number;\n};\n\n/**\n * Time series for a stacked chart: `values[i]` belongs to `buckets[i]`. At\n * most five named series; the rest are summed into one `other` series.\n */\nexport type DevtoolsAiSeriesSet = {\n /** Bucket starts, oldest first. */\n buckets: number[];\n series: {\n /** Stable identity (`provider/model`, an agent name, a category); the UI keys colours on it. */\n key: string;\n label: string;\n values: number[];\n /** `true` for the summed \"Other\" series. */\n other: boolean;\n }[];\n};\n\n/** One bucket of the error-rate line. */\nexport type DevtoolsAiRatePoint = {\n at: number;\n runs: number;\n /** Failed plus incomplete runs. */\n errors: number;\n /** `errors / runs`; `null` for a bucket without runs (the line has a gap there). */\n rate: number | null;\n};\n\n/** A row of the top agents or top models table. */\nexport type DevtoolsAiBreakdownRow = {\n /** The agent name, or `provider/model`. */\n key: string;\n label: string;\n /** The provider for a model row; `null` for an agent row. */\n provider: string | null;\n totals: DevtoolsAiTotals;\n /** Share of the range's estimated cost, 0 to 1 (share of runs when nothing was priced). */\n share: number;\n};\n\n/** The filter values present in a range, for the filter row. */\nexport type DevtoolsAiFilterOptions = {\n agents: string[];\n /** `provider/model` keys. */\n models: string[];\n providers: string[];\n};\n\n/** `GET api/ai/reports`. */\nexport type DevtoolsAiReportView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n /** The period of the same length just before `range`. */\n previousRange: { from: number; to: number };\n /** `false` when part of the previous period is older than the kept history: its totals are partial. */\n previousComplete: boolean;\n totals: DevtoolsAiTotals;\n previous: DevtoolsAiTotals;\n /** Estimated USD per bucket, by model (top five plus Other). */\n costByModel: DevtoolsAiSeriesSet;\n /** Tokens per bucket: series `uncached`, `cached`, `output`. */\n tokens: DevtoolsAiSeriesSet;\n errorRate: DevtoolsAiRatePoint[];\n /** Up to 10 rows, highest estimated cost first (most runs when nothing was priced). */\n topAgents: DevtoolsAiBreakdownRow[];\n topModels: DevtoolsAiBreakdownRow[];\n /** `provider/model` keys that used tokens without pricing in the range. */\n unpricedModels: string[];\n filters: DevtoolsAiFilterOptions;\n /** `true` when `@warlock.js/ai` observes nothing, so new runs are not counted. */\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** Whether a model's runs carried pricing in the range; `no-tokens` when no run used tokens. */\nexport type DevtoolsAiPricingState = \"set\" | \"missing\" | \"partial\" | \"no-tokens\";\n\n/** One row of the Models page. */\nexport type DevtoolsAiModelRow = {\n /** `provider/model`. */\n key: string;\n model: string;\n provider: string;\n totals: DevtoolsAiTotals;\n pricing: DevtoolsAiPricingState;\n /** Estimated USD per priced run; `null` when no run was priced. */\n costPerRunUsd: number | null;\n /** `fallbackRuns / runs`, 0 to 1. */\n fallbackRate: number;\n /** Agents that used the model, most runs first (at most 5). */\n agents: string[];\n /** Start of the last hour with a run. */\n lastSeenAt: number;\n};\n\n/** `GET api/ai/models`. */\nexport type DevtoolsAiModelsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n totals: DevtoolsAiTotals;\n /** Most runs first. */\n models: DevtoolsAiModelRow[];\n /** Runs per bucket by model (top five plus Other). */\n runsByModel: DevtoolsAiSeriesSet;\n filters: DevtoolsAiFilterOptions;\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** How failed runs are grouped on the Errors page. */\nexport type DevtoolsAiErrorCategory =\n | \"rate-limit\"\n | \"timeout\"\n | \"refusal\"\n | \"provider\"\n | \"budget\"\n | \"tool\"\n | \"schema\"\n | \"incomplete\"\n | \"other\";\n\n/** Every category, in the order the Errors page lists them. */\nexport const DEVTOOLS_AI_ERROR_CATEGORIES = [\n \"rate-limit\",\n \"timeout\",\n \"refusal\",\n \"provider\",\n \"budget\",\n \"tool\",\n \"schema\",\n \"incomplete\",\n \"other\",\n] as const satisfies readonly DevtoolsAiErrorCategory[];\n\n/** One category of failed runs. */\nexport type DevtoolsAiErrorGroup = {\n category: DevtoolsAiErrorCategory;\n /** \"Rate limit\", \"Timeout\", \"Refusal\", \"Provider error\", \"Budget\", \"Tool failed\", \"Invalid output\", \"Incomplete\", \"Other\". */\n label: string;\n count: number;\n /** Share of all failed runs in the range, 0 to 1. */\n share: number;\n previousCount: number;\n /** At most 5 each, most first. */\n byModel: { key: string; count: number }[];\n byAgent: { key: string; count: number }[];\n};\n\n/** A recent failed run (development only: production keeps no run details). */\nexport type DevtoolsAiFailedRun = {\n traceId: string;\n /** The agent span that failed. */\n agent: string;\n /** `provider/model`, or `null` when unreported. */\n model: string | null;\n status: string;\n category: DevtoolsAiErrorCategory;\n /** The error code (`PROVIDER_RATE_LIMIT`) or error name. */\n code: string | null;\n /** The error message, secrets scrubbed, at most 300 characters. */\n message: string | null;\n endedAt: number;\n requestId: string | null;\n};\n\n/** `GET api/ai/errors`. */\nexport type DevtoolsAiErrorsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n totals: DevtoolsAiTotals;\n previous: DevtoolsAiTotals;\n /** `false` when part of the previous period is older than the kept history: its totals are partial. */\n previousComplete: boolean;\n /** Categories with at least one failed run, most first. */\n groups: DevtoolsAiErrorGroup[];\n /** Failed runs per bucket by category (top five plus Other). */\n overTime: DevtoolsAiSeriesSet;\n /** Newest first, at most 50; `null` in production. */\n recent: DevtoolsAiFailedRun[] | null;\n filters: DevtoolsAiFilterOptions;\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** Usage of one run as the Runs page shows it. */\nexport type DevtoolsAiUsageView = {\n input: number;\n output: number;\n total: number;\n cachedTokens: number | null;\n cacheWriteTokens: number | null;\n /** `false` when `input` excludes cache tokens (the provider reports them on top). */\n inputIncludesCache: boolean | null;\n};\n\n/** One row of the Runs page (a Panoptic trace, content-free). */\nexport type DevtoolsAiRunRow = {\n traceId: string;\n requestId: string | null;\n sessionId: string | null;\n name: string;\n /** The root span type: `agent`, `workflow`, `supervisor`, … */\n type: string;\n status: string;\n startedAt: string;\n duration: number;\n usage: DevtoolsAiUsageView;\n /** Estimated USD; `null` when the run carried no pricing. */\n cost: number | null;\n models: string[];\n /** `promptName@promptVersion` of the root agent, or `null`. */\n promptKey: string | null;\n toolCalls: number;\n retries: number;\n incomplete: boolean;\n};\n\n/** A group of the Runs page (`groupBy=session|prompt|type`). */\nexport type DevtoolsAiRunGroup = {\n key: string;\n label: string;\n runs: number;\n failed: number;\n estimatedCostUsd: number;\n p95Ms: number | null;\n /** Trace ids of the group, newest first (at most 50). */\n traceIds: string[];\n};\n\n/** `GET api/ai/runs`. */\nexport type DevtoolsAiRunsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n /** Newest first, at most `limit` (default 200). */\n runs: DevtoolsAiRunRow[];\n /** `null` unless `groupBy` was given. */\n groups: DevtoolsAiRunGroup[] | null;\n stats: {\n /** Runs matching the filter (before `limit`). */\n count: number;\n failed: number;\n /** Priced runs only. */\n estimatedCostUsd: number;\n /** Runs that used tokens on a model without pricing (not in `estimatedCostUsd`). */\n unpricedRuns: number;\n p50Ms: number | null;\n p95Ms: number | null;\n };\n /** How many traces the dashboard keeps (`maxRequests`). */\n capacity: number;\n };\n\n/** A distinct system prompt seen in recent agent runs (the Evaluate picker). */\nexport type DevtoolsAiEvaluatePrompt = {\n /** The prompt's hash from the agent trace. */\n hash: string;\n /** Agents that used it, most recent first. */\n agents: string[];\n /** The newest run that carried its text. */\n runId: string;\n lastSeenAt: string;\n /** The first 200 characters. */\n preview: string;\n length: number;\n};\n\n/** `GET api/ai/evaluate`. */\nexport type DevtoolsAiEvaluateView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n /** Whether `panoptic.evaluate` (or `panoptic.dashboard.evaluate`) has a judge model. */\n configured: boolean;\n /** The judge model as `provider/name`; `null` when not configured. */\n judge: string | null;\n /** The configured default grading instructions; `\"\"` when none. */\n instructions: string;\n /** Newest first, at most 50. */\n prompts: DevtoolsAiEvaluatePrompt[];\n };\n\n/** `POST api/ai/evaluate` body: exactly one of `runId` and `systemPrompt`. */\nexport type DevtoolsAiEvaluateRequest = {\n /** An agent run whose system prompt text is kept. */\n runId?: string;\n /** A pasted prompt, 1 to 100,000 characters. */\n systemPrompt?: string;\n /** Overrides the configured instructions for this run; at most 4,000 characters. */\n instructions?: string;\n};\n\n/** `POST api/ai/evaluate` answer. */\nexport type DevtoolsAiEvaluateResult = {\n /** 0 to 1; `null` when the judge returned no score. */\n score: number | null;\n issues: string[];\n /** The judge model as `provider/name`. */\n judge: string;\n durationMs: number;\n};\n"],"mappings":";;;;;;;AA+DA,MAAa,8BAA8B;CACzC;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAK;CAAK;CAAK;CAAM;CAAM;CAAM;CAAO;AAC/D;;;;;;;;;;;AAwYA,MAAa,2BAA2B;CACtC;EAAE,IAAI;EAAY,OAAO;EAAY,YAAY;CAAK;CACtD;EAAE,IAAI;EAAW,OAAO;EAAW,YAAY;CAAK;CACpD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAa,OAAO;EAAa,YAAY;CAAK;CACxD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAK;CAC9C;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAK;CAC9C;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAM;CAC/C;EAAE,IAAI;EAAc,OAAO;EAAW,YAAY;CAAK;CACvD;EAAE,IAAI;EAAM,OAAO;EAAQ,YAAY;CAAM;CAC7C;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAM;CACnD;EAAE,IAAI;EAAa,OAAO;EAAU,YAAY;CAAK;CACrD;EAAE,IAAI;EAAa,OAAO;EAAU,YAAY;CAAK;CACrD;EAAE,IAAI;EAAe,OAAO;EAAY,YAAY;CAAM;CAC1D;EAAE,IAAI;EAAO,OAAO;EAAO,YAAY;CAAM;AAC/C;;AAwMA,MAAa,+BAA6D;CACxE;CACA;CACA;AACF;;;;;;;;AAwFA,MAAa,iCAAiC;CAC5C;CAAK;CAAK;CAAM;CAAM;CAAM;CAAM;CAAM;CAAO;CAAO;CAAO;CAAO;CAAO;CAAO;CAAQ;AAC5F;;AAuNA,MAAa,+BAA+B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
|
|
@@ -122,9 +122,14 @@ function mountProductionDevtools(server, deps) {
|
|
|
122
122
|
lastWarningAt = now;
|
|
123
123
|
deps.warn?.(message);
|
|
124
124
|
};
|
|
125
|
-
const notFound = (request, reply) => {
|
|
125
|
+
const notFound = async (request, reply) => {
|
|
126
126
|
uniformNotFound.add(request);
|
|
127
|
-
|
|
127
|
+
try {
|
|
128
|
+
if (!(await deps.answerUnknownUrl?.(request, reply) ?? false)) reply.callNotFound();
|
|
129
|
+
} catch (error) {
|
|
130
|
+
warn(`The app's answer for an unknown URL failed, the dashboard answers with the plain 404: ${error instanceof Error ? error.message : String(error)}`);
|
|
131
|
+
if (!reply.sent) reply.callNotFound();
|
|
132
|
+
}
|
|
128
133
|
return reply;
|
|
129
134
|
};
|
|
130
135
|
const streamSession = async (request) => {
|
|
@@ -296,6 +301,7 @@ function mountProductionDevtools(server, deps) {
|
|
|
296
301
|
});
|
|
297
302
|
});
|
|
298
303
|
instance.setErrorHandler((error, request, reply) => {
|
|
304
|
+
if (uniformNotFound.has(request)) throw error;
|
|
299
305
|
if (devtoolsRequestContext(request)?.pattern === SHARE_OPEN_PATTERN) return notFound(request, reply);
|
|
300
306
|
if (error instanceof DevtoolsApiError) return reply.code(error.statusCode).send(error.toBody());
|
|
301
307
|
const status = error.statusCode;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mount.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/http/mount.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { listPanelInfos } from \"../../panels\";\nimport { registerAiReportRoutes } from \"../../server/ai-report-routes\";\nimport { registerAiRoutes } from \"../../server/ai-routes\";\nimport { registerShapeExplainRoute } from \"../../server/explain-route\";\nimport { registerInsightsRoutes } from \"../../server/insights-routes\";\nimport { registerLogRoutes } from \"../../server/log-routes\";\nimport { registerMailRoutes } from \"../../server/mail-routes\";\nimport { registerOpenApiRoutes } from \"../../server/openapi-routes\";\nimport { registerPanelRoutes } from \"../../server/panel-routes\";\nimport { registerRequestsRoutes } from \"../../server/requests-routes\";\nimport { registerRouteRoutes } from \"../../server/route-routes\";\nimport { registerStreamRoute } from \"../../server/stream-route\";\nimport type { DevtoolsStreamSession, MountDevtoolsRoutesDeps } from \"../../server/types\";\nimport { registerUiAssets } from \"../../server/ui-assets\";\nimport type { DevtoolsAuthenticated, DevtoolsRequestMeta } from \"../auth/types\";\nimport { DevtoolsApiError, createErrorRef, DEVTOOLS_ERROR_MESSAGES } from \"../errors\";\nimport { createAccessLookup, productionRouteAccess } from \"./access\";\nimport { registerAuthRoutes } from \"./auth-routes\";\nimport { resolveClient } from \"./client\";\nimport { setDevtoolsRequestContext, devtoolsRequestContext } from \"./context\";\nimport { readCookie, sessionCookieName } from \"./cookie\";\nimport { DASHBOARD_CSP, DASHBOARD_HEADERS, DOCS_CSP } from \"./headers\";\nimport { DEVTOOLS_CSRF_HEADER } from \"./constants\";\nimport { createDevtoolsShare } from \"./share\";\nimport { ipMatches } from \"./ip\";\nimport type { DevtoolsRouteAccess, MountProductionDevtoolsDeps } from \"./types\";\n\n/** Open live streams a session may hold, and an instance may serve. */\nconst MAX_STREAMS_PER_SESSION = 3;\nconst MAX_STREAMS_PER_INSTANCE = 50;\n\nconst MAX_USER_AGENT = 200;\n\n/** Methods that never change state. */\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/** The routes of the opt-in API documentation pages (they keep a CSP of their own). */\nconst DOCS_PATTERNS = new Set([\"/docs\", \"/docs/swagger\"]);\n\n/** The grant exchange of a share link: every failure of it answers the uniform 404. */\nconst SHARE_OPEN_PATTERN = \"/api/share/open\";\n\n/** The mail preview's HTML: framed by the dashboard, with a policy of its own. */\nconst MAIL_HTML_PATTERN = \"/api/mails/:id/html\";\n\n/** Which tab a route belongs to: a route of a tab that is off answers the uniform 404. */\nconst TAB_OF_ROUTE: readonly (readonly [prefix: string, tab: string])[] = [\n [\"/api/resources\", \"resources\"],\n [\"/api/queries\", \"queries\"],\n [\"/api/routes/stats\", \"routes\"],\n [\"/api/routes\", \"routes\"],\n [\"/api/health\", \"health\"],\n [\"/api/errors\", \"errors\"],\n [\"/api/jobs\", \"jobs\"],\n [\"/api/logs\", \"logs\"],\n [\"/api/requests\", \"requests\"],\n [\"/api/mails\", \"mail\"],\n [\"/api/ai/agent-runs\", \"agents\"],\n [\"/api/ai/reports\", \"ai-reports\"],\n [\"/api/ai/models\", \"ai-models\"],\n [\"/api/ai/errors\", \"ai-errors\"],\n [\"/api/ai/evaluate\", \"ai-evaluate\"],\n [\"/api/ai\", \"ai\"],\n [\"/api/openapi.json\", \"api\"],\n [\"/api/postman.json\", \"api\"],\n [\"/docs\", \"api\"],\n];\n\n/** The tabs the AI report routes serve; the routes register when any of them is on. */\nconst AI_REPORT_TABS = [\"ai-reports\", \"ai-models\", \"ai-errors\", \"ai-evaluate\"] as const;\n\nfunction tabOf(pattern: string): string | undefined {\n return TAB_OF_ROUTE.find(\n ([prefix]) => pattern === prefix || pattern.startsWith(`${prefix}/`),\n )?.[1];\n}\n\nfunction tokenHash(token: string): string {\n return createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\n/** Requests that were answered with the uniform 404: they get none of the dashboard's headers. */\nconst uniformNotFound = new WeakSet<FastifyRequest>();\n\n/**\n * The origin the browser must send for an unsafe request: `production.origin`,\n * else the scheme and host the request was addressed to.\n */\nfunction originAllowed(request: FastifyRequest, expected: string): boolean {\n const origin = request.headers.origin;\n const site = request.headers[\"sec-fetch-site\"];\n\n if (site !== undefined && site !== \"same-origin\") return false;\n\n if (origin !== undefined) return origin.toLowerCase() === expected.toLowerCase();\n\n // No Origin header: a same-origin fetch from an older browser. Accept it only with the fetch metadata that proves it.\n return site === \"same-origin\";\n}\n\nfunction hasBody(request: FastifyRequest): boolean {\n const length = request.headers[\"content-length\"];\n\n return (\n (length !== undefined && length !== \"0\") || request.headers[\"transfer-encoding\"] !== undefined\n );\n}\n\nfunction isJson(request: FastifyRequest): boolean {\n return /^application\\/json\\s*(;|$)/i.test(request.headers[\"content-type\"] ?? \"\");\n}\n\nfunction sessionAccessOk(\n access: Exclude<DevtoolsRouteAccess, { type: \"public\" }>,\n stage: string,\n): boolean {\n if (stage === \"active\") return true;\n\n return access.type === \"pending\" && (access.stages as readonly string[]).includes(stage);\n}\n\n/**\n * Mounts the production monitor under `production.path` in one encapsulated\n * Fastify context: the gate (uniform 404, HTTPS, allowed IPs, open state),\n * session and role checks from the access table, CSRF and origin checks,\n * security headers and CORS stripping, the auth/account/admin routes, and\n * the shared data routes of the enabled tabs.\n */\nexport function mountProductionDevtools(\n server: FastifyInstance,\n deps: MountProductionDevtoolsDeps,\n): void {\n const { production, auth, state, store } = deps;\n const prefix = production.path;\n const cookieName = sessionCookieName(production.requireHttps);\n const enabledTabs = new Set(deps.builtInPanels);\n const share = production.share.enabled ? createDevtoolsShare(deps) : null;\n const lookup = createAccessLookup(\n productionRouteAccess(\n deps.panels.map((panel) => panel.id),\n { share: share !== null },\n ),\n );\n const streamsPerSession = new Map<string, number>();\n let streamsInstance = 0;\n let lastWarningAt = 0;\n\n const warn = (message: string): void => {\n // At most one line a minute: a database outage must not flood the log.\n const now = Date.now();\n\n if (now - lastWarningAt < 60_000) return;\n\n lastWarningAt = now;\n deps.warn?.(message);\n };\n\n const notFound = (request: FastifyRequest, reply: FastifyReply): FastifyReply => {\n uniformNotFound.add(request);\n\n // The app's own not-found handler answers, so the reply is the one any unknown URL gets.\n reply.callNotFound();\n\n // Returning the reply is what stops an async hook's lifecycle.\n return reply;\n };\n\n const streamSession = async (request: FastifyRequest): Promise<DevtoolsStreamSession> => {\n const authenticated = devtoolsRequestContext(request)?.authenticated;\n\n if (!authenticated) throw new Error(\"A dashboard stream was opened without a session.\");\n\n const sessionId = authenticated.session.id;\n const token = readCookie(request.headers.cookie, cookieName);\n const open = streamsPerSession.get(sessionId) ?? 0;\n\n if (open >= MAX_STREAMS_PER_SESSION || streamsInstance >= MAX_STREAMS_PER_INSTANCE) {\n throw new DevtoolsApiError(\"stream.too-many\");\n }\n\n streamsPerSession.set(sessionId, open + 1);\n streamsInstance += 1;\n\n let released = false;\n\n return {\n role: authenticated.account.role,\n logLevels: production.logLevels,\n headers: DASHBOARD_HEADERS,\n // Reads the session without touching `lastSeenAt`: a stream left open must not keep the session alive.\n async revalidate() {\n if (token === undefined || !(await state.isOpen())) return false;\n\n const session = await store.sessions.findByTokenHash(tokenHash(token));\n const now = Date.now();\n\n if (\n session === null ||\n session.stage !== \"active\" ||\n now >= session.expiresAt ||\n now - session.lastSeenAt >= production.session.idleMinutes * 60_000\n ) {\n return false;\n }\n\n return (await store.accounts.findById(session.accountId)) !== null;\n },\n release() {\n if (released) return;\n\n released = true;\n streamsInstance -= 1;\n\n const left = (streamsPerSession.get(sessionId) ?? 1) - 1;\n\n if (left <= 0) streamsPerSession.delete(sessionId);\n else streamsPerSession.set(sessionId, left);\n },\n };\n };\n\n // The route deps the shared route files read: the development deps, completed.\n const routes: MountDevtoolsRoutesDeps = {\n ...deps.routes,\n mode: \"production\",\n isDevelopment: () => false,\n instance: deps.instance,\n insights: deps.insights,\n collector: deps.routes.collector ?? deps.capture.collector,\n requests: deps.routes.requests ?? deps.capture.requests,\n explainShape: deps.routes.explainShape ?? ((shapeId) => deps.capture.explain(shapeId)),\n builtInPanels: deps.builtInPanels,\n streamSession,\n };\n\n server.register(\n async (instance) => {\n // ---- The gate -------------------------------------------------------\n instance.addHook(\"onRequest\", async (request, reply) => {\n let open: boolean;\n\n try {\n open = await state.isOpen();\n } catch (error) {\n // Fail closed: when the state cannot be read the dashboard does not answer.\n warn(\n `The devtools dashboard state could not be read and the dashboard is closed: ${error instanceof Error ? error.message : String(error)}`,\n );\n open = false;\n }\n\n if (!open) return notFound(request, reply);\n\n const client = resolveClient(request, production.trustedProxies);\n\n if (production.requireHttps && client.proto !== \"https\") return notFound(request, reply);\n\n if (production.allowedIps.length > 0 && !ipMatches(client.ip, production.allowedIps)) {\n return notFound(request, reply);\n }\n\n const userAgent = request.headers[\"user-agent\"];\n const expectedOrigin = production.origin ?? `${client.proto}://${client.host}`;\n const meta: DevtoolsRequestMeta = {\n ip: client.ip,\n userAgent: typeof userAgent === \"string\" ? userAgent.slice(0, MAX_USER_AGENT) : null,\n origin: expectedOrigin,\n hostname: client.hostname,\n };\n\n const routeUrl = request.routeOptions.url ?? \"\";\n const relative = routeUrl.startsWith(prefix) ? routeUrl.slice(prefix.length) : routeUrl;\n // The shell is registered once for both `<path>` and `<path>/`.\n const pattern = relative === \"\" ? \"/\" : relative;\n const method = request.method;\n\n // The bare path (no trailing slash) redirects to the shell's address. The\n // address as sent: core's server drops a trailing slash before routing,\n // so the rewritten URL of `<path>/` is the bare path too.\n const sent = request.originalUrl ?? request.raw.url ?? \"\";\n\n if (sent.split(\"?\")[0] === prefix) {\n setDevtoolsRequestContext(request, {\n client,\n meta,\n rule: undefined,\n pattern,\n authenticated: null,\n });\n\n if (method !== \"GET\" && method !== \"HEAD\") return notFound(request, reply);\n\n const search = sent.includes(\"?\") ? `?${sent.split(\"?\").slice(1).join(\"?\")}` : \"\";\n\n return reply.redirect(`${prefix}/${search}`, 308);\n }\n\n const tab = tabOf(pattern);\n\n if (tab !== undefined && !enabledTabs.has(tab)) return notFound(request, reply);\n\n const rule = lookup(method, pattern);\n const access: DevtoolsRouteAccess = rule?.access ?? { type: \"admin\" };\n let authenticated: DevtoolsAuthenticated | null = null;\n\n // A share link has no account: its cookie grants one panel's shared view and nothing else.\n if (access.type === \"share\") {\n const grant = share ? await share.authorize(request, meta) : null;\n\n if (grant === null) return notFound(request, reply);\n\n setDevtoolsRequestContext(request, {\n client,\n meta,\n rule,\n pattern,\n authenticated: null,\n share: grant,\n });\n\n return;\n }\n\n if (access.type !== \"public\") {\n try {\n authenticated = await auth.authenticate(readCookie(request.headers.cookie, cookieName));\n } catch (error) {\n warn(\n `The devtools session could not be checked and the request was refused: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return notFound(request, reply);\n }\n\n if (authenticated === null || !sessionAccessOk(access, authenticated.stage)) {\n return notFound(request, reply);\n }\n\n if (access.type === \"admin\" && authenticated.account.role !== \"admin\") {\n setDevtoolsRequestContext(request, { client, meta, rule, pattern, authenticated });\n throw new DevtoolsApiError(\"role.forbidden\");\n }\n }\n\n setDevtoolsRequestContext(request, { client, meta, rule, pattern, authenticated });\n\n if (SAFE_METHODS.has(method)) return;\n\n if (!originAllowed(request, expectedOrigin)) {\n if (authenticated === null) return notFound(request, reply);\n\n throw new DevtoolsApiError(\"csrf.invalid\");\n }\n\n if (hasBody(request) && !isJson(request)) {\n if (pattern === SHARE_OPEN_PATTERN) return notFound(request, reply);\n\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n if (authenticated !== null) {\n const header = request.headers[DEVTOOLS_CSRF_HEADER];\n\n if (!auth.verifyCsrf(authenticated, Array.isArray(header) ? header[0] : header)) {\n throw new DevtoolsApiError(\"csrf.invalid\");\n }\n }\n });\n\n // ---- Headers --------------------------------------------------------\n instance.addHook(\"onSend\", async (request, reply, payload) => {\n // The uniform 404 must look like any other 404 of the app.\n if (uniformNotFound.has(request)) return payload;\n\n for (const name of Object.keys(reply.getHeaders())) {\n if (name.startsWith(\"access-control-\")) reply.removeHeader(name);\n }\n\n reply.headers(DASHBOARD_HEADERS);\n\n const pattern = devtoolsRequestContext(request)?.pattern ?? \"\";\n\n // The mail preview is the one page the dashboard frames, from its own origin, and it sends its own policy.\n if (pattern === MAIL_HTML_PATTERN) {\n reply.header(\"X-Frame-Options\", \"SAMEORIGIN\");\n\n return payload;\n }\n\n // The API docs pages are shown in a frame by the dashboard's API tab.\n if (DOCS_PATTERNS.has(pattern)) reply.header(\"X-Frame-Options\", \"SAMEORIGIN\");\n\n // Always the dashboard's policy: the app's own (core's security headers set one on every response) is not\n // written for this page and must not replace it.\n if (String(reply.getHeader(\"content-type\") ?? \"\").startsWith(\"text/html\")) {\n reply.header(\n \"Content-Security-Policy\",\n DOCS_PATTERNS.has(pattern) ? DOCS_CSP : DASHBOARD_CSP,\n );\n }\n\n return payload;\n });\n\n // ---- Audit ----------------------------------------------------------\n instance.addHook(\"onResponse\", async (request, reply) => {\n const context = devtoolsRequestContext(request);\n const type = context?.rule?.audit;\n\n if (!context || !type || reply.statusCode < 200 || reply.statusCode > 299) return;\n\n const params = (request.params ?? {}) as Record<string, string | undefined>;\n const detail: Record<string, string | number | boolean | null> =\n type === \"explain.run\"\n ? { shapeId: params.shapeId ?? null }\n : type === \"panel.action\"\n ? {\n panel: context.pattern.split(\"/\")[2] ?? null,\n method: request.method,\n route: context.pattern,\n }\n : {};\n\n await auth.audit(type, { auth: context.authenticated, meta: context.meta, detail });\n });\n\n // ---- Errors ---------------------------------------------------------\n instance.setErrorHandler(\n (error: Error & { statusCode?: number; code?: string }, request, reply) => {\n // A malformed grant exchange (bad JSON, too large) answers like any unknown URL.\n if (devtoolsRequestContext(request)?.pattern === SHARE_OPEN_PATTERN) {\n return notFound(request, reply);\n }\n\n if (error instanceof DevtoolsApiError) {\n return reply.code(error.statusCode).send(error.toBody());\n }\n\n const status = error.statusCode;\n\n // The request itself was wrong (bad JSON, too large): say so in the dashboard's own shape.\n if (status !== undefined && status >= 400 && status < 500) {\n return reply\n .code(status)\n .send(\n error.code?.startsWith(\"FST_ERR_\")\n ? new DevtoolsApiError(\"input.invalid\").toBody()\n : { error: error.message },\n );\n }\n\n const ref = createErrorRef();\n\n // Never rate limited: the reference the browser shows must always be findable in the log. The route is\n // written relative to the dashboard path, which never reaches the log.\n deps.warn?.(\n `Devtools dashboard error ${ref} on ${request.method} ${devtoolsRequestContext(request)?.pattern ?? \"(dashboard route)\"}: ${error.message}`,\n );\n request.log.error({ ref, err: error }, \"devtools dashboard error\");\n\n return reply.code(500).send({\n error: DEVTOOLS_ERROR_MESSAGES[\"server.error\"],\n code: \"server.error\",\n ref,\n });\n },\n );\n\n // ---- Routes ---------------------------------------------------------\n registerUiAssets(instance, { notFound });\n registerAuthRoutes(instance, deps);\n\n instance.get(\"/api/panels\", async () => listPanelInfos(deps.panels, deps.builtInPanels));\n\n registerRequestsRoutes(instance, routes);\n registerRouteRoutes(instance, routes);\n registerInsightsRoutes(instance, routes);\n registerLogRoutes(instance, routes);\n registerShapeExplainRoute(instance, routes);\n registerPanelRoutes(instance, deps.panels, { notFound });\n\n share?.register(instance, notFound);\n\n if (enabledTabs.has(\"mail\")) registerMailRoutes(instance, routes);\n if (enabledTabs.has(\"ai\") || enabledTabs.has(\"agents\")) registerAiRoutes(instance, routes);\n if (AI_REPORT_TABS.some((tab) => enabledTabs.has(tab)))\n registerAiReportRoutes(instance, routes);\n if (enabledTabs.has(\"api\")) registerOpenApiRoutes(instance, routes);\n\n registerStreamRoute(instance, routes);\n },\n { prefix },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,0BAA0B;AAChC,MAAM,2BAA2B;AAEjC,MAAM,iBAAiB;;AAGvB,MAAM,+BAAe,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;;AAGvD,MAAM,gCAAgB,IAAI,IAAI,CAAC,SAAS,eAAe,CAAC;;AAGxD,MAAM,qBAAqB;;AAG3B,MAAM,oBAAoB;;AAG1B,MAAM,eAAoE;CACxE,CAAC,kBAAkB,WAAW;CAC9B,CAAC,gBAAgB,SAAS;CAC1B,CAAC,qBAAqB,QAAQ;CAC9B,CAAC,eAAe,QAAQ;CACxB,CAAC,eAAe,QAAQ;CACxB,CAAC,eAAe,QAAQ;CACxB,CAAC,aAAa,MAAM;CACpB,CAAC,aAAa,MAAM;CACpB,CAAC,iBAAiB,UAAU;CAC5B,CAAC,cAAc,MAAM;CACrB,CAAC,sBAAsB,QAAQ;CAC/B,CAAC,mBAAmB,YAAY;CAChC,CAAC,kBAAkB,WAAW;CAC9B,CAAC,kBAAkB,WAAW;CAC9B,CAAC,oBAAoB,aAAa;CAClC,CAAC,WAAW,IAAI;CAChB,CAAC,qBAAqB,KAAK;CAC3B,CAAC,qBAAqB,KAAK;CAC3B,CAAC,SAAS,KAAK;AACjB;;AAGA,MAAM,iBAAiB;CAAC;CAAc;CAAa;CAAa;AAAa;AAE7E,SAAS,MAAM,SAAqC;CAClD,OAAO,aAAa,MACjB,CAAC,YAAY,YAAY,UAAU,QAAQ,WAAW,GAAG,OAAO,EAAE,CACrE,CAAC,GAAG;AACN;AAEA,SAAS,UAAU,OAAuB;CACxC,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO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AAK,aAAa,CAAC;EAEvF,uBAAuB,UAAU,MAAM;EACvC,oBAAoB,UAAU,MAAM;EACpC,uBAAuB,UAAU,MAAM;EACvC,kBAAkB,UAAU,MAAM;EAClC,0BAA0B,UAAU,MAAM;EAC1C,oBAAoB,UAAU,KAAK,QAAQ,EAAE,SAAS,CAAC;EAEvD,OAAO,SAAS,UAAU,QAAQ;EAElC,IAAI,YAAY,IAAI,MAAM,GAAG,mBAAmB,UAAU,MAAM;EAChE,IAAI,YAAY,IAAI,IAAI,KAAK,YAAY,IAAI,QAAQ,GAAG,iBAAiB,UAAU,MAAM;EACzF,IAAI,eAAe,MAAM,QAAQ,YAAY,IAAI,GAAG,CAAC,GACnD,uBAAuB,UAAU,MAAM;EACzC,IAAI,YAAY,IAAI,KAAK,GAAG,sBAAsB,UAAU,MAAM;EAElE,oBAAoB,UAAU,MAAM;CACtC,GACA,EAAE,OAAO,CACX;AACF"}
|
|
1
|
+
{"version":3,"file":"mount.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/http/mount.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { listPanelInfos } from \"../../panels\";\nimport { registerAiReportRoutes } from \"../../server/ai-report-routes\";\nimport { registerAiRoutes } from \"../../server/ai-routes\";\nimport { registerShapeExplainRoute } from \"../../server/explain-route\";\nimport { registerInsightsRoutes } from \"../../server/insights-routes\";\nimport { registerLogRoutes } from \"../../server/log-routes\";\nimport { registerMailRoutes } from \"../../server/mail-routes\";\nimport { registerOpenApiRoutes } from \"../../server/openapi-routes\";\nimport { registerPanelRoutes } from \"../../server/panel-routes\";\nimport { registerRequestsRoutes } from \"../../server/requests-routes\";\nimport { registerRouteRoutes } from \"../../server/route-routes\";\nimport { registerStreamRoute } from \"../../server/stream-route\";\nimport type { DevtoolsStreamSession, MountDevtoolsRoutesDeps } from \"../../server/types\";\nimport { registerUiAssets } from \"../../server/ui-assets\";\nimport type { DevtoolsAuthenticated, DevtoolsRequestMeta } from \"../auth/types\";\nimport { DevtoolsApiError, createErrorRef, DEVTOOLS_ERROR_MESSAGES } from \"../errors\";\nimport { createAccessLookup, productionRouteAccess } from \"./access\";\nimport { registerAuthRoutes } from \"./auth-routes\";\nimport { resolveClient } from \"./client\";\nimport { setDevtoolsRequestContext, devtoolsRequestContext } from \"./context\";\nimport { readCookie, sessionCookieName } from \"./cookie\";\nimport { DASHBOARD_CSP, DASHBOARD_HEADERS, DOCS_CSP } from \"./headers\";\nimport { DEVTOOLS_CSRF_HEADER } from \"./constants\";\nimport { createDevtoolsShare } from \"./share\";\nimport { ipMatches } from \"./ip\";\nimport type { DevtoolsRouteAccess, MountProductionDevtoolsDeps } from \"./types\";\n\n/** Open live streams a session may hold, and an instance may serve. */\nconst MAX_STREAMS_PER_SESSION = 3;\nconst MAX_STREAMS_PER_INSTANCE = 50;\n\nconst MAX_USER_AGENT = 200;\n\n/** Methods that never change state. */\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/** The routes of the opt-in API documentation pages (they keep a CSP of their own). */\nconst DOCS_PATTERNS = new Set([\"/docs\", \"/docs/swagger\"]);\n\n/** The grant exchange of a share link: every failure of it answers the uniform 404. */\nconst SHARE_OPEN_PATTERN = \"/api/share/open\";\n\n/** The mail preview's HTML: framed by the dashboard, with a policy of its own. */\nconst MAIL_HTML_PATTERN = \"/api/mails/:id/html\";\n\n/** Which tab a route belongs to: a route of a tab that is off answers the uniform 404. */\nconst TAB_OF_ROUTE: readonly (readonly [prefix: string, tab: string])[] = [\n [\"/api/resources\", \"resources\"],\n [\"/api/queries\", \"queries\"],\n [\"/api/routes/stats\", \"routes\"],\n [\"/api/routes\", \"routes\"],\n [\"/api/health\", \"health\"],\n [\"/api/errors\", \"errors\"],\n [\"/api/jobs\", \"jobs\"],\n [\"/api/logs\", \"logs\"],\n [\"/api/requests\", \"requests\"],\n [\"/api/mails\", \"mail\"],\n [\"/api/ai/agent-runs\", \"agents\"],\n [\"/api/ai/reports\", \"ai-reports\"],\n [\"/api/ai/models\", \"ai-models\"],\n [\"/api/ai/errors\", \"ai-errors\"],\n [\"/api/ai/evaluate\", \"ai-evaluate\"],\n [\"/api/ai\", \"ai\"],\n [\"/api/openapi.json\", \"api\"],\n [\"/api/postman.json\", \"api\"],\n [\"/docs\", \"api\"],\n];\n\n/** The tabs the AI report routes serve; the routes register when any of them is on. */\nconst AI_REPORT_TABS = [\"ai-reports\", \"ai-models\", \"ai-errors\", \"ai-evaluate\"] as const;\n\nfunction tabOf(pattern: string): string | undefined {\n return TAB_OF_ROUTE.find(\n ([prefix]) => pattern === prefix || pattern.startsWith(`${prefix}/`),\n )?.[1];\n}\n\nfunction tokenHash(token: string): string {\n return createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\n/** Requests that were answered with the uniform 404: they get none of the dashboard's headers. */\nconst uniformNotFound = new WeakSet<FastifyRequest>();\n\n/**\n * The origin the browser must send for an unsafe request: `production.origin`,\n * else the scheme and host the request was addressed to.\n */\nfunction originAllowed(request: FastifyRequest, expected: string): boolean {\n const origin = request.headers.origin;\n const site = request.headers[\"sec-fetch-site\"];\n\n if (site !== undefined && site !== \"same-origin\") return false;\n\n if (origin !== undefined) return origin.toLowerCase() === expected.toLowerCase();\n\n // No Origin header: a same-origin fetch from an older browser. Accept it only with the fetch metadata that proves it.\n return site === \"same-origin\";\n}\n\nfunction hasBody(request: FastifyRequest): boolean {\n const length = request.headers[\"content-length\"];\n\n return (\n (length !== undefined && length !== \"0\") || request.headers[\"transfer-encoding\"] !== undefined\n );\n}\n\nfunction isJson(request: FastifyRequest): boolean {\n return /^application\\/json\\s*(;|$)/i.test(request.headers[\"content-type\"] ?? \"\");\n}\n\nfunction sessionAccessOk(\n access: Exclude<DevtoolsRouteAccess, { type: \"public\" }>,\n stage: string,\n): boolean {\n if (stage === \"active\") return true;\n\n return access.type === \"pending\" && (access.stages as readonly string[]).includes(stage);\n}\n\n/**\n * Mounts the production monitor under `production.path` in one encapsulated\n * Fastify context: the gate (uniform 404, HTTPS, allowed IPs, open state),\n * session and role checks from the access table, CSRF and origin checks,\n * security headers and CORS stripping, the auth/account/admin routes, and\n * the shared data routes of the enabled tabs.\n */\nexport function mountProductionDevtools(\n server: FastifyInstance,\n deps: MountProductionDevtoolsDeps,\n): void {\n const { production, auth, state, store } = deps;\n const prefix = production.path;\n const cookieName = sessionCookieName(production.requireHttps);\n const enabledTabs = new Set(deps.builtInPanels);\n const share = production.share.enabled ? createDevtoolsShare(deps) : null;\n const lookup = createAccessLookup(\n productionRouteAccess(\n deps.panels.map((panel) => panel.id),\n { share: share !== null },\n ),\n );\n const streamsPerSession = new Map<string, number>();\n let streamsInstance = 0;\n let lastWarningAt = 0;\n\n const warn = (message: string): void => {\n // At most one line a minute: a database outage must not flood the log.\n const now = Date.now();\n\n if (now - lastWarningAt < 60_000) return;\n\n lastWarningAt = now;\n deps.warn?.(message);\n };\n\n const notFound = async (request: FastifyRequest, reply: FastifyReply): Promise<FastifyReply> => {\n uniformNotFound.add(request);\n\n // The app's own answer for an unknown URL (a web site's catch-all route);\n // without one, Fastify's not-found handler gives the same 404 any URL gets.\n try {\n if (!((await deps.answerUnknownUrl?.(request, reply)) ?? false)) reply.callNotFound();\n } catch (error) {\n warn(\n `The app's answer for an unknown URL failed, the dashboard answers with the plain 404: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n if (!reply.sent) reply.callNotFound();\n }\n\n // Returning the reply is what stops an async hook's lifecycle.\n return reply;\n };\n\n const streamSession = async (request: FastifyRequest): Promise<DevtoolsStreamSession> => {\n const authenticated = devtoolsRequestContext(request)?.authenticated;\n\n if (!authenticated) throw new Error(\"A dashboard stream was opened without a session.\");\n\n const sessionId = authenticated.session.id;\n const token = readCookie(request.headers.cookie, cookieName);\n const open = streamsPerSession.get(sessionId) ?? 0;\n\n if (open >= MAX_STREAMS_PER_SESSION || streamsInstance >= MAX_STREAMS_PER_INSTANCE) {\n throw new DevtoolsApiError(\"stream.too-many\");\n }\n\n streamsPerSession.set(sessionId, open + 1);\n streamsInstance += 1;\n\n let released = false;\n\n return {\n role: authenticated.account.role,\n logLevels: production.logLevels,\n headers: DASHBOARD_HEADERS,\n // Reads the session without touching `lastSeenAt`: a stream left open must not keep the session alive.\n async revalidate() {\n if (token === undefined || !(await state.isOpen())) return false;\n\n const session = await store.sessions.findByTokenHash(tokenHash(token));\n const now = Date.now();\n\n if (\n session === null ||\n session.stage !== \"active\" ||\n now >= session.expiresAt ||\n now - session.lastSeenAt >= production.session.idleMinutes * 60_000\n ) {\n return false;\n }\n\n return (await store.accounts.findById(session.accountId)) !== null;\n },\n release() {\n if (released) return;\n\n released = true;\n streamsInstance -= 1;\n\n const left = (streamsPerSession.get(sessionId) ?? 1) - 1;\n\n if (left <= 0) streamsPerSession.delete(sessionId);\n else streamsPerSession.set(sessionId, left);\n },\n };\n };\n\n // The route deps the shared route files read: the development deps, completed.\n const routes: MountDevtoolsRoutesDeps = {\n ...deps.routes,\n mode: \"production\",\n isDevelopment: () => false,\n instance: deps.instance,\n insights: deps.insights,\n collector: deps.routes.collector ?? deps.capture.collector,\n requests: deps.routes.requests ?? deps.capture.requests,\n explainShape: deps.routes.explainShape ?? ((shapeId) => deps.capture.explain(shapeId)),\n builtInPanels: deps.builtInPanels,\n streamSession,\n };\n\n server.register(\n async (instance) => {\n // ---- The gate -------------------------------------------------------\n instance.addHook(\"onRequest\", async (request, reply) => {\n let open: boolean;\n\n try {\n open = await state.isOpen();\n } catch (error) {\n // Fail closed: when the state cannot be read the dashboard does not answer.\n warn(\n `The devtools dashboard state could not be read and the dashboard is closed: ${error instanceof Error ? error.message : String(error)}`,\n );\n open = false;\n }\n\n if (!open) return notFound(request, reply);\n\n const client = resolveClient(request, production.trustedProxies);\n\n if (production.requireHttps && client.proto !== \"https\") return notFound(request, reply);\n\n if (production.allowedIps.length > 0 && !ipMatches(client.ip, production.allowedIps)) {\n return notFound(request, reply);\n }\n\n const userAgent = request.headers[\"user-agent\"];\n const expectedOrigin = production.origin ?? `${client.proto}://${client.host}`;\n const meta: DevtoolsRequestMeta = {\n ip: client.ip,\n userAgent: typeof userAgent === \"string\" ? userAgent.slice(0, MAX_USER_AGENT) : null,\n origin: expectedOrigin,\n hostname: client.hostname,\n };\n\n const routeUrl = request.routeOptions.url ?? \"\";\n const relative = routeUrl.startsWith(prefix) ? routeUrl.slice(prefix.length) : routeUrl;\n // The shell is registered once for both `<path>` and `<path>/`.\n const pattern = relative === \"\" ? \"/\" : relative;\n const method = request.method;\n\n // The bare path (no trailing slash) redirects to the shell's address. The\n // address as sent: core's server drops a trailing slash before routing,\n // so the rewritten URL of `<path>/` is the bare path too.\n const sent = request.originalUrl ?? request.raw.url ?? \"\";\n\n if (sent.split(\"?\")[0] === prefix) {\n setDevtoolsRequestContext(request, {\n client,\n meta,\n rule: undefined,\n pattern,\n authenticated: null,\n });\n\n if (method !== \"GET\" && method !== \"HEAD\") return notFound(request, reply);\n\n const search = sent.includes(\"?\") ? `?${sent.split(\"?\").slice(1).join(\"?\")}` : \"\";\n\n return reply.redirect(`${prefix}/${search}`, 308);\n }\n\n const tab = tabOf(pattern);\n\n if (tab !== undefined && !enabledTabs.has(tab)) return notFound(request, reply);\n\n const rule = lookup(method, pattern);\n const access: DevtoolsRouteAccess = rule?.access ?? { type: \"admin\" };\n let authenticated: DevtoolsAuthenticated | null = null;\n\n // A share link has no account: its cookie grants one panel's shared view and nothing else.\n if (access.type === \"share\") {\n const grant = share ? await share.authorize(request, meta) : null;\n\n if (grant === null) return notFound(request, reply);\n\n setDevtoolsRequestContext(request, {\n client,\n meta,\n rule,\n pattern,\n authenticated: null,\n share: grant,\n });\n\n return;\n }\n\n if (access.type !== \"public\") {\n try {\n authenticated = await auth.authenticate(readCookie(request.headers.cookie, cookieName));\n } catch (error) {\n warn(\n `The devtools session could not be checked and the request was refused: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return notFound(request, reply);\n }\n\n if (authenticated === null || !sessionAccessOk(access, authenticated.stage)) {\n return notFound(request, reply);\n }\n\n if (access.type === \"admin\" && authenticated.account.role !== \"admin\") {\n setDevtoolsRequestContext(request, { client, meta, rule, pattern, authenticated });\n throw new DevtoolsApiError(\"role.forbidden\");\n }\n }\n\n setDevtoolsRequestContext(request, { client, meta, rule, pattern, authenticated });\n\n if (SAFE_METHODS.has(method)) return;\n\n if (!originAllowed(request, expectedOrigin)) {\n if (authenticated === null) return notFound(request, reply);\n\n throw new DevtoolsApiError(\"csrf.invalid\");\n }\n\n if (hasBody(request) && !isJson(request)) {\n if (pattern === SHARE_OPEN_PATTERN) return notFound(request, reply);\n\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n if (authenticated !== null) {\n const header = request.headers[DEVTOOLS_CSRF_HEADER];\n\n if (!auth.verifyCsrf(authenticated, Array.isArray(header) ? header[0] : header)) {\n throw new DevtoolsApiError(\"csrf.invalid\");\n }\n }\n });\n\n // ---- Headers --------------------------------------------------------\n instance.addHook(\"onSend\", async (request, reply, payload) => {\n // The uniform 404 must look like any other 404 of the app.\n if (uniformNotFound.has(request)) return payload;\n\n for (const name of Object.keys(reply.getHeaders())) {\n if (name.startsWith(\"access-control-\")) reply.removeHeader(name);\n }\n\n reply.headers(DASHBOARD_HEADERS);\n\n const pattern = devtoolsRequestContext(request)?.pattern ?? \"\";\n\n // The mail preview is the one page the dashboard frames, from its own origin, and it sends its own policy.\n if (pattern === MAIL_HTML_PATTERN) {\n reply.header(\"X-Frame-Options\", \"SAMEORIGIN\");\n\n return payload;\n }\n\n // The API docs pages are shown in a frame by the dashboard's API tab.\n if (DOCS_PATTERNS.has(pattern)) reply.header(\"X-Frame-Options\", \"SAMEORIGIN\");\n\n // Always the dashboard's policy: the app's own (core's security headers set one on every response) is not\n // written for this page and must not replace it.\n if (String(reply.getHeader(\"content-type\") ?? \"\").startsWith(\"text/html\")) {\n reply.header(\n \"Content-Security-Policy\",\n DOCS_PATTERNS.has(pattern) ? DOCS_CSP : DASHBOARD_CSP,\n );\n }\n\n return payload;\n });\n\n // ---- Audit ----------------------------------------------------------\n instance.addHook(\"onResponse\", async (request, reply) => {\n const context = devtoolsRequestContext(request);\n const type = context?.rule?.audit;\n\n if (!context || !type || reply.statusCode < 200 || reply.statusCode > 299) return;\n\n const params = (request.params ?? {}) as Record<string, string | undefined>;\n const detail: Record<string, string | number | boolean | null> =\n type === \"explain.run\"\n ? { shapeId: params.shapeId ?? null }\n : type === \"panel.action\"\n ? {\n panel: context.pattern.split(\"/\")[2] ?? null,\n method: request.method,\n route: context.pattern,\n }\n : {};\n\n await auth.audit(type, { auth: context.authenticated, meta: context.meta, detail });\n });\n\n // ---- Errors ---------------------------------------------------------\n instance.setErrorHandler(\n (error: Error & { statusCode?: number; code?: string }, request, reply) => {\n // A request answered like an unknown URL (a rate-limit 429, a failing catch-all) gets the app's own error\n // answer: thrown on, Fastify hands it to the parent error handler.\n if (uniformNotFound.has(request)) throw error;\n\n // A malformed grant exchange (bad JSON, too large) answers like any unknown URL.\n if (devtoolsRequestContext(request)?.pattern === SHARE_OPEN_PATTERN) {\n return notFound(request, reply);\n }\n\n if (error instanceof DevtoolsApiError) {\n return reply.code(error.statusCode).send(error.toBody());\n }\n\n const status = error.statusCode;\n\n // The request itself was wrong (bad JSON, too large): say so in the dashboard's own shape.\n if (status !== undefined && status >= 400 && status < 500) {\n return reply\n .code(status)\n .send(\n error.code?.startsWith(\"FST_ERR_\")\n ? new DevtoolsApiError(\"input.invalid\").toBody()\n : { error: error.message },\n );\n }\n\n const ref = createErrorRef();\n\n // Never rate limited: the reference the browser shows must always be findable in the log. The route is\n // written relative to the dashboard path, which never reaches the log.\n deps.warn?.(\n `Devtools dashboard error ${ref} on ${request.method} ${devtoolsRequestContext(request)?.pattern ?? \"(dashboard route)\"}: ${error.message}`,\n );\n request.log.error({ ref, err: error }, \"devtools dashboard error\");\n\n return reply.code(500).send({\n error: DEVTOOLS_ERROR_MESSAGES[\"server.error\"],\n code: \"server.error\",\n ref,\n });\n },\n );\n\n // ---- Routes ---------------------------------------------------------\n registerUiAssets(instance, { notFound });\n registerAuthRoutes(instance, deps);\n\n instance.get(\"/api/panels\", async () => listPanelInfos(deps.panels, deps.builtInPanels));\n\n registerRequestsRoutes(instance, routes);\n registerRouteRoutes(instance, routes);\n registerInsightsRoutes(instance, routes);\n registerLogRoutes(instance, routes);\n registerShapeExplainRoute(instance, routes);\n registerPanelRoutes(instance, deps.panels, { notFound });\n\n share?.register(instance, notFound);\n\n if (enabledTabs.has(\"mail\")) registerMailRoutes(instance, routes);\n if (enabledTabs.has(\"ai\") || enabledTabs.has(\"agents\")) registerAiRoutes(instance, routes);\n if (AI_REPORT_TABS.some((tab) => enabledTabs.has(tab)))\n registerAiReportRoutes(instance, routes);\n if (enabledTabs.has(\"api\")) registerOpenApiRoutes(instance, routes);\n\n registerStreamRoute(instance, routes);\n },\n { prefix },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,0BAA0B;AAChC,MAAM,2BAA2B;AAEjC,MAAM,iBAAiB;;AAGvB,MAAM,+BAAe,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;;AAGvD,MAAM,gCAAgB,IAAI,IAAI,CAAC,SAAS,eAAe,CAAC;;AAGxD,MAAM,qBAAqB;;AAG3B,MAAM,oBAAoB;;AAG1B,MAAM,eAAoE;CACxE,CAAC,kBAAkB,WAAW;CAC9B,CAAC,gBAAgB,SAAS;CAC1B,CAAC,qBAAqB,QAAQ;CAC9B,CAAC,eAAe,QAAQ;CACxB,CAAC,eAAe,QAAQ;CACxB,CAAC,eAAe,QAAQ;CACxB,CAAC,aAAa,MAAM;CACpB,CAAC,aAAa,MAAM;CACpB,CAAC,iBAAiB,UAAU;CAC5B,CAAC,cAAc,MAAM;CACrB,CAAC,sBAAsB,QAAQ;CAC/B,CAAC,mBAAmB,YAAY;CAChC,CAAC,kBAAkB,WAAW;CAC9B,CAAC,kBAAkB,WAAW;CAC9B,C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-
{"version":3,"file":"share.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/http/share.ts"],"sourcesContent":["import type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { panelContentType, type MountedDevtoolsPanel } from \"../../panels\";\nimport { sendPanelFile } from \"../../server/panel-routes\";\nimport { sendFile } from \"../../server/ui-assets\";\nimport type { DevtoolsPanelRequest } from \"../../types\";\nimport { generateToken, hashToken } from \"../auth/helpers\";\nimport type { DevtoolsAuthenticated, DevtoolsRequestMeta } from \"../auth/types\";\nimport {\n DEVTOOLS_FAILURE_AUDIT_TYPES,\n DEVTOOLS_SHARE_LABEL_MAX,\n type DevtoolsCreatedShare,\n type DevtoolsShareList,\n type DevtoolsShareOpenAnswer,\n type DevtoolsShareView,\n} from \"../contracts\";\nimport { DevtoolsApiError } from \"../errors\";\nimport type { DevtoolsShareRecord } from \"../store/types\";\nimport { devtoolsRequestContext } from \"./context\";\nimport { readCookie, shareCookie, shareCookieName } from \"./cookie\";\nimport { rateLimitClient } from \"./ip\";\nimport { createShareSessions, type DevtoolsShareGrant } from \"./share-session\";\nimport type { MountProductionDevtoolsDeps } from \"./types\";\n\nconst DAY_MS = 86_400_000;\nconst MAX_TOKEN = 512;\nconst MAX_PANEL_ID = 64;\n\n/** A failed token is not looked up again for this long once its client is over the limit. */\nconst BLOCK_CACHE_MS = 30_000;\nconst BLOCK_CACHE_SIZE = 1000;\n\n/** A cookie failure is audited at most this often per client (a revoked link in use must not flood the log). */\nconst COOKIE_AUDIT_INTERVAL_MS = 60_000;\n\ntype Notfound = (request: FastifyRequest, reply: FastifyReply) => FastifyReply;\n\n/** The path pattern `pattern` (`/flows/:feature`) matched against `path`, as its params; `null` for no match. */\nexport function matchSharePath(pattern: string, path: string): Record<string, string> | null {\n if (/[\\0\\\\]/.test(path)) return null;\n\n const wanted = pattern.split(\"/\");\n const given = path.split(\"/\");\n\n if (wanted.length !== given.length) return null;\n\n const params: Record<string, string> = {};\n\n for (const [index, part] of wanted.entries()) {\n const actual = given[index];\n\n if (actual === undefined) return null;\n\n if (part.startsWith(\":\")) {\n if (actual === \"\") return null;\n\n params[part.slice(1)] = actual;\n } else if (part !== actual) {\n return null;\n }\n }\n\n return params;\n}\n\nfunction bodyOf(request: FastifyRequest): Record<string, unknown> {\n const body: unknown = request.body;\n\n if (body === null || typeof body !== \"object\" || Array.isArray(body)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return body as Record<string, unknown>;\n}\n\nfunction viewOf(\n record: DevtoolsShareRecord,\n createdBy: string | null,\n at: number,\n): DevtoolsShareView {\n return {\n id: record.id,\n panel: record.panel,\n label: record.label,\n createdBy,\n createdAt: record.createdAt,\n expiresAt: record.expiresAt,\n revokedAt: record.revokedAt,\n lastUsedAt: record.lastUsedAt,\n uses: record.uses,\n status: record.revokedAt !== null ? \"revoked\" : record.expiresAt <= at ? \"expired\" : \"active\",\n };\n}\n\nfunction openAnswer(grant: DevtoolsShareGrant): DevtoolsShareOpenAnswer {\n const { panel, share } = grant;\n\n return {\n panel: panel.id,\n title: panel.title,\n label: share.label,\n expiresAt: share.expiresAt,\n assets: [...(panel.share?.assets ?? [])],\n files: panel.share?.files === true,\n };\n}\n\n/** What `mountProductionDevtools` gets back when sharing is on. */\nexport type DevtoolsShareMount = {\n /** The grant of a request's share cookie, or `null` (the gate then answers the uniform 404). */\n authorize(request: FastifyRequest, meta: DevtoolsRequestMeta): Promise<DevtoolsShareGrant | null>;\n /** Registers the share routes and the admin routes that manage links. */\n register(server: FastifyInstance, notFound: Notfound): void;\n};\n\n/**\n * Read-only share links of the production monitor. An admin creates a link\n * for a panel that declares `share`; the token is shown once and only its\n * SHA-256 is stored. Opening a link exchanges the token for a scoped cookie\n * (`__Secure-warlock-devtools-share`) that reaches only that panel's shared\n * view. Every refusal answers the dashboard's uniform 404, is audited as\n * `share.failed` (which counts toward the per-IP failure limit) and never\n * records the token.\n */\nexport function createDevtoolsShare(\n deps: MountProductionDevtoolsDeps & { now?: () => number },\n): DevtoolsShareMount {\n const { production, store, auth } = deps;\n const now = deps.now ?? (() => Date.now());\n\n if (typeof deps.hmac !== \"function\") {\n throw new Error(\"Share links need deps.hmac (HMAC-SHA256 keyed with encryption.key).\");\n }\n\n const sessions = createShareSessions({\n store,\n panels: deps.panels,\n hmac: deps.hmac,\n now,\n ...(deps.warn ? { warn: deps.warn } : {}),\n });\n const cookieOptions = { path: production.path, secure: production.requireHttps };\n const cookieName = shareCookieName(production.requireHttps);\n const sharePanels = deps.panels.filter((panel) => panel.share !== null);\n const blocked = new Map<string, number>();\n const cookieAudited = new Map<string, number>();\n\n const limits = production.rateLimits;\n const windowMs = limits.windowMinutes * 60_000;\n\n async function overLimit(ip: string): Promise<boolean> {\n const client = rateLimitClient(ip);\n const at = now();\n const until = blocked.get(client);\n\n if (until !== undefined && at < until) return true;\n\n const state = await store.state.read();\n const since = Math.max(at - windowMs, state.failuresResetAt ?? 0);\n const count = await store.audit.count({ types: DEVTOOLS_FAILURE_AUDIT_TYPES, since, ip });\n\n blocked.delete(client);\n\n if (count < limits.ip) return false;\n\n if (blocked.size >= BLOCK_CACHE_SIZE) {\n const oldest = blocked.keys().next();\n\n if (!oldest.done) blocked.delete(oldest.value);\n }\n\n blocked.set(client, at + BLOCK_CACHE_MS);\n\n return true;\n }\n\n /** Writes one `share.failed` entry (never the token). Never throws. */\n async function failed(\n meta: DevtoolsRequestMeta,\n reason: string,\n shareId: string | null,\n ): Promise<void> {\n await auth.audit(\"share.failed\", { meta, detail: { reason, share: shareId } });\n }\n\n /** The cookie check for a share request. */\n async function authorize(\n request: FastifyRequest,\n meta: DevtoolsRequestMeta,\n ): Promise<DevtoolsShareGrant | null> {\n const value = readCookie(request.headers.cookie, cookieName);\n\n if (value === undefined) return null;\n\n let result;\n\n try {\n result = await sessions.verify(value);\n } catch (error) {\n deps.warn?.(\n `A devtools share link could not be checked and the request was refused: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return null;\n }\n\n if (\"grant\" in result) {\n sessions.touch(result.grant.share.id);\n\n return result.grant;\n }\n\n const client = rateLimitClient(meta.ip);\n const last = cookieAudited.get(client);\n\n if (last === undefined || now() - last >= COOKIE_AUDIT_INTERVAL_MS) {\n cookieAudited.delete(client);\n\n if (cookieAudited.size >= BLOCK_CACHE_SIZE) {\n const oldest = cookieAudited.keys().next();\n\n if (!oldest.done) cookieAudited.delete(oldest.value);\n }\n\n cookieAudited.set(client, now());\n\n try {\n if (!(await overLimit(meta.ip))) await failed(meta, result.refused, result.shareId);\n } catch {\n // The refusal stands even when the audit cannot be written.\n }\n }\n\n return null;\n }\n\n function grantOf(request: FastifyRequest): DevtoolsShareGrant {\n const grant = devtoolsRequestContext(request)?.share;\n\n if (!grant) throw new Error(\"A share route ran without its grant.\");\n\n return grant;\n }\n\n function createdByOf(\n accounts: readonly { id: string; email: string }[],\n id: string | null,\n ): string | null {\n return accounts.find((account) => account.id === id)?.email ?? null;\n }\n\n // ---- Admin ----------------------------------------------------------------\n\n async function list(): Promise<DevtoolsShareList> {\n const [records, accounts] = await Promise.all([store.shares.list(), store.accounts.list()]);\n const at = now();\n\n return {\n enabled: true,\n maxDays: production.share.maxDays,\n panels: sharePanels.map((panel) => ({ id: panel.id, title: panel.title })),\n shares: records.map((record) => viewOf(record, createdByOf(accounts, record.createdBy), at)),\n };\n }\n\n async function create(\n authenticated: DevtoolsAuthenticated,\n meta: DevtoolsRequestMeta,\n body: Record<string, unknown>,\n ): Promise<DevtoolsCreatedShare> {\n const panel = body.panel;\n const label = typeof body.label === \"string\" ? body.label.trim() : \"\";\n const days = body.days;\n\n if (\n typeof panel !== \"string\" ||\n panel.length > MAX_PANEL_ID ||\n !sharePanels.some((item) => item.id === panel) ||\n label === \"\" ||\n label.length > DEVTOOLS_SHARE_LABEL_MAX ||\n // eslint-disable-next-line no-control-regex\n /[\\u0000-\\u001f\\u007f]/.test(label) ||\n typeof days !== \"number\" ||\n !Number.isInteger(days) ||\n days < 1 ||\n days > production.share.maxDays\n ) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const token = generateToken();\n const at = now();\n const record = await store.shares.create({\n tokenHash: hashToken(token),\n panel,\n label,\n createdBy: authenticated.account.id,\n createdAt: at,\n expiresAt: at + days * DAY_MS,\n });\n\n sessions.invalidate();\n await auth.audit(\"share.created\", {\n auth: authenticated,\n meta,\n detail: { share: record.id, panel, days },\n });\n\n return {\n share: viewOf(record, authenticated.account.email, at),\n // The token rides in the fragment: it never reaches an access log or a Referer header.\n url: `${meta.origin}${production.path}/#/share/${token}`,\n };\n }\n\n // ---- Registration -----------------------------------------------------------\n\n function register(server: FastifyInstance, notFound: Notfound): void {\n const requireAuth = (request: FastifyRequest) => {\n const context = devtoolsRequestContext(request);\n\n if (!context?.authenticated) throw new Error(\"A dashboard route ran without its session.\");\n\n return { auth: context.authenticated, meta: context.meta };\n };\n\n // The grant exchange. Every failure answers the uniform 404.\n server.post(\"/api/share/open\", async (request, reply) => {\n const context = devtoolsRequestContext(request);\n\n if (!context) return notFound(request, reply);\n\n const { meta } = context;\n const token = (request.body as { token?: unknown } | null | undefined)?.token;\n\n if (typeof token !== \"string\" || token === \"\" || token.length > MAX_TOKEN) {\n return notFound(request, reply);\n }\n\n try {\n if (await overLimit(meta.ip)) return notFound(request, reply);\n\n const result = await sessions.open(hashToken(token));\n\n if (!(\"grant\" in result)) {\n await failed(meta, result.refused, result.shareId);\n\n return notFound(request, reply);\n }\n\n const { value, maxAgeSeconds } = sessions.issue(result.grant.share);\n\n sessions.touch(result.grant.share.id);\n reply.header(\"set-cookie\", shareCookie(value, { ...cookieOptions, maxAgeSeconds }));\n\n return openAnswer(result.grant);\n } catch (error) {\n deps.warn?.(\n `A devtools share link could not be opened: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return notFound(request, reply);\n }\n });\n\n server.get(\"/api/share/info\", async (request) => openAnswer(grantOf(request)));\n\n server.get(\"/api/share/view.js\", async (request, reply) => {\n const view = grantOf(request).panel.share?.view;\n\n if (view === undefined) return notFound(request, reply);\n\n sendFile(reply, view, \"text/javascript; charset=utf-8\");\n\n return reply;\n });\n\n server.get<{ Params: { name: string } }>(\"/api/share/assets/:name\", async (request, reply) => {\n const { panel } = grantOf(request);\n const name = request.params.name;\n const file =\n panel.share?.assets.includes(name) === true && Object.hasOwn(panel.assets, name)\n ? panel.assets[name]\n : undefined;\n\n if (file === undefined) return notFound(request, reply);\n\n sendFile(reply, file, panelContentType(name));\n\n return reply;\n });\n\n server.get<{ Params: { \"*\": string } }>(\"/api/share/files/*\", async (request, reply) => {\n const { panel } = grantOf(request);\n\n return sendPanelFile(\n { files: panel.share?.files === true ? panel.files : null },\n request.params[\"*\"],\n request,\n reply,\n notFound,\n );\n });\n\n const panelRoute = async (request: FastifyRequest, reply: FastifyReply) => {\n const { panel } = grantOf(request);\n const sub = (request.params as { \"*\"?: string })[\"*\"];\n const path = sub === undefined || sub === \"\" ? \"\" : `/${sub}`;\n let matched: {\n route: MountedDevtoolsPanel[\"routes\"][number];\n params: Record<string, string>;\n } | null = null;\n\n for (const pattern of panel.share?.routes ?? []) {\n const params = matchSharePath(pattern, path);\n const route = panel.routes.find(\n (candidate) => candidate.method === \"GET\" && candidate.path === pattern,\n );\n\n if (params !== null && route !== undefined) {\n matched = { route, params };\n break;\n }\n }\n\n if (matched === null) return notFound(request, reply);\n\n const input: DevtoolsPanelRequest = {\n params: matched.params,\n query: (request.query ?? {}) as Record<string, string | string[]>,\n body: undefined,\n shared: true,\n };\n const result = await matched.route.handler(input);\n\n reply.header(\"cache-control\", \"no-store\");\n\n if (result === undefined) return reply.code(204).send();\n\n return result;\n };\n\n server.get(\"/api/share/panel\", panelRoute);\n server.get(\"/api/share/panel/*\", panelRoute);\n\n server.get(\"/api/admin/shares\", async () => list());\n\n server.post(\"/api/admin/shares\", async (request, reply) => {\n const { auth: authenticated, meta } = requireAuth(request);\n const created = await create(authenticated, meta, bodyOf(request));\n\n return reply.code(201).send(created);\n });\n\n server.delete<{ Params: { id: string } }>(\"/api/admin/shares/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = requireAuth(request);\n const id = request.params.id;\n\n if (typeof id !== \"string\" || id === \"\" || id.length > 64) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const record = await store.shares.get(id);\n\n if (!record || !(await store.shares.revoke(id, now()))) {\n throw new DevtoolsApiError(\"share.not-found\");\n }\n\n sessions.invalidate();\n await auth.audit(\"share.revoked\", {\n auth: authenticated,\n meta,\n detail: { share: id, panel: record.panel },\n });\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/admin/shares/revoke-all\", async (request) => {\n const { auth: authenticated, meta } = requireAuth(request);\n const revoked = await store.shares.revokeAll(now());\n\n sessions.invalidate();\n await auth.audit(\"share.revoked\", {\n auth: authenticated,\n meta,\n detail: { all: true, count: revoked },\n });\n\n return { revoked };\n });\n }\n\n return { authorize, register };\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,MAAM,SAAS;AACf,MAAM,YAAY;AAClB,MAAM,eAAe;;AAGrB,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;;AAGzB,MAAM,2BAA2B;;AAKjC,SAAgB,eAAe,SAAiB,MAA6C;CAC3F,IAAI,SAAS,KAAK,IAAI,GAAG,OAAO;CAEhC,MAAM,SAAS,QAAQ,MAAM,GAAG;CAChC,MAAM,QAAQ,KAAK,MAAM,GAAG;CAE5B,IAAI,OAAO,WAAW,MAAM,QAAQ,OAAO;CAE3C,MAAM,SAAiC,CAAC;CAExC,KAAK,MAAM,CAAC,OAAO,SAAS,OAAO,QAAQ,GAAG;EAC5C,MAAM,SAAS,MAAM;EAErB,IAAI,WAAW,QAAW,OAAO;EAEjC,IAAI,KAAK,WAAW,GAAG,GAAG;GACxB,IAAI,WAAW,IAAI,OAAO;GAE1B,OAAO,KAAK,MAAM,CAAC,KAAK;EAC1B,OAAO,IAAI,SAAS,QAClB,OAAO;CAEX;CAEA,OAAO;AACT;AAEA,SAAS,OAAO,SAAkD;CAChE,MAAM,OAAgB,QAAQ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KAAK,QAAQ,OAAO;GAE1B,IAAI,OAAO,OAAO,YAAY,OAAO,MAAM,GAAG,SAAS,IACrD,MAAM,IAAI,iBAAiB,eAAe;GAG5C,MAAM,SAAS,MAAM,MAAM,OAAO,IAAI,EAAE;GAExC,IAAI,CAAC,UAAU,CAAE,MAAM,MAAM,OAAO,OAAO,IAAI,IAAI,CAAC,GAClD,MAAM,IAAI,iBAAiB,iBAAiB;GAG9C,SAAS,WAAW;GACpB,MAAM,KAAK,MAAM,iBAAiB;IAChC,MAAM;IACN;IACA,QAAQ;KAAE,OAAO;KAAI,OAAO,OAAO;IAAM;GAC3C,CAAC;GAED,OAAO,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK;EAC9B,CAAC;EAED,OAAO,KAAK,gCAAgC,OAAO,YAAY;GAC7D,MAAM,EAAE,MAAM,eAAe,SAAS,YAAY,OAAO;GACzD,MAAM,UAAU,MAAM,MAAM,OAAO,UAAU,IAAI,CAAC;GAElD,SAAS,WAAW;GACpB,MAAM,KAAK,MAAM,iBAAiB;IAChC,MAAM;IACN;IACA,QAAQ;KAAE,KAAK;KAAM,OAAO;IAAQ;GACtC,CAAC;GAED,OAAO,EAAE,QAAQ;EACnB,CAAC;CACH;CAEA,OAAO;EAAE;EAAW;CAAS;AAC/B"}
|
|
1
|
+
{"version":3,"file":"share.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/http/share.ts"],"sourcesContent":["import type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { panelContentType, type MountedDevtoolsPanel } from \"../../panels\";\nimport { sendPanelFile } from \"../../server/panel-routes\";\nimport { sendFile } from \"../../server/ui-assets\";\nimport type { DevtoolsPanelRequest } from \"../../types\";\nimport { generateToken, hashToken } from \"../auth/helpers\";\nimport type { DevtoolsAuthenticated, DevtoolsRequestMeta } from \"../auth/types\";\nimport {\n DEVTOOLS_FAILURE_AUDIT_TYPES,\n DEVTOOLS_SHARE_LABEL_MAX,\n type DevtoolsCreatedShare,\n type DevtoolsShareList,\n type DevtoolsShareOpenAnswer,\n type DevtoolsShareView,\n} from \"../contracts\";\nimport { DevtoolsApiError } from \"../errors\";\nimport type { DevtoolsShareRecord } from \"../store/types\";\nimport { devtoolsRequestContext } from \"./context\";\nimport { readCookie, shareCookie, shareCookieName } from \"./cookie\";\nimport { rateLimitClient } from \"./ip\";\nimport { createShareSessions, type DevtoolsShareGrant } from \"./share-session\";\nimport type { MountProductionDevtoolsDeps } from \"./types\";\n\nconst DAY_MS = 86_400_000;\nconst MAX_TOKEN = 512;\nconst MAX_PANEL_ID = 64;\n\n/** A failed token is not looked up again for this long once its client is over the limit. */\nconst BLOCK_CACHE_MS = 30_000;\nconst BLOCK_CACHE_SIZE = 1000;\n\n/** A cookie failure is audited at most this often per client (a revoked link in use must not flood the log). */\nconst COOKIE_AUDIT_INTERVAL_MS = 60_000;\n\ntype Notfound = (\n request: FastifyRequest,\n reply: FastifyReply,\n) => FastifyReply | Promise<FastifyReply>;\n\n/** The path pattern `pattern` (`/flows/:feature`) matched against `path`, as its params; `null` for no match. */\nexport function matchSharePath(pattern: string, path: string): Record<string, string> | null {\n if (/[\\0\\\\]/.test(path)) return null;\n\n const wanted = pattern.split(\"/\");\n const given = path.split(\"/\");\n\n if (wanted.length !== given.length) return null;\n\n const params: Record<string, string> = {};\n\n for (const [index, part] of wanted.entries()) {\n const actual = given[index];\n\n if (actual === undefined) return null;\n\n if (part.startsWith(\":\")) {\n if (actual === \"\") return null;\n\n params[part.slice(1)] = actual;\n } else if (part !== actual) {\n return null;\n }\n }\n\n return params;\n}\n\nfunction bodyOf(request: FastifyRequest): Record<string, unknown> {\n const body: unknown = request.body;\n\n if (body === null || typeof body !== \"object\" || Array.isArray(body)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return body as Record<string, unknown>;\n}\n\nfunction viewOf(\n record: DevtoolsShareRecord,\n createdBy: string | null,\n at: number,\n): DevtoolsShareView {\n return {\n id: record.id,\n panel: record.panel,\n label: record.label,\n createdBy,\n createdAt: record.createdAt,\n expiresAt: record.expiresAt,\n revokedAt: record.revokedAt,\n lastUsedAt: record.lastUsedAt,\n uses: record.uses,\n status: record.revokedAt !== null ? \"revoked\" : record.expiresAt <= at ? \"expired\" : \"active\",\n };\n}\n\nfunction openAnswer(grant: DevtoolsShareGrant): DevtoolsShareOpenAnswer {\n const { panel, share } = grant;\n\n return {\n panel: panel.id,\n title: panel.title,\n label: share.label,\n expiresAt: share.expiresAt,\n assets: [...(panel.share?.assets ?? [])],\n files: panel.share?.files === true,\n };\n}\n\n/** What `mountProductionDevtools` gets back when sharing is on. */\nexport type DevtoolsShareMount = {\n /** The grant of a request's share cookie, or `null` (the gate then answers the uniform 404). */\n authorize(request: FastifyRequest, meta: DevtoolsRequestMeta): Promise<DevtoolsShareGrant | null>;\n /** Registers the share routes and the admin routes that manage links. */\n register(server: FastifyInstance, notFound: Notfound): void;\n};\n\n/**\n * Read-only share links of the production monitor. An admin creates a link\n * for a panel that declares `share`; the token is shown once and only its\n * SHA-256 is stored. Opening a link exchanges the token for a scoped cookie\n * (`__Secure-warlock-devtools-share`) that reaches only that panel's shared\n * view. Every refusal answers the dashboard's uniform 404, is audited as\n * `share.failed` (which counts toward the per-IP failure limit) and never\n * records the token.\n */\nexport function createDevtoolsShare(\n deps: MountProductionDevtoolsDeps & { now?: () => number },\n): DevtoolsShareMount {\n const { production, store, auth } = deps;\n const now = deps.now ?? (() => Date.now());\n\n if (typeof deps.hmac !== \"function\") {\n throw new Error(\"Share links need deps.hmac (HMAC-SHA256 keyed with encryption.key).\");\n }\n\n const sessions = createShareSessions({\n store,\n panels: deps.panels,\n hmac: deps.hmac,\n now,\n ...(deps.warn ? { warn: deps.warn } : {}),\n });\n const cookieOptions = { path: production.path, secure: production.requireHttps };\n const cookieName = shareCookieName(production.requireHttps);\n const sharePanels = deps.panels.filter((panel) => panel.share !== null);\n const blocked = new Map<string, number>();\n const cookieAudited = new Map<string, number>();\n\n const limits = production.rateLimits;\n const windowMs = limits.windowMinutes * 60_000;\n\n async function overLimit(ip: string): Promise<boolean> {\n const client = rateLimitClient(ip);\n const at = now();\n const until = blocked.get(client);\n\n if (until !== undefined && at < until) return true;\n\n const state = await store.state.read();\n const since = Math.max(at - windowMs, state.failuresResetAt ?? 0);\n const count = await store.audit.count({ types: DEVTOOLS_FAILURE_AUDIT_TYPES, since, ip });\n\n blocked.delete(client);\n\n if (count < limits.ip) return false;\n\n if (blocked.size >= BLOCK_CACHE_SIZE) {\n const oldest = blocked.keys().next();\n\n if (!oldest.done) blocked.delete(oldest.value);\n }\n\n blocked.set(client, at + BLOCK_CACHE_MS);\n\n return true;\n }\n\n /** Writes one `share.failed` entry (never the token). Never throws. */\n async function failed(\n meta: DevtoolsRequestMeta,\n reason: string,\n shareId: string | null,\n ): Promise<void> {\n await auth.audit(\"share.failed\", { meta, detail: { reason, share: shareId } });\n }\n\n /** The cookie check for a share request. */\n async function authorize(\n request: FastifyRequest,\n meta: DevtoolsRequestMeta,\n ): Promise<DevtoolsShareGrant | null> {\n const value = readCookie(request.headers.cookie, cookieName);\n\n if (value === undefined) return null;\n\n let result;\n\n try {\n result = await sessions.verify(value);\n } catch (error) {\n deps.warn?.(\n `A devtools share link could not be checked and the request was refused: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return null;\n }\n\n if (\"grant\" in result) {\n sessions.touch(result.grant.share.id);\n\n return result.grant;\n }\n\n const client = rateLimitClient(meta.ip);\n const last = cookieAudited.get(client);\n\n if (last === undefined || now() - last >= COOKIE_AUDIT_INTERVAL_MS) {\n cookieAudited.delete(client);\n\n if (cookieAudited.size >= BLOCK_CACHE_SIZE) {\n const oldest = cookieAudited.keys().next();\n\n if (!oldest.done) cookieAudited.delete(oldest.value);\n }\n\n cookieAudited.set(client, now());\n\n try {\n if (!(await overLimit(meta.ip))) await failed(meta, result.refused, result.shareId);\n } catch {\n // The refusal stands even when the audit cannot be written.\n }\n }\n\n return null;\n }\n\n function grantOf(request: FastifyRequest): DevtoolsShareGrant {\n const grant = devtoolsRequestContext(request)?.share;\n\n if (!grant) throw new Error(\"A share route ran without its grant.\");\n\n return grant;\n }\n\n function createdByOf(\n accounts: readonly { id: string; email: string }[],\n id: string | null,\n ): string | null {\n return accounts.find((account) => account.id === id)?.email ?? null;\n }\n\n // ---- Admin ----------------------------------------------------------------\n\n async function list(): Promise<DevtoolsShareList> {\n const [records, accounts] = await Promise.all([store.shares.list(), store.accounts.list()]);\n const at = now();\n\n return {\n enabled: true,\n maxDays: production.share.maxDays,\n panels: sharePanels.map((panel) => ({ id: panel.id, title: panel.title })),\n shares: records.map((record) => viewOf(record, createdByOf(accounts, record.createdBy), at)),\n };\n }\n\n async function create(\n authenticated: DevtoolsAuthenticated,\n meta: DevtoolsRequestMeta,\n body: Record<string, unknown>,\n ): Promise<DevtoolsCreatedShare> {\n const panel = body.panel;\n const label = typeof body.label === \"string\" ? body.label.trim() : \"\";\n const days = body.days;\n\n if (\n typeof panel !== \"string\" ||\n panel.length > MAX_PANEL_ID ||\n !sharePanels.some((item) => item.id === panel) ||\n label === \"\" ||\n label.length > DEVTOOLS_SHARE_LABEL_MAX ||\n // eslint-disable-next-line no-control-regex\n /[\\u0000-\\u001f\\u007f]/.test(label) ||\n typeof days !== \"number\" ||\n !Number.isInteger(days) ||\n days < 1 ||\n days > production.share.maxDays\n ) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const token = generateToken();\n const at = now();\n const record = await store.shares.create({\n tokenHash: hashToken(token),\n panel,\n label,\n createdBy: authenticated.account.id,\n createdAt: at,\n expiresAt: at + days * DAY_MS,\n });\n\n sessions.invalidate();\n await auth.audit(\"share.created\", {\n auth: authenticated,\n meta,\n detail: { share: record.id, panel, days },\n });\n\n return {\n share: viewOf(record, authenticated.account.email, at),\n // The token rides in the fragment: it never reaches an access log or a Referer header.\n url: `${meta.origin}${production.path}/#/share/${token}`,\n };\n }\n\n // ---- Registration -----------------------------------------------------------\n\n function register(server: FastifyInstance, notFound: Notfound): void {\n const requireAuth = (request: FastifyRequest) => {\n const context = devtoolsRequestContext(request);\n\n if (!context?.authenticated) throw new Error(\"A dashboard route ran without its session.\");\n\n return { auth: context.authenticated, meta: context.meta };\n };\n\n // The grant exchange. Every failure answers the uniform 404.\n server.post(\"/api/share/open\", async (request, reply) => {\n const context = devtoolsRequestContext(request);\n\n if (!context) return notFound(request, reply);\n\n const { meta } = context;\n const token = (request.body as { token?: unknown } | null | undefined)?.token;\n\n if (typeof token !== \"string\" || token === \"\" || token.length > MAX_TOKEN) {\n return notFound(request, reply);\n }\n\n try {\n if (await overLimit(meta.ip)) return notFound(request, reply);\n\n const result = await sessions.open(hashToken(token));\n\n if (!(\"grant\" in result)) {\n await failed(meta, result.refused, result.shareId);\n\n return notFound(request, reply);\n }\n\n const { value, maxAgeSeconds } = sessions.issue(result.grant.share);\n\n sessions.touch(result.grant.share.id);\n reply.header(\"set-cookie\", shareCookie(value, { ...cookieOptions, maxAgeSeconds }));\n\n return openAnswer(result.grant);\n } catch (error) {\n deps.warn?.(\n `A devtools share link could not be opened: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return notFound(request, reply);\n }\n });\n\n server.get(\"/api/share/info\", async (request) => openAnswer(grantOf(request)));\n\n server.get(\"/api/share/view.js\", async (request, reply) => {\n const view = grantOf(request).panel.share?.view;\n\n if (view === undefined) return notFound(request, reply);\n\n sendFile(reply, view, \"text/javascript; charset=utf-8\");\n\n return reply;\n });\n\n server.get<{ Params: { name: string } }>(\"/api/share/assets/:name\", async (request, reply) => {\n const { panel } = grantOf(request);\n const name = request.params.name;\n const file =\n panel.share?.assets.includes(name) === true && Object.hasOwn(panel.assets, name)\n ? panel.assets[name]\n : undefined;\n\n if (file === undefined) return notFound(request, reply);\n\n sendFile(reply, file, panelContentType(name));\n\n return reply;\n });\n\n server.get<{ Params: { \"*\": string } }>(\"/api/share/files/*\", async (request, reply) => {\n const { panel } = grantOf(request);\n\n return sendPanelFile(\n { files: panel.share?.files === true ? panel.files : null },\n request.params[\"*\"],\n request,\n reply,\n notFound,\n );\n });\n\n const panelRoute = async (request: FastifyRequest, reply: FastifyReply) => {\n const { panel } = grantOf(request);\n const sub = (request.params as { \"*\"?: string })[\"*\"];\n const path = sub === undefined || sub === \"\" ? \"\" : `/${sub}`;\n let matched: {\n route: MountedDevtoolsPanel[\"routes\"][number];\n params: Record<string, string>;\n } | null = null;\n\n for (const pattern of panel.share?.routes ?? []) {\n const params = matchSharePath(pattern, path);\n const route = panel.routes.find(\n (candidate) => candidate.method === \"GET\" && candidate.path === pattern,\n );\n\n if (params !== null && route !== undefined) {\n matched = { route, params };\n break;\n }\n }\n\n if (matched === null) return notFound(request, reply);\n\n const input: DevtoolsPanelRequest = {\n params: matched.params,\n query: (request.query ?? {}) as Record<string, string | string[]>,\n body: undefined,\n shared: true,\n };\n const result = await matched.route.handler(input);\n\n reply.header(\"cache-control\", \"no-store\");\n\n if (result === undefined) return reply.code(204).send();\n\n return result;\n };\n\n server.get(\"/api/share/panel\", panelRoute);\n server.get(\"/api/share/panel/*\", panelRoute);\n\n server.get(\"/api/admin/shares\", async () => list());\n\n server.post(\"/api/admin/shares\", async (request, reply) => {\n const { auth: authenticated, meta } = requireAuth(request);\n const created = await create(authenticated, meta, bodyOf(request));\n\n return reply.code(201).send(created);\n });\n\n server.delete<{ Params: { id: string } }>(\"/api/admin/shares/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = requireAuth(request);\n const id = request.params.id;\n\n if (typeof id !== \"string\" || id === \"\" || id.length > 64) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const record = await store.shares.get(id);\n\n if (!record || !(await store.shares.revoke(id, now()))) {\n throw new DevtoolsApiError(\"share.not-found\");\n }\n\n sessions.invalidate();\n await auth.audit(\"share.revoked\", {\n auth: authenticated,\n meta,\n detail: { share: id, panel: record.panel },\n });\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/admin/shares/revoke-all\", async (request) => {\n const { auth: authenticated, meta } = requireAuth(request);\n const revoked = await store.shares.revokeAll(now());\n\n sessions.invalidate();\n await auth.audit(\"share.revoked\", {\n auth: authenticated,\n meta,\n detail: { all: true, count: revoked },\n });\n\n return { revoked };\n });\n }\n\n return { authorize, register };\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,MAAM,SAAS;AACf,MAAM,YAAY;AAClB,MAAM,eAAe;;AAGrB,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;;AAGzB,MAAM,2BAA2B;;AAQjC,SAAgB,eAAe,SAAiB,MAA6C;CAC3F,IAAI,SAAS,KAAK,IAAI,GAAG,OAAO;CAEhC,MAAM,SAAS,QAAQ,MAAM,GAAG;CAChC,MAAM,QAAQ,KAAK,MAAM,GAAG;CAE5B,IAAI,OAAO,WAAW,MAAM,QAAQ,OAAO;CAE3C,MAAM,SAAiC,CAAC;CAExC,KAAK,MAAM,CAAC,OAAO,SAAS,OAAO,QAAQ,GAAG;EAC5C,MAAM,SAAS,MAAM;EAErB,IAAI,WAAW,QAAW,OAAO;EAEjC,IAAI,KAAK,WAAW,GAAG,GAAG;GACxB,IAAI,WAAW,IAAI,OAAO;GAE1B,OAAO,KAAK,MAAM,CAAC,KAAK;EAC1B,OAAO,IAAI,SAAS,QAClB,OAAO;CAEX;CAEA,OAAO;AACT;AAEA,SAAS,OAAO,SAAkD;CAChE,MAAM,OAAgB,QAAQ;CAE9B,IAAI,SAAS,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GACjE,MAAM,IAAI,iBAAiB,eAAe;CAG5C,OAAO;AACT;AAEA,SAAS,OACP,QACA,WACA,IACmB;CACnB,OAAO;EACL,IAAI,OAAO;EACX,OAAO,OAAO;EACd,OAAO,OAAO;EACd;EACA,WAAW,OAAO;EAClB,WAAW,OAAO;EAClB,WAAW,OAAO;EAClB,YAAY,OAAO;EACnB,MAAM,OAAO;EACb,QAAQ,OAAO,cAAc,OAAO,YAAY,OAAO,aAAa,KAAK,YAAY;CACvF;AACF;AAEA,SAAS,WAAW,OAAoD;C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O,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK;EAC9B,CAAC;EAED,OAAO,KAAK,gCAAgC,OAAO,YAAY;GAC7D,MAAM,EAAE,MAAM,eAAe,SAAS,YAAY,OAAO;GACzD,MAAM,UAAU,MAAM,MAAM,OAAO,UAAU,IAAI,CAAC;GAElD,SAAS,WAAW;GACpB,MAAM,KAAK,MAAM,iBAAiB;IAChC,MAAM;IACN;IACA,QAAQ;KAAE,KAAK;KAAM,OAAO;IAAQ;GACtC,CAAC;GAED,OAAO,EAAE,QAAQ;EACnB,CAAC;CACH;CAEA,OAAO;EAAE;EAAW;CAAS;AAC/B"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { DEVTOOLS_AI_ERROR_CATEGORIES, DEVTOOLS_AI_LATENCY_BUCKETS_MS, DEVTOOLS_BUILT_IN_PANELS, DEVTOOLS_FAILURE_AUDIT_TYPES, DEVTOOLS_LATENCY_BUCKETS_MS, DEVTOOLS_SHARE_LABEL_MAX, DevtoolsAccountView, DevtoolsAiBreakdownRow, DevtoolsAiCostTotals, DevtoolsAiErrorCategory, DevtoolsAiErrorGroup, DevtoolsAiErrorsView, DevtoolsAiEvaluatePrompt, DevtoolsAiEvaluateRequest, DevtoolsAiEvaluateResult, DevtoolsAiEvaluateView, DevtoolsAiFailedRun, DevtoolsAiFilterOptions, DevtoolsAiLatencyTotals, DevtoolsAiModelRow, DevtoolsAiModelsView, DevtoolsAiPricingState, DevtoolsAiRangePreset, DevtoolsAiRatePoint, DevtoolsAiReportView, DevtoolsAiResolvedRange, DevtoolsAiRunGroup, DevtoolsAiRunRow, DevtoolsAiRunsView, DevtoolsAiSeriesSet, DevtoolsAiTokenTotals, DevtoolsAiTotals, DevtoolsAiUnavailableReasonView, DevtoolsAiUnavailableView, DevtoolsAiUsageView, DevtoolsApiErrorBody, DevtoolsAuditEntry, DevtoolsAuditType, DevtoolsAuthStepResult, DevtoolsBuiltInPanelId, DevtoolsCaptureCounters, DevtoolsCreatedInvite, DevtoolsCreatedShare, DevtoolsErrorCode, DevtoolsErrorGroup, DevtoolsErrorsView, DevtoolsExplainResult, DevtoolsHealthReport, DevtoolsHealthView, DevtoolsHistogram, DevtoolsInstanceInfo, DevtoolsInstanceReport, DevtoolsInstancesView, DevtoolsInviteView, DevtoolsJobsReport, DevtoolsJobsView, DevtoolsLogRow, DevtoolsLoginInput, DevtoolsLogsView, DevtoolsMode, DevtoolsPanelInfo, DevtoolsPasswordSource, DevtoolsQueryShapeRow, DevtoolsQueryShapeStats, DevtoolsQueryStatsView, DevtoolsRecoveryCodes, DevtoolsReportLogEntry, DevtoolsResourcePoint, DevtoolsResourceSnapshot, DevtoolsResourcesView, DevtoolsRole, DevtoolsRoutePhaseStats, DevtoolsRouteStats, DevtoolsRouteStatsRow, DevtoolsRouteStatsView, DevtoolsSampleDetail, DevtoolsSampleQuery, DevtoolsSampleSummary, DevtoolsScheduleInfo, DevtoolsSessionInfo, DevtoolsSessionStage, DevtoolsSessionView, DevtoolsShareCreateInput, DevtoolsShareList, DevtoolsShareOpenAnswer, DevtoolsShareStatus, DevtoolsShareView, DevtoolsTotpEnrolment, DevtoolsUserListView } from "./contracts.mjs";
|
|
1
|
+
import { DEVTOOLS_AI_ERROR_CATEGORIES, DEVTOOLS_AI_LATENCY_BUCKETS_MS, DEVTOOLS_BUILT_IN_PANELS, DEVTOOLS_FAILURE_AUDIT_TYPES, DEVTOOLS_LATENCY_BUCKETS_MS, DEVTOOLS_SHARE_LABEL_MAX, DevtoolsAccountView, DevtoolsAiBreakdownRow, DevtoolsAiCostTotals, DevtoolsAiErrorCategory, DevtoolsAiErrorGroup, DevtoolsAiErrorsView, DevtoolsAiEvaluatePrompt, DevtoolsAiEvaluateRequest, DevtoolsAiEvaluateResult, DevtoolsAiEvaluateView, DevtoolsAiFailedRun, DevtoolsAiFilterOptions, DevtoolsAiLatencyTotals, DevtoolsAiModelRow, DevtoolsAiModelsView, DevtoolsAiPricingState, DevtoolsAiRangePreset, DevtoolsAiRatePoint, DevtoolsAiReportView, DevtoolsAiResolvedRange, DevtoolsAiRunGroup, DevtoolsAiRunRow, DevtoolsAiRunsView, DevtoolsAiSeriesSet, DevtoolsAiTokenTotals, DevtoolsAiTotals, DevtoolsAiUnavailableReasonView, DevtoolsAiUnavailableView, DevtoolsAiUsageView, DevtoolsApiErrorBody, DevtoolsAuditEntry, DevtoolsAuditType, DevtoolsAuthStepResult, DevtoolsBuiltInPanelId, DevtoolsCaptureCounters, DevtoolsCreatedInvite, DevtoolsCreatedShare, DevtoolsErrorCode, DevtoolsErrorGroup, DevtoolsErrorsView, DevtoolsExplainResult, DevtoolsHealthReport, DevtoolsHealthView, DevtoolsHistogram, DevtoolsInstanceInfo, DevtoolsInstanceReport, DevtoolsInstancesView, DevtoolsInviteView, DevtoolsJobsReport, DevtoolsJobsView, DevtoolsLogRow, DevtoolsLoginInput, DevtoolsLogsView, DevtoolsMode, DevtoolsPanelInfo, DevtoolsPasswordSource, DevtoolsQueryShapeRow, DevtoolsQueryShapeStats, DevtoolsQueryStatsView, DevtoolsQueueInfo, DevtoolsRecoveryCodes, DevtoolsReportLogEntry, DevtoolsResourcePoint, DevtoolsResourceSnapshot, DevtoolsResourcesView, DevtoolsRole, DevtoolsRoutePhaseStats, DevtoolsRouteStats, DevtoolsRouteStatsRow, DevtoolsRouteStatsView, DevtoolsSampleDetail, DevtoolsSampleQuery, DevtoolsSampleSummary, DevtoolsScheduleInfo, DevtoolsScheduleRun, DevtoolsSessionInfo, DevtoolsSessionStage, DevtoolsSessionView, DevtoolsShareCreateInput, DevtoolsShareList, DevtoolsShareOpenAnswer, DevtoolsShareStatus, DevtoolsShareView, DevtoolsTotpEnrolment, DevtoolsUserListView } from "./contracts.mjs";
|
|
2
2
|
import { registerDevtoolsCommands } from "./cli/index.mjs";
|
|
3
3
|
import { DEVTOOLS_CONFIG_CODES, DevtoolsConfigCode, DevtoolsProductionConfigError } from "./errors.mjs";
|
|
4
4
|
import { devtoolsMigrations } from "./store/migrations.mjs";
|
|
5
5
|
import { ResolvedDevtoolsProductionOptions } from "./options.mjs";
|
|
6
|
-
export { type DEVTOOLS_AI_ERROR_CATEGORIES, type DEVTOOLS_AI_LATENCY_BUCKETS_MS, type DEVTOOLS_BUILT_IN_PANELS, DEVTOOLS_CONFIG_CODES, type DEVTOOLS_FAILURE_AUDIT_TYPES, type DEVTOOLS_LATENCY_BUCKETS_MS, type DEVTOOLS_SHARE_LABEL_MAX, type DevtoolsAccountView, type DevtoolsAiBreakdownRow, type DevtoolsAiCostTotals, type DevtoolsAiErrorCategory, type DevtoolsAiErrorGroup, type DevtoolsAiErrorsView, type DevtoolsAiEvaluatePrompt, type DevtoolsAiEvaluateRequest, type DevtoolsAiEvaluateResult, type DevtoolsAiEvaluateView, type DevtoolsAiFailedRun, type DevtoolsAiFilterOptions, type DevtoolsAiLatencyTotals, type DevtoolsAiModelRow, type DevtoolsAiModelsView, type DevtoolsAiPricingState, type DevtoolsAiRangePreset, type DevtoolsAiRatePoint, type DevtoolsAiReportView, type DevtoolsAiResolvedRange, type DevtoolsAiRunGroup, type DevtoolsAiRunRow, type DevtoolsAiRunsView, type DevtoolsAiSeriesSet, type DevtoolsAiTokenTotals, type DevtoolsAiTotals, type DevtoolsAiUnavailableReasonView, type DevtoolsAiUnavailableView, type DevtoolsAiUsageView, type DevtoolsApiErrorBody, type DevtoolsAuditEntry, type DevtoolsAuditType, type DevtoolsAuthStepResult, type DevtoolsBuiltInPanelId, type DevtoolsCaptureCounters, type DevtoolsConfigCode, type DevtoolsCreatedInvite, type DevtoolsCreatedShare, type DevtoolsErrorCode, type DevtoolsErrorGroup, type DevtoolsErrorsView, type DevtoolsExplainResult, type DevtoolsHealthReport, type DevtoolsHealthView, type DevtoolsHistogram, type DevtoolsInstanceInfo, type DevtoolsInstanceReport, type DevtoolsInstancesView, type DevtoolsInviteView, type DevtoolsJobsReport, type DevtoolsJobsView, type DevtoolsLogRow, type DevtoolsLoginInput, type DevtoolsLogsView, type DevtoolsMode, type DevtoolsPanelInfo, type DevtoolsPasswordSource, DevtoolsProductionConfigError, type DevtoolsQueryShapeRow, type DevtoolsQueryShapeStats, type DevtoolsQueryStatsView, type DevtoolsRecoveryCodes, type DevtoolsReportLogEntry, type DevtoolsResourcePoint, type DevtoolsResourceSnapshot, type DevtoolsResourcesView, type DevtoolsRole, type DevtoolsRoutePhaseStats, type DevtoolsRouteStats, type DevtoolsRouteStatsRow, type DevtoolsRouteStatsView, type DevtoolsSampleDetail, type DevtoolsSampleQuery, type DevtoolsSampleSummary, type DevtoolsScheduleInfo, type DevtoolsSessionInfo, type DevtoolsSessionStage, type DevtoolsSessionView, type DevtoolsShareCreateInput, type DevtoolsShareList, type DevtoolsShareOpenAnswer, type DevtoolsShareStatus, type DevtoolsShareView, type DevtoolsTotpEnrolment, type DevtoolsUserListView, type ResolvedDevtoolsProductionOptions, devtoolsMigrations, registerDevtoolsCommands };
|
|
6
|
+
export { type DEVTOOLS_AI_ERROR_CATEGORIES, type DEVTOOLS_AI_LATENCY_BUCKETS_MS, type DEVTOOLS_BUILT_IN_PANELS, DEVTOOLS_CONFIG_CODES, type DEVTOOLS_FAILURE_AUDIT_TYPES, type DEVTOOLS_LATENCY_BUCKETS_MS, type DEVTOOLS_SHARE_LABEL_MAX, type DevtoolsAccountView, type DevtoolsAiBreakdownRow, type DevtoolsAiCostTotals, type DevtoolsAiErrorCategory, type DevtoolsAiErrorGroup, type DevtoolsAiErrorsView, type DevtoolsAiEvaluatePrompt, type DevtoolsAiEvaluateRequest, type DevtoolsAiEvaluateResult, type DevtoolsAiEvaluateView, type DevtoolsAiFailedRun, type DevtoolsAiFilterOptions, type DevtoolsAiLatencyTotals, type DevtoolsAiModelRow, type DevtoolsAiModelsView, type DevtoolsAiPricingState, type DevtoolsAiRangePreset, type DevtoolsAiRatePoint, type DevtoolsAiReportView, type DevtoolsAiResolvedRange, type DevtoolsAiRunGroup, type DevtoolsAiRunRow, type DevtoolsAiRunsView, type DevtoolsAiSeriesSet, type DevtoolsAiTokenTotals, type DevtoolsAiTotals, type DevtoolsAiUnavailableReasonView, type DevtoolsAiUnavailableView, type DevtoolsAiUsageView, type DevtoolsApiErrorBody, type DevtoolsAuditEntry, type DevtoolsAuditType, type DevtoolsAuthStepResult, type DevtoolsBuiltInPanelId, type DevtoolsCaptureCounters, type DevtoolsConfigCode, type DevtoolsCreatedInvite, type DevtoolsCreatedShare, type DevtoolsErrorCode, type DevtoolsErrorGroup, type DevtoolsErrorsView, type DevtoolsExplainResult, type DevtoolsHealthReport, type DevtoolsHealthView, type DevtoolsHistogram, type DevtoolsInstanceInfo, type DevtoolsInstanceReport, type DevtoolsInstancesView, type DevtoolsInviteView, type DevtoolsJobsReport, type DevtoolsJobsView, type DevtoolsLogRow, type DevtoolsLoginInput, type DevtoolsLogsView, type DevtoolsMode, type DevtoolsPanelInfo, type DevtoolsPasswordSource, DevtoolsProductionConfigError, type DevtoolsQueryShapeRow, type DevtoolsQueryShapeStats, type DevtoolsQueryStatsView, type DevtoolsQueueInfo, type DevtoolsRecoveryCodes, type DevtoolsReportLogEntry, type DevtoolsResourcePoint, type DevtoolsResourceSnapshot, type DevtoolsResourcesView, type DevtoolsRole, type DevtoolsRoutePhaseStats, type DevtoolsRouteStats, type DevtoolsRouteStatsRow, type DevtoolsRouteStatsView, type DevtoolsSampleDetail, type DevtoolsSampleQuery, type DevtoolsSampleSummary, type DevtoolsScheduleInfo, type DevtoolsScheduleRun, type DevtoolsSessionInfo, type DevtoolsSessionStage, type DevtoolsSessionView, type DevtoolsShareCreateInput, type DevtoolsShareList, type DevtoolsShareOpenAnswer, type DevtoolsShareStatus, type DevtoolsShareView, type DevtoolsTotpEnrolment, type DevtoolsUserListView, type ResolvedDevtoolsProductionOptions, devtoolsMigrations, registerDevtoolsCommands };
|