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,682 @@
1
+ // Workspace administration for the console API: invites with their history,
2
+ // the access overview ("who has access to what"), API tokens across the
3
+ // workspace, the audit log with filters and paging, workspace settings, and
4
+ // deleting a workspace. Mounted by createHostedApp on the session router;
5
+ // every query goes through the request's tenant handle (req.t).
6
+ //
7
+ // Who may do what: src/hosted/permissions.js (NEEDS), shared with the
8
+ // console and the public demo. Deleting the workspace also needs a fresh
9
+ // passkey check and the workspace's name typed back.
10
+
11
+ import fs from 'node:fs'
12
+ import path from 'node:path'
13
+ import { ID_PATTERNS } from './crypto.js'
14
+ import { transaction } from './db.js'
15
+ import { ID_RE } from '../config.js'
16
+ import { createCommentStore } from './comments.js'
17
+ import { NEEDS, ROLE_ACCESS, tokenCreatorOk } from './permissions.js'
18
+ import { projectDir } from './projects.js'
19
+ import { auditAccount } from './tenancy.js'
20
+ import { ZIP_MAX_BYTES, createZip } from './zip.js'
21
+
22
+ const AUDIT_PAGE = 50
23
+ const AUDIT_PAGE_MAX = 200
24
+ const HISTORY_MAX = 100
25
+ const ACTION_RE = /^[a-z_]{1,40}$/
26
+
27
+ const AUDIT_CSV_MAX = 10_000
28
+ // The export's audit.json: at most this many entries, read a page at a time.
29
+ const AUDIT_EXPORT_MAX = 100_000
30
+ const AUDIT_EXPORT_PAGE = 1000
31
+
32
+ const AUDIT_SELECT = `SELECT a.id, a.action, a.target, a.ip, a.detail, a.at, a.user_id, a.token_id, a.share_id,
33
+ u.handle, u.display_name, k.name AS token_name, s.name AS share_name,
34
+ tu.handle AS target_handle, tu.display_name AS target_user, tp.name AS target_project,
35
+ tk.name AS target_token, ts.name AS target_share
36
+ FROM audit_log a
37
+ LEFT JOIN users u ON u.id = a.user_id
38
+ LEFT JOIN api_tokens k ON k.id = a.token_id AND k.workspace_id = a.workspace_id
39
+ LEFT JOIN shares s ON s.id = a.share_id AND s.workspace_id = a.workspace_id
40
+ LEFT JOIN users tu ON tu.id = a.target
41
+ LEFT JOIN projects tp ON tp.id = a.target AND tp.workspace_id = a.workspace_id
42
+ LEFT JOIN api_tokens tk ON tk.id = a.target AND tk.workspace_id = a.workspace_id
43
+ LEFT JOIN shares ts ON ts.id = a.target AND ts.workspace_id = a.workspace_id`
44
+
45
+ // What the search looks through: one string per row (no OR, which the tenant
46
+ // guard refuses).
47
+ const AUDIT_HAYSTACK = [
48
+ "replace(a.action, '_', ' ')",
49
+ 'a.target',
50
+ 'a.ip',
51
+ 'a.detail',
52
+ 'u.display_name',
53
+ 'u.handle',
54
+ 'k.name',
55
+ 's.name',
56
+ 'tu.display_name',
57
+ 'tu.handle',
58
+ 'tp.name',
59
+ 'tk.name',
60
+ 'ts.name',
61
+ ]
62
+ .map((column) => `coalesce(${column}, '')`)
63
+ .join(" || ' ' || ")
64
+
65
+ function auditEntry(row) {
66
+ const detail = JSON.parse(row.detail || '{}')
67
+ return {
68
+ id: row.id,
69
+ action: row.action,
70
+ target: row.target,
71
+ targetLabel:
72
+ row.target_user || row.target_project || row.target_token || row.target_share || (row.target_handle ? `@${row.target_handle}` : null),
73
+ at: row.at,
74
+ ip: row.ip,
75
+ user: row.handle || null,
76
+ tokenId: row.token_id,
77
+ actor: actorOf(row, detail),
78
+ detail,
79
+ }
80
+ }
81
+
82
+ // A CSV cell: quoted, and never starting like a spreadsheet formula.
83
+ function csvCell(value) {
84
+ let text = String(value ?? '')
85
+ if (/^[=+\-@\t\r]/.test(text)) text = `'${text}`
86
+ return `"${text.replace(/"/g, '""')}"`
87
+ }
88
+
89
+ const fileSafe = (name) =>
90
+ String(name || 'workspace')
91
+ .toLowerCase()
92
+ .replace(/[^a-z0-9]+/g, '-')
93
+ .replace(/^-+|-+$/g, '')
94
+ .slice(0, 60) || 'workspace'
95
+
96
+ // Deletes every row of a workspace, then its files. Shared by deleting a
97
+ // workspace and deleting an account that is a workspace's only member.
98
+ export function deleteWorkspaceData(db, t, dataDir) {
99
+ const removeFiles = transaction(db, () => deleteWorkspaceRows(t, dataDir))
100
+ removeFiles()
101
+ }
102
+
103
+ // The rows only, inside the caller's transaction (account deletion deletes
104
+ // several workspaces and the account in one). Returns what removes the
105
+ // files, to run once the transaction committed.
106
+ export function deleteWorkspaceRows(t, dataDir) {
107
+ const openPushes = t.all("SELECT id FROM pushes WHERE workspace_id = :ws AND status = 'open'").map((row) => row.id)
108
+ for (const table of ['comments', 'boards', 'pushes', 'api_tokens', 'shares', 'invites', 'projects', 'memberships', 'audit_log']) {
109
+ t.run(`DELETE FROM ${table} WHERE workspace_id = :ws`)
110
+ }
111
+ t.run('DELETE FROM workspaces WHERE workspace_id = :ws')
112
+ return () => {
113
+ if (ID_PATTERNS.workspace.test(t.workspaceId)) fs.rmSync(path.join(dataDir, 'files', t.workspaceId), { recursive: true, force: true })
114
+ for (const id of openPushes) {
115
+ if (ID_PATTERNS.push.test(id)) fs.rmSync(path.join(dataDir, 'staging', id), { recursive: true, force: true })
116
+ }
117
+ }
118
+ }
119
+
120
+ // API tokens of a workspace (or one project) with who made them, and
121
+ // whether that person has left. A token whose maker left or is no longer
122
+ // an admin is 'inactive': refused at every request (tokenCreatorOk), and
123
+ // working again only if they come back as an admin. Revoke those.
124
+ export function listTokens(t, { projectId = null, now: at }) {
125
+ const rows = projectId
126
+ ? t.all(
127
+ `SELECT k.*, p.name AS project_name, u.handle AS creator_handle, u.display_name AS creator_name, m.role AS creator_role
128
+ FROM api_tokens k JOIN projects p ON p.id = k.project_id AND p.workspace_id = k.workspace_id
129
+ LEFT JOIN users u ON u.id = k.created_by
130
+ LEFT JOIN memberships m ON m.user_id = k.created_by AND m.workspace_id = k.workspace_id
131
+ WHERE k.workspace_id = :ws AND k.project_id = :project ORDER BY k.created_at DESC`,
132
+ { project: projectId },
133
+ )
134
+ : t.all(
135
+ `SELECT k.*, p.name AS project_name, u.handle AS creator_handle, u.display_name AS creator_name, m.role AS creator_role
136
+ FROM api_tokens k JOIN projects p ON p.id = k.project_id AND p.workspace_id = k.workspace_id
137
+ LEFT JOIN users u ON u.id = k.created_by
138
+ LEFT JOIN memberships m ON m.user_id = k.created_by AND m.workspace_id = k.workspace_id
139
+ WHERE k.workspace_id = :ws ORDER BY k.created_at DESC`,
140
+ )
141
+ return rows.map((row) => ({
142
+ id: row.id,
143
+ name: row.name,
144
+ prefix: row.prefix,
145
+ projectId: row.project_id,
146
+ projectName: row.project_name,
147
+ scopes: JSON.parse(row.scopes),
148
+ createdAt: row.created_at,
149
+ expiresAt: row.expires_at,
150
+ lastUsedAt: row.last_used_at,
151
+ revokedAt: row.revoked_at,
152
+ status: row.revoked_at
153
+ ? 'revoked'
154
+ : row.expires_at && row.expires_at <= at
155
+ ? 'expired'
156
+ : !row.created_by || !tokenCreatorOk(row.creator_role)
157
+ ? 'inactive'
158
+ : 'active',
159
+ createdBy: row.created_by
160
+ ? { userId: row.created_by, handle: row.creator_handle || null, displayName: row.creator_name || null, left: !row.creator_role }
161
+ : null,
162
+ }))
163
+ }
164
+
165
+ function sizeOf(file) {
166
+ try {
167
+ return fs.statSync(file).size
168
+ } catch (error) {
169
+ if (error.code === 'ENOENT') return null
170
+ throw error
171
+ }
172
+ }
173
+
174
+ // Every file under a folder, as [relative path, absolute path], sorted.
175
+ function filesUnder(root) {
176
+ const out = []
177
+ const walk = (dir, prefix) => {
178
+ let entries = []
179
+ try {
180
+ entries = fs.readdirSync(dir, { withFileTypes: true })
181
+ } catch {
182
+ return
183
+ }
184
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
185
+ const full = path.join(dir, entry.name)
186
+ if (entry.isDirectory()) walk(full, `${prefix}${entry.name}/`)
187
+ else if (entry.isFile()) out.push([`${prefix}${entry.name}`, full])
188
+ }
189
+ }
190
+ walk(root, '')
191
+ return out
192
+ }
193
+
194
+ // What a workspace export holds, read before the first byte goes out: the
195
+ // workspace, members, tokens and share links (no secrets), the files of
196
+ // every board and their total size (callers refuse over ZIP_MAX_BYTES), and
197
+ // the newest audit entry (the export's own entry comes after). Shared by the
198
+ // console's "Download a copy" and `shapewall hosted admin export`.
199
+ export function planWorkspaceExport(t, { dataDir, projects, iso }) {
200
+ const workspace = t.get('SELECT id, name, created_at FROM workspaces WHERE workspace_id = :ws')
201
+ const plan = []
202
+ let total = 0
203
+ for (const project of projects) {
204
+ for (const row of t.all('SELECT * FROM boards WHERE workspace_id = :ws AND project_id = :project ORDER BY created_at, board_id', {
205
+ project: project.id,
206
+ })) {
207
+ if (!ID_RE.test(row.board_id)) continue
208
+ const dir = path.join(projectDir(dataDir, t.workspaceId, project.id), row.board_id)
209
+ // A push commit or retention may remove files while this runs.
210
+ const files = filesUnder(dir).filter(([, file]) => {
211
+ const size = sizeOf(file)
212
+ if (size === null) return false
213
+ total += size
214
+ return true
215
+ })
216
+ plan.push({ project, row, files })
217
+ }
218
+ }
219
+ const members = t
220
+ .all(
221
+ `SELECT m.role, m.created_at, u.handle, u.display_name FROM memberships m JOIN users u ON u.id = m.user_id
222
+ WHERE m.workspace_id = :ws ORDER BY m.created_at`,
223
+ )
224
+ .map((row) => ({ handle: row.handle, displayName: row.display_name, role: row.role, joinedAt: row.created_at }))
225
+ const tokens = listTokens(t, { now: iso() }).map((token) => ({
226
+ name: token.name,
227
+ prefix: token.prefix,
228
+ project: token.projectName,
229
+ scopes: token.scopes,
230
+ createdAt: token.createdAt,
231
+ expiresAt: token.expiresAt,
232
+ lastUsedAt: token.lastUsedAt,
233
+ status: token.status,
234
+ createdBy: token.createdBy?.handle || null,
235
+ }))
236
+ const shares = t
237
+ .all('SELECT name, project_id, mode, passcode_hash, created_at, expires_at, revoked_at, opens FROM shares WHERE workspace_id = :ws')
238
+ .map((row) => ({
239
+ name: row.name,
240
+ projectId: row.project_id,
241
+ mode: row.mode,
242
+ passcode: Boolean(row.passcode_hash),
243
+ createdAt: row.created_at,
244
+ expiresAt: row.expires_at,
245
+ revokedAt: row.revoked_at,
246
+ opens: row.opens,
247
+ }))
248
+ const auditTop = t.get('SELECT MAX(id) AS id FROM audit_log WHERE workspace_id = :ws').id || 0
249
+ return {
250
+ workspace,
251
+ projects,
252
+ plan,
253
+ total,
254
+ files: plan.reduce((sum, item) => sum + item.files.length, 0),
255
+ members,
256
+ tokens,
257
+ shares,
258
+ auditTop,
259
+ }
260
+ }
261
+
262
+ // Writes the zip of a planned export through `write(buffer)` (which may
263
+ // return a promise for backpressure).
264
+ export async function writeWorkspaceExport(t, exported, { write, now, iso, exportedBy }) {
265
+ const { workspace, projects, plan, members, tokens, shares, auditTop } = exported
266
+ const zip = createZip(write, { now })
267
+ const root = `${fileSafe(workspace.name)}-export/`
268
+ const skipped = []
269
+ await zip.add(
270
+ `${root}workspace.json`,
271
+ JSON.stringify(
272
+ {
273
+ format: 'shapewall-workspace-export',
274
+ version: 1,
275
+ exportedAt: iso(),
276
+ exportedBy,
277
+ workspace: { id: workspace.id, name: workspace.name, createdAt: workspace.created_at },
278
+ members,
279
+ projects: projects.map((project) => ({
280
+ id: project.id,
281
+ name: project.name,
282
+ slug: project.slug,
283
+ createdAt: project.created_at,
284
+ })),
285
+ tokens,
286
+ shares,
287
+ },
288
+ null,
289
+ 2,
290
+ ),
291
+ )
292
+ const audit = zip.stream(`${root}audit.json`)
293
+ await audit.write('[')
294
+ let before = auditTop + 1
295
+ let count = 0
296
+ while (count < AUDIT_EXPORT_MAX) {
297
+ const rows = t.all(`${AUDIT_SELECT} WHERE a.workspace_id = :ws AND a.id < :before ORDER BY a.id DESC LIMIT :limit`, {
298
+ before,
299
+ limit: Math.min(AUDIT_EXPORT_PAGE, AUDIT_EXPORT_MAX - count),
300
+ })
301
+ if (!rows.length) break
302
+ let text = ''
303
+ for (const row of rows) text += `${count++ ? ',' : ''}\n ${JSON.stringify(auditEntry(row))}`
304
+ await audit.write(text)
305
+ before = rows[rows.length - 1].id
306
+ }
307
+ await audit.write(count ? '\n]\n' : ']\n')
308
+ await audit.end()
309
+ for (const { project, row, files } of plan) {
310
+ const base = `${root}projects/${project.slug}/boards/${row.board_id}/`
311
+ const comments = createCommentStore(t, project.id, row.board_id).list()
312
+ await zip.add(
313
+ `${base}board.json`,
314
+ JSON.stringify({ ...JSON.parse(row.definition), pushedAt: row.pushed_at, pushes: row.push_count }, null, 2),
315
+ )
316
+ await zip.add(`${base}comments.json`, JSON.stringify(comments, null, 2))
317
+ for (const [relative, file] of files) {
318
+ let data
319
+ try {
320
+ data = fs.readFileSync(file)
321
+ } catch (error) {
322
+ if (error.code !== 'ENOENT') throw error
323
+ skipped.push(`${base.slice(root.length)}files/${relative}`)
324
+ continue
325
+ }
326
+ await zip.add(`${base}files/${relative}`, data)
327
+ }
328
+ }
329
+ // Files removed after the plan (a push swapped the board, retention pruned
330
+ // a version) are listed instead of cutting the zip short.
331
+ if (skipped.length)
332
+ await zip.add(
333
+ `${root}skipped-files.json`,
334
+ JSON.stringify({ reason: 'removed on the server while the export was written', files: skipped }, null, 2),
335
+ )
336
+ await zip.finish()
337
+ return { skipped: skipped.length }
338
+ }
339
+
340
+ export { fileSafe as exportFileName }
341
+
342
+ export { ROLE_ACCESS }
343
+
344
+ function isoOrNull(value) {
345
+ if (typeof value !== 'string' || !value || value.length > 40) return null
346
+ const time = Date.parse(value)
347
+ return Number.isFinite(time) ? new Date(time).toISOString() : null
348
+ }
349
+
350
+ export function mountAdmin(router, deps) {
351
+ const { db, dataDir, iso, now, handle, inWorkspace, needFresh, auditOf, HttpError, listTokens, clientIp, limit } = deps
352
+ // Workspaces with an export being written: one at a time each.
353
+ const exporting = new Set()
354
+
355
+ // ---- Invites: open ones and what happened to the rest ----
356
+ router.get(
357
+ '/workspaces/:ws/invites',
358
+ inWorkspace(NEEDS.invites),
359
+ handle(async (req, res) => {
360
+ const rows = req.t.all(
361
+ `SELECT i.id, i.role, i.created_at, i.expires_at, i.used_at, i.revoked_at, i.email, i.emailed_at, i.note,
362
+ c.handle AS creator_handle, c.display_name AS creator_name, u.handle AS used_handle, u.display_name AS used_name
363
+ FROM invites i LEFT JOIN users c ON c.id = i.created_by LEFT JOIN users u ON u.id = i.used_by
364
+ WHERE i.workspace_id = :ws ORDER BY i.created_at DESC LIMIT :limit`,
365
+ { limit: HISTORY_MAX * 2 },
366
+ )
367
+ const at = iso()
368
+ const invites = rows.map((row) => ({
369
+ id: row.id,
370
+ role: row.role,
371
+ createdAt: row.created_at,
372
+ expiresAt: row.expires_at,
373
+ status: row.used_at ? 'used' : row.revoked_at ? 'revoked' : row.expires_at <= at ? 'expired' : 'pending',
374
+ usedAt: row.used_at,
375
+ revokedAt: row.revoked_at,
376
+ email: row.email || null,
377
+ emailedAt: row.emailed_at || null,
378
+ note: row.note || null,
379
+ createdBy: row.creator_handle ? { handle: row.creator_handle, displayName: row.creator_name } : null,
380
+ usedBy: row.used_handle ? { handle: row.used_handle, displayName: row.used_name } : null,
381
+ }))
382
+ res.json({
383
+ pending: invites.filter((item) => item.status === 'pending'),
384
+ history: invites.filter((item) => item.status !== 'pending').slice(0, HISTORY_MAX),
385
+ })
386
+ }),
387
+ )
388
+
389
+ // ---- Who has access to what ----
390
+ // People get their workspace role on every project; tokens and share
391
+ // links reach one project each.
392
+ router.get(
393
+ '/workspaces/:ws/access',
394
+ inWorkspace(NEEDS.access),
395
+ handle(async (req, res) => {
396
+ const at = iso()
397
+ const projects = req.projects.list().map((project) => ({ id: project.id, name: project.name }))
398
+ const people = req.t
399
+ .all(
400
+ `SELECT m.user_id, m.role, m.created_at, m.last_active_at, u.handle, u.display_name FROM memberships m JOIN users u ON u.id = m.user_id
401
+ WHERE m.workspace_id = :ws ORDER BY m.created_at`,
402
+ )
403
+ .map((row) => ({
404
+ userId: row.user_id,
405
+ handle: row.handle,
406
+ displayName: row.display_name,
407
+ role: row.role,
408
+ access: ROLE_ACCESS[row.role],
409
+ joinedAt: row.created_at,
410
+ lastActiveAt: row.last_active_at || null,
411
+ }))
412
+ const tokens = listTokens(req.t, { now: at }).filter((token) => token.status === 'active')
413
+ const shares = req.t
414
+ .all(
415
+ `SELECT s.*, c.handle AS creator_handle FROM shares s LEFT JOIN users c ON c.id = s.created_by
416
+ WHERE s.workspace_id = :ws AND s.revoked_at IS NULL AND s.expires_at > :now ORDER BY s.created_at DESC`,
417
+ { now: at },
418
+ )
419
+ .map((row) => ({
420
+ id: row.id,
421
+ name: row.name,
422
+ projectId: row.project_id,
423
+ mode: row.mode,
424
+ passcode: Boolean(row.passcode_hash),
425
+ createdAt: row.created_at,
426
+ expiresAt: row.expires_at,
427
+ lastUsedAt: row.last_used_at,
428
+ opens: row.opens,
429
+ createdBy: row.creator_handle || null,
430
+ }))
431
+ const pendingInvites = req.t.all(
432
+ 'SELECT role, COUNT(*) AS n FROM invites WHERE workspace_id = :ws AND used_at IS NULL AND revoked_at IS NULL AND expires_at > :now GROUP BY role',
433
+ { now: at },
434
+ )
435
+ const workspace = req.t.get('SELECT share_links FROM workspaces WHERE workspace_id = :ws')
436
+ res.json({
437
+ projects,
438
+ people,
439
+ tokens,
440
+ shares,
441
+ shareLinksOn: Boolean(workspace.share_links),
442
+ pendingInvites: Object.fromEntries(pendingInvites.map((row) => [row.role, row.n])),
443
+ })
444
+ }),
445
+ )
446
+
447
+ // ---- API tokens across the workspace ----
448
+ router.get(
449
+ '/workspaces/:ws/tokens',
450
+ inWorkspace(NEEDS.tokens),
451
+ handle(async (req, res) => {
452
+ res.json({ tokens: listTokens(req.t, { now: iso() }), projects: req.projects.list().map((p) => ({ id: p.id, name: p.name })) })
453
+ }),
454
+ )
455
+
456
+ // ---- Audit log: filters, search and paging ----
457
+ // ?actor=user:<id>|token:<id>|share:<id>&action=<name>&from=<iso>&to=<iso>&q=<text>&before=<entry id>&limit=50
458
+ // Only fixed fragments make up the WHERE clause; values are bound.
459
+ function auditRows(req, { limit, before }) {
460
+ const query = req.query || {}
461
+ const where = ['a.workspace_id = :ws', 'a.id < :before']
462
+ const params = { before, limit }
463
+ if (typeof query.actor === 'string' && query.actor) {
464
+ const [kind, id] = query.actor.split(':')
465
+ const column = { user: 'a.user_id', token: 'a.token_id', share: 'a.share_id' }[kind]
466
+ if (!column || !/^[a-z]{2}_[a-f0-9]{24}$/.test(id || ''))
467
+ throw new HttpError(400, 'invalid_actor', 'actor: user:<id>, token:<id> or share:<id>.')
468
+ where.push(`${column} = :actor`)
469
+ params.actor = id
470
+ }
471
+ if (typeof query.action === 'string' && query.action) {
472
+ if (!ACTION_RE.test(query.action)) throw new HttpError(400, 'invalid_action', 'action: an action name.')
473
+ where.push('a.action = :action')
474
+ params.action = query.action
475
+ }
476
+ const from = isoOrNull(query.from)
477
+ const to = isoOrNull(query.to)
478
+ if (query.from && !from) throw new HttpError(400, 'invalid_date', 'from: an ISO date.')
479
+ if (query.to && !to) throw new HttpError(400, 'invalid_date', 'to: an ISO date.')
480
+ if (from) {
481
+ where.push('a.at >= :from')
482
+ params.from = from
483
+ }
484
+ if (to) {
485
+ where.push('a.at < :to')
486
+ params.to = to
487
+ }
488
+ // Search: one LIKE over the names, action, target, address and detail.
489
+ const text = typeof query.q === 'string' ? query.q.trim().toLowerCase().slice(0, 100) : ''
490
+ if (text) {
491
+ where.push(`lower(${AUDIT_HAYSTACK}) LIKE :q ESCAPE '\\'`)
492
+ params.q = `%${text.replace(/[\\%_]/g, (char) => `\\${char}`)}%`
493
+ }
494
+ return req.t.all(`${AUDIT_SELECT} WHERE ${where.join(' AND ')} ORDER BY a.id DESC LIMIT :limit`, params)
495
+ }
496
+
497
+ router.get(
498
+ '/workspaces/:ws/audit',
499
+ inWorkspace(NEEDS.audit),
500
+ handle(async (req, res) => {
501
+ const before = Number(req.query?.before)
502
+ const limit = Math.min(Math.max(Number.parseInt(req.query?.limit, 10) || AUDIT_PAGE, 1), AUDIT_PAGE_MAX)
503
+ const rows = auditRows(req, {
504
+ limit: limit + 1,
505
+ before: Number.isSafeInteger(before) && before > 0 ? before : Number.MAX_SAFE_INTEGER,
506
+ })
507
+ const more = rows.length > limit
508
+ const page = rows.slice(0, limit)
509
+ res.json({ entries: page.map(auditEntry), next: more ? page[page.length - 1].id : null })
510
+ }),
511
+ )
512
+
513
+ // The same filters as a CSV file (at most AUDIT_CSV_MAX rows, newest first).
514
+ router.get(
515
+ '/workspaces/:ws/audit/export',
516
+ inWorkspace(NEEDS.audit),
517
+ handle(async (req, res) => {
518
+ const rows = auditRows(req, { limit: AUDIT_CSV_MAX, before: Number.MAX_SAFE_INTEGER })
519
+ const lines = [['time', 'actor_type', 'actor', 'actor_handle', 'action', 'target', 'ip', 'detail']]
520
+ for (const row of rows) {
521
+ const entry = auditEntry(row)
522
+ lines.push([
523
+ entry.at,
524
+ entry.actor.type,
525
+ entry.actor.label,
526
+ entry.actor.handle || '',
527
+ entry.action,
528
+ entry.targetLabel || entry.target || '',
529
+ entry.ip || '',
530
+ JSON.stringify(entry.detail),
531
+ ])
532
+ }
533
+ const workspace = req.t.get('SELECT name FROM workspaces WHERE workspace_id = :ws')
534
+ res.setHeader('Content-Type', 'text/csv; charset=utf-8')
535
+ res.setHeader('Content-Disposition', `attachment; filename="${fileSafe(workspace.name)}-audit.csv"`)
536
+ res.send(`${lines.map((line) => line.map(csvCell).join(',')).join('\r\n')}\r\n`)
537
+ }),
538
+ )
539
+
540
+ // The people, tokens and links that appear in the log, and its actions,
541
+ // for the filter pickers.
542
+ router.get(
543
+ '/workspaces/:ws/audit/filters',
544
+ inWorkspace(NEEDS.audit),
545
+ handle(async (req, res) => {
546
+ const actors = req.t
547
+ .all(
548
+ `SELECT a.user_id, a.token_id, a.share_id, u.handle, u.display_name, k.name AS token_name, s.name AS share_name, COUNT(*) AS n
549
+ FROM audit_log a LEFT JOIN users u ON u.id = a.user_id
550
+ LEFT JOIN api_tokens k ON k.id = a.token_id AND k.workspace_id = a.workspace_id
551
+ LEFT JOIN shares s ON s.id = a.share_id AND s.workspace_id = a.workspace_id
552
+ WHERE a.workspace_id = :ws GROUP BY a.user_id, a.token_id, a.share_id ORDER BY n DESC LIMIT 200`,
553
+ )
554
+ .map((row) => actorOf(row, {}))
555
+ .filter((actor) => actor.type !== 'system')
556
+ const actions = req.t.all('SELECT DISTINCT action FROM audit_log WHERE workspace_id = :ws ORDER BY action').map((row) => row.action)
557
+ res.json({ actors, actions })
558
+ }),
559
+ )
560
+
561
+ // ---- Export: a zip of the workspace before it is deleted (admins) ----
562
+ // workspace.json (members, projects, tokens and share links without their
563
+ // secrets), audit.json, and per project and board the board definition,
564
+ // its comments and every pushed file. Needs a fresh passkey check: it is
565
+ // everything in the workspace in one download.
566
+ // One export at a time per workspace (409 while one runs), a few an hour
567
+ // per person (LIMITS.export), and the audit log read 1000 rows at a time.
568
+ router.post(
569
+ '/workspaces/:ws/export',
570
+ inWorkspace(NEEDS.export),
571
+ limit('export', (req) => req.user.id),
572
+ needFresh,
573
+ handle(async (req, res) => {
574
+ const t = req.t
575
+ if (exporting.has(t.workspaceId))
576
+ throw new HttpError(409, 'export_running', 'An export of this workspace is running. Wait for it to finish, then try again.')
577
+ // Released when the export is written (finally, below) or the
578
+ // response ends some other way (an error before the zip started).
579
+ exporting.add(t.workspaceId)
580
+ res.once('close', () => exporting.delete(t.workspaceId))
581
+ const projects = req.projects.list()
582
+ const exported = planWorkspaceExport(t, { dataDir, projects, iso })
583
+ if (exported.total > ZIP_MAX_BYTES)
584
+ throw new HttpError(413, 'export_too_large', 'This workspace is too large to export here. Back up the server data folder instead.')
585
+ auditOf(req, 'workspace_exported', null, { projects: projects.length, files: exported.files })
586
+
587
+ const stamp = iso().slice(0, 10)
588
+ res.setHeader('Content-Type', 'application/zip')
589
+ res.setHeader('Content-Disposition', `attachment; filename="${fileSafe(exported.workspace.name)}-export-${stamp}.zip"`)
590
+ // Backpressure: wait for the socket to drain, or stop if it closed.
591
+ const write = (buffer) => {
592
+ if (res.destroyed) throw new Error('the download was cancelled')
593
+ if (res.write(buffer)) return null
594
+ return new Promise((resolve) => {
595
+ const done = () => {
596
+ res.off('drain', done)
597
+ res.off('close', done)
598
+ resolve()
599
+ }
600
+ res.on('drain', done)
601
+ res.on('close', done)
602
+ })
603
+ }
604
+ try {
605
+ await writeWorkspaceExport(t, exported, { write, now: now(), iso, exportedBy: req.user.handle })
606
+ res.end()
607
+ } catch (error) {
608
+ // Headers are out: the only honest answer is a broken download.
609
+ deps.log?.(`export: ${error.message}`)
610
+ res.destroy(error)
611
+ } finally {
612
+ exporting.delete(t.workspaceId)
613
+ }
614
+ }),
615
+ )
616
+
617
+ // ---- Settings ----
618
+ router.patch(
619
+ '/workspaces/:ws/settings',
620
+ inWorkspace(NEEDS.settings),
621
+ handle(async (req, res) => {
622
+ const { shareLinks } = req.body || {}
623
+ if (typeof shareLinks !== 'boolean') throw new HttpError(400, 'invalid_settings', 'shareLinks: true or false.')
624
+ // Letting people outside the workspace in is a sensitive change.
625
+ if (shareLinks) deps.freshOrThrow(req)
626
+ const current = req.t.get('SELECT share_links FROM workspaces WHERE workspace_id = :ws')
627
+ if (Boolean(current.share_links) !== shareLinks) {
628
+ req.t.run('UPDATE workspaces SET share_links = :on WHERE workspace_id = :ws', { on: shareLinks ? 1 : 0 })
629
+ auditOf(req, shareLinks ? 'share_links_enabled' : 'share_links_disabled')
630
+ }
631
+ res.json({ settings: { shareLinks } })
632
+ }),
633
+ )
634
+
635
+ // ---- Deleting a workspace (owner) ----
636
+ // Every row of the workspace goes, then its files. The account-level log
637
+ // keeps one line that it happened.
638
+ router.delete(
639
+ '/workspaces/:ws',
640
+ inWorkspace(NEEDS.deleteWorkspace),
641
+ needFresh,
642
+ handle(async (req, res) => {
643
+ const workspace = req.t.get('SELECT id, name FROM workspaces WHERE workspace_id = :ws')
644
+ if (typeof req.body?.confirm !== 'string' || req.body.confirm.trim() !== workspace.name) {
645
+ throw new HttpError(400, 'confirm_name', 'Type the workspace name exactly to delete it.')
646
+ }
647
+ const projects = req.projects.list().length
648
+ const members = req.t.get('SELECT COUNT(*) AS n FROM memberships WHERE workspace_id = :ws').n
649
+ deleteWorkspaceData(db, req.t, dataDir)
650
+ auditAccount(db, {
651
+ userId: req.user.id,
652
+ action: 'workspace_deleted',
653
+ target: workspace.id,
654
+ ip: clientIp(req),
655
+ at: iso(),
656
+ detail: { name: workspace.name, projects, members },
657
+ })
658
+ res.json({ ok: true })
659
+ }),
660
+ )
661
+ }
662
+
663
+ function actorOf(row, detail) {
664
+ if (row.user_id) return { type: 'user', id: row.user_id, label: row.display_name || 'Former member', handle: row.handle || null }
665
+ if (row.token_id) return { type: 'token', id: row.token_id, label: row.token_name || 'Deleted token' }
666
+ if (row.share_id) {
667
+ // Guests who gave no name are "Guest" in the log; only named ones get
668
+ // the "(guest)" mark beside their name, so nobody reads "Guest (guest)".
669
+ const named = [detail.guest, ...(Array.isArray(detail.guests) ? detail.guests : [])].filter(
670
+ (name, index, list) => typeof name === 'string' && name && name !== 'Guest' && list.indexOf(name) === index,
671
+ )
672
+ const unnamed = !detail.guest && Array.isArray(detail.guests) && detail.guests.includes('Guest')
673
+ return {
674
+ type: 'guest',
675
+ id: row.share_id,
676
+ label: named.length ? `${named.join(', ')}${unnamed ? ' and a guest' : ''}` : 'A guest',
677
+ named: named.length > 0,
678
+ link: row.share_name || 'Share link',
679
+ }
680
+ }
681
+ return { type: 'system', id: null, label: 'System' }
682
+ }