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
@@ -0,0 +1,242 @@
1
+ // What this machine allows a connected agent (`shapewall agent connect`),
2
+ // in a file of its own beside the saved agents: $XDG_CONFIG_HOME/shapewall/
3
+ // agent-policy.json (default ~/.config/...), the folder 0700, the file 0600.
4
+ // Outside every repository, read by the connector only, and never sent
5
+ // anywhere but as the summary the board shows. The server cannot change it:
6
+ // this file is the ceiling, and a setting on the server only ever narrows it.
7
+ //
8
+ // audience "server": whoever the agent's audience on the server names
9
+ // (set when the connection is approved, and on its Agents page)
10
+ // "owner": the server is told to keep it to the person who
11
+ // connected it, and this machine refuses a job the server
12
+ // labels as someone else's. The machine cannot check that
13
+ // label: this does not protect against a server that lies
14
+ // approvals "none" (the default): the agent reads and answers only. Nobody
15
+ // answers a permission request from the board, and no fix runs.
16
+ // "owner": the person who connected it may allow an edit from
17
+ // the board. "admins": anyone the server lets answer may.
18
+ // Either way the edit is made on a new branch in a folder of
19
+ // its own, never in this checkout.
20
+ // commands the exact commands the agent may ever ask to run, each still
21
+ // approved on the board. Empty (the default): never.
22
+ // auto the kinds ("edits", "commands") the server's "always allow"
23
+ // rule may apply to. Empty (the default): every request waits
24
+ // for a person. Never widens `commands` or what may be edited.
25
+ // allowPaths files that decide what runs later or hold settings (dotfiles,
26
+ // package.json, a Makefile, ...) the agent may ask to edit all
27
+ // the same. Empty (the default): such an edit is refused here.
28
+ // base the branch a fix starts from. null (the default): the commit
29
+ // this checkout is on, and only while it has no uncommitted
30
+ // changes.
31
+ // remote the git remote a finished fix is pushed to ("origin"), or
32
+ // null: never pushed.
33
+ //
34
+ // One entry per server and connection name.
35
+
36
+ import fs from 'node:fs'
37
+ import path from 'node:path'
38
+ import { randomBytes } from 'node:crypto'
39
+ import { credentialsFile } from './credentials.js'
40
+
41
+ export const POLICY_AUDIENCES = ['server', 'owner']
42
+ export const POLICY_APPROVALS = ['none', 'owner', 'admins']
43
+ export const POLICY_AUTO_KINDS = ['edits', 'commands']
44
+ export const COMMANDS_MAX = 20
45
+ export const COMMAND_MAX = 200
46
+ export const ALLOW_PATHS_MAX = 40
47
+ export const DEFAULT_MACHINE_POLICY = {
48
+ audience: 'server',
49
+ approvals: 'none',
50
+ commands: [],
51
+ auto: [],
52
+ allowPaths: [],
53
+ base: null,
54
+ remote: 'origin',
55
+ }
56
+
57
+ export const policyFile = (env = process.env) => path.join(path.dirname(credentialsFile(env)), 'agent-policy.json')
58
+
59
+ // The file, read only once it is this person's and only theirs to write:
60
+ // owner and mode are checked on the open file, before a byte of it is trusted.
61
+ function readAll(file) {
62
+ let fd
63
+ try {
64
+ fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0))
65
+ } catch (error) {
66
+ if (error.code === 'ENOENT') return { version: 1, connections: {} }
67
+ if (error.code === 'ELOOP') throw new Error(`${file} is a symbolic link. A policy file is a plain file of your own.`, { cause: error })
68
+ throw error
69
+ }
70
+ let text
71
+ try {
72
+ const stat = fs.fstatSync(fd)
73
+ if (!stat.isFile()) throw new Error(`${file} is not a plain file.`)
74
+ if (process.platform !== 'win32') {
75
+ // A policy another user owns, or others can write, is not this person's policy.
76
+ if (typeof process.getuid === 'function' && stat.uid !== process.getuid())
77
+ throw new Error(`${file} belongs to another user of this machine. Remove it, then run agent connect again.`)
78
+ if (stat.mode & 0o022) throw new Error(`${file} can be changed by other users of this machine. Run: chmod 600 "${file}"`)
79
+ }
80
+ text = fs.readFileSync(fd, 'utf8')
81
+ } finally {
82
+ fs.closeSync(fd)
83
+ }
84
+ let data
85
+ try {
86
+ data = JSON.parse(text)
87
+ } catch {
88
+ throw new Error(`${file} is not valid JSON. Fix it or delete it.`)
89
+ }
90
+ if (!data || typeof data.connections !== 'object' || !data.connections || Array.isArray(data.connections))
91
+ throw new Error(`${file} has no "connections". Fix it or delete it.`)
92
+ return data
93
+ }
94
+
95
+ // One command as it is compared: single spaces, no control characters, no
96
+ // line breaks. An agent's request must equal it exactly.
97
+ export function cleanCommand(value) {
98
+ if (typeof value !== 'string') return null
99
+ // eslint-disable-next-line no-control-regex
100
+ if (/[\u0000-\u001f\u007f]/.test(value)) return null
101
+ const text = value.trim().replace(/ +/g, ' ')
102
+ return text && text.length <= COMMAND_MAX ? text : null
103
+ }
104
+
105
+ // A project-relative path with plain segments ("package.json", ".github/workflows/ci.yml").
106
+ export function cleanAllowPath(value) {
107
+ if (typeof value !== 'string' || !value || value.length > 300 || value.includes('\0') || value.includes('\\')) return null
108
+ const parts = value.split('/')
109
+ if (path.isAbsolute(value) || parts.some((part) => !part || part === '.' || part === '..')) return null
110
+ // Never git's own folder or Shapewall's store, whatever the file says.
111
+ if (['.git', '.shapewall'].includes(parts[0])) return null
112
+ return parts.join('/')
113
+ }
114
+
115
+ const BRANCH_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/
116
+ export const cleanBase = (value) =>
117
+ typeof value === 'string' && value.length <= 120 && BRANCH_RE.test(value) && !value.includes('..') && !value.endsWith('.lock')
118
+ ? value
119
+ : null
120
+ const REMOTE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,59}$/
121
+ export const cleanRemote = (value) => (typeof value === 'string' && REMOTE_RE.test(value) ? value : null)
122
+
123
+ // One entry of the file, as the policy in effect. A key that is missing
124
+ // reads as its default. A key that is there but is not a value this file
125
+ // knows (a typo, a wrong type, false, "", 0) reads as the NARROWEST setting
126
+ // for that key, never as the default: no approvals, only the person who
127
+ // connected it, no commands, nothing automatic, no settings files, never
128
+ // pushed. `warn(text)` hears about each such key by name.
129
+ const KNOWN_KEYS = ['audience', 'approvals', 'commands', 'auto', 'allowPaths', 'base', 'remote']
130
+ const unique = (list) => [...new Set(list)]
131
+ function clean(entry, warn = () => {}) {
132
+ const has = (key) =>
133
+ entry !== null && typeof entry === 'object' && !Array.isArray(entry) && Object.hasOwn(entry, key) && entry[key] !== undefined
134
+ if (entry !== undefined && entry !== null && (typeof entry !== 'object' || Array.isArray(entry))) {
135
+ warn('this connection\'s entry is not an object: read as "read and answer only, for the person who connected it"')
136
+ return { ...DEFAULT_MACHINE_POLICY, audience: 'owner', remote: null }
137
+ }
138
+ for (const key of Object.keys(entry || {})) if (!KNOWN_KEYS.includes(key)) warn(`"${key}" is not a setting this version knows: ignored`)
139
+ const bad = (key, narrow) => {
140
+ warn(`"${key}" has a value this version does not know: read as ${narrow}`)
141
+ }
142
+ let audience = DEFAULT_MACHINE_POLICY.audience
143
+ if (has('audience')) {
144
+ if (POLICY_AUDIENCES.includes(entry.audience)) audience = entry.audience
145
+ else {
146
+ audience = 'owner'
147
+ bad('audience', '"owner" (only the person who connected it)')
148
+ }
149
+ }
150
+ let approvals = 'none'
151
+ if (has('approvals')) {
152
+ if (POLICY_APPROVALS.includes(entry.approvals)) approvals = entry.approvals
153
+ else bad('approvals', '"none" (read and answer only)')
154
+ }
155
+ const on = approvals !== 'none'
156
+ // A list with one entry it cannot read is not trusted for the rest either.
157
+ const list = (key, each, max) => {
158
+ if (!has(key)) return []
159
+ const value = entry[key]
160
+ if (!Array.isArray(value) || value.length > max || value.some((item) => each(item) === null)) {
161
+ bad(key, 'empty')
162
+ return []
163
+ }
164
+ return unique(value.map(each))
165
+ }
166
+ const commands = list('commands', cleanCommand, COMMANDS_MAX)
167
+ const auto = list('auto', (kind) => (POLICY_AUTO_KINDS.includes(kind) ? kind : null), POLICY_AUTO_KINDS.length)
168
+ const allowPaths = list('allowPaths', cleanAllowPath, ALLOW_PATHS_MAX)
169
+ let base = null
170
+ if (has('base') && entry.base !== null) {
171
+ base = cleanBase(entry.base)
172
+ if (!base) bad('base', 'none (the commit the checkout is on)')
173
+ }
174
+ let remote = DEFAULT_MACHINE_POLICY.remote
175
+ if (has('remote')) {
176
+ remote = entry.remote === null ? null : cleanRemote(entry.remote)
177
+ if (entry.remote !== null && !remote) bad('remote', 'none (a fix is never pushed)')
178
+ }
179
+ return {
180
+ audience,
181
+ approvals,
182
+ commands: on ? commands : [],
183
+ auto: on ? auto.filter((kind) => kind !== 'commands' || commands.length > 0) : [],
184
+ allowPaths: on ? allowPaths : [],
185
+ base,
186
+ remote,
187
+ }
188
+ }
189
+ export { clean as cleanMachinePolicy }
190
+
191
+ // The policy for one connection (defaults when nothing is saved).
192
+ // `warn(text)`: told about every value in the file that was not understood.
193
+ export function readMachinePolicy(origin, slug = 'default', env = process.env, { warn = () => {} } = {}) {
194
+ const file = policyFile(env)
195
+ return clean(readAll(file).connections[`${origin}#${slug}`], (text) => warn(`${file}: ${text}`))
196
+ }
197
+
198
+ // Saves what was chosen for one connection; returns the policy in effect.
199
+ export function saveMachinePolicy(origin, slug, changes, env = process.env) {
200
+ const file = policyFile(env)
201
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
202
+ const data = readAll(file)
203
+ const next = clean({ ...clean(data.connections[`${origin}#${slug}`]), ...changes })
204
+ data.version = 1
205
+ data.connections[`${origin}#${slug}`] = next
206
+ const temp = `${file}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`
207
+ try {
208
+ fs.writeFileSync(temp, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600, flag: 'wx' })
209
+ fs.renameSync(temp, file)
210
+ } catch (error) {
211
+ fs.rmSync(temp, { force: true })
212
+ throw error
213
+ }
214
+ if (process.platform !== 'win32') fs.chmodSync(file, 0o600)
215
+ return next
216
+ }
217
+
218
+ // The policy in one line each, for the terminal when the agent connects.
219
+ export function describeMachinePolicy(policy) {
220
+ if (policy.approvals === 'none') return ['Reads and answers. No edits, no commands (this machine refuses both).']
221
+ const who = policy.approvals === 'owner' ? 'the person who connected it' : 'the people the server lets answer (admins by default)'
222
+ const lines = [
223
+ `Edits: asked on the board, allowed by ${who}. Each fix is made on a new branch in a folder of its own, never in this checkout.`,
224
+ policy.commands.length
225
+ ? `Commands: only ${policy.commands.map((command) => `"${command}"`).join(', ')}, each asked on the board.`
226
+ : 'Commands: never.',
227
+ ]
228
+ if (policy.auto.length)
229
+ lines.push(
230
+ `May be allowed without asking: ${policy.auto.join(' and ')}, once ${policy.approvals === 'owner' ? 'the person who connected it (nobody else)' : "someone with the agent's rule-changing role (an admin by default)"} switches that on in the console. Still only inside the project, never a file that runs something, and such a fix is not pushed until a person has looked at its whole diff on the board.`,
231
+ )
232
+ if (policy.allowPaths.length) lines.push(`Settings files it may ask to edit: ${policy.allowPaths.join(', ')}.`)
233
+ lines.push(
234
+ policy.base
235
+ ? `A fix starts from the branch ${policy.base}.`
236
+ : 'A fix starts from the commit this checkout is on (refused while it has uncommitted changes; --base BRANCH lifts that).',
237
+ )
238
+ lines.push(
239
+ policy.remote ? `A finished fix is pushed to the remote "${policy.remote}" when this machine may push there.` : 'Fixes are not pushed.',
240
+ )
241
+ return lines
242
+ }
@@ -3,6 +3,10 @@
3
3
  // folder 0700, the file 0600, written whole through a temporary file. The
4
4
  // --remote commands read it when $SHAPEWALL_TOKEN and --token-file are not
5
5
  // set. Nothing here ever prints a token.
6
+ //
7
+ // A connected agent (`shapewall agent connect`) has a token of its own,
8
+ // kept apart under `agents`, by server and connection name ("default"
9
+ // unless --as names another): the same file, the same rules.
6
10
 
7
11
  import fs from 'node:fs'
8
12
  import { randomBytes } from 'node:crypto'
@@ -40,14 +44,44 @@ export function readCredential(origin, env = process.env) {
40
44
  return entry && typeof entry.token === 'string' ? entry : null
41
45
  }
42
46
 
47
+ // The saved token of a connected agent: one per server and connection name.
48
+ export const AGENT_SLUG_RE = /^[a-z0-9][a-z0-9-]{0,31}$/
49
+ const agentKey = (origin, slug) => `${origin}#${slug}`
50
+ export function readAgentCredential(origin, slug = 'default', env = process.env) {
51
+ const entry = readAll(credentialsFile(env)).agents?.[agentKey(origin, slug)]
52
+ return entry && typeof entry.token === 'string' ? entry : null
53
+ }
54
+ export function saveAgentCredential(origin, slug, entry, env = process.env) {
55
+ return save(env, (data) => {
56
+ data.agents = data.agents && typeof data.agents === 'object' && !Array.isArray(data.agents) ? data.agents : {}
57
+ data.agents[agentKey(origin, slug)] = entry
58
+ })
59
+ }
60
+
61
+ // Forgets a connected agent's saved token (the server refused it).
62
+ export function forgetAgentCredential(origin, slug = 'default', env = process.env) {
63
+ if (!readAgentCredential(origin, slug, env)) return false
64
+ save(env, (data) => {
65
+ delete data.agents[agentKey(origin, slug)]
66
+ })
67
+ return true
68
+ }
69
+
43
70
  export function saveCredential(origin, entry, env = process.env) {
71
+ return save(env, (data) => {
72
+ data.servers[origin] = entry
73
+ })
74
+ }
75
+
76
+ // Reads the file, lets `change` edit it, and writes it back whole.
77
+ function save(env, change) {
44
78
  const file = credentialsFile(env)
45
79
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
46
80
  // mkdir's mode only applies to a folder it creates: make an existing one private too.
47
81
  if (process.platform !== 'win32') fs.chmodSync(path.dirname(file), 0o700)
48
82
  const data = readAll(file)
49
83
  data.version = 1
50
- data.servers[origin] = entry
84
+ change(data)
51
85
  // A fresh, unguessable temporary file ('wx' never follows a planted symlink).
52
86
  const temp = `${file}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`
53
87
  try {
@@ -6,6 +6,12 @@
6
6
  // over once; it goes into the credentials file (0600, see credentials.js)
7
7
  // and is never printed. `push`, `comments`, `watch` and `mcp --remote` use
8
8
  // it from then on.
9
+ //
10
+ // On a server with tailnet sign-in, run on a tailnet machine: the server
11
+ // already knows the machine's user, and that account approves the login
12
+ // itself, with no code and no browser (src/remote/tailnet-cli.js). The
13
+ // project comes from --project (and --workspace); the code below is the
14
+ // fallback whenever that does not apply.
9
15
 
10
16
  import os from 'node:os'
11
17
  import { spawn } from 'node:child_process'
@@ -85,12 +91,25 @@ export async function login(
85
91
  sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
86
92
  signal = null,
87
93
  purpose = null,
94
+ // `shapewall agent connect`: what this machine will run ({ kind, name }),
95
+ // shown on the approval page, and what to do with the approved token
96
+ // in place of saving it as this server's login.
97
+ agent = null,
98
+ onApproved = null,
99
+ // false: never ask the server who this machine's tailnet user is (tests of the code flow).
100
+ tailnet = true,
101
+ // The command that was run, for "run it again" (`shapewall agent connect`, `shapewall import`).
102
+ command = 'shapewall login',
88
103
  } = {},
89
104
  ) {
90
105
  out = safeOut(out)
91
106
  const origin = remoteOrigin(flags, env)
92
107
  const machine = os.hostname().split('.')[0] || 'this computer'
93
- const started = await post(fetchImpl, origin, '/api/v1/device/start', { name: machine, ...(purpose === 'import' ? { purpose } : {}) })
108
+ const started = await post(fetchImpl, origin, '/api/v1/device/start', {
109
+ name: machine,
110
+ ...(['import', 'agent'].includes(purpose) ? { purpose } : {}),
111
+ ...(purpose === 'agent' && agent ? { agent } : {}),
112
+ })
94
113
  if (started.status !== 201 || !started.data?.deviceCode) {
95
114
  throw new Error(
96
115
  terminalSafe(started.data?.error?.message) || `Could not start a login on ${origin} (${started.status}). Is it a Shapewall server?`,
@@ -102,18 +121,30 @@ export async function login(
102
121
  // The page is ours to build: the server's verificationUrl is not used.
103
122
  const page = deviceLoginUrl(origin)
104
123
  if (!page) throw new Error(`Cannot build a login page for ${origin}; open its /device page yourself.`)
105
- out(`To log in, open ${page} and enter this code:`)
106
- out('')
107
- out(` ${userCode}`)
108
- out('')
109
- out(`Check that the console shows the same code and "${machine}". It expires in ${Math.round(Number(expiresIn) / 60) || 10} minutes.`)
110
- if (open(page, env)) out('(Opened it in your browser.)')
124
+ // Tailnet sign-in: approved by this machine's tailnet user, when the server knows one who may.
125
+ const { approveByTailnet } = await import('./tailnet-cli.js')
126
+ const approvedHere = tailnet
127
+ ? await approveByTailnet({ origin, userCode, flags, purpose, agent, out, fetchImpl, machine }).catch((error) => {
128
+ // A choice only flags can make (which project): that is the answer, not a fallback.
129
+ throw error
130
+ })
131
+ : false
132
+ if (!approvedHere) {
133
+ out(`${purpose === 'agent' ? 'To connect this agent' : 'To log in'}, open ${page} and enter this code:`)
134
+ out('')
135
+ out(` ${userCode}`)
136
+ out('')
137
+ out(`Check that the console shows the same code and "${machine}". It expires in ${Math.round(Number(expiresIn) / 60) || 10} minutes.`)
138
+ if (open(page, env)) out('(Opened it in your browser.)')
139
+ }
140
+ let first = approvedHere
111
141
  const deadline = Date.now() + Math.min(Math.max(Number(expiresIn) || 600, 1), 3600) * 1000
112
142
  for (;;) {
113
143
  if (signal?.aborted) throw new Error('Login cancelled.')
114
- if (Date.now() > deadline) throw new Error('The code expired before anyone approved it. Run shapewall login again.')
144
+ if (Date.now() > deadline) throw new Error(`The code expired before anyone approved it. Run ${command} again for a new one.`)
115
145
  // 1 to 30 seconds whatever the server says (NaN would poll in a tight loop).
116
- await sleep(Math.min(Math.max(Number(interval) || 3, 1), 30) * 1000)
146
+ if (!first) await sleep(Math.min(Math.max(Number(interval) || 3, 1), 30) * 1000)
147
+ first = false
117
148
  let polled
118
149
  try {
119
150
  polled = await post(fetchImpl, origin, '/api/v1/device/poll', { deviceCode })
@@ -126,10 +157,14 @@ export async function login(
126
157
  continue
127
158
  }
128
159
  if (polled.status !== 200 || polled.data?.status !== 'approved') {
160
+ // The server's words name "shapewall login"; an expired code names the command that was run.
161
+ if (polled.status === 410 && polled.data?.error?.code === 'login_expired')
162
+ throw new Error(`The code expired before anyone approved it. Run ${command} again for a new one.`)
129
163
  throw new Error(terminalSafe(polled.data?.error?.message) || `The login did not finish (${polled.status}).`)
130
164
  }
131
165
  const result = polled.data
132
166
  if (typeof result.token !== 'string' || !/^swp_[A-Za-z0-9_-]{43}$/.test(result.token)) throw new Error('The server sent no token.')
167
+ if (onApproved) return onApproved(result, { origin, machine })
133
168
  const file = saveCredential(
134
169
  origin,
135
170
  {
@@ -287,7 +287,7 @@ async function runShare(
287
287
  'This token has no one-time import scope. Unset SHAPEWALL_TOKEN/--token-file, then run shapewall share to approve a moving-project login.',
288
288
  )
289
289
  out('Sign in to move a local project. Pick or create its destination and check the one-time Import box.')
290
- await loginImpl(flags, out, { env, fetchImpl, purpose: 'import', signal, ...(open ? { open } : {}) })
290
+ await loginImpl(flags, out, { env, fetchImpl, purpose: 'import', command: 'shapewall share', signal, ...(open ? { open } : {}) })
291
291
  settings = remoteSettings(flags, env)
292
292
  remote = createRemote({ ...settings, fetchImpl })
293
293
  project = await remote.project()