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,301 @@
1
+ // Tenancy: every row of a tenant table belongs to one workspace, and every
2
+ // query on one goes through tenant(db, workspaceId). The handle binds :ws
3
+ // itself and refuses SQL that does not constrain workspace_id = :ws (or, for
4
+ // an INSERT, write :ws into workspace_id), so a route cannot forget the scope.
5
+ //
6
+ // The only queries on tenant tables that do not start from a known workspace
7
+ // are the entry points below (an API token or invite looked up by its hash,
8
+ // the workspaces of a signed-in user). They live here and nowhere else;
9
+ // test/hosted-tenancy.test.js fails if other hosted modules touch tenant
10
+ // tables through the raw database handle.
11
+
12
+ import { ID_PATTERNS } from './crypto.js'
13
+ import { inviteCreatorOk, shareCreatorOk, tokenCreatorOk } from './permissions.js'
14
+
15
+ export const TENANT_TABLES = [
16
+ 'workspaces',
17
+ 'memberships',
18
+ 'invites',
19
+ 'projects',
20
+ 'boards',
21
+ 'comments',
22
+ 'api_tokens',
23
+ 'pushes',
24
+ 'audit_log',
25
+ 'shares',
26
+ 'guest_sessions',
27
+ 'agent_claims',
28
+ 'agent_approvals',
29
+ 'import_sessions',
30
+ 'import_batches',
31
+ 'comment_imports',
32
+ ]
33
+ export { ROLES, roleAtLeast } from './permissions.js'
34
+
35
+ export class TenancyError extends Error {}
36
+
37
+ const statements = new WeakMap()
38
+ // node:sqlite binds a missing named parameter as NULL without a word; a
39
+ // typo must fail instead. Every :name in the SQL needs a key (null is fine).
40
+ function prepare(db, sql) {
41
+ let cache = statements.get(db)
42
+ if (!cache) statements.set(db, (cache = new Map()))
43
+ let entry = cache.get(sql)
44
+ if (!entry) {
45
+ entry = { statement: db.prepare(sql), names: [...new Set([...sql.matchAll(/:([a-z_][a-z0-9_]*)/gi)].map((match) => match[1]))] }
46
+ cache.set(sql, entry)
47
+ }
48
+ const check = (params = {}) => {
49
+ for (const name of entry.names) if (params[name] === undefined) throw new TenancyError(`missing SQL parameter :${name}`)
50
+ return params
51
+ }
52
+ return {
53
+ get: (params) => entry.statement.get(check(params)),
54
+ all: (params) => entry.statement.all(check(params)),
55
+ run: (params) => entry.statement.run(check(params)),
56
+ }
57
+ }
58
+
59
+ // Queries on account tables (users, passkeys, sessions, ...), which belong to
60
+ // no workspace. Same parameter checks; tenant tables are refused.
61
+ export function accounts(db) {
62
+ const guard = (sql) => {
63
+ const tables = [...sql.matchAll(/\b(?:FROM|JOIN|INTO|UPDATE)\s+([a-z_]+)/gi)].map((match) => match[1].toLowerCase())
64
+ if (tables.some((name) => TENANT_TABLES.includes(name))) throw new TenancyError('tenant table outside tenant()')
65
+ return prepare(db, sql)
66
+ }
67
+ return {
68
+ get: (sql, params) => guard(sql).get(params),
69
+ all: (sql, params) => guard(sql).all(params),
70
+ run: (sql, params) => guard(sql).run(params),
71
+ }
72
+ }
73
+
74
+ function checkScoped(sql) {
75
+ const text = sql.replace(/\s+/g, ' ').trim()
76
+ if (/^INSERT /i.test(text)) {
77
+ if (!/^INSERT INTO [a-z_]+ \(workspace_id,/i.test(text) || !/VALUES \(:ws,/i.test(text)) {
78
+ throw new TenancyError('tenant INSERT must write :ws as the first column, workspace_id')
79
+ }
80
+ return
81
+ }
82
+ // The scope is the first condition of the WHERE clause, and nothing can
83
+ // widen it: no OR, no second statement, no UNION.
84
+ if (!/\bWHERE (?:[a-z]\.)?workspace_id = :ws(?: AND | ORDER | GROUP | LIMIT |$)/i.test(text)) {
85
+ throw new TenancyError('tenant query must start its WHERE with "workspace_id = :ws"')
86
+ }
87
+ if (/\bOR\b|\bUNION\b|;/i.test(text)) throw new TenancyError('tenant query with OR, UNION or a second statement')
88
+ }
89
+
90
+ // A handle scoped to one workspace. Params are named (:name); :ws is bound
91
+ // here and cannot be overridden by the caller.
92
+ export function tenant(db, workspaceId) {
93
+ if (!ID_PATTERNS.workspace.test(String(workspaceId || ''))) throw new TenancyError('invalid workspace id')
94
+ const bind = (params = {}) => {
95
+ if (Object.hasOwn(params, 'ws')) throw new TenancyError(':ws is bound by the tenant handle')
96
+ return { ...params, ws: workspaceId }
97
+ }
98
+ return {
99
+ workspaceId,
100
+ get(sql, params) {
101
+ checkScoped(sql)
102
+ return prepare(db, sql).get(bind(params))
103
+ },
104
+ all(sql, params) {
105
+ checkScoped(sql)
106
+ return prepare(db, sql).all(bind(params))
107
+ },
108
+ run(sql, params) {
109
+ checkScoped(sql)
110
+ return prepare(db, sql).run(bind(params))
111
+ },
112
+ }
113
+ }
114
+
115
+ // ---- Entry points (global lookups that yield a workspace) ----------------------
116
+
117
+ // The token row for a SHA-256 hash, if it is live: not revoked, not
118
+ // expired, and its maker is still a member who may hold tokens (an admin or
119
+ // owner here; tokenCreatorOk). Callers then scope by its workspace_id.
120
+ export function findApiToken(db, tokenHash, now) {
121
+ const row = prepare(
122
+ db,
123
+ `SELECT t.*, p.name AS project_name, p.slug AS project_slug, w.name AS workspace_name, w.suspended_at AS workspace_suspended_at,
124
+ m.role AS creator_role
125
+ FROM api_tokens t JOIN projects p ON p.id = t.project_id AND p.workspace_id = t.workspace_id
126
+ JOIN workspaces w ON w.id = t.workspace_id
127
+ LEFT JOIN memberships m ON m.workspace_id = t.workspace_id AND m.user_id = t.created_by
128
+ WHERE t.token_hash = :hash`,
129
+ ).get({ hash: tokenHash })
130
+ if (!row || row.revoked_at || (row.expires_at && row.expires_at <= now)) return null
131
+ if (!row.created_by || !tokenCreatorOk(row.creator_role)) return null
132
+ // A workspace the operator suspended refuses every token.
133
+ if (row.workspace_suspended_at) return null
134
+ return row
135
+ }
136
+
137
+ // A share link by the SHA-256 of its token, with what decides whether it
138
+ // works: the workspace switch and the project. Callers check revoked and
139
+ // expiry (shareUsable) and then scope by its workspace_id.
140
+ export function findShareByHash(db, tokenHash) {
141
+ return (
142
+ prepare(
143
+ db,
144
+ `SELECT s.*, w.name AS workspace_name, (w.share_links AND w.suspended_at IS NULL) AS workspace_share_links, p.name AS project_name, m.role AS creator_role
145
+ FROM shares s JOIN workspaces w ON w.id = s.workspace_id
146
+ JOIN projects p ON p.id = s.project_id AND p.workspace_id = s.workspace_id
147
+ LEFT JOIN memberships m ON m.workspace_id = s.workspace_id AND m.user_id = s.created_by
148
+ WHERE s.token_hash = :hash`,
149
+ ).get({ hash: tokenHash }) || null
150
+ )
151
+ }
152
+
153
+ // The same, by id, for a guest session cookie (which names its share).
154
+ export function findShareById(db, shareId) {
155
+ return (
156
+ prepare(
157
+ db,
158
+ `SELECT s.*, w.name AS workspace_name, (w.share_links AND w.suspended_at IS NULL) AS workspace_share_links, p.name AS project_name, m.role AS creator_role
159
+ FROM shares s JOIN workspaces w ON w.id = s.workspace_id
160
+ JOIN projects p ON p.id = s.project_id AND p.workspace_id = s.workspace_id
161
+ LEFT JOIN memberships m ON m.workspace_id = s.workspace_id AND m.user_id = s.created_by
162
+ WHERE s.id = :id`,
163
+ ).get({ id: shareId }) || null
164
+ )
165
+ }
166
+
167
+ // A public project by its public id (src/hosted/public.js), with the
168
+ // workspace switch. Callers check the switch and then scope by workspace_id.
169
+ export function findPublicProject(db, publicId) {
170
+ return (
171
+ prepare(
172
+ db,
173
+ `SELECT p.*, w.public_projects AS workspace_public_projects FROM projects p JOIN workspaces w ON w.id = p.workspace_id
174
+ WHERE p.public_id = :id AND w.suspended_at IS NULL`,
175
+ ).get({ id: publicId }) || null
176
+ )
177
+ }
178
+
179
+ // Whether a share row (from the two lookups above) lets a guest in now.
180
+ // The admin who made the link must still be an admin or owner here: removing
181
+ // or demoting them revokes their links, and this is the second check.
182
+ export const shareUsable = (row, nowIso) =>
183
+ Boolean(row && !row.revoked_at && row.expires_at > nowIso && row.workspace_share_links && shareCreatorOk(row.creator_role))
184
+
185
+ export function findInviteByHash(db, tokenHash) {
186
+ return (
187
+ prepare(
188
+ db,
189
+ `SELECT i.*, w.name AS workspace_name, m.role AS creator_role FROM invites i JOIN workspaces w ON w.id = i.workspace_id
190
+ LEFT JOIN memberships m ON m.workspace_id = i.workspace_id AND m.user_id = i.created_by
191
+ WHERE i.token_hash = :hash`,
192
+ ).get({ hash: tokenHash }) || null
193
+ )
194
+ }
195
+
196
+ // Whether an invite row (from findInviteByHash) still works: unused, not
197
+ // revoked, not expired, and its creator can still invite to that role (an
198
+ // admin up to admin, an owner for owners). A removed or demoted admin's
199
+ // invites are revoked too; this is the second check.
200
+ export function inviteUsable(row, nowIso) {
201
+ if (!row || row.used_at || row.revoked_at || row.expires_at <= nowIso) return false
202
+ return inviteCreatorOk(row.creator_role, row.role)
203
+ }
204
+
205
+ // The workspaces a user belongs to, with their role.
206
+ export function workspacesForUser(db, userId) {
207
+ return prepare(
208
+ db,
209
+ `SELECT w.id, w.name, w.created_at, m.role FROM memberships m JOIN workspaces w ON w.id = m.workspace_id
210
+ WHERE m.user_id = :user ORDER BY w.created_at, w.id`,
211
+ ).all({ user: userId })
212
+ }
213
+
214
+ // The role of a user in a workspace, or null.
215
+ export function roleIn(db, userId, workspaceId) {
216
+ if (!ID_PATTERNS.workspace.test(String(workspaceId || ''))) return null
217
+ const row = tenant(db, workspaceId).get('SELECT role FROM memberships WHERE workspace_id = :ws AND user_id = :user', { user: userId })
218
+ return row?.role || null
219
+ }
220
+
221
+ // Every workspace, for the operator CLI and the retention job
222
+ // (src/hosted/operator.js, retention.js). Each caller then works through
223
+ // tenant(db, id) per workspace.
224
+ export function allWorkspaces(db) {
225
+ return prepare(
226
+ db,
227
+ 'SELECT id, name, created_at, created_by, share_links, suspended_at, suspended_reason, retention_versions FROM workspaces ORDER BY created_at, id',
228
+ ).all()
229
+ }
230
+
231
+ // ---- Audit log ----------------------------------------------------------------
232
+
233
+ function auditRow({ userId = null, tokenId = null, shareId = null, action, target = null, ip = null, detail = {}, at }) {
234
+ return { user: userId, token: tokenId, share: shareId, action, target, ip, detail: JSON.stringify(detail), at }
235
+ }
236
+
237
+ export function audit(t, entry) {
238
+ t.run(
239
+ 'INSERT INTO audit_log (workspace_id, user_id, token_id, share_id, action, target, ip, detail, at) VALUES (:ws, :user, :token, :share, :action, :target, :ip, :detail, :at)',
240
+ auditRow(entry),
241
+ )
242
+ }
243
+
244
+ // Account events that belong to no workspace (sign-in, sign-up, recovery).
245
+ export function auditAccount(db, entry) {
246
+ prepare(
247
+ db,
248
+ 'INSERT INTO audit_log (workspace_id, user_id, token_id, share_id, action, target, ip, detail, at) VALUES (NULL, :user, :token, :share, :action, :target, :ip, :detail, :at)',
249
+ ).run(auditRow(entry))
250
+ }
251
+
252
+ // The account-level events of one user (no workspace): sign-ins, recovery
253
+ // codes, passkeys, sessions. Newest first, `before` an entry id for paging.
254
+ export function accountEvents(db, userId, { before = Number.MAX_SAFE_INTEGER, limit = 50 } = {}) {
255
+ return prepare(
256
+ db,
257
+ 'SELECT id, action, target, ip, detail, at FROM audit_log WHERE workspace_id IS NULL AND user_id = :user AND id < :before ORDER BY id DESC LIMIT :limit',
258
+ ).all({ user: userId, before, limit })
259
+ }
260
+
261
+ // The newest sign-in with a recovery code after `since` (null: ever).
262
+ export function lastRecoverySignIn(db, userId, since) {
263
+ return (
264
+ prepare(
265
+ db,
266
+ `SELECT id, ip, at FROM audit_log WHERE workspace_id IS NULL AND user_id = :user AND action = 'signed_in'
267
+ AND json_extract(detail, '$.via') = 'recovery_code' AND at > :since ORDER BY id DESC LIMIT 1`,
268
+ ).get({ user: userId, since: since || '' }) || null
269
+ )
270
+ }
271
+
272
+ // Whether this account signed in before from a device with this label
273
+ // ("Chrome on macOS"), for the "new device" mark in Account activity.
274
+ export function seenDevice(db, userId, device) {
275
+ if (!device) return true
276
+ return Boolean(
277
+ prepare(
278
+ db,
279
+ `SELECT id FROM audit_log WHERE workspace_id IS NULL AND user_id = :user AND action IN ('signed_in', 'account_created')
280
+ AND json_extract(detail, '$.device') = :device LIMIT 1`,
281
+ ).get({ user: userId, device }),
282
+ )
283
+ }
284
+
285
+ // Account deletion: the person's own account-level log goes with them.
286
+ export function deleteAccountEvents(db, userId) {
287
+ prepare(db, 'DELETE FROM audit_log WHERE workspace_id IS NULL AND user_id = :user').run({ user: userId })
288
+ }
289
+
290
+ // Open pushes older than `cutoff` in any workspace, and the ids of every open
291
+ // push, for the staging sweep (src/hosted/push.js sweepStaging).
292
+ export function staleOpenPushes(db, cutoff) {
293
+ return prepare(db, "SELECT workspace_id, id FROM pushes WHERE status = 'open' AND created_at < :cutoff").all({ cutoff })
294
+ }
295
+ export function openPushIds(db) {
296
+ return new Set(
297
+ prepare(db, "SELECT id FROM pushes WHERE status = 'open'")
298
+ .all()
299
+ .map((row) => row.id),
300
+ )
301
+ }