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
@@ -16,6 +16,10 @@
16
16
  // swaps board folders inside its own transaction, so the two never interleave,
17
17
  // also when the CLI runs it from another process.
18
18
  //
19
+ // Usage records (agent_runs: one small row per agent turn) are pruned by age:
20
+ // 400 days by default, or the workspace's own setting (`shapewall hosted admin
21
+ // retention <ws> --usage-days N`). A turn still running is never removed.
22
+ //
19
23
  // A later push brings back the versions the pushing machine still keeps; the
20
24
  // next run trims them again.
21
25
 
@@ -26,6 +30,7 @@ import { listVersions } from '../store.js'
26
30
  import { transaction } from './db.js'
27
31
  import { boardConfig } from './projects.js'
28
32
  import { allWorkspaces, tenant } from './tenancy.js'
33
+ import { USAGE_RETENTION_DAYS, createUsage } from './usage.js'
29
34
 
30
35
  export const RETENTION_DEFAULT = 2
31
36
  export const RETENTION_EVERY_HOURS = 6
@@ -47,13 +52,23 @@ export function planBoardRetention(versions, referenced, keep) {
47
52
  return remove
48
53
  }
49
54
 
50
- export function runRetention({ db, dataDir, keepDefault = RETENTION_DEFAULT, dryRun = false, workspaceId = null }) {
51
- const result = { workspaces: 0, boards: 0, files: 0, bytes: 0, dryRun }
55
+ export function runRetention({
56
+ db,
57
+ dataDir,
58
+ keepDefault = RETENTION_DEFAULT,
59
+ usageDaysDefault = USAGE_RETENTION_DAYS,
60
+ dryRun = false,
61
+ workspaceId = null,
62
+ now = () => new Date(),
63
+ }) {
64
+ const result = { workspaces: 0, boards: 0, files: 0, bytes: 0, usageRows: 0, dryRun }
52
65
  for (const workspace of allWorkspaces(db)) {
53
66
  if (workspaceId && workspace.id !== workspaceId) continue
54
67
  result.workspaces += 1
55
68
  const keep = workspace.retention_versions ?? keepDefault
56
69
  const t = tenant(db, workspace.id)
70
+ // Usage records (one row per agent turn) older than the workspace keeps them.
71
+ result.usageRows += transaction(db, () => createUsage(t, { now }).prune(workspace.retention_usage_days ?? usageDaysDefault, { dryRun }))
57
72
  for (const row of t.all('SELECT project_id, board_id FROM boards WHERE workspace_id = :ws ORDER BY project_id, board_id')) {
58
73
  if (!ID_RE.test(row.board_id)) continue
59
74
  const removed = pruneBoard(db, t, dataDir, row.project_id, row.board_id, keep, dryRun)
@@ -133,6 +148,7 @@ export function startRetention({ db, dataDir, hours = RETENTION_EVERY_HOURS, kee
133
148
  const run = () => {
134
149
  try {
135
150
  const result = runRetention({ db, dataDir, keepDefault })
151
+ if (result.usageRows) log(`retention: removed ${result.usageRows} old usage records`)
136
152
  if (result.files)
137
153
  log(`retention: removed ${result.files} old version files (${(result.bytes / 1048576).toFixed(1)} MB) from ${result.boards} boards`)
138
154
  } catch (error) {
@@ -10,6 +10,7 @@
10
10
  import fs from 'node:fs'
11
11
  import path from 'node:path'
12
12
  import http from 'node:http'
13
+ import { EventEmitter } from 'node:events'
13
14
  import { randomBytes } from 'node:crypto'
14
15
  import { MIN_NODE, nodeSupportsSqlite, openDatabase, quietSqliteWarning } from './db.js'
15
16
  import { writeSetupLink } from './setup-link.js'
@@ -65,6 +66,9 @@ export function proxyWarning({ origin, host, trustProxy }) {
65
66
  return 'Warning: the origin is https but the server listens on loopback without --trust-proxy, so rate limits see every client as the proxy. Add --trust-proxy when a reverse proxy on this host forwards to it.'
66
67
  }
67
68
 
69
+ // Why tailnet sign-in cannot be switched on (the CLI prints the message).
70
+ export class TailnetSignInError extends Error {}
71
+
68
72
  function listen(handler, port, host) {
69
73
  const server = http.createServer(handler)
70
74
  return new Promise((resolve, reject) => {
@@ -86,8 +90,19 @@ export async function startHosted({
86
90
  trustProxy = false,
87
91
  previousOrigin = null,
88
92
  reportEmail = null,
93
+ ownersSeeSignIns = false,
89
94
  // Mode 1 (src/hosted/tailscale.js): { httpsPort, funnel: { httpsPort, localPort } | null, run }
90
95
  tailscale = null,
96
+ // Tailnet sign-in (--tailnet-sign-in, with --tailscale): a tailnet user who
97
+ // arrives through tailscale serve is signed in as the account linked to
98
+ // their login (src/tailnet-proof.js). `tailnetProof` replaces the check
99
+ // that a connection comes from tailscaled, and `tailnetFacts` what the
100
+ // machine says about tailscaled (tests).
101
+ tailnetSignIn = false,
102
+ // With tailnet sign-in: also allow passkeys (--tailnet-passkeys). Off by default: Tailscale is the sign-in.
103
+ tailnetPasskeys = false,
104
+ tailnetProof = null,
105
+ tailnetFacts = null,
91
106
  quotasFile = null,
92
107
  retentionHours = undefined,
93
108
  retentionKeep = undefined,
@@ -116,6 +131,10 @@ export async function startHosted({
116
131
  if (tailscale && host !== '127.0.0.1')
117
132
  throw new Error('--tailscale listens on 127.0.0.1 only (tailscale serve forwards to it); drop --host')
118
133
  if (tailscale && origin) throw new Error('--tailscale sets the origin itself (https://<machine>.<tailnet>.ts.net); drop --origin')
134
+ if (tailnetSignIn && !tailscale)
135
+ throw new TailnetSignInError(
136
+ '--tailnet-sign-in goes with --tailscale: it signs people in by the identity that tailscale serve adds, and this server would not be behind it.',
137
+ )
119
138
  const db = await openDatabase(path.join(dir, 'shapewall.db'))
120
139
  const cleanup = []
121
140
  const stopAll = async () => {
@@ -139,13 +158,38 @@ export async function startHosted({
139
158
 
140
159
  // Mode 1: listen on loopback first (port 0 picks one), then point
141
160
  // tailscale serve at it; the origin is only known after that.
142
- const holder = { app: null, share: null }
143
- const server = await listen((req, res) => (holder.app ? holder.app(req, res) : res.writeHead(503).end()), port, host)
161
+ const holder = { app: null, share: null, gate: null }
162
+ let tailnetWatch = null
163
+ // With tailnet sign-in every request is first asked how it came in (the
164
+ // serve secret comes off its path there, and who it is from is worked out).
165
+ const entry = (req, res) => {
166
+ const pass = () => (holder.app ? holder.app(req, res) : res.writeHead(503).end())
167
+ if (!holder.gate) return pass()
168
+ holder.gate.admit(req, res).then(
169
+ (ok) => ok && pass(),
170
+ () => res.writeHead(500).end(),
171
+ )
172
+ }
173
+ const server = await listen(entry, port, host)
144
174
  cleanup.push(() => new Promise((resolve) => server.close(() => resolve())))
145
175
  const localPort = server.address().port
146
176
  let publicOrigin = origin || `http://${host.includes(':') ? `[${host}]` : host}:${localPort}`
147
177
  let shareOrigin = null
148
178
  let shareServer = null
179
+ // Tailnet sign-in: refuse to start when this machine cannot prove that a
180
+ // request came from tailscaled, before anything is put on the tailnet.
181
+ let gate = null
182
+ let serveSecret = null
183
+ let proof = null
184
+ const refuse = (problem) => new TailnetSignInError(`Tailnet sign-in stays off, and the server did not start: ${problem}`)
185
+ const proofModule = tailnetSignIn ? await import('../tailnet-proof.js') : null
186
+ if (tailnetSignIn) {
187
+ proof = tailnetProof || proofModule.procPeerProof()
188
+ const problem = proof.problem?.() || (await proofModule.proofSelfTest(server, proof))
189
+ if (problem) throw refuse(problem)
190
+ // Known to this process and to the serve entry it makes, new at each start. Never logged.
191
+ serveSecret = proofModule.newServeSecret()
192
+ }
149
193
  if (tailscale) {
150
194
  const ts = await import('./tailscale.js')
151
195
  let funnel = null
@@ -154,12 +198,18 @@ export async function startHosted({
154
198
  cleanup.push(() => new Promise((resolve) => shareServer.close(() => resolve())))
155
199
  funnel = { httpsPort: tailscale.funnel.httpsPort, localPort: shareServer.address().port }
156
200
  }
157
- const served = await ts.startTailscale({
158
- localPort,
159
- httpsPort: tailscale.httpsPort ?? 443,
160
- funnel,
161
- ...(tailscale.run ? { run: tailscale.run } : {}),
162
- })
201
+ const served = await ts
202
+ .startTailscale({
203
+ localPort,
204
+ httpsPort: tailscale.httpsPort ?? 443,
205
+ funnel,
206
+ ...(tailscale.run ? { run: tailscale.run } : {}),
207
+ ...(serveSecret ? { secret: serveSecret } : {}),
208
+ ...(tailnetFacts ? { facts: tailnetFacts } : {}),
209
+ })
210
+ .catch((error) => {
211
+ throw error instanceof ts.TailnetSignInRefused ? refuse(`${error.message}.`) : error
212
+ })
163
213
  cleanup.push(async () => {
164
214
  const ok = await served.stop()
165
215
  out(
@@ -173,6 +223,48 @@ export async function startHosted({
173
223
  trustProxy = true
174
224
  out(`On your tailnet: ${publicOrigin} (tailscale serve, not public)`)
175
225
  if (shareOrigin) out(`Share links are public through Tailscale Funnel: ${shareOrigin} (share pages only; the console is not there)`)
226
+ if (serveSecret) {
227
+ // The serve entry must be the only way to this port, and tailscaled
228
+ // one whose connections can be believed, now and while the server
229
+ // runs: checked again every half minute, and nobody is believed
230
+ // while it is not so.
231
+ const first = await served.verify()
232
+ if (first) throw refuse(`${first}.`)
233
+ out(
234
+ tailnetPasskeys
235
+ ? 'Sign-in: your Tailscale account, and passkeys for accounts that add one (--tailnet-passkeys).'
236
+ : 'Sign-in: your Tailscale account, on every tailnet device of yours. No passkeys (shapewall hosted admin passkeys on turns them on).',
237
+ )
238
+ out('This machine itself is never signed in by its tailnet identity: use another tailnet device, or shapewall hosted admin here.')
239
+ gate = proofModule.createTailnetGate({
240
+ secret: serveSecret,
241
+ proof,
242
+ whois: served.whois,
243
+ self: served.self,
244
+ log: (line) => out(line),
245
+ })
246
+ holder.gate = gate
247
+ const watch = async () => {
248
+ const problem = await served.verify().catch(() => 'tailscale serve status could not be read')
249
+ if (problem && !gate.suspended()) {
250
+ out(`Tailnet sign-in is suspended: ${problem}. Nobody is signed in by tailnet identity until this is fixed.`)
251
+ gate.suspend(problem)
252
+ // What a tailnet session still has open (live streams) ends now.
253
+ holder.app?.locals.cutTailnetSessions?.()
254
+ } else if (!problem && gate.suspended()) {
255
+ out('Tailnet sign-in is back: the tailscale serve entry and tailscaled are as this server needs them.')
256
+ gate.resume()
257
+ }
258
+ }
259
+ const every = tailscale.watchMs ?? 30_000
260
+ const timer = every ? setInterval(watch, every) : null
261
+ timer?.unref()
262
+ cleanup.push(() => timer && clearInterval(timer))
263
+ tailnetWatch = watch
264
+ out(
265
+ 'Tailnet sign-in: on. A tailnet user who arrives through tailscale serve is signed in as the account linked to their login; an admin still decides who is in a workspace. Tagged devices and Funnel visitors are never signed in.',
266
+ )
267
+ }
176
268
  }
177
269
 
178
270
  const warning = proxyWarning({ origin: publicOrigin, host, trustProxy })
@@ -189,10 +281,30 @@ export async function startHosted({
189
281
  usercontentOrigin,
190
282
  turnstile,
191
283
  reportEmail,
284
+ ownersSeeSignIns,
192
285
  log: (line) => out(line),
193
286
  }
194
- const app = createHostedApp({ ...common, origin: publicOrigin, shareOrigin, previousOrigin, mailer: mailer.configured ? mailer : null })
195
- app.locals.presence.attach(server)
287
+ const app = createHostedApp({
288
+ ...common,
289
+ origin: publicOrigin,
290
+ shareOrigin,
291
+ previousOrigin,
292
+ mailer: mailer.configured ? mailer : null,
293
+ tailnet: gate,
294
+ tailnetPasskeys,
295
+ })
296
+ if (gate) {
297
+ // A WebSocket upgrade does not pass through the handler above: it is
298
+ // admitted here first, then handed to the presence listener.
299
+ const upgrades = new EventEmitter()
300
+ app.locals.presence.attach(upgrades)
301
+ server.on('upgrade', (req, socket, head) => {
302
+ gate.admit(req).then(
303
+ (ok) => ok && upgrades.emit('upgrade', req, socket, head),
304
+ () => socket.destroy(),
305
+ )
306
+ })
307
+ } else app.locals.presence.attach(server)
196
308
  holder.app = app
197
309
  cleanup.push(() => app.locals.close())
198
310
  if (shareServer) {
@@ -251,7 +363,7 @@ export async function startHosted({
251
363
  }
252
364
  process.once('SIGINT', stop)
253
365
  process.once('SIGTERM', stop)
254
- return { server, shareServer, app, db, origin: publicOrigin, shareOrigin, stop }
366
+ return { server, shareServer, app, db, origin: publicOrigin, shareOrigin, stop, tailnet: gate, tailnetWatch }
255
367
  } catch (error) {
256
368
  await stopAll().catch(() => {})
257
369
  db.close()
@@ -149,7 +149,7 @@ const SHARE_SELECT = `SELECT s.*, p.name AS project_name, c.handle AS creator_ha
149
149
 
150
150
  // Console routes for admins: list, create and revoke a project's links.
151
151
  export function mountShareAdmin(router, deps) {
152
- const { iso, handle, inWorkspace, inProject, needFresh, auditOf, HttpError, publicOrigin } = deps
152
+ const { iso, handle, inWorkspace, inProject, stepUp, auditOf, HttpError, publicOrigin } = deps
153
153
 
154
154
  router.get(
155
155
  '/workspaces/:ws/shares',
@@ -178,7 +178,7 @@ export function mountShareAdmin(router, deps) {
178
178
  router.post(
179
179
  '/workspaces/:ws/projects/:pid/shares',
180
180
  inWorkspace(NEEDS.shares),
181
- needFresh,
181
+ stepUp('tokens'),
182
182
  inProject,
183
183
  handle(async (req, res) => {
184
184
  const workspace = req.t.get('SELECT share_links FROM workspaces WHERE workspace_id = :ws')
@@ -0,0 +1,68 @@
1
+ // A workspace's step-up settings ("Ask for a passkey again before...",
2
+ // src/hosted/step-up.js): reading them, and one function per setting to
3
+ // change them, so the console's routes and a later admin tool call the same
4
+ // code. Every change is an owner's, is written to the audit log with the
5
+ // value before and after, and a change that asks for the passkey less needs
6
+ // a fresh passkey check itself (the actor says whether it has one; a caller
7
+ // cannot leave that out).
8
+ //
9
+ // const settings = stepUpSettings(t)
10
+ // settings.get()
11
+ // settings.setGroup(actor, 'tokens', true)
12
+ // settings.setWindow(actor, 30)
13
+ // settings.setAdminIdle(actor, true)
14
+ // settings.setCliApproval(actor, true)
15
+ //
16
+ // actor: { role, fresh, audit(action, target, detail) }
17
+ // fresh: true when the person passed a passkey check in the last 10
18
+ // minutes; or a function that throws the refusal to send when they did not.
19
+
20
+ import { HttpError } from './http.js'
21
+ import { STEP_UP_GROUPS, STEP_UP_WINDOWS, readStepUp, stepUpWeaker } from './step-up.js'
22
+
23
+ export function stepUpSettings(t) {
24
+ const get = () => readStepUp(t.get('SELECT step_up FROM workspaces WHERE workspace_id = :ws')?.step_up)
25
+
26
+ function change(actor, setting, next) {
27
+ if (actor?.role !== 'owner')
28
+ throw new HttpError(403, 'forbidden', 'Only an owner changes when this workspace asks for a passkey again.')
29
+ const before = get()
30
+ const after = readStepUp({ ...before, ...next })
31
+ if (JSON.stringify(before) === JSON.stringify(after)) return after
32
+ if (stepUpWeaker(before, after)) {
33
+ if (typeof actor.fresh === 'function') actor.fresh()
34
+ else if (actor.fresh !== true)
35
+ throw new HttpError(403, 'reauth_required', 'Confirm with your passkey first (always needed to make these settings weaker).')
36
+ }
37
+ t.run('UPDATE workspaces SET step_up = :value WHERE workspace_id = :ws', { value: JSON.stringify(after) })
38
+ const key = Object.keys(next)[0]
39
+ actor.audit('step_up_changed', null, { setting, before: before[key], after: after[key] })
40
+ return after
41
+ }
42
+
43
+ return {
44
+ get,
45
+ // One group on or off.
46
+ setGroup(actor, group, on) {
47
+ if (!STEP_UP_GROUPS.includes(group)) throw new HttpError(400, 'invalid_settings', `group: one of ${STEP_UP_GROUPS.join(', ')}.`)
48
+ if (typeof on !== 'boolean') throw new HttpError(400, 'invalid_settings', 'on: true or false.')
49
+ return change(actor, group, { [group]: on })
50
+ },
51
+ // How long one passkey check counts for the groups that are on.
52
+ setWindow(actor, minutes) {
53
+ if (!STEP_UP_WINDOWS.includes(minutes))
54
+ throw new HttpError(400, 'invalid_settings', `windowMinutes: one of ${STEP_UP_WINDOWS.join(', ')}.`)
55
+ return change(actor, 'windowMinutes', { windowMinutes: minutes })
56
+ },
57
+ // Admin pages ask again after 12 hours without a visit to one.
58
+ setAdminIdle(actor, on) {
59
+ if (typeof on !== 'boolean') throw new HttpError(400, 'invalid_settings', 'adminIdle: true or false.')
60
+ return change(actor, 'adminIdle', { adminIdle: on })
61
+ },
62
+ // Tailnet sign-in: CLI logins and agent connections wait for the browser anyway.
63
+ setCliApproval(actor, on) {
64
+ if (typeof on !== 'boolean') throw new HttpError(400, 'invalid_settings', 'cliApproval: true or false.')
65
+ return change(actor, 'cliApproval', { cliApproval: on })
66
+ },
67
+ }
68
+ }
@@ -0,0 +1,135 @@
1
+ // Step-up: asking for the passkey again before an action. Plain values and
2
+ // functions with no imports, so the server (guards.js, step-up-settings.js),
3
+ // the console and the public demo's in-browser backend all name the groups
4
+ // the same way.
5
+ //
6
+ // By default a signed-in session with the right role is enough for
7
+ // everything in a workspace. Two things ask for the passkey again:
8
+ //
9
+ // 1. The fixed core, always (STEP_UP_ALWAYS): what guards the account
10
+ // itself or cannot be undone for everyone. Not a setting.
11
+ // 2. A workspace's own choice (STEP_UP_GROUPS): an owner switches a group
12
+ // on in Settings, "Ask for a passkey again before...". Off by default.
13
+ //
14
+ // Sessions that started with a recovery code, or with a passkey that was
15
+ // added with one in the last 24 hours, are stricter whatever the settings
16
+ // say: every action in a group needs a passkey check they cannot give yet
17
+ // (src/hosted/auth.js `restricted`).
18
+
19
+ // The groups a workspace can switch on, in the order Settings shows them.
20
+ export const STEP_UP_GROUPS = ['cards', 'agents', 'tokens', 'members', 'data']
21
+
22
+ export const STEP_UP_GROUP_LABEL = {
23
+ cards: 'Agent edits and pushes',
24
+ agents: 'Agents and machines',
25
+ tokens: 'Tokens and share links',
26
+ members: 'Members and roles',
27
+ data: 'Exports and deletes',
28
+ }
29
+
30
+ // What each group covers, as Settings says it.
31
+ export const STEP_UP_GROUP_COVERS = {
32
+ cards: "Allow on an agent's edit or command, Push this fix, approving an agent run or a shell command",
33
+ agents: 'approving a machine or an agent, who may use an agent, its approval rule, the project agent policy',
34
+ tokens: 'new API tokens, new share links, turning share links or public projects on, making a project public',
35
+ members: 'inviting an admin, making someone an admin, changing or removing an admin',
36
+ data: 'exporting the workspace, deleting a project or a board',
37
+ }
38
+
39
+ // The words a refusal uses: "This workspace asks for your passkey again before <this>."
40
+ export const STEP_UP_GROUP_BEFORE = {
41
+ cards: 'agent edits and pushes',
42
+ agents: 'changes to agents and machines',
43
+ tokens: 'new tokens and share links',
44
+ members: 'changes to admins',
45
+ data: 'exports and deletes',
46
+ }
47
+
48
+ // How long one passkey check counts for a group that is on (minutes).
49
+ export const STEP_UP_WINDOWS = [5, 15, 30, 60]
50
+ export const STEP_UP_WINDOW_DEFAULT = 15
51
+
52
+ // The fixed core: what always needs a fresh passkey check (10 minutes), on
53
+ // every server. ONE TABLE: to add a route to the core, add a line here.
54
+ //
55
+ // A line with `method` and `path` is enforced for every request by one
56
+ // middleware (src/hosted/guards.js fixedCore), before the route runs:
57
+ // path the full path, `:name` for one segment
58
+ // role only for members of the workspace (`:ws`) with at least this
59
+ // role; anyone else gets the route's own 404 or 403
60
+ // first true: the first passkey of an account that has none may be added
61
+ // without a check (a recovery session in its first 30 minutes, an
62
+ // account that only its tailnet signs in)
63
+ // A line with `inRoute` depends on what the request changes, or on which
64
+ // host it arrives at, so its route asks itself (coreFreshOrThrow / needFresh).
65
+ // `says`: the words Settings lists; lines with the same words are one item.
66
+ export const FIXED_CORE = [
67
+ { method: 'POST', path: '/auth/passkeys/options', first: true, says: 'adding or removing a passkey' },
68
+ { method: 'POST', path: '/auth/passkeys/verify', first: true, says: 'adding or removing a passkey' },
69
+ // held: a tailnet session may take away a passkey that a tailnet session added and that is still on hold.
70
+ { method: 'DELETE', path: '/auth/passkeys/:id', held: true, says: 'adding or removing a passkey' },
71
+ { method: 'POST', path: '/auth/recovery-codes', says: 'new recovery codes' },
72
+ { method: 'POST', path: '/auth/tailnet/link', says: 'linking or unlinking a tailnet login' },
73
+ { method: 'DELETE', path: '/auth/tailnet/link', says: 'linking or unlinking a tailnet login' },
74
+ { method: 'DELETE', path: '/auth/me', says: 'deleting your account' },
75
+ { method: 'DELETE', path: '/api/workspaces/:ws', role: 'owner', says: 'deleting a workspace' },
76
+ {
77
+ inRoute: 'console-routes.js roleStepUp',
78
+ says: 'making someone an owner, changing or removing an owner (leaving as one too), inviting an owner',
79
+ },
80
+ { inRoute: 'rebind.js POST /auth/rebind/start', says: "moving your account to the server's new address" },
81
+ { inRoute: 'step-up-settings.js change', says: 'making these settings weaker' },
82
+ ]
83
+ export const STEP_UP_ALWAYS = [...new Set(FIXED_CORE.map((line) => line.says))]
84
+
85
+ export const STEP_UP_DEFAULTS = Object.freeze({
86
+ cards: false,
87
+ agents: false,
88
+ tokens: false,
89
+ members: false,
90
+ data: false,
91
+ // Admin pages ask again after 12 hours without a visit to one.
92
+ adminIdle: false,
93
+ // On a server with tailnet sign-in: `shapewall login` and `agent connect`
94
+ // from a tailnet machine are approved in the browser anyway, as on any
95
+ // other server (off: the tailnet identity of the machine's user is enough).
96
+ cliApproval: false,
97
+ windowMinutes: STEP_UP_WINDOW_DEFAULT,
98
+ })
99
+
100
+ // The stored value (a JSON string or an object) as complete settings.
101
+ // Anything unknown or malformed reads as the default: off.
102
+ export function readStepUp(raw) {
103
+ let value = raw
104
+ if (typeof raw === 'string') {
105
+ try {
106
+ value = JSON.parse(raw || '{}')
107
+ } catch {
108
+ value = {}
109
+ }
110
+ }
111
+ if (!value || typeof value !== 'object' || Array.isArray(value)) value = {}
112
+ const out = { ...STEP_UP_DEFAULTS }
113
+ for (const group of STEP_UP_GROUPS) out[group] = value[group] === true
114
+ out.adminIdle = value.adminIdle === true
115
+ out.cliApproval = value.cliApproval === true
116
+ out.windowMinutes = STEP_UP_WINDOWS.includes(value.windowMinutes) ? value.windowMinutes : STEP_UP_WINDOW_DEFAULT
117
+ return out
118
+ }
119
+
120
+ // Whether `after` asks for the passkey less than `before`: a group or the
121
+ // admin idle rule switched off, or a longer window.
122
+ export function stepUpWeaker(before, after) {
123
+ if (STEP_UP_GROUPS.some((group) => before[group] && !after[group])) return true
124
+ if (before.adminIdle && !after.adminIdle) return true
125
+ if (before.cliApproval && !after.cliApproval) return true
126
+ return after.windowMinutes > before.windowMinutes
127
+ }
128
+
129
+ // "5 minutes", "1 hour".
130
+ export const stepUpWindowLabel = (minutes) => (minutes === 60 ? '1 hour' : `${minutes} minutes`)
131
+
132
+ // Which members-and-roles changes are the fixed core (an owner is involved)
133
+ // and which belong to the "members" group (an admin is).
134
+ export const roleChangeTouchesOwner = (targetRole, newRole) => newRole === 'owner' || (targetRole === 'owner' && targetRole !== newRole)
135
+ export const roleChangeTouchesAdmin = (targetRole, newRole) => newRole === 'admin' || (targetRole === 'admin' && targetRole !== newRole)
@@ -0,0 +1,24 @@
1
+ // Tailnet sign-in (`shapewall hosted --tailscale --tailnet-sign-in`): who a
2
+ // request is from. The proof that a request came through Tailscale's serve
3
+ // proxy is shared with the local board and lives in src/tailnet-proof.js
4
+ // (the serve secret, the owner of the connection's other end, tailscaled's
5
+ // own whois, clean headers, and the refusals); read its head for what each
6
+ // part stops and what is still trusted.
7
+ export {
8
+ SECRET_PREFIX,
9
+ TAILNET_LOGIN_RE,
10
+ TAILSCALE_MIN_VERSION,
11
+ cleanTailnetLogin,
12
+ createTailnetGate,
13
+ decodeHeaderValue,
14
+ forwardedTailnetAddress,
15
+ hostFacts,
16
+ newServeSecret,
17
+ parseIdentity,
18
+ peerOwner,
19
+ procAddress,
20
+ procPeerProof,
21
+ serveTarget,
22
+ tailscaledProblem,
23
+ whoisAnswer,
24
+ } from '../tailnet-proof.js'