shapewall 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +267 -0
  2. package/README.md +39 -2
  3. package/THIRD_PARTY.md +15 -0
  4. package/dist/agent/package-lock.json +594 -2
  5. package/dist/client/assets/{BoardChat-DdwBcb2N.js → BoardChat-Bv4UDOjO.js} +1 -1
  6. package/dist/client/assets/{BuzzDialog-DpUcnU6S.js → BuzzDialog-DwEAN6va.js} +1 -1
  7. package/dist/client/assets/{ChecksPanel-CngYV4yz.js → ChecksPanel-C6r_Tc9g.js} +1 -1
  8. package/dist/client/assets/{History-CD0saQA5.js → History-ajFROfWC.js} +1 -1
  9. package/dist/client/assets/{LocalSettings-MZy2baig.js → LocalSettings-BSbmmpbN.js} +1 -1
  10. package/dist/client/assets/{Management-CSvZ-SHO.js → Management-mo8uv2qG.js} +1 -1
  11. package/dist/client/assets/{QuickConnect-foLh2QUm.js → QuickConnect-DlaijESK.js} +1 -1
  12. package/dist/client/assets/{ShareDialog-DPWDftoL.js → ShareDialog-CdLdd6WQ.js} +1 -1
  13. package/dist/client/assets/{app-update-dialog-CtiXpTRD.js → app-update-dialog-BHVNR5Cp.js} +1 -1
  14. package/dist/client/assets/{circle-x-CteRBtXC.js → circle-x-D5MkDLJk.js} +1 -1
  15. package/dist/client/assets/index-B4AoX3ZW.css +2 -0
  16. package/dist/client/assets/index-CQeHY7en.js +37 -0
  17. package/dist/client/assets/{play-BjRNIGSf.js → play--xrZ7VCR.js} +1 -1
  18. package/dist/client/assets/{refresh-cw-r_tZiFfB.js → refresh-cw-B-npxKae.js} +1 -1
  19. package/dist/client/assets/{ui-zQpn-PdL.js → ui-2lMx-4bc.js} +2 -2
  20. package/dist/client/build-info.json +1 -1
  21. package/dist/client/index.html +3 -3
  22. package/dist/client/sw.js +2 -2
  23. package/dist/console/assets/LocalAccountsApp-C1sCag6a.js +1 -0
  24. package/dist/console/assets/LocalConsole-LXQmzRFT.js +2 -0
  25. package/dist/console/assets/LocalUsage-Br3Ddp7_.js +1 -0
  26. package/dist/console/assets/app-update-dialog-CVniDJKA.js +1 -0
  27. package/dist/console/assets/app-version-CTHwlY6g.js +1 -0
  28. package/dist/console/assets/console-CMNNLtFw.js +11 -0
  29. package/dist/console/assets/console-sMMn_Rwc.css +2 -0
  30. package/dist/console/assets/local-agents-DwYJ9cPb.js +6 -0
  31. package/dist/console/assets/minus-887msXez.js +1 -0
  32. package/dist/console/assets/tailnet--wXsG3uh.js +2 -0
  33. package/dist/console/assets/theme-CPfJOmcz.js +1 -0
  34. package/dist/console/assets/ui-DnyJhoQU.js +41 -0
  35. package/dist/console/assets/usage-C5CJHejQ.js +5 -0
  36. package/dist/console/assets/usage-CIPWnHaS.css +1 -0
  37. package/dist/console/assets/usage-DjmUlnXL.js +56 -0
  38. package/dist/console/build-info.json +1 -1
  39. package/dist/console/console.html +8 -2
  40. package/docs/agent-hardening.md +31 -17
  41. package/docs/agents.md +35 -0
  42. package/docs/architecture.md +10 -4
  43. package/docs/deployment.md +39 -17
  44. package/docs/design-system.md +56 -7
  45. package/docs/hosted.md +1004 -43
  46. package/docs/images/board-overview.png +0 -0
  47. package/docs/images/journeys.png +0 -0
  48. package/docs/images/live-comment.png +0 -0
  49. package/docs/images/phone-comment.png +0 -0
  50. package/docs/images/phone-overview.png +0 -0
  51. package/docs/images/variant.png +0 -0
  52. package/docs/where-to-run.md +82 -1
  53. package/package.json +6 -1
  54. package/src/agent/backends/acp.js +224 -26
  55. package/src/agent/routes.js +21 -0
  56. package/src/agent/usage-log.js +251 -0
  57. package/src/cli/args.js +24 -0
  58. package/src/cli/help.js +37 -2
  59. package/src/cli/init.js +2 -1
  60. package/src/cli/serve.js +20 -5
  61. package/src/cli.js +8 -0
  62. package/src/hosted/access-cli.js +99 -1
  63. package/src/hosted/activity-core.js +232 -0
  64. package/src/hosted/activity.js +375 -0
  65. package/src/hosted/admin.js +80 -13
  66. package/src/hosted/agent-approvals.js +2 -2
  67. package/src/hosted/agent-routes.js +3 -3
  68. package/src/hosted/agents.js +11 -4
  69. package/src/hosted/app.js +89 -7
  70. package/src/hosted/auth-routes.js +156 -15
  71. package/src/hosted/auth.js +123 -20
  72. package/src/hosted/board-routes.js +3 -3
  73. package/src/hosted/chat-frames.js +5 -15
  74. package/src/hosted/chat-permissions.js +12 -0
  75. package/src/hosted/chat-routes.js +8 -8
  76. package/src/hosted/chat-store.js +20 -3
  77. package/src/hosted/comment-files.js +5 -2
  78. package/src/hosted/console-routes.js +111 -34
  79. package/src/hosted/db.js +130 -0
  80. package/src/hosted/device-routes.js +25 -3
  81. package/src/hosted/device.js +23 -4
  82. package/src/hosted/guards.js +337 -27
  83. package/src/hosted/http.js +6 -3
  84. package/src/hosted/membership.js +13 -2
  85. package/src/hosted/operator-access.js +418 -0
  86. package/src/hosted/operator.js +106 -2
  87. package/src/hosted/ops-cli.js +238 -3
  88. package/src/hosted/pages.js +2 -0
  89. package/src/hosted/passkey-policy.js +75 -0
  90. package/src/hosted/permissions.js +14 -6
  91. package/src/hosted/presence.js +14 -2
  92. package/src/hosted/projects.js +2 -1
  93. package/src/hosted/public.js +4 -4
  94. package/src/hosted/ratelimit.js +6 -0
  95. package/src/hosted/retention.js +18 -2
  96. package/src/hosted/server.js +123 -11
  97. package/src/hosted/shares.js +2 -2
  98. package/src/hosted/step-up-settings.js +68 -0
  99. package/src/hosted/step-up.js +135 -0
  100. package/src/hosted/tailnet-identity.js +24 -0
  101. package/src/hosted/tailnet-routes.js +342 -0
  102. package/src/hosted/tailnet.js +220 -0
  103. package/src/hosted/tailscale.js +75 -9
  104. package/src/hosted/tenancy.js +48 -1
  105. package/src/hosted/token-api.js +2 -2
  106. package/src/hosted/tokens.js +9 -2
  107. package/src/hosted/usage-core.js +624 -0
  108. package/src/hosted/usage-layout.js +724 -0
  109. package/src/hosted/usage-routes.js +375 -0
  110. package/src/hosted/usage-shape.js +256 -0
  111. package/src/hosted/usage.js +641 -0
  112. package/src/remote/agent-connect.js +37 -1
  113. package/src/remote/agent-link.js +2 -0
  114. package/src/remote/login.js +33 -8
  115. package/src/remote/share.js +1 -1
  116. package/src/remote/tailnet-cli.js +547 -0
  117. package/src/server/app.js +15 -0
  118. package/src/server/pairing-routes.js +34 -5
  119. package/src/server/tailscale.js +97 -4
  120. package/src/tailnet-proof.js +766 -0
  121. package/dist/client/assets/index-Cxz1UVcV.css +0 -2
  122. package/dist/client/assets/index-uUZVBYUS.js +0 -37
  123. package/dist/console/assets/LocalAccountsApp-DIdy1KnN.js +0 -1
  124. package/dist/console/assets/LocalConsole-DfcQztF-.js +0 -1
  125. package/dist/console/assets/app-update-dialog-ttl9lF5A.js +0 -1
  126. package/dist/console/assets/console-OqAjD0kV.js +0 -55
  127. package/dist/console/assets/console-kvjrAArQ.css +0 -2
@@ -15,10 +15,12 @@ import { HttpError, fail, cleanWorkspaceName } from './http.js'
15
15
  import { LIMITS } from './ratelimit.js'
16
16
  import { moveInfo } from './rebind.js'
17
17
  import { removeSetupLink } from './setup-link.js'
18
+ import { mountTailnetAuth } from './tailnet-routes.js'
18
19
  import {
19
20
  accountEvents,
20
21
  auditAccount,
21
22
  deleteAccountEvents,
23
+ deleteSavedViewsOf,
22
24
  findInviteByHash,
23
25
  inviteUsable,
24
26
  lastRecoverySignIn,
@@ -51,20 +53,31 @@ export function mountAuthRoutes(authRouter, deps) {
51
53
  needSession,
52
54
  needFresh,
53
55
  needFreshOrRecovery,
56
+ passkeys,
57
+ needFreshOrHeldRemoval,
58
+ removesHeldPasskey,
59
+ noPasskey,
60
+ needPasskeyBacked,
54
61
  auditOf,
55
62
  publicUser,
56
63
  createWorkspace,
57
64
  acceptInvite,
58
65
  revokeGrantsOf,
59
66
  ownerCount,
67
+ tailnetAccounts,
60
68
  } = deps
61
69
 
70
+ // Tailnet sign-in (src/hosted/tailnet-routes.js); `tailnet.on` false when the server runs without it.
71
+ const tailnet = mountTailnetAuth(authRouter, deps)
72
+
62
73
  // What the sign-up ceremony keeps (in challenges.data) is the SHA-256 of
63
74
  // the invite or setup token, never the token itself.
64
- function signupAllowed({ invite, setup }) {
75
+ function signupAllowed({ invite, setup }, req) {
65
76
  if (typeof invite === 'string' && invite) {
66
77
  const row = findInviteByHash(db, sha256(invite))
67
- if (!inviteUsable(row, iso())) throw new AuthError(403, 'invalid_invite', 'This invite link is used, expired or revoked.')
78
+ // An invite made for a tailnet login is that login's alone.
79
+ if (!inviteUsable(row, iso()) || (row.tailnet_login && row.tailnet_login !== tailnet.identityOf(req)?.login))
80
+ throw new AuthError(403, 'invalid_invite', 'This invite link is used, expired or revoked.')
68
81
  return { inviteHash: sha256(invite) }
69
82
  }
70
83
  if (typeof setup === 'string' && setup) {
@@ -84,6 +97,7 @@ export function mountAuthRoutes(authRouter, deps) {
84
97
  const token = auth.createSession(userId, { ...options, device: deviceLabel(req.headers['user-agent']), ip: clientIp(req) })
85
98
  setCookie(res, SESSION_COOKIE, token, 30 * 86400)
86
99
  setCookie(res, CEREMONY_COOKIE, '', 0)
100
+ if (tailnet.on) tailnet.clearSignedOut(res)
87
101
  return sha256(token)
88
102
  }
89
103
  const ceremonyCookie = (req) => parseCookies(req.headers.cookie)[CEREMONY_COOKIE]
@@ -93,7 +107,14 @@ export function mountAuthRoutes(authRouter, deps) {
93
107
  limit('ceremony'),
94
108
  handle(async (req, res) => {
95
109
  const { handle: name, displayName, invite, setup, workspaceName } = req.body || {}
96
- const allowed = signupAllowed({ invite, setup })
110
+ // "Also sign me in from this tailnet login": asked for on the sign-up
111
+ // page, never assumed. Kept with the ceremony as the login it was said for.
112
+ const wantsLink = req.body?.linkTailnet === true ? tailnet.identityOf(req)?.login || null : null
113
+ if (req.body?.linkTailnet === true && !wantsLink)
114
+ throw new HttpError(403, 'tailnet_required', 'Linking a tailnet login works only when you arrive through the tailnet.')
115
+ if (wantsLink && tailnetAccounts.userFor(wantsLink))
116
+ throw new HttpError(409, 'tailnet_login_taken', 'That tailnet login is linked to another account here.')
117
+ const allowed = signupAllowed({ invite, setup }, req)
97
118
  // Without an invite the account gets a workspace of its own: its name
98
119
  // can be picked now (the setup page asks for it).
99
120
  let ownWorkspace = null
@@ -113,7 +134,7 @@ export function mountAuthRoutes(authRouter, deps) {
113
134
  const { options, ceremony } = await auth.registrationOptions({
114
135
  handle: name,
115
136
  displayName,
116
- data: { ...allowed, ...(ownWorkspace ? { workspaceName: ownWorkspace } : {}) },
137
+ data: { ...allowed, ...(ownWorkspace ? { workspaceName: ownWorkspace } : {}), ...(wantsLink ? { linkTailnet: wantsLink } : {}) },
117
138
  })
118
139
  setCookie(res, CEREMONY_COOKIE, ceremony, 300)
119
140
  res.json({ options })
@@ -127,8 +148,16 @@ export function mountAuthRoutes(authRouter, deps) {
127
148
  limit('ceremony'),
128
149
  handle(async (req, res) => {
129
150
  const ip = clientIp(req)
151
+ // Signing up while arriving through the tailnet links the new account
152
+ // to that login only when the person asked for it on the sign-up page,
153
+ // and the request that finishes the sign-up still arrives as that login.
154
+ const identity = tailnet.identityOf(req)
130
155
  const { user, extra } = await auth.finishSignUp(ceremonyCookie(req), req.body?.response, (created, data) => {
131
156
  let workspaceId
157
+ const linked =
158
+ identity && data.linkTailnet === identity.login ? tailnetAccounts.link(created.id, identity.login, identity.userId) : null
159
+ if (linked)
160
+ auditAccount(db, { userId: created.id, action: 'tailnet_linked', ip, at: iso(), detail: { tailnet: linked, atSignUp: true } })
132
161
  // Ceremonies started before hashes were kept carry the raw token.
133
162
  const inviteHash = data.inviteHash || (data.invite ? sha256(data.invite) : null)
134
163
  const setupHash = data.setupHash || (data.setup ? sha256(data.setup) : null)
@@ -136,7 +165,7 @@ export function mountAuthRoutes(authRouter, deps) {
136
165
  const invite = findInviteByHash(db, inviteHash)
137
166
  if (!inviteUsable(invite, iso())) throw new AuthError(403, 'invalid_invite', 'This invite link is used, expired or revoked.')
138
167
  const t = tenant(db, invite.workspace_id)
139
- acceptInvite(t, invite, created.id, ip)
168
+ acceptInvite(t, invite, created.id, ip, { tailnetLogin: linked })
140
169
  workspaceId = invite.workspace_id
141
170
  } else {
142
171
  if (setupHash) {
@@ -153,7 +182,11 @@ export function mountAuthRoutes(authRouter, deps) {
153
182
  action: 'account_created',
154
183
  ip,
155
184
  at: iso(),
156
- detail: { via: inviteHash ? 'invite' : setupHash ? 'setup' : 'open', device: deviceLabel(req.headers['user-agent']) },
185
+ detail: {
186
+ via: inviteHash ? 'invite' : setupHash ? 'setup' : 'open',
187
+ device: deviceLabel(req.headers['user-agent']),
188
+ ...(linked ? { tailnet: linked } : {}),
189
+ },
157
190
  })
158
191
  return { workspaceId, recoveryCodes: auth.newRecoveryCodes(created.id), setup: Boolean(setupHash) }
159
192
  })
@@ -251,15 +284,30 @@ export function mountAuthRoutes(authRouter, deps) {
251
284
  '/logout',
252
285
  handle(async (req, res) => {
253
286
  const current = sessionOf(req)
254
- if (current) auth.deleteSession(current.session.hash)
287
+ const viaTailnet = current?.session.via === 'tailnet'
288
+ if (current) {
289
+ auth.deleteSession(current.session.hash)
290
+ auditAccount(db, {
291
+ userId: current.user.id,
292
+ action: 'signed_out',
293
+ ip: clientIp(req),
294
+ at: iso(),
295
+ detail: { device: deviceLabel(req.headers['user-agent']), ...(viaTailnet ? { via: 'tailnet' } : {}) },
296
+ })
297
+ }
255
298
  setCookie(res, SESSION_COOKIE, '', 0)
256
- res.json({ ok: true })
299
+ // The tailnet would sign this browser straight back in: it stays
300
+ // signed out until the person presses "Continue as ...".
301
+ if (viaTailnet) tailnet.markSignedOut(res)
302
+ res.json({ ok: true, ...(viaTailnet ? { tailnet: current.session.tailnet_login } : {}) })
257
303
  }),
258
304
  )
259
305
 
260
306
  authRouter.get(
261
307
  '/me',
262
308
  // Signed out is an answer here, not an error (the console asks on every page).
309
+ // A GET makes no session: a linked tailnet login is answered 'linked', and the client signs in with
310
+ // POST /auth/tailnet/sign-in (tailnet-routes.js).
263
311
  (req, res, next) =>
264
312
  sessionOf(req)
265
313
  ? next()
@@ -269,6 +317,9 @@ export function mountAuthRoutes(authRouter, deps) {
269
317
  rpId: siteOf(req).auth.rpId,
270
318
  ...(turnstile && signup === 'open' ? { turnstile: turnstile.siteKey } : {}),
271
319
  ...moveInfo(sites, req),
320
+ ...tailnet.anonInfo(req),
321
+ // Tailscale is the only sign-in here: no passkey is asked for or offered.
322
+ ...(passkeys.on() ? {} : { passkeysOff: true }),
272
323
  }),
273
324
  needSession,
274
325
  handle(async (req, res) => {
@@ -283,7 +334,15 @@ export function mountAuthRoutes(authRouter, deps) {
283
334
  recoveryCodesLeft: auth.recoveryRemaining(req.user.id),
284
335
  fresh: auth.isFresh(req.auth.session),
285
336
  viaRecovery: req.auth.session.via === 'recovery',
337
+ // How this session came in: passkey, recovery or tailnet.
338
+ via: req.auth.session.via,
339
+ ...tailnet.memberInfo(req),
286
340
  securityNotice: securityNoticeFor(req),
341
+ ...(passkeys.on() ? {} : { passkeysOff: true }),
342
+ // Passkeys a tailnet session added that are still on hold: shown on every page ("Not you? Remove it").
343
+ heldPasskeys: auth
344
+ .heldPasskeys(req.user.id, passkeys.holdsAt?.() || null)
345
+ .map((key) => ({ ...key, canRemove: req.auth.session.via === 'tailnet' })),
287
346
  signup,
288
347
  })
289
348
  }),
@@ -374,6 +433,7 @@ export function mountAuthRoutes(authRouter, deps) {
374
433
  revokeGrantsOf(req, user.id, null, { revokeTokens: true, t })
375
434
  }
376
435
  deleteAccountEvents(db, user.id)
436
+ deleteSavedViewsOf(db, user.id)
377
437
  q.run('DELETE FROM users WHERE id = :id', { id: user.id })
378
438
  auditAccount(db, {
379
439
  action: 'account_deleted',
@@ -436,7 +496,7 @@ export function mountAuthRoutes(authRouter, deps) {
436
496
  'This passkey was added with a recovery code; it can confirm this 24 hours after it was added. Use another passkey.',
437
497
  )
438
498
  }
439
- if (req.auth.session.via !== 'passkey') {
499
+ if (req.auth.session.via === 'recovery') {
440
500
  // A recovery session becomes a passkey session once a trusted passkey confirms it.
441
501
  q.run("UPDATE sessions SET via = 'passkey' WHERE token_hash = :hash", { hash: req.auth.session.hash })
442
502
  }
@@ -445,12 +505,49 @@ export function mountAuthRoutes(authRouter, deps) {
445
505
  }),
446
506
  )
447
507
 
508
+ // The first passkey of an account that its tailnet signs in is added with
509
+ // no passkey check. Two conditions on top of the 24 hour hold, both cheap
510
+ // for a person and both honest about what they are:
511
+ // - the request comes from a page of this site in a browser (the fetch
512
+ // metadata a browser sets and a page cannot change), and not from a
513
+ // command line session. A program on the person's device can forge
514
+ // those headers; this is not a barrier against it. It keeps the
515
+ // command line's own tailnet sessions and cross-site requests out.
516
+ // - the person confirmed a step that names the device ("Add a passkey
517
+ // from Chrome on Linux?"): the request carries that name, the server
518
+ // compares it with the device it sees, and the passkey is stored with
519
+ // it, so the notice on the person's other devices can say where the
520
+ // passkey came from.
521
+ // What protects the account is the hold, the notice on every page and
522
+ // "Not you? Remove it" from any of the person's tailnet devices.
523
+ function firstByTailnetOrThrow(req) {
524
+ if (!noPasskey(req)) return null
525
+ const device = deviceLabel(req.headers['user-agent'])
526
+ const inBrowser =
527
+ req.headers['sec-fetch-site'] === 'same-origin' &&
528
+ ['cors', 'same-origin'].includes(req.headers['sec-fetch-mode']) &&
529
+ req.headers['sec-fetch-dest'] === 'empty' &&
530
+ device !== 'Shapewall CLI'
531
+ if (!inBrowser) {
532
+ throw new AuthError(403, 'browser_required', 'A first passkey is added in a browser, on the Account page of this server.')
533
+ }
534
+ if (req.body?.confirmDevice !== device) {
535
+ throw new HttpError(
536
+ 409,
537
+ 'confirm_device',
538
+ 'Confirm adding a passkey from ' + device + '. It is your account’s first passkey: it will be on hold for 24 hours.',
539
+ { device },
540
+ )
541
+ }
542
+ return device
543
+ }
448
544
  authRouter.post(
449
545
  '/passkeys/options',
450
546
  limit('ceremony'),
451
547
  needSession,
452
548
  needFreshOrRecovery,
453
549
  handle(async (req, res) => {
550
+ firstByTailnetOrThrow(req)
454
551
  const { options, ceremony } = await auth.registrationOptions({ userId: req.user.id })
455
552
  setCookie(res, CEREMONY_COOKIE, ceremony, 300)
456
553
  res.json({ options })
@@ -462,9 +559,29 @@ export function mountAuthRoutes(authRouter, deps) {
462
559
  needSession,
463
560
  needFreshOrRecovery,
464
561
  handle(async (req, res) => {
465
- const viaRecovery = !auth.isFresh(req.auth.session)
466
- const { id } = await auth.finishAddPasskey(ceremonyCookie(req), req.body?.response, req.user.id, req.body?.nickname, { viaRecovery })
467
- auditAccount(db, { userId: req.user.id, action: 'passkey_added', ip: clientIp(req), at: iso(), detail: { viaRecovery } })
562
+ // On hold for 24 hours (it signs in at once, it cannot confirm the
563
+ // fixed core until then) when it was added without a passkey check: by
564
+ // a recovery-code session, or as the first passkey of an account that
565
+ // only its tailnet signs in. A tailnet identity is per device: whatever
566
+ // runs as that person on one of their devices could add a passkey of
567
+ // its own, and without the hold use it at once for everything.
568
+ const tailnetFrom = firstByTailnetOrThrow(req)
569
+ const firstByTailnet = Boolean(tailnetFrom)
570
+ const viaRecovery = (req.auth.session.via === 'recovery' || firstByTailnet) && !auth.isFresh(req.auth.session)
571
+ const { id } = await auth.finishAddPasskey(ceremonyCookie(req), req.body?.response, req.user.id, req.body?.nickname, {
572
+ viaRecovery,
573
+ tailnetFrom: firstByTailnet && viaRecovery ? tailnetFrom : null,
574
+ })
575
+ auditAccount(db, {
576
+ userId: req.user.id,
577
+ action: 'passkey_added',
578
+ ip: clientIp(req),
579
+ at: iso(),
580
+ detail: {
581
+ viaRecovery: viaRecovery && !firstByTailnet,
582
+ ...(firstByTailnet ? { viaTailnet: true, onHold: viaRecovery, device: tailnetFrom } : {}),
583
+ },
584
+ })
468
585
  setCookie(res, CEREMONY_COOKIE, '', 0)
469
586
  res.status(201).json({ id, passkeys: auth.listPasskeys(req.user.id) })
470
587
  }),
@@ -480,8 +597,32 @@ export function mountAuthRoutes(authRouter, deps) {
480
597
  authRouter.delete(
481
598
  '/passkeys/:id',
482
599
  needSession,
483
- needFresh,
600
+ needFreshOrHeldRemoval,
484
601
  handle(async (req, res) => {
602
+ // "Not you? Remove it": a tailnet session takes away a passkey that a
603
+ // tailnet session added and that is still on hold (guards.js).
604
+ if (!auth.isFresh(req.auth.session) && removesHeldPasskey(req, req.params.id)) {
605
+ const key = auth.removeHeldPasskey(req.user.id, req.params.id, passkeys.holdsAt?.() || null)
606
+ auth.deleteOtherSessions(req.user.id, req.auth.session.hash)
607
+ auditAccount(db, {
608
+ userId: req.user.id,
609
+ action: 'passkey_removed',
610
+ ip: clientIp(req),
611
+ at: iso(),
612
+ detail: {
613
+ otherSessionsEnded: true,
614
+ onHold: true,
615
+ via: 'tailnet',
616
+ device: deviceLabel(req.headers['user-agent']),
617
+ addedFrom: key.tailnet_added_from,
618
+ addedAt: key.created_at,
619
+ },
620
+ })
621
+ return res.json({
622
+ passkeys: auth.listPasskeys(req.user.id),
623
+ heldPasskeys: auth.heldPasskeys(req.user.id, passkeys.holdsAt?.() || null),
624
+ })
625
+ }
485
626
  auth.removePasskey(req.user.id, req.params.id)
486
627
  // A session signed in with that passkey must not outlive it.
487
628
  auth.deleteOtherSessions(req.user.id, req.auth.session.hash)
@@ -508,7 +649,7 @@ export function mountAuthRoutes(authRouter, deps) {
508
649
  authRouter.post(
509
650
  '/sessions/revoke-others',
510
651
  needSession,
511
- needFresh,
652
+ needPasskeyBacked,
512
653
  handle(async (req, res) => {
513
654
  auth.deleteOtherSessions(req.user.id, req.auth.session.hash)
514
655
  auditAccount(db, { userId: req.user.id, action: 'sessions_revoked', ip: clientIp(req), at: iso(), detail: {} })
@@ -526,7 +667,7 @@ export function mountAuthRoutes(authRouter, deps) {
526
667
  authRouter.delete(
527
668
  '/sessions/:id',
528
669
  needSession,
529
- needFresh,
670
+ needPasskeyBacked,
530
671
  handle(async (req, res) => {
531
672
  const id = String(req.params.id)
532
673
  if (!SESSION_ID_RE.test(id)) throw new AuthError(404, 'unknown_session', 'No such session.')
@@ -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,
@@ -44,7 +44,7 @@ export function mountBoardRoutes(
44
44
  inWorkspace,
45
45
  inProject,
46
46
  handle,
47
- freshOrThrow,
47
+ stepUpOrThrow,
48
48
  auditOf,
49
49
  clientIp,
50
50
  policyFor,
@@ -166,7 +166,7 @@ export function mountBoardRoutes(
166
166
  const current = ctx.comments.get(req.params.cid)
167
167
  if (approve) {
168
168
  if (!roleAtLeast(req.role, 'admin')) throw new HttpError(403, 'forbidden', 'Only trusted admins approve runs.')
169
- freshOrThrow(req)
169
+ stepUpOrThrow(req, 'cards')
170
170
  }
171
171
  const agents = agentsFor(req.t)
172
172
  const going = agents.addressOf(req.project.id, current)
@@ -232,7 +232,7 @@ export function mountBoardRoutes(
232
232
  quotas,
233
233
  workspaceQuota,
234
234
  policyFor,
235
- freshOrThrow,
235
+ stepUpOrThrow,
236
236
  now,
237
237
  })
238
238
  : null
@@ -6,6 +6,8 @@
6
6
  // board renders only what its own components expect. Pure: no database, no
7
7
  // request.
8
8
 
9
+ import { usageRecordOf } from './usage-shape.js'
10
+
9
11
  export const FRAME_LIMITS = {
10
12
  // One POST of events.
11
13
  batchBytes: 256 * 1024,
@@ -239,18 +241,6 @@ export function cleanReply(message) {
239
241
  }
240
242
 
241
243
  // What the usage record keeps of an answer (src/hosted/chat-store.js
242
- // endRun): how it ended and the numbers the agent reported. Never text.
243
- export function usageOf(reply) {
244
- const find = (category) => reply.options?.find((item) => item.category === category)?.value || null
245
- return {
246
- // A fix that left a branch is "fix_ready".
247
- outcome: reply.status === 'done' ? (reply.summary ? 'fix_ready' : 'answered') : reply.status === 'stopped' ? 'stopped' : 'failed',
248
- model: find('model') || reply.model || null,
249
- effort: find('thought_level'),
250
- inputTokens: reply.usage?.input ?? null,
251
- outputTokens: reply.usage?.output ?? null,
252
- cachedTokens: reply.usage?.cached ?? null,
253
- costMicros: reply.usage?.costMicros ?? null,
254
- steps: reply.cards.filter((card) => card.kind === 'tool').length,
255
- }
256
- }
244
+ // endTurn): how it ended and the numbers the agent reported. Never text.
245
+ // The rule itself is shared with the local board: usage-shape.js.
246
+ export const usageOf = usageRecordOf