@warlock.js/devtools 5.55.0 → 5.56.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 (234) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +26 -13
  3. package/cjs/ai-source-DTpxumMA.cjs +381 -0
  4. package/cjs/ai-source-DTpxumMA.cjs.map +1 -0
  5. package/cjs/auth-DzU0gHDG.cjs +1655 -0
  6. package/cjs/auth-DzU0gHDG.cjs.map +1 -0
  7. package/cjs/boot-BQi0Etor.cjs +138 -0
  8. package/cjs/boot-BQi0Etor.cjs.map +1 -0
  9. package/cjs/capture-CqIiaznN.cjs +1342 -0
  10. package/cjs/capture-CqIiaznN.cjs.map +1 -0
  11. package/cjs/cascade-store-pHjKeSFm.cjs +863 -0
  12. package/cjs/cascade-store-pHjKeSFm.cjs.map +1 -0
  13. package/cjs/collector-CJbQbzzK.cjs +271 -0
  14. package/cjs/collector-CJbQbzzK.cjs.map +1 -0
  15. package/cjs/contracts-CVmplkNb.cjs +112 -0
  16. package/cjs/contracts-CVmplkNb.cjs.map +1 -0
  17. package/cjs/current-request-id-BoJJb3y7.cjs +37 -0
  18. package/cjs/current-request-id-BoJJb3y7.cjs.map +1 -0
  19. package/cjs/errors-CyZp5yS-.cjs +177 -0
  20. package/cjs/errors-CyZp5yS-.cjs.map +1 -0
  21. package/cjs/histogram-BaI-PnCv.cjs +102 -0
  22. package/cjs/histogram-BaI-PnCv.cjs.map +1 -0
  23. package/cjs/http-CabcUwBx.cjs +870 -0
  24. package/cjs/http-CabcUwBx.cjs.map +1 -0
  25. package/cjs/index.cjs +1 -1
  26. package/cjs/insights-BKtqxdnP.cjs +811 -0
  27. package/cjs/insights-BKtqxdnP.cjs.map +1 -0
  28. package/cjs/ip-DbNhPOzi.cjs +153 -0
  29. package/cjs/ip-DbNhPOzi.cjs.map +1 -0
  30. package/cjs/migrations-w7GMsrQw.cjs +297 -0
  31. package/cjs/migrations-w7GMsrQw.cjs.map +1 -0
  32. package/cjs/openapi-CC7OAUc6.cjs +52 -0
  33. package/cjs/openapi-CC7OAUc6.cjs.map +1 -0
  34. package/cjs/options-CWqFC5__.cjs +181 -0
  35. package/cjs/options-CWqFC5__.cjs.map +1 -0
  36. package/cjs/panels-B0dAfGbJ.cjs +298 -0
  37. package/cjs/panels-B0dAfGbJ.cjs.map +1 -0
  38. package/cjs/process-panel-DEOnLxoT.cjs +48 -0
  39. package/cjs/process-panel-DEOnLxoT.cjs.map +1 -0
  40. package/cjs/production/index.cjs +238 -0
  41. package/cjs/production/index.cjs.map +1 -0
  42. package/cjs/rolldown-runtime-Zuuoy_Rh.cjs +52 -0
  43. package/cjs/server-B6xdeKS8.cjs +184 -0
  44. package/cjs/server-B6xdeKS8.cjs.map +1 -0
  45. package/cjs/{src-Xwm3Eel9.cjs → src-Ce-3Lniv.cjs} +163 -295
  46. package/cjs/src-Ce-3Lniv.cjs.map +1 -0
  47. package/cjs/store-aq207T8v.cjs +9 -0
  48. package/cjs/stream-route-BGJa-zQu.cjs +875 -0
  49. package/cjs/stream-route-BGJa-zQu.cjs.map +1 -0
  50. package/esm/devtools-connector.d.mts +16 -13
  51. package/esm/devtools-connector.d.mts.map +1 -1
  52. package/esm/devtools-connector.mjs +127 -18
  53. package/esm/devtools-connector.mjs.map +1 -1
  54. package/esm/index.d.mts +3 -2
  55. package/esm/options.mjs +2 -1
  56. package/esm/options.mjs.map +1 -1
  57. package/esm/panels.mjs +50 -5
  58. package/esm/panels.mjs.map +1 -1
  59. package/esm/production/auth/common-passwords.mjs +303 -0
  60. package/esm/production/auth/common-passwords.mjs.map +1 -0
  61. package/esm/production/auth/default-crypto.mjs +19 -0
  62. package/esm/production/auth/default-crypto.mjs.map +1 -0
  63. package/esm/production/auth/helpers.mjs +77 -0
  64. package/esm/production/auth/helpers.mjs.map +1 -0
  65. package/esm/production/auth/index.mjs +6 -0
  66. package/esm/production/auth/passkeys.mjs +96 -0
  67. package/esm/production/auth/passkeys.mjs.map +1 -0
  68. package/esm/production/auth/service.mjs +1166 -0
  69. package/esm/production/auth/service.mjs.map +1 -0
  70. package/esm/production/boot.mjs +138 -0
  71. package/esm/production/boot.mjs.map +1 -0
  72. package/esm/production/capture/dev-stats.mjs +83 -0
  73. package/esm/production/capture/dev-stats.mjs.map +1 -0
  74. package/esm/production/capture/engine.mjs +442 -0
  75. package/esm/production/capture/engine.mjs.map +1 -0
  76. package/esm/production/capture/explain.mjs +271 -0
  77. package/esm/production/capture/explain.mjs.map +1 -0
  78. package/esm/production/capture/filter.mjs +24 -0
  79. package/esm/production/capture/filter.mjs.map +1 -0
  80. package/esm/production/capture/index.mjs +7 -0
  81. package/esm/production/capture/production-capture.mjs +134 -0
  82. package/esm/production/capture/production-capture.mjs.map +1 -0
  83. package/esm/production/capture/redact.mjs +109 -0
  84. package/esm/production/capture/redact.mjs.map +1 -0
  85. package/esm/production/capture/stats-stores.mjs +300 -0
  86. package/esm/production/capture/stats-stores.mjs.map +1 -0
  87. package/esm/production/cli/actions.mjs +151 -0
  88. package/esm/production/cli/actions.mjs.map +1 -0
  89. package/esm/production/cli/index.d.mts +17 -0
  90. package/esm/production/cli/index.d.mts.map +1 -0
  91. package/esm/production/cli/index.mjs +86 -0
  92. package/esm/production/cli/index.mjs.map +1 -0
  93. package/esm/production/contracts.d.mts +592 -0
  94. package/esm/production/contracts.d.mts.map +1 -0
  95. package/esm/production/contracts.mjs +95 -0
  96. package/esm/production/contracts.mjs.map +1 -0
  97. package/esm/production/errors.d.mts +31 -0
  98. package/esm/production/errors.d.mts.map +1 -0
  99. package/esm/production/errors.mjs +142 -0
  100. package/esm/production/errors.mjs.map +1 -0
  101. package/esm/production/http/access.mjs +124 -0
  102. package/esm/production/http/access.mjs.map +1 -0
  103. package/esm/production/http/auth-routes.mjs +280 -0
  104. package/esm/production/http/auth-routes.mjs.map +1 -0
  105. package/esm/production/http/client.mjs +57 -0
  106. package/esm/production/http/client.mjs.map +1 -0
  107. package/esm/production/http/constants.mjs +11 -0
  108. package/esm/production/http/constants.mjs.map +1 -0
  109. package/esm/production/http/context.mjs +14 -0
  110. package/esm/production/http/context.mjs.map +1 -0
  111. package/esm/production/http/cookie.mjs +39 -0
  112. package/esm/production/http/cookie.mjs.map +1 -0
  113. package/esm/production/http/headers.mjs +25 -0
  114. package/esm/production/http/headers.mjs.map +1 -0
  115. package/esm/production/http/index.mjs +10 -0
  116. package/esm/production/http/ip.mjs +130 -0
  117. package/esm/production/http/ip.mjs.map +1 -0
  118. package/esm/production/http/mount.mjs +300 -0
  119. package/esm/production/http/mount.mjs.map +1 -0
  120. package/esm/production/http/state.mjs +54 -0
  121. package/esm/production/http/state.mjs.map +1 -0
  122. package/esm/production/index.d.mts +6 -0
  123. package/esm/production/index.mjs +5 -0
  124. package/esm/production/insights/cap-report.mjs +67 -0
  125. package/esm/production/insights/cap-report.mjs.map +1 -0
  126. package/esm/production/insights/health.mjs +88 -0
  127. package/esm/production/insights/health.mjs.map +1 -0
  128. package/esm/production/insights/index.mjs +10 -0
  129. package/esm/production/insights/insights.mjs +167 -0
  130. package/esm/production/insights/insights.mjs.map +1 -0
  131. package/esm/production/insights/instance.mjs +24 -0
  132. package/esm/production/insights/instance.mjs.map +1 -0
  133. package/esm/production/insights/jobs.mjs +100 -0
  134. package/esm/production/insights/jobs.mjs.map +1 -0
  135. package/esm/production/insights/reporter.mjs +59 -0
  136. package/esm/production/insights/reporter.mjs.map +1 -0
  137. package/esm/production/insights/resources.mjs +139 -0
  138. package/esm/production/insights/resources.mjs.map +1 -0
  139. package/esm/production/insights/writer.mjs +72 -0
  140. package/esm/production/insights/writer.mjs.map +1 -0
  141. package/esm/production/openapi.mjs +52 -0
  142. package/esm/production/openapi.mjs.map +1 -0
  143. package/esm/production/options.d.mts +60 -0
  144. package/esm/production/options.d.mts.map +1 -0
  145. package/esm/production/options.mjs +170 -0
  146. package/esm/production/options.mjs.map +1 -0
  147. package/esm/production/stats/histogram.mjs +67 -0
  148. package/esm/production/stats/histogram.mjs.map +1 -0
  149. package/esm/production/stats/merge.mjs +106 -0
  150. package/esm/production/stats/merge.mjs.map +1 -0
  151. package/esm/production/store/cascade-store.mjs +322 -0
  152. package/esm/production/store/cascade-store.mjs.map +1 -0
  153. package/esm/production/store/index.mjs +5 -0
  154. package/esm/production/store/mapping.mjs +258 -0
  155. package/esm/production/store/mapping.mjs.map +1 -0
  156. package/esm/production/store/memory-store.mjs +291 -0
  157. package/esm/production/store/memory-store.mjs.map +1 -0
  158. package/esm/production/store/migrations.d.mts +11 -0
  159. package/esm/production/store/migrations.d.mts.map +1 -0
  160. package/esm/production/store/migrations.mjs +29 -0
  161. package/esm/production/store/migrations.mjs.map +1 -0
  162. package/esm/production/store/models/account.migration.mjs +34 -0
  163. package/esm/production/store/models/account.migration.mjs.map +1 -0
  164. package/esm/production/store/models/account.model.mjs +13 -0
  165. package/esm/production/store/models/account.model.mjs.map +1 -0
  166. package/esm/production/store/models/audit.migration.mjs +30 -0
  167. package/esm/production/store/models/audit.migration.mjs.map +1 -0
  168. package/esm/production/store/models/audit.model.mjs +13 -0
  169. package/esm/production/store/models/audit.model.mjs.map +1 -0
  170. package/esm/production/store/models/base.mjs +27 -0
  171. package/esm/production/store/models/base.mjs.map +1 -0
  172. package/esm/production/store/models/index.mjs +17 -0
  173. package/esm/production/store/models/invite.migration.mjs +26 -0
  174. package/esm/production/store/models/invite.migration.mjs.map +1 -0
  175. package/esm/production/store/models/invite.model.mjs +13 -0
  176. package/esm/production/store/models/invite.model.mjs.map +1 -0
  177. package/esm/production/store/models/report.migration.mjs +20 -0
  178. package/esm/production/store/models/report.migration.mjs.map +1 -0
  179. package/esm/production/store/models/report.model.mjs +13 -0
  180. package/esm/production/store/models/report.model.mjs.map +1 -0
  181. package/esm/production/store/models/sample.migration.mjs +25 -0
  182. package/esm/production/store/models/sample.migration.mjs.map +1 -0
  183. package/esm/production/store/models/sample.model.mjs +13 -0
  184. package/esm/production/store/models/sample.model.mjs.map +1 -0
  185. package/esm/production/store/models/session.migration.mjs +31 -0
  186. package/esm/production/store/models/session.migration.mjs.map +1 -0
  187. package/esm/production/store/models/session.model.mjs +13 -0
  188. package/esm/production/store/models/session.model.mjs.map +1 -0
  189. package/esm/production/store/models/state.migration.mjs +26 -0
  190. package/esm/production/store/models/state.migration.mjs.map +1 -0
  191. package/esm/production/store/models/state.model.mjs +13 -0
  192. package/esm/production/store/models/state.model.mjs.map +1 -0
  193. package/esm/query-shape.mjs +14 -1
  194. package/esm/query-shape.mjs.map +1 -1
  195. package/esm/server/explain-route.mjs +26 -1
  196. package/esm/server/explain-route.mjs.map +1 -1
  197. package/esm/server/index.mjs +9 -4
  198. package/esm/server/index.mjs.map +1 -1
  199. package/esm/server/insights-routes.mjs +62 -0
  200. package/esm/server/insights-routes.mjs.map +1 -0
  201. package/esm/server/log-routes.mjs +32 -5
  202. package/esm/server/log-routes.mjs.map +1 -1
  203. package/esm/server/openapi-routes.mjs +3 -2
  204. package/esm/server/openapi-routes.mjs.map +1 -1
  205. package/esm/server/requests-routes.mjs +125 -0
  206. package/esm/server/requests-routes.mjs.map +1 -1
  207. package/esm/server/session-routes.mjs +42 -0
  208. package/esm/server/session-routes.mjs.map +1 -0
  209. package/esm/server/stream-route.mjs +81 -11
  210. package/esm/server/stream-route.mjs.map +1 -1
  211. package/esm/server/ui-assets.mjs +34 -25
  212. package/esm/server/ui-assets.mjs.map +1 -1
  213. package/esm/sources/log-source.mjs +14 -1
  214. package/esm/sources/log-source.mjs.map +1 -1
  215. package/esm/types.d.mts +202 -1
  216. package/esm/types.d.mts.map +1 -1
  217. package/esm/ui-root.mjs +9 -4
  218. package/esm/ui-root.mjs.map +1 -1
  219. package/llms-full.txt +159 -21
  220. package/llms.txt +2 -2
  221. package/package.json +32 -8
  222. package/skills/SKILL.md +159 -21
  223. package/ui/dashboard/assets/app.css +3 -0
  224. package/ui/dashboard/assets/app.js +50 -0
  225. package/ui/dashboard/build-info.json +21 -0
  226. package/ui/dashboard/index.html +15 -0
  227. package/cjs/ai-source-Dz_3tlZ5.cjs +0 -703
  228. package/cjs/ai-source-Dz_3tlZ5.cjs.map +0 -1
  229. package/cjs/server-B11ShQYE.cjs +0 -628
  230. package/cjs/server-B11ShQYE.cjs.map +0 -1
  231. package/cjs/src-Xwm3Eel9.cjs.map +0 -1
  232. package/ui/app.css +0 -376
  233. package/ui/app.js +0 -1158
  234. package/ui/index.html +0 -28
@@ -0,0 +1,1166 @@
1
+ import { DEVTOOLS_FAILURE_AUDIT_TYPES } from "../contracts.mjs";
2
+ import { DevtoolsApiError, DevtoolsProductionConfigError, DevtoolsStoreConflictError, createErrorRef } from "../errors.mjs";
3
+ import { rateLimitClient } from "../http/ip.mjs";
4
+ import { checkPasswordPolicy, generateRecoveryCode, generateToken, hashRecoveryCode, hashToken, isPlausibleEmail, normalizeEmail, normalizeRecoveryCode, safeEqual } from "./helpers.mjs";
5
+ import { randomBytes } from "node:crypto";
6
+
7
+ //#region ../../packages/devtools/src/production/auth/service.ts
8
+ const MINUTE = 6e4;
9
+ const HOUR = 60 * MINUTE;
10
+ /** Password verifications (and hashes) a process runs at the same time. */
11
+ const MAX_IN_FLIGHT = 4;
12
+ /** `lastSeenAt` is written at most this often. */
13
+ const TOUCH_INTERVAL = MINUTE;
14
+ const INVITE_TTL = 24 * HOUR;
15
+ const CHALLENGE_TTL = 5 * MINUTE;
16
+ const TOTP_ISSUER = "Warlock monitor";
17
+ const RECOVERY_CODE_COUNT = 10;
18
+ /** A password longer than this is cut before hashing, so input size is no CPU lever. */
19
+ const MAX_PASSWORD_INPUT = 1024;
20
+ /** How long this process remembers that an IP was over its limit. */
21
+ const IP_BLOCK_CACHE_MS = 3e4;
22
+ const IP_BLOCK_CACHE_SIZE = 1e3;
23
+ /** A refused try is written to the audit log at most this often per address and account. */
24
+ const BLOCKED_AUDIT_INTERVAL = MINUTE;
25
+ const BLOCKED_AUDIT_CACHE_SIZE = 1e3;
26
+ /** Marks the session as having passed a passkey check a moment ago (sensitive actions). */
27
+ const STEP_UP_CHALLENGE = "stepup:ok";
28
+ /** A stored hash no password can match. */
29
+ const NO_PASSWORD_HASH = "!no-password-set";
30
+ const hasFactor = (account) => account.totpSecret !== null || account.passkeys.length > 0;
31
+ function fail(code, ref) {
32
+ throw new DevtoolsApiError(code, ref === void 0 ? {} : { ref });
33
+ }
34
+ function cut(value, length) {
35
+ return typeof value === "string" ? value.slice(0, length) : null;
36
+ }
37
+ /** The accounts, sessions and two-factor service of the production monitor. */
38
+ function createDevtoolsAuth(deps) {
39
+ const { store, options, crypto, passkeys, instance } = deps;
40
+ const now = deps.now ?? Date.now;
41
+ const limits = options.rateLimits;
42
+ const windowMs = limits.windowMinutes * MINUTE;
43
+ let inFlight = 0;
44
+ let dummyHashPromise = null;
45
+ const blockedIps = /* @__PURE__ */ new Map();
46
+ const blockedAudits = /* @__PURE__ */ new Map();
47
+ /** Runs password work (hashing or verifying) while fewer than four are in flight. */
48
+ async function withSlot(run) {
49
+ if (inFlight >= MAX_IN_FLIGHT) fail("auth.busy");
50
+ inFlight++;
51
+ try {
52
+ return await run();
53
+ } finally {
54
+ inFlight--;
55
+ }
56
+ }
57
+ function dummyHash() {
58
+ dummyHashPromise ??= crypto.hashPassword(`devtools-timing-${randomBytes(12).toString("hex")}`);
59
+ return dummyHashPromise;
60
+ }
61
+ async function verifyPassword(password, hash) {
62
+ try {
63
+ return await crypto.verifyPassword(password, hash) === true;
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+ const hashPassword = (password) => withSlot(() => crypto.hashPassword(password));
69
+ const passwordInput = (value) => typeof value === "string" ? value.slice(0, MAX_PASSWORD_INPUT) : "";
70
+ function requirePolicy(password, email) {
71
+ const problem = checkPasswordPolicy(password, email);
72
+ if (problem !== null) fail(problem);
73
+ }
74
+ const csrfToken = (session) => Buffer.from(crypto.hmac(`devtools-csrf:${session.id}:${session.csrfSecret}`)).toString("base64url");
75
+ function accountView(account) {
76
+ return {
77
+ id: account.id,
78
+ email: account.email,
79
+ role: account.role,
80
+ twoFactor: {
81
+ totp: account.totpSecret !== null,
82
+ passkeys: account.passkeys.map((passkey) => ({
83
+ id: passkey.id,
84
+ name: passkey.name,
85
+ createdAt: passkey.createdAt,
86
+ lastUsedAt: passkey.lastUsedAt
87
+ })),
88
+ recoveryCodesLeft: account.recoveryCodes.length
89
+ },
90
+ mustChangePassword: account.mustChangePassword,
91
+ createdAt: account.createdAt,
92
+ lastLoginAt: account.lastLoginAt
93
+ };
94
+ }
95
+ function inviteView(invite) {
96
+ return {
97
+ id: invite.id,
98
+ email: invite.email,
99
+ role: invite.role,
100
+ createdAt: invite.createdAt,
101
+ expiresAt: invite.expiresAt,
102
+ createdBy: invite.createdBy,
103
+ usedAt: invite.usedAt
104
+ };
105
+ }
106
+ const twoFactorRequired = (account) => options.twoFactor === "everyone" || account.role === "admin";
107
+ /** Where an account goes after its password is accepted. */
108
+ function nextStage(account) {
109
+ if (account.mustChangePassword) return "password-change";
110
+ if (hasFactor(account)) return "mfa-verify";
111
+ if (twoFactorRequired(account)) return "mfa-enrol";
112
+ return "active";
113
+ }
114
+ function rpIdFor(meta) {
115
+ if (options.passkeys.rpId) return options.passkeys.rpId;
116
+ if (options.origin) try {
117
+ return new URL(options.origin).hostname;
118
+ } catch {}
119
+ return meta.hostname;
120
+ }
121
+ async function audit(type, input = {}) {
122
+ const ref = createErrorRef();
123
+ try {
124
+ const email = input.email ?? input.auth?.account.email ?? null;
125
+ await store.audit.append({
126
+ at: now(),
127
+ type,
128
+ accountId: input.accountId ?? input.auth?.account.id ?? null,
129
+ email: email === null ? null : email.trim().toLowerCase().slice(0, 254),
130
+ ip: input.meta?.ip ?? null,
131
+ userAgent: cut(input.meta?.userAgent, 200),
132
+ detail: input.detail ?? {},
133
+ ref
134
+ });
135
+ } catch (error) {
136
+ try {
137
+ deps.warn?.(`devtools audit write failed (${type}, ref ${ref}): ${error instanceof Error ? error.message : "unknown error"}`);
138
+ } catch {}
139
+ }
140
+ return ref;
141
+ }
142
+ /**
143
+ * Writes a `login.blocked` entry, at most once a minute per address and
144
+ * account: refused tries cost no password check against the limits, so
145
+ * without this a caller over its limit could grow the audit log without
146
+ * bound. A skipped write answers the reference of the last one.
147
+ */
148
+ async function auditBlocked(input) {
149
+ const key = `${rateLimitClient(input.meta.ip)}|${input.accountId ?? input.auth?.account.id ?? ""}`;
150
+ const at = now();
151
+ const last = blockedAudits.get(key);
152
+ if (last && at - last.at < BLOCKED_AUDIT_INTERVAL) return last.ref;
153
+ blockedAudits.delete(key);
154
+ if (blockedAudits.size >= BLOCKED_AUDIT_CACHE_SIZE) {
155
+ const oldest = blockedAudits.keys().next();
156
+ if (!oldest.done) blockedAudits.delete(oldest.value);
157
+ }
158
+ const ref = await audit("login.blocked", input);
159
+ blockedAudits.set(key, {
160
+ at,
161
+ ref
162
+ });
163
+ return ref;
164
+ }
165
+ /**
166
+ * Applies the patch `build` makes from the latest record. When another write
167
+ * wins, the record is read again and `build` runs again, so a rule it checks
168
+ * (a replayed TOTP step, a recovery code already used) is checked against
169
+ * the newest data. `build` returns `null` to refuse.
170
+ */
171
+ async function casAccount(account, build) {
172
+ let current = account;
173
+ for (let attempt = 0; attempt < 4 && current; attempt++) {
174
+ const patch = build(current);
175
+ if (patch === null) return null;
176
+ const updated = await store.accounts.update(current.id, current.version, patch);
177
+ if (updated) return updated;
178
+ current = await store.accounts.findById(current.id);
179
+ }
180
+ return null;
181
+ }
182
+ async function casSession(session, build) {
183
+ let current = session;
184
+ for (let attempt = 0; attempt < 4 && current; attempt++) {
185
+ const patch = build(current);
186
+ if (patch === null) return null;
187
+ const updated = await store.sessions.update(current.id, current.version, patch);
188
+ if (updated) return updated;
189
+ current = await store.sessions.findByTokenHash(current.tokenHash);
190
+ }
191
+ return null;
192
+ }
193
+ /** Whether the client of `ip` (the address, or its /64 for IPv6) is over the per-IP limit. */
194
+ async function ipOverLimit(ip, since, stateResetAt) {
195
+ const client = rateLimitClient(ip);
196
+ const cached = blockedIps.get(client);
197
+ if (cached && now() < cached.until && cached.checkedAt >= stateResetAt) return true;
198
+ if (await store.audit.count({
199
+ types: DEVTOOLS_FAILURE_AUDIT_TYPES,
200
+ since,
201
+ ip
202
+ }) < limits.ip) {
203
+ blockedIps.delete(client);
204
+ return false;
205
+ }
206
+ if (blockedIps.size >= IP_BLOCK_CACHE_SIZE) {
207
+ const oldest = blockedIps.keys().next();
208
+ if (!oldest.done) blockedIps.delete(oldest.value);
209
+ }
210
+ blockedIps.set(client, {
211
+ until: now() + IP_BLOCK_CACHE_MS,
212
+ checkedAt: now()
213
+ });
214
+ return true;
215
+ }
216
+ /** Whether a try from `ip` for `account` is refused: dashboard locked, or the IP or the account is over its limit. */
217
+ async function isBlocked(account, ip) {
218
+ return await blockedBy(account, ip) !== null;
219
+ }
220
+ /**
221
+ * Why a try is refused: `"caller"` when the dashboard is locked or the IP is
222
+ * over its limit (nothing about the account), `"account"` when only the
223
+ * account is, `null` when it is not refused.
224
+ */
225
+ async function blockedBy(account, ip) {
226
+ const state = await store.state.read();
227
+ const at = now();
228
+ const stateResetAt = state.failuresResetAt ?? 0;
229
+ const since = Math.max(at - windowMs, stateResetAt);
230
+ const accountSince = Math.max(since, account?.failuresResetAt ?? 0);
231
+ const locked = state.lockedUntil !== null && state.lockedUntil > at;
232
+ const overIp = await ipOverLimit(ip, since, stateResetAt);
233
+ const accountCount = await store.audit.count({
234
+ types: DEVTOOLS_FAILURE_AUDIT_TYPES,
235
+ since: accountSince,
236
+ accountId: account?.id ?? "-"
237
+ });
238
+ if (locked || overIp) return "caller";
239
+ return account !== null && accountCount >= limits.account ? "account" : null;
240
+ }
241
+ /** Closes the whole dashboard for `lockMinutes` once failures anywhere reach the global limit. */
242
+ async function lockWhenOverGlobalLimit(meta) {
243
+ for (let attempt = 0; attempt < 3; attempt++) {
244
+ const state = await store.state.read();
245
+ const at = now();
246
+ if (state.lockedUntil !== null && state.lockedUntil > at) return;
247
+ const since = Math.max(at - windowMs, state.failuresResetAt ?? 0);
248
+ const count = await store.audit.count({
249
+ types: DEVTOOLS_FAILURE_AUDIT_TYPES,
250
+ since
251
+ });
252
+ if (count < limits.global) return;
253
+ if (await store.state.update(state.version, { lockedUntil: at + limits.lockMinutes * MINUTE })) {
254
+ await audit("dashboard.locked", {
255
+ meta,
256
+ detail: {
257
+ minutes: limits.lockMinutes,
258
+ failures: count
259
+ }
260
+ });
261
+ return;
262
+ }
263
+ }
264
+ }
265
+ async function failLogin(type, code, input) {
266
+ const ref = type === "login.blocked" ? await auditBlocked(input) : await audit(type, input);
267
+ if (type === "login.failed") await lockWhenOverGlobalLimit(input.meta);
268
+ return fail(code, ref);
269
+ }
270
+ /** Records a failed second factor (it counts toward the limits) and refuses. */
271
+ async function failSecondFactor(auth, meta, method, code = "auth.invalid-code") {
272
+ const ref = await audit("mfa.failed", {
273
+ auth,
274
+ meta,
275
+ detail: { method }
276
+ });
277
+ await lockWhenOverGlobalLimit(meta);
278
+ return fail(code, ref);
279
+ }
280
+ /** Refuses a second-factor try while the IP, the account or the dashboard is over its limit. */
281
+ async function guardSecondFactor(auth, meta, code = "auth.invalid-code") {
282
+ if (await isBlocked(auth.account, meta.ip)) fail(code, await auditBlocked({
283
+ auth,
284
+ meta,
285
+ detail: { step: "second-factor" }
286
+ }));
287
+ }
288
+ async function createSession(account, stage, meta) {
289
+ const token = generateToken();
290
+ const at = now();
291
+ const lifetime = stage === "active" ? options.session.maxHours * HOUR : options.session.pendingMinutes * MINUTE;
292
+ const session = await store.sessions.create({
293
+ tokenHash: hashToken(token),
294
+ accountId: account.id,
295
+ stage,
296
+ csrfSecret: randomBytes(32).toString("base64url"),
297
+ createdAt: at,
298
+ lastSeenAt: at,
299
+ expiresAt: at + lifetime,
300
+ ip: meta.ip,
301
+ userAgent: cut(meta.userAgent, 200),
302
+ pendingTotpSecret: null,
303
+ challenge: null,
304
+ challengeExpiresAt: null
305
+ });
306
+ return {
307
+ stage,
308
+ token,
309
+ csrf: csrfToken(session),
310
+ session
311
+ };
312
+ }
313
+ /**
314
+ * Moves a session to `stage`. Reaching `active` mints a new token (the old
315
+ * session is removed); any other stage changes the session in place.
316
+ */
317
+ async function moveTo(auth, account, stage, meta) {
318
+ if (stage === "active") {
319
+ const step = await createSession(await casAccount(account, () => ({ failuresResetAt: now() })) ?? account, "active", meta);
320
+ await store.sessions.remove(auth.session.id);
321
+ return step;
322
+ }
323
+ const session = await casSession(auth.session, () => ({
324
+ stage,
325
+ pendingTotpSecret: null,
326
+ challenge: null,
327
+ challengeExpiresAt: null,
328
+ expiresAt: now() + options.session.pendingMinutes * MINUTE
329
+ }));
330
+ if (!session) fail("server.error");
331
+ return {
332
+ stage,
333
+ token: null,
334
+ csrf: csrfToken(session),
335
+ session
336
+ };
337
+ }
338
+ function requireStage(auth, ...stages) {
339
+ if (!stages.includes(auth.stage)) fail("input.invalid");
340
+ }
341
+ function requireAdmin(auth) {
342
+ if (auth.stage !== "active" || auth.account.role !== "admin") fail("role.forbidden");
343
+ }
344
+ function newRecoveryCodes() {
345
+ const codes = Array.from({ length: RECOVERY_CODE_COUNT }, () => generateRecoveryCode());
346
+ return {
347
+ codes,
348
+ hashes: codes.map(hashRecoveryCode)
349
+ };
350
+ }
351
+ /** The step a TOTP code matches for this account, or `null` (also `null` when the step was already used). */
352
+ function totpStepFor(account, code) {
353
+ if (account.totpSecret === null) return null;
354
+ let secret;
355
+ try {
356
+ secret = crypto.decrypt(account.totpSecret);
357
+ } catch {
358
+ return null;
359
+ }
360
+ return crypto.verifyTotp(secret, String(code ?? ""), now());
361
+ }
362
+ /** Records `step` as used; refuses when the same or a later step was already accepted. */
363
+ async function consumeTotpStep(account, step) {
364
+ return casAccount(account, (fresh) => fresh.totpLastStep !== null && step <= fresh.totpLastStep ? null : { totpLastStep: step });
365
+ }
366
+ async function ensureFirstAdmin() {
367
+ const admin = options.admin;
368
+ const email = normalizeEmail(admin.email);
369
+ const existing = email ? await store.accounts.findByEmail(email) : null;
370
+ if (existing && existing.role === "admin") {
371
+ if (existing.passwordSource === "env" && admin.password !== null) {
372
+ if (!await withSlot(() => verifyPassword(admin.password, existing.passwordHash))) {
373
+ if (checkPasswordPolicy(admin.password, email) !== null) throw new DevtoolsProductionConfigError("DT004");
374
+ const hash = await hashPassword(admin.password);
375
+ const updated = await casAccount(existing, (fresh) => fresh.passwordSource === "env" ? {
376
+ passwordHash: hash,
377
+ mustChangePassword: true
378
+ } : null);
379
+ if (updated) {
380
+ await store.sessions.removeForAccount(updated.id);
381
+ await audit("admin.reset", {
382
+ accountId: updated.id,
383
+ email,
384
+ detail: { source: "env" }
385
+ });
386
+ }
387
+ }
388
+ }
389
+ return;
390
+ }
391
+ if (await store.accounts.countAdmins() > 0) return;
392
+ if (existing || !email || admin.password === null && admin.setupToken === null) throw new DevtoolsProductionConfigError("DT003");
393
+ let record;
394
+ if (admin.password !== null) {
395
+ if (checkPasswordPolicy(admin.password, email) !== null) throw new DevtoolsProductionConfigError("DT004");
396
+ record = {
397
+ email,
398
+ role: "admin",
399
+ passwordHash: await hashPassword(admin.password),
400
+ passwordSource: "env",
401
+ mustChangePassword: true,
402
+ totpSecret: null,
403
+ totpEnabledAt: null,
404
+ totpLastStep: null,
405
+ recoveryCodes: [],
406
+ passkeys: [],
407
+ failuresResetAt: null,
408
+ lastLoginAt: null,
409
+ createdBy: null
410
+ };
411
+ } else record = {
412
+ email,
413
+ role: "admin",
414
+ passwordHash: NO_PASSWORD_HASH,
415
+ passwordSource: "setup",
416
+ mustChangePassword: false,
417
+ totpSecret: null,
418
+ totpEnabledAt: null,
419
+ totpLastStep: null,
420
+ recoveryCodes: [],
421
+ passkeys: [],
422
+ failuresResetAt: null,
423
+ lastLoginAt: null,
424
+ createdBy: null
425
+ };
426
+ try {
427
+ await audit("admin.seeded", {
428
+ accountId: (await store.accounts.create(record)).id,
429
+ email,
430
+ detail: { source: record.passwordSource }
431
+ });
432
+ } catch (error) {
433
+ if (!(error instanceof DevtoolsStoreConflictError)) throw error;
434
+ }
435
+ }
436
+ async function login(input, meta) {
437
+ const email = normalizeEmail(input?.email);
438
+ const password = passwordInput(input?.password);
439
+ const account = email ? await store.accounts.findByEmail(email) : null;
440
+ const blockedReason = await blockedBy(account, meta.ip);
441
+ const blocked = blockedReason !== null;
442
+ const verifiable = !blocked && account !== null && !account.passwordHash.startsWith("!") && password !== "";
443
+ const hash = verifiable && account ? account.passwordHash : await dummyHash();
444
+ const matches = blockedReason === "caller" ? false : await withSlot(() => verifyPassword(password, hash));
445
+ if (blocked) return failLogin("login.blocked", "auth.invalid-credentials", {
446
+ email: email || null,
447
+ accountId: account?.id ?? null,
448
+ meta
449
+ });
450
+ if (!verifiable || !matches || account === null) return failLogin("login.failed", "auth.invalid-credentials", {
451
+ email: email || null,
452
+ accountId: account?.id ?? null,
453
+ meta
454
+ });
455
+ const at = now();
456
+ const updated = await casAccount(account, (fresh) => nextStage(fresh) === "active" ? {
457
+ failuresResetAt: at,
458
+ lastLoginAt: at
459
+ } : { lastLoginAt: at });
460
+ if (!updated) return failLogin("login.failed", "auth.invalid-credentials", {
461
+ email,
462
+ meta
463
+ });
464
+ await audit("login.succeeded", {
465
+ accountId: updated.id,
466
+ email,
467
+ meta
468
+ });
469
+ return createSession(updated, nextStage(updated), meta);
470
+ }
471
+ async function setup(input, meta) {
472
+ const configured = options.admin.setupToken;
473
+ const adminEmail = normalizeEmail(options.admin.email);
474
+ const account = adminEmail ? await store.accounts.findByEmail(adminEmail) : null;
475
+ const blocked = await isBlocked(null, meta.ip);
476
+ const tokenMatches = safeEqual(hashToken(typeof input?.token === "string" ? input.token : ""), hashToken(configured ?? ""));
477
+ const usable = configured !== null && tokenMatches && account !== null && account.passwordSource === "setup";
478
+ if (blocked) return failLogin("login.blocked", "auth.invalid-setup-token", {
479
+ email: adminEmail || null,
480
+ meta,
481
+ detail: { via: "setup" }
482
+ });
483
+ if (!usable || account === null) return failLogin("login.failed", "auth.invalid-setup-token", {
484
+ email: adminEmail || null,
485
+ meta,
486
+ detail: { via: "setup" }
487
+ });
488
+ const password = passwordInput(input.password);
489
+ requirePolicy(password, account.email);
490
+ const passwordHash = await hashPassword(password);
491
+ const at = now();
492
+ const updated = await casAccount(account, (fresh) => fresh.passwordSource === "setup" ? {
493
+ passwordHash,
494
+ passwordSource: "user",
495
+ mustChangePassword: false,
496
+ failuresResetAt: at,
497
+ lastLoginAt: at
498
+ } : null);
499
+ if (!updated) fail("auth.invalid-setup-token");
500
+ await audit("setup.completed", {
501
+ accountId: updated.id,
502
+ email: updated.email,
503
+ meta
504
+ });
505
+ return createSession(updated, nextStage(updated), meta);
506
+ }
507
+ async function findOpenInvite(token) {
508
+ if (typeof token !== "string" || token === "" || token.length > 200) fail("invite.invalid");
509
+ const invite = await store.invites.findByTokenHash(hashToken(token));
510
+ if (!invite || invite.usedAt !== null || invite.expiresAt <= now()) fail("invite.invalid");
511
+ return invite;
512
+ }
513
+ async function inspectInvite(token) {
514
+ const invite = await findOpenInvite(token);
515
+ return {
516
+ email: invite.email,
517
+ role: invite.role
518
+ };
519
+ }
520
+ async function acceptInvite(input, meta) {
521
+ const invite = await findOpenInvite(input?.token);
522
+ const password = passwordInput(input.password);
523
+ requirePolicy(password, invite.email);
524
+ const passwordHash = await hashPassword(password);
525
+ if (!await store.invites.markUsed(invite.id, now(), "pending")) fail("invite.invalid");
526
+ let account;
527
+ try {
528
+ account = await store.accounts.create({
529
+ email: invite.email,
530
+ role: invite.role,
531
+ passwordHash,
532
+ passwordSource: "invite",
533
+ mustChangePassword: false,
534
+ totpSecret: null,
535
+ totpEnabledAt: null,
536
+ totpLastStep: null,
537
+ recoveryCodes: [],
538
+ passkeys: [],
539
+ failuresResetAt: null,
540
+ lastLoginAt: now(),
541
+ createdBy: invite.createdBy
542
+ });
543
+ } catch (error) {
544
+ if (error instanceof DevtoolsStoreConflictError) fail("invite.email-taken");
545
+ throw error;
546
+ }
547
+ await audit("invite.accepted", {
548
+ accountId: account.id,
549
+ email: account.email,
550
+ meta,
551
+ detail: { role: account.role }
552
+ });
553
+ return createSession(account, nextStage(account), meta);
554
+ }
555
+ async function authenticate(token) {
556
+ if (typeof token !== "string" || token === "" || token.length > 200) return null;
557
+ const session = await store.sessions.findByTokenHash(hashToken(token));
558
+ if (!session) return null;
559
+ const at = now();
560
+ if (at >= session.expiresAt || at - session.lastSeenAt > options.session.idleMinutes * MINUTE) {
561
+ await store.sessions.remove(session.id);
562
+ return null;
563
+ }
564
+ const account = await store.accounts.findById(session.accountId);
565
+ if (!account) {
566
+ await store.sessions.remove(session.id);
567
+ return null;
568
+ }
569
+ let current = session;
570
+ if (at - session.lastSeenAt >= TOUCH_INTERVAL) {
571
+ const touched = await store.sessions.update(session.id, session.version, { lastSeenAt: at });
572
+ if (touched) current = touched;
573
+ }
574
+ return {
575
+ session: current,
576
+ account,
577
+ stage: current.stage
578
+ };
579
+ }
580
+ function verifyCsrf(auth, header) {
581
+ if (typeof header !== "string" || header === "") return false;
582
+ return safeEqual(header, csrfToken(auth.session));
583
+ }
584
+ function sessionView(auth) {
585
+ if (!auth) return {
586
+ mode: "production",
587
+ stage: "signed-out",
588
+ account: null,
589
+ role: null,
590
+ csrf: null,
591
+ expiresAt: null,
592
+ instance: null,
593
+ methods: null
594
+ };
595
+ return {
596
+ mode: "production",
597
+ stage: auth.stage,
598
+ account: accountView(auth.account),
599
+ role: auth.account.role,
600
+ csrf: csrfToken(auth.session),
601
+ expiresAt: auth.session.expiresAt,
602
+ instance,
603
+ methods: {
604
+ totp: true,
605
+ passkeys: passkeys !== null
606
+ }
607
+ };
608
+ }
609
+ async function logout(auth, meta) {
610
+ await store.sessions.remove(auth.session.id);
611
+ await audit("logout", {
612
+ auth,
613
+ meta
614
+ });
615
+ }
616
+ async function listSessions(auth) {
617
+ const at = now();
618
+ return (await store.sessions.listForAccount(auth.account.id)).filter((session) => session.expiresAt > at).map((session) => ({
619
+ id: session.id,
620
+ current: session.id === auth.session.id,
621
+ createdAt: session.createdAt,
622
+ lastSeenAt: session.lastSeenAt,
623
+ expiresAt: session.expiresAt,
624
+ ip: session.ip,
625
+ userAgent: session.userAgent
626
+ }));
627
+ }
628
+ async function revokeSession(auth, sessionId, meta) {
629
+ const own = (await store.sessions.listForAccount(auth.account.id)).find((session) => session.id === sessionId);
630
+ if (!own) fail("account.not-found");
631
+ await store.sessions.remove(own.id);
632
+ await audit("session.revoked", {
633
+ auth,
634
+ meta,
635
+ detail: { current: own.id === auth.session.id }
636
+ });
637
+ }
638
+ /**
639
+ * Checks the current password of an active session. A wrong one counts
640
+ * toward the sign-in limits like a failed sign-in.
641
+ */
642
+ async function requireCurrentPassword(auth, given, meta) {
643
+ const current = passwordInput(given);
644
+ const stored = auth.account.passwordHash;
645
+ const verifiable = !stored.startsWith("!") && current !== "";
646
+ if (await isBlocked(auth.account, meta.ip)) {
647
+ await verifyPassword(current, await dummyHash());
648
+ fail("auth.wrong-current-password", await auditBlocked({
649
+ auth,
650
+ meta,
651
+ detail: { step: "password" }
652
+ }));
653
+ }
654
+ const matches = await withSlot(async () => verifyPassword(current, verifiable ? stored : await dummyHash()));
655
+ if (!verifiable || !matches) {
656
+ const ref = await audit("login.failed", {
657
+ auth,
658
+ meta,
659
+ detail: { step: "password" }
660
+ });
661
+ await lockWhenOverGlobalLimit(meta);
662
+ fail("auth.wrong-current-password", ref);
663
+ }
664
+ }
665
+ /**
666
+ * Spends the session's step-up (a passkey check passed in this session in
667
+ * the last five minutes). Compare-and-set, so two requests racing on one
668
+ * step-up cannot both use it. Returns whether it was there to spend.
669
+ */
670
+ async function consumeStepUp(session) {
671
+ return await casSession(session, (fresh) => fresh.challenge === STEP_UP_CHALLENGE && fresh.challengeExpiresAt !== null && fresh.challengeExpiresAt > now() ? {
672
+ challenge: null,
673
+ challengeExpiresAt: null
674
+ } : null) !== null;
675
+ }
676
+ /**
677
+ * Before an active session adds or removes a second factor: the current
678
+ * password, or, when none is given, a fresh step-up, so a stolen session
679
+ * cookie alone cannot change how the account signs in. Not asked while
680
+ * enrolling the first factor at sign-in, which follows the password.
681
+ */
682
+ async function requireOwner(auth, current, meta) {
683
+ if (auth.stage !== "active") return;
684
+ if ((current === void 0 || current === "") && await consumeStepUp(auth.session)) return;
685
+ await requireCurrentPassword(auth, current, meta);
686
+ }
687
+ async function changePassword(auth, input, meta) {
688
+ requireStage(auth, "password-change", "active");
689
+ const password = passwordInput(input?.password);
690
+ if (auth.stage === "active") await requireCurrentPassword(auth, input?.current, meta);
691
+ requirePolicy(password, auth.account.email);
692
+ if (await withSlot(() => verifyPassword(password, auth.account.passwordHash))) fail("auth.password-unchanged");
693
+ const passwordHash = await hashPassword(password);
694
+ const updated = await casAccount(auth.account, () => ({
695
+ passwordHash,
696
+ passwordSource: "user",
697
+ mustChangePassword: false
698
+ }));
699
+ if (!updated) fail("server.error");
700
+ await audit("password.changed", {
701
+ auth,
702
+ meta
703
+ });
704
+ await store.sessions.removeForAccount(updated.id, auth.session.id);
705
+ if (auth.stage === "active") return {
706
+ stage: "active",
707
+ token: null,
708
+ csrf: csrfToken(auth.session),
709
+ session: auth.session
710
+ };
711
+ return moveTo(auth, updated, nextStage(updated), meta);
712
+ }
713
+ async function startTotp(auth, _meta) {
714
+ requireStage(auth, "mfa-enrol", "active");
715
+ if (auth.account.totpSecret !== null) fail("input.invalid");
716
+ const secret = crypto.generateTotpSecret();
717
+ if (!await casSession(auth.session, () => ({ pendingTotpSecret: crypto.encrypt(secret) }))) fail("server.error");
718
+ return {
719
+ secret,
720
+ uri: crypto.totpUri({
721
+ secret,
722
+ account: auth.account.email,
723
+ issuer: TOTP_ISSUER
724
+ }),
725
+ issuer: TOTP_ISSUER,
726
+ account: auth.account.email
727
+ };
728
+ }
729
+ async function confirmTotp(auth, code, meta, current) {
730
+ requireStage(auth, "mfa-enrol", "active");
731
+ const pending = auth.session.pendingTotpSecret;
732
+ if (pending === null) fail("input.invalid");
733
+ await requireOwner(auth, current, meta);
734
+ await guardSecondFactor(auth, meta);
735
+ let secret;
736
+ try {
737
+ secret = crypto.decrypt(pending);
738
+ } catch {
739
+ return failSecondFactor(auth, meta, "totp");
740
+ }
741
+ const step = crypto.verifyTotp(secret, String(code ?? ""), now());
742
+ if (step === null) return failSecondFactor(auth, meta, "totp");
743
+ const fresh = newRecoveryCodes();
744
+ let issued = null;
745
+ const updated = await casAccount(auth.account, (account) => {
746
+ if (account.totpSecret !== null) return null;
747
+ issued = account.recoveryCodes.length === 0 ? fresh.codes : null;
748
+ return {
749
+ totpSecret: pending,
750
+ totpEnabledAt: now(),
751
+ totpLastStep: step,
752
+ ...issued ? { recoveryCodes: fresh.hashes } : {}
753
+ };
754
+ });
755
+ if (!updated) fail("input.invalid");
756
+ await audit("mfa.enrolled", {
757
+ auth,
758
+ meta,
759
+ detail: { method: "totp" }
760
+ });
761
+ if (auth.stage === "mfa-enrol") return {
762
+ step: await moveTo(auth, updated, "active", meta),
763
+ recoveryCodes: issued
764
+ };
765
+ const session = await casSession(auth.session, () => ({ pendingTotpSecret: null }));
766
+ return {
767
+ step: {
768
+ stage: "active",
769
+ token: null,
770
+ csrf: csrfToken(auth.session),
771
+ session: session ?? auth.session
772
+ },
773
+ recoveryCodes: issued
774
+ };
775
+ }
776
+ async function removeTotp(auth, meta, current) {
777
+ requireStage(auth, "active");
778
+ if (auth.account.totpSecret === null) return;
779
+ if (twoFactorRequired(auth.account) && auth.account.passkeys.length === 0) fail("account.last-factor");
780
+ await requireOwner(auth, current, meta);
781
+ if (!await casAccount(auth.account, (account) => ({
782
+ totpSecret: null,
783
+ totpEnabledAt: null,
784
+ totpLastStep: null,
785
+ ...account.passkeys.length === 0 ? { recoveryCodes: [] } : {}
786
+ }))) fail("server.error");
787
+ await audit("mfa.removed", {
788
+ auth,
789
+ meta,
790
+ detail: { method: "totp" }
791
+ });
792
+ }
793
+ async function verifySecondFactor(auth, input, meta) {
794
+ requireStage(auth, "mfa-verify");
795
+ const hasCode = typeof input?.code === "string" && input.code !== "";
796
+ const hasRecovery = typeof input?.recoveryCode === "string" && input.recoveryCode !== "";
797
+ if (!hasCode && !hasRecovery) fail("input.invalid");
798
+ await guardSecondFactor(auth, meta);
799
+ if (hasCode) {
800
+ const step = totpStepFor(auth.account, input.code);
801
+ const consumed = step === null ? null : await consumeTotpStep(auth.account, step);
802
+ if (!consumed) return failSecondFactor(auth, meta, "totp");
803
+ await audit("mfa.succeeded", {
804
+ auth,
805
+ meta,
806
+ detail: { method: "totp" }
807
+ });
808
+ return moveTo(auth, consumed, "active", meta);
809
+ }
810
+ const given = hashRecoveryCode(input.recoveryCode);
811
+ let left = 0;
812
+ const used = await casAccount(auth.account, (account) => {
813
+ let found = -1;
814
+ account.recoveryCodes.forEach((stored, index) => {
815
+ if (safeEqual(stored, given) && normalizeRecoveryCode(input.recoveryCode).length === 10) found = index;
816
+ });
817
+ if (found === -1) return null;
818
+ const remaining = account.recoveryCodes.filter((_, index) => index !== found);
819
+ left = remaining.length;
820
+ return { recoveryCodes: remaining };
821
+ });
822
+ if (!used) return failSecondFactor(auth, meta, "recovery-code");
823
+ await audit("recovery-code.used", {
824
+ auth,
825
+ meta,
826
+ detail: { left }
827
+ });
828
+ return moveTo(auth, used, "active", meta);
829
+ }
830
+ async function regenerateRecoveryCodes(auth, code, meta) {
831
+ requireStage(auth, "active");
832
+ await guardSecondFactor(auth, meta);
833
+ let account = auth.account;
834
+ if (typeof code === "string" && code !== "" && account.totpSecret !== null) {
835
+ const step = totpStepFor(account, code);
836
+ const consumed = step === null ? null : await consumeTotpStep(account, step);
837
+ if (!consumed) return failSecondFactor(auth, meta, "totp");
838
+ account = consumed;
839
+ } else if (!await consumeStepUp(auth.session)) return failSecondFactor(auth, meta, "totp");
840
+ const fresh = newRecoveryCodes();
841
+ if (!await casAccount(account, () => ({ recoveryCodes: fresh.hashes }))) fail("server.error");
842
+ await audit("recovery-codes.regenerated", {
843
+ auth,
844
+ meta
845
+ });
846
+ return fresh.codes;
847
+ }
848
+ function requirePasskeys() {
849
+ if (passkeys === null) fail("passkey.unavailable");
850
+ return passkeys;
851
+ }
852
+ async function passkeyOptions(auth, purpose, meta) {
853
+ const adapter = requirePasskeys();
854
+ if (purpose === "register") requireStage(auth, "mfa-enrol", "active");
855
+ else requireStage(auth, "mfa-verify", "active");
856
+ const rpId = rpIdFor(meta);
857
+ let result;
858
+ if (purpose === "register") result = await adapter.registrationOptions({
859
+ account: auth.account,
860
+ rpId,
861
+ rpName: options.passkeys.rpName
862
+ });
863
+ else {
864
+ if (auth.account.passkeys.length === 0) fail("passkey.failed");
865
+ await guardSecondFactor(auth, meta, "passkey.failed");
866
+ result = await adapter.authenticationOptions({
867
+ account: auth.account,
868
+ rpId
869
+ });
870
+ }
871
+ if (!await casSession(auth.session, () => ({
872
+ challenge: result.challenge,
873
+ challengeExpiresAt: now() + CHALLENGE_TTL
874
+ }))) fail("server.error");
875
+ return result.options;
876
+ }
877
+ async function verifyPasskey(auth, purpose, response, meta, current) {
878
+ const adapter = requirePasskeys();
879
+ if (purpose === "register") requireStage(auth, "mfa-enrol", "active");
880
+ else requireStage(auth, "mfa-verify", "active");
881
+ if (purpose === "login") await guardSecondFactor(auth, meta, "passkey.failed");
882
+ else if (auth.stage === "active") await requireCurrentPassword(auth, current, meta);
883
+ const challenge = auth.session.challenge;
884
+ const live = challenge !== null && challenge !== STEP_UP_CHALLENGE && auth.session.challengeExpiresAt !== null && auth.session.challengeExpiresAt > now();
885
+ const consumed = live ? await casSession(auth.session, (fresh) => fresh.challenge === challenge ? {
886
+ challenge: null,
887
+ challengeExpiresAt: null
888
+ } : null) : null;
889
+ if (!live || !consumed || challenge === null) return purpose === "login" ? failSecondFactor(auth, meta, "passkey", "passkey.failed") : fail("passkey.failed");
890
+ const rpId = rpIdFor(meta);
891
+ if (purpose === "register") {
892
+ let credential;
893
+ try {
894
+ credential = await adapter.verifyRegistration({
895
+ response,
896
+ challenge,
897
+ origin: meta.origin,
898
+ rpId
899
+ });
900
+ } catch {
901
+ return fail("passkey.failed");
902
+ }
903
+ if (auth.account.passkeys.some((passkey) => passkey.id === credential.id)) fail("passkey.failed");
904
+ const fresh = newRecoveryCodes();
905
+ let issued = null;
906
+ const label = `Passkey added ${new Date(now()).toISOString().slice(0, 10)}`;
907
+ const updated = await casAccount(auth.account, (account) => {
908
+ if (account.passkeys.some((passkey) => passkey.id === credential.id)) return null;
909
+ issued = account.recoveryCodes.length === 0 ? fresh.codes : null;
910
+ return {
911
+ passkeys: [...account.passkeys, {
912
+ id: credential.id,
913
+ publicKey: credential.publicKey,
914
+ counter: credential.counter,
915
+ transports: credential.transports,
916
+ name: label,
917
+ createdAt: now(),
918
+ lastUsedAt: null
919
+ }],
920
+ ...issued ? { recoveryCodes: fresh.hashes } : {}
921
+ };
922
+ });
923
+ if (!updated) fail("passkey.failed");
924
+ await audit("passkey.added", {
925
+ auth,
926
+ meta
927
+ });
928
+ if (auth.stage === "mfa-enrol") return {
929
+ step: await moveTo(auth, updated, "active", meta),
930
+ recoveryCodes: issued
931
+ };
932
+ return {
933
+ step: null,
934
+ recoveryCodes: issued
935
+ };
936
+ }
937
+ let verified;
938
+ try {
939
+ verified = await adapter.verifyAuthentication({
940
+ response,
941
+ challenge,
942
+ origin: meta.origin,
943
+ rpId,
944
+ account: auth.account
945
+ });
946
+ } catch {
947
+ return failSecondFactor(auth, meta, "passkey", "passkey.failed");
948
+ }
949
+ const updated = await casAccount(auth.account, (account) => {
950
+ if (!account.passkeys.some((passkey) => passkey.id === verified.id)) return null;
951
+ return { passkeys: account.passkeys.map((passkey) => passkey.id === verified.id ? {
952
+ ...passkey,
953
+ counter: verified.newCounter,
954
+ lastUsedAt: now()
955
+ } : passkey) };
956
+ });
957
+ if (!updated) return failSecondFactor(auth, meta, "passkey", "passkey.failed");
958
+ await audit("mfa.succeeded", {
959
+ auth,
960
+ meta,
961
+ detail: { method: "passkey" }
962
+ });
963
+ if (auth.stage === "mfa-verify") return {
964
+ step: await moveTo(auth, updated, "active", meta),
965
+ recoveryCodes: null
966
+ };
967
+ await casSession(auth.session, () => ({
968
+ challenge: STEP_UP_CHALLENGE,
969
+ challengeExpiresAt: now() + CHALLENGE_TTL
970
+ }));
971
+ return {
972
+ step: null,
973
+ recoveryCodes: null
974
+ };
975
+ }
976
+ async function removePasskey(auth, passkeyId, meta, current) {
977
+ requireStage(auth, "active");
978
+ if (!auth.account.passkeys.some((passkey) => passkey.id === passkeyId)) fail("account.not-found");
979
+ if (twoFactorRequired(auth.account) && auth.account.totpSecret === null && auth.account.passkeys.length === 1) fail("account.last-factor");
980
+ await requireOwner(auth, current, meta);
981
+ if (!await casAccount(auth.account, (account) => {
982
+ const remaining = account.passkeys.filter((passkey) => passkey.id !== passkeyId);
983
+ return {
984
+ passkeys: remaining,
985
+ ...remaining.length === 0 && account.totpSecret === null ? { recoveryCodes: [] } : {}
986
+ };
987
+ })) fail("server.error");
988
+ await audit("passkey.removed", {
989
+ auth,
990
+ meta
991
+ });
992
+ }
993
+ async function listUsers(auth) {
994
+ requireAdmin(auth);
995
+ const at = now();
996
+ const [accounts, invites] = await Promise.all([store.accounts.list(), store.invites.list()]);
997
+ return {
998
+ accounts: accounts.map(accountView),
999
+ invites: invites.filter((invite) => invite.expiresAt > at).map(inviteView)
1000
+ };
1001
+ }
1002
+ async function createInvite(auth, input, meta) {
1003
+ requireAdmin(auth);
1004
+ const email = normalizeEmail(input?.email);
1005
+ if (!isPlausibleEmail(email) || input.role !== "admin" && input.role !== "viewer") fail("input.invalid");
1006
+ if (await store.accounts.findByEmail(email)) fail("invite.email-taken");
1007
+ const token = generateToken();
1008
+ const at = now();
1009
+ const invite = await store.invites.create({
1010
+ tokenHash: hashToken(token),
1011
+ email,
1012
+ role: input.role,
1013
+ createdBy: auth.account.id,
1014
+ createdAt: at,
1015
+ expiresAt: at + INVITE_TTL
1016
+ });
1017
+ await audit("invite.created", {
1018
+ auth,
1019
+ meta,
1020
+ detail: {
1021
+ invitee: email,
1022
+ role: input.role
1023
+ }
1024
+ });
1025
+ return {
1026
+ invite: inviteView(invite),
1027
+ token
1028
+ };
1029
+ }
1030
+ async function revokeInvite(auth, inviteId, meta) {
1031
+ requireAdmin(auth);
1032
+ if (!await store.invites.remove(inviteId)) fail("invite.invalid");
1033
+ await audit("invite.revoked", {
1034
+ auth,
1035
+ meta,
1036
+ detail: { invite: inviteId }
1037
+ });
1038
+ }
1039
+ async function targetAccount(accountId) {
1040
+ const target = await store.accounts.findById(accountId);
1041
+ if (!target) fail("account.not-found");
1042
+ return target;
1043
+ }
1044
+ async function setRole(auth, accountId, role, meta) {
1045
+ requireAdmin(auth);
1046
+ if (role !== "admin" && role !== "viewer") fail("input.invalid");
1047
+ const target = await targetAccount(accountId);
1048
+ if (target.id === auth.account.id) fail("account.self");
1049
+ if (target.role === role) return accountView(target);
1050
+ if (target.role === "admin" && await store.accounts.countAdmins() <= 1) fail("account.last-admin");
1051
+ const updated = await casAccount(target, () => ({ role }));
1052
+ if (!updated) fail("account.not-found");
1053
+ if (role === "admin" && options.twoFactor === "admins" && !hasFactor(updated)) await store.sessions.removeForAccount(updated.id);
1054
+ await audit("account.role-changed", {
1055
+ auth,
1056
+ meta,
1057
+ detail: {
1058
+ target: updated.email,
1059
+ from: target.role,
1060
+ to: role
1061
+ }
1062
+ });
1063
+ return accountView(updated);
1064
+ }
1065
+ async function removeAccount(auth, accountId, meta) {
1066
+ requireAdmin(auth);
1067
+ const target = await targetAccount(accountId);
1068
+ if (target.id === auth.account.id) fail("account.self");
1069
+ if (target.role === "admin" && await store.accounts.countAdmins() <= 1) fail("account.last-admin");
1070
+ await store.sessions.removeForAccount(target.id);
1071
+ await store.accounts.remove(target.id);
1072
+ await audit("account.removed", {
1073
+ auth,
1074
+ meta,
1075
+ detail: { target: target.email }
1076
+ });
1077
+ }
1078
+ async function resetSecondFactor(auth, accountId, meta) {
1079
+ requireAdmin(auth);
1080
+ const target = await targetAccount(accountId);
1081
+ if (target.id === auth.account.id) fail("account.self");
1082
+ const updated = await casAccount(target, () => ({
1083
+ totpSecret: null,
1084
+ totpEnabledAt: null,
1085
+ totpLastStep: null,
1086
+ recoveryCodes: [],
1087
+ passkeys: []
1088
+ }));
1089
+ if (!updated) fail("account.not-found");
1090
+ await store.sessions.removeForAccount(updated.id);
1091
+ await audit("account.mfa-reset", {
1092
+ auth,
1093
+ meta,
1094
+ detail: { target: updated.email }
1095
+ });
1096
+ }
1097
+ async function signOutAccount(auth, accountId, meta) {
1098
+ requireAdmin(auth);
1099
+ const target = await targetAccount(accountId);
1100
+ const removed = await store.sessions.removeForAccount(target.id, target.id === auth.account.id ? auth.session.id : void 0);
1101
+ await audit("account.signed-out", {
1102
+ auth,
1103
+ meta,
1104
+ detail: {
1105
+ target: target.email,
1106
+ sessions: removed
1107
+ }
1108
+ });
1109
+ }
1110
+ async function disableDashboard(auth, meta) {
1111
+ requireAdmin(auth);
1112
+ for (let attempt = 0; attempt < 3; attempt++) {
1113
+ const state = await store.state.read();
1114
+ if (await store.state.update(state.version, {
1115
+ disabled: true,
1116
+ disabledPathHash: hashToken(options.path),
1117
+ disabledAt: now(),
1118
+ disabledBy: auth.account.id
1119
+ })) {
1120
+ await audit("dashboard.disabled", {
1121
+ auth,
1122
+ meta
1123
+ });
1124
+ return;
1125
+ }
1126
+ }
1127
+ fail("server.error");
1128
+ }
1129
+ return {
1130
+ ensureFirstAdmin,
1131
+ login,
1132
+ setup,
1133
+ inspectInvite,
1134
+ acceptInvite,
1135
+ authenticate,
1136
+ verifyCsrf,
1137
+ changePassword,
1138
+ startTotp,
1139
+ confirmTotp,
1140
+ removeTotp,
1141
+ verifySecondFactor,
1142
+ regenerateRecoveryCodes,
1143
+ passkeyOptions,
1144
+ verifyPasskey,
1145
+ removePasskey,
1146
+ logout,
1147
+ listSessions,
1148
+ revokeSession,
1149
+ sessionView,
1150
+ csrfToken,
1151
+ accountView,
1152
+ listUsers,
1153
+ createInvite,
1154
+ revokeInvite,
1155
+ setRole,
1156
+ removeAccount,
1157
+ resetSecondFactor,
1158
+ signOutAccount,
1159
+ disableDashboard,
1160
+ audit: (type, input) => audit(type, input)
1161
+ };
1162
+ }
1163
+
1164
+ //#endregion
1165
+ export { createDevtoolsAuth };
1166
+ //# sourceMappingURL=service.mjs.map