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,375 @@
1
+ // One live terminal: it owns a PTY and the program inside it.
2
+ //
3
+ // Nothing here may discard the unwritten tail of a read when a viewer's socket
4
+ // fills: that is where corrupt escape sequences come from.
5
+ //
6
+ // One instance serves exactly one program, in one folder, for its whole life
7
+ // — no switching. Running several sessions concurrently, and picking between
8
+ // them, is `server/supervisor.js`'s job: it spawns one of these per PTY
9
+ // (over a Unix socket, see `socketPath` below) and keeps it running in the
10
+ // background, so this file only ever has to think about "one PTY, N viewers,
11
+ // one screen".
12
+ import { readFileSync } from 'node:fs'
13
+ import { createServer } from 'node:http'
14
+ import { basename, resolve } from 'node:path'
15
+ import { WebSocketServer } from 'ws'
16
+ import { watchIdentity } from './identity.js'
17
+ import { placeNames } from './places.js'
18
+ import { Session } from './session.js'
19
+ import { Viewer } from './viewer.js'
20
+ import { Mirror } from './mirror.js'
21
+ import { INPUT, RESIZE, PROCESS, DEFAULT_SCROLLBACK, decodeHandshake, decodeSize } from './protocol.js'
22
+
23
+ // Cloudflare drops idle sockets and the phone sleeps, so the socket has to be
24
+ // spoken to even when pi is silent. ttyd did this and it is why `up` survived a
25
+ // quiet evening.
26
+ const PING_MS = 30_000
27
+ // A resize costs pi a full transcript re-render, so viewers that flap their size
28
+ // are made to settle before anyone pays for it.
29
+ const RESIZE_COALESCE_MS = 100
30
+ // Generous for a paste, far short of what it takes to matter. Without it a
31
+ // viewer could hand the PTY a hundred megabytes in one frame.
32
+ const MAX_FRAME = 1024 * 1024
33
+ // How often the PTY's output is told to the supervisor at most. It orders the
34
+ // full-pool picker, so a word a second is all that needs.
35
+ const ACTIVITY_MS = 1_000
36
+ // How often the PTY's foreground program is sampled for shell labels. Sent over
37
+ // IPC only when it changes.
38
+ const FOREGROUND_MS = 500
39
+ // How long the program has to have stopped working before the supervisor is
40
+ // told. pi-subagents takes 300ms and more to start the turn that follows a
41
+ // finished subagent, and pi says done and working a few ms apart around a
42
+ // settled run: neither is the session stopping.
43
+ const STOP_HOLD_MS = 1_500
44
+
45
+ /**
46
+ * `scrollback` is how much history a reconnecting viewer gets back. pi does not
47
+ * page its own transcript, so this is the only way to read back through a
48
+ * conversation on a phone — roughly 75 bytes a line, so 10,000 lines is about
49
+ * 750 KB per connect and per resize, against a pi transcript re-render that
50
+ * starts at 12 KB and grows with every turn.
51
+ *
52
+ * The page carries the same number to the browser client, whose VT core keeps
53
+ * that many lines and silently drops the rest.
54
+ */
55
+
56
+ export function createTerminalServer({ socketPath, command, args = [], cwd = process.cwd(), scrollback = DEFAULT_SCROLLBACK, onExit }) {
57
+ // A program named by path means that program, not whatever happens to sit at
58
+ // the same relative path in the session's own folder. A bare name is a PATH
59
+ // lookup and is already independent of the cwd. Resolved against this
60
+ // process's own directory, which for a supervisor-spawned child is the
61
+ // directory the supervisor itself was launched from.
62
+ const program = command.includes('/') ? resolve(process.cwd(), command) : command
63
+ const viewers = new Set()
64
+
65
+ // The supervisor is told over IPC, which a background child has and a
66
+ // foreground server does not. A channel that has closed is a supervisor that
67
+ // is gone, which is no reason to take the PTY down with it.
68
+ const tell = msg => { if (process.connected) process.send(msg) }
69
+
70
+ // Whether the program is working, for the tab markers: pi's own status (OSC
71
+ // 7501, read by the mirror) says so. A program that does not report it
72
+ // never works. Starting is told at once; stopping only once it has held, and
73
+ // with the time it began, so a viewer who saw it stop and left during the
74
+ // hold has still seen it. A dialog opening on an idle pi is a stop of its
75
+ // own: either way the program is waiting on the user.
76
+ let programState = null
77
+ const current = () =>
78
+ programState === 'working' || programState === 'blocked' ? programState : 'resting'
79
+ // What the supervisor was last told this program is doing.
80
+ let told = 'resting'
81
+ let stopTimer = null
82
+ const settleWorking = () => {
83
+ if (current() === 'working') {
84
+ clearTimeout(stopTimer)
85
+ stopTimer = null
86
+ if (told !== 'working') tell({ afield: 'working', working: true })
87
+ told = 'working'
88
+ } else if (current() !== told && !stopTimer) {
89
+ const stoppedAt = Date.now()
90
+ stopTimer = setTimeout(() => {
91
+ stopTimer = null
92
+ const now = current()
93
+ // A dialog closing on an idle pi is nothing to come back to.
94
+ if (told === 'working' || (now === 'blocked' && told !== 'blocked')) {
95
+ tell({ afield: 'working', working: false, stoppedAt })
96
+ }
97
+ told = now
98
+ }, STOP_HOLD_MS)
99
+ stopTimer.unref()
100
+ }
101
+ }
102
+
103
+ // Set for a background child: the supervisor seeds it before forking and the
104
+ // afield-session extension rewrites it as pi switches conversations. The
105
+ // program may not be pi at all, so this is the only thing that knows what
106
+ // conversation a viewer was admitted to.
107
+ const identityPath = process.env.AFIELD_IDENTITY
108
+
109
+ // The program, its screen, and the folder it is in. Set once, when listening
110
+ // starts, and never replaced.
111
+ let active = null
112
+ let foreground = null
113
+ let foregroundTimer = null
114
+ const checkForeground = () => {
115
+ const name = active?.session.foreground()
116
+ if (!name || name === foreground) return
117
+ foreground = name
118
+ tell({ afield: 'foreground', name })
119
+ }
120
+
121
+ // Non-null while a snapshot is being taken. The mirror stops consuming for
122
+ // that moment so the screen it serializes is exactly the screen these bytes
123
+ // come after — see admit().
124
+ let held = null
125
+
126
+ const title = `${basename(program)} — ${cwd}`
127
+
128
+ /**
129
+ * The place this PTY is in, as one frame. The child is the only sender: it
130
+ * owns the identity file, so a relay never has to guess. `name` and `path`
131
+ * come from the same formatter a menu row uses.
132
+ */
133
+ const processFrame = state => JSON.stringify({
134
+ ...state,
135
+ processId: process.env.AFIELD_PROCESS_ID,
136
+ startedAt: Number(process.env.AFIELD_STARTED_AT) || undefined,
137
+ ...placeNames(state.cwd),
138
+ })
139
+
140
+ /** Start the program and make it the session. Called exactly once. */
141
+ const start = () => {
142
+ // PI_PROGRAM_STATUS: pi otherwise reports its status only to a terminal
143
+ // that answers its query, and nothing reliably answers for this PTY --
144
+ // there may be no viewer at all when pi starts.
145
+ const env = { ...process.env, PI_PROGRAM_STATUS: '1' }
146
+ const session = new Session({ command: program, args, cwd, env })
147
+ const onStatus = state => { programState = state; settleWorking() }
148
+ const unit = { session, mirror: new Mirror({ ...session.size, scrollback, onStatus }) }
149
+
150
+ unit.stopIdentity = identityPath && watchIdentity(identityPath, text => {
151
+ const frame = processFrame(JSON.parse(text))
152
+ for (const viewer of viewers) viewer.send(PROCESS, frame)
153
+ })
154
+
155
+ /**
156
+ * A resize re-sends the screen rather than letting viewers reflow it.
157
+ *
158
+ * The client's VT core and the mirror are separate implementations and
159
+ * need not rewrap history the same way, so a viewer that reflows its own
160
+ * history can end up with something the mirror disagrees with — and
161
+ * different again from what the next viewer to connect is given. The
162
+ * mirror is the only thing allowed to reflow: everyone else is handed the
163
+ * result.
164
+ */
165
+ session.onResize = size => {
166
+ unit.mirror.resize(size.cols, size.rows)
167
+ for (const viewer of viewers) if (viewer.queue === null) {
168
+ if (viewer.kind === 'attach') {
169
+ // A real terminal receives pi's redraw through the PTY. Sending it a
170
+ // fresh snapshot would clear its scrollback again.
171
+ viewer.sendSize(size)
172
+ continue
173
+ }
174
+ // Same unhandled-rejection guard as admit(): a throw while serializing
175
+ // the snapshot after a resize must not take the server (and the pi it
176
+ // owns) down with it. The viewer just loses the refresh.
177
+ sendScreen(viewer).catch(err => {
178
+ console.error('server: could not re-send the screen after a resize', err)
179
+ viewer.close()
180
+ })
181
+ }
182
+ }
183
+
184
+ let announcedActivity = 0
185
+ session.onData = data => {
186
+ const now = Date.now()
187
+ if (now - announcedActivity >= ACTIVITY_MS) {
188
+ announcedActivity = now
189
+ tell({ afield: 'activity', at: now })
190
+ }
191
+ // Viewers first: the mirror is a convenience, and a failure in it must not
192
+ // cost anyone bytes it was about to be sent.
193
+ for (const viewer of viewers) {
194
+ if (viewer.queue) viewer.queue.push(data)
195
+ else if (viewer.queue === null && !viewer.output(data)) viewers.delete(viewer)
196
+ }
197
+ if (held) held.push(data)
198
+ else unit.mirror.write(data)
199
+ }
200
+
201
+ session.onExit = status => {
202
+ clearInterval(foregroundTimer)
203
+ unit.stopIdentity?.()
204
+ for (const viewer of viewers) viewer.close(1000, 'session ended')
205
+ onExit?.(status)
206
+ }
207
+
208
+ active = unit
209
+ if (process.connected) {
210
+ foregroundTimer = setInterval(checkForeground, FOREGROUND_MS)
211
+ foregroundTimer.unref()
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Give a viewer the screen, then everything that happened while we took it.
217
+ *
218
+ * The split has to be exact. Draining alone is not enough: the parser is
219
+ * asynchronous, so bytes written behind the drain marker are parsed after the
220
+ * snapshot is serialized and would be in neither the screen nor the queue.
221
+ * Holding them out of the mirror instead makes the boundary a real one.
222
+ *
223
+ * Admissions are serialized, since two at once would fight over what is held.
224
+ */
225
+ let admitting = Promise.resolve()
226
+ const sendScreen = viewer => {
227
+ // `catch` before `then`, or one failure poisons the chain and every viewer
228
+ // after it is refused a screen for the life of the process — which, since
229
+ // the server is the session, means until pi is killed.
230
+ admitting = admitting.catch(() => {}).then(async () => {
231
+ if (!viewer.open) return
232
+ const unit = active
233
+
234
+ held = []
235
+ viewer.queue = []
236
+ try {
237
+ await unit.mirror.drain()
238
+ const snapshot = Buffer.from(unit.mirror.snapshot())
239
+
240
+ // Size before screen: the snapshot is drawn for the PTY's grid, so a
241
+ // viewer that asked for a different one has to be rendering at this
242
+ // size before it arrives.
243
+ viewer.sendSize(unit.session.size)
244
+ // Screen, then the bytes the screen could not contain yet, then what
245
+ // arrived while it was being taken.
246
+ if (viewer.output(snapshot)) {
247
+ const rest = unit.mirror.pending.length ? [Buffer.from(unit.mirror.pending), ...viewer.queue] : viewer.queue
248
+ for (const chunk of rest) if (!viewer.output(chunk)) break
249
+ }
250
+ } finally {
251
+ // Whatever happened to this viewer, the mirror has to be fed again or
252
+ // every screen after this one is stale.
253
+ viewer.queue = null
254
+ for (const chunk of held) unit.mirror.write(chunk)
255
+ held = null
256
+ }
257
+ })
258
+ return admitting
259
+ }
260
+
261
+ const admit = viewer => {
262
+ // Before the screen: a viewer knows which place it landed on by the frame
263
+ // that says so, and the frame cannot be second if the screen is to be
264
+ // committed to it. Reading the file rather than a cached copy, since
265
+ // admission can beat the watcher's first poll.
266
+ if (identityPath) viewer.send(PROCESS, processFrame(JSON.parse(readFileSync(identityPath, 'utf8'))))
267
+ active.session.add(viewer)
268
+ viewer.title(title)
269
+ return sendScreen(viewer)
270
+ }
271
+
272
+ let fitTimer = null
273
+ const scheduleFit = () => {
274
+ if (fitTimer) return
275
+ fitTimer = setTimeout(() => { fitTimer = null; active?.session.fit() }, RESIZE_COALESCE_MS)
276
+ fitTimer.unref()
277
+ }
278
+
279
+ // The supervisor serves the page and the login; this only takes its sockets.
280
+ const http = createServer()
281
+
282
+ const wss = new WebSocketServer({
283
+ server: http,
284
+ path: '/ws',
285
+ maxPayload: MAX_FRAME,
286
+ handleProtocols: () => 'tty',
287
+ })
288
+
289
+ wss.on('error', err => {
290
+ console.error(`server: cannot listen on ${socketPath}: ${err.message}`)
291
+ onExit?.({ exitCode: 1, signal: 0 })
292
+ })
293
+
294
+ wss.on('connection', ws => {
295
+ const viewer = new Viewer(ws)
296
+ viewers.add(viewer)
297
+ ws.on('pong', () => { viewer.alive = true })
298
+
299
+ ws.on('message', data => {
300
+ const buf = Buffer.from(data)
301
+ if (!viewer.started) {
302
+ const hello = decodeHandshake(buf)
303
+ if (!hello) return void viewer.close(1002, 'bad handshake')
304
+ viewer.started = true
305
+ viewer.kind = hello.client === 'attach' ? 'attach' : 'browser'
306
+ viewer.size = { cols: hello.cols, rows: hello.rows }
307
+ admit(viewer).catch(err => {
308
+ console.error('server: could not admit a viewer', err)
309
+ viewer.close(1011, 'could not send the screen')
310
+ })
311
+ return
312
+ }
313
+ if (buf.length === 0) return
314
+ switch (buf[0]) {
315
+ case INPUT:
316
+ active.session.write(buf.subarray(1))
317
+ break
318
+ case RESIZE: {
319
+ const size = decodeSize(buf.subarray(1))
320
+ if (size) {
321
+ viewer.size = size
322
+ scheduleFit()
323
+ }
324
+ break
325
+ }
326
+ default:
327
+ break
328
+ }
329
+ })
330
+
331
+ const drop = () => {
332
+ viewers.delete(viewer)
333
+ active?.session.remove(viewer)
334
+ }
335
+ ws.on('close', drop)
336
+ ws.on('error', drop)
337
+ })
338
+
339
+ const ping = setInterval(() => {
340
+ for (const viewer of viewers) {
341
+ if (!viewer.open) continue
342
+ if (!viewer.alive) { viewer.ws.terminate(); continue }
343
+ viewer.alive = false
344
+ viewer.ws.ping()
345
+ }
346
+ }, PING_MS)
347
+ ping.unref()
348
+
349
+ // The program starts here rather than before listening: one that cannot be
350
+ // served should never have been spawned, and a pi that starts only to be
351
+ // killed leaves a session file behind for the folder list to offer.
352
+ // The socket is reachable only by whatever can open that file -- never a
353
+ // network port.
354
+ http.listen(socketPath, start)
355
+
356
+ return {
357
+ http,
358
+ async close() {
359
+ clearInterval(ping)
360
+ clearTimeout(fitTimer)
361
+ clearTimeout(stopTimer)
362
+ clearInterval(foregroundTimer)
363
+ active?.stopIdentity?.()
364
+ active?.session.kill()
365
+ // Terminated, not closed: a close frame waits for one back, and a phone
366
+ // asleep behind a dead tunnel does not answer for 30 seconds — which is
367
+ // how long Ctrl-C would appear to hang, since an upgraded socket holds
368
+ // http.close() open until it goes. Nobody is owed a handshake from a
369
+ // server that is already gone.
370
+ for (const viewer of viewers) viewer.ws.terminate()
371
+ wss.close()
372
+ await new Promise(res => http.close(res))
373
+ },
374
+ }
375
+ }
@@ -0,0 +1,159 @@
1
+ // The screen, kept here so a new viewer does not have to make pi redraw for it.
2
+ //
3
+ // Making pi redraw is not cheap: it renders relatively and re-renders its whole
4
+ // transcript on SIGWINCH, which grows with the conversation — about 12 KB after
5
+ // one turn and linear from there. This turns every attach from O(transcript)
6
+ // into O(screen).
7
+ // Both ship CommonJS with no ESM named exports, so they arrive as one object.
8
+ import headless from '@xterm/headless'
9
+ import serialize from '@xterm/addon-serialize'
10
+
11
+ const { Terminal } = headless
12
+ const { SerializeAddon } = serialize
13
+
14
+ // pi sets these once at startup and never again, not even on resize, so a
15
+ // viewer restored from a serialized screen alone would have bracketed paste off
16
+ // and the wrong key encoding — and would silently send pi differently-encoded
17
+ // keys. The snapshot carries them.
18
+ const PREAMBLE = '\x1b[?2004h\x1b[>7u'
19
+
20
+ // Reset first: a reconnecting viewer already has a screen, a cursor, modes and
21
+ // scrollback, and serialized VT assumes a fresh terminal and resets nothing.
22
+ //
23
+ // RIS alone is not enough. It leaves the saved lines alone, so the history below
24
+ // would stack underneath whatever the viewer had before it dropped — duplicated
25
+ // and out of order. ED 3 is what clears them.
26
+ const RESET = '\x1bc\x1b[3J'
27
+
28
+ const ESC = 0x1b
29
+ const BEL = 0x07
30
+
31
+ // Far larger than any real sequence, including a long OSC title.
32
+ const MAX_PENDING = 64 * 1024
33
+
34
+ // What pi's program status report (OSC 7501) can say. Anything else is a
35
+ // payload this does not understand, and is not a state.
36
+ const PROGRAM_STATES = new Set(['idle', 'working', 'blocked', 'done', 'error', 'clear'])
37
+
38
+ /**
39
+ * Index just past the escape sequence starting at `i`, or -1 if it is unfinished.
40
+ *
41
+ * Scanning forward rather than back from the end is what makes this exact: a
42
+ * title longer than any fixed lookbehind, or a sequence whose payload contains
43
+ * another ESC, both defeat a backward search.
44
+ */
45
+ const escapeEnd = (buf, i) => {
46
+ const kind = buf[i + 1]
47
+ if (kind === undefined) return -1
48
+
49
+ if (kind === 0x5b) { // CSI: params, then 0x40..0x7e
50
+ let j = i + 2
51
+ while (j < buf.length && buf[j] >= 0x20 && buf[j] <= 0x3f) j++
52
+ return j < buf.length && buf[j] >= 0x40 && buf[j] <= 0x7e ? j + 1 : -1
53
+ }
54
+ if (kind === 0x5d) { // OSC: ends BEL or ST
55
+ for (let j = i + 2; j < buf.length; j++) {
56
+ if (buf[j] === BEL) return j + 1
57
+ if (buf[j] === ESC && buf[j + 1] === 0x5c) return j + 2
58
+ }
59
+ return -1
60
+ }
61
+ if (kind === 0x50 || kind === 0x58 || kind === 0x5e || kind === 0x5f) { // DCS/SOS/PM/APC: ST
62
+ for (let j = i + 2; j < buf.length; j++) {
63
+ if (buf[j] === ESC && buf[j + 1] === 0x5c) return j + 2
64
+ }
65
+ return -1
66
+ }
67
+ if (kind >= 0x20 && kind <= 0x2f) { // intermediates, then a final
68
+ let j = i + 1
69
+ while (j < buf.length && buf[j] >= 0x20 && buf[j] <= 0x2f) j++
70
+ return j < buf.length && buf[j] >= 0x30 && buf[j] <= 0x7e ? j + 1 : -1
71
+ }
72
+ return i + 2 // any other two-byte escape
73
+ }
74
+
75
+ /**
76
+ * How much of `buf` can be parsed without leaving a sequence half-finished.
77
+ *
78
+ * The parser keeps a partial sequence as invisible state, and `serialize()` only
79
+ * ever sees committed cells. So a snapshot taken mid-character omits its leading
80
+ * byte while the viewer still receives the continuation — an orphaned tail like
81
+ * `55;95;255m`, which is the corruption this whole server exists to stop.
82
+ *
83
+ * Every buffer starts on a clean boundary, because this is what decides where
84
+ * the last one ended. That is what lets the scan run forward and be exact.
85
+ */
86
+ const completeUpTo = buf => {
87
+ let i = 0
88
+ let clean = 0
89
+ while (i < buf.length) {
90
+ const b = buf[i]
91
+ if (b === ESC) {
92
+ const end = escapeEnd(buf, i)
93
+ if (end === -1) return clean
94
+ i = end
95
+ } else if (b < 0x80) {
96
+ i++
97
+ } else {
98
+ const width = b < 0xc0 ? 1 : b < 0xe0 ? 2 : b < 0xf0 ? 3 : b < 0xf8 ? 4 : 1
99
+ if (i + width > buf.length) return clean
100
+ i += width
101
+ }
102
+ clean = i
103
+ }
104
+ return clean
105
+ }
106
+
107
+ export class Mirror {
108
+ constructor({ cols, rows, scrollback = 0, onStatus = () => {} }) {
109
+ this.scrollback = scrollback
110
+ // Bytes held back because they do not yet form a complete sequence. They
111
+ // belong to a new viewer after the snapshot, since the screen cannot
112
+ // contain them yet.
113
+ this.pending = Buffer.alloc(0)
114
+ this.term = new Terminal({ cols, rows, allowProposedApi: true, scrollback })
115
+ this.serializer = new SerializeAddon()
116
+ this.term.loadAddon(this.serializer)
117
+ // The program's status, as pi reports it (`state=working:app=pi:...`). The
118
+ // parser is the one reader of the stream that only ever sees whole
119
+ // sequences, however the PTY happened to split them.
120
+ this.term.parser.registerOscHandler(7501, data => {
121
+ const state = /^state=([a-z]+)(?::|$)/.exec(data)?.[1]
122
+ if (PROGRAM_STATES.has(state)) onStatus(state)
123
+ return true
124
+ })
125
+ }
126
+
127
+ write(bytes) {
128
+ const buf = this.pending.length ? Buffer.concat([this.pending, bytes]) : Buffer.from(bytes)
129
+ // A program that opens a sequence and never closes it would otherwise hold
130
+ // everything after it in memory for ever. Past this, take the parser's word
131
+ // for it: a stream this malformed is already lost, and the mirror recovering
132
+ // beats the server growing without bound.
133
+ const cut = buf.length > MAX_PENDING ? buf.length : completeUpTo(buf)
134
+ this.pending = Buffer.from(buf.subarray(cut))
135
+ if (cut > 0) this.term.write(buf.subarray(0, cut))
136
+ }
137
+
138
+ resize(cols, rows) { this.term.resize(cols, rows) }
139
+
140
+ /**
141
+ * The screen, and the history above it, as bytes a terminal can apply.
142
+ *
143
+ * The history is not a luxury: pi renders inline and does not page itself, so
144
+ * the terminal's scrollback is the only way to read back through a
145
+ * conversation, and a snapshot without it makes every reload amnesiac.
146
+ */
147
+ snapshot() {
148
+ return RESET + PREAMBLE + this.serializer.serialize({ scrollback: this.scrollback })
149
+ }
150
+
151
+ /**
152
+ * Everything written so far has been parsed.
153
+ *
154
+ * `Terminal.write` is asynchronous, so a snapshot taken without draining can
155
+ * miss bytes that are already in the stream — which is the difference between
156
+ * a viewer seeing them twice and not at all.
157
+ */
158
+ drain() { return new Promise(resolve => this.term.write('', resolve)) }
159
+ }
@@ -0,0 +1,51 @@
1
+ // Who is allowed to open a socket to the terminal.
2
+ //
3
+ // A WebSocket handshake is exempt from the same-origin policy and has no
4
+ // preflight, so any page in any tab can open one to `ws://127.0.0.1:7681/ws`
5
+ // and start typing into pi. Binding to loopback does not help — the browser is
6
+ // on this machine. `Origin` is the only thing that separates the real client
7
+ // from a hostile page, and browsers cannot set it themselves.
8
+
9
+ // A rebound name is still a name, and a browser sends a literal address as Host
10
+ // only when the page it came from was loaded from that address. `localhost`
11
+ // resolves locally rather than through DNS, so it cannot be rebound either.
12
+ const LITERAL = /^(\d{1,3}(\.\d{1,3}){3}|\[[0-9a-f:]+\])$/i
13
+
14
+ const withoutPort = value =>
15
+ value.startsWith('[') ? value.slice(0, value.indexOf(']') + 1) : value.split(':')[0]
16
+
17
+ /** An address, unlike a name, is not something DNS can be made to lie about. */
18
+ export const isAddress = host => {
19
+ const name = withoutPort(host)
20
+ return name === 'localhost' || LITERAL.test(name)
21
+ }
22
+
23
+ /**
24
+ * `hostname` is the one name a proxy is allowed to present, given with
25
+ * `--hostname`. It has to be declared rather than discovered: a hostname is
26
+ * trustworthy exactly when the operator asserted it, because producing a
27
+ * plausible-looking name is the whole of the DNS rebinding trick.
28
+ */
29
+ export function originAllowed({ origin, host, hostname }) {
30
+ // Nothing but a browser sends Origin, and nothing but a browser is bound by
31
+ // it — attach, curl and the tests send none, and an attacker who is not a
32
+ // browser forges whatever it likes. Refusing a missing one costs attach and
33
+ // buys nothing.
34
+ if (!origin) return true
35
+ if (!host) return false
36
+
37
+ // Host is attacker-controlled, so Origin matching it is not enough on its
38
+ // own: rebinding makes both of them say evil.com.
39
+ if (!isAddress(host) && withoutPort(host) !== hostname) return false
40
+
41
+ // Scheme is deliberately not compared. `URL.host` drops default ports, so
42
+ // http://name and https://name both reduce to `name`; a page on plain http
43
+ // could then pass a wss:// handshake to the terminal. That needs an
44
+ // attacker-controlled http endpoint on the same declared hostname, which the
45
+ // threat this check addresses (a page on some other site) does not have.
46
+ try {
47
+ return new URL(origin).host === host
48
+ } catch {
49
+ return false
50
+ }
51
+ }