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,547 @@
1
+ // The command line on a server with tailnet sign-in (`shapewall hosted
2
+ // --tailscale --tailnet-sign-in`): where the machine's tailnet user is
3
+ // already known to the server, nothing needs a browser.
4
+ //
5
+ // shapewall login / agent connect approved by the tailnet identity (approveByTailnet)
6
+ // shapewall join take an invite (joinCommand)
7
+ // shapewall hosted claim the first account of a new server (claimCommand)
8
+ // shapewall admin ... a few admin commands (adminCommand)
9
+ //
10
+ // How: the CLI asks the server who it is (GET /auth/me). Tailscale's serve
11
+ // proxy adds the identity of the machine's user to the request; the server
12
+ // believes it only on a request that provably came through that proxy
13
+ // (src/hosted/tailnet-identity.js) and answers 'linked'. The CLI then signs in
14
+ // (POST /auth/tailnet/sign-in; a GET never makes a session) and is given a
15
+ // session cookie that works only together with that identity. The CLI then
16
+ // uses the same console API the browser uses, with that session: the same
17
+ // role checks, the same audit entries (marked as a tailnet session), and it
18
+ // signs out when the command ends. No token is stored for this.
19
+ //
20
+ // A tailnet identity is per device, not per person: whatever runs as you on
21
+ // a tailnet device of yours gets the same answer from the server as this
22
+ // command does. A workspace that wants more for approving machines switches
23
+ // on "Approve command line logins in the browser"; the server then refuses
24
+ // a session that only an identity stands behind, whatever the client sends.
25
+ //
26
+ // On any other server, and when the request did not come through the
27
+ // tailnet, nothing here applies: `login` and `agent connect` use the code
28
+ // and the browser as before, and the other commands say what they need.
29
+
30
+ import os from 'node:os'
31
+ import { readBounded, remoteOrigin } from './remote.js'
32
+ import { safeOut, terminalSafe } from './terminal.js'
33
+
34
+ const machineName = () => os.hostname().split('.')[0] || 'this computer'
35
+
36
+ // Any program on the server's machine can ask the server through its tailnet name and be answered as
37
+ // the machine's owner, so the server never takes an identity from its own machine.
38
+ const OWN_MACHINE =
39
+ 'This is the server’s own machine: the server never takes a tailnet identity from here (any program on this machine could ask the same way).'
40
+
41
+ // One CLI run's conversation with the server: keeps the cookies it is given.
42
+ export function tailnetClient(origin, { fetchImpl = fetch, machine = machineName() } = {}) {
43
+ const jar = new Map()
44
+ // confirm: what to say to a server that asks for a typed confirmation (--yes; see confirmed()).
45
+ let confirm = null
46
+ async function call(method, pathname, body) {
47
+ const response = await fetchImpl(`${origin}${pathname}`, {
48
+ method,
49
+ headers: {
50
+ Accept: 'application/json',
51
+ // The console API takes writes from its own origin only; this is the
52
+ // command line saying where it is talking to, not a browser.
53
+ Origin: origin,
54
+ 'Sec-Fetch-Site': 'same-origin',
55
+ 'X-Shapewall-Client': 'cli',
56
+ 'User-Agent': `shapewall-cli (${machine.replace(/[^\w .-]/g, '').slice(0, 40)})`,
57
+ ...(jar.size ? { Cookie: [...jar].map(([name, value]) => `${name}=${value}`).join('; ') } : {}),
58
+ ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
59
+ ...(confirm ? { 'X-Shapewall-Confirm': encodeURIComponent(confirm) } : {}),
60
+ },
61
+ body: body === undefined ? undefined : JSON.stringify(body),
62
+ redirect: 'error',
63
+ })
64
+ for (const line of response.headers.getSetCookie?.() || []) {
65
+ const pair = line.split(';')[0]
66
+ const index = pair.indexOf('=')
67
+ if (index < 1) continue
68
+ const name = pair.slice(0, index).trim()
69
+ const value = pair.slice(index + 1).trim()
70
+ if (!value || /max-age=0/i.test(line)) jar.delete(name)
71
+ else jar.set(name, value)
72
+ }
73
+ let data = null
74
+ try {
75
+ data = JSON.parse((await readBounded(response, 1024 * 1024)).toString('utf8'))
76
+ } catch {
77
+ data = null
78
+ }
79
+ return { status: response.status, data, ok: response.status >= 200 && response.status < 300 }
80
+ }
81
+ // One of the few things the server always asks about, on a server where Tailscale is the only sign-in:
82
+ // it answers confirm_required with the name to say (the workspace's, or the account's handle). With
83
+ // `yes` (--yes on the command line) the request is sent again saying it; without, the caller is told.
84
+ async function confirmed(send, { yes = false } = {}) {
85
+ const first = await send()
86
+ if (first.ok || first.data?.error?.code !== 'confirm_required' || typeof first.data.error.confirm !== 'string') return first
87
+ if (!yes) return { ...first, needsYes: first.data.error.confirm }
88
+ confirm = first.data.error.confirm
89
+ try {
90
+ return await send()
91
+ } finally {
92
+ confirm = null
93
+ }
94
+ }
95
+ return {
96
+ origin,
97
+ call,
98
+ confirmed,
99
+ get: (pathname) => call('GET', pathname),
100
+ post: (pathname, body = {}) => call('POST', pathname, body),
101
+ // Ends the session this run was given (best effort: it expires anyway).
102
+ signOut: () => call('POST', '/auth/logout', {}).catch(() => null),
103
+ }
104
+ }
105
+
106
+ // Who the server says this machine's user is.
107
+ // { mode: 'off' } no tailnet sign-in on this server (or it is not a Shapewall server)
108
+ // { mode: 'none' } tailnet sign-in, but this request names no person
109
+ // { mode: 'self' } this is the server's own machine: never taken by identity
110
+ // { mode: 'visitor', login, invites } a login without an account here
111
+ // { mode: 'account', login, me } signed in as the linked account
112
+ export async function whoAmI(client) {
113
+ let answer
114
+ try {
115
+ answer = await client.get('/auth/me')
116
+ } catch {
117
+ return { mode: 'off' }
118
+ }
119
+ let me = answer.data
120
+ if (!answer.ok || !me || typeof me !== 'object') return { mode: 'off' }
121
+ // A linked login: the server makes the session only for an explicit sign-in, never for the GET.
122
+ if (!me.user && me.tailnet?.state === 'linked') {
123
+ const signedIn = await client.post('/auth/tailnet/sign-in', {}).catch(() => null)
124
+ if (!signedIn?.ok) return { mode: 'none' }
125
+ const again = await client.get('/auth/me').catch(() => null)
126
+ if (!again?.ok || !again.data || typeof again.data !== 'object') return { mode: 'none' }
127
+ me = again.data
128
+ }
129
+ if (me.user && me.via === 'tailnet') return { mode: 'account', login: terminalSafe(me.tailnet?.linked || ''), me }
130
+ const state = me.tailnet?.state
131
+ if (state === 'unknown' || state === 'invited')
132
+ return { mode: 'visitor', login: terminalSafe(me.tailnet.login), invites: Array.isArray(me.tailnet.invites) ? me.tailnet.invites : [] }
133
+ if (state === 'self') return { mode: 'self' }
134
+ // 'changed': the login is linked here for another tailnet user than this one (nobody, like 'none').
135
+ if (state === 'none' || state === 'signed_out' || state === 'changed') return { mode: 'none' }
136
+ return { mode: 'off' }
137
+ }
138
+
139
+ const fold = (value) =>
140
+ String(value ?? '')
141
+ .trim()
142
+ .toLowerCase()
143
+ const quote = (value) => (/^[\w.@-]+$/.test(String(value)) ? String(value) : JSON.stringify(String(value)))
144
+ const errorOf = (answer, fallback) => terminalSafe(answer?.data?.error?.message) || fallback
145
+
146
+ // A workspace of the account, by --workspace (its id or its name). One
147
+ // workspace needs no flag. Never a prompt: several without the flag is an
148
+ // error that lists them with the flag to add.
149
+ export function pickWorkspace(workspaces, wanted, { flagHint = '' } = {}) {
150
+ const list = Array.isArray(workspaces) ? workspaces : []
151
+ if (wanted !== undefined && wanted !== null && wanted !== true) {
152
+ const found = list.filter((item) => item.id === wanted || fold(item.name) === fold(wanted))
153
+ if (found.length === 1) return found[0]
154
+ throw new Error(
155
+ found.length
156
+ ? `--workspace ${quote(wanted)} matches ${found.length} workspaces. Use an id: ${found.map((item) => item.id).join(', ')}`
157
+ : `No workspace "${terminalSafe(wanted)}" for this account. It is in: ${list.map((item) => terminalSafe(item.name)).join(', ') || 'none'}.`,
158
+ )
159
+ }
160
+ if (list.length === 1) return list[0]
161
+ if (!list.length) throw new Error('This account is in no workspace here.')
162
+ throw new Error(
163
+ `This account is in ${list.length} workspaces. Add one of:\n${list.map((item) => ` --workspace ${quote(item.name)}${flagHint}`).join('\n')}`,
164
+ )
165
+ }
166
+
167
+ // The project a login or an agent connection is for: --project (its slug,
168
+ // id or name) and, when the account may make tokens in several workspaces,
169
+ // --workspace. One project in all needs no flag.
170
+ export function pickProject(workspaces, flags) {
171
+ let list = Array.isArray(workspaces) ? workspaces : []
172
+ if (typeof flags.workspace === 'string') list = [pickWorkspace(list, flags.workspace)]
173
+ const all = list.flatMap((workspace) => (workspace.projects || []).map((project) => ({ workspace, project })))
174
+ const wanted = typeof flags.project === 'string' ? flags.project : null
175
+ const found = wanted
176
+ ? all.filter(({ project }) => project.id === wanted || fold(project.slug) === fold(wanted) || fold(project.name) === fold(wanted))
177
+ : all
178
+ if (found.length === 1) return found[0]
179
+ if (!all.length) throw new Error('There is no project to pick yet. Make one first: shapewall admin projects create "Name" --remote URL')
180
+ const lines = (found.length ? found : all).map(
181
+ ({ workspace, project }) =>
182
+ ` --project ${quote(project.slug || project.id)}${list.length > 1 || found.length > 1 ? ` --workspace ${quote(workspace.name)}` : ''} (${terminalSafe(project.name)} in ${terminalSafe(workspace.name)})`,
183
+ )
184
+ throw new Error(
185
+ wanted && !found.length
186
+ ? `No project "${terminalSafe(wanted)}" that this account may make tokens for. Use one of:\n${lines.join('\n')}`
187
+ : `Which project? Add the flags of one of these:\n${lines.join('\n')}`,
188
+ )
189
+ }
190
+
191
+ // What the browser's approval page ticks by default (client/src/console/pages/device.jsx).
192
+ export const LOGIN_SCOPES = ['read', 'reply', 'status', 'resolve', 'push']
193
+
194
+ // `shapewall login` / `agent connect`, after the login was started: approves
195
+ // it as the account the tailnet signs this machine's user in as, when there
196
+ // is one that may. Returns true when approved (the caller polls for the
197
+ // token as always); false when the code and the browser are needed, with
198
+ // the reason printed. A choice only flags can make is an Error.
199
+ export async function approveByTailnet({ origin, userCode, flags, purpose, agent, out, fetchImpl = fetch, machine = machineName() }) {
200
+ const client = tailnetClient(origin, { fetchImpl, machine })
201
+ const who = await whoAmI(client)
202
+ if (who.mode === 'self') {
203
+ out(OWN_MACHINE)
204
+ out('So this login is approved with the code, from another tailnet device (or with a passkey, where the server allows them):')
205
+ return false
206
+ }
207
+ if (who.mode === 'off' || who.mode === 'none') return false
208
+ if (who.mode === 'visitor') {
209
+ out(`This server signs tailnet users in, and ${who.login} has no account on it yet (shapewall join --remote ${origin}).`)
210
+ return false
211
+ }
212
+ try {
213
+ const looked = await client.post('/api/device/lookup', { code: userCode })
214
+ if (!looked.ok) return false
215
+ const workspaces = looked.data?.workspaces || []
216
+ if (!workspaces.length) {
217
+ out(`${who.login} may not make tokens in any workspace here (that takes the admin role), so someone who may approves it:`)
218
+ return false
219
+ }
220
+ const { workspace, project } = pickProject(workspaces, flags)
221
+ const body = { code: userCode, workspaceId: workspace.id, projectId: project.id }
222
+ if (purpose === 'agent') {
223
+ const audience = flags['used-by'] === undefined ? 'owner' : String(flags['used-by'])
224
+ if (!['owner', 'trusted'].includes(audience))
225
+ throw new Error(
226
+ '--used-by: "owner" (only you, the default) or "trusted" (everyone the project lets send work to an agent). Named members are picked in the console.',
227
+ )
228
+ body.agent = {
229
+ name: typeof flags.name === 'string' && flags.name.trim() ? flags.name.trim() : agent?.name || machine,
230
+ icon: typeof flags.icon === 'string' ? flags.icon : null,
231
+ tint: typeof flags.tint === 'string' ? flags.tint : null,
232
+ audience,
233
+ }
234
+ } else body.scopes = purpose === 'import' ? [...LOGIN_SCOPES, 'import'] : LOGIN_SCOPES
235
+ const approved = await client.post('/api/device/approve', body)
236
+ if (approved.ok) {
237
+ out(
238
+ `Approved by your tailnet identity (${who.login}) for ${terminalSafe(workspace.name)} / ${terminalSafe(project.name)}: no code, no browser.`,
239
+ )
240
+ return true
241
+ }
242
+ const code = approved.data?.error?.code
243
+ // The server decides (from the session, not from anything this command sends) whether a tailnet
244
+ // identity alone may approve: a workspace can want the code, the browser and a passkey.
245
+ if (['browser_approval_required', 'reauth_required', 'passkey_required'].includes(code)) {
246
+ out(
247
+ approved.data.error.stepUp === 'cliApproval' || code === 'browser_approval_required'
248
+ ? 'This workspace approves logins and agent connections in the browser, with a passkey, also from a tailnet machine:'
249
+ : 'This workspace asks for a passkey before it approves a machine, so it is approved in the browser:',
250
+ )
251
+ return false
252
+ }
253
+ // A refusal the browser would get too (a bad name or icon, a full project): said as it is.
254
+ throw new Error(errorOf(approved, `The server refused the approval (${approved.status}).`))
255
+ } finally {
256
+ await client.signOut()
257
+ }
258
+ }
259
+
260
+ // ---- shapewall join ------------------------------------------------------------
261
+
262
+ // An invite as given: the link (https://host/invite#code) or the code alone.
263
+ export function inviteCode(value) {
264
+ const text = String(value || '').trim()
265
+ const hash = text.indexOf('#')
266
+ const code = hash >= 0 ? text.slice(hash + 1) : text
267
+ return /^[A-Za-z0-9_-]{20,100}$/.test(code) ? code : null
268
+ }
269
+
270
+ async function describeWorkspace(client, workspaceId, out) {
271
+ const detail = await client.get(`/api/workspaces/${workspaceId}`)
272
+ if (!detail.ok) return
273
+ const { workspace, role, projects = [] } = detail.data
274
+ out(` ${terminalSafe(workspace.name)}: you are ${role === 'owner' || role === 'admin' ? 'an' : 'a'} ${role}.`)
275
+ if (!projects.length) out(' No projects yet.')
276
+ for (const project of projects) out(` ${terminalSafe(project.name)} ${client.origin}${project.boardUrl}`)
277
+ }
278
+
279
+ // `shapewall join --remote URL [--invite LINK|CODE]`. Returns the exit code.
280
+ export async function joinCommand(flags, print, { env = process.env, fetchImpl = fetch } = {}) {
281
+ const out = safeOut(print)
282
+ const origin = remoteOrigin(flags, env)
283
+ const client = tailnetClient(origin, { fetchImpl })
284
+ const invite = flags.invite === undefined ? null : inviteCode(flags.invite)
285
+ if (flags.invite !== undefined && !invite) throw new Error('--invite: an invite link (https://.../invite#...) or its code.')
286
+ const who = await whoAmI(client)
287
+ if (who.mode === 'off') {
288
+ out(`${origin} does not sign people in by tailnet identity: an account there needs a passkey, and a passkey is made in the browser.`)
289
+ out(`Open ${invite ? `${origin}/invite#${invite}` : `the invite link an admin sent you (or ${origin}/signin if you have an account)`}.`)
290
+ return 1
291
+ }
292
+ if (who.mode === 'self') {
293
+ out(OWN_MACHINE)
294
+ out(
295
+ `Run shapewall join on another tailnet device of yours, or open ${invite ? `${origin}/invite#${invite}` : origin} in a browser there.`,
296
+ )
297
+ return 1
298
+ }
299
+ if (who.mode === 'none') {
300
+ out('The server could not tell who you are: this request did not come through the tailnet from a device that belongs to a person')
301
+ out('(a tagged device and a node shared in without a user are never signed in). Use the invite link in a browser instead.')
302
+ return 1
303
+ }
304
+ try {
305
+ let joined = []
306
+ if (who.mode === 'account' && invite) {
307
+ const accepted = await client.post('/api/invites/accept', { token: invite })
308
+ if (!accepted.ok) throw new Error(errorOf(accepted, `The invite was refused (${accepted.status}).`))
309
+ joined = [accepted.data.workspaceId]
310
+ } else {
311
+ if (who.mode === 'visitor' && !invite && !who.invites.length) {
312
+ out(`No invite is waiting for ${who.login} on ${origin}.`)
313
+ out(
314
+ `Ask an admin of a workspace there to invite you: shapewall admin invites create --login ${who.login} --role member --remote ${origin}`,
315
+ )
316
+ out('(They also see you under Members, "Arrived through the tailnet". You cannot join a workspace that did not invite you.)')
317
+ return 1
318
+ }
319
+ const answer = await client.post('/auth/tailnet/join', invite ? { invite } : {})
320
+ if (!answer.ok) throw new Error(errorOf(answer, `Joining was refused (${answer.status}).`))
321
+ joined = answer.data.joined || (answer.data.workspaceId ? [answer.data.workspaceId] : [])
322
+ if (who.mode === 'visitor')
323
+ out(`Made your account on ${origin}: @${terminalSafe(answer.data.user?.handle)}, signed in by your tailnet login ${who.login}.`)
324
+ }
325
+ if (!joined.length) {
326
+ out(`No invite is waiting for ${who.login} on ${origin}; nothing changed.`)
327
+ return 1
328
+ }
329
+ out(`Joined as ${who.login}:`)
330
+ for (const id of joined) await describeWorkspace(client, id, out)
331
+ out('The role is the one the invite gave. Your Tailscale account is the sign-in here, from every tailnet device of yours.')
332
+ return 0
333
+ } finally {
334
+ await client.signOut()
335
+ }
336
+ }
337
+
338
+ // ---- shapewall hosted claim ---------------------------------------------------
339
+
340
+ // `shapewall hosted claim --data DIR [--workspace-name NAME] [--login LOGIN]`:
341
+ // the first account of a new tailnet server, without the browser. `setupUrl`
342
+ // is the one-time link from the data folder: only someone who can read that
343
+ // folder has it. Who the owner is comes from the request through the proxy;
344
+ // --login can only refuse another answer, never choose one.
345
+ export async function claimServer({ setupUrl, flags, out: print, fetchImpl = fetch }) {
346
+ const out = safeOut(print)
347
+ let url
348
+ try {
349
+ url = new URL(setupUrl)
350
+ } catch {
351
+ throw new Error('The setup link in the data folder is not a URL.')
352
+ }
353
+ const setup = new URLSearchParams(url.hash.slice(1)).get('setup')
354
+ if (!setup) throw new Error('The setup link in the data folder has no setup code.')
355
+ const origin = url.origin
356
+ const client = tailnetClient(origin, { fetchImpl })
357
+ const who = await whoAmI(client)
358
+ if (who.mode === 'off') {
359
+ out(`The server at ${origin} does not sign people in by tailnet identity (or it is not running).`)
360
+ out('Start it with --tailscale --tailnet-sign-in, or open the setup link in a browser and make the first account with a passkey.')
361
+ return 1
362
+ }
363
+ if (who.mode === 'self') {
364
+ out(OWN_MACHINE)
365
+ out(
366
+ 'On the server’s machine the data folder is the proof instead: shapewall hosted claim --data <dir> --login <the owner’s tailnet login>',
367
+ )
368
+ return 1
369
+ }
370
+ if (who.mode === 'none') {
371
+ out(
372
+ `The server at ${origin} could not tell who you are: the request must come through the tailnet from a device that belongs to a person.`,
373
+ )
374
+ out('Open the setup link in a browser on such a device instead (shapewall hosted setup-link).')
375
+ return 1
376
+ }
377
+ if (who.mode === 'account') {
378
+ await client.signOut()
379
+ out(`${who.login} already has an account on this server; a server is claimed once.`)
380
+ return 1
381
+ }
382
+ const wanted = typeof flags.login === 'string' ? flags.login.trim().toLowerCase() : null
383
+ if (wanted && wanted !== who.login) {
384
+ out(`The tailnet says you are ${who.login}, not ${terminalSafe(wanted)}. Nothing was claimed.`)
385
+ return 1
386
+ }
387
+ try {
388
+ const answer = await client.post('/auth/tailnet/join', {
389
+ setup,
390
+ ...(wanted ? { expectLogin: wanted } : {}),
391
+ ...(typeof flags['workspace-name'] === 'string' ? { workspaceName: flags['workspace-name'] } : {}),
392
+ })
393
+ if (!answer.ok) throw new Error(errorOf(answer, `The server refused the claim (${answer.status}).`))
394
+ out(`Claimed ${origin}.`)
395
+ out(` Owner: ${who.login} (account @${terminalSafe(answer.data.user?.handle)}), signed in by tailnet identity.`)
396
+ const detail = await client.get(`/api/workspaces/${answer.data.workspaceId}`)
397
+ if (detail.ok) out(` Workspace: ${terminalSafe(detail.data.workspace.name)} (you are its owner).`)
398
+ out(' The setup link is used up.')
399
+ const signedIn = await client.get('/auth/me')
400
+ if (signedIn.data?.passkeysOff) {
401
+ out('Your Tailscale account is the sign-in: no passkey was made and none is asked for. Deleting a workspace, changing owners')
402
+ out('and a few other things ask you to type a name to confirm (--yes on the command line).')
403
+ } else {
404
+ out(
405
+ `No passkey was made. Add one in the browser (${origin}/account) before you need it: deleting a workspace, changing owners and a few`,
406
+ )
407
+ out('other things always ask for one, and a first passkey can confirm them 24 hours after it is added (it signs in at once).')
408
+ }
409
+ out('Anything that runs as you on a tailnet device of yours can act as you here: your tailnet identity is per device, not per person.')
410
+ out(`Next: shapewall admin projects create "My site" --remote ${origin}`)
411
+ return 0
412
+ } finally {
413
+ await client.signOut()
414
+ }
415
+ }
416
+
417
+ // ---- shapewall admin ------------------------------------------------------------
418
+
419
+ const ADMIN_USAGE =
420
+ 'shapewall admin projects list|create NAME, admin invites create --login LOGIN|--link [--role ROLE] [--days N], admin members list, admin agents list (each with --remote URL, and --workspace NAME when you are in several)'
421
+
422
+ const table = (rows) => {
423
+ const widths = []
424
+ for (const row of rows) row.forEach((cell, index) => (widths[index] = Math.max(widths[index] || 0, String(cell).length)))
425
+ return rows.map(
426
+ (row) =>
427
+ ` ${row
428
+ .map((cell, index) => String(cell).padEnd(widths[index]))
429
+ .join(' ')
430
+ .trimEnd()}`,
431
+ )
432
+ }
433
+
434
+ // `shapewall admin <what> <action>`: a few of the console's admin pages from
435
+ // the command line, as the account the tailnet signs this machine's user in
436
+ // as. The server checks the role and writes the audit entry, as for the
437
+ // console. Returns the exit code.
438
+ export async function adminCommand(positional, flags, print, { env = process.env, fetchImpl = fetch } = {}) {
439
+ const out = safeOut(print)
440
+ const [what, action = 'list', ...rest] = positional
441
+ const known = { projects: ['list', 'create'], invites: ['create'], members: ['list'], agents: ['list'] }
442
+ if (!known[what] || !known[what].includes(action)) throw new Error(`Usage: ${ADMIN_USAGE}`)
443
+ const origin = remoteOrigin(flags, env)
444
+ const client = tailnetClient(origin, { fetchImpl })
445
+ const who = await whoAmI(client)
446
+ if (who.mode !== 'account') {
447
+ if (who.mode === 'off') {
448
+ out(
449
+ `${origin} does not sign people in by tailnet identity, so these commands would need an admin token, and admin tokens do not exist yet.`,
450
+ )
451
+ out(`Use the console: ${origin}/`)
452
+ } else if (who.mode === 'self') {
453
+ out(OWN_MACHINE)
454
+ out(`Run this on another tailnet device of yours, or use the console: ${origin}/`)
455
+ } else if (who.mode === 'visitor') out(`${who.login} has no account on ${origin} yet: shapewall join --remote ${origin}`)
456
+ else out('The server could not tell who you are: this request did not come through the tailnet from a device that belongs to a person.')
457
+ return 1
458
+ }
459
+ try {
460
+ const workspace = pickWorkspace(who.me.workspaces, flags.workspace)
461
+ const base = `/api/workspaces/${workspace.id}`
462
+ const refuse = (answer) => {
463
+ throw new Error(errorOf(answer, `The server refused (${answer.status}).`))
464
+ }
465
+ if (what === 'projects' && action === 'create') {
466
+ const name = rest.join(' ').trim() || (typeof flags.name === 'string' ? flags.name : '')
467
+ if (!name) throw new Error('admin projects create NAME: the name of the project.')
468
+ const made = await client.post(`${base}/projects`, { name })
469
+ if (!made.ok) refuse(made)
470
+ if (flags.json) out(JSON.stringify(made.data.project, null, 2))
471
+ else {
472
+ out(`Made the project "${terminalSafe(made.data.project.name)}" in ${terminalSafe(workspace.name)}.`)
473
+ out(` Board: ${origin}${made.data.project.boardUrl}`)
474
+ out(` Next: shapewall login --remote ${origin} --project ${quote(made.data.project.slug)}`)
475
+ }
476
+ return 0
477
+ }
478
+ if (what === 'invites') {
479
+ const role = flags.role === undefined ? 'member' : String(flags.role)
480
+ const login = typeof flags.login === 'string' ? flags.login.trim() : null
481
+ if (Boolean(login) === Boolean(flags.link))
482
+ throw new Error('admin invites create: --login LOGIN (for one tailnet login) or --link (a link anyone you send it to can use).')
483
+ const days = flags.days === undefined ? undefined : Number(flags.days)
484
+ const made = await client.confirmed(
485
+ () =>
486
+ client.post(`${base}/invites`, {
487
+ role,
488
+ ...(login ? { tailnetLogin: login } : {}),
489
+ ...(days === undefined ? {} : { expiresInDays: days }),
490
+ }),
491
+ { yes: Boolean(flags.yes) },
492
+ )
493
+ if (made.needsYes)
494
+ throw new Error(
495
+ `This invites ${role === 'owner' ? 'an owner' : `someone as ${role}`} to ${terminalSafe(workspace.name)}. Shapewall always asks before that: run the command again with --yes.`,
496
+ )
497
+ if (!made.ok) refuse(made)
498
+ if (flags.json) out(JSON.stringify({ invite: made.data.invite, ...(login ? {} : { url: made.data.url }) }, null, 2))
499
+ else if (login) {
500
+ out(
501
+ `Invited ${terminalSafe(made.data.invite.tailnetLogin)} to ${terminalSafe(workspace.name)} as ${role}. Only that tailnet login can take it.`,
502
+ )
503
+ out(` They run: shapewall join --remote ${origin} (or open ${origin}/ in a browser on the tailnet)`)
504
+ } else {
505
+ out(`An invite to ${terminalSafe(workspace.name)} as ${role}. Whoever has this link can use it once:`)
506
+ out(` ${made.data.url}`)
507
+ }
508
+ return 0
509
+ }
510
+ const detail = await client.get(base)
511
+ if (!detail.ok) refuse(detail)
512
+ if (what === 'projects') {
513
+ if (flags.json) out(JSON.stringify(detail.data.projects, null, 2))
514
+ else if (!detail.data.projects.length)
515
+ out(`No projects in ${terminalSafe(workspace.name)} yet. shapewall admin projects create "Name" --remote ${origin}`)
516
+ else
517
+ for (const line of table(detail.data.projects.map((item) => [terminalSafe(item.name), item.slug, `${origin}${item.boardUrl}`])))
518
+ out(line)
519
+ return 0
520
+ }
521
+ if (what === 'members') {
522
+ if (flags.json) out(JSON.stringify(detail.data.members, null, 2))
523
+ else
524
+ for (const line of table(detail.data.members.map((item) => [terminalSafe(item.displayName), `@${item.handle}`, item.role])))
525
+ out(line)
526
+ return 0
527
+ }
528
+ const agents = await client.get(`${base}/agents`)
529
+ if (!agents.ok) refuse(agents)
530
+ const list = agents.data.agents || []
531
+ if (flags.json) out(JSON.stringify(list, null, 2))
532
+ else if (!list.length) out(`No agents in ${terminalSafe(workspace.name)} yet. shapewall agent connect --remote ${origin}`)
533
+ else
534
+ for (const line of table(
535
+ list.map((item) => [
536
+ terminalSafe(item.name),
537
+ terminalSafe(item.projectName || ''),
538
+ terminalSafe(item.state || ''),
539
+ terminalSafe(item.machine || ''),
540
+ ]),
541
+ ))
542
+ out(line)
543
+ return 0
544
+ } finally {
545
+ await client.signOut()
546
+ }
547
+ }
package/src/server/app.js CHANGED
@@ -8,6 +8,7 @@ import { spawn } from 'node:child_process'
8
8
  import { randomBytes } from 'node:crypto'
9
9
  import { fileURLToPath } from 'node:url'
10
10
  import express from 'express'
11
+ import { SECRET_PREFIX } from '../tailnet-proof.js'
11
12
  import { boardViewports, frameScale, joinUrl, thumbScale } from '../config.js'
12
13
  import {
13
14
  CommentError,
@@ -187,6 +188,20 @@ export function createApp({
187
188
  if (buzzBridge) requireCleanBuzzEnvironment()
188
189
  const chatOn = chat && !readOnly
189
190
  const app = express()
191
+ // `serve --tailscale`: first, how the request came in. The serve entry's
192
+ // secret comes off its path here, and whether it is the owner by tailnet
193
+ // identity is worked out (src/tailnet-proof.js).
194
+ if (remote?.tailscale?.gate)
195
+ app.use((req, res, next) => {
196
+ remote.tailscale.gate.admit(req, res).then((ok) => {
197
+ if (!ok) return
198
+ // The listener takes the secret off before Express sees the request (src/cli/serve.js). Should this
199
+ // application be mounted another way, nothing after this line may see it either: Express kept the
200
+ // first URL as originalUrl, and redirects are built from that.
201
+ if (String(req.originalUrl || '').startsWith(SECRET_PREFIX)) req.originalUrl = req.url
202
+ next()
203
+ }, next)
204
+ })
190
205
  app.disable('x-powered-by')
191
206
  app.set('trust proxy', false)
192
207
  const children = new Set()
@@ -12,13 +12,28 @@ export function cookieValue(req, name) {
12
12
  }
13
13
  const loopback = (address) =>
14
14
  address === '::1' || /^127\.\d+\.\d+\.\d+$/.test(address || '') || /^::ffff:127\.\d+\.\d+\.\d+$/.test(address || '')
15
+ // The board's owner, arriving from another of their tailnet devices. The
16
+ // Tailscale-User-Login header alone proves nothing: any program on this
17
+ // machine (an agent whose command waits for approval included) can send it
18
+ // to the loopback port. It counts only on a request the identity proof let
19
+ // through (src/tailnet-proof.js: the serve entry's secret, a connection
20
+ // owned by tailscaled, tailscaled's own whois; `tailscale.gate`, made in
21
+ // src/server/tailscale.js and asked for every request in src/server/app.js).
22
+ // No gate (the proof is not possible here), no identity: such devices pair.
15
23
  export function ownerIdentity(req, tailscale) {
16
- if (!tailscale?.ownerLogin || !tailscale.host || tailscale.noIdentity) return false
24
+ if (!tailscale?.ownerLogin || !tailscale.host || tailscale.noIdentity || !tailscale.gate) return false
17
25
  if (!loopback(req.socket?.remoteAddress)) return false
18
26
  const host = String(req.headers.host || '')
19
27
  .toLowerCase()
20
28
  .replace(/:\d+$/, '')
21
- return host === tailscale.host && req.headers['tailscale-user-login'] === tailscale.ownerLogin
29
+ const identity = tailscale.gate.identityOf(req)
30
+ // The owner's login, and the same tailnet user as the one this node belongs to.
31
+ return (
32
+ host === tailscale.host &&
33
+ identity?.login === String(tailscale.ownerLogin).toLowerCase() &&
34
+ Boolean(tailscale.ownerUserId) &&
35
+ identity.userId === tailscale.ownerUserId
36
+ )
22
37
  }
23
38
 
24
39
  // Before every board API and file route: there is one owner, never anonymous guests.
@@ -82,7 +97,15 @@ export function remoteAccess({
82
97
  router.get('/api/pairing', (req, res) => {
83
98
  const pairing = devices.poll(cookieValue(req, devices.pairCookie))
84
99
  if (pairing.state === 'approved') cookie(req, res, devices.cookie, cookieValue(req, devices.pairCookie), DEVICE_IDLE_MS)
85
- res.json({ enabled: true, secure: secure(req), access: req.shapewallAccess.kind, pairing })
100
+ res.json({
101
+ enabled: true,
102
+ secure: secure(req),
103
+ access: req.shapewallAccess.kind,
104
+ pairing,
105
+ // This browser is on the computer that runs Shapewall and came in through its tailnet name:
106
+ // the tailnet identity is never taken from here (src/tailnet-proof.js).
107
+ ownMachine: Boolean(tailscale?.gate?.ownMachine?.(req)),
108
+ })
86
109
  })
87
110
  router.post('/api/pairing', protectedWrite, express.json({ limit: '2kb' }), (req, res) => {
88
111
  try {
@@ -129,6 +152,14 @@ export function remoteAccess({
129
152
  const access = req.shapewallAccess
130
153
  // Express routes are case-insensitive by default; authorization must be too.
131
154
  const route = req.path.toLowerCase()
155
+ // Answering an agent's request to run a command or edit a file: the
156
+ // settings token from the host's own terminal, whatever the request
157
+ // looks like, unless it is the owner by proven tailnet identity or a
158
+ // device the owner paired (its own cookie, approved on the host). A
159
+ // local program cannot approve its own command by dressing a request up
160
+ // as coming from somewhere else.
161
+ if (/\/permissions\//.test(route) && !['identity', 'device'].includes(access.kind) && !settingsTokenOk(req, token))
162
+ return fail(res, 403, 'host_only', 'Use the settings link on the host computer to approve commands.')
132
163
  if (access.kind === 'nobody') {
133
164
  if (route.startsWith('/api/')) return fail(res, 401, 'pairing_required', 'Pair this device on the computer running Shapewall.')
134
165
  // Only the application shell and public static assets. Captures and data never pass this gate.
@@ -145,8 +176,6 @@ export function remoteAccess({
145
176
  } else if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method)) {
146
177
  if (!sameOriginWrite(req)) return fail(res, 403, 'bad_origin', 'Use the board page itself.')
147
178
  }
148
- if (access.kind === 'host' && /\/permissions\//.test(route) && !settingsTokenOk(req, token))
149
- return fail(res, 403, 'host_only', 'Use the settings link on the host computer to approve commands.')
150
179
  if (access.kind !== 'host' && route.startsWith('/api/agent/')) {
151
180
  if (noRemoteChat && !route.startsWith('/api/agent/settings'))
152
181
  return fail(res, 403, 'remote_chat_disabled', 'Chat from other devices is off (--no-remote-chat).')