shapewall 0.6.0 → 0.7.1

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 (127) hide show
  1. package/CHANGELOG.md +267 -0
  2. package/README.md +39 -2
  3. package/THIRD_PARTY.md +15 -0
  4. package/dist/agent/package-lock.json +594 -2
  5. package/dist/client/assets/{BoardChat-DdwBcb2N.js → BoardChat-Bv4UDOjO.js} +1 -1
  6. package/dist/client/assets/{BuzzDialog-DpUcnU6S.js → BuzzDialog-DwEAN6va.js} +1 -1
  7. package/dist/client/assets/{ChecksPanel-CngYV4yz.js → ChecksPanel-C6r_Tc9g.js} +1 -1
  8. package/dist/client/assets/{History-CD0saQA5.js → History-ajFROfWC.js} +1 -1
  9. package/dist/client/assets/{LocalSettings-MZy2baig.js → LocalSettings-BSbmmpbN.js} +1 -1
  10. package/dist/client/assets/{Management-CSvZ-SHO.js → Management-mo8uv2qG.js} +1 -1
  11. package/dist/client/assets/{QuickConnect-foLh2QUm.js → QuickConnect-DlaijESK.js} +1 -1
  12. package/dist/client/assets/{ShareDialog-DPWDftoL.js → ShareDialog-CdLdd6WQ.js} +1 -1
  13. package/dist/client/assets/{app-update-dialog-CtiXpTRD.js → app-update-dialog-BHVNR5Cp.js} +1 -1
  14. package/dist/client/assets/{circle-x-CteRBtXC.js → circle-x-D5MkDLJk.js} +1 -1
  15. package/dist/client/assets/index-B4AoX3ZW.css +2 -0
  16. package/dist/client/assets/index-CQeHY7en.js +37 -0
  17. package/dist/client/assets/{play-BjRNIGSf.js → play--xrZ7VCR.js} +1 -1
  18. package/dist/client/assets/{refresh-cw-r_tZiFfB.js → refresh-cw-B-npxKae.js} +1 -1
  19. package/dist/client/assets/{ui-zQpn-PdL.js → ui-2lMx-4bc.js} +2 -2
  20. package/dist/client/build-info.json +1 -1
  21. package/dist/client/index.html +3 -3
  22. package/dist/client/sw.js +2 -2
  23. package/dist/console/assets/LocalAccountsApp-C1sCag6a.js +1 -0
  24. package/dist/console/assets/LocalConsole-LXQmzRFT.js +2 -0
  25. package/dist/console/assets/LocalUsage-Br3Ddp7_.js +1 -0
  26. package/dist/console/assets/app-update-dialog-CVniDJKA.js +1 -0
  27. package/dist/console/assets/app-version-CTHwlY6g.js +1 -0
  28. package/dist/console/assets/console-CMNNLtFw.js +11 -0
  29. package/dist/console/assets/console-sMMn_Rwc.css +2 -0
  30. package/dist/console/assets/local-agents-DwYJ9cPb.js +6 -0
  31. package/dist/console/assets/minus-887msXez.js +1 -0
  32. package/dist/console/assets/tailnet--wXsG3uh.js +2 -0
  33. package/dist/console/assets/theme-CPfJOmcz.js +1 -0
  34. package/dist/console/assets/ui-DnyJhoQU.js +41 -0
  35. package/dist/console/assets/usage-C5CJHejQ.js +5 -0
  36. package/dist/console/assets/usage-CIPWnHaS.css +1 -0
  37. package/dist/console/assets/usage-DjmUlnXL.js +56 -0
  38. package/dist/console/build-info.json +1 -1
  39. package/dist/console/console.html +8 -2
  40. package/docs/agent-hardening.md +31 -17
  41. package/docs/agents.md +35 -0
  42. package/docs/architecture.md +10 -4
  43. package/docs/deployment.md +39 -17
  44. package/docs/design-system.md +56 -7
  45. package/docs/hosted.md +1004 -43
  46. package/docs/images/board-overview.png +0 -0
  47. package/docs/images/journeys.png +0 -0
  48. package/docs/images/live-comment.png +0 -0
  49. package/docs/images/phone-comment.png +0 -0
  50. package/docs/images/phone-overview.png +0 -0
  51. package/docs/images/variant.png +0 -0
  52. package/docs/where-to-run.md +82 -1
  53. package/package.json +6 -1
  54. package/src/agent/backends/acp.js +224 -26
  55. package/src/agent/routes.js +21 -0
  56. package/src/agent/usage-log.js +251 -0
  57. package/src/cli/args.js +24 -0
  58. package/src/cli/help.js +37 -2
  59. package/src/cli/init.js +2 -1
  60. package/src/cli/serve.js +20 -5
  61. package/src/cli.js +8 -0
  62. package/src/hosted/access-cli.js +99 -1
  63. package/src/hosted/activity-core.js +232 -0
  64. package/src/hosted/activity.js +375 -0
  65. package/src/hosted/admin.js +80 -13
  66. package/src/hosted/agent-approvals.js +2 -2
  67. package/src/hosted/agent-routes.js +3 -3
  68. package/src/hosted/agents.js +11 -4
  69. package/src/hosted/app.js +89 -7
  70. package/src/hosted/auth-routes.js +156 -15
  71. package/src/hosted/auth.js +123 -20
  72. package/src/hosted/board-routes.js +3 -3
  73. package/src/hosted/chat-frames.js +5 -15
  74. package/src/hosted/chat-permissions.js +12 -0
  75. package/src/hosted/chat-routes.js +8 -8
  76. package/src/hosted/chat-store.js +20 -3
  77. package/src/hosted/comment-files.js +5 -2
  78. package/src/hosted/console-routes.js +111 -34
  79. package/src/hosted/db.js +130 -0
  80. package/src/hosted/device-routes.js +25 -3
  81. package/src/hosted/device.js +23 -4
  82. package/src/hosted/guards.js +337 -27
  83. package/src/hosted/http.js +6 -3
  84. package/src/hosted/membership.js +13 -2
  85. package/src/hosted/operator-access.js +418 -0
  86. package/src/hosted/operator.js +106 -2
  87. package/src/hosted/ops-cli.js +238 -3
  88. package/src/hosted/pages.js +2 -0
  89. package/src/hosted/passkey-policy.js +75 -0
  90. package/src/hosted/permissions.js +14 -6
  91. package/src/hosted/presence.js +14 -2
  92. package/src/hosted/projects.js +2 -1
  93. package/src/hosted/public.js +4 -4
  94. package/src/hosted/ratelimit.js +6 -0
  95. package/src/hosted/retention.js +18 -2
  96. package/src/hosted/server.js +123 -11
  97. package/src/hosted/shares.js +2 -2
  98. package/src/hosted/step-up-settings.js +68 -0
  99. package/src/hosted/step-up.js +135 -0
  100. package/src/hosted/tailnet-identity.js +24 -0
  101. package/src/hosted/tailnet-routes.js +342 -0
  102. package/src/hosted/tailnet.js +220 -0
  103. package/src/hosted/tailscale.js +75 -9
  104. package/src/hosted/tenancy.js +48 -1
  105. package/src/hosted/token-api.js +2 -2
  106. package/src/hosted/tokens.js +9 -2
  107. package/src/hosted/usage-core.js +624 -0
  108. package/src/hosted/usage-layout.js +724 -0
  109. package/src/hosted/usage-routes.js +375 -0
  110. package/src/hosted/usage-shape.js +256 -0
  111. package/src/hosted/usage.js +641 -0
  112. package/src/remote/agent-connect.js +37 -1
  113. package/src/remote/agent-link.js +2 -0
  114. package/src/remote/login.js +33 -8
  115. package/src/remote/share.js +1 -1
  116. package/src/remote/tailnet-cli.js +547 -0
  117. package/src/server/app.js +15 -0
  118. package/src/server/pairing-routes.js +34 -5
  119. package/src/server/tailscale.js +97 -4
  120. package/src/tailnet-proof.js +766 -0
  121. package/dist/client/assets/index-Cxz1UVcV.css +0 -2
  122. package/dist/client/assets/index-uUZVBYUS.js +0 -37
  123. package/dist/console/assets/LocalAccountsApp-DIdy1KnN.js +0 -1
  124. package/dist/console/assets/LocalConsole-DfcQztF-.js +0 -1
  125. package/dist/console/assets/app-update-dialog-ttl9lF5A.js +0 -1
  126. package/dist/console/assets/console-OqAjD0kV.js +0 -55
  127. package/dist/console/assets/console-kvjrAArQ.css +0 -2
@@ -0,0 +1,232 @@
1
+ // The parts of the Activity pages that are not SQL: who may read whose
2
+ // activity, the filter a request names, how an audit entry reads as activity
3
+ // (its group, where it came from, what changed), which entries count as
4
+ // unused in the access review, and the CSV files.
5
+ //
6
+ // No imports beyond plain values, so the server (src/hosted/activity.js) and
7
+ // the public demo's in-browser backend (client/src/demo/usage) share it.
8
+
9
+ import { HttpError } from './http.js'
10
+ import { roleAtLeast } from './permissions.js'
11
+ import { csvCell } from './usage-core.js'
12
+ import { ACTION_GROUPS, ACTION_GROUP_IDS, SENSITIVE_ACTIONS, actionGroup } from './usage-shape.js'
13
+
14
+ export const ACTIVITY_LIMITS = { page: 50, pageMax: 200, exportRows: 10_000, staleDays: 90, searchDays: 90 }
15
+ const DAY = 86_400_000
16
+ export const USER_ID = /^us_[a-f0-9]{24}$/
17
+ export const AGENT_ID = /^ag_[a-f0-9]{24}$/
18
+ export const PROJECT_ID = /^pr_[a-f0-9]{24}$/
19
+ export const ACTION_RE = /^[a-z_]{1,40}$/
20
+
21
+ // { all: true }: the workspace's log. { all: false }: their own entries.
22
+ // `accounts`: whose account events (sign-ins, passkeys, sessions: they belong
23
+ // to a person, not to a workspace) this reader may see. "own" unless the
24
+ // server's operator switched on `ownersSeeSignIns` and the reader is an
25
+ // owner: then "members" (the people of this workspace, since each joined).
26
+ export function activityViewer(role, userId, { ownersSeeSignIns = false } = {}) {
27
+ if (!role) return null
28
+ return { all: roleAtLeast(role, 'admin'), userId, accounts: ownersSeeSignIns && role === 'owner' ? 'members' : 'own' }
29
+ }
30
+
31
+ const instant = (value, name) => {
32
+ if (value === undefined || value === null || value === '') return null
33
+ const ms = typeof value === 'string' && value.length <= 40 ? Date.parse(value) : NaN
34
+ if (!Number.isFinite(ms)) throw new HttpError(400, 'invalid_date', `${name}: an ISO date and time.`)
35
+ return new Date(ms).toISOString()
36
+ }
37
+ const id = (value, pattern, name) => {
38
+ if (value === undefined || value === null || value === '') return null
39
+ if (typeof value !== 'string' || !pattern.test(value)) throw new HttpError(400, 'invalid_filter', `${name}: not a valid id.`)
40
+ return value
41
+ }
42
+
43
+ export function cleanActivityFilter(query = {}) {
44
+ const group = query.group === undefined || query.group === '' ? null : query.group
45
+ if (group !== null && !ACTION_GROUP_IDS.includes(group))
46
+ throw new HttpError(400, 'invalid_filter', `group: one of ${ACTION_GROUP_IDS.join(', ')}.`)
47
+ const action = query.action === undefined || query.action === '' ? null : query.action
48
+ if (action !== null && (typeof action !== 'string' || !ACTION_RE.test(action)))
49
+ throw new HttpError(400, 'invalid_action', 'action: an action name.')
50
+ const source = query.source === undefined || query.source === '' ? null : query.source
51
+ if (source !== null && !['person', 'token', 'guest', 'system'].includes(source))
52
+ throw new HttpError(400, 'invalid_filter', 'source: person, token, guest or system.')
53
+ return {
54
+ person: id(query.person, USER_ID, 'person'),
55
+ agent: id(query.agent, AGENT_ID, 'agent'),
56
+ project: id(query.project, PROJECT_ID, 'project'),
57
+ group,
58
+ action,
59
+ source,
60
+ sensitive: query.sensitive === '1' || query.sensitive === 'true',
61
+ from: instant(query.from, 'from'),
62
+ to: instant(query.to, 'to'),
63
+ q: typeof query.q === 'string' ? query.q.trim().toLowerCase().slice(0, 100) : '',
64
+ }
65
+ }
66
+
67
+ // Settings whose audit entry says what changed: before and after, as text.
68
+ export function changeOf(action, detail) {
69
+ if (detail.from !== undefined && detail.to !== undefined && typeof detail.from !== 'object' && typeof detail.to !== 'object')
70
+ return { before: String(detail.from ?? ''), after: String(detail.to ?? '') }
71
+ if (detail.before !== undefined || detail.after !== undefined) {
72
+ const text = (value) =>
73
+ value === null || value === undefined
74
+ ? 'none'
75
+ : typeof value === 'object'
76
+ ? Object.keys(value).length === 1 && typeof Object.values(value)[0] !== 'object'
77
+ ? String(Object.values(value)[0] ?? 'none')
78
+ : Object.entries(value)
79
+ .map(([key, item]) => `${key}: ${Array.isArray(item) ? item.length : (item ?? 'none')}`)
80
+ .join(', ')
81
+ : String(value)
82
+ return { before: text(detail.beforeName ?? detail.before), after: text(detail.afterName ?? detail.after) }
83
+ }
84
+ if (action === 'share_links_enabled') return { before: 'off', after: 'on' }
85
+ if (action === 'share_links_disabled') return { before: 'on', after: 'off' }
86
+ if (action === 'project_made_public') return { before: 'private', after: 'public' }
87
+ if (action === 'project_made_private') return { before: 'public', after: 'private' }
88
+ return null
89
+ }
90
+
91
+ // An audit entry (src/hosted/admin.js auditEntry) as the Activity page shows
92
+ // it: plus its group, where it came from, the agent and project it is about,
93
+ // and what changed for a setting. `names()`: { agent, project } maps of id
94
+ // to name.
95
+ export function activityEntry(entry, names, { account = false } = {}) {
96
+ const detail = entry.detail
97
+ const agentId = [entry.target, detail.agent, detail.from].find((value) => typeof value === 'string' && AGENT_ID.test(value)) || null
98
+ const projectId =
99
+ [entry.target?.slice?.(0, 27), detail.project].find((value) => typeof value === 'string' && PROJECT_ID.test(value)) || null
100
+ return {
101
+ ...entry,
102
+ group: actionGroup(entry.action),
103
+ scope: account ? 'account' : 'workspace',
104
+ source: entry.actor.type === 'user' ? 'person' : entry.actor.type,
105
+ sensitive: SENSITIVE_ACTIONS.includes(entry.action),
106
+ device: typeof detail.device === 'string' ? detail.device : null,
107
+ // Done in a session the person's tailnet signed in (src/hosted/tailnet.js).
108
+ tailnetSession: detail.signedInBy === 'tailnet' || detail.via === 'tailnet',
109
+ agent: agentId ? { id: agentId, name: detail.agentName || detail.name || names().agent.get(agentId) || 'Removed agent' } : null,
110
+ project: projectId ? { id: projectId, name: names().project.get(projectId) || detail.project_name || 'Removed project' } : null,
111
+ change: changeOf(entry.action, detail),
112
+ }
113
+ }
114
+
115
+ // The actions a filter asks for (null: all of them).
116
+ export function wantedActions(filter) {
117
+ let wanted = null
118
+ const narrow = (values) => {
119
+ wanted = wanted ? wanted.filter((item) => values.includes(item)) : [...values]
120
+ }
121
+ if (filter.group) narrow(ACTION_GROUPS[filter.group])
122
+ if (filter.action) narrow([filter.action])
123
+ if (filter.sensitive) narrow(SENSITIVE_ACTIONS)
124
+ return wanted
125
+ }
126
+
127
+ // The access review's "unused": not used for ACTIVITY_LIMITS.staleDays (or
128
+ // never, and made longer ago than that). `at`: now, as an ISO time.
129
+ export function staleSince(at) {
130
+ const cutoff = new Date(Date.parse(at) - ACTIVITY_LIMITS.staleDays * DAY).toISOString()
131
+ return (lastUsed, created) => (lastUsed ? lastUsed < cutoff : Boolean(created) && created < cutoff)
132
+ }
133
+
134
+ // ---- CSV ----
135
+
136
+ const who = (person) => (person ? `${person.displayName || 'Former member'}${person.handle ? ` (@${person.handle})` : ''}` : '')
137
+ // The access review as one CSV: a row per person, token, agent, share link
138
+ // and open invite.
139
+ export function reviewCsv(data) {
140
+ const lines = [['type', 'name', 'reaches', 'access', 'made_by', 'made_at', 'last_used', 'expires', 'stale', 'id']]
141
+ for (const item of data.people)
142
+ lines.push([
143
+ 'person',
144
+ who(item),
145
+ item.reaches,
146
+ item.role,
147
+ '',
148
+ item.joinedAt,
149
+ item.lastActiveAt,
150
+ '',
151
+ item.stale ? 'yes' : '',
152
+ item.userId,
153
+ ])
154
+ for (const item of data.tokens)
155
+ lines.push([
156
+ 'token',
157
+ item.name,
158
+ item.projectName,
159
+ `${item.scopes.join(' ')}${item.status === 'inactive' ? ' (inactive)' : ''}`,
160
+ who(item.createdBy),
161
+ item.createdAt,
162
+ item.lastUsedAt,
163
+ item.expiresAt,
164
+ item.stale ? 'yes' : '',
165
+ item.id,
166
+ ])
167
+ for (const item of data.agents)
168
+ lines.push([
169
+ 'agent',
170
+ `${item.name}${item.machine ? ` (${item.machine})` : ''}`,
171
+ item.projectName,
172
+ `audience: ${item.audienceLabel || item.audience || ''}; approvals: ${item.approvalRule}`,
173
+ who(item.createdBy),
174
+ item.createdAt,
175
+ item.lastSeenAt,
176
+ '',
177
+ item.stale ? 'yes' : '',
178
+ item.id,
179
+ ])
180
+ for (const item of data.shares)
181
+ lines.push([
182
+ 'share link',
183
+ item.name,
184
+ item.projectName,
185
+ `${item.mode}${item.passcode ? ' (passcode)' : ''}`,
186
+ who(item.createdBy),
187
+ item.createdAt,
188
+ item.lastUsedAt,
189
+ item.expiresAt,
190
+ item.stale ? 'yes' : '',
191
+ item.id,
192
+ ])
193
+ for (const item of data.publicProjects)
194
+ lines.push(['public project', item.name, item.name, 'anyone with the address', '', item.publicAt, '', '', '', item.id])
195
+ for (const item of data.invites)
196
+ lines.push([
197
+ 'open invite',
198
+ item.note || '',
199
+ 'Every project',
200
+ item.role,
201
+ who(item.createdBy),
202
+ item.createdAt,
203
+ '',
204
+ item.expiresAt,
205
+ '',
206
+ item.id,
207
+ ])
208
+ return `${lines.map((line) => line.map(csvCell).join(',')).join('\r\n')}\r\n`
209
+ }
210
+ export function activityCsv(entries) {
211
+ const lines = [
212
+ ['time', 'who', 'handle', 'source', 'action', 'group', 'target', 'agent', 'project', 'before', 'after', 'address', 'device', 'detail'],
213
+ ]
214
+ for (const entry of entries)
215
+ lines.push([
216
+ entry.at,
217
+ entry.actor.label,
218
+ entry.actor.handle || '',
219
+ entry.source,
220
+ entry.action,
221
+ entry.group,
222
+ entry.targetLabel || entry.target || '',
223
+ entry.agent?.name || '',
224
+ entry.project?.name || '',
225
+ entry.change?.before ?? '',
226
+ entry.change?.after ?? '',
227
+ entry.ip || '',
228
+ entry.device || '',
229
+ JSON.stringify(entry.detail),
230
+ ])
231
+ return `${lines.map((line) => line.map(csvCell).join(',')).join('\r\n')}\r\n`
232
+ }
@@ -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
+ }