@warlock.js/devtools 5.57.0 → 5.58.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 (114) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +3 -0
  3. package/cjs/{auth-DzU0gHDG.cjs → auth-DV2GA1A9.cjs} +33 -403
  4. package/cjs/auth-DV2GA1A9.cjs.map +1 -0
  5. package/cjs/{boot-Dy5OqgTM.cjs → boot-CyeHPFtk.cjs} +14 -12
  6. package/cjs/boot-CyeHPFtk.cjs.map +1 -0
  7. package/cjs/{capture-CqIiaznN.cjs → capture-DcyBhdqw.cjs} +3 -3
  8. package/cjs/{capture-CqIiaznN.cjs.map → capture-DcyBhdqw.cjs.map} +1 -1
  9. package/cjs/{cascade-store-pHjKeSFm.cjs → cascade-store-DEGxAFDI.cjs} +141 -4
  10. package/cjs/cascade-store-DEGxAFDI.cjs.map +1 -0
  11. package/cjs/{contracts-CVmplkNb.cjs → contracts-CDuY-ahl.cjs} +6 -2
  12. package/cjs/{contracts-CVmplkNb.cjs.map → contracts-CDuY-ahl.cjs.map} +1 -1
  13. package/cjs/{errors-CyZp5yS-.cjs → errors-DEqdWaqm.cjs} +3 -1
  14. package/cjs/{errors-CyZp5yS-.cjs.map → errors-DEqdWaqm.cjs.map} +1 -1
  15. package/cjs/helpers-7k_Q-abk.cjs +436 -0
  16. package/cjs/helpers-7k_Q-abk.cjs.map +1 -0
  17. package/cjs/{histogram-BaI-PnCv.cjs → histogram-BRV5eHcp.cjs} +2 -2
  18. package/cjs/{histogram-BaI-PnCv.cjs.map → histogram-BRV5eHcp.cjs.map} +1 -1
  19. package/cjs/{http-DCfXQvw-.cjs → http-XNLYU2vS.cjs} +517 -28
  20. package/cjs/http-XNLYU2vS.cjs.map +1 -0
  21. package/cjs/index.cjs +1 -1
  22. package/cjs/{insights-BKtqxdnP.cjs → insights-BBZnUpWO.cjs} +4 -3
  23. package/cjs/{insights-BKtqxdnP.cjs.map → insights-BBZnUpWO.cjs.map} +1 -1
  24. package/cjs/{migrations-w7GMsrQw.cjs → migrations-DTTzCNpR.cjs} +38 -3
  25. package/cjs/migrations-DTTzCNpR.cjs.map +1 -0
  26. package/cjs/{options-CWqFC5__.cjs → options-CHhmQJic.cjs} +16 -4
  27. package/cjs/options-CHhmQJic.cjs.map +1 -0
  28. package/cjs/{panels-Rcmeitu3.cjs → panels-CHd20RK5.cjs} +74 -7
  29. package/cjs/panels-CHd20RK5.cjs.map +1 -0
  30. package/cjs/production/index.cjs +4 -4
  31. package/cjs/{server-ykxsOwob.cjs → server-C8JfggQU.cjs} +5 -4
  32. package/cjs/server-C8JfggQU.cjs.map +1 -0
  33. package/cjs/{src-UPtTCI2j.cjs → src-DjOUdhKc.cjs} +47 -10
  34. package/cjs/src-DjOUdhKc.cjs.map +1 -0
  35. package/cjs/{store-aq207T8v.cjs → store-C06KO_A1.cjs} +2 -2
  36. package/cjs/{stream-route-CJTABkUy.cjs → stream-route-D4k-sJvW.cjs} +70 -9
  37. package/cjs/stream-route-D4k-sJvW.cjs.map +1 -0
  38. package/esm/devtools-connector.d.mts.map +1 -1
  39. package/esm/devtools-connector.mjs +10 -3
  40. package/esm/devtools-connector.mjs.map +1 -1
  41. package/esm/index.d.mts +3 -3
  42. package/esm/panel-errors.mjs +33 -0
  43. package/esm/panel-errors.mjs.map +1 -0
  44. package/esm/panels.mjs +73 -6
  45. package/esm/panels.mjs.map +1 -1
  46. package/esm/production/auth/service.mjs +4 -2
  47. package/esm/production/auth/service.mjs.map +1 -1
  48. package/esm/production/boot.mjs +4 -2
  49. package/esm/production/boot.mjs.map +1 -1
  50. package/esm/production/contracts.d.mts +68 -2
  51. package/esm/production/contracts.d.mts.map +1 -1
  52. package/esm/production/contracts.mjs +5 -1
  53. package/esm/production/contracts.mjs.map +1 -1
  54. package/esm/production/errors.mjs +2 -0
  55. package/esm/production/errors.mjs.map +1 -1
  56. package/esm/production/http/access.mjs +6 -2
  57. package/esm/production/http/access.mjs.map +1 -1
  58. package/esm/production/http/constants.mjs +7 -1
  59. package/esm/production/http/constants.mjs.map +1 -1
  60. package/esm/production/http/context.mjs.map +1 -1
  61. package/esm/production/http/cookie.mjs +23 -2
  62. package/esm/production/http/cookie.mjs.map +1 -1
  63. package/esm/production/http/mount.mjs +25 -3
  64. package/esm/production/http/mount.mjs.map +1 -1
  65. package/esm/production/http/share-session.mjs +114 -0
  66. package/esm/production/http/share-session.mjs.map +1 -0
  67. package/esm/production/http/share.mjs +339 -0
  68. package/esm/production/http/share.mjs.map +1 -0
  69. package/esm/production/index.d.mts +2 -2
  70. package/esm/production/insights/writer.mjs +2 -1
  71. package/esm/production/insights/writer.mjs.map +1 -1
  72. package/esm/production/options.d.mts +5 -0
  73. package/esm/production/options.d.mts.map +1 -1
  74. package/esm/production/options.mjs +14 -2
  75. package/esm/production/options.mjs.map +1 -1
  76. package/esm/production/store/cascade-store.mjs +49 -2
  77. package/esm/production/store/cascade-store.mjs.map +1 -1
  78. package/esm/production/store/mapping.mjs +29 -1
  79. package/esm/production/store/mapping.mjs.map +1 -1
  80. package/esm/production/store/memory-store.mjs +62 -0
  81. package/esm/production/store/memory-store.mjs.map +1 -1
  82. package/esm/production/store/migrations.d.mts +2 -1
  83. package/esm/production/store/migrations.d.mts.map +1 -1
  84. package/esm/production/store/migrations.mjs +5 -2
  85. package/esm/production/store/migrations.mjs.map +1 -1
  86. package/esm/production/store/models/index.mjs +3 -1
  87. package/esm/production/store/models/share.migration.mjs +27 -0
  88. package/esm/production/store/models/share.migration.mjs.map +1 -0
  89. package/esm/production/store/models/share.model.mjs +13 -0
  90. package/esm/production/store/models/share.model.mjs.map +1 -0
  91. package/esm/server/panel-files.mjs +35 -0
  92. package/esm/server/panel-files.mjs.map +1 -0
  93. package/esm/server/panel-routes.mjs +27 -7
  94. package/esm/server/panel-routes.mjs.map +1 -1
  95. package/esm/server/session-routes.mjs +2 -1
  96. package/esm/server/session-routes.mjs.map +1 -1
  97. package/esm/types.d.mts +81 -2
  98. package/esm/types.d.mts.map +1 -1
  99. package/llms-full.txt +34 -4
  100. package/package.json +8 -8
  101. package/skills/SKILL.md +34 -4
  102. package/ui/dashboard/assets/app.css +1 -1
  103. package/ui/dashboard/assets/app.js +16 -16
  104. package/ui/dashboard/build-info.json +7 -7
  105. package/cjs/auth-DzU0gHDG.cjs.map +0 -1
  106. package/cjs/boot-Dy5OqgTM.cjs.map +0 -1
  107. package/cjs/cascade-store-pHjKeSFm.cjs.map +0 -1
  108. package/cjs/http-DCfXQvw-.cjs.map +0 -1
  109. package/cjs/migrations-w7GMsrQw.cjs.map +0 -1
  110. package/cjs/options-CWqFC5__.cjs.map +0 -1
  111. package/cjs/panels-Rcmeitu3.cjs.map +0 -1
  112. package/cjs/server-ykxsOwob.cjs.map +0 -1
  113. package/cjs/src-UPtTCI2j.cjs.map +0 -1
  114. package/cjs/stream-route-CJTABkUy.cjs.map +0 -1
@@ -1,4 +1,4 @@
1
- const require_errors = require("./errors-CyZp5yS-.cjs");
1
+ const require_errors = require("./errors-DEqdWaqm.cjs");
2
2
  const require_ip = require("./ip-DbNhPOzi.cjs");
3
3
  let node_crypto = require("node:crypto");
4
4
 
@@ -148,6 +148,34 @@ function rowToInvite(row) {
148
148
  accountId: toStringOrNull(row.account_id)
149
149
  };
150
150
  }
151
+ function shareToRow(record) {
152
+ return {
153
+ id: record.id,
154
+ token_hash: record.tokenHash,
155
+ panel: record.panel,
156
+ label: record.label,
157
+ created_by: record.createdBy,
158
+ created_at: record.createdAt,
159
+ expires_at: record.expiresAt,
160
+ revoked_at: record.revokedAt,
161
+ last_used_at: record.lastUsedAt,
162
+ uses: record.uses
163
+ };
164
+ }
165
+ function rowToShare(row) {
166
+ return {
167
+ id: String(row.id),
168
+ tokenHash: String(row.token_hash),
169
+ panel: String(row.panel),
170
+ label: String(row.label),
171
+ createdBy: toStringOrNull(row.created_by),
172
+ createdAt: toNumber(row.created_at),
173
+ expiresAt: toNumber(row.expires_at),
174
+ revokedAt: toNumberOrNull(row.revoked_at),
175
+ lastUsedAt: toNumberOrNull(row.last_used_at),
176
+ uses: toNumber(row.uses)
177
+ };
178
+ }
151
179
  function auditToRow(entry) {
152
180
  return {
153
181
  id: entry.id,
@@ -308,6 +336,7 @@ function createMemoryStore(options = {}) {
308
336
  const accounts = /* @__PURE__ */ new Map();
309
337
  const sessions = /* @__PURE__ */ new Map();
310
338
  const invites = /* @__PURE__ */ new Map();
339
+ const shares = /* @__PURE__ */ new Map();
311
340
  const audit = [];
312
341
  const samples = /* @__PURE__ */ new Map();
313
342
  const reports = /* @__PURE__ */ new Map();
@@ -536,6 +565,67 @@ function createMemoryStore(options = {}) {
536
565
  async remove(instanceId) {
537
566
  return reports.delete(instanceId);
538
567
  }
568
+ },
569
+ shares: {
570
+ async create(input) {
571
+ for (const share of shares.values()) if (share.tokenHash === input.tokenHash) throw new require_errors.DevtoolsStoreConflictError("tokenHash");
572
+ const record = {
573
+ ...copy(input),
574
+ id: (0, node_crypto.randomUUID)(),
575
+ revokedAt: null,
576
+ lastUsedAt: null,
577
+ uses: 0
578
+ };
579
+ shares.set(record.id, record);
580
+ return copy(record);
581
+ },
582
+ async findByTokenHash(tokenHash) {
583
+ for (const share of shares.values()) if (share.tokenHash === tokenHash) return copy(share);
584
+ return null;
585
+ },
586
+ async get(id) {
587
+ const share = shares.get(id);
588
+ return share ? copy(share) : null;
589
+ },
590
+ async list() {
591
+ return [...shares.values()].sort((a, b) => b.createdAt - a.createdAt).map(copy);
592
+ },
593
+ async revoke(id, at) {
594
+ const share = shares.get(id);
595
+ if (!share || share.revokedAt !== null) return false;
596
+ shares.set(id, {
597
+ ...share,
598
+ revokedAt: at
599
+ });
600
+ return true;
601
+ },
602
+ async revokeAll(at) {
603
+ let revoked = 0;
604
+ for (const share of [...shares.values()]) if (share.revokedAt === null && share.expiresAt > at) {
605
+ shares.set(share.id, {
606
+ ...share,
607
+ revokedAt: at
608
+ });
609
+ revoked++;
610
+ }
611
+ return revoked;
612
+ },
613
+ async touch(id, at) {
614
+ const share = shares.get(id);
615
+ if (share) shares.set(id, {
616
+ ...share,
617
+ lastUsedAt: at,
618
+ uses: share.uses + 1
619
+ });
620
+ },
621
+ async removeOld(before) {
622
+ let removed = 0;
623
+ for (const share of [...shares.values()]) if (share.expiresAt < before || share.revokedAt !== null && share.revokedAt < before) {
624
+ shares.delete(share.id);
625
+ removed++;
626
+ }
627
+ return removed;
628
+ }
539
629
  }
540
630
  };
541
631
  }
@@ -581,12 +671,12 @@ async function createCascadeStore(options = {}) {
581
671
  const now = options.now ?? Date.now;
582
672
  let models;
583
673
  try {
584
- models = await Promise.resolve().then(() => require("./migrations-w7GMsrQw.cjs")).then((n) => n.models_exports);
674
+ models = await Promise.resolve().then(() => require("./migrations-DTTzCNpR.cjs")).then((n) => n.models_exports);
585
675
  models.DevtoolsAccountRow.getDataSource();
586
676
  } catch (error) {
587
677
  throw new require_errors.DevtoolsProductionConfigError("DT005", error instanceof Error ? `(${error.message})` : void 0);
588
678
  }
589
- const { DevtoolsAccountRow: Accounts, DevtoolsSessionRow: Sessions, DevtoolsInviteRow: Invites, DevtoolsAuditRow: Audit, DevtoolsStateRow: State, DevtoolsSampleRow: Samples, DevtoolsReportRow: Reports } = models;
679
+ const { DevtoolsAccountRow: Accounts, DevtoolsSessionRow: Sessions, DevtoolsInviteRow: Invites, DevtoolsAuditRow: Audit, DevtoolsStateRow: State, DevtoolsSampleRow: Samples, DevtoolsReportRow: Reports, DevtoolsShareRow: Shares } = models;
590
680
  const tables = [
591
681
  Accounts,
592
682
  Sessions,
@@ -596,10 +686,15 @@ async function createCascadeStore(options = {}) {
596
686
  Samples,
597
687
  Reports
598
688
  ];
689
+ if (options.shares === true) tables.push(Shares);
599
690
  const accountById = async (id) => {
600
691
  const row = await byId(Accounts, id);
601
692
  return row ? rowToAccount(row) : null;
602
693
  };
694
+ const shareById = async (id) => {
695
+ const row = await byId(Shares, id);
696
+ return row ? rowToShare(row) : null;
697
+ };
603
698
  const sessionById = async (id) => {
604
699
  const row = await byId(Sessions, id);
605
700
  return row ? rowToSession(row) : null;
@@ -850,6 +945,48 @@ async function createCascadeStore(options = {}) {
850
945
  async remove(instanceId) {
851
946
  return removeWhere(Reports, "id", instanceId);
852
947
  }
948
+ },
949
+ shares: {
950
+ async create(input) {
951
+ const record = {
952
+ ...structuredClone(input),
953
+ id: (0, node_crypto.randomUUID)(),
954
+ revokedAt: null,
955
+ lastUsedAt: null,
956
+ uses: 0
957
+ };
958
+ await insert(Shares, shareToRow(record));
959
+ return record;
960
+ },
961
+ async findByTokenHash(tokenHash) {
962
+ const row = await rows(Shares).where("token_hash", "=", tokenHash).first();
963
+ return row ? rowToShare(row) : null;
964
+ },
965
+ get: shareById,
966
+ async list() {
967
+ return (await rows(Shares).orderBy("created_at", "desc").get()).map(rowToShare);
968
+ },
969
+ async revoke(id, at) {
970
+ return await Shares.atomic({
971
+ id,
972
+ revoked_at: null
973
+ }, { $set: { revoked_at: at } }, { trustedFilter: true }) > 0;
974
+ },
975
+ async revokeAll(at) {
976
+ return Shares.atomic({
977
+ revoked_at: null,
978
+ expires_at: { $gt: at }
979
+ }, { $set: { revoked_at: at } }, { trustedFilter: true });
980
+ },
981
+ async touch(id, at) {
982
+ await Shares.atomic({ id }, {
983
+ $set: { last_used_at: at },
984
+ $inc: { uses: 1 }
985
+ }, { trustedFilter: true });
986
+ },
987
+ async removeOld(before) {
988
+ return await query(Shares).where("expires_at", "<", before).delete() + await query(Shares).where("revoked_at", "<", before).delete();
989
+ }
853
990
  }
854
991
  };
855
992
  }
@@ -860,4 +997,4 @@ exports.createMemoryStore = createMemoryStore;
860
997
  exports.defaultStateRecord = defaultStateRecord;
861
998
  exports.sampleMatches = sampleMatches;
862
999
  exports.sampleStatusMatches = sampleStatusMatches;
863
- //# sourceMappingURL=cascade-store-pHjKeSFm.cjs.map
1000
+ //# sourceMappingURL=cascade-store-DEGxAFDI.cjs.map
@@ -0,0 +1 @@
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,OAAO;EAAE,IAAI,OAAO;EAAI,GAAG,YAAY,iBAAiB,MAAM;CAAE;AAClE;AAEA,SAAgB,kBAAkB,OAAkC;CAClE,OAAO,YAAY,iBAAiB,KAAK;AAC3C;AAEA,SAAgB,aAAa,KAAiC;CAC5D,OAAO;E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e,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"}
@@ -88,7 +88,11 @@ const DEVTOOLS_BUILT_IN_PANELS = [
88
88
  }
89
89
  ];
90
90
  /** The audit types that count toward the account, IP and global failure limits. */
91
- const DEVTOOLS_FAILURE_AUDIT_TYPES = ["login.failed", "mfa.failed"];
91
+ const DEVTOOLS_FAILURE_AUDIT_TYPES = [
92
+ "login.failed",
93
+ "mfa.failed",
94
+ "share.failed"
95
+ ];
92
96
 
93
97
  //#endregion
94
98
  Object.defineProperty(exports, "DEVTOOLS_BUILT_IN_PANELS", {
@@ -109,4 +113,4 @@ Object.defineProperty(exports, "DEVTOOLS_LATENCY_BUCKETS_MS", {
109
113
  return DEVTOOLS_LATENCY_BUCKETS_MS;
110
114
  }
111
115
  });
112
- //# sourceMappingURL=contracts-CVmplkNb.cjs.map
116
+ //# sourceMappingURL=contracts-CDuY-ahl.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"contracts-CVmplkNb.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};\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};\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// 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\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];\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 | \"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;;;;;AA8WA,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;;AAkIA,MAAa,+BAA6D,CACxE,gBACA,YACF"}
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"}
@@ -58,6 +58,7 @@ const DEVTOOLS_ERROR_MESSAGES = {
58
58
  "explain.failed": "The database could not explain this query. The reference is in the server log.",
59
59
  "request.not-found": "This request is no longer stored. Requests are kept for a limited time (24 hours by default).",
60
60
  "request.invalid-filter": "A filter value is not valid. Check the status, method and dates.",
61
+ "share.not-found": "This share link no longer exists or is already revoked. Reload the list.",
61
62
  "stream.too-many": "Too many live views are open for this session. Close another dashboard tab and reload.",
62
63
  "input.invalid": "Some fields are missing or not valid. Check the form and try again.",
63
64
  "server.error": "The dashboard could not complete this action. Try again; if it keeps failing, give your admin the reference shown."
@@ -90,6 +91,7 @@ const DEVTOOLS_ERROR_STATUS = {
90
91
  "explain.failed": 502,
91
92
  "request.not-found": 404,
92
93
  "request.invalid-filter": 400,
94
+ "share.not-found": 404,
93
95
  "stream.too-many": 429,
94
96
  "input.invalid": 422,
95
97
  "server.error": 500
@@ -174,4 +176,4 @@ Object.defineProperty(exports, "createErrorRef", {
174
176
  return createErrorRef;
175
177
  }
176
178
  });
177
- //# sourceMappingURL=errors-CyZp5yS-.cjs.map
179
+ //# sourceMappingURL=errors-DEqdWaqm.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors-CyZp5yS-.cjs","names":["randomBytes"],"sources":["../../../../../../../packages/devtools/src/production/errors.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport type { DevtoolsApiErrorBody, DevtoolsErrorCode } from \"./contracts\";\n\n/**\n * Why production mode refused to start. Each code names one missing or\n * invalid setting; the message says which and how to fix it.\n */\nexport const DEVTOOLS_CONFIG_CODES = {\n DT001:\n \"Devtools production mode needs a dashboard path. Set DEVTOOLS_PATH (for example /ops-7f3k2q) or devtools.production.path.\",\n DT002:\n 'The devtools dashboard path must start with \"/\", be at least 8 characters, use only letters, digits, \"-\", \"_\", \".\", \"~\" and \"/\", and not be \"/__warlock\".',\n DT003:\n \"Devtools production mode has no admin yet. Set DEVTOOLS_ADMIN_EMAIL with DEVTOOLS_ADMIN_PASSWORD or DEVTOOLS_SETUP_TOKEN, or run `warlock devtools:reset-admin --email <email>`.\",\n DT004:\n \"DEVTOOLS_ADMIN_PASSWORD does not meet the password rules (at least 8 characters, at most 72 bytes, not a common password, not the email). Choose another one.\",\n DT005:\n \"Devtools production mode stores its accounts in the database. Install @warlock.js/cascade and configure a database connection.\",\n DT006:\n \"Devtools production mode encrypts two-factor secrets with the app key. Set encryption.key (64 hex characters) in src/config/encryption.ts.\",\n DT007:\n \"A devtools production option has an invalid value. The message names the option and the accepted values.\",\n DT008:\n \"The devtools tables are missing. Add devtoolsMigrations from @warlock.js/devtools/production to database.migrations in warlock.config.ts and run `warlock migrate`.\",\n DT009: \"Set either DEVTOOLS_ADMIN_PASSWORD or DEVTOOLS_SETUP_TOKEN, not both.\",\n DT010:\n \"DEVTOOLS_SETUP_TOKEN must be at least 32 characters. Generate one with: openssl rand -base64 32\",\n} as const;\n\n/** A production configuration error code (`DT001`–`DT010`). */\nexport type DevtoolsConfigCode = keyof typeof DEVTOOLS_CONFIG_CODES;\n\n/**\n * Thrown while the devtools connector boots in production when the monitor is\n * enabled but cannot start safely. It stops the app from booting, so a\n * misconfigured deploy fails at once instead of serving an unprotected\n * dashboard.\n */\nexport class DevtoolsProductionConfigError extends Error {\n public readonly code: DevtoolsConfigCode;\n\n public constructor(code: DevtoolsConfigCode, detail?: string) {\n super(`[${code}] ${detail ? `${detail} ` : \"\"}${DEVTOOLS_CONFIG_CODES[code]}`);\n this.name = \"DevtoolsProductionConfigError\";\n this.code = code;\n }\n}\n\n/** The message every API error code answers with: what failed and what to do next. */\nexport const DEVTOOLS_ERROR_MESSAGES: Record<DevtoolsErrorCode, string> = {\n \"auth.invalid-credentials\":\n \"The email or password is not correct. Check both and try again; after several failed tries, wait 15 minutes.\",\n \"auth.invalid-code\":\n \"The code is not correct or has expired. Enter the current 6-digit code from your authenticator app, or a recovery code.\",\n \"auth.invalid-setup-token\":\n \"This setup link is not valid. Use the link built from DEVTOOLS_SETUP_TOKEN, or run `warlock devtools:reset-admin`.\",\n \"auth.password-too-short\": \"Use a password of at least 8 characters.\",\n \"auth.password-too-long\": \"Use a password of at most 72 bytes (about 72 letters).\",\n \"auth.password-common\": \"This password is too common. Choose one that is harder to guess.\",\n \"auth.password-same-as-email\": \"The password must not be your email address. Choose another one.\",\n \"auth.password-unchanged\": \"Choose a new password that differs from the current one.\",\n \"auth.wrong-current-password\": \"The current password is not correct. Enter it again.\",\n \"auth.busy\": \"The server is busy checking other sign-ins. Wait a few seconds and try again.\",\n \"invite.invalid\":\n \"This invite link is not valid, was already used, or has expired. Ask an admin for a new one.\",\n \"invite.email-taken\": \"An account with this email already exists. Sign in instead.\",\n \"account.not-found\": \"This account no longer exists. Reload the list.\",\n \"account.last-admin\": \"This is the last admin. Make another account an admin first.\",\n \"account.self\": \"You cannot do this to your own account. Ask another admin.\",\n \"account.last-factor\":\n \"This is your only second factor. Add another one (an authenticator app or a passkey) before removing it.\",\n \"role.forbidden\": \"Only admins can do this. Ask an admin.\",\n \"csrf.invalid\": \"This page is out of date. Reload the dashboard and try again.\",\n \"passkey.unavailable\":\n \"Passkeys are not available on this server (the @simplewebauthn/server package is not installed). Use an authenticator app instead.\",\n \"passkey.failed\": \"The passkey could not be verified. Try again, or use your authenticator app.\",\n \"explain.not-allowed\": \"Only admins can run EXPLAIN. Ask an admin.\",\n \"explain.unsupported\":\n \"This query cannot be explained: only PostgreSQL SELECT/WITH queries and MongoDB find, aggregate and count commands can.\",\n \"explain.elsewhere\":\n \"Only the instance that ran this query can explain it, and this request reached another one. Try again later or from that instance.\",\n \"explain.failed\":\n \"The database could not explain this query. The reference is in the server log.\",\n \"request.not-found\":\n \"This request is no longer stored. Requests are kept for a limited time (24 hours by default).\",\n \"request.invalid-filter\": \"A filter value is not valid. Check the status, method and dates.\",\n \"stream.too-many\":\n \"Too many live views are open for this session. Close another dashboard tab and reload.\",\n \"input.invalid\": \"Some fields are missing or not valid. Check the form and try again.\",\n \"server.error\":\n \"The dashboard could not complete this action. Try again; if it keeps failing, give your admin the reference shown.\",\n};\n\n/** The HTTP status each code answers with. */\nexport const DEVTOOLS_ERROR_STATUS: Record<DevtoolsErrorCode, number> = {\n \"auth.invalid-credentials\": 401,\n \"auth.invalid-code\": 401,\n \"auth.invalid-setup-token\": 401,\n \"auth.password-too-short\": 422,\n \"auth.password-too-long\": 422,\n \"auth.password-common\": 422,\n \"auth.password-same-as-email\": 422,\n \"auth.password-unchanged\": 422,\n \"auth.wrong-current-password\": 401,\n \"auth.busy\": 503,\n \"invite.invalid\": 410,\n \"invite.email-taken\": 409,\n \"account.not-found\": 404,\n \"account.last-admin\": 409,\n \"account.self\": 409,\n \"account.last-factor\": 409,\n \"role.forbidden\": 403,\n \"csrf.invalid\": 403,\n \"passkey.unavailable\": 501,\n \"passkey.failed\": 401,\n \"explain.not-allowed\": 403,\n \"explain.unsupported\": 400,\n \"explain.elsewhere\": 409,\n \"explain.failed\": 502,\n \"request.not-found\": 404,\n \"request.invalid-filter\": 400,\n \"stream.too-many\": 429,\n \"input.invalid\": 422,\n \"server.error\": 500,\n};\n\n/** A short reference id (8 characters, base32 alphabet) to quote to support. */\nexport function createErrorRef(): string {\n const alphabet = \"ABCDEFGHJKMNPQRSTUVWXYZ23456789\";\n const bytes = randomBytes(8);\n let ref = \"\";\n\n for (const byte of bytes) ref += alphabet[byte % alphabet.length];\n\n return ref;\n}\n\n/**\n * An error a dashboard route answers with. The production error handler turns\n * it into `{ error, code, ref?, instance? }` with `statusCode`.\n */\nexport class DevtoolsApiError extends Error {\n public readonly code: DevtoolsErrorCode;\n public readonly statusCode: number;\n public readonly ref: string | undefined;\n public readonly instance: string | undefined;\n\n public constructor(\n code: DevtoolsErrorCode,\n options: { ref?: string; instance?: string; cause?: unknown } = {},\n ) {\n super(\n DEVTOOLS_ERROR_MESSAGES[code],\n options.cause === undefined ? {} : { cause: options.cause },\n );\n this.name = \"DevtoolsApiError\";\n this.code = code;\n this.statusCode = DEVTOOLS_ERROR_STATUS[code];\n this.ref = options.ref;\n this.instance = options.instance;\n }\n\n /** The JSON body this error answers with. */\n public toBody(): DevtoolsApiErrorBody {\n return {\n error: this.message,\n code: this.code,\n ...(this.ref === undefined ? {} : { ref: this.ref }),\n ...(this.instance === undefined ? {} : { instance: this.instance }),\n };\n }\n}\n\n/**\n * Raised by a store when a unique value is taken (an email) so callers can\n * answer with their own error code.\n */\nexport class DevtoolsStoreConflictError extends Error {\n public constructor(public readonly field: string) {\n super(`A devtools record with this ${field} already exists.`);\n this.name = \"DevtoolsStoreConflictError\";\n }\n}\n"],"mappings":";;;;;;;AAOA,MAAa,wBAAwB;CACnC,OACE;CACF,OACE;CACF,OACE;CACF,OACE;CACF,OACE;CACF,OACE;CACF,OACE;CACF,OACE;CACF,OAAO;CACP,OACE;AACJ;;;;;;;AAWA,IAAa,gCAAb,cAAmD,MAAM;CAGvD,AAAO,YAAY,MAA0B,Q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,MACE,wBAAwB,OACxB,QAAQ,UAAU,SAAY,CAAC,IAAI,EAAE,OAAO,QAAQ,MAAM,CAC5D;EACA,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,aAAa,sBAAsB;EACxC,KAAK,MAAM,QAAQ;EACnB,KAAK,WAAW,QAAQ;CAC1B;;CAGA,AAAO,SAA+B;EACpC,OAAO;GACL,OAAO,KAAK;GACZ,MAAM,KAAK;GACX,GAAI,KAAK,QAAQ,SAAY,CAAC,IAAI,EAAE,KAAK,KAAK,IAAI;GAClD,GAAI,KAAK,aAAa,SAAY,CAAC,IAAI,EAAE,UAAU,KAAK,SAAS;EACnE;CACF;AACF;;;;;AAMA,IAAa,6BAAb,cAAgD,MAAM;CACpD,AAAO,YAAY,AAAgB,OAAe;EAChD,MAAM,+BAA+B,MAAM,iBAAiB;EAD3B;EAEjC,KAAK,OAAO;CACd;AACF"}
1
+ {"version":3,"file":"errors-DEqdWaqm.cjs","names":["randomBytes"],"sources":["../../../../../../../packages/devtools/src/production/errors.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport type { DevtoolsApiErrorBody, DevtoolsErrorCode } from \"./contracts\";\n\n/**\n * Why production mode refused to start. Each code names one missing or\n * invalid setting; the message says which and how to fix it.\n */\nexport const DEVTOOLS_CONFIG_CODES = {\n DT001:\n \"Devtools production mode needs a dashboard path. Set DEVTOOLS_PATH (for example /ops-7f3k2q) or devtools.production.path.\",\n DT002:\n 'The devtools dashboard path must start with \"/\", be at least 8 characters, use only letters, digits, \"-\", \"_\", \".\", \"~\" and \"/\", and not be \"/__warlock\".',\n DT003:\n \"Devtools production mode has no admin yet. Set DEVTOOLS_ADMIN_EMAIL with DEVTOOLS_ADMIN_PASSWORD or DEVTOOLS_SETUP_TOKEN, or run `warlock devtools:reset-admin --email <email>`.\",\n DT004:\n \"DEVTOOLS_ADMIN_PASSWORD does not meet the password rules (at least 8 characters, at most 72 bytes, not a common password, not the email). Choose another one.\",\n DT005:\n \"Devtools production mode stores its accounts in the database. Install @warlock.js/cascade and configure a database connection.\",\n DT006:\n \"Devtools production mode encrypts two-factor secrets with the app key. Set encryption.key (64 hex characters) in src/config/encryption.ts.\",\n DT007:\n \"A devtools production option has an invalid value. The message names the option and the accepted values.\",\n DT008:\n \"The devtools tables are missing. Add devtoolsMigrations from @warlock.js/devtools/production to database.migrations in warlock.config.ts and run `warlock migrate`.\",\n DT009: \"Set either DEVTOOLS_ADMIN_PASSWORD or DEVTOOLS_SETUP_TOKEN, not both.\",\n DT010:\n \"DEVTOOLS_SETUP_TOKEN must be at least 32 characters. Generate one with: openssl rand -base64 32\",\n} as const;\n\n/** A production configuration error code (`DT001`–`DT010`). */\nexport type DevtoolsConfigCode = keyof typeof DEVTOOLS_CONFIG_CODES;\n\n/**\n * Thrown while the devtools connector boots in production when the monitor is\n * enabled but cannot start safely. It stops the app from booting, so a\n * misconfigured deploy fails at once instead of serving an unprotected\n * dashboard.\n */\nexport class DevtoolsProductionConfigError extends Error {\n public readonly code: DevtoolsConfigCode;\n\n public constructor(code: DevtoolsConfigCode, detail?: string) {\n super(`[${code}] ${detail ? `${detail} ` : \"\"}${DEVTOOLS_CONFIG_CODES[code]}`);\n this.name = \"DevtoolsProductionConfigError\";\n this.code = code;\n }\n}\n\n/** The message every API error code answers with: what failed and what to do next. */\nexport const DEVTOOLS_ERROR_MESSAGES: Record<DevtoolsErrorCode, string> = {\n \"auth.invalid-credentials\":\n \"The email or password is not correct. Check both and try again; after several failed tries, wait 15 minutes.\",\n \"auth.invalid-code\":\n \"The code is not correct or has expired. Enter the current 6-digit code from your authenticator app, or a recovery code.\",\n \"auth.invalid-setup-token\":\n \"This setup link is not valid. Use the link built from DEVTOOLS_SETUP_TOKEN, or run `warlock devtools:reset-admin`.\",\n \"auth.password-too-short\": \"Use a password of at least 8 characters.\",\n \"auth.password-too-long\": \"Use a password of at most 72 bytes (about 72 letters).\",\n \"auth.password-common\": \"This password is too common. Choose one that is harder to guess.\",\n \"auth.password-same-as-email\": \"The password must not be your email address. Choose another one.\",\n \"auth.password-unchanged\": \"Choose a new password that differs from the current one.\",\n \"auth.wrong-current-password\": \"The current password is not correct. Enter it again.\",\n \"auth.busy\": \"The server is busy checking other sign-ins. Wait a few seconds and try again.\",\n \"invite.invalid\":\n \"This invite link is not valid, was already used, or has expired. Ask an admin for a new one.\",\n \"invite.email-taken\": \"An account with this email already exists. Sign in instead.\",\n \"account.not-found\": \"This account no longer exists. Reload the list.\",\n \"account.last-admin\": \"This is the last admin. Make another account an admin first.\",\n \"account.self\": \"You cannot do this to your own account. Ask another admin.\",\n \"account.last-factor\":\n \"This is your only second factor. Add another one (an authenticator app or a passkey) before removing it.\",\n \"role.forbidden\": \"Only admins can do this. Ask an admin.\",\n \"csrf.invalid\": \"This page is out of date. Reload the dashboard and try again.\",\n \"passkey.unavailable\":\n \"Passkeys are not available on this server (the @simplewebauthn/server package is not installed). Use an authenticator app instead.\",\n \"passkey.failed\": \"The passkey could not be verified. Try again, or use your authenticator app.\",\n \"explain.not-allowed\": \"Only admins can run EXPLAIN. Ask an admin.\",\n \"explain.unsupported\":\n \"This query cannot be explained: only PostgreSQL SELECT/WITH queries and MongoDB find, aggregate and count commands can.\",\n \"explain.elsewhere\":\n \"Only the instance that ran this query can explain it, and this request reached another one. Try again later or from that instance.\",\n \"explain.failed\":\n \"The database could not explain this query. The reference is in the server log.\",\n \"request.not-found\":\n \"This request is no longer stored. Requests are kept for a limited time (24 hours by default).\",\n \"request.invalid-filter\": \"A filter value is not valid. Check the status, method and dates.\",\n \"share.not-found\": \"This share link no longer exists or is already revoked. Reload the list.\",\n \"stream.too-many\":\n \"Too many live views are open for this session. Close another dashboard tab and reload.\",\n \"input.invalid\": \"Some fields are missing or not valid. Check the form and try again.\",\n \"server.error\":\n \"The dashboard could not complete this action. Try again; if it keeps failing, give your admin the reference shown.\",\n};\n\n/** The HTTP status each code answers with. */\nexport const DEVTOOLS_ERROR_STATUS: Record<DevtoolsErrorCode, number> = {\n \"auth.invalid-credentials\": 401,\n \"auth.invalid-code\": 401,\n \"auth.invalid-setup-token\": 401,\n \"auth.password-too-short\": 422,\n \"auth.password-too-long\": 422,\n \"auth.password-common\": 422,\n \"auth.password-same-as-email\": 422,\n \"auth.password-unchanged\": 422,\n \"auth.wrong-current-password\": 401,\n \"auth.busy\": 503,\n \"invite.invalid\": 410,\n \"invite.email-taken\": 409,\n \"account.not-found\": 404,\n \"account.last-admin\": 409,\n \"account.self\": 409,\n \"account.last-factor\": 409,\n \"role.forbidden\": 403,\n \"csrf.invalid\": 403,\n \"passkey.unavailable\": 501,\n \"passkey.failed\": 401,\n \"explain.not-allowed\": 403,\n \"explain.unsupported\": 400,\n \"explain.elsewhere\": 409,\n \"explain.failed\": 502,\n \"request.not-found\": 404,\n \"request.invalid-filter\": 400,\n \"share.not-found\": 404,\n \"stream.too-many\": 429,\n \"input.invalid\": 422,\n \"server.error\": 500,\n};\n\n/** A short reference id (8 characters, base32 alphabet) to quote to support. */\nexport function createErrorRef(): string {\n const alphabet = \"ABCDEFGHJKMNPQRSTUVWXYZ23456789\";\n const bytes = randomBytes(8);\n let ref = \"\";\n\n for (const byte of bytes) ref += alphabet[byte % alphabet.length];\n\n return ref;\n}\n\n/**\n * An error a dashboard route answers with. The production error handler turns\n * it into `{ error, code, ref?, instance? }` with `statusCode`.\n */\nexport class DevtoolsApiError extends Error {\n public readonly code: DevtoolsErrorCode;\n public readonly statusCode: number;\n public readonly ref: string | undefined;\n public readonly instance: string | undefined;\n\n public constructor(\n code: DevtoolsErrorCode,\n options: { ref?: string; instance?: string; cause?: unknown } = {},\n ) {\n super(\n DEVTOOLS_ERROR_MESSAGES[code],\n options.cause === undefined ? {} : { cause: options.cause },\n );\n this.name = \"DevtoolsApiError\";\n this.code = code;\n this.statusCode = DEVTOOLS_ERROR_STATUS[code];\n this.ref = options.ref;\n this.instance = options.instance;\n }\n\n /** The JSON body this error answers with. */\n public toBody(): DevtoolsApiErrorBody {\n return {\n error: this.message,\n code: this.code,\n ...(this.ref === undefined ? {} : { ref: this.ref }),\n ...(this.instance === undefined ? {} : { instance: this.instance }),\n };\n }\n}\n\n/**\n * Raised by a store when a unique value is taken (an email) so callers can\n * answer with their own error code.\n */\nexport class DevtoolsStoreConflictError extends Error {\n public constructor(public readonly field: string) {\n super(`A devtools record with this ${field} already exists.`);\n this.name = \"DevtoolsStoreConflictError\";\n }\n}\n"],"mappings":";;;;;;;AAOA,MAAa,wBAAwB;CACnC,OACE;CACF,OACE;CACF,OACE;CACF,OACE;CACF,OACE;CACF,OACE;CACF,OACE;CACF,OACE;CACF,OAAO;CACP,OACE;AACJ;;;;;;;AAWA,IAAa,gCAAb,cAAmD,MAAM;CAGvD,AAAO,YAAY,MAA0B,QAAiB;EAC5D,MAAM,IAAI,KAAK,IAAI,SAAS,GAAG,OAAO,KAAK,KAAK,sBAAsB,OAAO;EAC7E,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;;AAGA,MAAa,0BAA6D;CACxE,4BACE;CACF,qBACE;CACF,4BACE;CACF,2BAA2B;CAC3B,0BAA0B;CAC1B,wBAAwB;CACxB,+BAA+B;CAC/B,2BAA2B;CAC3B,+BAA+B;CAC/B,aAAa;CACb,kBACE;CACF,sBAAsB;CACtB,qBAAqB;CACrB,sBAAsB;CACtB,gBAAgB;CAChB,uBACE;CACF,kBAAkB;CAClB,gBAAgB;CAChB,uBACE;CACF,kBAAkB;CAClB,uBAAuB;CACvB,uBACE;CACF,qBACE;CACF,kBACE;CACF,qBACE;CACF,0BAA0B;CAC1B,mBAAmB;CACnB,mBACE;CACF,iBAAiB;CACjB,gBACE;AACJ;;AAGA,MAAa,wBAA2D;CACtE,4BAA4B;CAC5B,qBAAqB;CACrB,4BAA4B;CAC5B,2BAA2B;CAC3B,0BAA0B;CAC1B,wBAAwB;CACxB,+BAA+B;CAC/B,2BAA2B;CAC3B,+BAA+B;CAC/B,aAAa;CACb,kBAAkB;CAClB,sBAAsB;CACtB,qBAAqB;CACrB,sBA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