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,372 @@
1
+ // Transient board awareness, never a shared document. The server owns every
2
+ // awareness id and identity; clients submit only bounded display coordinates.
3
+ import { randomInt } from 'node:crypto'
4
+ import { WebSocketServer, WebSocket } from 'ws'
5
+ import { Doc } from 'yjs'
6
+ import { Awareness, encodeAwarenessUpdate } from 'y-protocols/awareness.js'
7
+ import { cleanDisplayName } from './auth.js'
8
+ import { readGuest } from './shares.js'
9
+ import { PUBLIC_ID_RE, readPublic } from './public.js'
10
+ import { createProjectStore } from './projects.js'
11
+ import { roleIn, tenant } from './tenancy.js'
12
+ import { guestCookieName, sessionCookieName } from './cookies.js'
13
+ import { ID_PATTERNS, SHARE_ID_RE } from './crypto.js'
14
+ import { ID_RE } from '../config.js'
15
+
16
+ export const PRESENCE_PROTOCOL = 'shapewall-presence-v1'
17
+ export const PRESENCE_LIMITS = {
18
+ messages: 30,
19
+ bytes: 1024,
20
+ connections: 50,
21
+ // One workspace or one address cannot take every slot on the server.
22
+ workspaceConnections: 100,
23
+ ipConnections: 50,
24
+ globalConnections: 500,
25
+ idleMs: 60000,
26
+ pingMs: 20000,
27
+ sweepMs: 5000,
28
+ bufferBytes: 65536,
29
+ }
30
+ const COLORS = ['#1d4ed8', '#6d28d9', '#be185d', '#b45309', '#047857', '#0e7490', '#4338ca', '#a21caf']
31
+ // A board mode: a viewport name (VIEWPORT_NAME_RE) or 'all'.
32
+ const MODES = { includes: (mode) => typeof mode === 'string' && (mode === 'all' || /^[a-z][a-z0-9-]{0,31}$/.test(mode)) }
33
+ export function presenceColor(name) {
34
+ let hash = 0
35
+ const text = String(name).toLowerCase()
36
+ for (let i = 0; i < text.length; i++) hash = (hash * 31 + text.charCodeAt(i)) >>> 0
37
+ return COLORS[hash % COLORS.length]
38
+ }
39
+ const keys = (value, names) =>
40
+ value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).every((key) => names.includes(key))
41
+ const coordinate = (value) => typeof value === 'number' && Number.isFinite(value) && Math.abs(value) <= 10000000
42
+ export function cleanPresenceState(input) {
43
+ if (!keys(input, ['type', 'cursor', 'viewport', 'selection', 'mode']) || input.type !== 'state') return null
44
+ if (input.cursor !== null && (!keys(input.cursor, ['x', 'y']) || !coordinate(input.cursor.x) || !coordinate(input.cursor.y))) return null
45
+ if (
46
+ input.viewport !== null &&
47
+ (!keys(input.viewport, ['x', 'y', 'zoom']) ||
48
+ !coordinate(input.viewport.x) ||
49
+ !coordinate(input.viewport.y) ||
50
+ typeof input.viewport.zoom !== 'number' ||
51
+ !Number.isFinite(input.viewport.zoom) ||
52
+ input.viewport.zoom < 0.02 ||
53
+ input.viewport.zoom > 8)
54
+ )
55
+ return null
56
+ if (input.selection !== null && (!Number.isSafeInteger(input.selection) || input.selection < 1 || input.selection > 2147483647))
57
+ return null
58
+ if (!MODES.includes(input.mode)) return null
59
+ return { cursor: input.cursor, viewport: input.viewport, selection: input.selection, mode: input.mode }
60
+ }
61
+
62
+ // The three presence routes, built from the shared id formats.
63
+ const part = (re) => re.source.replace(/^\^|\$$/g, '')
64
+ const BOARD = part(ID_RE)
65
+ const MEMBER_ROUTE = new RegExp(`^/w/(${part(ID_PATTERNS.workspace)})/p/(${part(ID_PATTERNS.project)})/api/boards/(${BOARD})/presence$`)
66
+ const SHARE_ROUTE = new RegExp(`^/s/(${part(SHARE_ID_RE)})/api/boards/(${BOARD})/presence$`)
67
+ const PUBLIC_ROUTE = new RegExp(`^/p/(${part(PUBLIC_ID_RE)})/api/boards/(${BOARD})/presence$`)
68
+
69
+ function cookie(req, name) {
70
+ const values = String(req.headers.cookie || '')
71
+ .split(';')
72
+ .map((part) => part.trim())
73
+ .filter((part) => part.startsWith(`${name}=`))
74
+ return values.length === 1 ? values[0].slice(name.length + 1) : null
75
+ }
76
+
77
+ // Re-run for every message and heartbeat. No cached membership or share grant.
78
+ export function presenceAuthorizer({ db, dataDir, origin, auth, now = () => new Date(), guestOnly = false }) {
79
+ const url = new URL(origin)
80
+ const secure = url.protocol === 'https:'
81
+ const iso = () => now().toISOString()
82
+ return (req) => {
83
+ if (
84
+ req.headers.origin !== url.origin ||
85
+ String(req.headers.host || '').toLowerCase() !== url.host.toLowerCase() ||
86
+ req.headers.authorization
87
+ )
88
+ return null
89
+ let route
90
+ try {
91
+ const value = new URL(req.url, url)
92
+ if (value.origin !== url.origin || value.search || value.hash) return null
93
+ route = value.pathname
94
+ } catch {
95
+ return null
96
+ }
97
+ const member = MEMBER_ROUTE.exec(route)
98
+ const share = SHARE_ROUTE.exec(route)
99
+ const publicRoute = PUBLIC_ROUTE.exec(route)
100
+ let access
101
+ if (member && !guestOnly) {
102
+ const token = cookie(req, sessionCookieName(secure))
103
+ const session = token && auth.readSession(token)
104
+ if (!session || !roleIn(db, session.user.id, member[1])) return null
105
+ access = {
106
+ workspace: member[1],
107
+ project: member[2],
108
+ board: member[3],
109
+ kind: 'member',
110
+ name: cleanDisplayName(session.user.display_name) || 'Member',
111
+ }
112
+ } else if (share) {
113
+ if (!cookie(req, guestCookieName(secure))) return null
114
+ const guest = readGuest({ headers: req.headers, params: { sid: share[1] } }, { db, secure, iso, now })
115
+ if (!guest) return null
116
+ access = { workspace: guest.workspaceId, project: guest.projectId, board: share[2], kind: 'guest', name: 'Guest' }
117
+ } else if (publicRoute && !guestOnly) {
118
+ const viewer = readPublic({ params: { pubid: publicRoute[1] } }, db)
119
+ if (!viewer) return null
120
+ access = { workspace: viewer.workspaceId, project: viewer.projectId, board: publicRoute[2], kind: 'public', name: null }
121
+ } else return null
122
+ const t = tenant(db, access.workspace)
123
+ const workspace = t.get('SELECT suspended_at FROM workspaces WHERE workspace_id = :ws')
124
+ if (!workspace || workspace.suspended_at) return null
125
+ const projects = createProjectStore(t, { db, dataDir })
126
+ if (!projects.get(access.project) || !projects.board(access.project, access.board)) return null
127
+ return { ...access, room: `${access.workspace}:${access.project}:${access.board}` }
128
+ }
129
+ }
130
+
131
+ // A hub may be shared by the primary server and its guest-only listener. It
132
+ // owns one event subscription. Each attached listener owns only its sockets.
133
+ export function createPresenceHub({ events = null, limits = {}, now = () => Date.now() } = {}) {
134
+ const limit = { ...PRESENCE_LIMITS, ...limits }
135
+ const rooms = new Map()
136
+ const listeners = new Set()
137
+ let closed = false
138
+ let total = 0
139
+ const perWorkspace = new Map()
140
+ const perIp = new Map()
141
+ const bump = (map, key, by) => {
142
+ const n = (map.get(key) || 0) + by
143
+ if (n > 0) map.set(key, n)
144
+ else map.delete(key)
145
+ }
146
+ const send = (peer, value, binary = false) => {
147
+ if (!peer.live || peer.ws.readyState !== WebSocket.OPEN) return
148
+ if (peer.ws.bufferedAmount > limit.bufferBytes) return peer.drop(1013, 'Slow connection')
149
+ peer.ws.send(binary ? value : JSON.stringify(value))
150
+ }
151
+ const live = (peer) => {
152
+ let access
153
+ try {
154
+ access = peer.authorize(peer.req)
155
+ } catch {
156
+ /* fail closed */
157
+ }
158
+ if (!access || access.room !== peer.access.room || access.kind !== peer.access.kind || access.name !== peer.access.name) {
159
+ peer.drop(1008, 'Access ended')
160
+ return false
161
+ }
162
+ return peer.live
163
+ }
164
+ const counts = (room) => {
165
+ for (const peer of [...room.peers]) if (peer.live) send(peer, { type: 'count', count: room.peers.size })
166
+ }
167
+ const broadcast = (room, data) => {
168
+ // Recipients retain authorization only until the next bounded sweep.
169
+ // Incoming frames and comment invalidations still reauthorize immediately.
170
+ for (const peer of [...room.peers]) if (peer.access.kind !== 'public' && peer.live) send(peer, data, true)
171
+ }
172
+ const unsubscribe = events?.subscribe((event) => {
173
+ if (event.type === 'close') return close()
174
+ if (!event.board || !event.workspace || !event.project) return
175
+ const room = rooms.get(`${event.workspace}:${event.project}:${event.board}`)
176
+ if (!room) return
177
+ const comment = Number.isSafeInteger(event.comment) && event.comment > 0 ? event.comment : null
178
+ if (!comment && !['push.committed', 'comment.created'].includes(event.type)) return
179
+ for (const peer of [...room.peers])
180
+ if (peer.access.kind !== 'public' && live(peer)) send(peer, { type: 'invalidate', comment, sequence: event.sequence || 0 })
181
+ })
182
+ function close() {
183
+ if (closed) return
184
+ closed = true
185
+ clearInterval(timer)
186
+ unsubscribe?.()
187
+ for (const listener of [...listeners]) listener.close()
188
+ rooms.clear()
189
+ }
190
+ function sweep() {
191
+ const at = now()
192
+ for (const room of [...rooms.values()])
193
+ for (const peer of [...room.peers]) {
194
+ if (!live(peer)) continue
195
+ if (at - peer.seenAt >= limit.idleMs) {
196
+ peer.drop(1001, 'Idle connection')
197
+ continue
198
+ }
199
+ if (at - peer.pingAt >= limit.pingMs) {
200
+ peer.pingAt = at
201
+ peer.ws.ping()
202
+ }
203
+ }
204
+ }
205
+ const timer = setInterval(sweep, limit.sweepMs)
206
+ timer.unref()
207
+ // clientIp: the address a request comes from (behind a trusted proxy, from
208
+ // X-Forwarded-For), for the per-address cap.
209
+ function listener(authorize, { clientIp = (req) => req.socket.remoteAddress || 'unknown' } = {}) {
210
+ const wss = new WebSocketServer({
211
+ noServer: true,
212
+ maxPayload: limit.bytes,
213
+ perMessageDeflate: false,
214
+ handleProtocols: (protocols) => (protocols.has(PRESENCE_PROTOCOL) ? PRESENCE_PROTOCOL : false),
215
+ })
216
+ const peers = new Set()
217
+ const servers = new Set()
218
+ let disposed = false
219
+ const reject = (socket, status = 404) => {
220
+ socket.end(`HTTP/1.1 ${status} Refused\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`, () => socket.destroy())
221
+ }
222
+ const upgrade = (req, socket, head) => {
223
+ // HTTP upgrade sockets can reset before ws has attached its handlers.
224
+ const onSocketError = () => socket.destroy()
225
+ socket.on('error', onSocketError)
226
+ if (closed || req.method !== 'GET' || req.headers['sec-websocket-protocol'] !== PRESENCE_PROTOCOL) return reject(socket)
227
+ let access
228
+ try {
229
+ access = authorize(req)
230
+ } catch {
231
+ /* unauthorized */
232
+ }
233
+ if (!access) return reject(socket)
234
+ let room = rooms.get(access.room)
235
+ if (!room) room = { peers: new Set() }
236
+ const ip = clientIp(req)
237
+ if (
238
+ room.peers.size >= limit.connections ||
239
+ total >= limit.globalConnections ||
240
+ (perWorkspace.get(access.workspace) || 0) >= limit.workspaceConnections ||
241
+ (perIp.get(ip) || 0) >= limit.ipConnections
242
+ )
243
+ return reject(socket, 429)
244
+ wss.handleUpgrade(req, socket, head, (ws) => {
245
+ socket.removeListener('error', onSocketError)
246
+ rooms.set(access.room, room)
247
+ const ids = new Set([...room.peers].map((peer) => peer.id))
248
+ let id
249
+ do {
250
+ id = randomInt(1, 0x100000000)
251
+ } while (ids.has(id))
252
+ const doc = access.kind === 'public' ? null : new Doc()
253
+ if (doc) doc.clientID = id
254
+ const awareness = doc ? new Awareness(doc) : null
255
+ const peer = {
256
+ ws,
257
+ req,
258
+ authorize,
259
+ access,
260
+ id,
261
+ doc,
262
+ awareness,
263
+ live: true,
264
+ seenAt: now(),
265
+ pingAt: now(),
266
+ windowAt: now(),
267
+ messages: 0,
268
+ }
269
+ const drop = (code = 1000, reason = 'Left') => {
270
+ if (!peer.live) return
271
+ peer.live = false
272
+ if (awareness) {
273
+ awareness.setLocalState(null)
274
+ broadcast(room, encodeAwarenessUpdate(awareness, [id]))
275
+ awareness.destroy()
276
+ doc.destroy()
277
+ }
278
+ room.peers.delete(peer)
279
+ peers.delete(peer)
280
+ total -= 1
281
+ bump(perWorkspace, access.workspace, -1)
282
+ bump(perIp, ip, -1)
283
+ if (!room.peers.size) rooms.delete(access.room)
284
+ else counts(room)
285
+ ws.close(code, reason)
286
+ // Do not leave a revoked peer alive while waiting for a close frame.
287
+ ws.terminate()
288
+ }
289
+ peer.drop = drop
290
+ ws.on('error', () => drop(1008, 'Connection error'))
291
+ ws.on('close', () => drop())
292
+ const check = () => {
293
+ if (!live(peer)) return false
294
+ const at = now()
295
+ if (at - peer.windowAt >= 1000) {
296
+ peer.messages = 0
297
+ peer.windowAt = at
298
+ }
299
+ if (++peer.messages > limit.messages) {
300
+ drop(1008, 'Rate limit')
301
+ return false
302
+ }
303
+ peer.seenAt = at
304
+ return true
305
+ }
306
+ ws.on('pong', () => {
307
+ if (check()) peer.seenAt = now()
308
+ })
309
+ ws.on('ping', () => check())
310
+ ws.on('message', (data, binary) => {
311
+ if (!check()) return
312
+ if (binary || data.length > limit.bytes) return drop(1008, 'Invalid message')
313
+ let input
314
+ try {
315
+ input = JSON.parse(data.toString('utf8'))
316
+ } catch {
317
+ return drop(1008, 'Invalid message')
318
+ }
319
+ if (keys(input, ['type']) && input.type === 'ping') return
320
+ const state = cleanPresenceState(input)
321
+ if (!state || access.kind === 'public') return drop(1008, 'Invalid state')
322
+ awareness.setLocalState({ ...state, name: access.name, color: presenceColor(access.name), kind: access.kind })
323
+ })
324
+ peers.add(peer)
325
+ room.peers.add(peer)
326
+ total += 1
327
+ bump(perWorkspace, access.workspace, 1)
328
+ bump(perIp, ip, 1)
329
+ send(peer, { type: 'ready', id: access.kind === 'public' ? null : id, countsOnly: access.kind === 'public' })
330
+ if (awareness) {
331
+ awareness.setLocalState({
332
+ name: access.name,
333
+ color: presenceColor(access.name),
334
+ kind: access.kind,
335
+ cursor: null,
336
+ viewport: null,
337
+ selection: null,
338
+ mode: 'desktop',
339
+ })
340
+ awareness.on('update', () => {
341
+ if (peer.live) broadcast(room, encodeAwarenessUpdate(awareness, [id]))
342
+ })
343
+ for (const other of [...room.peers])
344
+ if (other.awareness && live(other)) send(peer, encodeAwarenessUpdate(other.awareness, [other.id]), true)
345
+ broadcast(room, encodeAwarenessUpdate(awareness, [id]))
346
+ }
347
+ counts(room)
348
+ })
349
+ }
350
+ const api = {
351
+ attach(server) {
352
+ if (!servers.has(server)) {
353
+ servers.add(server)
354
+ server.on('upgrade', upgrade)
355
+ }
356
+ return api
357
+ },
358
+ close() {
359
+ if (disposed) return
360
+ disposed = true
361
+ for (const server of servers) server.off('upgrade', upgrade)
362
+ servers.clear()
363
+ for (const peer of [...peers]) peer.drop(1001, 'Server stopped')
364
+ wss.close()
365
+ listeners.delete(api)
366
+ },
367
+ }
368
+ listeners.add(api)
369
+ return api
370
+ }
371
+ return { listener, close, sweep, rooms }
372
+ }
@@ -0,0 +1,124 @@
1
+ // Projects and their boards. A project belongs to a workspace; its boards
2
+ // come from pushes. Board files (captures, variants, versions) live on disk
3
+ // in the same layout the local tool uses, under
4
+ // <data>/files/<workspace>/<project>/<board>/, so the board view and file
5
+ // lookups reuse src/store.js unchanged. A synthetic config per board points
6
+ // the store at that folder; nothing in it comes from a user-supplied path.
7
+
8
+ import fs from 'node:fs'
9
+ import path from 'node:path'
10
+ import { ID_PATTERNS, newId } from './crypto.js'
11
+ import { transaction } from './db.js'
12
+
13
+ export const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,39}$/
14
+ export const PROJECTS_MAX = 50
15
+
16
+ export class ProjectError extends Error {
17
+ constructor(status, code, message) {
18
+ super(message)
19
+ this.statusCode = status
20
+ this.code = code
21
+ }
22
+ }
23
+
24
+ export function projectDir(dataDir, workspaceId, projectId) {
25
+ if (!ID_PATTERNS.workspace.test(workspaceId) || !ID_PATTERNS.project.test(projectId)) throw new Error('invalid project path')
26
+ return path.join(dataDir, 'files', workspaceId, projectId)
27
+ }
28
+
29
+ // The config the store functions need for one pushed board.
30
+ export function boardConfig(dataDir, workspaceId, projectId, row) {
31
+ const definition = JSON.parse(row.definition)
32
+ return {
33
+ file: null,
34
+ dir: projectDir(dataDir, workspaceId, projectId),
35
+ title: definition.title,
36
+ outputDir: projectDir(dataDir, workspaceId, projectId),
37
+ viewports: definition.viewports,
38
+ ...(definition.checksEnvironments ? { checksEnvironments: definition.checksEnvironments } : {}),
39
+ versions: definition.versions,
40
+ auth: { storageState: null, loginScript: null },
41
+ browser: {},
42
+ liveHtml: true,
43
+ concurrency: 1,
44
+ timeouts: {},
45
+ boards: [definition.board],
46
+ }
47
+ }
48
+
49
+ // eslint-disable-next-line no-control-regex
50
+ const CONTROL_RE = /[\u0000-\u001f\u007f]/g
51
+
52
+ export function cleanProjectName(value) {
53
+ const name = typeof value === 'string' ? value.replace(/\s+/g, ' ').replace(CONTROL_RE, '').trim() : ''
54
+ if (!name || name.length > 80) throw new ProjectError(400, 'invalid_name', 'Project name: 1 to 80 characters.')
55
+ return name
56
+ }
57
+
58
+ export function slugFor(name) {
59
+ return (
60
+ String(name)
61
+ .toLowerCase()
62
+ .replace(/[^a-z0-9]+/g, '-')
63
+ .replace(/^-+|-+$/g, '')
64
+ .slice(0, 40) || 'project'
65
+ )
66
+ }
67
+
68
+ export function createProjectStore(t, { db, dataDir, maxProjects = PROJECTS_MAX }) {
69
+ const get = (projectId) =>
70
+ ID_PATTERNS.project.test(String(projectId || ''))
71
+ ? t.get('SELECT * FROM projects WHERE workspace_id = :ws AND id = :id', { id: projectId }) || null
72
+ : null
73
+
74
+ function list() {
75
+ return t.all('SELECT * FROM projects WHERE workspace_id = :ws ORDER BY created_at, id')
76
+ }
77
+
78
+ function create({ name, slug, userId, now = new Date() }) {
79
+ const clean = cleanProjectName(name)
80
+ const wanted = slug === undefined || slug === null || slug === '' ? slugFor(clean) : String(slug)
81
+ if (!SLUG_RE.test(wanted)) throw new ProjectError(400, 'invalid_slug', 'Slug: lowercase letters, digits and dashes.')
82
+ return transaction(db, () => {
83
+ if (t.get('SELECT COUNT(*) AS n FROM projects WHERE workspace_id = :ws').n >= maxProjects) {
84
+ throw new ProjectError(409, 'too_many_projects', `A workspace holds at most ${maxProjects} projects.`)
85
+ }
86
+ if (t.get('SELECT id FROM projects WHERE workspace_id = :ws AND slug = :slug', { slug: wanted })) {
87
+ throw new ProjectError(409, 'slug_taken', 'A project with that slug exists in this workspace.')
88
+ }
89
+ const id = newId('pr')
90
+ t.run('INSERT INTO projects (workspace_id, id, slug, name, created_by, created_at) VALUES (:ws, :id, :slug, :name, :user, :at)', {
91
+ id,
92
+ slug: wanted,
93
+ name: clean,
94
+ user: userId || null,
95
+ at: now.toISOString(),
96
+ })
97
+ return get(id)
98
+ })
99
+ }
100
+
101
+ // Rows first (comments, boards, tokens and pushes go with them), then files.
102
+ function remove(projectId) {
103
+ const project = get(projectId)
104
+ if (!project) throw new ProjectError(404, 'unknown_project', 'No such project.')
105
+ transaction(db, () => {
106
+ for (const table of ['comments', 'boards', 'api_tokens', 'pushes']) {
107
+ t.run(`DELETE FROM ${table} WHERE workspace_id = :ws AND project_id = :id`, { id: project.id })
108
+ }
109
+ t.run('DELETE FROM projects WHERE workspace_id = :ws AND id = :id', { id: project.id })
110
+ })
111
+ fs.rmSync(projectDir(dataDir, t.workspaceId, project.id), { recursive: true, force: true })
112
+ return project
113
+ }
114
+
115
+ const boards = (projectId) =>
116
+ t.all('SELECT * FROM boards WHERE workspace_id = :ws AND project_id = :project ORDER BY created_at, board_id', { project: projectId })
117
+ const board = (projectId, boardId) =>
118
+ t.get('SELECT * FROM boards WHERE workspace_id = :ws AND project_id = :project AND board_id = :board', {
119
+ project: projectId,
120
+ board: String(boardId || ''),
121
+ }) || null
122
+
123
+ return { get, list, create, remove, boards, board }
124
+ }
@@ -0,0 +1,109 @@
1
+ // Public projects: a project anyone with its URL can view, read-only.
2
+ //
3
+ // - Off in every workspace until an owner turns public projects on
4
+ // (Settings, with a fresh passkey check). Then an owner makes one project
5
+ // public (again with a fresh check): it gets a public id of 128 random bits
6
+ // and the URL /p/<public id>/. Admins and owners can turn either off at
7
+ // once (the kill switches); turning a project public again makes a new id,
8
+ // so an old URL stays dead. Turning the workspace switch off makes every
9
+ // project private, so turning it on again publishes nothing by itself.
10
+ // - The public board is the same client on a view-only API
11
+ // (/p/<id>/api/...): pages, captures, live HTML through the same signed
12
+ // URLs, and comments as a share link guest sees them, with every guest
13
+ // named "Guest". No cookie is read or set there, and every write (POST,
14
+ // PUT, PATCH, DELETE) answers 403. Pages keep X-Robots-Tag: noindex.
15
+ // - Public viewers never comment (give them a comment share link), so
16
+ // nothing they do reaches an agent.
17
+
18
+ import { randomBytes } from 'node:crypto'
19
+ import { transaction } from './db.js'
20
+ import { NEEDS } from './permissions.js'
21
+ import { findPublicProject } from './tenancy.js'
22
+
23
+ export const PUBLIC_ID_RE = /^pb_[a-f0-9]{32}$/
24
+ export const newPublicId = () => `pb_${randomBytes(16).toString('hex')}`
25
+ export const publicUrl = (publicId) => `/p/${publicId}/`
26
+
27
+ // The workspace switch and the per-project switch, for the console.
28
+ export function mountPublicAdmin(router, deps) {
29
+ const { db, handle, inWorkspace, inProject, freshOrThrow, auditOf, HttpError, iso } = deps
30
+
31
+ router.patch(
32
+ '/workspaces/:ws/public-projects',
33
+ inWorkspace(NEEDS.settings),
34
+ handle(async (req, res) => {
35
+ const enabled = req.body?.enabled
36
+ if (typeof enabled !== 'boolean') throw new HttpError(400, 'invalid_settings', 'enabled: true or false.')
37
+ const current = Boolean(req.t.get('SELECT public_projects FROM workspaces WHERE workspace_id = :ws').public_projects)
38
+ if (enabled && !current) {
39
+ // Putting boards on the open web: the owner, with a passkey check.
40
+ if (req.role !== 'owner') throw new HttpError(403, 'forbidden', 'Only an owner turns public projects on.')
41
+ freshOrThrow(req)
42
+ }
43
+ if (enabled !== current) {
44
+ transaction(db, () => {
45
+ req.t.run('UPDATE workspaces SET public_projects = :on WHERE workspace_id = :ws', { on: enabled ? 1 : 0 })
46
+ // Off makes every project private for good: turning the switch on
47
+ // again brings no old URL back (a project gets a new id then).
48
+ const ended = enabled
49
+ ? 0
50
+ : req.t.run(
51
+ 'UPDATE projects SET public_id = NULL, public_at = NULL, public_by = NULL WHERE workspace_id = :ws AND public_id IS NOT NULL',
52
+ ).changes
53
+ auditOf(req, enabled ? 'public_projects_enabled' : 'public_projects_disabled', null, enabled ? {} : { projects: ended })
54
+ })
55
+ }
56
+ res.json({ settings: { publicProjects: enabled } })
57
+ }),
58
+ )
59
+
60
+ router.put(
61
+ '/workspaces/:ws/projects/:pid/public',
62
+ inWorkspace(NEEDS.settings),
63
+ inProject,
64
+ handle(async (req, res) => {
65
+ const wanted = req.body?.public
66
+ if (typeof wanted !== 'boolean') throw new HttpError(400, 'invalid_settings', 'public: true or false.')
67
+ const isPublic = Boolean(req.project.public_id)
68
+ if (wanted && !isPublic) {
69
+ if (req.role !== 'owner') throw new HttpError(403, 'forbidden', 'Only an owner makes a project public.')
70
+ const on = req.t.get('SELECT public_projects FROM workspaces WHERE workspace_id = :ws').public_projects
71
+ if (!on) throw new HttpError(409, 'public_off', 'Public projects are off in this workspace. An owner turns them on in Settings.')
72
+ freshOrThrow(req)
73
+ const id = newPublicId()
74
+ req.t.run('UPDATE projects SET public_id = :pub, public_at = :at, public_by = :user WHERE workspace_id = :ws AND id = :id', {
75
+ pub: id,
76
+ at: iso(),
77
+ user: req.user.id,
78
+ id: req.project.id,
79
+ })
80
+ auditOf(req, 'project_made_public', req.project.id, { name: req.project.name })
81
+ return res.json({ public: { id, url: publicUrl(id), since: iso() } })
82
+ }
83
+ if (!wanted && isPublic) {
84
+ req.t.run('UPDATE projects SET public_id = NULL, public_at = NULL, public_by = NULL WHERE workspace_id = :ws AND id = :id', {
85
+ id: req.project.id,
86
+ })
87
+ auditOf(req, 'project_made_private', req.project.id, { name: req.project.name })
88
+ }
89
+ const project = req.projects.get(req.project.id)
90
+ res.json({
91
+ public: project.public_id ? { id: project.public_id, url: publicUrl(project.public_id), since: project.public_at } : null,
92
+ })
93
+ }),
94
+ )
95
+ }
96
+
97
+ // The public project of a request (/p/:pubid/...), or null: the id is live
98
+ // and the workspace still has public projects on.
99
+ export function readPublic(req, db) {
100
+ const id = String(req.params?.pubid || '')
101
+ if (!PUBLIC_ID_RE.test(id)) return null
102
+ const row = findPublicProject(db, id)
103
+ if (!row || !row.workspace_public_projects || row.public_id !== id) return null
104
+ return { workspaceId: row.workspace_id, projectId: row.id, publicId: id }
105
+ }
106
+
107
+ // The console's view of a project's public state (null: private).
108
+ export const projectPublic = (project) =>
109
+ project.public_id ? { id: project.public_id, url: publicUrl(project.public_id), since: project.public_at } : null