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
@@ -11,12 +11,33 @@ import { suspendedWrite } from './operator.js'
11
11
  import { ProjectError, createProjectStore } from './projects.js'
12
12
  import { PushError } from './push.js'
13
13
  import { LIMITS } from './ratelimit.js'
14
- import { TenancyError, audit, roleAtLeast, roleIn, tenant } from './tenancy.js'
14
+ import { TenancyError, audit, roleAtLeast, roleIn, tenant, workspacesForUser } from './tenancy.js'
15
15
  import { CommentError } from '../store.js'
16
+ import { FIXED_CORE, STEP_UP_GROUP_BEFORE, stepUpWindowLabel } from './step-up.js'
17
+ import { stepUpSettings } from './step-up-settings.js'
18
+ import { sessionReader } from './tailnet.js'
19
+ import { PASSKEYS_OFF_MESSAGE, isPasskeyRoute } from './passkey-policy.js'
16
20
 
17
21
  const ACTIVE_EVERY_MS = 5 * 60_000
18
22
 
19
- export function createGuards({ db, dataDir, auth, quotas, secure, trustProxy, rateLimiter, siteOf, SESSION_COOKIE, iso, now, log }) {
23
+ export function createGuards({
24
+ db,
25
+ dataDir,
26
+ auth,
27
+ quotas,
28
+ secure,
29
+ trustProxy,
30
+ rateLimiter,
31
+ siteOf,
32
+ SESSION_COOKIE,
33
+ iso,
34
+ now,
35
+ log,
36
+ // Tailnet sign-in ({ identityOf(req) }, src/hosted/tailnet-identity.js), or null.
37
+ tailnet = null,
38
+ // Whether passkeys exist on this server ({ on() }, src/hosted/passkey-policy.js).
39
+ passkeys = { on: () => true },
40
+ }) {
20
41
  const clientIp = (req) => (trustProxy ? req.ip : req.socket.remoteAddress) || 'unknown'
21
42
  const setCookie = (res, name, value, maxAgeSeconds) => {
22
43
  res.append('Set-Cookie', `${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${secure ? '; Secure' : ''}`)
@@ -31,12 +52,91 @@ export function createGuards({ db, dataDir, auth, quotas, secure, trustProxy, ra
31
52
  }
32
53
 
33
54
  // ---- Sessions ----
55
+ // A session that came in by tailnet identity counts only on a request that
56
+ // carries that identity (src/hosted/tailnet.js sessionReader).
57
+ const readSession = sessionReader({ auth, tailnet, passkeys })
34
58
  function sessionOf(req) {
35
59
  if (req.sessionChecked) return req.auth
36
60
  req.sessionChecked = true
37
- req.auth = auth.readSession(parseCookies(req.headers.cookie)[SESSION_COOKIE]) || null
61
+ req.auth = readSession(req, parseCookies(req.headers.cookie)[SESSION_COOKIE]) || null
62
+ // With passkeys off (a tailnet sign-in server, the default there) only the tailnet signs anyone in:
63
+ // a session a passkey or a recovery code started, from before they were switched off, does not count.
64
+ if (req.auth && req.auth.session.via !== 'tailnet' && !passkeys.on()) req.auth = null
38
65
  return req.auth
39
66
  }
67
+ // Passkey routes on a server where passkeys are off: a clear answer, before anything else looks at them.
68
+ // One of them stays open: taking away a passkey that a tailnet session added and that is still on hold
69
+ // ("Not you? Remove it", shown on every page). The person must be able to do that whatever the switch says.
70
+ const HELD_REMOVAL = /^\/auth\/passkeys\/([^/]+)\/?$/i
71
+ const passkeysGate = (req, res, next) => {
72
+ if (!isPasskeyRoute(req.path) || passkeys.on()) return next()
73
+ const removal = req.method === 'DELETE' ? HELD_REMOVAL.exec(req.path) : null
74
+ if (removal && sessionOf(req)) {
75
+ let id = ''
76
+ try {
77
+ id = decodeURIComponent(removal[1])
78
+ } catch {
79
+ id = ''
80
+ }
81
+ if (removesHeldPasskey(req, id)) return next()
82
+ }
83
+ return fail(res, 403, 'passkeys_off', PASSKEYS_OFF_MESSAGE)
84
+ }
85
+ // ---- The fixed core without passkeys: a typed confirmation ----
86
+ //
87
+ // On a tailnet sign-in server with passkeys off, a session is a proven
88
+ // tailnet identity and there is nothing stronger to ask for. The tailnet
89
+ // is the trust boundary: anything running as the person on one of their
90
+ // tailnet devices can act as them, and no prompt here changes that. What
91
+ // the fixed core still gives is deliberateness: the request must name what
92
+ // it is about, typed by the person (the console's dialog) or passed with
93
+ // --yes on the command line. The name is the workspace's for something in
94
+ // a workspace, the account's handle otherwise; the request carries it in
95
+ // X-Shapewall-Confirm (URI-encoded). Stateless: every such request says it.
96
+ const tailnetOnly = (req) => req.auth.session.via === 'tailnet' && !passkeys.on()
97
+ const CONFIRM_HEADER = 'x-shapewall-confirm'
98
+ function confirmRefusal(req, workspaceId = null) {
99
+ const ws = workspaceId || req.t?.workspaceId || null
100
+ const name = ws ? tenant(db, ws).get('SELECT name FROM workspaces WHERE workspace_id = :ws')?.name : null
101
+ // A name says which workspace only while it is the person's only one of that name. With two "Team"s the
102
+ // name would confirm either, so the request must say this workspace's id, and the prompt says so.
103
+ const sameName = name ? workspacesForUser(db, req.auth.user.id).filter((item) => item.name.trim() === name.trim()).length > 1 : false
104
+ if (sameName) {
105
+ let saidId = ''
106
+ try {
107
+ saidId = decodeURIComponent(String(req.headers[CONFIRM_HEADER] || '')).trim()
108
+ } catch {
109
+ saidId = ''
110
+ }
111
+ if (saidId === ws) return null
112
+ return new HttpError(
113
+ 403,
114
+ 'confirm_required',
115
+ 'You are in more than one workspace named ' +
116
+ name +
117
+ '. Type the id of this one, ' +
118
+ ws +
119
+ ', to confirm. Shapewall always asks before this.',
120
+ { stepUp: 'always', confirm: ws, confirms: 'workspace-id', workspace: name },
121
+ )
122
+ }
123
+ const phrase = name || req.auth.user.handle
124
+ let said = ''
125
+ try {
126
+ said = decodeURIComponent(String(req.headers[CONFIRM_HEADER] || '')).trim()
127
+ } catch {
128
+ said = ''
129
+ }
130
+ if (said && said === String(phrase).trim()) return null
131
+ return new HttpError(
132
+ 403,
133
+ 'confirm_required',
134
+ name
135
+ ? 'Type the workspace’s name, ' + phrase + ', to confirm. Shapewall always asks before this.'
136
+ : 'Type your handle, ' + phrase + ', to confirm. Shapewall always asks before this.',
137
+ { stepUp: 'always', confirm: phrase, confirms: name ? 'workspace' : 'account' },
138
+ )
139
+ }
40
140
 
41
141
  // Cookie-authenticated writes: JSON only, from this origin.
42
142
  function sameOrigin(req) {
@@ -52,27 +152,219 @@ export function createGuards({ db, dataDir, auth, quotas, secure, trustProxy, ra
52
152
  next()
53
153
  }
54
154
 
155
+ // Responses of tailnet sessions that are still open (a live stream): cut
156
+ // when the identity can no longer be believed, or its login is unlinked.
157
+ const tailnetOpen = new Set()
158
+ function cutTailnetSessions(userId = null) {
159
+ for (const res of [...tailnetOpen]) {
160
+ if (userId && res.req?.auth?.user?.id !== userId) continue
161
+ tailnetOpen.delete(res)
162
+ res.destroy()
163
+ }
164
+ }
55
165
  const needSession = (req, res, next) => {
56
166
  if (!sessionOf(req)) return fail(res, 401, 'signed_out', 'Sign in first.')
57
167
  req.user = req.auth.user
168
+ if (req.auth.session.via === 'tailnet' && !tailnetOpen.has(res)) {
169
+ tailnetOpen.add(res)
170
+ res.once('close', () => tailnetOpen.delete(res))
171
+ }
58
172
  next()
59
173
  }
60
- const needFresh = (req, res, next) => {
61
- if (!auth.isFresh(req.auth.session)) {
62
- return fail(
63
- res,
174
+ // ---- Asking for the passkey again (src/hosted/step-up.js) ----
175
+ //
176
+ // notFresh(req, windowMs, message, extra): the refusal to send when the
177
+ // session has no passkey check in the window, or null. An account that
178
+ // signs in by its tailnet identity and has no passkey cannot give one: it
179
+ // is told to add a passkey first (`passkey_required`), never let through.
180
+ const noPasskey = (req) => req.auth.session.via === 'tailnet' && auth.passkeyCount(req.auth.user.id) === 0
181
+ function notFresh(req, windowMs, message, extra) {
182
+ // No passkeys on this server: the fixed core asks for a typed confirmation, and nothing else asks
183
+ // (a workspace's "Ask for a passkey again" groups have nothing to ask for; the card is not shown).
184
+ if (tailnetOnly(req)) return extra?.stepUp === 'always' ? confirmRefusal(req, extra.workspaceId) : null
185
+ if (auth.isFresh(req.auth.session, windowMs)) return null
186
+ if (noPasskey(req)) {
187
+ const lead = extra.stepUp === 'always' ? 'This always needs a passkey' : 'This needs a passkey here'
188
+ return new HttpError(
64
189
  403,
65
- 'reauth_required',
66
- `Confirm with your passkey first (needed every ${Math.round(REAUTH_MS / 60000)} minutes for this).`,
190
+ 'passkey_required',
191
+ lead + ', and your account has none: your tailnet signs you in. Add a passkey in Account and security, then try again.',
192
+ extra,
67
193
  )
68
194
  }
69
- next()
195
+ return new HttpError(403, 'reauth_required', message, extra)
196
+ }
197
+ const CORE_MINUTES = Math.round(REAUTH_MS / 60000)
198
+ // The fixed core: always, on every server.
199
+ // workspaceId: the workspace the request is about, when the route has not said yet (the table's middleware).
200
+ const coreRefusal = (req, workspaceId = null) =>
201
+ notFresh(
202
+ req,
203
+ REAUTH_MS,
204
+ 'Confirm with your passkey first. Shapewall always asks before this (once every ' + CORE_MINUTES + ' minutes).',
205
+ { stepUp: 'always', ...(workspaceId ? { workspaceId } : {}) },
206
+ )
207
+ // Recovery-code sessions, and sessions of a passkey still on hold, keep
208
+ // the strict rules for everything that ever asked for a passkey.
209
+ const restrictedRefusal = (req) =>
210
+ auth.restricted(req.auth.session)
211
+ ? notFresh(
212
+ req,
213
+ REAUTH_MS,
214
+ 'Confirm with your passkey first: this session started with a recovery code, or with a passkey that was added with one in the last 24 hours.',
215
+ { stepUp: 'restricted' },
216
+ )
217
+ : null
218
+ // A workspace's own choice: only when its owner switched the group on.
219
+ function groupRefusal(req, group, t = req.t) {
220
+ const restricted = restrictedRefusal(req)
221
+ if (restricted) return restricted
222
+ const settings = stepUpSettings(t).get()
223
+ if (!settings[group]) return null
224
+ return notFresh(
225
+ req,
226
+ settings.windowMinutes * 60_000,
227
+ 'This workspace asks for your passkey again before ' +
228
+ STEP_UP_GROUP_BEFORE[group] +
229
+ ' (once every ' +
230
+ stepUpWindowLabel(settings.windowMinutes) +
231
+ '). An owner sets this in Settings, "Ask for a passkey again".',
232
+ { stepUp: group, windowMinutes: settings.windowMinutes },
233
+ )
70
234
  }
71
- const needFreshOrRecovery = (req, res, next) => (auth.canAddAfterRecovery(req.auth.session) ? next() : needFresh(req, res, next))
72
- const freshOrThrow = (req) => {
73
- if (!auth.isFresh(req.auth.session))
74
- throw new HttpError(403, 'reauth_required', 'Confirm with your passkey first (needed for owner changes).')
235
+ const refuse = (res, error) => fail(res, error.statusCode, error.code, error.message, error.extra)
236
+ const asMiddleware = (refusalOf) => (req, res, next) => {
237
+ const error = refusalOf(req)
238
+ return error ? refuse(res, error) : next()
75
239
  }
240
+ const asThrow =
241
+ (refusalOf) =>
242
+ (req, ...rest) => {
243
+ const error = refusalOf(req, ...rest)
244
+ if (error) throw error
245
+ }
246
+ const needFresh = asMiddleware(coreRefusal)
247
+ const coreFreshOrThrow = asThrow(coreRefusal)
248
+ // "Approve command line logins in the browser" (a workspace's switch,
249
+ // cliApproval). What it covers, exactly: while it is on, a session that
250
+ // only a tailnet identity stands behind (a tailnet session with no passkey
251
+ // check in the last 10 minutes; such an identity is per device, so anything
252
+ // running as the person on a tailnet device of theirs has it) may not
253
+ // 1. approve a waiting command line login or agent (device-routes.js),
254
+ // 2. make an API token on a project's page (console-routes.js),
255
+ // 3. invite an admin, or make a member an admin (console-routes.js): an
256
+ // admin's own session could then do 1 and 2. Owners are the fixed
257
+ // core's, always.
258
+ // Each alone would be no barrier, which is why they go together. What it
259
+ // does not cover: everything else that session's role allows in the
260
+ // workspace (projects, comments, members and viewers, settings that ask
261
+ // for more), and tokens and agents that exist already. Decided from the
262
+ // session; nothing a client sends changes it.
263
+ const identityOnly = (req) => req.auth.session.via === 'tailnet' && !auth.isFresh(req.auth.session)
264
+ const cliApprovalOrThrow = (req, t, message) => {
265
+ if (identityOnly(req) && stepUpSettings(t).get().cliApproval) {
266
+ const error = notFresh(req, REAUTH_MS, message, { stepUp: 'cliApproval' })
267
+ if (error) throw error
268
+ }
269
+ return identityOnly(req)
270
+ }
271
+ // Returns whether only an identity stands behind the session (for the audit entry).
272
+ const machineTokensOrThrow = (req, t = req.t) =>
273
+ cliApprovalOrThrow(
274
+ req,
275
+ t,
276
+ 'This workspace makes tokens for machines and agents only with a passkey, in the browser (Settings, "Approve command line logins in the browser"). Confirm with your passkey.',
277
+ )
278
+ const adminMakingOrThrow = (req, t = req.t) =>
279
+ cliApprovalOrThrow(
280
+ req,
281
+ t,
282
+ 'This workspace invites and makes admins only with a passkey (Settings, "Approve command line logins in the browser": an admin can make tokens). Confirm with your passkey.',
283
+ )
284
+ // A passkey check in the last 10 minutes for a rule of its own: passkeyOrThrow(req, message, { stepUp }).
285
+ const passkeyOrThrow = asThrow((req, message, extra) => notFresh(req, REAUTH_MS, message, extra))
286
+ // After inWorkspace (req.t): stepUp('tokens').
287
+ const stepUp = (group) => asMiddleware((req) => groupRefusal(req, group))
288
+ // stepUpOrThrow(req, 'cards'), or with a tenant handle the route made itself.
289
+ const stepUpOrThrow = asThrow(groupRefusal)
290
+ // Account routes outside the core that a restricted session still may not use.
291
+ const needUnrestricted = asMiddleware(restrictedRefusal)
292
+ // Ending my other sessions (one, or all the others). Not part of the fixed
293
+ // core, but not free either: whoever merely holds a session must not be
294
+ // able to sign the real person out everywhere unchallenged. The rule: this
295
+ // session itself passed a passkey check at some point (at sign-in, or
296
+ // since), or the account has no passkey at all, so that this session is
297
+ // as strong as the account gets (its tailnet signs it in). A tailnet
298
+ // session of an account that has a passkey confirms with it first.
299
+ const needPasskeyBacked = asMiddleware((req) => {
300
+ // No passkeys on this server: the tailnet identity is the account, also when a passkey from before the
301
+ // switch is still stored. It could not be asked for, so it is not.
302
+ if (tailnetOnly(req)) return null
303
+ const restricted = restrictedRefusal(req)
304
+ if (restricted) return restricted
305
+ if (auth.passedPasskey(req.auth.session) || noPasskey(req)) return null
306
+ return new HttpError(
307
+ 403,
308
+ 'reauth_required',
309
+ 'Confirm with your passkey first: this session was signed in by your tailnet, and ending your other sessions needs your passkey once.',
310
+ {
311
+ stepUp: 'sessions',
312
+ },
313
+ )
314
+ })
315
+
316
+ // The fixed core's table (src/hosted/step-up.js FIXED_CORE), enforced in
317
+ // one place for every request, before its route.
318
+ const coreLines = FIXED_CORE.filter((line) => line.method && line.path).map((line) => ({
319
+ ...line,
320
+ // As Express matches its routes: any letter case, an optional trailing slash.
321
+ pattern: new RegExp(`^${line.path.replace(/:[a-z]+/g, '([^/]+)')}/?$`, 'i'),
322
+ params: [...line.path.matchAll(/:([a-z]+)/g)].map((match) => match[1]),
323
+ }))
324
+ // A parameter as Express hands it to the route: decoded (a malformed one matches nothing).
325
+ const param = (match, line, name) => {
326
+ try {
327
+ return decodeURIComponent(match[1 + line.params.indexOf(name)] || '')
328
+ } catch {
329
+ return ''
330
+ }
331
+ }
332
+ // "Not you? Remove it." The first passkey of an account that its tailnet
333
+ // signs in is added with no passkey check (there is none to check with),
334
+ // so whatever runs as the person on one of their tailnet devices can add
335
+ // one. The person must be able to take it away again from any of their
336
+ // devices, and a passkey check cannot be the condition: the only passkey
337
+ // is the one in question, and it is on hold. So while such a passkey is on
338
+ // hold, a tailnet session of the same account (the same proven identity
339
+ // that could add it) may remove it. That gives the identity nothing it did
340
+ // not have: the account ends as it was before the passkey.
341
+ function removesHeldPasskey(req, id) {
342
+ return req.auth.session.via === 'tailnet' && auth.isHeldByTailnet(req.auth.user.id, String(id || ''), passkeys.holdsAt?.() || null)
343
+ }
344
+ const needFreshOrHeldRemoval = (req, res, next) => (removesHeldPasskey(req, req.params.id) ? next() : needFresh(req, res, next))
345
+ const fixedCore = (req, res, next) => {
346
+ for (const line of coreLines) {
347
+ if (line.method !== req.method) continue
348
+ const match = line.pattern.exec(req.path)
349
+ if (!match || !sessionOf(req)) continue
350
+ if (line.role) {
351
+ const ws = param(match, line, 'ws')
352
+ const role = ID_PATTERNS.workspace.test(ws) ? roleIn(db, req.auth.user.id, ws) : null
353
+ // Not theirs to do: the route says so (404 or 403), as for anyone.
354
+ if (!role || !roleAtLeast(role, line.role)) continue
355
+ }
356
+ if (line.first && (auth.canAddAfterRecovery(req.auth.session) || noPasskey(req))) continue
357
+ if (line.held && removesHeldPasskey(req, param(match, line, 'id'))) continue
358
+ const error = coreRefusal(req, line.params.includes('ws') ? param(match, line, 'ws') : null)
359
+ if (error) return refuse(res, error)
360
+ }
361
+ next()
362
+ }
363
+ // Adding a passkey: a fresh check, or shortly after a recovery sign-in, or
364
+ // the first passkey of an account that signs in by its tailnet identity
365
+ // (it has nothing stronger to be checked with yet).
366
+ const needFreshOrRecovery = (req, res, next) =>
367
+ auth.canAddAfterRecovery(req.auth.session) || noPasskey(req) ? next() : needFresh(req, res, next)
76
368
  // :ws must be a workspace the user is in, with at least `role`. Unknown
77
369
  // and foreign workspaces answer the same 404.
78
370
  const inWorkspace =
@@ -82,19 +374,22 @@ export function createGuards({ db, dataDir, auth, quotas, secure, trustProxy, ra
82
374
  const current = ID_PATTERNS.workspace.test(ws) ? roleIn(db, req.user.id, ws) : null
83
375
  if (!current) return fail(res, 404, 'unknown_workspace', 'No such workspace.')
84
376
  if (!roleAtLeast(current, role)) return fail(res, 403, 'forbidden', `This needs the ${role} role or higher.`)
85
- // Admin pages idle-expire: 12 hours without one, a passkey check
86
- // brings them back (the rest of the session keeps working).
87
- if (roleAtLeast(role, 'admin')) {
88
- if (auth.adminIdleExpired(req.auth.session))
89
- return fail(
90
- res,
91
- 403,
92
- 'reauth_required',
93
- 'You have been away from admin pages for 12 hours. Confirm with your passkey to continue.',
377
+ req.t = tenant(db, ws)
378
+ // Admin pages idle-expire when the workspace's owner asked for it
379
+ // (Settings, "Ask for a passkey again"): 12 hours without one, a
380
+ // passkey check brings them back (the rest of the session keeps working).
381
+ if (roleAtLeast(role, 'admin') && stepUpSettings(req.t).get().adminIdle) {
382
+ if (auth.adminIdleExpired(req.auth.session)) {
383
+ const error = notFresh(
384
+ req,
385
+ REAUTH_MS,
386
+ 'You have been away from admin pages for 12 hours, and this workspace asks for your passkey after that (Settings, "Ask for a passkey again"). Confirm with your passkey to continue.',
387
+ { stepUp: 'adminIdle' },
94
388
  )
389
+ if (error) return refuse(res, error)
390
+ }
95
391
  auth.touchAdmin(req.auth.session)
96
392
  }
97
- req.t = tenant(db, ws)
98
393
  // Suspended by the operator: read-only (export still works).
99
394
  const suspended = suspendedWrite(req, req.t)
100
395
  if (suspended) return fail(res, 403, 'workspace_suspended', suspended)
@@ -122,7 +417,7 @@ export function createGuards({ db, dataDir, auth, quotas, secure, trustProxy, ra
122
417
  error instanceof HttpError ||
123
418
  error instanceof AgentPolicyError
124
419
  ) {
125
- return fail(res, error.statusCode, error.code, error.message)
420
+ return fail(res, error.statusCode, error.code, error.message, error.extra || null)
126
421
  }
127
422
  if (!(error instanceof TenancyError)) log(`error: ${error.name || 'Error'} (request failed; request values omitted)`)
128
423
  else log(`tenancy error: ${error.message}`)
@@ -138,7 +433,8 @@ export function createGuards({ db, dataDir, auth, quotas, secure, trustProxy, ra
138
433
  action,
139
434
  target,
140
435
  ip: clientIp(req),
141
- detail,
436
+ // What a person did in a session their tailnet signed in says so.
437
+ detail: req.auth?.session?.via === 'tailnet' && req.user ? { ...detail, signedInBy: 'tailnet' } : detail,
142
438
  at: iso(),
143
439
  })
144
440
 
@@ -162,7 +458,21 @@ export function createGuards({ db, dataDir, auth, quotas, secure, trustProxy, ra
162
458
  needSession,
163
459
  needFresh,
164
460
  needFreshOrRecovery,
165
- freshOrThrow,
461
+ passkeysGate,
462
+ tailnetOnly,
463
+ needFreshOrHeldRemoval,
464
+ removesHeldPasskey,
465
+ noPasskey,
466
+ needUnrestricted,
467
+ needPasskeyBacked,
468
+ fixedCore,
469
+ cutTailnetSessions,
470
+ passkeyOrThrow,
471
+ machineTokensOrThrow,
472
+ adminMakingOrThrow,
473
+ coreFreshOrThrow,
474
+ stepUp,
475
+ stepUpOrThrow,
166
476
  inWorkspace,
167
477
  inProject,
168
478
  handle,
@@ -1,16 +1,19 @@
1
1
  // Small HTTP and input helpers shared by the hosted app's routes
2
2
  // (src/hosted/app.js and the modules it mounts).
3
3
 
4
+ // `extra`: more fields for the error object the client reads (a refusal that
5
+ // asks for a passkey says which rule asked: { stepUp }).
4
6
  export class HttpError extends Error {
5
- constructor(status, code, message) {
7
+ constructor(status, code, message, extra = null) {
6
8
  super(message)
7
9
  this.statusCode = status
8
10
  this.code = code
11
+ this.extra = extra
9
12
  }
10
13
  }
11
14
 
12
- export function fail(res, status, code, message) {
13
- res.status(status).json({ error: { code, message } })
15
+ export function fail(res, status, code, message, extra = null) {
16
+ res.status(status).json({ error: { ...(extra || {}), code, message } })
14
17
  }
15
18
 
16
19
  // A share link visitor as the board names them: "Ada (guest)", or just
@@ -13,7 +13,7 @@ import { audit, inviteUsable, tenant, workspacesForUser } from './tenancy.js'
13
13
 
14
14
  const WORKSPACES_PER_USER = 10
15
15
 
16
- export function createMembership({ db, quotas, iso, auditOf }) {
16
+ export function createMembership({ db, quotas, iso, auditOf, agentsFor = null }) {
17
17
  function publicUser(user) {
18
18
  return { id: user.id, handle: user.handle, displayName: user.display_name, avatarUrl: avatarUrl(db, user.id) }
19
19
  }
@@ -40,8 +40,12 @@ export function createMembership({ db, quotas, iso, auditOf }) {
40
40
  return id
41
41
  }
42
42
 
43
- function acceptInvite(t, invite, userId, ip) {
43
+ // `tailnetLogin`: the tailnet login the accepting account is linked to and
44
+ // arrives with. An invite made for a login is that login's alone.
45
+ function acceptInvite(t, invite, userId, ip, { tailnetLogin = null } = {}) {
44
46
  return transaction(db, () => {
47
+ if (invite.tailnet_login && invite.tailnet_login !== tailnetLogin)
48
+ throw new AuthError(403, 'invalid_invite', 'This invite link is used, expired or revoked.')
45
49
  if (t.get('SELECT role FROM memberships WHERE workspace_id = :ws AND user_id = :user', { user: userId })) {
46
50
  throw new HttpError(409, 'already_member', 'You are already in this workspace.')
47
51
  }
@@ -66,7 +70,14 @@ export function createMembership({ db, quotas, iso, auditOf }) {
66
70
  role: invite.role,
67
71
  at: iso(),
68
72
  })
69
- audit(t, { userId, action: 'invite_accepted', target: invite.id, ip, at: iso(), detail: { role: invite.role } })
73
+ audit(t, {
74
+ userId,
75
+ action: 'invite_accepted',
76
+ target: invite.id,
77
+ ip,
78
+ at: iso(),
79
+ detail: { role: invite.role, ...(invite.tailnet_login ? { tailnet: invite.tailnet_login } : {}) },
80
+ })
70
81
  })
71
82
  }
72
83
 
@@ -102,6 +113,14 @@ export function createMembership({ db, quotas, iso, auditOf }) {
102
113
  }).changes
103
114
  : 0
104
115
  if (invites || shares || tokens) auditOf(req, 'member_grants_revoked', userId, { invites, shares, tokens }, t)
116
+ // A revoked token that was an agent lets go of what it held and what
117
+ // waited for it (src/hosted/agents.js releaseGone).
118
+ if (tokens && agentsFor) {
119
+ const agents = agentsFor(t)
120
+ agents.forget()
121
+ for (const project of t.all('SELECT id FROM projects WHERE workspace_id = :ws'))
122
+ agents.releaseGone(project.id, (action, target, detail) => auditOf(req, action, target, detail, t))
123
+ }
105
124
  return { invites, shares, tokens }
106
125
  }
107
126