shapewall 0.3.3 → 0.7.0

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 (157) hide show
  1. package/CHANGELOG.md +501 -0
  2. package/README.md +87 -4
  3. package/THIRD_PARTY.md +15 -0
  4. package/dist/agent/package-lock.json +594 -2
  5. package/dist/client/assets/BoardChat-WS8mAIW6.js +27 -0
  6. package/dist/client/assets/{BuzzDialog-Ix9qJvim.js → BuzzDialog-B-Mlr6wF.js} +1 -1
  7. package/dist/client/assets/ChecksPanel-Dx1ZLBR6.js +1 -0
  8. package/dist/client/assets/History-sXhmpcvs.js +1 -0
  9. package/dist/client/assets/LocalSettings-CtGzz9F3.js +1 -0
  10. package/dist/client/assets/{Management-NVFDtSZB.js → Management-CGHe8Wt9.js} +1 -1
  11. package/dist/client/assets/QuickConnect-DEk84E4A.js +1 -0
  12. package/dist/client/assets/{ShareDialog-By0ETg6n.js → ShareDialog-CGGx-AYK.js} +2 -2
  13. package/dist/client/assets/{app-update-dialog-RGIw24iZ.js → app-update-dialog-_bVp8hnC.js} +1 -1
  14. package/dist/client/assets/{circle-x-B6KfScOE.js → circle-x-BWoHA1QY.js} +1 -1
  15. package/dist/client/assets/index-Bm-Xd3YN.js +37 -0
  16. package/dist/client/assets/index-C7Ostk3K.css +2 -0
  17. package/dist/client/assets/play-BzQ3tRTv.js +1 -0
  18. package/dist/client/assets/{refresh-cw-vkgvCCfR.js → refresh-cw-BYBMyDKT.js} +1 -1
  19. package/dist/client/assets/{runtime-Bft6x_6E.js → runtime-Bvq10IhH.js} +1 -1
  20. package/dist/client/assets/ui-CAY6myRA.js +41 -0
  21. package/dist/client/build-info.json +1 -1
  22. package/dist/client/index.html +3 -3
  23. package/dist/client/sw.js +2 -2
  24. package/dist/console/assets/LocalAccountsApp-CWRguRRL.js +1 -0
  25. package/dist/console/assets/LocalConsole--I2SaIpr.js +2 -0
  26. package/dist/console/assets/LocalUsage-BmpCZ36k.js +1 -0
  27. package/dist/console/assets/app-update-dialog-B8M9plaT.js +1 -0
  28. package/dist/console/assets/app-version-muKrQqbL.js +1 -0
  29. package/dist/console/assets/console-CrhTsPbz.css +2 -0
  30. package/dist/console/assets/console-DxapQ9oS.js +11 -0
  31. package/dist/console/assets/local-agents-CoqD4dSN.js +6 -0
  32. package/dist/console/assets/minus-DDQ0ydcM.js +1 -0
  33. package/dist/console/assets/tailnet-C5Flwl_d.js +2 -0
  34. package/dist/console/assets/theme-DCd0qh4l.js +1 -0
  35. package/dist/console/assets/ui-Bry1mnCY.js +41 -0
  36. package/dist/console/assets/usage-CIPWnHaS.css +1 -0
  37. package/dist/console/assets/usage-CqVjMb7m.js +5 -0
  38. package/dist/console/assets/usage-D1G0GgE3.js +56 -0
  39. package/dist/console/build-info.json +1 -1
  40. package/dist/console/console.html +8 -2
  41. package/docs/agent-hardening.md +206 -0
  42. package/docs/agent-recipes.md +23 -0
  43. package/docs/agent-workflow.md +5 -0
  44. package/docs/agents.md +49 -6
  45. package/docs/architecture.md +10 -4
  46. package/docs/deployment.md +39 -17
  47. package/docs/design-system.md +56 -7
  48. package/docs/hosted.md +1800 -46
  49. package/docs/images/board-overview.png +0 -0
  50. package/docs/images/journeys.png +0 -0
  51. package/docs/images/live-comment.png +0 -0
  52. package/docs/images/phone-comment.png +0 -0
  53. package/docs/images/phone-overview.png +0 -0
  54. package/docs/images/variant.png +0 -0
  55. package/docs/where-to-run.md +119 -3
  56. package/package.json +6 -1
  57. package/src/agent/backends/acp.js +745 -44
  58. package/src/agent/branch-mode.js +17 -3
  59. package/src/agent/card-hash.js +65 -0
  60. package/src/agent/context.js +41 -0
  61. package/src/agent/exec-paths.js +105 -0
  62. package/src/agent/routes.js +23 -2
  63. package/src/agent/run.js +11 -1
  64. package/src/agent/starter/cli.js +6 -1
  65. package/src/agent/turn-changes.js +70 -8
  66. package/src/agent/usage-log.js +251 -0
  67. package/src/cli/args.js +37 -0
  68. package/src/cli/commands.js +20 -5
  69. package/src/cli/help.js +73 -3
  70. package/src/cli/init.js +2 -1
  71. package/src/cli/serve.js +20 -5
  72. package/src/cli.js +8 -0
  73. package/src/hosted/access-cli.js +99 -1
  74. package/src/hosted/activity-core.js +232 -0
  75. package/src/hosted/activity.js +375 -0
  76. package/src/hosted/admin.js +87 -13
  77. package/src/hosted/agent-approvals.js +29 -4
  78. package/src/hosted/agent-link.js +1032 -0
  79. package/src/hosted/agent-policy.js +10 -3
  80. package/src/hosted/agent-presence.js +63 -22
  81. package/src/hosted/agent-routes.js +135 -0
  82. package/src/hosted/agents.js +1206 -0
  83. package/src/hosted/app.js +178 -12
  84. package/src/hosted/auth-routes.js +156 -15
  85. package/src/hosted/auth.js +123 -20
  86. package/src/hosted/board-routes.js +129 -5
  87. package/src/hosted/chat-frames.js +246 -0
  88. package/src/hosted/chat-job.js +204 -0
  89. package/src/hosted/chat-permissions.js +203 -0
  90. package/src/hosted/chat-routes.js +1009 -0
  91. package/src/hosted/chat-store.js +477 -0
  92. package/src/hosted/comment-files.js +11 -1
  93. package/src/hosted/comments.js +1 -1
  94. package/src/hosted/console-routes.js +122 -34
  95. package/src/hosted/db.js +295 -0
  96. package/src/hosted/device-routes.js +88 -10
  97. package/src/hosted/device.js +54 -4
  98. package/src/hosted/events.js +3 -3
  99. package/src/hosted/guards.js +337 -27
  100. package/src/hosted/http.js +6 -3
  101. package/src/hosted/membership.js +22 -3
  102. package/src/hosted/operator-access.js +418 -0
  103. package/src/hosted/operator.js +106 -2
  104. package/src/hosted/ops-cli.js +238 -3
  105. package/src/hosted/pages.js +4 -0
  106. package/src/hosted/passkey-policy.js +75 -0
  107. package/src/hosted/permissions.js +52 -6
  108. package/src/hosted/presence.js +31 -2
  109. package/src/hosted/projects.js +30 -2
  110. package/src/hosted/public.js +4 -4
  111. package/src/hosted/ratelimit.js +14 -0
  112. package/src/hosted/retention.js +18 -2
  113. package/src/hosted/server.js +123 -11
  114. package/src/hosted/shares.js +2 -2
  115. package/src/hosted/step-up-settings.js +68 -0
  116. package/src/hosted/step-up.js +135 -0
  117. package/src/hosted/tailnet-identity.js +24 -0
  118. package/src/hosted/tailnet-routes.js +342 -0
  119. package/src/hosted/tailnet.js +220 -0
  120. package/src/hosted/tailscale.js +75 -9
  121. package/src/hosted/tenancy.js +66 -1
  122. package/src/hosted/token-api.js +119 -20
  123. package/src/hosted/token-events.js +5 -3
  124. package/src/hosted/tokens.js +29 -6
  125. package/src/hosted/turn-hub.js +152 -0
  126. package/src/hosted/usage-core.js +624 -0
  127. package/src/hosted/usage-layout.js +724 -0
  128. package/src/hosted/usage-routes.js +375 -0
  129. package/src/hosted/usage-shape.js +256 -0
  130. package/src/hosted/usage.js +641 -0
  131. package/src/remote/agent-connect.js +469 -0
  132. package/src/remote/agent-fix.js +611 -0
  133. package/src/remote/agent-job.js +216 -0
  134. package/src/remote/agent-link.js +906 -0
  135. package/src/remote/agent-policy-file.js +242 -0
  136. package/src/remote/credentials.js +35 -1
  137. package/src/remote/login.js +44 -9
  138. package/src/remote/share.js +1 -1
  139. package/src/remote/tailnet-cli.js +547 -0
  140. package/src/server/app.js +15 -0
  141. package/src/server/pairing-routes.js +34 -5
  142. package/src/server/tailscale.js +97 -4
  143. package/src/tailnet-proof.js +766 -0
  144. package/dist/client/assets/BoardChat-DxehB761.js +0 -27
  145. package/dist/client/assets/ChecksPanel-pA_ueIaJ.js +0 -1
  146. package/dist/client/assets/History-C9N32kCv.js +0 -1
  147. package/dist/client/assets/LocalSettings-DawtKnvi.js +0 -1
  148. package/dist/client/assets/QuickConnect-DO1TjS1t.js +0 -1
  149. package/dist/client/assets/index-CsqLdqGx.css +0 -2
  150. package/dist/client/assets/index-DnZarJ3U.js +0 -37
  151. package/dist/client/assets/shield-check-QzwGhz0t.js +0 -1
  152. package/dist/client/assets/ui-DI-FGWWK.js +0 -41
  153. package/dist/console/assets/LocalAccountsApp-VOCZg8dg.js +0 -1
  154. package/dist/console/assets/LocalConsole-CMwAW-mF.js +0 -1
  155. package/dist/console/assets/app-update-dialog-Cw6UDqNP.js +0 -1
  156. package/dist/console/assets/console-DgfWmUEx.js +0 -55
  157. package/dist/console/assets/console-Lis0vvdL.css +0 -2
@@ -0,0 +1,375 @@
1
+ // People's activity in a workspace, read from the audit log (it stays the
2
+ // security record; this adds no second log). Who signed in, who changed
3
+ // which setting and from what to what, who connected, approved, revoked or
4
+ // reconfigured which agent, who answered which approval card, who exported
5
+ // what, which token was made or revoked. Usage (src/hosted/usage.js) is the
6
+ // record of agent turns; the two link to each other and are never merged.
7
+ //
8
+ // viewer activityViewer(role, userId): owners and admins read the whole
9
+ // workspace; anyone else in it reads their own activity only.
10
+ // list workspace audit entries, plus the account events of the
11
+ // workspace's members since each joined (sign-in, sign-out,
12
+ // passkeys, sessions: src/hosted/tenancy.js memberAccountEvents),
13
+ // filtered by person, agent, project, kind of action and period.
14
+ // review the access review: every person, token, agent and share link
15
+ // with what it reaches, who made it and when it was last used.
16
+ //
17
+ // The log holds no comment text, prompt or answer: actions, ids, names and
18
+ // before/after values of settings.
19
+
20
+ import { AUDIT_HAYSTACK, AUDIT_SELECT, auditEntry, listTokens } from './admin.js'
21
+ import { ACTION_RE, ACTIVITY_LIMITS, USER_ID, activityEntry, staleSince, wantedActions } from './activity-core.js'
22
+ import { HttpError } from './http.js'
23
+ import { ROLE_ACCESS } from './permissions.js'
24
+ import { memberAccountEvents } from './tenancy.js'
25
+ import { ACCOUNT_ACTIONS, ACTION_GROUP_IDS } from './usage-shape.js'
26
+
27
+ // Everything that is not SQL lives in activity-core.js (the public demo's
28
+ // in-browser backend shares it); callers keep importing it from here.
29
+ export { ACTIVITY_LIMITS, activityCsv, activityViewer, cleanActivityFilter, reviewCsv } from './activity-core.js'
30
+
31
+ const DAY = 86_400_000
32
+
33
+ const quoted = (values) => values.map((value) => `'${value}'`).join(', ')
34
+ export function createActivity(t, { db, now = () => new Date() } = {}) {
35
+ const iso = (offset = 0) => new Date(now().getTime() + offset).toISOString()
36
+ let lookup = null
37
+ function names() {
38
+ if (lookup) return lookup
39
+ lookup = { agent: new Map(), project: new Map() }
40
+ for (const row of t.all(
41
+ `SELECT a.id, k.name FROM agents a JOIN api_tokens k ON k.id = a.token_id AND k.workspace_id = a.workspace_id WHERE a.workspace_id = :ws`,
42
+ ))
43
+ lookup.agent.set(row.id, row.name)
44
+ for (const row of t.all('SELECT id, name FROM projects WHERE workspace_id = :ws')) lookup.project.set(row.id, row.name)
45
+ return lookup
46
+ }
47
+
48
+ // An audit entry as the Activity page shows it: the audit view, plus its
49
+ // group, where it came from, the agent and project it is about, and what
50
+ // changed for a setting.
51
+ const entryView = (row, { account = false } = {}) =>
52
+ activityEntry(auditEntry({ token_id: null, share_id: null, ...row }), names, { account })
53
+
54
+ // One page, newest first. `before`: the last entry id of the page before.
55
+ function list(filter, viewer, { before = null, limit = ACTIVITY_LIMITS.page } = {}) {
56
+ if (!viewer) throw new HttpError(403, 'forbidden', 'Activity is for the people of this workspace.')
57
+ const size = Math.min(Math.max(Number.parseInt(limit, 10) || ACTIVITY_LIMITS.page, 1), ACTIVITY_LIMITS.pageMax)
58
+ // A text search reads every entry it is given: it always has a start. Without one, the last 90 days.
59
+ const searchedFrom = filter.q && !filter.from ? iso(-ACTIVITY_LIMITS.searchDays * DAY) : null
60
+ if (searchedFrom) filter = { ...filter, from: searchedFrom }
61
+ const cursor = Number.isSafeInteger(Number(before)) && Number(before) > 0 ? Number(before) : Number.MAX_SAFE_INTEGER
62
+ // Anyone but an admin reads their own entries, whatever the filter says.
63
+ const person = viewer.all ? filter.person : viewer.userId
64
+ const wanted = wantedActions(filter)
65
+ const clauses = ['a.workspace_id = :ws', 'a.id < :before']
66
+ const params = { before: cursor, limit: size + 1 }
67
+ if (person) {
68
+ clauses.push('a.user_id = :person')
69
+ params.person = person
70
+ }
71
+ if (filter.source === 'person') clauses.push('a.user_id IS NOT NULL')
72
+ if (filter.source === 'token') clauses.push('a.token_id IS NOT NULL')
73
+ if (filter.source === 'guest') clauses.push('a.share_id IS NOT NULL')
74
+ if (filter.source === 'system') clauses.push('a.user_id IS NULL AND a.token_id IS NULL AND a.share_id IS NULL')
75
+ if (wanted) clauses.push(wanted.length ? `a.action IN (${quoted(wanted.filter((item) => ACTION_RE.test(item)))})` : '1 = 0')
76
+ if (filter.agent) {
77
+ clauses.push(":agent IN (a.target, json_extract(a.detail, '$.agent'), json_extract(a.detail, '$.from'))")
78
+ params.agent = filter.agent
79
+ }
80
+ if (filter.project) {
81
+ clauses.push(":project IN (substr(coalesce(a.target, ''), 1, 27), json_extract(a.detail, '$.project'))")
82
+ params.project = filter.project
83
+ }
84
+ if (filter.from) {
85
+ clauses.push('a.at >= :from')
86
+ params.from = filter.from
87
+ }
88
+ if (filter.to) {
89
+ clauses.push('a.at < :to')
90
+ params.to = filter.to
91
+ }
92
+ if (filter.q) {
93
+ clauses.push(`lower(${AUDIT_HAYSTACK}) LIKE :q ESCAPE '\\'`)
94
+ params.q = `%${filter.q.replace(/[\\%_]/g, (char) => `\\${char}`)}%`
95
+ }
96
+ const workspace = t.all(`${AUDIT_SELECT} WHERE ${clauses.join(' AND ')} ORDER BY a.id DESC LIMIT :limit`, params)
97
+ // Account events are about a person, never an agent, a project or a
98
+ // token: they join in only when the filter could match them.
99
+ const accountActions = (wanted || ACCOUNT_ACTIONS).filter((item) => ACCOUNT_ACTIONS.includes(item))
100
+ // And they are the person's own: a reader gets their own (when the list
101
+ // is theirs alone), and an owner the members' only where the operator
102
+ // said so (activityViewer).
103
+ const accountsOf = viewer.accounts === 'members' && viewer.all ? person : person === viewer.userId ? viewer.userId : false
104
+ const account =
105
+ accountsOf !== false && !filter.agent && !filter.project && (!filter.source || filter.source === 'person') && accountActions.length
106
+ ? memberAccountEvents(db, t.workspaceId, {
107
+ userId: accountsOf,
108
+ actions: accountActions,
109
+ from: filter.from,
110
+ to: filter.to,
111
+ q: filter.q || null,
112
+ before: cursor,
113
+ limit: size + 1,
114
+ })
115
+ : []
116
+ const merged = [
117
+ ...workspace.map((row) => ({ id: row.id, view: () => entryView(row) })),
118
+ ...account.map((row) => ({ id: row.id, view: () => entryView(row, { account: true }) })),
119
+ ].sort((a, b) => b.id - a.id)
120
+ const page = merged.slice(0, size)
121
+ return { entries: page.map((item) => item.view()), next: merged.length > size ? page.at(-1).id : null, searchedFrom }
122
+ }
123
+ // Every entry of a filter, newest first, up to `max`, a page at a time: for the export.
124
+ function all(filter, viewer, { max = ACTIVITY_LIMITS.exportRows } = {}) {
125
+ const entries = []
126
+ let before = null
127
+ while (entries.length < max) {
128
+ const page = list(filter, viewer, { before, limit: Math.min(ACTIVITY_LIMITS.pageMax, max - entries.length) })
129
+ entries.push(...page.entries)
130
+ if (!page.next) break
131
+ before = page.next
132
+ }
133
+ return entries
134
+ }
135
+
136
+ // What the filters offer: people, agents, projects, and the groups.
137
+ function filters(viewer) {
138
+ if (!viewer) throw new HttpError(403, 'forbidden', 'Activity is for the people of this workspace.')
139
+ if (!viewer.all) return { people: [], agents: [], projects: [], groups: ACTION_GROUP_IDS, accounts: viewer.accounts }
140
+ return {
141
+ accounts: viewer.accounts,
142
+ people: t
143
+ .all(
144
+ 'SELECT m.user_id, m.role, u.handle, u.display_name FROM memberships m JOIN users u ON u.id = m.user_id WHERE m.workspace_id = :ws ORDER BY u.display_name',
145
+ )
146
+ .map((row) => ({ id: row.user_id, name: row.display_name, handle: row.handle, role: row.role })),
147
+ agents: [...names().agent].map(([key, name]) => ({ id: key, name })),
148
+ projects: [...names().project].map(([key, name]) => ({ id: key, name })),
149
+ groups: ACTION_GROUP_IDS,
150
+ }
151
+ }
152
+
153
+ // ---- A person ----
154
+
155
+ // One member as a security review reads them: role, when they joined and
156
+ // were last active, what they made (tokens, agents, share links, invites),
157
+ // what they can reach, how much they wrote, and their devices. Admins and
158
+ // owners, or the person themselves. `sessionsOf(userId)`: their live
159
+ // sessions (account data, src/hosted/auth.js listSessions).
160
+ function person(userId, viewer, { sessionsOf = () => [] } = {}) {
161
+ if (!viewer || typeof userId !== 'string' || !USER_ID.test(userId)) return null
162
+ if (!viewer.all && viewer.userId !== userId) return null
163
+ const member = t.get(
164
+ `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
165
+ WHERE m.workspace_id = :ws AND m.user_id = :user`,
166
+ { user: userId },
167
+ )
168
+ if (!member) return null
169
+ const at = iso()
170
+ const roleChange = t.get(
171
+ "SELECT a.at, a.detail, a.user_id FROM audit_log a WHERE a.workspace_id = :ws AND a.action = 'member_role_changed' AND a.target = :user ORDER BY a.id DESC LIMIT 1",
172
+ { user: userId },
173
+ )
174
+ const comments = t.get(
175
+ 'SELECT COUNT(*) AS n, MAX(created_at) AS last FROM comments WHERE workspace_id = :ws AND author_user_id = :user',
176
+ { user: userId },
177
+ )
178
+ const chats = t.get(
179
+ 'SELECT COUNT(*) AS n, MAX(created_at) AS last FROM chat_messages WHERE workspace_id = :ws AND author_user_id = :user',
180
+ {
181
+ user: userId,
182
+ },
183
+ )
184
+ const approvals = t.get(
185
+ "SELECT COUNT(*) AS n, MAX(answered_at) AS last FROM chat_permissions WHERE workspace_id = :ws AND answered_by = :user AND state IN ('approved', 'denied')",
186
+ { user: userId },
187
+ )
188
+ let change = null
189
+ if (roleChange) {
190
+ try {
191
+ const detail = JSON.parse(roleChange.detail || '{}')
192
+ change = { at: roleChange.at, from: detail.from || null, to: detail.to || null }
193
+ } catch {
194
+ change = { at: roleChange.at, from: null, to: null }
195
+ }
196
+ }
197
+ return {
198
+ userId: member.user_id,
199
+ handle: member.handle,
200
+ displayName: member.display_name,
201
+ role: member.role,
202
+ access: ROLE_ACCESS[member.role],
203
+ joinedAt: member.created_at,
204
+ lastActiveAt: member.last_active_at || null,
205
+ roleChanged: change,
206
+ // What they reach: their role, on every project of the workspace.
207
+ projects: t
208
+ .all('SELECT id, name FROM projects WHERE workspace_id = :ws ORDER BY name')
209
+ .map((row) => ({ id: row.id, name: row.name })),
210
+ tokens: listTokens(t, { now: at })
211
+ .filter((token) => token.createdBy?.userId === userId)
212
+ .map((token) => ({
213
+ id: token.id,
214
+ name: token.name,
215
+ projectId: token.projectId,
216
+ projectName: token.projectName,
217
+ scopes: token.scopes,
218
+ status: token.status,
219
+ createdAt: token.createdAt,
220
+ lastUsedAt: token.lastUsedAt,
221
+ })),
222
+ agents: t
223
+ .all(
224
+ `SELECT a.id, a.machine, a.kind, a.created_at, a.last_seen_at, k.name, k.revoked_at, p.name AS project_name, a.project_id
225
+ FROM agents a JOIN api_tokens k ON k.id = a.token_id AND k.workspace_id = a.workspace_id
226
+ JOIN projects p ON p.id = a.project_id AND p.workspace_id = a.workspace_id
227
+ WHERE a.workspace_id = :ws AND a.created_by = :user ORDER BY a.created_at DESC`,
228
+ { user: userId },
229
+ )
230
+ .map((row) => ({
231
+ id: row.id,
232
+ name: row.name,
233
+ machine: row.machine || null,
234
+ kind: row.kind,
235
+ projectId: row.project_id,
236
+ projectName: row.project_name,
237
+ revoked: Boolean(row.revoked_at),
238
+ createdAt: row.created_at,
239
+ lastSeenAt: row.last_seen_at || null,
240
+ })),
241
+ shares: t.get(
242
+ 'SELECT COUNT(*) AS n FROM shares WHERE workspace_id = :ws AND created_by = :user AND revoked_at IS NULL AND expires_at > :at',
243
+ {
244
+ user: userId,
245
+ at,
246
+ },
247
+ ).n,
248
+ // Reading and commenting is activity, not audit: counts and last times.
249
+ counts: {
250
+ comments: { count: comments.n, lastAt: comments.last || null },
251
+ chatMessages: { count: chats.n, lastAt: chats.last || null },
252
+ approvalsAnswered: { count: approvals.n, lastAt: approvals.last || null },
253
+ },
254
+ // Devices they are signed in on: a label and when it was last seen.
255
+ // Sessions are the person's own (they cover every workspace they are
256
+ // in): shown to them, and to an owner only where the operator said so.
257
+ // null: not this reader's to see.
258
+ sessions:
259
+ viewer.userId === userId || viewer.accounts === 'members'
260
+ ? sessionsOf(userId).map((session) => ({
261
+ device: session.device || null,
262
+ via: session.via,
263
+ createdAt: session.createdAt,
264
+ lastSeenAt: session.lastSeenAt,
265
+ }))
266
+ : null,
267
+ }
268
+ }
269
+
270
+ // ---- The access review ----
271
+
272
+ // Everything that can reach the workspace, in one place: people, tokens,
273
+ // agents, share links and open invites, each with who made it, what it
274
+ // reaches and when it was last used. `stale`: not used for 90 days (or
275
+ // never, and made more than 90 days ago). `agents`: the console's list of
276
+ // agents (src/hosted/agents.js consoleList).
277
+ function review({ agents = [] } = {}) {
278
+ const at = iso()
279
+ const stale = staleSince(at)
280
+ const people = t
281
+ .all(
282
+ `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
283
+ WHERE m.workspace_id = :ws ORDER BY m.created_at`,
284
+ )
285
+ .map((row) => ({
286
+ userId: row.user_id,
287
+ handle: row.handle,
288
+ displayName: row.display_name,
289
+ role: row.role,
290
+ access: ROLE_ACCESS[row.role],
291
+ reaches: 'Every project',
292
+ joinedAt: row.created_at,
293
+ lastActiveAt: row.last_active_at || null,
294
+ stale: stale(row.last_active_at, row.created_at),
295
+ }))
296
+ const tokens = listTokens(t, { now: at })
297
+ .filter((token) => token.status === 'active' || token.status === 'inactive')
298
+ .map((token) => ({
299
+ id: token.id,
300
+ name: token.name,
301
+ prefix: token.prefix,
302
+ projectId: token.projectId,
303
+ projectName: token.projectName,
304
+ scopes: token.scopes,
305
+ status: token.status,
306
+ createdAt: token.createdAt,
307
+ expiresAt: token.expiresAt,
308
+ lastUsedAt: token.lastUsedAt,
309
+ createdBy: token.createdBy,
310
+ stale: stale(token.lastUsedAt, token.createdAt),
311
+ }))
312
+ const agentRows = agents
313
+ .filter((agent) => agent.state !== 'revoked')
314
+ .map((agent) => ({
315
+ id: agent.id,
316
+ name: agent.name,
317
+ kind: agent.kind,
318
+ machine: agent.machine,
319
+ projectId: agent.projectId,
320
+ projectName: agent.projectName,
321
+ state: agent.state,
322
+ audience: agent.audience?.effective || agent.audience?.kind || null,
323
+ audienceLabel: agent.audience?.text || null,
324
+ approvalRule: agent.approval?.effectiveRule || 'ask',
325
+ edits: agent.approval?.mode || null,
326
+ createdAt: agent.createdAt,
327
+ createdBy: agent.createdBy,
328
+ lastSeenAt: agent.lastSeenAt || null,
329
+ tokenId: agent.token?.id || null,
330
+ stale: stale(agent.lastSeenAt, agent.createdAt),
331
+ }))
332
+ const shares = t
333
+ .all(
334
+ `SELECT s.*, c.handle AS creator_handle, c.display_name AS creator_name, p.name AS project_name FROM shares s
335
+ LEFT JOIN users c ON c.id = s.created_by JOIN projects p ON p.id = s.project_id AND p.workspace_id = s.workspace_id
336
+ WHERE s.workspace_id = :ws AND s.revoked_at IS NULL AND s.expires_at > :now ORDER BY s.created_at DESC`,
337
+ { now: at },
338
+ )
339
+ .map((row) => ({
340
+ id: row.id,
341
+ name: row.name,
342
+ projectId: row.project_id,
343
+ projectName: row.project_name,
344
+ mode: row.mode,
345
+ passcode: Boolean(row.passcode_hash),
346
+ createdAt: row.created_at,
347
+ expiresAt: row.expires_at,
348
+ lastUsedAt: row.last_used_at,
349
+ opens: row.opens,
350
+ createdBy: row.created_by ? { userId: row.created_by, handle: row.creator_handle, displayName: row.creator_name } : null,
351
+ stale: stale(row.last_used_at, row.created_at),
352
+ }))
353
+ const publicProjects = t
354
+ .all('SELECT id, name, public_at FROM projects WHERE workspace_id = :ws AND public_id IS NOT NULL ORDER BY name')
355
+ .map((row) => ({ id: row.id, name: row.name, publicAt: row.public_at }))
356
+ const invites = t
357
+ .all(
358
+ `SELECT i.id, i.role, i.created_at, i.expires_at, i.note, c.handle AS creator_handle, c.display_name AS creator_name, i.created_by
359
+ FROM invites i LEFT JOIN users c ON c.id = i.created_by
360
+ WHERE i.workspace_id = :ws AND i.used_at IS NULL AND i.revoked_at IS NULL AND i.expires_at > :now ORDER BY i.created_at DESC`,
361
+ { now: at },
362
+ )
363
+ .map((row) => ({
364
+ id: row.id,
365
+ role: row.role,
366
+ createdAt: row.created_at,
367
+ expiresAt: row.expires_at,
368
+ note: row.note || null,
369
+ createdBy: row.created_by ? { userId: row.created_by, handle: row.creator_handle, displayName: row.creator_name } : null,
370
+ }))
371
+ return { at, staleDays: ACTIVITY_LIMITS.staleDays, people, tokens, agents: agentRows, shares, publicProjects, invites }
372
+ }
373
+
374
+ return { list, all, filters, person, review, entryView }
375
+ }
@@ -5,8 +5,9 @@
5
5
  // every query goes through the request's tenant handle (req.t).
6
6
  //
7
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.
8
+ // console and the public demo. Deleting the workspace always needs a fresh
9
+ // passkey check and the workspace's name typed back; what else asks for the
10
+ // passkey again is the workspace's own choice (src/hosted/step-up.js).
10
11
 
11
12
  import fs from 'node:fs'
12
13
  import path from 'node:path'
@@ -16,8 +17,11 @@ import { ID_RE } from '../config.js'
16
17
  import { createCommentStore } from './comments.js'
17
18
  import { NEEDS, ROLE_ACCESS, tokenCreatorOk } from './permissions.js'
18
19
  import { projectDir } from './projects.js'
20
+ import { stepUpSettings } from './step-up-settings.js'
19
21
  import { auditAccount } from './tenancy.js'
20
22
  import { ZIP_MAX_BYTES, createZip } from './zip.js'
23
+ import { createChatStore } from './chat-store.js'
24
+ import { createUsage } from './usage.js'
21
25
 
22
26
  const AUDIT_PAGE = 50
23
27
  const AUDIT_PAGE_MAX = 200
@@ -29,7 +33,7 @@ const AUDIT_CSV_MAX = 10_000
29
33
  const AUDIT_EXPORT_MAX = 100_000
30
34
  const AUDIT_EXPORT_PAGE = 1000
31
35
 
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,
36
+ export 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
37
  u.handle, u.display_name, k.name AS token_name, s.name AS share_name,
34
38
  tu.handle AS target_handle, tu.display_name AS target_user, tp.name AS target_project,
35
39
  tk.name AS target_token, ts.name AS target_share
@@ -44,7 +48,7 @@ const AUDIT_SELECT = `SELECT a.id, a.action, a.target, a.ip, a.detail, a.at, a.u
44
48
 
45
49
  // What the search looks through: one string per row (no OR, which the tenant
46
50
  // guard refuses).
47
- const AUDIT_HAYSTACK = [
51
+ export const AUDIT_HAYSTACK = [
48
52
  "replace(a.action, '_', ' ')",
49
53
  'a.target',
50
54
  'a.ip',
@@ -62,7 +66,7 @@ const AUDIT_HAYSTACK = [
62
66
  .map((column) => `coalesce(${column}, '')`)
63
67
  .join(" || ' ' || ")
64
68
 
65
- function auditEntry(row) {
69
+ export function auditEntry(row) {
66
70
  const detail = JSON.parse(row.detail || '{}')
67
71
  return {
68
72
  id: row.id,
@@ -324,6 +328,21 @@ export async function writeWorkspaceExport(t, exported, { write, now, iso, expor
324
328
  }
325
329
  await audit.write(count ? '\n]\n' : ']\n')
326
330
  await audit.end()
331
+ // The usage records (src/hosted/usage.js): one row per agent turn, numbers
332
+ // and ids only, newest first, all of them.
333
+ const usage = zip.stream(`${root}usage.json`)
334
+ await usage.write('[')
335
+ let turns = 0
336
+ const end = Date.now() + 86_400_000
337
+ const store = createUsage(t)
338
+ // Every record, a page at a time: an export is the whole workspace.
339
+ for (const page of store.pages({ fromMs: 0, toMs: end }, { all: true, userId: null }, { max: Infinity })) {
340
+ let text = ''
341
+ for (const row of page) text += `${turns++ ? ',' : ''}\n ${JSON.stringify(row)}`
342
+ await usage.write(text)
343
+ }
344
+ await usage.write(turns ? '\n]\n' : ']\n')
345
+ await usage.end()
327
346
  for (const { project, row, files, images = [] } of plan) {
328
347
  const base = `${root}projects/${project.slug}/boards/${row.board_id}/`
329
348
  const comments = createCommentStore(t, project.id, row.board_id).list()
@@ -332,6 +351,12 @@ export async function writeWorkspaceExport(t, exported, { write, now, iso, expor
332
351
  JSON.stringify({ ...JSON.parse(row.definition), pushedAt: row.pushed_at, pushes: row.push_count }, null, 2),
333
352
  )
334
353
  await zip.add(`${base}comments.json`, JSON.stringify(comments, null, 2))
354
+ // Chat with connected agents: the threads every member reads (the
355
+ // board's and each comment's). A member's own chats are not in a copy
356
+ // an admin downloads; chats.json says how many there are.
357
+ const chats = createChatStore(t).shared(project.id, row.board_id)
358
+ if (chats.threads.length || chats.privateChats)
359
+ await zip.add(`${base}chats.json`, JSON.stringify({ threads: chats.threads, privateChatsNotIncluded: chats.privateChats }, null, 2))
335
360
  for (const [relative, file] of files) {
336
361
  let data
337
362
  try {
@@ -380,7 +405,23 @@ function isoOrNull(value) {
380
405
  }
381
406
 
382
407
  export function mountAdmin(router, deps) {
383
- const { db, dataDir, iso, now, handle, inWorkspace, needFresh, auditOf, HttpError, listTokens, clientIp, limit } = deps
408
+ const {
409
+ db,
410
+ dataDir,
411
+ iso,
412
+ now,
413
+ handle,
414
+ inWorkspace,
415
+ needFresh,
416
+ stepUp,
417
+ stepUpOrThrow,
418
+ coreFreshOrThrow,
419
+ auditOf,
420
+ HttpError,
421
+ listTokens,
422
+ clientIp,
423
+ limit,
424
+ } = deps
384
425
  // Workspaces with an export being written: one at a time each.
385
426
  const exporting = new Set()
386
427
 
@@ -390,7 +431,7 @@ export function mountAdmin(router, deps) {
390
431
  inWorkspace(NEEDS.invites),
391
432
  handle(async (req, res) => {
392
433
  const rows = req.t.all(
393
- `SELECT i.id, i.role, i.created_at, i.expires_at, i.used_at, i.revoked_at, i.email, i.emailed_at, i.note,
434
+ `SELECT i.id, i.role, i.created_at, i.expires_at, i.used_at, i.revoked_at, i.email, i.emailed_at, i.note, i.tailnet_login,
394
435
  c.handle AS creator_handle, c.display_name AS creator_name, u.handle AS used_handle, u.display_name AS used_name
395
436
  FROM invites i LEFT JOIN users c ON c.id = i.created_by LEFT JOIN users u ON u.id = i.used_by
396
437
  WHERE i.workspace_id = :ws ORDER BY i.created_at DESC LIMIT :limit`,
@@ -408,6 +449,7 @@ export function mountAdmin(router, deps) {
408
449
  email: row.email || null,
409
450
  emailedAt: row.emailed_at || null,
410
451
  note: row.note || null,
452
+ tailnetLogin: row.tailnet_login || null,
411
453
  createdBy: row.creator_handle ? { handle: row.creator_handle, displayName: row.creator_name } : null,
412
454
  usedBy: row.used_handle ? { handle: row.used_handle, displayName: row.used_name } : null,
413
455
  }))
@@ -548,6 +590,7 @@ export function mountAdmin(router, deps) {
548
590
  inWorkspace(NEEDS.audit),
549
591
  handle(async (req, res) => {
550
592
  const rows = auditRows(req, { limit: AUDIT_CSV_MAX, before: Number.MAX_SAFE_INTEGER })
593
+ auditOf(req, 'audit_exported', null, { rows: rows.length, scope: 'workspace', view: 'audit' })
551
594
  const lines = [['time', 'actor_type', 'actor', 'actor_handle', 'action', 'target', 'ip', 'detail']]
552
595
  for (const row of rows) {
553
596
  const entry = auditEntry(row)
@@ -593,15 +636,15 @@ export function mountAdmin(router, deps) {
593
636
  // ---- Export: a zip of the workspace before it is deleted (admins) ----
594
637
  // workspace.json (members, projects, tokens and share links without their
595
638
  // secrets), audit.json, and per project and board the board definition,
596
- // its comments and every pushed file. Needs a fresh passkey check: it is
597
- // everything in the workspace in one download.
639
+ // its comments and every pushed file. Everything in the workspace in one
640
+ // download: the passkey again when the workspace asks ("Exports and deletes").
598
641
  // One export at a time per workspace (409 while one runs), a few an hour
599
642
  // per person (LIMITS.export), and the audit log read 1000 rows at a time.
600
643
  router.post(
601
644
  '/workspaces/:ws/export',
602
645
  inWorkspace(NEEDS.export),
603
646
  limit('export', (req) => req.user.id),
604
- needFresh,
647
+ stepUp('data'),
605
648
  handle(async (req, res) => {
606
649
  const t = req.t
607
650
  if (exporting.has(t.workspaceId))
@@ -654,7 +697,7 @@ export function mountAdmin(router, deps) {
654
697
  const { shareLinks } = req.body || {}
655
698
  if (typeof shareLinks !== 'boolean') throw new HttpError(400, 'invalid_settings', 'shareLinks: true or false.')
656
699
  // Letting people outside the workspace in is a sensitive change.
657
- if (shareLinks) deps.freshOrThrow(req)
700
+ if (shareLinks) stepUpOrThrow(req, 'tokens')
658
701
  const current = req.t.get('SELECT share_links FROM workspaces WHERE workspace_id = :ws')
659
702
  if (Boolean(current.share_links) !== shareLinks) {
660
703
  req.t.run('UPDATE workspaces SET share_links = :on WHERE workspace_id = :ws', { on: shareLinks ? 1 : 0 })
@@ -664,6 +707,36 @@ export function mountAdmin(router, deps) {
664
707
  }),
665
708
  )
666
709
 
710
+ // When this workspace asks for the passkey again (src/hosted/step-up.js):
711
+ // one setting per request, { group, on } | { windowMinutes } | { adminIdle } | { cliApproval }.
712
+ // Owners only; asking for less needs a fresh passkey check itself.
713
+ router.patch(
714
+ '/workspaces/:ws/step-up',
715
+ inWorkspace(NEEDS.settings),
716
+ handle(async (req, res) => {
717
+ const body = req.body || {}
718
+ const actor = {
719
+ role: req.role,
720
+ fresh: () => coreFreshOrThrow(req),
721
+ audit: (action, target, detail) => auditOf(req, action, target, detail),
722
+ }
723
+ const settings = stepUpSettings(req.t)
724
+ const named = ['group', 'windowMinutes', 'adminIdle', 'cliApproval'].filter((key) => Object.hasOwn(body, key))
725
+ if (named.length !== 1)
726
+ throw new HttpError(400, 'invalid_settings', 'One setting at a time: group and on, windowMinutes, adminIdle or cliApproval.')
727
+ const stepUpNow = transaction(db, () =>
728
+ named[0] === 'group'
729
+ ? settings.setGroup(actor, body.group, body.on)
730
+ : named[0] === 'windowMinutes'
731
+ ? settings.setWindow(actor, body.windowMinutes)
732
+ : named[0] === 'adminIdle'
733
+ ? settings.setAdminIdle(actor, body.adminIdle)
734
+ : settings.setCliApproval(actor, body.cliApproval),
735
+ )
736
+ res.json({ settings: { stepUp: stepUpNow } })
737
+ }),
738
+ )
739
+
667
740
  // ---- Deleting a workspace (owner) ----
668
741
  // Every row of the workspace goes, then its files. The account-level log
669
742
  // keeps one line that it happened.
@@ -692,7 +765,7 @@ export function mountAdmin(router, deps) {
692
765
  )
693
766
  }
694
767
 
695
- function actorOf(row, detail) {
768
+ export function actorOf(row, detail) {
696
769
  if (row.user_id) return { type: 'user', id: row.user_id, label: row.display_name || 'Former member', handle: row.handle || null }
697
770
  if (row.token_id) return { type: 'token', id: row.token_id, label: row.token_name || 'Deleted token' }
698
771
  if (row.share_id) {
@@ -710,5 +783,6 @@ function actorOf(row, detail) {
710
783
  link: row.share_name || 'Share link',
711
784
  }
712
785
  }
713
- return { type: 'system', id: null, label: 'System' }
786
+ // Done on the server's machine with `shapewall hosted admin` (src/hosted/operator-access.js).
787
+ return { type: 'system', id: null, label: detail?.by === 'operator' ? 'Server operator' : 'System' }
714
788
  }
@@ -4,9 +4,22 @@ import { randomBytes } from 'node:crypto'
4
4
  import { sha256 } from './crypto.js'
5
5
  import { dispatchHash, AgentPolicyError, agentPolicy } from './agent-policy.js'
6
6
  import { findApiToken } from './tenancy.js'
7
- import { roleAtLeast } from './permissions.js'
7
+ import { canAnswerApproval, roleAtLeast } from './permissions.js'
8
8
 
9
- export function mountHostedApprovals({ v1, boardApi, handle, scope, db, transaction, policyFor, boardContext, needFresh, auditOf, now }) {
9
+ export function mountHostedApprovals({
10
+ v1,
11
+ boardApi,
12
+ handle,
13
+ scope,
14
+ db,
15
+ transaction,
16
+ policyFor,
17
+ agentsFor = null,
18
+ boardContext,
19
+ stepUp,
20
+ auditOf,
21
+ now,
22
+ }) {
10
23
  const error = (statusCode, code, message) => new AgentPolicyError(statusCode, code, message)
11
24
  const keyOf = (req) => ({ project: req.project.id, board: req.params.bid })
12
25
  function validate(req, row) {
@@ -35,6 +48,13 @@ export function mountHostedApprovals({ v1, boardApi, handle, scope, db, transact
35
48
  throw error(409, 'approval_expired', 'This approval no longer matches a live run.')
36
49
  return row
37
50
  }
51
+ // Who may answer an agent's approvals is a setting of that agent (admin by
52
+ // default, or owner): the same rule connected agents' cards will use
53
+ // (src/hosted/permissions.js canAnswerApproval).
54
+ const mayAnswer = (req, row) => {
55
+ const agent = agentsFor?.(req.t).forToken(req.project.id, row.token_id) || null
56
+ return canAnswerApproval(req.role, agent ? { approvalAnswerRole: agent.approval_answer_role } : null)
57
+ }
38
58
  const byId = (req) =>
39
59
  req.t.get('SELECT * FROM agent_approvals WHERE workspace_id = :ws AND project_id = :project AND board_id = :board AND id = :id', {
40
60
  ...keyOf(req),
@@ -49,6 +69,10 @@ export function mountHostedApprovals({ v1, boardApi, handle, scope, db, transact
49
69
  throw error(400, 'invalid_command', 'Command: 1 to 8000 characters.')
50
70
  const ctx = boardContext(req.t, req.project, req.params.bid)
51
71
  const comment = ctx.comments.get(req.params.cid)
72
+ // A comment sent to another agent does not exist for this token, here
73
+ // as on every other route.
74
+ if (agentsFor && !agentsFor(req.t).workCheck(req.agent, req.project.id, comment).ok)
75
+ throw error(404, 'unknown_comment', 'No dispatched comment at that id.')
52
76
  const at = now().toISOString()
53
77
  const id = `sa_${randomBytes(10).toString('hex')}`
54
78
  const claim = req.t.get(
@@ -119,7 +143,7 @@ export function mountHostedApprovals({ v1, boardApi, handle, scope, db, transact
119
143
  approvals: rows.filter((row) => {
120
144
  try {
121
145
  validate(req, row)
122
- return true
146
+ return mayAnswer(req, row)
123
147
  } catch {
124
148
  return false
125
149
  }
@@ -129,13 +153,14 @@ export function mountHostedApprovals({ v1, boardApi, handle, scope, db, transact
129
153
  )
130
154
  boardApi.post(
131
155
  '/boards/:bid/approvals/:aid',
132
- needFresh,
156
+ stepUp('cards'),
133
157
  handle((req, res) => {
134
158
  if (!roleAtLeast(req.role, 'admin') || !policyFor(req.t).trusted(agentPolicy(req.t, req.project.id, req.params.bid), req.user.id))
135
159
  throw error(403, 'forbidden', 'Only trusted admins approve shell commands.')
136
160
  if (!['approved', 'denied'].includes(req.body?.state)) throw error(400, 'invalid_approval', 'Choose approved or denied.')
137
161
  const row = transaction(db, () => {
138
162
  const row = validate(req, byId(req))
163
+ if (!mayAnswer(req, row)) throw error(403, 'forbidden', "Answering this agent's approvals needs the owner role.")
139
164
  if (row.state !== 'pending' || req.body?.hash !== row.command_hash)
140
165
  throw error(409, 'approval_changed', 'This exact command is no longer pending.')
141
166
  req.t.run(