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
@@ -65,6 +65,8 @@ export function cleanDisplayName(value) {
65
65
  export function deviceLabel(userAgent) {
66
66
  const ua = String(userAgent || '').slice(0, 512)
67
67
  if (!ua) return null
68
+ // The command line, signed in by tailnet identity (src/remote/tailnet-cli.js).
69
+ if (/^shapewall-cli\b/.test(ua)) return 'Shapewall CLI'
68
70
  const browser = /Edg\//.test(ua)
69
71
  ? 'Edge'
70
72
  : /OPR\//.test(ua)
@@ -203,13 +205,13 @@ export function createAuth({ db, origin, rpId, rpName = 'Shapewall', now = () =>
203
205
  return { row, info }
204
206
  }
205
207
 
206
- function storePasskey(userId, info, nickname = '', { viaRecovery = false } = {}) {
208
+ function storePasskey(userId, info, nickname = '', { viaRecovery = false, tailnetFrom = null } = {}) {
207
209
  if (q.get('SELECT id FROM passkeys WHERE id = :id', { id: info.credential.id })) {
208
210
  throw new AuthError(409, 'passkey_exists', 'That passkey is already registered.')
209
211
  }
210
212
  q.run(
211
- `INSERT INTO passkeys (id, user_id, public_key, counter, transports, device_type, backed_up, nickname, created_at, recovery_added_at, rp_id)
212
- VALUES (:id, :user, :key, :counter, :transports, :device, :backed, :nickname, :at, :recovery, :rp)`,
213
+ `INSERT INTO passkeys (id, user_id, public_key, counter, transports, device_type, backed_up, nickname, created_at, recovery_added_at, rp_id, tailnet_added_from)
214
+ VALUES (:id, :user, :key, :counter, :transports, :device, :backed, :nickname, :at, :recovery, :rp, :tailnet)`,
213
215
  {
214
216
  id: info.credential.id,
215
217
  user: userId,
@@ -222,6 +224,7 @@ export function createAuth({ db, origin, rpId, rpName = 'Shapewall', now = () =>
222
224
  at: iso(),
223
225
  recovery: viaRecovery ? iso() : null,
224
226
  rp: rpId,
227
+ tailnet: tailnetFrom ? String(tailnetFrom).slice(0, 80) : null,
225
228
  },
226
229
  )
227
230
  }
@@ -253,13 +256,13 @@ export function createAuth({ db, origin, rpId, rpName = 'Shapewall', now = () =>
253
256
  // no session yet). `check(row)` runs in the same transaction before the
254
257
  // passkey is stored and may return { viaRecovery } (a rebind consumes its
255
258
  // token there, so a token is used at most once).
256
- async function finishAddPasskey(ceremony, response, userId, nickname, { viaRecovery = false, check = null } = {}) {
259
+ async function finishAddPasskey(ceremony, response, userId, nickname, { viaRecovery = false, tailnetFrom = null, check = null } = {}) {
257
260
  const { row, info } = await verifyRegistration(ceremony, response)
258
261
  if (!row.user_id || (userId !== null && row.user_id !== userId))
259
262
  throw new AuthError(400, 'no_ceremony', 'Start again: the sign-in request expired.')
260
263
  transaction(db, () => {
261
264
  const extra = check ? check(row) || {} : {}
262
- storePasskey(row.user_id, info, nickname, { viaRecovery: extra.viaRecovery ?? viaRecovery })
265
+ storePasskey(row.user_id, info, nickname, { viaRecovery: extra.viaRecovery ?? viaRecovery, tailnetFrom })
263
266
  })
264
267
  return { id: info.credential.id, userId: row.user_id, data: row.data }
265
268
  }
@@ -320,7 +323,23 @@ export function createAuth({ db, origin, rpId, rpName = 'Shapewall', now = () =>
320
323
  return { ...user, trusted: !onHold(key), passkeyId: key.id }
321
324
  }
322
325
 
323
- const onHold = (key) => Boolean(key.recovery_added_at) && now().getTime() - Date.parse(key.recovery_added_at) < RECOVERY_HOLD_MS
326
+ // `at`: the moment to judge the hold at (now, unless passkeys are off on this server and holds stand still).
327
+ const onHold = (key, at = null) =>
328
+ Boolean(key.recovery_added_at) && (at || now()).getTime() - Date.parse(key.recovery_added_at) < RECOVERY_HOLD_MS
329
+ // On hold, and added by a tailnet session with no passkey check (the first
330
+ // passkey of an account its tailnet signs in). Until the hold ends, any
331
+ // tailnet session of the account may take it away again (removeHeldPasskey).
332
+ const heldByTailnet = (key, at = null) => Boolean(key.tailnet_added_from) && onHold(key, at)
333
+ const heldPasskeys = (userId, at = null) =>
334
+ passkeysOf(userId)
335
+ .filter((key) => heldByTailnet(key, at))
336
+ .map((key) => ({
337
+ id: key.id,
338
+ nickname: key.nickname,
339
+ addedAt: key.created_at,
340
+ device: key.tailnet_added_from,
341
+ onHoldUntil: new Date(Date.parse(key.recovery_added_at) + RECOVERY_HOLD_MS).toISOString(),
342
+ }))
324
343
 
325
344
  // ---- Passkey management ----
326
345
 
@@ -368,6 +387,44 @@ export function createAuth({ db, origin, rpId, rpName = 'Shapewall', now = () =>
368
387
  })
369
388
  }
370
389
 
390
+ // "Not you? Remove it": a passkey that a tailnet session added, taken away
391
+ // while it is still on hold. Unlike removePasskey this needs no passkey
392
+ // check and no recovery codes, and may leave the account with no passkey:
393
+ // the account is back where it was before the passkey (its tailnet signs
394
+ // it in), and nothing else could remove a passkey that somebody else on one
395
+ // of the person's devices made. Every other passkey still on hold starts
396
+ // its 24 hours again: someone objected, so nothing added around then is
397
+ // trusted sooner. Returns the removed passkey's row.
398
+ function removeHeldPasskey(userId, id, at = null) {
399
+ return transaction(db, () => {
400
+ const key = passkeysOf(userId).find((item) => item.id === id)
401
+ if (!key) throw new AuthError(404, 'unknown_passkey', 'No such passkey.')
402
+ if (!heldByTailnet(key, at))
403
+ throw new AuthError(409, 'passkey_not_held', 'That passkey is no longer on hold. Removing it needs a passkey check.')
404
+ q.run('DELETE FROM passkeys WHERE id = :id AND user_id = :user', { id, user: userId })
405
+ q.run(
406
+ 'UPDATE passkeys SET recovery_added_at = :at WHERE user_id = :user AND recovery_added_at IS NOT NULL AND recovery_added_at > :since',
407
+ {
408
+ at: iso(),
409
+ user: userId,
410
+ since: iso(-RECOVERY_HOLD_MS),
411
+ },
412
+ )
413
+ return key
414
+ })
415
+ }
416
+
417
+ // The operator's way (shapewall hosted admin passkeys): any passkey, also
418
+ // the last one, with no rule about recovery codes. Returns the row or null.
419
+ function removePasskeyAsOperator(userId, id) {
420
+ return transaction(db, () => {
421
+ const key = passkeysOf(userId).find((item) => item.id === id)
422
+ if (!key) return null
423
+ q.run('DELETE FROM passkeys WHERE id = :id AND user_id = :user', { id, user: userId })
424
+ return key
425
+ })
426
+ }
427
+
371
428
  // ---- Recovery codes ----
372
429
 
373
430
  function newRecoveryCodes(userId) {
@@ -410,22 +467,32 @@ export function createAuth({ db, origin, rpId, rpName = 'Shapewall', now = () =>
410
467
 
411
468
  // ---- Sessions ----
412
469
 
413
- // `verified`: the sign-in counts as a fresh passkey check. `via`: passkey
414
- // or recovery (a recovery session is never fresh). `device` is a short
415
- // label from the User-Agent ("Chrome on macOS"), never the raw header.
416
- function createSession(userId, { verified = true, via = 'passkey', device = null, ip = null } = {}) {
470
+ // `verified`: the sign-in counts as a fresh passkey check. `via`: passkey,
471
+ // recovery (a recovery session is never fresh) or tailnet (`tailnetLogin`:
472
+ // the tailnet identity the session came in with; never fresh until a
473
+ // passkey confirms it). `device` is a short label from the User-Agent
474
+ // ("Chrome on macOS"), never the raw header.
475
+ //
476
+ // A tailnet session is stored with via 'passkey' and its login in
477
+ // tailnet_login (the column's CHECK predates it, and a build before tailnet
478
+ // sign-in then reads it as a session that never passed a passkey check).
479
+ function createSession(userId, { verified = true, via = 'passkey', device = null, ip = null, tailnetLogin = null } = {}) {
417
480
  const token = randomToken(32)
481
+ if (via === 'tailnet' && !tailnetLogin) throw new Error('a tailnet session needs its login')
482
+ if (via === 'tailnet') via = 'passkey'
483
+ else tailnetLogin = null
418
484
  q.run(
419
- `INSERT INTO sessions (token_hash, id, user_id, created_at, last_seen_at, expires_at, verified_at, via, user_agent, ip)
420
- VALUES (:hash, :id, :user, :at, :at, :expires, :verified, :via, :device, :ip)`,
485
+ `INSERT INTO sessions (token_hash, id, user_id, created_at, last_seen_at, expires_at, verified_at, via, user_agent, ip, tailnet_login)
486
+ VALUES (:hash, :id, :user, :at, :at, :expires, :verified, :via, :device, :ip, :tailnet)`,
421
487
  {
422
- hash: sha256(token),
488
+ hash: sessionHash(token, tailnetLogin),
423
489
  id: newId('se'),
424
490
  user: userId,
425
491
  at: iso(),
426
492
  expires: iso(SESSION_DAYS * DAY),
427
- verified: verified && via === 'passkey' ? iso() : NEVER_VERIFIED,
493
+ verified: verified && via === 'passkey' && !tailnetLogin ? iso() : NEVER_VERIFIED,
428
494
  via,
495
+ tailnet: tailnetLogin,
429
496
  device: device ? String(device).slice(0, 80) : null,
430
497
  ip: ip ? String(ip).slice(0, 64) : null,
431
498
  },
@@ -433,6 +500,15 @@ export function createAuth({ db, origin, rpId, rpName = 'Shapewall', now = () =>
433
500
  return token
434
501
  }
435
502
 
503
+ // A tailnet session is stored under the hash of "tailnet:<token>", not of
504
+ // the token: a build from before tailnet sign-in looks a cookie up by the
505
+ // hash of the token alone (readSession there), finds nothing, and so can
506
+ // never use such a session as an ordinary one after a downgrade.
507
+ const sessionHash = (token, tailnetLogin) => sha256(tailnetLogin ? `tailnet:${token}` : token)
508
+
509
+ // How a session came in, as the API and the audit log say it.
510
+ const viaOf = (row) => (row.tailnet_login ? 'tailnet' : row.via)
511
+
436
512
  // The account's live sessions for the Account page: ids, never hashes.
437
513
  function listSessions(userId, currentHash) {
438
514
  return q
@@ -444,7 +520,7 @@ export function createAuth({ db, origin, rpId, rpName = 'Shapewall', now = () =>
444
520
  createdAt: row.created_at,
445
521
  lastSeenAt: row.last_seen_at,
446
522
  expiresAt: row.expires_at,
447
- via: row.via,
523
+ via: viaOf(row),
448
524
  device: row.user_agent || null,
449
525
  ip: row.ip || null,
450
526
  }))
@@ -462,8 +538,14 @@ export function createAuth({ db, origin, rpId, rpName = 'Shapewall', now = () =>
462
538
  // at most once an hour).
463
539
  function readSession(token) {
464
540
  if (typeof token !== 'string' || token.length < 20 || token.length > 100) return null
465
- const hash = sha256(token)
466
- const session = q.get('SELECT * FROM sessions WHERE token_hash = :hash', { hash })
541
+ // An ordinary session by the token's hash; a tailnet session by its own
542
+ // (never the other way round: the login column must agree with the hash).
543
+ let hash = sha256(token)
544
+ let session = q.get('SELECT * FROM sessions WHERE token_hash = :hash AND tailnet_login IS NULL', { hash })
545
+ if (!session) {
546
+ hash = sessionHash(token, true)
547
+ session = q.get('SELECT * FROM sessions WHERE token_hash = :hash AND tailnet_login IS NOT NULL', { hash })
548
+ }
467
549
  if (!session) return null
468
550
  if (session.expires_at <= iso() || Date.parse(session.created_at) + SESSION_MAX_DAYS * DAY <= now().getTime()) {
469
551
  q.run('DELETE FROM sessions WHERE token_hash = :hash', { hash })
@@ -479,7 +561,7 @@ export function createAuth({ db, origin, rpId, rpName = 'Shapewall', now = () =>
479
561
  hash,
480
562
  })
481
563
  }
482
- return { user, session: { ...session, hash } }
564
+ return { user, session: { ...session, via: viaOf(session), hash } }
483
565
  }
484
566
 
485
567
  const markVerified = (sessionHash) =>
@@ -488,7 +570,7 @@ export function createAuth({ db, origin, rpId, rpName = 'Shapewall', now = () =>
488
570
  // sign-in itself) more than ADMIN_IDLE_MS ago.
489
571
  const lastAdminSeen = (session) =>
490
572
  Math.max(
491
- ...[session.admin_seen_at, session.via === 'passkey' ? session.verified_at : null, session.created_at]
573
+ ...[session.admin_seen_at, session.via !== 'recovery' ? session.verified_at : null, session.created_at]
492
574
  .filter(Boolean)
493
575
  .map((value) => Date.parse(value)),
494
576
  )
@@ -498,7 +580,20 @@ export function createAuth({ db, origin, rpId, rpName = 'Shapewall', now = () =>
498
580
  if (now().getTime() - lastAdminSeen(session) < 60_000) return
499
581
  q.run('UPDATE sessions SET admin_seen_at = :at WHERE token_hash = :hash', { at: iso(), hash: session.hash })
500
582
  }
501
- const isFresh = (session) => session.via === 'passkey' && now().getTime() - Date.parse(session.verified_at) <= REAUTH_MS
583
+ // A passkey check in the last `windowMs` (10 minutes for the fixed core; a
584
+ // workspace's own window for the groups it switched on). A tailnet session
585
+ // is fresh once a passkey of the account confirmed it.
586
+ const isFresh = (session, windowMs = REAUTH_MS) =>
587
+ session.via !== 'recovery' && now().getTime() - Date.parse(session.verified_at) <= windowMs
588
+ // Sessions that keep the strict rules whatever a workspace chose: one that
589
+ // started with a recovery code, and one a passkey started that could not
590
+ // confirm sensitive actions then (added with a recovery code in the last 24
591
+ // hours) and that no trusted passkey has confirmed since.
592
+ const restricted = (session) => session.via === 'recovery' || (session.via === 'passkey' && session.verified_at === NEVER_VERIFIED)
593
+ // Whether this session itself ever passed a passkey check (at sign-in or since).
594
+ const passedPasskey = (session) => session.via !== 'recovery' && session.verified_at !== NEVER_VERIFIED
595
+ const deleteTailnetSessions = (userId) =>
596
+ q.run('DELETE FROM sessions WHERE user_id = :user AND tailnet_login IS NOT NULL', { user: userId })
502
597
  // A recovery session may add a passkey for a short while after signing in.
503
598
  const canAddAfterRecovery = (session) => session.via === 'recovery' && now().getTime() - Date.parse(session.created_at) <= RECOVERY_ADD_MS
504
599
  const deleteSession = (sessionHash) => q.run('DELETE FROM sessions WHERE token_hash = :hash', { hash: sessionHash })
@@ -514,6 +609,10 @@ export function createAuth({ db, origin, rpId, rpName = 'Shapewall', now = () =>
514
609
  listPasskeys,
515
610
  renamePasskey,
516
611
  removePasskey,
612
+ removeHeldPasskey,
613
+ removePasskeyAsOperator,
614
+ heldPasskeys,
615
+ isHeldByTailnet: (userId, id, at = null) => passkeysOf(userId).some((key) => key.id === id && heldByTailnet(key, at)),
517
616
  newRecoveryCodes,
518
617
  recoveryRemaining,
519
618
  useRecoveryCode,
@@ -525,6 +624,10 @@ export function createAuth({ db, origin, rpId, rpName = 'Shapewall', now = () =>
525
624
  adminIdleExpired,
526
625
  touchAdmin,
527
626
  isFresh,
627
+ restricted,
628
+ passedPasskey,
629
+ deleteTailnetSessions,
630
+ passkeyCount: (userId) => passkeysOf(userId).length,
528
631
  canAddAfterRecovery,
529
632
  deleteSession,
530
633
  deleteOtherSessions,
@@ -13,6 +13,7 @@ import { avatarUrl } from '../accounts/avatar.js'
13
13
  import { checksView, readReport } from '../checks/store.js'
14
14
  import { agentPolicy } from './agent-policy.js'
15
15
  import { hostedBoardView, sendPng } from './board-context.js'
16
+ import { mountChatRoutes } from './chat-routes.js'
16
17
  import { guestView, rowToComment } from './comments.js'
17
18
  import { transaction } from './db.js'
18
19
  import { publicView } from './guest-view.js'
@@ -43,10 +44,11 @@ export function mountBoardRoutes(
43
44
  inWorkspace,
44
45
  inProject,
45
46
  handle,
46
- freshOrThrow,
47
+ stepUpOrThrow,
47
48
  auditOf,
48
49
  clientIp,
49
50
  policyFor,
51
+ agentsFor,
50
52
  dispatchView,
51
53
  boardContext,
52
54
  // Cleans comment images off the event loop (src/hosted/cleaner.js).
@@ -56,6 +58,11 @@ export function mountBoardRoutes(
56
58
  workspaceQuota = undefined,
57
59
  // What readGuest needs (the shared deps of src/hosted/app.js).
58
60
  deps,
61
+ // Chat with connected agents (src/hosted/chat-routes.js): members only.
62
+ chatFor = null,
63
+ hub = null,
64
+ links = null,
65
+ chat = null,
59
66
  },
60
67
  ) {
61
68
  // ---- Usercontent: live HTML through signed URLs ----
@@ -76,7 +83,8 @@ export function mountBoardRoutes(
76
83
  // New comments and replies may carry images (base64, 4 of 5 MB): their
77
84
  // body is read after the session and role checks, with its own limit
78
85
  // (mediaBody); every other route keeps 64 kB.
79
- const MEDIA_POST_RE = /^\/boards\/[^/]+\/comments(?:\/[^/]+\/replies)?\/?$/
86
+ // A chat message to a connected agent has its own limit too (chat-routes.js).
87
+ const MEDIA_POST_RE = /^\/(?:boards\/[^/]+\/comments(?:\/[^/]+\/replies)?|agent\/boards\/[^/]+\/threads\/[^/]+\/messages)\/?$/
80
88
  const skipMedia = (parser) => (req, res, next) =>
81
89
  req.method === 'POST' && MEDIA_POST_RE.test(req.path) ? next() : parser(req, res, next)
82
90
  boardApi.use(skipMedia(express.json({ limit: '64kb' })))
@@ -110,11 +118,45 @@ export function mountBoardRoutes(
110
118
  }),
111
119
  )
112
120
 
121
+ // The project's agents as this person may see and use them, for the
122
+ // board's Agent panel and "Send to agent": names, faces, states, what each
123
+ // holds on this board, and whether this person may send it work (with the
124
+ // reason when not). Members and viewers only: this router is never
125
+ // mounted for a share link's guests or a public project's visitors. No
126
+ // token ids, prefixes or scopes, and no account ids.
127
+ boardApi.get(
128
+ '/boards/:bid/agents',
129
+ handle((req, res) => {
130
+ const ctx = boardContext(req.t, req.project, req.params.bid)
131
+ // Reading the list is also where an agent that is gone lets go of its
132
+ // work, and where a token from an older build is first seen.
133
+ const audit = (action, target, detail) => auditOf(req, action, target, detail)
134
+ res.json(
135
+ transaction(db, () =>
136
+ agentsFor(req.t).boardList(req.project.id, { userId: req.user.id, role: req.role }, { boardId: ctx.board.id, audit }),
137
+ ),
138
+ )
139
+ }),
140
+ )
141
+ const actorOf = (req) => ({
142
+ userId: req.user.id,
143
+ role: req.role,
144
+ audit: (action, target, detail) => auditOf(req, action, target, detail),
145
+ })
146
+
147
+ // Sends a comment to an agent. `agentId` names one agent of the project
148
+ // (the sender must be in its audience), null means any agent, and without
149
+ // it the project's default agent is used when the sender may use it (any
150
+ // agent otherwise). An admin's approval of a run someone else asked for
151
+ // keeps where that comment was going.
113
152
  boardApi.post(
114
153
  '/boards/:bid/comments/:cid/send-to-agent',
115
154
  handle((req, res) => {
116
155
  const ctx = boardContext(req.t, req.project, req.params.bid)
117
156
  const approve = req.body?.approve === true
157
+ const named = Object.hasOwn(req.body || {}, 'agentId')
158
+ if (named && req.body.agentId !== null && typeof req.body.agentId !== 'string')
159
+ throw new HttpError(400, 'invalid_agent', 'agentId: an agent id, or null for any agent.')
118
160
  // The vouch covers the text its sender saw: the body carries the
119
161
  // comment's dispatchHash (from the board API), compared with the row
120
162
  // in the transaction that writes the vouch. Edited meanwhile: 409
@@ -124,16 +166,77 @@ export function mountBoardRoutes(
124
166
  const current = ctx.comments.get(req.params.cid)
125
167
  if (approve) {
126
168
  if (!roleAtLeast(req.role, 'admin')) throw new HttpError(403, 'forbidden', 'Only trusted admins approve runs.')
127
- freshOrThrow(req)
169
+ stepUpOrThrow(req, 'cards')
170
+ }
171
+ const agents = agentsFor(req.t)
172
+ const going = agents.addressOf(req.project.id, current)
173
+ const wanted = named ? req.body.agentId : approve && current.dispatch_hash ? going : undefined
174
+ // Work an agent already took stays with it, and so does the approval
175
+ // it was taken under: sending it again changes nothing (not who
176
+ // vouched for it, not where it goes), and sending it elsewhere is
177
+ // refused. Without a named agent (an older board) it is "again".
178
+ if (['queued', 'working'].includes(current.agent_status)) {
179
+ if (!roleAtLeast(req.role, 'member') || !agents.trusted(req.project.id, ctx.board.id, req.user.id))
180
+ throw new HttpError(403, 'untrusted_member', 'Only a trusted member may send work to an agent.')
181
+ if (named && wanted !== going) throw new HttpError(409, 'agent_working', 'An agent is already working on this comment.')
182
+ return current
128
183
  }
129
184
  policyFor(req.t).vouch(req.project.id, ctx.board.id, current, req.user.id, { role: req.role, approve, expect })
130
- auditOf(req, 'comment_vouched', `${ctx.board.id}#${current.number}`, { project: req.project.id, approve })
185
+ // After the vouch (which refuses people the agent policy does not
186
+ // trust): the audience of the agent it is sent to, checked for the
187
+ // sender, and for the admin who approves someone else's run.
188
+ const agent = agents.address(req.project.id, ctx.board.id, current, { userId: req.user.id, role: req.role }, wanted)
189
+ auditOf(req, 'comment_vouched', `${ctx.board.id}#${current.number}`, { project: req.project.id, approve, agent })
131
190
  return current
132
191
  })
133
192
  res.json({ comment: dispatchView(req.t, req.project.id, ctx.board.id, rowToComment(ctx.comments.get(row.number))) })
134
193
  }),
135
194
  )
136
195
 
196
+ // "Let any agent take it": a comment that waits for one agent (it is
197
+ // offline, say) goes to whichever agent takes it first. For the people who
198
+ // may send comments to an agent here; not once an agent has taken it.
199
+ boardApi.post(
200
+ '/boards/:bid/comments/:cid/release-agent',
201
+ handle((req, res) => {
202
+ const ctx = boardContext(req.t, req.project, req.params.bid)
203
+ const agents = agentsFor(req.t)
204
+ transaction(db, () => {
205
+ const current = ctx.comments.get(req.params.cid)
206
+ if (!roleAtLeast(req.role, 'member') || !agents.trusted(req.project.id, ctx.board.id, req.user.id))
207
+ throw new HttpError(403, 'untrusted_member', 'Only a trusted member may send work to an agent.')
208
+ if (['queued', 'working'].includes(current.agent_status))
209
+ throw new HttpError(409, 'agent_working', 'An agent is already working on this comment.')
210
+ agents.release(actorOf(req), req.project.id, ctx.board.id, current)
211
+ })
212
+ res.json({ comment: dispatchView(req.t, req.project.id, ctx.board.id, rowToComment(ctx.comments.get(req.params.cid))) })
213
+ }),
214
+ )
215
+
216
+ // Chat with the project's connected agents: on the members' API only.
217
+ // A share link's guests and a public project's visitors have no such
218
+ // routes at all (their routers below never mount them).
219
+ const chatApi =
220
+ chatFor && hub && links && chat
221
+ ? mountChatRoutes(boardApi, {
222
+ db,
223
+ handle,
224
+ auditOf,
225
+ agentsFor,
226
+ chatFor,
227
+ hub,
228
+ links,
229
+ chat,
230
+ boardContext,
231
+ rateLimiter,
232
+ quotas,
233
+ workspaceQuota,
234
+ policyFor,
235
+ stepUpOrThrow,
236
+ now,
237
+ })
238
+ : null
239
+
137
240
  const shareApi = express.Router({ mergeParams: true })
138
241
  shareApi.use((req, res, next) => {
139
242
  res.setHeader('Cache-Control', 'no-store')
@@ -302,6 +405,16 @@ export function mountBoardRoutes(
302
405
  app.use('/s/:sid/api', shareApi)
303
406
  app.use('/p/:pubid/api', publicApi)
304
407
 
408
+ function hostedAgentInfo(req) {
409
+ try {
410
+ const found = chatApi.chatAgents(req, null)
411
+ if (!found.agents.length) return {}
412
+ return { agent: chatApi.agentInfo(chatApi.defaultOf(found)) }
413
+ } catch {
414
+ return {}
415
+ }
416
+ }
417
+
305
418
  function boardRoutes(router) {
306
419
  router.get('/info', (req, res) =>
307
420
  res.json({
@@ -317,6 +430,10 @@ export function mountBoardRoutes(
317
430
  consoleUrl: `/w/${req.t.workspaceId}`,
318
431
  // The board header's way back to the project's page in the console.
319
432
  project: { id: req.project.id, name: req.project.name, url: `/w/${req.t.workspaceId}/projects/${req.project.id}` },
433
+ // Chat with a connected agent: for members and up, once an agent
434
+ // that chats is connected to the project (online or not). Never for
435
+ // a share link's guest or a public visitor (their /info is their own).
436
+ ...(router === boardApi && chatApi && roleAtLeast(req.role, 'member') ? hostedAgentInfo(req) : {}),
320
437
  }),
321
438
  )
322
439
 
@@ -436,7 +553,14 @@ export function mountBoardRoutes(
436
553
  const comment = transaction(db, () => {
437
554
  checkStorageQuota(req.t, imageBytes(media), quotaOf(req))
438
555
  const made = ctx.comments.create(ctx.config, ctx.board, req.body, authorOf(req), now(), media)
439
- if (!req.guest) policyFor(req.t).autoVouch(req.project.id, ctx.board.id, ctx.comments.get(made.id), req.user.id, req.role)
556
+ if (!req.guest) {
557
+ policyFor(req.t).autoVouch(req.project.id, ctx.board.id, ctx.comments.get(made.id), req.user.id, req.role)
558
+ // Vouched for as it was written: it goes to the project's default
559
+ // agent when its author may use that agent, to any agent otherwise.
560
+ const vouched = ctx.comments.get(made.id)
561
+ if (vouched.dispatch_hash)
562
+ agentsFor(req.t).address(req.project.id, ctx.board.id, vouched, { userId: req.user.id, role: req.role }, undefined)
563
+ }
440
564
  if (req.guest) auditOf(req, 'guest_commented', `${ctx.board.id}#${made.id}`, { project: req.project.id, guest: req.guest.name })
441
565
  return made
442
566
  })