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,264 @@
1
+ // `afield attach`: a viewer like any other, in a real terminal.
2
+ //
3
+ // It speaks the same protocol as the phone, so the desktop is not a special
4
+ // case and cannot resize the PTY behind the server's back. What it has to do
5
+ // that a browser gets for free is act like a terminal: raw mode restored
6
+ // whatever happens, SIGWINCH forwarded, and Ctrl-C and Ctrl-Z passed through to
7
+ // the far side rather than acted on here.
8
+ import { writeFileSync } from 'node:fs'
9
+ import { readFile } from 'node:fs/promises'
10
+ import { homedir } from 'node:os'
11
+ import { join } from 'node:path'
12
+ import { WebSocket } from 'ws'
13
+ import { keyHeaders } from './auth.js'
14
+ import { INPUT, RESIZE, OUTPUT, SET_TITLE, SET_SIZE, PROCESS } from './protocol.js'
15
+ import { ask, endOne, fetchPlaces, indexArgument, matching, pickFrom } from './picker.js'
16
+
17
+ // Ctrl-] detaches, the way telnet and ssh do it. Not Ctrl-\, which pi wants,
18
+ // and not Ctrl-C or Ctrl-Z, which are the whole point of passing through.
19
+ //
20
+ // The snapshot's preamble enables the kitty keyboard protocol, so a terminal
21
+ // that honors it reports Ctrl-] as `ESC[93;5u` — the ] codepoint with the
22
+ // ctrl bit set — instead of the raw 0x1d byte. Both are the same chord.
23
+ const DETACH = 0x1d
24
+ const DETACH_KITTY = /\x1b\[93(:[0-9]+)?;\d+u/
25
+
26
+ // Detaching leaves the server up for the phone, so it must not report itself
27
+ // as the session ending.
28
+ const DETACHED = 3
29
+
30
+ // The supervisor's code for the session itself being over — pi exited, or
31
+ // someone ended it. Every other way a socket can close here is this terminal
32
+ // failing to stay attached, and reports itself as a failure.
33
+ const SESSION_ENDED = 1001
34
+
35
+ // Same chord in either encoding.
36
+ export const isDetach = chunk => chunk.includes(DETACH) || DETACH_KITTY.test(chunk)
37
+
38
+ // The chord is the one thing a viewer cannot discover on its own, so say it
39
+ // once on the way in. Long enough to read, short enough not to be in the way.
40
+ const BANNER = '\r\n\r\n [afield] Ctrl-] to detach\r\n\r\n'
41
+ const BANNER_MS = 2000
42
+ const LAST_SESSION = join(homedir(), '.afield-last-terminal')
43
+
44
+ const frame = (cmd, text) => Buffer.concat([Buffer.from([cmd]), Buffer.from(text)])
45
+
46
+ // A place this terminal wrote on its way out, or null. Unreadable, truncated,
47
+ // or from a build that stored something else: all of them mean the same thing
48
+ // here, which is that there is no previous session to reattach to.
49
+ async function readLastSession() {
50
+ try { return JSON.parse(await readFile(LAST_SESSION, 'utf8')) } catch { return null }
51
+ }
52
+
53
+ const rememberSession = place => writeFileSync(LAST_SESSION, JSON.stringify(place), { mode: 0o600 })
54
+
55
+ /**
56
+ * Which session to join: a running row selected by a bare number, the one a
57
+ * substring of `match` picks out uniquely, or, failing either, a numbered prompt.
58
+ *
59
+ * Reads `GET /places` rather than a fixed id, since sessions come and go — the
60
+ * list this shows is exactly the one the phone's menu would.
61
+ */
62
+ export async function resolveSession(url, { session, match, headers }) {
63
+ if (typeof session === 'string') return { processId: session }
64
+
65
+ const places = params => fetchPlaces(url, { headers, params, prefix: 'attach: ' })
66
+ const { sessions } = await places() ?? {}
67
+ if (!sessions) return null
68
+ if (session) {
69
+ // A remembered session a server restart unlisted is still joinable by its
70
+ // own id, which also covers a fork -- the list this falls back past never
71
+ // shows one, yet `rememberSession` will happily have recorded it.
72
+ // A remembered place can have no processId, and non-running rows have
73
+ // none either, so only compare when there is one to compare -- otherwise
74
+ // this matches the first listed row that happens not to be running.
75
+ const previous = (session.processId && sessions.find(s => s.processId === session.processId))
76
+ ?? sessions.find(s => s.id === session.id && s.cwd === session.cwd)
77
+ ?? (session.id && await places({ id: session.id }))?.sessions[0]
78
+ if (!previous) console.error('attach: previous conversation is no longer listed')
79
+ return previous ?? null
80
+ }
81
+ if (sessions.length === 0 && !match) {
82
+ console.error('attach: no sessions to join yet')
83
+ return null
84
+ }
85
+
86
+ const index = indexArgument(match)
87
+ if (index !== null) {
88
+ const running = sessions.filter(s => s.running)
89
+ if (!Number.isSafeInteger(index) || index < 1 || index > running.length) {
90
+ console.error(`attach: no running session numbered ${match}`)
91
+ return null
92
+ }
93
+ return running[index - 1]
94
+ }
95
+
96
+ const candidates = match ? matching(sessions, match) : sessions
97
+ if (candidates.length === 1) return candidates[0]
98
+ if (candidates.length === 0) {
99
+ // The listing omits forked sessions, so a fragment can name a session the
100
+ // menu never showed; the server still answers that one, by exact id.
101
+ const exact = match ? (await places({ id: match }))?.sessions[0] : null
102
+ if (exact) return exact
103
+ console.error(`attach: nothing matches ${JSON.stringify(match)}`)
104
+ return null
105
+ }
106
+
107
+ console.error('attach: which session?')
108
+ const choice = await pickFrom(candidates, { ask, out: console.error })
109
+ return choice ?? null
110
+ }
111
+
112
+ export async function attach({ url, session, match, previous = false }) {
113
+ if (previous && !session) {
114
+ session = await readLastSession()
115
+ if (!session) {
116
+ console.error('attach: no previous session to reattach')
117
+ process.exit(1)
118
+ }
119
+ }
120
+
121
+ const { stdin, stdout } = process
122
+ if (!stdin.isTTY) {
123
+ console.error('attach: not a terminal')
124
+ process.exit(2)
125
+ }
126
+
127
+ // Before the terminal is touched, so a refusal leaves it exactly as found.
128
+ const headers = keyHeaders()
129
+
130
+ let place = await resolveSession(url, { session, match, headers })
131
+ if (!place) process.exit(1)
132
+ const target = new URL(url)
133
+ if (place.processId) target.searchParams.set('process', place.processId)
134
+ else {
135
+ target.searchParams.set('session', place.id)
136
+ target.searchParams.set('cwd', place.cwd)
137
+ }
138
+
139
+ const ws = new WebSocket(target, ['tty'], { headers })
140
+ let restored = false
141
+ let inputHandler, resizeHandler, timer
142
+
143
+ // The snapshot's preamble leaves the terminal in the kitty keyboard protocol
144
+ // and bracketed paste, and pi's own frames leave the cursor hidden and may
145
+ // leave synchronized output holding. Undo all of it on the way out, or the
146
+ // shell that comes back is fed escape-encoded keys and has no cursor.
147
+ const UNPREP = '\x1b[?2026l\x1b[<1u\x1b[?2004l\x1b[?25h'
148
+
149
+ // One restore path for every exit, including a throw: leaving a terminal in
150
+ // raw mode is the kind of bug that outlives the process that caused it.
151
+ const restore = () => {
152
+ if (restored) return
153
+ restored = true
154
+ stdout.write(UNPREP)
155
+ if (stdin.isRaw) stdin.setRawMode(false)
156
+ stdin.pause()
157
+ }
158
+ // Restores the terminal before writing: a message printed in raw mode
159
+ // staircases. Diagnostics go to stderr, so the reason a terminal detached
160
+ // itself survives `attach > somewhere`; the two messages that are part of
161
+ // the session on screen ask for stdout by name.
162
+ const leave = (message, code = 0, stream = process.stderr) => {
163
+ restore()
164
+ if (message) stream.write(`\r\n${message}\r\n`)
165
+ process.exit(code)
166
+ }
167
+ const onExit = restore
168
+ const onUncaughtException = err => { restore(); throw err }
169
+ // Killed from outside, the terminal still gets restored.
170
+ const onSigterm = () => leave()
171
+ const onSighup = () => leave()
172
+ process.on('exit', onExit)
173
+ process.on('uncaughtException', onUncaughtException)
174
+ process.on('SIGTERM', onSigterm)
175
+ process.on('SIGHUP', onSighup)
176
+
177
+ const size = () => ({ columns: stdout.columns || 80, rows: stdout.rows || 24 })
178
+
179
+ ws.on('open', () => {
180
+ stdin.setRawMode(true)
181
+ stdin.resume()
182
+
183
+ // The server sends nothing until this hello, so holding it back gives the
184
+ // banner the screen to itself and the snapshot repaints over it. No output
185
+ // is buffered or lost here — none has been asked for yet.
186
+ stdout.write(`\x1b[2J\x1b[H${BANNER}`)
187
+ let started = false
188
+ const start = () => {
189
+ if (started) return
190
+ started = true
191
+ clearTimeout(timer)
192
+ ws.send(JSON.stringify({ client: 'attach', ...size() }))
193
+ resizeHandler = () => ws.send(frame(RESIZE, JSON.stringify(size())))
194
+ stdout.on('resize', resizeHandler)
195
+ }
196
+ timer = setTimeout(start, BANNER_MS)
197
+
198
+ inputHandler = chunk => {
199
+ if (isDetach(chunk)) leave(
200
+ 'detached; the session is still running\r\n' +
201
+ ' rejoin it afield attach\r\n' +
202
+ ' end it afield end [fragment|n]\r\n' +
203
+ ' end all Ctrl-C in the terminal serving it', DETACHED, stdout)
204
+ // The key that dismisses the banner is spent doing so: the session has
205
+ // not been shown yet, so it was not typed at what is about to appear.
206
+ if (!started) return start()
207
+ ws.send(frame(INPUT, chunk))
208
+ }
209
+ stdin.on('data', inputHandler)
210
+ })
211
+
212
+ let announced = null
213
+ let receivedProcess = false
214
+
215
+ ws.on('message', data => {
216
+ const buf = Buffer.from(data)
217
+ if (buf[0] === OUTPUT) {
218
+ // A terminal that cannot keep up must slow the socket down rather than
219
+ // let the server's queue grow until it disconnects us.
220
+ if (!stdout.write(buf.subarray(1))) {
221
+ ws._socket.pause()
222
+ stdout.once('drain', () => ws._socket.resume())
223
+ }
224
+ }
225
+ else if (buf[0] === PROCESS) {
226
+ receivedProcess = true
227
+ place = { ...place, ...JSON.parse(buf.subarray(1).toString()) }
228
+ rememberSession(place)
229
+ }
230
+ else if (buf[0] === SET_TITLE) stdout.write(`\x1b]0;${buf.subarray(1)}\x07`)
231
+ else if (buf[0] === SET_SIZE) {
232
+ // A real terminal cannot be resized from in here, so when a narrower
233
+ // viewer owns the grid the program simply draws in part of this window.
234
+ // Say so once, or it reads as a rendering fault.
235
+ const { columns, rows } = JSON.parse(buf.subarray(1))
236
+ const note = `${columns}x${rows}`
237
+ if (note !== announced && columns < size().columns) {
238
+ stdout.write(`\r\n[drawing at ${note} — a narrower viewer owns the grid]\r\n`)
239
+ }
240
+ announced = note
241
+ }
242
+ })
243
+
244
+ ws.on('close', async (code, reason) => {
245
+ if (code === 4006 && !receivedProcess) {
246
+ clearTimeout(timer)
247
+ if (inputHandler) stdin.removeListener('data', inputHandler)
248
+ if (resizeHandler) stdout.removeListener('resize', resizeHandler)
249
+ restore()
250
+ if (await endOne(url, headers)) {
251
+ process.removeListener('exit', onExit)
252
+ process.removeListener('uncaughtException', onUncaughtException)
253
+ process.removeListener('SIGTERM', onSigterm)
254
+ process.removeListener('SIGHUP', onSighup)
255
+ return attach({ url, session: { id: place.id, cwd: place.cwd } })
256
+ }
257
+ return leave(null, 1)
258
+ }
259
+ leave(
260
+ code === 1013 ? 'disconnected: this terminal fell too far behind' : `disconnected (${code}) ${reason}`,
261
+ code === SESSION_ENDED ? 0 : 1)
262
+ })
263
+ ws.on('error', err => leave(`attach: ${err.message}`, 1))
264
+ }
package/server/auth.js ADDED
@@ -0,0 +1,169 @@
1
+ // Sign-in, for every connection unless `serve --no-sign-in`.
2
+ //
3
+ // There is one server key per user, kept in the config folder, so `serve` and
4
+ // the CLI commands both read it. It is made the first time it is needed and
5
+ // never printed. A browser signs in once with a pairing key that `serve`
6
+ // prints, typed or opened from the link in its QR code, and is handed the
7
+ // server key itself as its cookie: the key does nothing else, so a cookie
8
+ // made from it would be worth exactly as much. A restart changes nothing;
9
+ // `afield reset-key` makes a new server key, which signs every device out.
10
+ //
11
+ // It has to be a cookie. Basic auth cannot work here whatever the server does:
12
+ // Safari puts no Authorization header on a WebSocket handshake and the page has
13
+ // no way to add one, so the terminal would never connect. A cookie is the one
14
+ // credential a browser carries onto a handshake.
15
+ import { createHash, randomBytes, randomInt, timingSafeEqual } from 'node:crypto'
16
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
17
+ import { homedir } from 'node:os'
18
+ import { dirname, join } from 'node:path'
19
+
20
+ const COOKIE = 'afield'
21
+ // The longest a browser keeps a cookie (Chrome's cap).
22
+ const MAX_AGE = 60 * 60 * 24 * 400
23
+
24
+ // Short enough to type on a phone, with no 0/o or 1/l/i to mix up, in groups
25
+ // of four as printed. A pairing key's 10 of these 30 characters is 49 bits,
26
+ // far past guessing over the network.
27
+ const ALPHABET = '23456789abcdefghjkmnpqrstvwxyz'
28
+ const typeable = length => Array.from({ length }, () => ALPHABET[randomInt(ALPHABET.length)])
29
+ .join('').match(/.{1,4}/g).join('-')
30
+
31
+ const digest = value => createHash('sha256').update(value).digest()
32
+ // Capitals, spaces and dashes don't count, so a key can be typed as printed
33
+ // on a phone keyboard.
34
+ const normalize = value => value.toLowerCase().replace(/[\s-]/g, '')
35
+
36
+ // Read on each call rather than once at import, so tests can point it elsewhere.
37
+ export const keyPath = () =>
38
+ join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'afield', 'key')
39
+
40
+ /** This user's server key, or undefined before any `serve` has needed one. */
41
+ export function readKey() {
42
+ try {
43
+ return readFileSync(keyPath(), 'utf8').trim()
44
+ } catch (err) {
45
+ if (err.code === 'ENOENT') return undefined
46
+ throw err
47
+ }
48
+ }
49
+
50
+ const writeKey = flag => {
51
+ const key = randomBytes(32).toString('base64url')
52
+ mkdirSync(dirname(keyPath()), { recursive: true, mode: 0o700 })
53
+ writeFileSync(keyPath(), `${key}\n`, { mode: 0o600, flag })
54
+ return key
55
+ }
56
+
57
+ /** The server key, made on first use and readable only by this user. */
58
+ export function ensureKey() {
59
+ const existing = readKey()
60
+ if (existing === undefined) return writeKey('wx')
61
+ if (!existing) throw new Error(`${keyPath()} has no key in it; delete it or run: afield reset-key`)
62
+ return existing
63
+ }
64
+
65
+ /** A new server key in place of the old, for `afield reset-key`. */
66
+ export const resetKey = () => writeKey('w')
67
+
68
+ /** Request headers that sign in as this user, for the CLI commands. */
69
+ export function keyHeaders() {
70
+ const key = readKey()
71
+ return key ? { cookie: `${COOKIE}=${key}` } : undefined
72
+ }
73
+
74
+ export class Auth {
75
+ #key
76
+ // The current pairing key. Kept in memory, so a restart voids it.
77
+ #pairing
78
+
79
+ /** No key means no sign-in. */
80
+ constructor(key) {
81
+ this.#key = key
82
+ }
83
+
84
+ get required() {
85
+ return this.#key !== undefined
86
+ }
87
+
88
+ admits(req) {
89
+ if (!this.required) return true
90
+ const value = req.headers.cookie?.split(';')
91
+ .map(part => part.trim())
92
+ .find(part => part.startsWith(`${COOKIE}=`))
93
+ ?.slice(COOKIE.length + 1)
94
+ return Boolean(value) && timingSafeEqual(digest(value), digest(this.#key))
95
+ }
96
+
97
+ /** A new pairing key, voiding the last. It signs in one browser, so what a
98
+ * log or history keeps is a key already spent. */
99
+ pair() {
100
+ this.#pairing = typeable(10)
101
+ return this.#pairing
102
+ }
103
+
104
+ // Hashed before comparing so both sides are the same length, which is what
105
+ // timingSafeEqual needs and what keeps the length of the real one quiet.
106
+ redeem(attempt) {
107
+ if (this.#pairing === undefined || !timingSafeEqual(digest(normalize(attempt)), digest(normalize(this.#pairing)))) return false
108
+ this.#pairing = undefined
109
+ return true
110
+ }
111
+
112
+ // Strict: this cookie exists to open a shell, and no other site has any
113
+ // business causing a request that carries it. Opening the QR link from the
114
+ // camera, or submitting the form, is not another site's request, so the
115
+ // cookie set there still rides the redirect to the page.
116
+ cookie({ secure }) {
117
+ return `${COOKIE}=${this.#key}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${MAX_AGE}` +
118
+ (secure ? '; Secure' : '')
119
+ }
120
+ }
121
+
122
+ export const loginPage = (refused = '') => `<!doctype html>
123
+ <html lang="en">
124
+ <head>
125
+ <meta charset="utf-8">
126
+ <title>afield</title>
127
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
128
+ <meta name="apple-mobile-web-app-capable" content="yes">
129
+ <meta name="apple-mobile-web-app-status-bar-style" content="black">
130
+ <meta name="theme-color" content="#0b0b0d">
131
+ <style>
132
+ html { color-scheme: dark }
133
+ body { margin: 0; min-height: 100dvh; display: grid; place-items: center;
134
+ background: #0b0b0d; color: #e8e8ea;
135
+ font: 16px/1.4 ui-sans-serif, system-ui, sans-serif }
136
+ form { display: grid; gap: 12px; width: min(20rem, 82vw) }
137
+ input, button { font: inherit; padding: 12px; border-radius: 10px; border: 1px solid #303036 }
138
+ input { background: #17171b; color: inherit }
139
+ button { background: #2b6cb0; color: #fff; border-color: transparent }
140
+ p { margin: 0; font-size: 14px; color: #9a9aa2 }
141
+ .refused { color: #ff6b6b }
142
+ </style>
143
+ </head>
144
+ <body>
145
+ <form method="post" action="/login">
146
+ ${refused ? `<p class="refused">${refused}</p>` : ''}
147
+ <input name="code" placeholder="pairing key" aria-label="pairing key"
148
+ autocomplete="off" autocapitalize="none" autocorrect="off" spellcheck="false" autofocus>
149
+ <button type="submit">Sign in</button>
150
+ <p>afield serve prints a pairing key, and a QR code that signs in with it.</p>
151
+ </form>
152
+ <script>
153
+ // A link carries its pairing key after the #, which a browser never sends to
154
+ // a server or proxy, so the page posts it. A link opened in a tab already on
155
+ // this page only changes the #, so that counts too.
156
+ const post = () => {
157
+ const code = location.hash.slice(1)
158
+ if (!code) return
159
+ history.replaceState(null, '', location.pathname)
160
+ const form = document.querySelector('form')
161
+ form.elements.code.value = code
162
+ form.submit()
163
+ }
164
+ post()
165
+ addEventListener('hashchange', post)
166
+ </script>
167
+ </body>
168
+ </html>
169
+ `
@@ -0,0 +1,64 @@
1
+ // The client is one document: JS, CSS, and the VT core's WASM (already base64
2
+ // inside @wterm/core) inlined into the HTML. One file means one thing for the
3
+ // cache to be right or wrong about, which is what makes the build-id check at
4
+ // startup enough on its own.
5
+ //
6
+ // It is built per request rather than into dist/. A document built from the
7
+ // source on disk at the moment it is asked for cannot be stale, so there is no
8
+ // staleness to detect, and editing the client needs no restart — which matters
9
+ // because a restart would kill pi.
10
+ import { build } from 'esbuild'
11
+ import { createHash } from 'node:crypto'
12
+ import { readFile } from 'node:fs/promises'
13
+ import { fileURLToPath } from 'node:url'
14
+
15
+ const root = new URL('../', import.meta.url)
16
+ const at = path => fileURLToPath(new URL(path, root))
17
+
18
+ // The client knows nothing about which theme was baked in beyond what the
19
+ // served HTML carries as a class on <html>.
20
+ const THEMES = {
21
+ dark: { className: 'theme-dark', color: '#0b0b0d' },
22
+ light: { className: 'theme-light', color: '#fafafa' },
23
+ }
24
+
25
+ /**
26
+ * Returns the page and its ETag, which is a hash of everything that went into
27
+ * it. Identical source gives an identical tag, so an unchanged client answers
28
+ * a launch with a 304 instead of 74 KB.
29
+ */
30
+ export async function buildClient({ theme = 'dark', scrollback }) {
31
+ const themes = THEMES[theme] ?? THEMES.dark
32
+ const bundled = await build({
33
+ entryPoints: [at('src/app.js')],
34
+ absWorkingDir: at('.'),
35
+ tsconfig: at('tsconfig.json'),
36
+ bundle: true,
37
+ format: 'esm',
38
+ target: 'safari17',
39
+ minify: true,
40
+ write: false,
41
+ })
42
+ const js = bundled.outputFiles[0].text
43
+ const [html, wtermCss, css] = await Promise.all([
44
+ readFile(at('src/index.html'), 'utf8'),
45
+ readFile(at('vendor/wterm/packages/@wterm/dom/src/terminal.css'), 'utf8'),
46
+ readFile(at('src/style.css'), 'utf8'),
47
+ ])
48
+
49
+ // Hashed before the stamp goes in, since the stamp is part of the page. The
50
+ // theme and scrollback are hashed too: a page built for one setting must
51
+ // never be served for another off the same ETag.
52
+ const hash = createHash('sha256')
53
+ for (const part of [js, html, wtermCss, css, theme, String(scrollback)]) hash.update(part)
54
+ const id = hash.digest('base64url').slice(0, 12)
55
+
56
+ const page = html
57
+ .replace('%BUILD_ID%', id)
58
+ .replace('%THEME_CLASS%', themes.className)
59
+ .replace('%THEME_COLOR%', themes.color)
60
+ .replace('%SCROLLBACK%', String(scrollback))
61
+ .replace('/*%CSS%*/', () => `${wtermCss}\n${css}`)
62
+ .replace('/*%JS%*/', () => js)
63
+ return { page, etag: `"${id}"` }
64
+ }
@@ -0,0 +1,65 @@
1
+ // `afield sessions` and `afield end`: read the supervisor's list and
2
+ // act on it, signed in with the same key the phone and attach use. A server that is
3
+ // not answering is an answer, not an error: say how to start one and leave.
4
+
5
+ import { keyHeaders } from './auth.js'
6
+ import { ask, baseUrl, deleteTerminal, endOne, fetchPlaces, pickTarget, placeRow } from './picker.js'
7
+
8
+ /** The listed sessions and request headers, or null when the server cannot be read. */
9
+ const reach = async (url, prefix = '') => {
10
+ const headers = keyHeaders()
11
+ const data = await fetchPlaces(url, { headers, prefix, onNoServer: () => noServer(url) })
12
+ return data && { data, headers }
13
+ }
14
+
15
+ /** `afield sessions` — the sessions actually running, with ● and a count.
16
+ * Transcript history is the picker's business; this is what is live now. */
17
+ export async function sessions(url) {
18
+ const result = await reach(url)
19
+ if (!result) return
20
+ const live = result.data.sessions.filter(s => s.running)
21
+ if (live.length === 0) return console.error('nothing is running')
22
+ live.forEach((s, i) => console.log(placeRow(s, i + 1)))
23
+ }
24
+
25
+ /** `afield new [--shell]` — start a fresh session in the caller's folder,
26
+ * pi unless `kind` is `shell`. Returns the started session and the ws url to attach to, or nothing after saying why
27
+ * not. `attach` joins what exists; this starts one — in any directory the
28
+ * supervisor can see, since a joined session is a full bash prompt either way. */
29
+ export async function start(url, { cwd, kind, confirm = ask }) {
30
+ const result = await reach(url, 'new: ')
31
+ if (!result) return
32
+ const post = () => fetch(new URL('/start', baseUrl(url)), {
33
+ method: 'POST',
34
+ headers: { ...result.headers, 'content-type': 'application/json' },
35
+ body: JSON.stringify({ cwd, kind }),
36
+ }).catch(() => null)
37
+ let res = await post()
38
+ if (!res) return noServer(url)
39
+ if (res.status === 409) {
40
+ if (!await endOne(url, result.headers, confirm)) return
41
+ res = await post()
42
+ if (!res) return noServer(url)
43
+ if (res.status === 409) return console.error(`new: ${await res.text()}`)
44
+ }
45
+ // A 422 is the server naming what it refused: the folder, or the kind.
46
+ if (!res.ok) return console.error(res.status === 422
47
+ ? `new: ${await res.text()}`
48
+ : `new: could not start a session (HTTP ${res.status})`)
49
+ const { processId } = await res.json()
50
+ return { processId, wsUrl: new URL('/ws', baseUrl(url)).toString() }
51
+ }
52
+
53
+ /** `afield end [fragment|n]` — end a running session for good, confirmed once. */
54
+ export async function end(url, { match, yes = false }) {
55
+ const result = await reach(url)
56
+ if (!result) return
57
+ const running = result.data.sessions.filter(s => s.running)
58
+ if (running.length === 0) return console.error('nothing is running')
59
+
60
+ const target = await pickTarget(running, match)
61
+ if (!target) return
62
+ await deleteTerminal(url, target, { headers: result.headers, yes })
63
+ }
64
+
65
+ const noServer = url => console.error(`server not started; run afield serve (connects to ${url})`)
@@ -0,0 +1,45 @@
1
+ // The conversation a pi has open, reported by the afield-session extension as a
2
+ // JSON file it replaces by rename. Polled rather than fs.watch because the file
3
+ // exists only when the served program is pi -- most programs never write one --
4
+ // and watching a directory for a file that may never appear means noise from
5
+ // every other tmp file on the machine. Two tiny reads a second is nothing.
6
+ // Removing the file is the supervisor's job: it seeds the first one, and it
7
+ // needs the last one to outlive the program that reported through it.
8
+ import { readFile } from 'node:fs/promises'
9
+
10
+ const POLL_MS = 500
11
+
12
+ export function watchIdentity(path, onChange) {
13
+ let stopped = false
14
+ let last = null
15
+
16
+ const tick = async () => {
17
+ if (stopped) return
18
+ let text
19
+ try {
20
+ text = await readFile(path, 'utf8')
21
+ } catch (err) {
22
+ if (err.code === 'ENOENT') return // not there yet, or the program never writes one
23
+ throw err
24
+ }
25
+ if (stopped) return
26
+ if (text === last) return
27
+ last = text
28
+ onChange(text)
29
+ }
30
+
31
+ const timer = setInterval(() => {
32
+ tick().catch(err => {
33
+ // A file that appeared and then could not be read is retried on the next
34
+ // poll. It is not worth taking down the server -- and the pi it owns --
35
+ // over which conversation is open.
36
+ console.error('server: could not read the identity file', err)
37
+ })
38
+ }, POLL_MS)
39
+ timer.unref()
40
+
41
+ return () => {
42
+ stopped = true
43
+ clearInterval(timer)
44
+ }
45
+ }