afield 0.0.0-stage → 0.1.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 (43) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +165 -2
  3. package/afield +214 -0
  4. package/package.json +42 -4
  5. package/pi-extensions/afield-session.ts +59 -0
  6. package/pi-extensions/elastic-footer.ts +167 -0
  7. package/server/attach.js +264 -0
  8. package/server/auth.js +169 -0
  9. package/server/client.js +64 -0
  10. package/server/control.js +65 -0
  11. package/server/identity.js +45 -0
  12. package/server/index.js +375 -0
  13. package/server/mirror.js +159 -0
  14. package/server/origin.js +51 -0
  15. package/server/picker.js +187 -0
  16. package/server/places.js +348 -0
  17. package/server/protocol.js +51 -0
  18. package/server/quick-tunnel.js +40 -0
  19. package/server/registry.js +190 -0
  20. package/server/serve.js +100 -0
  21. package/server/session-main.js +27 -0
  22. package/server/session.js +112 -0
  23. package/server/supervisor.js +432 -0
  24. package/server/viewer.js +65 -0
  25. package/src/app.js +1683 -0
  26. package/src/apple-touch-icon.png +0 -0
  27. package/src/index.html +96 -0
  28. package/src/keys.js +59 -0
  29. package/src/pi-icon.svg +13 -0
  30. package/src/style.css +559 -0
  31. package/src/transport.js +153 -0
  32. package/src/ttyd.js +51 -0
  33. package/src/viewport.js +168 -0
  34. package/tsconfig.json +14 -0
  35. package/vendor/wterm/LICENSE +191 -0
  36. package/vendor/wterm/README.md +7 -0
  37. package/vendor/wterm/packages/@wterm/dom/src/debug.ts +347 -0
  38. package/vendor/wterm/packages/@wterm/dom/src/hyperlink.ts +8 -0
  39. package/vendor/wterm/packages/@wterm/dom/src/index.ts +13 -0
  40. package/vendor/wterm/packages/@wterm/dom/src/input.ts +662 -0
  41. package/vendor/wterm/packages/@wterm/dom/src/renderer.ts +725 -0
  42. package/vendor/wterm/packages/@wterm/dom/src/terminal.css +195 -0
  43. package/vendor/wterm/packages/@wterm/dom/src/wterm.ts +609 -0
@@ -0,0 +1,432 @@
1
+ // The front door: one supervisor holding live PTYs independently of pi conversations.
2
+ //
3
+ // Auth, origin-checking and the client HTML build live here. A session a viewer
4
+ // joins keeps running after that viewer leaves, and a different viewer (phone,
5
+ // a second `attach`, a third) can be looking at a different one at the same
6
+ // time. `GET /places` answers what sessions exist and which are running;
7
+ // `POST /start` begins a fresh PTY, pi or a shell; `/ws?process=<id>` joins a live one,
8
+ // while `/ws?session=<id>&cwd=<path>` opens a saved conversation.
9
+ import { createServer } from 'node:http'
10
+ import { randomUUID } from 'node:crypto'
11
+ import { mkdtempSync } from 'node:fs'
12
+ import { readFile, rm } from 'node:fs/promises'
13
+ import { tmpdir } from 'node:os'
14
+ import { basename, join } from 'node:path'
15
+ import { WebSocket, WebSocketServer } from 'ws'
16
+ import { Auth, loginPage } from './auth.js'
17
+ import { buildClient } from './client.js'
18
+ import { isAddress, originAllowed } from './origin.js'
19
+ import { PI_SESSIONS, placeNames, readPlaces, findPlace, canonical, subfolders } from './places.js'
20
+ import { BACKLOG_LIMIT, TOO_FAR_BEHIND } from './viewer.js'
21
+ import { DEFAULT_SCROLLBACK } from './protocol.js'
22
+ import { Registry } from './registry.js'
23
+
24
+ const MAX_FRAME = 1024 * 1024
25
+
26
+ // How long a just-spawned child gets to come up before a join gives up on it,
27
+ // and how often to retry while waiting. Generous: a slow machine cold-starting
28
+ // node plus pi is not the same failure as pi simply not existing.
29
+ const CHILD_READY_MS = 8_000
30
+ const CHILD_RETRY_MS = 75
31
+
32
+ // Said the same way whether /start answers it or a socket closes on it. The
33
+ // registry decides the number, so nothing here repeats the default.
34
+ const poolFull = cap => `${cap} sessions are running (the limit); end one first`
35
+
36
+ /** The order a full pool is picked over: the longest since any output goes first. */
37
+ const pickOrder = (a, b) => a.active - b.active
38
+
39
+ const connectChild = (socketPath, readyMs) => new Promise((resolveConn, rejectConn) => {
40
+ const deadline = Date.now() + readyMs
41
+ const attempt = () => {
42
+ const sock = new WebSocket(`ws+unix://${socketPath}:/ws`, ['tty'])
43
+ sock.once('open', () => resolveConn(sock))
44
+ sock.once('error', () => {
45
+ sock.terminate()
46
+ if (Date.now() > deadline) return rejectConn(new Error(`session on ${socketPath} never came up`))
47
+ setTimeout(attempt, CHILD_RETRY_MS)
48
+ })
49
+ }
50
+ attempt()
51
+ })
52
+
53
+ export function createSupervisor({ port, bind, hostname, key, pi, shell, sessionMain, sessionDir = PI_SESSIONS, cap, theme = 'dark', scrollback = DEFAULT_SCROLLBACK, newDir, pingMs = 30_000, childReadyMs = CHILD_READY_MS, onListen, onPaired, onExit }) {
54
+ const auth = new Auth(key)
55
+ // A fresh private directory for session sockets, removed by close(): they
56
+ // must not land in the shared tmpdir under a guessable name, where any local
57
+ // user could squat on one and answer a join in our place.
58
+ const socketDir = mkdtempSync(join(tmpdir(), 'afield-sock-'))
59
+ const registry = new Registry({ sessionMain, pi, shell, socketDir, cap, scrollback })
60
+ // Without pi there are no conversations to list or open, wherever pi once kept them.
61
+ const store = pi ? sessionDir : null
62
+ // Where a brand-new session starts: given, or the folder this run was
63
+ // launched from.
64
+ const defaultDir = newDir ?? process.cwd()
65
+
66
+ // How many viewers are on a live child: "2 watching" on a row says the
67
+ // session is shared right now, not just alive.
68
+ const watching = processId => [...wss.clients].filter(c => c.readyState === c.OPEN && c.processId === processId).length
69
+
70
+ /** Every running terminal, as rows of the list. */
71
+ const runningRows = () => registry.running().map(child => {
72
+ const current = registry.current(child)
73
+ return {
74
+ id: current.id,
75
+ cwd: current.cwd,
76
+ file: current.file,
77
+ ...placeNames(current.cwd),
78
+ // Opening a terminal counts as touching it, so the menu lists it as recent.
79
+ at: Math.max(current.at, child.joinedAt),
80
+ // When its program last printed anything, which the full-pool picker orders by.
81
+ active: child.lastOutputAt,
82
+ // As the child reports it (server/index.js): a program that says nothing never works.
83
+ working: child.working,
84
+ // Unread when nobody is watching and it stopped working after the last viewer left or spawn.
85
+ // The registry's list, not open sockets: it drops a viewer in the same step seenAt is stamped.
86
+ unread: !child.working && child.sockets.length === 0 && child.stoppedAt > child.seenAt,
87
+ // A shell in the same folder as a pi needs telling apart from it; name
88
+ // whatever program currently holds its foreground rather than always naming the shell.
89
+ label: child.kind === 'shell' ? `${child.foreground || basename(shell)} · ${basename(current.cwd)}` : basename(current.cwd),
90
+ kind: child.kind,
91
+ processId: child.processId,
92
+ startedAt: child.startedAt,
93
+ }
94
+ })
95
+
96
+ // The query is ignored: `?b=<id>` is only there to give the client a URL iOS
97
+ // has no cached copy of, and what it gets back is whatever is current. It must
98
+ // not be cached any harder than `/` either — the home screen launches a fixed
99
+ // URL, so pinning that one would strand the phone on an old build for good.
100
+ const loginHeaders = { 'content-type': 'text/html', 'cache-control': 'no-store' }
101
+ const sendJson = (res, data, status = 200) =>
102
+ res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }).end(JSON.stringify(data))
103
+ const sendText = (res, status, text) =>
104
+ res.writeHead(status, { 'content-type': 'text/plain' }).end(text)
105
+ const originAllowedReq = req => originAllowed({
106
+ origin: req.headers.origin,
107
+ host: req.headers.host,
108
+ hostname,
109
+ })
110
+
111
+ /** A request body as text, capped hard: no route here takes much. */
112
+ const readBody = (req, cap) => new Promise((resolve, reject) => {
113
+ let size = 0
114
+ const chunks = []
115
+ req.on('data', chunk => {
116
+ size += chunk.length
117
+ if (size > cap) return void req.destroy()
118
+ chunks.push(chunk)
119
+ })
120
+ req.on('end', () => resolve(Buffer.concat(chunks).toString()))
121
+ req.on('error', reject)
122
+ })
123
+
124
+ const handle = async (req, res) => {
125
+ // One gate ahead of dispatch, so no route can forget it: to a rebound
126
+ // page every request here is same-origin (see origin.js).
127
+ if (!originAllowedReq(req)) return void res.writeHead(403).end()
128
+ const url = new URL(req.url, 'http://internal')
129
+ const path = url.pathname
130
+
131
+ // A pairing key only ever arrives posted, so no address, history or log
132
+ // holds one unspent. The page is served signed in or not: a link's key
133
+ // after the # is spent by the page, which a signed-in browser opening it
134
+ // would otherwise skip.
135
+ if (path === '/login' && req.method === 'GET' && auth.required) return void res.writeHead(200, loginHeaders).end(loginPage())
136
+ if (path === '/login' && req.method === 'POST' && auth.required) {
137
+ const attempt = new URLSearchParams(await readBody(req, 4096).catch(() => '')).get('code')
138
+ if (!attempt || !auth.redeem(attempt)) {
139
+ return void res.writeHead(401, loginHeaders).end(loginPage('That pairing key is wrong or was already used.'))
140
+ }
141
+ onPaired?.()
142
+ const secure = req.headers['x-forwarded-proto'] === 'https'
143
+ return void res.writeHead(303, { location: '/', 'set-cookie': auth.cookie({ secure }) }).end()
144
+ }
145
+
146
+ // The Home-screen icon, the one thing here that is not the page itself.
147
+ // iOS asks for it without the session cookie when the page is added to the
148
+ // Home screen, so it answers without auth -- a 401 there means no icon.
149
+ // Read per request like the page, so editing it needs no restart.
150
+ if (path === '/apple-touch-icon.png' && req.method === 'GET') {
151
+ const png = await readFile(new URL('../src/apple-touch-icon.png', import.meta.url))
152
+ return void res.writeHead(200, { 'content-type': 'image/png', 'cache-control': 'no-cache' }).end(png)
153
+ }
154
+
155
+ if (path === '/') {
156
+ if (!auth.admits(req)) return void res.writeHead(200, loginHeaders).end(loginPage())
157
+ const client = await buildClient({ theme, scrollback })
158
+ const headers = { etag: client.etag, 'cache-control': 'no-cache' }
159
+ if (req.headers['if-none-match'] === client.etag) return void res.writeHead(304, headers).end()
160
+ return void res.writeHead(200, { ...headers, 'content-type': 'text/html' }).end(client.page)
161
+ }
162
+
163
+ // Every API route below requires sign-in, gated once so none can forget it.
164
+ if (!auth.admits(req)) return void res.writeHead(401).end()
165
+
166
+ if (path === '/places' && req.method === 'GET') {
167
+ // A caller that names no window gets every session there is, so
168
+ // `afield end` and `attach` can never be reading a list that quietly
169
+ // omits a running one. The phone menu asks for a window at a time.
170
+ const query = url.searchParams
171
+ const limit = query.has('limit') ? Number(query.get('limit')) : Number.MAX_SAFE_INTEGER
172
+ const offset = query.has('offset') ? Number(query.get('offset')) : 0
173
+ // Window params mean nothing to an exact-id request, so they are not
174
+ // validated there: naming an id is not a malformed window.
175
+ if (!query.has('id') && (!Number.isSafeInteger(limit) || limit < 1 || !Number.isSafeInteger(offset) || offset < 0)) {
176
+ return void sendText(res, 422, 'offset and limit must be whole numbers, limit at least 1')
177
+ }
178
+ // An exact id is answered even when the session is a fork, which the
179
+ // windowed list never shows: a caller that already knows the id needs
180
+ // no menu row, and the join below serves whatever findPlace returns.
181
+ const named = query.get('id')
182
+ // Past the cap, the picker asks which running session to end: the rows
183
+ // it shows are the same ones, quietest first.
184
+ if (query.get('running') === '1') {
185
+ const rows = runningRows().map(s => ({ ...s, running: true, viewers: watching(s.processId) }))
186
+ const sessions = rows.sort(pickOrder)
187
+ return void sendJson(res, { sessions, more: false, offset: 0, here: defaultDir })
188
+ }
189
+ // What the running terminals have open, as rows of the same list.
190
+ const live = runningRows()
191
+ // A row answered by id is the live one when its terminal is up -- a
192
+ // running terminal answers from the registry before the store is read
193
+ // at all -- so running and viewer counts read like any row of the list.
194
+ const liveHit = named && live.find(r => r.id === named)
195
+ const single = named && !liveHit ? await findPlace({ sessionDir: store, id: named }) : null
196
+ const { sessions: found, more } = named
197
+ ? { sessions: [liveHit ?? single].filter(Boolean), more: false }
198
+ : await readPlaces({ sessionDir: store, offset, limit, live })
199
+ // How many viewers are on each live child, for the listings.
200
+ const sessions = found.map(place => ({
201
+ ...place,
202
+ running: Boolean(place.processId),
203
+ viewers: place.processId ? watching(place.processId) : 0,
204
+ }))
205
+ return void sendJson(res, {
206
+ sessions,
207
+ more,
208
+ // Where the next window starts, passed back rather than counted by
209
+ // the caller: the rows to show are the server's to page.
210
+ offset: offset + found.length,
211
+ here: defaultDir,
212
+ kinds: registry.kinds,
213
+ })
214
+ }
215
+
216
+ // End a running session for good: the child gets SIGTERM, then SIGKILL
217
+ // after a grace (`registry.end`), and its viewers hear that a terminal
218
+ // asked for it. Deleted-for-real is pi's own business; this stops the
219
+ // process, which is what afield owns.
220
+ if (path === '/terminal' && req.method === 'DELETE') {
221
+ const id = url.searchParams.get('process')
222
+ const child = id && registry.child(id)
223
+ if (!child) return void sendText(res, 404, id ? 'that terminal is not running' : 'which terminal')
224
+ console.error(`server: ending terminal ${id} on request`)
225
+ await registry.end(id)
226
+ return void sendJson(res, { ended: id })
227
+ }
228
+
229
+ // Start a session that has no transcript yet: mint an id, spawn pi (or a
230
+ // shell, when asked) in the named directory, and let the client join it
231
+ // like any other.
232
+ if (path === '/start' && req.method === 'POST') {
233
+ // /start's whole payload is a directory and a kind.
234
+ const body = await readBody(req, 512).then(JSON.parse).catch(() => null)
235
+ // Any directory that exists can hold a session: joining one already
236
+ // gives a full bash prompt, so restricting the start list would be
237
+ // ceremony. canonical() is null for a path that does not resolve.
238
+ const wanted = typeof body?.cwd === 'string' ? await canonical(body.cwd.trim()) : null
239
+ if (!wanted) return void sendText(res, 422, 'no such directory to start a session in')
240
+ const kind = body.kind ?? 'pi'
241
+ if (!registry.kinds.includes(kind)) {
242
+ return void sendText(res, 422, `this server does not start ${JSON.stringify(kind)} sessions`)
243
+ }
244
+ const id = randomUUID()
245
+ // Past the cap nothing is ended behind the caller's back: the refusal is
246
+ // the pick list, and the caller ends the one it chooses.
247
+ const child = await registry.start(id, wanted, { kind })
248
+ if (!child) return void sendText(res, 409, poolFull(registry.cap))
249
+ return void sendJson(res, { id, cwd: wanted, processId: child.processId })
250
+ }
251
+
252
+ // Browsing folders requires the same authentication as listing sessions.
253
+ if (path === '/subfolders' && req.method === 'GET') {
254
+ const want = url.searchParams.get('cwd') ?? defaultDir
255
+ const found = await subfolders(want)
256
+ if (!found) return void sendText(res, 404, 'no such directory')
257
+ return void sendJson(res, found)
258
+ }
259
+
260
+ res.writeHead(404).end()
261
+ }
262
+
263
+ // A throw in here would otherwise be the end of the supervisor and every PTY under
264
+ // it; a request that cannot be answered is one 500 instead. One kind says
265
+ // more than that: spawn() itself refused -- no file descriptors left, say --
266
+ // which is the machine's failing rather than the request's, and a fresh 503
267
+ // is a retry later where a bare 500 reads like a bad request.
268
+ const http = createServer((req, res) => {
269
+ handle(req, res).catch(err => {
270
+ console.error('server: could not answer a request', err)
271
+ if (res.headersSent) return void res.end()
272
+ const spawnFailed = err?.syscall === 'spawn'
273
+ sendText(res, spawnFailed ? 503 : 500,
274
+ spawnFailed ? 'this server cannot start a terminal right now' : String(err.message ?? err))
275
+ })
276
+ })
277
+
278
+ const wss = new WebSocketServer({
279
+ server: http,
280
+ path: '/ws',
281
+ maxPayload: MAX_FRAME,
282
+ handleProtocols: () => 'tty',
283
+ verifyClient: ({ req }) => {
284
+ const { origin, host } = req.headers
285
+ if (!auth.admits(req)) {
286
+ console.error('server: refused a socket that has not logged in')
287
+ return false
288
+ }
289
+ if (originAllowed({ origin, host, hostname })) return true
290
+ const undeclared = !hostname && host && !isAddress(host)
291
+ console.error(`server: refused a socket from ${origin} for host ${host}` +
292
+ `${undeclared ? ' — a proxy in front of this needs --hostname' : ''}`)
293
+ return false
294
+ },
295
+ })
296
+
297
+ wss.on('error', err => {
298
+ console.error(err.code === 'EADDRINUSE'
299
+ ? `server: port ${port} is already in use\n` +
300
+ ` if that is another afield: afield sessions --port ${port}\n` +
301
+ ` if it is something else: afield serve --port N`
302
+ : `server: cannot listen on ${bind}:${port}: ${err.message}`)
303
+ onExit?.({ exitCode: 1, signal: 0 })
304
+ })
305
+
306
+ // A process ID joins an existing PTY regardless of /new or /resume inside
307
+ // it. A conversation ID plus cwd opens history only if it is not live.
308
+ wss.on('connection', (ws, req) => {
309
+ // Set by the pong that answers each ping and cleared by the ping itself;
310
+ // a socket that misses a round is terminated by the loop below.
311
+ ws.answered = true
312
+ ws.on('pong', () => { ws.answered = true })
313
+
314
+ const url = new URL(req.url, 'http://internal')
315
+ const id = url.searchParams.get('session')
316
+ const cwd = url.searchParams.get('cwd')
317
+ const processId = url.searchParams.get('process')
318
+
319
+ let inner = null
320
+ let buffered = []
321
+ let closed = false
322
+ // Registered with the registry once the relay is live, so the child's death can
323
+ // cut this browser side down here rather than waiting for the socket teardown
324
+ // to be noticed below.
325
+ let registered = null
326
+
327
+ // Attached before anything here awaits: the client sends its handshake the
328
+ // instant its socket opens, and a listener added even one microtask late
329
+ // would simply never see it — an EventEmitter drops what nothing is
330
+ // listening for rather than queuing it.
331
+ ws.on('message', data => {
332
+ if (inner && inner.readyState === inner.OPEN) inner.send(data)
333
+ else buffered?.push(data)
334
+ })
335
+ ws.on('close', () => { closed = true; registered?.(); inner?.close() })
336
+ ws.on('error', () => { closed = true; registered?.(); inner?.close() })
337
+
338
+ ;(async () => {
339
+ let child = processId ? registry.child(processId) : undefined
340
+ if (child) child.joinedAt = Date.now()
341
+ // A process from an earlier run of this server went with it. Sent with
342
+ // the conversation it was showing, that conversation reopens instead:
343
+ // how a phone gets back after a restart. One that ended in this run
344
+ // stays ended.
345
+ else if (processId && (registry.startedHere(processId) || !id || !cwd)) { ws.close(4004, 'terminal is no longer running'); return }
346
+ else {
347
+ const place = await findPlace({ sessionDir: store, id, cwd: cwd || undefined })
348
+ if (!id || !place) { ws.close(4004, 'no such conversation'); return }
349
+ child = await registry.ensure(id, place.cwd, { resume: true })
350
+ if (!child) { ws.close(4006, poolFull(registry.cap)); return }
351
+ }
352
+ if (closed) return
353
+ ws.processId = child.processId
354
+ const sock = await connectChild(child.socketPath, childReadyMs)
355
+ if (closed) { sock.close(); return }
356
+ // The child states the place on admission, from the identity file it
357
+ // owns: this relay carries frames, it does not invent them.
358
+ inner = sock
359
+ registered = registry.watch(child.processId, reason => { sock.close(); ws.close(1001, reason) })
360
+ for (const data of buffered) inner.send(data)
361
+ buffered = null
362
+ // Same rule the session itself applies to its viewers (server/viewer.js):
363
+ // catch up, or be disconnected — never fall behind without bound. The
364
+ // check is before the write, so a socket that cannot take this chunk is
365
+ // cut loose instead of being sent part of it; the client's own reconnect
366
+ // picks the stream back up at a fresh snapshot. Cutting only this hop
367
+ // also stops the drain here from hiding a stalled phone from the child's
368
+ // own backlog limit, which is what would otherwise grow without bound.
369
+ inner.on('message', data => {
370
+ if (ws.readyState !== ws.OPEN) return
371
+ if (ws.bufferedAmount + data.length > BACKLOG_LIMIT) {
372
+ ws.close(TOO_FAR_BEHIND, 'too far behind')
373
+ return
374
+ }
375
+ ws.send(data)
376
+ })
377
+ inner.on('close', () => {
378
+ registered?.()
379
+ // end() records the reason before it signals, so this lookup sees it
380
+ // whenever the inner socket beats the registry's own exit callback
381
+ // here; the other order, the callback above already closed this ws
382
+ // with the same reason and this close is the ignored one.
383
+ ws.close(1001, registry.child(child.processId)?.endReason ?? `${child.kind} exited`)
384
+ })
385
+ inner.on('error', () => { registered?.(); ws.close(1011, 'lost the session') })
386
+ })().catch(err => {
387
+ console.error(`server: could not reach terminal ${processId ?? id}`, err)
388
+ ws.close(4005, 'could not reach the session')
389
+ })
390
+ })
391
+
392
+ // Cleared before each ping and set by the pong that answers it, exactly as
393
+ // one session's server does its viewers (server/index.js): a socket that
394
+ // has not answered the last ping is terminated, since a phone asleep behind
395
+ // a dead tunnel is gone for good — and holding its relay open holds memory
396
+ // on this side too.
397
+ const ping = setInterval(() => {
398
+ for (const ws of wss.clients) {
399
+ if (ws.readyState !== ws.OPEN) continue
400
+ if (!ws.answered) { ws.terminate(); continue }
401
+ ws.answered = false
402
+ ws.ping()
403
+ }
404
+ }, pingMs)
405
+ ping.unref()
406
+
407
+ http.listen(port, bind, () => onListen?.({ port: http.address().port, address: http.address().address }))
408
+
409
+ return {
410
+ http,
411
+ registry,
412
+ // A code for a new sign-in link, voiding the last one.
413
+ pair: () => auth.pair(),
414
+ // For a name only known after listening: a quick tunnel's.
415
+ setHostname(name) { hostname = name },
416
+ async close() {
417
+ clearInterval(ping)
418
+ // Stop listening first. A phone retrying while the children die would
419
+ // otherwise reach this server, be told its terminal is gone, and give
420
+ // up; refused, it keeps backing off until the next server is up.
421
+ const closed = new Promise(res => http.close(res))
422
+ // That leaves open sockets alone, so they go next, before the children:
423
+ // ending a session makes its viewers reconnect, and nothing should be
424
+ // reconnecting to a session that is dying.
425
+ for (const ws of wss.clients) ws.terminate()
426
+ await registry.endAll()
427
+ wss.close()
428
+ await closed
429
+ await rm(socketDir, { recursive: true, force: true })
430
+ },
431
+ }
432
+ }
@@ -0,0 +1,65 @@
1
+ // A viewer: one WebSocket, and the rule that it can only ever hurt itself.
2
+ //
3
+ // The bug this whole server exists to escape was a fan-out that quietly dropped
4
+ // bytes when a client socket filled. So there are exactly three things a slow
5
+ // viewer may do here — catch up, or be disconnected — and skipping bytes is not
6
+ // among them. A disconnect is visible and recoverable; a gap is neither.
7
+ import { OUTPUT, SET_TITLE, SET_SIZE } from './protocol.js'
8
+
9
+ // Enough that a phone stalling through a tunnel for a few seconds rides it out,
10
+ // small enough that one dead socket cannot grow into the process's problem.
11
+ // It also has to hold a whole snapshot, which goes out as one chunk: 10,000
12
+ // lines of densely coloured text on a 200-column grid is about 7 MB.
13
+ export const BACKLOG_LIMIT = 16 * 1024 * 1024
14
+
15
+ // 1013 Try Again Later: the viewer is not wrong, it is behind.
16
+ export const TOO_FAR_BEHIND = 1013
17
+
18
+ export class Viewer {
19
+ constructor(ws) {
20
+ this.ws = ws
21
+ this.size = { cols: 0, rows: 0 }
22
+ this.kind = 'browser'
23
+ this.started = false
24
+ // Cleared before each ping and set by the pong that answers it.
25
+ this.alive = true
26
+ // undefined until the snapshot has been taken — output before that is
27
+ // already inside it. An array while the snapshot is in flight. null once
28
+ // this viewer is live.
29
+ this.queue = undefined
30
+ }
31
+
32
+ get open() { return this.ws.readyState === this.ws.OPEN }
33
+
34
+ send(kind, payload) {
35
+ if (!this.open) return
36
+ this.ws.send(Buffer.concat([Buffer.from([kind]), Buffer.from(payload)]))
37
+ }
38
+
39
+ /**
40
+ * Hand this viewer output. Returns false once it has been cut loose.
41
+ *
42
+ * The check is before the write: `bufferedAmount` is what this socket has
43
+ * failed to drain, so a viewer that cannot take this chunk is cut loose
44
+ * instead of being sent part of it.
45
+ */
46
+ output(bytes) {
47
+ if (!this.open) return false
48
+ // Counting the chunk about to be added, so a single large write cannot
49
+ // vault the backlog past the limit and sit there.
50
+ if (this.ws.bufferedAmount + bytes.length > BACKLOG_LIMIT) {
51
+ this.ws.close(TOO_FAR_BEHIND, 'too far behind')
52
+ return false
53
+ }
54
+ this.send(OUTPUT, bytes)
55
+ return true
56
+ }
57
+
58
+ title(text) { this.send(SET_TITLE, text) }
59
+
60
+ /** The grid the PTY actually has, which is not always the one this viewer
61
+ * asked for: the narrowest viewer wins and the rest render smaller. */
62
+ sendSize({ cols, rows }) { this.send(SET_SIZE, JSON.stringify({ columns: cols, rows })) }
63
+
64
+ close(code, reason) { if (this.open) this.ws.close(code, reason) }
65
+ }