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,536 @@
1
+ // Accounts for the hosted server: passkeys (WebAuthn through
2
+ // @simplewebauthn/server), one-time recovery codes, and sessions. No email
3
+ // and no passwords.
4
+ //
5
+ // - Registration and sign-in use discoverable credentials with user
6
+ // verification required, so there is no username to type.
7
+ // - Each ceremony's challenge is stored server-side (hashed key in a short
8
+ // cookie), lives 5 minutes and is deleted on the first attempt to use it.
9
+ // - Sessions are 32 random bytes; only the SHA-256 is stored. 30 days,
10
+ // sliding, never more than 90 days in all. `verified_at` records the last
11
+ // passkey check, for actions that need a fresh one (re-auth).
12
+ // - A recovery code signs in, but the session is never fresh: it can add a
13
+ // passkey (for 30 minutes) and nothing sensitive. A passkey added that way
14
+ // is on hold for 24 hours: it signs in, but cannot confirm sensitive
15
+ // actions (new recovery codes, removing passkeys, ending other sessions,
16
+ // tokens, owners) until the hold ends. Someone holding only a stolen code
17
+ // cannot lock the owner out; the owner's own passkey still can.
18
+ // - The signature counter is checked by the library only when the
19
+ // authenticator uses one; synced passkeys report 0 and pass.
20
+
21
+ import {
22
+ generateAuthenticationOptions,
23
+ generateRegistrationOptions,
24
+ verifyAuthenticationResponse,
25
+ verifyRegistrationResponse,
26
+ } from '@simplewebauthn/server'
27
+ import { newId, newRecoveryCode, normalizeRecoveryCode, randomToken, sha256 } from './crypto.js'
28
+ import { transaction } from './db.js'
29
+ import { accounts } from './tenancy.js'
30
+
31
+ export const HANDLE_RE = /^[a-z][a-z0-9-]{2,31}$/
32
+ export const SESSION_DAYS = 30
33
+ export const SESSION_MAX_DAYS = 90
34
+ export const REAUTH_MS = 10 * 60_000
35
+ export const RECOVERY_ADD_MS = 30 * 60_000
36
+ export const RECOVERY_HOLD_MS = 24 * 3_600_000
37
+ // Admin and owner sessions: console admin pages need a request in the last
38
+ // 12 hours (or a fresh passkey check) to keep working.
39
+ export const ADMIN_IDLE_MS = 12 * 3_600_000
40
+ const NEVER_VERIFIED = new Date(0).toISOString()
41
+ export const CEREMONY_MS = 5 * 60_000
42
+ export const RECOVERY_CODE_COUNT = 10
43
+ export const PASSKEYS_MAX = 20
44
+ const DAY = 86_400_000
45
+
46
+ export class AuthError extends Error {
47
+ constructor(status, code, message) {
48
+ super(message)
49
+ this.statusCode = status
50
+ this.code = code
51
+ }
52
+ }
53
+
54
+ // eslint-disable-next-line no-control-regex
55
+ const CONTROL_RE = /[\u0000-\u001f\u007f]/g
56
+
57
+ export function cleanDisplayName(value) {
58
+ const name = typeof value === 'string' ? value.replace(CONTROL_RE, '').replace(/\s+/g, ' ').trim() : ''
59
+ if (!name || name.length > 60) throw new AuthError(400, 'invalid_name', 'Your name: 1 to 60 characters.')
60
+ return name
61
+ }
62
+
63
+ // "Chrome on macOS" from a User-Agent header, for the session list. Only the
64
+ // label is stored.
65
+ export function deviceLabel(userAgent) {
66
+ const ua = String(userAgent || '').slice(0, 512)
67
+ if (!ua) return null
68
+ const browser = /Edg\//.test(ua)
69
+ ? 'Edge'
70
+ : /OPR\//.test(ua)
71
+ ? 'Opera'
72
+ : /Firefox\//.test(ua)
73
+ ? 'Firefox'
74
+ : /Chrome\/|CriOS\//.test(ua)
75
+ ? 'Chrome'
76
+ : /Safari\//.test(ua)
77
+ ? 'Safari'
78
+ : null
79
+ const os = /iPhone|iPad|iPod/.test(ua)
80
+ ? 'iOS'
81
+ : /Android/.test(ua)
82
+ ? 'Android'
83
+ : /Mac OS X|Macintosh/.test(ua)
84
+ ? 'macOS'
85
+ : /Windows/.test(ua)
86
+ ? 'Windows'
87
+ : /CrOS/.test(ua)
88
+ ? 'ChromeOS'
89
+ : /Linux/.test(ua)
90
+ ? 'Linux'
91
+ : null
92
+ if (!browser && !os) return 'Unknown device'
93
+ return [browser || 'Browser', os].filter(Boolean).join(' on ')
94
+ }
95
+
96
+ export function cleanHandle(value) {
97
+ const handle = typeof value === 'string' ? value.trim().toLowerCase() : ''
98
+ if (!HANDLE_RE.test(handle))
99
+ throw new AuthError(400, 'invalid_handle', 'Handle: 3 to 32 lowercase letters, digits and dashes, starting with a letter.')
100
+ return handle
101
+ }
102
+
103
+ const parseTransports = (value) => {
104
+ try {
105
+ const list = JSON.parse(value || '[]')
106
+ return Array.isArray(list) ? list.filter((item) => typeof item === 'string').slice(0, 8) : []
107
+ } catch {
108
+ return []
109
+ }
110
+ }
111
+
112
+ // `tag` keeps the ceremonies of a second relying party apart (a server
113
+ // moving to a new origin verifies old passkeys with the old RP ID; see
114
+ // src/hosted/rebind.js): a challenge made by one is never accepted by another.
115
+ export function createAuth({ db, origin, rpId, rpName = 'Shapewall', now = () => new Date(), tag = '' }) {
116
+ const q = accounts(db)
117
+ const iso = (offsetMs = 0) => new Date(now().getTime() + offsetMs).toISOString()
118
+
119
+ // ---- Ceremonies ----
120
+
121
+ function saveChallenge(kind, challenge, { userId = null, data = {} } = {}) {
122
+ kind = `${tag}${kind}`
123
+ const token = randomToken(32)
124
+ q.run('DELETE FROM challenges WHERE expires_at <= :now', { now: iso() })
125
+ q.run(
126
+ 'INSERT INTO challenges (token_hash, kind, challenge, user_id, data, expires_at) VALUES (:hash, :kind, :challenge, :user, :data, :expires)',
127
+ {
128
+ hash: sha256(token),
129
+ kind,
130
+ challenge,
131
+ user: userId,
132
+ data: JSON.stringify(data),
133
+ expires: iso(CEREMONY_MS),
134
+ },
135
+ )
136
+ return token
137
+ }
138
+
139
+ // Single use: deleted whether or not the response verifies.
140
+ function takeChallenge(token, kind) {
141
+ if (typeof token !== 'string' || token.length < 20 || token.length > 100)
142
+ throw new AuthError(400, 'no_ceremony', 'Start again: the sign-in request expired.')
143
+ const hash = sha256(token)
144
+ const row = q.get('SELECT * FROM challenges WHERE token_hash = :hash', { hash })
145
+ q.run('DELETE FROM challenges WHERE token_hash = :hash', { hash })
146
+ if (!row || row.kind !== `${tag}${kind}` || row.expires_at <= iso())
147
+ throw new AuthError(400, 'no_ceremony', 'Start again: the sign-in request expired.')
148
+ return { ...row, data: JSON.parse(row.data || '{}') }
149
+ }
150
+
151
+ function passkeysOf(userId) {
152
+ return q.all('SELECT * FROM passkeys WHERE user_id = :user ORDER BY created_at', { user: userId })
153
+ }
154
+
155
+ // New account (no userId) or another passkey for a signed-in user.
156
+ async function registrationOptions({ handle, displayName, userId = null, data = {} }) {
157
+ let user = null
158
+ if (userId) {
159
+ user = q.get('SELECT * FROM users WHERE id = :id', { id: userId })
160
+ if (!user) throw new AuthError(401, 'signed_out', 'Sign in first.')
161
+ if (passkeysOf(user.id).length >= PASSKEYS_MAX) throw new AuthError(409, 'too_many_passkeys', `At most ${PASSKEYS_MAX} passkeys.`)
162
+ } else {
163
+ handle = cleanHandle(handle)
164
+ displayName = cleanDisplayName(displayName)
165
+ if (q.get('SELECT id FROM users WHERE handle = :handle', { handle }))
166
+ throw new AuthError(409, 'handle_taken', 'That handle is taken.')
167
+ }
168
+ const webauthnUserId = user ? user.webauthn_user_id : randomToken(32)
169
+ const options = await generateRegistrationOptions({
170
+ rpName,
171
+ rpID: rpId,
172
+ userName: user ? user.handle : handle,
173
+ userDisplayName: user ? user.display_name : displayName,
174
+ userID: Buffer.from(webauthnUserId, 'base64url'),
175
+ attestationType: 'none',
176
+ excludeCredentials: user ? passkeysOf(user.id).map((key) => ({ id: key.id, transports: parseTransports(key.transports) })) : [],
177
+ authenticatorSelection: { residentKey: 'required', userVerification: 'required' },
178
+ timeout: CEREMONY_MS,
179
+ })
180
+ const ceremony = saveChallenge('register', options.challenge, {
181
+ userId: user?.id || null,
182
+ data: { ...data, handle: user ? null : handle, displayName: user ? null : displayName, webauthnUserId },
183
+ })
184
+ return { options, ceremony }
185
+ }
186
+
187
+ async function verifyRegistration(ceremony, response) {
188
+ const row = takeChallenge(ceremony, 'register')
189
+ let verification
190
+ try {
191
+ verification = await verifyRegistrationResponse({
192
+ response,
193
+ expectedChallenge: row.challenge,
194
+ expectedOrigin: origin,
195
+ expectedRPID: rpId,
196
+ requireUserVerification: true,
197
+ })
198
+ } catch {
199
+ throw new AuthError(400, 'passkey_failed', 'The passkey could not be verified. Try again.')
200
+ }
201
+ if (!verification.verified) throw new AuthError(400, 'passkey_failed', 'The passkey could not be verified. Try again.')
202
+ const info = verification.registrationInfo
203
+ return { row, info }
204
+ }
205
+
206
+ function storePasskey(userId, info, nickname = '', { viaRecovery = false } = {}) {
207
+ if (q.get('SELECT id FROM passkeys WHERE id = :id', { id: info.credential.id })) {
208
+ throw new AuthError(409, 'passkey_exists', 'That passkey is already registered.')
209
+ }
210
+ q.run(
211
+ `INSERT INTO passkeys (id, user_id, public_key, counter, transports, device_type, backed_up, nickname, created_at, recovery_added_at, rp_id)
212
+ VALUES (:id, :user, :key, :counter, :transports, :device, :backed, :nickname, :at, :recovery, :rp)`,
213
+ {
214
+ id: info.credential.id,
215
+ user: userId,
216
+ key: Buffer.from(info.credential.publicKey),
217
+ counter: info.credential.counter || 0,
218
+ transports: JSON.stringify(info.credential.transports || []),
219
+ device: info.credentialDeviceType || null,
220
+ backed: info.credentialBackedUp ? 1 : 0,
221
+ nickname: String(nickname || '').slice(0, 60),
222
+ at: iso(),
223
+ recovery: viaRecovery ? iso() : null,
224
+ rp: rpId,
225
+ },
226
+ )
227
+ }
228
+
229
+ // Creates the account with its first passkey. `onCreate(user)` runs in the
230
+ // same transaction (workspace, invite), so a failure there leaves nothing.
231
+ async function finishSignUp(ceremony, response, onCreate = () => {}) {
232
+ const { row, info } = await verifyRegistration(ceremony, response)
233
+ if (row.user_id) throw new AuthError(400, 'no_ceremony', 'Start again: the sign-in request expired.')
234
+ return transaction(db, () => {
235
+ const { handle, displayName, webauthnUserId } = row.data
236
+ if (q.get('SELECT id FROM users WHERE handle = :handle', { handle }))
237
+ throw new AuthError(409, 'handle_taken', 'That handle is taken.')
238
+ const user = { id: newId('us'), handle, display_name: displayName, webauthn_user_id: webauthnUserId, created_at: iso() }
239
+ q.run('INSERT INTO users (id, handle, display_name, webauthn_user_id, created_at) VALUES (:id, :handle, :name, :webauthn, :at)', {
240
+ id: user.id,
241
+ handle,
242
+ name: displayName,
243
+ webauthn: webauthnUserId,
244
+ at: user.created_at,
245
+ })
246
+ storePasskey(user.id, info, 'First passkey')
247
+ const extra = onCreate(user, row.data)
248
+ return { user, extra }
249
+ })
250
+ }
251
+
252
+ // `userId` null: the user the ceremony was started for (a rebind, which has
253
+ // no session yet). `check(row)` runs in the same transaction before the
254
+ // passkey is stored and may return { viaRecovery } (a rebind consumes its
255
+ // token there, so a token is used at most once).
256
+ async function finishAddPasskey(ceremony, response, userId, nickname, { viaRecovery = false, check = null } = {}) {
257
+ const { row, info } = await verifyRegistration(ceremony, response)
258
+ if (!row.user_id || (userId !== null && row.user_id !== userId))
259
+ throw new AuthError(400, 'no_ceremony', 'Start again: the sign-in request expired.')
260
+ transaction(db, () => {
261
+ const extra = check ? check(row) || {} : {}
262
+ storePasskey(row.user_id, info, nickname, { viaRecovery: extra.viaRecovery ?? viaRecovery })
263
+ })
264
+ return { id: info.credential.id, userId: row.user_id, data: row.data }
265
+ }
266
+
267
+ // Sign-in (no userId: any discoverable passkey) or re-auth (userId: one of theirs).
268
+ async function authenticationOptions({ userId = null } = {}) {
269
+ const options = await generateAuthenticationOptions({
270
+ rpID: rpId,
271
+ userVerification: 'required',
272
+ timeout: CEREMONY_MS,
273
+ allowCredentials: userId ? passkeysOf(userId).map((key) => ({ id: key.id, transports: parseTransports(key.transports) })) : [],
274
+ })
275
+ const ceremony = saveChallenge(userId ? 'reauth' : 'login', options.challenge, { userId })
276
+ return { options, ceremony }
277
+ }
278
+
279
+ async function finishAuthentication(ceremony, response, { userId = null } = {}) {
280
+ const row = takeChallenge(ceremony, userId ? 'reauth' : 'login')
281
+ if (userId && row.user_id !== userId) throw new AuthError(400, 'no_ceremony', 'Start again: the sign-in request expired.')
282
+ const fail = () => new AuthError(401, 'passkey_failed', 'That passkey is not registered here, or it could not be verified.')
283
+ const credentialId = typeof response?.id === 'string' ? response.id : ''
284
+ const key = credentialId ? q.get('SELECT * FROM passkeys WHERE id = :id', { id: credentialId }) : null
285
+ if (!key || (userId && key.user_id !== userId)) throw fail()
286
+ const user = q.get('SELECT * FROM users WHERE id = :id', { id: key.user_id })
287
+ if (!user) throw fail()
288
+ // A discoverable credential returns the user handle: it must be this user's.
289
+ const userHandle = response?.response?.userHandle
290
+ if (userHandle && userHandle !== user.webauthn_user_id) throw fail()
291
+ let verification
292
+ try {
293
+ verification = await verifyAuthenticationResponse({
294
+ response,
295
+ expectedChallenge: row.challenge,
296
+ expectedOrigin: origin,
297
+ expectedRPID: rpId,
298
+ requireUserVerification: true,
299
+ credential: {
300
+ id: key.id,
301
+ publicKey: new Uint8Array(key.public_key),
302
+ counter: key.counter,
303
+ transports: parseTransports(key.transports),
304
+ },
305
+ })
306
+ } catch {
307
+ throw fail()
308
+ }
309
+ if (!verification.verified) throw fail()
310
+ // rp_id: which host name the passkey belongs to (known once it signs in
311
+ // here; set at registration since migration 5).
312
+ q.run('UPDATE passkeys SET counter = :counter, last_used_at = :at, backed_up = :backed, rp_id = COALESCE(rp_id, :rp) WHERE id = :id', {
313
+ counter: verification.authenticationInfo.newCounter || 0,
314
+ at: iso(),
315
+ backed: verification.authenticationInfo.credentialBackedUp ? 1 : 0,
316
+ rp: rpId,
317
+ id: key.id,
318
+ })
319
+ // `trusted`: this passkey may confirm sensitive actions (not on hold).
320
+ return { ...user, trusted: !onHold(key), passkeyId: key.id }
321
+ }
322
+
323
+ const onHold = (key) => Boolean(key.recovery_added_at) && now().getTime() - Date.parse(key.recovery_added_at) < RECOVERY_HOLD_MS
324
+
325
+ // ---- Passkey management ----
326
+
327
+ function listPasskeys(userId) {
328
+ return passkeysOf(userId).map((key) => ({
329
+ id: key.id,
330
+ nickname: key.nickname,
331
+ createdAt: key.created_at,
332
+ lastUsedAt: key.last_used_at,
333
+ // synced: backed up to a cloud keychain or password manager (BS flag);
334
+ // deviceType 'multiDevice' may sync, 'singleDevice' never leaves this
335
+ // authenticator ("this device only").
336
+ synced: Boolean(key.backed_up),
337
+ deviceType: key.device_type,
338
+ storage: key.backed_up ? 'synced' : key.device_type === 'singleDevice' ? 'device' : 'unsynced',
339
+ transports: parseTransports(key.transports),
340
+ rpId: key.rp_id || null,
341
+ // Added with a recovery code: cannot confirm sensitive actions until then.
342
+ onHoldUntil: onHold(key) ? new Date(Date.parse(key.recovery_added_at) + RECOVERY_HOLD_MS).toISOString() : null,
343
+ }))
344
+ }
345
+
346
+ function renamePasskey(userId, id, nickname) {
347
+ const name = String(nickname || '')
348
+ .replace(/\s+/g, ' ')
349
+ .trim()
350
+ .slice(0, 60)
351
+ const result = q.run('UPDATE passkeys SET nickname = :name WHERE id = :id AND user_id = :user', { name, id: String(id), user: userId })
352
+ if (!result.changes) throw new AuthError(404, 'unknown_passkey', 'No such passkey.')
353
+ }
354
+
355
+ // The last passkey goes only when unused recovery codes remain.
356
+ function removePasskey(userId, id) {
357
+ return transaction(db, () => {
358
+ const keys = passkeysOf(userId)
359
+ if (!keys.some((key) => key.id === id)) throw new AuthError(404, 'unknown_passkey', 'No such passkey.')
360
+ if (keys.length === 1 && !recoveryRemaining(userId)) {
361
+ throw new AuthError(
362
+ 409,
363
+ 'last_passkey',
364
+ 'This is your only passkey and you have no recovery codes left. Add another passkey first.',
365
+ )
366
+ }
367
+ q.run('DELETE FROM passkeys WHERE id = :id AND user_id = :user', { id, user: userId })
368
+ })
369
+ }
370
+
371
+ // ---- Recovery codes ----
372
+
373
+ function newRecoveryCodes(userId) {
374
+ return transaction(db, () => {
375
+ q.run('DELETE FROM recovery_codes WHERE user_id = :user', { user: userId })
376
+ const codes = []
377
+ for (let index = 0; index < RECOVERY_CODE_COUNT; index += 1) {
378
+ const code = newRecoveryCode()
379
+ codes.push(code)
380
+ q.run('INSERT INTO recovery_codes (user_id, code_hash, created_at) VALUES (:user, :hash, :at)', {
381
+ user: userId,
382
+ hash: sha256(normalizeRecoveryCode(code)),
383
+ at: iso(),
384
+ })
385
+ }
386
+ return codes
387
+ })
388
+ }
389
+
390
+ function recoveryRemaining(userId) {
391
+ return q.get('SELECT COUNT(*) AS n FROM recovery_codes WHERE user_id = :user AND used_at IS NULL', { user: userId }).n
392
+ }
393
+
394
+ // Signs in with a code (used once). Returns the user or null. Codes are
395
+ // looked up by hash, then checked against the handle, so a code of another
396
+ // account reads the same as a wrong one.
397
+ function useRecoveryCode(handle, code) {
398
+ const normalized = normalizeRecoveryCode(code)
399
+ if (normalized.length !== 26 || !HANDLE_RE.test(String(handle || '').toLowerCase())) return null
400
+ return transaction(db, () => {
401
+ const row = q.get(
402
+ 'SELECT r.id, r.user_id FROM recovery_codes r JOIN users u ON u.id = r.user_id WHERE r.code_hash = :hash AND u.handle = :handle AND r.used_at IS NULL',
403
+ { hash: sha256(normalized), handle: String(handle).toLowerCase() },
404
+ )
405
+ if (!row) return null
406
+ q.run('UPDATE recovery_codes SET used_at = :at WHERE id = :id', { at: iso(), id: row.id })
407
+ return q.get('SELECT * FROM users WHERE id = :id', { id: row.user_id })
408
+ })
409
+ }
410
+
411
+ // ---- Sessions ----
412
+
413
+ // `verified`: the sign-in counts as a fresh passkey check. `via`: passkey
414
+ // or recovery (a recovery session is never fresh). `device` is a short
415
+ // label from the User-Agent ("Chrome on macOS"), never the raw header.
416
+ function createSession(userId, { verified = true, via = 'passkey', device = null, ip = null } = {}) {
417
+ const token = randomToken(32)
418
+ q.run(
419
+ `INSERT INTO sessions (token_hash, id, user_id, created_at, last_seen_at, expires_at, verified_at, via, user_agent, ip)
420
+ VALUES (:hash, :id, :user, :at, :at, :expires, :verified, :via, :device, :ip)`,
421
+ {
422
+ hash: sha256(token),
423
+ id: newId('se'),
424
+ user: userId,
425
+ at: iso(),
426
+ expires: iso(SESSION_DAYS * DAY),
427
+ verified: verified && via === 'passkey' ? iso() : NEVER_VERIFIED,
428
+ via,
429
+ device: device ? String(device).slice(0, 80) : null,
430
+ ip: ip ? String(ip).slice(0, 64) : null,
431
+ },
432
+ )
433
+ return token
434
+ }
435
+
436
+ // The account's live sessions for the Account page: ids, never hashes.
437
+ function listSessions(userId, currentHash) {
438
+ return q
439
+ .all('SELECT * FROM sessions WHERE user_id = :user AND expires_at > :now ORDER BY last_seen_at DESC', { user: userId, now: iso() })
440
+ .filter((row) => Date.parse(row.created_at) + SESSION_MAX_DAYS * DAY > now().getTime())
441
+ .map((row) => ({
442
+ id: row.id,
443
+ current: row.token_hash === currentHash,
444
+ createdAt: row.created_at,
445
+ lastSeenAt: row.last_seen_at,
446
+ expiresAt: row.expires_at,
447
+ via: row.via,
448
+ device: row.user_agent || null,
449
+ ip: row.ip || null,
450
+ }))
451
+ }
452
+
453
+ // Ends one session of this user by its id (not the current one: that is sign-out).
454
+ function deleteSessionById(userId, id, currentHash) {
455
+ const row = q.get('SELECT token_hash FROM sessions WHERE id = :id AND user_id = :user', { id: String(id), user: userId })
456
+ if (!row) throw new AuthError(404, 'unknown_session', 'No such session.')
457
+ if (row.token_hash === currentHash) throw new AuthError(409, 'current_session', 'That is this session. Use Sign out instead.')
458
+ q.run('DELETE FROM sessions WHERE token_hash = :hash', { hash: row.token_hash })
459
+ }
460
+
461
+ // { user, session } for a live session token, sliding its expiry (written
462
+ // at most once an hour).
463
+ function readSession(token) {
464
+ if (typeof token !== 'string' || token.length < 20 || token.length > 100) return null
465
+ const hash = sha256(token)
466
+ const session = q.get('SELECT * FROM sessions WHERE token_hash = :hash', { hash })
467
+ if (!session) return null
468
+ if (session.expires_at <= iso() || Date.parse(session.created_at) + SESSION_MAX_DAYS * DAY <= now().getTime()) {
469
+ q.run('DELETE FROM sessions WHERE token_hash = :hash', { hash })
470
+ return null
471
+ }
472
+ const user = q.get('SELECT * FROM users WHERE id = :id', { id: session.user_id })
473
+ if (!user) return null
474
+ if (now().getTime() - Date.parse(session.last_seen_at) > 3_600_000) {
475
+ const cap = Date.parse(session.created_at) + SESSION_MAX_DAYS * DAY
476
+ q.run('UPDATE sessions SET last_seen_at = :at, expires_at = :expires WHERE token_hash = :hash', {
477
+ at: iso(),
478
+ expires: new Date(Math.min(now().getTime() + SESSION_DAYS * DAY, cap)).toISOString(),
479
+ hash,
480
+ })
481
+ }
482
+ return { user, session: { ...session, hash } }
483
+ }
484
+
485
+ const markVerified = (sessionHash) =>
486
+ q.run('UPDATE sessions SET verified_at = :at, admin_seen_at = :at WHERE token_hash = :hash', { at: iso(), hash: sessionHash })
487
+ // Admin idle expiry: the last admin request (or passkey check, or the
488
+ // sign-in itself) more than ADMIN_IDLE_MS ago.
489
+ const lastAdminSeen = (session) =>
490
+ Math.max(
491
+ ...[session.admin_seen_at, session.via === 'passkey' ? session.verified_at : null, session.created_at]
492
+ .filter(Boolean)
493
+ .map((value) => Date.parse(value)),
494
+ )
495
+ const adminIdleExpired = (session) => now().getTime() - lastAdminSeen(session) > ADMIN_IDLE_MS
496
+ // Written at most once a minute.
497
+ const touchAdmin = (session) => {
498
+ if (now().getTime() - lastAdminSeen(session) < 60_000) return
499
+ q.run('UPDATE sessions SET admin_seen_at = :at WHERE token_hash = :hash', { at: iso(), hash: session.hash })
500
+ }
501
+ const isFresh = (session) => session.via === 'passkey' && now().getTime() - Date.parse(session.verified_at) <= REAUTH_MS
502
+ // A recovery session may add a passkey for a short while after signing in.
503
+ const canAddAfterRecovery = (session) => session.via === 'recovery' && now().getTime() - Date.parse(session.created_at) <= RECOVERY_ADD_MS
504
+ const deleteSession = (sessionHash) => q.run('DELETE FROM sessions WHERE token_hash = :hash', { hash: sessionHash })
505
+ const deleteOtherSessions = (userId, keepHash) =>
506
+ q.run('DELETE FROM sessions WHERE user_id = :user AND token_hash != :keep', { user: userId, keep: keepHash })
507
+
508
+ return {
509
+ registrationOptions,
510
+ finishSignUp,
511
+ finishAddPasskey,
512
+ authenticationOptions,
513
+ finishAuthentication,
514
+ listPasskeys,
515
+ renamePasskey,
516
+ removePasskey,
517
+ newRecoveryCodes,
518
+ recoveryRemaining,
519
+ useRecoveryCode,
520
+ createSession,
521
+ listSessions,
522
+ deleteSessionById,
523
+ readSession,
524
+ markVerified,
525
+ adminIdleExpired,
526
+ touchAdmin,
527
+ isFresh,
528
+ canAddAfterRecovery,
529
+ deleteSession,
530
+ deleteOtherSessions,
531
+ userCount: () => q.get('SELECT COUNT(*) AS n FROM users').n,
532
+ getUser: (id) => q.get('SELECT * FROM users WHERE id = :id', { id }),
533
+ rpId,
534
+ origin,
535
+ }
536
+ }