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,19 +11,14 @@ import { transaction } from './db.js'
11
11
  import { mountDeviceApprovals } from './device-routes.js'
12
12
  import { HttpError, fail, cleanInviteNote, cleanName, cleanWorkspaceName } from './http.js'
13
13
  import { cleanEmail } from './mail.js'
14
- import {
15
- NEEDS,
16
- canInvite,
17
- canManage,
18
- canRemoveMember,
19
- inviteNeedsFresh,
20
- leavesNoOwner,
21
- removalNeedsFresh,
22
- roleChangeNeedsFresh,
23
- } from './permissions.js'
14
+ import { NEEDS, canInvite, canManage, canRemoveMember, leavesNoOwner } from './permissions.js'
15
+ import { roleChangeTouchesAdmin, roleChangeTouchesOwner } from './step-up.js'
16
+ import { stepUpSettings } from './step-up-settings.js'
17
+ import { cleanTailnetLogin } from './tailnet-identity.js'
24
18
  import { projectPublic } from './public.js'
25
19
  import { LIMITS } from './ratelimit.js'
26
20
  import { SHARE_DAYS } from './shares.js'
21
+ import { createViews } from './usage.js'
27
22
  import { ROLES, findInviteByHash, inviteUsable, roleAtLeast, roleIn, tenant, workspacesForUser } from './tenancy.js'
28
23
 
29
24
  export const INVITE_DAYS = [1, 3, 7, 14, 30]
@@ -33,7 +28,9 @@ const DAY = 86_400_000
33
28
 
34
29
  // Invite links: preview needs no session, accepting one does.
35
30
  export function mountInviteLinks(consoleApi, deps) {
36
- const { db, iso, limit, handle, sessionOf, needSession, clientIp, acceptInvite } = deps
31
+ const { db, iso, limit, handle, sessionOf, needSession, clientIp, acceptInvite, tailnet = null } = deps
32
+ // The tailnet login a request arrives with (an invite can be for one login only).
33
+ const arrivesAs = (req) => (tailnet ? tailnet.identityOf(req)?.login || null : null)
37
34
 
38
35
  // Invite preview needs no session (the link is the secret). Invite and
39
36
  // setup links carry their token in the URL fragment, which browsers never
@@ -56,7 +53,9 @@ export function mountInviteLinks(consoleApi, deps) {
56
53
  usable: inviteUsable(invite, iso()),
57
54
  })
58
55
  }
59
- if (!inviteUsable(invite, iso())) return fail(res, 404, 'invalid_invite', 'This invite link is used, expired or revoked.')
56
+ // An invite made for a tailnet login reads as invalid to everyone else.
57
+ if (!inviteUsable(invite, iso()) || (invite.tailnet_login && invite.tailnet_login !== arrivesAs(req)))
58
+ return fail(res, 404, 'invalid_invite', 'This invite link is used, expired or revoked.')
60
59
  res.json({ workspace: { name: invite.workspace_name }, role: invite.role, expiresAt: invite.expires_at })
61
60
  }),
62
61
  )
@@ -67,7 +66,11 @@ export function mountInviteLinks(consoleApi, deps) {
67
66
  handle(async (req, res) => {
68
67
  const invite = typeof req.body?.token === 'string' ? findInviteByHash(db, sha256(req.body.token)) : null
69
68
  if (!invite) throw new AuthError(403, 'invalid_invite', 'This invite link is used, expired or revoked.')
70
- acceptInvite(tenant(db, invite.workspace_id), invite, req.user.id, clientIp(req))
69
+ // The account must be the one linked to the login it arrives with.
70
+ const login = arrivesAs(req)
71
+ acceptInvite(tenant(db, invite.workspace_id), invite, req.user.id, clientIp(req), {
72
+ tailnetLogin: login && req.user.tailnet_login === login ? login : null,
73
+ })
71
74
  res.json({ workspaceId: invite.workspace_id })
72
75
  }),
73
76
  )
@@ -88,14 +91,32 @@ export function mountConsoleRoutes(consoleApi, deps) {
88
91
  handle,
89
92
  inWorkspace,
90
93
  inProject,
91
- needFresh,
92
- freshOrThrow,
94
+ coreFreshOrThrow,
95
+ machineTokensOrThrow,
96
+ adminMakingOrThrow,
97
+ stepUp,
98
+ stepUpOrThrow,
93
99
  auditOf,
94
100
  createWorkspace,
95
101
  revokeGrantsOf,
96
102
  ownerCount,
97
103
  createApiToken,
104
+ agentsFor,
105
+ tailnet = null,
106
+ tailnetAccounts = null,
107
+ passkeys = null,
98
108
  } = deps
109
+ // Making, changing or removing an owner always asks for the passkey; the
110
+ // same for an admin when the workspace asks for it ("Members and roles").
111
+ // makesAdmin: the request gives someone the admin role (an invite, or a
112
+ // change of role). With "Approve command line logins in the browser" on,
113
+ // a session that only a tailnet identity stands behind may not: the new
114
+ // admin could make the tokens that switch keeps from it (guards.js).
115
+ const roleStepUp = (req, { owner, admin, makesAdmin = false }) => {
116
+ if (owner) coreFreshOrThrow(req)
117
+ else if (admin) stepUpOrThrow(req, 'members')
118
+ if (makesAdmin && !owner) adminMakingOrThrow(req)
119
+ }
99
120
 
100
121
  consoleApi.get(
101
122
  '/workspaces',
@@ -119,6 +140,7 @@ export function mountConsoleRoutes(consoleApi, deps) {
119
140
  const workspace = t.get(
120
141
  'SELECT id, name, created_at, share_links, public_projects, suspended_at, suspended_reason FROM workspaces WHERE workspace_id = :ws',
121
142
  )
143
+ const stepUpNow = stepUpSettings(t).get()
122
144
  const members = t
123
145
  .all(
124
146
  `SELECT m.user_id, m.role, m.created_at, m.last_active_at, u.handle, u.display_name FROM memberships m JOIN users u ON u.id = m.user_id
@@ -139,17 +161,29 @@ export function mountConsoleRoutes(consoleApi, deps) {
139
161
  const invites = roleAtLeast(req.role, NEEDS.invites)
140
162
  ? t
141
163
  .all(
142
- 'SELECT id, role, created_at, expires_at, note FROM invites WHERE workspace_id = :ws AND used_at IS NULL AND revoked_at IS NULL AND expires_at > :now ORDER BY created_at DESC',
164
+ 'SELECT id, role, created_at, expires_at, note, tailnet_login FROM invites WHERE workspace_id = :ws AND used_at IS NULL AND revoked_at IS NULL AND expires_at > :now ORDER BY created_at DESC',
143
165
  { now: iso() },
144
166
  )
145
- .map((row) => ({ id: row.id, role: row.role, createdAt: row.created_at, expiresAt: row.expires_at, note: row.note || null }))
167
+ .map((row) => ({
168
+ id: row.id,
169
+ role: row.role,
170
+ createdAt: row.created_at,
171
+ expiresAt: row.expires_at,
172
+ note: row.note || null,
173
+ tailnetLogin: row.tailnet_login || null,
174
+ }))
146
175
  : []
147
176
  res.json({
148
177
  workspace: {
149
178
  id: workspace.id,
150
179
  name: workspace.name,
151
180
  createdAt: workspace.created_at,
152
- settings: { shareLinks: Boolean(workspace.share_links), publicProjects: Boolean(workspace.public_projects) },
181
+ settings: {
182
+ shareLinks: Boolean(workspace.share_links),
183
+ publicProjects: Boolean(workspace.public_projects),
184
+ // When this workspace asks for the passkey again (src/hosted/step-up.js).
185
+ stepUp: stepUpNow,
186
+ },
153
187
  // Set by the server operator (shapewall hosted admin suspend).
154
188
  suspended: workspace.suspended_at ? { at: workspace.suspended_at, reason: workspace.suspended_reason || null } : null,
155
189
  },
@@ -159,7 +193,17 @@ export function mountConsoleRoutes(consoleApi, deps) {
159
193
  projects,
160
194
  invites,
161
195
  // What the console can offer: invite emails only when the server can send them.
162
- features: { inviteEmail: inviteEmailOn, inviteDays: INVITE_DAYS, shareDays: SHARE_DAYS, publicProjects: true, guestSessions: true },
196
+ features: {
197
+ inviteEmail: inviteEmailOn,
198
+ inviteDays: INVITE_DAYS,
199
+ shareDays: SHARE_DAYS,
200
+ publicProjects: true,
201
+ guestSessions: true,
202
+ // Invites for a tailnet login, and the list of tailnet visitors.
203
+ tailnetSignIn: Boolean(tailnet),
204
+ // false: Tailscale is the only sign-in here (no passkeys, so nothing in "Ask for a passkey again" applies).
205
+ passkeys: passkeys ? passkeys.on() : true,
206
+ },
163
207
  })
164
208
  }),
165
209
  )
@@ -182,8 +226,7 @@ export function mountConsoleRoutes(consoleApi, deps) {
182
226
  handle(async (req, res) => {
183
227
  const role = req.body?.role
184
228
  if (!ROLES.includes(role)) throw new HttpError(400, 'invalid_role', `Role: ${ROLES.join(', ')}.`)
185
- // Granting admin or owner needs a recent passkey check.
186
- if (inviteNeedsFresh(role)) freshOrThrow(req)
229
+ roleStepUp(req, { owner: role === 'owner', admin: role === 'admin', makesAdmin: role === 'admin' })
187
230
  let revoked = { invites: 0, shares: 0, tokens: 0 }
188
231
  transaction(db, () => {
189
232
  const target = req.t.get('SELECT role FROM memberships WHERE workspace_id = :ws AND user_id = :user', {
@@ -193,8 +236,8 @@ export function mountConsoleRoutes(consoleApi, deps) {
193
236
  if (!canManage(req.role, target.role, role)) throw new HttpError(403, 'forbidden', 'Only an owner can change owners and admins.')
194
237
  if (leavesNoOwner({ targetRole: target.role, newRole: role, owners: ownerCount(req.t) }))
195
238
  throw new HttpError(409, 'last_owner', 'A workspace needs an owner.')
196
- // Taking power away from an owner or admin needs a recent passkey check too.
197
- if (roleChangeNeedsFresh(target.role, role)) freshOrThrow(req)
239
+ // Taking power away from an owner (always) or an admin (when the workspace asks).
240
+ roleStepUp(req, { owner: roleChangeTouchesOwner(target.role, role), admin: roleChangeTouchesAdmin(target.role, role) })
198
241
  req.t.run('UPDATE memberships SET role = :role WHERE workspace_id = :ws AND user_id = :user', {
199
242
  role,
200
243
  user: String(req.params.uid),
@@ -220,8 +263,12 @@ export function mountConsoleRoutes(consoleApi, deps) {
220
263
  if (!canRemoveMember(req.role, target.role, { self })) throw new HttpError(403, 'forbidden', 'You cannot remove this member.')
221
264
  if (leavesNoOwner({ targetRole: target.role, owners: ownerCount(req.t) }))
222
265
  throw new HttpError(409, 'last_owner', 'A workspace needs an owner.')
223
- if (removalNeedsFresh(target.role, { self })) freshOrThrow(req)
266
+ // An owner who leaves is an owner removed, like any other: the fixed core asks. Leaving with a
267
+ // lesser role is one's own business and asks nothing.
268
+ roleStepUp(req, { owner: target.role === 'owner', admin: !self && target.role === 'admin' })
224
269
  req.t.run('DELETE FROM memberships WHERE workspace_id = :ws AND user_id = :user', { user: userId })
270
+ // Their saved views on the Usage and Activity pages go with them.
271
+ createViews(req.t).removeOf(userId)
225
272
  auditOf(req, self ? 'member_left' : 'member_removed', userId, { role: target.role })
226
273
  // Their API tokens are revoked too, unless an admin asks to keep them
227
274
  // ({ revokeTokens: false }). Kept or not, they stop working: a token
@@ -241,9 +288,22 @@ export function mountConsoleRoutes(consoleApi, deps) {
241
288
  const role = req.body?.role || 'member'
242
289
  if (!ROLES.includes(role)) throw new HttpError(400, 'invalid_role', `Role: ${ROLES.join(', ')}.`)
243
290
  if (!canInvite(req.role, role)) throw new HttpError(403, 'forbidden', 'Only an owner can invite an owner.')
244
- if (inviteNeedsFresh(role)) freshOrThrow(req)
291
+ roleStepUp(req, { owner: role === 'owner', admin: role === 'admin', makesAdmin: role === 'admin' })
245
292
  const days = req.body?.expiresInDays ?? INVITE_DAYS_DEFAULT
246
293
  if (!INVITE_DAYS.includes(days)) throw new HttpError(400, 'invalid_expiry', `expiresInDays: one of ${INVITE_DAYS.join(', ')}.`)
294
+ // An invite for one tailnet login: only an account linked to that login
295
+ // (or a first visit that arrives as it) can take it.
296
+ let tailnetLogin = null
297
+ if (req.body?.tailnetLogin !== undefined && req.body?.tailnetLogin !== null && req.body?.tailnetLogin !== '') {
298
+ if (!tailnet)
299
+ throw new HttpError(409, 'tailnet_off', 'Tailnet sign-in is off on this server, so an invite cannot be for a tailnet login.')
300
+ tailnetLogin = cleanTailnetLogin(req.body.tailnetLogin)
301
+ if (!tailnetLogin)
302
+ throw new HttpError(400, 'invalid_login', 'Tailnet login: the name the person signs in to Tailscale with, like ada@example.com.')
303
+ const holder = tailnetAccounts.userFor(tailnetLogin)
304
+ if (holder && roleIn(db, holder.id, req.t.workspaceId))
305
+ throw new HttpError(409, 'already_member', `${tailnetLogin} is already in this workspace.`)
306
+ }
247
307
  let email = null
248
308
  if (req.body?.email !== undefined && req.body?.email !== null && req.body?.email !== '') {
249
309
  if (!inviteEmailOn) throw new HttpError(409, 'email_off', 'This server does not send invite emails. Copy the link instead.')
@@ -274,10 +334,16 @@ export function mountConsoleRoutes(consoleApi, deps) {
274
334
  const id = newId('iv')
275
335
  const expiresAt = iso(days * DAY)
276
336
  req.t.run(
277
- 'INSERT INTO invites (workspace_id, id, token_hash, role, created_by, created_at, expires_at, email, note) VALUES (:ws, :id, :hash, :role, :user, :at, :expires, :email, :note)',
278
- { id, hash: sha256(token), role, user: req.user.id, at: iso(), expires: expiresAt, email, note },
337
+ 'INSERT INTO invites (workspace_id, id, token_hash, role, created_by, created_at, expires_at, email, note, tailnet_login) VALUES (:ws, :id, :hash, :role, :user, :at, :expires, :email, :note, :tailnet)',
338
+ { id, hash: sha256(token), role, user: req.user.id, at: iso(), expires: expiresAt, email, note, tailnet: tailnetLogin },
279
339
  )
280
- auditOf(req, 'invite_created', id, { role, days, ...(email ? { emailed: true } : {}), ...(note ? { note } : {}) })
340
+ auditOf(req, 'invite_created', id, {
341
+ role,
342
+ days,
343
+ ...(email ? { emailed: true } : {}),
344
+ ...(note ? { note } : {}),
345
+ ...(tailnetLogin ? { tailnet: tailnetLogin } : {}),
346
+ })
281
347
  const url = `${publicOrigin}/invite#${token}`
282
348
  let emailed = null
283
349
  if (email) {
@@ -293,7 +359,7 @@ export function mountConsoleRoutes(consoleApi, deps) {
293
359
  emailed = { ok: result.ok, error: result.ok ? null : result.error }
294
360
  if (result.ok) req.t.run('UPDATE invites SET emailed_at = :at WHERE workspace_id = :ws AND id = :id', { at: iso(), id })
295
361
  }
296
- res.status(201).json({ invite: { id, role, expiresAt, email, note }, url, emailed })
362
+ res.status(201).json({ invite: { id, role, expiresAt, email, note, tailnetLogin }, url, emailed })
297
363
  }),
298
364
  )
299
365
  consoleApi.delete(
@@ -334,7 +400,7 @@ export function mountConsoleRoutes(consoleApi, deps) {
334
400
  consoleApi.delete(
335
401
  '/workspaces/:ws/projects/:pid',
336
402
  inWorkspace(NEEDS.projects),
337
- needFresh,
403
+ stepUp('data'),
338
404
  inProject,
339
405
  handle(async (req, res) => {
340
406
  req.projects.remove(req.project.id)
@@ -351,7 +417,7 @@ export function mountConsoleRoutes(consoleApi, deps) {
351
417
  consoleApi.delete(
352
418
  '/workspaces/:ws/projects/:pid/boards/:bid',
353
419
  inWorkspace(NEEDS.projects),
354
- needFresh,
420
+ stepUp('data'),
355
421
  inProject,
356
422
  handle(async (req, res) => {
357
423
  const gone = req.projects.removeBoard(req.project.id, req.params.bid)
@@ -371,9 +437,11 @@ export function mountConsoleRoutes(consoleApi, deps) {
371
437
  consoleApi.post(
372
438
  '/workspaces/:ws/projects/:pid/tokens',
373
439
  inWorkspace(NEEDS.tokens),
374
- needFresh,
440
+ stepUp('tokens'),
375
441
  inProject,
376
442
  handle(async (req, res) => {
443
+ // A token is what a command line or an agent works with: where the workspace wants a passkey for those, here too.
444
+ machineTokensOrThrow(req)
377
445
  res.status(201).json(createApiToken(req, req.body || {}))
378
446
  }),
379
447
  )
@@ -387,15 +455,25 @@ export function mountConsoleRoutes(consoleApi, deps) {
387
455
  consoleApi.put(
388
456
  '/workspaces/:ws/projects/:pid/agent',
389
457
  inWorkspace('admin'),
390
- needFresh,
458
+ stepUp('agents'),
391
459
  inProject,
392
460
  handle((req, res) => {
393
461
  const policy = cleanPolicy(req.body)
462
+ const before = agentPolicy(req.t, req.project.id)
394
463
  req.t.run('UPDATE projects SET agent_policy = :policy WHERE workspace_id = :ws AND id = :project', {
395
464
  project: req.project.id,
396
465
  policy: JSON.stringify(policy),
397
466
  })
398
- auditOf(req, 'agent_policy_changed', req.project.id)
467
+ // What changed, setting by setting (names of settings and their values; the board overrides as a count).
468
+ const shown = (value) =>
469
+ Array.isArray(value) ? value.join(', ') || 'none' : value && typeof value === 'object' ? Object.keys(value).length : value
470
+ const changed = Object.keys(policy).filter((key) => JSON.stringify(policy[key]) !== JSON.stringify(before[key]))
471
+ auditOf(req, 'agent_policy_changed', req.project.id, {
472
+ name: req.project.name,
473
+ changed,
474
+ before: Object.fromEntries(changed.map((key) => [key, shown(before[key])])),
475
+ after: Object.fromEntries(changed.map((key) => [key, shown(policy[key])])),
476
+ })
399
477
  res.json({ policy })
400
478
  }),
401
479
  )
@@ -441,6 +519,16 @@ export function mountConsoleRoutes(consoleApi, deps) {
441
519
  )
442
520
  if (!result.changes) throw new HttpError(404, 'unknown_token', 'No such token.')
443
521
  auditOf(req, 'token_revoked', String(req.params.tid))
522
+ // A token that was an agent: what waited for it goes to any agent, and
523
+ // the project loses it as its default (src/hosted/agents.js).
524
+ const agents = agentsFor(req.t)
525
+ const agent = agents.forToken(req.project.id, String(req.params.tid))
526
+ if (agent)
527
+ agents.afterRevoke(
528
+ { userId: req.user.id, role: req.role, audit: (action, target, detail) => auditOf(req, action, target, detail) },
529
+ req.project.id,
530
+ agent.id,
531
+ )
444
532
  res.json({ ok: true })
445
533
  }),
446
534
  )
package/src/hosted/db.js CHANGED
@@ -462,6 +462,270 @@ const MIGRATIONS = [
462
462
  CREATE INDEX comment_files_comment ON comment_files(workspace_id, project_id, board_id, comment_number);
463
463
  CREATE INDEX comment_files_import ON comment_files(workspace_id, project_id, import_session, import_ref);
464
464
  `,
465
+ // 12: agents (0.4.0). A project API token that may take work (the claim
466
+ // scope) is an agent: this row gives it a face (kind, icon, tint, machine),
467
+ // an audience (who may send it work), an approval rule and who may change
468
+ // or answer it. The name stays the token's. A project has a default
469
+ // agent; a comment can be addressed to one agent (NULL: any agent); a
470
+ // claim remembers which agent took it. agent_runs is the usage record of
471
+ // each comment an agent took (who asked, which agent, when, how it ended;
472
+ // never comment or answer text), shaped for the usage dashboard, whose
473
+ // token and cost columns stay NULL until an agent reports them.
474
+ //
475
+ // Every token that already has the claim scope becomes an agent of kind
476
+ // "watcher" with the audience it had in effect before: everyone the
477
+ // project's agent policy trusts (audience_inherited marks that it was
478
+ // never chosen). Agents made from now on start with "owner".
479
+ `
480
+ CREATE TABLE agents (
481
+ workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
482
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
483
+ id TEXT PRIMARY KEY,
484
+ token_id TEXT NOT NULL UNIQUE REFERENCES api_tokens(id) ON DELETE CASCADE,
485
+ kind TEXT NOT NULL DEFAULT 'watcher',
486
+ icon TEXT,
487
+ tint TEXT,
488
+ machine TEXT,
489
+ capabilities TEXT NOT NULL DEFAULT '{}',
490
+ audience TEXT NOT NULL DEFAULT 'owner' CHECK (audience IN ('owner', 'members', 'trusted')),
491
+ audience_users TEXT NOT NULL DEFAULT '[]',
492
+ audience_inherited INTEGER NOT NULL DEFAULT 0,
493
+ approval_rule TEXT NOT NULL DEFAULT 'ask' CHECK (approval_rule IN ('ask', 'auto')),
494
+ approval_change_role TEXT NOT NULL DEFAULT 'admin' CHECK (approval_change_role IN ('admin', 'owner')),
495
+ approval_answer_role TEXT NOT NULL DEFAULT 'admin' CHECK (approval_answer_role IN ('admin', 'owner')),
496
+ created_by TEXT,
497
+ created_at TEXT NOT NULL,
498
+ approved_by TEXT,
499
+ approved_at TEXT,
500
+ last_seen_at TEXT
501
+ );
502
+ CREATE INDEX agents_project ON agents(workspace_id, project_id);
503
+ ALTER TABLE projects ADD COLUMN default_agent_id TEXT;
504
+ ALTER TABLE comments ADD COLUMN agent_id TEXT;
505
+ ALTER TABLE agent_claims ADD COLUMN agent_id TEXT;
506
+ INSERT INTO agents (workspace_id, project_id, id, token_id, kind, audience, audience_inherited, created_by, created_at,
507
+ approved_by, approved_at, last_seen_at)
508
+ SELECT workspace_id, project_id, 'ag_' || lower(hex(randomblob(12))), id, 'watcher', 'trusted', 1, created_by, created_at,
509
+ created_by, created_at, last_used_at
510
+ FROM api_tokens WHERE scopes LIKE '%"claim"%';
511
+ UPDATE agent_claims SET agent_id = (SELECT a.id FROM agents a WHERE a.token_id = agent_claims.token_id);
512
+ CREATE TABLE agent_runs (
513
+ workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
514
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
515
+ id TEXT PRIMARY KEY,
516
+ kind TEXT NOT NULL DEFAULT 'fix',
517
+ agent_id TEXT,
518
+ claim_id TEXT,
519
+ board_id TEXT,
520
+ comment_number INTEGER,
521
+ thread_id TEXT,
522
+ asked_by TEXT,
523
+ started_at TEXT NOT NULL,
524
+ ended_at TEXT,
525
+ outcome TEXT,
526
+ model TEXT,
527
+ effort TEXT,
528
+ input_tokens INTEGER,
529
+ output_tokens INTEGER,
530
+ cached_tokens INTEGER,
531
+ cost_micros INTEGER,
532
+ steps INTEGER
533
+ );
534
+ CREATE INDEX agent_runs_time ON agent_runs(workspace_id, started_at);
535
+ CREATE INDEX agent_runs_project ON agent_runs(workspace_id, project_id, started_at);
536
+ CREATE INDEX agent_runs_agent ON agent_runs(workspace_id, agent_id, started_at);
537
+ CREATE INDEX agent_runs_person ON agent_runs(workspace_id, asked_by, started_at);
538
+ CREATE INDEX agent_runs_claim ON agent_runs(workspace_id, claim_id);
539
+ `,
540
+ // 13: connected agents and chat (0.5.0). `shapewall agent connect` holds a
541
+ // link to the server and members chat with the agent on the board. A
542
+ // thread belongs to a board ("board" and "comment-<n>" are shared, a
543
+ // "chat-..." is its starter's own) and names the agent it talks to. Its
544
+ // messages are stored here (the person's text, the agent's answer with its
545
+ // cards in their final state); a turn is one question on its way through
546
+ // an agent, whose live events stay in memory. A device login remembers
547
+ // what the machine said it runs (meta), for the approval page.
548
+ `
549
+ ALTER TABLE device_logins ADD COLUMN meta TEXT;
550
+ CREATE TABLE chat_threads (
551
+ workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
552
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
553
+ board_id TEXT NOT NULL,
554
+ thread_id TEXT NOT NULL,
555
+ agent_id TEXT,
556
+ owner_user_id TEXT,
557
+ title TEXT,
558
+ title_source TEXT,
559
+ archived INTEGER NOT NULL DEFAULT 0,
560
+ created_by TEXT,
561
+ created_at TEXT NOT NULL,
562
+ updated_at TEXT NOT NULL,
563
+ PRIMARY KEY (workspace_id, project_id, board_id, thread_id)
564
+ );
565
+ CREATE TABLE chat_messages (
566
+ workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
567
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
568
+ board_id TEXT NOT NULL,
569
+ thread_id TEXT NOT NULL,
570
+ id TEXT PRIMARY KEY,
571
+ role TEXT NOT NULL CHECK (role IN ('user', 'assistant')),
572
+ author_user_id TEXT,
573
+ agent_id TEXT,
574
+ turn_id TEXT,
575
+ body TEXT NOT NULL,
576
+ bytes INTEGER NOT NULL DEFAULT 0,
577
+ created_at TEXT NOT NULL
578
+ );
579
+ CREATE INDEX chat_messages_thread ON chat_messages(workspace_id, project_id, board_id, thread_id, created_at);
580
+ CREATE TABLE chat_turns (
581
+ workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
582
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
583
+ id TEXT PRIMARY KEY,
584
+ board_id TEXT NOT NULL,
585
+ thread_id TEXT NOT NULL,
586
+ agent_id TEXT NOT NULL,
587
+ kind TEXT NOT NULL DEFAULT 'chat',
588
+ state TEXT NOT NULL DEFAULT 'queued',
589
+ acked_seq INTEGER NOT NULL DEFAULT 0,
590
+ started_by TEXT,
591
+ user_message_id TEXT,
592
+ run_id TEXT,
593
+ comment_number INTEGER,
594
+ created_at TEXT NOT NULL,
595
+ ended_at TEXT
596
+ );
597
+ CREATE INDEX chat_turns_thread ON chat_turns(workspace_id, project_id, board_id, thread_id, created_at);
598
+ CREATE INDEX chat_turns_agent ON chat_turns(workspace_id, agent_id, state);
599
+ `,
600
+ // 14: approvals and edits from a hosted board (0.6.0). chat_permissions is
601
+ // one row per permission card a connected agent asked during a fix: what
602
+ // it asked (the card, as hashed), its state, who answered and when. The
603
+ // usage record of a run gains how many requests it asked and how they
604
+ // ended. Additive; an older build ignores all of it.
605
+ `
606
+ CREATE TABLE chat_permissions (
607
+ workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
608
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
609
+ id TEXT NOT NULL,
610
+ turn_id TEXT NOT NULL,
611
+ agent_id TEXT NOT NULL,
612
+ board_id TEXT NOT NULL,
613
+ thread_id TEXT NOT NULL,
614
+ kind TEXT NOT NULL,
615
+ card TEXT NOT NULL,
616
+ card_hash TEXT NOT NULL,
617
+ state TEXT NOT NULL DEFAULT 'pending',
618
+ created_at TEXT NOT NULL,
619
+ expires_at TEXT NOT NULL,
620
+ answered_by TEXT,
621
+ answered_at TEXT,
622
+ PRIMARY KEY (workspace_id, turn_id, id)
623
+ );
624
+ CREATE INDEX chat_permissions_board ON chat_permissions(workspace_id, project_id, board_id, state);
625
+ ALTER TABLE agent_runs ADD COLUMN approvals_asked INTEGER;
626
+ ALTER TABLE agent_runs ADD COLUMN approvals_allowed INTEGER;
627
+ ALTER TABLE agent_runs ADD COLUMN approvals_denied INTEGER;
628
+ ALTER TABLE agents ADD COLUMN approval_rule_by TEXT;
629
+ `,
630
+ // 15: the Usage dashboard and people's activity (0.7.0). The usage record
631
+ // of a turn gains what the dashboard shows and nothing else: how long it
632
+ // took (duration_ms: the server's own clock; agent_ms: what the agent said),
633
+ // its tool calls counted by type (tools, JSON of name to count), requests
634
+ // allowed without asking and who answered the others (approvals_auto,
635
+ // approvals_by: JSON of user id to counts), the context window as the agent
636
+ // reported it, and the person who connected the agent (agent_owner: they
637
+ // may read everything that ran on their machine). Never text.
638
+ // saved_views: a person's named filters on the Usage and Activity pages
639
+ // (a name and a query string; a view never widens what its reader may see).
640
+ // retention_usage_days: how long a workspace keeps usage records (NULL: the
641
+ // server default). Indexes for the activity filters. Additive; an older
642
+ // build ignores all of it (docs/hosted.md, "Rolling back").
643
+ `
644
+ ALTER TABLE agent_runs ADD COLUMN agent_owner TEXT;
645
+ ALTER TABLE agent_runs ADD COLUMN duration_ms INTEGER;
646
+ ALTER TABLE agent_runs ADD COLUMN agent_ms INTEGER;
647
+ ALTER TABLE agent_runs ADD COLUMN tools TEXT;
648
+ ALTER TABLE agent_runs ADD COLUMN approvals_auto INTEGER;
649
+ ALTER TABLE agent_runs ADD COLUMN approvals_by TEXT;
650
+ ALTER TABLE agent_runs ADD COLUMN window_used INTEGER;
651
+ ALTER TABLE agent_runs ADD COLUMN window_size INTEGER;
652
+ UPDATE agent_runs SET agent_owner = (SELECT a.created_by FROM agents a WHERE a.id = agent_runs.agent_id);
653
+ UPDATE agent_runs SET duration_ms = MAX(0, CAST(ROUND((julianday(ended_at) - julianday(started_at)) * 86400000) AS INTEGER))
654
+ WHERE ended_at IS NOT NULL;
655
+ CREATE INDEX agent_runs_owner ON agent_runs(workspace_id, agent_owner, started_at);
656
+ CREATE INDEX agent_runs_thread ON agent_runs(workspace_id, project_id, board_id, thread_id);
657
+ CREATE TABLE saved_views (
658
+ workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
659
+ id TEXT PRIMARY KEY,
660
+ user_id TEXT NOT NULL,
661
+ page TEXT NOT NULL CHECK (page IN ('usage', 'activity')),
662
+ name TEXT NOT NULL,
663
+ query TEXT NOT NULL,
664
+ created_at TEXT NOT NULL,
665
+ updated_at TEXT NOT NULL
666
+ );
667
+ CREATE INDEX saved_views_user ON saved_views(workspace_id, user_id, page);
668
+ ALTER TABLE workspaces ADD COLUMN retention_usage_days INTEGER;
669
+ CREATE INDEX audit_workspace_at ON audit_log(workspace_id, at);
670
+ CREATE INDEX audit_workspace_user ON audit_log(workspace_id, user_id, id);
671
+ CREATE INDEX audit_account_user ON audit_log(user_id, id) WHERE workspace_id IS NULL;
672
+ `,
673
+ // 16: layouts of the Usage dashboard (0.7.0). One row per layout: a
674
+ // person's own (kind 'person', subject their user id), the workspace's
675
+ // default that people start from (kind 'default', subject ''), and the
676
+ // layout a saved view carries (kind 'view', subject the view's id). The
677
+ // layout is JSON, checked on the way in and again on the way out
678
+ // (src/hosted/usage-layout.js). One new table and nothing else: an older
679
+ // build ignores it (docs/hosted.md, "Migration 16 and rollback").
680
+ // The ledger below runs 16 and 17 in whichever order they reach a database: one made on the tailnet
681
+ // sign-in branch (17 ran, 16 absent) runs 16 later, and one that ran 16 first runs 17 next.
682
+ `
683
+ CREATE TABLE usage_layouts (
684
+ workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
685
+ kind TEXT NOT NULL CHECK (kind IN ('person', 'default', 'view')),
686
+ subject TEXT NOT NULL,
687
+ layout TEXT NOT NULL,
688
+ updated_by TEXT NOT NULL,
689
+ updated_at TEXT NOT NULL,
690
+ PRIMARY KEY (workspace_id, kind, subject)
691
+ );
692
+ `,
693
+ // 17. Step-up as a workspace's choice (step_up: a JSON object, '{}' is all off;
694
+ // src/hosted/step-up.js), and tailnet sign-in (src/hosted/tailnet.js): the
695
+ // tailnet login an account is linked to, the one a session came in with
696
+ // (such a session works only on requests that carry that identity), the
697
+ // one an invite is for, and the logins that arrived and belong to nobody
698
+ // yet. users.tailnet_user_id: Tailscale's own id of the user behind the
699
+ // linked login (a login string can be given to someone else later; the id
700
+ // cannot). passkeys.tailnet_added_from: set (to the device's label) on a
701
+ // passkey that a tailnet session added with no passkey check, the first
702
+ // of its account; with recovery_added_at as its 24 hour clock.
703
+ // server_settings: what the operator switched for the whole server
704
+ // (src/hosted/passkey-policy.js: passkeys on a tailnet sign-in server).
705
+ // Additive; an older build ignores all of it (docs/hosted.md,
706
+ // "Rolling back").
707
+ `
708
+ ALTER TABLE workspaces ADD COLUMN step_up TEXT NOT NULL DEFAULT '{}';
709
+ ALTER TABLE users ADD COLUMN tailnet_login TEXT;
710
+ ALTER TABLE users ADD COLUMN tailnet_linked_at TEXT;
711
+ ALTER TABLE users ADD COLUMN tailnet_user_id TEXT;
712
+ ALTER TABLE passkeys ADD COLUMN tailnet_added_from TEXT;
713
+ CREATE TABLE server_settings (
714
+ key TEXT PRIMARY KEY,
715
+ value TEXT NOT NULL,
716
+ updated_at TEXT NOT NULL
717
+ );
718
+ CREATE UNIQUE INDEX users_tailnet_login ON users(tailnet_login) WHERE tailnet_login IS NOT NULL;
719
+ ALTER TABLE sessions ADD COLUMN tailnet_login TEXT;
720
+ ALTER TABLE invites ADD COLUMN tailnet_login TEXT;
721
+ CREATE TABLE tailnet_visitors (
722
+ login TEXT PRIMARY KEY,
723
+ name TEXT NOT NULL DEFAULT '',
724
+ first_seen_at TEXT NOT NULL,
725
+ last_seen_at TEXT NOT NULL,
726
+ visits INTEGER NOT NULL DEFAULT 1
727
+ );
728
+ `,
465
729
  ]
466
730
 
467
731
  export async function openDatabase(file) {
@@ -473,6 +737,36 @@ export async function openDatabase(file) {
473
737
  return db
474
738
  }
475
739
 
740
+ // A database made by a build of 0.7.0 from before it was released, when the
741
+ // sign-in migration still had the number 16 (now 17; 16 is the saved Usage
742
+ // layouts'). Its ledger says "16 ran", which now means something else: the
743
+ // real 16 would never run, and 17 would run on top of its own tables and
744
+ // fail. Told apart by what is there: the ledger has 16 and not 17, the
745
+ // sign-in tables exist and usage_layouts does not. Repaired in place: what
746
+ // that early build did not have yet is added (each piece only if missing),
747
+ // and the ledger is corrected to "17 ran, 16 did not", so that both end
748
+ // applied once. A database where 16 is really the layouts' is left alone.
749
+ function repairEarlySignIn(db) {
750
+ const has = (version) => Boolean(db.prepare('SELECT 1 FROM schema_migrations WHERE version = ?').get(version))
751
+ const table = (name) => Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name))
752
+ const column = (name, col) =>
753
+ db
754
+ .prepare(`PRAGMA table_info(${name})`)
755
+ .all()
756
+ .some((row) => row.name === col)
757
+ if (!has(16) || has(17) || table('usage_layouts') || !table('tailnet_visitors') || !column('users', 'tailnet_login')) return
758
+ if (!column('workspaces', 'step_up')) db.exec("ALTER TABLE workspaces ADD COLUMN step_up TEXT NOT NULL DEFAULT '{}'")
759
+ if (!column('users', 'tailnet_linked_at')) db.exec('ALTER TABLE users ADD COLUMN tailnet_linked_at TEXT')
760
+ if (!column('users', 'tailnet_user_id')) db.exec('ALTER TABLE users ADD COLUMN tailnet_user_id TEXT')
761
+ if (!column('passkeys', 'tailnet_added_from')) db.exec('ALTER TABLE passkeys ADD COLUMN tailnet_added_from TEXT')
762
+ if (!column('sessions', 'tailnet_login')) db.exec('ALTER TABLE sessions ADD COLUMN tailnet_login TEXT')
763
+ if (!column('invites', 'tailnet_login')) db.exec('ALTER TABLE invites ADD COLUMN tailnet_login TEXT')
764
+ db.exec('CREATE UNIQUE INDEX IF NOT EXISTS users_tailnet_login ON users(tailnet_login) WHERE tailnet_login IS NOT NULL')
765
+ db.exec('CREATE TABLE IF NOT EXISTS server_settings (key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at TEXT NOT NULL)')
766
+ db.prepare('DELETE FROM schema_migrations WHERE version = 16').run()
767
+ db.prepare('INSERT INTO schema_migrations(version) VALUES (17)').run()
768
+ }
769
+
476
770
  // A ledger allows reserved workstreams to land out of order. user_version is
477
771
  // still the highest applied number, but an absent reserved migration is never
478
772
  // marked applied. Legacy databases (before the ledger) have contiguous 1..4.
@@ -486,6 +780,7 @@ export function migrate(db, migrations = MIGRATIONS) {
486
780
  throw new Error('Database has untracked migrations newer than version 4; restore its pre-upgrade backup before continuing.')
487
781
  for (let version = 1; version <= current; version += 1) db.prepare('INSERT INTO schema_migrations(version) VALUES (?)').run(version)
488
782
  }
783
+ if (migrations === MIGRATIONS) repairEarlySignIn(db)
489
784
  for (let index = 0; index < migrations.length; index += 1) {
490
785
  if (!migrations[index] || db.prepare('SELECT 1 FROM schema_migrations WHERE version = ?').get(index + 1)) continue
491
786
  db.exec(migrations[index])