shapewall 0.0.0-stage → 0.2.2

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 (304) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/Dockerfile.agent +45 -0
  3. package/LICENSE +202 -0
  4. package/NOTICE +12 -0
  5. package/README.md +651 -2
  6. package/THIRD_PARTY.md +165 -0
  7. package/bin/shapewall.js +29 -0
  8. package/dist/agent/package-lock.json +8384 -0
  9. package/dist/client/assets/BoardChat-D5SFd8HE.js +28 -0
  10. package/dist/client/assets/BuzzDialog-HWXBy52W.js +1 -0
  11. package/dist/client/assets/ChecksPanel-DTdImWoD.js +1 -0
  12. package/dist/client/assets/History-CEv6b-av.js +1 -0
  13. package/dist/client/assets/LocalSettings-C4vriEVQ.js +1 -0
  14. package/dist/client/assets/Management-DCfhcEUY.js +1 -0
  15. package/dist/client/assets/QuickConnect-DQGgUsl1.js +1 -0
  16. package/dist/client/assets/ShareDialog-C_plIto0.js +2 -0
  17. package/dist/client/assets/app-update-dialog-2hPz_N9G.js +1 -0
  18. package/dist/client/assets/circle-x-BZMPi8Zf.js +1 -0
  19. package/dist/client/assets/index-ByQRKVit.css +2 -0
  20. package/dist/client/assets/index-DweQ8Qtu.js +29 -0
  21. package/dist/client/assets/refresh-cw-CRow0Nbq.js +1 -0
  22. package/dist/client/assets/runtime-Bft6x_6E.js +4 -0
  23. package/dist/client/assets/square-A8EnIYLR.js +1 -0
  24. package/dist/client/assets/tts-dist-DYlBQmwG.js +18 -0
  25. package/dist/client/assets/tts-en-g2p-BPUtBFGG.js +1 -0
  26. package/dist/client/assets/tts-ort-wasm-simd-threaded-qh98TCA_.wasm +0 -0
  27. package/dist/client/assets/tts-ort.wasm.bundle.min-rEkcs_ow.js +12 -0
  28. package/dist/client/assets/tts-rolldown-runtime-D8NudN84.js +1 -0
  29. package/dist/client/assets/tts-spacy-en-tokenizer-6SNMl--A.json +1 -0
  30. package/dist/client/assets/tts-tts.worker-Bzm6aWbv.js +1 -0
  31. package/dist/client/assets/tts-us_gold-DcjeNMH1.json +92589 -0
  32. package/dist/client/assets/tts-us_silver-C964mEB5.json +93363 -0
  33. package/dist/client/assets/ui-CLbws0rx.js +41 -0
  34. package/dist/client/build-info.json +1 -0
  35. package/dist/client/favicon.svg +7 -0
  36. package/dist/client/icons/apple-touch-icon.png +0 -0
  37. package/dist/client/icons/icon-192.png +0 -0
  38. package/dist/client/icons/icon-512.png +0 -0
  39. package/dist/client/icons/maskable-512.png +0 -0
  40. package/dist/client/index.html +25 -0
  41. package/dist/client/manifest.webmanifest +15 -0
  42. package/dist/client/sw.js +53 -0
  43. package/dist/client/theme-boot.js +27 -0
  44. package/dist/console/assets/LocalAccountsApp-BQCcmj3x.js +1 -0
  45. package/dist/console/assets/LocalConsole-Bb2FUDs7.js +1 -0
  46. package/dist/console/assets/app-update-dialog-DIeYepLZ.js +1 -0
  47. package/dist/console/assets/console-C7uJLLOn.js +51 -0
  48. package/dist/console/assets/console-R8IBY3Am.css +2 -0
  49. package/dist/console/build-info.json +1 -0
  50. package/dist/console/console.html +21 -0
  51. package/dist/console/favicon.svg +7 -0
  52. package/dist/console/icons/apple-touch-icon.png +0 -0
  53. package/dist/console/icons/icon-192.png +0 -0
  54. package/dist/console/icons/icon-512.png +0 -0
  55. package/dist/console/icons/maskable-512.png +0 -0
  56. package/dist/console/manifest.webmanifest +15 -0
  57. package/dist/console/theme-boot.js +27 -0
  58. package/docs/agent-hardening.md +342 -0
  59. package/docs/agent-recipes.md +187 -0
  60. package/docs/agent-workflow.md +320 -0
  61. package/docs/agents.md +894 -0
  62. package/docs/architecture.md +242 -0
  63. package/docs/buzz.md +140 -0
  64. package/docs/capture-warnings.md +57 -0
  65. package/docs/config.md +489 -0
  66. package/docs/deployment.md +289 -0
  67. package/docs/design-system.md +162 -0
  68. package/docs/github.md +107 -0
  69. package/docs/hosted.md +764 -0
  70. package/docs/images/board-overview.png +0 -0
  71. package/docs/images/journeys.png +0 -0
  72. package/docs/images/live-comment.png +0 -0
  73. package/docs/images/phone-comment.png +0 -0
  74. package/docs/images/phone-overview.png +0 -0
  75. package/docs/images/variant.png +0 -0
  76. package/docs/interaction-audits.md +40 -0
  77. package/docs/journeys.md +137 -0
  78. package/docs/local-accounts.md +80 -0
  79. package/docs/notifications.md +237 -0
  80. package/docs/page-checks.md +69 -0
  81. package/docs/performance.md +174 -0
  82. package/docs/starter-agent.md +325 -0
  83. package/docs/updates.md +87 -0
  84. package/examples/audits/interaction.audit.json +17 -0
  85. package/package.json +132 -4
  86. package/src/accounts/avatar.js +121 -0
  87. package/src/accounts/local.js +464 -0
  88. package/src/agent/acp/command.js +204 -0
  89. package/src/agent/acp/detect.js +75 -0
  90. package/src/agent/acp/sandbox.js +160 -0
  91. package/src/agent/agent-health.js +75 -0
  92. package/src/agent/backends/acp.js +1297 -0
  93. package/src/agent/backends/index.js +61 -0
  94. package/src/agent/backends/openai.js +308 -0
  95. package/src/agent/composer.js +221 -0
  96. package/src/agent/config.js +338 -0
  97. package/src/agent/context.js +191 -0
  98. package/src/agent/control.js +122 -0
  99. package/src/agent/errors.js +17 -0
  100. package/src/agent/feedback-loop.js +137 -0
  101. package/src/agent/manage.js +94 -0
  102. package/src/agent/next-steps.js +51 -0
  103. package/src/agent/owner-mcp.js +38 -0
  104. package/src/agent/plain-text.js +52 -0
  105. package/src/agent/ratings-core.js +213 -0
  106. package/src/agent/ratings.js +100 -0
  107. package/src/agent/reply-text.js +67 -0
  108. package/src/agent/routes.js +1065 -0
  109. package/src/agent/run.js +326 -0
  110. package/src/agent/settings-routes.js +704 -0
  111. package/src/agent/showable.js +23 -0
  112. package/src/agent/starter/approvals.js +181 -0
  113. package/src/agent/starter/build-image.js +90 -0
  114. package/src/agent/starter/cli.js +163 -0
  115. package/src/agent/starter/disk.js +53 -0
  116. package/src/agent/starter/doctor.js +180 -0
  117. package/src/agent/starter/egress-proxy.js +351 -0
  118. package/src/agent/starter/gate.js +90 -0
  119. package/src/agent/starter/loop.js +114 -0
  120. package/src/agent/starter/model-relay.js +289 -0
  121. package/src/agent/starter/pause.js +14 -0
  122. package/src/agent/starter/probe.js +272 -0
  123. package/src/agent/starter/prompt.js +41 -0
  124. package/src/agent/starter/push-guard.js +146 -0
  125. package/src/agent/starter/rpc.js +164 -0
  126. package/src/agent/starter/runtime.js +287 -0
  127. package/src/agent/starter/sandbox-main.js +121 -0
  128. package/src/agent/starter/settings.js +290 -0
  129. package/src/agent/starter/source.js +69 -0
  130. package/src/agent/starter/supervisor.js +755 -0
  131. package/src/agent/starter/sweep.js +46 -0
  132. package/src/agent/starter/tools.js +524 -0
  133. package/src/agent/starter/watch.js +84 -0
  134. package/src/agent/starter/worktree.js +409 -0
  135. package/src/agent/text-diff.js +210 -0
  136. package/src/agent/thread-history.js +223 -0
  137. package/src/agent/threads.js +399 -0
  138. package/src/agent/tools.js +200 -0
  139. package/src/agent/turn-changes.js +424 -0
  140. package/src/agent/undo-state.js +26 -0
  141. package/src/agent/user-settings.js +308 -0
  142. package/src/auth/record.js +375 -0
  143. package/src/broken-links.js +164 -0
  144. package/src/buzz/client.js +75 -0
  145. package/src/buzz/config.js +151 -0
  146. package/src/buzz/environment.js +13 -0
  147. package/src/buzz/gateway.js +192 -0
  148. package/src/buzz/routes.js +61 -0
  149. package/src/buzz/signer-child.js +205 -0
  150. package/src/buzz/store.js +89 -0
  151. package/src/buzz/transport.js +60 -0
  152. package/src/buzz/verify.js +140 -0
  153. package/src/capture/actions.js +159 -0
  154. package/src/capture/capture.js +776 -0
  155. package/src/capture/dom-names.js +189 -0
  156. package/src/capture/element-map.js +509 -0
  157. package/src/capture/live.js +827 -0
  158. package/src/capture/media-scheme.js +317 -0
  159. package/src/capture/network-summary.js +86 -0
  160. package/src/capture/pacing.js +34 -0
  161. package/src/capture/requests.js +167 -0
  162. package/src/capture/sanitize.js +752 -0
  163. package/src/checks/accessibility.js +134 -0
  164. package/src/checks/budgets.js +58 -0
  165. package/src/checks/cli.js +55 -0
  166. package/src/checks/comparison.js +113 -0
  167. package/src/checks/environments.js +32 -0
  168. package/src/checks/flow-config.js +82 -0
  169. package/src/checks/flow-origin.js +53 -0
  170. package/src/checks/flows.js +398 -0
  171. package/src/checks/lighthouse-auth.js +145 -0
  172. package/src/checks/lighthouse-findings.js +130 -0
  173. package/src/checks/lighthouse.js +395 -0
  174. package/src/checks/robots.js +85 -0
  175. package/src/checks/routes.js +52 -0
  176. package/src/checks/run-control.js +259 -0
  177. package/src/checks/runner.js +724 -0
  178. package/src/checks/schema.js +133 -0
  179. package/src/checks/seo-analysis.js +443 -0
  180. package/src/checks/seo-probe.js +190 -0
  181. package/src/checks/seo-snapshot.js +99 -0
  182. package/src/checks/store.js +214 -0
  183. package/src/checks/transport.js +47 -0
  184. package/src/cli/args.js +319 -0
  185. package/src/cli/capture.js +79 -0
  186. package/src/cli/commands.js +92 -0
  187. package/src/cli/comments.js +84 -0
  188. package/src/cli/help.js +243 -0
  189. package/src/cli/init.js +214 -0
  190. package/src/cli/misc.js +64 -0
  191. package/src/cli/notify.js +87 -0
  192. package/src/cli/open.js +22 -0
  193. package/src/cli/serve.js +274 -0
  194. package/src/cli/variant.js +82 -0
  195. package/src/cli/watch.js +70 -0
  196. package/src/cli.js +130 -0
  197. package/src/comment-fields.js +76 -0
  198. package/src/comments-cli.js +208 -0
  199. package/src/config-reload.js +100 -0
  200. package/src/config.js +1061 -0
  201. package/src/devices-cli.js +21 -0
  202. package/src/diff.js +95 -0
  203. package/src/discover.js +284 -0
  204. package/src/doctor.js +295 -0
  205. package/src/event-log.js +268 -0
  206. package/src/events-cli.js +102 -0
  207. package/src/events.js +113 -0
  208. package/src/export.js +119 -0
  209. package/src/feedback.js +246 -0
  210. package/src/github.js +551 -0
  211. package/src/hosted/LICENSE.md +105 -0
  212. package/src/hosted/access-cli.js +78 -0
  213. package/src/hosted/admin.js +682 -0
  214. package/src/hosted/agent-approvals.js +163 -0
  215. package/src/hosted/agent-policy.js +189 -0
  216. package/src/hosted/app.js +510 -0
  217. package/src/hosted/auth-routes.js +540 -0
  218. package/src/hosted/auth.js +536 -0
  219. package/src/hosted/backup.js +483 -0
  220. package/src/hosted/board-context.js +35 -0
  221. package/src/hosted/board-routes.js +486 -0
  222. package/src/hosted/board-view.js +94 -0
  223. package/src/hosted/clean-worker.js +24 -0
  224. package/src/hosted/cleaner.js +89 -0
  225. package/src/hosted/comments.js +355 -0
  226. package/src/hosted/console-routes.js +401 -0
  227. package/src/hosted/cookies.js +18 -0
  228. package/src/hosted/crypto.js +80 -0
  229. package/src/hosted/db.js +496 -0
  230. package/src/hosted/device-routes.js +175 -0
  231. package/src/hosted/device.js +233 -0
  232. package/src/hosted/events.js +63 -0
  233. package/src/hosted/guards.js +172 -0
  234. package/src/hosted/guest-view.js +65 -0
  235. package/src/hosted/http.js +39 -0
  236. package/src/hosted/import.js +300 -0
  237. package/src/hosted/mail.js +73 -0
  238. package/src/hosted/mcp-http.js +71 -0
  239. package/src/hosted/membership.js +114 -0
  240. package/src/hosted/operator.js +478 -0
  241. package/src/hosted/ops-cli.js +345 -0
  242. package/src/hosted/pages.js +146 -0
  243. package/src/hosted/permissions.js +113 -0
  244. package/src/hosted/presence.js +372 -0
  245. package/src/hosted/projects.js +124 -0
  246. package/src/hosted/public.js +109 -0
  247. package/src/hosted/push.js +622 -0
  248. package/src/hosted/quotas.js +115 -0
  249. package/src/hosted/ratelimit.js +96 -0
  250. package/src/hosted/rebind.js +316 -0
  251. package/src/hosted/retention.js +128 -0
  252. package/src/hosted/server.js +260 -0
  253. package/src/hosted/setup-link.js +64 -0
  254. package/src/hosted/setup.js +323 -0
  255. package/src/hosted/shares.js +444 -0
  256. package/src/hosted/tailscale.js +204 -0
  257. package/src/hosted/tenancy.js +301 -0
  258. package/src/hosted/token-api.js +455 -0
  259. package/src/hosted/token-events.js +60 -0
  260. package/src/hosted/tokens.js +57 -0
  261. package/src/hosted/turnstile.js +49 -0
  262. package/src/hosted/usercontent.js +154 -0
  263. package/src/hosted/zip.js +155 -0
  264. package/src/invocation.js +58 -0
  265. package/src/journey-paths.js +282 -0
  266. package/src/journeys.js +189 -0
  267. package/src/links.js +106 -0
  268. package/src/local-projects.js +182 -0
  269. package/src/lock.js +193 -0
  270. package/src/mcp.js +417 -0
  271. package/src/mentions.js +151 -0
  272. package/src/net.js +15 -0
  273. package/src/notify/config.js +275 -0
  274. package/src/notify/index.js +301 -0
  275. package/src/notify/lease.js +73 -0
  276. package/src/notify/messages.js +212 -0
  277. package/src/notify/run.js +174 -0
  278. package/src/pixeldiff.js +49 -0
  279. package/src/png.js +143 -0
  280. package/src/reactions.js +111 -0
  281. package/src/remote/cli.js +133 -0
  282. package/src/remote/credentials.js +62 -0
  283. package/src/remote/ids.js +12 -0
  284. package/src/remote/login.js +155 -0
  285. package/src/remote/remote-mcp.js +237 -0
  286. package/src/remote/remote-watch.js +291 -0
  287. package/src/remote/remote.js +313 -0
  288. package/src/remote/share-state.js +78 -0
  289. package/src/remote/share.js +369 -0
  290. package/src/remote/terminal.js +13 -0
  291. package/src/serve-state.js +64 -0
  292. package/src/server/app.js +824 -0
  293. package/src/server/devices.js +186 -0
  294. package/src/server/local-console.js +28 -0
  295. package/src/server/local-user.js +59 -0
  296. package/src/server/pairing-routes.js +159 -0
  297. package/src/server/share-routes.js +89 -0
  298. package/src/server/tailscale.js +97 -0
  299. package/src/sitemap.js +431 -0
  300. package/src/store.js +983 -0
  301. package/src/tokens.js +11 -0
  302. package/src/update/routes.js +245 -0
  303. package/src/watch.js +403 -0
  304. package/src/which.js +58 -0
@@ -0,0 +1,540 @@
1
+ // The account routes under /auth (src/hosted/app.js): passkey sign-up and
2
+ // sign-in, recovery codes, the session, the account's own security log,
3
+ // deleting the account, re-auth, passkeys and sessions.
4
+ //
5
+ // mountAuthRoutes(authRouter, deps) adds them to the router app.js made
6
+ // (headers, write guard, avatar routes and JSON parser already on it) and
7
+ // returns { startSession, ceremonyCookie } for the other modules.
8
+
9
+ import { deleteWorkspaceRows } from './admin.js'
10
+ import { AuthError, cleanDisplayName, deviceLabel } from './auth.js'
11
+ import { parseCookies } from './cookies.js'
12
+ import { SESSION_ID_RE, sha256 } from './crypto.js'
13
+ import { transaction } from './db.js'
14
+ import { HttpError, fail, cleanWorkspaceName } from './http.js'
15
+ import { LIMITS } from './ratelimit.js'
16
+ import { moveInfo } from './rebind.js'
17
+ import { removeSetupLink } from './setup-link.js'
18
+ import {
19
+ accountEvents,
20
+ auditAccount,
21
+ deleteAccountEvents,
22
+ findInviteByHash,
23
+ inviteUsable,
24
+ lastRecoverySignIn,
25
+ seenDevice,
26
+ tenant,
27
+ workspacesForUser,
28
+ } from './tenancy.js'
29
+
30
+ export function mountAuthRoutes(authRouter, deps) {
31
+ const {
32
+ db,
33
+ dataDir,
34
+ auth,
35
+ q,
36
+ iso,
37
+ rateLimiter,
38
+ signup,
39
+ turnstile,
40
+ turnstileHosts,
41
+ sites,
42
+ siteOf,
43
+ ceremonyAuth,
44
+ SESSION_COOKIE,
45
+ CEREMONY_COOKIE,
46
+ clientIp,
47
+ setCookie,
48
+ limit,
49
+ handle,
50
+ sessionOf,
51
+ needSession,
52
+ needFresh,
53
+ needFreshOrRecovery,
54
+ auditOf,
55
+ publicUser,
56
+ createWorkspace,
57
+ acceptInvite,
58
+ revokeGrantsOf,
59
+ ownerCount,
60
+ } = deps
61
+
62
+ // What the sign-up ceremony keeps (in challenges.data) is the SHA-256 of
63
+ // the invite or setup token, never the token itself.
64
+ function signupAllowed({ invite, setup }) {
65
+ if (typeof invite === 'string' && invite) {
66
+ const row = findInviteByHash(db, sha256(invite))
67
+ if (!inviteUsable(row, iso())) throw new AuthError(403, 'invalid_invite', 'This invite link is used, expired or revoked.')
68
+ return { inviteHash: sha256(invite) }
69
+ }
70
+ if (typeof setup === 'string' && setup) {
71
+ const row = q.get('SELECT * FROM setup_codes WHERE code_hash = :hash', { hash: sha256(setup) })
72
+ if (!row || row.used_at || row.expires_at <= iso()) throw new AuthError(403, 'invalid_setup', 'This setup link is used or expired.')
73
+ return { setupHash: sha256(setup) }
74
+ }
75
+ if (signup === 'open') return {}
76
+ throw new AuthError(403, 'invite_required', 'Sign-up needs an invite link from a workspace admin.')
77
+ }
78
+
79
+ // A new sign-in always gets a new session; the one the browser had ends.
80
+ // Returns the new session's hash.
81
+ function startSession(req, res, userId, options = {}) {
82
+ const previous = sessionOf(req)
83
+ if (previous) auth.deleteSession(previous.session.hash)
84
+ const token = auth.createSession(userId, { ...options, device: deviceLabel(req.headers['user-agent']), ip: clientIp(req) })
85
+ setCookie(res, SESSION_COOKIE, token, 30 * 86400)
86
+ setCookie(res, CEREMONY_COOKIE, '', 0)
87
+ return sha256(token)
88
+ }
89
+ const ceremonyCookie = (req) => parseCookies(req.headers.cookie)[CEREMONY_COOKIE]
90
+
91
+ authRouter.post(
92
+ '/register/options',
93
+ limit('ceremony'),
94
+ handle(async (req, res) => {
95
+ const { handle: name, displayName, invite, setup, workspaceName } = req.body || {}
96
+ const allowed = signupAllowed({ invite, setup })
97
+ // Without an invite the account gets a workspace of its own: its name
98
+ // can be picked now (the setup page asks for it).
99
+ let ownWorkspace = null
100
+ if (!allowed.inviteHash && workspaceName !== undefined && workspaceName !== null && workspaceName !== '') {
101
+ ownWorkspace = cleanWorkspaceName(workspaceName)
102
+ if (!ownWorkspace) throw new HttpError(400, 'invalid_name', 'Workspace name: 1 to 80 characters.')
103
+ }
104
+ // Open sign-up (no invite, no setup link) passes the bot check first
105
+ // when the operator configured one. Checked before anything is stored.
106
+ if (
107
+ turnstile &&
108
+ !allowed.inviteHash &&
109
+ !allowed.setupHash &&
110
+ !(await turnstile.verify(req.body?.turnstileToken, clientIp(req), { hostnames: turnstileHosts }))
111
+ )
112
+ throw new HttpError(403, 'turnstile_failed', 'The bot check did not pass. Try again.')
113
+ const { options, ceremony } = await auth.registrationOptions({
114
+ handle: name,
115
+ displayName,
116
+ data: { ...allowed, ...(ownWorkspace ? { workspaceName: ownWorkspace } : {}) },
117
+ })
118
+ setCookie(res, CEREMONY_COOKIE, ceremony, 300)
119
+ res.json({ options })
120
+ }),
121
+ )
122
+
123
+ // Creates the user, their passkey, recovery codes and either joins the
124
+ // invited workspace or creates their own, in one transaction.
125
+ authRouter.post(
126
+ '/register/verify',
127
+ limit('ceremony'),
128
+ handle(async (req, res) => {
129
+ const ip = clientIp(req)
130
+ const { user, extra } = await auth.finishSignUp(ceremonyCookie(req), req.body?.response, (created, data) => {
131
+ let workspaceId
132
+ // Ceremonies started before hashes were kept carry the raw token.
133
+ const inviteHash = data.inviteHash || (data.invite ? sha256(data.invite) : null)
134
+ const setupHash = data.setupHash || (data.setup ? sha256(data.setup) : null)
135
+ if (inviteHash) {
136
+ const invite = findInviteByHash(db, inviteHash)
137
+ if (!inviteUsable(invite, iso())) throw new AuthError(403, 'invalid_invite', 'This invite link is used, expired or revoked.')
138
+ const t = tenant(db, invite.workspace_id)
139
+ acceptInvite(t, invite, created.id, ip)
140
+ workspaceId = invite.workspace_id
141
+ } else {
142
+ if (setupHash) {
143
+ const used = q.run('UPDATE setup_codes SET used_at = :at WHERE code_hash = :hash AND used_at IS NULL AND expires_at > :at', {
144
+ at: iso(),
145
+ hash: setupHash,
146
+ })
147
+ if (!used.changes) throw new AuthError(403, 'invalid_setup', 'This setup link is used or expired.')
148
+ } else if (signup !== 'open') throw new AuthError(403, 'invite_required', 'Sign-up needs an invite link.')
149
+ workspaceId = createWorkspace(created, data.workspaceName || `${created.display_name}'s workspace`, ip)
150
+ }
151
+ auditAccount(db, {
152
+ userId: created.id,
153
+ action: 'account_created',
154
+ ip,
155
+ at: iso(),
156
+ detail: { via: inviteHash ? 'invite' : setupHash ? 'setup' : 'open', device: deviceLabel(req.headers['user-agent']) },
157
+ })
158
+ return { workspaceId, recoveryCodes: auth.newRecoveryCodes(created.id), setup: Boolean(setupHash) }
159
+ })
160
+ // The setup link did its job: its file goes too.
161
+ if (extra.setup) removeSetupLink(dataDir)
162
+ startSession(req, res, user.id)
163
+ res.status(201).json({ user: publicUser(user), workspaceId: extra.workspaceId, recoveryCodes: extra.recoveryCodes })
164
+ }),
165
+ )
166
+
167
+ authRouter.post(
168
+ '/login/options',
169
+ limit('ceremony'),
170
+ handle(async (req, res) => {
171
+ const { options, ceremony } = await ceremonyAuth(req).authenticationOptions()
172
+ setCookie(res, CEREMONY_COOKIE, ceremony, 300)
173
+ res.json({ options })
174
+ }),
175
+ )
176
+ authRouter.post(
177
+ '/login/verify',
178
+ limit('ceremony'),
179
+ handle(async (req, res) => {
180
+ let user
181
+ try {
182
+ user = await ceremonyAuth(req).finishAuthentication(ceremonyCookie(req), req.body?.response)
183
+ } catch (error) {
184
+ auditAccount(db, { action: 'sign_in_failed', ip: clientIp(req), at: iso(), detail: { code: error.code || 'error' } })
185
+ throw error
186
+ }
187
+ const device = deviceLabel(req.headers['user-agent'])
188
+ auditAccount(db, {
189
+ userId: user.id,
190
+ action: 'signed_in',
191
+ ip: clientIp(req),
192
+ at: iso(),
193
+ detail: {
194
+ via: 'passkey',
195
+ device,
196
+ ...(seenDevice(db, user.id, device) ? {} : { newDevice: true }),
197
+ ...(ceremonyAuth(req) === sites.related ? { related: sites.previous.rpId } : {}),
198
+ },
199
+ })
200
+ startSession(req, res, user.id, { verified: user.trusted })
201
+ res.json({ user: publicUser(user) })
202
+ }),
203
+ )
204
+
205
+ authRouter.post(
206
+ '/recovery',
207
+ handle(async (req, res) => {
208
+ const ip = clientIp(req)
209
+ const handleKey = `${String(req.body?.handle || '')
210
+ .toLowerCase()
211
+ .slice(0, 40)}\u0000${ip}`
212
+ // Counted before the check and given back when right, so parallel
213
+ // guesses cannot slip past the limit.
214
+ const tries = rateLimiter.attempt([
215
+ ['recoveryFail', handleKey, LIMITS.recoveryFail],
216
+ ['recoveryFailIp', ip, LIMITS.recoveryFailIp],
217
+ ])
218
+ if (!tries.ok) {
219
+ res.setHeader('Retry-After', String(tries.retryAfter))
220
+ return fail(res, 429, 'rate_limited', 'Too many wrong codes. Wait a while and try again.')
221
+ }
222
+ const user = auth.useRecoveryCode(req.body?.handle, req.body?.code)
223
+ if (user) tries.success()
224
+ if (!user) {
225
+ auditAccount(db, { action: 'recovery_failed', ip, at: iso(), detail: {} })
226
+ throw new AuthError(401, 'bad_code', 'That handle and recovery code do not match an unused code.')
227
+ }
228
+ // Never a fresh session (it can add a passkey and nothing sensitive), and
229
+ // every other session of the account ends: if a device was stolen, its
230
+ // session goes with it.
231
+ const sessionHash = startSession(req, res, user.id, { via: 'recovery' })
232
+ auth.deleteOtherSessions(user.id, sessionHash)
233
+ auditAccount(db, {
234
+ userId: user.id,
235
+ action: 'signed_in',
236
+ ip,
237
+ at: iso(),
238
+ detail: {
239
+ via: 'recovery_code',
240
+ codesLeft: auth.recoveryRemaining(user.id),
241
+ otherSessionsEnded: true,
242
+ device: deviceLabel(req.headers['user-agent']),
243
+ ...(seenDevice(db, user.id, deviceLabel(req.headers['user-agent'])) ? {} : { newDevice: true }),
244
+ },
245
+ })
246
+ res.json({ user: publicUser(user), recoveryCodesLeft: auth.recoveryRemaining(user.id) })
247
+ }),
248
+ )
249
+
250
+ authRouter.post(
251
+ '/logout',
252
+ handle(async (req, res) => {
253
+ const current = sessionOf(req)
254
+ if (current) auth.deleteSession(current.session.hash)
255
+ setCookie(res, SESSION_COOKIE, '', 0)
256
+ res.json({ ok: true })
257
+ }),
258
+ )
259
+
260
+ authRouter.get(
261
+ '/me',
262
+ // Signed out is an answer here, not an error (the console asks on every page).
263
+ (req, res, next) =>
264
+ sessionOf(req)
265
+ ? next()
266
+ : res.json({
267
+ user: null,
268
+ signup,
269
+ rpId: siteOf(req).auth.rpId,
270
+ ...(turnstile && signup === 'open' ? { turnstile: turnstile.siteKey } : {}),
271
+ ...moveInfo(sites, req),
272
+ }),
273
+ needSession,
274
+ handle(async (req, res) => {
275
+ res.json({
276
+ // The host name passkeys are made for here, and a move in progress
277
+ // (moving: on the old origin; movedFrom: on the new one).
278
+ rpId: siteOf(req).auth.rpId,
279
+ ...moveInfo(sites, req),
280
+ user: publicUser(req.user),
281
+ workspaces: workspacesForUser(db, req.user.id).map((item) => ({ id: item.id, name: item.name, role: item.role })),
282
+ passkeys: auth.listPasskeys(req.user.id),
283
+ recoveryCodesLeft: auth.recoveryRemaining(req.user.id),
284
+ fresh: auth.isFresh(req.auth.session),
285
+ viaRecovery: req.auth.session.via === 'recovery',
286
+ securityNotice: securityNoticeFor(req),
287
+ signup,
288
+ })
289
+ }),
290
+ )
291
+
292
+ // A recovery code was used on this account since its owner last looked:
293
+ // told once, on a passkey sign-in (the recovery session has its own banner).
294
+ function securityNoticeFor(req) {
295
+ if (req.auth.session.via === 'recovery') return null
296
+ const seen = auth.getUser(req.user.id)?.security_seen_at || null
297
+ const used = lastRecoverySignIn(db, req.user.id, seen)
298
+ return used ? { kind: 'recovery_code_used', at: used.at, ip: used.ip } : null
299
+ }
300
+ authRouter.post(
301
+ '/security-notice/seen',
302
+ needSession,
303
+ handle(async (req, res) => {
304
+ q.run('UPDATE users SET security_seen_at = :at WHERE id = :id', { at: iso(), id: req.user.id })
305
+ res.json({ ok: true })
306
+ }),
307
+ )
308
+
309
+ // The account's own security log: sign-ins, recovery codes, passkeys,
310
+ // sessions ended, workspaces deleted. 50 a page, newest first.
311
+ authRouter.get(
312
+ '/security-log',
313
+ needSession,
314
+ handle(async (req, res) => {
315
+ const before = Number(req.query?.before)
316
+ const rows = accountEvents(db, req.user.id, {
317
+ before: Number.isSafeInteger(before) && before > 0 ? before : Number.MAX_SAFE_INTEGER,
318
+ limit: 51,
319
+ })
320
+ const page = rows.slice(0, 50)
321
+ res.json({
322
+ events: page.map((row) => {
323
+ let detail = {}
324
+ try {
325
+ detail = JSON.parse(row.detail || '{}') || {}
326
+ } catch {
327
+ detail = {}
328
+ }
329
+ return { id: row.id, action: row.action, at: row.at, ip: row.ip, detail }
330
+ }),
331
+ next: rows.length > 50 ? page[page.length - 1].id : null,
332
+ })
333
+ }),
334
+ )
335
+
336
+ // Deleting the account: needs a fresh passkey check and the handle typed
337
+ // back. Refused while the account is the only owner of a workspace that has
338
+ // other people in it (make someone else an owner first). Workspaces where
339
+ // it is the only member are deleted with it; in the others it leaves (its
340
+ // pending invites, share links and API tokens are revoked). Comments keep
341
+ // the name they were signed with.
342
+ authRouter.post(
343
+ '/delete-account/preview',
344
+ needSession,
345
+ handle(async (req, res) => {
346
+ res.json(accountDeletionPlan(req.user.id))
347
+ }),
348
+ )
349
+ authRouter.delete(
350
+ '/me',
351
+ needSession,
352
+ needFresh,
353
+ handle(async (req, res) => {
354
+ const user = req.user
355
+ if (typeof req.body?.confirm !== 'string' || req.body.confirm.trim().replace(/^@/, '').toLowerCase() !== user.handle)
356
+ throw new HttpError(400, 'confirm_handle', 'Type your handle exactly to delete your account.')
357
+ const ip = clientIp(req)
358
+ // The plan is made inside the transaction that carries it out, so a
359
+ // member joining or an owner leaving in between cannot change it.
360
+ const { plan, removeFiles } = transaction(db, () => {
361
+ const plan = accountDeletionPlan(user.id)
362
+ if (plan.blocked.length)
363
+ throw new HttpError(
364
+ 409,
365
+ 'sole_owner',
366
+ `You are the only owner of ${plan.blocked.map((item) => item.name).join(', ')}. Make someone else an owner there first.`,
367
+ )
368
+ const removeFiles = plan.deleted.map((item) => deleteWorkspaceRows(tenant(db, item.id), dataDir))
369
+ for (const item of plan.left) {
370
+ const t = tenant(db, item.id)
371
+ t.run('DELETE FROM memberships WHERE workspace_id = :ws AND user_id = :user', { user: user.id })
372
+ auditOf(req, 'member_left', user.id, { role: item.role, accountDeleted: true }, t)
373
+ // Always: the account is gone, and so is every token it made.
374
+ revokeGrantsOf(req, user.id, null, { revokeTokens: true, t })
375
+ }
376
+ deleteAccountEvents(db, user.id)
377
+ q.run('DELETE FROM users WHERE id = :id', { id: user.id })
378
+ auditAccount(db, {
379
+ action: 'account_deleted',
380
+ ip,
381
+ at: iso(),
382
+ detail: { workspacesDeleted: plan.deleted.length, workspacesLeft: plan.left.length },
383
+ })
384
+ return { plan, removeFiles }
385
+ })
386
+ for (const remove of removeFiles) remove()
387
+ setCookie(res, SESSION_COOKIE, '', 0)
388
+ res.json({ ok: true, deleted: plan.deleted.length, left: plan.left.length })
389
+ }),
390
+ )
391
+
392
+ function accountDeletionPlan(userId) {
393
+ const plan = { deleted: [], left: [], blocked: [] }
394
+ for (const item of workspacesForUser(db, userId)) {
395
+ const t = tenant(db, item.id)
396
+ const members = t.get('SELECT COUNT(*) AS n FROM memberships WHERE workspace_id = :ws').n
397
+ const entry = { id: item.id, name: item.name, role: item.role, members }
398
+ if (members <= 1) plan.deleted.push(entry)
399
+ else if (item.role === 'owner' && ownerCount(t) <= 1) plan.blocked.push(entry)
400
+ else plan.left.push(entry)
401
+ }
402
+ return plan
403
+ }
404
+ authRouter.patch(
405
+ '/me',
406
+ needSession,
407
+ handle(async (req, res) => {
408
+ const name = cleanDisplayName(req.body?.displayName)
409
+ q.run('UPDATE users SET display_name = :name WHERE id = :id', { name, id: req.user.id })
410
+ res.json({ user: publicUser(auth.getUser(req.user.id)) })
411
+ }),
412
+ )
413
+
414
+ // Re-auth: a passkey check that makes the session fresh for sensitive actions.
415
+ authRouter.post(
416
+ '/reauth/options',
417
+ limit('ceremony'),
418
+ needSession,
419
+ handle(async (req, res) => {
420
+ const { options, ceremony } = await ceremonyAuth(req).authenticationOptions({ userId: req.user.id })
421
+ setCookie(res, CEREMONY_COOKIE, ceremony, 300)
422
+ res.json({ options })
423
+ }),
424
+ )
425
+ authRouter.post(
426
+ '/reauth/verify',
427
+ limit('ceremony'),
428
+ needSession,
429
+ handle(async (req, res) => {
430
+ const checked = await ceremonyAuth(req).finishAuthentication(ceremonyCookie(req), req.body?.response, { userId: req.user.id })
431
+ setCookie(res, CEREMONY_COOKIE, '', 0)
432
+ if (!checked.trusted) {
433
+ throw new AuthError(
434
+ 403,
435
+ 'passkey_on_hold',
436
+ 'This passkey was added with a recovery code; it can confirm this 24 hours after it was added. Use another passkey.',
437
+ )
438
+ }
439
+ if (req.auth.session.via !== 'passkey') {
440
+ // A recovery session becomes a passkey session once a trusted passkey confirms it.
441
+ q.run("UPDATE sessions SET via = 'passkey' WHERE token_hash = :hash", { hash: req.auth.session.hash })
442
+ }
443
+ auth.markVerified(req.auth.session.hash)
444
+ res.json({ ok: true })
445
+ }),
446
+ )
447
+
448
+ authRouter.post(
449
+ '/passkeys/options',
450
+ limit('ceremony'),
451
+ needSession,
452
+ needFreshOrRecovery,
453
+ handle(async (req, res) => {
454
+ const { options, ceremony } = await auth.registrationOptions({ userId: req.user.id })
455
+ setCookie(res, CEREMONY_COOKIE, ceremony, 300)
456
+ res.json({ options })
457
+ }),
458
+ )
459
+ authRouter.post(
460
+ '/passkeys/verify',
461
+ limit('ceremony'),
462
+ needSession,
463
+ needFreshOrRecovery,
464
+ handle(async (req, res) => {
465
+ const viaRecovery = !auth.isFresh(req.auth.session)
466
+ const { id } = await auth.finishAddPasskey(ceremonyCookie(req), req.body?.response, req.user.id, req.body?.nickname, { viaRecovery })
467
+ auditAccount(db, { userId: req.user.id, action: 'passkey_added', ip: clientIp(req), at: iso(), detail: { viaRecovery } })
468
+ setCookie(res, CEREMONY_COOKIE, '', 0)
469
+ res.status(201).json({ id, passkeys: auth.listPasskeys(req.user.id) })
470
+ }),
471
+ )
472
+ authRouter.patch(
473
+ '/passkeys/:id',
474
+ needSession,
475
+ handle(async (req, res) => {
476
+ auth.renamePasskey(req.user.id, req.params.id, req.body?.nickname)
477
+ res.json({ passkeys: auth.listPasskeys(req.user.id) })
478
+ }),
479
+ )
480
+ authRouter.delete(
481
+ '/passkeys/:id',
482
+ needSession,
483
+ needFresh,
484
+ handle(async (req, res) => {
485
+ auth.removePasskey(req.user.id, req.params.id)
486
+ // A session signed in with that passkey must not outlive it.
487
+ auth.deleteOtherSessions(req.user.id, req.auth.session.hash)
488
+ auditAccount(db, {
489
+ userId: req.user.id,
490
+ action: 'passkey_removed',
491
+ ip: clientIp(req),
492
+ at: iso(),
493
+ detail: { otherSessionsEnded: true },
494
+ })
495
+ res.json({ passkeys: auth.listPasskeys(req.user.id) })
496
+ }),
497
+ )
498
+ authRouter.post(
499
+ '/recovery-codes',
500
+ needSession,
501
+ needFresh,
502
+ handle(async (req, res) => {
503
+ const codes = auth.newRecoveryCodes(req.user.id)
504
+ auditAccount(db, { userId: req.user.id, action: 'recovery_codes_created', ip: clientIp(req), at: iso(), detail: {} })
505
+ res.json({ recoveryCodes: codes })
506
+ }),
507
+ )
508
+ authRouter.post(
509
+ '/sessions/revoke-others',
510
+ needSession,
511
+ needFresh,
512
+ handle(async (req, res) => {
513
+ auth.deleteOtherSessions(req.user.id, req.auth.session.hash)
514
+ auditAccount(db, { userId: req.user.id, action: 'sessions_revoked', ip: clientIp(req), at: iso(), detail: {} })
515
+ res.json({ ok: true, sessions: auth.listSessions(req.user.id, req.auth.session.hash) })
516
+ }),
517
+ )
518
+ // The account's sessions (devices), and ending one of them.
519
+ authRouter.get(
520
+ '/sessions',
521
+ needSession,
522
+ handle(async (req, res) => {
523
+ res.json({ sessions: auth.listSessions(req.user.id, req.auth.session.hash) })
524
+ }),
525
+ )
526
+ authRouter.delete(
527
+ '/sessions/:id',
528
+ needSession,
529
+ needFresh,
530
+ handle(async (req, res) => {
531
+ const id = String(req.params.id)
532
+ if (!SESSION_ID_RE.test(id)) throw new AuthError(404, 'unknown_session', 'No such session.')
533
+ auth.deleteSessionById(req.user.id, id, req.auth.session.hash)
534
+ auditAccount(db, { userId: req.user.id, action: 'session_revoked', target: id, ip: clientIp(req), at: iso(), detail: {} })
535
+ res.json({ sessions: auth.listSessions(req.user.id, req.auth.session.hash) })
536
+ }),
537
+ )
538
+
539
+ return { startSession, ceremonyCookie }
540
+ }