pisha-server 0.0.0-stage → 0.0.11

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 (125) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +40 -2
  3. package/accounts/accounts.js +754 -0
  4. package/accounts/index.js +1 -0
  5. package/accounts/passwords.js +41 -0
  6. package/accounts/totp.js +54 -0
  7. package/boards/boards.js +1079 -0
  8. package/boards/github.js +212 -0
  9. package/boards/index.js +1 -0
  10. package/boards/sync.js +980 -0
  11. package/companies.js +294 -0
  12. package/company-export.js +101 -0
  13. package/company.js +79 -0
  14. package/dashboard/dashboard.js +407 -0
  15. package/dashboard/index.js +1 -0
  16. package/data-upgrade.js +69 -0
  17. package/install/linux.sh +181 -0
  18. package/install/macos.sh +121 -0
  19. package/install/windows.bat +54 -0
  20. package/machines/index.js +3 -0
  21. package/machines/machines.js +910 -0
  22. package/messaging/inbox.js +252 -0
  23. package/messaging/index.js +3 -0
  24. package/messaging/messaging.js +551 -0
  25. package/messaging/plans.js +67 -0
  26. package/observation/index.js +1 -0
  27. package/observation/observation.js +224 -0
  28. package/organization/index.js +1 -0
  29. package/organization/organization.js +218 -0
  30. package/package.json +54 -4
  31. package/permissions/index.js +1 -0
  32. package/permissions/permissions.js +211 -0
  33. package/pisha-host.mjs +3297 -0
  34. package/pisha-host.mjs.sig +1 -0
  35. package/platform/acme.js +207 -0
  36. package/platform/basics.js +14 -0
  37. package/platform/config.js +154 -0
  38. package/platform/control.js +93 -0
  39. package/platform/credentials.js +151 -0
  40. package/platform/database.js +251 -0
  41. package/platform/errors.js +13 -0
  42. package/platform/files.js +50 -0
  43. package/platform/http.js +207 -0
  44. package/platform/index.js +58 -0
  45. package/platform/limits.js +122 -0
  46. package/platform/listen.js +183 -0
  47. package/platform/roles.js +6 -0
  48. package/platform/stream.js +19 -0
  49. package/platform/text.js +83 -0
  50. package/platform/ws.js +186 -0
  51. package/routes.js +405 -0
  52. package/server.js +65 -0
  53. package/sessions/index.js +1 -0
  54. package/sessions/sessions.js +533 -0
  55. package/ui/LICENSE-affectui.txt +26 -0
  56. package/ui/addmachine.js +151 -0
  57. package/ui/api.js +20 -0
  58. package/ui/app.js +143 -0
  59. package/ui/attention.js +78 -0
  60. package/ui/back.js +166 -0
  61. package/ui/boards.js +958 -0
  62. package/ui/chat.js +388 -0
  63. package/ui/content.js +157 -0
  64. package/ui/dialogs.js +135 -0
  65. package/ui/doing.js +112 -0
  66. package/ui/dom.js +6 -0
  67. package/ui/ds-base.css +146 -0
  68. package/ui/ds-components.css +229 -0
  69. package/ui/fonts/LICENSE-space-grotesk.txt +93 -0
  70. package/ui/fonts/space-grotesk-latin-700-normal.woff2 +0 -0
  71. package/ui/fonts/space-grotesk-latin-ext-700-normal.woff2 +0 -0
  72. package/ui/format.js +25 -0
  73. package/ui/i18n.js +2093 -0
  74. package/ui/icons/apple-touch-icon.png +0 -0
  75. package/ui/icons/icon-192.png +0 -0
  76. package/ui/icons/icon-512.png +0 -0
  77. package/ui/icons/maskable-512.png +0 -0
  78. package/ui/icons.js +40 -0
  79. package/ui/inbox.js +535 -0
  80. package/ui/index.html +103 -0
  81. package/ui/machines.js +261 -0
  82. package/ui/manifest.webmanifest +16 -0
  83. package/ui/mosaic.js +189 -0
  84. package/ui/nav.js +141 -0
  85. package/ui/newteam.js +223 -0
  86. package/ui/org.js +653 -0
  87. package/ui/overlays.css +126 -0
  88. package/ui/palette.js +179 -0
  89. package/ui/people.js +370 -0
  90. package/ui/permissions.js +202 -0
  91. package/ui/qr.js +158 -0
  92. package/ui/router.js +171 -0
  93. package/ui/routes.js +46 -0
  94. package/ui/screen-boards.css +241 -0
  95. package/ui/screen-inbox.css +201 -0
  96. package/ui/screen-machines.css +76 -0
  97. package/ui/screen-mosaic.css +26 -0
  98. package/ui/screen-newteam.css +90 -0
  99. package/ui/screen-org.css +113 -0
  100. package/ui/screen-session.css +99 -0
  101. package/ui/screen-signin.css +28 -0
  102. package/ui/screen-team.css +80 -0
  103. package/ui/screen-teams.css +41 -0
  104. package/ui/session.js +42 -0
  105. package/ui/shell.css +122 -0
  106. package/ui/signin.js +120 -0
  107. package/ui/squads.js +370 -0
  108. package/ui/state.js +59 -0
  109. package/ui/stream.js +268 -0
  110. package/ui/styles.css +343 -0
  111. package/ui/team.js +115 -0
  112. package/ui/teams.js +58 -0
  113. package/ui/terminal.js +261 -0
  114. package/ui/theme.js +32 -0
  115. package/ui/timeline.js +163 -0
  116. package/ui/topbar.js +205 -0
  117. package/ui/voice-parse.js +98 -0
  118. package/ui/voice.js +320 -0
  119. package/vendor/InterVariable.woff2 +0 -0
  120. package/vendor/LICENSE-inter +92 -0
  121. package/vendor/LICENSE-xterm +21 -0
  122. package/vendor/README.md +8 -0
  123. package/vendor/addon-fit.js +2 -0
  124. package/vendor/xterm.css +218 -0
  125. package/vendor/xterm.js +2 -0
@@ -0,0 +1,910 @@
1
+ import {
2
+ createHash, randomBytes, createPublicKey, generateKeyPairSync, hkdfSync, diffieHellman, createCipheriv,
3
+ createDecipheriv,
4
+ } from 'node:crypto'
5
+ import {
6
+ bad, ApiError, allowServerWide, ipKey, cachedFile, now, sha256, serverBaseUrl, clientIp, refuseSocket, logError,
7
+ VERSION, cleanText, pathTooLong, cutText, acceptWebSocket, sameOrigin, trimSlashes, AGENTS,
8
+ } from '../platform/index.js'
9
+
10
+ const HOST_SCRIPT = [new URL('../../host/pisha-host.mjs', import.meta.url), new URL('../pisha-host.mjs', import.meta.url)]
11
+
12
+ // The installers that prepare a machine and run pisha-host (install/ in
13
+ // the repository, or next to this file in the Docker image).
14
+ export const INSTALLERS = { 'linux.sh': 'text/x-shellscript; charset=utf-8', 'macos.sh': 'text/x-shellscript; charset=utf-8', 'windows.bat': 'text/plain; charset=utf-8' }
15
+ const withSha = body => ({ sha: createHash('sha256').update(body).digest('hex') })
16
+ export const installer = name => cachedFile(new URL(`../../install/${name}`, import.meta.url), withSha) ?? cachedFile(new URL(`../install/${name}`, import.meta.url), withSha)
17
+ export const hostScript = () => {
18
+ for (const f of HOST_SCRIPT) {
19
+ const c = cachedFile(f, withSha)
20
+ if (c) return c
21
+ }
22
+ return null
23
+ }
24
+
25
+ export const hostSignature = () => {
26
+ for (const f of HOST_SCRIPT) {
27
+ const c = cachedFile(new URL(`${f.href}.sig`))
28
+ if (c) return c
29
+ }
30
+ return null
31
+ }
32
+
33
+ // Enrollment attempts: 10 a minute per address (IPv6 per /64). There is no
34
+ // overall cap on purpose: anyone could use it to block real enrollments, and
35
+ // codes are 40 bits, single use and valid 15 minutes, so guessing one is out
36
+ // of reach even from many addresses.
37
+ export const enrollmentKey = code => sha256(String(code ?? '').trim().toUpperCase())
38
+ export function checkEnrollRate(req) {
39
+ if (!allowServerWide('enroll', ipKey(clientIp(req)), 10)) throw new ApiError(429, 'Too Many Requests: retry in a minute')
40
+ }
41
+
42
+ // What a socket says it comes with: as subprotocols, the only thing a browser
43
+ // can set on one.
44
+ const offeredProtocols = req => String(req.headers['sec-websocket-protocol'] ?? '').split(',').map(x => x.trim())
45
+ export const offeredCredential = req => offeredProtocols(req).find(x => x.startsWith('auth.'))?.slice('auth.'.length) ?? ''
46
+
47
+ export function createMachines(platform, { sessions, observation, permissions }) {
48
+ const {
49
+ bus, db, broadcast, SERVER_KEY, joinToken, signAsServer, allow, takeChallenge, proofIsGood, credentialPrefix,
50
+ routeEnrollment, log, companyId, audit,
51
+ } = platform
52
+ const {
53
+ NAME_RE, roleOf, checkApproval, isOnline, keyRefused, holdsName, leases, linksOf, register, dropLease,
54
+ } = sessions
55
+ const { activityOf } = observation
56
+
57
+ // A persona: a skill or an agent a session follows (its machine found it in
58
+ // the session's folder, or in that user's ~/.claude). Its id on the machine:
59
+ const PERSONA_ID_RE = /^(skill|agent):(project|user):[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
60
+
61
+ // A coordinator giving one of its workers a new task, unrelated to the last
62
+ // one, can have the worker's context cleared first: lighter (cheaper) turns
63
+ // from then on. Claude can't clear its own context, so the worker's machine
64
+ // types /clear in its terminal, as the user would, and the worker's plugin
65
+ // confirms it (its SessionStart "clear" event). Only the coordinator's own
66
+ // worker, opened from the dashboard, connected and idle, once a minute.
67
+ const FRESH_WAIT_MS = Number(process.env.PISHA_FRESH_WAIT_MS ?? 20_000)
68
+ const freshWaiters = new Map() // worker -> resolve(confirmed)
69
+ bus.on('context-cleared', name => freshWaiters.get(name)?.(true))
70
+ // Codex CLI and Grok CLI are started again instead (the machine says so):
71
+ // a new plugin instance of the worker taking its name after it was asked
72
+ // confirms it.
73
+ const restarting = new Set()
74
+ const startedAt = new Map() // worker being cleared -> when it last started
75
+ bus.on('instance-started', name => {
76
+ if (!freshWaiters.has(name)) return
77
+ startedAt.set(name, Date.now())
78
+ if (restarting.has(name)) freshWaiters.get(name)(true)
79
+ })
80
+ async function freshStart(name, p) {
81
+ const worker = String(p.chat_id ?? '')
82
+ const no = (reason, text) => ({ cleared: false, reason, text })
83
+ if (!NAME_RE.test(worker)) throw bad('chat_id must be one of your workers')
84
+ const row = db.prepare('SELECT role, coordinator, host_id FROM identities WHERE name = ?').get(worker)
85
+ if (roleOf(name) !== 'coordinator' || row?.role !== 'worker' || row.coordinator !== name) return no('not_your_worker', `"${worker}" is not a worker of yours`)
86
+ checkApproval(name, worker, false)
87
+ if (!row.host_id || !hostLinks.has(row.host_id)) return no('no_machine', `"${worker}" was not opened from the dashboard, or its machine is not connected: nobody can type /clear in its terminal`)
88
+ if (!isOnline(worker)) return no('offline', `"${worker}" is not connected`)
89
+ const state = activityOf(worker).state
90
+ if (state !== 'idle') return no('busy', state === 'unknown' ? `what "${worker}" is doing is not known (its observation is off)` : `"${worker}" is not idle right now (${state})`)
91
+ if (freshWaiters.has(worker)) return no('busy', `"${worker}" is being cleared already`)
92
+ if (!allow('fresh', worker, 1, 60_000)) return no('too_soon', `"${worker}" was cleared less than a minute ago`)
93
+ const confirmed = new Promise(resolve => freshWaiters.set(worker, resolve))
94
+ const timer = setTimeout(() => freshWaiters.get(worker)?.(false), FRESH_WAIT_MS)
95
+ try {
96
+ const asked = Date.now()
97
+ try {
98
+ const reply = await askHost(row.host_id, { t: 'clear', term: worker, coordinator: name })
99
+ if (reply?.restarted === true) {
100
+ restarting.add(worker)
101
+ if ((startedAt.get(worker) ?? 0) >= asked) freshWaiters.get(worker)?.(true)
102
+ }
103
+ } catch (err) {
104
+ return no('machine_refused', `its machine did not clear it: ${err.message.replace(/^(Bad Request|Conflict): /, '')}`)
105
+ }
106
+ if (await confirmed) {
107
+ log(`"${name}" cleared the context of its worker "${worker}"`)
108
+ return { cleared: true }
109
+ }
110
+ return no('not_confirmed', `/clear was typed in the terminal of "${worker}" but it didn't confirm it within ${Math.round(FRESH_WAIT_MS / 1000)} s`)
111
+ } finally {
112
+ clearTimeout(timer)
113
+ freshWaiters.delete(worker)
114
+ restarting.delete(worker)
115
+ startedAt.delete(worker)
116
+ }
117
+ }
118
+
119
+ const machineMethods = {
120
+ freshStart,
121
+ }
122
+
123
+ // The user's answer to a question a coordinator left in their inbox, typed in
124
+ // that coordinator's terminal by its machine: it reaches it as the user's own
125
+ // words, not as a message from another session.
126
+ async function typeAnswer(coordinator, text) {
127
+ const row = db.prepare('SELECT host_id FROM identities WHERE name = ?').get(coordinator)
128
+ const link = row?.host_id ? hostLinks.get(row.host_id) : null
129
+ const conflict = (reason, text) => new ApiError(409, `Conflict: ${text}`, { parameters: { reason } })
130
+ if (!link) throw conflict('no_machine', `"${coordinator}" was not opened from the dashboard, or its machine is not connected: answer in its session`)
131
+ if (!link.info?.answers) throw conflict('old_machine', `the machine of "${coordinator}" is too old to type answers: update it, or answer in its session`)
132
+ if (!link.info.allow_input) throw conflict('typing_off', `the machine of "${coordinator}" doesn't let the dashboard type in its sessions: answer there`)
133
+ try {
134
+ await askHost(row.host_id, { t: 'answer', term: coordinator, text })
135
+ } catch (err) {
136
+ if (err instanceof ApiError && err.code !== 400) throw err
137
+ throw conflict('machine_refused', `its machine did not type it: ${err.message.replace(/^(Bad Request|Conflict): /, '')}`)
138
+ }
139
+ }
140
+
141
+ // A host is pisha-host running on a machine. It joins with a one-time code
142
+ // the dashboard generates (POST /host/enroll), gets its own secret, and keeps a
143
+ // WebSocket open to /host/connect. Through it the server can only ask for a
144
+ // session *spec* (name, role, folder, compact window, persona id) — the host validates it
145
+ // against its own local rules and always runs the same fixed command — and
146
+ // relay terminal output and keystrokes for the dashboard's web terminal.
147
+ //
148
+ // Sessions are never opened by Claude: only the dashboard (the user) can.
149
+ const ENROLL_TTL_MS = 15 * 60 * 1000
150
+ const HOST_REPLY_TIMEOUT_MS = 20_000
151
+ const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789' // no 0/O, 1/I
152
+ const hostLinks = new Map() // host id -> { ws, info, connectedAt, pending: Map(req -> {resolve, reject, timer}), viewers: Map(term -> Set(viewer)) }
153
+ let hostReqSeq = 0
154
+
155
+ function hostRow(id) {
156
+ return db.prepare('SELECT * FROM hosts WHERE id = ?').get(id)
157
+ }
158
+
159
+ function hostView(row) {
160
+ const link = hostLinks.get(row.id)
161
+ let info = null
162
+ try { info = link?.info ?? JSON.parse(row.info ?? 'null') } catch {}
163
+ return {
164
+ id: row.id,
165
+ name: row.name,
166
+ created_at: row.created_at,
167
+ last_seen_at: link ? now() : row.last_seen_at,
168
+ online: !!link,
169
+ // Enrolled but never connected (it failed, or was never started).
170
+ pending: !link && row.first_connected_at == null,
171
+ connected_since: link?.connectedAt ?? null,
172
+ enrollment: row.enrollment ?? null, // which "Add machine" code it used
173
+ info,
174
+ }
175
+ }
176
+
177
+ const listHosts = () => db.prepare('SELECT * FROM hosts ORDER BY name').all().map(hostView)
178
+
179
+ function broadcastHost(id) {
180
+ const row = hostRow(id)
181
+ broadcast('host', row ? hostView(row) : { id, removed: true })
182
+ }
183
+
184
+ function enrollCode() {
185
+ const bytes = randomBytes(8)
186
+ const chars = [...bytes].map(b => CODE_ALPHABET[b % CODE_ALPHABET.length]).join('')
187
+ return `${chars.slice(0, 4)}-${chars.slice(4)}`
188
+ }
189
+
190
+ // Dashboard: a one-time code, valid 15 minutes, and the command to run on the machine.
191
+ function createEnrollment(p, req) {
192
+ const name = String(p.name ?? '').trim()
193
+ if (name && !/^[\p{L}\p{N} ._-]{1,40}$/u.test(name)) throw bad('the name may have letters, digits, spaces, dots, dashes and underscores (max 40)')
194
+ const code = enrollCode()
195
+ const t = now()
196
+ db.prepare('DELETE FROM host_enrollments WHERE expires_at < ?').run(t)
197
+ // (A random id, not derived from the code: the dashboard tells the machine
198
+ // that used this very code from any other one that connects.)
199
+ const ticket = randomBytes(12).toString('hex')
200
+ db.prepare('INSERT INTO host_enrollments (code_hash, name, created_at, expires_at, configure_plugin, ticket) VALUES (?, ?, ?, ?, ?, ?)')
201
+ .run(enrollmentKey(code), name, t, t + ENROLL_TTL_MS, p.configure_plugin === true ? 1 : 0, ticket)
202
+ routeEnrollment(enrollmentKey(code), t + ENROLL_TTL_MS)
203
+ const base = serverBaseUrl(req)
204
+ const q = s => `'${String(s).replace(/'/g, `'\\''`)}'` // always a single shell word
205
+ const ps = s => `'${String(s).replace(/'/g, "''")}'`
206
+ // The command checks the program it downloads against this server's copy
207
+ // (sha256sum on Linux, shasum on macOS) before running it.
208
+ const sha = hostScript()?.sha ?? null
209
+ // (A company's machine gets its own copy of everything: see pisha-host.)
210
+ const company = credentialPrefix ? ` --company=${companyId}` : ''
211
+ const check = (sum, file) => (sum ? ` && echo ${q(`${sum} ${file}`)} | (sha256sum -c - 2>/dev/null || shasum -a 256 -c -)` : '')
212
+ // Downloaded, checked and only then run; and the code in a file (printf is
213
+ // part of the shell): a program's arguments can be read by anyone on the machine.
214
+ const unix = file => `cd "$(mktemp -d)" && curl -fsSLo install.sh ${q(`${base}/install/${file}`)}${check(installer(file)?.sha, 'install.sh')} && printf %s ${q(code)} > code && bash install.sh ${q(base)} --code-file code${sha ? ` --sha256 ${sha}` : ''} --server-key=${SERVER_KEY.hash}${company}`
215
+ const bat = '"$d\\pisha-install.bat"'
216
+ return {
217
+ code,
218
+ enrollment: ticket,
219
+ expires_at: t + ENROLL_TTL_MS,
220
+ server_url: base,
221
+ sha256: sha,
222
+ server_key: SERVER_KEY.hash,
223
+ // The Pisha plugin release that goes with this server (pisha-host pins the same one).
224
+ plugin_command: `claude plugin marketplace add roke22/pisha#v${VERSION} && claude plugin install pisha@pisha`,
225
+ // One command per system: the installer prepares the machine (tmux, Node,
226
+ // Claude Code) and runs pisha-host with this code. (Windows: inside WSL.)
227
+ install: {
228
+ linux: unix('linux.sh'),
229
+ macos: unix('macos.sh'),
230
+ // (PowerShell's quotes. "--server-key x", not "=": a .bat splits its arguments at "=".)
231
+ windows: `[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072; $d = Join-Path $env:TEMP ([guid]::NewGuid()); New-Item -ItemType Directory $d | Out-Null; irm ${ps(`${base}/install/windows.bat`)} -OutFile ${bat}; if ((Get-FileHash ${bat} -Algorithm SHA256).Hash -ne ${ps(installer('windows.bat')?.sha ?? '')}) { throw 'the installer does not match the checksum the dashboard gave' }; $env:PISHA_ENROLL_CODE = ${ps(code)}; & ${bat} ${ps(base)} --linux-sha256 ${installer('linux.sh')?.sha ?? ''}${sha ? ` --sha256 ${sha}` : ''} --server-key ${SERVER_KEY.hash}${credentialPrefix ? ` --company ${companyId}` : ''}`,
232
+ },
233
+ // Just pisha-host, on a machine that already has what it needs.
234
+ // Downloaded into a new private folder: nobody can swap the file between the check and the run.
235
+ command: `cd "$(mktemp -d)" && curl -fsSLo pisha-host.mjs ${q(`${base}/host/pisha-host.mjs`)}${check(sha, 'pisha-host.mjs')} && printf %s ${q(code)} > code && node pisha-host.mjs enroll ${q(base)} --code-file=code --server-key=${SERVER_KEY.hash}${company}`,
236
+ }
237
+ }
238
+
239
+ // Whoever could make codes lost access: those not used yet stop working.
240
+ const cancelEnrollments = () => db.prepare('DELETE FROM host_enrollments').run()
241
+
242
+ function enrollHost(p, req) {
243
+ const ip = clientIp(req)
244
+ const t = now()
245
+ const row = db.prepare('SELECT * FROM host_enrollments WHERE code_hash = ?').get(enrollmentKey(p.code))
246
+ if (!row || row.expires_at < t) {
247
+ throw new ApiError(403, 'Forbidden: the code is wrong or has expired; generate a new one in the dashboard (Machines → + Add machine)')
248
+ }
249
+ // A copy of pisha-host set up for another company (without what the
250
+ // dashboard's command says, say) would use another's folder.
251
+ // (Older ones don't say, and only a company's own copy keeps its sessions apart:
252
+ // the command for one always downloads this server's pisha-host.)
253
+ if (String(p.company ?? (credentialPrefix ? '' : companyId)) !== companyId) throw new ApiError(403, 'Forbidden: this code is for another company: run the whole command the dashboard gives')
254
+ db.prepare('DELETE FROM host_enrollments WHERE code_hash = ?').run(row.code_hash) // single use
255
+ const id = `h_${randomBytes(8).toString('hex')}`
256
+ const info = ownTerminals(sanitizeHostInfo(p.info), id)
257
+ const secret = `sh_${credentialPrefix}${randomBytes(32).toString('base64url')}`
258
+ // The hostname comes from the machine: keep only the characters a name may have.
259
+ const fromHost = String(info?.hostname ?? '').replace(/[^\p{L}\p{N} ._-]/gu, '').trim().slice(0, 40)
260
+ const name = row.name || fromHost || id
261
+ db.prepare('INSERT INTO hosts (id, name, secret_hash, created_at, last_seen_at, info, enrollment) VALUES (?, ?, ?, ?, ?, ?, ?)')
262
+ .run(id, uniqueHostName(name), sha256(secret), t, t, JSON.stringify(info), row.ticket ?? null)
263
+ broadcastHost(id)
264
+ log(`host "${hostRow(id).name}" (${id}) enrolled from ${ip}`)
265
+ return {
266
+ id, secret, name: hostRow(id).name,
267
+ // The plugin's server address always; the join token only if the admin
268
+ // asked for it (sessions opened from the dashboard don't need it: their
269
+ // names are registered by the server).
270
+ plugin: { url: serverBaseUrl(req), ...(row.configure_plugin ? { token: joinToken().token } : {}) },
271
+ }
272
+ }
273
+
274
+ function uniqueHostName(name) {
275
+ let candidate = name.slice(0, 40)
276
+ for (let i = 2; db.prepare('SELECT 1 FROM hosts WHERE name = ?').get(candidate); i++) candidate = `${name.slice(0, 36)}-${i}`
277
+ return candidate
278
+ }
279
+
280
+ // What a host says about itself is shown in the dashboard: keep it small and typed.
281
+ function sanitizeHostInfo(info) {
282
+ if (!info || typeof info !== 'object') return null
283
+ const str = (v, n = 200) => typeof v === 'string' ? cutText(cleanText(v.slice(0, n * 2)), n) : null
284
+ const terminals = (Array.isArray(info.terminals) ? info.terminals : []).slice(0, 64).map(t => ({
285
+ id: str(t?.id, 40),
286
+ // A terminal is shown by its session's name, which is its id (a machine
287
+ // can't label one of its terminals as another machine's session).
288
+ name: str(t?.id, 40),
289
+ role: ['coordinator', 'worker', 'solo'].includes(t?.role) ? t.role : null,
290
+ agent: AGENTS.includes(t?.agent) ? t.agent : 'claude',
291
+ coordinator: str(t?.coordinator, 40),
292
+ folder: str(t?.folder, 500),
293
+ compact_window: Number.isInteger(t?.compact_window) ? t.compact_window : null,
294
+ persona: t?.persona && PERSONA_ID_RE.test(String(t.persona.id)) && ['skill', 'agent'].includes(t.persona.kind)
295
+ ? { id: t.persona.id, kind: t.persona.kind, name: str(t.persona.name, 64) } : null,
296
+ created_at: Number.isFinite(t?.created_at) ? t.created_at : null,
297
+ // The permission profile it was opened with, by name (only for showing).
298
+ profile: str(t?.profile, 40),
299
+ })).filter(t => t.id && NAME_RE.test(t.id))
300
+ return {
301
+ hostname: str(info.hostname, 100),
302
+ machine: /^[0-9a-f]{16,64}$/.test(String(info.machine)) ? info.machine : null, // (its word: only for showing)
303
+ os_user: str(info.os_user, 64),
304
+ shares_user: info.shares_user === true,
305
+ platform: str(info.platform, 40),
306
+ arch: str(info.arch, 40),
307
+ node: str(info.node, 40),
308
+ tmux: str(info.tmux, 40),
309
+ claude: str(info.claude, 80),
310
+ // The agents it can run, each with its version (an older machine says
311
+ // nothing: Claude Code, as before).
312
+ agents: (Array.isArray(info.agents) ? info.agents : []).filter(a => AGENTS.includes(a?.id)).slice(0, 8).map(a => ({ id: a.id, version: str(a.version, 80) })),
313
+ version: str(info.version, 40),
314
+ folders: (Array.isArray(info.folders) ? info.folders : []).slice(0, 50).map(f => str(f, 500)).filter(Boolean),
315
+ home: str(info.home, 500),
316
+ // (Older machines don't say: their folders are changed there only.)
317
+ folders_from_dashboard: info.folders_from_dashboard === true,
318
+ max_sessions: Number.isInteger(info.max_sessions) ? info.max_sessions : null,
319
+ allow_input: info.allow_input !== false,
320
+ allow_resume: info.allow_resume === true, // (older machines don't say: taken as no)
321
+ answers: info.answers === true, // it types answers from the user's inbox (older machines can't)
322
+ // How far it takes permission profiles from the dashboard (older machines don't say: none).
323
+ permission_profiles: ['allow', 'restrict', 'off'].includes(info.permission_profiles) ? info.permission_profiles : null,
324
+ plugin: info.plugin && typeof info.plugin === 'object'
325
+ ? { installed: info.plugin.installed === true, enabled: info.plugin.enabled === true, version: str(info.plugin.version, 40) }
326
+ : null,
327
+ terminals,
328
+ }
329
+ }
330
+
331
+ // A machine can only list sessions it opened: a name the server reserved for
332
+ // another machine is dropped from what it says it runs.
333
+ function ownTerminals(info, hostId) {
334
+ if (!info) return info
335
+ info.terminals = info.terminals.filter(t => {
336
+ const owner = db.prepare('SELECT host_id FROM identities WHERE name = ?').get(t.id)?.host_id
337
+ return !owner || owner === hostId
338
+ })
339
+ return info
340
+ }
341
+
342
+ // Ask a connected host for something and wait for its reply.
343
+ function askHost(id, msg) {
344
+ const link = hostLinks.get(id)
345
+ if (!link) {
346
+ if (!hostRow(id)) throw bad('host not found')
347
+ throw new ApiError(409, 'Conflict: that machine is not connected right now', { parameters: { reason: 'host_offline' } })
348
+ }
349
+ const req = ++hostReqSeq
350
+ return new Promise((resolve, reject) => {
351
+ const timer = setTimeout(() => {
352
+ link.pending.delete(req)
353
+ reject(new ApiError(504, 'Gateway Timeout: the machine did not answer in time'))
354
+ }, HOST_REPLY_TIMEOUT_MS)
355
+ link.pending.set(req, { resolve, reject, timer })
356
+ link.ws.send(JSON.stringify({ ...msg, req }))
357
+ })
358
+ }
359
+
360
+ function dropHostLink(hostId, link) {
361
+ for (const p of link.pending.values()) { clearTimeout(p.timer); p.reject(new ApiError(502, 'Bad Gateway: the machine disconnected')) }
362
+ link.pending.clear()
363
+ for (const [term, set] of link.viewers) for (const v of set) { v.ws.send(JSON.stringify({ t: 'host_down', host: hostId, term })); v.attached.delete(`${hostId}\0${term}`); v.typed.delete(`${hostId}\0${term}`) }
364
+ link.viewers.clear()
365
+ }
366
+
367
+ function openHostLink(ws, req, row) {
368
+ let link = null
369
+ let hostId = null
370
+ const hello = setTimeout(() => ws.close(4000, 'hello expected'), 10_000)
371
+ // pisha-host pings every 25 s: a machine silent for 90 s is gone (it
372
+ // crashed, slept or lost its network without closing), not online.
373
+ let lastHeard = now()
374
+ const alive = setInterval(() => { if (now() - lastHeard > 90_000) ws.close(4008, 'nothing heard for 90 seconds') }, 30_000)
375
+ alive.unref?.()
376
+ ws.onactivity = () => { lastHeard = now() }
377
+ ws.onmessage = text => {
378
+ lastHeard = now()
379
+ let m
380
+ try { m = JSON.parse(text) } catch {}
381
+ if (!m || typeof m !== 'object' || Array.isArray(m)) return link ? undefined : ws.close(4000, 'hello expected')
382
+ if (!link) {
383
+ // (Authenticated when the socket was accepted: the hello carries its info.)
384
+ if (m.t !== 'hello') return ws.close(4000, 'hello expected')
385
+ // Disconnected from the dashboard meanwhile.
386
+ if (!db.prepare('SELECT 1 FROM hosts WHERE id = ?').get(row.id)) return ws.close(4001, 'unknown or disconnected host')
387
+ clearTimeout(hello)
388
+ ws.maxMessage = 8 * 1024 * 1024 // terminal screens can be large (pisha-host keeps them under 2 MB)
389
+ hostId = row.id
390
+ // One live connection per host: the newest wins. The old one is cleaned
391
+ // up first (its requests fail, its viewers are told).
392
+ const old = hostLinks.get(hostId)
393
+ if (old) { hostLinks.delete(hostId); dropHostLink(hostId, old); old.ws.close(4002, 'replaced by a newer connection') }
394
+ // A hello without info: until the machine sends it (right after the
395
+ // welcome), the last one known is shown.
396
+ let known = null
397
+ try { known = JSON.parse(row.info ?? 'null') } catch {}
398
+ link = { ws, info: ownTerminals(sanitizeHostInfo(m.info ?? known), row.id), connectedAt: now(), pending: new Map(), viewers: new Map() }
399
+ hostLinks.set(hostId, link)
400
+ db.prepare('UPDATE hosts SET last_seen_at = ?, info = ?, first_connected_at = COALESCE(first_connected_at, ?) WHERE id = ?').run(now(), JSON.stringify(link.info), now(), hostId)
401
+ ws.send(JSON.stringify({ t: 'welcome', host: { id: hostId, name: row.name } }))
402
+ log(`host "${row.name}" connected from ${req.socket.remoteAddress}`)
403
+ broadcastHost(hostId)
404
+ if (m.info) { link.listed = true; bus.emit('machine-listed', hostId, link.info) }
405
+ return
406
+ }
407
+ switch (m.t) {
408
+ case 'ping':
409
+ // (Answered: the machine notices a server that silently went away.
410
+ // Not to one that doesn't read its answers, and a few a minute.)
411
+ if (ws.buffered > 64 * 1024) break
412
+ if (allow('hostping', hostId, 30)) ws.send(JSON.stringify({ t: 'pong' }))
413
+ break
414
+ case 'info':
415
+ // pisha-host sends it when something changes: a machine sending
416
+ // it nonstop is ignored (each one is a database write and a broadcast).
417
+ if (!allow('hostinfo', hostId, 60)) break
418
+ link.info = ownTerminals(sanitizeHostInfo(m.info), hostId)
419
+ // (Its sessions, the first time since it connected: what changed while it was away.)
420
+ if (!link.listed) { link.listed = true; bus.emit('machine-listed', hostId, link.info) }
421
+ db.prepare('UPDATE hosts SET last_seen_at = ?, info = ? WHERE id = ?').run(now(), JSON.stringify(link.info), hostId)
422
+ broadcastHost(hostId)
423
+ break
424
+ case 'reply': {
425
+ const p = link.pending.get(m.req)
426
+ if (!p) break
427
+ link.pending.delete(m.req)
428
+ clearTimeout(p.timer)
429
+ // (Only text from the machine: anything else is its generic refusal.)
430
+ const why = typeof m.error === 'string' ? m.error : 'refused by the machine'
431
+ if (m.ok) p.resolve(m.result ?? true)
432
+ else p.reject(new ApiError(400, `Bad Request: ${cleanText(why.slice(0, 1000)).slice(0, 500)}`, { parameters: { reason: 'machine_refused' } }))
433
+ break
434
+ }
435
+ case 'screen': case 'out': case 'exit': case 'notice': {
436
+ if (typeof m.term !== 'string') break
437
+ const term = m.term
438
+ const set = link.viewers.get(term)
439
+ if (!set) break
440
+ const withData = m.t === 'out' || m.t === 'screen' // only output carries data
441
+ const out = JSON.stringify({ t: m.t, host: hostId, term, data: withData && typeof m.data === 'string' ? m.data : undefined, text: typeof m.text === 'string' ? cleanText(m.text.slice(0, 600)).slice(0, 300) : undefined })
442
+ for (const v of set) {
443
+ // A viewer that can't keep up misses output and gets a fresh screen later.
444
+ if (v.ws.buffered > 4 * 1024 * 1024) { if (withData) v.stale = true; continue }
445
+ // Caught up after missing output: ask the machine for a fresh screen.
446
+ if (v.stale && v.ws.buffered < 1024 * 1024) { v.stale = false; link.ws.send(JSON.stringify({ t: 'refresh', term })) }
447
+ if (link.viewers.get(term) !== set) break // (that send closed the machine's link: they were told)
448
+ v.ws.send(out)
449
+ }
450
+ if (m.t === 'exit') {
451
+ // That session is over: a later one of this name needs its own attach, written down.
452
+ for (const v of set) { v.attached.delete(`${hostId}\0${term}`); v.typed.delete(`${hostId}\0${term}`) }
453
+ link.viewers.delete(term)
454
+ }
455
+ break
456
+ }
457
+ }
458
+ }
459
+ ws.onclose = () => {
460
+ clearTimeout(hello)
461
+ clearInterval(alive)
462
+ if (!link || hostLinks.get(hostId) !== link) return
463
+ hostLinks.delete(hostId)
464
+ dropHostLink(hostId, link)
465
+ if (hostRow(hostId)) db.prepare('UPDATE hosts SET last_seen_at = ? WHERE id = ?').run(now(), hostId)
466
+ log(`host ${hostId} disconnected`)
467
+ broadcastHost(hostId)
468
+ }
469
+ }
470
+
471
+ // Dashboard web terminal: one WebSocket per browser tab, authenticated with
472
+ // the server token in its first message, multiplexing every terminal it shows.
473
+ function openViewerLink(ws, req, actor) {
474
+ // (Authenticated when the socket was accepted, with a one-time ticket,
475
+ // which says who asked for it: what is done here is theirs.)
476
+ const viewer = { ws, attached: new Set(), typed: new Set() }
477
+ ws.actor = actor
478
+ const who = actor?.email ?? `dashboard (${req.socket.remoteAddress})`
479
+ ws.maxMessage = 1024 * 1024 // (an image pasted into a terminal; text is at most 64 KB)
480
+ const detachAll = () => {
481
+ for (const key of viewer.attached) {
482
+ const [host, term] = key.split('\0')
483
+ detach(host, term)
484
+ }
485
+ viewer.attached.clear()
486
+ }
487
+ function detach(host, term) {
488
+ const link = hostLinks.get(host)
489
+ const set = link?.viewers.get(term)
490
+ if (!set) return
491
+ set.delete(viewer)
492
+ if (!set.size) { link.viewers.delete(term); link.ws.send(JSON.stringify({ t: 'detach', term })) }
493
+ }
494
+ const size = (c, r) => ({ cols: Math.floor(Math.max(20, Math.min(Number(c) || 120, 500))), rows: Math.floor(Math.max(5, Math.min(Number(r) || 36, 200))) })
495
+ ws.onmessage = text => {
496
+ let m
497
+ try { m = JSON.parse(text) } catch {}
498
+ if (!m || typeof m !== 'object' || Array.isArray(m)) return
499
+ const host = String(m.host ?? '')
500
+ const term = String(m.term ?? '')
501
+ const key = `${host}\0${term}`
502
+ const link = hostLinks.get(host)
503
+ // A dashboard can't make a machine work nonstop: at most 300 terminal
504
+ // messages every 10 seconds per dashboard socket.
505
+ const t = now()
506
+ viewer.msgTimes = (viewer.msgTimes ?? []).filter(x => t - x < 10_000)
507
+ if (viewer.msgTimes.length >= 300) return
508
+ viewer.msgTimes.push(t)
509
+ if (m.t === 'attach') {
510
+ if (!link) return ws.send(JSON.stringify({ t: 'host_down', host, term }))
511
+ if (!NAME_RE.test(term)) return
512
+ // Already watching it: a refresh at the new size, nothing else.
513
+ if (viewer.attached.has(key)) return link.ws.send(JSON.stringify({ t: 'resize', term, ...size(m.cols, m.rows) })), link.ws.send(JSON.stringify({ t: 'refresh', term }))
514
+ if (!link.viewers.has(term)) link.viewers.set(term, new Set())
515
+ link.viewers.get(term).add(viewer)
516
+ viewer.attached.add(key)
517
+ log(`${who} is viewing "${term}" on host ${host}`)
518
+ audit(actor, 'terminal-view', `${host}/${term}`, clientIp(req))
519
+ return link.ws.send(JSON.stringify({ t: 'attach', term, ...size(m.cols, m.rows) }))
520
+ }
521
+ if (!viewer.attached.has(key) || !link) return
522
+ if (m.t === 'detach') { viewer.attached.delete(key); viewer.typed.delete(key); return detach(host, term) }
523
+ if (m.t === 'resize') return link.ws.send(JSON.stringify({ t: 'resize', term, ...size(m.cols, m.rows) }))
524
+ if (m.t === 'refresh') { viewer.stale = false; return link.ws.send(JSON.stringify({ t: 'refresh', term })) }
525
+ const wroteDown = () => {
526
+ if (viewer.typed.has(key)) return
527
+ viewer.typed.add(key)
528
+ log(`${who} is typing in "${term}" on host ${host}`)
529
+ audit(actor ?? { token: true }, 'terminal-type', `${host}/${term}`, clientIp(req))
530
+ }
531
+ if (m.t === 'in' && typeof m.data === 'string' && m.data.length <= 64 * 1024) {
532
+ wroteDown()
533
+ return link.ws.send(JSON.stringify({ t: 'in', term, data: m.data }))
534
+ }
535
+ // An image pasted into the terminal: to the machine, which saves it and
536
+ // pastes its path into Claude Code (a few a minute per terminal).
537
+ if (m.t === 'image' && ['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(m.type) && typeof m.data === 'string' && m.data.length <= 800_000) {
538
+ if (!allow('paste-image', key, 20)) return ws.send(JSON.stringify({ t: 'notice', host, term, text: 'too many images pasted: wait a minute' }))
539
+ wroteDown()
540
+ return link.ws.send(JSON.stringify({ t: 'image', term, type: m.type, data: m.data }))
541
+ }
542
+ }
543
+ ws.onclose = () => detachAll()
544
+ ws.send(JSON.stringify({ t: 'ready' }))
545
+ }
546
+
547
+ function onUpgrade(req, socket, head) {
548
+ // Node hands the socket over without its error listener: a client that
549
+ // resets it after being refused must not raise an uncaught error.
550
+ socket.on('error', () => {})
551
+ // Nothing in a request can take the server down. An address that isn't
552
+ // even a URL is the client's mistake: refused, not logged.
553
+ try { upgrade(req, socket, head) } catch (err) {
554
+ if (err?.code === 'ERR_INVALID_URL') return refuseSocket(socket, '400 Bad Request')
555
+ logError(`bad upgrade request: ${err.message}`)
556
+ try { socket.destroy() } catch {}
557
+ }
558
+ }
559
+ function upgrade(req, socket, head) {
560
+ if (pathTooLong(req.url)) { refuseSocket(socket, '414 URI Too Long'); return }
561
+ const path = trimSlashes(new URL(req.url ?? '/', 'http://localhost').pathname)
562
+ // pisha-host never sends an Origin: a browser page can't hold machine slots.
563
+ if (path === '/host/connect' && req.headers.origin) { refuseSocket(socket, '403 Forbidden'); return }
564
+ if (path !== '/host/connect' && path !== '/api/terminal') {
565
+ refuseSocket(socket, '404 Not Found')
566
+ return
567
+ }
568
+ // The dashboard's terminal socket only from the dashboard's own page (a
569
+ // browser always sends Origin; pisha-host sends none).
570
+ if (path === '/api/terminal' && req.headers.origin && !sameOrigin(req)) { refuseSocket(socket, '403 Forbidden'); return }
571
+ // Authenticated before the socket is accepted, so nobody without a
572
+ // credential holds a connection open: the credential comes as a
573
+ // subprotocol ("pisha", "auth.<credential>"). The dashboard's is a
574
+ // one-time ticket (POST /api/terminal/ticket), and so is a machine's (POST
575
+ // /host/ticket); machines older than 0.0.7 send their secret here.
576
+ const offered = offeredProtocols(req)
577
+ const cred = offeredCredential(req)
578
+ // (Credentials are random, 192 bits or more: a wrong one costs one lookup.)
579
+ const refuse = (status, text) => refuseSocket(socket, `${status} ${text}`)
580
+ if (!offered.includes('pisha') || !cred) {
581
+ // pisha-host older than 0.0.2 (it sent its secret in a message): it is
582
+ // told why, in the close reason it prints, and the log says so (once a
583
+ // minute at most). The socket is closed at once.
584
+ if (path === '/host/connect' && req.headers.upgrade?.toLowerCase() === 'websocket') {
585
+ if (allowServerWide('old-host-log', 'all', 1)) log(`a pisha-host older than 0.0.2 tried to connect from ${req.socket.remoteAddress}: update it (see the README)`)
586
+ const old = acceptWebSocket(req, socket, head, { log: logError, maxMessage: 1024 })
587
+ old?.close(4426, 'this pisha-host is older than the server (0.0.2): update it: add the machine again from the dashboard (+ Add machine)')
588
+ return
589
+ }
590
+ return refuse(426, 'Upgrade Required')
591
+ }
592
+ let host = null
593
+ let ticketed = false
594
+ let linkKeys = null
595
+ let viewerTicket = null
596
+ if (path === '/host/connect') {
597
+ ticketed = cred.startsWith(HOST_TICKET_PREFIX)
598
+ if (ticketed) {
599
+ const taken = takeHostTicket(cred)
600
+ host = taken ? db.prepare('SELECT * FROM hosts WHERE id = ?').get(taken.host) : null
601
+ linkKeys = taken?.keys ?? null
602
+ } else host = db.prepare('SELECT * FROM hosts WHERE secret_hash = ?').get(sha256(cred))
603
+ // A machine reconnecting nonstop would write to the database and update
604
+ // every dashboard each time: at most 30 connections a minute.
605
+ if (host && !allow('hosthello', host.id, 30)) return refuse(429, 'Too Many Requests')
606
+ } else {
607
+ viewerTicket = takeTerminalTicket(cred)
608
+ if (!viewerTicket) return refuse(401, 'Unauthorized')
609
+ }
610
+ const ws = acceptWebSocket(req, socket, head, { log: logError, maxMessage: 16 * 1024, protocol: 'pisha' })
611
+ if (!ws) return
612
+ // A machine that was disconnected is told so (and stops), at once.
613
+ // (A ticket says nothing about the machine: lost in a restart of this
614
+ // server, say. It asks for another, which tells it if it was disconnected.)
615
+ if (path === '/host/connect' && !host && ticketed) { ws.close(4002, 'ticket expired: asking for another'); return }
616
+ if (path === '/host/connect' && !host) { ws.close(4001, 'unknown or disconnected host'); return }
617
+ // A machine that has proved its key doesn't connect with its secret alone,
618
+ // nor without the encrypted link that key gets it.
619
+ if (path === '/host/connect' && host.public_key && !linkKeys) { ws.close(4003, 'this machine has a key: update its pisha-host (0.0.7 or later)'); return }
620
+ if (linkKeys) encryptSocket(ws, linkKeys)
621
+ wsClients.add(ws)
622
+ if (path === '/host/connect') openHostLink(ws, req, host)
623
+ else openViewerLink(ws, req, viewerTicket.actor)
624
+ const handler = ws.onclose
625
+ ws.onclose = () => { wsClients.delete(ws); handler() }
626
+ }
627
+
628
+ // The same for a machine's link: 30 seconds, used once, for that machine.
629
+ const HOST_TICKET_PREFIX = 'ht_'
630
+ const hostTickets = new Map() // ticket -> { host, expires }
631
+ function newHostTicket(host, keys = null) {
632
+ for (const [t, v] of hostTickets) if (v.expires < Date.now()) hostTickets.delete(t)
633
+ if (hostTickets.size >= 1000) hostTickets.delete(hostTickets.keys().next().value)
634
+ const ticket = `${HOST_TICKET_PREFIX}${randomBytes(24).toString('base64url')}`
635
+ hostTickets.set(ticket, { host, keys, expires: Date.now() + 30_000 })
636
+ return ticket
637
+ }
638
+ function takeHostTicket(ticket) {
639
+ const v = hostTickets.get(ticket)
640
+ if (!v) return null
641
+ hostTickets.delete(ticket)
642
+ return v.expires >= Date.now() ? v : null
643
+ }
644
+
645
+ // A machine's ticket. With a proof of its key, the link it opens is encrypted
646
+ // between the two of them, whatever is on the way: the keys come from an
647
+ // exchange that this server signs and that machine proved it took part in.
648
+ function hostTicketAnswer(host, p) {
649
+ if (p.proof == null) {
650
+ if (host.public_key) throw keyRefused('this machine has a key, and this request doesn\'t prove it: update its pisha-host (0.0.7 or later)')
651
+ return { ticket: newHostTicket(host.id) }
652
+ }
653
+ const offered = String(p.key ?? '')
654
+ const eph = String(p.eph ?? '')
655
+ const fresh = takeChallenge(String(p.challenge ?? ''))
656
+ if (!fresh || !proofIsGood(offered, 'host-ticket', host.id, p.challenge, eph, p.proof)) throw keyRefused('this request does not prove the machine\'s key; try again')
657
+ if (host.public_key && host.public_key !== offered) throw keyRefused('this machine has a different key on this server. If it really lost its key, remove it in the dashboard and add it again; if not, something else may be using its secret')
658
+ let peer
659
+ try {
660
+ peer = createPublicKey({ key: Buffer.from(eph, 'base64url'), format: 'der', type: 'spki' })
661
+ if (peer.asymmetricKeyType !== 'x25519') throw new Error('not x25519')
662
+ } catch { throw bad('eph is not a key') }
663
+ if (!host.public_key) db.prepare('UPDATE hosts SET public_key = ? WHERE id = ?').run(offered, host.id)
664
+ const mine = generateKeyPairSync('x25519')
665
+ const myEph = mine.publicKey.export({ format: 'der', type: 'spki' }).toString('base64url')
666
+ const okm = Buffer.from(hkdfSync('sha256', diffieHellman({ privateKey: mine.privateKey, publicKey: peer }), String(p.challenge), `pisha-link-1|${eph}|${myEph}`, 64))
667
+ const ticket = newHostTicket(host.id, { fromHost: okm.subarray(0, 32), toHost: okm.subarray(32) })
668
+ return { ticket, eph: myEph, sig: signAsServer(['pisha-link-1', eph, myEph, String(p.challenge), ticket]) }
669
+ }
670
+
671
+ // Every message on that link: AES-256-GCM, numbered by its place in each
672
+ // direction, so none can be changed, repeated, dropped or moved unnoticed.
673
+ const linkIv = n => { const iv = Buffer.alloc(12); iv.writeBigUInt64BE(n, 4); return iv }
674
+ function encryptSocket(ws, { fromHost, toHost }) {
675
+ let sent = 0n
676
+ let received = 0n
677
+ const rawSend = ws.send
678
+ ws.send = text => {
679
+ const c = createCipheriv('aes-256-gcm', toHost, linkIv(sent++))
680
+ const body = Buffer.concat([c.update(String(text), 'utf8'), c.final()])
681
+ return rawSend(Buffer.concat([body, c.getAuthTag()]).toString('base64'))
682
+ }
683
+ let handler = () => {}
684
+ const inbound = raw => {
685
+ let text
686
+ try {
687
+ const all = Buffer.from(raw, 'base64')
688
+ const d = createDecipheriv('aes-256-gcm', fromHost, linkIv(received++))
689
+ d.setAuthTag(all.subarray(-16))
690
+ text = Buffer.concat([d.update(all.subarray(0, -16)), d.final()]).toString('utf8')
691
+ } catch {
692
+ return ws.close(4003, 'a message that does not check')
693
+ }
694
+ handler(text)
695
+ }
696
+ Object.defineProperty(ws, 'onmessage', { get: () => inbound, set: h => { handler = h } })
697
+ }
698
+
699
+ // One-time tickets for the dashboard's terminal socket (a browser can't send
700
+ // an Authorization header on a WebSocket): 30 seconds, used once.
701
+ const terminalTickets = new Map() // ticket -> { expires (ms), actor }
702
+ function newTerminalTicket(actor) {
703
+ for (const [t, v] of terminalTickets) if (v.expires < Date.now()) terminalTickets.delete(t)
704
+ if (terminalTickets.size >= 100) terminalTickets.delete(terminalTickets.keys().next().value)
705
+ const ticket = randomBytes(24).toString('base64url')
706
+ terminalTickets.set(ticket, { expires: Date.now() + 30_000, actor })
707
+ return { ticket }
708
+ }
709
+ function takeTerminalTicket(ticket) {
710
+ const v = ticket ? terminalTickets.get(ticket) : undefined
711
+ if (v === undefined) return null
712
+ terminalTickets.delete(ticket)
713
+ return v.expires >= Date.now() ? v : null
714
+ }
715
+ // Someone lost access: a ticket they asked for and haven't used goes too.
716
+ function dropTickets(match) {
717
+ for (const [t, v] of terminalTickets) if (v.actor && match(v.actor)) terminalTickets.delete(t)
718
+ }
719
+ // (Tickets say nothing of whose they are: each company knows its own.)
720
+ const hasTicket = ticket => hostTickets.has(ticket) || terminalTickets.has(ticket)
721
+ const wsClients = new Set()
722
+
723
+ function removeHost(id) {
724
+ const row = hostRow(id)
725
+ if (!row) throw bad('host not found')
726
+ db.prepare('UPDATE identities SET host_id = NULL WHERE host_id = ?').run(id) // no longer "opened from the dashboard"
727
+ db.prepare('DELETE FROM hosts WHERE id = ?').run(id)
728
+ hostLinks.get(id)?.ws.close(4001, 'this machine was disconnected from the dashboard')
729
+ broadcast('host', { id, removed: true })
730
+ log(`host "${row.name}" (${id}) removed from the dashboard`)
731
+ return { id, removed: true }
732
+ }
733
+
734
+ function renameHost(id, name) {
735
+ name = String(name ?? '').trim()
736
+ if (!/^[\p{L}\p{N} ._-]{1,40}$/u.test(name)) throw bad('the name may have letters, digits, spaces, dots, dashes and underscores (max 40)')
737
+ if (!hostRow(id)) throw bad('host not found')
738
+ if (db.prepare('SELECT 1 FROM hosts WHERE name = ? AND id != ?').get(name, id)) throw bad(`another machine is already called "${name}"`)
739
+ db.prepare('UPDATE hosts SET name = ? WHERE id = ?').run(name, id)
740
+ broadcastHost(id)
741
+ return hostView(hostRow(id))
742
+ }
743
+
744
+ // Open a session on a host. The spec is passed through as-is: the host is the
745
+ // one that validates it (its rules are local and the server can't widen them).
746
+ // Here we only refuse names already taken by a connected session.
747
+ // The name is reserved here, for this machine: the server registers it and
748
+ // hands its secret to the machine with the spec, so nobody holding the join
749
+ // token can grab the name first. A name registered by some other session is
750
+ // refused (delete that session in the dashboard to free it).
751
+ // Allow or remove a folder on a machine: the machine checks it against its
752
+ // own rules (and may keep its folders to itself) and answers with its list.
753
+ async function changeHostFolders(p) {
754
+ const id = String(p.host ?? '')
755
+ const action = p.action === 'add' || p.action === 'remove' ? p.action : null
756
+ if (!action) throw bad('action must be add or remove')
757
+ const path = typeof p.path === 'string' ? p.path.trim() : ''
758
+ if (!path || path.length > 4096 || /[\x00-\x1f\x7f]/.test(path)) throw bad('a folder path is needed')
759
+ const r = await askHost(id, { t: 'folders', action, path })
760
+ return { folders: (Array.isArray(r?.folders) ? r.folders : []).slice(0, 50).filter(f => typeof f === 'string').map(f => cleanText(f.slice(0, 1000)).slice(0, 500)) }
761
+ }
762
+
763
+ // The skills and agents a session opened in that folder of a machine could
764
+ // follow (the machine looks for them, within its own rules).
765
+ async function hostPersonas(p) {
766
+ const id = String(p.host ?? '')
767
+ const folder = typeof p.folder === 'string' ? p.folder.trim() : ''
768
+ if (!folder || folder.length > 4096 || /[\x00-\x1f\x7f]/.test(folder)) throw bad('a folder path is needed')
769
+ const r = await askHost(id, { t: 'personas', folder })
770
+ const str = (v, n) => typeof v === 'string' ? cleanText(v.slice(0, n * 2)).replace(/\s+/g, ' ').trim().slice(0, n) : ''
771
+ return {
772
+ personas: (Array.isArray(r?.personas) ? r.personas : []).slice(0, 200)
773
+ .filter(x => x && PERSONA_ID_RE.test(String(x.id)) && ['skill', 'agent'].includes(x.kind) && ['project', 'user'].includes(x.scope))
774
+ .map(x => ({ id: x.id, kind: x.kind, scope: x.scope, name: str(x.name, 64) || x.id.split(':')[2], description: str(x.description, 300), no_pisha_tools: x.no_pisha_tools === true })),
775
+ }
776
+ }
777
+
778
+ async function openTerminalOn(p, actor = null) {
779
+ const id = String(p.host ?? '')
780
+ const spec = p.spec && typeof p.spec === 'object' && !Array.isArray(p.spec) ? { ...p.spec } : null
781
+ if (!spec) throw bad('spec is required')
782
+ delete spec.identity
783
+ const name = String(spec.name ?? '')
784
+ if (!NAME_RE.test(name)) throw bad('name must match [A-Za-z0-9_-]{1,32}')
785
+ if (!hostLinks.has(id)) return askHost(id, { t: 'open', spec }) // reports host_offline / not found
786
+ if (holdsName(name, leases.get(name))) {
787
+ throw new ApiError(409, `Conflict: a session named "${name}" is already connected`, { parameters: { reason: 'name_in_use' } })
788
+ }
789
+ const existing = db.prepare('SELECT host_id FROM identities WHERE name = ?').get(name)
790
+ if (existing && existing.host_id !== id) {
791
+ throw new ApiError(409, `Conflict: the name "${name}" is already registered by another session; pick another name, or delete that session in the dashboard`, { parameters: { reason: 'name_taken' } })
792
+ }
793
+ // Already running there (its plugin just not connected right now), or
794
+ // being opened right now (a second click, another tab): its secret is left
795
+ // alone, and the machine would refuse a second one anyway.
796
+ const key = `${id}\0${name}`
797
+ if (hostLinks.get(id)?.info?.terminals?.some(t => t.id === name) || opening.has(key)) {
798
+ throw new ApiError(409, `Conflict: a session named "${name}" is already open on that machine`, { parameters: { reason: 'open_on_host' } })
799
+ }
800
+ opening.set(key, now())
801
+ let timedOut = false
802
+ try { return await openNow(id, name, spec, existing, actor) } catch (err) {
803
+ timedOut = err instanceof ApiError && err.code === 504
804
+ throw err
805
+ } finally {
806
+ // (Kept a little after a timeout only: the machine may still be opening it.
807
+ // Once it answered, yes or no, the name is free to try again.)
808
+ if (timedOut) setTimeout(() => opening.delete(key), 15_000).unref?.()
809
+ else opening.delete(key)
810
+ }
811
+ }
812
+ const opening = new Map() // "host\0name" -> since: an open in progress
813
+
814
+ // The permission profile the session follows (its own, or its team's), as
815
+ // rules for its machine to give Claude Code. Never opened with less than it
816
+ // says: a machine that can't apply it (too old, or set not to take them from
817
+ // the dashboard) doesn't open the session. Codex CLI and Grok CLI have no
818
+ // such rules: a profile that only allows things is left out for them, one
819
+ // that asks or forbids keeps them from opening.
820
+ function withPermissions(id, name, role, agent, spec) {
821
+ const p = permissions.compile(permissions.effectiveProfile(name, role, spec.coordinator ?? null))
822
+ if (!p || (!p.allow.length && !p.ask.length && !p.deny.length && !p.notes)) return
823
+ const conflict = (reason, text) => new ApiError(409, `Conflict: ${text}`, { parameters: { reason } })
824
+ if (agent !== 'claude') {
825
+ if (p.ask.length || p.deny.length) throw conflict('profile_agent', `"${name}" follows the permission profile "${p.name}", which only Claude Code can apply: open it with Claude Code, or give it no profile`)
826
+ return
827
+ }
828
+ const takes = hostLinks.get(id)?.info?.permission_profiles
829
+ if (takes == null) throw conflict('old_machine', `"${name}" follows the permission profile "${p.name}", and its machine is too old to apply one: update it (pisha-host update), or give the session no profile`)
830
+ // (How far it takes them is the machine's to say, as it is now: it refuses what it doesn't.)
831
+ spec.permissions = { profile: p.name, allow: p.allow, ask: p.ask, deny: p.deny, notes: p.notes }
832
+ }
833
+ async function openNow(id, name, spec, existing, actor) {
834
+ let created = false
835
+ // The role it was opened with (the dashboard trusts that one, not whatever
836
+ // the session claims later).
837
+ const openedRole = spec.role === 'coordinator' || spec.role === 'solo' ? spec.role : 'worker'
838
+ const openedPersona = PERSONA_ID_RE.test(String(spec.persona ?? '')) ? spec.persona : null
839
+ const openedCoordinator = openedRole === 'worker' && NAME_RE.test(String(spec.coordinator ?? '')) ? spec.coordinator : null
840
+ // The agent it runs, among those that machine has (one that says none has Claude Code only).
841
+ const agent = AGENTS.includes(spec.agent) ? spec.agent : 'claude'
842
+ const has = hostLinks.get(id)?.info?.agents
843
+ if (agent !== 'claude' && !(Array.isArray(has) && has.some(a => a?.id === agent))) throw bad(`that machine doesn't have ${agent} installed`)
844
+ if (agent === 'claude') delete spec.agent; else spec.agent = agent
845
+ // A coordinator's links are the ones set here, never what the page sends.
846
+ delete spec.links
847
+ // Nor its permissions: those of the profile it follows (below).
848
+ delete spec.permissions
849
+ if (openedRole === 'coordinator') { const l = linksOf(name); if (l.length) spec.links = l }
850
+ if (!existing) {
851
+ spec.identity = register(name, false).secret
852
+ db.prepare('UPDATE identities SET host_id = ?, opened_role = ?, opened_persona = ?, opened_coordinator = ?, agent = ? WHERE name = ?').run(id, openedRole, openedPersona, openedCoordinator, agent, name)
853
+ created = true
854
+ } else {
855
+ // Already this machine's name, and not connected: a new secret goes with
856
+ // it, so the session can log in even if the last one never arrived (or
857
+ // the session was disconnected from the dashboard).
858
+ dropLease(name)
859
+ spec.identity = register(name, true).secret
860
+ db.prepare('UPDATE identities SET opened_role = ?, opened_persona = ?, opened_coordinator = ?, agent = ? WHERE name = ?').run(openedRole, openedPersona, openedCoordinator, agent, name)
861
+ }
862
+ // A worker's coordinator, as it was opened (until it says so itself at
863
+ // login): the org chart keeps it in its squad while it isn't connected.
864
+ // (None named: the machine's own default, known here as well from the start.)
865
+ if (openedRole === 'worker' && !spec.coordinator) spec.coordinator = 'coord'
866
+ if (openedRole === 'worker' && NAME_RE.test(String(spec.coordinator ?? ''))) db.prepare('UPDATE identities SET coordinator = ? WHERE name = ?').run(spec.coordinator, name)
867
+ try {
868
+ withPermissions(id, name, openedRole, agent, spec)
869
+ const result = await askHost(id, { t: 'open', spec })
870
+ log(`opened session "${name}" on host ${id}`)
871
+ if (openedRole === 'worker') void approveOnCoordinator(spec.coordinator, name, actor)
872
+ return result
873
+ } catch (err) {
874
+ // Only when the machine said no: after a timeout it may still open the
875
+ // session, and the name must stay reserved for it.
876
+ if (created && err instanceof ApiError && err.code === 400) db.prepare('DELETE FROM identities WHERE name = ? AND host_id = ?').run(name, id)
877
+ throw err
878
+ }
879
+ }
880
+
881
+ // A worker opened from here for a coordinator also opened from here: the
882
+ // coordinator's machine approves it, as /pisha:access pair would (whoever
883
+ // opened both meant them to work together). A coordinator opened by hand,
884
+ // or not connected, pairs as before. Written down either way it happens.
885
+ async function approveOnCoordinator(coordinator, worker, actor) {
886
+ const row = NAME_RE.test(String(coordinator ?? '')) ? db.prepare('SELECT host_id, opened_role FROM identities WHERE name = ?').get(coordinator) : null
887
+ if (!row?.host_id || row.opened_role !== 'coordinator' || !hostLinks.has(row.host_id)) return
888
+ // (The registration opened, not just the name: the coordinator pins it.)
889
+ const identity = db.prepare('SELECT epoch FROM identities WHERE name = ?').get(worker)?.epoch
890
+ if (!identity) return
891
+ try {
892
+ await askHost(row.host_id, { t: 'approve', term: coordinator, worker, identity })
893
+ audit(actor ?? { token: true }, 'worker-approved', `${worker} → ${coordinator}`, null)
894
+ log(`"${worker}" approved for "${coordinator}" on its machine`)
895
+ } catch (err) { log(`could not approve "${worker}" for "${coordinator}": ${err.message}`) }
896
+ }
897
+
898
+ async function killTerminalOn(p) {
899
+ const id = String(p.host ?? '')
900
+ const term = String(p.term ?? '')
901
+ if (!NAME_RE.test(term)) throw bad('invalid session')
902
+ return askHost(id, { t: 'kill', term })
903
+ }
904
+
905
+ return {
906
+ machineMethods, onUpgrade, wsClients, sanitizeHostInfo, ownTerminals, PERSONA_ID_RE, listHosts,
907
+ createEnrollment, renameHost, removeHost, changeHostFolders, hostPersonas, openTerminalOn,
908
+ killTerminalOn, newTerminalTicket, typeAnswer, hostRow, hostLinks, askHost, enrollHost, hostTicketAnswer, hasTicket, dropTickets, cancelEnrollments,
909
+ }
910
+ }