@warlock.js/devtools 5.54.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 (239) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +26 -13
  3. package/cjs/{ai-source-CSPh1HqJ.cjs → ai-source-DTpxumMA.cjs} +54 -3
  4. package/cjs/{ai-source-CSPh1HqJ.cjs.map → ai-source-DTpxumMA.cjs.map} +1 -1
  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-BzuntLcd.cjs → src-Ce-3Lniv.cjs} +171 -308
  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 -12
  51. package/esm/devtools-connector.d.mts.map +1 -1
  52. package/esm/devtools-connector.mjs +137 -18
  53. package/esm/devtools-connector.mjs.map +1 -1
  54. package/esm/index.d.mts +3 -2
  55. package/esm/options.mjs +3 -1
  56. package/esm/options.mjs.map +1 -1
  57. package/esm/panels.mjs +267 -0
  58. package/esm/panels.mjs.map +1 -0
  59. package/esm/process-panel.mjs +20 -1
  60. package/esm/process-panel.mjs.map +1 -1
  61. package/esm/production/auth/common-passwords.mjs +303 -0
  62. package/esm/production/auth/common-passwords.mjs.map +1 -0
  63. package/esm/production/auth/default-crypto.mjs +19 -0
  64. package/esm/production/auth/default-crypto.mjs.map +1 -0
  65. package/esm/production/auth/helpers.mjs +77 -0
  66. package/esm/production/auth/helpers.mjs.map +1 -0
  67. package/esm/production/auth/index.mjs +6 -0
  68. package/esm/production/auth/passkeys.mjs +96 -0
  69. package/esm/production/auth/passkeys.mjs.map +1 -0
  70. package/esm/production/auth/service.mjs +1166 -0
  71. package/esm/production/auth/service.mjs.map +1 -0
  72. package/esm/production/boot.mjs +138 -0
  73. package/esm/production/boot.mjs.map +1 -0
  74. package/esm/production/capture/dev-stats.mjs +83 -0
  75. package/esm/production/capture/dev-stats.mjs.map +1 -0
  76. package/esm/production/capture/engine.mjs +442 -0
  77. package/esm/production/capture/engine.mjs.map +1 -0
  78. package/esm/production/capture/explain.mjs +271 -0
  79. package/esm/production/capture/explain.mjs.map +1 -0
  80. package/esm/production/capture/filter.mjs +24 -0
  81. package/esm/production/capture/filter.mjs.map +1 -0
  82. package/esm/production/capture/index.mjs +7 -0
  83. package/esm/production/capture/production-capture.mjs +134 -0
  84. package/esm/production/capture/production-capture.mjs.map +1 -0
  85. package/esm/production/capture/redact.mjs +109 -0
  86. package/esm/production/capture/redact.mjs.map +1 -0
  87. package/esm/production/capture/stats-stores.mjs +300 -0
  88. package/esm/production/capture/stats-stores.mjs.map +1 -0
  89. package/esm/production/cli/actions.mjs +151 -0
  90. package/esm/production/cli/actions.mjs.map +1 -0
  91. package/esm/production/cli/index.d.mts +17 -0
  92. package/esm/production/cli/index.d.mts.map +1 -0
  93. package/esm/production/cli/index.mjs +86 -0
  94. package/esm/production/cli/index.mjs.map +1 -0
  95. package/esm/production/contracts.d.mts +592 -0
  96. package/esm/production/contracts.d.mts.map +1 -0
  97. package/esm/production/contracts.mjs +95 -0
  98. package/esm/production/contracts.mjs.map +1 -0
  99. package/esm/production/errors.d.mts +31 -0
  100. package/esm/production/errors.d.mts.map +1 -0
  101. package/esm/production/errors.mjs +142 -0
  102. package/esm/production/errors.mjs.map +1 -0
  103. package/esm/production/http/access.mjs +124 -0
  104. package/esm/production/http/access.mjs.map +1 -0
  105. package/esm/production/http/auth-routes.mjs +280 -0
  106. package/esm/production/http/auth-routes.mjs.map +1 -0
  107. package/esm/production/http/client.mjs +57 -0
  108. package/esm/production/http/client.mjs.map +1 -0
  109. package/esm/production/http/constants.mjs +11 -0
  110. package/esm/production/http/constants.mjs.map +1 -0
  111. package/esm/production/http/context.mjs +14 -0
  112. package/esm/production/http/context.mjs.map +1 -0
  113. package/esm/production/http/cookie.mjs +39 -0
  114. package/esm/production/http/cookie.mjs.map +1 -0
  115. package/esm/production/http/headers.mjs +25 -0
  116. package/esm/production/http/headers.mjs.map +1 -0
  117. package/esm/production/http/index.mjs +10 -0
  118. package/esm/production/http/ip.mjs +130 -0
  119. package/esm/production/http/ip.mjs.map +1 -0
  120. package/esm/production/http/mount.mjs +300 -0
  121. package/esm/production/http/mount.mjs.map +1 -0
  122. package/esm/production/http/state.mjs +54 -0
  123. package/esm/production/http/state.mjs.map +1 -0
  124. package/esm/production/index.d.mts +6 -0
  125. package/esm/production/index.mjs +5 -0
  126. package/esm/production/insights/cap-report.mjs +67 -0
  127. package/esm/production/insights/cap-report.mjs.map +1 -0
  128. package/esm/production/insights/health.mjs +88 -0
  129. package/esm/production/insights/health.mjs.map +1 -0
  130. package/esm/production/insights/index.mjs +10 -0
  131. package/esm/production/insights/insights.mjs +167 -0
  132. package/esm/production/insights/insights.mjs.map +1 -0
  133. package/esm/production/insights/instance.mjs +24 -0
  134. package/esm/production/insights/instance.mjs.map +1 -0
  135. package/esm/production/insights/jobs.mjs +100 -0
  136. package/esm/production/insights/jobs.mjs.map +1 -0
  137. package/esm/production/insights/reporter.mjs +59 -0
  138. package/esm/production/insights/reporter.mjs.map +1 -0
  139. package/esm/production/insights/resources.mjs +139 -0
  140. package/esm/production/insights/resources.mjs.map +1 -0
  141. package/esm/production/insights/writer.mjs +72 -0
  142. package/esm/production/insights/writer.mjs.map +1 -0
  143. package/esm/production/openapi.mjs +52 -0
  144. package/esm/production/openapi.mjs.map +1 -0
  145. package/esm/production/options.d.mts +60 -0
  146. package/esm/production/options.d.mts.map +1 -0
  147. package/esm/production/options.mjs +170 -0
  148. package/esm/production/options.mjs.map +1 -0
  149. package/esm/production/stats/histogram.mjs +67 -0
  150. package/esm/production/stats/histogram.mjs.map +1 -0
  151. package/esm/production/stats/merge.mjs +106 -0
  152. package/esm/production/stats/merge.mjs.map +1 -0
  153. package/esm/production/store/cascade-store.mjs +322 -0
  154. package/esm/production/store/cascade-store.mjs.map +1 -0
  155. package/esm/production/store/index.mjs +5 -0
  156. package/esm/production/store/mapping.mjs +258 -0
  157. package/esm/production/store/mapping.mjs.map +1 -0
  158. package/esm/production/store/memory-store.mjs +291 -0
  159. package/esm/production/store/memory-store.mjs.map +1 -0
  160. package/esm/production/store/migrations.d.mts +11 -0
  161. package/esm/production/store/migrations.d.mts.map +1 -0
  162. package/esm/production/store/migrations.mjs +29 -0
  163. package/esm/production/store/migrations.mjs.map +1 -0
  164. package/esm/production/store/models/account.migration.mjs +34 -0
  165. package/esm/production/store/models/account.migration.mjs.map +1 -0
  166. package/esm/production/store/models/account.model.mjs +13 -0
  167. package/esm/production/store/models/account.model.mjs.map +1 -0
  168. package/esm/production/store/models/audit.migration.mjs +30 -0
  169. package/esm/production/store/models/audit.migration.mjs.map +1 -0
  170. package/esm/production/store/models/audit.model.mjs +13 -0
  171. package/esm/production/store/models/audit.model.mjs.map +1 -0
  172. package/esm/production/store/models/base.mjs +27 -0
  173. package/esm/production/store/models/base.mjs.map +1 -0
  174. package/esm/production/store/models/index.mjs +17 -0
  175. package/esm/production/store/models/invite.migration.mjs +26 -0
  176. package/esm/production/store/models/invite.migration.mjs.map +1 -0
  177. package/esm/production/store/models/invite.model.mjs +13 -0
  178. package/esm/production/store/models/invite.model.mjs.map +1 -0
  179. package/esm/production/store/models/report.migration.mjs +20 -0
  180. package/esm/production/store/models/report.migration.mjs.map +1 -0
  181. package/esm/production/store/models/report.model.mjs +13 -0
  182. package/esm/production/store/models/report.model.mjs.map +1 -0
  183. package/esm/production/store/models/sample.migration.mjs +25 -0
  184. package/esm/production/store/models/sample.migration.mjs.map +1 -0
  185. package/esm/production/store/models/sample.model.mjs +13 -0
  186. package/esm/production/store/models/sample.model.mjs.map +1 -0
  187. package/esm/production/store/models/session.migration.mjs +31 -0
  188. package/esm/production/store/models/session.migration.mjs.map +1 -0
  189. package/esm/production/store/models/session.model.mjs +13 -0
  190. package/esm/production/store/models/session.model.mjs.map +1 -0
  191. package/esm/production/store/models/state.migration.mjs +26 -0
  192. package/esm/production/store/models/state.migration.mjs.map +1 -0
  193. package/esm/production/store/models/state.model.mjs +13 -0
  194. package/esm/production/store/models/state.model.mjs.map +1 -0
  195. package/esm/query-shape.mjs +14 -1
  196. package/esm/query-shape.mjs.map +1 -1
  197. package/esm/server/explain-route.mjs +26 -1
  198. package/esm/server/explain-route.mjs.map +1 -1
  199. package/esm/server/index.mjs +16 -6
  200. package/esm/server/index.mjs.map +1 -1
  201. package/esm/server/insights-routes.mjs +62 -0
  202. package/esm/server/insights-routes.mjs.map +1 -0
  203. package/esm/server/log-routes.mjs +32 -5
  204. package/esm/server/log-routes.mjs.map +1 -1
  205. package/esm/server/openapi-routes.mjs +3 -2
  206. package/esm/server/openapi-routes.mjs.map +1 -1
  207. package/esm/server/panel-routes.mjs +44 -0
  208. package/esm/server/panel-routes.mjs.map +1 -0
  209. package/esm/server/requests-routes.mjs +125 -0
  210. package/esm/server/requests-routes.mjs.map +1 -1
  211. package/esm/server/session-routes.mjs +42 -0
  212. package/esm/server/session-routes.mjs.map +1 -0
  213. package/esm/server/stream-route.mjs +81 -11
  214. package/esm/server/stream-route.mjs.map +1 -1
  215. package/esm/server/ui-assets.mjs +34 -12
  216. package/esm/server/ui-assets.mjs.map +1 -1
  217. package/esm/sources/log-source.mjs +14 -1
  218. package/esm/sources/log-source.mjs.map +1 -1
  219. package/esm/types.d.mts +271 -1
  220. package/esm/types.d.mts.map +1 -1
  221. package/esm/ui-root.mjs +11 -6
  222. package/esm/ui-root.mjs.map +1 -1
  223. package/llms-full.txt +208 -19
  224. package/llms.txt +2 -2
  225. package/package.json +32 -8
  226. package/skills/SKILL.md +208 -19
  227. package/ui/dashboard/assets/app.css +3 -0
  228. package/ui/dashboard/assets/app.js +50 -0
  229. package/ui/dashboard/build-info.json +21 -0
  230. package/ui/dashboard/index.html +15 -0
  231. package/ui/panels/processes.js +15 -0
  232. package/cjs/server-BlQshJLE.cjs +0 -658
  233. package/cjs/server-BlQshJLE.cjs.map +0 -1
  234. package/cjs/src-BzuntLcd.cjs.map +0 -1
  235. package/esm/server/process-routes.mjs +0 -11
  236. package/esm/server/process-routes.mjs.map +0 -1
  237. package/ui/app.css +0 -376
  238. package/ui/app.js +0 -1054
  239. package/ui/index.html +0 -28
@@ -0,0 +1,1655 @@
1
+ const require_contracts = require("./contracts-CVmplkNb.cjs");
2
+ const require_errors = require("./errors-CyZp5yS-.cjs");
3
+ const require_ip = require("./ip-DbNhPOzi.cjs");
4
+ let node_crypto = require("node:crypto");
5
+
6
+ //#region ../../packages/devtools/src/production/auth/common-passwords.ts
7
+ /**
8
+ * Passwords the monitor refuses (compared lower-cased). Short entries are
9
+ * left out: the length rule already refuses them.
10
+ */
11
+ const COMMON_PASSWORDS = /* @__PURE__ */ new Set([
12
+ "password",
13
+ "password1",
14
+ "password12",
15
+ "password123",
16
+ "password1234",
17
+ "passw0rd",
18
+ "p@ssw0rd",
19
+ "p@ssword",
20
+ "password!",
21
+ "password1!",
22
+ "password2",
23
+ "password3",
24
+ "password01",
25
+ "password11",
26
+ "password99",
27
+ "pa55word",
28
+ "pa$$word",
29
+ "12345678",
30
+ "123456789",
31
+ "1234567890",
32
+ "12345678910",
33
+ "123123123",
34
+ "1234qwer",
35
+ "1q2w3e4r",
36
+ "1q2w3e4r5t",
37
+ "1q2w3e4r5t6y",
38
+ "1qaz2wsx",
39
+ "1qaz2wsx3edc",
40
+ "1qazxsw2",
41
+ "qwertyui",
42
+ "qwertyuiop",
43
+ "qwerty123",
44
+ "qwerty1234",
45
+ "qwerty12",
46
+ "qwertyuio",
47
+ "qwerty123456",
48
+ "qwerty12345",
49
+ "asdfghjk",
50
+ "asdfghjkl",
51
+ "asdfgh123",
52
+ "zxcvbnm1",
53
+ "zxcvbnmasd",
54
+ "zxcvbnm123",
55
+ "abcd1234",
56
+ "abcd12345",
57
+ "abc12345",
58
+ "abc123456",
59
+ "abcdefgh",
60
+ "abcdefg1",
61
+ "abcdefgh1",
62
+ "abcdefghi",
63
+ "iloveyou",
64
+ "iloveyou1",
65
+ "iloveyou2",
66
+ "iloveyou123",
67
+ "letmein1",
68
+ "letmein123",
69
+ "letmein12",
70
+ "welcome1",
71
+ "welcome12",
72
+ "welcome123",
73
+ "welcome01",
74
+ "welcome2",
75
+ "monkey123",
76
+ "monkey12",
77
+ "dragon123",
78
+ "dragon12",
79
+ "master123",
80
+ "master12",
81
+ "shadow123",
82
+ "shadow12",
83
+ "sunshine",
84
+ "sunshine1",
85
+ "sunshine123",
86
+ "princess",
87
+ "princess1",
88
+ "princess123",
89
+ "football",
90
+ "football1",
91
+ "football123",
92
+ "baseball",
93
+ "baseball1",
94
+ "baseball123",
95
+ "basketball",
96
+ "soccer123",
97
+ "hockey123",
98
+ "superman",
99
+ "superman1",
100
+ "superman123",
101
+ "batman123",
102
+ "batman12",
103
+ "spiderman",
104
+ "spiderman1",
105
+ "trustno1",
106
+ "trustno123",
107
+ "trustnoone",
108
+ "whatever",
109
+ "whatever1",
110
+ "whatever123",
111
+ "freedom1",
112
+ "freedom123",
113
+ "starwars",
114
+ "starwars1",
115
+ "starwars123",
116
+ "pokemon1",
117
+ "pokemon123",
118
+ "charlie1",
119
+ "charlie123",
120
+ "michael1",
121
+ "michael123",
122
+ "jessica1",
123
+ "jessica123",
124
+ "jennifer",
125
+ "jennifer1",
126
+ "daniel123",
127
+ "daniel12",
128
+ "thomas123",
129
+ "hunter123",
130
+ "hunter12",
131
+ "hunter2hunter2",
132
+ "hello123",
133
+ "hello1234",
134
+ "hello12345",
135
+ "helloworld",
136
+ "helloworld1",
137
+ "hello@123",
138
+ "admin123",
139
+ "admin1234",
140
+ "admin12345",
141
+ "admin@123",
142
+ "admin@1234",
143
+ "administrator",
144
+ "administrator1",
145
+ "adminadmin",
146
+ "adminadmin1",
147
+ "admin2020",
148
+ "admin2021",
149
+ "admin2022",
150
+ "admin2023",
151
+ "admin2024",
152
+ "admin2025",
153
+ "admin2026",
154
+ "root1234",
155
+ "root12345",
156
+ "toor1234",
157
+ "test1234",
158
+ "test12345",
159
+ "test123456",
160
+ "testtest",
161
+ "testing123",
162
+ "testing1",
163
+ "guest123",
164
+ "guest1234",
165
+ "changeme",
166
+ "changeme1",
167
+ "changeme123",
168
+ "change123",
169
+ "default1",
170
+ "default123",
171
+ "secret123",
172
+ "secret1234",
173
+ "secretpassword",
174
+ "mypassword",
175
+ "mypassword1",
176
+ "mypassword123",
177
+ "mypass123",
178
+ "mysecret1",
179
+ "login123",
180
+ "login1234",
181
+ "access123",
182
+ "access14",
183
+ "qazwsxedc",
184
+ "qazwsx123",
185
+ "qazxswedc",
186
+ "qweasdzxc",
187
+ "qweasd123",
188
+ "qweqweqwe",
189
+ "asdasdasd",
190
+ "asdasd123",
191
+ "zaq12wsx",
192
+ "zaq1zaq1",
193
+ "zaq1xsw2",
194
+ "aaaaaaaa",
195
+ "aaaaaaa1",
196
+ "11111111",
197
+ "111111111",
198
+ "1111111111",
199
+ "00000000",
200
+ "000000000",
201
+ "0000000000",
202
+ "12341234",
203
+ "12121212",
204
+ "11223344",
205
+ "1122334455",
206
+ "123321123",
207
+ "12344321",
208
+ "123456789a",
209
+ "123456abc",
210
+ "1234567a",
211
+ "1234abcd",
212
+ "987654321",
213
+ "9876543210",
214
+ "98765432",
215
+ "88888888",
216
+ "66666666",
217
+ "55555555",
218
+ "77777777",
219
+ "99999999",
220
+ "22222222",
221
+ "33333333",
222
+ "44444444",
223
+ "pass1234",
224
+ "pass12345",
225
+ "pass123456",
226
+ "passpass",
227
+ "passpass1",
228
+ "pass@123",
229
+ "pass@1234",
230
+ "mustang1",
231
+ "mustang123",
232
+ "ranger123",
233
+ "harley123",
234
+ "ferrari1",
235
+ "porsche1",
236
+ "computer",
237
+ "computer1",
238
+ "computer123",
239
+ "internet",
240
+ "internet1",
241
+ "internet123",
242
+ "windows1",
243
+ "windows123",
244
+ "microsoft",
245
+ "linux123",
246
+ "ubuntu123",
247
+ "google123",
248
+ "google12",
249
+ "facebook",
250
+ "facebook1",
251
+ "facebook123",
252
+ "twitter1",
253
+ "youtube1",
254
+ "instagram",
255
+ "samsung1",
256
+ "samsung123",
257
+ "iphone123",
258
+ "android1",
259
+ "android123",
260
+ "liverpool",
261
+ "liverpool1",
262
+ "manchester",
263
+ "chelsea1",
264
+ "arsenal1",
265
+ "barcelona",
266
+ "realmadrid1",
267
+ "cheese123",
268
+ "chocolate",
269
+ "chocolate1",
270
+ "cookie123",
271
+ "banana123",
272
+ "butterfly",
273
+ "butterfly1",
274
+ "flower123",
275
+ "rainbow1",
276
+ "rainbow123",
277
+ "summer123",
278
+ "summer2024",
279
+ "summer2025",
280
+ "winter123",
281
+ "winter2024",
282
+ "winter2025",
283
+ "spring123",
284
+ "autumn123",
285
+ "january1",
286
+ "february1",
287
+ "december1",
288
+ "qwerty@123",
289
+ "abc@12345",
290
+ "p@55w0rd",
291
+ "p@$$w0rd",
292
+ "passw0rd1",
293
+ "passw0rd!",
294
+ "warlock123",
295
+ "warlock1",
296
+ "devtools",
297
+ "devtools1",
298
+ "devtools123",
299
+ "monitor123",
300
+ "monitor1",
301
+ "dashboard",
302
+ "dashboard1",
303
+ "dashboard123"
304
+ ]);
305
+
306
+ //#endregion
307
+ //#region ../../packages/devtools/src/production/auth/helpers.ts
308
+ const MIN_PASSWORD_LENGTH = 8;
309
+ const MAX_PASSWORD_BYTES = 72;
310
+ /** The alphabet of recovery codes and references: no 0, 1, 8, 9, I, L, O. */
311
+ const CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
312
+ /** Letters and digits that cannot be mistaken for each other. */
313
+ const TEMPORARY_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789";
314
+ /**
315
+ * The password rules: at least 8 characters, at most 72 bytes (UTF-8), not in
316
+ * the built-in common list (compared lower-cased), not equal to the email
317
+ * (lower-cased). Returns the failing rule's error code, or `null`.
318
+ */
319
+ function checkPasswordPolicy(password, email) {
320
+ if (typeof password !== "string" || [...password].length < MIN_PASSWORD_LENGTH) return "auth.password-too-short";
321
+ if (Buffer.byteLength(password, "utf8") > MAX_PASSWORD_BYTES) return "auth.password-too-long";
322
+ const lower = password.toLowerCase();
323
+ if (COMMON_PASSWORDS.has(lower)) return "auth.password-common";
324
+ if (email !== null && lower === email.trim().toLowerCase()) return "auth.password-same-as-email";
325
+ return null;
326
+ }
327
+ /** 32 random bytes, base64url (43 characters): session, CSRF and invite tokens. */
328
+ function generateToken() {
329
+ return (0, node_crypto.randomBytes)(32).toString("base64url");
330
+ }
331
+ /** SHA-256 hex of a token: what the store keeps. */
332
+ function hashToken(token) {
333
+ return (0, node_crypto.createHash)("sha256").update(token).digest("hex");
334
+ }
335
+ /**
336
+ * A random temporary password for `warlock devtools:reset-admin`: 20
337
+ * characters from an unambiguous alphabet, passes `checkPasswordPolicy`.
338
+ */
339
+ function generateTemporaryPassword() {
340
+ for (;;) {
341
+ let password = "";
342
+ for (let index = 0; index < 20; index++) password += TEMPORARY_ALPHABET[(0, node_crypto.randomInt)(54)];
343
+ if (checkPasswordPolicy(password, null) === null) return password;
344
+ }
345
+ }
346
+ /** Compares two strings in constant time (both are hashed first, so lengths do not leak). */
347
+ function safeEqual(a, b) {
348
+ const left = (0, node_crypto.createHash)("sha256").update(String(a)).digest();
349
+ const right = (0, node_crypto.createHash)("sha256").update(String(b)).digest();
350
+ return (0, node_crypto.timingSafeEqual)(left, right);
351
+ }
352
+ /** Emails are compared trimmed and lower-cased. */
353
+ function normalizeEmail(email) {
354
+ return typeof email === "string" ? email.trim().toLowerCase() : "";
355
+ }
356
+ /** A deliberately plain shape check; the invite flow is the real proof of ownership. */
357
+ function isPlausibleEmail(email) {
358
+ return email.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
359
+ }
360
+ /** One recovery code, `xxxxx-xxxxx` from the unambiguous alphabet. */
361
+ function generateRecoveryCode() {
362
+ let code = "";
363
+ for (let index = 0; index < 10; index++) {
364
+ if (index === 5) code += "-";
365
+ code += CODE_ALPHABET[(0, node_crypto.randomInt)(31)];
366
+ }
367
+ return code;
368
+ }
369
+ /** The form a recovery code is hashed in: upper case, letters and digits only. */
370
+ function normalizeRecoveryCode(code) {
371
+ return String(code).toUpperCase().replace(/[^A-Z0-9]/g, "");
372
+ }
373
+ /** SHA-256 hex of a normalized recovery code. */
374
+ function hashRecoveryCode(code) {
375
+ return hashToken(normalizeRecoveryCode(code));
376
+ }
377
+
378
+ //#endregion
379
+ //#region ../../packages/devtools/src/production/auth/service.ts
380
+ const MINUTE = 6e4;
381
+ const HOUR = 60 * MINUTE;
382
+ /** Password verifications (and hashes) a process runs at the same time. */
383
+ const MAX_IN_FLIGHT = 4;
384
+ /** `lastSeenAt` is written at most this often. */
385
+ const TOUCH_INTERVAL = MINUTE;
386
+ const INVITE_TTL = 24 * HOUR;
387
+ const CHALLENGE_TTL = 5 * MINUTE;
388
+ const TOTP_ISSUER = "Warlock monitor";
389
+ const RECOVERY_CODE_COUNT = 10;
390
+ /** A password longer than this is cut before hashing, so input size is no CPU lever. */
391
+ const MAX_PASSWORD_INPUT = 1024;
392
+ /** How long this process remembers that an IP was over its limit. */
393
+ const IP_BLOCK_CACHE_MS = 3e4;
394
+ const IP_BLOCK_CACHE_SIZE = 1e3;
395
+ /** A refused try is written to the audit log at most this often per address and account. */
396
+ const BLOCKED_AUDIT_INTERVAL = MINUTE;
397
+ const BLOCKED_AUDIT_CACHE_SIZE = 1e3;
398
+ /** Marks the session as having passed a passkey check a moment ago (sensitive actions). */
399
+ const STEP_UP_CHALLENGE = "stepup:ok";
400
+ /** A stored hash no password can match. */
401
+ const NO_PASSWORD_HASH = "!no-password-set";
402
+ const hasFactor = (account) => account.totpSecret !== null || account.passkeys.length > 0;
403
+ function fail(code, ref) {
404
+ throw new require_errors.DevtoolsApiError(code, ref === void 0 ? {} : { ref });
405
+ }
406
+ function cut(value, length) {
407
+ return typeof value === "string" ? value.slice(0, length) : null;
408
+ }
409
+ /** The accounts, sessions and two-factor service of the production monitor. */
410
+ function createDevtoolsAuth(deps) {
411
+ const { store, options, crypto, passkeys, instance } = deps;
412
+ const now = deps.now ?? Date.now;
413
+ const limits = options.rateLimits;
414
+ const windowMs = limits.windowMinutes * MINUTE;
415
+ let inFlight = 0;
416
+ let dummyHashPromise = null;
417
+ const blockedIps = /* @__PURE__ */ new Map();
418
+ const blockedAudits = /* @__PURE__ */ new Map();
419
+ /** Runs password work (hashing or verifying) while fewer than four are in flight. */
420
+ async function withSlot(run) {
421
+ if (inFlight >= MAX_IN_FLIGHT) fail("auth.busy");
422
+ inFlight++;
423
+ try {
424
+ return await run();
425
+ } finally {
426
+ inFlight--;
427
+ }
428
+ }
429
+ function dummyHash() {
430
+ dummyHashPromise ??= crypto.hashPassword(`devtools-timing-${(0, node_crypto.randomBytes)(12).toString("hex")}`);
431
+ return dummyHashPromise;
432
+ }
433
+ async function verifyPassword(password, hash) {
434
+ try {
435
+ return await crypto.verifyPassword(password, hash) === true;
436
+ } catch {
437
+ return false;
438
+ }
439
+ }
440
+ const hashPassword = (password) => withSlot(() => crypto.hashPassword(password));
441
+ const passwordInput = (value) => typeof value === "string" ? value.slice(0, MAX_PASSWORD_INPUT) : "";
442
+ function requirePolicy(password, email) {
443
+ const problem = checkPasswordPolicy(password, email);
444
+ if (problem !== null) fail(problem);
445
+ }
446
+ const csrfToken = (session) => Buffer.from(crypto.hmac(`devtools-csrf:${session.id}:${session.csrfSecret}`)).toString("base64url");
447
+ function accountView(account) {
448
+ return {
449
+ id: account.id,
450
+ email: account.email,
451
+ role: account.role,
452
+ twoFactor: {
453
+ totp: account.totpSecret !== null,
454
+ passkeys: account.passkeys.map((passkey) => ({
455
+ id: passkey.id,
456
+ name: passkey.name,
457
+ createdAt: passkey.createdAt,
458
+ lastUsedAt: passkey.lastUsedAt
459
+ })),
460
+ recoveryCodesLeft: account.recoveryCodes.length
461
+ },
462
+ mustChangePassword: account.mustChangePassword,
463
+ createdAt: account.createdAt,
464
+ lastLoginAt: account.lastLoginAt
465
+ };
466
+ }
467
+ function inviteView(invite) {
468
+ return {
469
+ id: invite.id,
470
+ email: invite.email,
471
+ role: invite.role,
472
+ createdAt: invite.createdAt,
473
+ expiresAt: invite.expiresAt,
474
+ createdBy: invite.createdBy,
475
+ usedAt: invite.usedAt
476
+ };
477
+ }
478
+ const twoFactorRequired = (account) => options.twoFactor === "everyone" || account.role === "admin";
479
+ /** Where an account goes after its password is accepted. */
480
+ function nextStage(account) {
481
+ if (account.mustChangePassword) return "password-change";
482
+ if (hasFactor(account)) return "mfa-verify";
483
+ if (twoFactorRequired(account)) return "mfa-enrol";
484
+ return "active";
485
+ }
486
+ function rpIdFor(meta) {
487
+ if (options.passkeys.rpId) return options.passkeys.rpId;
488
+ if (options.origin) try {
489
+ return new URL(options.origin).hostname;
490
+ } catch {}
491
+ return meta.hostname;
492
+ }
493
+ async function audit(type, input = {}) {
494
+ const ref = require_errors.createErrorRef();
495
+ try {
496
+ const email = input.email ?? input.auth?.account.email ?? null;
497
+ await store.audit.append({
498
+ at: now(),
499
+ type,
500
+ accountId: input.accountId ?? input.auth?.account.id ?? null,
501
+ email: email === null ? null : email.trim().toLowerCase().slice(0, 254),
502
+ ip: input.meta?.ip ?? null,
503
+ userAgent: cut(input.meta?.userAgent, 200),
504
+ detail: input.detail ?? {},
505
+ ref
506
+ });
507
+ } catch (error) {
508
+ try {
509
+ deps.warn?.(`devtools audit write failed (${type}, ref ${ref}): ${error instanceof Error ? error.message : "unknown error"}`);
510
+ } catch {}
511
+ }
512
+ return ref;
513
+ }
514
+ /**
515
+ * Writes a `login.blocked` entry, at most once a minute per address and
516
+ * account: refused tries cost no password check against the limits, so
517
+ * without this a caller over its limit could grow the audit log without
518
+ * bound. A skipped write answers the reference of the last one.
519
+ */
520
+ async function auditBlocked(input) {
521
+ const key = `${require_ip.rateLimitClient(input.meta.ip)}|${input.accountId ?? input.auth?.account.id ?? ""}`;
522
+ const at = now();
523
+ const last = blockedAudits.get(key);
524
+ if (last && at - last.at < BLOCKED_AUDIT_INTERVAL) return last.ref;
525
+ blockedAudits.delete(key);
526
+ if (blockedAudits.size >= BLOCKED_AUDIT_CACHE_SIZE) {
527
+ const oldest = blockedAudits.keys().next();
528
+ if (!oldest.done) blockedAudits.delete(oldest.value);
529
+ }
530
+ const ref = await audit("login.blocked", input);
531
+ blockedAudits.set(key, {
532
+ at,
533
+ ref
534
+ });
535
+ return ref;
536
+ }
537
+ /**
538
+ * Applies the patch `build` makes from the latest record. When another write
539
+ * wins, the record is read again and `build` runs again, so a rule it checks
540
+ * (a replayed TOTP step, a recovery code already used) is checked against
541
+ * the newest data. `build` returns `null` to refuse.
542
+ */
543
+ async function casAccount(account, build) {
544
+ let current = account;
545
+ for (let attempt = 0; attempt < 4 && current; attempt++) {
546
+ const patch = build(current);
547
+ if (patch === null) return null;
548
+ const updated = await store.accounts.update(current.id, current.version, patch);
549
+ if (updated) return updated;
550
+ current = await store.accounts.findById(current.id);
551
+ }
552
+ return null;
553
+ }
554
+ async function casSession(session, build) {
555
+ let current = session;
556
+ for (let attempt = 0; attempt < 4 && current; attempt++) {
557
+ const patch = build(current);
558
+ if (patch === null) return null;
559
+ const updated = await store.sessions.update(current.id, current.version, patch);
560
+ if (updated) return updated;
561
+ current = await store.sessions.findByTokenHash(current.tokenHash);
562
+ }
563
+ return null;
564
+ }
565
+ /** Whether the client of `ip` (the address, or its /64 for IPv6) is over the per-IP limit. */
566
+ async function ipOverLimit(ip, since, stateResetAt) {
567
+ const client = require_ip.rateLimitClient(ip);
568
+ const cached = blockedIps.get(client);
569
+ if (cached && now() < cached.until && cached.checkedAt >= stateResetAt) return true;
570
+ if (await store.audit.count({
571
+ types: require_contracts.DEVTOOLS_FAILURE_AUDIT_TYPES,
572
+ since,
573
+ ip
574
+ }) < limits.ip) {
575
+ blockedIps.delete(client);
576
+ return false;
577
+ }
578
+ if (blockedIps.size >= IP_BLOCK_CACHE_SIZE) {
579
+ const oldest = blockedIps.keys().next();
580
+ if (!oldest.done) blockedIps.delete(oldest.value);
581
+ }
582
+ blockedIps.set(client, {
583
+ until: now() + IP_BLOCK_CACHE_MS,
584
+ checkedAt: now()
585
+ });
586
+ return true;
587
+ }
588
+ /** Whether a try from `ip` for `account` is refused: dashboard locked, or the IP or the account is over its limit. */
589
+ async function isBlocked(account, ip) {
590
+ return await blockedBy(account, ip) !== null;
591
+ }
592
+ /**
593
+ * Why a try is refused: `"caller"` when the dashboard is locked or the IP is
594
+ * over its limit (nothing about the account), `"account"` when only the
595
+ * account is, `null` when it is not refused.
596
+ */
597
+ async function blockedBy(account, ip) {
598
+ const state = await store.state.read();
599
+ const at = now();
600
+ const stateResetAt = state.failuresResetAt ?? 0;
601
+ const since = Math.max(at - windowMs, stateResetAt);
602
+ const accountSince = Math.max(since, account?.failuresResetAt ?? 0);
603
+ const locked = state.lockedUntil !== null && state.lockedUntil > at;
604
+ const overIp = await ipOverLimit(ip, since, stateResetAt);
605
+ const accountCount = await store.audit.count({
606
+ types: require_contracts.DEVTOOLS_FAILURE_AUDIT_TYPES,
607
+ since: accountSince,
608
+ accountId: account?.id ?? "-"
609
+ });
610
+ if (locked || overIp) return "caller";
611
+ return account !== null && accountCount >= limits.account ? "account" : null;
612
+ }
613
+ /** Closes the whole dashboard for `lockMinutes` once failures anywhere reach the global limit. */
614
+ async function lockWhenOverGlobalLimit(meta) {
615
+ for (let attempt = 0; attempt < 3; attempt++) {
616
+ const state = await store.state.read();
617
+ const at = now();
618
+ if (state.lockedUntil !== null && state.lockedUntil > at) return;
619
+ const since = Math.max(at - windowMs, state.failuresResetAt ?? 0);
620
+ const count = await store.audit.count({
621
+ types: require_contracts.DEVTOOLS_FAILURE_AUDIT_TYPES,
622
+ since
623
+ });
624
+ if (count < limits.global) return;
625
+ if (await store.state.update(state.version, { lockedUntil: at + limits.lockMinutes * MINUTE })) {
626
+ await audit("dashboard.locked", {
627
+ meta,
628
+ detail: {
629
+ minutes: limits.lockMinutes,
630
+ failures: count
631
+ }
632
+ });
633
+ return;
634
+ }
635
+ }
636
+ }
637
+ async function failLogin(type, code, input) {
638
+ const ref = type === "login.blocked" ? await auditBlocked(input) : await audit(type, input);
639
+ if (type === "login.failed") await lockWhenOverGlobalLimit(input.meta);
640
+ return fail(code, ref);
641
+ }
642
+ /** Records a failed second factor (it counts toward the limits) and refuses. */
643
+ async function failSecondFactor(auth, meta, method, code = "auth.invalid-code") {
644
+ const ref = await audit("mfa.failed", {
645
+ auth,
646
+ meta,
647
+ detail: { method }
648
+ });
649
+ await lockWhenOverGlobalLimit(meta);
650
+ return fail(code, ref);
651
+ }
652
+ /** Refuses a second-factor try while the IP, the account or the dashboard is over its limit. */
653
+ async function guardSecondFactor(auth, meta, code = "auth.invalid-code") {
654
+ if (await isBlocked(auth.account, meta.ip)) fail(code, await auditBlocked({
655
+ auth,
656
+ meta,
657
+ detail: { step: "second-factor" }
658
+ }));
659
+ }
660
+ async function createSession(account, stage, meta) {
661
+ const token = generateToken();
662
+ const at = now();
663
+ const lifetime = stage === "active" ? options.session.maxHours * HOUR : options.session.pendingMinutes * MINUTE;
664
+ const session = await store.sessions.create({
665
+ tokenHash: hashToken(token),
666
+ accountId: account.id,
667
+ stage,
668
+ csrfSecret: (0, node_crypto.randomBytes)(32).toString("base64url"),
669
+ createdAt: at,
670
+ lastSeenAt: at,
671
+ expiresAt: at + lifetime,
672
+ ip: meta.ip,
673
+ userAgent: cut(meta.userAgent, 200),
674
+ pendingTotpSecret: null,
675
+ challenge: null,
676
+ challengeExpiresAt: null
677
+ });
678
+ return {
679
+ stage,
680
+ token,
681
+ csrf: csrfToken(session),
682
+ session
683
+ };
684
+ }
685
+ /**
686
+ * Moves a session to `stage`. Reaching `active` mints a new token (the old
687
+ * session is removed); any other stage changes the session in place.
688
+ */
689
+ async function moveTo(auth, account, stage, meta) {
690
+ if (stage === "active") {
691
+ const step = await createSession(await casAccount(account, () => ({ failuresResetAt: now() })) ?? account, "active", meta);
692
+ await store.sessions.remove(auth.session.id);
693
+ return step;
694
+ }
695
+ const session = await casSession(auth.session, () => ({
696
+ stage,
697
+ pendingTotpSecret: null,
698
+ challenge: null,
699
+ challengeExpiresAt: null,
700
+ expiresAt: now() + options.session.pendingMinutes * MINUTE
701
+ }));
702
+ if (!session) fail("server.error");
703
+ return {
704
+ stage,
705
+ token: null,
706
+ csrf: csrfToken(session),
707
+ session
708
+ };
709
+ }
710
+ function requireStage(auth, ...stages) {
711
+ if (!stages.includes(auth.stage)) fail("input.invalid");
712
+ }
713
+ function requireAdmin(auth) {
714
+ if (auth.stage !== "active" || auth.account.role !== "admin") fail("role.forbidden");
715
+ }
716
+ function newRecoveryCodes() {
717
+ const codes = Array.from({ length: RECOVERY_CODE_COUNT }, () => generateRecoveryCode());
718
+ return {
719
+ codes,
720
+ hashes: codes.map(hashRecoveryCode)
721
+ };
722
+ }
723
+ /** The step a TOTP code matches for this account, or `null` (also `null` when the step was already used). */
724
+ function totpStepFor(account, code) {
725
+ if (account.totpSecret === null) return null;
726
+ let secret;
727
+ try {
728
+ secret = crypto.decrypt(account.totpSecret);
729
+ } catch {
730
+ return null;
731
+ }
732
+ return crypto.verifyTotp(secret, String(code ?? ""), now());
733
+ }
734
+ /** Records `step` as used; refuses when the same or a later step was already accepted. */
735
+ async function consumeTotpStep(account, step) {
736
+ return casAccount(account, (fresh) => fresh.totpLastStep !== null && step <= fresh.totpLastStep ? null : { totpLastStep: step });
737
+ }
738
+ async function ensureFirstAdmin() {
739
+ const admin = options.admin;
740
+ const email = normalizeEmail(admin.email);
741
+ const existing = email ? await store.accounts.findByEmail(email) : null;
742
+ if (existing && existing.role === "admin") {
743
+ if (existing.passwordSource === "env" && admin.password !== null) {
744
+ if (!await withSlot(() => verifyPassword(admin.password, existing.passwordHash))) {
745
+ if (checkPasswordPolicy(admin.password, email) !== null) throw new require_errors.DevtoolsProductionConfigError("DT004");
746
+ const hash = await hashPassword(admin.password);
747
+ const updated = await casAccount(existing, (fresh) => fresh.passwordSource === "env" ? {
748
+ passwordHash: hash,
749
+ mustChangePassword: true
750
+ } : null);
751
+ if (updated) {
752
+ await store.sessions.removeForAccount(updated.id);
753
+ await audit("admin.reset", {
754
+ accountId: updated.id,
755
+ email,
756
+ detail: { source: "env" }
757
+ });
758
+ }
759
+ }
760
+ }
761
+ return;
762
+ }
763
+ if (await store.accounts.countAdmins() > 0) return;
764
+ if (existing || !email || admin.password === null && admin.setupToken === null) throw new require_errors.DevtoolsProductionConfigError("DT003");
765
+ let record;
766
+ if (admin.password !== null) {
767
+ if (checkPasswordPolicy(admin.password, email) !== null) throw new require_errors.DevtoolsProductionConfigError("DT004");
768
+ record = {
769
+ email,
770
+ role: "admin",
771
+ passwordHash: await hashPassword(admin.password),
772
+ passwordSource: "env",
773
+ mustChangePassword: true,
774
+ totpSecret: null,
775
+ totpEnabledAt: null,
776
+ totpLastStep: null,
777
+ recoveryCodes: [],
778
+ passkeys: [],
779
+ failuresResetAt: null,
780
+ lastLoginAt: null,
781
+ createdBy: null
782
+ };
783
+ } else record = {
784
+ email,
785
+ role: "admin",
786
+ passwordHash: NO_PASSWORD_HASH,
787
+ passwordSource: "setup",
788
+ mustChangePassword: false,
789
+ totpSecret: null,
790
+ totpEnabledAt: null,
791
+ totpLastStep: null,
792
+ recoveryCodes: [],
793
+ passkeys: [],
794
+ failuresResetAt: null,
795
+ lastLoginAt: null,
796
+ createdBy: null
797
+ };
798
+ try {
799
+ await audit("admin.seeded", {
800
+ accountId: (await store.accounts.create(record)).id,
801
+ email,
802
+ detail: { source: record.passwordSource }
803
+ });
804
+ } catch (error) {
805
+ if (!(error instanceof require_errors.DevtoolsStoreConflictError)) throw error;
806
+ }
807
+ }
808
+ async function login(input, meta) {
809
+ const email = normalizeEmail(input?.email);
810
+ const password = passwordInput(input?.password);
811
+ const account = email ? await store.accounts.findByEmail(email) : null;
812
+ const blockedReason = await blockedBy(account, meta.ip);
813
+ const blocked = blockedReason !== null;
814
+ const verifiable = !blocked && account !== null && !account.passwordHash.startsWith("!") && password !== "";
815
+ const hash = verifiable && account ? account.passwordHash : await dummyHash();
816
+ const matches = blockedReason === "caller" ? false : await withSlot(() => verifyPassword(password, hash));
817
+ if (blocked) return failLogin("login.blocked", "auth.invalid-credentials", {
818
+ email: email || null,
819
+ accountId: account?.id ?? null,
820
+ meta
821
+ });
822
+ if (!verifiable || !matches || account === null) return failLogin("login.failed", "auth.invalid-credentials", {
823
+ email: email || null,
824
+ accountId: account?.id ?? null,
825
+ meta
826
+ });
827
+ const at = now();
828
+ const updated = await casAccount(account, (fresh) => nextStage(fresh) === "active" ? {
829
+ failuresResetAt: at,
830
+ lastLoginAt: at
831
+ } : { lastLoginAt: at });
832
+ if (!updated) return failLogin("login.failed", "auth.invalid-credentials", {
833
+ email,
834
+ meta
835
+ });
836
+ await audit("login.succeeded", {
837
+ accountId: updated.id,
838
+ email,
839
+ meta
840
+ });
841
+ return createSession(updated, nextStage(updated), meta);
842
+ }
843
+ async function setup(input, meta) {
844
+ const configured = options.admin.setupToken;
845
+ const adminEmail = normalizeEmail(options.admin.email);
846
+ const account = adminEmail ? await store.accounts.findByEmail(adminEmail) : null;
847
+ const blocked = await isBlocked(null, meta.ip);
848
+ const tokenMatches = safeEqual(hashToken(typeof input?.token === "string" ? input.token : ""), hashToken(configured ?? ""));
849
+ const usable = configured !== null && tokenMatches && account !== null && account.passwordSource === "setup";
850
+ if (blocked) return failLogin("login.blocked", "auth.invalid-setup-token", {
851
+ email: adminEmail || null,
852
+ meta,
853
+ detail: { via: "setup" }
854
+ });
855
+ if (!usable || account === null) return failLogin("login.failed", "auth.invalid-setup-token", {
856
+ email: adminEmail || null,
857
+ meta,
858
+ detail: { via: "setup" }
859
+ });
860
+ const password = passwordInput(input.password);
861
+ requirePolicy(password, account.email);
862
+ const passwordHash = await hashPassword(password);
863
+ const at = now();
864
+ const updated = await casAccount(account, (fresh) => fresh.passwordSource === "setup" ? {
865
+ passwordHash,
866
+ passwordSource: "user",
867
+ mustChangePassword: false,
868
+ failuresResetAt: at,
869
+ lastLoginAt: at
870
+ } : null);
871
+ if (!updated) fail("auth.invalid-setup-token");
872
+ await audit("setup.completed", {
873
+ accountId: updated.id,
874
+ email: updated.email,
875
+ meta
876
+ });
877
+ return createSession(updated, nextStage(updated), meta);
878
+ }
879
+ async function findOpenInvite(token) {
880
+ if (typeof token !== "string" || token === "" || token.length > 200) fail("invite.invalid");
881
+ const invite = await store.invites.findByTokenHash(hashToken(token));
882
+ if (!invite || invite.usedAt !== null || invite.expiresAt <= now()) fail("invite.invalid");
883
+ return invite;
884
+ }
885
+ async function inspectInvite(token) {
886
+ const invite = await findOpenInvite(token);
887
+ return {
888
+ email: invite.email,
889
+ role: invite.role
890
+ };
891
+ }
892
+ async function acceptInvite(input, meta) {
893
+ const invite = await findOpenInvite(input?.token);
894
+ const password = passwordInput(input.password);
895
+ requirePolicy(password, invite.email);
896
+ const passwordHash = await hashPassword(password);
897
+ if (!await store.invites.markUsed(invite.id, now(), "pending")) fail("invite.invalid");
898
+ let account;
899
+ try {
900
+ account = await store.accounts.create({
901
+ email: invite.email,
902
+ role: invite.role,
903
+ passwordHash,
904
+ passwordSource: "invite",
905
+ mustChangePassword: false,
906
+ totpSecret: null,
907
+ totpEnabledAt: null,
908
+ totpLastStep: null,
909
+ recoveryCodes: [],
910
+ passkeys: [],
911
+ failuresResetAt: null,
912
+ lastLoginAt: now(),
913
+ createdBy: invite.createdBy
914
+ });
915
+ } catch (error) {
916
+ if (error instanceof require_errors.DevtoolsStoreConflictError) fail("invite.email-taken");
917
+ throw error;
918
+ }
919
+ await audit("invite.accepted", {
920
+ accountId: account.id,
921
+ email: account.email,
922
+ meta,
923
+ detail: { role: account.role }
924
+ });
925
+ return createSession(account, nextStage(account), meta);
926
+ }
927
+ async function authenticate(token) {
928
+ if (typeof token !== "string" || token === "" || token.length > 200) return null;
929
+ const session = await store.sessions.findByTokenHash(hashToken(token));
930
+ if (!session) return null;
931
+ const at = now();
932
+ if (at >= session.expiresAt || at - session.lastSeenAt > options.session.idleMinutes * MINUTE) {
933
+ await store.sessions.remove(session.id);
934
+ return null;
935
+ }
936
+ const account = await store.accounts.findById(session.accountId);
937
+ if (!account) {
938
+ await store.sessions.remove(session.id);
939
+ return null;
940
+ }
941
+ let current = session;
942
+ if (at - session.lastSeenAt >= TOUCH_INTERVAL) {
943
+ const touched = await store.sessions.update(session.id, session.version, { lastSeenAt: at });
944
+ if (touched) current = touched;
945
+ }
946
+ return {
947
+ session: current,
948
+ account,
949
+ stage: current.stage
950
+ };
951
+ }
952
+ function verifyCsrf(auth, header) {
953
+ if (typeof header !== "string" || header === "") return false;
954
+ return safeEqual(header, csrfToken(auth.session));
955
+ }
956
+ function sessionView(auth) {
957
+ if (!auth) return {
958
+ mode: "production",
959
+ stage: "signed-out",
960
+ account: null,
961
+ role: null,
962
+ csrf: null,
963
+ expiresAt: null,
964
+ instance: null,
965
+ methods: null
966
+ };
967
+ return {
968
+ mode: "production",
969
+ stage: auth.stage,
970
+ account: accountView(auth.account),
971
+ role: auth.account.role,
972
+ csrf: csrfToken(auth.session),
973
+ expiresAt: auth.session.expiresAt,
974
+ instance,
975
+ methods: {
976
+ totp: true,
977
+ passkeys: passkeys !== null
978
+ }
979
+ };
980
+ }
981
+ async function logout(auth, meta) {
982
+ await store.sessions.remove(auth.session.id);
983
+ await audit("logout", {
984
+ auth,
985
+ meta
986
+ });
987
+ }
988
+ async function listSessions(auth) {
989
+ const at = now();
990
+ return (await store.sessions.listForAccount(auth.account.id)).filter((session) => session.expiresAt > at).map((session) => ({
991
+ id: session.id,
992
+ current: session.id === auth.session.id,
993
+ createdAt: session.createdAt,
994
+ lastSeenAt: session.lastSeenAt,
995
+ expiresAt: session.expiresAt,
996
+ ip: session.ip,
997
+ userAgent: session.userAgent
998
+ }));
999
+ }
1000
+ async function revokeSession(auth, sessionId, meta) {
1001
+ const own = (await store.sessions.listForAccount(auth.account.id)).find((session) => session.id === sessionId);
1002
+ if (!own) fail("account.not-found");
1003
+ await store.sessions.remove(own.id);
1004
+ await audit("session.revoked", {
1005
+ auth,
1006
+ meta,
1007
+ detail: { current: own.id === auth.session.id }
1008
+ });
1009
+ }
1010
+ /**
1011
+ * Checks the current password of an active session. A wrong one counts
1012
+ * toward the sign-in limits like a failed sign-in.
1013
+ */
1014
+ async function requireCurrentPassword(auth, given, meta) {
1015
+ const current = passwordInput(given);
1016
+ const stored = auth.account.passwordHash;
1017
+ const verifiable = !stored.startsWith("!") && current !== "";
1018
+ if (await isBlocked(auth.account, meta.ip)) {
1019
+ await verifyPassword(current, await dummyHash());
1020
+ fail("auth.wrong-current-password", await auditBlocked({
1021
+ auth,
1022
+ meta,
1023
+ detail: { step: "password" }
1024
+ }));
1025
+ }
1026
+ const matches = await withSlot(async () => verifyPassword(current, verifiable ? stored : await dummyHash()));
1027
+ if (!verifiable || !matches) {
1028
+ const ref = await audit("login.failed", {
1029
+ auth,
1030
+ meta,
1031
+ detail: { step: "password" }
1032
+ });
1033
+ await lockWhenOverGlobalLimit(meta);
1034
+ fail("auth.wrong-current-password", ref);
1035
+ }
1036
+ }
1037
+ /**
1038
+ * Spends the session's step-up (a passkey check passed in this session in
1039
+ * the last five minutes). Compare-and-set, so two requests racing on one
1040
+ * step-up cannot both use it. Returns whether it was there to spend.
1041
+ */
1042
+ async function consumeStepUp(session) {
1043
+ return await casSession(session, (fresh) => fresh.challenge === STEP_UP_CHALLENGE && fresh.challengeExpiresAt !== null && fresh.challengeExpiresAt > now() ? {
1044
+ challenge: null,
1045
+ challengeExpiresAt: null
1046
+ } : null) !== null;
1047
+ }
1048
+ /**
1049
+ * Before an active session adds or removes a second factor: the current
1050
+ * password, or, when none is given, a fresh step-up, so a stolen session
1051
+ * cookie alone cannot change how the account signs in. Not asked while
1052
+ * enrolling the first factor at sign-in, which follows the password.
1053
+ */
1054
+ async function requireOwner(auth, current, meta) {
1055
+ if (auth.stage !== "active") return;
1056
+ if ((current === void 0 || current === "") && await consumeStepUp(auth.session)) return;
1057
+ await requireCurrentPassword(auth, current, meta);
1058
+ }
1059
+ async function changePassword(auth, input, meta) {
1060
+ requireStage(auth, "password-change", "active");
1061
+ const password = passwordInput(input?.password);
1062
+ if (auth.stage === "active") await requireCurrentPassword(auth, input?.current, meta);
1063
+ requirePolicy(password, auth.account.email);
1064
+ if (await withSlot(() => verifyPassword(password, auth.account.passwordHash))) fail("auth.password-unchanged");
1065
+ const passwordHash = await hashPassword(password);
1066
+ const updated = await casAccount(auth.account, () => ({
1067
+ passwordHash,
1068
+ passwordSource: "user",
1069
+ mustChangePassword: false
1070
+ }));
1071
+ if (!updated) fail("server.error");
1072
+ await audit("password.changed", {
1073
+ auth,
1074
+ meta
1075
+ });
1076
+ await store.sessions.removeForAccount(updated.id, auth.session.id);
1077
+ if (auth.stage === "active") return {
1078
+ stage: "active",
1079
+ token: null,
1080
+ csrf: csrfToken(auth.session),
1081
+ session: auth.session
1082
+ };
1083
+ return moveTo(auth, updated, nextStage(updated), meta);
1084
+ }
1085
+ async function startTotp(auth, _meta) {
1086
+ requireStage(auth, "mfa-enrol", "active");
1087
+ if (auth.account.totpSecret !== null) fail("input.invalid");
1088
+ const secret = crypto.generateTotpSecret();
1089
+ if (!await casSession(auth.session, () => ({ pendingTotpSecret: crypto.encrypt(secret) }))) fail("server.error");
1090
+ return {
1091
+ secret,
1092
+ uri: crypto.totpUri({
1093
+ secret,
1094
+ account: auth.account.email,
1095
+ issuer: TOTP_ISSUER
1096
+ }),
1097
+ issuer: TOTP_ISSUER,
1098
+ account: auth.account.email
1099
+ };
1100
+ }
1101
+ async function confirmTotp(auth, code, meta, current) {
1102
+ requireStage(auth, "mfa-enrol", "active");
1103
+ const pending = auth.session.pendingTotpSecret;
1104
+ if (pending === null) fail("input.invalid");
1105
+ await requireOwner(auth, current, meta);
1106
+ await guardSecondFactor(auth, meta);
1107
+ let secret;
1108
+ try {
1109
+ secret = crypto.decrypt(pending);
1110
+ } catch {
1111
+ return failSecondFactor(auth, meta, "totp");
1112
+ }
1113
+ const step = crypto.verifyTotp(secret, String(code ?? ""), now());
1114
+ if (step === null) return failSecondFactor(auth, meta, "totp");
1115
+ const fresh = newRecoveryCodes();
1116
+ let issued = null;
1117
+ const updated = await casAccount(auth.account, (account) => {
1118
+ if (account.totpSecret !== null) return null;
1119
+ issued = account.recoveryCodes.length === 0 ? fresh.codes : null;
1120
+ return {
1121
+ totpSecret: pending,
1122
+ totpEnabledAt: now(),
1123
+ totpLastStep: step,
1124
+ ...issued ? { recoveryCodes: fresh.hashes } : {}
1125
+ };
1126
+ });
1127
+ if (!updated) fail("input.invalid");
1128
+ await audit("mfa.enrolled", {
1129
+ auth,
1130
+ meta,
1131
+ detail: { method: "totp" }
1132
+ });
1133
+ if (auth.stage === "mfa-enrol") return {
1134
+ step: await moveTo(auth, updated, "active", meta),
1135
+ recoveryCodes: issued
1136
+ };
1137
+ const session = await casSession(auth.session, () => ({ pendingTotpSecret: null }));
1138
+ return {
1139
+ step: {
1140
+ stage: "active",
1141
+ token: null,
1142
+ csrf: csrfToken(auth.session),
1143
+ session: session ?? auth.session
1144
+ },
1145
+ recoveryCodes: issued
1146
+ };
1147
+ }
1148
+ async function removeTotp(auth, meta, current) {
1149
+ requireStage(auth, "active");
1150
+ if (auth.account.totpSecret === null) return;
1151
+ if (twoFactorRequired(auth.account) && auth.account.passkeys.length === 0) fail("account.last-factor");
1152
+ await requireOwner(auth, current, meta);
1153
+ if (!await casAccount(auth.account, (account) => ({
1154
+ totpSecret: null,
1155
+ totpEnabledAt: null,
1156
+ totpLastStep: null,
1157
+ ...account.passkeys.length === 0 ? { recoveryCodes: [] } : {}
1158
+ }))) fail("server.error");
1159
+ await audit("mfa.removed", {
1160
+ auth,
1161
+ meta,
1162
+ detail: { method: "totp" }
1163
+ });
1164
+ }
1165
+ async function verifySecondFactor(auth, input, meta) {
1166
+ requireStage(auth, "mfa-verify");
1167
+ const hasCode = typeof input?.code === "string" && input.code !== "";
1168
+ const hasRecovery = typeof input?.recoveryCode === "string" && input.recoveryCode !== "";
1169
+ if (!hasCode && !hasRecovery) fail("input.invalid");
1170
+ await guardSecondFactor(auth, meta);
1171
+ if (hasCode) {
1172
+ const step = totpStepFor(auth.account, input.code);
1173
+ const consumed = step === null ? null : await consumeTotpStep(auth.account, step);
1174
+ if (!consumed) return failSecondFactor(auth, meta, "totp");
1175
+ await audit("mfa.succeeded", {
1176
+ auth,
1177
+ meta,
1178
+ detail: { method: "totp" }
1179
+ });
1180
+ return moveTo(auth, consumed, "active", meta);
1181
+ }
1182
+ const given = hashRecoveryCode(input.recoveryCode);
1183
+ let left = 0;
1184
+ const used = await casAccount(auth.account, (account) => {
1185
+ let found = -1;
1186
+ account.recoveryCodes.forEach((stored, index) => {
1187
+ if (safeEqual(stored, given) && normalizeRecoveryCode(input.recoveryCode).length === 10) found = index;
1188
+ });
1189
+ if (found === -1) return null;
1190
+ const remaining = account.recoveryCodes.filter((_, index) => index !== found);
1191
+ left = remaining.length;
1192
+ return { recoveryCodes: remaining };
1193
+ });
1194
+ if (!used) return failSecondFactor(auth, meta, "recovery-code");
1195
+ await audit("recovery-code.used", {
1196
+ auth,
1197
+ meta,
1198
+ detail: { left }
1199
+ });
1200
+ return moveTo(auth, used, "active", meta);
1201
+ }
1202
+ async function regenerateRecoveryCodes(auth, code, meta) {
1203
+ requireStage(auth, "active");
1204
+ await guardSecondFactor(auth, meta);
1205
+ let account = auth.account;
1206
+ if (typeof code === "string" && code !== "" && account.totpSecret !== null) {
1207
+ const step = totpStepFor(account, code);
1208
+ const consumed = step === null ? null : await consumeTotpStep(account, step);
1209
+ if (!consumed) return failSecondFactor(auth, meta, "totp");
1210
+ account = consumed;
1211
+ } else if (!await consumeStepUp(auth.session)) return failSecondFactor(auth, meta, "totp");
1212
+ const fresh = newRecoveryCodes();
1213
+ if (!await casAccount(account, () => ({ recoveryCodes: fresh.hashes }))) fail("server.error");
1214
+ await audit("recovery-codes.regenerated", {
1215
+ auth,
1216
+ meta
1217
+ });
1218
+ return fresh.codes;
1219
+ }
1220
+ function requirePasskeys() {
1221
+ if (passkeys === null) fail("passkey.unavailable");
1222
+ return passkeys;
1223
+ }
1224
+ async function passkeyOptions(auth, purpose, meta) {
1225
+ const adapter = requirePasskeys();
1226
+ if (purpose === "register") requireStage(auth, "mfa-enrol", "active");
1227
+ else requireStage(auth, "mfa-verify", "active");
1228
+ const rpId = rpIdFor(meta);
1229
+ let result;
1230
+ if (purpose === "register") result = await adapter.registrationOptions({
1231
+ account: auth.account,
1232
+ rpId,
1233
+ rpName: options.passkeys.rpName
1234
+ });
1235
+ else {
1236
+ if (auth.account.passkeys.length === 0) fail("passkey.failed");
1237
+ await guardSecondFactor(auth, meta, "passkey.failed");
1238
+ result = await adapter.authenticationOptions({
1239
+ account: auth.account,
1240
+ rpId
1241
+ });
1242
+ }
1243
+ if (!await casSession(auth.session, () => ({
1244
+ challenge: result.challenge,
1245
+ challengeExpiresAt: now() + CHALLENGE_TTL
1246
+ }))) fail("server.error");
1247
+ return result.options;
1248
+ }
1249
+ async function verifyPasskey(auth, purpose, response, meta, current) {
1250
+ const adapter = requirePasskeys();
1251
+ if (purpose === "register") requireStage(auth, "mfa-enrol", "active");
1252
+ else requireStage(auth, "mfa-verify", "active");
1253
+ if (purpose === "login") await guardSecondFactor(auth, meta, "passkey.failed");
1254
+ else if (auth.stage === "active") await requireCurrentPassword(auth, current, meta);
1255
+ const challenge = auth.session.challenge;
1256
+ const live = challenge !== null && challenge !== STEP_UP_CHALLENGE && auth.session.challengeExpiresAt !== null && auth.session.challengeExpiresAt > now();
1257
+ const consumed = live ? await casSession(auth.session, (fresh) => fresh.challenge === challenge ? {
1258
+ challenge: null,
1259
+ challengeExpiresAt: null
1260
+ } : null) : null;
1261
+ if (!live || !consumed || challenge === null) return purpose === "login" ? failSecondFactor(auth, meta, "passkey", "passkey.failed") : fail("passkey.failed");
1262
+ const rpId = rpIdFor(meta);
1263
+ if (purpose === "register") {
1264
+ let credential;
1265
+ try {
1266
+ credential = await adapter.verifyRegistration({
1267
+ response,
1268
+ challenge,
1269
+ origin: meta.origin,
1270
+ rpId
1271
+ });
1272
+ } catch {
1273
+ return fail("passkey.failed");
1274
+ }
1275
+ if (auth.account.passkeys.some((passkey) => passkey.id === credential.id)) fail("passkey.failed");
1276
+ const fresh = newRecoveryCodes();
1277
+ let issued = null;
1278
+ const label = `Passkey added ${new Date(now()).toISOString().slice(0, 10)}`;
1279
+ const updated = await casAccount(auth.account, (account) => {
1280
+ if (account.passkeys.some((passkey) => passkey.id === credential.id)) return null;
1281
+ issued = account.recoveryCodes.length === 0 ? fresh.codes : null;
1282
+ return {
1283
+ passkeys: [...account.passkeys, {
1284
+ id: credential.id,
1285
+ publicKey: credential.publicKey,
1286
+ counter: credential.counter,
1287
+ transports: credential.transports,
1288
+ name: label,
1289
+ createdAt: now(),
1290
+ lastUsedAt: null
1291
+ }],
1292
+ ...issued ? { recoveryCodes: fresh.hashes } : {}
1293
+ };
1294
+ });
1295
+ if (!updated) fail("passkey.failed");
1296
+ await audit("passkey.added", {
1297
+ auth,
1298
+ meta
1299
+ });
1300
+ if (auth.stage === "mfa-enrol") return {
1301
+ step: await moveTo(auth, updated, "active", meta),
1302
+ recoveryCodes: issued
1303
+ };
1304
+ return {
1305
+ step: null,
1306
+ recoveryCodes: issued
1307
+ };
1308
+ }
1309
+ let verified;
1310
+ try {
1311
+ verified = await adapter.verifyAuthentication({
1312
+ response,
1313
+ challenge,
1314
+ origin: meta.origin,
1315
+ rpId,
1316
+ account: auth.account
1317
+ });
1318
+ } catch {
1319
+ return failSecondFactor(auth, meta, "passkey", "passkey.failed");
1320
+ }
1321
+ const updated = await casAccount(auth.account, (account) => {
1322
+ if (!account.passkeys.some((passkey) => passkey.id === verified.id)) return null;
1323
+ return { passkeys: account.passkeys.map((passkey) => passkey.id === verified.id ? {
1324
+ ...passkey,
1325
+ counter: verified.newCounter,
1326
+ lastUsedAt: now()
1327
+ } : passkey) };
1328
+ });
1329
+ if (!updated) return failSecondFactor(auth, meta, "passkey", "passkey.failed");
1330
+ await audit("mfa.succeeded", {
1331
+ auth,
1332
+ meta,
1333
+ detail: { method: "passkey" }
1334
+ });
1335
+ if (auth.stage === "mfa-verify") return {
1336
+ step: await moveTo(auth, updated, "active", meta),
1337
+ recoveryCodes: null
1338
+ };
1339
+ await casSession(auth.session, () => ({
1340
+ challenge: STEP_UP_CHALLENGE,
1341
+ challengeExpiresAt: now() + CHALLENGE_TTL
1342
+ }));
1343
+ return {
1344
+ step: null,
1345
+ recoveryCodes: null
1346
+ };
1347
+ }
1348
+ async function removePasskey(auth, passkeyId, meta, current) {
1349
+ requireStage(auth, "active");
1350
+ if (!auth.account.passkeys.some((passkey) => passkey.id === passkeyId)) fail("account.not-found");
1351
+ if (twoFactorRequired(auth.account) && auth.account.totpSecret === null && auth.account.passkeys.length === 1) fail("account.last-factor");
1352
+ await requireOwner(auth, current, meta);
1353
+ if (!await casAccount(auth.account, (account) => {
1354
+ const remaining = account.passkeys.filter((passkey) => passkey.id !== passkeyId);
1355
+ return {
1356
+ passkeys: remaining,
1357
+ ...remaining.length === 0 && account.totpSecret === null ? { recoveryCodes: [] } : {}
1358
+ };
1359
+ })) fail("server.error");
1360
+ await audit("passkey.removed", {
1361
+ auth,
1362
+ meta
1363
+ });
1364
+ }
1365
+ async function listUsers(auth) {
1366
+ requireAdmin(auth);
1367
+ const at = now();
1368
+ const [accounts, invites] = await Promise.all([store.accounts.list(), store.invites.list()]);
1369
+ return {
1370
+ accounts: accounts.map(accountView),
1371
+ invites: invites.filter((invite) => invite.expiresAt > at).map(inviteView)
1372
+ };
1373
+ }
1374
+ async function createInvite(auth, input, meta) {
1375
+ requireAdmin(auth);
1376
+ const email = normalizeEmail(input?.email);
1377
+ if (!isPlausibleEmail(email) || input.role !== "admin" && input.role !== "viewer") fail("input.invalid");
1378
+ if (await store.accounts.findByEmail(email)) fail("invite.email-taken");
1379
+ const token = generateToken();
1380
+ const at = now();
1381
+ const invite = await store.invites.create({
1382
+ tokenHash: hashToken(token),
1383
+ email,
1384
+ role: input.role,
1385
+ createdBy: auth.account.id,
1386
+ createdAt: at,
1387
+ expiresAt: at + INVITE_TTL
1388
+ });
1389
+ await audit("invite.created", {
1390
+ auth,
1391
+ meta,
1392
+ detail: {
1393
+ invitee: email,
1394
+ role: input.role
1395
+ }
1396
+ });
1397
+ return {
1398
+ invite: inviteView(invite),
1399
+ token
1400
+ };
1401
+ }
1402
+ async function revokeInvite(auth, inviteId, meta) {
1403
+ requireAdmin(auth);
1404
+ if (!await store.invites.remove(inviteId)) fail("invite.invalid");
1405
+ await audit("invite.revoked", {
1406
+ auth,
1407
+ meta,
1408
+ detail: { invite: inviteId }
1409
+ });
1410
+ }
1411
+ async function targetAccount(accountId) {
1412
+ const target = await store.accounts.findById(accountId);
1413
+ if (!target) fail("account.not-found");
1414
+ return target;
1415
+ }
1416
+ async function setRole(auth, accountId, role, meta) {
1417
+ requireAdmin(auth);
1418
+ if (role !== "admin" && role !== "viewer") fail("input.invalid");
1419
+ const target = await targetAccount(accountId);
1420
+ if (target.id === auth.account.id) fail("account.self");
1421
+ if (target.role === role) return accountView(target);
1422
+ if (target.role === "admin" && await store.accounts.countAdmins() <= 1) fail("account.last-admin");
1423
+ const updated = await casAccount(target, () => ({ role }));
1424
+ if (!updated) fail("account.not-found");
1425
+ if (role === "admin" && options.twoFactor === "admins" && !hasFactor(updated)) await store.sessions.removeForAccount(updated.id);
1426
+ await audit("account.role-changed", {
1427
+ auth,
1428
+ meta,
1429
+ detail: {
1430
+ target: updated.email,
1431
+ from: target.role,
1432
+ to: role
1433
+ }
1434
+ });
1435
+ return accountView(updated);
1436
+ }
1437
+ async function removeAccount(auth, accountId, meta) {
1438
+ requireAdmin(auth);
1439
+ const target = await targetAccount(accountId);
1440
+ if (target.id === auth.account.id) fail("account.self");
1441
+ if (target.role === "admin" && await store.accounts.countAdmins() <= 1) fail("account.last-admin");
1442
+ await store.sessions.removeForAccount(target.id);
1443
+ await store.accounts.remove(target.id);
1444
+ await audit("account.removed", {
1445
+ auth,
1446
+ meta,
1447
+ detail: { target: target.email }
1448
+ });
1449
+ }
1450
+ async function resetSecondFactor(auth, accountId, meta) {
1451
+ requireAdmin(auth);
1452
+ const target = await targetAccount(accountId);
1453
+ if (target.id === auth.account.id) fail("account.self");
1454
+ const updated = await casAccount(target, () => ({
1455
+ totpSecret: null,
1456
+ totpEnabledAt: null,
1457
+ totpLastStep: null,
1458
+ recoveryCodes: [],
1459
+ passkeys: []
1460
+ }));
1461
+ if (!updated) fail("account.not-found");
1462
+ await store.sessions.removeForAccount(updated.id);
1463
+ await audit("account.mfa-reset", {
1464
+ auth,
1465
+ meta,
1466
+ detail: { target: updated.email }
1467
+ });
1468
+ }
1469
+ async function signOutAccount(auth, accountId, meta) {
1470
+ requireAdmin(auth);
1471
+ const target = await targetAccount(accountId);
1472
+ const removed = await store.sessions.removeForAccount(target.id, target.id === auth.account.id ? auth.session.id : void 0);
1473
+ await audit("account.signed-out", {
1474
+ auth,
1475
+ meta,
1476
+ detail: {
1477
+ target: target.email,
1478
+ sessions: removed
1479
+ }
1480
+ });
1481
+ }
1482
+ async function disableDashboard(auth, meta) {
1483
+ requireAdmin(auth);
1484
+ for (let attempt = 0; attempt < 3; attempt++) {
1485
+ const state = await store.state.read();
1486
+ if (await store.state.update(state.version, {
1487
+ disabled: true,
1488
+ disabledPathHash: hashToken(options.path),
1489
+ disabledAt: now(),
1490
+ disabledBy: auth.account.id
1491
+ })) {
1492
+ await audit("dashboard.disabled", {
1493
+ auth,
1494
+ meta
1495
+ });
1496
+ return;
1497
+ }
1498
+ }
1499
+ fail("server.error");
1500
+ }
1501
+ return {
1502
+ ensureFirstAdmin,
1503
+ login,
1504
+ setup,
1505
+ inspectInvite,
1506
+ acceptInvite,
1507
+ authenticate,
1508
+ verifyCsrf,
1509
+ changePassword,
1510
+ startTotp,
1511
+ confirmTotp,
1512
+ removeTotp,
1513
+ verifySecondFactor,
1514
+ regenerateRecoveryCodes,
1515
+ passkeyOptions,
1516
+ verifyPasskey,
1517
+ removePasskey,
1518
+ logout,
1519
+ listSessions,
1520
+ revokeSession,
1521
+ sessionView,
1522
+ csrfToken,
1523
+ accountView,
1524
+ listUsers,
1525
+ createInvite,
1526
+ revokeInvite,
1527
+ setRole,
1528
+ removeAccount,
1529
+ resetSecondFactor,
1530
+ signOutAccount,
1531
+ disableDashboard,
1532
+ audit: (type, input) => audit(type, input)
1533
+ };
1534
+ }
1535
+
1536
+ //#endregion
1537
+ //#region ../../packages/devtools/src/production/auth/default-crypto.ts
1538
+ /** Core's password hashing, encryption and TOTP helpers, loaded lazily. */
1539
+ async function defaultDevtoolsCrypto() {
1540
+ const core = await import("@warlock.js/core");
1541
+ return {
1542
+ hashPassword: (password) => core.hashPassword(password),
1543
+ verifyPassword: (password, hash) => core.verifyPassword(password, hash),
1544
+ encrypt: (plain) => core.encrypt(plain),
1545
+ decrypt: (cipher) => core.decrypt(cipher),
1546
+ generateTotpSecret: () => core.generateTotpSecret(),
1547
+ verifyTotp: (secret, code, at) => core.verifyTotp(secret, code, { at }),
1548
+ totpUri: (input) => core.totpUri(input),
1549
+ hmac: (value) => core.hmacHash(value)
1550
+ };
1551
+ }
1552
+
1553
+ //#endregion
1554
+ //#region ../../packages/devtools/src/production/auth/passkeys.ts
1555
+ /**
1556
+ * Passkey ceremonies over `@simplewebauthn/server`, or `null` when that
1557
+ * package cannot be imported.
1558
+ */
1559
+ async function loadDevtoolsPasskeys() {
1560
+ let webauthn;
1561
+ try {
1562
+ webauthn = await import(
1563
+ /* @vite-ignore */
1564
+ "@simplewebauthn/server"
1565
+ );
1566
+ if (typeof webauthn.generateRegistrationOptions !== "function") return null;
1567
+ } catch {
1568
+ return null;
1569
+ }
1570
+ const credentialsOf = (account) => account.passkeys.map((passkey) => ({
1571
+ id: passkey.id,
1572
+ transports: passkey.transports
1573
+ }));
1574
+ return {
1575
+ async registrationOptions({ account, rpId, rpName }) {
1576
+ const options = await webauthn.generateRegistrationOptions({
1577
+ rpName,
1578
+ rpID: rpId,
1579
+ userName: account.email,
1580
+ userID: new TextEncoder().encode(account.id),
1581
+ attestationType: "none",
1582
+ excludeCredentials: credentialsOf(account),
1583
+ authenticatorSelection: {
1584
+ residentKey: "preferred",
1585
+ userVerification: "required"
1586
+ }
1587
+ });
1588
+ return {
1589
+ options,
1590
+ challenge: options.challenge
1591
+ };
1592
+ },
1593
+ async verifyRegistration({ response, challenge, origin, rpId }) {
1594
+ const verification = await webauthn.verifyRegistrationResponse({
1595
+ response,
1596
+ expectedChallenge: challenge,
1597
+ expectedOrigin: origin,
1598
+ expectedRPID: rpId,
1599
+ requireUserVerification: true
1600
+ });
1601
+ if (!verification.verified || !verification.registrationInfo) throw new Error("The passkey registration was not verified.");
1602
+ const { id, publicKey, counter, transports } = verification.registrationInfo.credential;
1603
+ return {
1604
+ id,
1605
+ publicKey: Buffer.from(publicKey).toString("base64url"),
1606
+ counter,
1607
+ transports: transports ?? []
1608
+ };
1609
+ },
1610
+ async authenticationOptions({ account, rpId }) {
1611
+ const options = await webauthn.generateAuthenticationOptions({
1612
+ rpID: rpId,
1613
+ userVerification: "required",
1614
+ allowCredentials: credentialsOf(account)
1615
+ });
1616
+ return {
1617
+ options,
1618
+ challenge: options.challenge
1619
+ };
1620
+ },
1621
+ async verifyAuthentication({ response, challenge, origin, rpId, account }) {
1622
+ const presented = response?.id;
1623
+ const stored = account.passkeys.find((passkey) => passkey.id === presented);
1624
+ if (!stored) throw new Error("The passkey is not registered for this account.");
1625
+ const verification = await webauthn.verifyAuthenticationResponse({
1626
+ response,
1627
+ expectedChallenge: challenge,
1628
+ expectedOrigin: origin,
1629
+ expectedRPID: rpId,
1630
+ credential: {
1631
+ id: stored.id,
1632
+ publicKey: new Uint8Array(Buffer.from(stored.publicKey, "base64url")),
1633
+ counter: stored.counter,
1634
+ transports: stored.transports
1635
+ },
1636
+ requireUserVerification: true
1637
+ });
1638
+ if (!verification.verified) throw new Error("The passkey was not verified.");
1639
+ return {
1640
+ id: stored.id,
1641
+ newCounter: verification.authenticationInfo.newCounter
1642
+ };
1643
+ }
1644
+ };
1645
+ }
1646
+
1647
+ //#endregion
1648
+ exports.checkPasswordPolicy = checkPasswordPolicy;
1649
+ exports.createDevtoolsAuth = createDevtoolsAuth;
1650
+ exports.defaultDevtoolsCrypto = defaultDevtoolsCrypto;
1651
+ exports.generateTemporaryPassword = generateTemporaryPassword;
1652
+ exports.generateToken = generateToken;
1653
+ exports.hashToken = hashToken;
1654
+ exports.loadDevtoolsPasskeys = loadDevtoolsPasskeys;
1655
+ //# sourceMappingURL=auth-DzU0gHDG.cjs.map