@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.
Files changed (162) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/cjs/app-versions-C_ZyzuvD.cjs +138 -0
  3. package/cjs/app-versions-C_ZyzuvD.cjs.map +1 -0
  4. package/cjs/attach-D5aMqUnA.cjs +1342 -0
  5. package/cjs/attach-D5aMqUnA.cjs.map +1 -0
  6. package/cjs/{auth-DV2GA1A9.cjs → auth-ChHh5E7j.cjs} +20 -13
  7. package/cjs/auth-ChHh5E7j.cjs.map +1 -0
  8. package/cjs/{boot-CyeHPFtk.cjs → boot-Dg5YZGGR.cjs} +78 -14
  9. package/cjs/boot-Dg5YZGGR.cjs.map +1 -0
  10. package/cjs/{capture-DcyBhdqw.cjs → capture-CBgONYhk.cjs} +4 -4
  11. package/cjs/{capture-DcyBhdqw.cjs.map → capture-CBgONYhk.cjs.map} +1 -1
  12. package/cjs/{cascade-store-DEGxAFDI.cjs → cascade-store-DUT2Laha.cjs} +3 -3
  13. package/cjs/cascade-store-DUT2Laha.cjs.map +1 -0
  14. package/cjs/{current-request-id-BoJJb3y7.cjs → current-request-id-Badec-TH.cjs} +3 -3
  15. package/cjs/{current-request-id-BoJJb3y7.cjs.map → current-request-id-Badec-TH.cjs.map} +1 -1
  16. package/cjs/{errors-DEqdWaqm.cjs → errors-DNQ-g49I.cjs} +201 -4
  17. package/cjs/errors-DNQ-g49I.cjs.map +1 -0
  18. package/cjs/extract-8kaX_cUV.cjs +1103 -0
  19. package/cjs/extract-8kaX_cUV.cjs.map +1 -0
  20. package/cjs/{helpers-7k_Q-abk.cjs → helpers-BcMBFy9v.cjs} +9 -6
  21. package/cjs/{helpers-7k_Q-abk.cjs.map → helpers-BcMBFy9v.cjs.map} +1 -1
  22. package/cjs/{histogram-BRV5eHcp.cjs → histogram-CkoVizdf.cjs} +6 -6
  23. package/cjs/{histogram-BRV5eHcp.cjs.map → histogram-CkoVizdf.cjs.map} +1 -1
  24. package/cjs/{http-XNLYU2vS.cjs → http-DCVCf44M.cjs} +26 -9
  25. package/cjs/http-DCVCf44M.cjs.map +1 -0
  26. package/cjs/index.cjs +1 -1
  27. package/cjs/{insights-BBZnUpWO.cjs → insights-CFof59kF.cjs} +6 -6
  28. package/cjs/{insights-BBZnUpWO.cjs.map → insights-CFof59kF.cjs.map} +1 -1
  29. package/cjs/migrations-BQdNOL5_.cjs +30 -0
  30. package/cjs/migrations-BQdNOL5_.cjs.map +1 -0
  31. package/cjs/{migrations-DTTzCNpR.cjs → models-DF1agAm4.cjs} +107 -25
  32. package/cjs/models-DF1agAm4.cjs.map +1 -0
  33. package/cjs/{process-panel-DEOnLxoT.cjs → process-panel-D3D9Y_dc.cjs} +5 -5
  34. package/cjs/{process-panel-DEOnLxoT.cjs.map → process-panel-D3D9Y_dc.cjs.map} +1 -1
  35. package/cjs/production/index.cjs +4 -4
  36. package/cjs/runs-DECWPGnq.cjs +390 -0
  37. package/cjs/runs-DECWPGnq.cjs.map +1 -0
  38. package/cjs/{server-C8JfggQU.cjs → server-CC5DpObz.cjs} +10 -7
  39. package/cjs/server-CC5DpObz.cjs.map +1 -0
  40. package/cjs/{src-DjOUdhKc.cjs → src-VyOjEEAo.cjs} +179 -24
  41. package/cjs/src-VyOjEEAo.cjs.map +1 -0
  42. package/cjs/{store-C06KO_A1.cjs → store-EFn4wp0T.cjs} +2 -2
  43. package/cjs/{stream-route-D4k-sJvW.cjs → stream-route-DFHuIWgg.cjs} +125 -19
  44. package/cjs/stream-route-DFHuIWgg.cjs.map +1 -0
  45. package/esm/ai/attach.mjs +92 -0
  46. package/esm/ai/attach.mjs.map +1 -0
  47. package/esm/ai/options.mjs +31 -0
  48. package/esm/ai/options.mjs.map +1 -0
  49. package/esm/ai/reports/aggregate.mjs +330 -0
  50. package/esm/ai/reports/aggregate.mjs.map +1 -0
  51. package/esm/ai/reports/evaluate.mjs +108 -0
  52. package/esm/ai/reports/evaluate.mjs.map +1 -0
  53. package/esm/ai/reports/range.mjs +121 -0
  54. package/esm/ai/reports/range.mjs.map +1 -0
  55. package/esm/ai/reports/runs.d.mts +2 -0
  56. package/esm/ai/reports/runs.mjs +212 -0
  57. package/esm/ai/reports/runs.mjs.map +1 -0
  58. package/esm/ai/reports/service.mjs +132 -0
  59. package/esm/ai/reports/service.mjs.map +1 -0
  60. package/esm/ai/rollup/cascade-store.mjs +84 -0
  61. package/esm/ai/rollup/cascade-store.mjs.map +1 -0
  62. package/esm/ai/rollup/categories.mjs +67 -0
  63. package/esm/ai/rollup/categories.mjs.map +1 -0
  64. package/esm/ai/rollup/extract.mjs +225 -0
  65. package/esm/ai/rollup/extract.mjs.map +1 -0
  66. package/esm/ai/rollup/file-store.mjs +147 -0
  67. package/esm/ai/rollup/file-store.mjs.map +1 -0
  68. package/esm/ai/rollup/histogram.mjs +42 -0
  69. package/esm/ai/rollup/histogram.mjs.map +1 -0
  70. package/esm/ai/rollup/increment-error.mjs +19 -0
  71. package/esm/ai/rollup/increment-error.mjs.map +1 -0
  72. package/esm/ai/rollup/index.mjs +9 -0
  73. package/esm/ai/rollup/mapping.mjs +69 -0
  74. package/esm/ai/rollup/mapping.mjs.map +1 -0
  75. package/esm/ai/rollup/memory-store.mjs +26 -0
  76. package/esm/ai/rollup/memory-store.mjs.map +1 -0
  77. package/esm/ai/rollup/writer.mjs +113 -0
  78. package/esm/ai/rollup/writer.mjs.map +1 -0
  79. package/esm/ai/types.d.mts +29 -0
  80. package/esm/ai/types.d.mts.map +1 -0
  81. package/esm/app-versions.mjs +74 -0
  82. package/esm/app-versions.mjs.map +1 -0
  83. package/esm/devtools-connector.d.mts.map +1 -1
  84. package/esm/devtools-connector.mjs +54 -2
  85. package/esm/devtools-connector.mjs.map +1 -1
  86. package/esm/index.d.mts +3 -2
  87. package/esm/options.mjs +4 -0
  88. package/esm/options.mjs.map +1 -1
  89. package/esm/production/auth/helpers.mjs +8 -5
  90. package/esm/production/auth/helpers.mjs.map +1 -1
  91. package/esm/production/auth/service.mjs +14 -6
  92. package/esm/production/auth/service.mjs.map +1 -1
  93. package/esm/production/boot.mjs +70 -3
  94. package/esm/production/boot.mjs.map +1 -1
  95. package/esm/production/contracts.d.mts +378 -2
  96. package/esm/production/contracts.d.mts.map +1 -1
  97. package/esm/production/contracts.mjs +64 -2
  98. package/esm/production/contracts.mjs.map +1 -1
  99. package/esm/production/errors.d.mts +1 -1
  100. package/esm/production/errors.mjs +11 -3
  101. package/esm/production/errors.mjs.map +1 -1
  102. package/esm/production/http/access.mjs +6 -0
  103. package/esm/production/http/access.mjs.map +1 -1
  104. package/esm/production/http/mount.mjs +13 -0
  105. package/esm/production/http/mount.mjs.map +1 -1
  106. package/esm/production/http/share-session.mjs.map +1 -1
  107. package/esm/production/index.d.mts +2 -2
  108. package/esm/production/insights/writer.mjs.map +1 -1
  109. package/esm/production/options.d.mts +5 -1
  110. package/esm/production/options.d.mts.map +1 -1
  111. package/esm/production/options.mjs +13 -1
  112. package/esm/production/options.mjs.map +1 -1
  113. package/esm/production/store/memory-store.mjs.map +1 -1
  114. package/esm/production/store/migrations.d.mts +1 -1
  115. package/esm/production/store/migrations.d.mts.map +1 -1
  116. package/esm/production/store/migrations.mjs +4 -2
  117. package/esm/production/store/migrations.mjs.map +1 -1
  118. package/esm/production/store/models/ai-rollup.migration.mjs +48 -0
  119. package/esm/production/store/models/ai-rollup.migration.mjs.map +1 -0
  120. package/esm/production/store/models/ai-rollup.model.mjs +13 -0
  121. package/esm/production/store/models/ai-rollup.model.mjs.map +1 -0
  122. package/esm/production/store/models/index.mjs +3 -1
  123. package/esm/server/ai-report-routes.mjs +72 -0
  124. package/esm/server/ai-report-routes.mjs.map +1 -0
  125. package/esm/server/ai-routes.mjs +41 -6
  126. package/esm/server/ai-routes.mjs.map +1 -1
  127. package/esm/server/index.mjs +2 -0
  128. package/esm/server/index.mjs.map +1 -1
  129. package/esm/server/session-routes.mjs +3 -1
  130. package/esm/server/session-routes.mjs.map +1 -1
  131. package/esm/sources/agent-trace-source.d.mts.map +1 -1
  132. package/esm/sources/agent-trace-source.mjs.map +1 -1
  133. package/esm/sources/ai-source.d.mts +2 -0
  134. package/esm/sources/ai-source.d.mts.map +1 -1
  135. package/esm/sources/ai-source.mjs +120 -11
  136. package/esm/sources/ai-source.mjs.map +1 -1
  137. package/esm/types.d.mts +23 -4
  138. package/esm/types.d.mts.map +1 -1
  139. package/llms-full.txt +79 -32
  140. package/package.json +8 -8
  141. package/skills/SKILL.md +79 -32
  142. package/ui/dashboard/assets/app.css +1 -1
  143. package/ui/dashboard/assets/app.js +23 -16
  144. package/ui/dashboard/build-info.json +7 -7
  145. package/cjs/ai-source-DTpxumMA.cjs +0 -381
  146. package/cjs/ai-source-DTpxumMA.cjs.map +0 -1
  147. package/cjs/auth-DV2GA1A9.cjs.map +0 -1
  148. package/cjs/boot-CyeHPFtk.cjs.map +0 -1
  149. package/cjs/cascade-store-DEGxAFDI.cjs.map +0 -1
  150. package/cjs/contracts-CDuY-ahl.cjs +0 -116
  151. package/cjs/contracts-CDuY-ahl.cjs.map +0 -1
  152. package/cjs/errors-DEqdWaqm.cjs.map +0 -1
  153. package/cjs/http-XNLYU2vS.cjs.map +0 -1
  154. package/cjs/migrations-DTTzCNpR.cjs.map +0 -1
  155. package/cjs/options-CHhmQJic.cjs +0 -193
  156. package/cjs/options-CHhmQJic.cjs.map +0 -1
  157. package/cjs/panels-CHd20RK5.cjs +0 -385
  158. package/cjs/panels-CHd20RK5.cjs.map +0 -1
  159. package/cjs/rolldown-runtime-Zuuoy_Rh.cjs +0 -52
  160. package/cjs/server-C8JfggQU.cjs.map +0 -1
  161. package/cjs/src-DjOUdhKc.cjs.map +0 -1
  162. package/cjs/stream-route-D4k-sJvW.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"auth-DV2GA1A9.cjs","names":["DevtoolsApiError","randomBytes","checkPasswordPolicy","createErrorRef","rateLimitClient","DEVTOOLS_FAILURE_AUDIT_TYPES","generateToken","hashToken","generateRecoveryCode","hashRecoveryCode","normalizeEmail","DevtoolsProductionConfigError","DevtoolsStoreConflictError","safeEqual","normalizeRecoveryCode","isPlausibleEmail"],"sources":["../../../../../../../packages/devtools/src/production/auth/service.ts","../../../../../../../packages/devtools/src/production/auth/default-crypto.ts","../../../../../../../packages/devtools/src/production/auth/passkeys.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport type {\n DevtoolsAccountView,\n DevtoolsAuditType,\n DevtoolsErrorCode,\n DevtoolsInviteView,\n DevtoolsRole,\n DevtoolsSessionInfo,\n DevtoolsSessionStage,\n DevtoolsSessionView,\n} from \"../contracts\";\nimport { DEVTOOLS_FAILURE_AUDIT_TYPES } from \"../contracts\";\nimport {\n createErrorRef,\n DevtoolsApiError,\n DevtoolsProductionConfigError,\n DevtoolsStoreConflictError,\n} from \"../errors\";\nimport { rateLimitClient } from \"../http/ip\";\nimport type {\n DevtoolsAccountPatch,\n DevtoolsAccountRecord,\n DevtoolsInviteRecord,\n DevtoolsSessionPatch,\n DevtoolsSessionRecord,\n} from \"../store/types\";\nimport {\n checkPasswordPolicy,\n generateRecoveryCode,\n generateToken,\n hashRecoveryCode,\n hashToken,\n isPlausibleEmail,\n normalizeEmail,\n normalizeRecoveryCode,\n safeEqual,\n} from \"./helpers\";\nimport type {\n DevtoolsAuthDeps,\n DevtoolsAuthenticated,\n DevtoolsAuthService,\n DevtoolsAuthStep,\n DevtoolsRequestMeta,\n} from \"./types\";\n\ntype Stage = Exclude<DevtoolsSessionStage, \"signed-out\">;\ntype AuditDetail = Record<string, string | number | boolean | null>;\n\nconst MINUTE = 60_000;\nconst HOUR = 60 * MINUTE;\n/** Password verifications (and hashes) a process runs at the same time. */\nconst MAX_IN_FLIGHT = 4;\n/** `lastSeenAt` is written at most this often. */\nconst TOUCH_INTERVAL = MINUTE;\nconst INVITE_TTL = 24 * HOUR;\nconst CHALLENGE_TTL = 5 * MINUTE;\nconst TOTP_ISSUER = \"Warlock monitor\";\nconst RECOVERY_CODE_COUNT = 10;\n/** A password longer than this is cut before hashing, so input size is no CPU lever. */\nconst MAX_PASSWORD_INPUT = 1024;\n/** How long this process remembers that an IP was over its limit. */\nconst IP_BLOCK_CACHE_MS = 30_000;\nconst IP_BLOCK_CACHE_SIZE = 1000;\n/** A refused try is written to the audit log at most this often per address and account. */\nconst BLOCKED_AUDIT_INTERVAL = MINUTE;\nconst BLOCKED_AUDIT_CACHE_SIZE = 1000;\n/** Marks the session as having passed a passkey check a moment ago (sensitive actions). */\nconst STEP_UP_CHALLENGE = \"stepup:ok\";\n/** A stored hash no password can match. */\nconst NO_PASSWORD_HASH = \"!no-password-set\";\n\nconst hasFactor = (account: DevtoolsAccountRecord): boolean =>\n account.totpSecret !== null || account.passkeys.length > 0;\n\nfunction fail(code: DevtoolsErrorCode, ref?: string): never {\n throw new DevtoolsApiError(code, ref === undefined ? {} : { ref });\n}\n\nfunction cut(value: string | null | undefined, length: number): string | null {\n return typeof value === \"string\" ? value.slice(0, length) : null;\n}\n\n/** The accounts, sessions and two-factor service of the production monitor. */\nexport function createDevtoolsAuth(deps: DevtoolsAuthDeps): DevtoolsAuthService {\n const { store, options, crypto, passkeys, instance } = deps;\n const now = deps.now ?? Date.now;\n const limits = options.rateLimits;\n const windowMs = limits.windowMinutes * MINUTE;\n\n let inFlight = 0;\n let dummyHashPromise: Promise<string> | null = null;\n const blockedIps = new Map<string, { until: number; checkedAt: number }>();\n const blockedAudits = new Map<string, { at: number; ref: string }>();\n\n // -------------------------------------------------------------------------\n // Small helpers\n // -------------------------------------------------------------------------\n\n /** Runs password work (hashing or verifying) while fewer than four are in flight. */\n async function withSlot<T>(run: () => Promise<T>): Promise<T> {\n if (inFlight >= MAX_IN_FLIGHT) fail(\"auth.busy\");\n\n inFlight++;\n\n try {\n return await run();\n } finally {\n inFlight--;\n }\n }\n\n function dummyHash(): Promise<string> {\n dummyHashPromise ??= crypto.hashPassword(`devtools-timing-${randomBytes(12).toString(\"hex\")}`);\n\n return dummyHashPromise;\n }\n\n async function verifyPassword(password: string, hash: string): Promise<boolean> {\n try {\n return (await crypto.verifyPassword(password, hash)) === true;\n } catch {\n return false;\n }\n }\n\n const hashPassword = (password: string): Promise<string> =>\n withSlot(() => crypto.hashPassword(password));\n\n const passwordInput = (value: unknown): string =>\n typeof value === \"string\" ? value.slice(0, MAX_PASSWORD_INPUT) : \"\";\n\n function requirePolicy(password: string, email: string): void {\n const problem = checkPasswordPolicy(password, email);\n\n if (problem !== null) fail(problem);\n }\n\n const csrfToken = (session: DevtoolsSessionRecord): string =>\n Buffer.from(crypto.hmac(`devtools-csrf:${session.id}:${session.csrfSecret}`)).toString(\n \"base64url\",\n );\n\n function accountView(account: DevtoolsAccountRecord): DevtoolsAccountView {\n return {\n id: account.id,\n email: account.email,\n role: account.role,\n twoFactor: {\n totp: account.totpSecret !== null,\n passkeys: account.passkeys.map((passkey) => ({\n id: passkey.id,\n name: passkey.name,\n createdAt: passkey.createdAt,\n lastUsedAt: passkey.lastUsedAt,\n })),\n recoveryCodesLeft: account.recoveryCodes.length,\n },\n mustChangePassword: account.mustChangePassword,\n createdAt: account.createdAt,\n lastLoginAt: account.lastLoginAt,\n };\n }\n\n function inviteView(invite: DevtoolsInviteRecord): DevtoolsInviteView {\n return {\n id: invite.id,\n email: invite.email,\n role: invite.role,\n createdAt: invite.createdAt,\n expiresAt: invite.expiresAt,\n createdBy: invite.createdBy,\n usedAt: invite.usedAt,\n };\n }\n\n const twoFactorRequired = (account: DevtoolsAccountRecord): boolean =>\n options.twoFactor === \"everyone\" || account.role === \"admin\";\n\n /** Where an account goes after its password is accepted. */\n function nextStage(account: DevtoolsAccountRecord): Stage {\n if (account.mustChangePassword) return \"password-change\";\n\n if (hasFactor(account)) return \"mfa-verify\";\n\n if (twoFactorRequired(account)) return \"mfa-enrol\";\n\n return \"active\";\n }\n\n function rpIdFor(meta: DevtoolsRequestMeta): string {\n if (options.passkeys.rpId) return options.passkeys.rpId;\n\n if (options.origin) {\n try {\n return new URL(options.origin).hostname;\n } catch {\n // Fall through to the request's host.\n }\n }\n\n return meta.hostname;\n }\n\n // -------------------------------------------------------------------------\n // Audit\n // -------------------------------------------------------------------------\n\n async function audit(\n type: DevtoolsAuditType,\n input: {\n auth?: DevtoolsAuthenticated | null;\n accountId?: string | null;\n email?: string | null;\n meta?: DevtoolsRequestMeta | null;\n detail?: AuditDetail;\n } = {},\n ): Promise<string> {\n const ref = createErrorRef();\n\n try {\n const email = input.email ?? input.auth?.account.email ?? null;\n\n await store.audit.append({\n at: now(),\n type,\n accountId: input.accountId ?? input.auth?.account.id ?? null,\n email: email === null ? null : email.trim().toLowerCase().slice(0, 254),\n ip: input.meta?.ip ?? null,\n userAgent: cut(input.meta?.userAgent, 200),\n detail: input.detail ?? {},\n ref,\n });\n } catch (error) {\n try {\n deps.warn?.(\n `devtools audit write failed (${type}, ref ${ref}): ${error instanceof Error ? error.message : \"unknown error\"}`,\n );\n } catch {\n // Logging must never throw.\n }\n }\n\n return ref;\n }\n\n /**\n * Writes a `login.blocked` entry, at most once a minute per address and\n * account: refused tries cost no password check against the limits, so\n * without this a caller over its limit could grow the audit log without\n * bound. A skipped write answers the reference of the last one.\n */\n async function auditBlocked(input: {\n auth?: DevtoolsAuthenticated | null;\n accountId?: string | null;\n email?: string | null;\n meta: DevtoolsRequestMeta;\n detail?: AuditDetail;\n }): Promise<string> {\n const key = `${rateLimitClient(input.meta.ip)}|${input.accountId ?? input.auth?.account.id ?? \"\"}`;\n const at = now();\n const last = blockedAudits.get(key);\n\n if (last && at - last.at < BLOCKED_AUDIT_INTERVAL) return last.ref;\n\n blockedAudits.delete(key);\n\n if (blockedAudits.size >= BLOCKED_AUDIT_CACHE_SIZE) {\n const oldest = blockedAudits.keys().next();\n\n if (!oldest.done) blockedAudits.delete(oldest.value);\n }\n\n const ref = await audit(\"login.blocked\", input);\n\n blockedAudits.set(key, { at, ref });\n\n return ref;\n }\n\n // -------------------------------------------------------------------------\n // Compare-and-set helpers\n // -------------------------------------------------------------------------\n\n /**\n * Applies the patch `build` makes from the latest record. When another write\n * wins, the record is read again and `build` runs again, so a rule it checks\n * (a replayed TOTP step, a recovery code already used) is checked against\n * the newest data. `build` returns `null` to refuse.\n */\n async function casAccount(\n account: DevtoolsAccountRecord,\n build: (fresh: DevtoolsAccountRecord) => DevtoolsAccountPatch | null,\n ): Promise<DevtoolsAccountRecord | null> {\n let current: DevtoolsAccountRecord | null = account;\n\n for (let attempt = 0; attempt < 4 && current; attempt++) {\n const patch = build(current);\n\n if (patch === null) return null;\n\n const updated = await store.accounts.update(current.id, current.version, patch);\n\n if (updated) return updated;\n\n current = await store.accounts.findById(current.id);\n }\n\n return null;\n }\n\n async function casSession(\n session: DevtoolsSessionRecord,\n build: (fresh: DevtoolsSessionRecord) => DevtoolsSessionPatch | null,\n ): Promise<DevtoolsSessionRecord | null> {\n let current: DevtoolsSessionRecord | null = session;\n\n for (let attempt = 0; attempt < 4 && current; attempt++) {\n const patch = build(current);\n\n if (patch === null) return null;\n\n const updated = await store.sessions.update(current.id, current.version, patch);\n\n if (updated) return updated;\n\n current = await store.sessions.findByTokenHash(current.tokenHash);\n }\n\n return null;\n }\n\n // -------------------------------------------------------------------------\n // Rate limits\n // -------------------------------------------------------------------------\n\n /** Whether the client of `ip` (the address, or its /64 for IPv6) is over the per-IP limit. */\n async function ipOverLimit(ip: string, since: number, stateResetAt: number): Promise<boolean> {\n const client = rateLimitClient(ip);\n const cached = blockedIps.get(client);\n\n if (cached && now() < cached.until && cached.checkedAt >= stateResetAt) return true;\n\n const count = await store.audit.count({\n types: DEVTOOLS_FAILURE_AUDIT_TYPES,\n since,\n ip,\n });\n\n if (count < limits.ip) {\n blockedIps.delete(client);\n\n return false;\n }\n\n if (blockedIps.size >= IP_BLOCK_CACHE_SIZE) {\n const oldest = blockedIps.keys().next();\n\n if (!oldest.done) blockedIps.delete(oldest.value);\n }\n\n blockedIps.set(client, { until: now() + IP_BLOCK_CACHE_MS, checkedAt: now() });\n\n return true;\n }\n\n /** Whether a try from `ip` for `account` is refused: dashboard locked, or the IP or the account is over its limit. */\n async function isBlocked(account: DevtoolsAccountRecord | null, ip: string): Promise<boolean> {\n return (await blockedBy(account, ip)) !== null;\n }\n\n /**\n * Why a try is refused: `\"caller\"` when the dashboard is locked or the IP is\n * over its limit (nothing about the account), `\"account\"` when only the\n * account is, `null` when it is not refused.\n */\n async function blockedBy(\n account: DevtoolsAccountRecord | null,\n ip: string,\n ): Promise<\"caller\" | \"account\" | null> {\n const state = await store.state.read();\n const at = now();\n const stateResetAt = state.failuresResetAt ?? 0;\n const since = Math.max(at - windowMs, stateResetAt);\n const accountSince = Math.max(since, account?.failuresResetAt ?? 0);\n const locked = state.lockedUntil !== null && state.lockedUntil > at;\n // Both counts always run, so an unknown email costs the same queries.\n const overIp = await ipOverLimit(ip, since, stateResetAt);\n const accountCount = await store.audit.count({\n types: DEVTOOLS_FAILURE_AUDIT_TYPES,\n since: accountSince,\n accountId: account?.id ?? \"-\",\n });\n\n if (locked || overIp) return \"caller\";\n\n return account !== null && accountCount >= limits.account ? \"account\" : null;\n }\n\n /** Closes the whole dashboard for `lockMinutes` once failures anywhere reach the global limit. */\n async function lockWhenOverGlobalLimit(meta: DevtoolsRequestMeta): Promise<void> {\n for (let attempt = 0; attempt < 3; attempt++) {\n const state = await store.state.read();\n const at = now();\n\n if (state.lockedUntil !== null && state.lockedUntil > at) return;\n\n const since = Math.max(at - windowMs, state.failuresResetAt ?? 0);\n const count = await store.audit.count({ types: DEVTOOLS_FAILURE_AUDIT_TYPES, since });\n\n if (count < limits.global) return;\n\n const updated = await store.state.update(state.version, {\n lockedUntil: at + limits.lockMinutes * MINUTE,\n });\n\n if (updated) {\n await audit(\"dashboard.locked\", {\n meta,\n detail: { minutes: limits.lockMinutes, failures: count },\n });\n\n return;\n }\n }\n }\n\n async function failLogin(\n type: \"login.failed\" | \"login.blocked\",\n code: DevtoolsErrorCode,\n input: {\n email: string | null;\n accountId?: string | null;\n meta: DevtoolsRequestMeta;\n detail?: AuditDetail;\n },\n ): Promise<never> {\n const ref = type === \"login.blocked\" ? await auditBlocked(input) : await audit(type, input);\n\n if (type === \"login.failed\") await lockWhenOverGlobalLimit(input.meta);\n\n return fail(code, ref);\n }\n\n /** Records a failed second factor (it counts toward the limits) and refuses. */\n async function failSecondFactor(\n auth: DevtoolsAuthenticated,\n meta: DevtoolsRequestMeta,\n method: string,\n code: DevtoolsErrorCode = \"auth.invalid-code\",\n ): Promise<never> {\n const ref = await audit(\"mfa.failed\", { auth, meta, detail: { method } });\n\n await lockWhenOverGlobalLimit(meta);\n\n return fail(code, ref);\n }\n\n /** Refuses a second-factor try while the IP, the account or the dashboard is over its limit. */\n async function guardSecondFactor(\n auth: DevtoolsAuthenticated,\n meta: DevtoolsRequestMeta,\n code: DevtoolsErrorCode = \"auth.invalid-code\",\n ): Promise<void> {\n if (await isBlocked(auth.account, meta.ip)) {\n const ref = await auditBlocked({ auth, meta, detail: { step: \"second-factor\" } });\n\n fail(code, ref);\n }\n }\n\n // -------------------------------------------------------------------------\n // Sessions\n // -------------------------------------------------------------------------\n\n async function createSession(\n account: DevtoolsAccountRecord,\n stage: Stage,\n meta: DevtoolsRequestMeta,\n ): Promise<DevtoolsAuthStep> {\n const token = generateToken();\n const at = now();\n const lifetime =\n stage === \"active\"\n ? options.session.maxHours * HOUR\n : options.session.pendingMinutes * MINUTE;\n const session = await store.sessions.create({\n tokenHash: hashToken(token),\n accountId: account.id,\n stage,\n csrfSecret: randomBytes(32).toString(\"base64url\"),\n createdAt: at,\n lastSeenAt: at,\n expiresAt: at + lifetime,\n ip: meta.ip,\n userAgent: cut(meta.userAgent, 200),\n pendingTotpSecret: null,\n challenge: null,\n challengeExpiresAt: null,\n });\n\n return { stage, token, csrf: csrfToken(session), session };\n }\n\n /**\n * Moves a session to `stage`. Reaching `active` mints a new token (the old\n * session is removed); any other stage changes the session in place.\n */\n async function moveTo(\n auth: DevtoolsAuthenticated,\n account: DevtoolsAccountRecord,\n stage: Stage,\n meta: DevtoolsRequestMeta,\n ): Promise<DevtoolsAuthStep> {\n if (stage === \"active\") {\n // Fully signed in: earlier failures of this account stop counting. Never at the password step, or each new\n // sign-in with a known password would open a fresh round of second-factor guesses.\n const reset = await casAccount(account, () => ({ failuresResetAt: now() }));\n const step = await createSession(reset ?? account, \"active\", meta);\n\n await store.sessions.remove(auth.session.id);\n\n return step;\n }\n\n const session = await casSession(auth.session, () => ({\n stage,\n pendingTotpSecret: null,\n challenge: null,\n challengeExpiresAt: null,\n expiresAt: now() + options.session.pendingMinutes * MINUTE,\n }));\n\n if (!session) fail(\"server.error\");\n\n return { stage, token: null, csrf: csrfToken(session), session };\n }\n\n function requireStage(auth: DevtoolsAuthenticated, ...stages: Stage[]): void {\n if (!stages.includes(auth.stage)) fail(\"input.invalid\");\n }\n\n function requireAdmin(auth: DevtoolsAuthenticated): void {\n if (auth.stage !== \"active\" || auth.account.role !== \"admin\") fail(\"role.forbidden\");\n }\n\n // -------------------------------------------------------------------------\n // Recovery codes\n // -------------------------------------------------------------------------\n\n function newRecoveryCodes(): { codes: string[]; hashes: string[] } {\n const codes = Array.from({ length: RECOVERY_CODE_COUNT }, () => generateRecoveryCode());\n\n return { codes, hashes: codes.map(hashRecoveryCode) };\n }\n\n /** The step a TOTP code matches for this account, or `null` (also `null` when the step was already used). */\n function totpStepFor(account: DevtoolsAccountRecord, code: string): number | null {\n if (account.totpSecret === null) return null;\n\n let secret: string;\n\n try {\n secret = crypto.decrypt(account.totpSecret);\n } catch {\n return null;\n }\n\n return crypto.verifyTotp(secret, String(code ?? \"\"), now());\n }\n\n /** Records `step` as used; refuses when the same or a later step was already accepted. */\n async function consumeTotpStep(\n account: DevtoolsAccountRecord,\n step: number,\n ): Promise<DevtoolsAccountRecord | null> {\n return casAccount(account, (fresh) =>\n fresh.totpLastStep !== null && step <= fresh.totpLastStep ? null : { totpLastStep: step },\n );\n }\n\n // -------------------------------------------------------------------------\n // First admin\n // -------------------------------------------------------------------------\n\n async function ensureFirstAdmin(): Promise<void> {\n const admin = options.admin;\n const email = normalizeEmail(admin.email);\n const existing = email ? await store.accounts.findByEmail(email) : null;\n\n if (existing && existing.role === \"admin\") {\n if (existing.passwordSource === \"env\" && admin.password !== null) {\n const same = await withSlot(() =>\n verifyPassword(admin.password as string, existing.passwordHash),\n );\n\n if (!same) {\n if (checkPasswordPolicy(admin.password, email) !== null) {\n throw new DevtoolsProductionConfigError(\"DT004\");\n }\n\n const hash = await hashPassword(admin.password);\n const updated = await casAccount(existing, (fresh) =>\n fresh.passwordSource === \"env\"\n ? { passwordHash: hash, mustChangePassword: true }\n : null,\n );\n\n if (updated) {\n await store.sessions.removeForAccount(updated.id);\n await audit(\"admin.reset\", { accountId: updated.id, email, detail: { source: \"env\" } });\n }\n }\n }\n\n return;\n }\n\n if ((await store.accounts.countAdmins()) > 0) return;\n\n if (existing || !email || (admin.password === null && admin.setupToken === null)) {\n throw new DevtoolsProductionConfigError(\"DT003\");\n }\n\n let record: Parameters<typeof store.accounts.create>[0];\n\n if (admin.password !== null) {\n if (checkPasswordPolicy(admin.password, email) !== null) {\n throw new DevtoolsProductionConfigError(\"DT004\");\n }\n\n record = {\n email,\n role: \"admin\",\n passwordHash: await hashPassword(admin.password),\n passwordSource: \"env\",\n mustChangePassword: true,\n totpSecret: null,\n totpEnabledAt: null,\n totpLastStep: null,\n recoveryCodes: [],\n passkeys: [],\n failuresResetAt: null,\n lastLoginAt: null,\n createdBy: null,\n };\n } else {\n record = {\n email,\n role: \"admin\",\n passwordHash: NO_PASSWORD_HASH,\n passwordSource: \"setup\",\n mustChangePassword: false,\n totpSecret: null,\n totpEnabledAt: null,\n totpLastStep: null,\n recoveryCodes: [],\n passkeys: [],\n failuresResetAt: null,\n lastLoginAt: null,\n createdBy: null,\n };\n }\n\n try {\n const created = await store.accounts.create(record);\n\n await audit(\"admin.seeded\", {\n accountId: created.id,\n email,\n detail: { source: record.passwordSource },\n });\n } catch (error) {\n // Another instance seeded the same admin at the same time.\n if (!(error instanceof DevtoolsStoreConflictError)) throw error;\n }\n }\n\n // -------------------------------------------------------------------------\n // Sign-in\n // -------------------------------------------------------------------------\n\n async function login(\n input: { email: string; password: string },\n meta: DevtoolsRequestMeta,\n ): Promise<DevtoolsAuthStep> {\n const email = normalizeEmail(input?.email);\n const password = passwordInput(input?.password);\n const account = email ? await store.accounts.findByEmail(email) : null;\n const blockedReason = await blockedBy(account, meta.ip);\n const blocked = blockedReason !== null;\n const verifiable =\n !blocked && account !== null && !account.passwordHash.startsWith(\"!\") && password !== \"\";\n // Unknown email, blocked account or unusable hash: verify against a dummy\n // hash so the answer takes as long as a real check. A caller that is over\n // its own limit (or a locked dashboard) learns nothing about the account\n // from the timing, so it costs no password work at all: a blocked address\n // is no lever on the app's CPU and cannot hold the verification slots.\n const hash = verifiable && account ? account.passwordHash : await dummyHash();\n const matches =\n blockedReason === \"caller\" ? false : await withSlot(() => verifyPassword(password, hash));\n\n if (blocked) {\n return failLogin(\"login.blocked\", \"auth.invalid-credentials\", {\n email: email || null,\n accountId: account?.id ?? null,\n meta,\n });\n }\n\n if (!verifiable || !matches || account === null) {\n return failLogin(\"login.failed\", \"auth.invalid-credentials\", {\n email: email || null,\n accountId: account?.id ?? null,\n meta,\n });\n }\n\n const at = now();\n // The failures count resets only when the password alone completes the sign-in (see `moveTo`).\n const updated = await casAccount(account, (fresh) =>\n nextStage(fresh) === \"active\"\n ? { failuresResetAt: at, lastLoginAt: at }\n : { lastLoginAt: at },\n );\n\n if (!updated) return failLogin(\"login.failed\", \"auth.invalid-credentials\", { email, meta });\n\n await audit(\"login.succeeded\", { accountId: updated.id, email, meta });\n\n return createSession(updated, nextStage(updated), meta);\n }\n\n async function setup(\n input: { token: string; password: string },\n meta: DevtoolsRequestMeta,\n ): Promise<DevtoolsAuthStep> {\n const configured = options.admin.setupToken;\n const adminEmail = normalizeEmail(options.admin.email);\n const account = adminEmail ? await store.accounts.findByEmail(adminEmail) : null;\n const blocked = await isBlocked(null, meta.ip);\n const tokenMatches = safeEqual(\n hashToken(typeof input?.token === \"string\" ? input.token : \"\"),\n hashToken(configured ?? \"\"),\n );\n const usable =\n configured !== null && tokenMatches && account !== null && account.passwordSource === \"setup\";\n\n if (blocked) {\n return failLogin(\"login.blocked\", \"auth.invalid-setup-token\", {\n email: adminEmail || null,\n meta,\n detail: { via: \"setup\" },\n });\n }\n\n if (!usable || account === null) {\n return failLogin(\"login.failed\", \"auth.invalid-setup-token\", {\n email: adminEmail || null,\n meta,\n detail: { via: \"setup\" },\n });\n }\n\n const password = passwordInput(input.password);\n\n requirePolicy(password, account.email);\n\n const passwordHash = await hashPassword(password);\n const at = now();\n const updated = await casAccount(account, (fresh) =>\n fresh.passwordSource === \"setup\"\n ? {\n passwordHash,\n passwordSource: \"user\",\n mustChangePassword: false,\n failuresResetAt: at,\n lastLoginAt: at,\n }\n : null,\n );\n\n // Another request completed the setup first: the token is spent.\n if (!updated) fail(\"auth.invalid-setup-token\");\n\n await audit(\"setup.completed\", { accountId: updated.id, email: updated.email, meta });\n\n return createSession(updated, nextStage(updated), meta);\n }\n\n async function findOpenInvite(token: string): Promise<DevtoolsInviteRecord> {\n if (typeof token !== \"string\" || token === \"\" || token.length > 200) fail(\"invite.invalid\");\n\n const invite = await store.invites.findByTokenHash(hashToken(token));\n\n if (!invite || invite.usedAt !== null || invite.expiresAt <= now()) fail(\"invite.invalid\");\n\n return invite;\n }\n\n async function inspectInvite(token: string): Promise<{ email: string; role: DevtoolsRole }> {\n const invite = await findOpenInvite(token);\n\n return { email: invite.email, role: invite.role };\n }\n\n async function acceptInvite(\n input: { token: string; password: string },\n meta: DevtoolsRequestMeta,\n ): Promise<DevtoolsAuthStep> {\n const invite = await findOpenInvite(input?.token);\n const password = passwordInput(input.password);\n\n requirePolicy(password, invite.email);\n\n const passwordHash = await hashPassword(password);\n\n // The invite is spent before the account exists; the loser of a race stops here.\n if (!(await store.invites.markUsed(invite.id, now(), \"pending\"))) fail(\"invite.invalid\");\n\n let account: DevtoolsAccountRecord;\n\n try {\n account = await store.accounts.create({\n email: invite.email,\n role: invite.role,\n passwordHash,\n passwordSource: \"invite\",\n mustChangePassword: false,\n totpSecret: null,\n totpEnabledAt: null,\n totpLastStep: null,\n recoveryCodes: [],\n passkeys: [],\n failuresResetAt: null,\n lastLoginAt: now(),\n createdBy: invite.createdBy,\n });\n } catch (error) {\n if (error instanceof DevtoolsStoreConflictError) fail(\"invite.email-taken\");\n\n throw error;\n }\n\n await audit(\"invite.accepted\", {\n accountId: account.id,\n email: account.email,\n meta,\n detail: { role: account.role },\n });\n\n return createSession(account, nextStage(account), meta);\n }\n\n // -------------------------------------------------------------------------\n // Sessions in use\n // -------------------------------------------------------------------------\n\n async function authenticate(token: string | undefined): Promise<DevtoolsAuthenticated | null> {\n if (typeof token !== \"string\" || token === \"\" || token.length > 200) return null;\n\n const session = await store.sessions.findByTokenHash(hashToken(token));\n\n if (!session) return null;\n\n const at = now();\n\n if (at >= session.expiresAt || at - session.lastSeenAt > options.session.idleMinutes * MINUTE) {\n await store.sessions.remove(session.id);\n\n return null;\n }\n\n const account = await store.accounts.findById(session.accountId);\n\n if (!account) {\n await store.sessions.remove(session.id);\n\n return null;\n }\n\n let current = session;\n\n if (at - session.lastSeenAt >= TOUCH_INTERVAL) {\n // A lost race only means another request touched the session first.\n const touched = await store.sessions.update(session.id, session.version, { lastSeenAt: at });\n\n if (touched) current = touched;\n }\n\n return { session: current, account, stage: current.stage };\n }\n\n function verifyCsrf(auth: DevtoolsAuthenticated, header: string | undefined): boolean {\n if (typeof header !== \"string\" || header === \"\") return false;\n\n return safeEqual(header, csrfToken(auth.session));\n }\n\n function sessionView(auth: DevtoolsAuthenticated | null): DevtoolsSessionView {\n if (!auth) {\n return {\n mode: \"production\",\n stage: \"signed-out\",\n account: null,\n role: null,\n csrf: null,\n expiresAt: null,\n instance: null,\n methods: null,\n share: null,\n };\n }\n\n return {\n mode: \"production\",\n stage: auth.stage,\n account: accountView(auth.account),\n role: auth.account.role,\n csrf: csrfToken(auth.session),\n expiresAt: auth.session.expiresAt,\n instance,\n methods: { totp: true, passkeys: passkeys !== null },\n share: { enabled: options.share.enabled },\n };\n }\n\n async function logout(auth: DevtoolsAuthenticated, meta: DevtoolsRequestMeta): Promise<void> {\n await store.sessions.remove(auth.session.id);\n await audit(\"logout\", { auth, meta });\n }\n\n async function listSessions(auth: DevtoolsAuthenticated): Promise<DevtoolsSessionInfo[]> {\n const at = now();\n const sessions = await store.sessions.listForAccount(auth.account.id);\n\n return sessions\n .filter((session) => session.expiresAt > at)\n .map((session) => ({\n id: session.id,\n current: session.id === auth.session.id,\n createdAt: session.createdAt,\n lastSeenAt: session.lastSeenAt,\n expiresAt: session.expiresAt,\n ip: session.ip,\n userAgent: session.userAgent,\n }));\n }\n\n async function revokeSession(\n auth: DevtoolsAuthenticated,\n sessionId: string,\n meta: DevtoolsRequestMeta,\n ): Promise<void> {\n // Only the caller's own sessions can be found here.\n const own = (await store.sessions.listForAccount(auth.account.id)).find(\n (session) => session.id === sessionId,\n );\n\n if (!own) fail(\"account.not-found\");\n\n await store.sessions.remove(own.id);\n await audit(\"session.revoked\", { auth, meta, detail: { current: own.id === auth.session.id } });\n }\n\n // -------------------------------------------------------------------------\n // Proving the owner again\n // -------------------------------------------------------------------------\n\n /**\n * Checks the current password of an active session. A wrong one counts\n * toward the sign-in limits like a failed sign-in.\n */\n async function requireCurrentPassword(\n auth: DevtoolsAuthenticated,\n given: string | undefined,\n meta: DevtoolsRequestMeta,\n ): Promise<void> {\n const current = passwordInput(given);\n const stored = auth.account.passwordHash;\n const verifiable = !stored.startsWith(\"!\") && current !== \"\";\n\n if (await isBlocked(auth.account, meta.ip)) {\n await verifyPassword(current, await dummyHash());\n\n const ref = await auditBlocked({ auth, meta, detail: { step: \"password\" } });\n\n fail(\"auth.wrong-current-password\", ref);\n }\n\n const matches = await withSlot(async () =>\n verifyPassword(current, verifiable ? stored : await dummyHash()),\n );\n\n if (!verifiable || !matches) {\n const ref = await audit(\"login.failed\", { auth, meta, detail: { step: \"password\" } });\n\n await lockWhenOverGlobalLimit(meta);\n\n fail(\"auth.wrong-current-password\", ref);\n }\n }\n\n /**\n * Spends the session's step-up (a passkey check passed in this session in\n * the last five minutes). Compare-and-set, so two requests racing on one\n * step-up cannot both use it. Returns whether it was there to spend.\n */\n async function consumeStepUp(session: DevtoolsSessionRecord): Promise<boolean> {\n const spent = await casSession(session, (fresh) =>\n fresh.challenge === STEP_UP_CHALLENGE &&\n fresh.challengeExpiresAt !== null &&\n fresh.challengeExpiresAt > now()\n ? { challenge: null, challengeExpiresAt: null }\n : null,\n );\n\n return spent !== null;\n }\n\n /**\n * Before an active session adds or removes a second factor: the current\n * password, or, when none is given, a fresh step-up, so a stolen session\n * cookie alone cannot change how the account signs in. Not asked while\n * enrolling the first factor at sign-in, which follows the password.\n */\n async function requireOwner(\n auth: DevtoolsAuthenticated,\n current: string | undefined,\n meta: DevtoolsRequestMeta,\n ): Promise<void> {\n if (auth.stage !== \"active\") return;\n\n if ((current === undefined || current === \"\") && (await consumeStepUp(auth.session))) return;\n\n await requireCurrentPassword(auth, current, meta);\n }\n\n // -------------------------------------------------------------------------\n // Password change\n // -------------------------------------------------------------------------\n\n async function changePassword(\n auth: DevtoolsAuthenticated,\n input: { current?: string; password: string },\n meta: DevtoolsRequestMeta,\n ): Promise<DevtoolsAuthStep> {\n requireStage(auth, \"password-change\", \"active\");\n\n const password = passwordInput(input?.password);\n\n if (auth.stage === \"active\") await requireCurrentPassword(auth, input?.current, meta);\n\n requirePolicy(password, auth.account.email);\n\n if (await withSlot(() => verifyPassword(password, auth.account.passwordHash))) {\n fail(\"auth.password-unchanged\");\n }\n\n const passwordHash = await hashPassword(password);\n const updated = await casAccount(auth.account, () => ({\n passwordHash,\n passwordSource: \"user\",\n mustChangePassword: false,\n }));\n\n if (!updated) fail(\"server.error\");\n\n await audit(\"password.changed\", { auth, meta });\n // Every other session of the account ends with the old password.\n await store.sessions.removeForAccount(updated.id, auth.session.id);\n\n if (auth.stage === \"active\") {\n return { stage: \"active\", token: null, csrf: csrfToken(auth.session), session: auth.session };\n }\n\n return moveTo(auth, updated, nextStage(updated), meta);\n }\n\n // -------------------------------------------------------------------------\n // TOTP\n // -------------------------------------------------------------------------\n\n async function startTotp(auth: DevtoolsAuthenticated, _meta: DevtoolsRequestMeta) {\n requireStage(auth, \"mfa-enrol\", \"active\");\n\n // Replacing an app needs it removed first, so a hijacked session cannot swap it silently.\n if (auth.account.totpSecret !== null) fail(\"input.invalid\");\n\n const secret = crypto.generateTotpSecret();\n const saved = await casSession(auth.session, () => ({\n pendingTotpSecret: crypto.encrypt(secret),\n }));\n\n if (!saved) fail(\"server.error\");\n\n return {\n secret,\n uri: crypto.totpUri({ secret, account: auth.account.email, issuer: TOTP_ISSUER }),\n issuer: TOTP_ISSUER,\n account: auth.account.email,\n };\n }\n\n async function confirmTotp(\n auth: DevtoolsAuthenticated,\n code: string,\n meta: DevtoolsRequestMeta,\n current?: string,\n ): Promise<{ step: DevtoolsAuthStep; recoveryCodes: string[] | null }> {\n requireStage(auth, \"mfa-enrol\", \"active\");\n\n const pending = auth.session.pendingTotpSecret;\n\n if (pending === null) fail(\"input.invalid\");\n\n await requireOwner(auth, current, meta);\n await guardSecondFactor(auth, meta);\n\n let secret: string;\n\n try {\n secret = crypto.decrypt(pending);\n } catch {\n return failSecondFactor(auth, meta, \"totp\");\n }\n\n const step = crypto.verifyTotp(secret, String(code ?? \"\"), now());\n\n if (step === null) return failSecondFactor(auth, meta, \"totp\");\n\n const fresh = newRecoveryCodes();\n let issued = null as string[] | null;\n const updated = await casAccount(auth.account, (account) => {\n if (account.totpSecret !== null) return null;\n\n issued = account.recoveryCodes.length === 0 ? fresh.codes : null;\n\n return {\n totpSecret: pending,\n totpEnabledAt: now(),\n totpLastStep: step,\n ...(issued ? { recoveryCodes: fresh.hashes } : {}),\n };\n });\n\n if (!updated) fail(\"input.invalid\");\n\n await audit(\"mfa.enrolled\", { auth, meta, detail: { method: \"totp\" } });\n\n if (auth.stage === \"mfa-enrol\") {\n return { step: await moveTo(auth, updated, \"active\", meta), recoveryCodes: issued };\n }\n\n const session = await casSession(auth.session, () => ({ pendingTotpSecret: null }));\n\n return {\n step: {\n stage: \"active\",\n token: null,\n csrf: csrfToken(auth.session),\n session: session ?? auth.session,\n },\n recoveryCodes: issued,\n };\n }\n\n async function removeTotp(\n auth: DevtoolsAuthenticated,\n meta: DevtoolsRequestMeta,\n current?: string,\n ): Promise<void> {\n requireStage(auth, \"active\");\n\n if (auth.account.totpSecret === null) return;\n\n if (twoFactorRequired(auth.account) && auth.account.passkeys.length === 0) {\n fail(\"account.last-factor\");\n }\n\n await requireOwner(auth, current, meta);\n\n const updated = await casAccount(auth.account, (account) => ({\n totpSecret: null,\n totpEnabledAt: null,\n totpLastStep: null,\n ...(account.passkeys.length === 0 ? { recoveryCodes: [] } : {}),\n }));\n\n if (!updated) fail(\"server.error\");\n\n await audit(\"mfa.removed\", { auth, meta, detail: { method: \"totp\" } });\n }\n\n async function verifySecondFactor(\n auth: DevtoolsAuthenticated,\n input: { code?: string; recoveryCode?: string },\n meta: DevtoolsRequestMeta,\n ): Promise<DevtoolsAuthStep> {\n requireStage(auth, \"mfa-verify\");\n\n const hasCode = typeof input?.code === \"string\" && input.code !== \"\";\n const hasRecovery = typeof input?.recoveryCode === \"string\" && input.recoveryCode !== \"\";\n\n if (!hasCode && !hasRecovery) fail(\"input.invalid\");\n\n await guardSecondFactor(auth, meta);\n\n if (hasCode) {\n const step = totpStepFor(auth.account, input.code as string);\n const consumed = step === null ? null : await consumeTotpStep(auth.account, step);\n\n if (!consumed) return failSecondFactor(auth, meta, \"totp\");\n\n await audit(\"mfa.succeeded\", { auth, meta, detail: { method: \"totp\" } });\n\n return moveTo(auth, consumed, \"active\", meta);\n }\n\n const given = hashRecoveryCode(input.recoveryCode as string);\n let left = 0 as number;\n // No early exit: every stored hash is compared.\n const used = await casAccount(auth.account, (account) => {\n let found = -1;\n\n account.recoveryCodes.forEach((stored, index) => {\n if (\n safeEqual(stored, given) &&\n normalizeRecoveryCode(input.recoveryCode as string).length === 10\n ) {\n found = index;\n }\n });\n\n if (found === -1) return null;\n\n const remaining = account.recoveryCodes.filter((_, index) => index !== found);\n\n left = remaining.length;\n\n return { recoveryCodes: remaining };\n });\n\n if (!used) return failSecondFactor(auth, meta, \"recovery-code\");\n\n await audit(\"recovery-code.used\", { auth, meta, detail: { left } });\n\n return moveTo(auth, used, \"active\", meta);\n }\n\n async function regenerateRecoveryCodes(\n auth: DevtoolsAuthenticated,\n code: string,\n meta: DevtoolsRequestMeta,\n ): Promise<string[]> {\n requireStage(auth, \"active\");\n await guardSecondFactor(auth, meta);\n\n let account = auth.account;\n\n if (typeof code === \"string\" && code !== \"\" && account.totpSecret !== null) {\n const step = totpStepFor(account, code);\n const consumed = step === null ? null : await consumeTotpStep(account, step);\n\n if (!consumed) return failSecondFactor(auth, meta, \"totp\");\n\n account = consumed;\n } else if (!(await consumeStepUp(auth.session))) {\n // No step-up, or a parallel request spent it first.\n return failSecondFactor(auth, meta, \"totp\");\n }\n\n const fresh = newRecoveryCodes();\n const updated = await casAccount(account, () => ({ recoveryCodes: fresh.hashes }));\n\n if (!updated) fail(\"server.error\");\n\n await audit(\"recovery-codes.regenerated\", { auth, meta });\n\n return fresh.codes;\n }\n\n // -------------------------------------------------------------------------\n // Passkeys\n // -------------------------------------------------------------------------\n\n function requirePasskeys() {\n if (passkeys === null) fail(\"passkey.unavailable\");\n\n return passkeys;\n }\n\n async function passkeyOptions(\n auth: DevtoolsAuthenticated,\n purpose: \"register\" | \"login\",\n meta: DevtoolsRequestMeta,\n ): Promise<unknown> {\n const adapter = requirePasskeys();\n\n if (purpose === \"register\") requireStage(auth, \"mfa-enrol\", \"active\");\n else requireStage(auth, \"mfa-verify\", \"active\");\n\n const rpId = rpIdFor(meta);\n let result: { options: unknown; challenge: string };\n\n if (purpose === \"register\") {\n result = await adapter.registrationOptions({\n account: auth.account,\n rpId,\n rpName: options.passkeys.rpName,\n });\n } else {\n if (auth.account.passkeys.length === 0) fail(\"passkey.failed\");\n\n await guardSecondFactor(auth, meta, \"passkey.failed\");\n\n result = await adapter.authenticationOptions({ account: auth.account, rpId });\n }\n\n const saved = await casSession(auth.session, () => ({\n challenge: result.challenge,\n challengeExpiresAt: now() + CHALLENGE_TTL,\n }));\n\n if (!saved) fail(\"server.error\");\n\n return result.options;\n }\n\n async function verifyPasskey(\n auth: DevtoolsAuthenticated,\n purpose: \"register\" | \"login\",\n response: unknown,\n meta: DevtoolsRequestMeta,\n current?: string,\n ): Promise<{ step: DevtoolsAuthStep | null; recoveryCodes: string[] | null }> {\n const adapter = requirePasskeys();\n\n if (purpose === \"register\") requireStage(auth, \"mfa-enrol\", \"active\");\n else requireStage(auth, \"mfa-verify\", \"active\");\n\n if (purpose === \"login\") await guardSecondFactor(auth, meta, \"passkey.failed\");\n // The registration challenge replaced any step-up, so an active session gives its password here.\n else if (auth.stage === \"active\") await requireCurrentPassword(auth, current, meta);\n\n const challenge = auth.session.challenge;\n const live =\n challenge !== null &&\n challenge !== STEP_UP_CHALLENGE &&\n auth.session.challengeExpiresAt !== null &&\n auth.session.challengeExpiresAt > now();\n\n // The challenge is single use: it is cleared before the answer is checked.\n const consumed = live\n ? await casSession(auth.session, (fresh) =>\n fresh.challenge === challenge ? { challenge: null, challengeExpiresAt: null } : null,\n )\n : null;\n\n if (!live || !consumed || challenge === null) {\n return purpose === \"login\"\n ? failSecondFactor(auth, meta, \"passkey\", \"passkey.failed\")\n : fail(\"passkey.failed\");\n }\n\n const rpId = rpIdFor(meta);\n\n if (purpose === \"register\") {\n let credential: Awaited<ReturnType<typeof adapter.verifyRegistration>>;\n\n try {\n credential = await adapter.verifyRegistration({\n response,\n challenge,\n origin: meta.origin,\n rpId,\n });\n } catch {\n return fail(\"passkey.failed\");\n }\n\n if (auth.account.passkeys.some((passkey) => passkey.id === credential.id)) {\n fail(\"passkey.failed\");\n }\n\n const fresh = newRecoveryCodes();\n let issued = null as string[] | null;\n const label = `Passkey added ${new Date(now()).toISOString().slice(0, 10)}`;\n const updated = await casAccount(auth.account, (account) => {\n if (account.passkeys.some((passkey) => passkey.id === credential.id)) return null;\n\n issued = account.recoveryCodes.length === 0 ? fresh.codes : null;\n\n return {\n passkeys: [\n ...account.passkeys,\n {\n id: credential.id,\n publicKey: credential.publicKey,\n counter: credential.counter,\n transports: credential.transports,\n name: label,\n createdAt: now(),\n lastUsedAt: null,\n },\n ],\n ...(issued ? { recoveryCodes: fresh.hashes } : {}),\n };\n });\n\n if (!updated) fail(\"passkey.failed\");\n\n await audit(\"passkey.added\", { auth, meta });\n\n if (auth.stage === \"mfa-enrol\") {\n return { step: await moveTo(auth, updated, \"active\", meta), recoveryCodes: issued };\n }\n\n return { step: null, recoveryCodes: issued };\n }\n\n let verified: { id: string; newCounter: number };\n\n try {\n verified = await adapter.verifyAuthentication({\n response,\n challenge,\n origin: meta.origin,\n rpId,\n account: auth.account,\n });\n } catch {\n return failSecondFactor(auth, meta, \"passkey\", \"passkey.failed\");\n }\n\n const updated = await casAccount(auth.account, (account) => {\n if (!account.passkeys.some((passkey) => passkey.id === verified.id)) return null;\n\n return {\n passkeys: account.passkeys.map((passkey) =>\n passkey.id === verified.id\n ? { ...passkey, counter: verified.newCounter, lastUsedAt: now() }\n : passkey,\n ),\n };\n });\n\n if (!updated) return failSecondFactor(auth, meta, \"passkey\", \"passkey.failed\");\n\n await audit(\"mfa.succeeded\", { auth, meta, detail: { method: \"passkey\" } });\n\n if (auth.stage === \"mfa-verify\") {\n return { step: await moveTo(auth, updated, \"active\", meta), recoveryCodes: null };\n }\n\n // An active session proved itself again: sensitive actions are open for five minutes.\n await casSession(auth.session, () => ({\n challenge: STEP_UP_CHALLENGE,\n challengeExpiresAt: now() + CHALLENGE_TTL,\n }));\n\n return { step: null, recoveryCodes: null };\n }\n\n async function removePasskey(\n auth: DevtoolsAuthenticated,\n passkeyId: string,\n meta: DevtoolsRequestMeta,\n current?: string,\n ): Promise<void> {\n requireStage(auth, \"active\");\n\n if (!auth.account.passkeys.some((passkey) => passkey.id === passkeyId))\n fail(\"account.not-found\");\n\n if (\n twoFactorRequired(auth.account) &&\n auth.account.totpSecret === null &&\n auth.account.passkeys.length === 1\n ) {\n fail(\"account.last-factor\");\n }\n\n await requireOwner(auth, current, meta);\n\n const updated = await casAccount(auth.account, (account) => {\n const remaining = account.passkeys.filter((passkey) => passkey.id !== passkeyId);\n\n return {\n passkeys: remaining,\n ...(remaining.length === 0 && account.totpSecret === null ? { recoveryCodes: [] } : {}),\n };\n });\n\n if (!updated) fail(\"server.error\");\n\n await audit(\"passkey.removed\", { auth, meta });\n }\n\n // -------------------------------------------------------------------------\n // Admin actions\n // -------------------------------------------------------------------------\n\n async function listUsers(auth: DevtoolsAuthenticated) {\n requireAdmin(auth);\n\n const at = now();\n const [accounts, invites] = await Promise.all([store.accounts.list(), store.invites.list()]);\n\n return {\n accounts: accounts.map(accountView),\n invites: invites.filter((invite) => invite.expiresAt > at).map(inviteView),\n };\n }\n\n async function createInvite(\n auth: DevtoolsAuthenticated,\n input: { email: string; role: DevtoolsRole },\n meta: DevtoolsRequestMeta,\n ) {\n requireAdmin(auth);\n\n const email = normalizeEmail(input?.email);\n\n if (!isPlausibleEmail(email) || (input.role !== \"admin\" && input.role !== \"viewer\")) {\n fail(\"input.invalid\");\n }\n\n if (await store.accounts.findByEmail(email)) fail(\"invite.email-taken\");\n\n const token = generateToken();\n const at = now();\n const invite = await store.invites.create({\n tokenHash: hashToken(token),\n email,\n role: input.role,\n createdBy: auth.account.id,\n createdAt: at,\n expiresAt: at + INVITE_TTL,\n });\n\n await audit(\"invite.created\", { auth, meta, detail: { invitee: email, role: input.role } });\n\n return { invite: inviteView(invite), token };\n }\n\n async function revokeInvite(\n auth: DevtoolsAuthenticated,\n inviteId: string,\n meta: DevtoolsRequestMeta,\n ): Promise<void> {\n requireAdmin(auth);\n\n if (!(await store.invites.remove(inviteId))) fail(\"invite.invalid\");\n\n await audit(\"invite.revoked\", { auth, meta, detail: { invite: inviteId } });\n }\n\n async function targetAccount(accountId: string): Promise<DevtoolsAccountRecord> {\n const target = await store.accounts.findById(accountId);\n\n if (!target) fail(\"account.not-found\");\n\n return target;\n }\n\n async function setRole(\n auth: DevtoolsAuthenticated,\n accountId: string,\n role: DevtoolsRole,\n meta: DevtoolsRequestMeta,\n ): Promise<DevtoolsAccountView> {\n requireAdmin(auth);\n\n if (role !== \"admin\" && role !== \"viewer\") fail(\"input.invalid\");\n\n const target = await targetAccount(accountId);\n\n if (target.id === auth.account.id) fail(\"account.self\");\n\n if (target.role === role) return accountView(target);\n\n if (target.role === \"admin\" && (await store.accounts.countAdmins()) <= 1) {\n fail(\"account.last-admin\");\n }\n\n const updated = await casAccount(target, () => ({ role }));\n\n if (!updated) fail(\"account.not-found\");\n\n // An admin without a second factor enrols at the next sign-in.\n if (role === \"admin\" && options.twoFactor === \"admins\" && !hasFactor(updated)) {\n await store.sessions.removeForAccount(updated.id);\n }\n\n await audit(\"account.role-changed\", {\n auth,\n meta,\n detail: { target: updated.email, from: target.role, to: role },\n });\n\n return accountView(updated);\n }\n\n async function removeAccount(\n auth: DevtoolsAuthenticated,\n accountId: string,\n meta: DevtoolsRequestMeta,\n ): Promise<void> {\n requireAdmin(auth);\n\n const target = await targetAccount(accountId);\n\n if (target.id === auth.account.id) fail(\"account.self\");\n\n if (target.role === \"admin\" && (await store.accounts.countAdmins()) <= 1) {\n fail(\"account.last-admin\");\n }\n\n await store.sessions.removeForAccount(target.id);\n await store.accounts.remove(target.id);\n await audit(\"account.removed\", { auth, meta, detail: { target: target.email } });\n }\n\n async function resetSecondFactor(\n auth: DevtoolsAuthenticated,\n accountId: string,\n meta: DevtoolsRequestMeta,\n ): Promise<void> {\n requireAdmin(auth);\n\n const target = await targetAccount(accountId);\n\n if (target.id === auth.account.id) fail(\"account.self\");\n\n const updated = await casAccount(target, () => ({\n totpSecret: null,\n totpEnabledAt: null,\n totpLastStep: null,\n recoveryCodes: [],\n passkeys: [],\n }));\n\n if (!updated) fail(\"account.not-found\");\n\n await store.sessions.removeForAccount(updated.id);\n await audit(\"account.mfa-reset\", { auth, meta, detail: { target: updated.email } });\n }\n\n async function signOutAccount(\n auth: DevtoolsAuthenticated,\n accountId: string,\n meta: DevtoolsRequestMeta,\n ): Promise<void> {\n requireAdmin(auth);\n\n const target = await targetAccount(accountId);\n const removed = await store.sessions.removeForAccount(\n target.id,\n target.id === auth.account.id ? auth.session.id : undefined,\n );\n\n await audit(\"account.signed-out\", {\n auth,\n meta,\n detail: { target: target.email, sessions: removed },\n });\n }\n\n async function disableDashboard(\n auth: DevtoolsAuthenticated,\n meta: DevtoolsRequestMeta,\n ): Promise<void> {\n requireAdmin(auth);\n\n for (let attempt = 0; attempt < 3; attempt++) {\n const state = await store.state.read();\n const updated = await store.state.update(state.version, {\n disabled: true,\n disabledPathHash: hashToken(options.path),\n disabledAt: now(),\n disabledBy: auth.account.id,\n });\n\n if (updated) {\n await audit(\"dashboard.disabled\", { auth, meta });\n\n return;\n }\n }\n\n fail(\"server.error\");\n }\n\n return {\n ensureFirstAdmin,\n login,\n setup,\n inspectInvite,\n acceptInvite,\n authenticate,\n verifyCsrf,\n changePassword,\n startTotp,\n confirmTotp,\n removeTotp,\n verifySecondFactor,\n regenerateRecoveryCodes,\n passkeyOptions,\n verifyPasskey,\n removePasskey,\n logout,\n listSessions,\n revokeSession,\n sessionView,\n csrfToken,\n accountView,\n listUsers,\n createInvite,\n revokeInvite,\n setRole,\n removeAccount,\n resetSecondFactor,\n signOutAccount,\n disableDashboard,\n audit: (type, input) => audit(type, input),\n };\n}\n","import type { DevtoolsCrypto } from \"./types\";\n\n/** Core's password hashing, encryption and TOTP helpers, loaded lazily. */\nexport async function defaultDevtoolsCrypto(): Promise<DevtoolsCrypto> {\n const core = await import(\"@warlock.js/core\");\n\n return {\n hashPassword: (password) => core.hashPassword(password),\n verifyPassword: (password, hash) => core.verifyPassword(password, hash),\n encrypt: (plain) => core.encrypt(plain),\n decrypt: (cipher) => core.decrypt(cipher),\n generateTotpSecret: () => core.generateTotpSecret(),\n verifyTotp: (secret, code, at) => core.verifyTotp(secret, code, { at }),\n totpUri: (input) => core.totpUri(input),\n hmac: (value) => core.hmacHash(value),\n };\n}\n","import type { DevtoolsPasskeys } from \"./types\";\n\ntype Options = Record<string, unknown>;\n\n/** The slice of `@simplewebauthn/server` (v13) the monitor uses; the package is an optional peer. */\ntype SimpleWebAuthnServer = {\n generateRegistrationOptions: (options: Options) => Promise<{ challenge: string }>;\n verifyRegistrationResponse: (options: Options) => Promise<{\n verified: boolean;\n registrationInfo?: {\n credential: {\n id: string;\n publicKey: Uint8Array;\n counter: number;\n transports?: string[];\n };\n };\n }>;\n generateAuthenticationOptions: (options: Options) => Promise<{ challenge: string }>;\n verifyAuthenticationResponse: (options: Options) => Promise<{\n verified: boolean;\n authenticationInfo: { newCounter: number };\n }>;\n};\n\n/**\n * Passkey ceremonies over `@simplewebauthn/server`, or `null` when that\n * package cannot be imported.\n */\nexport async function loadDevtoolsPasskeys(): Promise<DevtoolsPasskeys | null> {\n let webauthn: SimpleWebAuthnServer;\n\n try {\n const specifier = \"@simplewebauthn/server\";\n\n webauthn = (await import(/* @vite-ignore */ specifier)) as SimpleWebAuthnServer;\n\n if (typeof webauthn.generateRegistrationOptions !== \"function\") return null;\n } catch {\n return null;\n }\n\n const credentialsOf = (account: { passkeys: { id: string; transports: string[] }[] }) =>\n account.passkeys.map((passkey) => ({ id: passkey.id, transports: passkey.transports }));\n\n return {\n async registrationOptions({ account, rpId, rpName }) {\n const options = await webauthn.generateRegistrationOptions({\n rpName,\n rpID: rpId,\n userName: account.email,\n userID: new TextEncoder().encode(account.id),\n attestationType: \"none\",\n excludeCredentials: credentialsOf(account),\n authenticatorSelection: { residentKey: \"preferred\", userVerification: \"required\" },\n });\n\n return { options, challenge: options.challenge };\n },\n\n async verifyRegistration({ response, challenge, origin, rpId }) {\n const verification = await webauthn.verifyRegistrationResponse({\n response,\n expectedChallenge: challenge,\n expectedOrigin: origin,\n expectedRPID: rpId,\n requireUserVerification: true,\n });\n\n if (!verification.verified || !verification.registrationInfo) {\n throw new Error(\"The passkey registration was not verified.\");\n }\n\n const { id, publicKey, counter, transports } = verification.registrationInfo.credential;\n\n return {\n id,\n publicKey: Buffer.from(publicKey).toString(\"base64url\"),\n counter,\n transports: transports ?? [],\n };\n },\n\n async authenticationOptions({ account, rpId }) {\n const options = await webauthn.generateAuthenticationOptions({\n rpID: rpId,\n userVerification: \"required\",\n allowCredentials: credentialsOf(account),\n });\n\n return { options, challenge: options.challenge };\n },\n\n async verifyAuthentication({ response, challenge, origin, rpId, account }) {\n const presented = (response as { id?: unknown } | null)?.id;\n const stored = account.passkeys.find((passkey) => passkey.id === presented);\n\n if (!stored) throw new Error(\"The passkey is not registered for this account.\");\n\n const verification = await webauthn.verifyAuthenticationResponse({\n response,\n expectedChallenge: challenge,\n expectedOrigin: origin,\n expectedRPID: rpId,\n credential: {\n id: stored.id,\n publicKey: new Uint8Array(Buffer.from(stored.publicKey, \"base64url\")),\n counter: stored.counter,\n transports: stored.transports,\n },\n requireUserVerification: true,\n });\n\n if (!verification.verified) throw new Error(\"The passkey was not verified.\");\n\n return { id: stored.id, newCounter: verification.authenticationInfo.newCounter };\n },\n };\n}\n"],"mappings":";;;;;;;AAgDA,MAAM,SAAS;AACf,MAAM,OAAO,KAAK;;AAElB,MAAM,gBAAgB;;AAEtB,MAAM,iBAAiB;AACvB,MAAM,aAAa,KAAK;AACxB,MAAM,gBAAgB,IAAI;AAC1B,MAAM,cAAc;AACpB,MAAM,sBAAsB;;AAE5B,MAAM,qBAAqB;;AAE3B,MAAM,oBAAoB;AAC1B,MAAM,sBAAsB;;AAE5B,MAAM,yBAAyB;AAC/B,MAAM,2BAA2B;;AAEjC,MAAM,oBAAoB;;AAE1B,MAAM,mBAAmB;AAEzB,MAAM,aAAa,YACjB,QAAQ,eAAe,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../../../../../../packages/devtools/src/production/boot.ts"],"sourcesContent":["import type { FastifyInstance } from \"fastify\";\nimport { type MountedDevtoolsPanel, productionPanels } from \"../panels\";\nimport type { MountDevtoolsRoutesDeps } from \"../server/types\";\nimport type { DevtoolsDisposer, ResolvedDevtoolsOptions } from \"../types\";\nimport { DevtoolsProductionConfigError } from \"./errors\";\nimport type { DevtoolsInsights } from \"./insights/types\";\nimport { resolveProductionOptions } from \"./options\";\n\n/** What the connector hands production boot. */\nexport type BootProductionDevtoolsInput = {\n options: ResolvedDevtoolsOptions;\n env: Readonly<Record<string, string | undefined>>;\n server: FastifyInstance;\n /** Package panels loaded with `mode: \"production\"` (not yet filtered). */\n panels: readonly MountedDevtoolsPanel[];\n /** The route deps the connector builds for development, reused (requestLog, listRoutes, ai, …). */\n routes: Omit<MountDevtoolsRoutesDeps, \"collector\" | \"options\" | \"isDevelopment\">;\n /** Reads one config value (`encryption.key`); defaults to core's `config.get`. */\n readConfig?: (key: string) => unknown;\n /** Called once the shared insights exist (panels read captured error counts through them). */\n onInsights?: (insights: DevtoolsInsights) => void;\n log: {\n info(module: string, action: string, message: string): unknown;\n warn(module: string, action: string, message: string): unknown;\n error(module: string, action: string, message: string): unknown;\n };\n};\n\n/** `/ops-…`: the first part of the path, enough to recognise it and not enough to use it. */\nexport function maskDashboardPath(path: string): string {\n const match = /^\\/[A-Za-z]{1,8}-/.exec(path);\n\n return `${match ? match[0] : \"/\"}…`;\n}\n\n/** The key core encrypts with: 64 hex characters. */\nfunction hasEncryptionKey(value: unknown): boolean {\n return typeof value === \"string\" && /^[0-9a-fA-F]{64}$/.test(value);\n}\n\n/**\n * Starts the production monitor, in this order: resolve options (env) →\n * check `encryption.key` (DT006) → cascade store (DT005) → `store.verify()`\n * (DT008) → `ensureFirstAdmin()` (DT003/DT004) → instance info → capture\n * (attach hooks) → resource monitor, health history, jobs reader → local\n * reporter → report writer → shared insights → `excludeFromRequestLog(path)`\n * → mount. Logs one line with the path masked (`/ops-…`), never the full path.\n * Any `DevtoolsProductionConfigError` propagates: the app does not boot.\n *\n * Returns the disposer the connector calls at shutdown (flush samples, stop\n * timers, detach hooks).\n */\nexport async function bootProductionDevtools(\n input: BootProductionDevtoolsInput,\n): Promise<DevtoolsDisposer> {\n const { options, env, server, log } = input;\n const production = resolveProductionOptions(options.production, env);\n const core = await import(\"@warlock.js/core\");\n const readConfig = input.readConfig ?? ((key: string) => core.config.get(key));\n\n if (!hasEncryptionKey(readConfig(\"encryption.key\"))) {\n throw new DevtoolsProductionConfigError(\"DT006\");\n }\n\n const [{ createCascadeStore }, authModule, captureModule, insightsModule, httpModule] =\n await Promise.all([\n import(\"./store\"),\n import(\"./auth\"),\n import(\"./capture\"),\n import(\"./insights\"),\n import(\"./http\"),\n ]);\n\n const store = await createCascadeStore({ shares: production.share.enabled });\n\n await store.verify();\n\n const warn = (message: string): void => {\n log.warn(\"devtools\", \"production\", message);\n };\n const instance = insightsModule.createInstanceInfo();\n const [crypto, passkeys] = await Promise.all([\n authModule.defaultDevtoolsCrypto(),\n authModule.loadDevtoolsPasskeys(),\n ]);\n const auth = authModule.createDevtoolsAuth({\n store,\n options: production,\n instance,\n crypto,\n passkeys,\n warn,\n });\n\n await auth.ensureFirstAdmin();\n\n const isDashboardPath = (path: string): boolean =>\n path === production.path || path.startsWith(`${production.path}/`);\n const capture = captureModule.createProductionCapture({\n options,\n production,\n instance,\n store,\n isDashboardPath,\n warn,\n });\n const stops: (() => unknown)[] = [];\n\n try {\n stops.push(await capture.attach());\n\n const resources = insightsModule.createResourceMonitor();\n const health = insightsModule.createHealthHistory();\n\n resources.start();\n health.start();\n stops.push(\n () => resources.stop(),\n () => health.stop(),\n );\n\n const reporter = insightsModule.createLocalReporter({\n instance,\n resources,\n health,\n jobs: insightsModule.createJobsReader(),\n queries: capture.queries,\n routes: capture.routes,\n errors: capture.errors,\n logs: capture.logs,\n counters: () => capture.counters(),\n });\n const writer = insightsModule.startReportWriter({ reporter, store, production, warn });\n\n stops.push(() => writer.stop());\n\n const insights = insightsModule.createSharedInsights({\n store,\n reporter,\n sampleRate: production.sampleRate,\n });\n input.onInsights?.(insights);\n\n const state = httpModule.createDashboardState(store, production.path);\n const { builtIn, panels } = productionPanels(input.panels, production.panels);\n\n // The dashboard's own requests are not worth a line in the request log, and its sign-in bodies must not reach it.\n if (typeof core.excludeFromRequestLog === \"function\") {\n stops.push(core.excludeFromRequestLog(production.path));\n }\n\n // Mail previews exist only when the project turned that tab on.\n if (builtIn.includes(\"mail\")) {\n const { attachMailSource } = await import(\"../sources/mail-source\");\n\n stops.push(await attachMailSource(capture.collector));\n }\n\n httpModule.mountProductionDevtools(server, {\n routes: {\n ...input.routes,\n collector: capture.collector,\n options,\n isDevelopment: () => false,\n },\n production,\n store,\n auth,\n capture,\n insights,\n instance,\n panels,\n builtInPanels: builtIn,\n state,\n warn,\n hmac: (value) => crypto.hmac(value),\n });\n\n log.info(\n \"devtools\",\n \"ready\",\n `devtools production monitor mounted at ${maskDashboardPath(production.path)} (DEVTOOLS_PATH)`,\n );\n } catch (error) {\n for (const stop of stops.splice(0).reverse()) {\n try {\n void Promise.resolve(stop()).catch(() => undefined);\n } catch {\n // Cleanup after a failed boot must not hide the real error.\n }\n }\n\n void capture.dispose().catch(() => undefined);\n\n throw error;\n }\n\n return () => {\n for (const stop of stops.splice(0).reverse()) {\n try {\n void Promise.resolve(stop()).catch(() => undefined);\n } catch {\n // Shutdown continues past a failing step.\n }\n }\n\n void capture.dispose().catch(() => undefined);\n };\n}\n"],"mappings":";;;;;;AA6BA,SAAgB,kBAAkB,MAAsB;CACtD,MAAM,QAAQ,oBAAoB,KAAK,IAAI;CAE3C,OAAO,GAAG,QAAQ,MAAM,KAAK,IAAI;AACnC;;AAGA,SAAS,iBAAiB,OAAyB;CACjD,OAAO,OAAO,UAAU,YAAY,oBAAoB,KAAK,KAAK;AACpE;;;;;;;;;;;;;AAcA,eAAsB,uBACpB,OAC2B;CAC3B,MAAM,EAAE,SAAS,KAAK,QAAQ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AAK,QAAQ,QAAQ,KAAK,CAAC,CAAC,CAAC,YAAY,MAAS;EACpD,QAAQ,CAER;EAGF,AAAK,QAAQ,QAAQ,CAAC,CAAC,YAAY,MAAS;CAC9C;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"cascade-store-DEGxAFDI.cjs","names":["rateLimitClient","DevtoolsStoreConflictError","randomUUID","rateLimitClient","DevtoolsProductionConfigError","randomUUID","DevtoolsStoreConflictError","rateLimitClient"],"sources":["../../../../../../../packages/devtools/src/production/store/mapping.ts","../../../../../../../packages/devtools/src/production/store/memory-store.ts","../../../../../../../packages/devtools/src/production/store/cascade-store.ts"],"sourcesContent":["import type { DevtoolsAuditEntry, DevtoolsInstanceReport } from \"../contracts\";\nimport { rateLimitClient } from \"../http/ip\";\nimport type {\n DevtoolsAccountPatch,\n DevtoolsAccountRecord,\n DevtoolsInviteRecord,\n DevtoolsPasskeyRecord,\n DevtoolsSessionPatch,\n DevtoolsSessionRecord,\n DevtoolsShareRecord,\n DevtoolsStatePatch,\n DevtoolsStateRecord,\n DevtoolsStoredSample,\n} from \"./types\";\n\n/**\n * The record <-> row mapping of the cascade store. Rows use snake_case column\n * names; times are epoch milliseconds in integer columns on every driver.\n * Pure functions, so they are tested without a database.\n */\nexport type Row = Record<string, unknown>;\n\n/** A number from a column that a driver may return as a string (PostgreSQL `bigint`). */\nexport function toNumber(value: unknown): number {\n if (typeof value === \"number\") return value;\n\n const parsed = Number(value);\n\n return Number.isFinite(parsed) ? parsed : 0;\n}\n\n/** Like `toNumber`, keeping `null` for a missing value. */\nexport function toNumberOrNull(value: unknown): number | null {\n return value === null || value === undefined ? null : toNumber(value);\n}\n\nexport function toStringOrNull(value: unknown): string | null {\n return typeof value === \"string\" ? value : null;\n}\n\nexport function toBoolean(value: unknown): boolean {\n return value === true || value === 1 || value === \"true\" || value === \"t\";\n}\n\n/** Parses JSON text; a value a driver already parsed passes through. */\nexport function parseJson<T>(value: unknown, fallback: T): T {\n if (typeof value === \"string\") {\n try {\n return JSON.parse(value) as T;\n } catch {\n return fallback;\n }\n }\n\n return value === null || value === undefined ? fallback : (value as T);\n}\n\nfunction toArray<T>(value: unknown): T[] {\n const parsed = parseJson<unknown>(value, []);\n\n return Array.isArray(parsed) ? (parsed as T[]) : [];\n}\n\n// ---------------------------------------------------------------------------\n// Accounts\n// ---------------------------------------------------------------------------\n\nconst ACCOUNT_COLUMNS = {\n email: \"email\",\n role: \"role\",\n passwordHash: \"password_hash\",\n passwordSource: \"password_source\",\n mustChangePassword: \"must_change_password\",\n totpSecret: \"totp_secret\",\n totpEnabledAt: \"totp_enabled_at\",\n totpLastStep: \"totp_last_step\",\n recoveryCodes: \"recovery_codes\",\n passkeys: \"passkeys\",\n failuresResetAt: \"failures_reset_at\",\n createdAt: \"created_at\",\n updatedAt: \"updated_at\",\n lastLoginAt: \"last_login_at\",\n createdBy: \"created_by\",\n version: \"version\",\n} as const satisfies Record<keyof Omit<DevtoolsAccountRecord, \"id\">, string>;\n\nexport function accountToRow(record: DevtoolsAccountRecord): Row {\n return { id: record.id, ...fieldsToRow(ACCOUNT_COLUMNS, record) };\n}\n\nexport function accountPatchToRow(patch: DevtoolsAccountPatch): Row {\n return fieldsToRow(ACCOUNT_COLUMNS, patch);\n}\n\nexport function rowToAccount(row: Row): DevtoolsAccountRecord {\n return {\n id: String(row.id),\n email: String(row.email),\n role: row.role as DevtoolsAccountRecord[\"role\"],\n passwordHash: String(row.password_hash),\n passwordSource: row.password_source as DevtoolsAccountRecord[\"passwordSource\"],\n mustChangePassword: toBoolean(row.must_change_password),\n totpSecret: toStringOrNull(row.totp_secret),\n totpEnabledAt: toNumberOrNull(row.totp_enabled_at),\n totpLastStep: toNumberOrNull(row.totp_last_step),\n recoveryCodes: toArray<string>(row.recovery_codes),\n passkeys: toArray<DevtoolsPasskeyRecord>(row.passkeys),\n failuresResetAt: toNumberOrNull(row.failures_reset_at),\n createdAt: toNumber(row.created_at),\n updatedAt: toNumber(row.updated_at),\n lastLoginAt: toNumberOrNull(row.last_login_at),\n createdBy: toStringOrNull(row.created_by),\n version: toNumber(row.version),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Sessions\n// ---------------------------------------------------------------------------\n\nconst SESSION_COLUMNS = {\n tokenHash: \"token_hash\",\n accountId: \"account_id\",\n stage: \"stage\",\n csrfSecret: \"csrf_secret\",\n createdAt: \"created_at\",\n lastSeenAt: \"last_seen_at\",\n expiresAt: \"expires_at\",\n ip: \"ip\",\n userAgent: \"user_agent\",\n pendingTotpSecret: \"pending_totp_secret\",\n challenge: \"challenge\",\n challengeExpiresAt: \"challenge_expires_at\",\n version: \"version\",\n} as const satisfies Record<keyof Omit<DevtoolsSessionRecord, \"id\">, string>;\n\nexport function sessionToRow(record: DevtoolsSessionRecord): Row {\n return { id: record.id, ...fieldsToRow(SESSION_COLUMNS, record) };\n}\n\nexport function sessionPatchToRow(patch: DevtoolsSessionPatch): Row {\n return fieldsToRow(SESSION_COLUMNS, patch);\n}\n\nexport function rowToSession(row: Row): DevtoolsSessionRecord {\n return {\n id: String(row.id),\n tokenHash: String(row.token_hash),\n accountId: String(row.account_id),\n stage: row.stage as DevtoolsSessionRecord[\"stage\"],\n csrfSecret: String(row.csrf_secret),\n createdAt: toNumber(row.created_at),\n lastSeenAt: toNumber(row.last_seen_at),\n expiresAt: toNumber(row.expires_at),\n ip: toStringOrNull(row.ip),\n userAgent: toStringOrNull(row.user_agent),\n pendingTotpSecret: toStringOrNull(row.pending_totp_secret),\n challenge: toStringOrNull(row.challenge),\n challengeExpiresAt: toNumberOrNull(row.challenge_expires_at),\n version: toNumber(row.version),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Invites\n// ---------------------------------------------------------------------------\n\nexport function inviteToRow(record: DevtoolsInviteRecord): Row {\n return {\n id: record.id,\n token_hash: record.tokenHash,\n email: record.email,\n role: record.role,\n created_by: record.createdBy,\n created_at: record.createdAt,\n expires_at: record.expiresAt,\n used_at: record.usedAt,\n account_id: record.accountId,\n };\n}\n\nexport function rowToInvite(row: Row): DevtoolsInviteRecord {\n return {\n id: String(row.id),\n tokenHash: String(row.token_hash),\n email: String(row.email),\n role: row.role as DevtoolsInviteRecord[\"role\"],\n createdBy: toStringOrNull(row.created_by),\n createdAt: toNumber(row.created_at),\n expiresAt: toNumber(row.expires_at),\n usedAt: toNumberOrNull(row.used_at),\n accountId: toStringOrNull(row.account_id),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Share links\n// ---------------------------------------------------------------------------\n\nexport function shareToRow(record: DevtoolsShareRecord): Row {\n return {\n id: record.id,\n token_hash: record.tokenHash,\n panel: record.panel,\n label: record.label,\n created_by: record.createdBy,\n created_at: record.createdAt,\n expires_at: record.expiresAt,\n revoked_at: record.revokedAt,\n last_used_at: record.lastUsedAt,\n uses: record.uses,\n };\n}\n\nexport function rowToShare(row: Row): DevtoolsShareRecord {\n return {\n id: String(row.id),\n tokenHash: String(row.token_hash),\n panel: String(row.panel),\n label: String(row.label),\n createdBy: toStringOrNull(row.created_by),\n createdAt: toNumber(row.created_at),\n expiresAt: toNumber(row.expires_at),\n revokedAt: toNumberOrNull(row.revoked_at),\n lastUsedAt: toNumberOrNull(row.last_used_at),\n uses: toNumber(row.uses),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Audit\n// ---------------------------------------------------------------------------\n\nexport function auditToRow(entry: DevtoolsAuditEntry): Row {\n return {\n id: entry.id,\n type: entry.type,\n occurred_at: entry.at,\n account_id: entry.accountId,\n email: entry.email,\n ip: entry.ip,\n // What the per-IP limit counts by: the address, or its /64 for IPv6.\n ip_bucket: entry.ip === null ? null : rateLimitClient(entry.ip),\n user_agent: entry.userAgent,\n detail: entry.detail,\n ref: entry.ref,\n };\n}\n\nexport function rowToAudit(row: Row): DevtoolsAuditEntry {\n return {\n id: String(row.id),\n at: toNumber(row.occurred_at),\n type: row.type as DevtoolsAuditEntry[\"type\"],\n accountId: toStringOrNull(row.account_id),\n email: toStringOrNull(row.email),\n ip: toStringOrNull(row.ip),\n userAgent: toStringOrNull(row.user_agent),\n detail: parseJson<DevtoolsAuditEntry[\"detail\"]>(row.detail, {}),\n ref: String(row.ref),\n };\n}\n\n// ---------------------------------------------------------------------------\n// State\n// ---------------------------------------------------------------------------\n\nconst STATE_COLUMNS = {\n disabled: \"disabled\",\n disabledPathHash: \"disabled_path_hash\",\n disabledAt: \"disabled_at\",\n disabledBy: \"disabled_by\",\n lockedUntil: \"locked_until\",\n failuresResetAt: \"failures_reset_at\",\n updatedAt: \"updated_at\",\n version: \"version\",\n} as const satisfies Record<keyof DevtoolsStateRecord, string>;\n\nexport function stateToRow(record: DevtoolsStateRecord): Row {\n return fieldsToRow(STATE_COLUMNS, record);\n}\n\nexport function statePatchToRow(patch: DevtoolsStatePatch): Row {\n return fieldsToRow(STATE_COLUMNS, patch);\n}\n\nexport function rowToState(row: Row): DevtoolsStateRecord {\n return {\n disabled: toBoolean(row.disabled),\n disabledPathHash: toStringOrNull(row.disabled_path_hash),\n disabledAt: toNumberOrNull(row.disabled_at),\n disabledBy: toStringOrNull(row.disabled_by),\n lockedUntil: toNumberOrNull(row.locked_until),\n failuresResetAt: toNumberOrNull(row.failures_reset_at),\n updatedAt: toNumber(row.updated_at),\n version: toNumber(row.version),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Samples and reports\n// ---------------------------------------------------------------------------\n\n/**\n * `detail` is JSON text, not a JSON column: a sample holds keys from request\n * data (headers, query names) and MongoDB rejects or misreads field names\n * that start with `$` or contain dots.\n */\nexport function sampleToRow(sample: DevtoolsStoredSample): Row {\n return {\n id: sample.id,\n instance: sample.instance,\n started_at: sample.startedAt,\n status: sample.summary.status ?? null,\n method: sample.summary.method.toUpperCase(),\n path: sample.summary.path,\n summary: sample.summary,\n detail: sample.detail === null ? null : JSON.stringify(sample.detail),\n };\n}\n\nexport function rowToSampleSummary(row: Row): DevtoolsStoredSample[\"summary\"] {\n return parseJson<DevtoolsStoredSample[\"summary\"]>(row.summary, {} as never);\n}\n\nexport function rowToSample(row: Row): DevtoolsStoredSample {\n const detail = row.detail;\n\n return {\n id: String(row.id),\n instance: String(row.instance),\n startedAt: toNumber(row.started_at),\n summary: parseJson<DevtoolsStoredSample[\"summary\"]>(row.summary, {} as never),\n detail:\n detail === null || detail === undefined\n ? null\n : parseJson<DevtoolsStoredSample[\"detail\"]>(detail, null),\n };\n}\n\n/** `data` is JSON text for the same reason as a sample's `detail`. */\nexport function reportToRow(report: DevtoolsInstanceReport): Row {\n return {\n id: report.instance.id,\n seen_at: report.at,\n data: JSON.stringify(report),\n };\n}\n\nexport function rowToReport(row: Row): DevtoolsInstanceReport {\n return parseJson<DevtoolsInstanceReport>(row.data, {} as never);\n}\n\n// ---------------------------------------------------------------------------\n\n/** Maps the defined fields of `source` to their columns. */\nfunction fieldsToRow(columns: Record<string, string>, source: object): Row {\n const row: Row = {};\n const values = source as Record<string, unknown>;\n\n for (const [field, column] of Object.entries(columns)) {\n const value = values[field];\n\n if (value !== undefined) row[column] = value;\n }\n\n return row;\n}\n","import { randomUUID } from \"node:crypto\";\nimport type {\n DevtoolsAuditEntry,\n DevtoolsInstanceReport,\n DevtoolsSampleSummary,\n} from \"../contracts\";\nimport { DevtoolsStoreConflictError } from \"../errors\";\nimport { rateLimitClient } from \"../http/ip\";\nimport type {\n DevtoolsAccountRecord,\n DevtoolsInviteRecord,\n DevtoolsSampleFilter,\n DevtoolsSessionRecord,\n DevtoolsShareRecord,\n DevtoolsStateRecord,\n DevtoolsStore,\n DevtoolsStoredSample,\n} from \"./types\";\n\n/** A structural copy, so callers never hold the store's own objects. */\nfunction copy<T>(value: T): T {\n return structuredClone(value);\n}\n\n/** The state row before anything was written. */\nexport function defaultStateRecord(now = 0): DevtoolsStateRecord {\n return {\n disabled: false,\n disabledPathHash: null,\n disabledAt: null,\n disabledBy: null,\n lockedUntil: null,\n failuresResetAt: null,\n updatedAt: now,\n version: 0,\n };\n}\n\n/** Whether `status` matches a sample filter value: `\"5xx\"`, `\"4xx\"`, `\"404\"`. */\nexport function sampleStatusMatches(filter: string, status: number | undefined): boolean {\n if (status === undefined) return false;\n\n const value = filter.trim().toLowerCase();\n\n if (/^[1-5]xx$/.test(value)) return Math.floor(status / 100) === Number(value[0]);\n\n return String(status) === value;\n}\n\n/** Whether a sample summary passes `filter` (everything but `limit`). */\nexport function sampleMatches(\n summary: DevtoolsSampleSummary,\n filter: DevtoolsSampleFilter,\n): boolean {\n if (filter.status !== undefined && !sampleStatusMatches(filter.status, summary.status))\n return false;\n if (filter.method !== undefined && summary.method.toUpperCase() !== filter.method.toUpperCase()) {\n return false;\n }\n\n if (filter.route !== undefined) {\n const needle = filter.route.toLowerCase();\n const haystack = `${summary.route ?? \"\"} ${summary.path}`.toLowerCase();\n\n if (!haystack.includes(needle)) return false;\n }\n\n if (filter.q !== undefined && !summary.path.toLowerCase().includes(filter.q.toLowerCase())) {\n return false;\n }\n\n if (filter.since !== undefined && summary.startedAt < filter.since) return false;\n if (filter.until !== undefined && summary.startedAt > filter.until) return false;\n if (filter.instance !== undefined && summary.instance !== filter.instance) return false;\n\n return true;\n}\n\n/**\n * An in-process `DevtoolsStore` for specs (and nothing else: it is neither\n * shared between processes nor kept across restarts). It follows the store\n * contract exactly, compare-and-set included, so a spec written against it\n * holds for the database store too.\n *\n * `now` is read for `updatedAt` stamps; pass a fake clock in specs.\n */\nexport function createMemoryStore(options: { now?: () => number } = {}): DevtoolsStore {\n const now = options.now ?? Date.now;\n const accounts = new Map<string, DevtoolsAccountRecord>();\n const sessions = new Map<string, DevtoolsSessionRecord>();\n const invites = new Map<string, DevtoolsInviteRecord>();\n const shares = new Map<string, DevtoolsShareRecord>();\n const audit: DevtoolsAuditEntry[] = [];\n const samples = new Map<string, DevtoolsStoredSample>();\n const reports = new Map<string, DevtoolsInstanceReport>();\n let state: DevtoolsStateRecord | null = null;\n\n return {\n async verify() {},\n\n accounts: {\n async findByEmail(email) {\n for (const account of accounts.values()) {\n if (account.email === email) return copy(account);\n }\n\n return null;\n },\n async findById(id) {\n const account = accounts.get(id);\n\n return account ? copy(account) : null;\n },\n async list() {\n return [...accounts.values()].sort((a, b) => a.createdAt - b.createdAt).map(copy);\n },\n async countAdmins() {\n return [...accounts.values()].filter((account) => account.role === \"admin\").length;\n },\n async create(input) {\n for (const account of accounts.values()) {\n if (account.email === input.email) throw new DevtoolsStoreConflictError(\"email\");\n }\n\n const at = now();\n const record: DevtoolsAccountRecord = {\n ...copy(input),\n id: randomUUID(),\n createdAt: at,\n updatedAt: at,\n version: 1,\n };\n\n accounts.set(record.id, record);\n\n return copy(record);\n },\n async update(id, expectedVersion, patch) {\n const current = accounts.get(id);\n\n if (!current || current.version !== expectedVersion) return null;\n\n if (patch.email !== undefined && patch.email !== current.email) {\n for (const account of accounts.values()) {\n if (account.email === patch.email) throw new DevtoolsStoreConflictError(\"email\");\n }\n }\n\n const next: DevtoolsAccountRecord = {\n ...current,\n ...copy(patch),\n id,\n createdAt: current.createdAt,\n updatedAt: now(),\n version: current.version + 1,\n };\n\n accounts.set(id, next);\n\n return copy(next);\n },\n async remove(id) {\n return accounts.delete(id);\n },\n },\n\n sessions: {\n async create(input) {\n const record: DevtoolsSessionRecord = { ...copy(input), id: randomUUID(), version: 1 };\n\n sessions.set(record.id, record);\n\n return copy(record);\n },\n async findByTokenHash(tokenHash) {\n for (const session of sessions.values()) {\n if (session.tokenHash === tokenHash) return copy(session);\n }\n\n return null;\n },\n async listForAccount(accountId) {\n return [...sessions.values()]\n .filter((session) => session.accountId === accountId)\n .sort((a, b) => b.createdAt - a.createdAt)\n .map(copy);\n },\n async update(id, expectedVersion, patch) {\n const current = sessions.get(id);\n\n if (!current || current.version !== expectedVersion) return null;\n\n const next: DevtoolsSessionRecord = {\n ...current,\n ...copy(patch),\n id,\n accountId: current.accountId,\n version: current.version + 1,\n };\n\n sessions.set(id, next);\n\n return copy(next);\n },\n async remove(id) {\n return sessions.delete(id);\n },\n async removeForAccount(accountId, exceptId) {\n let removed = 0;\n\n for (const session of [...sessions.values()]) {\n if (session.accountId === accountId && session.id !== exceptId) {\n sessions.delete(session.id);\n removed++;\n }\n }\n\n return removed;\n },\n async removeExpired(at) {\n let removed = 0;\n\n for (const session of [...sessions.values()]) {\n if (session.expiresAt < at) {\n sessions.delete(session.id);\n removed++;\n }\n }\n\n return removed;\n },\n },\n\n invites: {\n async create(input) {\n const record: DevtoolsInviteRecord = {\n ...copy(input),\n id: randomUUID(),\n usedAt: null,\n accountId: null,\n };\n\n invites.set(record.id, record);\n\n return copy(record);\n },\n async findByTokenHash(tokenHash) {\n for (const invite of invites.values()) {\n if (invite.tokenHash === tokenHash) return copy(invite);\n }\n\n return null;\n },\n async list(listOptions = {}) {\n return [...invites.values()]\n .filter((invite) => listOptions.includeUsed === true || invite.usedAt === null)\n .sort((a, b) => b.createdAt - a.createdAt)\n .map(copy);\n },\n async markUsed(id, at, accountId) {\n const invite = invites.get(id);\n\n if (!invite || invite.usedAt !== null || at >= invite.expiresAt) return false;\n\n invites.set(id, { ...invite, usedAt: at, accountId });\n\n return true;\n },\n async remove(id) {\n return invites.delete(id);\n },\n async removeExpired(at) {\n let removed = 0;\n\n for (const invite of [...invites.values()]) {\n if (invite.usedAt === null && invite.expiresAt < at) {\n invites.delete(invite.id);\n removed++;\n }\n }\n\n return removed;\n },\n },\n\n audit: {\n async append(entry) {\n const record: DevtoolsAuditEntry = { ...copy(entry), id: randomUUID() };\n\n audit.push(record);\n\n return copy(record);\n },\n async list(filter) {\n const limit = Math.max(1, Math.min(500, filter.limit));\n\n return audit\n .filter(\n (entry) =>\n (filter.types === undefined || filter.types.includes(entry.type)) &&\n (filter.accountId === undefined || entry.accountId === filter.accountId) &&\n (filter.before === undefined || entry.at < filter.before),\n )\n .sort((a, b) => b.at - a.at)\n .slice(0, limit)\n .map(copy);\n },\n async count(filter) {\n return audit.filter(\n (entry) =>\n filter.types.includes(entry.type) &&\n entry.at >= filter.since &&\n (filter.accountId === undefined || entry.accountId === filter.accountId) &&\n (filter.ip === undefined ||\n (entry.ip !== null && rateLimitClient(entry.ip) === rateLimitClient(filter.ip))),\n ).length;\n },\n async prune(before) {\n const kept = audit.filter((entry) => entry.at >= before);\n const removed = audit.length - kept.length;\n\n audit.splice(0, audit.length, ...kept);\n\n return removed;\n },\n },\n\n state: {\n async read() {\n return copy(state ?? defaultStateRecord(now()));\n },\n async update(expectedVersion, patch) {\n const current = state ?? defaultStateRecord(now());\n\n if (current.version !== expectedVersion) return null;\n\n state = { ...current, ...copy(patch), updatedAt: now(), version: current.version + 1 };\n\n return copy(state);\n },\n },\n\n samples: {\n async insert(list) {\n for (const sample of list) samples.set(sample.id, copy(sample));\n },\n async list(filter) {\n const limit = Math.max(1, Math.min(1000, filter.limit));\n\n return [...samples.values()]\n .map((sample) => sample.summary)\n .filter((summary) => sampleMatches(summary, filter))\n .sort((a, b) => b.startedAt - a.startedAt)\n .slice(0, limit)\n .map(copy);\n },\n async get(id) {\n const sample = samples.get(id);\n\n return sample ? copy(sample) : null;\n },\n async prune(before) {\n let removed = 0;\n\n for (const sample of [...samples.values()]) {\n if (sample.startedAt < before) {\n samples.delete(sample.id);\n removed++;\n }\n }\n\n return removed;\n },\n async clear() {\n const removed = samples.size;\n\n samples.clear();\n\n return removed;\n },\n },\n\n reports: {\n async write(report) {\n reports.set(report.instance.id, copy(report));\n },\n async list(seenSince) {\n return [...reports.values()]\n .filter((report) => report.at >= seenSince)\n .sort((a, b) => b.at - a.at)\n .map(copy);\n },\n async prune(seenBefore) {\n let removed = 0;\n\n for (const report of [...reports.values()]) {\n if (report.at < seenBefore) {\n reports.delete(report.instance.id);\n removed++;\n }\n }\n\n return removed;\n },\n async remove(instanceId) {\n return reports.delete(instanceId);\n },\n },\n\n shares: {\n async create(input) {\n for (const share of shares.values()) {\n if (share.tokenHash === input.tokenHash) throw new DevtoolsStoreConflictError(\"tokenHash\");\n }\n\n const record: DevtoolsShareRecord = {\n ...copy(input),\n id: randomUUID(),\n revokedAt: null,\n lastUsedAt: null,\n uses: 0,\n };\n\n shares.set(record.id, record);\n\n return copy(record);\n },\n async findByTokenHash(tokenHash) {\n for (const share of shares.values()) {\n if (share.tokenHash === tokenHash) return copy(share);\n }\n\n return null;\n },\n async get(id) {\n const share = shares.get(id);\n\n return share ? copy(share) : null;\n },\n async list() {\n return [...shares.values()].sort((a, b) => b.createdAt - a.createdAt).map(copy);\n },\n async revoke(id, at) {\n const share = shares.get(id);\n\n if (!share || share.revokedAt !== null) return false;\n\n shares.set(id, { ...share, revokedAt: at });\n\n return true;\n },\n async revokeAll(at) {\n let revoked = 0;\n\n for (const share of [...shares.values()]) {\n if (share.revokedAt === null && share.expiresAt > at) {\n shares.set(share.id, { ...share, revokedAt: at });\n revoked++;\n }\n }\n\n return revoked;\n },\n async touch(id, at) {\n const share = shares.get(id);\n\n if (share) shares.set(id, { ...share, lastUsedAt: at, uses: share.uses + 1 });\n },\n async removeOld(before) {\n let removed = 0;\n\n for (const share of [...shares.values()]) {\n if (share.expiresAt < before || (share.revokedAt !== null && share.revokedAt < before)) {\n shares.delete(share.id);\n removed++;\n }\n }\n\n return removed;\n },\n },\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { DevtoolsAuditEntry, DevtoolsInstanceReport } from \"../contracts\";\nimport { DevtoolsProductionConfigError, DevtoolsStoreConflictError } from \"../errors\";\nimport { rateLimitClient } from \"../http/ip\";\nimport {\n accountPatchToRow,\n accountToRow,\n auditToRow,\n inviteToRow,\n reportToRow,\n rowToAccount,\n rowToAudit,\n rowToInvite,\n rowToReport,\n rowToSample,\n rowToSampleSummary,\n rowToSession,\n rowToShare,\n rowToState,\n sampleToRow,\n sessionPatchToRow,\n sessionToRow,\n shareToRow,\n statePatchToRow,\n stateToRow,\n type Row,\n} from \"./mapping\";\nimport { defaultStateRecord, sampleMatches } from \"./memory-store\";\nimport type {\n DevtoolsAccountRecord,\n DevtoolsInviteRecord,\n DevtoolsSessionRecord,\n DevtoolsShareRecord,\n DevtoolsStore,\n} from \"./types\";\n\ntype ModelsModule = typeof import(\"./models\");\n\n/** The part of cascade's query builder this store uses. */\ninterface RowQuery {\n where(field: string, operator: string, value: unknown): RowQuery;\n whereIn(field: string, values: unknown[]): RowQuery;\n whereNull(field: string): RowQuery;\n orderBy(field: string, direction: \"asc\" | \"desc\"): RowQuery;\n limit(value: number): RowQuery;\n select(fields: string[]): RowQuery;\n get(): Promise<Row[]>;\n first(): Promise<Row | null>;\n delete(): Promise<number>;\n count(): Promise<number>;\n}\n\n/** The part of a cascade model class this store uses (every table class has this shape). */\ntype RowClass = ModelsModule[\"DevtoolsAccountRow\"];\n\nexport type CascadeStoreOptions = {\n /** The clock for `updatedAt` stamps; defaults to `Date.now`. */\n now?: () => number;\n /**\n * Whether `verify()` also checks the `devtools_shares` table. Set it when\n * `production.share.enabled` is on; apps that do not share links need no\n * migration for it.\n */\n shares?: boolean;\n};\n\n/** The most rows scanned for a sample filter the database cannot apply (route, text). */\nconst SAMPLE_SCAN_LIMIT = 5000;\n\n/** A plain-row query (no model instances). */\nfunction rows(table: RowClass): RowQuery {\n return table.query().lean() as unknown as RowQuery;\n}\n\n/** A query for counting and deleting. */\nfunction query(table: RowClass): RowQuery {\n return table.query() as unknown as RowQuery;\n}\n\nfunction byId(table: RowClass, id: string): Promise<Row | null> {\n return rows(table).where(\"id\", \"=\", id).first();\n}\n\nasync function insert(table: RowClass, row: Row): Promise<void> {\n await table.create(row as never);\n}\n\nasync function removeWhere(table: RowClass, field: string, value: unknown): Promise<boolean> {\n return (await query(table).where(field, \"=\", value).delete()) > 0;\n}\n\n/** Applies `$set` to the row only while its `version` still equals `expected`. */\nasync function compareAndSet(\n table: RowClass,\n id: string,\n expected: number,\n set: Row,\n): Promise<boolean> {\n const updated = await table.atomic({ id, version: expected }, { $set: set });\n\n return updated > 0;\n}\n\n/**\n * The production `DevtoolsStore`: the app's database through\n * `@warlock.js/cascade` (MongoDB or SQL), using the models in `./models` and\n * the tables `devtoolsMigrations` creates. Imports cascade lazily so loading\n * this module never requires it.\n *\n * Throws `DevtoolsProductionConfigError(\"DT005\")` when cascade is not\n * installed or has no connection.\n */\nexport async function createCascadeStore(\n options: CascadeStoreOptions = {},\n): Promise<DevtoolsStore> {\n const now = options.now ?? Date.now;\n let models: ModelsModule;\n\n try {\n models = await import(\"./models\");\n // Throws when the app has no data source.\n models.DevtoolsAccountRow.getDataSource();\n } catch (error) {\n throw new DevtoolsProductionConfigError(\n \"DT005\",\n error instanceof Error ? `(${error.message})` : undefined,\n );\n }\n\n const {\n DevtoolsAccountRow: Accounts,\n DevtoolsSessionRow: Sessions,\n DevtoolsInviteRow: Invites,\n DevtoolsAuditRow: Audit,\n DevtoolsStateRow: State,\n DevtoolsSampleRow: Samples,\n DevtoolsReportRow: Reports,\n DevtoolsShareRow: Shares,\n } = models;\n const tables: RowClass[] = [Accounts, Sessions, Invites, Audit, State, Samples, Reports];\n\n if (options.shares === true) tables.push(Shares);\n\n const accountById = async (id: string): Promise<DevtoolsAccountRecord | null> => {\n const row = await byId(Accounts, id);\n\n return row ? rowToAccount(row) : null;\n };\n const shareById = async (id: string): Promise<DevtoolsShareRecord | null> => {\n const row = await byId(Shares, id);\n\n return row ? rowToShare(row) : null;\n };\n const sessionById = async (id: string): Promise<DevtoolsSessionRecord | null> => {\n const row = await byId(Sessions, id);\n\n return row ? rowToSession(row) : null;\n };\n\n return {\n async verify() {\n const blueprint = Accounts.getDriver().blueprint;\n const missing: string[] = [];\n\n for (const table of tables) {\n if (!(await blueprint.tableExists(table.table))) missing.push(table.table);\n }\n\n if (missing.length > 0) {\n throw new DevtoolsProductionConfigError(\"DT008\", `(missing: ${missing.join(\", \")})`);\n }\n },\n\n accounts: {\n async findByEmail(email) {\n const row = await rows(Accounts).where(\"email\", \"=\", email).first();\n\n return row ? rowToAccount(row) : null;\n },\n findById: accountById,\n async list() {\n const found = await rows(Accounts).orderBy(\"created_at\", \"asc\").get();\n\n return found.map(rowToAccount);\n },\n async countAdmins() {\n return query(Accounts).where(\"role\", \"=\", \"admin\").count();\n },\n async create(input) {\n const at = now();\n const record: DevtoolsAccountRecord = {\n ...structuredClone(input),\n id: randomUUID(),\n createdAt: at,\n updatedAt: at,\n version: 1,\n };\n\n if (await rows(Accounts).where(\"email\", \"=\", record.email).first()) {\n throw new DevtoolsStoreConflictError(\"email\");\n }\n\n try {\n await insert(Accounts, accountToRow(record));\n } catch (error) {\n // A concurrent request took the email between the check and the insert.\n if (await rows(Accounts).where(\"email\", \"=\", record.email).first()) {\n throw new DevtoolsStoreConflictError(\"email\");\n }\n\n throw error;\n }\n\n return record;\n },\n async update(id, expectedVersion, patch) {\n const current = await accountById(id);\n\n if (!current || current.version !== expectedVersion) return null;\n\n if (patch.email !== undefined && patch.email !== current.email) {\n if (await rows(Accounts).where(\"email\", \"=\", patch.email).first()) {\n throw new DevtoolsStoreConflictError(\"email\");\n }\n }\n\n const set = {\n ...accountPatchToRow(structuredClone(patch)),\n updated_at: now(),\n version: expectedVersion + 1,\n };\n let won: boolean;\n\n try {\n won = await compareAndSet(Accounts, id, expectedVersion, set);\n } catch (error) {\n if (\n patch.email !== undefined &&\n (await rows(Accounts).where(\"email\", \"=\", patch.email).first())\n ) {\n throw new DevtoolsStoreConflictError(\"email\");\n }\n\n throw error;\n }\n\n return won ? accountById(id) : null;\n },\n async remove(id) {\n return removeWhere(Accounts, \"id\", id);\n },\n },\n\n sessions: {\n async create(input) {\n const record: DevtoolsSessionRecord = {\n ...structuredClone(input),\n id: randomUUID(),\n version: 1,\n };\n\n await insert(Sessions, sessionToRow(record));\n\n return record;\n },\n async findByTokenHash(tokenHash) {\n const row = await rows(Sessions).where(\"token_hash\", \"=\", tokenHash).first();\n\n return row ? rowToSession(row) : null;\n },\n async listForAccount(accountId) {\n const found = await rows(Sessions)\n .where(\"account_id\", \"=\", accountId)\n .orderBy(\"created_at\", \"desc\")\n .get();\n\n return found.map(rowToSession);\n },\n async update(id, expectedVersion, patch) {\n const set = { ...sessionPatchToRow(structuredClone(patch)), version: expectedVersion + 1 };\n\n if (!(await compareAndSet(Sessions, id, expectedVersion, set))) return null;\n\n return sessionById(id);\n },\n async remove(id) {\n return removeWhere(Sessions, \"id\", id);\n },\n async removeForAccount(accountId, exceptId) {\n const target = query(Sessions).where(\"account_id\", \"=\", accountId);\n\n if (exceptId !== undefined) target.where(\"id\", \"!=\", exceptId);\n\n return target.delete();\n },\n async removeExpired(at) {\n return query(Sessions).where(\"expires_at\", \"<\", at).delete();\n },\n },\n\n invites: {\n async create(input) {\n const record: DevtoolsInviteRecord = {\n ...structuredClone(input),\n id: randomUUID(),\n usedAt: null,\n accountId: null,\n };\n\n await insert(Invites, inviteToRow(record));\n\n return record;\n },\n async findByTokenHash(tokenHash) {\n const row = await rows(Invites).where(\"token_hash\", \"=\", tokenHash).first();\n\n return row ? rowToInvite(row) : null;\n },\n async list(listOptions = {}) {\n const target = rows(Invites);\n\n if (listOptions.includeUsed !== true) target.whereNull(\"used_at\");\n\n return (await target.orderBy(\"created_at\", \"desc\").get()).map(rowToInvite);\n },\n async markUsed(id, at, accountId) {\n const updated = await Invites.atomic(\n { id, used_at: null, expires_at: { $gt: at } },\n { $set: { used_at: at, account_id: accountId } },\n // Code-authored filter; nothing here comes from a request.\n { trustedFilter: true },\n );\n\n return updated > 0;\n },\n async remove(id) {\n return removeWhere(Invites, \"id\", id);\n },\n async removeExpired(at) {\n return query(Invites).whereNull(\"used_at\").where(\"expires_at\", \"<\", at).delete();\n },\n },\n\n audit: {\n async append(entry) {\n const record: DevtoolsAuditEntry = { ...structuredClone(entry), id: randomUUID() };\n\n await insert(Audit, auditToRow(record));\n\n return record;\n },\n async list(filter) {\n const limit = Math.max(1, Math.min(500, filter.limit));\n const target = rows(Audit);\n\n if (filter.types !== undefined) target.whereIn(\"type\", [...filter.types]);\n if (filter.accountId !== undefined) target.where(\"account_id\", \"=\", filter.accountId);\n if (filter.before !== undefined) target.where(\"occurred_at\", \"<\", filter.before);\n\n const found = await target.orderBy(\"occurred_at\", \"desc\").limit(limit).get();\n\n return found.map(rowToAudit);\n },\n async count(filter) {\n const target = query(Audit)\n .whereIn(\"type\", [...filter.types])\n .where(\"occurred_at\", \">=\", filter.since);\n\n if (filter.accountId !== undefined) target.where(\"account_id\", \"=\", filter.accountId);\n if (filter.ip !== undefined) target.where(\"ip_bucket\", \"=\", rateLimitClient(filter.ip));\n\n return target.count();\n },\n async prune(before) {\n return query(Audit).where(\"occurred_at\", \"<\", before).delete();\n },\n },\n\n state: {\n async read() {\n const row = await byId(State, \"state\");\n\n return row ? rowToState(row) : defaultStateRecord(now());\n },\n async update(expectedVersion, patch) {\n const row = await byId(State, \"state\");\n\n if (!row) {\n if (expectedVersion !== 0) return null;\n\n const record = {\n ...defaultStateRecord(now()),\n ...structuredClone(patch),\n updatedAt: now(),\n version: 1,\n };\n\n try {\n await insert(State, { id: \"state\", ...stateToRow(record) });\n } catch {\n // Another process wrote the first row; this write lost the race.\n return null;\n }\n\n return record;\n }\n\n const set = {\n ...statePatchToRow(structuredClone(patch)),\n updated_at: now(),\n version: expectedVersion + 1,\n };\n\n if (!(await compareAndSet(State, \"state\", expectedVersion, set))) return null;\n\n const next = await byId(State, \"state\");\n\n return next ? rowToState(next) : null;\n },\n },\n\n samples: {\n async insert(list) {\n for (const sample of list) {\n const { id, ...data } = sampleToRow(structuredClone(sample));\n\n await Samples.upsert({ id } as never, data as never);\n }\n },\n async list(filter) {\n const limit = Math.max(1, Math.min(1000, filter.limit));\n const target = rows(Samples).select([\"summary\"]);\n const exact = !(filter.route !== undefined || filter.q !== undefined);\n\n if (filter.status !== undefined) {\n const status = filter.status.trim().toLowerCase();\n\n if (/^[1-5]xx$/.test(status)) {\n const base = Number(status[0]) * 100;\n\n target.where(\"status\", \">=\", base).where(\"status\", \"<\", base + 100);\n } else if (/^\\d+$/.test(status) && String(Number(status)) === status) {\n target.where(\"status\", \"=\", Number(status));\n } else {\n return [];\n }\n }\n\n if (filter.method !== undefined) target.where(\"method\", \"=\", filter.method.toUpperCase());\n if (filter.since !== undefined) target.where(\"started_at\", \">=\", filter.since);\n if (filter.until !== undefined) target.where(\"started_at\", \"<=\", filter.until);\n if (filter.instance !== undefined) target.where(\"instance\", \"=\", filter.instance);\n\n const found = await target\n .orderBy(\"started_at\", \"desc\")\n .limit(exact ? limit : SAMPLE_SCAN_LIMIT)\n .get();\n\n // Route and text filters are substring matches the databases do not\n // share, so they run here, with the same rules as the memory store.\n return found\n .map(rowToSampleSummary)\n .filter((summary) => sampleMatches(summary, filter))\n .slice(0, limit);\n },\n async get(id) {\n const row = await byId(Samples, id);\n\n return row ? rowToSample(row) : null;\n },\n async prune(before) {\n return query(Samples).where(\"started_at\", \"<\", before).delete();\n },\n async clear() {\n return query(Samples).where(\"started_at\", \">=\", 0).delete();\n },\n },\n\n reports: {\n async write(report: DevtoolsInstanceReport) {\n const { id, ...data } = reportToRow(report);\n\n await Reports.upsert({ id } as never, data as never);\n },\n async list(seenSince) {\n const found = await rows(Reports)\n .where(\"seen_at\", \">=\", seenSince)\n .orderBy(\"seen_at\", \"desc\")\n .get();\n\n return found.map(rowToReport);\n },\n async prune(seenBefore) {\n return query(Reports).where(\"seen_at\", \"<\", seenBefore).delete();\n },\n async remove(instanceId) {\n return removeWhere(Reports, \"id\", instanceId);\n },\n },\n\n shares: {\n async create(input) {\n const record: DevtoolsShareRecord = {\n ...structuredClone(input),\n id: randomUUID(),\n revokedAt: null,\n lastUsedAt: null,\n uses: 0,\n };\n\n await insert(Shares, shareToRow(record));\n\n return record;\n },\n async findByTokenHash(tokenHash) {\n const row = await rows(Shares).where(\"token_hash\", \"=\", tokenHash).first();\n\n return row ? rowToShare(row) : null;\n },\n get: shareById,\n async list() {\n return (await rows(Shares).orderBy(\"created_at\", \"desc\").get()).map(rowToShare);\n },\n async revoke(id, at) {\n const updated = await Shares.atomic(\n { id, revoked_at: null },\n { $set: { revoked_at: at } },\n // Code-authored filter: `id` is a string the route checked, never an operator object.\n { trustedFilter: true },\n );\n\n return updated > 0;\n },\n async revokeAll(at) {\n return Shares.atomic(\n { revoked_at: null, expires_at: { $gt: at } },\n { $set: { revoked_at: at } },\n { trustedFilter: true },\n );\n },\n async touch(id, at) {\n await Shares.atomic(\n { id },\n { $set: { last_used_at: at }, $inc: { uses: 1 } },\n { trustedFilter: true },\n );\n },\n async removeOld(before) {\n const expired = await query(Shares).where(\"expires_at\", \"<\", before).delete();\n const revoked = await query(Shares).where(\"revoked_at\", \"<\", before).delete();\n\n return expired + revoked;\n },\n },\n };\n}\n"],"mappings":";;;;;;AAuBA,SAAgB,SAAS,OAAwB;CAC/C,IAAI,OAAO,UAAU,UAAU,OAAO;CAEtC,MAAM,SAAS,OAAO,KAAK;CAE3B,OAAO,OAAO,SAAS,MAAM,IAAI,SAAS;AAC5C;;AAGA,SAAgB,eAAe,OAA+B;CAC5D,OAAO,UAAU,QAAQ,UAAU,SAAY,OAAO,SAAS,KAAK;AACtE;AAEA,SAAgB,eAAe,OAA+B;CAC5D,OAAO,OAAO,UAAU,WAAW,QAAQ;AAC7C;AAEA,SAAgB,UAAU,OAAyB;CACjD,OAAO,UAAU,QAAQ,UAAU,KAAK,UAAU,UAAU,UAAU;AACxE;;AAGA,SAAgB,UAAa,OAAgB,UAAgB;CAC3D,IAAI,OAAO,UAAU,UACnB,IAAI;EACF,OAAO,KAAK,MAAM,KAAK;CACzB,QAAQ;EACN,OAAO;CACT;CAGF,OAAO,UAAU,QAAQ,UAAU,SAAY,WAAY;AAC7D;AAEA,SAAS,QAAW,OAAqB;CACvC,MAAM,SAAS,UAAmB,OAAO,CAAC,CAAC;CAE3C,OAAO,MAAM,QAAQ,MAAM,IAAK,SAAiB,CAAC;AACpD;AAMA,MAAM,kBAAkB;CACtB,OAAO;CACP,MAAM;CACN,cAAc;CACd,gBAAgB;CAChB,oBAAoB;CACpB,YAAY;CACZ,eAAe;CACf,cAAc;CACd,eAAe;CACf,UAAU;CACV,iBAAiB;CACjB,WAAW;CACX,WAAW;CACX,aAAa;CACb,WAAW;CACX,SAAS;AACX;AAEA,SAAgB,aAAa,QAAoC;CAC/D,OAA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MAAM,OAAO,OACX,EAAE,GAAG,GACL;KAAE,MAAM,EAAE,cAAc,GAAG;KAAG,MAAM,EAAE,MAAM,EAAE;IAAE,GAChD,EAAE,eAAe,KAAK,CACxB;GACF;GACA,MAAM,UAAU,QAAQ;IAItB,OAAO,MAHe,MAAM,MAAM,CAAC,CAAC,MAAM,cAAc,KAAK,MAAM,CAAC,CAAC,OAAO,IAG3D,MAFK,MAAM,MAAM,CAAC,CAAC,MAAM,cAAc,KAAK,MAAM,CAAC,CAAC,OAAO;GAG9E;EACF;CACF;AACF"}
@@ -1,116 +0,0 @@
1
- //#region ../../packages/devtools/src/production/contracts.ts
2
- /**
3
- * Upper bounds (inclusive, ms) of the latency buckets every histogram uses.
4
- * A histogram's `counts` has one more entry than this list: the last entry
5
- * counts everything above the highest bound. Fixed bounds make histograms
6
- * from several instances merge exactly.
7
- */
8
- const DEVTOOLS_LATENCY_BUCKETS_MS = [
9
- 1,
10
- 2,
11
- 5,
12
- 10,
13
- 25,
14
- 50,
15
- 100,
16
- 250,
17
- 500,
18
- 1e3,
19
- 2500,
20
- 5e3,
21
- 1e4,
22
- 3e4
23
- ];
24
- /**
25
- * The built-in tabs, in display order, with whether production shows them
26
- * when the project says nothing (`production.panels` overrides per id).
27
- */
28
- const DEVTOOLS_BUILT_IN_PANELS = [
29
- {
30
- id: "requests",
31
- title: "Requests",
32
- production: true
33
- },
34
- {
35
- id: "queries",
36
- title: "Queries",
37
- production: true
38
- },
39
- {
40
- id: "routes",
41
- title: "Routes",
42
- production: true
43
- },
44
- {
45
- id: "resources",
46
- title: "Resources",
47
- production: true
48
- },
49
- {
50
- id: "health",
51
- title: "Health",
52
- production: true
53
- },
54
- {
55
- id: "errors",
56
- title: "Errors",
57
- production: true
58
- },
59
- {
60
- id: "logs",
61
- title: "Logs",
62
- production: true
63
- },
64
- {
65
- id: "jobs",
66
- title: "Jobs",
67
- production: true
68
- },
69
- {
70
- id: "mail",
71
- title: "Mail",
72
- production: false
73
- },
74
- {
75
- id: "ai",
76
- title: "AI",
77
- production: false
78
- },
79
- {
80
- id: "agents",
81
- title: "Agents",
82
- production: false
83
- },
84
- {
85
- id: "api",
86
- title: "API",
87
- production: false
88
- }
89
- ];
90
- /** The audit types that count toward the account, IP and global failure limits. */
91
- const DEVTOOLS_FAILURE_AUDIT_TYPES = [
92
- "login.failed",
93
- "mfa.failed",
94
- "share.failed"
95
- ];
96
-
97
- //#endregion
98
- Object.defineProperty(exports, "DEVTOOLS_BUILT_IN_PANELS", {
99
- enumerable: true,
100
- get: function () {
101
- return DEVTOOLS_BUILT_IN_PANELS;
102
- }
103
- });
104
- Object.defineProperty(exports, "DEVTOOLS_FAILURE_AUDIT_TYPES", {
105
- enumerable: true,
106
- get: function () {
107
- return DEVTOOLS_FAILURE_AUDIT_TYPES;
108
- }
109
- });
110
- Object.defineProperty(exports, "DEVTOOLS_LATENCY_BUCKETS_MS", {
111
- enumerable: true,
112
- get: function () {
113
- return DEVTOOLS_LATENCY_BUCKETS_MS;
114
- }
115
- });
116
- //# sourceMappingURL=contracts-CDuY-ahl.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"contracts-CDuY-ahl.cjs","names":[],"sources":["../../../../../../../packages/devtools/src/production/contracts.ts"],"sourcesContent":["/**\n * The contracts of the devtools production monitor: the shapes the server\n * stores, the JSON its API returns, and the few constants both sides share.\n *\n * This file has NO imports, so the dashboard (`ui-src/`) can import its types\n * too. Every timestamp is epoch milliseconds, every duration milliseconds,\n * every size bytes. Absent values are `null`, never missing.\n */\n\n// ---------------------------------------------------------------------------\n// Modes, roles and stages\n// ---------------------------------------------------------------------------\n\n/** Where the dashboard runs: the loopback development dashboard or the signed-in production monitor. */\nexport type DevtoolsMode = \"development\" | \"production\";\n\n/** What an account may do: `admin` manages users and the dashboard, `viewer` reads. */\nexport type DevtoolsRole = \"admin\" | \"viewer\";\n\n/**\n * Where a browser session stands. Only `active` reaches the data routes;\n * every other stage reaches only the sign-in steps it needs next.\n */\nexport type DevtoolsSessionStage =\n | \"signed-out\"\n | \"password-change\"\n | \"mfa-enrol\"\n | \"mfa-verify\"\n | \"active\";\n\n/** How an account's current password was set. `env` and `reset` passwords must be changed at the next sign-in. */\nexport type DevtoolsPasswordSource = \"env\" | \"setup\" | \"invite\" | \"user\" | \"reset\";\n\n// ---------------------------------------------------------------------------\n// Instances\n// ---------------------------------------------------------------------------\n\n/** One process that runs the monitor (a pm2 or cluster worker, a container). */\nexport type DevtoolsInstanceInfo = {\n /** Stable for the life of the process: `<host>:<pid>:<start time base36>`. */\n id: string;\n /** What the dashboard shows: `<host> #<worker>` or `<host> pid <pid>`. */\n label: string;\n host: string;\n pid: number;\n /** pm2's `NODE_APP_INSTANCE` / `pm_id`, or the cluster worker id; `null` when neither is set. */\n worker: string | null;\n startedAt: number;\n /** When the instance last wrote its report (the current time for the instance answering). */\n seenAt: number;\n nodeVersion: string;\n};\n\n// ---------------------------------------------------------------------------\n// Histograms (mergeable across instances)\n// ---------------------------------------------------------------------------\n\n/**\n * Upper bounds (inclusive, ms) of the latency buckets every histogram uses.\n * A histogram's `counts` has one more entry than this list: the last entry\n * counts everything above the highest bound. Fixed bounds make histograms\n * from several instances merge exactly.\n */\nexport const DEVTOOLS_LATENCY_BUCKETS_MS = [\n 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000,\n] as const;\n\n/** A latency histogram over `DEVTOOLS_LATENCY_BUCKETS_MS`. */\nexport type DevtoolsHistogram = {\n /** `DEVTOOLS_LATENCY_BUCKETS_MS.length + 1` entries. */\n counts: number[];\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n// ---------------------------------------------------------------------------\n// Query, route and error statistics\n// ---------------------------------------------------------------------------\n\n/** Statistics for one normalized query shape (literals and bindings replaced by `?`). */\nexport type DevtoolsQueryShapeStats = {\n /** First 16 hex characters of the SHA-256 of `shape`; the id the API and EXPLAIN use. */\n id: string;\n /** The normalized query, at most 2000 characters. Never holds a value. */\n shape: string;\n driver: \"postgres\" | \"mongodb\";\n connection: string;\n count: number;\n errors: number;\n histogram: DevtoolsHistogram;\n /** Sampled requests in which this shape reached the N+1 threshold, and the highest count in one request. */\n nPlusOne: { requests: number; maxPerRequest: number };\n /** The slowest run seen; its values stay in the process that ran it (see EXPLAIN). */\n slowest: {\n durationMs: number;\n at: number;\n route: string | null;\n requestId: string | null;\n instance: string;\n } | null;\n firstSeen: number;\n lastSeen: number;\n /** Whether EXPLAIN can run for this shape (a Postgres `SELECT`/`WITH`, or a MongoDB `find`/`aggregate`/`count`). */\n explainable: boolean;\n};\n\n/** Time spent in one named request phase (middleware, validation, handler, …) on one route. */\nexport type DevtoolsRoutePhaseStats = {\n name: string;\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n/** Statistics for one route pattern and method. */\nexport type DevtoolsRouteStats = {\n /** `\"<METHOD> <route pattern>\"`, e.g. `\"GET /posts/:slug\"`. */\n key: string;\n method: string;\n route: string;\n count: number;\n /** Responses with a 5xx status or a thrown error. */\n errors: number;\n histogram: DevtoolsHistogram;\n /** At most 30 phases, slowest total first. */\n phases: DevtoolsRoutePhaseStats[];\n slowest: { durationMs: number; at: number; requestId: string | null; instance: string } | null;\n};\n\n/** Errors grouped by fingerprint (normalized message + route + source). */\nexport type DevtoolsErrorGroup = {\n /** First 16 hex characters of the SHA-256 of the fingerprint. */\n id: string;\n /** The latest message as raised, at most 500 characters. */\n message: string;\n /** The error class name when known (`TypeError`). */\n name: string | null;\n source: \"request\" | \"log\";\n route: string | null;\n status: number | null;\n count: number;\n firstSeen: number;\n lastSeen: number;\n lastRequestId: string | null;\n /** The latest stack, at most 4000 characters; `null` when none was available. */\n stack: string | null;\n};\n\n/** A warn/error log entry kept for the Logs panel in production (no context: it may hold values). */\nexport type DevtoolsReportLogEntry = {\n level: \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\";\n module: string;\n action: string;\n /** At most 1000 characters. */\n message: string;\n at: number;\n requestId: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Resources, health, jobs\n// ---------------------------------------------------------------------------\n\n/** One resource reading of a process. */\nexport type DevtoolsResourcePoint = {\n at: number;\n rssBytes: number;\n heapUsedBytes: number;\n heapTotalBytes: number;\n externalBytes: number;\n /** Process CPU time over wall time since the previous point, 0–100 per core (can exceed 100). */\n cpuPercent: number;\n eventLoopDelayP50Ms: number;\n eventLoopDelayP99Ms: number;\n eventLoopDelayMaxMs: number;\n /** `performance.eventLoopUtilization()` since the previous point, 0–1. */\n eventLoopUtilization: number;\n /** Garbage collections since the previous point. */\n gcCount: number;\n /** Total GC pause since the previous point. */\n gcPauseMs: number;\n};\n\n/** The latest resource reading plus values that change rarely. */\nexport type DevtoolsResourceSnapshot = DevtoolsResourcePoint & {\n heapLimitBytes: number;\n uptimeSeconds: number;\n /** Totals since the monitor started, by GC kind. */\n gcByKind: Record<\n \"minor\" | \"major\" | \"incremental\" | \"weakcb\",\n { count: number; pauseMs: number }\n >;\n};\n\n/** Readiness checks (core's `health` registry) of one process, with a short history. */\nexport type DevtoolsHealthReport = {\n status: \"ok\" | \"error\" | \"unknown\";\n checkedAt: number | null;\n checks: Record<string, boolean>;\n /** Newest last, at most 60 entries. */\n history: { at: number; status: \"ok\" | \"error\"; failed: string[] }[];\n};\n\n/** One scheduled job (`@warlock.js/scheduler`). */\nexport type DevtoolsScheduleInfo = {\n name: string;\n /** The cron expression, or `null` for an interval schedule. */\n cron: string | null;\n /** A readable interval such as `\"every 5 minutes\"`, or `null`. */\n interval: string | null;\n isRunning: boolean;\n lastRunAt: number | null;\n nextRunAt: number | null;\n lastDurationMs: number | null;\n lastError: string | null;\n runs: number;\n failures: number;\n};\n\n/** Background work of one process: schedules and queue counts, each `available: false` when its package is not installed. */\nexport type DevtoolsJobsReport = {\n available: { scheduler: boolean; queue: boolean };\n schedules: DevtoolsScheduleInfo[];\n /** Job counts per queue and state (`waiting`, `active`, `delayed`, `failed`, `completed`). */\n queues: { name: string; counts: Record<string, number> }[];\n};\n\n/** What the capture did since the process started. */\nexport type DevtoolsCaptureCounters = {\n sampleRate: number;\n requests: number;\n sampled: number;\n /** Unsampled requests kept as a summary because they were slow or failed. */\n keptUnsampled: number;\n /** Samples written to the database. */\n stored: number;\n /** Samples not written because the per-minute budget was spent. */\n droppedStored: number;\n /** Query shapes, routes and error groups evicted to keep memory bounded. */\n evictedShapes: number;\n evictedRoutes: number;\n evictedErrors: number;\n /** Queries not kept inside a sampled request because it reached its per-request limit. */\n droppedQueries: number;\n};\n\n/**\n * Everything one process reports, written to the database every\n * `reportIntervalMs` (one row per instance) and merged by the dashboard.\n * Serialized it stays under 256 KB: lists are trimmed from the end.\n */\nexport type DevtoolsInstanceReport = {\n instance: DevtoolsInstanceInfo;\n at: number;\n resources: { snapshot: DevtoolsResourceSnapshot; history: DevtoolsResourcePoint[] };\n /** At most 200, highest total time first. */\n queries: DevtoolsQueryShapeStats[];\n /** At most 200, highest total time first. */\n routes: DevtoolsRouteStats[];\n /** At most 50, newest first. */\n errors: DevtoolsErrorGroup[];\n /** At most 50, newest first. */\n logs: DevtoolsReportLogEntry[];\n health: DevtoolsHealthReport;\n jobs: DevtoolsJobsReport;\n capture: DevtoolsCaptureCounters;\n};\n\n// ---------------------------------------------------------------------------\n// Requests (stored samples)\n// ---------------------------------------------------------------------------\n\n/**\n * A request row. Matches the development `DevtoolsRequestSummary` field for\n * field, plus where it was captured.\n */\nexport type DevtoolsSampleSummary = {\n id: string;\n method: string;\n path: string;\n route?: string;\n status?: number;\n startedAt: number;\n durationMs?: number;\n queryCount: number;\n warningCount: number;\n /** Read from the persisted request log only. */\n persisted?: true;\n /** The instance that served the request. */\n instance?: string;\n /** Kept because it was slow or failed, without a timeline (the request was not sampled). */\n partial?: true;\n};\n\n/** A query inside a stored sample: the shape only, never the SQL text with values or the bindings. */\nexport type DevtoolsSampleQuery = {\n id: string;\n connection: string;\n driver: \"postgres\" | \"mongodb\";\n /** Same as `shape`: kept under this name so the request view renders it like a development query. */\n sql?: string;\n collection?: string;\n command?: string;\n shape: string;\n shapeId: string;\n startedAt: number;\n durationMs: number;\n rowCount?: number;\n error?: string;\n};\n\n/** The timeline of a sampled request, with every value removed (see the redaction rules). */\nexport type DevtoolsSampleDetail = DevtoolsSampleSummary & {\n error?: string;\n phases: { name: string; startedAt: number; durationMs: number }[];\n queries: DevtoolsSampleQuery[];\n /** Cache operation counts only; keys are not kept. */\n cache: { hits: number; misses: number; writes: number };\n /** Log entries without context. */\n logs: { level: string; module: string; action: string; message: string; at: number }[];\n warnings: { type: \"n+1\"; message: string; shape: string; count: number }[];\n /** Queries left out because the request reached `maxQueriesPerRequest`. */\n droppedQueries: number;\n};\n\n// ---------------------------------------------------------------------------\n// API views (what the dashboard reads)\n// ---------------------------------------------------------------------------\n\n/** `GET api/instances`. */\nexport type DevtoolsInstancesView = {\n /** The instance that answered this request. */\n current: string;\n /** Instances seen in the last 5 minutes (the answering one included), newest first. */\n instances: DevtoolsInstanceInfo[];\n};\n\n/** `GET api/resources?instance=<id|all>`. */\nexport type DevtoolsResourcesView = {\n instances: {\n instance: DevtoolsInstanceInfo;\n snapshot: DevtoolsResourceSnapshot;\n history: DevtoolsResourcePoint[];\n }[];\n};\n\n/** A shape row with figures computed from its histogram. */\nexport type DevtoolsQueryShapeRow = DevtoolsQueryShapeStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n /** Ids of the instances that reported this shape. */\n instances: string[];\n};\n\n/** `GET api/queries/stats?instance=&sort=total|p95|count|n+1&limit=`. */\nexport type DevtoolsQueryStatsView = {\n shapes: DevtoolsQueryShapeRow[];\n /** The sample rate the counts come from; counts are of sampled requests only. */\n sampleRate: number;\n instanceCount: number;\n evicted: number;\n};\n\n/** A route row with figures computed from its histogram. */\nexport type DevtoolsRouteStatsRow = DevtoolsRouteStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n instances: string[];\n};\n\n/** `GET api/routes/stats?instance=&sort=total|p95|count|errors&limit=`. */\nexport type DevtoolsRouteStatsView = {\n routes: DevtoolsRouteStatsRow[];\n sampleRate: number;\n instanceCount: number;\n};\n\n/** `GET api/health?instance=`. */\nexport type DevtoolsHealthView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsHealthReport }[];\n};\n\n/** `GET api/errors?instance=&limit=`. */\nexport type DevtoolsErrorsView = {\n groups: (DevtoolsErrorGroup & { instances: string[] })[];\n};\n\n/**\n * One row of `GET api/logs?level=&module=&instance=` (newest first), in both\n * modes. Development rows carry `context` and no `instance`; production rows\n * carry `instance` and never `context`.\n */\nexport type DevtoolsLogRow = DevtoolsReportLogEntry & {\n instance: string | null;\n context?: unknown;\n};\n\n/** `GET api/logs`: the rows, newest first (a plain array, as in 5.55). */\nexport type DevtoolsLogsView = DevtoolsLogRow[];\n\n/** `GET api/jobs?instance=`. */\nexport type DevtoolsJobsView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsJobsReport }[];\n};\n\n/** `POST api/queries/:shapeId/explain`. */\nexport type DevtoolsExplainResult = {\n shapeId: string;\n driver: \"postgres\" | \"mongodb\";\n /** `true` only when the project allows executing plans (`explain.executing`). */\n executing: boolean;\n plan: unknown;\n /** The instance whose example ran the EXPLAIN. */\n instance: string;\n};\n\n/** One dashboard tab, as `GET api/panels` lists it (enabled tabs only, in display order). */\nexport type DevtoolsPanelInfo = {\n id: string;\n title: string;\n /** `built-in` tabs are React views in the bundle; `package` tabs load `panels/<id>/view.js`. */\n type: \"built-in\" | \"package\";\n /** Whether the panel declares a shared view (`DevtoolsPanel.share`); always `false` for built-in tabs. */\n shareable: boolean;\n};\n\n/**\n * The built-in tabs, in display order, with whether production shows them\n * when the project says nothing (`production.panels` overrides per id).\n */\nexport const DEVTOOLS_BUILT_IN_PANELS = [\n { id: \"requests\", title: \"Requests\", production: true },\n { id: \"queries\", title: \"Queries\", production: true },\n { id: \"routes\", title: \"Routes\", production: true },\n { id: \"resources\", title: \"Resources\", production: true },\n { id: \"health\", title: \"Health\", production: true },\n { id: \"errors\", title: \"Errors\", production: true },\n { id: \"logs\", title: \"Logs\", production: true },\n { id: \"jobs\", title: \"Jobs\", production: true },\n { id: \"mail\", title: \"Mail\", production: false },\n { id: \"ai\", title: \"AI\", production: false },\n { id: \"agents\", title: \"Agents\", production: false },\n { id: \"api\", title: \"API\", production: false },\n] as const;\n\n/** The id of a built-in tab. */\nexport type DevtoolsBuiltInPanelId = (typeof DEVTOOLS_BUILT_IN_PANELS)[number][\"id\"];\n\n// ---------------------------------------------------------------------------\n// Accounts, sessions, invites\n// ---------------------------------------------------------------------------\n\n/** An account as the API shows it (never a hash or a secret). */\nexport type DevtoolsAccountView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n twoFactor: {\n totp: boolean;\n passkeys: { id: string; name: string; createdAt: number; lastUsedAt: number | null }[];\n recoveryCodesLeft: number;\n };\n mustChangePassword: boolean;\n createdAt: number;\n lastLoginAt: number | null;\n};\n\n/** `GET api/auth/session`: who is signed in and what comes next. */\nexport type DevtoolsSessionView = {\n mode: DevtoolsMode;\n stage: DevtoolsSessionStage;\n /** `null` when signed out, and in development (no accounts there). */\n account: DevtoolsAccountView | null;\n /** `admin` in development; `null` when signed out. */\n role: DevtoolsRole | null;\n /** The token to send as `X-Devtools-Csrf` on every POST/PUT/PATCH/DELETE; `null` when signed out and in development. */\n csrf: string | null;\n /** When the session ends at the latest; `null` when signed out and in development. */\n expiresAt: number | null;\n /** The instance that answered; `null` when signed out. */\n instance: DevtoolsInstanceInfo | null;\n /** Sign-in methods the server offers; `null` when signed out. */\n methods: { totp: true; passkeys: boolean } | null;\n /** Read-only share links: `enabled` mirrors `production.share.enabled`; `null` when signed out and in development. */\n share: { enabled: boolean } | null;\n};\n\n/** `POST api/auth/login` body. */\nexport type DevtoolsLoginInput = { email: string; password: string };\n\n/** Answer of every sign-in step: the next stage, and the new CSRF token when the session changed. */\nexport type DevtoolsAuthStepResult = { stage: DevtoolsSessionStage; csrf: string | null };\n\n/** `POST api/auth/totp/start` (and `api/account/totp/start`). */\nexport type DevtoolsTotpEnrolment = {\n /** Base32, for manual entry. */\n secret: string;\n /** `otpauth://totp/...`, rendered as a QR code by the dashboard. */\n uri: string;\n issuer: string;\n account: string;\n};\n\n/** Recovery codes, shown once. */\nexport type DevtoolsRecoveryCodes = { codes: string[] };\n\n/** A pending or used invite. */\nexport type DevtoolsInviteView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n createdAt: number;\n expiresAt: number;\n createdBy: string | null;\n usedAt: number | null;\n};\n\n/** `POST api/admin/invites`: the token appears only in this answer. */\nexport type DevtoolsCreatedInvite = { invite: DevtoolsInviteView; token: string };\n\n/** `GET api/admin/users`. */\nexport type DevtoolsUserListView = {\n accounts: DevtoolsAccountView[];\n invites: DevtoolsInviteView[];\n};\n\n/** A session as its owner sees it (`GET api/account/sessions`). */\nexport type DevtoolsSessionInfo = {\n id: string;\n current: boolean;\n createdAt: number;\n lastSeenAt: number;\n expiresAt: number;\n ip: string | null;\n userAgent: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Share links\n// ---------------------------------------------------------------------------\n\n/** Where a share link stands. `revoked` wins over `expired`. */\nexport type DevtoolsShareStatus = \"active\" | \"expired\" | \"revoked\";\n\n/** A share link as the admin screen shows it (never the token or its hash). */\nexport type DevtoolsShareView = {\n id: string;\n /** The id of the panel the link opens. */\n panel: string;\n /** What the admin called it, 1-80 characters. */\n label: string;\n /** The email of the admin who made it; `null` when that account is gone. */\n createdBy: string | null;\n createdAt: number;\n expiresAt: number;\n revokedAt: number | null;\n lastUsedAt: number | null;\n /** How many times the link was used, counted at most once a minute. */\n uses: number;\n status: DevtoolsShareStatus;\n};\n\n/** `GET api/admin/shares`. */\nexport type DevtoolsShareList = {\n enabled: boolean;\n /** The longest life a link may have, in days. */\n maxDays: number;\n /** The panels that declare a shared view. */\n panels: { id: string; title: string }[];\n /** Newest first. */\n shares: DevtoolsShareView[];\n};\n\n/** `POST api/admin/shares` body. `label` is 1-80 characters, `days` a whole number from 1 to `maxDays`. */\nexport type DevtoolsShareCreateInput = { panel: string; label: string; days: number };\n\n/** `POST api/admin/shares`: the URL (with the token in its fragment) appears only in this answer. */\nexport type DevtoolsCreatedShare = { share: DevtoolsShareView; url: string };\n\n/**\n * What a share link opens, answered by `POST api/share/open` and\n * `GET api/share/info`: the panel and the names the shared view may load.\n */\nexport type DevtoolsShareOpenAnswer = {\n panel: string;\n /** The panel's title. */\n title: string;\n label: string;\n expiresAt: number;\n /** Served names from the panel's `assets` the shared page may load. */\n assets: string[];\n /** Whether the shared page may load images from the panel's `files`. */\n files: boolean;\n};\n\n/** The longest label of a share link. */\nexport const DEVTOOLS_SHARE_LABEL_MAX = 80;\n\n// ---------------------------------------------------------------------------\n// Audit log\n// ---------------------------------------------------------------------------\n\n/** Every audited event. `login.failed` and `mfa.failed` are the ones rate limits count. */\nexport type DevtoolsAuditType =\n | \"admin.seeded\"\n | \"admin.reset\"\n | \"setup.completed\"\n | \"login.succeeded\"\n | \"login.failed\"\n | \"login.blocked\"\n | \"mfa.succeeded\"\n | \"mfa.failed\"\n | \"mfa.enrolled\"\n | \"mfa.removed\"\n | \"recovery-code.used\"\n | \"recovery-codes.regenerated\"\n | \"passkey.added\"\n | \"passkey.removed\"\n | \"password.changed\"\n | \"logout\"\n | \"session.revoked\"\n | \"invite.created\"\n | \"invite.revoked\"\n | \"invite.accepted\"\n | \"account.role-changed\"\n | \"account.removed\"\n | \"account.mfa-reset\"\n | \"account.signed-out\"\n | \"dashboard.disabled\"\n | \"dashboard.enabled\"\n | \"dashboard.locked\"\n | \"explain.run\"\n | \"requests.cleared\"\n | \"panel.action\"\n | \"share.created\"\n | \"share.revoked\"\n | \"share.failed\";\n\n/** The audit types that count toward the account, IP and global failure limits. */\nexport const DEVTOOLS_FAILURE_AUDIT_TYPES: readonly DevtoolsAuditType[] = [\n \"login.failed\",\n \"mfa.failed\",\n \"share.failed\",\n];\n\n/** One audit log entry. */\nexport type DevtoolsAuditEntry = {\n id: string;\n at: number;\n type: DevtoolsAuditType;\n /** The account acting or targeted; `null` for an unknown email or the CLI. */\n accountId: string | null;\n /** The email as typed or as stored, lower-cased; `null` when there was none. */\n email: string | null;\n /** `\"cli\"` for a command, else the client IP after trusted-proxy resolution. */\n ip: string | null;\n /** At most 200 characters. */\n userAgent: string | null;\n /** Small flat facts: target account, role, shape id, panel route. Never a secret. */\n detail: Record<string, string | number | boolean | null>;\n /** Short reference shown to users in error messages (8 characters). */\n ref: string;\n};\n\n// ---------------------------------------------------------------------------\n// Errors the API returns\n// ---------------------------------------------------------------------------\n\n/**\n * Error codes in API answers. Each has a fixed message (see\n * `DEVTOOLS_ERROR_MESSAGES` in `errors.ts`) that says what failed and what to\n * do next.\n */\nexport type DevtoolsErrorCode =\n | \"auth.invalid-credentials\"\n | \"auth.invalid-code\"\n | \"auth.invalid-setup-token\"\n | \"auth.password-too-short\"\n | \"auth.password-too-long\"\n | \"auth.password-common\"\n | \"auth.password-same-as-email\"\n | \"auth.password-unchanged\"\n | \"auth.wrong-current-password\"\n | \"auth.busy\"\n | \"invite.invalid\"\n | \"invite.email-taken\"\n | \"account.not-found\"\n | \"account.last-admin\"\n | \"account.self\"\n | \"account.last-factor\"\n | \"role.forbidden\"\n | \"csrf.invalid\"\n | \"passkey.unavailable\"\n | \"passkey.failed\"\n | \"explain.not-allowed\"\n | \"explain.unsupported\"\n | \"explain.elsewhere\"\n | \"explain.failed\"\n | \"request.not-found\"\n | \"request.invalid-filter\"\n | \"share.not-found\"\n | \"stream.too-many\"\n | \"input.invalid\"\n | \"server.error\";\n\n/** The JSON body of every failed API call. */\nexport type DevtoolsApiErrorBody = {\n /** What failed and what to do next. */\n error: string;\n code: DevtoolsErrorCode;\n /** Short reference to quote to an admin; also written to the audit log or server log. */\n ref?: string;\n /** The instance that answered, when it matters (`explain.elsewhere`). */\n instance?: string;\n};\n"],"mappings":";;;;;;;AA+DA,MAAa,8BAA8B;CACzC;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAK;CAAK;CAAK;CAAM;CAAM;CAAM;CAAO;AAC/D;;;;;AAgXA,MAAa,2BAA2B;CACtC;EAAE,IAAI;EAAY,OAAO;EAAY,YAAY;CAAK;CACtD;EAAE,IAAI;EAAW,OAAO;EAAW,YAAY;CAAK;CACpD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAa,OAAO;EAAa,YAAY;CAAK;CACxD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAK;CAC9C;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAK;CAC9C;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAM;CAC/C;EAAE,IAAI;EAAM,OAAO;EAAM,YAAY;CAAM;CAC3C;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAM;CACnD;EAAE,IAAI;EAAO,OAAO;EAAO,YAAY;CAAM;AAC/C;;AAoMA,MAAa,+BAA6D;CACxE;CACA;CACA;AACF"}