@warlock.js/devtools 5.58.0 → 5.60.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 +32 -0
- package/cjs/app-versions-C_ZyzuvD.cjs +138 -0
- package/cjs/app-versions-C_ZyzuvD.cjs.map +1 -0
- package/cjs/attach-D5aMqUnA.cjs +1342 -0
- package/cjs/attach-D5aMqUnA.cjs.map +1 -0
- package/cjs/{auth-DV2GA1A9.cjs → auth-ChHh5E7j.cjs} +20 -13
- package/cjs/auth-ChHh5E7j.cjs.map +1 -0
- package/cjs/{boot-CyeHPFtk.cjs → boot-Dg5YZGGR.cjs} +78 -14
- package/cjs/boot-Dg5YZGGR.cjs.map +1 -0
- package/cjs/{capture-DcyBhdqw.cjs → capture-CBgONYhk.cjs} +4 -4
- package/cjs/{capture-DcyBhdqw.cjs.map → capture-CBgONYhk.cjs.map} +1 -1
- package/cjs/{cascade-store-DEGxAFDI.cjs → cascade-store-DUT2Laha.cjs} +3 -3
- package/cjs/cascade-store-DUT2Laha.cjs.map +1 -0
- package/cjs/{current-request-id-BoJJb3y7.cjs → current-request-id-Badec-TH.cjs} +3 -3
- package/cjs/{current-request-id-BoJJb3y7.cjs.map → current-request-id-Badec-TH.cjs.map} +1 -1
- package/cjs/{errors-DEqdWaqm.cjs → errors-DNQ-g49I.cjs} +201 -4
- package/cjs/errors-DNQ-g49I.cjs.map +1 -0
- package/cjs/extract-8kaX_cUV.cjs +1103 -0
- package/cjs/extract-8kaX_cUV.cjs.map +1 -0
- package/cjs/{helpers-7k_Q-abk.cjs → helpers-BcMBFy9v.cjs} +9 -6
- package/cjs/{helpers-7k_Q-abk.cjs.map → helpers-BcMBFy9v.cjs.map} +1 -1
- package/cjs/{histogram-BRV5eHcp.cjs → histogram-CkoVizdf.cjs} +6 -6
- package/cjs/{histogram-BRV5eHcp.cjs.map → histogram-CkoVizdf.cjs.map} +1 -1
- package/cjs/{http-XNLYU2vS.cjs → http-DCVCf44M.cjs} +26 -9
- package/cjs/http-DCVCf44M.cjs.map +1 -0
- package/cjs/index.cjs +1 -1
- package/cjs/{insights-BBZnUpWO.cjs → insights-CFof59kF.cjs} +6 -6
- package/cjs/{insights-BBZnUpWO.cjs.map → insights-CFof59kF.cjs.map} +1 -1
- package/cjs/migrations-BQdNOL5_.cjs +30 -0
- package/cjs/migrations-BQdNOL5_.cjs.map +1 -0
- package/cjs/{migrations-DTTzCNpR.cjs → models-DF1agAm4.cjs} +107 -25
- package/cjs/models-DF1agAm4.cjs.map +1 -0
- package/cjs/{process-panel-DEOnLxoT.cjs → process-panel-D3D9Y_dc.cjs} +5 -5
- package/cjs/{process-panel-DEOnLxoT.cjs.map → process-panel-D3D9Y_dc.cjs.map} +1 -1
- package/cjs/production/index.cjs +4 -4
- package/cjs/runs-DECWPGnq.cjs +390 -0
- package/cjs/runs-DECWPGnq.cjs.map +1 -0
- package/cjs/{server-C8JfggQU.cjs → server-CC5DpObz.cjs} +10 -7
- package/cjs/server-CC5DpObz.cjs.map +1 -0
- package/cjs/{src-DjOUdhKc.cjs → src-VyOjEEAo.cjs} +179 -24
- package/cjs/src-VyOjEEAo.cjs.map +1 -0
- package/cjs/{store-C06KO_A1.cjs → store-EFn4wp0T.cjs} +2 -2
- package/cjs/{stream-route-D4k-sJvW.cjs → stream-route-DFHuIWgg.cjs} +125 -19
- package/cjs/stream-route-DFHuIWgg.cjs.map +1 -0
- package/esm/ai/attach.mjs +92 -0
- package/esm/ai/attach.mjs.map +1 -0
- package/esm/ai/options.mjs +31 -0
- package/esm/ai/options.mjs.map +1 -0
- package/esm/ai/reports/aggregate.mjs +330 -0
- package/esm/ai/reports/aggregate.mjs.map +1 -0
- package/esm/ai/reports/evaluate.mjs +108 -0
- package/esm/ai/reports/evaluate.mjs.map +1 -0
- package/esm/ai/reports/range.mjs +121 -0
- package/esm/ai/reports/range.mjs.map +1 -0
- package/esm/ai/reports/runs.d.mts +2 -0
- package/esm/ai/reports/runs.mjs +212 -0
- package/esm/ai/reports/runs.mjs.map +1 -0
- package/esm/ai/reports/service.mjs +132 -0
- package/esm/ai/reports/service.mjs.map +1 -0
- package/esm/ai/rollup/cascade-store.mjs +84 -0
- package/esm/ai/rollup/cascade-store.mjs.map +1 -0
- package/esm/ai/rollup/categories.mjs +67 -0
- package/esm/ai/rollup/categories.mjs.map +1 -0
- package/esm/ai/rollup/extract.mjs +225 -0
- package/esm/ai/rollup/extract.mjs.map +1 -0
- package/esm/ai/rollup/file-store.mjs +147 -0
- package/esm/ai/rollup/file-store.mjs.map +1 -0
- package/esm/ai/rollup/histogram.mjs +42 -0
- package/esm/ai/rollup/histogram.mjs.map +1 -0
- package/esm/ai/rollup/increment-error.mjs +19 -0
- package/esm/ai/rollup/increment-error.mjs.map +1 -0
- package/esm/ai/rollup/index.mjs +9 -0
- package/esm/ai/rollup/mapping.mjs +69 -0
- package/esm/ai/rollup/mapping.mjs.map +1 -0
- package/esm/ai/rollup/memory-store.mjs +26 -0
- package/esm/ai/rollup/memory-store.mjs.map +1 -0
- package/esm/ai/rollup/writer.mjs +113 -0
- package/esm/ai/rollup/writer.mjs.map +1 -0
- package/esm/ai/types.d.mts +29 -0
- package/esm/ai/types.d.mts.map +1 -0
- package/esm/app-versions.mjs +74 -0
- package/esm/app-versions.mjs.map +1 -0
- package/esm/devtools-connector.d.mts.map +1 -1
- package/esm/devtools-connector.mjs +54 -2
- package/esm/devtools-connector.mjs.map +1 -1
- package/esm/index.d.mts +3 -2
- package/esm/options.mjs +4 -0
- package/esm/options.mjs.map +1 -1
- package/esm/production/auth/helpers.mjs +8 -5
- package/esm/production/auth/helpers.mjs.map +1 -1
- package/esm/production/auth/service.mjs +14 -6
- package/esm/production/auth/service.mjs.map +1 -1
- package/esm/production/boot.mjs +70 -3
- package/esm/production/boot.mjs.map +1 -1
- package/esm/production/contracts.d.mts +378 -2
- package/esm/production/contracts.d.mts.map +1 -1
- package/esm/production/contracts.mjs +64 -2
- package/esm/production/contracts.mjs.map +1 -1
- package/esm/production/errors.d.mts +1 -1
- package/esm/production/errors.mjs +11 -3
- package/esm/production/errors.mjs.map +1 -1
- package/esm/production/http/access.mjs +6 -0
- package/esm/production/http/access.mjs.map +1 -1
- package/esm/production/http/mount.mjs +13 -0
- package/esm/production/http/mount.mjs.map +1 -1
- package/esm/production/http/share-session.mjs.map +1 -1
- package/esm/production/index.d.mts +2 -2
- package/esm/production/insights/writer.mjs.map +1 -1
- package/esm/production/options.d.mts +5 -1
- package/esm/production/options.d.mts.map +1 -1
- package/esm/production/options.mjs +13 -1
- package/esm/production/options.mjs.map +1 -1
- package/esm/production/store/memory-store.mjs.map +1 -1
- package/esm/production/store/migrations.d.mts +1 -1
- package/esm/production/store/migrations.d.mts.map +1 -1
- package/esm/production/store/migrations.mjs +4 -2
- package/esm/production/store/migrations.mjs.map +1 -1
- package/esm/production/store/models/ai-rollup.migration.mjs +48 -0
- package/esm/production/store/models/ai-rollup.migration.mjs.map +1 -0
- package/esm/production/store/models/ai-rollup.model.mjs +13 -0
- package/esm/production/store/models/ai-rollup.model.mjs.map +1 -0
- package/esm/production/store/models/index.mjs +3 -1
- package/esm/server/ai-report-routes.mjs +72 -0
- package/esm/server/ai-report-routes.mjs.map +1 -0
- package/esm/server/ai-routes.mjs +41 -6
- package/esm/server/ai-routes.mjs.map +1 -1
- package/esm/server/index.mjs +2 -0
- package/esm/server/index.mjs.map +1 -1
- package/esm/server/session-routes.mjs +3 -1
- package/esm/server/session-routes.mjs.map +1 -1
- package/esm/sources/agent-trace-source.d.mts.map +1 -1
- package/esm/sources/agent-trace-source.mjs.map +1 -1
- package/esm/sources/ai-source.d.mts +2 -0
- package/esm/sources/ai-source.d.mts.map +1 -1
- package/esm/sources/ai-source.mjs +120 -11
- package/esm/sources/ai-source.mjs.map +1 -1
- package/esm/types.d.mts +23 -4
- package/esm/types.d.mts.map +1 -1
- package/llms-full.txt +79 -32
- package/package.json +8 -8
- package/skills/SKILL.md +79 -32
- package/ui/dashboard/assets/app.css +1 -1
- package/ui/dashboard/assets/app.js +23 -16
- package/ui/dashboard/build-info.json +7 -7
- package/cjs/ai-source-DTpxumMA.cjs +0 -381
- package/cjs/ai-source-DTpxumMA.cjs.map +0 -1
- package/cjs/auth-DV2GA1A9.cjs.map +0 -1
- package/cjs/boot-CyeHPFtk.cjs.map +0 -1
- package/cjs/cascade-store-DEGxAFDI.cjs.map +0 -1
- package/cjs/contracts-CDuY-ahl.cjs +0 -116
- package/cjs/contracts-CDuY-ahl.cjs.map +0 -1
- package/cjs/errors-DEqdWaqm.cjs.map +0 -1
- package/cjs/http-XNLYU2vS.cjs.map +0 -1
- package/cjs/migrations-DTTzCNpR.cjs.map +0 -1
- package/cjs/options-CHhmQJic.cjs +0 -193
- package/cjs/options-CHhmQJic.cjs.map +0 -1
- package/cjs/panels-CHd20RK5.cjs +0 -385
- package/cjs/panels-CHd20RK5.cjs.map +0 -1
- package/cjs/rolldown-runtime-Zuuoy_Rh.cjs +0 -52
- package/cjs/server-C8JfggQU.cjs.map +0 -1
- package/cjs/src-DjOUdhKc.cjs.map +0 -1
- package/cjs/stream-route-D4k-sJvW.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors-DEqdWaqm.cjs","names":["randomBytes"],"sources":["../../../../../../../packages/devtools/src/production/errors.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport type { DevtoolsApiErrorBody, DevtoolsErrorCode } from \"./contracts\";\n\n/**\n * Why production mode refused to start. Each code names one missing or\n * invalid setting; the message says which and how to fix it.\n */\nexport const DEVTOOLS_CONFIG_CODES = {\n DT001:\n \"Devtools production mode needs a dashboard path. Set DEVTOOLS_PATH (for example /ops-7f3k2q) or devtools.production.path.\",\n DT002:\n 'The devtools dashboard path must start with \"/\", be at least 8 characters, use only letters, digits, \"-\", \"_\", \".\", \"~\" and \"/\", and not be \"/__warlock\".',\n DT003:\n \"Devtools production mode has no admin yet. Set DEVTOOLS_ADMIN_EMAIL with DEVTOOLS_ADMIN_PASSWORD or DEVTOOLS_SETUP_TOKEN, or run `warlock devtools:reset-admin --email <email>`.\",\n DT004:\n \"DEVTOOLS_ADMIN_PASSWORD does not meet the password rules (at least 8 characters, at most 72 bytes, not a common password, not the email). Choose another one.\",\n DT005:\n \"Devtools production mode stores its accounts in the database. Install @warlock.js/cascade and configure a database connection.\",\n DT006:\n \"Devtools production mode encrypts two-factor secrets with the app key. Set encryption.key (64 hex characters) in src/config/encryption.ts.\",\n DT007:\n \"A devtools production option has an invalid value. The message names the option and the accepted values.\",\n DT008:\n \"The devtools tables are missing. Add devtoolsMigrations from @warlock.js/devtools/production to database.migrations in warlock.config.ts and run `warlock migrate`.\",\n DT009: \"Set either DEVTOOLS_ADMIN_PASSWORD or DEVTOOLS_SETUP_TOKEN, not both.\",\n DT010:\n \"DEVTOOLS_SETUP_TOKEN must be at least 32 characters. Generate one with: openssl rand -base64 32\",\n} as const;\n\n/** A production configuration error code (`DT001`–`DT010`). */\nexport type DevtoolsConfigCode = keyof typeof DEVTOOLS_CONFIG_CODES;\n\n/**\n * Thrown while the devtools connector boots in production when the monitor is\n * enabled but cannot start safely. It stops the app from booting, so a\n * misconfigured deploy fails at once instead of serving an unprotected\n * dashboard.\n */\nexport class DevtoolsProductionConfigError extends Error {\n public readonly code: DevtoolsConfigCode;\n\n public constructor(code: DevtoolsConfigCode, detail?: string) {\n super(`[${code}] ${detail ? `${detail} ` : \"\"}${DEVTOOLS_CONFIG_CODES[code]}`);\n this.name = \"DevtoolsProductionConfigError\";\n this.code = code;\n }\n}\n\n/** The message every API error code answers with: what failed and what to do next. */\nexport const DEVTOOLS_ERROR_MESSAGES: Record<DevtoolsErrorCode, string> = {\n \"auth.invalid-credentials\":\n \"The email or password is not correct. Check both and try again; after several failed tries, wait 15 minutes.\",\n \"auth.invalid-code\":\n \"The code is not correct or has expired. Enter the current 6-digit code from your authenticator app, or a recovery code.\",\n \"auth.invalid-setup-token\":\n \"This setup link is not valid. Use the link built from DEVTOOLS_SETUP_TOKEN, or run `warlock devtools:reset-admin`.\",\n \"auth.password-too-short\": \"Use a password of at least 8 characters.\",\n \"auth.password-too-long\": \"Use a password of at most 72 bytes (about 72 letters).\",\n \"auth.password-common\": \"This password is too common. Choose one that is harder to guess.\",\n \"auth.password-same-as-email\": \"The password must not be your email address. Choose another one.\",\n \"auth.password-unchanged\": \"Choose a new password that differs from the current one.\",\n \"auth.wrong-current-password\": \"The current password is not correct. Enter it again.\",\n \"auth.busy\": \"The server is busy checking other sign-ins. Wait a few seconds and try again.\",\n \"invite.invalid\":\n \"This invite link is not valid, was already used, or has expired. Ask an admin for a new one.\",\n \"invite.email-taken\": \"An account with this email already exists. Sign in instead.\",\n \"account.not-found\": \"This account no longer exists. Reload the list.\",\n \"account.last-admin\": \"This is the last admin. Make another account an admin first.\",\n \"account.self\": \"You cannot do this to your own account. Ask another admin.\",\n \"account.last-factor\":\n \"This is your only second factor. Add another one (an authenticator app or a passkey) before removing it.\",\n \"role.forbidden\": \"Only admins can do this. Ask an admin.\",\n \"csrf.invalid\": \"This page is out of date. Reload the dashboard and try again.\",\n \"passkey.unavailable\":\n \"Passkeys are not available on this server (the @simplewebauthn/server package is not installed). Use an authenticator app instead.\",\n \"passkey.failed\": \"The passkey could not be verified. Try again, or use your authenticator app.\",\n \"explain.not-allowed\": \"Only admins can run EXPLAIN. Ask an admin.\",\n \"explain.unsupported\":\n \"This query cannot be explained: only PostgreSQL SELECT/WITH queries and MongoDB find, aggregate and count commands can.\",\n \"explain.elsewhere\":\n \"Only the instance that ran this query can explain it, and this request reached another one. Try again later or from that instance.\",\n \"explain.failed\":\n \"The database could not explain this query. The reference is in the server log.\",\n \"request.not-found\":\n \"This request is no longer stored. Requests are kept for a limited time (24 hours by default).\",\n \"request.invalid-filter\": \"A filter value is not valid. Check the status, method and dates.\",\n \"share.not-found\": \"This share link no longer exists or is already revoked. Reload the list.\",\n \"stream.too-many\":\n \"Too many live views are open for this session. Close another dashboard tab and reload.\",\n \"input.invalid\": \"Some fields are missing or not valid. Check the form and try again.\",\n \"server.error\":\n \"The dashboard could not complete this action. Try again; if it keeps failing, give your admin the reference shown.\",\n};\n\n/** The HTTP status each code answers with. */\nexport const DEVTOOLS_ERROR_STATUS: Record<DevtoolsErrorCode, number> = {\n \"auth.invalid-credentials\": 401,\n \"auth.invalid-code\": 401,\n \"auth.invalid-setup-token\": 401,\n \"auth.password-too-short\": 422,\n \"auth.password-too-long\": 422,\n \"auth.password-common\": 422,\n \"auth.password-same-as-email\": 422,\n \"auth.password-unchanged\": 422,\n \"auth.wrong-current-password\": 401,\n \"auth.busy\": 503,\n \"invite.invalid\": 410,\n \"invite.email-taken\": 409,\n \"account.not-found\": 404,\n \"account.last-admin\": 409,\n \"account.self\": 409,\n \"account.last-factor\": 409,\n \"role.forbidden\": 403,\n \"csrf.invalid\": 403,\n \"passkey.unavailable\": 501,\n \"passkey.failed\": 401,\n \"explain.not-allowed\": 403,\n \"explain.unsupported\": 400,\n \"explain.elsewhere\": 409,\n \"explain.failed\": 502,\n \"request.not-found\": 404,\n \"request.invalid-filter\": 400,\n \"share.not-found\": 404,\n \"stream.too-many\": 429,\n \"input.invalid\": 422,\n \"server.error\": 500,\n};\n\n/** A short reference id (8 characters, base32 alphabet) to quote to support. */\nexport function createErrorRef(): string {\n const alphabet = \"ABCDEFGHJKMNPQRSTUVWXYZ23456789\";\n const bytes = randomBytes(8);\n let ref = \"\";\n\n for (const byte of bytes) ref += alphabet[byte % alphabet.length];\n\n return ref;\n}\n\n/**\n * An error a dashboard route answers with. The production error handler turns\n * it into `{ error, code, ref?, instance? }` with `statusCode`.\n */\nexport class DevtoolsApiError extends Error {\n public readonly code: DevtoolsErrorCode;\n public readonly statusCode: number;\n public readonly ref: string | undefined;\n public readonly instance: string | undefined;\n\n public constructor(\n code: DevtoolsErrorCode,\n options: { ref?: string; instance?: string; cause?: unknown } = {},\n ) {\n super(\n DEVTOOLS_ERROR_MESSAGES[code],\n options.cause === undefined ? {} : { cause: options.cause },\n );\n this.name = \"DevtoolsApiError\";\n this.code = code;\n this.statusCode = DEVTOOLS_ERROR_STATUS[code];\n this.ref = options.ref;\n this.instance = options.instance;\n }\n\n /** The JSON body this error answers with. */\n public toBody(): DevtoolsApiErrorBody {\n return {\n error: this.message,\n code: this.code,\n ...(this.ref === undefined ? {} : { ref: this.ref }),\n ...(this.instance === undefined ? {} : { instance: this.instance }),\n };\n }\n}\n\n/**\n * Raised by a store when a unique value is taken (an email) so callers can\n * answer with their own error code.\n */\nexport class DevtoolsStoreConflictError extends Error {\n public constructor(public readonly field: string) {\n super(`A devtools record with this ${field} already exists.`);\n this.name = \"DevtoolsStoreConflictError\";\n }\n}\n"],"mappings":";;;;;;;AAOA,MAAa,wBAAwB;CACnC,OACE;CACF,OACE;CACF,OACE;CACF,OACE;CACF,OACE;CACF,OACE;CACF,OACE;CACF,OACE;CACF,OAAO;CACP,OACE;AACJ;;;;;;;AAWA,IAAa,gCAAb,cAAmD,MAAM;CAGvD,AAAO,YAAY,MAA0B,QAAiB;EAC5D,MAAM,IAAI,KAAK,IAAI,SAAS,GAAG,OAAO,KAAK,KAAK,sBAAsB,OAAO;EAC7E,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;;AAGA,MAAa,0BAA6D;CACxE,4BACE;CACF,qBACE;CACF,4BACE;CACF,2BAA2B;CAC3B,0BAA0B;CAC1B,wBAAwB;CACxB,+BAA+B;CAC/B,2BAA2B;CAC3B,+BAA+B;CAC/B,aAAa;CACb,kBACE;CACF,sBAAsB;CACtB,qBAAqB;CACrB,sBAAsB;CACtB,gBAAgB;CAChB,uBACE;CACF,kBAAkB;CAClB,gBAAgB;CAChB,uBACE;CACF,kBAAkB;CAClB,uBAAuB;CACvB,uBACE;CACF,qBACE;CACF,kBACE;CACF,qBACE;CACF,0BAA0B;CAC1B,mBAAmB;CACnB,mBACE;CACF,iBAAiB;CACjB,gBACE;AACJ;;AAGA,MAAa,wBAA2D;CACtE,4BAA4B;CA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|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"http-XNLYU2vS.cjs","names":["normalizeIp","isIP","ipMatches","MAX_TOKEN","bodyOf","DevtoolsApiError","safeEqual","DevtoolsApiError","rateLimitClient","DEVTOOLS_FAILURE_AUDIT_TYPES","generateToken","hashToken","panelContentType","sendPanelFile","createHash","DevtoolsApiError","ipMatches","createErrorRef","DEVTOOLS_ERROR_MESSAGES","listPanelInfos","createHash"],"sources":["../../../../../../../packages/devtools/src/production/http/access.ts","../../../../../../../packages/devtools/src/production/http/client.ts","../../../../../../../packages/devtools/src/production/http/constants.ts","../../../../../../../packages/devtools/src/production/http/context.ts","../../../../../../../packages/devtools/src/production/http/cookie.ts","../../../../../../../packages/devtools/src/production/http/auth-routes.ts","../../../../../../../packages/devtools/src/production/http/headers.ts","../../../../../../../packages/devtools/src/production/http/share-session.ts","../../../../../../../packages/devtools/src/production/http/share.ts","../../../../../../../packages/devtools/src/production/http/mount.ts","../../../../../../../packages/devtools/src/production/http/state.ts"],"sourcesContent":["import type { DevtoolsRouteAccess, DevtoolsRouteAccessRule } from \"./types\";\n\ntype Method = DevtoolsRouteAccessRule[\"method\"];\n\nconst PUBLIC: DevtoolsRouteAccess = { type: \"public\" };\nconst VIEWER: DevtoolsRouteAccess = { type: \"viewer\" };\nconst ADMIN: DevtoolsRouteAccess = { type: \"admin\" };\nconst SHARE: DevtoolsRouteAccess = { type: \"share\" };\n\nconst pending = (...stages: Extract<DevtoolsRouteAccess, { type: \"pending\" }>[\"stages\"]) =>\n ({ type: \"pending\", stages }) satisfies DevtoolsRouteAccess;\n\nconst ALL_STEPS = [\"password-change\", \"mfa-enrol\", \"mfa-verify\"] as const;\n\n/**\n * The access table: every production route, its method and who may call it.\n * A route with no entry is `admin` (fail closed). A package panel `<id>`\n * gets `GET /api/<id>` and `GET /api/<id>/*` for viewers and every other\n * method there for admins, audited as `panel.action`; a url ending in `/*`\n * matches every pattern below it. The share routes exist only when\n * `options.share` is `true` (`production.share.enabled`).\n */\nexport function productionRouteAccess(\n panelIds: readonly string[],\n options: { share?: boolean } = {},\n): DevtoolsRouteAccessRule[] {\n const rule = (\n method: Method,\n url: string,\n access: DevtoolsRouteAccess,\n audit?: DevtoolsRouteAccessRule[\"audit\"],\n ): DevtoolsRouteAccessRule => ({ method, url, access, ...(audit ? { audit } : {}) });\n\n const rules: DevtoolsRouteAccessRule[] = [\n // The shell and its sign-in steps.\n rule(\"GET\", \"/\", PUBLIC),\n rule(\"GET\", \"/assets/:name\", PUBLIC),\n rule(\"GET\", \"/api/auth/session\", PUBLIC),\n rule(\"POST\", \"/api/auth/login\", PUBLIC),\n rule(\"POST\", \"/api/auth/setup\", PUBLIC),\n rule(\"POST\", \"/api/auth/invite/inspect\", PUBLIC),\n rule(\"POST\", \"/api/auth/invite/accept\", PUBLIC),\n rule(\"POST\", \"/api/auth/password\", pending(\"password-change\")),\n rule(\"POST\", \"/api/auth/totp/start\", pending(\"mfa-enrol\")),\n rule(\"POST\", \"/api/auth/totp/confirm\", pending(\"mfa-enrol\")),\n rule(\"POST\", \"/api/auth/passkey/options\", pending(\"mfa-enrol\", \"mfa-verify\")),\n rule(\"POST\", \"/api/auth/passkey/verify\", pending(\"mfa-enrol\", \"mfa-verify\")),\n rule(\"POST\", \"/api/auth/mfa\", pending(\"mfa-verify\")),\n rule(\"POST\", \"/api/auth/logout\", pending(...ALL_STEPS)),\n\n // The signed-in account.\n rule(\"GET\", \"/api/panels\", VIEWER),\n rule(\"GET\", \"/api/account\", VIEWER),\n rule(\"GET\", \"/api/account/sessions\", VIEWER),\n rule(\"DELETE\", \"/api/account/sessions/:id\", VIEWER),\n rule(\"POST\", \"/api/account/password\", VIEWER),\n rule(\"POST\", \"/api/account/totp/start\", VIEWER),\n rule(\"POST\", \"/api/account/totp/confirm\", VIEWER),\n rule(\"DELETE\", \"/api/account/totp\", VIEWER),\n rule(\"POST\", \"/api/account/recovery-codes\", VIEWER),\n rule(\"POST\", \"/api/account/passkey/options\", VIEWER),\n rule(\"POST\", \"/api/account/passkey/verify\", VIEWER),\n rule(\"DELETE\", \"/api/account/passkeys/:id\", VIEWER),\n\n // Administration.\n rule(\"GET\", \"/api/admin/users\", ADMIN),\n rule(\"POST\", \"/api/admin/invites\", ADMIN),\n rule(\"DELETE\", \"/api/admin/invites/:id\", ADMIN),\n rule(\"PATCH\", \"/api/admin/users/:id\", ADMIN),\n rule(\"DELETE\", \"/api/admin/users/:id\", ADMIN),\n rule(\"POST\", \"/api/admin/users/:id/reset-mfa\", ADMIN),\n rule(\"POST\", \"/api/admin/users/:id/sign-out\", ADMIN),\n rule(\"GET\", \"/api/admin/audit\", ADMIN),\n rule(\"POST\", \"/api/admin/disable\", ADMIN),\n\n // Data.\n rule(\"GET\", \"/api/stream\", VIEWER),\n rule(\"GET\", \"/api/instances\", VIEWER),\n rule(\"GET\", \"/api/resources\", VIEWER),\n rule(\"GET\", \"/api/queries/stats\", VIEWER),\n rule(\"GET\", \"/api/routes/stats\", VIEWER),\n rule(\"GET\", \"/api/health\", VIEWER),\n rule(\"GET\", \"/api/errors\", VIEWER),\n rule(\"GET\", \"/api/jobs\", VIEWER),\n rule(\"GET\", \"/api/logs\", VIEWER),\n rule(\"GET\", \"/api/requests\", VIEWER),\n rule(\"GET\", \"/api/requests/:id\", VIEWER),\n rule(\"GET\", \"/api/requests/:id/curl\", VIEWER),\n rule(\"DELETE\", \"/api/requests\", ADMIN, \"requests.cleared\"),\n rule(\"POST\", \"/api/queries/:shapeId/explain\", ADMIN, \"explain.run\"),\n rule(\"GET\", \"/api/routes\", VIEWER),\n rule(\"GET\", \"/panels/:id/:name\", VIEWER),\n rule(\"GET\", \"/panels/:id/files/*\", VIEWER),\n\n // Tabs that are off unless the project turns them on.\n rule(\"GET\", \"/api/mails\", VIEWER),\n rule(\"GET\", \"/api/mails/:id\", VIEWER),\n rule(\"GET\", \"/api/mails/:id/html\", VIEWER),\n rule(\"GET\", \"/api/ai\", VIEWER),\n rule(\"GET\", \"/api/ai/agent-runs\", VIEWER),\n rule(\"GET\", \"/api/ai/agent-runs/:id\", VIEWER),\n rule(\"GET\", \"/api/ai/runs/:id\", VIEWER),\n rule(\"GET\", \"/api/openapi.json\", VIEWER),\n rule(\"GET\", \"/api/postman.json\", VIEWER),\n rule(\"GET\", \"/docs\", VIEWER),\n rule(\"GET\", \"/docs/swagger\", VIEWER),\n ];\n\n if (options.share === true) {\n rules.push(\n // The grant exchange: public, answered only for a valid token.\n rule(\"POST\", \"/api/share/open\", PUBLIC),\n // What a share grant may reach.\n rule(\"GET\", \"/api/share/info\", SHARE),\n rule(\"GET\", \"/api/share/view.js\", SHARE),\n rule(\"GET\", \"/api/share/assets/:name\", SHARE),\n rule(\"GET\", \"/api/share/files/*\", SHARE),\n rule(\"GET\", \"/api/share/panel\", SHARE),\n rule(\"GET\", \"/api/share/panel/*\", SHARE),\n // Managing the links.\n rule(\"GET\", \"/api/admin/shares\", ADMIN),\n rule(\"POST\", \"/api/admin/shares\", ADMIN),\n rule(\"DELETE\", \"/api/admin/shares/:id\", ADMIN),\n rule(\"POST\", \"/api/admin/shares/revoke-all\", ADMIN),\n );\n }\n\n for (const id of panelIds) {\n rules.push(rule(\"GET\", `/api/${id}`, VIEWER), rule(\"GET\", `/api/${id}/*`, VIEWER));\n\n for (const method of [\"POST\", \"PUT\", \"PATCH\", \"DELETE\"] as const) {\n rules.push(\n rule(method, `/api/${id}`, ADMIN, \"panel.action\"),\n rule(method, `/api/${id}/*`, ADMIN, \"panel.action\"),\n );\n }\n }\n\n return rules;\n}\n\n/** Looks routes up by method and URL pattern: exact first, then the longest `/*` prefix. */\nexport function createAccessLookup(\n rules: readonly DevtoolsRouteAccessRule[],\n): (method: string, pattern: string) => DevtoolsRouteAccessRule | undefined {\n const exact = new Map<string, DevtoolsRouteAccessRule>();\n const wildcards: { method: Method; prefix: string; rule: DevtoolsRouteAccessRule }[] = [];\n\n for (const rule of rules) {\n if (rule.url.endsWith(\"/*\")) {\n wildcards.push({ method: rule.method, prefix: rule.url.slice(0, -1), rule });\n } else {\n exact.set(`${rule.method} ${rule.url}`, rule);\n }\n }\n\n wildcards.sort((a, b) => b.prefix.length - a.prefix.length);\n\n return (method, pattern) => {\n // A HEAD request is answered by the GET route.\n const verb = method === \"HEAD\" ? \"GET\" : method;\n const found = exact.get(`${verb} ${pattern}`);\n\n if (found) return found;\n\n return wildcards.find((item) => item.method === verb && pattern.startsWith(item.prefix))?.rule;\n };\n}\n","import { isIP } from \"node:net\";\nimport type { DevtoolsClientInfo, DevtoolsProxyRequest } from \"./types\";\nimport { ipMatches, normalizeIp } from \"./ip\";\n\n/** The first value of a header that may repeat or hold a comma list. */\nfunction firstValue(value: string | string[] | undefined): string | undefined {\n const text = Array.isArray(value) ? value[0] : value;\n const first = text?.split(\",\")[0]?.trim();\n\n return first === undefined || first === \"\" ? undefined : first;\n}\n\n/** The host name of a `Host` value: no port, lower case, brackets of an IPv6 literal kept. */\nfunction hostnameOf(host: string): string {\n const value = host.trim().toLowerCase();\n\n if (value.startsWith(\"[\")) {\n const end = value.indexOf(\"]\");\n\n return end === -1 ? value : value.slice(0, end + 1);\n }\n\n const colon = value.indexOf(\":\");\n\n return colon === -1 ? value : value.slice(0, colon);\n}\n\n/** The client address out of an `X-Forwarded-For` value, walking right to left past trusted hops. */\nfunction forwardedClient(\n header: string | string[] | undefined,\n trusted: readonly string[],\n): string | undefined {\n const text = Array.isArray(header) ? header.join(\",\") : header;\n const hops = (text ?? \"\")\n .split(\",\")\n .map((hop) => normalizeIp(hop.trim().replace(/^\\[|\\]$/g, \"\")))\n .filter((hop) => isIP(hop) !== 0);\n\n for (let index = hops.length - 1; index >= 0; index -= 1) {\n const hop = hops[index];\n\n if (hop !== undefined && !ipMatches(hop, trusted)) return hop;\n }\n\n // Every hop is a trusted proxy: the leftmost is the origin of the chain.\n return hops[0];\n}\n\n/**\n * The client IP, protocol and host. Forwarding headers are read only when the\n * socket peer is a trusted proxy; `X-Forwarded-For` is walked right to left,\n * skipping trusted addresses, and the first untrusted one is the client.\n */\nexport function resolveClient(\n request: DevtoolsProxyRequest,\n trustedProxies: readonly string[],\n): DevtoolsClientInfo {\n const peer = normalizeIp(request.socket.remoteAddress ?? \"\");\n const headers = request.headers;\n let ip = peer;\n let proto = request.socket.encrypted === true ? \"https\" : \"http\";\n let host = firstValue(headers.host) ?? \"\";\n\n if (peer !== \"\" && ipMatches(peer, trustedProxies)) {\n ip = forwardedClient(headers[\"x-forwarded-for\"], trustedProxies) ?? peer;\n\n const forwardedProto = firstValue(headers[\"x-forwarded-proto\"])?.toLowerCase();\n\n if (forwardedProto === \"http\" || forwardedProto === \"https\") proto = forwardedProto;\n\n host = firstValue(headers[\"x-forwarded-host\"]) ?? host;\n }\n\n host = host.toLowerCase();\n\n return { ip, proto, hostname: hostnameOf(host), host };\n}\n","/** The header the dashboard sends the CSRF token in. */\nexport const DEVTOOLS_CSRF_HEADER = \"x-devtools-csrf\";\n\n/** The session cookie name over HTTPS (`__Secure-` makes browsers refuse it over plain HTTP). */\nexport const DEVTOOLS_SESSION_COOKIE = \"__Secure-warlock-devtools\";\n\n/** The session cookie name when `requireHttps` is off (local trials only). */\nexport const DEVTOOLS_SESSION_COOKIE_INSECURE = \"warlock-devtools\";\n\n/** The share cookie name over HTTPS. */\nexport const DEVTOOLS_SHARE_COOKIE = \"__Secure-warlock-devtools-share\";\n\n/** The share cookie name when `requireHttps` is off (local trials only). */\nexport const DEVTOOLS_SHARE_COOKIE_INSECURE = \"warlock-devtools-share\";\n\n/** The longest a share cookie lives, whatever the link's expiry: 12 hours. */\nexport const DEVTOOLS_SHARE_COOKIE_MAX_SECONDS = 12 * 3600;\n","import type { FastifyRequest } from \"fastify\";\nimport type { DevtoolsAuthenticated, DevtoolsRequestMeta } from \"../auth/types\";\nimport type { DevtoolsShareGrant } from \"./share-session\";\nimport type { DevtoolsClientInfo, DevtoolsRouteAccessRule } from \"./types\";\n\n/** What the gate learned about a dashboard request, for the handlers that follow. */\nexport type DevtoolsRequestContext = {\n client: DevtoolsClientInfo;\n meta: DevtoolsRequestMeta;\n /** The access rule the route matched; `undefined` for a route with no entry (treated as admin). */\n rule: DevtoolsRouteAccessRule | undefined;\n /** The route pattern relative to the dashboard path (`/api/requests/:id`). */\n pattern: string;\n /** The session, for every route that is not public. */\n authenticated: DevtoolsAuthenticated | null;\n /** The share grant, for a request that passed the `share` access check. */\n share?: DevtoolsShareGrant | null;\n};\n\nconst contexts = new WeakMap<FastifyRequest, DevtoolsRequestContext>();\n\n/** Stores the context of `request` (the gate calls this). */\nexport function setDevtoolsRequestContext(\n request: FastifyRequest,\n context: DevtoolsRequestContext,\n): void {\n contexts.set(request, context);\n}\n\n/** The context the gate stored for `request`, or `undefined` outside the production dashboard. */\nexport function devtoolsRequestContext(\n request: FastifyRequest,\n): DevtoolsRequestContext | undefined {\n return contexts.get(request);\n}\n","import {\n DEVTOOLS_SESSION_COOKIE,\n DEVTOOLS_SESSION_COOKIE_INSECURE,\n DEVTOOLS_SHARE_COOKIE,\n DEVTOOLS_SHARE_COOKIE_INSECURE,\n} from \"./constants\";\n\n/** The cookie name for the HTTPS mode. */\nexport function sessionCookieName(secure: boolean): string {\n return secure ? DEVTOOLS_SESSION_COOKIE : DEVTOOLS_SESSION_COOKIE_INSECURE;\n}\n\n/**\n * `Set-Cookie` value for a session token (or a clearing cookie when `token`\n * is `null`). The cookie is a browser-session cookie scoped to the dashboard\n * path, `HttpOnly` and `SameSite=Strict`, with no `Domain`.\n */\nexport function sessionCookie(\n token: string | null,\n options: { path: string; secure: boolean },\n): string {\n const parts = [\n `${sessionCookieName(options.secure)}=${token ?? \"\"}`,\n `Path=${options.path}`,\n \"HttpOnly\",\n \"SameSite=Strict\",\n ];\n\n if (options.secure) parts.push(\"Secure\");\n\n if (token === null) parts.push(\"Max-Age=0\", \"Expires=Thu, 01 Jan 1970 00:00:00 GMT\");\n\n return parts.join(\"; \");\n}\n\n/** The value of cookie `name` in a `Cookie` header, or `undefined`. */\nexport function readCookie(header: string | undefined, name: string): string | undefined {\n if (!header) return undefined;\n\n for (const pair of header.split(\";\")) {\n const equals = pair.indexOf(\"=\");\n\n if (equals === -1) continue;\n\n if (pair.slice(0, equals).trim() === name) {\n const value = pair.slice(equals + 1).trim();\n\n return value === \"\" ? undefined : value;\n }\n }\n\n return undefined;\n}\n\n/** The share cookie name for the HTTPS mode. */\nexport function shareCookieName(secure: boolean): string {\n return secure ? DEVTOOLS_SHARE_COOKIE : DEVTOOLS_SHARE_COOKIE_INSECURE;\n}\n\n/**\n * `Set-Cookie` value for a share grant (or a clearing cookie when `value` is\n * `null`). Scoped to the dashboard path, `HttpOnly`, `SameSite=Strict`, no\n * `Domain`, and it ends after `maxAgeSeconds`.\n */\nexport function shareCookie(\n value: string | null,\n options: { path: string; secure: boolean; maxAgeSeconds?: number },\n): string {\n const parts = [\n `${shareCookieName(options.secure)}=${value ?? \"\"}`,\n `Path=${options.path}`,\n \"HttpOnly\",\n \"SameSite=Strict\",\n ];\n\n if (options.secure) parts.push(\"Secure\");\n\n if (value === null) parts.push(\"Max-Age=0\", \"Expires=Thu, 01 Jan 1970 00:00:00 GMT\");\n else parts.push(`Max-Age=${Math.max(1, Math.floor(options.maxAgeSeconds ?? 0))}`);\n\n return parts.join(\"; \");\n}\n","import type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { DevtoolsAuthenticated, DevtoolsAuthStep, DevtoolsRequestMeta } from \"../auth/types\";\nimport type { DevtoolsAuditType, DevtoolsAuthStepResult, DevtoolsRole } from \"../contracts\";\nimport { DevtoolsApiError } from \"../errors\";\nimport { readCookie, sessionCookie, sessionCookieName } from \"./cookie\";\nimport { devtoolsRequestContext } from \"./context\";\nimport type { MountProductionDevtoolsDeps } from \"./types\";\n\nconst MAX_TEXT = 1024;\nconst MAX_EMAIL = 320;\nconst MAX_CODE = 128;\nconst MAX_TOKEN = 512;\nconst ROLES: readonly DevtoolsRole[] = [\"admin\", \"viewer\"];\n\n/** A request body that is a plain JSON object, or `input.invalid`. */\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\n/** A non-empty string field no longer than `max`, or `input.invalid`. */\nfunction text(body: Record<string, unknown>, key: string, max = MAX_TEXT): string {\n const value = body[key];\n\n if (typeof value !== \"string\" || value === \"\" || value.length > max) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return value;\n}\n\n/** An optional string field; `undefined` when absent, `input.invalid` when present but wrong. */\nfunction optionalText(\n body: Record<string, unknown>,\n key: string,\n max = MAX_TEXT,\n): string | undefined {\n return body[key] === undefined ? undefined : text(body, key, max);\n}\n\nfunction email(body: Record<string, unknown>): string {\n const value = text(body, \"email\", MAX_EMAIL).trim().toLowerCase();\n\n if (!/^[^\\s@]+@[^\\s@]+$/.test(value)) throw new DevtoolsApiError(\"input.invalid\");\n\n return value;\n}\n\nfunction role(body: Record<string, unknown>): DevtoolsRole {\n const value = body.role;\n\n if (typeof value !== \"string\" || !ROLES.includes(value as DevtoolsRole)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return value as DevtoolsRole;\n}\n\nfunction purpose(body: Record<string, unknown>): \"register\" | \"login\" {\n const value = body.purpose;\n\n if (value !== \"register\" && value !== \"login\") throw new DevtoolsApiError(\"input.invalid\");\n\n return value;\n}\n\nfunction idParam(request: FastifyRequest): string {\n const { id } = (request.params ?? {}) as { id?: unknown };\n\n if (typeof id !== \"string\" || id === \"\" || id.length > MAX_CODE) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return id;\n}\n\n/** The `current` password of a request that may have no body (a DELETE). */\nfunction currentOf(request: FastifyRequest): string | undefined {\n return request.body === undefined || request.body === null\n ? undefined\n : optionalText(bodyOf(request), \"current\");\n}\n\n/** What the gate stored, for a route that is never reached without it. */\nfunction contextOf(request: FastifyRequest): {\n meta: DevtoolsRequestMeta;\n auth: DevtoolsAuthenticated;\n} {\n const context = devtoolsRequestContext(request);\n\n if (!context?.authenticated) throw new Error(\"A dashboard route ran without its session.\");\n\n return { meta: context.meta, auth: context.authenticated };\n}\n\nfunction metaOf(request: FastifyRequest): DevtoolsRequestMeta {\n const context = devtoolsRequestContext(request);\n\n if (!context) throw new Error(\"A dashboard route ran without its request context.\");\n\n return context.meta;\n}\n\n/**\n * Registers the sign-in, account and admin routes. All decisions live in the\n * auth service; the handlers read the body, call it and answer. The gate\n * (`mountProductionDevtools`) has already checked the session, role, origin\n * and CSRF token by the time a handler runs.\n */\nexport function registerAuthRoutes(\n server: FastifyInstance,\n deps: MountProductionDevtoolsDeps,\n): void {\n const { auth, store, state, production } = deps;\n const cookieOptions = { path: production.path, secure: production.requireHttps };\n\n /** Sets the new session cookie when the step minted one; answers the step. */\n const answerStep = (\n reply: FastifyReply,\n step: DevtoolsAuthStep,\n recoveryCodes?: string[] | null,\n ): DevtoolsAuthStepResult & { recoveryCodes?: string[] } => {\n if (step.token !== null) reply.header(\"set-cookie\", sessionCookie(step.token, cookieOptions));\n\n return {\n stage: step.stage,\n csrf: step.csrf,\n ...(recoveryCodes ? { recoveryCodes } : {}),\n };\n };\n\n /** The stage and CSRF token of the session in force, for answers that do not change it. */\n const currentStep = (authenticated: DevtoolsAuthenticated): DevtoolsAuthStepResult => ({\n stage: authenticated.stage,\n csrf: auth.csrfToken(authenticated.session),\n });\n\n const clearCookie = (reply: FastifyReply): void => {\n reply.header(\"set-cookie\", sessionCookie(null, cookieOptions));\n };\n\n const requireAdmin = (authenticated: DevtoolsAuthenticated): void => {\n if (authenticated.account.role !== \"admin\" || authenticated.stage !== \"active\") {\n throw new DevtoolsApiError(\"role.forbidden\");\n }\n };\n\n // ---- Public ------------------------------------------------------------\n\n server.get(\"/api/auth/session\", async (request, reply) => {\n const token = readCookie(request.headers.cookie, sessionCookieName(production.requireHttps));\n const authenticated = token === undefined ? null : await auth.authenticate(token);\n\n // A cookie that no longer matches a session is dead weight: clear it.\n if (token !== undefined && authenticated === null) clearCookie(reply);\n\n return auth.sessionView(authenticated);\n });\n\n server.post(\"/api/auth/login\", async (request, reply) => {\n const body = bodyOf(request);\n const step = await auth.login(\n { email: email(body), password: text(body, \"password\") },\n metaOf(request),\n );\n\n return answerStep(reply, step);\n });\n\n server.post(\"/api/auth/setup\", async (request, reply) => {\n const body = bodyOf(request);\n const step = await auth.setup(\n { token: text(body, \"token\", MAX_TOKEN), password: text(body, \"password\") },\n metaOf(request),\n );\n\n return answerStep(reply, step);\n });\n\n server.post(\"/api/auth/invite/inspect\", async (request) => {\n const body = bodyOf(request);\n\n return auth.inspectInvite(text(body, \"token\", MAX_TOKEN));\n });\n\n server.post(\"/api/auth/invite/accept\", async (request, reply) => {\n const body = bodyOf(request);\n const step = await auth.acceptInvite(\n { token: text(body, \"token\", MAX_TOKEN), password: text(body, \"password\") },\n metaOf(request),\n );\n\n return answerStep(reply, step);\n });\n\n // ---- Sign-in steps and the account (a session is required) --------------\n\n const changePassword = async (request: FastifyRequest, reply: FastifyReply) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n const current = optionalText(body, \"current\");\n const step = await auth.changePassword(\n authenticated,\n { ...(current === undefined ? {} : { current }), password: text(body, \"password\") },\n meta,\n );\n\n return answerStep(reply, step);\n };\n\n const startTotp = async (request: FastifyRequest) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n return auth.startTotp(authenticated, meta);\n };\n\n const confirmTotp = async (request: FastifyRequest, reply: FastifyReply) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n const result = await auth.confirmTotp(\n authenticated,\n text(body, \"code\", MAX_CODE),\n meta,\n optionalText(body, \"current\"),\n );\n\n return answerStep(reply, result.step, result.recoveryCodes);\n };\n\n const passkeyOptions = async (request: FastifyRequest) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n return auth.passkeyOptions(authenticated, purpose(bodyOf(request)), meta);\n };\n\n const passkeyVerify = async (request: FastifyRequest, reply: FastifyReply) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n\n if (body.response === null || typeof body.response !== \"object\") {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const result = await auth.verifyPasskey(\n authenticated,\n purpose(body),\n body.response,\n meta,\n optionalText(body, \"current\"),\n );\n\n if (result.step === null) {\n return {\n ...currentStep(authenticated),\n ...(result.recoveryCodes ? { recoveryCodes: result.recoveryCodes } : {}),\n };\n }\n\n return answerStep(reply, result.step, result.recoveryCodes);\n };\n\n server.post(\"/api/auth/password\", changePassword);\n server.post(\"/api/auth/totp/start\", startTotp);\n server.post(\"/api/auth/totp/confirm\", confirmTotp);\n server.post(\"/api/auth/passkey/options\", passkeyOptions);\n server.post(\"/api/auth/passkey/verify\", passkeyVerify);\n\n server.post(\"/api/auth/mfa\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n const code = optionalText(body, \"code\", MAX_CODE);\n const recoveryCode = optionalText(body, \"recoveryCode\", MAX_CODE);\n\n if ((code === undefined) === (recoveryCode === undefined)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const step = await auth.verifySecondFactor(\n authenticated,\n code === undefined ? { recoveryCode: recoveryCode as string } : { code },\n meta,\n );\n\n return answerStep(reply, step);\n });\n\n server.post(\"/api/auth/logout\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.logout(authenticated, meta);\n clearCookie(reply);\n\n return reply.code(204).send();\n });\n\n server.get(\"/api/account\", async (request) => {\n const { auth: authenticated } = contextOf(request);\n\n return auth.accountView(authenticated.account);\n });\n\n server.get(\"/api/account/sessions\", async (request) => {\n const { auth: authenticated } = contextOf(request);\n\n return auth.listSessions(authenticated);\n });\n\n server.delete(\"/api/account/sessions/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.revokeSession(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/account/password\", changePassword);\n server.post(\"/api/account/totp/start\", startTotp);\n server.post(\"/api/account/totp/confirm\", confirmTotp);\n\n server.delete(\"/api/account/totp\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.removeTotp(authenticated, meta, currentOf(request));\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/account/recovery-codes\", async (request) => {\n const { auth: authenticated, meta } = contextOf(request);\n // No code: a passkey step-up in this session stands in for it.\n const codes = await auth.regenerateRecoveryCodes(\n authenticated,\n optionalText(bodyOf(request), \"code\", MAX_CODE) ?? \"\",\n meta,\n );\n\n return { codes };\n });\n\n server.post(\"/api/account/passkey/options\", passkeyOptions);\n server.post(\"/api/account/passkey/verify\", passkeyVerify);\n\n server.delete(\"/api/account/passkeys/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.removePasskey(authenticated, idParam(request), meta, currentOf(request));\n\n return reply.code(204).send();\n });\n\n // ---- Admin ---------------------------------------------------------------\n\n server.get(\"/api/admin/users\", async (request) => {\n const { auth: authenticated } = contextOf(request);\n\n return auth.listUsers(authenticated);\n });\n\n server.post(\"/api/admin/invites\", async (request) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n\n return auth.createInvite(authenticated, { email: email(body), role: role(body) }, meta);\n });\n\n server.delete(\"/api/admin/invites/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.revokeInvite(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.patch(\"/api/admin/users/:id\", async (request) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n return auth.setRole(authenticated, idParam(request), role(bodyOf(request)), meta);\n });\n\n server.delete(\"/api/admin/users/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.removeAccount(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/admin/users/:id/reset-mfa\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.resetSecondFactor(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/admin/users/:id/sign-out\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.signOutAccount(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.get<{ Querystring: Record<string, string | undefined> }>(\n \"/api/admin/audit\",\n async (request) => {\n const { auth: authenticated } = contextOf(request);\n\n requireAdmin(authenticated);\n\n const query = request.query;\n const types = query.type\n ?.split(\",\")\n .map((type) => type.trim())\n .filter((type) => type !== \"\");\n const before = query.before === undefined ? undefined : Number(query.before);\n const limit = query.limit === undefined ? 100 : Number(query.limit);\n\n if (\n (before !== undefined && !Number.isFinite(before)) ||\n !Number.isInteger(limit) ||\n limit < 1\n ) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return store.audit.list({\n ...(types && types.length > 0 ? { types: types as DevtoolsAuditType[] } : {}),\n ...(query.account ? { accountId: query.account } : {}),\n ...(before === undefined ? {} : { before }),\n limit: Math.min(limit, 500),\n });\n },\n );\n\n server.post(\"/api/admin/disable\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n if (bodyOf(request).confirm !== \"disable\") throw new DevtoolsApiError(\"input.invalid\");\n\n await auth.disableDashboard(authenticated, meta);\n // This process closes at once; the others within the state cache time.\n state.invalidate();\n\n return reply.code(204).send();\n });\n}\n","/** Headers on every dashboard answer that is not the uniform 404. */\nexport const DASHBOARD_HEADERS: Readonly<Record<string, string>> = {\n \"Cache-Control\": \"no-store\",\n \"X-Robots-Tag\": \"noindex, nofollow, noarchive\",\n \"Referrer-Policy\": \"no-referrer\",\n \"X-Content-Type-Options\": \"nosniff\",\n \"X-Frame-Options\": \"DENY\",\n \"Cross-Origin-Opener-Policy\": \"same-origin\",\n \"Cross-Origin-Resource-Policy\": \"same-origin\",\n \"Permissions-Policy\":\n \"camera=(), microphone=(), geolocation=(), publickey-credentials-get=(self), publickey-credentials-create=(self)\",\n};\n\n/** The policy of the dashboard's own HTML: scripts and styles from the bundle only. */\nexport const DASHBOARD_CSP =\n \"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'; object-src 'none'\";\n\n/**\n * The policy of the opt-in API documentation pages: scripts from the dashboard\n * only (Scalar and Swagger UI probe `Function` in a try/catch and work without\n * `'unsafe-eval'`), inline styles, and framing by the dashboard itself, whose\n * API tab shows them in a frame.\n */\nexport const DOCS_CSP =\n \"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'self'; base-uri 'none'; form-action 'self'; object-src 'none'\";\n","import type { MountedDevtoolsPanel } from \"../../panels\";\nimport { safeEqual } from \"../auth/helpers\";\nimport type { DevtoolsShareRecord, DevtoolsStore } from \"../store/types\";\nimport { DEVTOOLS_SHARE_COOKIE_MAX_SECONDS } from \"./constants\";\n\n/** How long a read of a share record is reused. A revoke reaches every instance within this time. */\nexport const SHARE_CACHE_MS = 5000;\n\n/** Records kept in the cache of one process (oldest evicted). */\nconst SHARE_CACHE_SIZE = 500;\n\n/** A link's use is written at most this often per link and process. */\nconst TOUCH_INTERVAL_MS = 60_000;\n\n/** What a valid share cookie grants: the link and the panel it opens. */\nexport type DevtoolsShareGrant = {\n share: DevtoolsShareRecord;\n panel: MountedDevtoolsPanel;\n};\n\n/** Why a share cookie or token was refused (written to the audit log; never the value). */\nexport type DevtoolsShareRefusal = \"unknown\" | \"expired\" | \"revoked\" | \"panel\" | \"cookie\";\n\nexport type DevtoolsShareSessions = {\n /** The cookie value for `share`: `<id>.<exp>.<hmac>`, and its life in seconds. */\n issue(share: DevtoolsShareRecord): { value: string; maxAgeSeconds: number };\n /** The grant a `Cookie` value carries, or the reason it was refused. */\n verify(value: string | undefined): Promise<\n { grant: DevtoolsShareGrant } | { refused: DevtoolsShareRefusal; shareId: string | null }\n >;\n /** The record a token hash names, checked for life and panel; or the reason it is refused. */\n open(tokenHash: string): Promise<\n { grant: DevtoolsShareGrant } | { refused: DevtoolsShareRefusal; shareId: string | null }\n >;\n /** Counts one use of `share` (at most once a minute per link). */\n touch(shareId: string): void;\n /** Forgets cached records (after this process revoked or created a link). */\n invalidate(): void;\n};\n\n/**\n * The share grant: a cookie carrying `<shareId>.<exp>.<HMAC-SHA256(key,\n * \"share:<id>:<exp>\")>`. The signature proves this server issued it; the\n * link's record, read through a 5-second cache, proves it is still alive, so\n * a revoke takes effect everywhere within that time without a session table.\n */\nexport function createShareSessions(input: {\n store: DevtoolsStore;\n panels: readonly MountedDevtoolsPanel[];\n hmac: (value: string) => string;\n now?: () => number;\n warn?: (message: string) => void;\n}): DevtoolsShareSessions {\n const { store, hmac } = input;\n const now = input.now ?? (() => Date.now());\n const panels = new Map(\n input.panels.filter((panel) => panel.share !== null).map((panel) => [panel.id, panel]),\n );\n const cache = new Map<string, { record: DevtoolsShareRecord | null; at: number }>();\n const touched = new Map<string, number>();\n\n const sign = (id: string, exp: number): string => hmac(`share:${id}:${exp}`);\n\n async function record(id: string): Promise<DevtoolsShareRecord | null> {\n const cached = cache.get(id);\n\n if (cached && now() - cached.at < SHARE_CACHE_MS) return cached.record;\n\n const found = await store.shares.get(id);\n\n cache.delete(id);\n\n if (cache.size >= SHARE_CACHE_SIZE) {\n const oldest = cache.keys().next();\n\n if (!oldest.done) cache.delete(oldest.value);\n }\n\n cache.set(id, { record: found, at: now() });\n\n return found;\n }\n\n function grantFor(share: DevtoolsShareRecord):\n | { grant: DevtoolsShareGrant }\n | { refused: DevtoolsShareRefusal; shareId: string } {\n if (share.revokedAt !== null) return { refused: \"revoked\", shareId: share.id };\n\n if (share.expiresAt <= now()) return { refused: \"expired\", shareId: share.id };\n\n const panel = panels.get(share.panel);\n\n return panel ? { grant: { share, panel } } : { refused: \"panel\", shareId: share.id };\n }\n\n return {\n issue(share) {\n const remaining = Math.floor((share.expiresAt - now()) / 1000);\n const maxAgeSeconds = Math.max(1, Math.min(remaining, DEVTOOLS_SHARE_COOKIE_MAX_SECONDS));\n const exp = now() + maxAgeSeconds * 1000;\n\n return { value: `${share.id}.${exp}.${sign(share.id, exp)}`, maxAgeSeconds };\n },\n\n async verify(value) {\n const parts = (value ?? \"\").split(\".\");\n const [id, expText, signature] = parts;\n\n if (parts.length !== 3 || !id || !expText || !signature || !/^\\d{1,16}$/.test(expText)) {\n return { refused: \"cookie\", shareId: null };\n }\n\n const exp = Number(expText);\n\n if (!safeEqual(signature, sign(id, exp)) || exp <= now()) {\n return { refused: \"cookie\", shareId: null };\n }\n\n const share = await record(id);\n\n return share ? grantFor(share) : { refused: \"unknown\", shareId: id };\n },\n\n async open(tokenHash) {\n const share = await store.shares.findByTokenHash(tokenHash);\n\n return share ? grantFor(share) : { refused: \"unknown\", shareId: null };\n },\n\n touch(shareId) {\n const at = now();\n const last = touched.get(shareId);\n\n if (last !== undefined && at - last < TOUCH_INTERVAL_MS) return;\n\n touched.delete(shareId);\n\n if (touched.size >= SHARE_CACHE_SIZE) {\n const oldest = touched.keys().next();\n\n if (!oldest.done) touched.delete(oldest.value);\n }\n\n touched.set(shareId, at);\n // A failed write is not worth failing the request for.\n void store.shares.touch(shareId, at).catch((error: unknown) => {\n input.warn?.(\n `devtools could not record a share link use: ${error instanceof Error ? error.message : String(error)}`,\n );\n });\n },\n\n invalidate() {\n cache.clear();\n },\n };\n}\n","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","import { createHash } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { listPanelInfos } from \"../../panels\";\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\", \"ai\"],\n [\"/api/openapi.json\", \"api\"],\n [\"/api/postman.json\", \"api\"],\n [\"/docs\", \"api\"],\n];\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 (enabledTabs.has(\"api\")) registerOpenApiRoutes(instance, routes);\n\n registerStreamRoute(instance, routes);\n },\n { prefix },\n );\n}\n","import { createHash } from \"node:crypto\";\nimport type { DevtoolsStore } from \"../store/types\";\nimport type { DevtoolsDashboardState } from \"./types\";\n\n/** SHA-256 hex of a dashboard path: what `disabledPathHash` holds. */\nexport function hashDashboardPath(path: string): string {\n return createHash(\"sha256\").update(path).digest(\"hex\");\n}\n\n/**\n * The open/closed state with a `ttlMs` cache (default 5000). Open means the\n * dashboard is not disabled for this path and not locked. A failed read is\n * not cached and rejects, so the caller can fail closed.\n */\nexport function createDashboardState(\n store: DevtoolsStore,\n path: string,\n options: { ttlMs?: number; now?: () => number } = {},\n): DevtoolsDashboardState {\n const ttlMs = options.ttlMs ?? 5000;\n const now = options.now ?? Date.now;\n const pathHash = hashDashboardPath(path);\n let cached: { open: boolean; at: number } | null = null;\n let pending: Promise<boolean> | null = null;\n let generation = 0;\n\n const read = async (): Promise<boolean> => {\n const started = generation;\n const state = await store.state.read();\n const at = now();\n const disabled = state.disabled && state.disabledPathHash === pathHash;\n const locked = state.lockedUntil !== null && state.lockedUntil > at;\n const open = !disabled && !locked;\n\n if (started === generation) cached = { open, at };\n\n return open;\n };\n\n return {\n async isOpen() {\n if (cached !== null && now() - cached.at < ttlMs) return cached.open;\n\n if (pending === null) {\n const current = read().finally(() => {\n if (pending === current) pending = null;\n });\n\n pending = current;\n }\n\n return pending;\n },\n invalidate() {\n generation += 1;\n cached = null;\n pending = null;\n },\n };\n}\n"],"mappings":";;;;;;;;;;AAIA,MAAM,SAA8B,EAAE,MAAM,SAAS;AACrD,MAAM,SAA8B,EAAE,MAAM,SAAS;AACrD,MAAM,QAA6B,EAAE,MAAM,QAAQ;AACnD,MAAM,QAA6B,EAAE,MAAM,QAAQ;AAEnD,MAAM,WAAW,GAAG,YACjB;CAAE,MAAM;CAAW;AAAO;AAE7B,MAAM,YAAY;CAAC;CAAmB;CAAa;AAAY;;;;;;;;;AAU/D,SAAgB,sBACd,UACA,UAA+B,CAAC,GACL;CAC3B,MAAM,QACJ,QACA,KACA,QACA,WAC6B;EAAE;EAAQ;EAAK;EAAQ,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;CAAG;CAElF,MAAM,QAAmC;EAEvC,KAAK,OAAO,KAAK,MAAM;EACvB,KAAK,OAAO,iBAAiB,MAAM;EACnC,KAAK,OAAO,qBAAqB,MAAM;EACvC,KAAK,QAAQ,mBAAmB,MAAM;EACtC,KAAK,QAAQ,mBAAmB,MAAM;EACtC,KAAK,QAAQ,4BAA4B,MAAM;EAC/C,KAAK,QAAQ,2BAA2B,MAAM;EAC9C,KAAK,QAAQ,sBAAsB,QAAQ,iBAAiB,CAAC;EAC7D,KAAK,QAAQ,wBAAwB,QAAQ,WAAW,CAAC;EACzD,KAAK,QAAQ,0BAA0B,QAAQ,WAAW,CAAC;EAC3D,KAAK,QAAQ,6BAA6B,QAAQ,aAAa,YAAY,CAAC;EAC5E,KAAK,QAAQ,4BAA4B,QAAQ,aAAa,YAAY,CAAC;EAC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model","migrate","migrate","migrate","migrate","migrate","migrate","migrate","migrate"],"sources":["../../../../../../../packages/devtools/src/production/store/models/base.ts","../../../../../../../packages/devtools/src/production/store/models/account.model.ts","../../../../../../../packages/devtools/src/production/store/models/account.migration.ts","../../../../../../../packages/devtools/src/production/store/models/audit.model.ts","../../../../../../../packages/devtools/src/production/store/models/audit.migration.ts","../../../../../../../packages/devtools/src/production/store/models/invite.model.ts","../../../../../../../packages/devtools/src/production/store/models/invite.migration.ts","../../../../../../../packages/devtools/src/production/store/models/report.model.ts","../../../../../../../packages/devtools/src/production/store/models/report.migration.ts","../../../../../../../packages/devtools/src/production/store/models/sample.model.ts","../../../../../../../packages/devtools/src/production/store/models/sample.migration.ts","../../../../../../../packages/devtools/src/production/store/models/session.model.ts","../../../../../../../packages/devtools/src/production/store/models/session.migration.ts","../../../../../../../packages/devtools/src/production/store/models/share.model.ts","../../../../../../../packages/devtools/src/production/store/models/share.migration.ts","../../../../../../../packages/devtools/src/production/store/models/state.model.ts","../../../../../../../packages/devtools/src/production/store/models/state.migration.ts","../../../../../../../packages/devtools/src/production/store/models/index.ts","../../../../../../../packages/devtools/src/production/store/migrations.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\n\n/**\n * Settings shared by the monitor's tables. Ids are supplied by the store\n * (random uuids, or `\"state\"`), times are plain epoch-millisecond columns the\n * store writes itself, and a removal is always permanent: sessions, invites\n * and samples must not be copied into a trash table.\n */\nexport abstract class DevtoolsRowModel extends Model {\n public static autoGenerateId = false;\n\n public static createdAtColumn = false as const;\n\n public static updatedAtColumn = false as const;\n\n public static deleteStrategy = \"permanent\" as const;\n}\n","import { DevtoolsRowModel } from \"./base\";\n\n/** A row of `devtools_accounts`. */\nexport class DevtoolsAccountRow extends DevtoolsRowModel {\n public static table = \"devtools_accounts\";\n}\n","import { migrate } from \"@warlock.js/cascade\";\nimport { DevtoolsAccountRow } from \"./account.model\";\n\nexport const DevtoolsAccountsMigration = migrate(DevtoolsAccountRow, {\n name: \"devtoolsAccounts\",\n up() {\n this.createTableIfNotExists();\n\n // The id is a string the store supplies; `unique` also covers MongoDB,\n // which ignores primary keys.\n this.string(\"id\", 64).primary().unique();\n\n this.string(\"email\", 320).unique();\n this.string(\"role\", 16);\n this.text(\"password_hash\");\n this.string(\"password_source\", 32);\n this.boolean(\"must_change_password\").default(false);\n this.text(\"totp_secret\").nullable();\n this.bigInteger(\"totp_enabled_at\").nullable();\n this.bigInteger(\"totp_last_step\").nullable();\n this.json(\"recovery_codes\");\n this.json(\"passkeys\");\n this.bigInteger(\"failures_reset_at\").nullable();\n this.bigInteger(\"created_at\");\n this.bigInteger(\"updated_at\");\n this.bigInteger(\"last_login_at\").nullable();\n this.string(\"created_by\", 64).nullable();\n this.integer(\"version\").default(1);\n },\n down() {\n this.dropTableIfExists();\n },\n});\n","import { DevtoolsRowModel } from \"./base\";\n\n/** A row of `devtools_audit`. */\nexport class DevtoolsAuditRow extends DevtoolsRowModel {\n public static table = \"devtools_audit\";\n}\n","import { migrate } from \"@warlock.js/cascade\";\nimport { DevtoolsAuditRow } from \"./audit.model\";\n\nexport const DevtoolsAuditMigration = migrate(DevtoolsAuditRow, {\n name: \"devtoolsAudit\",\n up() {\n this.createTableIfNotExists();\n\n // The id is a string the store supplies; `unique` also covers MongoDB,\n // which ignores primary keys.\n this.string(\"id\", 64).primary().unique();\n\n this.string(\"type\", 64);\n this.bigInteger(\"occurred_at\").index();\n this.string(\"account_id\", 64).nullable();\n this.string(\"email\", 320).nullable();\n this.string(\"ip\", 64).nullable();\n // The per-IP sign-in limit counts by this: the address, or its /64 for IPv6.\n this.string(\"ip_bucket\", 64).nullable();\n this.string(\"user_agent\", 255).nullable();\n this.json(\"detail\");\n this.string(\"ref\", 16);\n\n this.index([\"type\", \"occurred_at\"]);\n this.index([\"ip_bucket\", \"occurred_at\"]);\n this.index([\"account_id\", \"occurred_at\"]);\n },\n down() {\n this.dropTableIfExists();\n },\n});\n","import { DevtoolsRowModel } from \"./base\";\n\n/** A row of `devtools_invites`. */\nexport class DevtoolsInviteRow extends DevtoolsRowModel {\n public static table = \"devtools_invites\";\n}\n","import { migrate } from \"@warlock.js/cascade\";\nimport { DevtoolsInviteRow } from \"./invite.model\";\n\nexport const DevtoolsInvitesMigration = migrate(DevtoolsInviteRow, {\n name: \"devtoolsInvites\",\n up() {\n this.createTableIfNotExists();\n\n // The id is a string the store supplies; `unique` also covers MongoDB,\n // which ignores primary keys.\n this.string(\"id\", 64).primary().unique();\n\n this.string(\"token_hash\", 64).unique();\n this.string(\"email\", 320);\n this.string(\"role\", 16);\n this.string(\"created_by\", 64).nullable();\n this.bigInteger(\"created_at\");\n this.bigInteger(\"expires_at\").index();\n this.bigInteger(\"used_at\").nullable();\n this.string(\"account_id\", 64).nullable();\n },\n down() {\n this.dropTableIfExists();\n },\n});\n","import { DevtoolsRowModel } from \"./base\";\n\n/** A row of `devtools_reports`. */\nexport class DevtoolsReportRow extends DevtoolsRowModel {\n public static table = \"devtools_reports\";\n}\n","import { migrate } from \"@warlock.js/cascade\";\nimport { DevtoolsReportRow } from \"./report.model\";\n\nexport const DevtoolsReportsMigration = migrate(DevtoolsReportRow, {\n name: \"devtoolsReports\",\n up() {\n this.createTableIfNotExists();\n\n // The id is a string the store supplies; `unique` also covers MongoDB,\n // which ignores primary keys.\n this.string(\"id\", 64).primary().unique();\n\n this.bigInteger(\"seen_at\").index();\n // JSON text, up to 256 KB.\n this.longText(\"data\");\n },\n down() {\n this.dropTableIfExists();\n },\n});\n","import { DevtoolsRowModel } from \"./base\";\n\n/** A row of `devtools_samples`. */\nexport class DevtoolsSampleRow extends DevtoolsRowModel {\n public static table = \"devtools_samples\";\n}\n","import { migrate } from \"@warlock.js/cascade\";\nimport { DevtoolsSampleRow } from \"./sample.model\";\n\nexport const DevtoolsSamplesMigration = migrate(DevtoolsSampleRow, {\n name: \"devtoolsSamples\",\n up() {\n this.createTableIfNotExists();\n\n // The id is a string the store supplies; `unique` also covers MongoDB,\n // which ignores primary keys.\n this.string(\"id\", 64).primary().unique();\n\n this.string(\"instance\", 128).index();\n this.bigInteger(\"started_at\").index();\n this.integer(\"status\").nullable().index();\n this.string(\"method\", 16);\n this.text(\"path\");\n this.json(\"summary\");\n // JSON text: request data may hold keys MongoDB cannot store as field names.\n this.longText(\"detail\").nullable();\n },\n down() {\n this.dropTableIfExists();\n },\n});\n","import { DevtoolsRowModel } from \"./base\";\n\n/** A row of `devtools_sessions`. */\nexport class DevtoolsSessionRow extends DevtoolsRowModel {\n public static table = \"devtools_sessions\";\n}\n","import { migrate } from \"@warlock.js/cascade\";\nimport { DevtoolsSessionRow } from \"./session.model\";\n\nexport const DevtoolsSessionsMigration = migrate(DevtoolsSessionRow, {\n name: \"devtoolsSessions\",\n up() {\n this.createTableIfNotExists();\n\n // The id is a string the store supplies; `unique` also covers MongoDB,\n // which ignores primary keys.\n this.string(\"id\", 64).primary().unique();\n\n this.string(\"token_hash\", 64).unique();\n this.string(\"account_id\", 64).index();\n this.string(\"stage\", 32);\n this.string(\"csrf_secret\", 128);\n this.bigInteger(\"created_at\");\n this.bigInteger(\"last_seen_at\");\n this.bigInteger(\"expires_at\").index();\n this.string(\"ip\", 64).nullable();\n this.string(\"user_agent\", 255).nullable();\n this.text(\"pending_totp_secret\").nullable();\n this.text(\"challenge\").nullable();\n this.bigInteger(\"challenge_expires_at\").nullable();\n this.integer(\"version\").default(1);\n },\n down() {\n this.dropTableIfExists();\n },\n});\n","import { DevtoolsRowModel } from \"./base\";\n\n/** A row of `devtools_shares`. */\nexport class DevtoolsShareRow extends DevtoolsRowModel {\n public static table = \"devtools_shares\";\n}\n","import { migrate } from \"@warlock.js/cascade\";\nimport { DevtoolsShareRow } from \"./share.model\";\n\nexport const DevtoolsSharesMigration = migrate(DevtoolsShareRow, {\n name: \"devtoolsShares\",\n up() {\n this.createTableIfNotExists();\n\n // The id is a string the store supplies; `unique` also covers MongoDB,\n // which ignores primary keys.\n this.string(\"id\", 64).primary().unique();\n\n this.string(\"token_hash\", 64).unique();\n this.string(\"panel\", 64);\n this.string(\"label\", 80);\n this.string(\"created_by\", 64).nullable();\n this.bigInteger(\"created_at\");\n this.bigInteger(\"expires_at\").index();\n this.bigInteger(\"revoked_at\").nullable();\n this.bigInteger(\"last_used_at\").nullable();\n this.integer(\"uses\").default(0);\n },\n down() {\n this.dropTableIfExists();\n },\n});\n","import { DevtoolsRowModel } from \"./base\";\n\n/** A row of `devtools_state`. */\nexport class DevtoolsStateRow extends DevtoolsRowModel {\n public static table = \"devtools_state\";\n}\n","import { migrate } from \"@warlock.js/cascade\";\nimport { DevtoolsStateRow } from \"./state.model\";\n\nexport const DevtoolsStateMigration = migrate(DevtoolsStateRow, {\n name: \"devtoolsState\",\n up() {\n this.createTableIfNotExists();\n\n // The id is a string the store supplies; `unique` also covers MongoDB,\n // which ignores primary keys.\n this.string(\"id\", 64).primary().unique();\n\n this.boolean(\"disabled\").default(false);\n this.string(\"disabled_path_hash\", 64).nullable();\n this.bigInteger(\"disabled_at\").nullable();\n this.string(\"disabled_by\", 64).nullable();\n this.bigInteger(\"locked_until\").nullable();\n this.bigInteger(\"failures_reset_at\").nullable();\n this.bigInteger(\"updated_at\");\n this.integer(\"version\").default(0);\n },\n down() {\n this.dropTableIfExists();\n },\n});\n","export { DevtoolsRowModel } from \"./base\";\nexport { DevtoolsAccountsMigration } from \"./account.migration\";\nexport { DevtoolsAccountRow } from \"./account.model\";\nexport { DevtoolsAuditMigration } from \"./audit.migration\";\nexport { DevtoolsAuditRow } from \"./audit.model\";\nexport { DevtoolsInvitesMigration } from \"./invite.migration\";\nexport { DevtoolsInviteRow } from \"./invite.model\";\nexport { DevtoolsReportsMigration } from \"./report.migration\";\nexport { DevtoolsReportRow } from \"./report.model\";\nexport { DevtoolsSamplesMigration } from \"./sample.migration\";\nexport { DevtoolsSampleRow } from \"./sample.model\";\nexport { DevtoolsSessionsMigration } from \"./session.migration\";\nexport { DevtoolsSessionRow } from \"./session.model\";\nexport { DevtoolsSharesMigration } from \"./share.migration\";\nexport { DevtoolsShareRow } from \"./share.model\";\nexport { DevtoolsStateMigration } from \"./state.migration\";\nexport { DevtoolsStateRow } from \"./state.model\";\n","import type { MigrationConstructor } from \"@warlock.js/cascade\";\nimport {\n DevtoolsAccountsMigration,\n DevtoolsAuditMigration,\n DevtoolsInvitesMigration,\n DevtoolsReportsMigration,\n DevtoolsSamplesMigration,\n DevtoolsSessionsMigration,\n DevtoolsSharesMigration,\n DevtoolsStateMigration,\n} from \"./models\";\n\n/**\n * The migrations of the production monitor's tables/collections:\n * `devtools_accounts`, `devtools_sessions`, `devtools_invites`,\n * `devtools_audit`, `devtools_state`, `devtools_samples`, `devtools_reports`,\n * `devtools_shares`.\n * An app lists them in `warlock.config.ts > database.migrations`.\n */\nexport const devtoolsMigrations: readonly MigrationConstructor[] = [\n DevtoolsAccountsMigration,\n DevtoolsSessionsMigration,\n DevtoolsInvitesMigration,\n DevtoolsAuditMigration,\n DevtoolsStateMigration,\n DevtoolsSamplesMigration,\n DevtoolsReportsMigration,\n DevtoolsSharesMigration,\n];\n"],"mappings":";;;;;;;;;;AAQA,IAAsB,mBAAtB,cAA+CA,0BAAM;;wBACpB;;;yBAEC;;;yBAEA;;;wBAED;;AACjC;;;;;ACbA,IAAa,qBAAb,cAAwC,iBAAiB;;eACjC;;AACxB;;;;ACFA,MAAa,gCAA4BC,6BAAQ,oBAAoB;CACnE,MAAM;CACN,KAAK;EACH,KAAK,uBAAuB;EAI5B,KAAK,OAAO,MAAM,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,OAAO;EAEvC,KAAK,OAAO,SAAS,GAAG,CAAC,CAAC,OAAO;EACjC,KAAK,OAAO,QAAQ,EAAE;EACtB,KAAK,KAAK,eAAe;EACzB,KAAK,OAAO,mBAAmB,EAAE;EACjC,KAAK,QAAQ,sBAAsB,CAAC,CAAC,QAAQ,KAAK;EAClD,KAAK,KAAK,aAAa,CAAC,CAAC,SAAS;EAClC,KAAK,WAAW,iBAAiB,CAAC,C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,KAAK,OAAO,SAAS,EAAE;EACvB,KAAK,OAAO,cAAc,EAAE,CAAC,CAAC,SAAS;EACvC,KAAK,WAAW,YAAY;EAC5B,KAAK,WAAW,YAAY,CAAC,CAAC,MAAM;EACpC,KAAK,WAAW,YAAY,CAAC,CAAC,SAAS;EACvC,KAAK,WAAW,cAAc,CAAC,CAAC,SAAS;EACzC,KAAK,QAAQ,MAAM,CAAC,CAAC,QAAQ,CAAC;CAChC;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC;;;;;ACtBD,IAAa,mBAAb,cAAsC,iBAAiB;;eAC/B;;AACxB;;;;ACFA,MAAa,6BAAyBC,6BAAQ,kBAAkB;CAC9D,MAAM;CACN,KAAK;EACH,KAAK,uBAAuB;EAI5B,KAAK,OAAO,MAAM,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,OAAO;EAEvC,KAAK,QAAQ,UAAU,CAAC,CAAC,QAAQ,KAAK;EACtC,KAAK,OAAO,sBAAsB,EAAE,CAAC,CAAC,SAAS;EAC/C,KAAK,WAAW,aAAa,CAAC,CAAC,SAAS;EACxC,KAAK,OAAO,eAAe,EAAE,CAAC,CAAC,SAAS;EACxC,KAAK,WAAW,cAAc,CAAC,CAAC,SAAS;EACzC,KAAK,WAAW,mBAAmB,CAAC,CAAC,SAAS;EAC9C,KAAK,WAAW,YAAY;EAC5B,KAAK,QAAQ,SAAS,CAAC,CAAC,QAAQ,CAAC;CACnC;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AELD,MAAa,qBAAsD;CACjE;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
|
package/cjs/options-CHhmQJic.cjs
DELETED
|
@@ -1,193 +0,0 @@
|
|
|
1
|
-
const require_errors = require("./errors-DEqdWaqm.cjs");
|
|
2
|
-
const require_ip = require("./ip-DbNhPOzi.cjs");
|
|
3
|
-
|
|
4
|
-
//#region ../../packages/devtools/src/production/options.ts
|
|
5
|
-
/** The defaults `resolveProductionOptions` applies (environment values excluded). */
|
|
6
|
-
const DEVTOOLS_PRODUCTION_DEFAULTS = {
|
|
7
|
-
sampleRate: .1,
|
|
8
|
-
slowRequestMs: 1e3,
|
|
9
|
-
slowQueryMs: 200,
|
|
10
|
-
maxRequests: 200,
|
|
11
|
-
maxQueriesPerRequest: 200,
|
|
12
|
-
maxShapes: 500,
|
|
13
|
-
maxRoutes: 300,
|
|
14
|
-
maxErrorGroups: 100,
|
|
15
|
-
requestRetentionHours: 24,
|
|
16
|
-
maxStoredSamplesPerMinute: 120,
|
|
17
|
-
reportIntervalMs: 1e4,
|
|
18
|
-
requireHttps: true,
|
|
19
|
-
session: {
|
|
20
|
-
idleMinutes: 30,
|
|
21
|
-
maxHours: 8,
|
|
22
|
-
pendingMinutes: 10
|
|
23
|
-
},
|
|
24
|
-
twoFactor: "admins",
|
|
25
|
-
rateLimits: {
|
|
26
|
-
windowMinutes: 15,
|
|
27
|
-
account: 5,
|
|
28
|
-
ip: 20,
|
|
29
|
-
global: 100,
|
|
30
|
-
lockMinutes: 15
|
|
31
|
-
},
|
|
32
|
-
explain: { executing: false },
|
|
33
|
-
logLevels: ["warn", "error"],
|
|
34
|
-
auditRetentionDays: 90,
|
|
35
|
-
passkeys: { rpName: "Warlock monitor" },
|
|
36
|
-
share: {
|
|
37
|
-
enabled: false,
|
|
38
|
-
maxDays: 30
|
|
39
|
-
}
|
|
40
|
-
};
|
|
41
|
-
/** The environment variables production mode reads. */
|
|
42
|
-
const DEVTOOLS_ENV = {
|
|
43
|
-
path: "DEVTOOLS_PATH",
|
|
44
|
-
adminEmail: "DEVTOOLS_ADMIN_EMAIL",
|
|
45
|
-
adminPassword: "DEVTOOLS_ADMIN_PASSWORD",
|
|
46
|
-
setupToken: "DEVTOOLS_SETUP_TOKEN"
|
|
47
|
-
};
|
|
48
|
-
const LOG_LEVELS = [
|
|
49
|
-
"debug",
|
|
50
|
-
"info",
|
|
51
|
-
"warn",
|
|
52
|
-
"error",
|
|
53
|
-
"success"
|
|
54
|
-
];
|
|
55
|
-
const PATH_CHARACTERS = /^[A-Za-z0-9._~/-]+$/;
|
|
56
|
-
const MIN_PATH_LENGTH = 8;
|
|
57
|
-
const MIN_SETUP_TOKEN_LENGTH = 32;
|
|
58
|
-
function invalid(option, expected) {
|
|
59
|
-
throw new require_errors.DevtoolsProductionConfigError("DT007", `Option "devtools.production.${option}" is not valid: ${expected}.`);
|
|
60
|
-
}
|
|
61
|
-
function present(value) {
|
|
62
|
-
return value === void 0 || value === "" ? null : value;
|
|
63
|
-
}
|
|
64
|
-
function integerAtLeastOne(option, value, fallback) {
|
|
65
|
-
if (value === void 0) return fallback;
|
|
66
|
-
if (!Number.isInteger(value) || value < 1) invalid(option, "use a whole number of 1 or more");
|
|
67
|
-
return value;
|
|
68
|
-
}
|
|
69
|
-
function networkList(option, value) {
|
|
70
|
-
if (value === void 0) return [];
|
|
71
|
-
if (!Array.isArray(value)) invalid(option, "use a list of IPs, CIDR ranges, \"loopback\" or \"private\"");
|
|
72
|
-
for (const entry of value) if (!require_ip.isValidNetworkEntry(entry)) invalid(option, `"${String(entry)}" is not an IP, a CIDR range, "loopback" or "private"`);
|
|
73
|
-
return [...value];
|
|
74
|
-
}
|
|
75
|
-
/** The dashboard path without a trailing slash, or a DT001/DT002 error. */
|
|
76
|
-
function resolvePath(value) {
|
|
77
|
-
const given = present(value);
|
|
78
|
-
if (given === null) throw new require_errors.DevtoolsProductionConfigError("DT001");
|
|
79
|
-
const path = given.replace(/\/+$/, "");
|
|
80
|
-
const segments = path.split("/").slice(1);
|
|
81
|
-
const lower = path.toLowerCase();
|
|
82
|
-
if (!path.startsWith("/") || path.length < MIN_PATH_LENGTH || !PATH_CHARACTERS.test(path) || segments.some((segment) => segment === "" || segment === "." || segment === "..") || lower === "/__warlock" || lower.startsWith("/__warlock/")) throw new require_errors.DevtoolsProductionConfigError("DT002");
|
|
83
|
-
return path;
|
|
84
|
-
}
|
|
85
|
-
/**
|
|
86
|
-
* Applies the defaults to `options`, reads the path and first admin from
|
|
87
|
-
* `env`, and validates everything.
|
|
88
|
-
*
|
|
89
|
-
* Throws `DevtoolsProductionConfigError`: DT001 (no path), DT002 (bad path),
|
|
90
|
-
* DT007 (an option out of range: sampleRate outside 0–1, share.maxDays outside 1–365, a non-positive
|
|
91
|
-
* limit, an unknown twoFactor value, a bad CIDR, an origin that is not
|
|
92
|
-
* `https://host[:port]`), DT009 (both a password and a setup token), DT010
|
|
93
|
-
* (setup token shorter than 32 characters). DT003/DT004 (admin) are checked
|
|
94
|
-
* later by `ensureFirstAdmin`, which needs the database.
|
|
95
|
-
*/
|
|
96
|
-
function resolveProductionOptions(options, env) {
|
|
97
|
-
const given = options ?? {};
|
|
98
|
-
const defaults = DEVTOOLS_PRODUCTION_DEFAULTS;
|
|
99
|
-
const path = resolvePath(given.path ?? env[DEVTOOLS_ENV.path]);
|
|
100
|
-
const sampleRate = given.sampleRate ?? defaults.sampleRate;
|
|
101
|
-
if (typeof sampleRate !== "number" || !Number.isFinite(sampleRate) || sampleRate < 0 || sampleRate > 1) invalid("sampleRate", "use a number from 0 to 1");
|
|
102
|
-
const requireHttps = given.requireHttps ?? defaults.requireHttps;
|
|
103
|
-
if (typeof requireHttps !== "boolean") invalid("requireHttps", "use true or false");
|
|
104
|
-
const twoFactor = given.twoFactor ?? defaults.twoFactor;
|
|
105
|
-
if (twoFactor !== "admins" && twoFactor !== "everyone") invalid("twoFactor", "use \"admins\" or \"everyone\"");
|
|
106
|
-
const origin = given.origin ?? null;
|
|
107
|
-
if (origin !== null) {
|
|
108
|
-
if (typeof origin !== "string" || !(requireHttps ? /^https:\/\/[^/\s]+$/ : /^https?:\/\/[^/\s]+$/).test(origin)) invalid("origin", requireHttps ? "use an origin such as https://app.example.com, without a path or a trailing slash" : "use an origin such as http://localhost:3000, without a path or a trailing slash");
|
|
109
|
-
}
|
|
110
|
-
const panels = given.panels ?? {};
|
|
111
|
-
if (panels === null || typeof panels !== "object" || Array.isArray(panels)) invalid("panels", "use an object of tab ids and true or false");
|
|
112
|
-
for (const [id, enabled] of Object.entries(panels)) if (typeof enabled !== "boolean") invalid(`panels.${id}`, "use true or false");
|
|
113
|
-
const logLevels = given.logLevels ?? defaults.logLevels;
|
|
114
|
-
if (!Array.isArray(logLevels) || logLevels.some((level) => !LOG_LEVELS.includes(level))) invalid("logLevels", `use a list of ${LOG_LEVELS.join(", ")}`);
|
|
115
|
-
const executing = given.explain?.executing ?? defaults.explain.executing;
|
|
116
|
-
if (typeof executing !== "boolean") invalid("explain.executing", "use true or false");
|
|
117
|
-
const rpName = given.passkeys?.rpName ?? defaults.passkeys.rpName;
|
|
118
|
-
const rpId = given.passkeys?.rpId ?? null;
|
|
119
|
-
if (typeof rpName !== "string" || rpName.trim() === "") invalid("passkeys.rpName", "use a non-empty name");
|
|
120
|
-
if (rpId !== null && (typeof rpId !== "string" || rpId.trim() === "")) invalid("passkeys.rpId", "use a host name such as app.example.com");
|
|
121
|
-
const shareEnabled = given.share?.enabled ?? defaults.share.enabled;
|
|
122
|
-
const shareMaxDays = given.share?.maxDays ?? defaults.share.maxDays;
|
|
123
|
-
if (typeof shareEnabled !== "boolean") invalid("share.enabled", "use true or false");
|
|
124
|
-
if (!Number.isInteger(shareMaxDays) || shareMaxDays < 1 || shareMaxDays > 365) invalid("share.maxDays", "use a whole number of days from 1 to 365");
|
|
125
|
-
const limits = given.rateLimits ?? {};
|
|
126
|
-
const session = given.session ?? {};
|
|
127
|
-
const resolved = {
|
|
128
|
-
path,
|
|
129
|
-
admin: {
|
|
130
|
-
email: present(env[DEVTOOLS_ENV.adminEmail]),
|
|
131
|
-
password: present(env[DEVTOOLS_ENV.adminPassword]),
|
|
132
|
-
setupToken: present(env[DEVTOOLS_ENV.setupToken])
|
|
133
|
-
},
|
|
134
|
-
sampleRate,
|
|
135
|
-
slowRequestMs: integerAtLeastOne("slowRequestMs", given.slowRequestMs, defaults.slowRequestMs),
|
|
136
|
-
slowQueryMs: integerAtLeastOne("slowQueryMs", given.slowQueryMs, defaults.slowQueryMs),
|
|
137
|
-
maxRequests: integerAtLeastOne("maxRequests", given.maxRequests, defaults.maxRequests),
|
|
138
|
-
maxQueriesPerRequest: defaults.maxQueriesPerRequest,
|
|
139
|
-
maxShapes: defaults.maxShapes,
|
|
140
|
-
maxRoutes: defaults.maxRoutes,
|
|
141
|
-
maxErrorGroups: defaults.maxErrorGroups,
|
|
142
|
-
requestRetentionHours: integerAtLeastOne("requestRetentionHours", given.requestRetentionHours, defaults.requestRetentionHours),
|
|
143
|
-
maxStoredSamplesPerMinute: integerAtLeastOne("maxStoredSamplesPerMinute", given.maxStoredSamplesPerMinute, defaults.maxStoredSamplesPerMinute),
|
|
144
|
-
reportIntervalMs: integerAtLeastOne("reportIntervalMs", given.reportIntervalMs, defaults.reportIntervalMs),
|
|
145
|
-
trustedProxies: networkList("trustedProxies", given.trustedProxies),
|
|
146
|
-
requireHttps,
|
|
147
|
-
allowedIps: networkList("allowedIps", given.allowedIps),
|
|
148
|
-
origin,
|
|
149
|
-
session: {
|
|
150
|
-
idleMinutes: integerAtLeastOne("session.idleMinutes", session.idleMinutes, defaults.session.idleMinutes),
|
|
151
|
-
maxHours: integerAtLeastOne("session.maxHours", session.maxHours, defaults.session.maxHours),
|
|
152
|
-
pendingMinutes: defaults.session.pendingMinutes
|
|
153
|
-
},
|
|
154
|
-
twoFactor,
|
|
155
|
-
rateLimits: {
|
|
156
|
-
windowMinutes: integerAtLeastOne("rateLimits.windowMinutes", limits.windowMinutes, defaults.rateLimits.windowMinutes),
|
|
157
|
-
account: integerAtLeastOne("rateLimits.account", limits.account, defaults.rateLimits.account),
|
|
158
|
-
ip: integerAtLeastOne("rateLimits.ip", limits.ip, defaults.rateLimits.ip),
|
|
159
|
-
global: integerAtLeastOne("rateLimits.global", limits.global, defaults.rateLimits.global),
|
|
160
|
-
lockMinutes: integerAtLeastOne("rateLimits.lockMinutes", limits.lockMinutes, defaults.rateLimits.lockMinutes)
|
|
161
|
-
},
|
|
162
|
-
explain: { executing },
|
|
163
|
-
panels: { ...panels },
|
|
164
|
-
logLevels: [...logLevels],
|
|
165
|
-
auditRetentionDays: integerAtLeastOne("auditRetentionDays", given.auditRetentionDays, defaults.auditRetentionDays),
|
|
166
|
-
passkeys: {
|
|
167
|
-
rpName,
|
|
168
|
-
rpId
|
|
169
|
-
},
|
|
170
|
-
share: {
|
|
171
|
-
enabled: shareEnabled,
|
|
172
|
-
maxDays: shareMaxDays
|
|
173
|
-
}
|
|
174
|
-
};
|
|
175
|
-
if (resolved.admin.password !== null && resolved.admin.setupToken !== null) throw new require_errors.DevtoolsProductionConfigError("DT009");
|
|
176
|
-
if (resolved.admin.setupToken !== null && resolved.admin.setupToken.length < MIN_SETUP_TOKEN_LENGTH) throw new require_errors.DevtoolsProductionConfigError("DT010");
|
|
177
|
-
return resolved;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
//#endregion
|
|
181
|
-
Object.defineProperty(exports, "DEVTOOLS_PRODUCTION_DEFAULTS", {
|
|
182
|
-
enumerable: true,
|
|
183
|
-
get: function () {
|
|
184
|
-
return DEVTOOLS_PRODUCTION_DEFAULTS;
|
|
185
|
-
}
|
|
186
|
-
});
|
|
187
|
-
Object.defineProperty(exports, "resolveProductionOptions", {
|
|
188
|
-
enumerable: true,
|
|
189
|
-
get: function () {
|
|
190
|
-
return resolveProductionOptions;
|
|
191
|
-
}
|
|
192
|
-
});
|
|
193
|
-
//# sourceMappingURL=options-CHhmQJic.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"options-CHhmQJic.cjs","names":["DevtoolsProductionConfigError","isValidNetworkEntry"],"sources":["../../../../../../../packages/devtools/src/production/options.ts"],"sourcesContent":["import type { DevtoolsLogEntry, DevtoolsProductionOptions } from \"../types\";\nimport { DevtoolsProductionConfigError } from \"./errors\";\nimport { isValidNetworkEntry } from \"./http/ip\";\n\n/**\n * `DevtoolsProductionOptions` with every default applied and the environment\n * read. Built once at boot by `resolveProductionOptions`.\n */\nexport type ResolvedDevtoolsProductionOptions = {\n /** The dashboard path, without a trailing slash. */\n path: string;\n /** The first admin from the environment; every field `null` when unset. */\n admin: { email: string | null; password: string | null; setupToken: string | null };\n sampleRate: number;\n slowRequestMs: number;\n slowQueryMs: number;\n maxRequests: number;\n /** Queries kept per sampled request; the rest are counted in `droppedQueries`. */\n maxQueriesPerRequest: number;\n /** Query shapes kept in memory per process (least recently seen evicted). */\n maxShapes: number;\n /** Route keys kept in memory per process. */\n maxRoutes: number;\n /** Error groups kept in memory per process. */\n maxErrorGroups: number;\n requestRetentionHours: number;\n maxStoredSamplesPerMinute: number;\n reportIntervalMs: number;\n trustedProxies: readonly string[];\n requireHttps: boolean;\n allowedIps: readonly string[];\n origin: string | null;\n session: { idleMinutes: number; maxHours: number; pendingMinutes: number };\n twoFactor: \"admins\" | \"everyone\";\n rateLimits: {\n windowMinutes: number;\n account: number;\n ip: number;\n global: number;\n lockMinutes: number;\n };\n explain: { executing: boolean };\n panels: Readonly<Record<string, boolean>>;\n logLevels: readonly DevtoolsLogEntry[\"level\"][];\n auditRetentionDays: number;\n passkeys: { rpName: string; rpId: string | null };\n /** Read-only share links. */\n share: { enabled: boolean; maxDays: number };\n};\n\n/** The defaults `resolveProductionOptions` applies (environment values excluded). */\nexport const DEVTOOLS_PRODUCTION_DEFAULTS = {\n sampleRate: 0.1,\n slowRequestMs: 1000,\n slowQueryMs: 200,\n maxRequests: 200,\n maxQueriesPerRequest: 200,\n maxShapes: 500,\n maxRoutes: 300,\n maxErrorGroups: 100,\n requestRetentionHours: 24,\n maxStoredSamplesPerMinute: 120,\n reportIntervalMs: 10_000,\n requireHttps: true,\n session: { idleMinutes: 30, maxHours: 8, pendingMinutes: 10 },\n twoFactor: \"admins\",\n rateLimits: { windowMinutes: 15, account: 5, ip: 20, global: 100, lockMinutes: 15 },\n explain: { executing: false },\n logLevels: [\"warn\", \"error\"],\n auditRetentionDays: 90,\n passkeys: { rpName: \"Warlock monitor\" },\n share: { enabled: false, maxDays: 30 },\n} as const;\n\n/** The environment variables production mode reads. */\nexport const DEVTOOLS_ENV = {\n path: \"DEVTOOLS_PATH\",\n adminEmail: \"DEVTOOLS_ADMIN_EMAIL\",\n adminPassword: \"DEVTOOLS_ADMIN_PASSWORD\",\n setupToken: \"DEVTOOLS_SETUP_TOKEN\",\n} as const;\n\nconst LOG_LEVELS: readonly DevtoolsLogEntry[\"level\"][] = [\n \"debug\",\n \"info\",\n \"warn\",\n \"error\",\n \"success\",\n];\n\nconst PATH_CHARACTERS = /^[A-Za-z0-9._~/-]+$/;\nconst MIN_PATH_LENGTH = 8;\nconst MIN_SETUP_TOKEN_LENGTH = 32;\n\nfunction invalid(option: string, expected: string): never {\n throw new DevtoolsProductionConfigError(\n \"DT007\",\n `Option \"devtools.production.${option}\" is not valid: ${expected}.`,\n );\n}\n\nfunction present(value: string | undefined): string | null {\n return value === undefined || value === \"\" ? null : value;\n}\n\nfunction integerAtLeastOne(option: string, value: number | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n\n if (!Number.isInteger(value) || value < 1) invalid(option, \"use a whole number of 1 or more\");\n\n return value;\n}\n\nfunction networkList(option: string, value: readonly string[] | undefined): readonly string[] {\n if (value === undefined) return [];\n\n if (!Array.isArray(value)) {\n invalid(option, 'use a list of IPs, CIDR ranges, \"loopback\" or \"private\"');\n }\n\n for (const entry of value as readonly unknown[]) {\n if (!isValidNetworkEntry(entry)) {\n invalid(option, `\"${String(entry)}\" is not an IP, a CIDR range, \"loopback\" or \"private\"`);\n }\n }\n\n return [...value];\n}\n\n/** The dashboard path without a trailing slash, or a DT001/DT002 error. */\nfunction resolvePath(value: string | undefined): string {\n const given = present(value);\n\n if (given === null) throw new DevtoolsProductionConfigError(\"DT001\");\n\n const path = given.replace(/\\/+$/, \"\");\n const segments = path.split(\"/\").slice(1);\n const lower = path.toLowerCase();\n\n if (\n !path.startsWith(\"/\") ||\n path.length < MIN_PATH_LENGTH ||\n !PATH_CHARACTERS.test(path) ||\n segments.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\") ||\n lower === \"/__warlock\" ||\n lower.startsWith(\"/__warlock/\")\n ) {\n throw new DevtoolsProductionConfigError(\"DT002\");\n }\n\n return path;\n}\n\n/**\n * Applies the defaults to `options`, reads the path and first admin from\n * `env`, and validates everything.\n *\n * Throws `DevtoolsProductionConfigError`: DT001 (no path), DT002 (bad path),\n * DT007 (an option out of range: sampleRate outside 0–1, share.maxDays outside 1–365, a non-positive\n * limit, an unknown twoFactor value, a bad CIDR, an origin that is not\n * `https://host[:port]`), DT009 (both a password and a setup token), DT010\n * (setup token shorter than 32 characters). DT003/DT004 (admin) are checked\n * later by `ensureFirstAdmin`, which needs the database.\n */\nexport function resolveProductionOptions(\n options: DevtoolsProductionOptions | undefined,\n env: Readonly<Record<string, string | undefined>>,\n): ResolvedDevtoolsProductionOptions {\n const given = options ?? {};\n const defaults = DEVTOOLS_PRODUCTION_DEFAULTS;\n const path = resolvePath(given.path ?? env[DEVTOOLS_ENV.path]);\n\n const sampleRate = given.sampleRate ?? defaults.sampleRate;\n\n if (\n typeof sampleRate !== \"number\" ||\n !Number.isFinite(sampleRate) ||\n sampleRate < 0 ||\n sampleRate > 1\n ) {\n invalid(\"sampleRate\", \"use a number from 0 to 1\");\n }\n\n const requireHttps: boolean = given.requireHttps ?? defaults.requireHttps;\n\n if (typeof requireHttps !== \"boolean\") invalid(\"requireHttps\", \"use true or false\");\n\n const twoFactor = given.twoFactor ?? defaults.twoFactor;\n\n if (twoFactor !== \"admins\" && twoFactor !== \"everyone\") {\n invalid(\"twoFactor\", 'use \"admins\" or \"everyone\"');\n }\n\n const origin = given.origin ?? null;\n\n if (origin !== null) {\n const pattern = requireHttps ? /^https:\\/\\/[^/\\s]+$/ : /^https?:\\/\\/[^/\\s]+$/;\n\n if (typeof origin !== \"string\" || !pattern.test(origin)) {\n invalid(\n \"origin\",\n requireHttps\n ? \"use an origin such as https://app.example.com, without a path or a trailing slash\"\n : \"use an origin such as http://localhost:3000, without a path or a trailing slash\",\n );\n }\n }\n\n const panels: Readonly<Record<string, unknown>> = given.panels ?? {};\n\n if (panels === null || typeof panels !== \"object\" || Array.isArray(panels)) {\n invalid(\"panels\", \"use an object of tab ids and true or false\");\n }\n\n for (const [id, enabled] of Object.entries(panels)) {\n if (typeof enabled !== \"boolean\") invalid(`panels.${id}`, \"use true or false\");\n }\n\n const logLevels = given.logLevels ?? defaults.logLevels;\n\n if (!Array.isArray(logLevels) || logLevels.some((level) => !LOG_LEVELS.includes(level))) {\n invalid(\"logLevels\", `use a list of ${LOG_LEVELS.join(\", \")}`);\n }\n\n const executing: boolean = given.explain?.executing ?? defaults.explain.executing;\n\n if (typeof executing !== \"boolean\") invalid(\"explain.executing\", \"use true or false\");\n\n const rpName: string = given.passkeys?.rpName ?? defaults.passkeys.rpName;\n const rpId = given.passkeys?.rpId ?? null;\n\n if (typeof rpName !== \"string\" || rpName.trim() === \"\") {\n invalid(\"passkeys.rpName\", \"use a non-empty name\");\n }\n\n if (rpId !== null && (typeof rpId !== \"string\" || rpId.trim() === \"\")) {\n invalid(\"passkeys.rpId\", \"use a host name such as app.example.com\");\n }\n\n const shareEnabled: boolean = given.share?.enabled ?? defaults.share.enabled;\n const shareMaxDays: number = given.share?.maxDays ?? defaults.share.maxDays;\n\n if (typeof shareEnabled !== \"boolean\") invalid(\"share.enabled\", \"use true or false\");\n\n if (!Number.isInteger(shareMaxDays) || shareMaxDays < 1 || shareMaxDays > 365) {\n invalid(\"share.maxDays\", \"use a whole number of days from 1 to 365\");\n }\n\n const limits = given.rateLimits ?? {};\n const session = given.session ?? {};\n\n const resolved: ResolvedDevtoolsProductionOptions = {\n path,\n admin: {\n email: present(env[DEVTOOLS_ENV.adminEmail]),\n password: present(env[DEVTOOLS_ENV.adminPassword]),\n setupToken: present(env[DEVTOOLS_ENV.setupToken]),\n },\n sampleRate,\n slowRequestMs: integerAtLeastOne(\"slowRequestMs\", given.slowRequestMs, defaults.slowRequestMs),\n slowQueryMs: integerAtLeastOne(\"slowQueryMs\", given.slowQueryMs, defaults.slowQueryMs),\n maxRequests: integerAtLeastOne(\"maxRequests\", given.maxRequests, defaults.maxRequests),\n maxQueriesPerRequest: defaults.maxQueriesPerRequest,\n maxShapes: defaults.maxShapes,\n maxRoutes: defaults.maxRoutes,\n maxErrorGroups: defaults.maxErrorGroups,\n requestRetentionHours: integerAtLeastOne(\n \"requestRetentionHours\",\n given.requestRetentionHours,\n defaults.requestRetentionHours,\n ),\n maxStoredSamplesPerMinute: integerAtLeastOne(\n \"maxStoredSamplesPerMinute\",\n given.maxStoredSamplesPerMinute,\n defaults.maxStoredSamplesPerMinute,\n ),\n reportIntervalMs: integerAtLeastOne(\n \"reportIntervalMs\",\n given.reportIntervalMs,\n defaults.reportIntervalMs,\n ),\n trustedProxies: networkList(\"trustedProxies\", given.trustedProxies),\n requireHttps,\n allowedIps: networkList(\"allowedIps\", given.allowedIps),\n origin,\n session: {\n idleMinutes: integerAtLeastOne(\n \"session.idleMinutes\",\n session.idleMinutes,\n defaults.session.idleMinutes,\n ),\n maxHours: integerAtLeastOne(\"session.maxHours\", session.maxHours, defaults.session.maxHours),\n pendingMinutes: defaults.session.pendingMinutes,\n },\n twoFactor,\n rateLimits: {\n windowMinutes: integerAtLeastOne(\n \"rateLimits.windowMinutes\",\n limits.windowMinutes,\n defaults.rateLimits.windowMinutes,\n ),\n account: integerAtLeastOne(\"rateLimits.account\", limits.account, defaults.rateLimits.account),\n ip: integerAtLeastOne(\"rateLimits.ip\", limits.ip, defaults.rateLimits.ip),\n global: integerAtLeastOne(\"rateLimits.global\", limits.global, defaults.rateLimits.global),\n lockMinutes: integerAtLeastOne(\n \"rateLimits.lockMinutes\",\n limits.lockMinutes,\n defaults.rateLimits.lockMinutes,\n ),\n },\n explain: { executing },\n panels: { ...(panels as Readonly<Record<string, boolean>>) },\n logLevels: [...logLevels],\n auditRetentionDays: integerAtLeastOne(\n \"auditRetentionDays\",\n given.auditRetentionDays,\n defaults.auditRetentionDays,\n ),\n passkeys: { rpName, rpId },\n share: { enabled: shareEnabled, maxDays: shareMaxDays },\n };\n\n if (resolved.admin.password !== null && resolved.admin.setupToken !== null) {\n throw new DevtoolsProductionConfigError(\"DT009\");\n }\n\n if (\n resolved.admin.setupToken !== null &&\n resolved.admin.setupToken.length < MIN_SETUP_TOKEN_LENGTH\n ) {\n throw new DevtoolsProductionConfigError(\"DT010\");\n }\n\n return resolved;\n}\n"],"mappings":";;;;;AAmDA,MAAa,+BAA+B;CAC1C,YAAY;CACZ,eAAe;CACf,aAAa;CACb,aAAa;CACb,sBAAsB;CACtB,WAAW;CACX,WAAW;CACX,gBAAgB;CAChB,uBAAuB;CACvB,2BAA2B;CAC3B,kBAAkB;CAClB,cAAc;CACd,SAAS;EAAE,aAAa;EAAI,UAAU;EAAG,gBAAgB;CAAG;CAC5D,WAAW;CACX,YAAY;EAAE,eAAe;EAAI,SAAS;EAAG,IAAI;EAAI,QAAQ;EAAK,aAAa;CAAG;CAClF,SAAS,EAAE,WAAW,MAAM;CAC5B,WAAW,CAAC,QAAQ,OAAO;CAC3B,oBAAoB;CACpB,UAAU,EAAE,QAAQ,kBAAkB;CACtC,OAAO;EAAE,SAAS;EAAO,SAAS;CAAG;AACvC;;AAGA,MAAa,eAAe;CAC1B,MAAM;CACN,YAAY;CACZ,eAAe;CACf,YAAY;AACd;AAEA,MAAM,aAAmD;CACvD;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AACxB,MAAM,yBAAyB;AAE/B,SAAS,QAAQ,QAAgB,UAAyB;CACxD,MAAM,IAAIA,6CACR,SACA,+BAA+B,OAAO,kBAAkB,SAAS,EACnE;AACF;AAEA,SAAS,QAAQ,OAA0C;CACzD,OAAO,UAAU,UAAa,UAAU,KAAK,OAAO;AACtD;AAEA,SAAS,kBAAkB,QAAgB,OAA2B,UAA0B;CAC9F,IAA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