@songsid/agend 2.3.5-alpha.10 → 2.3.5-alpha.12

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 (319) hide show
  1. package/dist/accounts-view.d.ts +17 -0
  2. package/dist/accounts-view.js +24 -8
  3. package/dist/accounts-view.js.map +1 -1
  4. package/dist/agent-cli-instructions.md +2 -2
  5. package/dist/auth-api.d.ts +48 -16
  6. package/dist/auth-api.js +83 -32
  7. package/dist/auth-api.js.map +1 -1
  8. package/dist/authority/settings-role.d.ts +56 -0
  9. package/dist/authority/settings-role.js +48 -0
  10. package/dist/authority/settings-role.js.map +1 -0
  11. package/dist/backend/claude-code.d.ts +2 -0
  12. package/dist/backend/claude-code.js +32 -6
  13. package/dist/backend/claude-code.js.map +1 -1
  14. package/dist/backend/cli-env-probe.js +6 -2
  15. package/dist/backend/cli-env-probe.js.map +1 -1
  16. package/dist/backend/codex.d.ts +5 -3
  17. package/dist/backend/codex.js +31 -13
  18. package/dist/backend/codex.js.map +1 -1
  19. package/dist/backend/credential-profile.d.ts +18 -0
  20. package/dist/backend/credential-profile.js +46 -0
  21. package/dist/backend/credential-profile.js.map +1 -1
  22. package/dist/backend/kiro.js +1 -1
  23. package/dist/backend/kiro.js.map +1 -1
  24. package/dist/backend/muse.d.ts +3 -1
  25. package/dist/backend/muse.js +31 -1
  26. package/dist/backend/muse.js.map +1 -1
  27. package/dist/backend/types.d.ts +17 -1
  28. package/dist/backend/types.js.map +1 -1
  29. package/dist/backend-availability.d.ts +15 -0
  30. package/dist/backend-availability.js +37 -1
  31. package/dist/backend-availability.js.map +1 -1
  32. package/dist/build-provenance.json +1 -1
  33. package/dist/bundled-tmux-guard.d.ts +4 -0
  34. package/dist/bundled-tmux-guard.js +7 -0
  35. package/dist/bundled-tmux-guard.js.map +1 -1
  36. package/dist/claude-auth-status.d.ts +20 -8
  37. package/dist/claude-auth-status.js +38 -22
  38. package/dist/claude-auth-status.js.map +1 -1
  39. package/dist/cli-audited.d.ts +60 -0
  40. package/dist/cli-audited.js +84 -0
  41. package/dist/cli-audited.js.map +1 -0
  42. package/dist/cli-capability.d.ts +36 -5
  43. package/dist/cli-capability.js +2 -2
  44. package/dist/cli-capability.js.map +1 -1
  45. package/dist/cli-caps-module.d.ts +5 -1
  46. package/dist/cli-caps-module.js +4 -2
  47. package/dist/cli-caps-module.js.map +1 -1
  48. package/dist/cli-registry-check.js +16 -2
  49. package/dist/cli-registry-check.js.map +1 -1
  50. package/dist/cli-registry.d.ts +56 -4
  51. package/dist/cli-registry.js +1 -1
  52. package/dist/cli-registry.js.map +1 -1
  53. package/dist/cli-spec-antigravity.d.ts +12 -1
  54. package/dist/cli-spec-antigravity.js +13 -1
  55. package/dist/cli-spec-antigravity.js.map +1 -1
  56. package/dist/cli-spec-claude-code.d.ts +9 -0
  57. package/dist/cli-spec-claude-code.js +4 -2
  58. package/dist/cli-spec-claude-code.js.map +1 -1
  59. package/dist/cli-spec-codex.d.ts +10 -1
  60. package/dist/cli-spec-codex.js +5 -3
  61. package/dist/cli-spec-codex.js.map +1 -1
  62. package/dist/cli-spec-grok.d.ts +5 -0
  63. package/dist/cli-spec-grok.js +6 -1
  64. package/dist/cli-spec-grok.js.map +1 -1
  65. package/dist/cli-spec-kiro-cli.d.ts +7 -1
  66. package/dist/cli-spec-kiro-cli.js +7 -3
  67. package/dist/cli-spec-kiro-cli.js.map +1 -1
  68. package/dist/cli-spec-muse.d.ts +2 -0
  69. package/dist/cli-spec-muse.js +3 -1
  70. package/dist/cli-spec-muse.js.map +1 -1
  71. package/dist/cli-spec-opencode.d.ts +11 -1
  72. package/dist/cli-spec-opencode.js +7 -2
  73. package/dist/cli-spec-opencode.js.map +1 -1
  74. package/dist/cli.js +28 -1
  75. package/dist/cli.js.map +1 -1
  76. package/dist/create-host-account.d.ts +17 -0
  77. package/dist/create-host-account.js +47 -0
  78. package/dist/create-host-account.js.map +1 -0
  79. package/dist/daemon.d.ts +26 -0
  80. package/dist/daemon.js +131 -10
  81. package/dist/daemon.js.map +1 -1
  82. package/dist/delivery-outbox.js +7 -0
  83. package/dist/delivery-outbox.js.map +1 -1
  84. package/dist/fleet-context.d.ts +5 -1
  85. package/dist/fleet-manager.d.ts +363 -71
  86. package/dist/fleet-manager.js +1374 -367
  87. package/dist/fleet-manager.js.map +1 -1
  88. package/dist/fleet-process-handlers.d.ts +1 -1
  89. package/dist/fleet-process-handlers.js +3 -2
  90. package/dist/fleet-process-handlers.js.map +1 -1
  91. package/dist/general-knowledge/skills/concepts/SKILL.md +21 -14
  92. package/dist/general-knowledge/skills/credential-profiles/SKILL.md +9 -8
  93. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +9 -1
  94. package/dist/general-knowledge/skills/kiro-engine-migration/SKILL.md +1 -1
  95. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +27 -20
  96. package/dist/instance-lifecycle.js +33 -3
  97. package/dist/instance-lifecycle.js.map +1 -1
  98. package/dist/instructions.js +29 -6
  99. package/dist/instructions.js.map +1 -1
  100. package/dist/locale.js +125 -81
  101. package/dist/locale.js.map +1 -1
  102. package/dist/login-manager.d.ts +2 -2
  103. package/dist/login-manager.js +3 -2
  104. package/dist/login-manager.js.map +1 -1
  105. package/dist/native-model-catalog.d.ts +20 -0
  106. package/dist/native-model-catalog.js +107 -2
  107. package/dist/native-model-catalog.js.map +1 -1
  108. package/dist/public-web-gateway.js +1 -1
  109. package/dist/public-web-gateway.js.map +1 -1
  110. package/dist/public-web-link.d.ts +5 -0
  111. package/dist/public-web-link.js +8 -0
  112. package/dist/public-web-link.js.map +1 -1
  113. package/dist/runtime-api.d.ts +1 -1
  114. package/dist/runtime-api.js +104 -12
  115. package/dist/runtime-api.js.map +1 -1
  116. package/dist/runtime-autostart.d.ts +61 -0
  117. package/dist/runtime-autostart.js +161 -0
  118. package/dist/runtime-autostart.js.map +1 -0
  119. package/dist/runtime-background.d.ts +200 -0
  120. package/dist/runtime-background.js +480 -0
  121. package/dist/runtime-background.js.map +1 -0
  122. package/dist/runtime-build-info.js +5 -5
  123. package/dist/runtime-build-info.js.map +1 -1
  124. package/dist/runtime-cli-background.d.ts +92 -0
  125. package/dist/runtime-cli-background.js +336 -0
  126. package/dist/runtime-cli-background.js.map +1 -0
  127. package/dist/runtime-cli-install.d.ts +148 -8
  128. package/dist/runtime-cli-install.js +253 -59
  129. package/dist/runtime-cli-install.js.map +1 -1
  130. package/dist/runtime-cli.d.ts +8 -1
  131. package/dist/runtime-cli.js +206 -44
  132. package/dist/runtime-cli.js.map +1 -1
  133. package/dist/runtime-client-store.d.ts +11 -0
  134. package/dist/runtime-client-store.js +20 -5
  135. package/dist/runtime-client-store.js.map +1 -1
  136. package/dist/runtime-client.d.ts +23 -1
  137. package/dist/runtime-client.js +92 -6
  138. package/dist/runtime-client.js.map +1 -1
  139. package/dist/runtime-connection.d.ts +1 -1
  140. package/dist/runtime-connection.js +1 -1
  141. package/dist/runtime-connection.js.map +1 -1
  142. package/dist/runtime-coordinator.d.ts +95 -1
  143. package/dist/runtime-coordinator.js +344 -10
  144. package/dist/runtime-coordinator.js.map +1 -1
  145. package/dist/runtime-enroll-notice.d.ts +4 -0
  146. package/dist/runtime-enroll-notice.js +21 -0
  147. package/dist/runtime-enroll-notice.js.map +1 -0
  148. package/dist/runtime-enrollment.d.ts +21 -0
  149. package/dist/runtime-enrollment.js +52 -0
  150. package/dist/runtime-enrollment.js.map +1 -0
  151. package/dist/runtime-pane-native.js +4 -4
  152. package/dist/runtime-pane-native.js.map +1 -1
  153. package/dist/runtime-protocol.d.ts +78 -1
  154. package/dist/runtime-protocol.js +95 -5
  155. package/dist/runtime-protocol.js.map +1 -1
  156. package/dist/runtime-remote-accounts.d.ts +12 -0
  157. package/dist/runtime-remote-accounts.js +56 -5
  158. package/dist/runtime-remote-accounts.js.map +1 -1
  159. package/dist/runtime-remote-setup.d.ts +4 -1
  160. package/dist/runtime-remote-setup.js +4 -1
  161. package/dist/runtime-remote-setup.js.map +1 -1
  162. package/dist/runtime-update-controller.d.ts +11 -0
  163. package/dist/runtime-update-controller.js +56 -4
  164. package/dist/runtime-update-controller.js.map +1 -1
  165. package/dist/settings-api.d.ts +13 -1
  166. package/dist/settings-api.js +44 -20
  167. package/dist/settings-api.js.map +1 -1
  168. package/dist/settings-change.d.ts +5 -13
  169. package/dist/settings-change.js.map +1 -1
  170. package/dist/settings-confirmation.d.ts +11 -13
  171. package/dist/settings-confirmation.js +2 -6
  172. package/dist/settings-confirmation.js.map +1 -1
  173. package/dist/settings-effect.d.ts +5 -0
  174. package/dist/settings-effect.js +76 -10
  175. package/dist/settings-effect.js.map +1 -1
  176. package/dist/settings-http-confirmation.d.ts +8 -1
  177. package/dist/settings-http-confirmation.js +39 -13
  178. package/dist/settings-http-confirmation.js.map +1 -1
  179. package/dist/settings-request-capability.d.ts +7 -0
  180. package/dist/settings-request-capability.js +3 -1
  181. package/dist/settings-request-capability.js.map +1 -1
  182. package/dist/setup-i18n.js +4 -4
  183. package/dist/setup-i18n.js.map +1 -1
  184. package/dist/signin-keepalive.d.ts +25 -1
  185. package/dist/signin-keepalive.js +44 -1
  186. package/dist/signin-keepalive.js.map +1 -1
  187. package/dist/subagent-records.d.ts +45 -0
  188. package/dist/subagent-records.js +214 -0
  189. package/dist/subagent-records.js.map +1 -0
  190. package/dist/subagent-service.d.ts +27 -0
  191. package/dist/subagent-service.js +199 -0
  192. package/dist/subagent-service.js.map +1 -0
  193. package/dist/tmux-manager.d.ts +2 -2
  194. package/dist/tmux-manager.js +5 -3
  195. package/dist/tmux-manager.js.map +1 -1
  196. package/dist/ui/account-identity.js +7 -5
  197. package/dist/ui/accounts-keepalive.js +17 -17
  198. package/dist/ui/accounts-manage.js +34 -34
  199. package/dist/ui/accounts-view.js +68 -24
  200. package/dist/ui/agent-runtime-settings.js +1 -1
  201. package/dist/ui/backend-signin.js +67 -67
  202. package/dist/ui/chat-msg-actions.js +50 -4
  203. package/dist/ui/chat-quote.js +256 -0
  204. package/dist/ui/chat-store.js +9 -4
  205. package/dist/ui/cli-caps.js +7 -7
  206. package/dist/ui/credential-profile-select.js +4 -4
  207. package/dist/ui/general-location.js +1 -1
  208. package/dist/ui/host-install.js +290 -0
  209. package/dist/ui/hub-company-join-strings.js +3 -0
  210. package/dist/ui/hub-company-join.js +20 -2
  211. package/dist/ui/hub-owner-strings.js +5 -4
  212. package/dist/ui/hub-pairing-progress-strings.js +1 -1
  213. package/dist/ui/hub-quick-strings.js +4 -4
  214. package/dist/ui/hub-strings.js +6 -6
  215. package/dist/ui/machine-signin.js +4 -4
  216. package/dist/ui/model-picker.js +68 -0
  217. package/dist/ui/panel-chat.js +74 -13
  218. package/dist/ui/panel-fleet.js +8 -2
  219. package/dist/ui/panel-hub.js +8 -4
  220. package/dist/ui/panel-needs.js +2 -2
  221. package/dist/ui/panel-runtimes.js +232 -33
  222. package/dist/ui/panel-settings.js +7 -1
  223. package/dist/ui/panel-windows-cli.js +1 -1
  224. package/dist/ui/runtime-cli-install.js +99 -20
  225. package/dist/ui/runtime-commands.d.ts +2 -0
  226. package/dist/ui/runtime-commands.js +34 -1
  227. package/dist/ui/runtime-update-status.js +2 -2
  228. package/dist/ui/search-dialog.js +1 -0
  229. package/dist/ui/settings-access-overview.js +167 -0
  230. package/dist/ui/settings-access-strings.js +1 -1
  231. package/dist/ui/settings-catalog.js +19 -3
  232. package/dist/ui/settings-confirm.js +2 -2
  233. package/dist/ui/settings-devices.js +59 -25
  234. package/dist/ui/settings-dialogs.js +12 -13
  235. package/dist/ui/settings-guests.js +1 -1
  236. package/dist/ui/settings-hub-company-join.js +10 -7
  237. package/dist/ui/settings-hub-connection.js +121 -0
  238. package/dist/ui/settings-hub-membership.js +1 -1
  239. package/dist/ui/settings-hub-run.js +5 -6
  240. package/dist/ui/settings-hub-section.js +3 -6
  241. package/dist/ui/settings-hub.js +12 -7
  242. package/dist/ui/settings-layout.js +9 -7
  243. package/dist/ui/settings-outside.js +87 -19
  244. package/dist/ui/settings-registry.js +2 -1
  245. package/dist/ui/settings-revoke-strings.js +28 -0
  246. package/dist/ui/settings-strings.js +25 -25
  247. package/dist/ui/settings-web-authority.js +11 -4
  248. package/dist/ui/shared/accounts.css +11 -1
  249. package/dist/ui/shared/agend-auth.js +8 -1
  250. package/dist/ui/shared/app-i18n.js +10 -12
  251. package/dist/ui/shared/app-session.js +13 -16
  252. package/dist/ui/shared/app-shell.js +37 -37
  253. package/dist/ui/shared/app-store.js +2 -0
  254. package/dist/ui/shared/app.css +85 -14
  255. package/dist/ui/shared/chat-render.js +17 -5
  256. package/dist/ui/shared/chat-strings.js +4 -4
  257. package/dist/ui/shared/device-roles.js +27 -0
  258. package/dist/ui/shared/host-install.css +10 -0
  259. package/dist/ui/shared/hub-owner.css +6 -0
  260. package/dist/ui/shared/model-picker.css +21 -0
  261. package/dist/ui/shared/runtime-install.css +26 -1
  262. package/dist/ui/shared/setup-host-text.js +4 -4
  263. package/dist/ui/shared/signin.js +171 -64
  264. package/dist/ui/shared/subagent-row.css +15 -0
  265. package/dist/ui/shared/usage-dialog.js +28 -16
  266. package/dist/ui/shared/view-strings.js +7 -7
  267. package/dist/ui/shared/web-authorize.js +54 -4
  268. package/dist/ui/signin.html +19 -8
  269. package/dist/ui/structured-signin.js +30 -30
  270. package/dist/ui/subagent-row.js +72 -0
  271. package/dist/ui/web-terminal/terminal.js +9 -9
  272. package/dist/update-launch.js +4 -1
  273. package/dist/update-launch.js.map +1 -1
  274. package/dist/update-npm-env.d.ts +70 -0
  275. package/dist/update-npm-env.js +128 -0
  276. package/dist/update-npm-env.js.map +1 -0
  277. package/dist/usage/format-rich.js +1 -1
  278. package/dist/usage/format-rich.js.map +1 -1
  279. package/dist/usage/providers.js +2 -2
  280. package/dist/usage/providers.js.map +1 -1
  281. package/dist/usage/usage-api.d.ts +8 -2
  282. package/dist/usage/usage-api.js +12 -5
  283. package/dist/usage/usage-api.js.map +1 -1
  284. package/dist/web-api.d.ts +38 -4
  285. package/dist/web-api.js +370 -18
  286. package/dist/web-api.js.map +1 -1
  287. package/dist/web-auth.js +1 -1
  288. package/dist/web-auth.js.map +1 -1
  289. package/dist/web-backend-login.d.ts +2 -0
  290. package/dist/web-backend-login.js.map +1 -1
  291. package/dist/web-channel-echo.js +3 -1
  292. package/dist/web-channel-echo.js.map +1 -1
  293. package/dist/web-commands.d.ts +9 -1
  294. package/dist/web-commands.js +7 -1
  295. package/dist/web-commands.js.map +1 -1
  296. package/dist/web-host-install.d.ts +127 -0
  297. package/dist/web-host-install.js +165 -0
  298. package/dist/web-host-install.js.map +1 -0
  299. package/dist/web-remote-access.d.ts +194 -11
  300. package/dist/web-remote-access.js +458 -34
  301. package/dist/web-remote-access.js.map +1 -1
  302. package/dist/web-session.d.ts +11 -3
  303. package/dist/web-session.js.map +1 -1
  304. package/dist/web-signin-device.d.ts +16 -0
  305. package/dist/web-signin-device.js +81 -0
  306. package/dist/web-signin-device.js.map +1 -0
  307. package/dist/web-update.js +3 -1
  308. package/dist/web-update.js.map +1 -1
  309. package/dist/windows-cli-api.js +2 -1
  310. package/dist/windows-cli-api.js.map +1 -1
  311. package/dist/windows-cli-worker.d.ts +14 -0
  312. package/dist/windows-cli-worker.js +145 -1
  313. package/dist/windows-cli-worker.js.map +1 -1
  314. package/dist/windows-cli.d.ts +4 -0
  315. package/dist/windows-cli.js +9 -1
  316. package/dist/windows-cli.js.map +1 -1
  317. package/launcher/agend-install.cjs +16 -3
  318. package/package.json +1 -1
  319. package/templates/runtime-install/install.ps1 +219 -12
@@ -13,6 +13,15 @@
13
13
  * code resets it — #3008 C(b), confirmed by the user, decision 0471da59). Never a permanent
14
14
  * lock (the user's decision 4). It is fleet-wide: one guesser from many addresses is one guesser.
15
15
  *
16
+ * AGEND-122 (upstream #3486, per-admin): the authenticator is each admin's own. The record above is the HOST OPERATOR's — a
17
+ * web-only fleet's one person, and the one connections from outside sign in with — and a chat fleet's other admins each have
18
+ * their own under `admins`, keyed by connection and account. An admin enrols, replaces and removes only their own; each has
19
+ * their own "ask for my code to confirm from other devices" switch (`strict`), kept with the record so removing the app removes
20
+ * it. The wrong-code limiter stays fleet-wide.
21
+ *
22
+ * #3486: the same per-admin app also signs a new browser in as that admin (`signIn`): one use per step with the confirmations
23
+ * (`lastStep`), its own limiters (per admin in the record, per typed name in memory, one fleet-wide), never the confirmations' own.
24
+ *
16
25
  * The secret never leaves this module except once, to the host operator who is setting it up (beginEnrollment). It is
17
26
  * never logged, never in a status, a Notice or an error.
18
27
  */
@@ -37,6 +46,50 @@ export const TOTP_WRONG_LIMIT = 5;
37
46
  /** The first wait; #3008 C(b): each further one doubles, up to TOTP_PAUSE_MAX_MS. A correct code resets it. */
38
47
  export const TOTP_PAUSE_MS = 15 * 60_000;
39
48
  export const TOTP_PAUSE_MAX_MS = 24 * 60 * 60_000;
49
+ /**
50
+ * #3486 (new-device sign-in with an admin's own authenticator): the wrong-code limits of that sign-in, which are NOT the
51
+ * confirmation limiter above — an unauthenticated route must not be able to pause the confirmations of admins already signed in.
52
+ * The browser types the code alone (AGEND-155): a wrong code with no name belongs to no admin, so it is counted in the browser's
53
+ * limiter and the whole sign-in's only (layers 1 and 4; plus a known device's own, below). Layers 2 and 3 are the legacy path where the
54
+ * request still carries a name (`account`, accepted for compatibility). Four layers, so that one person's typos stop only that person,
55
+ * and the shared ones are only ceilings:
56
+ * 1. **this browser** (first to trip): SIGNIN_BROWSER_WRONG_LIMIT wrong codes pause that browser alone — 5 minutes, doubling up to
57
+ * an hour. Memory only; it counts every failure the same, whatever name was typed;
58
+ * 2. **the admin**, 3. **the name typed** (a name that is no admin's is counted exactly like one that is: nothing tells them apart)
59
+ * and 4. **the whole sign-in**: shared ceilings (SIGNIN_WRONG_LIMIT, SIGNIN_WRONG_LIMIT, SIGNIN_FLEET_WRONG_LIMIT wrong codes →
60
+ * 15 minutes, doubling up to a day). A browser the admin already signed in from (its "known device" mark) is not held by these.
61
+ * A shared count forgets after a day of no wrong codes (this browser's after an hour), and the doubling level steps down once a day has
62
+ * passed without one. A browser with a valid known-device mark is counted by the mark instead of its cookie id (so shedding cookies
63
+ * resets nothing) and, with every other attempt carrying a mark for the same admin, in a fifth limiter (SIGNIN_KNOWN_WRONG_LIMIT).
64
+ * Half-way through the admin's count (and the whole sign-in's) the admins are told once per cycle.
65
+ */
66
+ export const SIGNIN_BROWSER_WRONG_LIMIT = 5;
67
+ export const SIGNIN_BROWSER_PAUSE_MS = 5 * 60_000;
68
+ export const SIGNIN_BROWSER_PAUSE_MAX_MS = 60 * 60_000;
69
+ export const SIGNIN_WRONG_LIMIT = 10;
70
+ /**
71
+ * The whole sign-in's ceiling: wrong codes, from every browser and every way of typing (with a name or without), before a wait that
72
+ * doubles. Tightened from 50 to 20 when the name went away (AGEND-155, #3486): a code with no name can match any of the N admins who
73
+ * have an app, so one wrong guess is worth N times as much to a guesser — docs/SECURITY.md has the arithmetic.
74
+ */
75
+ export const SIGNIN_FLEET_WRONG_LIMIT = 20;
76
+ /** A shared wrong-code count is forgotten after this long without one (a slow guesser must not escape by pacing); the doubling level drops one step per SIGNIN_LEVEL_QUIET_MS without one. */
77
+ export const SIGNIN_COUNT_QUIET_MS = 24 * 60 * 60_000;
78
+ /** This browser's own count forgets sooner: it only holds that browser. */
79
+ export const SIGNIN_BROWSER_QUIET_MS = 60 * 60_000;
80
+ /** Attempts that carry a valid known-device mark of one admin count together in one more limiter, whatever cookies they send. */
81
+ export const SIGNIN_KNOWN_WRONG_LIMIT = 30;
82
+ export const SIGNIN_LEVEL_QUIET_MS = 24 * 60 * 60_000;
83
+ /** How many typed names' limiters (saved) and browsers' (memory) are remembered; the shared ceilings bound how fast they can be made. */
84
+ const SIGNIN_IDENT_MAX = 4096;
85
+ const SIGNIN_BROWSER_MAX = 4096;
86
+ /**
87
+ * #3486: whether a chat fleet's admin may sign a new browser in with their own authenticator over a PUBLIC link too (the
88
+ * quick or named link). The one place that says so — the owner may veto it at acceptance: set this to `false` and a sign-in over
89
+ * a link is refused (404, as if the route were not there) while direct connections (LAN, tailnet, the owner's own proxy) keep
90
+ * working. A web-only fleet's link is another thing: only the outside link the owner opened with "Allow connections from outside".
91
+ */
92
+ export const TOTP_SIGNIN_OVER_PUBLIC_LINK = true;
40
93
  /** #3008 review (Prism P2 1): a state that could not be saved is written again this often until it is. */
41
94
  export const OUTSIDE_SAVE_RETRY_MS = 30_000;
42
95
  /** How long a secret being set up waits for its first code. */
@@ -124,11 +177,73 @@ export function totpSkew(secret, code, nowMs) {
124
177
  }
125
178
  return null;
126
179
  }
180
+ /**
181
+ * AGEND-155: how far, in time steps either side of now, a code-only sign-in looks at EVERY admin's app, always — the accepted window
182
+ * (k = max(TOTP_PAST_STEPS, TOTP_FUTURE_STEPS) steps), plus the further k..2k a collision is looked for in (below), which also covers
183
+ * the clock-skew probe. 3k = 3 steps, so 2·3+1 = 7 codes (7 HMACs) per admin per request, whatever the code typed is, whether a
184
+ * step was already used and whether the admin may sign in.
185
+ */
186
+ export const TOTP_REACH_STEPS = Math.max(3 * Math.max(TOTP_PAST_STEPS, TOTP_FUTURE_STEPS), TOTP_SKEW_PROBE_STEPS);
187
+ /**
188
+ * AGEND-155: an app that is removed or replaced keeps counting, for a short while, in the collision rule — never for anything else.
189
+ * A collision refused at a moment when admin B's app matched must stay refused while the other admin's matching step is still accepted;
190
+ * if B then removes or replaces their app, B's old secret is kept here ("retired", saved with the rest, so a restart keeps it) for
191
+ * (4k+2) steps — 3 minutes — which is longer than any step the refused digits could still be accepted for (at most 4k steps after B's
192
+ * app went). It is read by `signInByCode`'s collision check only: it can never sign anyone in, confirm anything or be asked for.
193
+ * The pool is fleet-wide and a fixed size, always compared in full (padded with decoys), so the work does not depend on how many apps
194
+ * were retired. If more are retired within the keep time than the pool holds, the oldest is dropped and code-only sign-in is
195
+ * refused (as an ordinary wrong code) until that one's keep time would have run out (`holdUntil`): nothing is ever forgotten quietly.
196
+ */
197
+ export const TOTP_RETIRED_KEEP_MS = (4 * Math.max(TOTP_PAST_STEPS, TOTP_FUTURE_STEPS) + 2) * TOTP_STEP_SECONDS * 1000;
198
+ export const TOTP_RETIRED_SLOTS = 8;
199
+ /** The codes of one app for every step from now−TOTP_REACH_STEPS to now+TOTP_REACH_STEPS (index 0 is the earliest): fixed work, no early exit. */
200
+ function codeReach(secret, nowMs) {
201
+ const first = totpStep(nowMs) - TOTP_REACH_STEPS;
202
+ return Array.from({ length: 2 * TOTP_REACH_STEPS + 1 }, (_, i) => hotp(secret, first + i));
203
+ }
127
204
  /** The `otpauth://` URI an authenticator app reads from the QR code (or the key typed in by hand). */
128
205
  export function otpauthUri(secretBase32, account) {
129
206
  const label = encodeURIComponent(`AgEnD:${account}`);
130
207
  return `otpauth://totp/${label}?secret=${secretBase32}&issuer=AgEnD&algorithm=SHA1&digits=${TOTP_DIGITS}&period=${TOTP_STEP_SECONDS}`;
131
208
  }
209
+ const NO_LIM = Object.freeze({ wrong: 0, level: 0, pausedUntil: 0, at: 0, told: false });
210
+ const readLimWith = (v, limit) => {
211
+ const l = v;
212
+ if (!l || typeof l !== "object")
213
+ return undefined;
214
+ const n = (x) => (Number.isSafeInteger(x) && x >= 0 ? x : 0);
215
+ const lim = { wrong: Math.min(n(l.wrong), limit - 1), level: Math.min(n(l.level), 32), pausedUntil: n(l.pausedUntil), at: n(l.at), told: l.told === true };
216
+ return lim.wrong || lim.level || lim.pausedUntil ? lim : undefined;
217
+ };
218
+ /** A limiter as it reads now: the count forgotten after a quiet spell (`quietMs`), the level one step down per quiet day (after any wait ended). */
219
+ function settle(l, now, quietMs = SIGNIN_COUNT_QUIET_MS) {
220
+ const quiet = now - Math.max(l.at, l.pausedUntil);
221
+ if (quiet < quietMs)
222
+ return l;
223
+ return { ...l, wrong: 0, told: false, level: Math.max(0, l.level - Math.floor(quiet / SIGNIN_LEVEL_QUIET_MS)) };
224
+ }
225
+ /** One more wrong code in a limiter: its new state, the wait it started (0: none), and whether it just passed `halfAt` for the first time this cycle. */
226
+ function bumpLim(l, limit, baseMs, maxMs, now, quietMs = SIGNIN_COUNT_QUIET_MS, halfAt = Infinity) {
227
+ const s = settle(l, now, quietMs), wrong = s.wrong + 1, half = !s.told && wrong >= halfAt;
228
+ if (wrong < limit)
229
+ return { lim: { ...s, wrong, at: now, told: s.told || half }, wait: 0, half };
230
+ const wait = Math.min(baseMs * 2 ** s.level, maxMs);
231
+ return { lim: { wrong: 0, level: s.level + 1, pausedUntil: now + wait, at: now, told: s.told || half }, wait, half };
232
+ }
233
+ const limitsIdle = (l, now) => { const s = settle(l, now); return !s.wrong && !s.level && s.pausedUntil <= now; };
234
+ /** The host operator's key (a web-only fleet's one admin; also a chat fleet's host session). */
235
+ export const HOST_ADMIN_KEY = "host\u0000operator";
236
+ /** An admin's key: their connection and their account on it (ids are per platform). */
237
+ export const adminKey = (adapterId, userId) => `${adapterId}\u0000${userId}`;
238
+ /** At most this many admins have an authenticator (a chat fleet's admin lists are short). */
239
+ export const ADMIN_AUTHENTICATORS_MAX = 64;
240
+ const readRec = (t) => {
241
+ const r = t;
242
+ return r && typeof r.secret === "string" && (base32Decode(r.secret)?.length ?? 0) >= 16 && Number.isSafeInteger(r.enrolledAt)
243
+ && Number.isSafeInteger(r.lastStep) ? { secret: r.secret, enrolledAt: r.enrolledAt, lastStep: r.lastStep, ...(r.strict === true ? { strict: true } : {}),
244
+ ...(readLimWith(r.lim, SIGNIN_WRONG_LIMIT) ? { lim: readLimWith(r.lim, SIGNIN_WRONG_LIMIT) } : {}),
245
+ ...(readLimWith(r.klim, SIGNIN_KNOWN_WRONG_LIMIT) ? { klim: readLimWith(r.klim, SIGNIN_KNOWN_WRONG_LIMIT) } : {}) } : undefined;
246
+ };
132
247
  /** How many sessions from outside one generation remembers (each is a sign-in with a code; older ones read as revoked). */
133
248
  export const OUTSIDE_HANDLES_MAX = 64;
134
249
  const blank = () => ({ v: 1, outside: false, wrong: 0, level: 0, pausedUntil: 0, handles: [] });
@@ -138,11 +253,18 @@ export class WebRemoteAccess {
138
253
  now;
139
254
  monotonic;
140
255
  state = blank();
141
- pending = null;
256
+ /** Set-ups waiting for their first code, per session handle: one session's start never replaces another's. */
257
+ pending = new Map();
142
258
  warned = false;
143
259
  /** The state in memory is not on disk yet (a write failed): written again, by the next change or the retry timer. */
144
260
  dirty = false;
145
261
  retry = null;
262
+ /** #3486: the limiter of each browser (memory only; bounded). Key: the caller's hash of its cookie id and address. */
263
+ browserLim = new Map();
264
+ /** #3486: what a sign-in for an identifier that is no admin's is compared with — a secret nobody has, so the work done is the same. */
265
+ decoySecret = randomBytes(SECRET_BYTES);
266
+ /** Test seam (AGEND-155): told of every comparison a code-only sign-in makes — the admin's key, or null for the decoy. Never set in production. */
267
+ compareTrace;
146
268
  constructor(path, log, now = Date.now, monotonic = () => performance.now()) {
147
269
  this.path = path;
148
270
  this.log = log;
@@ -161,11 +283,33 @@ export class WebRemoteAccess {
161
283
  const v = JSON.parse(raw);
162
284
  if (v.v !== 1)
163
285
  throw new Error("shape");
164
- const t = v.totp;
165
- const totp = t && typeof t.secret === "string" && (base32Decode(t.secret)?.length ?? 0) >= 16 && Number.isSafeInteger(t.enrolledAt)
166
- && Number.isSafeInteger(t.lastStep) ? { secret: t.secret, enrolledAt: t.enrolledAt, lastStep: t.lastStep } : undefined;
286
+ const totp = readRec(v.totp);
287
+ const admins = {};
288
+ if (v.admins && typeof v.admins === "object" && !Array.isArray(v.admins)) {
289
+ for (const [k, r] of Object.entries(v.admins).slice(0, ADMIN_AUTHENTICATORS_MAX)) {
290
+ const rec = readRec(r);
291
+ if (rec && k.length <= 400)
292
+ admins[k] = rec;
293
+ }
294
+ }
167
295
  const count = (n) => (Number.isSafeInteger(n) && n >= 0 ? n : 0);
168
- this.state = { v: 1, ...(totp ? { totp } : {}),
296
+ const signin = readLimWith(v.signin, SIGNIN_FLEET_WRONG_LIMIT);
297
+ const now0 = this.now();
298
+ const retired = (Array.isArray(v.retired) ? v.retired : []).filter((r) => !!r && typeof r === "object"
299
+ && typeof r.who === "string" && r.who.length <= 400 && typeof r.secret === "string"
300
+ && (base32Decode(r.secret)?.length ?? 0) >= 16 && Number.isSafeInteger(r.until)
301
+ && r.until > now0 && r.until <= now0 + TOTP_RETIRED_KEEP_MS).slice(-TOTP_RETIRED_SLOTS);
302
+ const holdUntil = Number.isSafeInteger(v.holdUntil) && v.holdUntil > now0 ? Math.min(v.holdUntil, now0 + TOTP_RETIRED_KEEP_MS) : 0;
303
+ const idents = {};
304
+ if (v.idents && typeof v.idents === "object" && !Array.isArray(v.idents)) {
305
+ for (const [k, l] of Object.entries(v.idents).slice(-SIGNIN_IDENT_MAX)) {
306
+ const lim = /^[0-9a-f]{64}$/.test(k) ? readLimWith(l, SIGNIN_WRONG_LIMIT) : undefined;
307
+ if (lim)
308
+ idents[k] = lim;
309
+ }
310
+ }
311
+ this.state = { v: 1, ...(totp ? { totp } : {}), ...(Object.keys(admins).length ? { admins } : {}), ...(signin ? { signin } : {}), ...(Object.keys(idents).length ? { idents } : {}),
312
+ ...(retired.length ? { retired } : {}), ...(holdUntil ? { holdUntil } : {}),
169
313
  // Never on without an app set up: a file that says otherwise is read as off.
170
314
  outside: v.outside === true && !!totp,
171
315
  wrong: Math.min(count(v.wrong), TOTP_WRONG_LIMIT - 1), level: Math.min(count(v.level), 32),
@@ -179,19 +323,69 @@ export class WebRemoteAccess {
179
323
  this.state = blank();
180
324
  }
181
325
  }
182
- status() {
183
- return { enrolled: !!this.state.totp, enrolledAt: this.state.totp?.enrolledAt ?? null, outside: this.state.outside,
326
+ /** The keys (adminKey) of the chat admins that have an authenticator — never shown to anyone; the sign-in resolves a typed name among them. */
327
+ get adminKeys() { return Object.keys(this.state.admins ?? {}); }
328
+ /** One admin's record (the host operator's by default). */
329
+ rec(who) { return who === HOST_ADMIN_KEY ? this.state.totp : this.state.admins?.[who]; }
330
+ /** The state with `who`'s record set (undefined: removed). */
331
+ withRec(state, who, rec) {
332
+ if (who === HOST_ADMIN_KEY) {
333
+ const { totp: _old, ...rest } = state;
334
+ return { ...rest, ...(rec ? { totp: rec } : {}) };
335
+ }
336
+ const { admins: _old, ...rest } = state, admins = { ...(state.admins ?? {}) };
337
+ if (rec)
338
+ admins[who] = rec;
339
+ else
340
+ delete admins[who];
341
+ return { ...rest, ...(Object.keys(admins).length ? { admins } : {}) };
342
+ }
343
+ /**
344
+ * `state` with `secret` (the app `who` is losing) kept as a retired one for TOTP_RETIRED_KEEP_MS. The host operator's is not kept: a
345
+ * web-only fleet has one admin, so there is no other admin to collide with. When the pool is full its oldest entry is dropped and
346
+ * code-only sign-in is held until that entry's own keep time would have run out.
347
+ */
348
+ withRetired(state, who, secret) {
349
+ if (who === HOST_ADMIN_KEY)
350
+ return state;
351
+ const now = this.now(), live = (state.retired ?? []).filter(r => r.until > now);
352
+ let hold = state.holdUntil && state.holdUntil > now ? state.holdUntil : 0;
353
+ while (live.length >= TOTP_RETIRED_SLOTS)
354
+ hold = Math.max(hold, live.shift().until);
355
+ live.push({ who, secret, until: now + TOTP_RETIRED_KEEP_MS });
356
+ const { holdUntil: _old, ...rest } = state;
357
+ return { ...rest, retired: live, ...(hold ? { holdUntil: hold } : {}) };
358
+ }
359
+ status(who = HOST_ADMIN_KEY) {
360
+ const r = this.rec(who);
361
+ return { enrolled: !!r, enrolledAt: r?.enrolledAt ?? null, outside: this.state.outside, strict: !!r?.strict,
184
362
  pausedForMs: Math.max(0, this.state.pausedUntil - this.now()) };
185
363
  }
186
364
  get enrolled() { return !!this.state.totp; }
365
+ /** Whether `who` has an authenticator set up. */
366
+ isEnrolled(who) { return !!this.rec(who); }
367
+ /** `who`'s own "ask for my code to confirm from other devices" switch (never on without an app). */
368
+ strictOf(who) { return !!this.rec(who)?.strict; }
187
369
  /**
188
370
  * #3355 review (Prism P2): which app is set up — an opaque id of this enrollment (its secret and when it was set up), null
189
371
  * when none. Replacing the app, or removing it and setting one up again, gives another id: what a code from the old one
190
372
  * authorized can tell it no longer holds. Never the secret itself.
191
373
  */
192
- get enrollment() {
193
- const t = this.state.totp;
194
- return t ? createHash("sha256").update(`agend-totp-enrollment\0${t.secret}\0${t.enrolledAt}`).digest("hex").slice(0, 32) : null;
374
+ get enrollment() { return this.enrollmentOf(HOST_ADMIN_KEY); }
375
+ enrollmentOf(who) {
376
+ const t = this.rec(who);
377
+ return t ? createHash("sha256").update(`agend-totp-enrollment\0${who}\0${t.secret}\0${t.enrolledAt}`).digest("hex").slice(0, 32) : null;
378
+ }
379
+ /** Turn `who`'s own switch on or off. On only with their app set up. "unsaved": in force in memory, not on disk yet. */
380
+ setStrict(who, on) {
381
+ const r = this.rec(who);
382
+ if (!r)
383
+ return "not_enrolled";
384
+ if (!!r.strict === on && !this.dirty)
385
+ return "ok";
386
+ const { strict: _s, ...rest } = r;
387
+ this.state = this.withRec(this.state, who, on ? { ...rest, strict: true } : rest);
388
+ return this.flush() ? "ok" : "unsaved";
195
389
  }
196
390
  /** The sessions authorized from outside since the last revocation (their receipts hold). */
197
391
  get admitted() { return new Set(this.state.handles); }
@@ -221,47 +415,74 @@ export class WebRemoteAccess {
221
415
  this.flush(); // still owed: keep trying (re-arms the timer)
222
416
  }
223
417
  get outside() { return this.state.outside && !!this.state.totp; }
418
+ /** Whether `who` can have a record: they already do, or there is room (the host operator's is always allowed). */
419
+ hasRoom(who) {
420
+ return who === HOST_ADMIN_KEY || !!this.state.admins?.[who] || Object.keys(this.state.admins ?? {}).length < ADMIN_AUTHENTICATORS_MAX;
421
+ }
422
+ /** Void the set-up the session `handle` began: its secret can never be finished (a fresh begin is the only way on). */
423
+ cancelEnrollment(handle) { this.pending.delete(handle); }
224
424
  /**
225
- * A new secret for the session `handle` to set up (it replaces nothing until confirmEnrollment). Returned once: the
226
- * caller shows it to that session and forgets it.
425
+ * A new secret for the session `handle` to set up, as `who` (it replaces nothing until confirmEnrollment). Returned once:
426
+ * the caller shows it to that session and forgets it.
227
427
  */
228
- beginEnrollment(handle, account) {
428
+ beginEnrollment(handle, account, who = HOST_ADMIN_KEY) {
229
429
  const secret = base32Encode(randomBytes(SECRET_BYTES));
230
- this.pending = { secret, handle, until: this.monotonic() + TOTP_ENROLL_TTL_MS };
430
+ this.pending.delete(handle);
431
+ this.pending.set(handle, { secret, who, until: this.monotonic() + TOTP_ENROLL_TTL_MS });
432
+ for (const [h, p] of this.pending)
433
+ if (this.monotonic() > p.until)
434
+ this.pending.delete(h);
435
+ while (this.pending.size > 32)
436
+ this.pending.delete(this.pending.keys().next().value);
231
437
  return { secret, uri: otpauthUri(secret, account), expiresInMs: TOTP_ENROLL_TTL_MS };
232
438
  }
233
439
  /**
234
- * The first code from the app being set up, by the session that began it. "ok": it is now the one (a previous one is
235
- * replaced; the limiter starts afresh). The caller then ends the sessions signed in with the old one.
440
+ * The first code from the app being set up, by the session that began it. "ok": it is now `who`'s (a previous one is
441
+ * replaced, their switch kept). The host operator's also ends what was authorized from outside, and starts the limiter
442
+ * afresh only when made on the AgEnD computer itself (`physicalHost`); another admin's does neither — enrolling must not be a way
443
+ * to reset the fleet-wide wrong-code limit. "full": no room for another admin's record (a record is never accepted that a restart
444
+ * would drop).
236
445
  */
237
- confirmEnrollment(handle, code) {
238
- const p = this.pending;
239
- if (!p || p.handle !== handle || this.monotonic() > p.until) {
240
- if (p && this.monotonic() > p.until)
241
- this.pending = null;
446
+ confirmEnrollment(handle, code, opts = {}) {
447
+ const p = this.pending.get(handle);
448
+ if (!p || this.monotonic() > p.until) {
449
+ this.pending.delete(handle);
242
450
  return "expired";
243
451
  }
452
+ // Capacity is enforced before a new record is acknowledged: one that would not survive a restart is never accepted.
453
+ if (!this.hasRoom(p.who))
454
+ return "full";
244
455
  const step = matchTotp(base32Decode(p.secret), code, this.now(), -1);
245
456
  if (step === null)
246
457
  return "wrong";
247
- const before = this.state, wasDirty = this.dirty;
248
- // A new app replaces the old one: what was authorized under the old one ends (the admitted sessions are forgotten).
249
- this.state = { ...this.state, totp: { secret: p.secret, enrolledAt: this.now(), lastStep: step }, wrong: 0, level: 0, pausedUntil: 0, handles: [] };
458
+ const before = this.state, wasDirty = this.dirty, old = this.rec(p.who);
459
+ const rec = { secret: p.secret, enrolledAt: this.now(), lastStep: step, ...(old?.strict ? { strict: true } : {}) };
460
+ // A new host app replaces the old one: what was authorized under it ends (the admitted sessions are forgotten). The fleet-wide
461
+ // wrong-code pause is reset only by an enrolment made on the AgEnD computer itself (`physicalHost`, the caller's proof of where
462
+ // it came from): the host operator's identity used remotely — a host cookie on another device — never clears it.
463
+ const reset = p.who === HOST_ADMIN_KEY && opts.physicalHost === true;
464
+ this.state = p.who === HOST_ADMIN_KEY ? { ...this.withRec(this.state, p.who, rec), ...(reset ? { wrong: 0, level: 0, pausedUntil: 0 } : {}), handles: [] }
465
+ : this.withRec(old ? this.withRetired(this.state, p.who, old.secret) : this.state, p.who, rec);
250
466
  if (!this.flush()) {
251
467
  // Not set up: the state before stands — and if it was itself still owed to the disk (an unsaved Off), it still is.
252
468
  this.restore(before, wasDirty);
253
469
  return "unsaved";
254
470
  }
255
- this.pending = null;
471
+ this.pending.delete(handle);
256
472
  return "ok";
257
473
  }
258
474
  /**
259
- * Forget the app; the outside switch goes off with it, and what was authorized from outside ends (handles). In force in
260
- * memory at once; false: not saved yet (retried — a restart before that would read the old file).
475
+ * Forget `who`'s app (their switch with it); the host operator's also turns the outside switch off and ends what was
476
+ * authorized from outside. Nothing set up: nothing happens — in particular a set-up still waiting for its first code is left
477
+ * alone (a recovery begun on the host must not be cleared by someone else's Remove). In force in memory at once; false: not
478
+ * saved yet (retried — a restart before that would read the old file).
261
479
  */
262
- remove() {
263
- this.pending = null;
264
- this.state = { ...blank() };
480
+ remove(who = HOST_ADMIN_KEY) {
481
+ const old = this.rec(who);
482
+ if (!old)
483
+ return true;
484
+ this.state = who === HOST_ADMIN_KEY ? { ...blank(), ...(this.state.admins ? { admins: this.state.admins } : {}), ...(this.state.signin ? { signin: this.state.signin } : {}), ...(this.state.idents ? { idents: this.state.idents } : {}),
485
+ ...(this.state.retired ? { retired: this.state.retired } : {}), ...(this.state.holdUntil ? { holdUntil: this.state.holdUntil } : {}) } : this.withRec(this.withRetired(this.state, who, old.secret), who, undefined);
265
486
  return this.flush();
266
487
  }
267
488
  /**
@@ -278,8 +499,8 @@ export class WebRemoteAccess {
278
499
  return this.flush() ? "ok" : "unsaved";
279
500
  }
280
501
  /** A code typed at sign-in from outside. Each step is accepted once; wrong codes count toward a wait. */
281
- verify(code) {
282
- const t = this.state.totp;
502
+ verify(code, who = HOST_ADMIN_KEY) {
503
+ const t = this.rec(who);
283
504
  if (!t)
284
505
  return { kind: "not_enrolled" };
285
506
  const now = this.now();
@@ -288,9 +509,9 @@ export class WebRemoteAccess {
288
509
  const step = matchTotp(base32Decode(t.secret), code, now, t.lastStep);
289
510
  if (step !== null) {
290
511
  const before = this.state;
291
- this.state = { ...this.state, totp: { ...t, lastStep: step }, wrong: 0, level: 0, pausedUntil: 0 };
512
+ this.state = { ...this.withRec(this.state, who, { ...t, lastStep: step }), wrong: 0, level: 0, pausedUntil: 0 };
292
513
  if (!this.flush()) {
293
- this.state = { ...before, totp: { ...t, lastStep: step } };
514
+ this.state = this.withRec(before, who, { ...t, lastStep: step });
294
515
  return { kind: "unavailable" };
295
516
  }
296
517
  return { kind: "ok" };
@@ -307,6 +528,209 @@ export class WebRemoteAccess {
307
528
  this.flush();
308
529
  return { kind: "wrong", paused: true, retryAfterMs: wait, wrong: TOTP_WRONG_LIMIT, skewSteps };
309
530
  }
531
+ /**
532
+ * #3486: a new browser signs in with an admin's OWN authenticator code. `who`: the admin the typed name resolved to (null: it
533
+ * resolved to nobody — no such name, an admin with no app, one no longer an admin: the caller does not say which); `ident`: the
534
+ * normalized text typed, whatever it is; `browser`: this browser's key, and whether it carries a valid "known device" mark for `who`.
535
+ * A code is compared with that admin's secret when there is one and with a decoy secret when there is not — the same work — and
536
+ * every failed attempt changes and saves the same counters, so neither the answer nor the time says whether a name is an admin who
537
+ * has an app. What can pause an attempt: this browser's own limiter, the typed name's, the whole sign-in's (all three answer
538
+ * identically for every name). The admin's own limiter is a ceiling that never changes an answer: while it is in force a
539
+ * code is not tried and is answered as any wrong one (so using two names of one admin shows nothing either). A known device is
540
+ * not held by the shared ceilings, only by its mark's own limiter and the known-path limiter of its admin (so shedding cookies resets nothing).
541
+ * `browser.key` is the cookie-derived key, or — when `known` — the key of the mark itself.
542
+ * - one use per time step: the same `lastStep` as the admin's confirmations and switch;
543
+ * - success clears that admin's own count, that name's and this browser's — never the whole sign-in's, which only time lowers.
544
+ */
545
+ signIn(who, ident, code, browser) {
546
+ const now = this.now(), rec = who ? this.rec(who) : undefined, known = browser.known && !!rec;
547
+ const identKey = createHash("sha256").update(`agend-signin-ident\0${ident}`).digest("hex");
548
+ const fleet = settle(this.state.signin ?? NO_LIM, now), byIdent = settle(this.state.idents?.[identKey] ?? NO_LIM, now);
549
+ const byAdmin = settle(rec?.lim ?? NO_LIM, now), byBrowser = settle(this.browserLim.get(browser.key) ?? NO_LIM, now, SIGNIN_BROWSER_QUIET_MS);
550
+ const byKnown = settle(rec?.klim ?? NO_LIM, now);
551
+ // A known device is held by its own mark's limiter and by the known-path limiter of its admin (every attempt carrying one of X's marks counts there), not by the shared ones.
552
+ const waits = [byBrowser.pausedUntil, ...(known ? [byKnown.pausedUntil] : [fleet.pausedUntil, byIdent.pausedUntil])].map(p => Math.min(p - now, TOTP_PAUSE_MAX_MS));
553
+ const wait = Math.max(...waits);
554
+ const idle = { fleet: false, admin: false, waitMs: 0, halfFleet: false, halfAdmin: false };
555
+ if (wait > 0)
556
+ return { kind: "paused", retryAfterMs: wait, began: idle };
557
+ const secret = rec ? base32Decode(rec.secret) : this.decoySecret;
558
+ const step = matchTotp(secret, code, now, rec ? rec.lastStep : -1);
559
+ const held = !known && byAdmin.pausedUntil > now; // the admin's ceiling: the code is not tried
560
+ if (rec && who && step !== null && !held) {
561
+ const before = this.state, beforeBrowser = this.browserLim.get(browser.key);
562
+ const { lim: _lim, klim: _klim, ...clean } = rec;
563
+ const idents = { ...(this.state.idents ?? {}) };
564
+ delete idents[identKey];
565
+ const { idents: _idents, ...rest } = this.withRec(this.state, who, { ...clean, lastStep: step });
566
+ this.state = { ...rest, ...(Object.keys(idents).length ? { idents } : {}) };
567
+ this.browserLim.delete(browser.key);
568
+ if (!this.flush()) {
569
+ this.state = { ...this.withRec(before, who, { ...clean, lastStep: step }), ...(before.signin ? { signin: before.signin } : {}), ...(before.idents ? { idents: before.idents } : {}) };
570
+ if (beforeBrowser)
571
+ this.browserLim.set(browser.key, beforeBrowser);
572
+ return { kind: "unavailable" };
573
+ }
574
+ return { kind: "ok", who };
575
+ }
576
+ // Wrong, or no such admin, or the admin's ceiling: the same counters, the same write — and the same clock-skew look (the decoy when there is no admin).
577
+ const skew = totpSkew(secret, code, now);
578
+ const f = bumpLim(fleet, SIGNIN_FLEET_WRONG_LIMIT, TOTP_PAUSE_MS, TOTP_PAUSE_MAX_MS, now, SIGNIN_COUNT_QUIET_MS, SIGNIN_FLEET_WRONG_LIMIT / 2);
579
+ const i = bumpLim(byIdent, SIGNIN_WRONG_LIMIT, TOTP_PAUSE_MS, TOTP_PAUSE_MAX_MS, now);
580
+ const a = rec ? bumpLim(byAdmin, SIGNIN_WRONG_LIMIT, TOTP_PAUSE_MS, TOTP_PAUSE_MAX_MS, now, SIGNIN_COUNT_QUIET_MS, SIGNIN_WRONG_LIMIT / 2) : { lim: NO_LIM, wait: 0, half: false };
581
+ const k = known ? bumpLim(byKnown, SIGNIN_KNOWN_WRONG_LIMIT, TOTP_PAUSE_MS, TOTP_PAUSE_MAX_MS, now, SIGNIN_COUNT_QUIET_MS, SIGNIN_KNOWN_WRONG_LIMIT / 2) : { lim: byKnown, wait: 0, half: false };
582
+ const w = bumpLim(byBrowser, SIGNIN_BROWSER_WRONG_LIMIT, SIGNIN_BROWSER_PAUSE_MS, SIGNIN_BROWSER_PAUSE_MAX_MS, now, SIGNIN_BROWSER_QUIET_MS);
583
+ this.browserLim.delete(browser.key);
584
+ this.browserLim.set(browser.key, w.lim);
585
+ while (this.browserLim.size > SIGNIN_BROWSER_MAX)
586
+ this.browserLim.delete(this.browserLim.keys().next().value);
587
+ const idents = {};
588
+ for (const [k, l] of Object.entries(this.state.idents ?? {}))
589
+ if (k !== identKey && !limitsIdle(l, now))
590
+ idents[k] = l;
591
+ idents[identKey] = i.lim;
592
+ for (const k of Object.keys(idents).slice(0, Math.max(0, Object.keys(idents).length - SIGNIN_IDENT_MAX)))
593
+ delete idents[k];
594
+ const { idents: _old, ...base } = rec && who ? this.withRec(this.state, who, { ...rec, lim: a.lim, ...(known ? { klim: k.lim } : {}) }) : this.state;
595
+ this.state = { ...base, signin: f.lim, idents };
596
+ this.flush();
597
+ const began = { fleet: f.wait > 0, admin: !!rec && (a.wait > 0 || i.wait > 0 || k.wait > 0), waitMs: Math.max(f.wait, i.wait, a.wait, k.wait),
598
+ halfFleet: f.half, halfAdmin: !!rec && (a.half || k.half) };
599
+ // Answered by what every name shares: this browser's wait, the name's, the whole sign-in's (a known device: its mark's and its admin's known-path wait).
600
+ const started = Math.max(w.wait, ...(known ? [k.wait] : [f.wait, i.wait]));
601
+ return started > 0 ? { kind: "paused", retryAfterMs: started, began } : { kind: "wrong", ...(rec && skew !== null ? { skewSteps: skew } : {}), began };
602
+ }
603
+ /**
604
+ * AGEND-155 (#3486): a new browser types ONLY the code; the server works out whose it is. The code is compared with the app of EVERY
605
+ * candidate — each one, every time, three time steps each, never stopping at a match — so the work is the same whoever (or nobody)
606
+ * it belongs to. `candidates` is every admin with an app, `eligible` saying whether they are still an admin of their connection
607
+ * (asked of each by the caller, so that does not stop early either); with none, one comparison with a decoy secret is made. `known`:
608
+ * the admins whose "known device" mark this browser carries (valid as their app and the epoch stand now), `browser.key` the mark's
609
+ * own key when there is one, else the cookie id's.
610
+ * - exactly one candidate matches (eligible, a step newer than their `lastStep`, and — unless this
611
+ * browser is a known device of that admin — no wait in force for the whole sign-in): that admin is signed in and their step spent;
612
+ * - none matches: a wrong code. The same answer — and the same counting — as a code that is right for no one;
613
+ * - two apps match (for a right code, ≈ 3 in 10⁶ per other admin; "match" = the raw codes of the two apps, one in the accepted window and
614
+ * the other within 2k steps of it, whoever has spent what): nobody is signed in, **nothing is spent**, and it is a wrong code in every way:
615
+ * counted in the same counters, answered with the same 401, so neither the answer nor a count says "your code collided with someone's".
616
+ * Not spending the step means a collision cannot be used to burn an admin's step; the person waits for the next code. Because it is a
617
+ * rule on the raw codes, those digits stay refused for as long as any step they matched is still accepted — after a step was spent, an
618
+ * admin was demoted, a limit moved, or one of the two steps aged out — and a restart changes nothing (no state is kept for it).
619
+ * Counting: a wrong code has no admin to blame, so it is counted in this browser's limiter, the whole sign-in's, and — for a known
620
+ * device — in the known-path limiter of each admin whose mark it carries (by mark × admin, as with a name). The per-admin and per-name
621
+ * counts do not apply to it (they stay for a request that still sends a name). What can pause an attempt: this browser's wait and the
622
+ * whole sign-in's (a known device: its mark's and its admins' known-path waits), the same answer for any code. An admin's own ceiling
623
+ * (started only by named attempts) does not apply here: otherwise anyone could block an admin's code-only sign-in by typing wrong
624
+ * codes under that admin's name. A success clears that admin's own counts and
625
+ * this browser's, never the whole sign-in's.
626
+ */
627
+ signInByCode(code, browser, candidates, known) {
628
+ const now = this.now(), fleet = settle(this.state.signin ?? NO_LIM, now);
629
+ const byBrowser = settle(this.browserLim.get(browser.key) ?? NO_LIM, now, SIGNIN_BROWSER_QUIET_MS);
630
+ const marks = known.filter((w, i) => known.indexOf(w) === i && this.rec(w));
631
+ const isKnown = marks.length > 0;
632
+ const knownLim = (w) => settle(this.rec(w)?.klim ?? NO_LIM, now);
633
+ const waits = [byBrowser.pausedUntil, ...(isKnown ? marks.map(w => knownLim(w).pausedUntil) : [fleet.pausedUntil])].map(p => Math.min(p - now, TOTP_PAUSE_MAX_MS));
634
+ const wait = Math.max(...waits);
635
+ const idle = { fleet: false, admin: false, waitMs: 0, halfFleet: false, halfAdmin: false };
636
+ if (wait > 0)
637
+ return { kind: "paused", retryAfterMs: wait, began: idle };
638
+ // Every candidate, always, the same work: all TOTP_REACH_STEPS-each-side codes of their app (7 HMACs), compared in full, no early exit;
639
+ // only afterwards is anything decided by what was spent, who may sign in here, and what is open. With no app at all, one app's worth
640
+ // of work is done with a decoy secret.
641
+ const typed = code.replace(/\s/g, ""), valid = /^\d{6}$/.test(typed), R = TOTP_REACH_STEPS, at = totpStep(now), k = Math.max(TOTP_PAST_STEPS, TOTP_FUTURE_STEPS);
642
+ const same = (candidate) => timingSafeEqual(Buffer.from(candidate), Buffer.from(valid ? typed : "x".repeat(candidate.length))) && valid;
643
+ const rows = [];
644
+ for (const c of candidates) {
645
+ const rec = this.rec(c.who);
646
+ if (!rec)
647
+ continue;
648
+ this.compareTrace?.(c.who);
649
+ rows.push({ who: c.who, eligible: c.eligible, lastStep: rec.lastStep, eq: codeReach(base32Decode(rec.secret), now).map(same) });
650
+ }
651
+ const compared = rows.length > 0;
652
+ if (!compared) {
653
+ this.compareTrace?.(null);
654
+ codeReach(this.decoySecret, now).map(same);
655
+ }
656
+ // The retired apps (see TOTP_RETIRED_KEEP_MS): a fixed number of slots, every one compared in full — an empty slot with a decoy — so the work is the
657
+ // same whatever has been removed or replaced. They take part in the collision check below and in nothing else.
658
+ const retired = (this.state.retired ?? []).filter(r => r.until > now).slice(-TOTP_RETIRED_SLOTS);
659
+ for (let slot = 0; slot < TOTP_RETIRED_SLOTS; slot++) {
660
+ const r = retired[slot];
661
+ const eq = codeReach(r ? base32Decode(r.secret) : this.decoySecret, now).map(same);
662
+ if (r)
663
+ rows.push({ who: r.who, eligible: false, lastStep: Number.MAX_SAFE_INTEGER, eq, retired: true });
664
+ }
665
+ const accepted = (i) => i - R >= -TOTP_PAST_STEPS && i - R <= TOTP_FUTURE_STEPS;
666
+ // A code that matches TWO admins' apps — in the accepted window for one, within 2k steps of it for the other — is refused, whatever has
667
+ // happened to either since: spent steps, demotion, limits and time (while any of the steps it matched is still accepted) do not
668
+ // matter, because only the raw codes of the apps are looked at. It needs no memory, so a restart cannot lose it. Without this a refused
669
+ // collision could be used later (after one admin spent their step, or after one of the steps aged out) to sign the same digits in as the other.
670
+ let ambiguous = (this.state.holdUntil ?? 0) > now; // a retired app that was still needed had to be dropped: refused until its keep time is over
671
+ for (const x of rows)
672
+ for (const y of rows) {
673
+ if (x.who === y.who)
674
+ continue; // one admin's old and new app do not collide with each other
675
+ for (let i = 0; i < x.eq.length; i++)
676
+ for (let j = 0; j < y.eq.length; j++)
677
+ ambiguous = ambiguous || (accepted(i) && x.eq[i] && y.eq[j] && Math.abs(i - j) <= 2 * k);
678
+ }
679
+ const hits = [], skews = [];
680
+ for (const r of rows) {
681
+ if (r.retired)
682
+ continue; // never a way in
683
+ let step = null;
684
+ for (let i = 0; i < r.eq.length; i++)
685
+ if (step === null && accepted(i) && r.eq[i] && at + i - R > r.lastStep)
686
+ step = at + i - R;
687
+ // A known device is not held by the whole sign-in's wait for its own admin; for anyone else it is (the wait was not checked above).
688
+ // The admin's own ceiling (started by named attempts) is not read: it holds the named path only.
689
+ const open = marks.includes(r.who) || fleet.pausedUntil <= now;
690
+ if (step !== null && r.eligible && open && !ambiguous)
691
+ hits.push(r.who);
692
+ else
693
+ for (let i = 0; i < r.eq.length; i++)
694
+ if (r.eq[i] && !accepted(i) && Math.abs(i - R) <= TOTP_SKEW_PROBE_STEPS)
695
+ skews.push(i - R); // the clock-skew look: log only
696
+ }
697
+ if (hits.length === 1) {
698
+ const who = hits[0], rec = this.rec(who), row = rows.find(r => r.who === who);
699
+ let step = -1;
700
+ for (let i = 0; i < row.eq.length; i++)
701
+ if (step < 0 && accepted(i) && row.eq[i] && at + i - R > rec.lastStep)
702
+ step = at + i - R;
703
+ const before = this.state, beforeBrowser = this.browserLim.get(browser.key);
704
+ const { lim: _lim, klim: _klim, ...clean } = rec;
705
+ this.state = this.withRec(this.state, who, { ...clean, lastStep: step });
706
+ this.browserLim.delete(browser.key);
707
+ if (!this.flush()) {
708
+ this.state = this.withRec(before, who, { ...clean, lastStep: step });
709
+ if (beforeBrowser)
710
+ this.browserLim.set(browser.key, beforeBrowser);
711
+ return { kind: "unavailable" };
712
+ }
713
+ return { kind: "ok", who };
714
+ }
715
+ // Wrong (or no one's, or a collision): the browser's own count, the whole sign-in's, a known device's known-path counts. Nothing else.
716
+ const f = bumpLim(fleet, SIGNIN_FLEET_WRONG_LIMIT, TOTP_PAUSE_MS, TOTP_PAUSE_MAX_MS, now, SIGNIN_COUNT_QUIET_MS, SIGNIN_FLEET_WRONG_LIMIT / 2);
717
+ const w = bumpLim(byBrowser, SIGNIN_BROWSER_WRONG_LIMIT, SIGNIN_BROWSER_PAUSE_MS, SIGNIN_BROWSER_PAUSE_MAX_MS, now, SIGNIN_BROWSER_QUIET_MS);
718
+ this.browserLim.delete(browser.key);
719
+ this.browserLim.set(browser.key, w.lim);
720
+ while (this.browserLim.size > SIGNIN_BROWSER_MAX)
721
+ this.browserLim.delete(this.browserLim.keys().next().value);
722
+ let next = this.state;
723
+ const ks = marks.map(who => ({ who, ...bumpLim(knownLim(who), SIGNIN_KNOWN_WRONG_LIMIT, TOTP_PAUSE_MS, TOTP_PAUSE_MAX_MS, now, SIGNIN_COUNT_QUIET_MS, SIGNIN_KNOWN_WRONG_LIMIT / 2) }));
724
+ for (const k of ks)
725
+ next = this.withRec(next, k.who, { ...this.rec(k.who), klim: k.lim });
726
+ this.state = { ...next, signin: f.lim };
727
+ this.flush();
728
+ const kWait = Math.max(0, ...ks.map(k => k.wait));
729
+ const began = { fleet: f.wait > 0, admin: kWait > 0, waitMs: Math.max(f.wait, kWait), halfFleet: f.half, halfAdmin: ks.some(k => k.half) };
730
+ const started = Math.max(w.wait, isKnown ? kWait : f.wait);
731
+ return started > 0 ? { kind: "paused", retryAfterMs: started, began }
732
+ : { kind: "wrong", ...(hits.length === 0 && compared && !ambiguous && skews.length === 1 ? { skewSteps: skews[0] } : {}), began };
733
+ }
310
734
  /**
311
735
  * Saved: true. Not saved: false (warned once until it works again) — memory keeps the new state, and it is written
312
736
  * again by the next change or every OUTSIDE_SAVE_RETRY_MS until it is (#3008 review, Prism P2 1).