shapewall 0.6.0 → 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 (127) hide show
  1. package/CHANGELOG.md +252 -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-WS8mAIW6.js} +1 -1
  6. package/dist/client/assets/{BuzzDialog-DpUcnU6S.js → BuzzDialog-B-Mlr6wF.js} +1 -1
  7. package/dist/client/assets/{ChecksPanel-CngYV4yz.js → ChecksPanel-Dx1ZLBR6.js} +1 -1
  8. package/dist/client/assets/{History-CD0saQA5.js → History-sXhmpcvs.js} +1 -1
  9. package/dist/client/assets/{LocalSettings-MZy2baig.js → LocalSettings-CtGzz9F3.js} +1 -1
  10. package/dist/client/assets/{Management-CSvZ-SHO.js → Management-CGHe8Wt9.js} +1 -1
  11. package/dist/client/assets/{QuickConnect-foLh2QUm.js → QuickConnect-DEk84E4A.js} +1 -1
  12. package/dist/client/assets/{ShareDialog-DPWDftoL.js → ShareDialog-CGGx-AYK.js} +1 -1
  13. package/dist/client/assets/{app-update-dialog-CtiXpTRD.js → app-update-dialog-_bVp8hnC.js} +1 -1
  14. package/dist/client/assets/{circle-x-CteRBtXC.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-BjRNIGSf.js → play-BzQ3tRTv.js} +1 -1
  18. package/dist/client/assets/{refresh-cw-r_tZiFfB.js → refresh-cw-BYBMyDKT.js} +1 -1
  19. package/dist/client/assets/{ui-zQpn-PdL.js → ui-CAY6myRA.js} +1 -1
  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-CWRguRRL.js +1 -0
  24. package/dist/console/assets/LocalConsole--I2SaIpr.js +2 -0
  25. package/dist/console/assets/LocalUsage-BmpCZ36k.js +1 -0
  26. package/dist/console/assets/app-update-dialog-B8M9plaT.js +1 -0
  27. package/dist/console/assets/app-version-muKrQqbL.js +1 -0
  28. package/dist/console/assets/console-CrhTsPbz.css +2 -0
  29. package/dist/console/assets/console-DxapQ9oS.js +11 -0
  30. package/dist/console/assets/local-agents-CoqD4dSN.js +6 -0
  31. package/dist/console/assets/minus-DDQ0ydcM.js +1 -0
  32. package/dist/console/assets/tailnet-C5Flwl_d.js +2 -0
  33. package/dist/console/assets/theme-DCd0qh4l.js +1 -0
  34. package/dist/console/assets/ui-Bry1mnCY.js +41 -0
  35. package/dist/console/assets/usage-CIPWnHaS.css +1 -0
  36. package/dist/console/assets/usage-CqVjMb7m.js +5 -0
  37. package/dist/console/assets/usage-D1G0GgE3.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,418 @@
1
+ // The operator's commands for who is in a workspace and how people sign in
2
+ // (`shapewall hosted admin members|invites|projects|passkeys ...`).
3
+ //
4
+ // For the person at the server's own machine. On a server with tailnet
5
+ // sign-in that machine is never signed in by its tailnet identity (any
6
+ // program there could ask the same way), so the owner at the machine has two
7
+ // ways: another tailnet device, or these commands. Being able to read and
8
+ // write the data folder is the proof, as for every operator command, and
9
+ // every change is in the operator log and in the workspace's audit log as
10
+ // the operator's doing.
11
+
12
+ import { newId, randomToken, sha256, ID_PATTERNS } from './crypto.js'
13
+ import { transaction } from './db.js'
14
+ import { OperatorError, logOperator } from './operator.js'
15
+ import { setTailnetPasskeys, tailnetPasskeysOffAt, tailnetPasskeysSetting } from './passkey-policy.js'
16
+ import { STEP_UP_GROUPS } from './step-up.js'
17
+ import { stepUpSettings } from './step-up-settings.js'
18
+ import { ROLES } from './permissions.js'
19
+ import { accounts, allWorkspaces, audit, auditAccount, tenant } from './tenancy.js'
20
+ import { cleanTailnetLogin } from '../tailnet-proof.js'
21
+
22
+ const DAY = 86_400_000
23
+
24
+ // The workspace a command is about: its id, or the only one there is.
25
+ function workspaceOf(db, id) {
26
+ const all = allWorkspaces(db)
27
+ if (id) {
28
+ const found = ID_PATTERNS.workspace.test(String(id)) ? all.find((row) => row.id === id) : all.find((row) => row.name === id)
29
+ if (!found) throw new OperatorError('no such workspace (see: shapewall hosted admin list)')
30
+ return found
31
+ }
32
+ if (all.length === 1) return all[0]
33
+ throw new OperatorError(
34
+ all.length
35
+ ? 'this server has several workspaces: name one by its id (see: shapewall hosted admin list)'
36
+ : 'this server has no workspace yet',
37
+ )
38
+ }
39
+
40
+ function roleOf(role, fallback = 'member') {
41
+ const value = role === undefined || role === null || role === true ? fallback : String(role)
42
+ if (!ROLES.includes(value)) throw new OperatorError(`--role: one of ${ROLES.join(', ')}`)
43
+ return value
44
+ }
45
+
46
+ // One account, by its handle or by the tailnet login it is linked to. null when there is none.
47
+ function accountBy(db, { handle = null, login = null }) {
48
+ const q = accounts(db)
49
+ const byHandle = typeof handle === 'string' && handle ? handle.trim().toLowerCase().replace(/^@/, '') : null
50
+ const byLogin = typeof login === 'string' && login ? cleanTailnetLogin(login) : null
51
+ if (Boolean(byHandle) === Boolean(byLogin)) throw new OperatorError('say who: --handle HANDLE or --login TAILNET_LOGIN (one of them)')
52
+ const user = byHandle
53
+ ? q.get('SELECT id, handle, display_name, tailnet_login FROM users WHERE handle = :handle', { handle: byHandle })
54
+ : q.get('SELECT id, handle, display_name, tailnet_login FROM users WHERE tailnet_login = :login', { login: byLogin })
55
+ return { user: user || null, login: byLogin, handle: byHandle }
56
+ }
57
+
58
+ const memberRows = (t) =>
59
+ t
60
+ .all(
61
+ `SELECT u.id, u.handle, u.display_name, u.tailnet_login, m.role, m.created_at,
62
+ (SELECT COUNT(*) FROM passkeys p WHERE p.user_id = u.id) AS passkeys
63
+ FROM memberships m JOIN users u ON u.id = m.user_id WHERE m.workspace_id = :ws ORDER BY m.created_at, u.handle`,
64
+ )
65
+ .map((row) => ({
66
+ id: row.id,
67
+ handle: row.handle,
68
+ name: row.display_name,
69
+ tailnetLogin: row.tailnet_login || null,
70
+ role: row.role,
71
+ joinedAt: row.created_at,
72
+ passkeys: row.passkeys,
73
+ }))
74
+
75
+ const inviteRows = (t, now) =>
76
+ t
77
+ .all(
78
+ 'SELECT id, role, created_at, expires_at, tailnet_login, note FROM invites WHERE workspace_id = :ws AND used_at IS NULL AND revoked_at IS NULL AND expires_at > :now ORDER BY created_at',
79
+ { now: now.toISOString() },
80
+ )
81
+ .map((row) => ({
82
+ id: row.id,
83
+ role: row.role,
84
+ createdAt: row.created_at,
85
+ expiresAt: row.expires_at,
86
+ tailnetLogin: row.tailnet_login || null,
87
+ note: row.note || null,
88
+ }))
89
+
90
+ export function listMembers(db, { workspaceId, operator, now = new Date() }) {
91
+ const workspace = workspaceOf(db, workspaceId)
92
+ logOperator(db, { operator, action: 'members_list', target: workspace.id, at: now.toISOString() })
93
+ return { workspace: { id: workspace.id, name: workspace.name }, members: memberRows(tenant(db, workspace.id)) }
94
+ }
95
+
96
+ export function listInvites(db, { workspaceId, operator, now = new Date() }) {
97
+ const workspace = workspaceOf(db, workspaceId)
98
+ logOperator(db, { operator, action: 'invites_list', target: workspace.id, at: now.toISOString() })
99
+ return { workspace: { id: workspace.id, name: workspace.name }, invites: inviteRows(tenant(db, workspace.id), now) }
100
+ }
101
+
102
+ export function listProjects(db, { workspaceId, operator, now = new Date() }) {
103
+ const workspace = workspaceOf(db, workspaceId)
104
+ logOperator(db, { operator, action: 'projects_list', target: workspace.id, at: now.toISOString() })
105
+ const projects = tenant(db, workspace.id)
106
+ .all('SELECT id, slug, name, created_at FROM projects WHERE workspace_id = :ws ORDER BY created_at, slug')
107
+ .map((row) => ({ id: row.id, slug: row.slug, name: row.name, createdAt: row.created_at }))
108
+ return { workspace: { id: workspace.id, name: workspace.name }, projects }
109
+ }
110
+
111
+ // An invite. For one tailnet login (only that login can take it: they open
112
+ // the server from a tailnet device and are in), or a link (`origin` given:
113
+ // whoever has it can use it once).
114
+ export function createInvite(db, { workspaceId, login = null, origin = null, role, days = 7, operator, now = new Date() }) {
115
+ const workspace = workspaceOf(db, workspaceId)
116
+ const wanted = roleOf(role)
117
+ const tailnetLogin = login ? cleanTailnetLogin(login) : null
118
+ if (login && !tailnetLogin) throw new OperatorError('--login: a tailnet login, like ada@example.com')
119
+ if (!tailnetLogin && !origin)
120
+ throw new OperatorError('an invite is for --login TAILNET_LOGIN, or a link: --link --origin https://the.server')
121
+ const length = Number(days)
122
+ if (!Number.isInteger(length) || length < 1 || length > 30) throw new OperatorError('--days: 1 to 30')
123
+ const t = tenant(db, workspace.id)
124
+ const at = now.toISOString()
125
+ return transaction(db, () => {
126
+ if (tailnetLogin) {
127
+ const holder = accounts(db).get('SELECT id FROM users WHERE tailnet_login = :login', { login: tailnetLogin })
128
+ if (holder && t.get('SELECT 1 AS n FROM memberships WHERE workspace_id = :ws AND user_id = :user', { user: holder.id }))
129
+ throw new OperatorError(`${tailnetLogin} is already in ${workspace.name}`)
130
+ }
131
+ // An invite works only while whoever made it may still invite that role (src/hosted/permissions.js
132
+ // inviteCreatorOk): there are no invites without a maker. The operator's invite is made in the name
133
+ // of the workspace's longest-standing owner, and the audit entry says it was the operator.
134
+ const owner = t.get("SELECT user_id FROM memberships WHERE workspace_id = :ws AND role = 'owner' ORDER BY created_at, user_id LIMIT 1")
135
+ if (!owner) throw new OperatorError('this workspace has no owner to make the invite for')
136
+ const token = randomToken(32)
137
+ const id = newId('iv')
138
+ const expiresAt = new Date(now.getTime() + length * DAY).toISOString()
139
+ t.run(
140
+ 'INSERT INTO invites (workspace_id, id, token_hash, role, created_by, created_at, expires_at, email, note, tailnet_login) VALUES (:ws, :id, :hash, :role, :owner, :at, :expires, NULL, :note, :tailnet)',
141
+ {
142
+ id,
143
+ hash: sha256(token),
144
+ role: wanted,
145
+ owner: owner.user_id,
146
+ at,
147
+ expires: expiresAt,
148
+ note: 'from the server’s operator',
149
+ tailnet: tailnetLogin,
150
+ },
151
+ )
152
+ audit(t, {
153
+ action: 'invite_created',
154
+ target: id,
155
+ at,
156
+ detail: { role: wanted, days: length, by: 'operator', operator, ...(tailnetLogin ? { tailnet: tailnetLogin } : {}) },
157
+ })
158
+ logOperator(db, {
159
+ operator,
160
+ action: 'invite_create',
161
+ target: workspace.id,
162
+ detail: { invite: id, role: wanted, tailnet: tailnetLogin },
163
+ at,
164
+ })
165
+ return {
166
+ workspace: { id: workspace.id, name: workspace.name },
167
+ invite: { id, role: wanted, expiresAt, tailnetLogin },
168
+ url: tailnetLogin ? null : `${String(origin).replace(/\/+$/, '')}/invite#${token}`,
169
+ }
170
+ })
171
+ }
172
+
173
+ export function revokeInvite(db, { workspaceId, id, operator, now = new Date() }) {
174
+ const workspace = workspaceOf(db, workspaceId)
175
+ const t = tenant(db, workspace.id)
176
+ const at = now.toISOString()
177
+ const changed = t.run(
178
+ 'UPDATE invites SET revoked_at = :at WHERE workspace_id = :ws AND id = :id AND used_at IS NULL AND revoked_at IS NULL',
179
+ { at, id: String(id || '') },
180
+ ).changes
181
+ if (!changed) throw new OperatorError('no open invite with that id (see: shapewall hosted admin invites list)')
182
+ audit(t, { action: 'invite_revoked', target: String(id), at, detail: { by: 'operator', operator } })
183
+ logOperator(db, { operator, action: 'invite_revoke', target: workspace.id, detail: { invite: String(id) }, at })
184
+ return { workspace: { id: workspace.id, name: workspace.name }, revoked: String(id) }
185
+ }
186
+
187
+ // Puts someone in a workspace. An account that exists (by handle, or by the
188
+ // tailnet login it is linked to) is a member at once, or gets the new role.
189
+ // A tailnet login with no account yet gets an invite only it can take.
190
+ export function addMember(db, { workspaceId, handle, login, role, operator, now = new Date() }) {
191
+ const workspace = workspaceOf(db, workspaceId)
192
+ const wanted = roleOf(role)
193
+ const who = accountBy(db, { handle, login })
194
+ if (!who.user) {
195
+ if (who.handle) throw new OperatorError('no account with that handle')
196
+ if (!who.login) throw new OperatorError('--login: a tailnet login, like ada@example.com')
197
+ return { ...createInvite(db, { workspaceId: workspace.id, login: who.login, role: wanted, days: 30, operator, now }), invited: true }
198
+ }
199
+ const t = tenant(db, workspace.id)
200
+ const at = now.toISOString()
201
+ return transaction(db, () => {
202
+ const current = t.get('SELECT role FROM memberships WHERE workspace_id = :ws AND user_id = :user', { user: who.user.id })
203
+ if (current?.role === wanted) throw new OperatorError(`@${who.user.handle} is already ${wanted} in ${workspace.name}`)
204
+ if (current) {
205
+ if (current.role === 'owner' && t.get("SELECT COUNT(*) AS n FROM memberships WHERE workspace_id = :ws AND role = 'owner'").n <= 1)
206
+ throw new OperatorError('a workspace needs an owner: make someone else an owner first')
207
+ t.run('UPDATE memberships SET role = :role WHERE workspace_id = :ws AND user_id = :user', { role: wanted, user: who.user.id })
208
+ audit(t, {
209
+ action: 'member_role_changed',
210
+ target: who.user.id,
211
+ at,
212
+ detail: { from: current.role, to: wanted, by: 'operator', operator },
213
+ })
214
+ } else {
215
+ t.run('INSERT INTO memberships (workspace_id, user_id, role, created_at) VALUES (:ws, :user, :role, :at)', {
216
+ user: who.user.id,
217
+ role: wanted,
218
+ at,
219
+ })
220
+ audit(t, { action: 'invite_accepted', target: who.user.id, at, detail: { role: wanted, by: 'operator', operator } })
221
+ }
222
+ logOperator(db, {
223
+ operator,
224
+ action: current ? 'member_role' : 'member_add',
225
+ target: workspace.id,
226
+ detail: { handle: who.user.handle, role: wanted, ...(current ? { from: current.role } : {}) },
227
+ at,
228
+ })
229
+ return {
230
+ workspace: { id: workspace.id, name: workspace.name },
231
+ member: { handle: who.user.handle, tailnetLogin: who.user.tailnet_login || null, role: wanted },
232
+ changedFrom: current?.role || null,
233
+ }
234
+ })
235
+ }
236
+
237
+ // Takes someone out of a workspace, with what they made there that lets
238
+ // others in: their open invites, share links and API tokens are revoked.
239
+ export function removeMember(db, { workspaceId, handle, login, operator, now = new Date() }) {
240
+ const workspace = workspaceOf(db, workspaceId)
241
+ const who = accountBy(db, { handle, login })
242
+ if (!who.user) throw new OperatorError(who.handle ? 'no account with that handle' : 'no account is linked to that tailnet login')
243
+ const t = tenant(db, workspace.id)
244
+ const at = now.toISOString()
245
+ return transaction(db, () => {
246
+ const current = t.get('SELECT role FROM memberships WHERE workspace_id = :ws AND user_id = :user', { user: who.user.id })
247
+ if (!current) throw new OperatorError(`@${who.user.handle} is not in ${workspace.name}`)
248
+ if (current.role === 'owner' && t.get("SELECT COUNT(*) AS n FROM memberships WHERE workspace_id = :ws AND role = 'owner'").n <= 1)
249
+ throw new OperatorError('a workspace needs an owner: make someone else an owner first (hosted admin members add ... --role owner)')
250
+ t.run('DELETE FROM memberships WHERE workspace_id = :ws AND user_id = :user', { user: who.user.id })
251
+ const mine = { at, user: who.user.id }
252
+ const invites = t.run(
253
+ 'UPDATE invites SET revoked_at = :at WHERE workspace_id = :ws AND created_by = :user AND used_at IS NULL AND revoked_at IS NULL',
254
+ mine,
255
+ ).changes
256
+ const shares = t.run(
257
+ 'UPDATE shares SET revoked_at = :at WHERE workspace_id = :ws AND created_by = :user AND revoked_at IS NULL',
258
+ mine,
259
+ ).changes
260
+ const tokens = t.run(
261
+ 'UPDATE api_tokens SET revoked_at = :at WHERE workspace_id = :ws AND created_by = :user AND revoked_at IS NULL',
262
+ mine,
263
+ ).changes
264
+ audit(t, { action: 'member_removed', target: who.user.id, at, detail: { role: current.role, by: 'operator', operator } })
265
+ if (invites || shares || tokens)
266
+ audit(t, { action: 'member_grants_revoked', target: who.user.id, at, detail: { invites, shares, tokens, by: 'operator', operator } })
267
+ logOperator(db, {
268
+ operator,
269
+ action: 'member_remove',
270
+ target: workspace.id,
271
+ detail: { handle: who.user.handle, role: current.role, invites, shares, tokens },
272
+ at,
273
+ })
274
+ return {
275
+ workspace: { id: workspace.id, name: workspace.name },
276
+ removed: { handle: who.user.handle, role: current.role },
277
+ revoked: { invites, shares, tokens },
278
+ }
279
+ })
280
+ }
281
+
282
+ // ---- Passkeys on a server with tailnet sign-in (src/hosted/passkey-policy.js) ----
283
+
284
+ // Where the switch stands and what turning it would mean.
285
+ export function passkeysStatus(db) {
286
+ const q = accounts(db)
287
+ return {
288
+ // true, false, or null: not set here (the server's --tailnet-passkeys flag decides; off without it).
289
+ setting: tailnetPasskeysSetting(db),
290
+ accounts: q.get('SELECT COUNT(*) AS n FROM users').n,
291
+ withPasskey: q.get('SELECT COUNT(DISTINCT user_id) AS n FROM passkeys').n,
292
+ // Accounts only a passkey signs in: with passkeys off they cannot sign in at all.
293
+ passkeyOnly: q.get('SELECT COUNT(*) AS n FROM users WHERE tailnet_login IS NULL').n,
294
+ }
295
+ }
296
+
297
+ // What a workspace switched on in "Ask for a passkey again" (and the command line switch): none of it is
298
+ // asked while the server has no passkeys.
299
+ const stepUpOn = (settings) => [...STEP_UP_GROUPS, 'adminIdle', 'cliApproval'].filter((key) => settings[key])
300
+
301
+ const HOLD_MS = 24 * 3_600_000
302
+
303
+ // Switching passkeys off or on for a server with tailnet sign-in. More than a flag:
304
+ // off - every session that a passkey or a recovery code started is deleted (not hidden: switching on
305
+ // later must not bring an old session back);
306
+ // - each workspace that asks for a passkey somewhere gets an audit entry saying that this is not
307
+ // asked for now (its Settings page says the same while it lasts);
308
+ // on - every passkey whose 24 hour hold had not ended when they were switched off starts its hold
309
+ // again: nobody could see or use it in between;
310
+ // - the same workspaces get an entry saying their settings are asked for again.
311
+ export function setPasskeys(db, { on, operator, now = new Date() }) {
312
+ const at = now.toISOString()
313
+ return transaction(db, () => {
314
+ const q = accounts(db)
315
+ const before = tailnetPasskeysSetting(db)
316
+ const offAt = tailnetPasskeysOffAt(db)
317
+ let sessionsEnded = 0
318
+ let holdsRestarted = 0
319
+ if (on) {
320
+ if (before === false && offAt && Number.isFinite(Date.parse(offAt)))
321
+ holdsRestarted = q.run(
322
+ 'UPDATE passkeys SET recovery_added_at = :at WHERE recovery_added_at IS NOT NULL AND recovery_added_at > :since',
323
+ {
324
+ at,
325
+ since: new Date(Date.parse(offAt) - HOLD_MS).toISOString(),
326
+ },
327
+ ).changes
328
+ } else sessionsEnded = q.run('DELETE FROM sessions WHERE tailnet_login IS NULL', {}).changes
329
+ setTailnetPasskeys(db, Boolean(on), at)
330
+ const workspaces = []
331
+ if (before !== Boolean(on))
332
+ for (const workspace of allWorkspaces(db)) {
333
+ const t = tenant(db, workspace.id)
334
+ const asked = stepUpOn(stepUpSettings(t).get())
335
+ if (!asked.length) continue
336
+ workspaces.push({ id: workspace.id, name: workspace.name, settings: asked })
337
+ audit(t, {
338
+ action: 'step_up_changed',
339
+ at,
340
+ detail: { setting: 'passkeys', after: Boolean(on), settings: asked, by: 'operator', operator },
341
+ })
342
+ }
343
+ logOperator(db, {
344
+ operator,
345
+ action: on ? 'passkeys_on' : 'passkeys_off',
346
+ detail: { before, sessionsEnded, holdsRestarted, workspaces: workspaces.map((item) => item.id) },
347
+ at,
348
+ })
349
+ return { ...passkeysStatus(db), before, sessionsEnded, holdsRestarted, workspaces }
350
+ })
351
+ }
352
+
353
+ // ---- A member's tailnet login (src/hosted/tailnet.js accountOf) ----
354
+ //
355
+ // An account is held to Tailscale's own id of the user behind its login. When Tailscale gives the person a
356
+ // new id (the tailnet moved to another identity provider, the user was removed and added again), their own
357
+ // login no longer signs them in: "This tailnet login belongs to someone else here". Nobody in the product
358
+ // can tell that case from a login that was given to somebody else, so the operator decides:
359
+ // relink forgets the id, so the next proven arrival as the login is taken as the account's person
360
+ // (and with --login, links the account to another login);
361
+ // unlink takes the login off the account.
362
+ // Both end the account's tailnet sessions.
363
+ function memberOf(db, { handle = null, login = null }) {
364
+ const who = accountBy(db, { handle, login })
365
+ if (!who.user) throw new OperatorError(who.handle ? 'no account with that handle' : 'no account is linked to that tailnet login')
366
+ return who.user
367
+ }
368
+
369
+ export function relinkMember(db, { handle, login = null, operator, now = new Date() }) {
370
+ const at = now.toISOString()
371
+ // --handle names the account, and --login (optional) the login it is to have. Without --handle, --login
372
+ // names the account that is linked to it now.
373
+ const user = memberOf(db, handle ? { handle } : { login })
374
+ const wanted = handle && login ? cleanTailnetLogin(login) : user.tailnet_login
375
+ if (handle && login && !wanted) throw new OperatorError('--login: a tailnet login, like ada@example.com')
376
+ if (!wanted) throw new OperatorError(`@${user.handle} is not linked to a tailnet login: give one with --login`)
377
+ return transaction(db, () => {
378
+ const q = accounts(db)
379
+ const holder = q.get('SELECT id, handle FROM users WHERE tailnet_login = :login', { login: wanted })
380
+ if (holder && holder.id !== user.id) throw new OperatorError(`${wanted} is linked to @${holder.handle}: unlink that account first`)
381
+ q.run('UPDATE users SET tailnet_login = :login, tailnet_linked_at = :at, tailnet_user_id = NULL WHERE id = :id', {
382
+ login: wanted,
383
+ at,
384
+ id: user.id,
385
+ })
386
+ q.run('DELETE FROM tailnet_visitors WHERE login = :login', { login: wanted })
387
+ const sessionsEnded = q.run('DELETE FROM sessions WHERE user_id = :user AND tailnet_login IS NOT NULL', { user: user.id }).changes
388
+ const detail = {
389
+ tailnet: wanted,
390
+ ...(user.tailnet_login && user.tailnet_login !== wanted ? { was: user.tailnet_login } : {}),
391
+ relinked: true,
392
+ }
393
+ auditAccount(db, { userId: user.id, action: 'tailnet_linked', at, detail: { ...detail, by: 'operator', operator } })
394
+ logOperator(db, { operator, action: 'member_relink', target: user.id, detail: { handle: user.handle, ...detail, sessionsEnded }, at })
395
+ return { user: { handle: user.handle }, login: wanted, was: user.tailnet_login || null, sessionsEnded }
396
+ })
397
+ }
398
+
399
+ export function unlinkMember(db, { handle, login = null, operator, now = new Date() }) {
400
+ const at = now.toISOString()
401
+ const user = memberOf(db, handle ? { handle } : { login })
402
+ if (!user.tailnet_login) throw new OperatorError(`@${user.handle} is not linked to a tailnet login`)
403
+ return transaction(db, () => {
404
+ const q = accounts(db)
405
+ q.run('UPDATE users SET tailnet_login = NULL, tailnet_linked_at = NULL, tailnet_user_id = NULL WHERE id = :id', { id: user.id })
406
+ const sessionsEnded = q.run('DELETE FROM sessions WHERE user_id = :user AND tailnet_login IS NOT NULL', { user: user.id }).changes
407
+ const passkeys = q.get('SELECT COUNT(*) AS n FROM passkeys WHERE user_id = :user', { user: user.id }).n
408
+ auditAccount(db, { userId: user.id, action: 'tailnet_unlinked', at, detail: { tailnet: user.tailnet_login, by: 'operator', operator } })
409
+ logOperator(db, {
410
+ operator,
411
+ action: 'member_unlink',
412
+ target: user.id,
413
+ detail: { handle: user.handle, tailnet: user.tailnet_login, sessionsEnded },
414
+ at,
415
+ })
416
+ return { user: { handle: user.handle }, was: user.tailnet_login, sessionsEnded, passkeys }
417
+ })
418
+ }
@@ -27,6 +27,8 @@ import { deleteWorkspaceRows, planWorkspaceExport, writeWorkspaceExport } from '
27
27
  import { createProjectStore } from './projects.js'
28
28
  import { ZIP_MAX_BYTES } from './zip.js'
29
29
  import { accounts, allWorkspaces, audit, auditAccount, findShareById, tenant } from './tenancy.js'
30
+ import { setUsageRetention } from './usage.js'
31
+ import { cleanTailnetLogin } from '../tailnet-proof.js'
30
32
 
31
33
  export const REPORT_REASONS = {
32
34
  copyright: 'Copyright or trademark',
@@ -82,7 +84,7 @@ function clean(value, max) {
82
84
  .slice(0, max)
83
85
  }
84
86
 
85
- function logOperator(db, { operator, action, target = null, detail = {}, at }) {
87
+ export function logOperator(db, { operator, action, target = null, detail = {}, at }) {
86
88
  accounts(db).run('INSERT INTO operator_log (operator, action, target, detail, at) VALUES (:operator, :action, :target, :detail, :at)', {
87
89
  operator,
88
90
  action,
@@ -92,6 +94,90 @@ function logOperator(db, { operator, action, target = null, detail = {}, at }) {
92
94
  })
93
95
  }
94
96
 
97
+ // ---- An account's passkeys (shapewall hosted admin passkeys) ----
98
+ //
99
+ // For the case nobody in the product can solve: an account whose only
100
+ // passkey is not its owner's (or is lost) and that cannot be asked for
101
+ // anything else. Being able to read and write the data folder is the proof,
102
+ // as for every operator command. One account, named by its handle or by the
103
+ // tailnet login it is linked to.
104
+ function accountOf(db, { handle = null, login = null }) {
105
+ const q = accounts(db)
106
+ const byHandle = typeof handle === 'string' && handle ? handle.trim().toLowerCase().replace(/^@/, '') : null
107
+ // The login as the server keeps it (the same cleaning as everywhere a login is read).
108
+ const byLogin = typeof login === 'string' && login ? cleanTailnetLogin(login) : null
109
+ if (typeof login === 'string' && login && !byLogin) throw new OperatorError('--login: a tailnet login, like ada@example.com')
110
+ if (Boolean(byHandle) === Boolean(byLogin))
111
+ throw new OperatorError('say whose passkeys: --handle HANDLE or --login TAILNET_LOGIN (one of them)')
112
+ const user = byHandle
113
+ ? q.get('SELECT id, handle, display_name, tailnet_login FROM users WHERE handle = :handle', { handle: byHandle })
114
+ : q.get('SELECT id, handle, display_name, tailnet_login FROM users WHERE tailnet_login = :login', { login: byLogin })
115
+ if (!user) throw new OperatorError(byHandle ? 'no account with that handle' : 'no account is linked to that tailnet login')
116
+ return user
117
+ }
118
+ const HOLD_MS = 24 * 3_600_000
119
+ const passkeyRows = (db, userId, now) =>
120
+ accounts(db)
121
+ .all(
122
+ 'SELECT id, nickname, created_at, last_used_at, recovery_added_at, tailnet_added_from FROM passkeys WHERE user_id = :user ORDER BY created_at',
123
+ { user: userId },
124
+ )
125
+ .map((row) => ({
126
+ id: row.id,
127
+ nickname: row.nickname || '',
128
+ createdAt: row.created_at,
129
+ lastUsedAt: row.last_used_at || null,
130
+ addedFrom: row.tailnet_added_from || null,
131
+ onHoldUntil:
132
+ row.recovery_added_at && now.getTime() - Date.parse(row.recovery_added_at) < HOLD_MS
133
+ ? new Date(Date.parse(row.recovery_added_at) + HOLD_MS).toISOString()
134
+ : null,
135
+ }))
136
+
137
+ export function listPasskeysOf(db, { handle, login, operator, now = new Date() }) {
138
+ const user = accountOf(db, { handle, login })
139
+ logOperator(db, { operator, action: 'passkeys_list', target: user.id, detail: { handle: user.handle }, at: now.toISOString() })
140
+ return { user: { id: user.id, handle: user.handle, tailnetLogin: user.tailnet_login || null }, passkeys: passkeyRows(db, user.id, now) }
141
+ }
142
+
143
+ // Removes one passkey, whatever it is (the last one too), and ends every
144
+ // session of the account that is not a tailnet session: one of them may have
145
+ // been signed in with that passkey. In the operator log, and in the
146
+ // account's own security log as the operator's doing.
147
+ export function removePasskeyOf(db, { handle, login, id, operator, now = new Date() }) {
148
+ const user = accountOf(db, { handle, login })
149
+ const at = now.toISOString()
150
+ return transaction(db, () => {
151
+ const q = accounts(db)
152
+ const key = passkeyRows(db, user.id, now).find((row) => row.id === String(id || ''))
153
+ if (!key) throw new OperatorError('that account has no passkey with that id (see: shapewall hosted admin passkeys list)')
154
+ q.run('DELETE FROM passkeys WHERE id = :id AND user_id = :user', { id: key.id, user: user.id })
155
+ const ended = q.run('DELETE FROM sessions WHERE user_id = :user AND tailnet_login IS NULL', { user: user.id }).changes
156
+ const left = passkeyRows(db, user.id, now).length
157
+ const detail = {
158
+ handle: user.handle,
159
+ passkey: key.id.slice(0, 12),
160
+ nickname: key.nickname,
161
+ addedFrom: key.addedFrom,
162
+ sessionsEnded: ended,
163
+ left,
164
+ }
165
+ logOperator(db, { operator, action: 'passkey_remove', target: user.id, detail, at })
166
+ auditAccount(db, {
167
+ userId: user.id,
168
+ action: 'passkey_removed',
169
+ at,
170
+ detail: { by: 'operator', operator, nickname: key.nickname, otherSessionsEnded: true },
171
+ })
172
+ return {
173
+ user: { id: user.id, handle: user.handle, tailnetLogin: user.tailnet_login || null },
174
+ removed: key,
175
+ sessionsEnded: ended,
176
+ left,
177
+ }
178
+ })
179
+ }
180
+
95
181
  export function operatorLog(db, { limit = 50 } = {}) {
96
182
  return accounts(db)
97
183
  .all('SELECT id, operator, action, target, detail, at FROM operator_log ORDER BY id DESC LIMIT :limit', { limit })
@@ -250,11 +336,29 @@ export function setRetention(db, { workspaceId, keep, operator, now = new Date()
250
336
  return { id: workspaceId, name: row.name, keep }
251
337
  }
252
338
 
339
+ // How long one workspace keeps its usage records, in days (null: the server
340
+ // default). The setting itself is changed by one function, usage.js
341
+ // setUsageRetention, which the workspace's audit log hears too.
342
+ export function setUsageRetentionFor(db, { workspaceId, days, operator, now = new Date() }) {
343
+ const { t, row } = findWorkspace(db, workspaceId)
344
+ if (days !== null && !(Number.isInteger(days) && days >= 1 && days <= 3650))
345
+ throw new OperatorError('--usage-days: a whole number from 1 to 3650, or "default"')
346
+ const at = now.toISOString()
347
+ const result = transaction(db, () => {
348
+ const set = setUsageRetention(t, days, {
349
+ audit: (action, target, detail) => audit(t, { action, target, detail: { ...detail, by: 'operator' }, at }),
350
+ })
351
+ logOperator(db, { operator, action: 'usage_retention', target: workspaceId, detail: { name: row.name, days }, at })
352
+ return set
353
+ })
354
+ return { id: workspaceId, name: row.name, usageDays: result.days, own: result.own }
355
+ }
356
+
253
357
  export function recordRetentionRun(db, { operator, result, dryRun, now = new Date() }) {
254
358
  logOperator(db, {
255
359
  operator,
256
360
  action: dryRun ? 'retention_dry_run' : 'retention_run',
257
- detail: { files: result.files, bytes: result.bytes, boards: result.boards },
361
+ detail: { files: result.files, bytes: result.bytes, boards: result.boards, usageRows: result.usageRows || 0 },
258
362
  at: now.toISOString(),
259
363
  })
260
364
  }