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,486 @@
1
+ // The board client's API (src/hosted/app.js), for members
2
+ // (/w/:ws/p/:pid/api), share link guests (/s/:sid/api) and public projects
3
+ // (/p/:pubid/api). mountBoardRoutes(app, options) mounts all three and
4
+ // returns { approvalApi }, the router src/hosted/agent-approvals.js adds
5
+ // the board's approval routes to.
6
+
7
+ import express from 'express'
8
+ import { boardSummary } from '../server/app.js'
9
+ import { listJourneys } from '../journeys.js'
10
+ import { MENTION_HANDLE_RE } from '../mentions.js'
11
+ import { resolveFile } from '../store.js'
12
+ import { avatarUrl } from '../accounts/avatar.js'
13
+ import { checksView, readReport } from '../checks/store.js'
14
+ import { agentPolicy } from './agent-policy.js'
15
+ import { hostedBoardView, sendPng } from './board-context.js'
16
+ import { guestView, rowToComment } from './comments.js'
17
+ import { transaction } from './db.js'
18
+ import { publicView } from './guest-view.js'
19
+ import { HttpError, fail, guestLabel } from './http.js'
20
+ import { boardPermissions, canDeleteComment, canEditComment, guestPermissions } from './permissions.js'
21
+ import { boardConfig, createProjectStore } from './projects.js'
22
+ import { readPublic } from './public.js'
23
+ import { LIMITS } from './ratelimit.js'
24
+ import { readGuest } from './shares.js'
25
+ import { roleAtLeast, tenant } from './tenancy.js'
26
+
27
+ export function mountBoardRoutes(
28
+ app,
29
+ {
30
+ db,
31
+ dataDir,
32
+ iso,
33
+ now,
34
+ rateLimiter,
35
+ reportEmail,
36
+ usercontent,
37
+ guardWrites,
38
+ needSession,
39
+ limit,
40
+ inWorkspace,
41
+ inProject,
42
+ handle,
43
+ freshOrThrow,
44
+ auditOf,
45
+ clientIp,
46
+ policyFor,
47
+ dispatchView,
48
+ boardContext,
49
+ // What readGuest needs (the shared deps of src/hosted/app.js).
50
+ deps,
51
+ },
52
+ ) {
53
+ // ---- Usercontent: live HTML through signed URLs ----
54
+ // Served by usercontent.gate (mounted first, src/hosted/usercontent.js).
55
+
56
+ // ---- The board client and its API (session, or a share link's guest) ----
57
+ //
58
+ // The same routes serve members (/w/:ws/p/:pid/api, session cookie) and
59
+ // the guests of a share link (/s/:sid/api, a guest cookie scoped to that
60
+ // path; the session cookie is never read there). A guest sees one project
61
+ // and, on a comment link, adds comments and replies; nothing else writes.
62
+ const boardApi = express.Router({ mergeParams: true })
63
+ boardApi.use((req, res, next) => {
64
+ res.setHeader('Cache-Control', 'no-store')
65
+ next()
66
+ })
67
+ boardApi.use(guardWrites)
68
+ boardApi.use(express.json({ limit: '64kb' }))
69
+ // Per account: API calls in one bucket, a board's files in a larger one.
70
+ const sessionLimits = { api: limit('session', (req) => req.user.id), files: limit('sessionFiles', (req) => req.user.id) }
71
+ const BOARD_FILE_RE = /^\/boards\/[^/]+\/(?:captures|variants|versions|live|variant-live|elements|variant-elements)\//
72
+ boardApi.use(needSession, (req, res, next) =>
73
+ (req.method === 'GET' && BOARD_FILE_RE.test(req.path) ? sessionLimits.files : sessionLimits.api)(req, res, next),
74
+ )
75
+ boardApi.use(inWorkspace('viewer'), inProject)
76
+
77
+ boardApi.get(
78
+ '/boards/:bid/agent-budget',
79
+ handle((req, res) => {
80
+ const policy = agentPolicy(req.t, req.project.id, req.params.bid)
81
+ const claims = req.t.get(
82
+ 'SELECT COUNT(*) AS n FROM agent_claims WHERE workspace_id = :ws AND project_id = :project AND created_at >= :start',
83
+ { project: req.project.id, start: `${iso().slice(0, 10)}T00:00:00.000Z` },
84
+ ).n
85
+ const open = req.t.get(
86
+ 'SELECT COUNT(*) AS n FROM agent_claims WHERE workspace_id = :ws AND project_id = :project AND ended_at IS NULL',
87
+ { project: req.project.id },
88
+ ).n
89
+ res.json({
90
+ claims,
91
+ open,
92
+ dailyLimit: policy.dailyClaims,
93
+ openLimit: policy.maxOpenClaims,
94
+ exhausted: claims >= policy.dailyClaims || open >= policy.maxOpenClaims,
95
+ })
96
+ }),
97
+ )
98
+
99
+ boardApi.post(
100
+ '/boards/:bid/comments/:cid/send-to-agent',
101
+ handle((req, res) => {
102
+ const ctx = boardContext(req.t, req.project, req.params.bid)
103
+ const approve = req.body?.approve === true
104
+ // The vouch covers the text its sender saw: the body carries the
105
+ // comment's dispatchHash (from the board API), compared with the row
106
+ // in the transaction that writes the vouch. Edited meanwhile: 409
107
+ // comment_changed.
108
+ const expect = typeof req.body?.dispatchHash === 'string' ? req.body.dispatchHash : null
109
+ const row = transaction(db, () => {
110
+ const current = ctx.comments.get(req.params.cid)
111
+ if (approve) {
112
+ if (!roleAtLeast(req.role, 'admin')) throw new HttpError(403, 'forbidden', 'Only trusted admins approve runs.')
113
+ freshOrThrow(req)
114
+ }
115
+ policyFor(req.t).vouch(req.project.id, ctx.board.id, current, req.user.id, { role: req.role, approve, expect })
116
+ auditOf(req, 'comment_vouched', `${ctx.board.id}#${current.number}`, { project: req.project.id, approve })
117
+ return current
118
+ })
119
+ res.json({ comment: dispatchView(req.t, req.project.id, ctx.board.id, rowToComment(ctx.comments.get(row.number))) })
120
+ }),
121
+ )
122
+
123
+ const shareApi = express.Router({ mergeParams: true })
124
+ shareApi.use((req, res, next) => {
125
+ res.setHeader('Cache-Control', 'no-store')
126
+ next()
127
+ })
128
+ shareApi.use(guardWrites)
129
+ shareApi.use((req, res, next) => {
130
+ const guest = readGuest(req, deps)
131
+ if (!guest) return fail(res, 401, 'share_ended', 'This share link has ended or needs to be opened again.')
132
+ // Per link and address: one busy guest cannot lock out the others.
133
+ const hits = rateLimiter.hit('guestApi', `${guest.shareId}\u0000${clientIp(req)}`, LIMITS.guestApi)
134
+ if (!hits.ok) {
135
+ res.setHeader('Retry-After', String(hits.retryAfter))
136
+ return fail(res, 429, 'rate_limited', 'Too many requests on this share link.')
137
+ }
138
+ req.guest = guest
139
+ req.t = tenant(db, guest.workspaceId)
140
+ req.role = 'guest'
141
+ req.projects = createProjectStore(req.t, { db, dataDir })
142
+ req.project = req.projects.get(guest.projectId)
143
+ if (!req.project) return fail(res, 401, 'share_ended', 'This share link has ended.')
144
+ next()
145
+ })
146
+ shareApi.use(express.json({ limit: '16kb' }))
147
+
148
+ // A public project's board API (src/hosted/public.js): no cookie, view only.
149
+ const publicApi = express.Router({ mergeParams: true })
150
+ publicApi.use((req, res, next) => {
151
+ res.setHeader('Cache-Control', 'no-store')
152
+ if (!['GET', 'HEAD'].includes(req.method))
153
+ return fail(res, 403, 'public_read_only', 'A public board is view-only. Ask the team for a comment link to comment.')
154
+ const found = readPublic(req, db)
155
+ if (!found) return fail(res, 404, 'not_found', 'No such public board.')
156
+ const hits = rateLimiter.hit('publicApi', clientIp(req), LIMITS.publicApi)
157
+ if (!hits.ok) {
158
+ res.setHeader('Retry-After', String(hits.retryAfter))
159
+ return fail(res, 429, 'rate_limited', 'Too many requests.')
160
+ }
161
+ req.publicViewer = true
162
+ req.t = tenant(db, found.workspaceId)
163
+ req.role = 'public'
164
+ req.projects = createProjectStore(req.t, { db, dataDir })
165
+ req.project = req.projects.get(found.projectId)
166
+ if (!req.project) return fail(res, 404, 'not_found', 'No such public board.')
167
+ next()
168
+ })
169
+
170
+ // Changes to existing comments: members and up, never guests.
171
+ const canWrite = (req, res, next) => {
172
+ if (req.guest) return fail(res, 403, 'guest_read_only', 'Guests add comments and replies; people in the workspace resolve and edit.')
173
+ return roleAtLeast(req.role, 'member') ? next() : fail(res, 403, 'read_only', 'Viewers cannot change comments.')
174
+ }
175
+ // New comments and replies: members and up, and guests of a comment link
176
+ // (rate limited per link and address).
177
+ const canComment = (req, res, next) => {
178
+ if (!req.guest) return canWrite(req, res, next)
179
+ if (req.guest.mode !== 'comment') return fail(res, 403, 'read_only', 'This share link is view-only.')
180
+ const hits = rateLimiter.hit('guestComment', `${req.guest.shareId}\u0000${clientIp(req)}`, LIMITS.guestComment)
181
+ if (!hits.ok) {
182
+ res.setHeader('Retry-After', String(hits.retryAfter))
183
+ return fail(res, 429, 'rate_limited', 'That is a lot of comments. Wait a while and try again.')
184
+ }
185
+ next()
186
+ }
187
+ // Who a new comment or reply is from. A guest's name always carries
188
+ // "(guest)", so it never reads as a member's.
189
+ const authorOf = (req) =>
190
+ req.guest
191
+ ? { name: `${req.guest.name} (guest)`, shareId: req.guest.shareId, guest: true }
192
+ : { name: req.user.display_name, userId: req.user.id, handle: req.user.handle }
193
+ // Comments as the asker may see them (guests get guestView).
194
+ const shown = (req, comment) =>
195
+ req.publicViewer
196
+ ? publicView(comment)
197
+ : req.guest
198
+ ? guestView(comment, req.guest.shareId)
199
+ : req.ctx
200
+ ? dispatchView(req.t, req.project.id, req.ctx.board.id, comment)
201
+ : comment
202
+ const withBoard = (fn) =>
203
+ handle(async (req, res) => {
204
+ req.ctx = boardContext(req.t, req.project, req.params.bid)
205
+ await fn(req, res, req.ctx)
206
+ })
207
+
208
+ shareApi.get('/info', (req, res) =>
209
+ res.json({
210
+ title: req.project.name,
211
+ readOnly: req.guest.mode !== 'comment',
212
+ allowCapture: false,
213
+ hosted: true,
214
+ guest: true,
215
+ checksAvailable: req.guest.includeChecks === true,
216
+ user: { name: guestLabel(req.guest.name), handle: null },
217
+ role: 'guest',
218
+ // What this guest may do, for clients that hide what they cannot.
219
+ permissions: guestPermissions(req.guest.mode),
220
+ shareExpiresAt: req.guest.expiresAt,
221
+ }),
222
+ )
223
+ const approvalApi = express.Router({ mergeParams: true })
224
+ boardApi.use(approvalApi)
225
+ function checkRoutes(router, guest = false) {
226
+ router.get(
227
+ '/boards/:bid/checks',
228
+ handle((req, res) => {
229
+ if (guest && !req.guest.includeChecks) return fail(res, 404, 'not_found', 'Check report not found.')
230
+ const ctx = boardContext(req.t, req.project, req.params.bid)
231
+ const requested = typeof req.query.env === 'string' ? req.query.env : null
232
+ if (requested && !(ctx.config.checksEnvironments || ctx.board.environments).some((env) => env.id === requested))
233
+ return fail(res, 404, 'not_found', 'No checks for this environment.')
234
+ res.json(checksView(ctx.config, ctx.board.id, requested, { imported: true }))
235
+ }),
236
+ )
237
+ router.get(
238
+ '/boards/:bid/checks/:id',
239
+ handle((req, res) => {
240
+ if (guest && !req.guest.includeChecks) return fail(res, 404, 'not_found', 'Check report not found.')
241
+ const ctx = boardContext(req.t, req.project, req.params.bid)
242
+ const report = readReport(ctx.config, ctx.board.id, req.params.id)
243
+ if (!report) return fail(res, 404, 'not_found', 'Check report not found.')
244
+ res.json({ report })
245
+ }),
246
+ )
247
+ }
248
+ checkRoutes(boardApi)
249
+ checkRoutes(shareApi, true)
250
+ boardRoutes(boardApi)
251
+ boardRoutes(shareApi)
252
+ publicApi.get('/info', (req, res) =>
253
+ res.json({
254
+ title: req.project.name,
255
+ readOnly: true,
256
+ allowCapture: false,
257
+ hosted: true,
258
+ guest: true,
259
+ public: true,
260
+ checksAvailable: false,
261
+ user: { name: 'Visitor', handle: null },
262
+ role: 'public',
263
+ permissions: { comment: false, reply: false, resolve: false, edit: false, delete: false, react: false },
264
+ ...(reportEmail
265
+ ? { reportUrl: `mailto:${reportEmail}?subject=${encodeURIComponent(`Report a Shapewall board: ${req.params.pubid}`)}` }
266
+ : {}),
267
+ }),
268
+ )
269
+ boardRoutes(publicApi)
270
+ app.use('/w/:ws/p/:pid/api', boardApi)
271
+ app.use('/s/:sid/api', shareApi)
272
+ app.use('/p/:pubid/api', publicApi)
273
+
274
+ function boardRoutes(router) {
275
+ router.get('/info', (req, res) =>
276
+ res.json({
277
+ title: req.project.name,
278
+ checksAvailable: true,
279
+ readOnly: !roleAtLeast(req.role, 'member'),
280
+ allowCapture: false,
281
+ hosted: true,
282
+ user: { name: req.user.display_name, handle: req.user.handle, avatarUrl: avatarUrl(db, req.user.id) },
283
+ role: req.role,
284
+ permissions: boardPermissions(req.role),
285
+ workspace: { id: req.t.workspaceId, name: req.t.get('SELECT name FROM workspaces WHERE workspace_id = :ws')?.name || null },
286
+ consoleUrl: `/w/${req.t.workspaceId}`,
287
+ // The board header's way back to the project's page in the console.
288
+ project: { id: req.project.id, name: req.project.name, url: `/w/${req.t.workspaceId}/projects/${req.project.id}` },
289
+ }),
290
+ )
291
+
292
+ router.get(
293
+ '/boards',
294
+ handle(async (req, res) => {
295
+ const rows = req.projects.boards(req.project.id)
296
+ res.json({
297
+ boards: rows.map((row) => {
298
+ const config = boardConfig(dataDir, req.t.workspaceId, req.project.id, row)
299
+ return boardSummary(config, config.boards[0])
300
+ }),
301
+ })
302
+ }),
303
+ )
304
+ router.get(
305
+ '/boards/:bid',
306
+ withBoard((req, res, ctx) => {
307
+ const trusted =
308
+ !req.guest && !req.publicViewer && policyFor(req.t).trusted(agentPolicy(req.t, req.project.id, ctx.board.id), req.user.id)
309
+ res.json({
310
+ ...hostedBoardView(ctx),
311
+ agentDispatch: Boolean(trusted),
312
+ agentApprove: Boolean(trusted && roleAtLeast(req.role, 'admin')),
313
+ })
314
+ }),
315
+ )
316
+ for (const kind of ['captures', 'variants', 'versions']) {
317
+ router.get(
318
+ `/boards/:bid/${kind}/:file`,
319
+ withBoard((req, res, ctx) => {
320
+ const name = req.params.file
321
+ const file = name.endsWith('.png') ? resolveFile(ctx.config, ctx.board.id, kind, name) : null
322
+ if (!file) return fail(res, 404, 'not_found', 'No such image.')
323
+ sendPng(res, file, Boolean(req.query.v))
324
+ }),
325
+ )
326
+ }
327
+ for (const [route, kind] of [
328
+ ['live', 'captures'],
329
+ ['variant-live', 'variants'],
330
+ ]) {
331
+ router.get(
332
+ `/boards/:bid/${route}/:file`,
333
+ withBoard((req, res, ctx) => {
334
+ const name = req.params.file
335
+ if (!name.endsWith('.html') || !resolveFile(ctx.config, ctx.board.id, kind, name))
336
+ return fail(res, 404, 'not_found', 'No such live page.')
337
+ res.redirect(
338
+ 302,
339
+ usercontent.signedUrl({
340
+ workspaceId: req.t.workspaceId,
341
+ projectId: req.project.id,
342
+ boardId: ctx.board.id,
343
+ kind,
344
+ file: name,
345
+ shareId: req.guest?.shareId || null,
346
+ }),
347
+ )
348
+ }),
349
+ )
350
+ }
351
+ usercontent.elementRoutes(router, withBoard, fail)
352
+ router.get(
353
+ '/boards/:bid/journeys',
354
+ withBoard((req, res, ctx) => res.json({ journeys: listJourneys(ctx.config, ctx.board) })),
355
+ )
356
+ router.all('/boards/:bid/journeys{/*rest}', (req, res) =>
357
+ fail(res, 403, 'hosted_journeys', 'Journeys come from your config on a hosted board; edit them there and push again.'),
358
+ )
359
+ router.all('/boards/:bid/capture', (req, res) => fail(res, 403, 'capture_disabled', 'Hosted boards are updated with shapewall push.'))
360
+
361
+ router.get(
362
+ '/boards/:bid/comments',
363
+ withBoard((req, res, ctx) => {
364
+ const status = ['open', 'resolved'].includes(req.query.status) ? req.query.status : null
365
+ const mention =
366
+ typeof req.query.mention === 'string' && MENTION_HANDLE_RE.test(req.query.mention.replace(/^@/, '')) ? req.query.mention : null
367
+ res.json({
368
+ comments: ctx.comments
369
+ .list({ status, mention })
370
+ .map((comment) =>
371
+ shown(req, req.guest || req.publicViewer ? comment : dispatchView(req.t, req.project.id, ctx.board.id, comment)),
372
+ ),
373
+ })
374
+ }),
375
+ )
376
+ router.post(
377
+ '/boards/:bid/comments',
378
+ canComment,
379
+ withBoard((req, res, ctx) => {
380
+ const comment = transaction(db, () => {
381
+ const made = ctx.comments.create(ctx.config, ctx.board, req.body, authorOf(req), now())
382
+ if (!req.guest) policyFor(req.t).autoVouch(req.project.id, ctx.board.id, ctx.comments.get(made.id), req.user.id, req.role)
383
+ if (req.guest) auditOf(req, 'guest_commented', `${ctx.board.id}#${made.id}`, { project: req.project.id, guest: req.guest.name })
384
+ return made
385
+ })
386
+ res.status(201).json({ comment: shown(req, comment) })
387
+ }),
388
+ )
389
+ router.patch(
390
+ '/boards/:bid/comments/:cid',
391
+ canWrite,
392
+ withBoard((req, res, ctx) => {
393
+ const { body, status, resolution, agentStatus, fixRef } = req.body || {}
394
+ // Agent statuses belong to claims (the token API). On the board an
395
+ // admin may set one; anyone else who writes may only clear it.
396
+ if (agentStatus !== undefined && agentStatus !== null && !roleAtLeast(req.role, 'admin'))
397
+ throw new HttpError(403, 'forbidden', 'Only an admin sets an agent status here; you can clear it.')
398
+ const comment = transaction(db, () => {
399
+ const row = ctx.comments.get(req.params.cid)
400
+ if (body !== undefined && !canEditComment({ isAuthor: row.author_user_id === req.user.id }))
401
+ throw new HttpError(403, 'not_author', 'Only the author can edit a comment.')
402
+ return ctx.comments.update(row.number, { body, status, resolution, agentStatus, fixRef }, now())
403
+ })
404
+ res.json({ comment: shown(req, comment) })
405
+ }),
406
+ )
407
+ router.post(
408
+ '/boards/:bid/comments/:cid/replies',
409
+ canComment,
410
+ withBoard((req, res, ctx) => {
411
+ const result = transaction(db, () => {
412
+ const author = authorOf(req)
413
+ const made = ctx.comments.reply(
414
+ req.params.cid,
415
+ { body: req.body?.body },
416
+ { name: author.name, handle: author.handle, userId: author.userId, guest: author.guest, shareId: author.shareId },
417
+ now(),
418
+ )
419
+ if (req.guest)
420
+ auditOf(req, 'guest_replied', `${ctx.board.id}#${made.comment.id}`, { project: req.project.id, guest: req.guest.name })
421
+ return made
422
+ })
423
+
424
+ res.status(201).json({ ...result, comment: shown(req, result.comment) })
425
+ }),
426
+ )
427
+ // Emoji reactions: people in the workspace who may comment (members and
428
+ // up), never guests or tokens.
429
+ router.post(
430
+ '/boards/:bid/comments/:cid/reactions',
431
+ canWrite,
432
+ withBoard((req, res, ctx) => {
433
+ const { emoji, replyId } = req.body || {}
434
+ const result = transaction(db, () =>
435
+ ctx.comments.react(
436
+ req.params.cid,
437
+ { emoji, replyId: replyId ?? null },
438
+ { name: req.user.display_name, handle: req.user.handle, userId: req.user.id },
439
+ ),
440
+ )
441
+ res.json({ ...result, comment: shown(req, result.comment) })
442
+ }),
443
+ )
444
+ router.post(
445
+ '/boards/:bid/comments/:cid/resolve',
446
+ canWrite,
447
+ withBoard((req, res, ctx) => {
448
+ const { resolution, fixRef } = req.body || {}
449
+ const comment = transaction(db, () => ctx.comments.update(req.params.cid, { status: 'resolved', resolution, fixRef }, now()))
450
+ auditOf(req, 'comment_resolved', `${ctx.board.id}#${comment.id}`, { project: req.project.id })
451
+ res.json({ comment: shown(req, comment) })
452
+ }),
453
+ )
454
+ router.post(
455
+ '/boards/:bid/comments/:cid/reopen',
456
+ canWrite,
457
+ withBoard((req, res, ctx) => {
458
+ res.json({
459
+ comment: shown(
460
+ req,
461
+ transaction(db, () => ctx.comments.update(req.params.cid, { status: 'open' }, now())),
462
+ ),
463
+ })
464
+ }),
465
+ )
466
+ router.delete(
467
+ '/boards/:bid/comments/:cid',
468
+ canWrite,
469
+ withBoard((req, res, ctx) => {
470
+ transaction(db, () => {
471
+ const row = ctx.comments.get(req.params.cid)
472
+ if (!canDeleteComment({ role: req.role, isAuthor: row.author_user_id === req.user.id })) {
473
+ throw new HttpError(403, 'not_author', 'Only the author or an admin can delete a comment.')
474
+ }
475
+ ctx.comments.remove(row.number)
476
+ auditOf(req, 'comment_deleted', `${ctx.board.id}#${row.number}`, { project: req.project.id })
477
+ })
478
+ res.json({ ok: true })
479
+ }),
480
+ )
481
+ router.get('/boards/:bid/compare', (req, res) => fail(res, 404, 'not_found', 'Compare is not on hosted boards yet.'))
482
+ router.use((req, res) => fail(res, 404, 'not_found', 'No such API route.'))
483
+ }
484
+
485
+ return { approvalApi }
486
+ }
@@ -0,0 +1,94 @@
1
+ // What a hosted board shows about where its pages live: capture addresses
2
+ // taken out (src/hosted/app.js serves this view to members and guests).
3
+
4
+ import { joinUrl } from '../config.js'
5
+
6
+ // Strings from a capture (a broken link, a shot's error) with the capture
7
+ // addresses taken out: the board's and its environments' base URLs become
8
+ // the public URL when there is one, else go.
9
+ function captureHostScrubber(board) {
10
+ const publicUrl = board.publicUrl ? String(board.publicUrl).replace(/\/+$/, '') : ''
11
+ const bases = new Set()
12
+ for (const value of [board.baseUrl, ...(board.environments || []).map((env) => env?.baseUrl)]) {
13
+ if (typeof value !== 'string' || !value) continue
14
+ try {
15
+ const url = new URL(value)
16
+ bases.add(url.href.replace(/\/+$/, ''))
17
+ bases.add(url.origin)
18
+ bases.add(url.host)
19
+ } catch {
20
+ /* not a URL: nothing to take out */
21
+ }
22
+ }
23
+ let publicHost = ''
24
+ try {
25
+ publicHost = publicUrl ? new URL(publicUrl).host : ''
26
+ } catch {
27
+ publicHost = ''
28
+ }
29
+ // Longest first: the full base URL, then its origin, then the bare host.
30
+ const ordered = [...bases].filter(Boolean).sort((a, b) => b.length - a.length)
31
+ return (text) => {
32
+ if (typeof text !== 'string') return text
33
+ let out = text
34
+ for (const base of ordered) out = out.split(base).join(base.includes('//') ? publicUrl : publicHost)
35
+ return out
36
+ }
37
+ }
38
+
39
+ // Page URLs a hosted board may show (members and share link guests alike):
40
+ // the board's public URL when its config has one, else none; the same for
41
+ // broken links and capture errors. The base URL is where it was captured (often
42
+ // http://localhost:3000 or a staging host), which says nothing useful to a
43
+ // reviewer and something about the team's machines to a guest.
44
+ export function publicBoardView(view, board) {
45
+ const publicUrl = board.publicUrl || null
46
+ const scrub = captureHostScrubber(board)
47
+ const brokenLinks = (list) =>
48
+ Array.isArray(list)
49
+ ? list.map((item) => ({
50
+ ...item,
51
+ url:
52
+ item?.kind === 'site' && typeof item.path === 'string'
53
+ ? publicUrl
54
+ ? joinUrl(publicUrl, item.path)
55
+ : item.path
56
+ : scrub(item?.url),
57
+ error: scrub(item?.error ?? null),
58
+ }))
59
+ : list
60
+ const out = {
61
+ ...view,
62
+ board: {
63
+ ...view.board,
64
+ siteUrl: publicUrl,
65
+ pages: view.board.pages.map((page) => ({ ...page, url: publicUrl ? joinUrl(publicUrl, page.path) : null })),
66
+ },
67
+ }
68
+ if (view.manifest?.pages) {
69
+ const pages = {}
70
+ for (const [pageId, viewports] of Object.entries(view.manifest.pages)) {
71
+ pages[pageId] = {}
72
+ for (const [viewport, entry] of Object.entries(viewports || {})) {
73
+ const rest = { ...(entry || {}) }
74
+ delete rest.url
75
+ if (typeof rest.error === 'string') rest.error = scrub(rest.error)
76
+ if (rest.html && typeof rest.html.error === 'string') rest.html = { ...rest.html, error: scrub(rest.html.error) }
77
+ const page = board.pages.find((item) => item.id === pageId)
78
+ pages[pageId][viewport] = publicUrl && page ? { ...rest, url: joinUrl(publicUrl, page.path) } : rest
79
+ }
80
+ }
81
+ out.manifest = { ...view.manifest, pages }
82
+ }
83
+ if (out.manifest && 'brokenLinks' in out.manifest) out.manifest = { ...out.manifest, brokenLinks: brokenLinks(out.manifest.brokenLinks) }
84
+ if (Array.isArray(view.brokenLinks)) out.brokenLinks = brokenLinks(view.brokenLinks)
85
+ if (Array.isArray(view.variants)) {
86
+ const base = String(board.baseUrl || '')
87
+ out.variants = view.variants.map((variant) =>
88
+ typeof variant.source === 'string' && /^https?:/i.test(variant.source) && (!publicUrl || !variant.source.startsWith(publicUrl))
89
+ ? { ...variant, source: base && variant.source.startsWith(base) ? variant.source.slice(base.length) || '/' : '' }
90
+ : variant,
91
+ )
92
+ }
93
+ return out
94
+ }
@@ -0,0 +1,24 @@
1
+ // Worker thread for cleaning pushed files (src/hosted/cleaner.js): decoding
2
+ // and re-encoding a PNG, or sanitizing live HTML, takes CPU time that must
3
+ // not block the server's event loop.
4
+
5
+ import { parentPort } from 'node:worker_threads'
6
+ import { cleanHtml, cleanPng, PushError } from './push.js'
7
+
8
+ parentPort.on('message', ({ id, kind, body, base }) => {
9
+ try {
10
+ const buffer = Buffer.from(body.buffer, body.byteOffset, body.byteLength)
11
+ const clean = kind === 'html' ? cleanHtml(buffer, { baseUrl: base }) : cleanPng(buffer)
12
+ const out = new Uint8Array(clean.buffer, clean.byteOffset, clean.byteLength)
13
+ parentPort.postMessage({ id, ok: true, body: out })
14
+ } catch (error) {
15
+ const known = error instanceof PushError
16
+ parentPort.postMessage({
17
+ id,
18
+ ok: false,
19
+ status: known ? error.statusCode : 500,
20
+ code: known ? error.code : 'clean_failed',
21
+ message: known ? error.message : 'The file could not be cleaned.',
22
+ })
23
+ }
24
+ })