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
@@ -13,9 +13,23 @@
13
13
  import fs from 'node:fs'
14
14
  import path from 'node:path'
15
15
  import { MIN_NODE, nodeSupportsSqlite, openDatabase, quietSqliteWarning } from './db.js'
16
- import { mintSetupLink, readSetupLink, setupFile, setupLinkUsable, userCount, writeSetupLink } from './setup-link.js'
16
+ import { mintSetupLink, readSetupLink, removeSetupLink, setupFile, setupLinkUsable, userCount, writeSetupLink } from './setup-link.js'
17
+ import { sha256 } from './crypto.js'
18
+ import { transaction } from './db.js'
19
+ import { createMembership } from './membership.js'
20
+ import { createQuotas } from './quotas.js'
21
+ import { createTailnetAccounts } from './tailnet.js'
22
+ import { accounts, auditAccount, tenant } from './tenancy.js'
23
+ import { cleanTailnetLogin } from '../tailnet-proof.js'
24
+
17
25
  import { MOVE_DAYS_MAX, getState, readMove, recordMove } from './rebind.js'
18
26
 
27
+ // A value as an error message may show it: printable ASCII only.
28
+ const show = (value) =>
29
+ String(value ?? '')
30
+ .replace(/[^ -~]/g, '')
31
+ .slice(0, 80)
32
+
19
33
  async function openData(dataDir) {
20
34
  if (!nodeSupportsSqlite())
21
35
  throw new Error(`shapewall hosted needs Node ${MIN_NODE.join('.')} or newer (for node:sqlite); this is ${process.versions.node}`)
@@ -29,6 +43,7 @@ async function openData(dataDir) {
29
43
  export async function operatorCommand(action, { dataDir, flags, env = process.env, out = console.log }) {
30
44
  const { dir, db } = await openData(dataDir)
31
45
  try {
46
+ if (action === 'claim') return claimCommand({ dir, db, flags, out })
32
47
  if (action === 'setup-link') return setupLinkCommand({ dir, db, flags, env, out })
33
48
  if (action === 'move-origin') return moveOriginCommand({ db, flags, out })
34
49
  } finally {
@@ -36,6 +51,89 @@ export async function operatorCommand(action, { dataDir, flags, env = process.en
36
51
  }
37
52
  }
38
53
 
54
+ // `shapewall hosted claim --data DIR --login LOGIN [--workspace-name NAME]`:
55
+ // the first account of a server with tailnet sign-in, made on the server's
56
+ // own machine without a browser.
57
+ //
58
+ // The proof is the data folder. Whoever can read it has the setup link (the
59
+ // one-time secret that makes the first account), the database and the
60
+ // signing secret: they control the server already. Who the owner is cannot
61
+ // be asked of the tailnet from here: a request from the server's own machine
62
+ // names the machine's owner whoever sends it, so the server never takes an
63
+ // identity from this machine (src/tailnet-proof.js). So the owner's tailnet
64
+ // login is said with --login, and it is the operator's word: the account is
65
+ // linked to that login, and whoever arrives through the tailnet as that
66
+ // login from another device is its owner. (From another tailnet device, the
67
+ // setup link opened in a browser claims by identity instead.)
68
+ function claimCommand({ dir, db, flags, out }) {
69
+ if (userCount(db) > 0)
70
+ throw new Error(
71
+ 'This server is claimed already: it has accounts. The setup link is only for the first one; admins invite everyone else.',
72
+ )
73
+ const link = readSetupLink(dir)
74
+ if (!link || !setupLinkUsable(db, link))
75
+ throw new Error(
76
+ `No usable setup link in ${dir}. Start the server (it writes one when it has no accounts), or run "shapewall hosted setup-link --new".`,
77
+ )
78
+ if (typeof flags.login !== 'string' || !flags.login.trim())
79
+ throw new Error(
80
+ 'claim: say whose server this is with --login <tailnet login> (like ada@example.com: the name the owner signs in to Tailscale with; "tailscale whois $(tailscale ip -4)" on one of their devices shows it).',
81
+ )
82
+ const login = cleanTailnetLogin(flags.login)
83
+ if (!login) throw new Error(`--login: "${show(flags.login)}" is not a tailnet login (user@domain, plain letters and digits).`)
84
+ const iso = () => new Date().toISOString()
85
+ const q = accounts(db)
86
+ const code = new URLSearchParams(new URL(link).hash.slice(1)).get('setup') || ''
87
+ const { createWorkspace } = createMembership({ db, quotas: createQuotas(), iso, auditOf: () => {} })
88
+ const made = transaction(db, () => {
89
+ const used = q.run('UPDATE setup_codes SET used_at = :at WHERE code_hash = :hash AND used_at IS NULL AND expires_at > :at', {
90
+ at: iso(),
91
+ hash: sha256(code),
92
+ })
93
+ if (!used.changes) throw new Error('The setup link was used or expired meanwhile. Nothing was claimed.')
94
+ const user = createTailnetAccounts({ db, iso, now: () => new Date() }).createUser({ login, name: login.split('@')[0] }, {})
95
+ const workspaceName =
96
+ typeof flags['workspace-name'] === 'string' && flags['workspace-name'].trim()
97
+ ? flags['workspace-name']
98
+ : `${user.display_name}'s workspace`
99
+ const workspaceId = createWorkspace(user, workspaceName, null)
100
+ auditAccount(db, {
101
+ userId: user.id,
102
+ action: 'account_created',
103
+ ip: null,
104
+ at: iso(),
105
+ detail: { via: 'setup', signIn: 'tailnet', tailnet: login, by: 'hosted claim on the server' },
106
+ })
107
+ auditAccount(db, {
108
+ userId: user.id,
109
+ action: 'tailnet_linked',
110
+ ip: null,
111
+ at: iso(),
112
+ detail: { tailnet: login, by: 'hosted claim on the server' },
113
+ })
114
+ const workspace = tenant(db, workspaceId).get('SELECT name FROM workspaces WHERE workspace_id = :ws')
115
+ return { user, workspaceName: workspace.name }
116
+ })
117
+ removeSetupLink(dir)
118
+ const origin = new URL(link).origin
119
+ out(`Claimed ${origin}.`)
120
+ out(` Owner account: @${made.user.handle}, linked to the tailnet login ${login}.`)
121
+ out(` Workspace: ${made.workspaceName} (that account owns it).`)
122
+ out(' The setup link is used up.')
123
+ out(`Whoever arrives through the tailnet as ${login}, from another device than this server, is signed in as the owner.`)
124
+ out(
125
+ 'That login was taken from --login on your word; it was not checked against the tailnet. If it is wrong, delete the data folder and start again.',
126
+ )
127
+ out('This machine itself is never signed in by its tailnet identity. Here, use another tailnet device of yours, or')
128
+ out('shapewall hosted admin with this data folder (members, invites, projects, passkeys; shapewall hosted admin help).')
129
+ out('Your Tailscale account is the sign-in: no passkey was made and none is asked for. Anything running as you on a tailnet')
130
+ out('device of yours can act as you there, so lock your devices and keep the tailnet to people and machines you trust.')
131
+ out('Deleting a workspace, changing owners and a few other things ask you to type a name to confirm.')
132
+ out('To also allow passkeys on this server: shapewall hosted admin passkeys on --data <dir>.')
133
+ out('The server must run with --tailscale --tailnet-sign-in for that login to sign in.')
134
+ return 0
135
+ }
136
+
39
137
  function setupLinkCommand({ dir, db, flags, env, out }) {
40
138
  if (userCount(db) > 0)
41
139
  throw new Error('This server has accounts already. The setup link is only for the first one; admins invite everyone else.')
@@ -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
+ }